> For the complete documentation index, see [llms.txt](https://docs.labs.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.labs.ai/reference/changelog/2026-10.md).

# October 2026

> Archived entries for October 2026, newest first. For recent work see [the live changelog](https://docs.labs.ai/reference/changelog.md).

***

## 🔧 ci: warm one complete Maven cache and retry Central rate limits (2026-10-31)

**Repo:** EDDI (`chore/ci-maven-cache`)

### What changed and why

A pull request's Build & Test job failed with an HTTP 429 from Maven Central while resolving `surefire-junit-platform`, before a single test ran. Every Java job used `setup-java` with `cache: maven`, which keys one shared cache on the `pom.xml` hash: whichever job finished first saved it and nothing ever updated it. A compile-only job (CodeQL) could therefore save a repository without the surefire/failsafe providers or the other test-time plugins, and every later job fetched those from Central, concurrently with every other open PR.

* **New `Maven Cache` job** (`.github/workflows/ci.yml`) is the only writer of `~/.m2/repository`. It resolves the dependencies and plugins, runs `package` once with tests skipped (formatter, Checkstyle, JaCoCo, Quarkus and its `*-deployment` jars), forces the surefire and failsafe JUnit providers, and fetches the SBOM and license plugins, then saves under `maven-v1-<os>-<hash of every pom.xml and maven-wrapper.properties>`. When that exact key already exists it does a lookup-only check and stops, so a docs-only PR pays seconds. A miss starts from the nearest older cache. It is `continue-on-error`, so a failed warm-up never blocks the required checks.
* **Build & Test, Integration Tests, CodeQL Analysis, Generate SBOM and Build Image** `need` it and only `actions/cache/restore` the same key (with the prefix as fallback); none saves. `cache: maven` is gone from them. Job names are unchanged.
* **`.mvn/maven.config`** sets Maven Resolver's HTTP retry: `aether.transport.http.retryHandler.count=8`, `.interval=10000`, `.intervalMax=300000`, `.serviceUnavailable=429,503`. A 429 or 503 is retried, the server's `Retry-After` is obeyed when sent, and a wait above five minutes fails the request instead of stalling the build.
* Review fix: the warm-up checks out before it computes its cache key (the key hashed files that were not on disk yet, so it never matched and every run rebuilt the cache), and it also stores the checksum-verified Node archive in the cache so Build Image downloads nothing.

### Design decisions

* The warm-up is ungated: CodeQL runs on every PR (Scorecard), so a gated warm-up would leave it uncached. The exact-key lookup keeps that cheap.
* Caches written on `main` are visible to every PR, caches written on a PR only to that PR, which is why the fallback prefix exists.
* The Node archive pin in Build Image is unchanged; it now rides in the same restored repository.
* `codeql.yml` and `loadtest-db-ops.yml` still use `cache: maven` (separate workflows, not in this change).

***

## 🐛 fix(ci): ratings races in the Chat UI and the integration-test stall on main (2026-10-31)

**Repo:** EDDI (`fix/main-ci-ratings-it-hang`)

### What changed and why

Three CI failures present on `main` (and so on every PR) at 01c3250.

* **Chat UI ratings restore clobbered the person's own action.** `useRatings` applied the server's restore read verbatim, so a thumb tapped while the read was in flight was undone (flaky `ChatWidget.ratings.test.tsx`, and a real bug). Changes made since the read left are now kept over the server's older view. The restore effect also closed the rating card whenever it re-ran, including when the profile merely arrived after paint, so a fast click on "Rate this conversation" opened and immediately closed it (the Playwright `ratings-feedback.fullstack` timeout waiting for `rating-star-1`). It now closes only on a switch to another conversation. Both have unit tests in `useRatings.test.tsx`.
* **`RagWorkflowExtensionIT` stalled the failsafe fork.** It was the one Mongo-backed `@QuarkusTest` without `@TestProfile(IntegrationTestProfile.class)`, so Quarkus restarted the application without the Mongo dev-service connection string. The app then pointed at the unresolvable `mongodb:27017` and every Mongo-touching bean waited out the driver's 30 s server selection: 250 s on the last green run, \~580 s on main since more stores were added. The 900 s fork timeout then killed whichever class was running (usually `PostgresGroupVerdictIT`, which is innocent). The test now carries the profile.
* **The rating card never opened for an agent that sends no greeting** (`ChatWidget.tsx`). With no messages the transcript renders its empty state, and the card was only rendered in the non-empty branch, so "Rate this conversation" set the state and nothing appeared. The Backend E2E agent has an empty workflow, so its ratings test waited for a star that was never rendered. The card now renders in both branches; a ChatWidget test covers the empty transcript.
* **Rating state across the restore read** (`useRatings`, `RatingCard`), from the review of this PR: an edit is now tracked per rating (in flight, confirmed since the read began, revision). A failed write rolls back to the server's value (from the read or the last confirmed write), never to empty, and only when no newer edit has started; a failed write before the read answers lets the read fill the value in. The per-conversation state is no longer cleared when the profile merely reloads for the same conversation, and the protection is retired when the next read begins. A card opened before the read finishes picks up the restored rating until the person has touched it.

### Design decisions

* No timeout was raised and nothing was skipped; the stall's cause was removed.

***

## 🔒 fix(backup): review findings on export, import and upgrade (2026-10-31)

**Repo:** EDDI (`fix/review-backup`)

### What changed and why

Verified findings from the CodeRabbit security review and the October code review, all on the backup / import / sync path. Several authorization findings only matter with `eddi.workspaces.enabled=true`; they are fixed regardless.

**Export**

* The agent and workflow documents are scrubbed like every other archived document — a Dream job's model `apiKey` and legacy `channels[].config` tokens used to leave verbatim.
* The export scrubber now redacts query parameters whose *name* marks a credential (`key`, `sig`, `signature`, `accessKey`, … — `ConfigSecretRedactor`'s rule) in relative paths and absolute URLs, so a signed-URL signature an editor's GET hides no longer leaves in the archive. Form bodies are not affected.
* A URI found anywhere in a workflow other than its step references (which the authoring check vetted) needs `VIEW` before export or preview reads it; previously a URI in a free field of a step's `config` pulled another space's configuration into the archive.
* Snippets are exported only with `VIEW` (a `USE`-only listing no longer suffices).
* Connections go through `ConnectionReadRedactor` before the generic scrubber, so a pre-validation literal `passwordRef` is not exported.

**Import**

* A workflow written straight to the store runs `RestWorkflowStore`'s reference check (now reused via `WorkflowReferenceAccess`, walking `RestWorkflowStore.referencedResources`).
* A workflow directory without a workflow document is a 400, not a kept foreign reference.
* Repeated workflow URIs in an agent are imported once (no orphan copies).
* `updateParser` now goes through `updateTracked`, so a failed merge rolls it back too.
* Connections are created only for an administrator, as over REST; an editor's import skips (and counts) them.

**Upgrade / sync**

* A source resource two workflows share is matched per workflow: extension diffs carry their workflow's `workflowIndex`, and the executor looks diffs up per workflow (#8).
* A 409 is retried against the store's version only when the descriptor lags the store (a lost descriptor write) or when the newer version is one this run wrote itself (a target resource two workflows share is written once per workflow); any other version whose descriptor moved is somebody's edit and is reported, not overwritten.
* `createExtension` decodes the JSON before `requireMayAuthor`, so a JSON-escaped `${caller:token}` no longer passes the check; a created RAG config gets `KnowledgeBaseStorageGuard.prepareNew`.
* A newly created workflow runs the reference check before any of its resources is written.
* `ScrubbedSecrets` restores a *literal* target credential only when the object's destination (`…Url`, `uri`, `endpoint`, `host`, absolute `path`) is unchanged, compared by origin with scheme and host case-folded and a default port equal to an omitted one; vault references still come from the target. The identity lookup for array elements is indexed once per list instead of a scan per element.
* Source readers refuse more than 256 workflow references; the remote source fetches each document once per sync.

**Archive extraction:** a ZIP directory entry carrying data, or an entry nested more than 32 levels deep, is refused.

**Dead code:** removed `StructuralMatcher.readLatestVersionOrDefault` and `UpgradeExecutor.readLatestVersion`; moved the stacked Javadoc in `StructuralMatcher` onto `readLatestVersion`.

### Design decisions

* Export keeps "VIEW on the agent covers the graph beneath it" for the structural step references (a non-cascading share still exports); only references the authoring check never saw need their own `VIEW`. That includes the dictionaries a *parser document* names (the parser store does not vet them on write), so a recipient of a non-cascading share whose agent uses parser-document dictionaries they cannot see now gets a 403 instead of an archive.
* Minimal edits outside `backup/`: `RestWorkflowStore.referencedResources` and `ConnectionReadRedactor.redactLegacyLiterals` made public for reuse; `SecretScrubber` gained the credential-query-name rule.

### Not done

* Consolidating `RestImportService`'s per-type create/update methods with `UpgradeExecutor.resolveExtensionOps` into one table: the import side carries per-type behaviour (RAG preparation, storage namespace, v5 LLM defaults) that makes it a larger refactor than this pass.
* Second review round: an upgrade write that meets a 409 for a version this run did not write is now always reported as "changed on this instance" instead of being retried when the descriptor lags the store (a lost descriptor bump and a save whose descriptor has not moved yet cannot be told apart, so the sync fails safe; preview and sync again). The workflow-reference rule now lives once, in `RestWorkflowStore.requireAccessToReferences`, shared with the backup paths.

**Files:** [`RestExportService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/backup/impl/RestExportService.java), [`RestImportService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/backup/impl/RestImportService.java), [`UpgradeExecutor.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/backup/impl/UpgradeExecutor.java), [`StructuralMatcher.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/backup/impl/StructuralMatcher.java), [`ScrubbedSecrets.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/backup/impl/ScrubbedSecrets.java), [`WorkflowReferenceAccess.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/backup/impl/WorkflowReferenceAccess.java), [`ZipArchive.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/backup/impl/ZipArchive.java), [`SecretScrubber.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/secrets/sanitize/SecretScrubber.java), [`import-export-an-agent.md`](https://docs.labs.ai/getting-started/import-export-an-agent.md), [`agent-sync-guide.md`](https://docs.labs.ai/conversations-and-orchestration/agent-sync-guide.md)

***

## fix(configs,datastore): review findings in the configuration stores and the datastore (2026-10-31)

**Repo:** EDDI (`fix/review-configs`)

Verified CodeRabbit findings and code-review leads (§4 Persistence, §5 dead code) for `configs/**` and `datastore/**`.

### What changed and why

**Configuration stores**

* **Reverse-reference lookups no longer loop on a caller-chosen version.** `AgentStore.getAgentDescriptorsContainingWorkflow` and `WorkflowStore.getWorkflowDescriptorsContainingResource` issued two to four queries per integer version from the `?version=` the caller sent down to 1, so `?version=2000000000&includePreviousVersions=true` kept a worker busy for billions of queries. The walk now starts at the referenced resource's LIVE version, read from its own store (`ResourceUtilities.clampToLiveVersion`; the workflow store for an agent lookup, `IResourceClientLibrary` for a workflow lookup), never from its descriptor: descriptors lag every in-process update, and clamping to a stale descriptor version made the cascade-delete and orphan-purge reference checks skip referrers of the live version. When the live version is unknown a walk above 1000 versions is refused (both delete paths read that as "still referenced") instead of being cut short. Only walks are clamped; an exact lookup (`includePreviousVersions=false`) queries the version it was asked about.
* **JSON Patch cannot relocate a credential the caller cannot read.** `ConfigJsonPatcher` applied the patch to the unredacted document, so an editor could `copy`/`move` a plaintext key into `description` and read it back. For anyone but an eddi-admin the patch now runs against a view where every credential `ConfigSecretRedactor` would redact is an opaque random token; a token is restored wherever it is a whole value, but one that ends up at another path (an `add`/`remove` earlier in an array shifts the indexes after it) is kept only if the redacted read still hides it there; a credential relocated into a readable field, or embedded in a larger string, is refused with a 400, and a `test` against a credential never sees its value.
* **JSON Patch output is bounded.** Operations are applied one by one and each `copy` is followed by a size check (nodes plus string length, counted with an early stop) that refuses growth beyond twice the stored document plus 1 MB, before anything is serialised. Shared JSON-P structure let a few copies build an exponentially large result.
* **Workflow references with a non-canonical scheme are checked.** `RestWorkflowStore.addReference` skipped any `config.uri` not starting with `eddi://`, but the engine resolves by host and id, so `Eddi://` or `x://ai.labs.llm/…` ran a configuration the access check never saw. Every URI with a scheme, host and id is now checked.
* **Parser documents check their dictionary references.** `RestParserStore` create, update and duplicate run the workflow store's reference check on the parser's extensions (VIEW on each newly introduced dictionary), so a private dictionary can no longer be reached through the standalone parse endpoint or an export.
* **Agent tests:** `maxCostPerRun` NaN/Infinity and a non-finite `expect.maxCostUsd` are refused (NaN passed the range check and disabled the budget).
* **Artifact JSON-schema validators** evaluate `pattern`/`patternProperties` through a deadline-bound regex factory sharing one 500 ms budget per validation, like the `REGEX` validator; a runaway pattern refuses the write. The budget is checked before every match as well as during one, so many short matches (every `patternProperties` pattern against every key) stop at it too.
* **Template migration is linear.** `TemplateSyntaxMigrator.unconvertibleReason` continues after the closer instead of re-scanning from every nested opener, and a text whose openers-times-length exceeds 50M is reported unconvertible and left alone instead of costing quadratic CPU at import or startup. Only anchors a conversion step can scan from count (`[[${`, `[(${`, `[#`, `#strings.`), so nested JSON arrays (`[[1,2]]`) no longer push a resource past the bound, and an import that the converter refuses as a whole text is reported in the log like a refused value.
* **Global variables:** the assembled-reference check scans in one linear pass instead of a regex retried at every unterminated opener. `ApiCallExecutor` refuses a full-form `${vars:tenant/key}` that only conversation data supplied (the configured template did not write it): it would read another workspace's variable.
* **Knowledge bases:** a 6.5.0 name-layout knowledge base that drops its explicit location moves to the id layout, as a rename already did (rename-keeping-location then drop-location reached another name's default store unchecked); an Elasticsearch `indexName` must name one concrete index (no wildcard, list or exclusion, and no surrounding whitespace, since the store receives it untrimmed); and the location collision scan fails closed when it runs past its 20,000-descriptor budget.
* **Channel integrations:** `duplicateChannel` runs the target USE check a create runs; the uniqueness checks and the write are serialised on the node, and a new integration's descriptor (which those checks enumerate) is written before the lock is released; a create whose descriptor cannot be written removes the integration again and fails with a 500 instead of leaving it invisible to the next check. A `channelId` a deployed agent's legacy Slack connector serves is refused instead of silently taking the route over. That check asks `ChannelTargetRouter.isServedByLegacyConnector`, which reads the live deployments and deployed agent configurations rather than the router's one-minute cache (a connector deployed a moment ago is not in it), and the save answers 503 when they cannot be read. The router is constructor-injected.
* **Group configurations:** `protocol.maxTurns` and a phase's `repeats` are capped at 1000, and `artifactConfig.maxArtifactsPerDiscussion` at 1000 (the quota counts a bounded listing).
* **Orphan purge:** the scan also walks the exact workflow version every current (not only deployed) agent pins, so a dependency a newer workflow version dropped is not purged from under an undeployed agent. It reads each agent and workflow at its live version rather than the version its (possibly stale) descriptor names, and the per-candidate re-check before a delete also asks whether a current agent pins a superseded workflow version that uses the extension (`IWorkflowStore.getWorkflowVersionsContainingResource`), failing closed.
* **Properties:** `PropertyValues.toProperty` and `copyOf` copy nested maps and lists, so a path assignment into a property built from a cached configuration value cannot write into that shared configuration.
* **`PropertiesMigrationService`** skips only on `postgres`, like every other datastore switch, instead of running only on the literal `mongodb`.

**Datastore**

* `PostgresUserConversationStore.deleteAllForUser` throws instead of returning 0 on a SQL error, so a failed GDPR erasure step is reported as failed.
* `DescriptorStore.findByOriginId` returns every match instead of the first ten, which was a cap applied before the caller's workspace/EDIT filter and could make a merge import create a duplicate.
* Sorted PostgreSQL `findResources` pages break ties on `id`, so offset paging over equal sort values neither repeats nor skips rows (the field index still supplies the leading key; the tie is ordered by an incremental sort). MongoDB deliberately keeps the single-key sort: its field indexes are single-field, and `{field: -1, _id: -1}` would turn every sorted page into a blocking in-memory sort over all matches.
* `PostgresAttachmentStore.grantAccess` throws `AttachmentNotFoundException` for a missing blob, as the MongoDB store does.
* Attachments that record no owner fail closed for **reads**: the MongoDB store no longer lets any conversation read them unless that conversation was explicitly granted access, matching PostgreSQL. **Deletes are unchanged** on both backends: an ownerless blob can still be deleted by its `storageRef`, because deleting discloses nothing and refusing it would strand personal data beyond erasure. `deleteByConversation` (conversation delete, purge, GDPR erasure) is untouched and matches on the owning conversation exactly as before. Docs: [Attachments guide](https://docs.labs.ai/agent-configuration/attachments-guide.md).
* `V6RenameMigration.saveDocument` addresses a string `_id` as stored (it queried `new ObjectId(string)`, which never matched) and counts a document only when the replace matched.
* Dead code removed: `datastore/model/ResourceId` and its test; the unreachable null-weight check in `AgentGroupStore.validateVotePhases` (`VoteConfig` copies weights with `Map.copyOf`, which refuses null values).

Docs updated: [RAG](https://docs.labs.ai/agent-configuration/rag.md), [Group conversations](https://docs.labs.ai/conversations-and-orchestration/group-conversations.md), [Attachments guide](https://docs.labs.ai/agent-configuration/attachments-guide.md).

### Design decisions

* **Patch protection by token, not by path rules.** Deciding which patch operations touch credentials by their pointers breaks on array shifts and nested copies; masking the document with per-request random tokens, and admitting a token at a new path only where the redaction rules still hide it, covers both and reuses the read redaction's own rules. Over-masking (no skip paths) only restricts copy/move for non-admins.
* **Reverse-lookup clamp uses the resource's live version from its own store**, injected lazily (`Provider`) because the workflow store and the resource client library reach back to the agent and workflow stores through the REST facades. The descriptor's version was tried first and is wrong: it lags in-process updates. A store-level prefix query would avoid the per-version walk entirely but needs new queries on both backends.
* **Ownerless attachments fail closed for reads only**: the PostgreSQL store already refused those reads, and an owner nobody can establish is not an owner. Deletes stay allowed, since a delete that refuses data it cannot attribute would make it impossible to erase.

### Deferred

* Descriptor PATCH vs. sharing race (full-snapshot write conditioned only on the resource version): needs a descriptor revision or field-level update on both backends.
* Slack approval records keyed by integration name: needs an immutable integration id on approval records (integrations area).
* Knowledge-base collision check against locations of older, still-pinned versions: needs a location index across versions.

***

## 🐛 fix(engine): conversation engine, HITL and memory findings from the external reviews (2026-10-31)

**Repo:** EDDI (`fix/review-engine-conv`)

Verified findings from the CodeRabbit security review and the full code review against `01c3250`, for the conversation engine (`engine/internal`), the HITL services and conversation memory (`engine/memory`).

### What changed and why

**Conversation state can no longer be resurrected or overwritten blindly**

* The agent-timeout watchdog and the turn error path wrote `EXECUTION_INTERRUPTED` / `ERROR` with an unconditional store write. An end only raises the cooperative-cancel flag, which a hung model call never sees, so ending a stuck conversation was undone by the watchdog — and `EXECUTION_INTERRUPTED` auto-recovers on the next say, so the ended conversation was drivable again and invisible to the ENDED-only retention sweep. Both are now a compare-and-set from the state they read, never over `ENDED` (`ConversationStepRunner.transitionUnlessEnded`; both stores already had `compareAndSetState`).
* The admin `PATCH /agents/{conversationId}/state` read the state and then wrote READY: `IConversationService.resetConversationState` now takes the expected state and is a compare-and-set; a lost race answers `409`.
* A cancelled say ends its pipeline through the `STOP_CONVERSATION` path, so the caller was told `ENDED` while the store recorded `EXECUTION_INTERRUPTED`. It is now reported as what the store holds (`ConversationService.reportCancelledTurnAsInterrupted`).

**HITL**

* An `ABORT` timeout (and the pending-approval retention sweep in `HitlCrashRecoveryObserver`) used the full cancel and was not bound to its pause: a fire claimed just before a resume stopped the resumed turn, or aborted a newer pause. Both now use the paused-only cancel bound to the pause id (`IConversationService.cancelPausedConversation(id, by, pauseId)`), which re-checks the pause after its compare-and-set and puts back a pause it did not mean. An `ABORT` fire that meets a resume of its pause still in flight (`IN_PROGRESS`) stays armed and is retried rather than completed, since that resume may still fail and restore the pause. The group surface is left to the groups work.
* Resume did not apply the GDPR Art. 18 processing restriction that start and say apply; a restricted owner could drive a resumed turn (including a rejection-note revision). It now refuses with the pause restored and its timeout still armed.
* A tool pause's timeout policy came from the governing rule of the *matched* calls only, so an `AUTO_APPROVE` rule for one endpoint auto-approved an unmatched gated call bundled into the same model message. A call that no policy-stating rule covers now contributes the policy it would inherit, strictest wins.
* `getAgent` keeps deploying a conversation's pinned version on demand even when its deployment record says `undeployed`: the old-version cleanup undeploys a previous version whose only open conversations are paused (and retirement does the same for movable ones), so refusing would strand those approvals at the next deploy. `docs/hitl.md` claimed a resume after an undeploy returned `409`; it now describes this.
* The approver projection stripped the revision candidate (frozen prompt + tool results) from active steps but not from the redo cache an undo fills.

**Memory, retention and reads**

* The raw read `GET /conversationstore/conversations/{id}` and `approval-status?detail=full` served `audit:compiled_prompt` — the agent's rendered system prompt — to an owner who may only USE the agent. Both now strip `audit:*` (keeping `audit:token_usage`) unless the caller has VIEW on the agent, as the detailed view and MCP `read_audit_trail` already did (`ConversationMemoryUtilities.stripAuditData`).
* The retention sweep deleted the snapshot without the memory checkpoints (copies of the properties) and the HITL tool journal, removing the only link a later user erasure had to them. It now runs the same dependent cascade as a permanent delete; and both paths keep the snapshot and descriptors when any dependent delete fails (`ConversationPurgeService.deleteDependentData`), or when the vault is unavailable while the conversation references auto-vaulted secrets, instead of orphaning the copies.
* The conversation listing's "search matches nothing → list everything" fallback decided by searching the whole store, an existence oracle over other users' conversations. It is now decided within the caller's own records.
* Mid-turn memory checkpoints copied properties before the turn-end secret-context scrub, persisting a secret context value a property instruction had copied. The checkpoint copy is now scrubbed with the same thresholds (`MemorySnapshotService.withoutSecretContextValues`).
* `SecretValueScrubber` decoded serialized JSON only in exact mode; in substring and whole-token mode a secret with a JSON-escaped character survived inside tool-call arguments. All modes now decode embedded JSON.
* Attachment uploads to a legacy conversation used the descriptor's (null) owner as the quota identity, exempting them from the per-user quota; they now use the owner the access guard resolved.
* An `Idempotency-Key` retry was served a turn's answer from the grace cache even when the turn's persist then failed; a failed persist now drops it (`TurnIdempotencyService.forgetUnpersisted`).

**Administration**

* `undeployThisAndAllPreviousAgentVersions` counted down from any requested integer (one DB read and one undeploy task per number, plus an "undeployed" record for versions that never existed). The starting version must now be one the agent has (`400` above its current version).
* The agent quota counted only each agent's newest runtime version, so a failed newer version hid a live older one; it now counts any READY version. A deployment-count outage failed open; it now refuses with `503` while an agent limit is in force (`TenantQuotaService.agentCountUnavailable`).
* The live log stream (`/administration/logs/stream`) kept delivering admin-only records after the opening token expired; it now closes at the token's expiry, as the cluster activity stream does.

**Dead code and duplication**

* Removed `SecretValueScrubber.scrubContext`, `ITurnAbandonment` with `ConversationService.abandonInFlightTurn` (only a test called it), and the unused `MemoryKeys.SYSTEM_MESSAGE` / `PROMPT`.
* `ConversationAccessGuard`'s four near-identical owner checks now share one helper.

### Design decisions

* Pause-bound cancels re-verify the pause *after* the state compare-and-set and restore it on a mismatch, before any side effect — the same pattern resume uses — rather than adding a pause-id predicate to both stores' CAS.
* The agent quota fails closed only where a limit applies, so a deployment-store outage never blocks deploys on deployments without an agent quota.
* Whether an admin's explicit undeploy should block resuming the version's pending approvals is open: it needs an undeploy record that tells an explicit undeploy from the automatic cleanup, which writes the same `undeployed` status today.
* Second review round: a bulk undeploy no longer answers 404 when the deployment records could not be read (500 instead); the log stream stops its initial batch when the token expires mid-batch; `ConversationPurgeService.purge` ends the conversation before the first irreversible cleanup step, so a delete that fails part-way leaves it unable to take a turn until the retry finishes (and when that write itself fails, the delete stops before any cleanup and is retried); the stale-turn tests also assert that no compare-and-set to `ERROR` happens.

### Deferred

* **A persistent pending-deletion state** (a dedicated state that blocks every read path, not only turns) is not added: a partly purged conversation is ENDED, findable for the retry, the retention sweep and erasure, but still readable through the history endpoints.
* API-call quota spent on turns refused after admission (duplicate, skipped, ended): needs a refund operation in both quota stores or moving acquisition into the queued turn — a product decision on whether skipped turns count.
* `ConversationService`'s thin private delegators kept for reflective tests (§7): reducing them means rewriting the characterization suites that reach them via `getDeclaredMethod`; not done here.

**Files:** [`ConversationStepRunner.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/ConversationStepRunner.java), [`ConversationService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/ConversationService.java), [`ConversationHitlService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/ConversationHitlService.java), [`HitlTimeoutHandler.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/HitlTimeoutHandler.java), [`HitlCrashRecoveryObserver.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/hitl/HitlCrashRecoveryObserver.java), [`RestAgentAdministration.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/RestAgentAdministration.java), [`RestAgentEngine.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/RestAgentEngine.java), [`RestLogAdmin.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/RestLogAdmin.java), [`TurnIdempotencyService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/TurnIdempotencyService.java), [`RestConversationStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/memory/rest/RestConversationStore.java), [`RestAttachmentUpload.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/memory/rest/RestAttachmentUpload.java), [`ConversationPurgeService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/memory/ConversationPurgeService.java), [`ConversationMemoryUtilities.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/memory/ConversationMemoryUtilities.java), [`MemorySnapshotService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/memory/MemorySnapshotService.java), [`SecretValueScrubber.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/memory/SecretValueScrubber.java), [`IConversationService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/api/IConversationService.java), [`TenantQuotaService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/tenancy/TenantQuotaService.java), [`ConversationAccessGuard.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/security/ConversationAccessGuard.java); docs [`hitl.md`](https://docs.labs.ai/conversations-and-orchestration/hitl.md), [`gdpr-compliance.md`](https://docs.labs.ai/security-and-compliance/gdpr-compliance.md), [`tenant-quotas.md`](https://docs.labs.ai/security-and-compliance/tenant-quotas.md), [`deployment-management-of-agents.md`](https://docs.labs.ai/conversations-and-orchestration/deployment-management-of-agents.md), [`rest-api-reference.md`](https://docs.labs.ai/conversations-and-orchestration/rest-api-reference.md).

***

## fix(engine): review findings — HITL, GDPR, Dream, alerts, audit, mail (2026-10-31)

**Repo:** EDDI (`fix/review-engine-hitl-alerts`)

Fixes from the CodeRabbit review and the full code review (against `01c3250`) for the engine runtime and the packages around it. Each fix has a unit test that fails without it.

### What changed and why

**HITL**

* A reissue of an approved call that has already executed is gated again (`ToolApprovalGate.REPEAT_REASON`) instead of running a second time on one approval.
* Approval patterns are matched by a linear glob matcher (`ToolApprovalPatterns.matches`), not one backtracking `.*` per wildcard.
* `TaskToolApprovalsResolver` (strict) pins a task rule with no `timeoutPolicy` to `WAIT_INDEFINITELY` when it would inherit the agent's `AUTO_APPROVE`, so it cannot hide a stricter agent rule.
* `SelfUngatingGuard` compares an LLM-store write against the stored configuration: a whole-document `PUT` that omits a stored task gate, or a patch on its ancestor, is refused (lookup wired through `ActingAgentResources`).
* The tool journal's TTL expires `EXECUTED` entries only; a crash-orphaned `EXECUTING` claim is kept until its conversation is deleted, so a late approval cannot run the call again.

**GDPR, tenancy, ratings, Dream**

* Erasure keeps conversation snapshots when attachment deletion failed, keeps mapping rows when their cache keys could not be read, and reports nodes that did not confirm the cluster stop (`IClusterRpc.expectedPeers`). `restrictProcessing` removes a legacy agent-owned row under the reserved key first, which otherwise made the restriction unenforced.
* `PostgresTenantQuotaStore.setQuota` propagates a write failure (503) instead of acknowledging a quota that was never stored.
* Withdrawing a rating blanks the comment excerpts alerts copied from it first; erasure could not find them afterwards.
* Dream partitions consolidation by group readership (no union of group ids across groups), merges duplicate keys in linear time with the cap checked per append, and refuses a cycle whose pinned agent version names an ungranted vault secret.

**Alerts and audit**

* Webhook targets, signing-secret references and multi-agent rules need the `eddi-admin` role (`AlertAccess.hasAdminRole`), not merely unrestricted visibility, which every editor has while workspaces are off.
* Digests go out per originating agent; deleting/disabling a rule or setting its digest to `NONE` releases its `DIGEST_PENDING` events (`IAlertEventStore.releaseDigestPending`). An output value older than the erasure fence's lifetime is not stored. `AlertEngine` lost its test-only constructors and the duplicated 24-argument event rebuilds (`AlertEvent.withMatch`), and uses `AlertMatchers.applies`.
* The audit chain check finds holes between sequenced rows in a window that also holds unsequenced rows (was `UNAVAILABLE`), and with signing on ignores positions claimed by v1/v2-signed rows, whose signature does not cover the sequence.

**Mail**

* `DkimVerifier` refuses a header block with a bare CR or LF (the MIME parser splits a header there, the verifier did not). `QuoteStripper`'s label patterns are possessive (quadratic backtracking on long blank runs).

Docs: [Alerts](https://docs.labs.ai/conversations-and-orchestration/alerts.md), [Audit Ledger](https://docs.labs.ai/security-and-compliance/audit-ledger.md), [HITL](https://docs.labs.ai/conversations-and-orchestration/hitl.md), [Secrets Vault](https://docs.labs.ai/security-and-compliance/secrets-vault.md).

* Second review round: a digest is skipped when its rule was disabled or deleted after the pass began, and withdrawn (not delivered) when every held event was released first; `NatsClusterRpc.expectedPeers` reads presence uncached, fails closed when it cannot, and excludes this node by id; erasure keeps conversation snapshots when the conversation-id lookup failed; a failed tool-journal delete keeps the conversation (`ConversationPurgeService.purge` throws) so a retry can still reach the rows naming the approver; Dream `warn` mode logs ungranted vault references; agent-trigger cache misses re-check inside the stripe lock; `AgentSetupService` registers API-call locations before the creation loop so rollback sees them; two docs/Javadoc corrections.

### Design decisions

* **A repeat of an executed approved call goes back to a human** rather than replaying the journaled result: replay needs a new result path through `ToolLoopRunner`; re-gating is safe with the code this group owns.

### Not done (deferred)

* **Stale cached alert rules** can, for up to the rule cache TTL (60 s) on another replica, still create a `DIGEST_PENDING` event after the rule was disabled; such an event stays visible in the inbox until retention. Reconciling them needs a store query for held events of rules that are no longer digest rules.
* **Mongo journal TTL migration during a rolling update:** an old pod can recreate the unfiltered `idx_journal_ttl_claimed` after a new pod dropped it, until it is stopped. Finish the upgrade (no old pods) before relying on the EXECUTING-claim retention; a versioned migration marker is not part of this change.
* **Audit tail / whole-trail deletion** stays undetectable: it needs an anchored chain head stored outside the trail (or a predecessor digest in a new canonical form), which is a format change.
* **Interim narration of a tool-approval pause** is not screened by the task's output guardrails: the narration is built in `modules/llm` (`ToolApprovalGateSupport`), where the guardrails live.
* **Alert webhook HMAC keys** have no grant model of their own; with webhooks now reserved to the administrator role (who controls grants anyway) the remaining oracle is administrator-only.

***

## fix(engine): review findings — runtime, scheduling, cluster (2026-10-31)

**Repo:** EDDI (`fix/review-engine-runtime`)

Fixes from the CodeRabbit review and the full code review (against `01c3250`) for the engine runtime and the packages around it. Each fix has a unit test that fails without it.

### What changed and why

**Runtime and REST**

* `CronParser.parseField` checks a range's endpoints against the field's domain *before* enumerating it; `0-2000000000` used to allocate billions of boxed integers first (reachable from group cadences and schedules). The stepped loop no longer wraps on a huge step.
* `DocumentDescriptorFilter` takes the deleted resource's id from the request path and the `version` parameter only; `?x=/<other id>` made it mark another resource's descriptor deleted.
* `LegacyPathRewriteFilter` rewrites a v5 store prefix only at the start of the path, and `restricted`/`unrestricted` only in `/administration/{environment}/…`. A substring replace turned `DELETE /admin/gdpr/restricted` into an erasure of user `production`.
* `WorkflowStoreClientLibrary` reads secret instructions from the executable `PropertySetter` the task configures to; the check for `PropertySetterConfiguration` never matched, so failed turns of secret-collecting agents kept their input in dead letters.
* `RestInterfaceFactory` addresses the HTTP listener EDDI is bound to (`SelfUrlResolver`'s logic), not always `127.0.0.1`, and forwards no caller token when that address cannot be resolved.

**Scheduling and cluster**

* A schedule whose claim expired without an outcome (its node died or the fire wedged) counts as a failed attempt instead of being re-fired at once with `failCount` untouched — a node-killing fire could never dead-letter. The poll runs with `concurrentExecution = SKIP`. `tryClaim` re-checks `enabled` (MongoDB and PostgreSQL). `POST /{id}/fire` and the MCP `fire_schedule_now` tool are bounded by the fire timeout like a polled fire, so a manual Dream or ingestion run cannot outlast its lease and start twice. A disabled schedule can no longer be fired manually.
* A scheduled fire that starts a conversation runs the agent's startup workflow under `maxCostPerFire`, and the turn gets the remainder.
* A dead letter a node kept locally while cut off from NATS is discarded, not forwarded, when its conversation no longer exists (erased in the meantime).
* NATS TLS verifies the broker host name (`eddi.nats.tls.verify-hostname`, default `true`); jnats sets no endpoint identification, so any trusted certificate for any host was accepted. **Upgrade note:** the broker certificate must now carry a SAN for every host in `eddi.nats.url` (an IP SAN for an IP address); see [Clustering](https://docs.labs.ai/deployment-and-infrastructure/clustering.md).
* `CacheFactory.evictLocal` remembers key hashes instead of SHA-256-ing every cached key on every eviction event. `BoundedLogStore`'s DB queue is capped (50,000; drops are counted and logged at flush). `BoundedFanOut` claims "not started" by compare-and-set, so an item reported as not sent can no longer go on and send. `AgentTestRunner` charges an abandoned (timed-out) turn's cost when it completes.

**Cleanup:** unused `ClusterConfig.withDegradedNonces/withDegradedRateLimits/withHitlRecovery` removed; misplaced Javadoc in `ScheduleFireExecutor` and `SchedulePollerService` moved to its methods; the nine fire-log blocks in `ScheduleFireExecutor` share `recordFire`.

Docs: [Clustering](https://docs.labs.ai/deployment-and-infrastructure/clustering.md), [Scheduling](https://docs.labs.ai/conversations-and-orchestration/scheduling.md), [Configuration Reference](https://docs.labs.ai/deployment-and-infrastructure/configuration-reference.md).

* Second review round: a manual fire cut off at its deadline (REST and MCP) answers a timeout (504 / an error result) instead of an empty 200, and leaves the schedule claimed until its lease expires rather than releasing it while the worker may still run (`FireAbandonedException`); a local dead letter whose conversation cannot be checked stays on the node instead of being published, and a legacy conversation without a stored state is no longer mistaken for a missing one; an unreadable startup spend leaves the turn no allowance instead of the full `maxCostPerFire`; `BoundedFanOut` no longer reports a gate-refused item as started; `BoundedLogStore` hands the database fixed-size batches; two docs/test corrections.

### Design decisions

* **An expired claim is a failure, not a retry-now.** The lease already outlasts the fire timeout by a margin, so a claim that expires means the fire is gone.
* **Hostname verification is on by default** and can be turned off; an IP address in `eddi.nats.url` then needs an IP SAN.

### Not done (deferred)

* **Late charges of an abandoned agent-test turn** (`AgentTestRunner`) are still not persisted into the already-finalised run record; that needs an atomic adjustment of the terminal record or a hold on finalisation until the turn's persistence completes.
* **Local dead-letter forwarding vs GDPR erasure** has no shared erasure marker: a node that reconnects between the shared purge and the snapshot deletion can still publish an erased turn (the existence check now closes the common case).
* **The `SKIP` poll cycle** still waits for its batch's fires, so one long fire delays claiming other schedules on that instance; splitting the short claim cycle from the bounded fire wait is a larger change to the poller.
* **One fire-timeout mechanism** instead of the executor's turn latch plus the poller's deadline: both now use `eddi.schedule.fire-timeout`, and the manual path is bounded; merging them is a refactor.

***

## 🔒 fix(engine-surface): review findings on channels, Slack, MCP, A2A, sharing and outbound HTTP (2026-10-31)

**Repo:** EDDI (`fix/review-engine-surface`)

Fixes from the CodeRabbit review and the full code review (revision 01c3250) for the external surfaces: `integrations/**`, `engine/mcp`, `engine/security`, `engine/a2a`, `engine/httpclient`.

### Channels and Slack

* **Only credentials are vault-resolved.** `ChannelTargetRouter` used to expand `${vault:...}` in every `platformConfig` value, so an editor could put a restricted reference into a webhook's `inputTemplate` and read the plaintext in the resulting conversation. Only `botToken` and `signingSecret` are resolved now; everything else stays literal.
* **An unresolved credential is dropped, for every channel type.** The resolver passes an unresolvable reference through unchanged, and Slack used that public text as its HMAC key. The router now drops it (as it already did for webhooks), and `SlackSignatureVerifier` refuses a reference-shaped key outright.
* **A Slack bot token honours its secret's `allowedHosts`** (checked against `https://slack.com/api/` via `VaultHostAllowlist`).
* **The approval card no longer borrows another integration's bot token** via the editor-chosen approval channel; resume outcomes are posted only for conversations owned by a Slack principal (`SlackUserIdentity.isSlackPrincipal`), so a hand-made `channel:slack:...` trigger intent cannot post with another integration's identity. Only the reserved `slack:` form counts: a raw `U123ABC`-shaped owner is just a shape an OIDC principal can share, so a legacy thread mapping gets resume posts again once its next message re-keys it.
* **Event user ids are validated** (`[UW][A-Z0-9]+`) before they become `slack:<team>:<user>`, so a teamless signer cannot alias a workspace-qualified user by sending `user: "T1:U2"`.
* **Approval-card text is mrkdwn-escaped** (tool previews, reason, agent label).
* **`/v1` matrix parameters** (`v1;x/chat/completions`) no longer skip `OpenAiAuthFilter`'s key check.

### MCP

* `chat_managed` re-checks USE on the retained conversation's own agent, and a refusal there is the neutral "you may not continue this conversation" (the owner does own it), not "you do not own this managed conversation".
* `submit_group_human_input` (and REST `POST .../human-input`) return an acknowledgement unless the caller is the owner or an admin. The Manager's `submitHumanInput` resolves to `GroupConversation | HumanInputAcknowledgement` (narrow with `isHumanInputAcknowledgement`).
* `McpAdminTools` no longer echoes raw exception text: caller-fixable failures are described, everything else returns a log reference (`toolFailure` overload). Two refusals stay caller errors rather than `INTERNAL`: a guard's Quarkus `ForbiddenException` (`ResourceAccessGuard`, `OwnershipValidator`) answers errorCode `FORBIDDEN` with its reason, and malformed JSON in a `config` / `resourceMappings` argument answers "config is not valid JSON (line L, column C)" (`McpToolUtils.readCallerJson`) — resources, channels and triggers alike. `list_agent_resources` reads each distinct workflow once.
* `McpApiToolBuilder`: spec parameter names that collide with template namespaces are renamed (`properties_2`); suffix allocation is linear; a spec server URL is literal (declared variables take their defaults, other `{...}` is refused).
* `OpenApiSpecFetcher` repeats the target-policy check after connecting (DNS rebinding) and discards the response if it now fails.

### Security, A2A, outbound HTTP

* With authentication off, `GET /agents/managed/...` (creates a conversation) gets the same cross-site check as a `POST`.
* Access requests answer a non-configuration id exactly like a missing one, after counting the attempt; a cascade skips `HUMAN` group members, budgets its seeding, and omits the name of a skipped resource the caller cannot view.
* A2A caps caller-chosen ids at 256 characters and refuses non-scalar JSON-RPC ids. Every JSON-RPC response now carries the `id` member, `"id": null` for an unreadable request, as JSON-RPC 2.0 requires (`JsonRpcResponse` was NON\_NULL).
* httpcalls: a cross-origin redirect hop keeps only content-negotiation headers (a credential can sit in any header name); with SSRF protection off a redirect hop's *connected* peer is held to the previous hop's address class.
* Constant-time compares in the area now use `HmacSignatures.constantTimeEquals`.

### Deferred

* Review eligibility pinned to the conversation's start version (`ConversationAccessGuard.requireConversationRead`) needs a descriptor field written by conversation setup (engine/internal) — left for that owner.
* Former team members' share notifications need the share subject stored on the notification (store schema change) for a cheap read-time check.
* Control-character scrubbers and domain normalisers (§6) live outside this area.

**Files:** [`ChannelTargetRouter.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/integrations/channels/ChannelTargetRouter.java), [`SlackSignatureVerifier.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/integrations/slack/SlackSignatureVerifier.java), [`SlackEventHandler.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/integrations/slack/SlackEventHandler.java), [`SlackHitlResumeObserver.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/integrations/slack/SlackHitlResumeObserver.java), [`SlackUserIdentity.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/integrations/slack/SlackUserIdentity.java), [`SlackHitlSupport.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/integrations/slack/SlackHitlSupport.java), [`OpenAiAuthFilter.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/integrations/openai/OpenAiAuthFilter.java), [`McpConversationTools.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/mcp/McpConversationTools.java), [`McpHitlTools.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/mcp/McpHitlTools.java), [`McpAdminTools.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/mcp/McpAdminTools.java), [`McpApiToolBuilder.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/mcp/McpApiToolBuilder.java), [`OpenApiSpecFetcher.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/mcp/OpenApiSpecFetcher.java), [`UnauthenticatedRequestGuard.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/security/UnauthenticatedRequestGuard.java), [`ResourceSharingService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/security/spaces/ResourceSharingService.java), [`ConfigGraphResolver.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/security/spaces/ConfigGraphResolver.java), [`WorkspaceNotifications.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/security/spaces/notifications/WorkspaceNotifications.java), [`A2AWireFormat.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/a2a/A2AWireFormat.java), [`A2AModels.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/a2a/A2AModels.java), [`McpToolUtils.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/mcp/McpToolUtils.java), [`HttpClientModule.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/httpclient/bootstrap/HttpClientModule.java); docs: [`slack-integration.md`](https://docs.labs.ai/protocols-and-integration/slack-integration.md), [`webhook-triggers.md`](https://docs.labs.ai/protocols-and-integration/webhook-triggers.md), [`httpcalls.md`](https://docs.labs.ai/agent-configuration/httpcalls.md), [`security.md`](https://docs.labs.ai/security-and-compliance/security.md), [`a2a-protocol.md`](https://docs.labs.ai/protocols-and-integration/a2a-protocol.md), [`workspaces.md`](https://docs.labs.ai/security-and-compliance/workspaces.md), [`group-conversations.md`](https://docs.labs.ai/conversations-and-orchestration/group-conversations.md), [`architecture.md`](https://docs.labs.ai/architecture-and-concepts/architecture.md).

***

## 🐛 fix(groups): review findings — HITL scope, follow-up budget, task-force results, negotiation, JSON extraction (2026-10-31)

**Repo:** EDDI (`fix/review-groups`)

Fixes from the external code review and the CodeRabbit pass against `01c3250`, group-conversation area.

### What changed and why

**HITL authority and read scope**

* **Approvers can no longer cancel another user's running discussion.** The group cancel on REST and on the MCP `cancel_group_discussion` tool now uses `HitlAccessGuard.mayCancelExecuting`, like the 1:1 surface: an approver-only caller gets a paused-only cancel (`cancelPausedDiscussion`, one compare-and-set on `AWAITING_APPROVAL` / `AWAITING_HUMAN_INPUT`) and `403` / `FORBIDDEN` on a running discussion. The Javadoc that claimed both surfaces already did this is now true.
* **Responses no longer hand the transcript to callers who may not read it.** The JSON approve, the human-input submission and the approver cancel return the conversation only to its owner or an admin; an approver or a pending HUMAN member gets `{"state": …}`. MCP `approve_group_phase` and `submit_group_human_input` match.
* **A human-turn resume no longer runs as the submitter.** `resolveHumanTurn` bound the submitting member's identity to the rest of the owner's discussion, so later `${caller:token}` calls went out with their token. It now uses `resumeCallerFor`, the rule the approval resume already followed.
* **Group HITL timeouts are bound to their pause.** Approval `ABORT`, human-turn `ABORT` and `SKIP_TURN` pass the schedule's `pauseId`; a late fire no longer skips a newer human turn or cancels a discussion that has resumed. Stale `skipHumanTurnOnTimeout` Javadoc ("never throws") corrected.

**Discussion engine**

* **Follow-ups respect the cost ceiling and are accounted.** `followUpWithMember` refuses once the effective `maxCostPerDiscussion` is spent (`409`), harvests the member's cost into the ledger, and propagates dynamic-agent tracking so sub-agents created in a follow-up are cleaned up with the discussion.
* **A skipped or errored task-force member fails its task.** It used to complete the task with a `null` result, unblocking dependents that then ran without its output. `SharedTaskList.completeTask` / `submitForApproval` now refuse a `null` result.
* **Negotiation cannot record a stale agreement.** Accepting a proposal withdraws the signer's signature from every other open proposal. An agreement keeps the dissents a dissent round recorded, and an arbitration verdict now replaces a dissent-only `NONE` record instead of being dropped.
* **One balanced JSON extractor for every group engine** (`EmbeddedJson`): facilitator, retro, vote, negotiation, bid, convergence and debate parsers, and the VERIFY phase. The greedy first-`{`-to-last-`}` slice dropped a ballot followed by a brace in prose; the first-`[`-to-last-`]` slice made VERIFY fail open on any bracketed aside. Each engine accepts only an object carrying a key it reads (`vote`/`votes`/`statement`, `bids`, `move`, `lessons`, `accept`/`proposal`/`concessions`, `passed`, `agreementScore`, `winner`), so an unrelated object in the prose (an example, a quoted config, `{}`) is neither taken for the reply nor a rival to it. A reply carrying two *well-shaped* values is ambiguous and rejected — unchanged for the greedy engines (two objects never parsed as one), but a behaviour change for bids and bargain moves, which used to take the first. The documented fail-open on a truly unparseable verdict is unchanged.
* **`groupTranscript` is scoped** by the phase's `contextScope`, like the rendered prompt, and a member conversation's startup step now receives the group's dynamic-agent policy instead of the permissive standalone default.
* **Stance extraction is linear.** `leadSentence` rescanned the prefix at every terminator.

**Dead code:** `GroupConversationService.DEFAULT_ENV`, `PhaseOutcome.endDiscussion` / `END_DISCUSSION` and the unreachable `endDiscussionEarly` handling, and the `findMember` / `findMemberIncludingDynamic` reflective delegators (covered directly by `TaskForceEngineTest`).

### Not done

* Retention revocation (`unretainAgent`) still does not propagate to the group registry, and the discussion-wide creation cap is still checked against a per-member copy. Both need a change in `modules/llm` (`DynamicAgentToolsProvider` / `CreateSubAgentTool`) to record revocations and reserve slots.
* The approval/reject CAS still compares only `state`, not the pause id; that needs a multi-field conditional write in the storage layer.
* The remaining \~24 private delegators in `GroupConversationService` stay until their reflective tests are ported.
* Second review round: the follow-up cost-ceiling lookup propagates store failures instead of meaning "unlimited"; an exhausted `EmbeddedJson` candidate budget is ambiguous, not a unique match; an ABORT no-result task turn stops the following waves; a blank task result is no result; a verification array is accepted only when an element carries a `subject`.

**Files:** [`GroupHitlCoordinator.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/groups/GroupHitlCoordinator.java), [`RestGroupConversation.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/RestGroupConversation.java), [`McpHitlTools.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/mcp/McpHitlTools.java), [`HitlAccessGuard.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/hitl/HitlAccessGuard.java), [`HitlTimeoutHandler.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/HitlTimeoutHandler.java), [`GroupLifecycleOps.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/groups/GroupLifecycleOps.java), [`TaskForceEngine.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/groups/TaskForceEngine.java), [`NegotiationEngine.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/groups/NegotiationEngine.java), [`EmbeddedJson.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/groups/EmbeddedJson.java), [`hitl.md`](https://docs.labs.ai/conversations-and-orchestration/hitl.md), [`group-conversations.md`](https://docs.labs.ai/conversations-and-orchestration/group-conversations.md), [`passing-context-information.md`](https://docs.labs.ai/agent-configuration/passing-context-information.md)

***

## Deployment and script hardening from the code review (2026-10-31)

Repo: EDDI, branch `fix/review-infra`. Low-severity findings in operator scripts and manifests.

* `install.sh`: every Keycloak admin call now sends its bearer token through a 0600 curl config file (`kc_authed_curl`) instead of `-H` on the command line, so it no longer shows in `/proc/<pid>/cmdline`. The already-running repair path verifies the downloaded `keycloak/eddi-realm.json` against the release `SHA256SUMS` before posting scope definitions to Keycloak, and no longer sends stored Keycloak/Grafana admin passwords to a localhost port unless Docker reports a running container of this installation's compose project, for that service, publishing that port; when Docker cannot be queried the credentials are withheld. The check sits in `kc_password_token`, so every password grant is covered. A bearer token is accepted into the curl config only if it consists of token characters, and a failed realm download is truncated so no unverified partial file reaches Keycloak.
* `gcp/provision-vm.sh`: `--vault-key` is removed. The key was appended to the installer flags, uploaded as startup-script instance metadata and echoed into `/var/log/eddi-install.log`; the VM now generates its own master key (in `/root/.eddi/.env` on the VM), like the Keycloak admin password. Passing the flag is an error that says why.
* `docker-compose.yml`, `docker-compose.cluster.yml`, `docker-compose.postgres-only.yml`: the bind guard fails closed. Only `false`/`0`/`no`/`off` (any case) count as "authentication on"; `TRUE`, `1`, `yes`... no longer slip past the refusal.
* `docker-compose.auth.yml`: `keycloak-admin-rotate` writes the `.eddi-admin-verified` marker only after a successful login with the configured credentials. When `KC_BOOTSTRAP_ADMIN_USERNAME` names another user, the original `admin` account is also tried with `admin` and rotated to the configured password if it still accepts it, so a renamed admin user can no longer certify a volume whose `admin/admin` remains. kcadm reads the configured password from `KC_CLI_PASSWORD` (supported by kcadm 26.x) instead of `--password`, so it stays out of the process arguments; stdin is not an option because kcadm's prompt needs a console.
* Helm: `nats.externalUrl` containing `@` is refused (it lands in a ConfigMap); new `nats.externalUsername` / `nats.externalPassword` go to the chart Secret. A password without a username, these values alongside `eddi.existingSecret` (which would make them inert), and these credentials with a non-`tls://`/`wss://` server are all refused at render time; `nats.externalAllowPlaintext=true` is the opt-out for an encrypted transport underneath EDDI. Chart `2.12.0` → `2.13.0`. `docs/kubernetes.md` updated.
* Kustomize: warnings in the ingress component (plain HTTP as shipped; the redirect annotation is named as ingress-nginx-only) and in the auth overlay (remove the localhost redirect URIs outside dev). `k8s/create-secrets.ps1` writes the temporary key file into a private directory made before any cluster change (`mktemp -d`, mode 0700 from creation, on Linux/macOS; a per-user temp subdirectory on Windows), so it works on every PowerShell 7.x and a failure there cannot follow the `-Force` delete.
* `docs-site/scripts/check-live.mjs`: redirects are followed only to the configured origins (parsed origin comparison, not string prefix).
* `scripts/cluster-demo/mock_llm.py`: 10 s socket timeout, 1 MiB body cap, and loopback by default (`demo.py` binds it to the docker bridge gateway with Docker Engine on Linux via `MOCK_LLM_BIND`, keeps loopback on Docker Desktop, including Docker Desktop for Linux, never all interfaces, and aborts when the mock does not come up listening; the README's manual `--external-mock` example sets the same binding). `scripts/loadtest/loadtest.py`: startup state moved from the world-writable `results/` to `scripts/loadtest/.state/` (0700), written atomically through a fresh `mkstemp` file per save (no shared `.tmp` between overlapping runs), a symlinked state directory refused, symlink ignored on read. `src/main/docker/seed-demo-agent.sh`: the provider key goes to curl on stdin, not `-d`, and a key or allowed host with anything but printable ASCII (a trailing newline included) is refused instead of being altered or producing invalid JSON — the curl image has no JSON encoder.

Decision: the shipped k8s base (unauthenticated quickstart), the Prometheus overlay and the other BY\_DESIGN findings are unchanged.

***

## 🐛 fix(ingestion): resource limits in HTML conversion, crawling, extraction and the RAG pipeline (2026-10-31)

**Repo:** EDDI (`fix/review-ingestion`)

Fixes from the external code review and CodeRabbit for the ingestion and RAG modules. Almost all are denial-of-service shapes: compact input from a crawled page or an uploaded file that made a worker do work out of all proportion to its size before any limit was consulted.

### What changed and why

* **Nested HTML tables were exponential** (`HtmlToMarkdownConverter`). Rows and cells were found with descendant selectors, so a table also rendered the rows of every table nested inside it, and again inside the cell holding them; cells restarted the depth count at zero, so `MAX_DEPTH` never applied. Twenty nested tables did not finish. A table now reads only the `tr`s it owns (its children and those of its own `thead`/`tbody`/`tfoot`) and a row only its child cells, with the depth carried through. The same doubling existed for a `summary` or `figcaption` nested below a `details`/`figure`; those are now taken from direct children only. A per-conversion work budget (`Walk`) backs this up: at most 1,000,000 elements visited, and the walk stops writing once the text written is certain to be truncated by the caller's cap; whitespace-only text between tags is not charged, or an indented page with a small cap stopped before its first paragraph. Ordinary tables render as before (checked differentially against the previous converter); a table with several `tbody`s, a `tfoot` or a multi-row `thead` now keeps those rows instead of silently dropping them, and a table whose `thead` is empty takes its first body row as the header.
* **Trailing newlines in a `<pre>` were trimmed quadratically** — one `substring` per newline. Now one backward scan and one copy.
* **Sitemap `<loc>` text was copied once per nesting level** (`WebCrawler.collectText`): only a leaf `<loc>`/`<link>` counts now, and entries longer than the protocol's 2,048 characters are dropped. Links longer than 8,192 characters are not followed. The unused `BYTE_ORDER_MARK` constant is now the one the text-sitemap reader compares against, in place of a unicode escape.
* **Exclude globs no longer compile to a backtracking regex** (`UrlPattern`). A pattern with several wildcards could take combinatorial time on a near-miss path from a crawled page; matching now steps the set of reachable pattern positions per character — pattern length × path length, always. It steps by code point, as the regex did, so `?` still matches one supplementary character. The one difference: `*`, `**` and `?` now match a line terminator (a decoded `%0A` in a path), which the regex's `.` did not, so such a path can no longer slip past an exclusion.
* **Spreadsheet cells were copied in full before the character limit was checked** (`MarkdownTable`). One shared string referenced from 64 header cells rendered hundreds of MB. Each cell is cut to what can still fit before it is normalised and escaped.
* **`maxSegmentsPerRun` was checked after paying for the document that crossed it** (`IngestionPipeline`). It is now checked after splitting and before embedding: a document that would cross it waits for the next run (stamped as looked-at so it is not counted as missing), and a document larger than the whole budget is reported as failed instead of embedded in part.
* **Ownership is re-checked after the embedding provider answers**, before `addAll`, so a run reaped during a stalled provider call can no longer republish a deleted file's chunks.
* **Chunk settings are bounded**: `chunkSize` 1–32768 and `chunkOverlap` ≤ half of it are enforced in `RagConfiguration.validate()`, and both ingestion paths (`IngestionPipeline`, `RagIngestionService`) read them through `chunkSizeOrDefault()`/`chunkOverlapOrDefault()`, which clamp a configuration stored before the check. An imported archive's out-of-range values are clamped the same way (`RagConfiguration.clampChunkSettings()`, from `RestImportService` on create and update) rather than failing the import, and the Manager's chunk-size slider now pulls the overlap down to half the new size, so the default overlap of 64 no longer makes a chunk size of 64 unsaveable. The crawl pipeline's fallback for an explicit `null` was 1000/100 and is now the documented 512/64; `RagIngestionService` threw on an explicit `null`.
* **PDF**: `PdfStreamBudget` remembered neither the next `endstream` nor the last `obj`, so a file of unterminated `stream` keywords was scanned in quadratic time — both are now carried forward. `PdfDecodeBudget` refuses a PNG/TIFF predictor whose declared row exceeds 4 MB before PDFBox allocates its two row buffers. `PdfTextExtractor` now charges the decode budget for the page content PDFBox reads around the counted filters: a lone `/FlateDecode` `/Contents` stream (which PDFBox 3.0.8 inflates with a `FlateFilterDecoderStream` it builds itself — confirmed in the bytecode) is decoded once through the counted filter first, and every reference to an unfiltered content stream is charged its length.

### Design decisions

* The table fix is structural (ownership + depth) and the work budget is a backstop, not the fix: the budget alone would have turned the exponential case into a silently truncated document.
* Over-budget documents are deferred, not truncated: a partially embedded document recorded as ingested would hide its tail until the page next changed.
* Not changed: the review suggested keeping an upload source's files when `forgetSource` fails to remove its chunks. `RagSourceIngestionServiceTest.survivesAVectorStoreThatRefuses` pins the opposite as a deliberate decision — the configuration is already saved, so keeping the files leaves the operator no way to retry — and nothing would ever retry. A durable retirement/retry record is the real fix and is left open.

**Files:** [`HtmlToMarkdownConverter.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/ingestion/HtmlToMarkdownConverter.java), [`WebCrawler.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/ingestion/crawl/WebCrawler.java), [`UrlPattern.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/ingestion/crawl/UrlPattern.java), [`MarkdownTable.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/ingestion/extract/MarkdownTable.java), [`PdfStreamBudget.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/ingestion/extract/PdfStreamBudget.java), [`PdfDecodeBudget.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/ingestion/extract/PdfDecodeBudget.java), [`PdfTextExtractor.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/ingestion/extract/PdfTextExtractor.java), [`IngestionPipeline.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/ingestion/IngestionPipeline.java), [`RagIngestionService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/rag/RagIngestionService.java), [`RagConfiguration.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/rag/model/RagConfiguration.java), [`RestImportService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/backup/impl/RestImportService.java), [`rag-editor.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/components/editors/rag-editor.tsx), [`rag.md`](https://docs.labs.ai/agent-configuration/rag.md), and the matching tests.

***

## 🐛 fix(llm): every model-phase exit records its spend; guardrail redactions reach the summarizer and recall tool (2026-10-31)

**Repo:** EDDI · **Branch:** `fix/review-llm-cost` · Review group H1 (LLM task core: cost accounting, spend gate, guardrails), from the code review report (§3 #2, #3, #4, #12, §5, §6, §7) and the verified CodeRabbit findings

### What changed and why

**Spend of a failed model phase was never recorded (#2).** A task wrote its cost from the result of its model phase, so a phase that threw — a tool loop whose seventh round hit a provider error or the context limit, a cascade step that timed out, a cascade whose every step failed — lost everything it had spent: the tenant's monthly counter and `maxCostPerConversationUsd` never saw it, with or without `onError: fallback`. Now:

* `UnrecordedSpend` carries a failed phase's spend on the failure (a suppressed throwable, so it survives wrapping; drained at most once). The tool loop attaches its answered rounds and tool cost on every failure exit; the cascade folds a failed step's rounds into its run totals, prices a timed-out step's completed rounds from the step's `ToolExchangeRecorder` (which now records each round's usage as it finishes), and attaches the run's totals to the failure it finally throws — including a spend refusal, an open circuit, or a run ceiling (`maxCostPerRun`, duration, turn deadline) reached before a later step when every earlier step had failed.
* `LlmTask.recordSpend` is the one place spend reaches the step; a returned phase, a pause (`recordPrePauseSpend`) and a failure (`recordFailedPhaseSpend`) all pass through it. The returned phase's spend is now recorded as soon as the phase is over, before JSON conversion and `postResponse` can fail the task, and a rejected answer (`responseValidation` `error`, a failed reprompt) records the answer's cost before it rethrows.

**One price decision instead of six (§6).** `ModelPrices` decides which prices a phase is charged at (task, or cascade step → cascade default). The tool loop used the *task's* prices for its mid-loop ceiling and its pause spend even inside a cascade step, so with prices set only on the cascade the ceiling ignored token spend and a pause recorded $0. The cascade now hands the loop its step's prices through the recorder, and a resumed cascade step is priced at that step again.

**Tenant check before a tool call (#12).** It compared the budget against the counter as it stood before the turn. It now passes the step's unmetered `audit:cost` plus the running loop's spend, the figure `LlmSpendGate.admit` uses for every other paid call.

**Redactions leaked through the rolling summary and the recall tool (#3).** Memory keeps the user's text as sent; `pii-redaction`, `regex-filter` and `prompt-injection` re-screen only the history window, so a turn they rewrote reached the summarizer (possibly another vendor), the summary placed in every later system prompt, and `recallConversationDetail` verbatim. `GuardrailService.screenHistoricInput` applies the history rule to one stored text; the summarizer screens the turns it sends and the recall tool the turns it returns. The summary sits in the system prompt inside the retrieved-context provenance envelope. The summary call and a tool result's `summarize` truncation are now admitted by the spend checks and priced at the task's rates (the summary on `audit:cost`, the tool summary as a priced `summarizeToolResponse` tool call). A cross-provider summary no longer inherits `customHeaders`, `customQueryParams`, `customParameters` or provider account keys.

**Guardrails.**

* `pii-redaction` missed a card followed by its CVV or expiry: the greedy run failed Luhn as a whole and was skipped. The digit-group windows of the run are now checked (longest Luhn-valid window wins; an unseparated number is never split), and a run that holds no card is searched again from its next digit group, so groups in front of a card (`ref 1234 4111 1111 1111 1111`) do not hide it. Unspaced `+E.164` numbers count as phones. Every pattern repetition is bounded, so the e-mail scan is linear (it was quadratic on a long local-part run).
* A `warn` output guardrail with `failMode: closed` now forces buffering — it can withhold the answer.
* The `expression` guardrail reads the answer the tolerant way too and treats a disagreement as undecided: strict extraction could skip an earlier duplicate-key object and approve a later one while the task's conversion consumed the earlier.
* The HITL self-checks judge an MCP/A2A call by its arguments as well (`RemoteToolRequestResolvers.Envelope`): the resolved URI is the server, not the conversation or resource the call targets. The approved call's outgoing request is also refused when a `preRequest` instruction pointed it at the running conversation (`ApprovedCallScope` carries the conversation id).

**Tool cost tracking.** A non-finite `toolPricing` value fell through `Math.max` as NaN and poisoned every total; it now falls back to the default price. A timed-out tool call is charged. An entry found over budget is evicted only after every under-budget one, and the conversation whose charge triggered the eviction is never a victim (with the map nearly all exhausted entries it used to go with the other under-budget ones). A tool whose waiting pipeline thread is interrupted (a cascade step timeout, the agent watchdog) is charged like a timed-out one, and a timed-out cascade step is given up to `CANCELLED_STEP_SETTLE_MS` (1 s) to unwind before its tool spend is snapshotted, so that charge lands in the failed step's spend and `maxCostPerRun`. `ToolCostTracker.resetConversation` (unused) is gone.

**Self-ungating argument check.** `SelfUngatingGuard.refusalFromArguments` searched the raw arguments only, percent-decoded, so a JSON unicode escape (`toolApprovals` or an id with one letter written as `\uXXXX`) passed it while every downstream JSON parser read the plain key. It now also searches every key and string value of the arguments parsed as JSON, re-parsing string values that are themselves JSON a few levels deep.

**Streaming.** A tool-loop round that failed after forwarding text was retried into the same sink (partial + full answer); it is now raised as `PartiallyStreamedRoundException`, which the retry does not repeat. Its message is fixed: it used to carry the forwarded character count, and a count of 429 or 502-504 read as an HTTP status to `LlmFailureClassifier`, making exactly that failure retryable again.

**Dead code / docs (§5).** `LlmSpendGate`'s misplaced Javadoc fixed; `AgentOrchestrator`'s unused `DEFAULT_MAX_PAUSES_PER_TURN`, `PAUSE_REASON_MAX_CHARS`, `mergeExternalTools` and the test-only delegators removed.

**Files:** [`LlmTask.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/LlmTask.java), [`ToolLoopRunner.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/ToolLoopRunner.java), [`CascadingModelExecutor.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/CascadingModelExecutor.java), [`ModelPrices.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/ModelPrices.java), [`UnrecordedSpend.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/UnrecordedSpend.java), [`ConversationSummarizer.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/ConversationSummarizer.java), [`GuardrailService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/guardrails/GuardrailService.java), [`PiiRedactionGuardrail.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/guardrails/impl/PiiRedactionGuardrail.java), [`ToolCostTracker.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/tools/ToolCostTracker.java), [`ToolExecutionService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/tools/ToolExecutionService.java), [`ToolLoopStreamingChatModel.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/ToolLoopStreamingChatModel.java), [`SelfUngatingGuard.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/hitl/tools/SelfUngatingGuard.java); docs: [`langchain.md`](https://docs.labs.ai/agent-configuration/langchain.md), [`tenant-quotas.md`](https://docs.labs.ai/security-and-compliance/tenant-quotas.md).

### Design decisions

* **Carry spend on the failure, don't write it as you go.** Writing each round into `audit:cost` immediately would have changed the accounting model of every path; a carrier mirrors the pause's `addSpend` and leaves the success path untouched.
* **Summaries are priced at the task's rates.** No price is configured for a summarizer; the task's model is the same provider and normally the dearer model, so this errs on the side of the budget. A dedicated summarizer price is a possible follow-up.
* **Screen at the consumer, lazily.** The summarizer screens only the batch it sends and the recall tool only the turns it returns, rather than `modelFacingOutputs` screening the whole conversation every turn.

### Not done

* `SecretRedactionFilter` still has no `Cookie`/`Set-Cookie` rule (owned by the secrets area; a fuzzed filter — left for that group).
* The per-conversation tool budget stays in memory (lost on restart); documented, with `maxCostPerConversationUsd` as the durable bound.

***

## 🔒 fix(llm): review findings in the LLM module periphery — secrets, SSRF, tool limits (2026-10-31)

**Repo:** EDDI (`fix/review-llm-tools`)

### What changed and why

Fixes from the two external reviews of revision `01c3250` (CodeRabbit security scan and the code-review report), for the built-in tools, model builders and embedding/A2A tool providers.

**Secrets and destinations**

* **Embedding/vector-store errors no longer quote parameter values.** Parameters reach the factories with vault references already resolved, and RAG search responses and ingestion status return the error message to the editor: a `${vault:…}` reference put in `timeout`, `dimensions` or a store's `port` came back as plaintext. The messages now name the parameter only (and drop the `NumberFormatException` cause, whose message quotes the input); the `model`/`modelName` conflict check runs before resolution.
* **Vertex `apiEndpoint` is an endpoint key** for `allowedHosts` (`ChatModelRegistry.ENDPOINT_KEYS`), and an **OpenAI-compatible preset without `baseUrl`** is checked against the URL its editor-chosen `region` selects (new `ILanguageModelBuilder.defaultEndpoint`).
* **Secret invalidation reaches models built through `${vars:…}`**: the cache key holds unexpanded parameters, so every variable-bearing chat model is evicted with a changed secret.
* **Embedding model and store caches use structural keys** instead of `TreeMap.toString()`, which could render two different parameter maps identically and share one client.
* **Cached model clients re-check their destination before every request.** `BoundedJdkHttpClient` takes the `OutboundTargetPolicy` and validates each request URL (OpenAI, OpenAI-compatible, Ollama, Anthropic, Gemini, Mistral; OpenAI and Ollama embeddings) — a hostname validated once at build was otherwise re-resolved unchecked for the model's whole cache life (DNS rebinding). `docs/security.md` gains a row for this path and names what stays build-time only (other SDK transports, MongoDB Atlas replica-set discovery).

**Tools and providers**

* `WebScraperTool` and `PdfReaderTool` send model-chosen URLs `STRICT`, not `HOPS_ONLY`, so the first hop gets the facade's post-connect re-check. `OpenApiSpecFetcher` (policy `NONE`, own loop) re-validates each hop after the response arrives. `WeatherTool`/`WebSearchTool` keep `HOPS_ONLY`: their hosts are fixed.
* `WebScraperTool.extractWithSelector` refuses CSS escapes (jsoup decoded `:\6d atches` into a regex selector) and sibling combinators `~`/`+` (quadratic evaluation the parse timeout cannot interrupt); the same characters in quotes, attribute selectors, `:contains(…)` text or `:nth-*` formulas are not combinators and still pass (unterminated quotes or brackets fail closed).
* `TextSummarizerTool` splits sentences with a linear pattern (the old one was quadratic on a punctuation run without whitespace). `DataFormatterTool.csvToJson` caps rows and output size; `extractJsonValue` reports a missing/non-array field instead of an NPE.
* `AttachmentTextExtractor` extracts with a bounded stripper: an operator budget, a deadline and interrupt checks (repeated unfiltered forms spent no decode budget).
* A2A discovery bounds agent-name/skill-id length and skill count, logs duplicate skills once per card, and skips a tool name another peer already registered (the later peer's executor used to replace the first's under the first's spec).
* `find_agents_by_capability` filters by the caller's USE rule, as the REST search does. `converse_with_agent` carries the chain's depth ceiling (`delegationDepthMax`, inside the reserved context namespace) so a delegate cannot extend a chain the originator capped.
* Group artifact and task tools honour a member's non-empty `builtInToolsWhitelist` (slugs `artifacts`, `group_tasks`). **Behaviour change on upgrade:** a member whose LLM task already has a non-empty whitelist stops receiving these tools in groups that enable them until `artifacts` / `group_tasks` is added to that list. The Manager's tool picker (`BUILT_IN_TOOLS` in `ui/manager`) now offers both slugs, and switching a task to whitelist mode there selects them along with the rest — they are self-gating, so they enable nothing outside a group that asks for them.
* `FetchToolResponsePageTool` is marked `@ConversationBound` and no longer served from the tool cache.
* `UserMemoryTool` re-checks cancellation right before writing and takes back an insert that landed after the turn was cancelled (erasure race).
* Negative rate limits are refused at save time (`ToolRateLimiter.validateLimits`, called from `LlmStore`); `0` blocks a tool.
* `ObservableChatModel`/`ObservableStreamingChatModel` log model responses at DEBUG, like requests.
* The confidence judge's JSON extraction delegates to the new `ModelOutputParser.extractFirstObject`. Removed the unused `CustomToolConfiguration`.
* Second review round: `UserMemoryTool` no longer deletes anything to make room before the write has landed (the eviction victims are planned first, deleted afterwards, each only if unchanged since it was chosen), and a cancelled turn takes back only its own write, conditionally, leaving a different turn's entry under the same key alone; A2A skill filters compare the skill id as the card gave it, and an id too long for a tool name keeps a hash of the whole id so distinct long ids stay distinct tools.

### Design decisions

* Redaction instead of rejecting vault references in non-credential fields: the leak was the echo, and rejecting would break any config that legitimately keeps e.g. a host in the vault.
* The per-request destination check is the MCP transport's approach (pre-send check, cache-expiry residual), not address pinning — the JDK client has no resolver hook.
* `DataFormatterTool` and `OpenAiCompatibleLanguageModelBuilder.putPath` keep their own path walkers: `PathNavigator` works on maps with `+`/`-` arithmetic (a hyphenated JSON key would resolve to `null`) and its `setValue` neither creates intermediate maps nor copies shared ones.

### Deferred

* Jlama loader allocation/path-traversal findings are in `jlama-core` 0.8.4 (third party); needs an upgrade or an operator allow-list of model repositories.
* MongoDB Atlas replica-set discovery is not re-checked against the outbound policy (documented); forcing `directConnection` would break `mongodb+srv` clusters.
* A store-level erasure generation for user memories (needs `IUserMemoryStore` and `GdprComplianceService` changes).
* Provider-builder `build()`/`buildStreaming()` duplication: langchain4j's separate builder types make a shared helper no cleaner.

**Files:** [`ChatModelRegistry.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/ChatModelRegistry.java), [`EmbeddingModelFactory.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/EmbeddingModelFactory.java), [`EmbeddingStoreFactory.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/EmbeddingStoreFactory.java), [`BoundedJdkHttpClient.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/builder/BoundedJdkHttpClient.java), [`A2AToolProviderManager.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/A2AToolProviderManager.java), [`WebScraperTool.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/tools/impl/WebScraperTool.java), [`security.md`](https://docs.labs.ai/security-and-compliance/security.md), [`secrets-vault.md`](https://docs.labs.ai/security-and-compliance/secrets-vault.md), [`langchain.md`](https://docs.labs.ai/agent-configuration/langchain.md), [`group-conversations.md`](https://docs.labs.ai/conversations-and-orchestration/group-conversations.md)

***

## fix(modules): pipeline-module review findings (2026-10-31)

**Repo:** EDDI (`fix/review-modules`)

### What changed and why

Fixes from the code review and the CodeRabbit sweep over the pipeline modules (`nlp`, `apicalls`, `properties`, `templating`, `rules`, `mcpcalls`).

**apicalls**

* A delayed HTTP call (`preRequest.delayBeforeExecutingInMillis`, retry backoff) no longer hands its blocking send to the single shared `eddi-scheduler` thread. The delay is served on the calling turn thread, so one slow request cannot queue every delayed call in the node behind it, and an interrupted wait sends nothing instead of leaving a queued send to fire later; the thread's interrupt flag is restored when the step fails on it.
* Vault references are found with the linear `SecretReference.scanner()` (request building) and a new linear scanner in `ConfigReferenceGuard`, instead of regex `find()` loops that rescanned the remaining text at every unterminated `${vault:` opener (quadratic work on a long input).
* A vault secret resolved into the URL, body or a query value now disables redirect following, as a header secret already did; the redirect handler would otherwise replay the body on a 307/308 to a host the secret's `allowedHosts` never judged.
* The malformed-JSON warning no longer logs a resolved credential that the parser quoted in its message.

**nlp**

* `POST /parser/{parserId}` rejects an id that is not a store id (hex or UUID) before authorizing it. An id such as `<other>?version=3&x=` was authorized as one resource and resolved to another.
* The merged-terms and Damerau-Levenshtein corrections skip tokens over 100 characters (`ICorrection.MAX_CORRECTABLE_LENGTH`): their cost is quadratic in the token length and the parser limits the number of tokens, not their length.
* `PunctuationNormalizerProvider` no longer stores one parser's `punctuationRegexPattern` in a singleton field that became the default of every parser built afterwards. `PunctuationNormalizer` matches under the same 200 ms regex budget as dictionary regexes, because the pattern can leave its character class.

**properties**

* `scope: "secret"` with `toObjectPath` is rejected on save and at run time (the copy returned before any vaulting). A secret instruction whose value is converted to an object and refused now scrubs the raw input first. Properties extracted earlier in the turn can no longer put a vaulted plaintext back or overwrite a vault reference created in the same execution (one from an earlier turn stays replaceable, as before); a normalized copy of the plaintext (punctuation or whitespace stripped by a parser normalizer) is caught by the same normalization-insensitive match the input scrub uses, and the whole value is replaced. The live output scrub is deep, so a credential in a typed output item (an LLM reply) is removed.

**rules**

* `dependency` conditions evaluate a rule once per evaluation instead of once per path to it; a chain of rules that each depend twice on the previous one cost 2^n evaluations. A remembered result is not reused for a rule on the active trace, so a rule depending on its own (duplicated) name still fails as an infinite loop.
* `connector` `operator` is case-insensitive, defaults to `AND` (as documented) and an unknown value is refused at validation instead of silently becoming `OR`; `getConfigs()`/`clone()` can no longer throw on a connector without one.
* Removed `Rule.clone()`: unused, and it dropped the rule's actions.

**mcpcalls**

* An MCP call without a `retry` block now makes a single attempt (it used to fall through to the shared three-attempt default, so a side-effecting tool could run three times), and retries stop when the turn deadline leaves no room. Inside a turn deadline the attempt runs on the retry helper's executor, so the task now carries the turn's caller across (`CallerIdentityContext.propagate`): without it an MCP server's `apiKey: "${caller:token}"` would have found no caller there and failed closed. An interrupted turn is rethrown as such: it no longer writes an `<name>Error` entry, runs `postResponse` or continues to later calls under `continueOnError`.

**templating**

* `str:concat` and `str:join` are measured before the generated resolver builds them, so reusing one permitted value many times can no longer allocate past `eddi.templating.max-output-chars`. The measurement follows Qute's varargs binding: a list is one argument rendered with its brackets and separators, and only a sole `Object[]` is expanded into its elements.
* Template preview redacts the `snippets` namespace for restricted callers whatever `getAll()` returns.

### Not changed (decisions)

* `SecretPropertyVault` still reads the `tenantId` conversation property: the guard reads the same property and multi-tenancy is not implemented yet; deriving the tenant from trusted context is a product decision.
* `CapabilityMatchCondition` stays unfiltered: rules run off the request thread, where the access guard has no identity to filter by.
* Quick-reply expression values from an HTTP response are not escaped (needs an expression-escaping design); a per-parse regex deadline for `RegularDictionary` and a cumulative loop-result budget in the template engine are left as defense-in-depth follow-ups.
* An MCP attempt abandoned at the turn deadline is not cancelled inside the transport: langchain4j's `DefaultMcpClient` exposes no cancellation of the in-flight request, and a request already sent cannot be recalled by any client-side cancel. Retries stay opt-in, so the tool runs at most once.
* The dotted-path walkers in `OutputMatcher` and `ResponseShapeValidator` are not replaced by `PathNavigator`: its arithmetic-expression fallback and array syntax differ from their strict lookups, and both live outside this area.

**Files:** [`ApiCallExecutor.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/apicalls/impl/ApiCallExecutor.java), [`ConfigReferenceGuard.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/apicalls/impl/ConfigReferenceGuard.java), [`RestSemanticParser.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/nlp/impl/RestSemanticParser.java), [`PropertyInstructionExecutor.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/properties/impl/PropertyInstructionExecutor.java), [`Dependency.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/rules/impl/conditions/Dependency.java), [`Connector.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/rules/impl/conditions/Connector.java), [`McpCallsTask.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/mcpcalls/impl/McpCallsTask.java), [`BoundedFormat.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/templating/impl/BoundedFormat.java)

***

## fix(secrets): review findings on the vault grant check, redaction, connections and legacy sealing (2026-10-31)

**Repo:** EDDI (`fix/review-secrets`)

Fixes from the 2026-10 external review (CodeRabbit plus a manual code review) in `secrets/**` and `connections/**`.

### What changed and why

**Deploy-time grant check (`VaultGrantChecker`): it now reads what the runtime reads**

* A step's config URI is trimmed, as `ResourceUris.require` does at runtime, and the store is picked by an exact match on the **config URI's host**, the key `ResourceClientLibrary` reads with. Before, a URI with surrounding whitespace failed to parse and went unchecked, a step typed with the `ai.labs.langchain` alias went unscanned, and `contains()` on the step type could pick the wrong store, fail, and skip the config.
* Every string value is scanned **on its own**, not the serialized document. An unterminated `${vault:x` in one field used to run on to the next field's closing brace and swallow the real reference behind it.
* A workflow, credential-bearing extension config or `${vars:…}` that cannot be read is now a **violation** (fail closed), as an unreadable connection already was. Unreadable grant *metadata* still counts as granted, as documented.

**Redaction**

* `ConfigSecretRedactor`: a header or query map stored as a JSON string (`customHeaders`, `customQueryParams`) has its entries judged like a real `headers`/`queryParams` map. In a credential field, a value with no reference is always a literal (a scheme word alone included), and symbols or non-ASCII letters beside a reference no longer count as scaffolding.
* Query names are classified **percent-decoded** in `ConfigSecretRedactor`, `SecretScrubber` and `UriRedactor` (`%61pi_key` is `api_key`).
* `UriRedactor`'s shared header rule adds `cookie` and `signature` (substring) and `sig`, `session`, `sessionid`, `sid` (whole word).
* `SecretRedactionFilter`: a connection string with an empty username (`redis://:pw@host`) and a password containing a comma are redacted; Digest directives allow whitespace around `=`. A `Cookie` / `Set-Cookie` header has every cookie value redacted with the cookie names kept (`Cookie: sid=<REDACTED>; theme=<REDACTED>`); `Set-Cookie` attributes such as `Path`, `Expires` and `HttpOnly` stay readable, and a second pass is a no-op.
* Linear time: `SecretRedactionFilter`'s optional vault-reference prefix is bounded (a run of `password:${vault:` was quadratic), and `SecretScrubber`, `VaultHostAllowlist.referencesIn` and `CredentialReferenceResolver` use the linear `ReferenceScanner` instead of `[^}]*` regexes. `SecretScrubber.redactFreeText` restores its masks in one pass.

**Vault**

* `SecretResolver`: a value read while an invalidation ran is no longer left in the cache for the TTL (invalidation counter, re-checked after the put).
* `VaultHostAllowlist.requireAllowed` refuses a reference whose secret does not exist instead of skipping it: on the API-call path it runs after resolution.
* A secret's `allowedHosts` now applies through a connection: a `STATIC`/`BASIC` connection's vault references are checked against the call's target, an OAuth client secret against the token URL (`CredentialReferenceResolver.requireHostsAllowed`).
* `VaultSecretProvider.store`: a rotation is update-only (`ISecretPersistence.updateSecretIfPresent`); a row deleted mid-rotation is treated as a create and needs a grant, instead of being re-created with `allowedAgents: ["*"]`.
* Legacy unbound (no-AAD) data: every open through the fallback is counted (`eddi.vault.legacy.unbound.opened.count`), and `eddi.vault.accept-unbound-legacy-data=false` (default `true`) retires the fallback once a DEK rotation has re-sealed everything. Re-sealing a legacy secret on read also replaces its bare SHA-256 checksum with the keyed form. `decryptSecretWithFallback` (a one-line wrapper) is inlined. The property is in the [configuration reference](https://docs.labs.ai/deployment-and-infrastructure/configuration-reference.md) and the counter in [metrics.md](https://docs.labs.ai/deployment-and-infrastructure/metrics.md), the monitoring guide and the Full Metrics Reference dashboard ("Vault errors" panel). `updateSecretIfPresent` and the checksum-replacing re-seal have their own unit tests on both stores.
* `RestSecretStore.updateGrant` evicts cached clients when the host list was written, even if the grant write after it is refused (409) or fails.
* `AutoVaultedSecrets.belongsToUser` reads the owner from the slot's second segment only; a property name carrying another user's hash no longer makes the slot theirs.

**Connections**

* `RestConnectionStore.createConnection` requires `eddi-admin` in the implementation too: the archive import (open to `eddi-editor`) called it directly. An editor's import now skips connections with a logged reason.
* The OAuth callback re-reads its claimed state row after storing the grant and discards the grant if the row is gone: a GDPR erasure that ran during the token exchange no longer leaves a live refresh token behind (`IOAuthStateStore.exists`, Mongo and Postgres).
* A `client_credentials` mint checks the connection's id before the exchange and after the write, and discards the grant if the connection was deleted or re-created under the same name meanwhile.
* `requirePrincipal` refuses a user whose principal name is the reserved `__service__`.
* Docs: the `enabled` connections switch governs account linking only; it does not stop `${connection:…}` resolving ([Connections](https://docs.labs.ai/protocols-and-integration/connections.md)).

### Design decisions

* **Store chosen by config-URI host, not step type.** Whichever task a step runs, the document it loads is the one the config URI names, so that is what the scan reads.
* **`accept-unbound-legacy-data` defaults to `true`.** Turning the fallback off before a rotation would make never-read legacy rows unreadable; the counter tells the operator when it is safe.
* **The connections master switch was documented, not enforced on resolution.** It defaults to off, and `STATIC`/`BASIC` connections work with it off today; enforcing it would break those deployments.

### Not changed

* `VaultGrantImpactAnalyzer`: a deployment racing a restrictive secret creation is still unseen (already documented). Closing it needs a post-record re-check on the deploy side (`AgentFactory`), outside this area.
* `ConnectionRegistry` can re-cache the previous version of an updated connection for up to its one-minute TTL: the descriptor advances in `DocumentDescriptorFilter` (engine) after the store has invalidated.
* `allowedHosts` entries without a port still admit `http`; requiring https for vault-backed hosts is a policy decision.
* A Qute-looking credential value such as `{abc}` is still read as a template.

***

## chore(ui): review cleanup — RTL icon mirroring, dead code, chat query keys (2026-10-31)

**Repo:** EDDI (`chore/review-ui-cleanup`) — Manager (`ui/manager`) and Chat UI (`ui/chat`) only. The behavioural fixes from the same review are on `fix/review-ui`.

### What changed and why

* **RTL:** directional arrows and chevrons carry `rtl:rotate-180` — 59 icons across the Manager plus the three page-local `BackLink`s (`agent-detail`, `conversation-detail`, `workflow-detail`). In Arabic they pointed the wrong way: "back" arrows pointed forward and collapsed chevrons pointed at the content. [`rtl-directional-icons.test.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/test/rtl-directional-icons.test.ts) scans the sources so a new left/right arrow or chevron without an `rtl:` variant fails the unit run.
* **Dead code removed:** `use-coordinator.ts` and `createCoordinatorEventSource`, `useUpdateAgentWorkflows`, `useDeployAgent`, `formatDateOnly`, `mapIfArray`, `debounced-inputs.tsx`, `cascadeHasErrors`, `EVENT_STATES`/`MATCH_OPS`, the Variables page's unreachable `copyRef` template branch, six unreferenced type aliases, and the Chat UI's `SUPPORTED_LOCALES`, with the tests that only exercised them.
* **Query keys:** `chatKeys` in [`query-keys.ts`](https://github.com/labsai/EDDI/tree/main/ui/packages/app-kit/src/lib/query-keys.ts) replaces nine hand-typed `["chat","deployedAgents"]` keys, and the `agentKeys` header no longer claims `agentKeys.all` clears the detail, descriptor and prompt entries.

### Design decisions

* Not changed: the SSE payload interfaces in `hitl.ts`/`groups.ts` that nothing references (they document the wire format next to their used siblings), the remaining \~100 single-hook literal `queryKey` arrays (the header allows a key read and invalidated inside one hook), and `getDeadLetters`/`replayDeadLetter`/`discardDeadLetter`/`purgeDeadLetters` (still wrapped by tests).
* No behaviour change is intended: the branch is independent of `fix/review-ui` and merges cleanly with it in either order.

### Tests

`npm run typecheck`, `npm run lint`, `npm run i18n:check` and the full Vitest run in `ui/manager`; `npm run typecheck`, `npm run lint` and `vitest run` in `ui/chat`.

***

## fix(ui): review findings in the Manager and Chat UI — operator gate check, approval binding, hostile-input bounds (2026-10-31)

**Repo:** EDDI (`fix/review-ui`) — Manager (`ui/manager`) and Chat UI (`ui/chat`) only. The mechanical half of the same review (RTL icon mirroring, dead code, `chatKeys`) is on `chore/review-ui-cleanup`.

### What changed and why

**Platform Operator**

* `gateLooksInstalled` ([`operator.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/api/operator.ts)) now judges a gate the way the backend's `ToolApprovalPatterns` matches it: `*` is a wildcard anywhere in a pattern. An `exempt` entry is refused when it can match any `http.{post,put,patch,delete}:/…` address (`*:*`, `h*`, `*post*`, `http.*:/x` all pass the old check and exempt every write at runtime, `exempt` being tested first), and the same test now applies to the AUTO\_APPROVE `rules` check, which used to omit the `http.*:` prefix. `requireApproval` must cover **every** write method with a `<head>*` pattern — a PATCH-only gate used to certify an operator whose POST/PUT/DELETE calls ran unapproved. The gate `buildToolApprovals()` writes (all four methods, unchanged since it was introduced) passes, so no shipped operator is newly reported as ungated. A per-task `toolApprovals` override lives in the llmstore document and is not inspected here; the backend's default `strict` mode only lets it strengthen the agent gate. The verifier is outside the revision fingerprint (the prompt, allow-list and `buildToolApprovals()` are unchanged), so `operator-revision.json` stays at its value.
* The same judgement drives the `agentCreatedWithoutGate` approval warning, which now also fires for a gate covering only some write methods; its text (all 11 locales) says the gate does not cover every write method instead of claiming there is no gate.
* The operator chat's resume now carries a `pauseId` ([`use-operator-chat.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/hooks/use-operator-chat.ts), [`operator.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/pages/operator.tsx)): the id of the pause the card showed, else the displayed pause's start, else the pause read just before the resume. If the displayed pause and the one read now differ, the decision is refused client-side. A top-level REJECTED could previously land on a pause nobody had looked at.
* The cascade approval preview reads `redeploy`/`compatible` the way Jackson's default coercion does — `"true"`, `"True"`, `"TRUE"` (trimmed) and any non-zero integer are true — so a redeploy requested in one of those forms no longer shows as none.

**Hostile or oversized input (Manager)**

* [`group-utils.ts`](https://github.com/labsai/EDDI/tree/main/ui/packages/conversation/src/team/group-utils.ts): the markdown link-destination mask is bounded (`](` runs with no `)` rescanned the text from every opener, \~5 s per 100k characters); `maskIndentedCode` builds its line table once instead of re-splitting the prefix for every indented run; the ✅/❌ verification header is parsed with string steps and a per-line cap instead of a backtracking regex. `formatJsonSafely` (artifacts panel) returns content over 64 KiB or nested deeper than 32 as written. The sync diff viewer gives `diffLines` a time budget and falls back to one removal plus one addition.
* `useLatestVersions` counts only descriptors whose own id is the requested resource (the `filter=` search is a substring match); erasure also sweeps the `workforce-analytics` cache; a conversation loaded for one agent is refused when it belongs to another; selective export sends the snippet and schedule selections (an empty list means none) instead of exporting every one.

**Correctness**

* Agent config number fields keep a typed `0` (`pruneStaleAfterDays: 0` was saved as 90, the opposite of "never prune"); the Dream cost default shown is the backend's 0.50, not 5.
* "Switch to latest" is disabled while the editor holds unsaved edits. The Workforce settings page reads the group's **current** version when the URL names none (and offers Retry if the lookup fails), registers with the in-app navigation guard, and its delete flow (like the agent, channel and group-config delete flows) calls `allowNextNavigation()`. A deleted group discussion no longer re-selects itself while the list still holds it.
* The Variables page documents `{vars.key}` (Qute), not `{{vars.key}}`, in all 11 locales. RAG ingestion shows translated status labels (9 new `ragEditor.status*` keys, all 11 locales), polls for \~11 minutes (2 s, then 10 s) and then says "stopped checking" instead of declaring a failure while the server is still ingesting; `kbId`/`ingestionId` go through `seg()`.
* The deploy/undeploy button no longer acts on another agent's status shown as placeholder data. The tool-approval pattern validator accepts `/ { }` and method-qualified `http.<method>:` patterns like the backend and rejects the shapes it rejects. Upgrade preview and live sync send `X-EDDI-Space`; the cluster activity stream re-reads the bearer token on each reconnect. The update-check card now says the request origin is sent (a CORS fetch always carries `Origin`).
* Chat UI: `embed-auth` backs off (10 s doubling to 5 min) when the host keeps handing over an already-expired token, instead of re-requesting every 5 s forever.
* Second review round: the export sends an empty snippet/schedule selection (not an omitted one) when the preview lists none of that type; a stopped RAG ingestion row says "Last known" and has a "Check again" action; the markdown link-destination pattern takes its run atomically (about twice as fast on a hostile 100k-character input; the remaining cost is the bounded forward scan) and a verification header is bounded by its header part, not the whole line; the operator gate check matches wildcard patterns with a linear matcher (`lib/glob.ts`, shared with the HITL pattern validator) instead of a generated regular expression that went exponential on runs of `*`; after a `PauseChangedError` the approval status is keyed to the pause that is paused now; Deploy stays unavailable until the version's status is known (first fetch and failed lookups included); deleting a discussion drops its retained stream.

### Design decisions

* `ui/manager/AGENTS.md` now says the app runs under a data router (`createBrowserRouter`), as `main.tsx` and §4b already did.
* The Variables page's unreachable `copyRef` template branch (it still builds `{{vars.key}}`) is left alone here: `chore/review-ui-cleanup` deletes it, and editing it on both branches would make the two PRs conflict.

### Tests

Focused vitest suites for each fix; `npm run typecheck`, `npm run lint` and `npm run i18n:check` pass in `ui/manager`; `npm run typecheck`, `npm run lint` and `vitest run` pass in `ui/chat`. `resource-detail-rag-upload-source.test.tsx` (3 tests) fails on the base commit as well and is untouched.

***

## CI: the changelog collation PR no longer runs the Java suite (2026-10-27)

**Repo:** EDDI, branch `ci/skip-tests-on-collation-pr`.

**What changed:** `.github/workflows/ci.yml` — `detect-changes` now forces `operator_docs=false` for a pull request whose head is this repository's own `chore/collate-changelog` branch **and** whose diff contains only files the collator writes (`docs/changelog.md`, `docs/changelog.d/*`, `docs/changelog/*.md`, `docs/SUMMARY.md`). Build & Test and the dependent jobs are skipped for it; a skipped required check still satisfies branch protection.

**Design decisions:** the exemption checks the diff as well as the branch name, because a name alone was already abused as an opt-out of the Changelog Discipline job. Any other file on that branch restores full gating.

***

## 📐 feat(docs-site): resizable and hideable sidebars (2026-10-27)

**Repo:** EDDI (`feat/docs-site-resizable-sidebars`)

### What changed and why

The docs site's two sidebars — navigation on the left, "On this page" on the right — can now be resized and hidden on desktop, so a reader can give the page the room it needs.

* **Resize:** drag a sidebar's inner edge. The handle is also a keyboard control (`role="separator"`, ← → in 16px steps, Home/End for the limits, double-click to reset), with limits of 200–520px (navigation) and 180–480px (table of contents).
* **Hide:** a button in the header for each side — before the logo for the navigation, before "Website" for the table of contents — with `aria-expanded` and a label that says what it will do.
* **Remembered:** widths and hidden sides are kept per browser in `localStorage` (`eddi-docs-layout`) and applied by an inline script before first paint, so pages do not jump. That script is generated from the same functions the drag code uses ([`sidebar-layout.mjs`](https://github.com/labsai/EDDI/tree/main/docs-site/src/lib/sidebar-layout.mjs)), so its limits cannot drift; a test runs it against a fake document.
* Starlight sizes both sidebars from one `--sl-sidebar-width`; each side now has its own variable, and the right sidebar's fixed box gets an explicit width (Starlight relied on a fixed-width inner container). Drags measure against `documentElement.clientWidth`, not `innerWidth`, so the right pane's edge stays under the pointer when the page has a scrollbar — both found while testing in the browser.
* Desktop only: the navigation from 50rem, the table of contents from 72rem. Phones keep Starlight's own menu and "On this page" dropdown, untouched.
* `docs/mcp-server.md`: the same one-line anchor fix as #1166 (identical bytes, so whichever lands first, the other merges cleanly), so this branch builds against today's `main`.

### Verification

* `npm test` in `docs-site/`: 65 tests, 11 of them new for the layout logic; mutation-checked (swapping the right pane's arrow direction, dropping the clamp from the pre-paint script).
* In a browser at 1440px: dragging each edge (left to 400px, right to 404px with the edge exactly under the pointer), keyboard steps and Home, hiding and showing both sides (content re-centres, handles disappear, labels flip), persistence across reloads with no flash, double-click reset; at 375px nothing new appears and nothing overflows.

***

## SSE keep-alive on turn streams (2026-10-27)

**Repo:** EDDI · **Branch:** `feat/sse-keepalive`

**Problem.** A turn can go a minute without a single SSE event: a model that is working out a tool call, or a structured (JSON) reply, emits no tokens until it is done. Load balancers and proxies close a connection that carries no bytes for their idle timeout — 60 s on an AWS ALB by default — and with `eddi.streaming.cancel-on-client-disconnect` on (the default), that close also discards the turn. Seen in a production-like deployment on 2026-10-27: a turn spent about 50 s before its first action, and the slowest ones run past 60 s.

**Change.** `RestAgentEngineStreaming` writes an SSE comment line, `: keep-alive`, on a turn stream that has carried nothing for `eddi.streaming.keepalive-interval-seconds` (default `15`, `0` turns it off).

* One daemon thread (`eddi-sse-keepalive`) ticks every open turn stream at the interval; a tick writes only when the stream has been silent for the whole interval, so a stream of tokens carries no extra frames.
* Writes to the sink are serialised, so a comment never lands between the lines of an event.
* The tick stops when the stream ends (`done`, `error`, start failure) or the client is gone.
* A tick that finds the sink closed, once the turn has written an event of its own, is handled like any send to a vanished client: with `cancel-on-client-disconnect` on, the turn is cancelled during the silent stretch instead of at its next event, on a separate thread so the cancel's store work does not delay other streams' ticks. Before its first event a turn may still be queued behind another turn of the same conversation, whose cancel would hit that other turn, so the tick then only stops and the turn's own first event handles the disconnect, as before. A send that fails on a sink that is still open is not taken for a disconnect, as before.
* The tick runs every quarter interval, so the longest silence is about 1.25 intervals.
* SSE clients ignore comment lines by definition, so no consumer changes. `docs/rest-api-reference.md` notes that a hand-written parser must skip lines starting with `:`.

**Files.** `RestAgentEngineStreaming.java`, new `RestAgentEngineStreamingKeepAliveTest` (9 tests, the scheduler and clock replaced so each tick runs by hand), [`configuration-reference.md`](https://docs.labs.ai/deployment-and-infrastructure/configuration-reference.md), [`rest-api-reference.md`](https://docs.labs.ai/conversations-and-orchestration/rest-api-reference.md).

**Decision.** Comment frames rather than a named `ping` event: a named event reaches every client's handler and some treat unknown events as errors, while comments are dropped by every SSE parser. The interval is a setting because the right value depends on the shortest idle timeout between EDDI and the client.

***

## An untyped context entry is a 400, not a 500 (2026-10-27)

**Repo:** EDDI · **Branch:** `fix/context-entry-without-type`

**Problem.** `POST /agents/{agentId}/start` answered `500` with a `NullPointerException` ("`contextType` is null") when a context entry had no `type`. The usual cause is a caller wrapping the map in `{"context": {…}}`: the start body *is* the context map, so Jackson reads `context` as one entry with no type, and `ConversationMemoryUtilities.prepareContext` switched on it. Found on a staging deployment while scripting an end-to-end test; a `say` with an untyped entry went the same way.

**Change.**

* `RestAgentEngine.requireTypedContext` refuses a null or untyped entry with `400` `{"error": {"code": "INVALID_CONTEXT", …}}` naming the key and the valid types. It runs on `start`, on `say` and on the streaming `say`, before the turn is queued or the stream is opened, next to the existing input checks.
* `prepareContext` skips an untyped entry like an unknown type instead of throwing, so a producer other than these three endpoints cannot crash a turn with it either.
* [`rest-api-reference.md`](https://docs.labs.ai/conversations-and-orchestration/rest-api-reference.md) documents the rule.

**Tests.** `RestAgentEngineClientContextTest` (start, say and streaming say: 400, nothing forwarded, no SSE frame) and `ConversationMemoryUtilitiesTest` (an untyped entry is skipped, the others kept).

***

## 🔀 fix(docs-site): docs.labs.ai redirects with a 301, kept forever; repair the docs build on main (2026-10-27)

**Repo:** EDDI (`fix/docs-site-301-redirects`)

### What changed and why

**301, not 308.** The decision for the docs move is now final: `docs.eddi.technology` is canonical, and `docs.labs.ai` answers every path with a **301** to the same path there, for good (released images print docs.labs.ai links forever). The generated redirects used Vercel's `permanent: true`, which sends a 308. That is just as permanent, but 301 is what was decided and what every crawler and HTTP client has always read as a move. [`redirects.mjs`](https://github.com/labsai/EDDI/tree/main/docs-site/scripts/redirects.mjs) now writes an explicit `statusCode: 301` on all 434 rules (`REDIRECT_STATUS`), and a test fails if any rule loses it or uses `permanent` again. Vercel's own `trailingSlash` redirect (`/x` → `/x/`) stays a 308, because it cannot be configured; [`check-live.mjs`](https://github.com/labsai/EDDI/tree/main/docs-site/scripts/check-live.mjs) therefore checks the status of the hop that *leaves* docs.labs.ai and requires it to be the 301, whichever order Vercel runs the two in.

**The Vercel project now builds from the repository root.** The `eddi-docs` project was created with Root Directory `docs-site`, and Vercel checks that the Root Directory exists *before* any ignore step runs — so every push to a branch without `docs-site/` failed, with a failure email: the orphan `metrics` data branch that `docker-pull-notify.yml` writes every 10–35 minutes, and every branch cut before the site existed. The Root Directory is now the repository root (it exists on every branch), `vercel.json` moves to the repository root (Vercel reads it from the Root Directory) with `cd docs-site && …` commands and output `docs-site/.generated/dist`, and the ignore step `test ! -d docs-site || git diff --quiet HEAD^ HEAD -- docs-site docs PRIVACY.md vercel.json` skips a branch without the site and any commit that does not touch the docs. The project settings carry the same commands, for branches without the root `vercel.json` (`main` until this merges). The Docs Site workflow now also watches `vercel.json`, and a test pins the layout.

**Only `main` deploys.** Decided the same day, after branches that had merged a broken `main` (the ratings anchor below) started failing their previews and emailing: the ignore step now begins with `[ "$VERCEL_ENV" != production ] ||`, so every non-production deployment — every branch and pull request — is skipped. Pull requests keep the `Docs Site` check, which builds the site and validates every link; the project setting carries the same command. On `main`, "did the docs change?" is asked against the last successful deployment (`$VERCEL_GIT_PREVIOUS_SHA`), not `HEAD^`, so a docs build Vercel cancelled is still published by the next commit; without a previous deployment in the clone, it builds. (Vercel caps the project setting at 256 characters, so the command is written compactly; a test holds it under the cap.)

**`main`'s Docs Site check was red.** #1136 (conversation ratings) linked `mcp-server.md` to `conversation-ratings.md#mcp-tools-and-the-platform-operator`, a section that page does not have, so the docs build has failed on every push to `main` since. The link now points to the section that describes the same scoping — "Analyzing and triaging (the people running the agent)". The ratings page's status note says it covers the MCP rating tools, but it has no section on them; adding one is for the ratings work, not this fix.

### Verification

* `npm test` in `docs-site/`: 55 tests, including the new 301 test.
* `check-live` against a local stand-in for Vercel that applies `vercel.json`, with a second port posing as docs.labs.ai: every legacy URL ends on the right page on the canonical host, leaving the legacy host with a 301. With the host rule switched back to `permanent` (308), the legacy checks fail.

### Next

The cutover itself: phase 5 of [`planning/docs-site-migration-plan.md`](https://github.com/labsai/EDDI/tree/main/planning/docs-site-migration-plan.md).

***

## 🐛 fix(hitl): email-notification review follow-ups (2026-10-27)

**Repo:** EDDI (`fix/hitl-email-review-followups`)

### What changed and why

Follow-up to the HITL email notifications PR (#1141), for the review threads left open when it merged.

* **Docs and Javadoc named the wrong thing.** The `email.notify` audit entry carries `recipientPseudonym` (the GDPR pseudonym token: keyed with the audit ledger's key, salted per deployment when it has none, and an unsalted hash only when a deployment has neither) next to `recipientDomain`, and the rate-limit WARN names the recipient by that same pseudonym. [`hitl.md`](https://docs.labs.ai/conversations-and-orchestration/hitl.md), [`configuration-reference.md`](https://docs.labs.ai/deployment-and-infrastructure/configuration-reference.md) and the `HitlEmailNotifier` class Javadoc still said "SHA-256 hash" / "by hash", which would send an operator looking for a value that is never written.
* **Manager: off then on again lost the typed recipients.** Switching email notifications off clears the stored list, and the effect that resyncs the field to the stored list then emptied the draft, so switching back on (before saving) came back empty. The typed list is now kept when the user switches it off.
* **Manager: internationalised domains were rejected.** The server converts the domain to ASCII (`AddressNormalizer`, `IDN.toASCII`) and accepts `ops@bücher.example`; the Manager's check was ASCII-only and marked such an agent invalid. The domain is now converted the same way before it is checked (the local part must still be ASCII, as on the server), and the Unicode and punycode spellings of one domain count as a duplicate. [`hitl.md`](https://docs.labs.ai/conversations-and-orchestration/hitl.md) now says so. Two further gaps CodeRabbit found in that conversion are closed: URL syntax after the domain (`/path`, `?q`, `#f`, `:25`, a backslash, `%`) is refused instead of being parsed away, and a domain containing ß, ς or a zero-width (non-)joiner is refused, because the platform's IDNA processing keeps those and the server's `IDN.toASCII` maps or drops them, so the two would normalise the domain differently (the punycode spelling stays valid).
* **No change needed:** the metrics dashboard panel ids are unique and the split dashboard parts are in sync with the source (`sync-monitoring-assets.py` produces no diff); the collision the thread described was renumbered after the review.

### Design decisions

* The Manager still sends the addresses as typed; normalisation stays the server's job.
* Browser IDNA conversion (`new URL`) stands in for `IDN.toASCII`, with the known divergent characters refused outright; the backend remains the authority and answers 400 for anything the two still disagree on.

***

## perf(audit): the stored conversation no longer repeats the prompt and response the ledger holds (2026-10-27)

**Repo:** EDDI (`perf/audit-copies-out-of-memory`)

### What changed and why

With auditing on, `LlmTask` writes `audit:compiled_prompt` (system prompt plus prompt) and `audit:model_response` to every step so `LifecycleManager` can build the ledger entry. Nothing removed them afterwards, so the full text lived in the conversation document too. On a measured 1.6 MB, 20-step conversation the compiled prompt alone was 325 KB (20%) and the model response 39 KB. Large documents slow every read and write of a conversation, and a deployment whose link to MongoDB is bandwidth-limited felt it directly.

* **Release after hand-over.** `Conversation` (say and resume paths) calls `TurnAuditBuffer.releaseLedgerOwnedEvidence` once the turn's buffer has been flushed and the ledger accepted every entry. Within the turn nothing changes: the entries are built, buffered and redacted exactly as before; the keys are removed afterwards, before the conversation is stored.
* **Only what was accepted.** `AuditLedgerService.submit` now returns whether the entry was queued, and the collectors `ConversationService` and `ConversationHitlService` install implement the new `IAuditEntryCollector.Acknowledging`. `TurnAuditBuffer.flush` returns false if any entry was refused (full queue) or any submit threw, and then the evidence stays in the stored step. A plain collector (tests) counts as accepting unless it throws.
* **Paused turns keep it.** A turn that ends `AWAITING_HUMAN` resumes from the stored step, so the keys stay until the resume that completes the turn.
* **Deliberately kept:** `audit:tool_calls`, `audit:token_usage`, `audit:cost`, `audit:model_name` and the guardrail records. Agent tests read tool calls, cost and model from the stored step (`TurnObservation.fromSnapshot`), the `/v1` adapter reads token usage, and the history replay reads the guardrail records. They are small by comparison.
* **No consumer needed the removed keys.** Searched the Manager UI, Chat UI, REST and MCP surfaces, conversation log, exports and GDPR export: the only reader of the two keys is `LifecycleManager.buildAuditEntry`, inside the turn. The text is read from the ledger (`GET /auditstore/{conversationId}`). Documented in [`audit-ledger.md`](https://docs.labs.ai/security-and-compliance/audit-ledger.md).
* **Auditing off:** the keys are never written and no code path changes.
* **Already-stored conversations** keep what they hold; only new turns are slimmer.

**Files:** [`TurnAuditBuffer.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/audit/TurnAuditBuffer.java), [`IAuditEntryCollector.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/audit/IAuditEntryCollector.java), [`AuditLedgerService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/audit/AuditLedgerService.java), [`Conversation.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/runtime/internal/Conversation.java), [`ConversationService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/ConversationService.java), [`ConversationHitlService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/ConversationHitlService.java); tests `ConversationAuditEvidenceReleaseTest`, `TurnAuditBufferTest`, `AuditLedgerServiceTest`.

***

## ⚡ perf(conversations): current-step and approval-status reads no longer transfer the whole conversation (2026-10-27)

**Repo:** EDDI (`perf/slim-conversation-reads`)

### What changed and why

Every read of a conversation loaded its whole stored document, and for an agent with tools that document is 0.5–3 MB after twenty turns, almost all of it step history. On a staging deployment whose link to MongoDB was intermittently bandwidth-limited (\~100 KB/s for whole-document reads, while small reads stayed at 0.3 s and EDDI itself was idle), `GET /agents/{conversationId}/approval-status` and the chat-reload read `GET /agents/{conversationId}?returnCurrentStepOnly=true` took 11–29 s, and the approval card's spinner showed for that long. Both responses describe only where the conversation is now.

* **New store read, `IConversationMemoryStore#loadConversationMemoryTail`**, returning a `ConversationMemoryTail`: the document with `conversationSteps` and `conversationOutputs` cut to their last element, no `redoCache`, and none of the pending tool-call batch's resume-only fields (`chatTranscriptJson`, `gatingAssistantMessageJson`, `traceSoFar`, `fingerprint`, each call's `argumentsRaw`), plus the totals the projection still needs from what stayed behind — step, output and redo counts, and the `audit:cost` / `audit:discarded_cost` values for `conversationCost`. **MongoDB:** one aggregation (`$match` on `_id`, `$set` with `$slice: -1` and the computed totals, `$unset`). **PostgreSQL:** one query using `->-1`, `jsonb_array_length` and `jsonb_path_query_array`. The spend values come back in document order and are summed in Java with the same filter and the same left-to-right addition as before, so the cost is bit-identical, not merely close.
* **`IConversationMemoryStore#loadConversationMemorySnapshotForApprover`** for `approval-status?detail=full`: that response *is* the whole snapshot, so it still carries the history; only the resume-only batch fields — which `sanitizePendingToolCallsForApprover` nulls before serving — stay on the server (MongoDB: all five; PostgreSQL: the four batch-level ones, `argumentsRaw` sits inside an array `#-` cannot wildcard and is small).
* **Wired into:** `ConversationService.readConversation` (both overloads) when `returnCurrentStepOnly=true` — which serves REST `GET /agents/{conversationId}`, the managed-agent read, MCP `read_conversation` and the A2A status read; `RestAgentEngine.getApprovalStatus` and `McpHitlTools.getApprovalStatus` (summary → tail, `detail=full` → approver read). A RULE pause's `pauseDetails.actions` comes from the tail's last step; only when that step has no actions does it load the full history and walk back, as before.
* **Unchanged:** every write path, undo/redo, resume, the conversation log, export, `returnCurrentStepOnly=false` (and `null`), and every other caller of `getConversationMemorySnapshot` / `loadConversationMemorySnapshot`.
* `ConversationMemoryUtilities.convertSimpleConversationMemory` was split into a shared body taking the rendered lists plus the totals explicitly, so the full-snapshot and the tail projection run the same code.
* A document still storing a step under EDDI 5's `packages` key (read by the load's `@JsonAlias`, not by the server-side expressions) is detected in the same round trip and loaded in full, so its cost is never under-counted.

**Files:** [`ConversationMemoryTail.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/memory/ConversationMemoryTail.java), [`IConversationMemoryStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/memory/IConversationMemoryStore.java), [`ConversationMemoryStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/memory/ConversationMemoryStore.java), [`PostgresConversationMemoryStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/datastore/postgres/PostgresConversationMemoryStore.java), [`ConversationMemoryUtilities.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/memory/ConversationMemoryUtilities.java), [`IConversationService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/api/IConversationService.java), [`ConversationService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/ConversationService.java), [`RestAgentEngine.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/RestAgentEngine.java), [`McpHitlTools.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/mcp/McpHitlTools.java). Tests: `ConversationMemoryTailParityTest` (Testcontainers MongoDB + PostgreSQL: for a READY 20-turn conversation with spend and a redo entry, a one-turn conversation, a TOOL\_CALL pause, a RULE pause, a secret last turn, a drifted steps/outputs document and an ERROR turn, the tail projection serializes to the same JSON as the full one for every `returnDetailed` × `returningFields` combination; the approver projection of the slim approver read equals that of the full read; legacy `packages` fallback; unknown ids), `ConversationServiceTest$ReadConversationSingleArg`, `RestAgentEngineToolPauseDetailsTest$RulePauseDetails`, plus the HITL REST/MCP tests re-stubbed for the new reads.

### Not covered

`detail=full` still transfers the step history — the response is the full snapshot. The Manager's own approval card uses the summary.

***

## 📚 feat(docs-site): redirects for every URL GitBook ever served, CI, and the cutover kit (2026-10-27)

**Repo:** EDDI (`feat/docs-site-astro`)

### What changed and why

Phases 2–4 of [`planning/docs-site-migration-plan.md`](https://github.com/labsai/EDDI/tree/main/planning/docs-site-migration-plan.md). After this, moving docs.labs.ai off GitBook is a Vercel project and a DNS record — the checklist is phase 5 of the plan.

* **Fidelity (phase 2), by script over all 94 pages.** Source against build: the same number of tables and code blocks, and no Markdown leaking into rendered text. GitBook against build: 98.4% mean word coverage, every gap GitBook's page chrome or text that changed on `main` after the branch was cut.
* **Every old URL keeps working (phase 3).** [`docs-site/legacy-urls.txt`](https://github.com/labsai/EDDI/tree/main/docs-site/legacy-urls.txt) lists every URL docs.labs.ai has served — today's sitemap, the Wayback Machine's older flat and chatbot-era URLs, the links in this repo and the website. [`scripts/redirects.mjs`](https://github.com/labsai/EDDI/tree/main/docs-site/scripts/redirects.mjs) generates `vercel.json`'s redirects from it: docs.labs.ai → the same path on docs.eddi.technology, then each legacy path in its plain, trailing-slash and `.md` forms, then a per-section fallback. Pages whose slug contains a dot (`upgrading-from-6.4`) get an explicit slash redirect, because `trailingSlash` takes `.4` for a file extension and would 404 them — found by the new checker.
* **A guard over docs links in the repository.** Every docs URL written in the backend, the UIs, README, CONTRIBUTING, AGENTS, the plugin and `.github/` must land on a page, anchor included. Released images print those links forever; three of them 404 on GitBook today.
* [**`scripts/check-live.mjs`**](https://github.com/labsai/EDDI/tree/main/docs-site/scripts/check-live.mjs) checks a deployment over HTTP — 693 URLs followed hop by hop. Run locally against a stand-in for Vercel's serving of `vercel.json`, it found the dotted-slug 404s and a generator bug that rewrote an external `…/CONTRIBUTING.md` target to `…/CONTRIBUTING/`; both are fixed and covered by tests.
* **Headers:** the website's security headers, with a CSP written for this site (`'wasm-unsafe-eval'` for the search index, shields.io and quay.io images). Search, Mermaid and badges were checked in a browser under it with no violations.
* **CI (phase 4):** [`docs-site.yml`](https://github.com/labsai/EDDI/tree/main/.github/workflows/docs-site.yml) — check *Docs Site* — runs the tests on every PR (they hold the repo-wide link guard) and the site build when docs changed. Dependabot watches `/docs-site`, because CI's Trivy scan reads its lockfile and an advisory there would fail every backend PR. `ci.yml`'s `backend` filter gains `docs-site/**/*.md`, and `BuildQualityGatesTest` holds `docs-site/.nvmrc` to the pom's Node.
* **Branding matched to the website and the Manager, value for value.** Tokens copied from the website's `global.css`; the header bar, its right side (Website, Get Started, GitHub) and the sun/moon toggle from its `Header.astro`, replacing Starlight's theme `<select>`; prose from its `GuidePage.astro`; code blocks in Astro's default `github-dark` theme with the same geometry; the website's favicons; the Manager's sidebar active/hover treatment and scrollbars. Checked against the live site by computed style (header, logo, CTA, nav link, headings, body text, links, code, tables: identical) and by screenshot in both themes and at phone width. Two deliberate differences: light-mode links use the website's own light accent token (accent-700) rather than accent-400, which is \~1.9:1 on its light background; and the docs render Outfit and JetBrains Mono for real, which the live website currently does not (it asks for `Outfit`, but `@fontsource-variable/outfit` registers `Outfit Variable`, so it falls back to the system font; inline code falls back to the browser's generic monospace).
* **No `sharp`.** Dependency Review failed the PR on the ten `@img/sharp-libvips-*` packages (LGPL-3.0), which `sharp` — Astro's optional default image optimiser — pulls in and the repository's licence policy denies. The site has no raster images, so it uses Astro's pass-through image service and `package.json` overrides `sharp` with a local stub (`docs-site/stubs/sharp`); the policy is unchanged. [`licenses.test.mjs`](https://github.com/labsai/EDDI/tree/main/docs-site/scripts/licenses.test.mjs) checks the lockfile against the deny-list read from `dependency-review.yml`, so this fails `npm test` next time rather than a PR check.
* AGENTS.md (ecosystem row: the website is Astro + Tailwind on Vercel at eddi.technology), CONTRIBUTING (how to add a page), the ship-pr skill (the new check) and the monorepo plan now describe the docs as they are built.

### Verification

`npm test` in `docs-site/`: 52 tests; the new guards were mutation-checked. `npm run build` clean; `check-live` 693/693 against the local stand-in. The Java guards touched here (`BuildQualityGatesTest`, `DocumentationLinksTest`, `DocumentationAccuracyTest`, `DocumentedRestPathsTest`, the changelog tests) pass.

***

## 🐛 fix(email): HITL notification review findings after the retarget to main (2026-10-27)

**Repo:** EDDI (`feat/email-hitl-notifications`)

### What changed and why

Once #1140 merged and #1141 was retargeted to `main`, the review bots saw the whole slice and raised these:

* **One recipient's failure no longer drops the rest.** `HitlEmailNotifier.notifyPause` handles each recipient on its own: a store error while counting, inserting or attempting one recipient is logged under that recipient's pseudonym and the loop moves on. The sweep only retries rows that exist, so a recipient skipped this way would never have been mailed for that pause.
* **A send failure that is not a `MailSendException` is an attempt.** A `RuntimeException` from `SystemMailer.send` (a bad address, a mailer bean that could not be built) used to escape `attempt`, leaving the row PENDING and reclaimed after every lease without ever reaching `max-attempts`. It is now rescheduled with backoff and FAILED at the limit, like a transient SMTP failure.
* **The audit entry names the recipient by keyed pseudonym.** It carried an unkeyed SHA-256 of the address beside the recipient's domain, which anyone reading the ledger or the logs could confirm by hashing candidate addresses. It is now `recipientPseudonym`, from `GdprPseudonymizer` (the audit ledger's keyed pseudonym, or the per-deployment salt), the same token GDPR erasure writes for that identifier; the rate-limit WARN uses it too.
* **A `From` with a valid mailbox beside an unparseable entry has no sender.** `MimeMessageParser.parseFrom` now records `MULTIPLE_FROM` for it, as `AddressNormalizer.parseSingle` already did, so DKIM/DMARC never authenticates a domain the header did not name unambiguously.
* **Manager:** a switched-off HITL section no longer blocks the save over hidden recipients, and the section resets per agent and version (`key` on `HitlConfigSection`).
* **`SystemMailer`** states `mail.smtp.ssl.checkserveridentity=true` where the session is built (CodeQL `java/insecure-smtp-ssl`); `SafeSocketConnector.angusProperties` already set it under the protocol's prefix.
* **Dashboard:** the email panels collided with main's Conversation Ratings panels on ids 264 and 265; they are now 267 and 268.

Files: [`HitlEmailNotifier.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/integrations/email/notify/HitlEmailNotifier.java), [`MimeMessageParser.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/mail/MimeMessageParser.java), [`SystemMailer.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/mail/SystemMailer.java), [`agent-config-sections.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/components/editors/agent-config-sections.tsx), [`agent-detail.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/pages/agent-detail.tsx), [`eddi-full-metrics-dashboard.json`](https://github.com/labsai/EDDI/tree/main/docs/monitoring/eddi-full-metrics-dashboard.json), with tests for each; each new test fails with its fix reverted.

***

## ✅ test(e2e): brand-leak acceptance test, and Keycloak's card-top rule — white-label phase 7 (2026-10-26)

**Repo:** EDDI (`feat/white-label-6-chat-operator-surfaces`)

### What changed and why

Phase 7 of the [white-labeling plan](https://github.com/labsai/EDDI/tree/main/planning/white-label-ui-plan.md) (§7), the acceptance test; the plan is now marked implemented. [`docs/white-labeling.md`](https://docs.labs.ai/deployment-and-infrastructure/white-labeling.md#verification) gains "Verification".

* **`ui/manager/e2e/fullstack/brand-leak.fullstack.spec.ts`** (+ `fixtures/zebra-logo.svg`, `zebra-icon.svg`). Resets the brand, sets "Zebra Labs" / "Zebra" / a tagline / teal `#0f766e` on white / `poweredBy: false` and uploads an SVG logo and icon through the admin REST, creates and deploys an empty agent, then walks 57 pages: `/`, `/welcome`, every static `/manage` route and every `RESOURCE_TYPES` list page (both read from source, `src/app.tsx` and `resources.ts`, with a floor on the count so a broken parse cannot pass), every static `/workforce` route, the fixture agent's agent, workflow and Studio pages, `/chat/production/<agent>` and `/chat/demo/showcase`. Per page: `\bEDDI\b`, `[Ll]abs.ai`, `LABS.AI` in `innerText`, `document.title`, `alt`/`aria-label`/`title`/`placeholder`/`aria-description`/`aria-roledescription`, the live `<meta>` contents and the raw HTML's `<title>` and `<meta>` contents; the title must name the brand, every same-origin `<img>` and icon link must be under `/branding/`, and `--color-primary` (chat: `--chat-accent`) must be the brand's. Then the OpenAPI title and contact, MCP `initialize` `serverInfo.name`, and Swagger UI (packaged build). Then a reset, after which `/welcome`, `/manage`, `/workforce`, the chat demo and the OpenAPI title say EDDI. `afterAll` resets the brand and removes the agent whatever happened. Leaks are collected for the whole run and reported by route with where and a snippet; allow-listed hits are printed too, so a stale entry is visible.
* **CI:** none needed. The `fullstack` project's `testDir` is `e2e/fullstack`, so `npm run test:e2e:fullstack` in the Backend E2E job (both databases, `workers: 1`) picks it up.
* **Allow-list (2):** the "EDDI Cluster" Grafana dashboard named on `/manage/coordinator` (a technical name, as documented), and the Branding page's empty Product-name placeholder, which shows the EDDI default the field falls back to.
* **Keycloak** (found in Phase 6): keycloak.v2 26.x draws a 4px `border-top` on the card in `--keycloak-card-top-color` (`:root`, PatternFly blue-400). `eddi-login.css` now sets it to `var(--eddi-primary)` (amber), and `KeycloakThemeExport`'s generated `brand-overrides.css` sets it explicitly with the other PF tokens. `KeycloakThemeExportTest` checks both.

### Verified

* Full `./mvnw package -DskipTests` (with the UIs), the jar on :7070 with MongoDB 7 and the compose file's three opt-outs, `PORT=7070 E2E_AGAINST_BACKEND=1 npx playwright test --project=fullstack`: the new spec passes (3 tests, about a minute; no leaks, the two allow-listed hits), and the whole `fullstack` project with `--workers=1` passes (38 tests).
* The first run found one hit, the Branding page placeholder, which became the second allow-list entry.
* Injected leak: the jar's Manager bundle patched so `landing.title` reads "Welcome to EDDI" fails the spec with `2 brand leak(s) on 2 route(s): / → /welcome [visible text] "EDDI" in: Welcome to EDDI Choose your workspace…` and the same for `/welcome`; the original jar was restored.
* Manager `npm run lint` and `npm run typecheck` green. Backend: `formatter:format`, `compile`, and `KeycloakThemeExportTest`, the `Brand*`/`Branding*` tests, `ImportStyleTest`, `BuildQualityGatesTest`, `ChangelogFragmentTest` and the `Documentation*Test`s (244 tests) green.

### Not verified

* PostgreSQL (CI's second leg), A2A agent cards (needs an A2A-enabled agent; covered by Phase 6's manual check), the Keycloak login page (not served in this tier), and a re-screenshot of the card-top colour on Keycloak 26.8.

***

## 🎨 refactor(manager): brand, warn and ochre colour scales — white-label colours, part 1 of 2 (2026-10-26)

**Repo:** EDDI (`feat/white-label-2-colour-scales`)

### What changed and why

Next step of the [white-labeling plan](https://github.com/labsai/EDDI/tree/main/planning/white-label-ui-plan.md) after the brand store: the Manager's colours become able to follow a brand. Amber was both the EDDI brand and the app's caution colour, written out as about 745 `amber-N` utilities, so a brand colour could not reach them. This part adds the colour scales and converts the pages, `lib/` and the HTML shells; the components follow in part 2, together with the guard that forbids `amber-N`. With no brand set, every pixel is unchanged.

* **Three scales in `ui/manager/src/index.css`**, in plain `@theme` (not `@theme inline`) so the utilities read the variable at runtime. All three are `var(--color-amber-N)` unbranded:
  * `--color-brand-50…950` follows the brand: accents, selection, primary emphasis.
  * `--color-warn-50…950` is fixed amber for cautions: warnings, approval pauses, pending and degraded states, unsaved-changes markers.
  * `--color-ochre-50…950` is a fixed categorical hue (per-type badges, section accents, avatar and syntax palettes) that is neither a warning nor re-branded, so two categories can never collide with the brand.
* **Pages and `lib/` converted by meaning,** read per component. The welcome modal's `rgba(245,158,11,…)` became `color-mix` over `--color-primary`, and the dark scrollbar greys became `--color-scrollbar-thumb(-hover)`. The shells' loader spinner reads `var(--brand-loader-accent, #d4a843)`.
* **`BrandDelivery`'s `brand.css`**, when a primary colour is set, re-declares the brand scale in `:root` and `.dark` as fixed `color-mix(in oklch, var(--color-primary) N%, white|black)` text and sets `--brand-loader-accent`. It never touches `warn` or `ochre`, and unbranded output stays empty. `BrandDeliveryTest` checks the scale against `index.css`, that `ochre` maps to amber and is never branded, and the shells' loader fallback.
* **Docs:** `docs/white-labeling.md` and the `eddi-ui` skill describe the three scales and when to use each.

### Design decisions

* **Full scales rather than the plan's single `warning` token.** The existing utilities need 50…950 with opacity modifiers; a one-for-one swap keeps the classification reviewable and the output identical.
* **The loader uses its own variable.** The bundle CSS in `<head>` already defines `--color-primary` as `#f59e0b`, so `var(--color-primary, #d4a843)` would have changed the unbranded spinner.
* **Mix ratios** put each brand step near the OKLCH lightness of the amber step it replaces.

### Fixed on the way

`docs/mcp-server.md` linked to an anchor `docs/conversation-ratings.md` does not have, which failed the docs-site build on `main` and on every PR. It now points at the page's "Analyzing and triaging" section, where the rating tools are described.

***

## 🎨 refactor(manager): components move off hard-coded amber, and a guard keeps it that way — white-label colours, part 2 of 2 (2026-10-26)

**Repo:** EDDI (`feat/white-label-3-colour-sweep`)

### What changed and why

Second half of the colour work in the [white-labeling plan](https://github.com/labsai/EDDI/tree/main/planning/white-label-ui-plan.md). Part 1 added the `brand`, `warn` and `ochre` scales and converted the pages; this part converts every component under `ui/manager/src/components`, so no `amber-N` utility is left in the Manager. With no brand set, every pixel is unchanged, because all three scales resolve to the same amber.

* **Classified by meaning, per component:**
  * `brand` (follows the brand): the Workforce synthesis cards, the dashboard's agents card, the wizard choice card and the pinned-response star.
  * `warn` (cautions): HITL pauses and approval surfaces, pending badges, unsaved markers, in-progress and degraded states, vault and secret-rotation cautions, amber callouts, the amber middle of red/amber/green scales.
  * `ochre` (fixed categorical hue): per-type badges, discussion-style palettes, section accents, the avatar palette (kept in sync with `lib/utils.ts`), syntax and number colours, tool chips, the search `<mark>`, the welcome-modal gradient.
* **Guard:** `src/__tests__/no-hardcoded-amber.test.ts` fails on any `amber-N` utility or brand-gold hex (`#f59e0b`, `#fbbf24`, `#d4a843` and their `rgb()` forms) in `ui/manager/src` and the three shells. Its allow-list is empty; the theme file's custom-property declarations are the one place amber is named.
* Tests that asserted `amber` class names now assert the new scale (`badges`, `resource-type-badge`, `pipeline-railroad`).

***

## 🐛 fix(security): bound the regex work of seven matchers (CWE-1333) (2026-10-26)

**Repo:** EDDI (`fix/regex-redos-bounds`)

### What changed and why

A repository security scan flagged seven places where a pattern from configuration, or text from a user, could make `java.util.regex` backtrack super-linearly. All seven were reproduced; each is now bounded, and where a regex was kept its meaning is unchanged — each fix ships with a test comparing old and new over a dense random or exhaustive corpus, plus a timing-bounded pathological input that hangs the old code.

* **`ToolApprovalPatterns.compile`** (HITL tool-approval globs): one greedy `.*` per star made `a*a*…*z` exponential in the star count, at save-time validation and on every gated tool call. Middle segments are now matched at their earliest occurrence inside atomic groups (`(?>.*?B)`), which loses no match, so matching costs pattern length × input length. The `Pattern` return type stays, so the gate and the rules are untouched.
* **`UrlPattern`** (crawl `excludePatterns`): the glob is no longer translated to a regex; a dynamic-programming pass over the tokens costs pattern length × path length. `**` now also crosses a decoded line terminator — the regex's `.` did not, so `/private/**` let `/private/a%0Ab` through.
* **`BoundedRegex`** (agent test-suite regexes): its deadline only fires on `charAt`, and a counted repetition of something that matches empty reads nothing — `(?:(?:){99999}){99999}` spun for 25 s on a three-character text. Counted minimums over groups, anchors and back-references may now force at most 1,000 iterations in total (nested counts multiply), and `(?x)` is refused. Checked when a suite is saved (`AgentTestSuiteValidator`) and again before every match, for suites saved earlier. What remains is documented in the class: a pattern within the cap that reads nothing still costs up to 1,000 steps per start position, unchecked by the deadline.
* **`TemplateSyntaxMigrator`** (Thymeleaf→Qute import): the three `#strings` patterns are possessive where the next token cannot be what the quantifier consumes, and the two-argument form checks for its `)` with a lookahead first; a long whitespace run in an unterminated call was quadratic.
* **`SecretRedactionFilter`** unquoted-value rules: the optional `${vault:…}` prefix searched for its closing brace afresh at every key, so repeated `token:${vault:` without a `}` was quadratic in the message. The key is still found by regex; the reference and value are now found by a forward-only scan whose brace search is reused across keys. Whole-reference exemption and reference-plus-tail redaction are unchanged (no new bypass).
* **`PunctuationNormalizerProvider`**: the punctuation setting is spliced into `[…]` and could close that class (`!]|(a+)+$|[!`). It is used as a class body only when its brackets balance and it has no `\Q…\E`; otherwise its characters are taken literally. The provider also no longer keeps the last parser's setting in a field of the shared singleton, which made one parser's custom punctuation the default of every later one.
* **`PromptInjectionGuardrail`**: whitespace runs in the built-in patterns are possessive; `ignore` or `<` followed by a long whitespace run was quadratic.

**Docs:** [`agent-testing.md`](https://docs.labs.ai/conversations-and-orchestration/agent-testing.md) — the repetition cap.

**Files:** `ToolApprovalPatterns`, `UrlPattern`, `BoundedRegex`, `AgentTestSuiteValidator`, `TemplateSyntaxMigrator`, `SecretRedactionFilter`, `PunctuationNormalizerProvider`, `PromptInjectionGuardrail` and their tests (new: `BoundedRegexTest`, `SecretRedactionFilterUnquotedValuesTest`).

***

## 🔒 fix(secrets): `allowedHosts` now also governs transport, connections, Slack bot tokens and discovery's `authHeaderRef` (2026-10-26)

**Repo:** EDDI (`fix/secret-allowed-hosts`)

Four findings from the repository security scan of `daecb3513`, all about a vaulted secret reaching a destination its `allowedHosts` list was meant to exclude.

### What changed and why

* **Plaintext http to an allowed host.** [`VaultHostAllowlist`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/secrets/VaultHostAllowlist.java) compared host and port only, so `http://api.openai.com` matched `api.openai.com` and an editor could send a restricted key unencrypted. A secret with a list is now refused for `http://` / `ws://` to any non-loopback host, even a listed one. Loopback (`localhost`, `127.0.0.1`, `[::1]`) is exempt, the same rule a connection's `allowPlaintextRemoteOrigins` applies. A deployment that does send restricted secrets to an internal service over http sets `eddi.vault.allow-plaintext-remote-hosts=true`, which still admits only listed hosts. Schemeless destinations (pgvector/Qdrant `host:port`) and `mongodb://` are not judged by scheme. Unrestricted secrets are unchanged.
* **A connection bypassed the secret's own list.** [`ConnectionResolver`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/connections/ConnectionResolver.java) checked the target against the connection's `baseUrlAllowlist` and then turned the `${vault:…}` references behind a STATIC `valueTemplate` or BASIC `passwordRef` into plaintext without consulting their `allowedHosts`. [`CredentialReferenceResolver`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/connections/CredentialReferenceResolver.java) now takes the target and checks every vault reference, after `${vars:…}` expansion and before decryption; a refusal is `TARGET_NOT_ALLOWED`. Because the check sits in the resolver, it covers every caller (`ApiCallExecutor`, MCP), not only the one the finding named.
* **Slack `botToken` resolved without a destination check.** [`ChannelTargetRouter`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/integrations/channels/ChannelTargetRouter.java) now checks a vaulted `botToken` (new-style integrations and legacy agent connectors) against `SlackWebApiClient.SLACK_API_BASE` before resolving it. A refused token is withheld (the integration cannot post) with a `[SECURITY]` WARN. Signing secrets are inbound-only and not checked.
* **`authHeaderRef` prefix check.** [`RestApiCallsStore`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/apicalls/rest/RestApiCallsStore.java) discovery accepted any value that *started with* a reference prefix, so `${vault:x}sk-live-…` passed and the literal was copied into every generated call. The value must now be exactly one `${vault|eddivault|vars|caller:…}` reference, whole-string.

### What operators see

A restricted secret that is used today over plain http to a non-loopback host — e.g. an in-cluster `http://elasticsearch:9200` or an OpenAI-compatible server at `http://vllm:8000` — now fails at that call/build with a message naming the destination and `eddi.vault.allow-plaintext-remote-hosts`. Switch the endpoint to https, or set the property. Docs: [secrets-vault.md → Destination allow-list](https://docs.labs.ai/security-and-compliance/secrets-vault.md#destination-allow-list-allowedhosts).

### Tests

`VaultHostAllowlistTest` (new `EncryptedTransport` group), new `ConnectionResolverVaultAllowedHostsTest`, new `ChannelTargetRouterAllowedHostsTest`, and a new case in `RestApiCallsStoreBranchTest`. Each was mutation-checked: with the fix reverted, the new tests fail.

### Not done

* The Manager's `isAuthReference` (`ui/manager/src/lib/secret-reference.ts`) is still a prefix check. The server now refuses what it lets through, but it should use the same whole-string grammar.
* An OAuth connection's client secret is not checked against its own `allowedHosts` at the token endpoint. `credentialEndpointAllowlist` governs where it goes.

***

## 🧪 test(email): full-application IT for the email channel (2026-10-26)

**Repo:** EDDI (`feat/email-conversation-mode`)

The existing email ITs (`EmailImapPollingIT`, `EmailConversationModeIT`) wire the poller, processor and reply sender by hand around a mocked conversation engine. `EmailFullApplicationIT` boots the real application (`@QuarkusTest`, MongoDB Dev Services) and drives it through its REST API, with GreenMail as IMAPS and SMTPS server and a deterministic agent (dictionary, behavior rules, output — no LLM):

* **Trigger mode** — `POST /channelstore/channels` answers `X-Eddi-Warnings: email.open-trigger` and creates `email-poll:<id>`; the poll is fired through `POST /schedulestore/schedules/{id}/fire` (claimed, then `ScheduleFireExecutor`); the mail runs a real turn with the mail as input and the `mail` context, its PDF lands in the attachment store, the ledger row ends `DONE`, the mail is moved, and nothing is sent. An `Auto-Submitted: auto-replied` mail is refused without a conversation.
* **Conversation mode** — DKIM-signed mail (real `DkimVerifier`/`SenderAuthenticator`) is answered in the thread (`In-Reply-To`, `References`, `Auto-Submitted`, AI disclosure); the answer to EDDI's Message-ID continues the conversation, another sender quoting it gets their own, unsigned and body-tampered mail is refused unanswered.
* **HITL in the thread** — a `PAUSE_CONVERSATION` turn sends the in-thread notice with the pause reason; `POST /agents/{conversationId}/resume` sends the continuation.
* **Bounce** — a permanent DSN for a reply lists the address under `GET /channelstore/channels/{id}/email-suppressions` (hashed) and the sender's next reply row ends `SUPPRESSED`.

Two test seams, enabled only by the IT's profile (`getEnabledAlternatives`), replace beans; no production code changed:

* `E2eMailSocketConnector` (`engine.net`, test sources) runs the production author policy of `SafeSocketConnector` in full on every call, over an injected resolver that answers a public documentation address for `imap.mail.test` / `smtp.mail.test`; only an endpoint that passed is re-pinned to the loopback GreenMail port, keeping host name and TLS mode, so TLS and host-name verification run against a certificate for those names.
* `E2eMailDns` (`engine.mail`, test sources) is the production `MailDnsResolver` over an offline TXT source that publishes the `DkimTestSigner` key and a DMARC record.

Finding while writing it (no code change): the regular dictionary parser splits on spaces only, and the default `inputTemplate` puts the body on the line after `-----`, so the body's first word is read as one token with the separator (`instructions.\n-----\nhello,`). A dictionary agent on an email channel should not rely on the first word of the body; LLM agents are unaffected.

***

## fix(alerts): a per-event send claim closes the erasure-vs-delivery window (2026-10-26)

**Repo:** EDDI (`feat/alerts-backend`, PR #1138)

### What changed and why

A delivery could read an event, an erasure redact it and finish, and the delivery then send what it had read. Now **no send starts with erased content after an erasure has completed**.

* **Send claim.** `IAlertEventStore.claimSend(eventId, token, now, until)` is an atomic conditional write that succeeds only when no claim is live (none, or an expired one); `releaseSend(eventId, token)` clears it only for its own token. Both stores keep the claim in internal fields (`sendClaimToken` / `sendClaimUntil`; `send_claim_token` / `send_claim_until`) that no read maps into an event. `AlertDeliveryService` — the one path for first deliveries and retries — claims for `SEND_CLAIM_LEASE` (a fixed 30 s, three times the default 10 s webhook timeout; not tied to a configured `eddi.alerts.webhook-timeout`), reads the event, checks that more than the send timeout is left of the lease, sends, and releases in a `finally`. A claim it cannot take, or a lease too short to finish in, leaves the delivery pending, due again after one lease; the worker never blocks.
* **Erasure waits for live claims.** The redactions erasure uses (`redactOutputValues`, `redactRatingComments`, and the engine's `redactRatingComment`) take `now` and skip an event whose claim is live. [`AlertErasureRedactor`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/alerts/AlertErasureRedactor.java) — used by `AlertGdprParticipant` and `ConversationRatingGdprParticipant` — repeats the redaction with a short pause until `countOutputValues` / `countRatingComments` report nothing left, so the erasure completes only after every send that had read the content has finished or its claim has expired.
* **The engine's own post-insert redactions cannot wait on themselves:** they run before the event's first delivery and before the maintenance pass may pick it up (its `nextAttemptAt` is a claim lease away), so no claim on it can exist yet (said in the code).
* [Alerts → Privacy](https://docs.labs.ai/conversations-and-orchestration/alerts.md#privacy) states the guarantee and its one limit: a send that started before the erasure completed cannot be recalled.

### Design decisions

* **Claim per send, not per event delivery:** an event with five targets would otherwise hold one claim across up to five webhook timeouts.
* **The erasure's wait is bounded** by ten leases (5 minutes). A claim always expires within one lease, so only a store that keeps failing the update — or deliveries re-claiming without pause, which the backoff rules out — reaches the bound; the step is then reported failed instead of hanging the erasure. This is the one place the implementation is stricter than "keep going until the claims expire".

### Tests

`AlertSendClaimTest` drives the races with latches, not sleeps: a send paused after its final read holds the erasure (asserted not complete after two redaction passes), the erasure completes once the send finishes, and a retry then sends the redacted event; erasure first, then delivery, sends the redacted event; a live claim makes the attempt skip, an expired one is taken over; a lease too short after the read releases and skips; the erasure's bound fails the step. Store contract (both ITs): conditional claim, token-checked release, expiry takeover, redaction skipping a claimed event until it is released or expired.

***

## 📚 feat(docs-site): build docs/ with Astro + Starlight, the replacement for GitBook (2026-10-26)

**Repo:** EDDI (`feat/docs-site-astro`)

### What changed and why

docs.labs.ai is GitBook, syncing `docs/` one way. The documentation moves to a site we build ourselves: Astro + Starlight, deployed on Vercel like the marketing site, at `docs.eddi.technology`, with docs.labs.ai redirecting there permanently. The plan, and the facts it rests on (the URLs GitBook has served over the years, the website's hosting, what GitBook provides besides pages), is [`planning/docs-site-migration-plan.md`](https://github.com/labsai/EDDI/tree/main/planning/docs-site-migration-plan.md). This is its phase 1: the site builds locally. Nothing is deployed and docs.labs.ai is unchanged.

* **`docs/` is untouched as a format.** It stays plain GitHub Markdown, because GitHub renders it, `McpDocResources` serves it raw to MCP clients and `DocumentationLinksTest` checks it. [`docs-site/scripts/sync-docs.mjs`](https://github.com/labsai/EDDI/tree/main/docs-site/scripts/sync-docs.mjs) reads it on every dev/build run and writes the Starlight copy. `docs/SUMMARY.md` still decides what is published and is now the sidebar too.
* **Flat URLs from file names** — `docs/secrets-vault.md` → `/secrets-vault/`. GitBook's URLs carried the SUMMARY section (`/security-and-compliance/secrets-vault`), so moving a page between sections changed its address; and the flat links the backend and the Manager already print (`VaultStartupBanner`, `ComplianceStartupChecks`, the coordinator page) 404 on GitBook today. They resolve on the new site.
* **Links are rewritten, and checked.** A link to a published page becomes its route; a link to anything else in the repository becomes a GitHub link. The sync fails on a SUMMARY entry without a file, a link to nothing, two pages that would share a URL, and an `#anchor` that does not exist. Anchors are checked against the source because `starlight-links-validator` 0.27 cannot check them under Astro 7: Astro's satteri processor runs plugins before it assigns heading ids, so the plugin sees none and reports every anchor as broken. The source-side check computes the ids with `github-slugger`, the same way Astro does, and matches all 5,235 heading ids of the built site, none missing and none extra. The plugin still checks every page link.
* **GitBook's machine-readable surface is kept:** every page also exists as `/<slug>.md` (the website links to GitBook's `.md` URLs), and `/llms.txt` lists every page, with `/llms-full.txt` and `/llms-small.txt` (no changelog) beside it.
* **Everything generated lives in `docs-site/.generated/`**, which is gitignored. `DocumentationLinksTest`, `DocumentationAccuracyTest` and `DocumentedRestPathsTest` skip it by name, so a local site build cannot feed them a second copy of `docs/` with site-relative links.
* The anchor check found one real broken link: two references in [`changelog/2026-08.md`](https://docs.labs.ai/reference/changelog/2026-08.md) pointed at a heading that had been rotated into the July archive. They now link there.

### Verification

* `npm test` in `docs-site/`: 32 tests, including a full sync over the real `docs/`. Each guard was mutation-checked: disabling the anchor check, blockquote headings, setext headings, entity decoding, the intra-word underscore rule, fence-length and code-span handling, directory READMEs or the slug-collision check each fails a test.
* `npm run build`: 94 pages, link validator clean. Seen in a browser — search, Mermaid, dark and light theme, phone width, `.md` endpoints, the no-slash URLs the backend uses — with no console errors.

### Next

Phase 2 of the plan: a page-by-page comparison against GitBook. Then phase 3, the redirect map from every URL GitBook has served, and phase 4, the CI workflow and the Vercel project.

***

## 🔐 fix(auth): MCP logins last 30 days, and Keycloak behind TLS advertises https token endpoints (2026-10-26)

**Repo:** EDDI (`fix/mcp-long-lived-sessions`)

### What changed and why

Connecting Claude Code to a TLS-proxied EDDI deployment surfaced two gaps, both configuration only — no Java change.

**1. An MCP login died after 30 idle minutes.** An MCP client keeps a refresh token, but it was tied to the realm's SSO session (Keycloak default: 30 minutes idle, 10 hours max), so the user re-ran the browser flow after every break. `eddi-mcp` now issues **offline tokens** (30 days idle, renewed on use, revocable per user). In all three realm copies (`keycloak/`, `helm/eddi/files/`, `k8s/overlays/auth/`): `offline_access` is a Default client scope of `eddi-mcp`, the role is in its scope mapping, `default-roles-eddi` includes it, and each seed user lists it. The scope, the role and the scope's role mapping are now defined in the file itself: the realm supplies its own `clientScopes`, and `everyReferencedClientScopeIsDefined` rightly refuses a reference to a scope the file does not define, even though Keycloak 26.8 happens to create this one anyway. `default-roles-eddi` is stated twice in the file (`defaultRole` and the `roles.realm` entry) and the roles-list entry is the one an import keeps — with the role added only under `defaultRole`, a newly created user was refused, so both carry it and the test checks both. `eddi-frontend` is unchanged — no 30-day tokens in browser storage.

Verified against Keycloak 26.8.0 with the edited realm imported: all seed users and a newly created user receive `typ=Offline` refresh tokens (2 592 000 s) with their roles and `aud=eddi-backend`, and the refresh grant works. The same test disproved both recipes `docs/mcp-server.md` previously gave:

* `default-roles-eddi` did **not** grant `offline_access` (the realm defines its composites explicitly) — without the role: *Offline tokens not allowed for the user or client*.
* Advertising `offline_access` in `quarkus.oidc.resource-metadata.scopes` makes Keycloak fail the **whole login** with `invalid_scope` on any realm whose client lacks the scope — i.e. every existing deployment. Left at `openid`.

**2. Keycloak behind a TLS proxy advertised `http://` token endpoints.** With `KC_HOSTNAME_BACKCHANNEL_DYNAMIC=true`, Keycloak derives the token, JWKS and userinfo URLs from the request, which is plain http behind the proxy; the issuer and authorization URLs come from `KC_HOSTNAME` and stayed https. Claude Code refuses to send credentials to an http token endpoint, so login failed after the browser step. Fix: `KC_PROXY_HEADERS=xforwarded`.

* `gcp/provision-vm.sh --https` now sets it, and its nginx Keycloak location now **sets** every forwarded header instead of passing client values through: `X-Forwarded-Host $host`, `X-Forwarded-Port 443`, `X-Forwarded-For $remote_addr` (was appended). Once Keycloak trusts these headers, a client-supplied `X-Forwarded-Host` would choose the host in that caller's discovery response (review finding, CWE-346).
* Helm: new `keycloak.proxyHeaders` — empty means `xforwarded` when `eddi.oidc.publicUrl` is https, nothing otherwise; `none` opts out. Rendered and checked for all four cases. Chart `2.11.0` → `2.12.0`.

### Files

* `keycloak/eddi-realm.json`, `helm/eddi/files/eddi-realm.json`, `k8s/overlays/auth/eddi-realm.json` — offline-token wiring.
* `helm/eddi/values.yaml`, `helm/eddi/templates/keycloak.yaml`, `helm/eddi/Chart.yaml` — `keycloak.proxyHeaders`.
* `gcp/provision-vm.sh` — `KC_PROXY_HEADERS` in the HTTPS override.
* `src/test/java/ai/labs/eddi/deploy/DeploymentManifestsTest.java` — the `eddi-mcp` scope-mapping assertion allows `offline_access`; new `mcpClientIssuesOfflineTokens` pins the three conditions in every realm copy and that `eddi-frontend` stays without it.
* `ui/manager/scripts/make-test-realm.mjs`, `ui/manager/e2e/auth/auth-helpers.ts` — the Auth E2E fixtures pin each seed user's exact roles; they now include `offline_access`. `ui/manager/e2e/auth/mcp-oauth.spec.ts` — the real authorization-code + PKCE + consent flow against `eddi-mcp` now asserts the refresh token is `typ: Offline`, the one path the container check could not drive.
* `docs/mcp-server.md` — corrected offline-token section, upgrade steps for an existing realm, proxy-header deployment note. `docs/kubernetes.md` — settings row.

### Upgrade note

`--import-realm` does not touch an existing realm. Existing deployments keep working with ordinary 30-minute MCP logins; for long-lived ones they add the three pieces by hand (steps in `docs/mcp-server.md`, "Upgrading an existing realm"), the Default scope **last** — with the scope in place but the role missing from the user or the client's scope mapping, Keycloak refuses the login with *Offline tokens not allowed* rather than falling back to an ordinary token. Revoke a single offline token under *Users* → the user → *Consents*. The nginx Keycloak location also clears `X-Forwarded-Prefix` (review finding). The `quarkus.oidc.roles.role-claim-path=realm_access/roles` fix for "requires role" on every tool is already in the image since 6.6.0; deployments on older images should pin it as `QUARKUS_OIDC_ROLES_ROLE_CLAIM_PATH`.

***

## 🐛 fix(ci): the Playwright install no longer waits on the Ubuntu apt mirror (2026-10-26)

**Repo:** EDDI (`fix/playwright-install-slow-apt`)

### What changed and why

`main` went red on the `fast-uri` bump (`daecb3513`) with no test failing. `UI Manager E2E (MSW)` and `Backend E2E (postgres)` both hit the 10-minute limit of `Install Playwright browsers`, and the re-run failed the same way. `npx playwright install --with-deps chromium` always runs apt-get. On `ubuntu-latest` that meant about 26 MB of fonts (CJK, unifont, xfonts) plus a few library upgrades from `azure.archive.ubuntu.com`, which was serving 25–50 KB/s that afternoon. None of it is needed: the suites take screenshots only on failure and compare none, and the runner image already carries Chromium's shared libraries.

The three steps that installed Playwright (`UI Manager E2E (MSW)`, `Backend E2E`, `Auth E2E (Keycloak)`) now run [`ui/manager/scripts/install-playwright-chromium.mjs`](https://github.com/labsai/EDDI/tree/main/ui/scripts/install-playwright-chromium.mjs). It:

* downloads the browser from Playwright's CDN (no apt);
* launches it once, and if that works, skips apt altogether;
* otherwise prints a `::warning::`, runs `npx playwright install-deps chromium`, and fails the step if Chromium still does not launch.

So a runner image that drops a library still works, it just pays the apt cost again, and the warning says so.

### Verified

Both paths ran in Docker against `@playwright/test` 1.64.1:

* `node:24-bookworm` (no Chromium libraries): the probe reported a missing shared library, apt installed the dependencies, the second launch succeeded, exit 0.
* `mcr.microsoft.com/playwright:v1.64.1-noble`: launched first time, apt skipped, exit 0.

The `ubuntu-latest` path itself is verified only by this PR's own CI run.

***

## 🔒 fix(security): schedule fire authority, maxCostPerFire, group approver scope, currentversion VIEW (2026-10-26)

**Repo:** EDDI (`fix/schedule-group-authz`)

Six findings of the repository security scan (revision `daecb3513`) on scheduling and group-conversation authorization.

### What changed and why

* **Schedule creator re-check used historical teams (#4).** `ScheduleFireExecutor.creatorUseCheck` re-checked USE with the create-time `creatorTeams` snapshot, so a creator removed from a team kept firing a schedule on an agent shared only with that team. The snapshot is now narrowed by the user directory: when the creator signed in after the schedule was created, a team their latest token no longer lists stops counting (`currentCreatorTeams`). Only ever narrowing; with no newer directory entry the snapshot stands. **Not fixed:** `creatorAdmin` — the directory records teams, not roles, and EDDI has no server-side role source outside a request, so a creator who loses `eddi-admin` keeps an admin-created schedule firing. Recording roles in the directory (both stores) would close it.
* **`maxCostPerFire` capped nothing (#26).** The field was accepted, stored and shown but never reached the turn. The fire now carries it in the input context (`scheduleMaxCostPerFire`), and `LlmSpendGate.effectiveCeiling` — used by the pre-call spend gate and between tool-loop rounds — tightens the agent's `maxCostPerConversationUsd` to "every earlier step's `audit:cost` plus the allowance", so a `persistent` schedule is capped per fire. `0` or below stays unlimited (PostgreSQL stores `0` as NULL).
* **`pendingHumanPrompt` went to every approver (#8).** The approval-status summary (REST and MCP `get_group_approval_status`) returned a HUMAN member's rendered prompt — discussion content — to any `eddi-approver`. It now goes only to the pending member, the owner, admins, and an approver while the conversation awaits approval (`HitlAccessGuard.mayReadPendingHumanPrompt`), the same window the full view grants.
* **`approve/stream` streamed the resumed discussion to approvers (#27).** An approver-only caller now gets a listener that forwards `hitl_resume` (or, on a rejection, `group_complete` without the synthesized answer), errors and cancellation, then closes; the owner and admins keep the full stream (`HitlAccessGuard.mayReadResumedDiscussion`). Same boundary as the agent resume's "a reply is a read". The approver's `hitl_resume` is held until `resumeDiscussion` returns: the coordinator announces the resume before it submits the resumed run, and a submit failure restores the pause and throws, so sending it at once told the approver their decision was applied while the discussion stayed paused, and closed the stream before the endpoint's `group_error` could reach it (`ApproverStreamingListener.resumeEnqueued`).
* **A tool-call resume skipped the cost ceiling.** `LlmTask.executeResume` never asked the spend gate, and the tool loop checks its ceiling only after the model has answered, so a conversation (or a scheduled fire under `maxCostPerFire`) spent while it waited for approval still ran the approved calls and its first resumed model request. The resume now runs the same preflight before the approved calls (refused → the fallback answer, `llm:spend_refused:<taskId>`, the batch consumed), and the resumed loop checks before its first request too, counting what the approved calls charged: `runToolCallLoop` takes the tool-cost baseline from its caller, taken before those calls, instead of snapshotting it at loop start. What the turn spent *before* the pause was invisible to both checks: the loop's tokens and tool cost so far died with the pause signal, so a fire that had used $0.02 of a $0.025 allowance resumed as if it had spent nothing. The pause now carries that spend (`ToolApprovalRequiredException.addSpend`: the loop's rounds at the task's prices plus its tool-cost delta, and an enclosing cascade's earlier steps), and `LlmTask.execute` adds it to the step's `audit:cost` and `audit:token_usage` as the pause passes — the step the pause snapshot persists and the pause's settle meters. The resume reads it through `audit:cost` in its preflight, its loop ceiling and its total, so it counts once; this also closes the documented gap where a resumed turn's ledger entry under-reported its pre-pause segment. Docs: [`langchain.md`](https://docs.labs.ai/agent-configuration/langchain.md#per-conversation-llm-cost-ceiling).
* **Follow-up did not re-check group USE (#37).** `POST …/followup` (and MCP `followup_with_member`) checked transcript ownership only; like a continuation, it now also requires current USE on the group.
* **`/{id}/currentversion` had no per-resource check (#6).** `IRestVersionInfo`'s two endpoints now call `requireCurrentVersionAccess(id)` first; all sixteen stores (and `RestVersionInfo`) implement it as VIEW via `RestVersionInfo.requireViewAccess`. The default refuses, so a new store that forgets fails closed. `getCurrentResourceId` stays the unguarded resolver in-process engine code uses.

### Files

[`ScheduleFireExecutor.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/runtime/internal/ScheduleFireExecutor.java), [`ScheduleConfiguration.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/schedule/model/ScheduleConfiguration.java), [`LlmSpendGate.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/LlmSpendGate.java), [`ToolLoopRunner.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/ToolLoopRunner.java), [`ToolLoopResumer.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/ToolLoopResumer.java), [`ToolApprovalRequiredException.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/hitl/tools/ToolApprovalRequiredException.java), [`CascadingModelExecutor.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/CascadingModelExecutor.java), [`LlmTask.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/LlmTask.java), [`HitlAccessGuard.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/hitl/HitlAccessGuard.java), [`RestGroupConversation.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/RestGroupConversation.java), [`McpHitlTools.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/mcp/McpHitlTools.java), [`McpGroupTools.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/mcp/McpGroupTools.java), [`IRestVersionInfo.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/IRestVersionInfo.java) and the sixteen `Rest*Store` classes. Docs: [`scheduling.md`](https://docs.labs.ai/conversations-and-orchestration/scheduling.md), [`hitl.md`](https://docs.labs.ai/conversations-and-orchestration/hitl.md), [`langchain.md`](https://docs.labs.ai/agent-configuration/langchain.md), [`group-conversations.md`](https://docs.labs.ai/conversations-and-orchestration/group-conversations.md).

### Design decisions

* `maxCostPerFire` rides the existing priced-spend ceiling rather than a new tool-only budget: it then covers model tokens as well as tools, and every node that runs the turn enforces it because the value travels in the input. A client that sets the context key itself can only lower its own ceiling.
* The approver stream closes at the resume instead of filtering event by event: everything after the resume is outside the approval window, and a closed stream cannot start leaking when a new event type is added.
* The pre-pause spend is recorded on the step at the pause, not carried on the persisted `PendingToolCallBatch` for the resume to add: the step already survives into the pause snapshot and is what `TurnCostMeter` settles, so the spend is metered even if the pause is never resumed, and a figure on the batch would be one more place a cost could be applied twice.

***

## 🔒 fix(security): close the DNS-rebinding gap between the SSRF check and the connection (2026-10-26)

**Repo:** EDDI (`fix/ssrf-dns-pinning`)

### What changed and why

A repository security scan flagged three paths where the SSRF check resolves a host and the HTTP client then resolves it again to connect: `OutboundHttp` (JDK client), the Vert.x httpcalls client, and cached MCP transports. Both lookups normally hit the JVM's positive DNS cache and agree; a rebinding name aims for the moment that cache entry expires between them. This was recorded as an accepted risk in `docs/architecture.md`. None of the clients can be handed the validated addresses (the JDK `HttpClient` has no resolver hook, and an IP-literal URL breaks SNI and certificate checks), so each path now closes the gap with what it can see:

* **httpcalls (Vert.x):** a web-client interceptor checks the address the connection actually reached in the `SEND_REQUEST` phase, before a byte is written, on every request, pooled connection and redirect hop. A metadata or link-local peer is refused always; with `eddi.security.ssrf-protection.enabled=true` a private peer is refused unless the host is allow-listed. This is a real pin of the decision to the connection.
* **`OutboundHttp`:** each hop's SSRF check runs again once the response headers are in. The connection's own lookup is what the cache now holds, so a target that turned private (or into the metadata service) has its response discarded and closed before it reaches the caller or a redirect. A startup warning names `networkaddress.cache.ttl=0`, which would defeat it.
* **MCP:** the server URL is validated on a tool-cache hit too, not only on a fresh discovery, and again inside the transport's per-request header hook, so a cached transport never sends to a URL that no longer passes.

What remains (written up in [security.md → DNS rebinding](https://docs.labs.ai/security-and-compliance/security.md#dns-rebinding)): on the `OutboundHttp` path the request itself has already been sent when the second check refuses it, so this blocks reading the response, not a blind request; an exchange slower than the cache lifetime defeats the second look; MCP keeps the pre-connect window. A full pin of the JDK path needs a resolver hook the JDK does not offer, or one `HttpClient` per pinned host with explicit SNI, which is a larger change.

**Files:** [`HttpClientModule.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/httpclient/bootstrap/HttpClientModule.java), [`OutboundHttp.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/httpclient/outbound/OutboundHttp.java), [`McpToolProviderManager.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/McpToolProviderManager.java), [`UrlValidationUtils.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/tools/UrlValidationUtils.java), [`security.md`](https://docs.labs.ai/security-and-compliance/security.md), [`architecture.md`](https://docs.labs.ai/architecture-and-concepts/architecture.md). Tests: `HttpClientModuleConnectedPeerTest`, `OutboundHttpTest$Rebinding`, `McpTransportRevalidationTest`, `McpToolProviderManagerDiscoveryTest#cacheHitIsRevalidated`.

***

## 🔒 fix(llm): tool results redacted before the model, bounded selector extraction (2026-10-26)

**Repo:** EDDI (`fix/tool-result-redaction`)

Two findings from a repository security scan of `daecb3513`.

### What changed and why

* **Tool results are redacted before they reach the model.** Only the display trace was filtered: an administrator's config-read tool (the Platform Operator) showed `<REDACTED>` while the hosted model provider received the plaintext key. `ToolLoopRunner.executeToolCall` now runs `SecretRedactionFilter.redact` on the result before truncation (the `summarize` strategy sends it to a model too) and before the guardrail envelope; the raw result stays internal (LAZY activation, repeat guard). Trade-off, documented: a key-named value such as `nextPageToken` reaches the model as `<REDACTED>`.
* **Selector extraction no longer multiplies nested text.** `WebScraperTool.extractWithSelector` copied each match's whole descendant text, so nested matching ancestors repeated the same text up to 20 times. An element inside an already listed one is skipped, and text is gathered by a bounded walk (`boundedText`) against one 20,000-character output budget (5,000 per element), so nothing past the budget is materialized.

### Design decisions

* **The webhook replay findings of the same scan are not in this change.** Open PR #1126 already moves the webhook dedup cache to a cluster-shared bucket and refuses instead of evicting; the longer retention for body-signed schemes (`github`, `generic-hmac`) follows once it has merged, so the two do not conflict in `WebhookEventHandler` and `CacheFactory`.

**Files:** [`ToolLoopRunner.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/ToolLoopRunner.java), [`WebScraperTool.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/tools/impl/WebScraperTool.java), [`security.md`](https://docs.labs.ai/security-and-compliance/security.md)

***

## 🔒 fix(secrets): linear-time reference scanning, a new secret's grant is checked against agents already referencing it, rotation retires legacy checksums (2026-10-26)

**Repo:** EDDI (`fix/vault-reference-scanning`)

Follow-up to a repository security scan of the vault and connection code.

### What changed and why

* **Reference scanning is linear.** `find()` over the `${vault:…}`, `${connection:…}`, `${vars:…}` and tenant-reference regexes retried at every opener, and when no closing brace followed, each attempt scanned the rest of the text. A global variable value or a parameter with thousands of unterminated openers therefore cost time quadratic in its length, on every variable write, every deployment grant check and every resolved parameter. The new [`ReferenceScanner`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/secrets/model/ReferenceScanner.java) gives the regex's answers match for match (same start, end, tenant and name, nested openers included) but remembers its searches for the next `}` and `/`, so each character is examined a constant number of times. `SecretResolver`, `VaultGrantChecker`, `SecretReference.parse` and `ConnectionReference` (`contains`, `requireSole`, `parse`) use it. `SecretReference.VAULT_PATTERN` and `ConnectionReference.CONNECTION_PATTERN` stay as the documented grammar.
* **A secret's grant is checked when it is created, against the agents already referencing it.** [`VaultGrantChecker`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/secrets/VaultGrantChecker.java) lets a deployment through when a referenced secret does not exist yet — agent sync promotes a workflow to an instance that does not hold the source's secret and then deploys it, and `AgentSyncIT` covers that flow. The resolver checks no grants, so a secret created later and restricted to another agent used to resolve for every agent already deployed with a reference to it, until its next deployment. `PUT /secretstore/secrets/{tenantId}/{keyName}` and the space-secret endpoint now answer **409** under `enforce` to a create whose `allowedAgents` leaves out such an agent, naming it ([`VaultGrantImpactAnalyzer.refusalToCreate`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/secrets/VaultGrantImpactAnalyzer.java), reusing the grant-change impact scan); `warn` logs and creates, `off` does not look. A first version of this branch made the absent secret a deploy-time violation instead, which broke the agent-sync flow.
* **The create-time scan covers the cluster, and refuses when it could not look everywhere.** The scan read only `IAgentFactory`, a per-node registry, while the vault is shared by every node, so an agent deployed on another node was invisible to a create handled here. It now also reads the deployment records in the shared database (`IDeploymentStore.readDeploymentInfos(deployed)`), deduplicated against the local registry, which alone sees a deployment still `IN_PROGRESS` (now counted) or one made with `autoDeploy=false`. And `refusalToCreate` used to ignore the scan's `complete` flag, so under `enforce` an agent whose configuration could not be read, or a listing that failed, let the create through on an empty list. It now refuses with its own 409 naming the unread agents (`GrantImpact.unverifiedAgents`). This is the opposite of the deploy gate on purpose: a refused deployment is an outage, a refused create is a retry, and naming the agent on the grant or granting `*` needs no scan. The grant-change response's `agentsLosingAccessScope` reads `cluster` instead of `this-node`. Left open: a deployment recorded on another node a moment after the scan read the records.
* **The checksum key cannot be stranded under a retired KEK.** `loadOrCreateChecksumKey` checked the KEK before inserting the key, but a node stalled between that check and the insert past `rotateKek`'s last read of the key would persist it wrapped under the retired KEK, and every node restarted with the new master key would then fail on its next store. The race predates this branch (first `store`), and the legacy-checksum upgrade in `rotateDek` made it reachable a second way. The insert is now followed by a second check, as for a DEK (`takeBackIfKekRetired`): when the KEK moved, the key is deleted only while it is still the value this node wrote (`ISecretPersistence.deleteMetaValueIfEquals`, atomic on Mongo and Postgres), so a key the rotation already re-wrapped is kept.
* **DEK rotation upgrades legacy checksums.** A row written before the keyed checksum still held a bare SHA-256 of the plaintext, which anyone with the row or a backup can test guesses against offline. `VaultSecretProvider.rotateDek` has the authenticated plaintext in hand, so it now writes the keyed, tenant-bound checksum in the same guarded re-seal. `updateSecretSealing` (Mongo and Postgres) persists the checksum with the ciphertext.

Docs: [`secrets-vault.md`](https://docs.labs.ai/security-and-compliance/secrets-vault.md) ("What counts as granted", and the checksum note under the REST API).

### Tests

* `ReferenceScannerTest`: parity with the regexes on hand-picked and fuzzed input, `matchesWhole`, `replaceAll`, and timing guards on many unterminated openers for each caller.
* `VaultGrantCheckerTest.absentSecretIsNotAViolation`; `VaultGrantImpactAnalyzerTest` (create-time refusal, modes, an unreadable agent or a failed listing refusing under `enforce`, agents found only in the deployment records, one agent in both sources checked once, `IN_PROGRESS` counted); `RestSecretStoreGrantOnCreateTest` (409 and no write).
* `MongoSecretPersistenceTest` and `PostgresSecretPersistenceTest` (Testcontainers): `deleteMetaValueIfEquals` keeps a value that differs from the expected one and removes only the exact one.
* `VaultKeySafetyTest.StaleReplicaRace`: a checksum key inserted after a KEK rotation, via `rotateDek` and via `store`, is taken back and a node on the new master key can store.
* `VaultKeySafetyTest.rotationRetiresLegacyChecksums`.
* `PostgresSecretPersistenceUnitTest` follows the new parameter order.

**Stale deployment rows.** The deployment sweep now checks for a missing Agent config before skipping rows this node already tracks, so a shared row that the agent-delete cascade could not remove is retired (and the agent undeployed locally) instead of lingering (for rows this node already tracks the check runs at most once every 5 minutes per row, since the agent store has no read cache) and making the grant analyzer answer UNKNOWN for it.

***

## feat(hitl): a person's note on a rejected tool call asks the model to revise (2026-10-26)

**Repo:** EDDI (`feat/hitl-note-asks-for-changes`)

### What changed and why

An approval card lets a person send a note instead of approving ("use a shorter title"). Until now a rejected call always told the model "the reviewer declined this action, do not retry, offer alternatives", so a note that asked for a change produced an explanation instead of a corrected proposal. Two small changes in [`ToolLoopResumer`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/ToolLoopResumer.java):

* **The instruction depends on who decided.** When the note is non-blank and `decidedBy` does not start with `system:`, the rejection tool-result says the user did not approve the call and left a note: if the note asks for changes, call the tool again with exactly those changes and nothing else changed (the user will be asked to approve the new call); if it declines or asks for something else, do not call it again and reply briefly. With no note, or for an automated decision (`system:timeout`, `system:group`), the text is exactly what it was. Detection is the existing `system:` convention on `decidedBy`, never the note text, so the group-conversation auto-reject cannot make the model retry a call that can never be approved.
* **A per-call rejection falls back to the top-level note.** A call listed in `toolDecisions` with `REJECTED` and no note of its own (absent or blank) now uses `decision.note`, as an unlisted call already did. A call's own note still wins; approved calls are unaffected.

The re-proposed call is an ordinary new call: it is gated, pauses again with a new `pauseId` and needs its own approval, so an approved call is never silently changed. Each re-proposal counts toward `hitlConfig.toolApprovals.maxPausesPerTurn` (default 3, maximum 10); [`docs/hitl.md`](https://docs.labs.ai/conversations-and-orchestration/hitl.md) says to raise it where notes are expected to come back as revisions.

No REST shape, verdict type or default changes.

### Tests

`ToolLoopResumerNoteTest`: the envelope for a person's note, for no or blank note, and for `system:timeout` / `system:group` with a note; the per-call fallback through the real resume loop (own note kept, absent and blank fall back, unlisted unchanged); and one test that stores a paused conversation as a snapshot document, loads it back, resumes it `REJECTED` with a note and asserts the model's next request carries the new instruction and the note.

***

## 🐛 fix(llm): a `\'` inside a JSON reply no longer turns a complete answer into the fallback (2026-10-26)

**Repo:** EDDI (`fix/llm-json-repair-backslash-quote`)

### What changed and why

Gemini sometimes escapes an apostrophe inside a JSON string the way JavaScript and Python allow: `"Japan\'s ruling class"`. JSON has no `\'` escape, so `ModelOutputParser` reported `invalid JSON syntax` for the whole reply, and a `convertToObject` task served its fallback answer ("Sorry, I could not answer that just now"). In the case that showed it, the reply was complete and correct, about 1,300 characters long, and one apostrophe was the only defect.

[`ModelOutputParser`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/ModelOutputParser.java) now drops the backslash of `\'` inside JSON strings, after the fence strip and before parsing. This is the one exception to its "invalid JSON is never fixed" rule, and the class Javadoc says so. It is safe because `\'` is never valid JSON and can only mean `'`.

* The pass is string-aware and linear. It copies every other escape as the pair it is, so `\\'` (an escaped backslash, then a quote) stays valid JSON and `\"` does not end the string. Outside strings nothing changes.
* The whole reply is repaired once; when the object has to be extracted from prose, each candidate is repaired on its own, so an unmatched `"` in the text before the object cannot shift what counts as inside a string.
* A reply without `\'` is not copied.
* A repaired reply reports `repaired`, like a stripped fence.
* A reply that is still invalid keeps its raw text, and a second, real syntax error is not hidden.

### Tests

`ModelOutputParserTest`:

* accepted: the observed case, several `\'` in one object and inside an array, fenced, with prose around it, and with an unmatched quote in the prose before it;
* left alone: `\\'` stays valid and unrepaired, and an escaped double quote does not end the string;
* still rejected: prose containing `\'` is `not JSON` with the raw text kept, and `\'` plus a trailing comma is still `invalid JSON syntax`.

Mutation checks:

* With the repair switched off entirely, the acceptance cases that contain `\'` fail, and the `\\'` case passes either way, as it should.
* With only the per-candidate repair removed, the two extraction cases fail: prose around the object, and the unmatched quote before it.

***

## ✨ feat(email): conversation mode — the agent replies in the mail thread — email Phase 3 (2026-10-25)

**Repo:** EDDI (`feat/email-conversation-mode`, on top of `feat/email-trigger-mode`, `feat/email-dkim`, `feat/email-hitl-notifications` and `feat/email-mail-core`)

Phase 3 of [the email plan](https://github.com/labsai/EDDI/tree/main/planning/email-channel-plan.md) (§5 conversation column, §9, §10, §11, §12, §13, §15, §16, §17, §20, §21): `channelType: "email"` with `mode: "conversation"`. The agent answers in the thread over SMTP — **only to the DKIM/DMARC-authenticated `From`** of the mail it answers, never `Cc`, never an unauthenticated or `email-anon:` sender, never an address the model chooses. Trigger mode is unchanged and still sends nothing. Docs: [email-integration.md → Conversation mode](https://docs.labs.ai/protocols-and-integration/email-integration.md#conversation-mode).

### Settings and save validation

* **`EmailChannelSettings`**: `mode: "conversation"` is accepted, with `smtpHost` (required), `smtpPort` (587 STARTTLS required, default, or 465), `fromName` (header-safe, ≤ 100), `replyTemplate` (`{output}`, ≤ 4000), `aiDisclosure` (a default sentence; **a present, empty value switches it off**, ≤ 500), `threadParticipants` (`originalSenderOnly` | `anyAuthenticatedParticipant`), `maxRepliesPerThreadPerHour` (5, 1–1000) and `honorReplyTo` (false). `requireAuthentication: false` is refused in conversation mode, and `from()` forces it true so no reader can see false; `correlateThreads` is implied (and refused with a value). Each mode refuses the other's keys when they carry a value. New save warnings in `X-Eddi-Warnings`: `email.ai-disclosure-disabled`, `email.honor-reply-to`.
* **`EmailChannelSupport`** also resolves `smtpHost` under the **author** socket policy (`SafeSocketConnector.resolve`, `Protocol.SMTP`) and requires the connection's allowlist to name `smtp://<host>:587` / `smtps://<host>` besides the IMAP origin.

### Transport and the reply path

* **`SmtpSubmitter`** (`engine/mail`, new): the one SMTP submission over Angus Mail on a `SafeSocketConnector` endpoint, extracted from `SystemMailer` (which now delegates). The policy is the caller's: it takes an `Endpoint` and never resolves a host.
* **`MailTransport.send`** (SPI) — `ImapMailTransport` sends over SMTP with the integration's connection (BASIC, or XOAUTH2 with the mailbox as user), envelope sender = the mailbox (bounces come back to it). It refuses an integration that is not in conversation mode, and any endpoint that is not an author-policy SMTP endpoint, before a socket opens. `MailboxSession.findByMessageId` finds a mail again by `SEARCH HEADER Message-ID` (exact match after) in the polled folder or the move folder.
* **`integrations/email/reply/`** (new): `EmailReplyRecipients` (the one recipient decision, re-applied on every attempt: conversation mode; the answered mail is this integration's inbound row and reached a turn; the conversation runs as `email:<id>` / `email:<id>:<address>`, never `email-anon:`; the mail's step in memory names the same mail, `aligned-pass` and the same `From`; under perSender + originalSenderOnly the identity is that address; never the own address; `Reply-To` only with `honorReplyTo` and exactly one address), `EmailReplyComposer` (`replyTemplate` on the restricted engine with the output and subject as data, then the disclosure; `OutboundMail.replyInThread`, new), `EmailReplyThread` (reads the reply from conversation outputs — the same outputs from the completion callback and from the stored conversation), `EmailReplySender` (ledger rows, inline first attempt on a managed executor, retries, bounces), `EmailHitlResumeObserver`.
* **Ledger**: `Kind.REPLY`, `Direction.OUT`, idempotency key `reply:<sha256(conversation, inbound row + step, kind)>`, `sourceRef` = `<inbound row>|<kind>|<step|pause|verdict>`; claim/lease/complete/reschedule like notifications, its own worker (`@Scheduled(identity = "email-reply-sweeper")`, `eddi.email.reply.sweep-interval`, `claimDue(Kind.REPLY)`), backoff and attempts from `eddi.email.outbound.*`, `FAILED` → owner notice `reply_failed`. No body: a retry re-reads the conversation and re-renders under the row's Message-ID. New `findByConversation` and `countByConversationSince` (indexes on both stores).
* **Inbound** (`EmailInboundProcessor`, conversation-mode branch only): the turn is submitted with all outputs in the **detailed** projection — the default one strips each step's `context`, where the mail map lives, so a reply would find no step to answer (`EmailReplyThreadSnapshotTest` pins this against the real converter, and the retry and sweep reads ask for the same) — and with the mail's ledger key as its idempotency key; its completion hands the snapshot to the reply sender **before** the row moves to `DONE`. A mail whose `In-Reply-To`/`References` names one of the integration's replies continues that reply's conversation — when its sender started it, or (anyAuthenticatedParticipant) a reply in it was sent to them; anyone else falls through to the sender-keyed thread key. The `mail` context map gains `inReplyTo`, `references`, `replyTo`. A group target's synthesis is the reply (`GroupDiscussionEventListener.onGroupComplete`).
* **HITL in the thread**: on `HitlPauseCommittedEvent` the sender gets the output so far plus the pause reason — never the tool or its arguments; on `HitlResumeCompletedEvent` the continuation (approval) or a plain notice (rejection, cancellation, timeout, failed continuation), the approver never named. Human takeover: not built (`planning/human-takeover-design.md` is a design under review), so nothing to send.

### Loops, bounces, suppression

* `maxRepliesPerThreadPerHour` counted from the ledger per conversation; over it the row is `SUPPRESSED` (`THREAD_BUDGET`) with a once-a-day owner notice `thread_throttled`.
* A DSN for one of the integration's own reply Message-IDs, with a permanent failure for **that reply's recipient**, fails the row (`BOUNCED: <status>`) and adds the address to the new **`IEmailSuppressionStore`** (Mongo + Postgres, per integration, SHA-256 + domain, no address); delays are noted. Never sent to a suppressed address (checked at queueing and before each attempt). Cleared by an administrator through the new `GET /channelstore/channels/{id}/email-suppressions` and `POST …/email-suppressions/clear` (EDIT on the integration; the address in the body, not the URL). Deleting the integration drops its list; GDPR erasure deletes an address's entries (`EmailSuppressionGdprParticipant`, step `emailSuppressions`).

### Stranded handling (both modes)

* A `TURN_SUBMITTED` row whose conversation holds the mail's step: conversation mode rebuilds the missing reply (or pause notice) from the stored conversation (`stranded_recovered{outcome=reply_rebuilt}`) before closing the row.
* **The trigger-mode gap is closed**: a conversation that was started but never ran the mail's turn (idle or paused, no step for the mail) is handed back to `RECEIVED` keeping its conversation (conditional — one sweeper wins, `outcome=resubmitted`); the next poll finds the mail by Message-ID in the polled or move folder and runs it once in that conversation (the turn's idempotency key is the mail's ledger key). Not in the mailbox any more → `REFUSED(stranded:not_in_mailbox)` + `lost` notice. Ended or failed conversations, and unreadable ones, are resolved as before — when in doubt, a mail is not run twice.

### Metrics, audit, Manager, operator, docs

* `eddi.email.outbound{kind=reply,outcome=sent|retry|failed|suppressed|throttled|refused|bounced|no_output}`, `eddi.email.outbound.latency{kind=reply}`, `eddi.email.suppressions{reason}`; `eddi.email.inbound` gains `outcome=bounce` and real `mode` tags. Three Full Metrics panels (k8s copy re-synced), [metrics.md](https://docs.labs.ai/deployment-and-infrastructure/metrics.md).
* Audit `email.reply` per sent, failed or bounced reply (integration, reply kind, outcome, Message-ID, ledger row, recipient domain + SHA-256 — no address, no body).
* Manager: a mode selector, a Replies section (SMTP host/port, sender name, who may continue a thread, reply limit, Reply-To with its warning, AI disclosure toggle with its warning, reply template), forced authentication in conversation mode, mode switches drop the other mode's keys, DKIM/DMARC and suppression notes, the two new warning toasts; 38 new `emailChannel.*` keys and one reworded (`modeNote`) in all 11 locales. **Operator revision 38 → 39**: the system prompt explains conversation mode, its recipient rules, HITL in the thread, bounces and how suppressions are cleared; no channel endpoints are granted (the operator has none), so `tool-scopes.ts` is unchanged. MCP channel tool descriptions and the `eddi-admin` plugin skill cover conversation mode.
* Docs: [email-integration.md](https://docs.labs.ai/protocols-and-integration/email-integration.md), [hitl.md](https://docs.labs.ai/conversations-and-orchestration/hitl.md#email-conversations), [security.md](https://docs.labs.ai/security-and-compliance/security.md#email-replies-conversation-mode), [configuration-reference.md](https://docs.labs.ai/deployment-and-infrastructure/configuration-reference.md#email), [gdpr-compliance.md](https://docs.labs.ai/security-and-compliance/gdpr-compliance.md), [compliance-data-flow.md](https://docs.labs.ai/security-and-compliance/compliance-data-flow.md); the plan's status line says Phases 0–3 are implemented and 4–7 are not.

### Tests

Unit: `EmailReplyRecipientsTest` (every rule alone), `EmailReplyComposerTest` (output and subject as data, `{#include}` printed, threading headers, header injection), `EmailReplySenderTest` (idempotency under concurrency, suppression at queueing and before the attempt, thread budget, retries rebuilt with the same Message-ID, permanent failure → owner notice, re-checked rules on retry, pause notice minimisation, resume continuation, DSN mapping and spoofed DSNs, group synthesis), `EmailConversationModeTest` (processor + sender: reply, thread via EDDI's Message-ID, hijack guard, participants, unauthenticated never answered, bounce → suppression, resubmission, trigger mode never touches the reply sender), `EmailChannelSupportTest`, `EmailHitlResumeObserverTest`, `EmailSuppressionGdprParticipantTest`, the suppression store contract on the in-memory double, and new cases in `EmailChannelSettingsTest`, `RestChannelIntegrationStoreEmailTest`, `EmailInboundSweeperTest`, the ledger contract. `EmailTriggerModeSendsNothingTest` is rewritten on purpose: `SystemMailer` only in the staff notifiers, SMTP only in `ImapMailTransport` (and the save-time host check), composing only in the notifiers and the reply path, `transport.send` only in `EmailReplySender`, and the transport refusing trigger mode. ITs: `EmailConversationModeIT` (GreenMail IMAPS + SMTPS on loopback, TLS verified: full loop with headers, answer to EDDI's Message-ID, third party, bounce → suppression, crash before send → exactly one rebuilt reply, resubmission found by Message-ID and run once), `Mongo/PostgresEmailSuppressionStoreIT`, the new cases of `Mongo/PostgresEmailMessageLedgerIT`. The security guards were mutation-checked.

### Review follow-up (PR #1144)

* **Resubmissions per integration.** `pendingResubmissions` read one global batch of 50 due `RECEIVED` rows and filtered it in memory, so rows nobody polls any more (a deleted or invalid integration's) could fill it for ever. The new `IEmailMessageLedger.findDueResubmissions(integrationId, now, limit)` filters in the store (MongoDB, PostgreSQL, in-memory, contract case). Orphaned rows block nobody now and are left to ledger retention.
* **No 500-row cap on a thread.** `findByConversation` (oldest 500 rows) gives way to `findInboundTurn(conversationId, latest)` and `hasSentReply(conversationId, recipient)`, so a long thread still finds the mail a pause notice or continuation answers, and `anyAuthenticatedParticipant` still admits an address a late reply went to.
* **Cost before the reply.** `completed()` records the turn's spend before queueing the reply, so a reply that cannot be queued no longer drops the cost from `dailyCostBudgetUsd`.
* **A failed reply rebuild keeps the row.** The stranded sweep leaves the row `TURN_SUBMITTED` (`reply_rebuild_failed:<n>`, deadline moved by `stranded-after`) and tries again, 5 sweeps in all, instead of closing it `DONE` with no reply.
* **Oversized resubmission.** A resubmitted mail found over `maxMessageBytes` ends `REFUSED(too_large)` and the poll goes on, instead of failing and backing off on the same row every poll.
* **Wording.** [hitl.md](https://docs.labs.ai/conversations-and-orchestration/hitl.md#email-conversations), [configuration-reference.md](https://docs.labs.ai/deployment-and-infrastructure/configuration-reference.md#email) and [email-integration.md](https://docs.labs.ai/protocols-and-integration/email-integration.md) say the ledger deduplicates rows, not deliveries: a crash after the relay accepted a message and before its row completed can send it twice (same Message-ID). The recipient rule in the Manager's mode note, the operator prompt (revision 40), the `create_channel_integration` description and the `eddi-admin` skill now name the `honorReplyTo` exception; the throttle hint says further replies are not sent (they are `SUPPRESSED`), not delayed — all 11 locales.
* **Manager mode.** `emailMode` reads the mode case-insensitively like `Mode.fromId`, so an API-saved `"CONVERSATION"` integration keeps its conversation controls and reply settings on save.
* Tests: `EmailConversationModeTest`, `EmailReplySenderTest`, `EmailInboundSweeperTest`, `EmailMailboxPollerTest`, the ledger contract (`Mongo/PostgresEmailMessageLedgerIT`) and `email-channel.test.ts`, each mutation-checked.

***

## ✨ feat(email): the email channel in trigger mode over IMAP — email Phase 2 (2026-10-25)

**Repo:** EDDI (`feat/email-trigger-mode`, on top of `feat/email-dkim`, `feat/email-hitl-notifications` and `feat/email-mail-core`)

Phase 2 of [the email plan](https://github.com/labsai/EDDI/tree/main/planning/email-channel-plan.md) (§3, §5 trigger column, §6, §7.1 inbound, §9–§14, §17, §20, §21): `channelType: "email"` with `mode: "trigger"`. EDDI polls an IMAP mailbox and every new mail starts one agent turn. **Nothing is ever sent to a sender** — no reply, no bounce. Conversation mode is refused at save time until Phase 3. Docs: [email-integration.md](https://docs.labs.ai/protocols-and-integration/email-integration.md).

### The channel

* **`EmailChannelSettings`** (`configs/channels/model`): one reader for the save and the poll path, every key of plan §10's trigger mode with its default, plus `port` (993 / 143), `correlateThreads` and `ownerNotifyAddresses`. Unknown keys and the conversation-mode keys (`smtpHost`, `replyTemplate`, `aiDisclosure`, …) are refused; the connection is a name, never a credential; `attachments: store` needs a MIME allowlist.
* **`RestChannelIntegrationStore`** registers `email`. Besides the static checks, `EmailChannelSupport` checks against the deployment: the host passes `SafeSocketConnector.resolve` (author policy), the connection exists, is `BASIC` or OAuth, not `PER_USER`, and its allowlist names `imaps://<host>` / `imap://<host>:143` (`ConnectionResolver.requireMailLoginTarget`, new — no credential is resolved), and the address is unique per deployment (fail closed). `observeMode` is refused. Saving (re)creates the poll schedule; deleting removes it; duplicating is refused (same address). **Warnings** ride in a new `X-Eddi-Warnings` header as stable codes: `email.open-trigger` (no allowlist and no authentication requirement) and `email.tools-without-approvals` (a target agent can use tools but has no `toolApprovals`, found by `EmailAgentToolsInspector` — plan §14 item 6). MCP `create_channel_integration` / `update_channel_integration` describe the email keys and return the warnings.

### Polling (no custom scheduler)

* **`EmailPollSchedules`** (marker, like `RagIngestionSchedules`): one `HEARTBEAT` schedule per integration, `email-poll:<integrationId>`, every `pollSeconds`. `ScheduleFireExecutor` hands it to `EmailMailboxPoller` before the creator check (the integration governs it) and refuses a row whose name does not match its metadata; `RestScheduleStore` refuses client bodies declaring the marker, refuses updates of a managed poll schedule (409), and requires EDIT on the integration to fire one. A mail-server outage is a COMPLETED fire with the error in the fire log: the poller backs off by itself (`pollSeconds × 2^(failures−1)`, ≤ 1 h) instead of the schedule dead-lettering.
* **`ImapMailTransport`** (Angus Mail on `SafeSocketConnector`, author policy only): XOAUTH2 with `resolveAccessToken` (the address as the user) or `BASIC` with `resolveBasicLogin`; one folder opened read-write; envelope + flags + `RFC822.SIZE` + `INTERNALDATE` first, then `BODY.PEEK[]` (never `\Seen`) bounded by `maxMessageBytes`; marking sets `$EddiProcessed` where the server takes keywords and moves with `MOVE` when configured — never a copy-and-delete, never an expunge (the folder is closed with `expunge=false`).
* **Cursor** (`IEmailMailboxStateStore`, Mongo + Postgres, new): `UIDVALIDITY` + the last UID up to which everything is settled; a deferred mail holds it back. The first poll starts at `UIDNEXT` and records `since`, so mail predating the integration is never processed (rescans included, with 5 min slack for whole-second `INTERNALDATE`s). A changed `UIDVALIDITY` rescans, deduplicated by the ledger and the keyword, counted.

### The inbound pipeline (`EmailInboundProcessor`)

Envelope Message-ID pre-check (a deferred or settled mail costs no download) → size → fetch → parse → **ledger row `RECEIVED`** (conditional insert on `(integration, IN, Message-ID)`) → `SenderAuthenticator` as of `INTERNALDATE` (a `temporary` verdict defers the mail, unmarked, for at most a day) → `EmailLoopGuard` (auto-reply headers, reports, daemon/null return paths, own address, another integration's address, EDDI-minted Message-IDs, replies to mail another integration or the system mailer sent) → blocklist → allowlist → `requireAuthentication` → daily cost budget (stops the batch) → per-sender daily turns (defers to the next UTC day) → identity → routing (plus-tag, then subject word, then default) → optional thread correlation → **claim `RECEIVED → TURN_SUBMITTED`** → conversation, attachments, turn (queued, not awaited) → `DONE` from the completion callback with the turn's cost added to the day. Every refusal is `REFUSED(<reason>)`, counted, never answered.

* **Identity** (`EmailUserIdentity`): `email:<integrationId>:<address>` (perSender) or `email:<integrationId>` (integration) only for `ALIGNED_PASS`; otherwise, with `requireAuthentication: false`, a one-off `email-anon:<random>` that never correlates and **has no memory**: `ReservedPrincipals.hasNoPersistentMemory` makes `ConversationService.createPropertiesHandler` hand it no user-memory store and no memory tools, and `ContextualToolsProvider` refuses the memory tool for it as a second line. Both prefixes are reserved principals. Turns are `SELF_ASSERTED` (no caller identity on the poll thread), so `PER_USER` connections are refused.
* **Hijack guard**: the thread mapping key (`IUserConversationStore`) is `email:<integrationId>:<agentId>:sha256(threadRoot + sender)` — a continuation from anyone but the original authenticated sender starts its own conversation, in both identity modes. Busy or paused conversations defer the mail.
* **Mail is data**: `inputTemplate` (default: the mail framed as untrusted third-party content, plan §14 item 4 — a deliberate deviation from §10's bare `{mail.subject}\n\n{mail.text}`) renders on the restricted runtime engine with the mail as data; a failing template falls back to subject + text joined in Java. The `mail` context carries plan §10's fields plus `anomalies` (e.g. `alternatives_diverge`); `mail.text` goes to the template only.
* **Attachments**: `store` puts allowlisted types into `IAttachmentStore` under the conversation and passes `attachment_<n>` (`storageRef`) to the multimodal pipeline; executables never, at most 20, every skip named.
* **Budgets and owner notices** (`EmailOwnerNotifier`): once per UTC day and reason (`budget`, `throttled`, `quota`), cluster-wide via `claimNotice`: a WARN line always, plus a plain-text mail through the Phase 1 system mailer to `ownerNotifyAddresses` inside `eddi.mail.notify.allowed-recipient-domains` when a mailer is configured; one attempt, a `NOTICE` ledger row, no retry. Tenant quotas apply as for webhooks (a refusal hands the claim back and stops the poll).

### Ledger, stranded turns, GDPR

* `IEmailMessageLedger` gains `Kind.TRIGGER`/`NOTICE`, the inbound states, `transition`, `findDue`, `findByMessage`, `findOutboundByMessageId` and `countInboundTurns` (new indexes on both stores). An inbound row's `recipient` is the sender, so the existing erasure/export path reaches it.
* **Stranded turns** (`EmailInboundSweeper`, `@Scheduled(identity = "email-inbound-sweeper")`): a row still `TURN_SUBMITTED` past `eddi.email.inbound.stranded-after` is resolved from its conversation — idle/failed/paused → `DONE`, running → deadline extended, no conversation → `REFUSED(stranded)`. In trigger mode there is no reply to rebuild, and a mail is **never run twice** (the raw bytes are not kept and a second run could repeat tool side effects), so a node dying between claim and turn is the one way a mail can be lost; it is logged and counted. The sweep also re-creates missing poll schedules (e.g. after a ZIP import).
* **Audit**: every refused mail is an audit entry `email.inbound` (integration, reason category, ledger row, Message-ID, sender domain + SHA-256, no address or content). Integration create/update is not audited separately yet.
* **GDPR**: `EmailIdentityGdprParticipant` (`emailIdentities`) runs the erasure/export cascade for every `email:<integrationId>:<address>` identity of an address (current integrations and those its inbound rows name); `EmailLedgerGdprParticipant` also matches `email:` identities.

### Metrics, docs, Manager, operator

* `eddi.email.inbound{integration,transport,mode,outcome}`, `eddi.email.poll.duration{…,outcome}`, `eddi.email.poll.cursor_resets`, `eddi.email.ledger.stranded_recovered{outcome}`; `eddi.email.outbound` gains `kind=notice`. Four panels on the Full Metrics dashboard's Integrations row (k8s copy re-synced), [metrics.md](https://docs.labs.ai/deployment-and-infrastructure/metrics.md). `eddi.email.auth{result}` stays deployment-wide (one tag set per name).
* New properties `eddi.email.poll.max-messages-per-poll` (50), `eddi.email.poll.max-duration` (2m), `eddi.email.inbound.stranded-after` (30m), `eddi.email.inbound.sweep-interval` (5m).
* Docs: [email-integration.md](https://docs.labs.ai/protocols-and-integration/email-integration.md) (Exchange Online with OAuth client credentials and a per-mailbox permission, app passwords, every key, what the agent sees, identity, threads, budgets, security, the **helpdesk recipe** — webhook channel + `httpcalls`), [SUMMARY.md](https://github.com/labsai/EDDI/tree/main/docs/SUMMARY.md), [security.md](https://docs.labs.ai/security-and-compliance/security.md), [configuration-reference.md](https://docs.labs.ai/deployment-and-infrastructure/configuration-reference.md#email), [compliance-data-flow.md](https://docs.labs.ai/security-and-compliance/compliance-data-flow.md) (the mailbox host as processor), [gdpr-compliance.md](https://docs.labs.ai/security-and-compliance/gdpr-compliance.md), [connections.md](https://docs.labs.ai/protocols-and-integration/connections.md).
* Manager: an Email channel type with a trigger-mode form, the security hints (allowlist, Exchange per-mailbox permission, tool approvals), the open-trigger warning before saving and the `X-Eddi-Warnings` codes as toasts after (`api-client.ts` now exposes response headers); 73 `emailChannel.*` keys in all 11 locales. **Operator revision 37 → 38**: the system prompt explains the email trigger channel, its security posture and when to use the helpdesk recipe instead; no new endpoint, so `tool-scopes.ts` is unchanged. The `eddi-admin` Claude plugin skill mentions the email channel.
* `ReservedPrincipalsTest` classifies the new non-principal prefixes (and `sha256:` / `notify:`, which the previous slice left unclassified).

### Tests

Unit: `EmailChannelSettingsTest`, `EmailInboundProcessorTest` (state machine; temporary verdicts not marked; unauthenticated refused or anonymous without correlation; loop guard; lists; oversize before download; crash after claim; hijack guard in both identity modes; executables never stored; Qute in subject/body printed, not run; budgets, throttle, quota), `EmailMailboxPollerTest` (mark after the ledger, cursor holding, STOP, skips, UIDVALIDITY, backoff, self-removal), `EmailInboundSweeperTest`, `EmailChannelPiecesTest` (patterns, identity, schedule, notices, GDPR), `RestChannelIntegrationStoreEmailTest`, and email cases in `ScheduleFireExecutorTest`, `RestScheduleStoreTest`, `ConversationServiceDeepBranchTest`. ITs: `EmailImapPollingIT` (GreenMail IMAPS on loopback through the `SafeSocketTestSupport` seam, TLS verified: new mail runs and is flagged but not `\Seen`, move, oversize, crash between ledger and mark, UIDVALIDITY change, login failure), `Mongo/PostgresEmailMailboxStateStoreIT`, and the inbound cases of `Mongo/PostgresEmailMessageLedgerIT`. The security guards were mutation-checked.

### Review follow-up: crash recovery, keywords, type switching, a send guard

* **A claimed mail that did nothing is processed again.** New inbound state `CLAIMED` between `RECEIVED` and `TURN_SUBMITTED`: the claim is taken first, and `TURN_SUBMITTED` (the point of no return) is written immediately before the first side effect (conversation start, group discussion, turn). A mail is marked or moved only when its row is past that point or refused, and the cursor never passes an unsettled mail, so a `CLAIMED` mail is still unmarked in the polled folder. A stale claim (past `eddi.email.inbound.stranded-after`) is given back to `RECEIVED` — by the next poll that meets it, or by the inbound sweep — and the poll fetches and processes it again (`stranded_recovered{outcome=requeued}`). The sweep deliberately opens no IMAP session: the poller owns the mailbox under its schedule's cluster claim. Only `TURN_SUBMITTED` without a recorded conversation (a crash inside `startConversation`, whose `CONVERSATION_START` may have called tools) stays `REFUSED(stranded)`, now also with the once-a-day owner notice reason `lost`.
* **Servers without custom keywords** (Exchange Online, some hosters): marking checks `PERMANENTFLAGS` for `\*` or `$EddiProcessed`; without them — or when the server refuses the STORE anyway — no keyword is set, the poll goes on (cursor + ledger), one WARN per integration per node, and the new `eddi.email.poll.marked{result}` counter (dashboard panel) shows `nothing`. Not refused at save time: saving does not connect to the mailbox. The docs recommend `move:<folder>` for Exchange.
* **Manager:** switching an existing channel's type drops the old type's keys (`platformConfigForType`); switching to email starts from the fixed mode/transport keys, and nothing resurfaces on a round trip.
* **No reply path, pinned:** `EmailTriggerModeSendsNothingTest` scans `integrations/email/` and fails if anything but the two staff notifiers (`EmailOwnerNotifier`, `HitlEmailNotifier`) references `SystemMailer`, an SMTP transport or the outbound renderer. Phase 3 changes that test on purpose.
* Not handled yet: a node that dies after starting a conversation but before the queued turn ran is resolved as `DONE`.

### Review follow-up 2: one start per mail, no partial integration list, CORS

* **A retried mail reuses the conversation an earlier attempt started.** When the turn failed after `startConversation` (a quota, a busy executor, a failed `say`), the row went back to `RECEIVED` and the retry started a second conversation, so `CONVERSATION_START` (which may call tools) ran again — for any mail without a thread mapping (`correlateThreads` off, or unauthenticated). `EmailInboundProcessor` now reads the row's `conversationId` on the retry and sends the turn there; a busy one defers, an ended one starts a new conversation (as a mapped one does). Chosen over refusing such mails, which would drop every mail that met a passing rate limit.
* **`EmailIntegrationDirectory.scan()` no longer returns a partial list.** A store read failure on one integration was swallowed per descriptor, so address uniqueness at save time (fail closed, 503), GDPR identity expansion and schedule ensuring could silently miss it. `find()` now throws `StoreUnavailableException`, which `scan()` lets through; only an unparseable descriptor is skipped.
* **`X-Eddi-Warnings` is in `quarkus.http.cors.exposed-headers`**, so a Manager on another origin sees a channel save's warnings (`CorsExposedHeadersConfigTest`).
* Docs: the ledger lifecycle in [email-integration.md](https://docs.labs.ai/protocols-and-integration/email-integration.md#the-message-ledger) names `CLAIMED`; the Full Metrics Reference's stranded panel describes `requeued` and the current meaning of `lost`.

### For Phase 3 (conversation mode)

* Replies are `Kind.REPLY` rows, `Direction.OUT`, with `sourceRef` = the conversation step; the loop guard already exempts replies to an integration's *own* outbound ids. The thread key (`EmailInboundProcessor.correlationIntent`) and `threadRoot` are the mapping to reuse; add the outbound Message-IDs to the root lookup.
* The stranded sweep is where a lost reply is rebuilt from the snapshot (`TURN_SUBMITTED` past its deadline with a completed step and no `REPLY` row).
* SMTP for a channel must use `SafeSocketConnector.resolve` (author policy), never `SystemMailer`/`resolveOperator`.
* `email-anon:` identities must never receive a reply (plan §9); `requireAuthentication` is forced on there.

***

## 🎨 feat(manager): brand-aware strings, logos, titles, update UI and About — white-label phase 3 (2026-10-25)

**Repo:** EDDI (`feat/white-label-4-manager-strings`)

### What changed and why

Phase 3 of the [white-labeling plan](https://github.com/labsai/EDDI/tree/main/planning/white-label-ui-plan.md): the Manager names the brand instead of EDDI. Unbranded, everything reads and looks as before. [`docs/white-labeling.md`](https://docs.labs.ai/deployment-and-infrastructure/white-labeling.md) has a new "The Manager" section.

* **`src/lib/brand.ts`** reads `window.__EDDI_BRAND__` field by field, with the EDDI defaults for anything missing, so Vitest, the dev server and MSW mode need no backend. It is one store (`getBrand`, `setBrand`, `subscribeBrand`); components use `useBrand()` (`src/hooks/use-brand.ts`, `useSyncExternalStore`). `brand.test.ts` evaluates the Vite plugin's `DEFAULT_BRAND_SCRIPT` and requires it to equal `DEFAULT_BRAND`, which closes the chain Java = plugin = `brand.ts` that `BrandDeliveryTest` starts.
* **Strings.** `src/i18n/config.ts` sets `interpolation.defaultVariables = { productName, shortName }` before `i18nReady` resolves, and updates them in place (then re-announces the language) when `setBrand` runs, which is what Phase 4's live reload needs. Of the 77 English values naming EDDI, 63 product mentions became `{{productName}}` in all 11 locales by script; 12 engine-version gates ("Needs EDDI 6.6 or later", "This EDDI does not record…") were rewritten by hand to "server version" wording in every locale; 2 technical names stay (the `eddi-v1` webhook signature hint and the "EDDI Cluster" Grafana dashboard). 76 `t()` fallbacks in 45 files follow `en.json`. Eleven translations that had dropped the name, or named it once where English names it twice (`onboarding.tour.dashboard.step4Desc` in four locales, `syncPage.*` in three, one German sentence) were retranslated with the variable, because the interpolation-integrity test now sees it. The secrets API's English error no longer names EDDI.
* **Guard:** `src/__tests__/no-eddi-brand-literal.test.ts` fails on `\bEDDI\b` in any locale value, `t()` fallback, `defaultValue`, JSX text, or `alt`/`aria-label`/`title`/`placeholder` in `src` (tests, test mocks and comments excepted), after stripping `EDDI_*`, `X-EDDI-*` and `labsai/EDDI`. Its key allow-list holds the Powered-by notice and the two technical names, each with a reason. The Platform Operator's files are excluded with a TODO naming Phase 6.
* **Logos.** `components/layout/brand-logo.tsx` (`BrandWordmark`, `BrandIcon`) replaces the bundled data URI in both sidebars and `/eddi-icon.svg` on the landing page, the Workforce collapsed sidebar and the Workforce onboarding hero. The collapsed Manager sidebar shows `/branding/icon` when branded and the "E." monogram otherwise. Alt texts and labels are the product name.
* **Titles:** `use-document-title.ts` builds `<page> — <app.title>`, and `app.title` is `{{productName}} Manager`.
* **Update UI (R5):** `isUpdateUiVisible(brand)` (`!branded || showUpdateCheck`) gates the Updates nav entry and command-palette entry (through `useMayOpenScreen`), the `/manage/updates` route (redirects to `/manage`), the banner in `AppLayout`, and the automatic check itself (`useUpdateCheck`'s query is disabled), so a stored auto-check preference never contacts GitHub on a branded deployment.
* **About dialog** (`components/layout/about-dialog.tsx`), opened from the Help menu in the sidebar footer, and from the version label when the update UI is hidden: product name, tagline, version, and while `poweredBy` is on, "Powered by EDDI" with the Apache 2.0 notice and a license link. Six `about.*` keys in all 11 locales.
* **Dev entry.** `ui/manager/index.html`, which serves deep links under `npm run dev`, now loads `/branding/__brand__.js` before the bundle and `/branding/brand.css`, uses `/branding/icon` and the `%BRAND_PRODUCT_NAME%` placeholders; `vite-plugin-brand.test.ts` pins it.
* **Monaco:** the prompt editor's template-variable colours come from `--editor-template-variable(-light)` in `index.css`, read once at registration (`src/lib/css-color.ts`), with today's hex as the fallback.

### Design decisions

* **The light/dark logo trick depends on `branded`.** The bundled default for both `/branding/logo` and `/branding/logo-dark` is the white EDDI wordmark (the shells' loader shows `/branding/logo` on a dark background, so the default cannot be dark). Unbranded, the sidebar keeps one image with `invert dark:invert-0`, pixel for pixel as before. Branded, it shows the light and the dark slot as two images switched by the `.dark` class (a `<picture>` media query cannot see the app's theme) and never inverts, since inverting a colour logo produces its negative. Trade-off: a brand that sets only a name keeps the white EDDI wordmark, which is faint on the light sidebar. The settings page (Phase 4) can warn about that; `__brand__.js` does not say which slots are uploaded.
* **A failed `/branding/*` logo falls back to the bundled wordmark** (`onError`), so the design-system bundle, which has no server, still renders it; `src/assets/logo_eddi.png` therefore stays.
* **Engine-version gates name the server, not the brand.** "Needs Acme 6.6" would mix the brand with EDDI's version numbers; "server version 6.6" is true under any brand. The sidebar's version label does show `<product> <version>`, as the plan asks.
* **The update strings use `{{productName}}`** rather than an allow-list: they only show unbranded or when the brand opted in.
* **About sits in the Help menu** so it is reachable with the sidebar collapsed too. "Version" is a label beside the number rather than `Version {{version}}`, which would have counted as untranslated in German and French.

### Verified

`npm run typecheck`, ESLint over every changed file, `npm run i18n:check` (6,066 keys, no drift), and Vitest over 94 files touching the changed components plus all `src/i18n/__tests__` (plural categories, translation-debt baseline, interpolation integrity), the new guard, `brand.test.ts` and `branding.test.tsx` (14 branded-mode tests: sidebar logo, monogram and icon, a brand applied after render, Workforce sidebar, landing page, version label, About with and without Powered-by, update UI hidden and restored, the route redirect, the document title). Mutation checks: the guard fails on an `EDDI` in a locale value, in a `t()` fallback and in an `alt`, and on removing a Phase-6 exclusion; the branded tests fail when the update query, `useMayOpenScreen`'s gate, the route gate, the logo branch or the title are reverted (the `AppLayout` banner gate is defence in depth: the disabled query already keeps the banner away). Brand-leak smoke in MSW mode with a "Zebra Labs" brand forced into `window.__EDDI_BRAND__`: `/welcome`, `/manage`, agents, resources, approvals, secrets, connections, cluster, sync, privacy and `/workforce` show no EDDI in text, alt, aria-label or title, and every image comes from `/branding/`. The remaining hits are the "EDDI Cluster" Grafana name (allow-listed) and the shell `<title>` on `/welcome` and `/workforce`, which only the dev plugin fills with EDDI; EDDI itself renders it per brand. `/manage/updates` redirected to the dashboard. The full Vitest suite was not run locally.

### What's next

Phase 4: the Settings → Branding page, which calls `setBrand` after a save. Phase 6: the Platform Operator (its prompt, activation screen and API errors still say EDDI; the guard excludes those files with a TODO) and the A2A agent-card defaults in `agent-detail.tsx`. Also open: `src/lib/llm-parameter-catalog.data.ts` carries two generated notes naming EDDI.

***

## 🎨 feat(manager): Settings → Branding page with live preview and live update — white-label phase 4 (2026-10-25)

**Repo:** EDDI (`feat/white-label-5-branding-page`)

### What changed and why

Phase 4 of the [white-labeling plan](https://github.com/labsai/EDDI/tree/main/planning/white-label-ui-plan.md): an admin edits the brand in the Manager instead of with `curl`. [`docs/white-labeling.md`](https://docs.labs.ai/deployment-and-infrastructure/white-labeling.md) has a new "The Branding page" section.

* **Backend tweak.** `__brand__.js` now carries `assets: {logo, logoDark, icon, favicon, ogImage}`, booleans saying which slots have an image of their own (uploaded or from `assets-dir`); the hashes stay on the admin API. `/branding/logo` always answers an image, the bundled EDDI one when nothing is uploaded, so without this a brand that set only a name kept the EDDI wordmark (the Phase 3 gap). Both Vite plugins' `DEFAULT_BRAND_SCRIPT` and `brand.ts`'s `DEFAULT_BRAND` follow; `BrandDeliveryTest` gains a test for the flags and one that `ui/manager/src/lib/brand-css.ts` carries `BRAND_SCALE` verbatim.
* **Logos close the Phase 3 gap.** `BrandWordmark` shows the product name as a text wordmark when the brand has no logo (per mode: only a dark logo means text in light mode). `BrandIcon` draws the short name's initial on the primary colour when the brand has no icon. Branded image URLs carry `?r=<revision>` (`brandAssetUrl`), so a replaced logo shows at once despite `max-age=300`.
* **The page** (`src/pages/branding.tsx`, route `/manage/branding`, Admin section, `nav.branding`): names with character counts; five colours with a picker and a text field; the two toggles; a light and a dark preview (`components/branding/brand-preview.tsx`); five image drop zones (`components/branding/brand-asset-slot.tsx`); Save; Reset behind a confirmation; the source badge and last-saved line; a locked notice naming `eddi.branding.locked` and the source.
* **Validation** mirrors `BrandValidator` in `src/lib/brand-validation.ts` (caps 40/12/120, `<`/`>`, control and bidi characters, the colour grammar, WCAG contrast). Save is disabled while any field fails; server `violations` are shown on the field they name, and server `warnings` after an accepted save. A per-pair contrast badge updates as you type.
* **Preview** uses the brand's tokens on the preview container: `brand-css.ts` builds the same declarations `BrandDelivery.stylesheet` writes, and `index.css` gains `.brand-preview-light` / `.brand-preview-dark`, which restate each mode's surfaces and the EDDI defaults (token-definition lines, so the no-amber guard allows them). So the light panel is light on a dark page, and a cleared colour previews as the default instead of the brand still in effect.
* **Concurrency.** The PUT carries the revision the form was based on. A 409 with `currentRevision` shows a conflict notice and disables Save until **Reload latest** rebases the form. An image upload or removal moves the base revision without touching the text fields, so unsaved edits survive it and the next save does not conflict with the admin's own upload.
* **Live update** (`src/lib/brand-live.ts`): after every successful write, swap the shell's `brand.css` and favicon `<link>`s to `?r=<revision>` in place, inject a fresh `<script src="/branding/__brand__.js?r=…">` (no `eval`, CSP unchanged), and `setBrand(window.__EDDI_BRAND__)` on load. A failed reload leaves the brand in effect and shows a "reload the page" toast; the write itself is not failed.
* **API and hooks.** `src/lib/api/branding.ts` (typed `BrandingView`, `BrandUpdate`, `brandingErrorInfo`), `src/hooks/use-branding.ts` (query plus four mutations with `meta.silent`, since the page renders every refusal in place). `ApiClientError` gains an optional parsed `body`, and `ApiClient` passes `Blob`/`ArrayBuffer` bodies through unchanged, so the upload keeps the token-refresh path instead of a raw `fetch`.
* **Roles.** `/manage/branding` is `eddi-admin` in `lib/roles.ts`, so the sidebar and command palette hide it from everyone else (the page explains a 403 too).
* **MSW.** `src/test/mocks/branding-handlers.ts` is a stateful stand-in for the admin API (revision checks, validation, magic-byte type check, unsafe-SVG 400, 413, 415, locked 409) and, in the browser worker, answers `__brand__.js`, `brand.css` and uploaded images from the mock's state so the live update can be seen without a backend. Variants: `sessionStorage["eddi-mock-branding-locked"]="true"`, and the tagline `trigger a conflict`. `resetBrandingMockState` runs after every test.
* **i18n.** 88 `branding.*` keys plus `nav.branding`, translated in all 11 locales; the subtitle uses `{{productName}}`.
* **Fix found on the way:** `route-integrity.test.ts` was red since Phase 3, because the Updates route was declared as `path={UPDATES_PATH}` and the test reads the route table as text. The route is literal again; `brand.test.ts` pins `UPDATES_PATH` to it.

### Design decisions

* **The route is `/manage/branding` in the Admin section**, not a new Settings section: the Manager has no settings area, and the Admin section is where the other deployment-wide admin screens are. The page title says "Branding". The plan's "Settings → Branding" wording is for Phase 6 to align (the operator prompt names the page).
* **Hidden, not just refused, for non-admins.** The neighbouring admin entries are role-gated the same way through `SCREEN_ROLES`; this page has nothing to show a non-admin.
* **Images apply on upload, text on Save.** An image is one atomic request with its own errors; holding it until Save would mean staging binary data in the form. The page says so.
* **Mock delivery, not a second dev plugin.** The dev plugin keeps answering the defaults on load (as Phase 1 decided); the mock answers only what it owns. Its `/branding/*` handler had to be anchored at the origin: the leading-wildcard mask `*/branding/*` also matched `/administration/branding/assets/…` and sent uploads past MSW to the absent backend. `browser-handlers.test.ts` pins it.

### Verified

`npm run typecheck`, `npm run lint` (full), `npm run i18n:check` (6,155 keys), and Vitest over `src/__tests__` (both guards, route integrity), `src/i18n/__tests__`, `src/test/mocks/__tests__` (OpenAPI contract, unhandled recorder, browser handlers), the layout, roles and route-registry tests, and the new `pages/__tests__/branding.test.tsx` (15 tests: load, client validation, contrast, preview tokens, save + live update through a real `applyBrandRevision` run, server violations, server warnings, the 409 → Reload latest flow, reset confirmation, locked mode, upload/remove, 400/415/413/409 image errors), `lib/__tests__/brand-{css,validation,live}.test.ts` and `lib/api/__tests__/branding.test.ts`. Mutation checks: dropping the live-update call, the base-revision rebase after an upload, the text-wordmark branch, and the origin anchor of the mock's `/branding/*` handler each fail a test. Backend: `formatter:format`, then `Brand*Test,Branding*Test,BrandedShell*Test,ImportStyleTest,BuildQualityGatesTest,ChangelogFragmentTest,Documentation*Test` — 225 tests, green. The full Vitest suite: 8,955 of 8,957 passed; the two failures were `badges.test.tsx` still expecting `warn` for the rules/behavior badge after the ochre split, fixed in a separate commit. In MSW mock mode in Chrome: name, colours and an SVG logo saved and uploaded; the sidebar logo, the title, the mock banner and every brand colour changed live in light and dark; the conflict notice and the locked view shown. Against a real backend (full `./mvnw package`, the jar on MongoDB 7): save, logo upload, the unsafe-SVG refusal and a 409 after a concurrent `curl` PUT all behaved as in mock mode, and `__brand__.js` carried the new `assets` flags. Locked mode was not run against a real backend.

### What's next

Phase 5 (Chat UI) can read the new `assets` flags the same way (`chat.logo` when a logo is uploaded). Phase 6: tell the Platform Operator where the page is (the screen-context table in `use-current-screen-context.ts` has no `branding` entry yet, on purpose), and offer the Keycloak theme download on this page. Phase 7's brand-leak E2E can drive this page, or the REST API, to set its test brand.

***

## 🎨 feat(chat): deployment brand for title, logo, accent and head — white-label phase 5 (2026-10-25)

**Repo:** EDDI (`feat/white-label-6-chat-operator-surfaces`)

### What changed and why

Phase 5 of the [white-labeling plan](https://github.com/labsai/EDDI/tree/main/planning/white-label-ui-plan.md): the Chat UI widget follows the deployment brand. [`docs/white-labeling.md`](https://docs.labs.ai/deployment-and-infrastructure/white-labeling.md#the-chat-ui) has a new "The Chat UI" section, and the [Chat UI README](https://github.com/labsai/EDDI/tree/main/ui/chat/README.md) and [embedding guide](https://docs.labs.ai/protocols-and-integration/chat-ui-embedding.md) say what overrides what.

* **`ui/chat/src/api/brand.ts`** reads `window.__EDDI_BRAND__` field by field, with `DEFAULT_BRAND` equal to the Vite plugin's `DEFAULT_BRAND_SCRIPT` (`brand.test.ts` pins it; `BrandDeliveryTest` already pins the plugin against the backend). It derives the header title (`brandTitle`), the logo (`brandLogoUrl`: `/branding/logo?r=<revision>` when a logo is uploaded, `null` meaning "show the name as text" when branded without one, EDDI's logo otherwise), the tab title (`brandDocumentTitle`) and the brand's config layer.
* **Precedence**, highest first: URL parameters, the embedder's `<ChatProvider config>`, the agent's own appearance (`agentAppearanceLayer()`, a named seam that answers nothing yet), the brand, the built-in defaults. `ChatProvider` builds its initial config from those layers once, at mount; `ChatWidget` dispatches the URL's config over it as before.
* **Header.** The title nobody overrode is the product name; an explicit `?title=` still replaces the agent name. A brand without a logo shows its name as a text wordmark (`chat-header__title--wordmark`). Alt text is the title. The tab title is `<agent> — <product>` when branded and exactly `<agent> — EDDI Chat` / `EDDI Chat` when not.
* **Accent, and the old gap.** `ChatConfig.accentColor` was stored but never applied. It now goes through `applyAccentColor`, the same function `?accentColor=` uses (accent, user bubble, focus ring, the `color-mix` tints). One effect applies `config.accentColor` and then the URL's colour parameters, so `?accentColor=` beats the embedder and the brand, and `?userBg=` still beats the bubble colour an accent derives. `defaultConfig` no longer carries `accentColor: "#113B92"` or the logo URL: unset means "the stylesheet's tokens" and "the brand's logo", so setting either is always an override and an unbranded widget paints exactly as before.
* **Demo route.** `ChatRoute` wraps the `/chat/:environment/:agentId[/:userId]` routes; under a brand `/chat/demo/showcase` shows a neutral "The demo is not available on this site." (`demo.unavailable`, all four locales) instead of EDDI's showcase script, and makes no request.
* **Head.** `chat.html` already had the placeholders, `/branding/favicon.ico` and `/branding/og-image` from Phase 1. The dev entry `index.html` now has the same brand wiring (placeholders, `brand.css`, `__brand__.js`), the plugin knows its defaults, and `vite-plugin-brand.test.ts` grades both shells. `vite-proxy.test.ts` exempts `/branding`, which the dev plugin serves itself.
* **Guard.** `src/no-eddi-brand-literal.test.ts` fails on `\bEDDI\b` in a locale value, a string literal or JSX text outside an exact allow-list (the unbranded defaults and one integrator console warning) and `demo-api.ts`. It caught the old tab-title template when mutated back in.

### Design decisions

* **The accent is applied in JS, not only by `brand.css`.** `brand.css` sets `--chat-accent` alone, so the user bubbles, focus ring and quick replies stayed EDDI blue. The JS path sets the full set the URL parameter sets, as inline styles that beat both stylesheets. Both read the same resolved value (chat accent, else primary), so they never disagree; `brand.css` stays for the first paint.
* **The demo route is refused in the client, not with a backend 404.** The Chat shell is one SPA page; a 404 would need a route-aware resource for one path. The neutral state shows nothing of EDDI either way.
* **The "Chat" suffix was not made translatable.** Branded titles no longer carry it, and the unbranded title stays byte-identical.

### Verified

In `ui/chat` on Node 24: `npm run typecheck`, `npm run lint` and the full `npm test` — 32 files, 531 tests, green. New: `brand.test.ts` (defaults = plugin script, normalisation, title/logo/tab-title/config layer), `ChatWidget.brand.test.tsx` (12 tests: unbranded unchanged, branded logo and alt, text wordmark, tab title, `?title=` and `logoUrl` still override, brand accent, `?accentColor=` beats the brand, `config.accentColor` beats the brand and an unsafe one is ignored, `?userBg=` beats the derived bubble colour, demo route branded and unbranded) and the guard. Mutation checks: the old `ChatHeader` fails the guard and two header tests; dropping `applyAccentColor(config.accentColor)` fails three accent tests; disabling the demo guard fails the demo test. Backend: `BrandDeliveryTest,BrandedShellRendererTest,RestHtmlChatResourceTest,ChangelogFragmentTest,Documentation*Test,BuildQualityGatesTest,ImportStyleTest` — 93 tests, green. Against a real backend (full `./mvnw package`, the jar on MongoDB 7, an agent with no workflows deployed): unbranded, the demo and a chat look as before (EDDI logo, `EDDI Chat`, no inline accent); with a name and teal colours, the header shows "Zebra Labs" as text, the user bubble and focus ring are teal, the tab title is the product name and the demo shows the notice; after an SVG logo upload the header shows `/branding/logo?r=2` with alt "Zebra Labs", and the head carries the brand's description, `theme-color`, favicon and `og:image`; `?accentColor=%23cc3366&title=Support%20Desk` turns the bubble pink and titles the tab "Support Desk" under the brand; after a reset everything is EDDI again.

### What's next

Phase 6 (Platform Operator, Keycloak theme download) and Phase 7 (brand-leak E2E). The per-agent appearance seam (`agentAppearanceLayer`) needs its own design pass (§4.6). Noticed, not changed: `chat.html` lacks the `viewport-fit=cover, interactive-widget=resizes-content` viewport the dev `index.html` got in #1075, so production phones do not get that fix.

***

## 🎨 feat(branding): operator persona, API surfaces, Keycloak theme download and Helm values — white-label phase 6 (2026-10-25)

**Repo:** EDDI (`feat/white-label-6-chat-operator-surfaces`)

### What changed and why

Phase 6 of the [white-labeling plan](https://github.com/labsai/EDDI/tree/main/planning/white-label-ui-plan.md) (§4.7–4.9, R6, R7, R9). [`docs/white-labeling.md`](https://docs.labs.ai/deployment-and-infrastructure/white-labeling.md) gains "The Platform Operator", "API surfaces", "The Keycloak login page" and "Helm"; [`docs/kubernetes.md`](https://docs.labs.ai/deployment-and-infrastructure/kubernetes.md#white-labeling-helm) and the [configuration reference](https://docs.labs.ai/deployment-and-infrastructure/configuration-reference.md#white-labeling) point at them.

* **Platform Operator** (`ui/manager/src/lib/operator/system-prompt.ts`, revision **38**). The preamble now opens "You are the Platform Operator" and carries the one sentence that still names the engine ("built on the EDDI engine; its documentation and `eddi.*` configuration properties use that name"); every other mention says "this deployment", "the platform" or "the engine". The default body is brand-independent, so a rebrand never flips an untouched body to "customized", and the revision fingerprint hashes the preamble with the EDDI default name. The body tells the operator that Admin → Branding exists, what it controls, that it has no tool for it and that its own name changes on Upgrade; the docs map gains "white-labeling". Braces are dropped from the name in the prompt (it is a Qute template server-side and the validator allows `{}`). New operators are named `operatorAgentName()` = `<product> Platform Operator`. The branding endpoints stay off the allow-list; `tool-scopes.ts` documents the exclusion and a test keeps any `/branding` path out of both scopes. `use-current-screen-context.ts` gains `/manage/branding` → `branding`. The operator's user-facing errors say "this deployment" / "the server" instead of EDDI.
* **Identification audit.** Activation, supersede, upgrade, trust (`useOperatorTrust`) and discovery read the `[eddi-platform-operator]` descriptor marker or the configured agent id; the only name read is discovery's fallback for pre-marker operators (`/operator/i`), which every built name satisfies. A new test proves a marked operator named "Acme Assist Helper" is still recognised; requiring a name match fails it.
* **Guard.** `no-eddi-brand-literal.test.ts` loses its Phase-6 exclusions and now also grades `new Error("…")` messages.
* **Manager, other.** The A2A card preview on the agent page uses the product name. The two generated LLM-parameter notes say "the server" (`model-parameters.json`, regenerated into `llm-parameter-catalog.data.ts` and `docs/llm-parameters.md`). On the Branding page an empty colour's swatch shows what it falls back to — dark → light, chat accent → primary, otherwise the unbranded default (`UNBRANDED_COLORS`, pinned to `index.css` and the chat's `variables.css`) — instead of black.
* **A2A** (`AgentCardService`): provider, fallback name and description, default skill and token description use the product name, read per card; an unreadable brand serves the card under EDDI.
* **OpenAPI** (`BrandedOpenApiRoute`): under a brand `info.title` is `<product> API` and the LABS.AI contact is dropped; unbranded the request falls through to SmallRye's cached document untouched. A first attempt as a `RUNTIME_PER_REQUEST` `OASFilter` passed its unit tests and did nothing at runtime: SmallRye's `OpenApiDocument.initialize` runs `filterModel` and then `ConfigUtil.applyConfig`, so the `info-*` properties overwrite whatever a filter set. Found only against the real jar.
* **Swagger UI** (`BrandedSwaggerUiRoute` + `SwaggerUiBranding`, R6 spike → implemented). Swagger UI requests `index.html`, `logo.png`, `favicon.ico` and `style.css` relative to `/q/swagger-ui/`; Quarkus serves them from generated web-jar resources (`META-INF/io.smallrye_smallrye-open-api-ui__jar/META-INF/resources/openapi-ui/`). A Vert.x route at the shell route's order answers those four while a brand is set: title and alt from the product, no footer, the brand's logo (or its name as text), its favicon/icon, and the stylesheet with amber accents swapped per mode (the PUT method colour stays). Unbranded, and under `quarkus:dev` where the files are not on the classpath, it falls through.
* **MCP** (`BrandedMcpServerInfo implements InitialResponseInfo`): `serverInfo.name`/`title` are the product name under a brand, asked per `initialize`; an explicit `quarkus.mcp.server.server-info.name` wins.
* **Keycloak theme ZIP** (`KeycloakThemeExport`, `GET /administration/branding/keycloak-theme.zip`, `eddi-admin`). `pom.xml` copies `keycloak/themes/eddi` to `keycloak-theme/eddi` on the classpath (outside `META-INF/resources`). The ZIP is the theme renamed `brand`: the shipped files byte for byte, `theme.properties` loading `css/brand-overrides.css` last, the generated overrides (the `--eddi-*` palette per mode plus both PF5 tiers, F18; warnings stay amber; text heading when there is no logo), the brand's logo / dark logo / ICO-or-PNG favicon, and a README with `loginTheme`, `displayName` and HTML-escaped `displayNameHtml` as JSON. Fixed file list (a test pins it to the directory), fixed entry times, colours re-validated on output, the name only in the README. Branding page: "Download login theme" (all 11 locales), MSW handler, `openapi-operations.json`.
* **Helm** (chart **2.13.0**, `EXPECTED_CHART_VERSION`): `eddi.branding.*` values (names, colours, `poweredBy`/`showUpdateCheck`, `locked`, `assets.configMap` + `mountPath`) render `EDDI_BRANDING_*` only when set and mount the ConfigMap read-only as `assets-dir`. Off by default. `HelmBrandingValuesTest` pins the mapping.

### Design decisions

* **Neutral wording over i18n for the operator's errors.** They are thrown `Error` messages shown verbatim; "this deployment" / "the server" removes the leak without a second translation path for one screen.
* **The operator's persona lives in the non-editable preamble.** The body stays brand-free, so "is the body the default?" keeps working across a rebrand, and the persona is rebuilt on every Upgrade/Reconfigure.
* **OpenAPI as a response rewrite, not a filter or a property change.** Moving the title and contact from properties to `@OpenAPIDefinition` was tried so a filter would win; Quarkus then defaults the title to `quarkus.application.name` + " API" ("eddi API") and dropped the annotation contact, changing the unbranded document. The route keeps the unbranded document byte-identical and cached, and costs one parse and serialisation per `/openapi` fetch only while branded.
* **Swagger's page is derived from the generated file** rather than re-implemented, so a Quarkus upgrade that changes the page keeps working (the rewrites are regex replacements that leave a non-matching page as it was).
* **The Keycloak favicon is replaced only by an ICO or PNG**, because Keycloak links `favicon.ico` by name; an SVG icon keeps the shipped one and the README says so.
* **No Keycloak theme mount in the Helm chart.** Its in-cluster Keycloak mounts no themes today; documented instead of adding a second ConfigMap layout. `install.sh` / `docker-compose.auth.yml` are documented, not changed.
* Outbound `User-Agent` and logs keep EDDI, as decided.

### Verified

* **Manager** (Node 24): `npm run typecheck`, `npm run lint`, `npm run i18n:check` green; the full Vitest suite 624 files / 8973 tests green. Mutation checks: requiring a name match next to the marker in `operator-discovery.ts` fails the new discovery test; putting "EDDI" back into an operator error fails the brand guard.
* **Backend:** the full `./mvnw test` ran 29,948 tests with 42 failures and 134 errors, all of them `Unable to establish loopback connection` / `failed to create a child event loop` in the HTTP-client, LLM-builder, A2A-client and MCP-client tests (the known long-session environment fault), none in a branding, A2A-card, Swagger, Helm or guard class. The repo-wide guards (`ImportStyleTest`, `BuildQualityGatesTest`, `Documentation*Test`, `ChangelogFragmentTest`, `DocumentedRestPathsTest`, `HttpMetricsUriTagsConfigTest`, `SkillToolReferencesTest`) and the new and changed classes pass on their own. Mutation checks: writing an unvalidated colour fails `KeycloakThemeExportTest`; dropping the comment strip fails `SwaggerUiBrandingTest`.
* **Helm:** `helm lint` and `helm template` (alpine/helm 3.16.3) render the default with no `EDDI_BRANDING_*` and no branding volume, and a branded values set with the env vars and the read-only mount.
* **Real jar** (full `./mvnw package`, MongoDB 7). Unbranded: `/openapi` equals the Phase-5 jar's document except the new path, and `/q/swagger-ui/`, `style.css` and `logo.png` are byte-identical. With "Zebra Labs", teal colours, an SVG logo and a PNG favicon: `/openapi`, `/openapi.json`, `?format=JSON` and `/openapi.yaml` say "Zebra Labs API" with no contact; Swagger UI shows the title, the logo, no footer, the favicon and teal accents (PUT stays amber); MCP `initialize` answers `serverInfo` "Zebra Labs"; an A2A-enabled agent's card names Zebra Labs as provider, name, description and skill; the theme ZIP holds the 10 shipped files, the overrides, the logo, the PNG favicon and the README. Keycloak 26.8.0 with the ZIP mounted and a realm using `loginTheme: brand` shows the Zebra logo, teal button, focus ring and bloom, in dark and light.
* **Found, not changed:** on Keycloak 26.8 the card header gets a 4 px blue top border from keycloak.v2's new `--keycloak-card-top-color`, which `eddi-login.css` (written against 26.0) does not set. Nothing in the shipped theme sets it either, so the unbranded theme is affected the same way (read from the stylesheets, not screenshotted); it belongs to a theme fix, not the brand.

### What's next

Phase 7: the brand-leak E2E. Notes for it: Swagger UI is branded only in a packaged build; the operator's name changes only after Upgrade, so an E2E that rebrands an existing operator should expect the old name until then; A2A discovery lags a rebrand by up to \~60 s (brand + roster caches); the Keycloak login page is branded only once the downloaded theme is installed.

***

## feat(alerts): masked webhook URLs, protected system schedule, OUTPUT\_MATCH rules and e2e specs (2026-10-25)

**Repo:** EDDI (`feat/conversation-ratings`) — review fixes to PR 5a and PR 5b of [`planning/conversation-rating-plan.md`](https://github.com/labsai/EDDI/tree/main/planning/conversation-rating-plan.md) (§0.2)

### What changed and why

**Webhook URLs are treated as secrets.** A webhook URL often carries its own token, so no read returns it any more, for administrators either: REST (list, single read, create/update responses), MCP and the operator see `https://host/***` plus `urlConfigured: true` ([`DeliveryTarget.masked()`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/alerts/model/DeliveryTarget.java), applied in `AlertAccess.redact`). On update an omitted or masked URL keeps the stored one (`RestAlertRules.restoreUrls`, matched by position and host, else the only stored webhook on that host); a new value replaces it; a masked URL in a create is refused. A `${vault:…}` reference is accepted as the URL itself and resolved only at send time (`AlertSenders`); unresolvable, or not http(s), means no delivery — the rule the signing secret already followed. "Send test alert" for a saved rule restores the stored URL server-side and requires write access to that rule. The Manager editor shows the masked URL with a "kept unless you replace it" hint.

**The `alerts-maintenance` schedule cannot be changed through the schedule surfaces.** `RestScheduleStore` answers 409 `{"error":"SYSTEM_SCHEDULE"}` to update, delete, enable, disable, retry and dismiss of a schedule carrying the system `alertType`; MCP `delete_schedule` refuses with `errorCode: SYSTEM_SCHEDULE`. Self-healing on startup and rule save stays as the backstop. The Manager's schedule list marks it system-managed with no edit, toggle or delete.

**`OUTPUT_MATCH` (§0.2).** A rule can now fire on what a clean turn produced:

* [`OutputMatcher`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/alerts/OutputMatcher.java) — paths `properties.<a.b>`, `output.json.<a.b.c>` (the agent's output parsed only when it starts with `{`/`[`, at most 64 KB, Jackson nesting capped) and `actions`; depth ≤ 8, segments `[A-Za-z0-9_-]`, no wildcards or indexes; ops `exists|eq|neq|in|gt|gte|lt|lte|contains`, comparisons type-strict (numbers by value, a string never equals a number). The value is the author's constant: no expression engine, no template evaluation of runtime data.
* Save-time validation (`AlertRuleValidator` → `OutputMatcher.problems`): path grammar, op/value fit, `in` list 1–50 scalars, constants ≤ 1000 characters, `actions` only with `contains`/`exists`, and no field of another source.
* [`OutputMatchHook`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/alerts/OutputMatchHook.java) runs from `ConversationStepRunner` for a turn that completed cleanly (not failed, not timed out, not paused for a human). On the turn thread it does one `getIfPresent` on `AlertRuleCache.cachedOutputNeeds`; an agent without enabled `OUTPUT_MATCH` rules stops there. Otherwise it copies only what the rules read — the named top-level properties (detached copies), the output text, the action list — into a `TurnSnapshot` and hands it to the alert worker; the live memory never leaves the turn. A cache miss loads the needs on the worker and that one turn copies all three.
* `includeValue` is honoured only when the agent version has conversation review enabled (`ConversationReviewPolicy`); the value goes to `match.value`, cut to 280 characters. Otherwise the alert names path, operator and constant only.
* Manager: condition builder ([`output-match-builder.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/components/alerts/output-match-builder.tsx)) — path source dropdown, path input with inline validation, value type, operator filtered by type, value, and an includeValue toggle explaining the review requirement; `pathProblem`/`outputMatchProblems` in [`alert-rules.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/alert-rules.ts) mirror the server. 30 keys in all 11 locales; MSW fixture masks its webhook.
* Operator prompt: masked URLs, the system schedule and `OUTPUT_MATCH`; revision 38 → 40.
* Docs: [Alerts](https://docs.labs.ai/conversations-and-orchestration/alerts.md#matching-a-turns-result) with the three §0.2 examples, masking, the system schedule.

**E2E specs.** `ui/manager/e2e/alerts.spec.ts` (MSW tier: inbox acknowledge, create rule, output-match builder, badge) and `e2e/fullstack/ratings-feedback.fullstack.spec.ts` (Chat UI rating → Feedback "Needs attention" + badge → mark reviewed → count back). Not run locally — Playwright browsers were not downloaded on purpose; CI runs them.

### Design decisions

* **A masked URL is restored by position and host, never by position alone.** A reordered target list still gets the right URL back when its host is unique among the stored webhooks; when it is not and the position does not match, nothing is restored and the masked URL is refused at validation rather than guessed.
* **Only top-level property names are copied**, even for a nested path: the snapshot copies the property's value detached (`AlertJson`), so a later change to live memory cannot reach the worker.
* **A cache miss copies everything once** instead of loading rules on the turn thread: the turn never waits on the store, and the first turn after a restart is not lost.

### Tests

* **Review fixes:** `RestAlertRulesTest.WebhookUrls` (list, single read, create/update response, restore by position and host, masked create refused, test send restores and needs write access), `AlertSendersTest` (vault URL resolved at send, unresolved → no delivery, labels), `RestScheduleStoreExpandedTest` and `McpAdminToolsBranchCoverageTest` (system schedule refused). Mutation check: 9 of 9 mutants killed (redaction, create and update responses, `masked()`, the label, `restoreUrls`, unresolved vault URL, the REST and the MCP system-schedule guards).
* **OUTPUT\_MATCH:** `OutputMatcherTest` (paths, JSON-only parsing, size and nesting caps, type-strict operators, grammar and op/value validation), `OutputMatchHookTest` (an agent without rules costs one cache lookup and touches nothing else — `verifyNoMoreInteractions` on memory and cache, nothing queued; only needed values copied, detached; cache miss copies everything; `includeValue` needs review; 280-character cut), `AlertRuleValidatorTest`, `ConversationStepRunnerTurnOutcomeTest` (only clean turns reach the hook), `AlertStoreContract.outputMatchRuleRoundTrips` (ITs 28/28, 14 MongoDB + 14 PostgreSQL). Mutation check: 6 of 6 killed — value without review, hook working for agents without rules, wildcard grammar, no truncation, type-mismatched equality, whole property map copied.
* **Manager:** `alert-rules.test.ts` (path grammar, ops per type, problems), `alerts.test.tsx` (builder, inline path error, actions ops, masked URL hint), `schedules-regressions.test.tsx` (alerts-maintenance has no edit, toggle or delete); operator tests for revision 40.
* **Live check** (dev mode on MongoDB 7 in Docker): an agent with `ratingConfig` and conversation review rated over REST (conversation + reply), `/ratings`, `/ratings/summary`, `/ratings/attention-count`, `PATCH /ratings/{id}` (count 2 → 1); a RATING rule with inbox-only delivery produced exactly one event when a 5-star rating was re-rated to 1, and a second low re-rating in the same window counted as `duplicates: 1`; acknowledged. An OUTPUT\_MATCH rule on `actions contains handoff_requested` fired once over two turns with `match.value` present (review on). An agent whose LLM points at `127.0.0.1:9` produced one CONVERSATION\_ERROR event (`TURN_ERROR`). A webhook rule read back as `https://hooks.example.com/***` everywhere while MongoDB kept the full URL across a PUT that sent the masked value; its delivery stayed PENDING with "signing secret could not be resolved"; `DELETE` and `disable` on `alerts-maintenance` returned 409 `SYSTEM_SCHEDULE`.
* **Full runs:** backend `./mvnw test` 29,924 run, 3 failures, 8 skipped. Two failures (`PostgresIngestionStateStoreTest.recordedDeadlineGoverns`, `PostgresSecretPersistenceTest.timestampsRoundTrip`) are off by exactly one hour because the run fell in the night the clocks went back (Europe, 2026-10-25); both pass with the JVM in UTC (77/77) and neither class is touched here. The third is the known-flaky `DocumentExtractorsTest.honoursItsTimeBudget`. Manager vitest: 622 files, 8,961 tests passed; `npm run lint`, `npm run typecheck` and `npm run i18n:check` (6,333 keys) clean.

***

## ✨ feat(mail): EDDI verifies DKIM and DMARC alignment itself — email sender authentication (2026-10-25)

**Repo:** EDDI (`feat/email-dkim`, on top of `feat/email-hitl-notifications` and `feat/email-mail-core`)

The sender-authentication slice of [the email plan](https://github.com/labsai/EDDI/tree/main/planning/email-channel-plan.md) (§8, the DKIM/DMARC part of §21), built ahead of Phase 2 so the IMAP poller can call it. No channel, transport or poller is part of this change.

### The facade Phase 2 calls

* **`SenderAuthenticator.authenticate(byte[] raw, InboundMail parsed)`** (`engine/mail`, `@ApplicationScoped`) → `MailAuthentication`: verdict `ALIGNED_PASS` · `PASS_UNALIGNED` · `FAIL` · `NONE`, the signing domain, a fixed-text reason (safe to log), a `temporary` flag (a DNS failure or the lookup budget kept a check from running — retrying later may authenticate), and one `DkimResult` per evaluated signature (domain, selector, algorithm, `PASS` · `FAIL` · `TEMPERROR` · `TESTING`, reason). The caller passes the bytes it received and the parser's `InboundMail` of those bytes (a size mismatch is refused), then attaches the verdict with `InboundMail.withAuthentication`. Never throws.
* **Only an aligned pass authenticates**, and never when the message has anything but exactly one `From` field with one mailbox (counted on the raw bytes and from the parser's `MULTIPLE_FROM`/`MISSING_FROM`) or a duplicated singleton header (`DUPLICATE_SINGLETON_HEADER`): an unsigned second `From` or `Subject` added above a validly signed one is not hashed, so the signature still verifies, while clients show the forged one.
* `MailAuthentication` gains `reason`, `temporary` and `signatures` (the two-argument constructor stays).
* **Judged as of delivery:** `authenticate(raw, parsed, Instant deliveredAt, fallback)` evaluates `x=` and the future-`t=` check at the delivery instant — the transport passes the mailbox server's `INTERNALDATE`, the receiving server's own clock, never a sender header — so a short `x=` does not expire while the mail waits for the poller or the cost budget. The instant is clamped to `[now − eddi.email.dkim.max-delivery-age, now]` (new property, default `7d`): a later value is now, an older one is the cap boundary, so a broken or forged value can neither revive an ancient signature nor postdate one. Without it, signatures are judged at the current time, as before. `DkimVerifier.verify(raw, budget, evaluatedAt)` takes the instant unclamped.
* **Provider fallback**: `authenticate(raw, parsed, SignedProviderVerdict)`, an interface for a verdict delivered under a signature the transport checked (SES over SNS). Consulted only when the local check could not run (no raw bytes, or every key lookup failed temporarily); never over a local fail, none or pass; alignment is still EDDI's. No provider is implemented.

### DKIM (`DkimVerifier`)

* RFC 6376 on the raw bytes: `simple`/`relaxed` header and body canonicalisation in all four combinations, `rsa-sha256` (1024–8192-bit keys, exponent ≤ 64 bits; SPKI or bare PKCS#1 `p=`) and `ed25519-sha256` (RFC 8463, the JDK's EdDSA). Refused as `FAIL`: `rsa-sha1` (RFC 8301) and other algorithms, `l=` (body-extension attack), a signature not covering `From`, `i=` outside `d=`, expired `x=`, `x=` before `t=`, `t=` in the future (5 min skew), revoked (`p=` empty) or missing keys, more than one key record, `k=`/`h=`/`s=` that do not admit the signature, `t=s` with `i=` ≠ `d=`, malformed or duplicated tags. A `t=y` key gives `TESTING`, not a pass.
* Bottom-up header-instance selection with over-signing semantics (a name in `h=` more often than present binds the absence); the signature being verified is never one of its own `h=` instances. Bare-LF input is converted to CRLF.
* Bounds: 5 signatures evaluated (rest counted), 256 KB header block, 100 `h=` names, 8 KB signature field, one body hash per canonicalisation, the body checked before the key is fetched (a tampered mail spends no lookup).

### DMARC alignment (`DmarcAlignment`) and the Public Suffix List

* RFC 7489 §3.1.1: relaxed (same organisational domain) or strict (equal) per the `From` domain's `_dmarc` `adkim=`, falling back to the organisational domain's record (§6.6.3); no record = relaxed; several `v=DMARC1` records = no DMARC; a temporary lookup failure assumes strict and is flagged. `p=` is not applied. **SPF is not evaluated** (EDDI never sees the connecting IP).
* **`PublicSuffixList`**: the upstream file bundled unmodified as `src/main/resources/mail/public_suffix_list.dat` (MPL-2.0, new `licenses/MPL-2.0.txt`; commit `8437e5262f13`, 2026-10-22), ICANN and private sections, wildcard and exception rules, IDN rules in ASCII. `public_suffix_list.properties` records commit and SHA-256; `PublicSuffixListTest` fails when the file is missing, small, or differs from that hash. Refresh with the new `scripts/update-public-suffix-list.py`. The `.dat` is `-text` in `.gitattributes` so its hash is stable.

### DNS (`MailDnsResolver`, `DnsjavaTxtSource`)

* **dnsjava 3.6.5** (BSD-3-Clause; runtime dependency slf4j-api only, BOM-managed; CVE-2024-25638 and the KeyTrap advisories fixed in 3.6.0 and confined to the DNSSEC validator, which is not used). Its jar registers a `java.net.spi.InetAddressResolverProvider` that stays inert unless `org.dnsjava.spi.enable=true` — documented in `pom.xml` and `security.md`, with a test that fails if the switch's constant disappears.
* New properties `eddi.email.dns.servers` (empty = system resolvers), `.timeout` (5 s, one retry), `.cache-max-entries` (10000), `.cache-max-ttl` (1 h; record TTLs and the SOA minimum for negative answers honoured, temporary failures not cached), `.max-lookups-per-message` (10; cache hits free). Records over 4096 characters or answers over 10 records are refused; multi-string TXT records are joined. No DNSSEC requirement. The `TxtSource` seam keeps every test offline.

### Metrics, docs

* `eddi.email.auth{result}` and `eddi.email.dns.lookups{result,cached}`: two panels in the Full Metrics dashboard's Integrations row (k8s copy re-synced), described in [`metrics.md`](https://docs.labs.ai/deployment-and-infrastructure/metrics.md).
* [`security.md` → Mail Sender Authentication](https://docs.labs.ai/security-and-compliance/security.md#mail-sender-authentication--dkim-and-dmarc): the rules, what an aligned pass proves and does not (the domain, not the person; forwarded and list mail; no ARC; no SPF), the PSL refresh and the dnsjava resolver switch. [`configuration-reference.md` → Email](https://docs.labs.ai/deployment-and-infrastructure/configuration-reference.md#email) lists the six properties. [`compliance-data-flow.md` → Other outbound recipients](https://docs.labs.ai/security-and-compliance/compliance-data-flow.md#other-outbound-recipients): the DNS resolver learns the signing domains, selectors and `From` domains of received mail.

### Tests

* `DkimVerifierTest` (60): the RFC 8463 Appendix A message and key records stored as fixtures (`src/test/resources/mail/dkim/`, byte exact) — both signatures pass, also with LF endings; body, header, second-`From` tampering and re-folding. The RFC 6376 §3.4.6 canonicalisation example, signed over the canonical text the RFC prints. Self-signed RSA-2048 and Ed25519 messages (`DkimTestSigner`, a regex-based signer written independently of the verifier) in all canonicalisations, with folded headers, trailing whitespace, 8-bit text, empty and header-only bodies; every refusal above; DNS outcomes; bounds.
* `SenderAuthenticatorTest` (31): verdicts, DMARC through the facade (subdomain relaxed/strict, org-domain fallback, `d=co.uk`, DMARC tempfail), header injection (second `From`, two mailboxes, no `From`, second `Subject`, mismatched bytes, and each of the two From guards on its own against a parser that disagrees), judging as of delivery (expired since delivery passes; a delivery instant older than the cap or in the future is clamped), provider fallback, 300 random inputs, and a hostile message (5000 header lines, 50 signatures × 100 `h=` names, 10 MB body) within a 5 s budget.
* `DmarcAlignmentTest` (9), `PublicSuffixListTest` (24), `MailDnsResolverTest` (13; three run dnsjava against a loopback UDP server built in the test).
* Every verdict path was mutation-checked: the check reverted, a test failed, the check restored.

### For Phase 2

* Call `authenticate` with the transport's bytes right after parsing; keep `temporary` in mind (leave the message for the next poll rather than treating a DNS outage as an unauthenticated sender).
* Pass the mailbox server's `INTERNALDATE` as `deliveredAt`; without it, `x=` is judged at processing time.
* `eddi.email.auth` carries only `result`. Prometheus requires one tag set per meter name, so per-integration tags mean moving the counter to the channel layer rather than adding tags here.
* No real-world signed mail (Gmail, Outlook.com, Exchange Online, a list) is in the corpus yet (§21); add it with its DNS records when a test mailbox is available.

***

## fix(manager): https-only webhook check, bulk-acknowledge mock, operator revision 41 (2026-10-25)

**Repo:** EDDI (`feat/alerts-manager`, PR #1139) — the Manager side of the alerts backend review fixes (PR #1138)

### What changed and why

* **Rule editor:** `ruleProblems` ([`alert-rules.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/alert-rules.ts)) accepts only an `https://` webhook URL or a `${vault:…}` reference, as the server now requires; the masked `https://host/***` of a stored URL still passes.
* **MSW:** the bulk-acknowledge handler answers 400 `INVALID_PARAMETER` to an empty `ids` list or an empty entry, as the server does; the Manager sends `{}` when it acknowledges by filter and a non-empty list otherwise, so its calls are unchanged.
* **Platform Operator:** the prompt says webhooks must be https and corrects "no conversation text" — a rating comment, or an `OUTPUT_MATCH` value with `includeValue` and conversation review on, can appear, each at most 280 characters. Revision 40 → 41.

### Review follow-ups

* `AlertDeliveryService` derives the send claim lease as the longer of 30 s and three times `eddi.alerts.webhook-timeout`, and `AlertSettings` keeps that timeout between 1 s and 60 s, so a long timeout can no longer make every send skip.
* Manager: test-result rows in the rule editor have unique keys; removing a chat rating clears its reasons and comment; the chat hook reads a conversation's own rating controls even when the current profile is null; the feedback list steps back to the last existing page when triage empties the current one.

### Tests

`npm run typecheck`, eslint on the changed files and `npm run i18n:check` pass; the alert and operator suites (19 files, 530 tests) pass.

***

## fix(manager): second round of alerts review findings — throttle bounds, bulk-acknowledge body, inbox paging (2026-10-25)

**Repo:** EDDI (`feat/alerts-manager`, PR #1139)

### What changed and why

* **Throttle checked before saving:** `throttleProblems` in [`alert-rules.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/alert-rules.ts) uses `AlertRuleValidator`'s bounds exactly (whole numbers, 1–1440 minutes, 1–1000 per window); `ruleProblems` reports `throttle`, which disables Save and Send test, and the editor marks the field with an inline error (`alerts.throttleRange`, all 11 locales).
* **Bulk acknowledge body:** `acknowledgeAlertEvents` sends `{}` only for `null`/`undefined` and `{ ids }` otherwise, so an empty list reaches the server, which refuses it, instead of being widened to everything matching. The page's only "all matching" caller passes `null`.
* **Inbox:** keyed on the agent, so changing it starts from page 1 with nothing selected; the page moves back to the last one that exists when acknowledging empties the one it is on (instead of "No open alerts"); the selection clears when the source or the acknowledged filter changes.
* **Schedules:** a dead-lettered server-owned schedule (`alerts-maintenance`) gets no Retry on its row and no Retry/Dismiss in Failed fires — the server answers 409 `SYSTEM_SCHEDULE` to both.
* **Output-match builder:** switching the path source to `actions` turns the value into text (contains compares strings) and keeps `exists` without one.
* **Full-stack e2e spec:** each resource is recorded as soon as it exists, and cleanup removes every recorded one even when setup failed midway.

### Tests

New: `output-match-builder.test.tsx` (5), `lib/api/__tests__/alerts.test.ts` (3), throttle cases in `alert-rules.test.ts`, four page tests in `alerts.test.tsx` (throttle error, page clamp, selection reset on filters, fresh inbox on agent change) and the server-owned case in `schedules-regressions.test.tsx`. The alerts, schedules, operator, mocks and i18n suites: 34 files, 770 tests. Mutation check: 10 of 10 mutants killed (throttle not reported, window bound off by one, fractions accepted, empty ids widened, no page clamp, selection kept on either filter, Inbox not keyed on the agent, row Retry and Failed-fires actions for a server-owned schedule). The Playwright spec is typechecked and linted, not run.

***

## fix(manager): carry each webhook target's targetId through the rule editor (2026-10-25)

**Repo:** EDDI (`feat/alerts-manager`, PR #1139) — the Manager side of the backend's `targetId` restore (PR #1138)

### What changed and why

* **Types:** `DeliveryTarget.targetId` in [`lib/api/alerts.ts`](https://github.com/labsai/EDDI/tree/main/ui/packages/app-kit/src/lib/api/alerts.ts), documented as the server's id to send back unchanged.
* **Editor** ([`alert-rule-editor.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/components/alerts/alert-rule-editor.tsx)): targets are edited, removed and — new — moved up or down as whole objects, so each keeps its own `targetId`; rows are keyed by it. A new target has none. Save and Send test send the ids as loaded. Two new strings (`alerts.moveTargetUp`, `alerts.moveTargetDown`) in all 11 locales.
* **Validation:** `ruleProblems` accepts a masked URL only together with a `targetId`, so a masked URL is never sent without one.
* **MSW** ([`alert-handlers.ts`](https://github.com/labsai/EDDI/tree/main/ui/packages/app-kit/src/test/mocks/alert-handlers.ts)) now mirrors the server: it stores full URLs and answers reads masked, assigns ids on create (replacing client ones), restores a masked or empty URL on update and test send only from the stored target with the same `targetId`, and refuses one without a known id with 400 `INVALID_RULE`.
* **Platform Operator:** the masked-URL paragraph explains `targetId` and the `INVALID_RULE` refusal. Revision 41 → 42; it ships as **43**, because merging main (where the ratings work had moved the operator to 39) needed a revision above both.

### Tests

New page tests (`alerts.test.tsx`): removing one of two masked same-host webhooks sends the other with its own id, reordering moves ids with their targets, editing a masked target's secret keeps its id, a new target goes without one, a test send of a saved rule sends the ids, and saving the stored webhook rule round-trips through the mock. `alert-handlers.test.ts` (4) pins the mock's contract; `alert-rules.test.ts` covers the masked-URL check. `npm run typecheck`, the full `npm run lint` and `npm run i18n:check` (6,336 keys) pass; the alerts page, alert components, `src/lib` (operator included), `src/test/mocks` (OpenAPI contract included), schedules and i18n suites: 143 files, 2,518 tests. Mutation check: 5 of 5 killed (edit drops the id, removal re-pairs ids by position, reorder leaves ids behind, masked URL accepted without an id, mock restoring without matching the id).

***

## fix(alerts): review findings on the alerts backend — https-only webhooks, GDPR export, digest healing, bulk acknowledge (2026-10-25)

**Repo:** EDDI (`feat/alerts-backend`, PR #1138; Manager follow-ups on `feat/alerts-manager`, PR #1139)

### What changed and why

* **Webhook URLs must be https.** `AlertRuleValidator` refuses a plain `http` URL at save time; `AlertSenders` checks again at delivery, which is the only place a `${vault:…}` URL is known — one that resolves to `http` (or to no host) is not delivered to. STRICT SSRF and no redirects are unchanged. Docs: [Alerts → Delivery](https://docs.labs.ai/conversations-and-orchestration/alerts.md#delivery).
* **GDPR export** (`AlertGdprParticipant.export` returned `null`): it now lists the rules the person created or last edited (id, name, created/updated time, `author` and/or `lastEditor`) and the events they acknowledged (id, rule name, source, agent, fired and acknowledged time), at most 10,000 of each, and no other person's identity or event content. New store reads `IAlertRuleStore.findByAuthor` and `IAlertEventStore.findAcknowledgedBy`, implemented for MongoDB and PostgreSQL and covered by `AlertStoreContract`. Docs: [Alerts → Privacy](https://docs.labs.ai/conversations-and-orchestration/alerts.md#privacy), [GDPR Compliance](https://docs.labs.ai/security-and-compliance/gdpr-compliance.md).
* **A digest could stay stuck.** When the digest's insert hit its dedupe key — another runner sent it, or this one crashed between the insert and marking the held events — the held events stayed `DIGEST_PENDING` and every pass retried a digest that never inserted. `AlertMaintenanceService.sendDigest` now marks them on a dedupe hit too, still without delivering.
* **`actions exists` fired on every clean turn**: an empty action list is now absent (`OutputMatcher.resolve`); `contains` is unchanged.
* **A cache miss copied the turn even when nothing would run it**: when submitting the output-needs loader fails (alerts off, queue full), `OutputMatchHook` returns before building a snapshot.
* **Bulk acknowledge:** a present `ids` list is the selector. An empty list or an empty entry is a 400 `INVALID_PARAMETER` instead of falling through to "everything matching the filter"; the filter applies only when `ids` is left out. The MCP tool acknowledges one event by id and the Manager sends `{}` when acknowledging by filter, so both stay valid.
* **Wording:** `OUTPUT_MATCH` added to the `source` tag of `eddi_alerts_fired_total` ([Metrics](https://docs.labs.ai/deployment-and-infrastructure/metrics.md#alert-metrics)), to `AlertEventQueryParams.source` and to `list_alert_events`' description and `source` argument. "No conversation text" is corrected wherever it was repeated (REST Javadoc, MCP description, [Alerts](https://docs.labs.ai/conversations-and-orchestration/alerts.md), [MCP Server](https://docs.labs.ai/protocols-and-integration/mcp-server.md), the `eddi-admin` skill): a rating comment and, only with `includeValue` and conversation review on, an `OUTPUT_MATCH` value appear, each cut to 280 characters.

### Design decisions

* **On a digest dedupe hit every held event is marked**, including any held after the existing digest was written. They stay in the inbox but are not listed in a digest message. The alternative, reading the existing digest to mark only what it covered, needs the event ids on the digest, which it does not store.
* The export re-checks each row against the user id, so a store returning a wider set cannot leak another person's rule or acknowledgement into it.

### Tests

448 unit tests across the alert, output-match, REST, MCP, step-runner and GDPR classes pass, among them the new `AlertGdprParticipantTest`, `RestAlertEventsTest.bulkEmptyIdsRefused`, `AlertMaintenanceServiceTest.digestCrashBetweenInsertAndMark`, `OutputMatchHookTest.cacheMissLoaderRefused`, `OutputMatcherTest.emptyActionsAreAbsent` and `AlertSendersTest.httpsOnly`. Store ITs: 32/32 (16 MongoDB + 16 PostgreSQL, with the two new contract cases). The doc and style guards pass. Mutation check: 9 of 9 mutants killed — http accepted at save, an http vault URL delivered to, an empty export, another person's acknowledgement exported, the lastEditor role lost, a dedupe hit leaving events pending, a refused loader submit still snapshotting, an empty ids list falling back to the filter, a blank id entry accepted.

***

## fix(alerts): erasable output values, queued rating alerts, exact digest recovery, targetId-based URL restore (2026-10-25)

**Repo:** EDDI (`feat/alerts-backend`, PR #1138) — the second round of review findings

### What changed and why

* **OUTPUT\_MATCH values can be erased.** An event that stores a matched value (only with `includeValue` and conversation review on) also records the conversation owner in an internal field, `AlertEvent.subjectUserId`. It is `@JsonIgnore`d, written by both stores and never read back, so no REST row, MCP answer, operator answer, Slack message or webhook payload can carry it (asserted on the serialized row and on both payloads). Events without a stored value never get it. `AlertGdprParticipant.erase` blanks the value and the field (`IAlertEventStore.redactOutputValues`, partial index on both stores); the owner's export lists those values (value, conversation, time) under `outputMatchValues` — their own conversation content, as the ratings export lists their ratings.
* **A rating alert queued across an erasure.** `AlertEngine.evaluateRating` re-reads the rating first and skips it when it is gone or its `updatedAt` changed (the newer save has its own alert). After the event is written it re-reads again; if the rating was erased in between, the event's excerpt is blanked (`redactRatingComment`) before anything is delivered. No per-user lock.
* **Digest recovery marks exactly what the digest covers.** The digest records the held event ids it covers (`digestEventIds`, internal, at most the 500-event batch); on a dedupe hit the maintenance pass reads that digest (`findByDedupeKey`) and marks only those ids, so events held later stay `DIGEST_PENDING` for the next digest.
* **Webhook URLs are restored by `targetId`, never by position or host.** Every delivery target gets a server-assigned `targetId`, kept across updates and returned by every read. An update or test send that sends a masked or empty URL keeps the stored URL of the target with the same `targetId` only; a masked or empty URL without a known id is a 400 `INVALID_RULE`; a new target must bring a real URL; ids the stored rule does not have (and all ids on a create) are replaced. Removing or reordering two masked targets on one host no longer hands one target the other's URL.
* [Alerts → Privacy](https://docs.labs.ai/conversations-and-orchestration/alerts.md#privacy) now says what is stored: the acknowledger's id (shown in the inbox, never sent out) and the internal subject id of a stored output value, both until erasure or retention.

### Design decisions

* **Rules saved before ids existed need no migration.** A target without an id gets `t` + its existing hashed `key()` on every read — the same id each time — so the first update of such a rule matches the ids the client read, and that save stores them. Both stores already persist targets as JSON, so `targetId` is stored without a schema change.
* **The subject id is write-only.** Erasure and the export query by it in the store; no read maps it back into an event, which is a stronger guarantee than hiding it at each serializer.
* **A digest written before covered ids existed** would match nothing on a dedupe hit. Alerts have not shipped, so no such digest exists outside development databases.

### Tests

477 unit tests across the alert, output-match, REST, MCP, step-runner, GDPR and rating classes pass, including the new `AlertPrivacyRaceTest` (both race orderings, the subject recorded only with a value, never serialized or sent) and the `targetId` cases in `RestAlertRulesTest` (remove one of two same-host targets, reorder, new target, unknown id refused, client ids replaced, legacy rule). Store ITs: alert stores 20/20 on MongoDB and on PostgreSQL (new contract cases: erasable subject, covered ids and `findByDedupeKey`, one-event excerpt redaction, persisted `targetId`), rating stores 15/15 on each. Mutation check: 9 of 9 for the erasure, race and digest changes, 5 of 5 for the `targetId` match.

***

## fix(alerts): erasure fence for queued alert work, deliveries send the stored event (2026-10-25)

**Repo:** EDDI (`feat/alerts-backend`, PR #1138) — two more review findings

### What changed and why

* **A queued OUTPUT\_MATCH value could land after an erasure.** [`AlertErasureFence`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/alerts/AlertErasureFence.java) is a `UserErasureParticipant`: the erasure's step 0 (`stopInFlightWork`, and `stopInFlightWorkByHash` on every other node through the existing cluster `gdpr-stop` broadcast, as `ConversationService` and `AuditLedgerService` receive it) records the time the erasure started, per user, keyed by the user id's hash. `TurnSnapshot` now carries its capture time. `AlertEngine.evaluateOutput` stores no value (and no subject) when the snapshot was captured before a live fence — the alert still fires — and after the insert re-checks the fence and blanks value and subject (`redactOutputValues`) before delivery when the fence went up meanwhile. Queued rating alerts use the same fence on top of the re-read: a fenced rating is not evaluated, and an excerpt written while the fence went up is blanked. Fences last 15 minutes (`AlertErasureFence.FENCE_TTL`).
* **A hand-made schedule could pass for `alerts-maintenance`.** The schedule API refused only bodies carrying the alert marker, so a plain schedule named `alerts-maintenance` could be created, and `AlertMaintenanceSchedule.ensure` — which looked the schedule up by name — then took it for the installed one, leaving retries, digests and retention unprocessed. The API now also refuses the reserved name (trimmed, case-insensitive) on create and on a rename (`AlertSchedules.isReservedName`), and `ensure` counts only a row carrying the maintenance marker; a same-named row without it (possible on a deployment from before the name was reserved) triggers a bounded scan for the marked row, and the real schedule is created when none exists. `AlertMaintenanceScheduleTest` and a new `RestScheduleStoreExpandedTest` case cover it; the docs now say a rating alert captured before an erasure is dropped altogether, while an `OUTPUT_MATCH` alert fires without its value.
* **Delivery could send a copy older than the store.** `AlertDeliveryService.deliver` skips an event that no longer exists and reads the event again right before each send, sending the stored (possibly redacted) version — first delivery and every retry, on any node. No cross-node lock: the remaining window is between that read and the send, and a send already on its way cannot be recalled (said in the code and in [Alerts → Privacy](https://docs.labs.ai/conversations-and-orchestration/alerts.md#privacy)).

### Design decisions

* **A dedicated fence bean**, not the dispatcher or the engine: it has one job, both the engine and the cluster handler reach it through CDI, and it keeps the engine free of erasure bookkeeping.
* **The fence only holds back content captured before the erasure started**, so expiry is a matter of memory, not correctness: a later conversation of a reused id is never blocked, and 15 minutes is far longer than the alert queue takes to drain.

### Tests

486 unit tests across the alert, output-match, REST, MCP, step-runner, GDPR, rating and cluster-handler classes pass, including the fence cases in `AlertPrivacyRaceTest` (captured before the fence stores no value, fence up between check and insert blanks before delivery, captured after keeps the value, expiry, set by hash, fenced rating not evaluated) and `AlertDeliveryServiceTest` (first delivery and a retry send the redacted stored version, a deleted event is not sent). Mutation check: 7 of 7 killed.

***

## 🐛 fix(email): HITL email notification review findings (2026-10-25)

**Repo:** EDDI (`feat/email-hitl-notifications`)

Eight review findings on the HITL email notifications ([`docs/hitl.md`](https://docs.labs.ai/conversations-and-orchestration/hitl.md), section "Email notifications").

### What changed and why

* **GDPR erasure keeps the user directory entry when an earlier participant failed** (`GdprComplianceService`). The email ledger finds a person's rows by the address in the user directory, which is why the directory participant runs `LAST`. The loop did not link the two: with the ledger step failing, the directory entry was still erased, so the re-run the result asks for could no longer find those rows and they stayed until ledger retention. A `LAST` participant is now skipped, and reported as failed, when an earlier participant failed (the same reasoning as step 4c, which keeps the snapshots for the retry).
* **A pause on the conversation-start turn is announced only after the descriptor is written** (`ConversationService.startConversation`). A failed descriptor write discards the conversation again, and the asynchronous notifier could already have mailed about it. The say and resume sites already fire after the conversation is final.
* **`eddi.mail.smtp.connection` must match the connection-name grammar** (`SystemMailer.parse`). A name no stored connection can carry (`"my mail"`) used to leave the mailer reported as enabled with every send failing; it now disables the mailer at startup with the reason.
* **The email ledger caps `providerId` (255) and `lastError` (512) on every write, in both stores** (`IEmailMessageLedger.cap`, Mongo and PostgreSQL). Those are the PostgreSQL column widths; an uncapped render error made PostgreSQL refuse the update, which left the row claimed until its lease ran out and retried it after every lease. The cap never splits a surrogate pair.
* **A timeout past the end of the time-line no longer aborts the notification** (`HitlNotificationContent`). A positive duration such as `P1000000000000D` passes config validation but overflows `Instant`; the deadline line now names the duration instead of a date. `HitlEmailNotifier.attempt` also treats any runtime failure while building the mail as a terminal `FAILED` row, instead of letting it escape and leave the row `PENDING`.
* **Manager: Save is refused while the recipients box is invalid** (`HitlConfigSection` reports it through `onValidityChange`, `agent-detail.tsx` refuses every save path, as it does for the spend limit). An invalid list never enters the draft, so an earlier valid edit was saved while the field showed something else. The recipients label is now associated with its textarea, and the hint no longer says the mail carries no conversation content: a tool-call pause lists the pending tools with redacted, shortened arguments (all 11 locales, plus the new `agentDetail.hitlNotifyFixBeforeSave` message).

The operator system prompt already described the content correctly (it names the redacted tool arguments), so it is unchanged.

***

## feat(alerts): alert rules framework — ratings and failed turns to inbox, Slack and signed webhooks (2026-10-24)

**Repo:** EDDI (`feat/conversation-ratings`) — PR 5a of [`planning/conversation-rating-plan.md`](https://github.com/labsai/EDDI/tree/main/planning/conversation-rating-plan.md) (§0.2, §11)

### What changed and why

People running an agent can now be told when something needs them: a low rating or a comment, or a turn that failed, was interrupted, ran past its deadline or was stopped by a cost limit. One mechanism with sources, evaluated outside the pipeline — see [Alerts](https://docs.labs.ai/conversations-and-orchestration/alerts.md), whose top section is the design note.

* **Model and stores** — `AlertRule` and `AlertEvent` ([`engine/alerts`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/alerts/README.md)), MongoDB (`alertrules`, `alertevents`, `alertwindows` with a TTL index) and PostgreSQL (`alert_rules`, `alert_events`, `alert_windows`) twins selected in `DataStoreProducers`. `OUTPUT_MATCH` is not accepted yet; its fields slot into `AlertCondition` and a constant into `AlertSource`.
* **REST** — `/alerts/rules` (CRUD + `POST /alerts/rules/test`) and `/alerts/events` (list, unacknowledged count, read, acknowledge one / bulk, retry), save-time validation (`AlertRuleValidator`, every problem named), coded errors (`AlertErrors`).
* **Hooks** — ratings: a CDI event after the rating is stored (`ConversationRatingSaved`). Turns: `ConversationStepRunner.waitForExecutionFinishOrTimeout`, the one method the say path and the HITL resume path both wait in, now classifies the outcome from in-memory data (ERROR, cancelled / EXECUTION\_INTERRUPTED, watchdog timeout, an `llm:spend_refused:*` record) and fires `TurnOutcome` only for a bad one. `AlertDispatcher` observes both and only enqueues onto one worker with a bounded queue; a full queue drops with `eddi.alerts.dropped` and a rate-limited WARN.
* **Cluster-safe spam control** — the dedupe is a unique index over `ruleId|agentId|conversationId|windowStart`; the per-rule cap an atomic window counter (`$inc` upsert / `INSERT … ON CONFLICT DO UPDATE RETURNING`); delivery updates and claims are conditional on a version (Postgres claims with `FOR UPDATE SKIP LOCKED`); digests mark only events still `DIGEST_PENDING` and carry a dedupe key of their own.
* **Delivery** — Slack through the channel integration that serves the channel (`ChannelTargetRouter` bot token + `SlackWebApiClient`), mrkdwn-escaped; webhooks through `OutboundHttp` (STRICT SSRF, no redirects, timeout, 64 KB body cap, 16 KB answer read) signed `X-Eddi-Signature: t=…,v1=…` with `HmacSignatures` — the scheme EDDI's own inbound webhook channel verifies; the signing secret must be a `${vault:…}` reference and an unresolved one stops the delivery. The inbox always.
* **Retries, digests, retention** — one `alerts-maintenance` system schedule (HEARTBEAT, 60 s) routed by a metadata fast-path in `ScheduleFireExecutor` to `AlertMaintenanceService`, so it runs under the poller's cluster-wide claim and lease. Backoff 30 s × 4ⁿ⁻¹, 5 attempts. An idle pass writes no fire log. User-created schedules claiming `alertType` are refused.
* **Privacy** — no user id and no conversation text anywhere an alert goes; the payload is built field by field (`AlertPayloads`); the rating comment is cut to 280 characters, and GDPR erasure blanks it (`ConversationRatingGdprParticipant` redacts before deleting the ratings) and forgets acknowledgers and rule authors (`AlertGdprParticipant`).
* **Manager** — Alerts page ([`pages/alerts.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/pages/alerts.tsx), `/manage/alerts`, admin + editor): inbox with source / acknowledged filters, per-target delivery status, Retry, acknowledge one / selected / everything here; rules list and editor (source picker, scope, condition, Slack and webhook targets, "Send test alert", throttle and digest, delete with confirmation). Sidebar badge of unacknowledged alerts, administrators only, polled every 30 s. 99 alert keys plus `nav.alerts` in all 11 locales; MSW handlers ([`alert-handlers.ts`](https://github.com/labsai/EDDI/tree/main/ui/packages/app-kit/src/test/mocks/alert-handlers.ts)); `openapi-operations.json` regenerated.
* **MCP** — `list_alert_events`, `acknowledge_alert_event` (`McpAlertTools`, AUTHOR tier, in-process bean); `McpRatingTools`' coded-error mapping moved to `McpToolUtils.codedFailure` and shared. 95 tools.
* **Operator** — reads `GET /alerts/events`, `/alerts/events/unacknowledged-count`, `/alerts/rules`, `/alerts/rules/{ruleId}`; prompt section on rules, states, retries and scoping; revision 37 → 38.
* **Docs** — [Alerts](https://docs.labs.ai/conversations-and-orchestration/alerts.md) (new, in `SUMMARY.md`), [Metrics](https://docs.labs.ai/deployment-and-infrastructure/metrics.md#alert-metrics), a Grafana alert-rule example in the [Monitoring Guide](https://docs.labs.ai/deployment-and-infrastructure/monitoring-guide.md#alerting-on-alert-delivery), an Alerts row in the full metrics dashboard (synced to `k8s/overlays/monitoring`), the `eddi.alerts.*` properties in the [Configuration Reference](https://docs.labs.ai/deployment-and-infrastructure/configuration-reference.md#alerts), [MCP Server](https://docs.labs.ai/protocols-and-integration/mcp-server.md#alert-tools-2), the `eddi-admin` skill.

### Design decisions

* **The turn hook sits in the wait, not at error sites.** `waitForExecutionFinishOrTimeout` is where ERROR, interruption and the watchdog's deadline converge for both turn paths, and `BaseRuntime` runs the turn's callbacks before `Future.get` returns. A mid-loop cost-ceiling stop is not visible there (the loop ends with an answer); the next turn's refusal is.
* **One maintenance schedule, not one per event or rule.** Fewer rows in the schedule list, one claim per minute; every step it takes is a conditional write, so a duplicated schedule (two nodes creating it at once) is harmless.
* **Editors: one agent, Slack and inbox only.** A rule over several agents and a webhook target (arbitrary URL, signed with a vault secret) are an administrator's. An editor sees a webhook by host only. Access is re-checked against the stored rule on update and delete.
* **Fixed, epoch-aligned windows** for dedupe and cap — exact across replicas through unique keys and atomic counters, at the price of a boundary where two windows meet.
* **The rule author, the acknowledger and the reviewer come from the caller**, never the body; MCP and the operator use the same in-process resources.
* **Operator: reads only.** Acknowledging is a person's statement; retry and test send real messages; rule writes decide where alert content goes. A rule read shows a webhook URL to the operator (it runs as the admin); the prompt says not to repeat it.

### Tests

Backend unit: 129 in the alert, step-runner, GDPR and MCP classes run together, plus `ScheduleFireExecutorTest` and `RestScheduleStoreExpandedTest` (648 with the related service suites); "never blocks" is proven twice — `AlertDispatcherTest` (10,000 hand-offs to a stuck worker in under a second) and `ConversationStepRunnerTurnOutcomeTest` (2,000 failing turns through the real hook). ITs: `MongoAlertStoresIT` and `PostgresAlertStoresIT` share `AlertStoreContract` (13 each, incl. a 40-thread window-counter race, the unique dedupe, version-conditional updates and single claims). Mutation check: 22 of 22 mutants killed by a test failure — every editor scoping guard (agentId required, single-agent scope, no webhooks, the EDIT check, agent-less events, webhook redaction, the stored-rule re-check on update and delete, editor rule listing, per-id bulk acknowledgement, single acknowledgement), the author from the caller, the privacy guards (comment truncation, no comment in the summary, Slack escaping, GDPR redaction), the hook never throwing into the turn, deadline classification, a full queue never throwing, and the webhook's strict SSRF, no redirects and unresolved-secret refusal. Manager: 18 new tests (page, editor, badge, `ruleProblems`). Full backend `./mvnw test`: 29,895 run; the two coverage guards it caught (configuration reference, dashboard) are fixed, the third failure is the known-flaky `DocumentExtractorsTest.honoursItsTimeBudget`.

***

## ✨ feat(engine): self-continuation — an agent can start its own next turn (2026-10-24)

**Repo:** EDDI (`feat/conversation-continuation`) — item E8 (core) of the evaluated-generation plan

### What changed and why

A job of many model calls (the plan's video pipeline: \~150 calls over \~20 minutes) cannot be one turn: the per-request deadline header is capped at 10 minutes, and the turn is EDDI's unit of tracing, persistence and recovery. Instead of a workflow engine, a job is now many ordinary turns of one conversation, and the conversation is its job log.

* **`CONTINUE_CONVERSATION`** — a new reserved action ([`IConversation`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/lifecycle/IConversation.java), [`ReservedActionLint`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/hitl/lint/ReservedActionLint.java)). A turn that emits it queues the next turn of the same conversation, without user input, **after the turn has been committed**.
* **Off unless configured.** Two agent-level fields ([`AgentConfiguration`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/agents/model/AgentConfiguration.java)): `maxContinuations` (per conversation, `0`..`10000`, default unset = off — the action is ignored with a WARN, the step records `continuation:refused = disabled`, and `eddi.continuation.refused{reason="disabled"}` counts it) and `continuationInput` (a literal string, ≤ 4096 characters, never a template; default empty). Validated at save time and on ZIP import ([`AgentStore`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/agents/mongo/AgentStore.java)).
* **Bounds.** Each continuation is an ordinary turn under the agent's `turnDeadlineMs`. The count is the number of steps carrying the engine-written marker `continuation:number`. `maxCostPerConversationUsd` bounds them all together — it already sums `audit:cost` over every step (`LlmSpendGate.conversationCost`, verified); a continuation is also refused before it is armed once the ceiling is reached. The tenant budget applies through `say` like on any turn.
* **What a continuation turn sees.** The designer's `continuationInput` and the engine-reserved context entry `selfContinuation = {number, max}` (added to [`ClientContextGuard.RESERVED_KEYS`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/security/ClientContextGuard.java), so a client cannot forge it). Rules route on a phase property, so the job is a state machine in config.
* **Delivery: a one-shot schedule, not the coordinator queue** ([`ConversationContinuations`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/continuation/ConversationContinuations.java), [`ContinuationFireHandler`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/continuation/ContinuationFireHandler.java), a fast-path in [`ScheduleFireExecutor`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/runtime/internal/ScheduleFireExecutor.java)). The coordinator's queue lives in memory and dies with its node; a schedule row survives a restart, exactly one node claims it, a failed fire is retried with backoff and dead-lettered, and the turn it starts still goes through `say` — coordinator, conversation lease and fencing, quotas, audit. The cost is the poll interval (≤ 15 s) between two continuation turns.
* **Once only.** Delivery is at-least-once, so two guards: the fire first looks for a step carrying its number in the stored conversation (written before the persist, never expires), and the turn carries an automatic `Idempotency-Key` (`eddi-continuation-<n>`). Under the lease, a queued turn rebuilt over a newer document is dropped when that document already holds its marker — also with the `Idempotency-Key` feature switched off ([`ConversationService`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/ConversationService.java)).
* **Lifecycle.** Decided before the persist (the outcome — `continuation:next` or `continuation:refused` — is part of the committed step) and armed only after it, in the say path ([`ConversationStepRunner`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/ConversationStepRunner.java)), the resume path and the `CONVERSATION_START` turn. Nothing is armed for a turn that paused, failed, was cancelled, lost its lease or could not be stored. A fire never runs a turn for an `ENDED`, `AWAITING_HUMAN`, deleted/erased or Art. 18-restricted conversation; an undeployed agent is retried (undeploy disables the schedule, redeploy re-enables it) and dead-lettered; an interrupted continuation stops the chain. `endConversation` and `cancel` withdraw the pending continuation — cancel between two continuation turns now answers `CANCELLED` instead of `409` ([`ConversationHitlService`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/ConversationHitlService.java)); the approver's paused-only cancel never touches it. A group member's turn cannot continue itself. The schedule carries the owner's `userId`, so erasure deletes it.
* **Schedule surfaces.** A continuation schedule cannot be fired manually (REST `409`, MCP error) and is never exported ([`RestScheduleStore`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/schedule/rest/RestScheduleStore.java), [`McpAdminTools`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/mcp/McpAdminTools.java), [`RestExportService`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/backup/impl/RestExportService.java)).
* **Metrics:** `eddi.continuation.scheduled`, `eddi.continuation.run`, `eddi.continuation.refused{reason}` — described in [`metrics.md`](https://docs.labs.ai/deployment-and-infrastructure/metrics.md#self-continuation-metrics) and charted in the Scheduling row of the Full Metrics Reference (k8s copy re-synced).
* **Docs:** new page [Long Jobs — the Conversation as the Job Log](https://docs.labs.ai/conversations-and-orchestration/long-jobs.md); reserved-action lists ([`agent-config-authoring.md`](https://docs.labs.ai/agent-configuration/agent-config-authoring.md), [`hitl.md`](https://docs.labs.ai/conversations-and-orchestration/hitl.md), `AGENTS.md`), reserved context key ([`passing-context-information.md`](https://docs.labs.ai/agent-configuration/passing-context-information.md), [`configuration-reference.md`](https://docs.labs.ai/deployment-and-infrastructure/configuration-reference.md)), [`conversations.md`](https://docs.labs.ai/conversations-and-orchestration/conversations.md), [`scheduling.md`](https://docs.labs.ai/conversations-and-orchestration/scheduling.md) (engine-minted schedules), [`httpcalls.md`](https://docs.labs.ai/agent-configuration/httpcalls.md) (do not poll long operations with retries), [`upgrading-from-6.5.md`](https://docs.labs.ai/deployment-and-infrastructure/upgrading-from-6.5.md) (newly reserved names, the cancel `200`).
* **Manager:** a **Self-continuation** section on the agent page beside Limits (`maxContinuations` with the backend's 0..10000 bound, refusing to save an invalid count; `continuationInput`), i18n in all 11 locales ([`agent-config-sections.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/components/editors/agent-config-sections.tsx), [`continuation.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/continuation.ts)).
* **Platform Operator:** the prompt explains self-continuation, its schedule, step records and metrics, and maps the `long-jobs` page; revision **36 → 37**. Other open branches also bump `operator-revision.json` — operator PRs land one at a time.

### Review fixes

* **Only the engine arms a continuation.** REST schedule create, update and ZIP import accepted the `continuationType` marker, and a fire runs a turn in the conversation its metadata names — so a client that may create schedules could inject a turn into another user's conversation. The marker is now refused (`400`, for everyone, like the HITL-timeout and ingestion markers), and a fire whose schedule `userId` does not own the conversation runs nothing (`owner_mismatch`, a new refusal reason) ([`RestScheduleStore`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/schedule/rest/RestScheduleStore.java), [`ContinuationFireHandler`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/continuation/ContinuationFireHandler.java)).
* **A fire is `COMPLETED` only for a turn that was stored.** The reply reaches the handler before the persist; the handler now confirms the turn's marker is in the stored conversation (re-checked for about two seconds) and fails the fire otherwise, so the schedule retries it.
* **A schedule write that fails for a moment is retried** (three attempts) before `schedule_failed`. The crash window between commit and arm is documented in [long-jobs.md](https://docs.labs.ai/conversations-and-orchestration/long-jobs.md) with how to spot and resume a stopped job; an automatic reconciliation sweep is planned with part 2.
* Manager: a half-typed count (`5e`, `-`) no longer silently clears `maxContinuations` and lets Save through.
* Docs: only continuation turns are retried by their schedule (the first turn is resent by its caller); the poll interval does not guarantee a minimum delay between continuations.
* **A cancel that races the arm wins.** A cancel that signalled a running turn found no schedule to withdraw yet, and the turn then armed one. Arming now skips a cancelled turn, and withdraws a schedule it wrote if the cancel landed during the write (`interrupted`).
* **Interrupts are kept.** An interrupted retry pause gives up and keeps the thread's interrupt flag, and the continuation fire log is written with the interrupt parked and restored afterwards, as the other fire paths already do.
* **End-to-end ITs on both datastores** ([`ConversationContinuationIT`](https://github.com/labsai/EDDI/tree/main/src/test/java/ai/labs/eddi/integration/ConversationContinuationIT.java) and its Postgres twin, with a one-second poll profile). A deterministic agent (rules + output, no LLM) runs one user turn, then the real poller runs continuations 1..3 on its own and the fourth is refused (`limit`); asserted on the stored conversation through REST (markers, `continuation:next`, the reserved context, the literal input), the schedule listing and the fire logs. Also: cancel between turns withdraws the pending continuation (`200`) and nothing runs after it, `endConversation` withdraws it, REST create/update with the marker is `400`, and an agent without `maxContinuations` arms nothing.
* **Fixed, found by those ITs: cancelling a finished job answered `CANCELLED`.** A fired one-shot is disabled, not deleted, so every continuation that ran stays under `continuation-<conversationId>`, and `disarm` counted those spent rows as withdrawn: a cancel after the job ended answered `200` instead of `409`. `disarm` still deletes them but now reports only the pending ones — enabled, or switched off by an undeploy — through a new `IScheduleStore.countPendingSchedulesByName` (Mongo and Postgres) ([`ConversationContinuations`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/continuation/ConversationContinuations.java)).
* **Spent continuation rows are bounded.** Every fired continuation stayed behind as a disabled one-shot with its fire log — up to `maxContinuations` rows per conversation. Arming the next continuation, and the last continuation turn of a job, now first deletes the conversation's used-up rows with their fire logs through a new `IScheduleStore.deleteUsedUpOneShotsByName` (Mongo and Postgres, reusing the delete cascades). Used up means exactly what `markCompleted` leaves for a one-shot: disabled, `PENDING`, no next fire, fired, unclaimed, no disabled reason — so the running continuation's claimed row, dead-lettered, undeploy-disabled and hand-disabled rows are never touched, and a conversation keeps at most its latest used-up continuation plus the pending one. A failed prune is logged and never stops the arm. Rejected: deleting a continuation's row when its fire completes, which would erase its fire history and put continuation logic into the generic poller. `deleteSchedulesByName` no longer logs every deletion as "HITL timeout schedule(s)".

### Not in this change (planned)

Part 2 of E8 — parking a turn on an external long-running operation (the HITL pause machinery with a machine as the resolver, a poll schedule bound to the `pauseId`, an optional signed webhook to resolve it sooner) — and the async video provider (needs E6/E7).

### Verification

New: `ConversationContinuationsTest`, `ContinuationFireHandlerTest`, `ConversationServiceContinuationTest` (the real `say` path: armed only after the commit; fire twice → one pipeline run through the stored document; two deliveries serialized by the lease → one run, with and without `Idempotency-Key`), `AgentStoreContinuationValidationTest`; extended `ConversationHitlServiceCancelTest`, `ScheduleFireExecutorTest`, `RestScheduleStoreTest`, `AgentStoreClientLibraryMemoryToolsTest`, `ClientContextGuardTest`.

***

## ✨ feat(llm): spend checks that see every attempt, and per-conversation reservations (2026-10-24)

**Repo:** EDDI · **Branch:** `feat/llm-spend-checks` · Plan item E4 of `planning/evaluated-generation-plan.md`

### What changed and why

The agent's `maxCostPerConversationUsd` and the tenant's monthly budget were checked once per LLM task, before its first model call, and between tool-loop rounds. Every further paid call of the task ran unchecked — and, since a task writes its cost into `audit:cost` only once it has finished, even a check would have missed the attempts before it:

* a same-model re-ask (`FormatRetryRunner`) was bounded only by `maxRetryCostUsd`, priced from per-1M prices, and never consulted the conversation's spend;
* a cascade escalation to its next step was bounded only by the cascade's own `maxCostPerRun`;
* an output guardrail `reprompt` and a `classifier` guardrail's model call (input and output) ran whatever the ceiling or the tenant budget said;
* nothing reserved the cost of a call in flight, so calls running at the same time would all pass the same check.

Now every one of these is admitted by `LlmSpendGate.admit` before it starts, with what the task has already spent and not yet recorded (earlier attempts at their prices; the primary answer's cost before a reprompt; earlier cascade steps before an escalation; the tool loop's tool cost before its final re-ask). A refused re-ask is skipped (`eddi.llm.recovery{outcome="skipped_spend"}`) and the reply is handled as unresolved; a refused escalation returns the cascade's best answer so far (`eddi.llm.cascade.ceiling.exceeded{kind="spend"}`) — or, when no earlier step produced one, raises the spend refusal so `LlmTask` serves the task's fallback answer, as for a refused primary call; a refused reprompt degrades to the existing "no reprompt could start" block; a refused classifier call is "could not decide" with the new audit reason `spend_refused`, so its `failMode` applies. Every refusal is counted by the existing `eddi.llm.spend.refused{reason}` with the existing reasons — no new meter.

**Reservations.** `SpendReservations` (one per loaded `ConversationMemory`, transient) holds the expected cost of each admitted call until it is closed; `LlmSpendGate.check` and `admit` both count what is held. It is per conversation and per node — exact for the ceiling, because a conversation's turns are serialized (coordinator; conversation lease in a cluster) and the ceiling is computed from the conversation's own steps, not from the cluster `COSTS` KV. The tenant budget is read, not reserved — but its check now adds the turn's unsettled spend (the current step's `audit:cost` not yet metered, plus the running task's unrecorded spend), through a new `TenantQuotaService.checkCostBudget(tenantId, pendingUsd)`: the monthly counter is charged only when a turn settles, so without it every paid call of a turn was compared with the counter as it stood before the turn. `LlmSpendGate.admit(memory, pendingUsd, expectedUsd)` and `TaskSpend` (a `PaidCallGate`) are the entry points for E5 (`forEach`) and E7 (media).

**Behaviour kept, now documented precisely.** A call is admitted while the spend so far — recorded, unrecorded and in flight — is *below* the ceiling; its own price is not compared, so the call that crosses the ceiling completes and the next is refused. No configuration field was added; an agent without a ceiling and with quotas off behaves exactly as before.

### Design decisions

* One gate, one rule: re-asks, escalations, reprompts and classifier calls use the same `admit` the primary call's `check` is built on, and the same reasons and metric.
* The reprompt check sits in `GuardrailService.runOutput`, behind `GuardrailContext.spend()`, so every execution branch (plain, tool loop, cascade, HITL resume) gets it; `Reprompter.Attempt` now carries the reprompt's priced cost.
* A phase's unrecorded spend lives in a `TaskSpend` that is discarded once the phase's cost is recorded, so no amount is counted both there and in `audit:cost`.
* Expected costs are cheap estimates (previous attempt's price; the classifier prompt at its input price). They only matter for concurrent calls, of which there are none inside one task today.

### Files

[`SpendReservations.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/memory/SpendReservations.java), [`LlmSpendGate.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/LlmSpendGate.java), [`TaskSpend.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/TaskSpend.java), [`PaidCallGate.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/guardrails/PaidCallGate.java), [`FormatRetryRunner.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/FormatRetryRunner.java), [`CascadingModelExecutor.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/CascadingModelExecutor.java), [`GuardrailService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/guardrails/GuardrailService.java), [`ClassifierGuardrail.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/guardrails/impl/ClassifierGuardrail.java), [`LlmTask.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/LlmTask.java); docs in [`langchain.md`](https://docs.labs.ai/agent-configuration/langchain.md#per-conversation-llm-cost-ceiling), [`llm-resilience.md`](https://docs.labs.ai/agent-configuration/llm-resilience.md), [`tenant-quotas.md`](https://docs.labs.ai/security-and-compliance/tenant-quotas.md), [`metrics.md`](https://docs.labs.ai/deployment-and-infrastructure/metrics.md); Platform Operator prompt and revision 37.

### End-to-end tests

* [`LlmSpendChecksIT`](https://github.com/labsai/EDDI/tree/main/src/test/java/ai/labs/eddi/integration/LlmSpendChecksIT.java) and its PostgreSQL twin [`PostgresLlmSpendChecksIT`](https://github.com/labsai/EDDI/tree/main/src/test/java/ai/labs/eddi/integration/postgres/PostgresLlmSpendChecksIT.java) drive a deployed agent against a WireMock OpenAI endpoint whose `usage` blocks are priced by the task: the ceiling refusing the turn after the one that crosses it; a re-ask, a guardrail reprompt, a cascade escalation and an output `classifier` call each refused on the task's unrecorded spend (each with a control that makes the call when nothing stops it); the tenant budget charged by one conversation and refusing the next, and refusing a re-ask on the same turn's unsettled spend; and an under-budget turn whose `audit:cost` and tenant usage equal the reported usage at the configured prices. Each asserts the client's answer, the stored conversation and the exact number of provider requests.

### Not done / next

* The cascade's `judge_model` confidence call is still unchecked (it is priced through the cascade's run cost and the next step's check sees it).
* Tenant-level reservations would need the quota store: a turn's own spend is now counted, but another conversation's unsettled turn is not, so concurrent conversations can each complete one call past the tenant budget.
* Operator revision 37 will collide with other open branches that bump it; re-bump at merge.

***

## 🐛 fix(llm): per-cascade-step vision, one repeat-guard test, consistent trace-header presence (2026-10-24)

**Repo:** EDDI (`fix/provider-capability-gaps`)

### What changed and why

Follow-ups from the review of #1056, #1057 and #1062.

* **Attachments are decided by the endpoint actually called.** `LlmTask` forwarded attachments once, with the task's own type and parameters, so a cascade step on its own `openai-compatible` endpoint with `vision=true` got no images, and a step without it inherited the task's. The JSON response format already used the step's parameters. `CascadingModelExecutor` now takes an optional per-step prompt provider; `LlmTask` supplies one that re-forwards the attachments with the step's type, model and vision decision, but only when the task or the step is `openai-compatible` and the endpoint differs (type, model or vision decision). Non-cascade tasks and `type: openai` cascades take exactly the old path. The re-forward is non-recording (`AttachmentForwarder.forward(..., record=false)`), so the turn's attachment errors and meters are not counted twice. A rebuilt-prompt retry after a context-too-long error (`onContextTooLong: retry`) still forwards with the task's decision; that rarely-hit path is unchanged.
* **Input guardrails no longer undo it.** The step's prompt is screened by carrying the task-level rewrites onto it (`LlmTask.screenedStepPrompt`): each text part the screening changed is rewritten by its text in the step's message, while the step's own image and document parts and engine notes are kept. `GuardrailService.reapply` is not used for a step, because it swaps the whole last user message for the task's screened one, attachments included.
* **Text only a step's prompt carries is screened.** An attachment can turn into different text per endpoint (a PDF extracted to text for a step without native PDF, a file inlined for one step and skipped for the task, a vision-skip note naming the file). That text is current-turn content the task-level screening never saw, so `GuardrailService.screenUnseenText` screens it with **every** input guardrail, including the classifier, which skips earlier messages for cost. It is quiet (no outcome, metric, SSE event or audit entry; the turn's findings were recorded once); its cost is added to the turn. `redact` rewrites the text; a block, or a guardrail that cannot decide (a classifier that is down or unparseable) according to its `failMode` (a `redact` guardrail without `failMode` lets the text through), replaces it with the withheld placeholder. This differs from the task path on purpose: a BLOCK on attachment text there blocks the whole turn, while on a cascade step's step-only text the part is withheld and the turn continues, because step-only parts are never replayed into later history. The cost of a classifier call is counted whether it flags or clears the text. A verdict is kept for the turn by text, so several cascade steps carrying the same part cost one classifier call. When the step's prompt cannot be matched to the task's, the step gets the task's screened prompt.
* **What is recorded.** The attachment errors written to the step data and the `eddi.attachment.*` meters come from the task-level pass (the task's endpoint), not from the cascade step that answered. A step's own forwarding is non-recording.
* **Repeat guard, gated batch.** `ToolLoopRunnerToolPolicyTest` gains a test for the ungated half of a gated (HITL) batch, the second `executeGuarded` call site, which no test drove.
* **MCP trace headers.** `McpToolProviderManager.withTraceHeaders` checked `traceparent` and `tracestate` one at a time, while `TracePropagation.headersMissingFrom` is all-or-nothing. It now reuses the shared rule (`TracePropagation.withoutIfAnyPresent`): an author's own `traceparent` or `tracestate` suppresses both.
* **Refuted:** `create_api_agent` already runs the same `OutboundTargetPolicy` check on `llmBaseUrl` as `setup_agent` does on `baseUrl` (`AgentSetupService.createApiAgent`, covered by `AgentSetupLlmBaseUrlPolicyTest`); no change.

### Design decisions

* The per-step decision compares (type, model name, effective vision) of the step with the task's and re-forwards only on a difference, so the common cascade keeps the one prompt it always had.

### Verification

Mutation-checked: bypassing the per-step provider, the guard at the gated-batch site, and the shared presence rule each fail the new tests.

***

## chore(release): attest SHA256SUMS with SLSA provenance (2026-10-24)

**Repo:** EDDI · **Branch:** `chore/release-provenance-attestation`

The OpenSSF Scorecard Signed-Releases check reported 6.6.0 as signed (the cosign bundle `SHA256SUMS.sigstore.json`) but without provenance. The image job already attested its digest with `actions/attest-build-provenance`; the release job, which publishes the installer checksum list, did not attest anything.

* [`ci.yml`](https://github.com/labsai/EDDI/tree/main/.github/workflows/ci.yml) — the `release` job gets `attestations: write` and a `Generate SLSA provenance attestation (SHA256SUMS)` step after the cosign signature, using the same pinned action as the image job. It runs before the GitHub Release is created, so a failed attestation publishes nothing.
* Verify a release with `gh attestation verify SHA256SUMS --repo labsai/EDDI`.
* Applies to tags cut after this merges. 6.6.0 stays without provenance; it cannot be attested retroactively.
* Open question: Scorecard's check may look for a `.intoto.jsonl` release asset rather than the attestation store. Confirm on the next tag; if it still warns, the fallback is the `slsa-framework/slsa-github-generator` generic generator, which emits that asset.

***

## 📝 docs(planning): evaluated generation — checks and repair for every step that produces something (2026-10-24)

**Repo:** EDDI (`docs/evaluated-generation-plan`)

### What changed and why

New planning document [`planning/evaluated-generation-plan.md`](https://github.com/labsai/EDDI/tree/main/planning/evaluated-generation-plan.md). No code changes.

It started as an analysis of whether EDDI could host a production AI video-generation pipeline: about 150 model calls per job, best-of-N keyframes, multimodal judges, a repair ladder, a human cost gate, and ffmpeg assembly. The answer generalises beyond video. **Make → judge → repair** is the loop behind grounded RAG answers, extraction, text-to-SQL, output compliance, content production, group deliverables and media.

Verified against `main` at `5028af0a3`, EDDI already runs that loop in seven places:

* output guardrails (#1064, with the `classifier` type from #1112);
* format recovery (R5);
* the model cascade;
* TASK\_FORCE VERIFY, which has no rework within a run;
* group task approval;
* single-agent HITL;
* team cadences.

The plan builds on them instead of adding an eighth:

| Item | What it adds                                                                                                                                                                                                                                                    |
| ---- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| E1   | A `judge` output guardrail that answers with author-declared issue codes, so a reprompt says what to fix; `onExhausted: deliver-best` for quality checks, so the best attempt is delivered (still screened by every other guardrail) instead of a block message |
| E1c  | A deterministic `expression` guardrail                                                                                                                                                                                                                          |
| E2   | Rework after a failed verdict, for humans and groups                                                                                                                                                                                                            |
| E4   | Spend checks that see every attempt, and reservations for parallel calls                                                                                                                                                                                        |
| E5   | Checks and `forEach` on tool and HTTP steps                                                                                                                                                                                                                     |
| E6   | Media groundwork                                                                                                                                                                                                                                                |
| E7   | Speech and image providers                                                                                                                                                                                                                                      |
| E8   | Long jobs through self-continuation and parked operations                                                                                                                                                                                                       |
| E9   | A fingerprinted DAG                                                                                                                                                                                                                                             |
| E10  | A composition service outside core                                                                                                                                                                                                                              |

### Design decisions

* **Checks on meaning are output guardrails**, not a new block in `responseValidation`. Guardrails already run after it in every execution mode, with their own reprompt loop, cost metering and `failMode`.
* **`judge` is a sibling of `classifier`, not a mode of it.** It shares the classifier's model-call machinery: provider pass-through, timeouts, deadline, pricing and `promptTemplate` data. Its contract differs: a structured list of codes rather than "safe is a positive label".
* **Judge feedback uses a closed vocabulary.** `GuardrailService.correctiveMessage` never puts the user's or the model's text into a reprompt, so the judge returns only declared codes, and the producer is told only the designer's fix text for them.
* **The pipeline stays a straight line.** Loops live inside a step, and repairs that must reach an earlier step leave as actions.
* **ffmpeg, music and domain-specific logic stay outside core.**

***

## feat(chat-ui): conversation and reply ratings (2026-10-24)

**Repo:** EDDI (`feat/conversation-ratings`) — PR 2 of [`planning/conversation-rating-plan.md`](https://github.com/labsai/EDDI/tree/main/planning/conversation-rating-plan.md) (§7 and §0.1 "User — UX rules")

### What changed and why

The Chat UI now lets the person chatting rate the conversation and, when the agent asks for it, single replies, against the owner endpoints PR 1 added. Everything is driven by the profile's `rating` object; without it the widget renders exactly as before.

* **Reply thumbs** ([`StepRating.tsx`](https://github.com/labsai/EDDI/tree/main/ui/packages/conversation/src/components/StepRating.tsx)) under the last agent bubble of each step — hover/focus on desktop, always on touch, `aria-pressed`, 44px targets on touch. Thumbs down rates at once, then offers optional reason tags and a comment.
* **Rating card** ([`RatingCard.tsx`](https://github.com/labsai/EDDI/tree/main/ui/packages/conversation/src/components/RatingCard.tsx)), a sibling of `PausedCard`: stars as a radio group (roving focus) or thumbs; offered on end (`askOnEnd`) and/or after `askAfterTurns` replies, at most once per conversation, never to somebody who already rated, never again once closed (localStorage, guarded); always available from a header entry. One tap rates, tags/comment follow (comment per `askBelowScore`), then a thanks state naming who receives the feedback; editable and removable afterwards; never blocks the composer.
* **State** ([`useRatings.ts`](https://github.com/labsai/EDDI/tree/main/ui/chat/src/hooks/useRatings.ts)): restored via `GET /agents/{id}/rating` when a conversation opens; optimistic updates with rollback and a short notice; every backend error code mapped to translated copy ([`rating-api.ts`](https://github.com/labsai/EDDI/tree/main/ui/chat/src/api/rating-api.ts)); a rerun clears the local thumb of that step.
* **Steps** ([`rating-steps.ts`](https://github.com/labsai/EDDI/tree/main/ui/packages/core/src/rating-steps.ts)): reply ratings are keyed by step. Full conversation reads now stamp `stepIndex` on their messages (`stepsToMessages(…, fullHistory)`, `processSnapshot({ fullHistory })`); live turns are counted from the nearest stamped message.
* **Demo mode** gets an in-memory rating backend and a profile asking for every control. i18n for en/de/fr/es; styles for both themes and phones.
* Docs: Chat UI section in [`conversation-ratings.md`](https://docs.labs.ai/conversations-and-orchestration/conversation-ratings.md); [`ui/chat/AGENTS.md`](https://github.com/labsai/EDDI/tree/main/ui/chat/AGENTS.md) structure and the rating error envelope.

### Design decisions

* The rating endpoints' error body is `{error: CODE, message}`, not the attachments' `{error, code}`; `rating-api.ts` parses its own and never shows the server's message.
* One thumb per **step**, under the step's last bubble, because the server stores one reply rating per step.
* Stars use radio semantics for screen readers, but arrow keys only move focus and Enter/Space rates: with "one tap rates", arrow-selects-and-submits would send a rating per key press.
* A rerun clears the thumb locally only, as plan R8 says; the stored rating reappears after a reload (documented limitation).

### Testing

`npm run typecheck`, `npm run lint` and the full vitest suite (34 files, 564 tests, 67 of them new) pass; key logic was mutation-checked. Vitest needs Node ≥ 22.15 (jsdom 30's undici): the Maven-downloaded `ui/node/v24.*` works.

***

## feat(ratings): conversation ratings — backend (2026-10-24)

**Repo:** EDDI (`feat/conversation-ratings`) — PR 1 of the plan in [`planning/conversation-rating-plan.md`](https://github.com/labsai/EDDI/tree/main/planning/conversation-rating-plan.md)

### What changed and why

People chatting with an agent can now rate the conversation and, if the agent asks for it, single agent replies; the people running the agent can list, summarize, export and triage those ratings. Off unless the agent designer adds `ratingConfig` with `"enabled": true` (checked per agent version the conversation runs on, cached per version in `ConversationRatingPolicy` like `ConversationReviewPolicy`).

* **Config:** `AgentConfiguration.ratingConfig` (scale `THUMBS|FIVE_STAR`, conversation and reply ratings, comment rules, reason tags, rating window), validated on agent create/update/duplicate (`RatingConfigValidator`), and a `rating` subset on `GET /agents/{agentId}/profile` so chat clients need no extra call.
* **Store:** `IConversationRatingStore` with MongoDB ([`ConversationRatingStore`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/ratings/mongo/ConversationRatingStore.java)) and PostgreSQL ([`PostgresConversationRatingStore`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/datastore/postgres/PostgresConversationRatingStore.java)) implementations selected in `DataStoreProducers`. Key `(conversationId, stepIndex)`, conversation rating at `-1`; atomic upsert keeping `id`/`createdAt`; summaries aggregated in the database; indexes for agent+time, agent+version, user (GDPR) and the needs-attention count.
* **Owner REST** (`IRestConversationRating`): `PUT|GET|DELETE /agents/{conversationId}/rating` and `PUT|DELETE /agents/{conversationId}/steps/{stepIndex}/rating`, with stable error codes (`RATING_DISABLED`, `RATING_WINDOW_CLOSED`, `INVALID_STEP`, `INVALID_SCORE`, `INVALID_TAG`, `COMMENT_NOT_ALLOWED`, `COMMENT_TOO_LONG`, `NOT_CONVERSATION_OWNER`, `CONVERSATION_NOT_FOUND`).
* **Maintainer REST** (`IRestConversationRatingAdmin`, `eddi-admin`/`eddi-editor`): `GET /ratings`, `/ratings/summary`, `/ratings/export` (CSV, 100k cap, formula-injection escaping), and the triage loop of plan §0.1: `GET /ratings/attention-count`, `PATCH /ratings/{ratingId}`, `POST /ratings/review`.
* **GDPR:** `ConversationRatingGdprParticipant` joins erasure (deletes the user's ratings, clears them as reviewer) and export; processing restriction blocks new ratings.
* **Metrics:** `eddi_conversation_ratings_total`, `eddi_conversation_ratings_normalized`, `eddi_conversation_ratings_withdrawn_total`, charted in a new "Conversation Ratings" row of the Full Metrics Reference dashboard.
* **Docs:** new [`conversation-ratings.md`](https://docs.labs.ai/conversations-and-orchestration/conversation-ratings.md), `ratingConfig` section in [`agent-config-authoring.md`](https://docs.labs.ai/agent-configuration/agent-config-authoring.md), [`gdpr-compliance.md`](https://docs.labs.ai/security-and-compliance/gdpr-compliance.md), [`metrics.md`](https://docs.labs.ai/deployment-and-infrastructure/metrics.md).

### Design decisions

* **Only the owner rates.** `requireConversationOwner` admits administrators too; the endpoint additionally requires `OwnershipValidator.isOwner`, so an admin can read and withdraw but never write a rating in somebody's name.
* **User ids for administrators only** — decided on `isAdmin()`, not `seesEverything()`: without workspace enforcement every editor "sees everything", and the plan's R3 is about admins.
* **Scoping (R6):** a caller who does not see everything must pass `agentId` and hold `EDIT`; `PATCH` checks `EDIT` on the rating's own agent.
* **`canOpenTranscript`** applies the existing conversation-read rule per row (owner, admin, or conversation review) and is false for purged conversations — one descriptor read per distinct conversation on the page (≤ 100).
* **Triage is hidden from the rater:** owner responses strip status, reviewer and note. A re-rating resets triage to `NEW` and clears the note. `PATCH` is conditional on the rating's `updatedAt`, so a maintainer cannot mark reviewed a rating that changed after they read it (409 `RATING_CHANGED`). The reviewer always comes from the principal.
* **`minScore`/`maxScore` filter the normalized score** (0..1), so one filter means the same on every scale. Added `sort=newest|lowest`, `reviewStatus` and `needsAttention` filters.
* Admin endpoints share one `@BeanParam` (`RatingQueryParams`) so the five filtered endpoints cannot drift.

### Deviations from the plan

* A reply rating records the conversation's agent version at rating time: conversation memory stores no version per step (plan §10 assumed one).
* The per-reply excerpt for callers who may read the transcript (§6) is not returned; clients with `canOpenTranscript` open the conversation instead.
* GDPR: implemented as an `IGdprParticipant` (erase + export), which is the SPI for stores; `UserErasureParticipant` is for stopping in-flight work and has nothing to stop here.
* No separate `(conversationId)` index: the unique key's prefix serves it.

### What's next

The MCP rating tools ship with this backend. Next: the Chat UI and the Manager Feedback page (badge on `attention-count`) with the Platform Operator's read access, then push alerts. The store ITs (`MongoConversationRatingStoreIT`, `PostgresConversationRatingStoreIT`) need Docker.

***

## ✨ feat(mail): email notifications for pending approvals — email Phase 1 (2026-10-24)

**Repo:** EDDI (`feat/email-hitl-notifications`, on top of `feat/email-mail-core`)

Phase 1 of [the email plan](https://github.com/labsai/EDDI/tree/main/planning/email-channel-plan.md) (§16 "Notifications", the outbound half of §12).

### Socket guard: an operator policy

* **`SafeSocketConnector.resolveOperator`** (`Policy.OPERATOR`) for a host the operator set in `application.properties` — today only the system mailer's relay. Private and loopback addresses, IP literals, single-label names and any port (25 included) are allowed, and `eddi.email.allowed-hosts` (which confines authors) is not consulted. Still resolved once and pinned, still no link-local or cloud-metadata address, TLS still verified. `TlsMode.PLAINTEXT` exists only on an operator endpoint: the `Endpoint` constructor refuses it for an author one. `resolve` (the author policy) is unchanged.

### Connections: mail origins on `baseUrlAllowlist`

* A connection's `baseUrlAllowlist` now accepts `smtp://`, `smtps://`, `imap://` and `imaps://` origins (`ConnectionConfiguration.requireCanonicalAllowlistOrigin`), so `resolveAccessToken` (XOAUTH2) and the new `resolveBasicLogin` (username + vault-backed password for SMTP/IMAP login) can check a mail server against it. The ports a mail scheme implies fold away (`smtps` 465, `smtp` 587, `imaps` 993, `imap` 143); `smtp://relay:25` stays a distinct origin. An https entry for the same host does not cover a mail origin. The credential-endpoint allowlist and the public base URL stay http(s) only. The Manager's `connection-validation.ts` mirror accepts the same schemes, with the `originScheme` message updated in all 11 locales.

### The system mailer

* **`SystemMailer`** (`engine/mail`): the deployment's one SMTP sender, configured by the operator under `eddi.mail.smtp.*` (host, port, `tls` = `starttls` | `implicit` | `none`, `from`, `from-name`, and at most one credential source: `connection` — `BASIC` or `OAUTH2_CLIENT_CREDENTIALS`/XOAUTH2 — or `username` + `password`). Unset host = disabled, one INFO line at startup; an unusable configuration disables it with one ERROR line and never falls back to something weaker. Sockets come from `SafeSocketConnector.resolveOperator`. STARTTLS is required, not opportunistic; `tls=none` needs `eddi.mail.smtp.allow-plaintext=true` and never carries a credential. Failures are classified (`MailSendException.Category`), permanent only for a 5xx refusal.
* **GreenMail 2.1.14** (Apache-2.0, test scope; its aggregate `org.eclipse.angus:jakarta.mail` and JUnit 4 are excluded) runs implicit TLS, plain SMTP and AUTH in `SystemMailerTest`; a small in-test STARTTLS server covers the upgrade GreenMail does not speak, and proves AUTH (PLAIN and XOAUTH2) only ever crosses the wire after it. The certificate is a throwaway made with the JDK's `keytool`; the production TLS path, with certificate and host-name checks, is what accepts it.

### The message ledger (outbound)

* **`IEmailMessageLedger`** (`integrations/email/ledger`) with `MongoEmailMessageLedger` (`email_message_ledger` collection) and `PostgresEmailMessageLedger` (`email_message_ledger` table, created on first use), selected by `eddi.datastore.type` in `DataStoreProducers`. One row per message: integration (`system` for system mail), kind (`NOTIFY`; `REPLY` later), direction, RFC Message-ID, conversation, `sourceRef` (what the message is rebuilt from — the pause id for a notification), idempotency key, recipient, state `PENDING → SENT | FAILED | SUPPRESSED`, attempts, `nextAttemptAt`, claim token, provider response, last error, created/updated/expires. **No body, subject or MIME** — a retry re-renders from the source. Two unique keys (idempotency key; `(integrationId, direction, messageId)`) make an insert a cluster-wide claim. `claimDue` leases rows by a conditional update (`findOneAndUpdate` per row on Mongo; `UPDATE … FOR UPDATE SKIP LOCKED … RETURNING` on Postgres), and every state change is conditional on the claim token, so a taken-over claim cannot overwrite the new owner's result.
* `MongoEmailMessageLedgerIT` / `PostgresEmailMessageLedgerIT` run one shared contract against real databases (Testcontainers): duplicate keys, eight concurrent inserts of one notification (one winner), two sweepers claiming 20 rows at once (no overlap), lease expiry and stale claims, reschedule, retention, erasure by recipient, and the stored field set (no body field exists).

### HITL email notifications

* **Agent opt-in** `hitlConfig.notify.email.recipients` (`HitlNotifyConfig`): 1–20 plain ASCII addresses, validated at save and import time (`HitlConfigValidation.validateNotify` — empty, over 20, malformed, display-name, non-ASCII and duplicate-after-normalisation entries refused with the position, never the address). Configs without the field are unchanged.
* **The hook:** `HitlPauseCommittedEvent(conversationId, pauseId)`, fired asynchronously by `ConversationService.firePauseCommitted` at the three places a regular pause is committed — the say turn (`ConversationStepRunner`, after the state CAS and the timeout schedule), the `CONVERSATION_START` turn, and a resume that pauses again (`ConversationHitlService`). Not for a pause restored after a failed resume, nor on a CAS miss. Group discussions are not covered yet.
* **`HitlEmailNotifier`** (`integrations/email/notify`): re-reads the pause from the store (state and `pauseId` must still match), inserts one ledger row per recipient under a digest key of kind/conversation/pause/recipient, and sends at once for the rows it won. A `@Scheduled(identity = "email-ledger-sweeper")` sweep retries due rows with exponential backoff (`eddi.email.outbound.retry-backoff`, capped at 1 h) up to `eddi.email.outbound.max-attempts`, removes expired rows (`eddi.email.ledger-retention`) and refreshes the `eddi.email.ledger.pending` gauge. A decided pause ends `SUPPRESSED`; a 5xx fails at once.
* **Content** (`HitlNotificationContent`): agent name, pause type, reason, start, deadline + policy, conversation id, and for a tool-call pause the same redacted, 300-char-truncated argument lines as the Slack card — extracted from `SlackHitlSupport` into the shared `HitlToolCallPreview`. No conversation content. Subject `[EDDI] Approval needed: <agent name>`, designer text flattened to one line. The link is `eddi.connections.public-base-url` + `/manage/approvals`, no token; without a base URL the page is named, not linked.
* **Metrics** `eddi.email.outbound{kind,outcome}` and `eddi.email.ledger.pending`, on the Full Metrics dashboard's Human-in-the-Loop row and in `metrics.md`. **Audit** entry `email.notify` per sent/failed notification with the recipient as a SHA-256 hash plus domain (the audit ledger is write-once). **GDPR**: `EmailLedgerGdprParticipant` (`emailLedger`) erases/exports rows by the user id's address and the directory's recorded email; `IGdprParticipant.order()` makes the user directory run last so the address is still readable.

### Recipient domain policy and flood brake (review follow-up)

* **`eddi.mail.notify.allowed-recipient-domains`** (`NotifyRecipientPolicy`, `engine/mail`): exact domains, `*.domain` for subdomains, `*` for any; **unset = the domain of `eddi.mail.smtp.from` and its subdomains**. Recipients are set by anyone with EDIT on an agent while the mail leaves through the operator's relay under the operator's sender, so without a bound the relay was an open mailer for agent authors. Enforced at send time on every attempt (the row ends `SUPPRESSED`, `RECIPIENT_NOT_ALLOWED`, `outcome=not_allowed`) and at save time in `HitlConfigValidation` — refused when a mailer is configured, accepted with a WARN when not (read through `ConfigProvider`, since the validation is static). A malformed entry fails closed: nobody is mailed, ERROR at startup.
* **`eddi.mail.notify.max-per-recipient-per-hour`** (default 30): `IEmailMessageLedger.countCreatedSince(recipient, kind, since)` counts the recipient's non-suppressed `NOTIFY` rows of the last hour across the cluster (new index `(recipient, kind, createdAt)` on both stores); over the limit the row is `SUPPRESSED` (`RATE_LIMITED`, `outcome=rate_limited`) and each instance logs one WARN per recipient per hour, naming it by hash. Suppressed rows do not count, so the window empties once the flood stops. Count and insert are two steps, so concurrent pods can overshoot by a few.
* Docs (`hitl.md`, `configuration-reference.md`, `metrics.md`), the Manager hint and the operator prompt say so; operator revision stays 37 (one PR) with the new fingerprint.

### Manager and the Platform Operator

* The agent's **Human-in-the-Loop** settings gain "Email people when this agent waits for approval" with a recipients field (`agent-config-sections.tsx`, parser in `lib/hitl-notify.ts` mirroring the save-time rules: 1–20, plain ASCII, no duplicates). As with the approval timeout, an unsavable list never enters the draft; the field shows what is wrong. Eight new `agentDetail.hitlNotify*` keys in all 11 locales.
* **Operator prompt** (`system-prompt.ts`): how email notifications are set up — the operator's `eddi.mail.smtp.*`, the agent's `hitlConfig.notify.email.recipients` in the Manager (the operator cannot write `hitlConfig`), what the mail contains, why there is no "all approvers" switch. No new endpoint, so `tool-scopes.ts` is unchanged. **Operator revision 36 → 37.**
* Docs: [`hitl.md` → Email notifications](https://docs.labs.ai/conversations-and-orchestration/hitl.md#email-notifications) (with a sample config), [`configuration-reference.md` → Email](https://docs.labs.ai/deployment-and-infrastructure/configuration-reference.md#email), [`metrics.md`](https://docs.labs.ai/deployment-and-infrastructure/metrics.md#hitl-metrics), [`security.md` → the operator policy](https://docs.labs.ai/security-and-compliance/security.md#the-operator-policy--the-system-mailers-relay), [`connections.md`](https://docs.labs.ai/protocols-and-integration/connections.md), [`gdpr-compliance.md`](https://docs.labs.ai/security-and-compliance/gdpr-compliance.md), [`compliance-data-flow.md`](https://docs.labs.ai/security-and-compliance/compliance-data-flow.md).

### For Phase 2 and 3

* The ledger API is the one they extend: add inbound states and a stranded-turn query to `IEmailMessageLedger`, `Kind.REPLY` rows get their own worker (`claimDue` takes a kind), `sourceRef` carries the conversation step a reply is rebuilt from. The unique `(integrationId, direction, messageId)` key is already the inbound dedup key.
* The SMTP client is `SystemMailer` for operator relays only; a channel's author-configured SMTP must use `SafeSocketConnector.resolve` (the author policy), not `resolveOperator`.
* Group discussions (`AWAITING_APPROVAL`) are not notified yet; `GroupHitlCoordinator` commits group pauses in three places and would need its own event.

***

## ✨ feat(mail): mail core, socket guard and bare OAuth tokens — email Phase 0 + 0b (2026-10-24)

**Repo:** EDDI (`feat/email-mail-core`)

The first slice of [the email plan](https://github.com/labsai/EDDI/tree/main/planning/email-channel-plan.md) (Phase 0 and 0b): a pure library under `engine/mail` that later phases (notifications, trigger mode, conversation mode) and the mail RAG source ([`rag-ingestion-source-types-plan.md`](https://github.com/labsai/EDDI/tree/main/planning/rag-ingestion-source-types-plan.md) §8) build on. No channel, no transport, no conversation code — nothing here is reachable from an agent yet.

### What changed and why

* **Angus Mail** (`org.eclipse.angus:angus-mail` 2.0.5, `jakarta.mail:jakarta.mail-api` 2.1.5 — the versions the Quarkus BOM manages, so one copy on the classpath; EPL-2.0 / GPL-2.0-with-CPE / EDL-1.0) for MIME grammar.
* **`MimeMessageParser`**: raw RFC 5322 bytes → `InboundMail`. Every limit (`MailLimits`: raw bytes, header bytes, nesting depth, part count, attachments, per-attachment bytes, output characters) is enforced before the work it bounds — multipart delimiters are counted in the raw bytes before Jakarta Mail materialises a part, so a few KB declaring thousands of parts is refused, not allocated, and a base64-encoded multipart (which would hide its delimiters) is skipped. `text/plain` preferred, HTML converted as fallback. Broken and unknown charsets, RFC 2047 words (split multi-byte, unknown charset), unparseable dates and invalid addresses become `MailAnomaly` values, never exceptions. A message without a Message-ID gets `sha256:<hex of raw bytes>`, flagged `syntheticMessageId`. Executables (by name, type and magic bytes) never carry content; archives are flagged, never expanded; `message/rfc822` is never walked into. `multipart/report` DSNs are parsed into a `DeliveryReport` (recipient, action, status, original Message-ID) for later bounce suppression.
* **`AddressNormalizer`** (lower-case, IDN→ASCII, no dot/`+tag` folding, no domain literals or numeric TLDs), **`QuoteStripper`** (trailing `>` blocks with en/de/fr/es/it/nl attributions; Outlook header blocks in en/de/fr; Gmail `gmail_quote`, Apple/Thunderbird `blockquote type=cite` + `moz-cite-prefix`, Outlook web markers — interleaved inline replies, forwards and quote-only messages are kept whole), **`AutoReplyDetector`** (RFC 3834, `X-Autoreply`/`X-Autorespond`, `Precedence`, `List-*`, null/daemon return paths, reports), **`PlainTextMailRenderer`** (`text/plain` UTF-8 `format=flowed`, threading headers with a capped References chain, `Re:` without stacking, `Auto-Submitted`, `X-Auto-Response-Suppress: All`, random `<eddi.<uuid>@domain>` ids, and a refusal of any header value containing CR/LF or another control character).
* **`HiddenContentFilter`**, run by `HtmlToMarkdownConverter`, in two modes. **Page mode** (`convert()`, every existing caller — crawler, file upload, `WebScraperTool`) is conservative: only HTML comments, text of 1px or less, transparent text, and text the colour of a background set explicitly on it or an ancestor are dropped. Accordions, `hidden` tab panels, `opacity:0` fade-ins, off-screen skip links and `sr-only` text — what pages hide until script reveals it, and what a knowledge base wants — are kept. **Mail mode** (`convertMail`) is strict, since mail runs no script: also `display:none`, opacity \~0, `mso-hide`, zero-size + overflow hidden, off-screen, `clip`, `scale(0)`, `hidden`, inherited `visibility:hidden`, `display:none`/`visibility:hidden` rules in `<style>` outside `@media` (`HiddenStylesheetRules`), and an assumed white page with black text. `convertMail` also skips the `main`/`article` scoping and the `<title>`.
* **Linear on hostile input.** Style blocks are read by one forward `indexOf` scan (no backtracking regex) and matched in one pass against an index of rules; nothing is truncated, so a hiding rule after megabytes of junk is still applied. Where exact matching would cost more, it over-approximates (rightmost compound selector only; an element more than 64 hiding rules could apply to counts as hidden), which can only remove more. The quote stripper's Outlook-header search computes subtree text sizes bottom-up and its top-level searches skip matched subtrees. jsoup 1.23.2 itself caps tree depth at 512 (deeper elements become siblings).
* **`ALTERNATIVES_DIVERGE`**: when a `multipart/alternative` has both parts, the plain text (what the agent reads) is compared with the HTML as rendered, hidden content removed (what a reviewer sees), by word sets in both directions; a substantial difference adds the anomaly. `text/plain` stays the preference.
* **`SafeSocketConnector`** (`engine/net`): the socket-level SSRF guard the RAG plan §3.10 proposed. DNS names only (every IP-literal spelling refused), IMAP 993/143-STARTTLS and SMTP 465/587-STARTTLS only, optional `eddi.email.allowed-hosts`, resolved once with every address checked by `UrlValidationUtils.isPrivateAddress`, pinned to the first address (`PinnedSocket` ignores a library's second lookup), TLS always verified, timeouts. `angusProperties(endpoint)` wires Angus Mail to it with `socketFactory.fallback=false`; a loopback smoke test proves Angus connects through it, requires STARTTLS before any credential, and does not fall back.
* **`ConnectionResolver.resolveAccessToken`**: the bare access token for `XOAUTH2`, OAuth connections only (`STATIC`, `BASIC`, `CALLER_SUPPLIED` → `UNSUPPORTED_PLACEMENT`), with the allowlist, `PER_USER`/`VERIFIED` rules and the shared token supplier (refresh, caching) unchanged.

### For the next phases

* `InboundMail.authentication()` is `NOT_EVALUATED` until the DKIM verifier attaches a verdict with `withAuthentication`; only `ALIGNED_PASS` authenticates. The verifier must also treat the `MULTIPLE_FROM` and `DUPLICATE_SINGLETON_HEADER` anomalies as unauthenticated. Raw bytes are not kept in `InboundMail`; the verifier gets them from the transport.
* `baseUrlAllowlist` holds http(s) origins only, so `resolveAccessToken` refuses an `imaps://` target today (fails closed). The IMAP phase must teach the connection model (and the Manager's mirror in `connection-validation.ts`) mail origins.
* Private-address mail servers (on-premises Exchange) are refused, with no override yet.

**Files:** [`engine/mail/`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/mail/README.md), [`SafeSocketConnector.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/net/SafeSocketConnector.java), [`HiddenContentFilter.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/ingestion/HiddenContentFilter.java), [`HiddenStylesheetRules.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/ingestion/HiddenStylesheetRules.java), [`ConnectionResolver.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/connections/ConnectionResolver.java), [`security.md`](https://docs.labs.ai/security-and-compliance/security.md#mail-sockets--safesocketconnector), [`configuration-reference.md`](https://docs.labs.ai/deployment-and-infrastructure/configuration-reference.md#email), [`rag.md`](https://docs.labs.ai/agent-configuration/rag.md), fixtures under [`src/test/resources/mail/`](https://github.com/labsai/EDDI/tree/main/src/test/resources/mail/README.md).

***

## ✨ feat(llm): `expression` guardrail — a deterministic check over a JSON answer (2026-10-24)

**Repo:** EDDI (`feat/llm-expression-guardrail`, from `main` at `5028af0a3`) — item E1c of the evaluated-generation plan. Independent of the `judge` guardrail (#1121, `feat/llm-judge-guardrail`): it builds only on what `main` has (`ContentGuardrail`, `GuardrailVerdict.violation(reason, hint)`, `GuardrailUndecidedException`, `failMode`).

### What changed and why

A well-formed answer can still be wrong: an invoice whose `total` is not the sum of its lines passes `responseSchema` and `json-object`. `expression` (output only) parses the answer as JSON and evaluates an author-written boolean expression over it, and reprompts with author-written feedback — the deterministic sibling of the `judge`.

```json
{ "type": "expression", "action": "reprompt", "maxRetries": 1,
  "parameters": { "expr": "sum(lines[*].amount) == total", "issue": "LINE_SUM",
                  "fix": "Make total equal the sum of the line amounts, to the cent." } }
```

* **`SafeJsonExpression`** (`ai.labs.eddi.utils`, new) — a small recursive-descent language in the style of `CalculatorTool.SafeMathParser`: number/string/`true`/`false`/`null` literals; paths (`invoice.total`, `lines[0].amount`, `invoice['due-date']`, `$` for the answer itself) with a `[*]` wildcard that yields a list; `+ - * / %` on `BigDecimal` (34 significant digits, `0.1 + 0.2 == 0.3` is true); `== != < <= > >=` (not chainable); `&& || !` with short-circuit; parentheses; nine functions — `sum`, `count`, `min`, `max`, `len`, `abs`, `round(x, n)` (half-up), `exists(path)`, `approx(a, b, tolerance)`. No script engine, no expression library, no reflection, no Qute; an unknown function is a compile-time error. JDK-only and Java 17 syntax so ClusterFuzzLite can compile a vendored copy.
* **Null semantics:** a missing path and a JSON `null` are both `null`; `== null` / `!= null` test it; any other comparison with `null` is `false`; arithmetic, logic or a function on `null`, a type mismatch, division by zero, an empty `min`/`max` and an out-of-range number are evaluation errors — *could not decide*, never `false`. `exists(path)` tells a present key holding `null` from a missing one.
* **Bounds:** expression ≤ 2000 characters, nesting ≤ 32, ≤ 500 parts, ≤ 32 segments per path (all refused at compile time with a position, never a `StackOverflowError`); ≤ 10,000 values per path, ≤ 200,000 steps per evaluation; numbers beyond 1000 digits or a ±1000 scale refused rather than materialised.
* **`ExpressionGuardrail`** (`modules/llm/guardrails/impl`, new bean, picked up by `GuardrailService`'s type index) — parameters `expr`, `issue` (`[A-Z][A-Z0-9_]{0,39}`), `fix` (≤ 1000 characters), all required and checked in `validate()` at deploy (`parameter 'expr' is not valid at position 21: '=' is not an operator; compare with '=='`). Compiled expressions sit in a bounded Caffeine cache (512, refusals cached too). The answer is read with `ModelOutputParser` (fence and prose tolerant) over its own exact mapper: decimals as `BigDecimal`, integers as `BigInteger`, duplicate keys refused. Verdicts: `true` → allow; `false` → `VIOLATION` `expression_failed:<ISSUE>` with a hint that is EDDI's fixed frame (the judge guardrail's wording) around the author's `fix` only; not JSON / > 262,144 characters / duplicate key → `GuardrailUndecidedException` `expression_unparseable`; evaluation error or a non-boolean result → `expression_undecided:<cause>` (the evaluator's own codes). `failMode` decides as for every type.
* **Fuzzing:** `SafeJsonExpressionFuzzTest` (Jazzer `@FuzzTest` over expressions and over JSON data, plus seeded random sweeps that run in every unit-test run) and a ClusterFuzzLite target `SafeJsonExpressionFuzzer`; `.clusterfuzzlite/SafeJsonExpression.java` is the vendored copy, and the `Vendored Fuzz Sources In Sync` guard knows the fourth file.
* **Docs:** [langchain.md](https://docs.labs.ai/agent-configuration/langchain.md#the-expression-type-a-deterministic-check-over-a-json-answer) (grammar, semantics, bounds, the invoice example and the exact corrective message), [security.md](https://docs.labs.ai/security-and-compliance/security.md) (sandboxed evaluator, closed vocabulary, fuzz targets), [security-review.md](https://docs.labs.ai/security-and-compliance/security-review.md).
* **End-to-end proof:** `ExpressionGuardrailIT` runs a real agent against a WireMock fake OpenAI endpoint: pass (also from a code fence), fail then repair (the second request carries the fixed frame around the author's `fix` and no computed value), exhausted reprompt and `block`/`warn` actions, non-JSON, duplicate-key and null-operand answers under both `failMode`s, exact decimal arithmetic (`0.1 + 0.2 == 0.3`, a one-cent difference caught), and deploy refusal for a syntax error, an over-long or over-deep expression, sandbox escapes and a bad issue code or fix.

### Design decisions

* **A new evaluator, not `ExpressionProvider`** (plan §9.1): that is the NLP expression grammar, with no arithmetic or paths into JSON. `PathNavigator` has only `+`/`-` on path values, no comparisons, logic or aggregates.
* **Could not decide is the safe default for anything ambiguous.** A missing amount inside `sum(...)` is not skipped, comparing a number with a string is not `false`: both are undecided, so a `reprompt`/`block` guardrail withholds the answer (fail closed) unless the author set `failMode: open`.
* **Closed vocabulary:** nothing read or computed from the answer — not the sum, not the total — reaches the corrective message. Only the issue code (author-declared, pattern-checked) reaches the audit reason.
* **Duplicate keys are unparseable**, so the check and a downstream reader of `convertToObject` cannot see two different totals.
* **No new meter**; `eddi.guardrail.triggered` counts the action as for every type.

### Manager and operator

* The guardrail editor offers `expression` on the output side (`guardrails.ts`: type list, phases, no-rewrite set, list-row summary `ISSUE · expr`, type text). Its sheet has fields for `expr`, `issue` and `fix`, and `expressionProblems()` mirrors `validate()`'s refusals (required, length caps, the issue-code pattern) as warnings; the expression's syntax is left to the server, which names the position at deploy. 16 new `llmEditor.grExpr*`/`grTypeExpression*` keys in all 11 locales. Tests: `guardrails-expression.test.ts` and an `expression` block in `task-guardrails-section.test.tsx`.
* The Platform Operator's prompt explains the type (parameters, the language, null rules, the reasons, closed-vocabulary feedback, deploy refusals with a position); `operator-revision.json` 36 → 37. #1121 also takes 37, so whichever merges second re-bumps.

### Next

* When #1121 lands, `expression` can use `onExhausted: deliver-best` like any reprompting type, and its `HINT_HEADER`/`HINT_FOOTER` can be shared with the judge's (same wording today).

***

## ✨ feat(llm): `judge` guardrail and `onExhausted: deliver-best` — evaluated generation E1a + E1b (2026-10-24)

**Repo:** EDDI (`feat/llm-judge-guardrail`) — item E1 (E1a and E1b; not E1c) of the evaluated-generation plan.

### What changed and why

A well-formed but wrong answer passed every output guardrail EDDI had: the built-ins check shape and patterns, the `classifier` checks safety. E1a adds a check on **meaning** whose feedback says what to fix; E1b lets a quality check that cannot be satisfied deliver its best attempt instead of a block message.

* **`GuardrailModelClient`** (`modules/llm/guardrails/impl`, package-private) — the classifier's model-call machinery, extracted rather than forked: `ChatModelRegistry` provider build with parameter pass-through (vault and `${vars}` resolved by the registry), `timeoutMs` capped at 60 s and bounded by the turn deadline, the virtual-thread executor, `promptTemplate` rendering with the screened text as data only (`{input}`, `{output}`, `{context}`), `includeRetrievedContext`, pricing from `inputPricePer1M`/`outputPricePer1M`, the unavailable/unparseable mapping (provider messages never propagated) and the per-call timer. `ClassifierGuardrail` now delegates to it; its behaviour, reasons, metric and test surface are unchanged (all 54 of its tests pass untouched). Each type passes its timer as `() -> Timer.builder(METRIC_DURATION)` so `MonitoringSeries` still finds the meter where it is named.
* **`JudgeGuardrail`** (`judge`, output only, `screensHistory()` false) — parameters `provider`, `promptTemplate` and `issues` (a JSON object of issue code → author fix text; 1–20 codes matching `[A-Z][A-Z0-9_]{0,39}`, fix text non-blank and ≤ 1000 chars, duplicate codes refused), plus the shared ones and a per-guardrail `jsonResponseFormat` override. After the rendered template EDDI appends a fixed instruction listing the codes and the reply shape `{"issues": [...]}`. The request carries a JSON response format per request through `JsonResponseFormatPolicy` — with the codes as an `enum` schema where the provider enforces one — never baked into the cached model. The reply is read with `ModelOutputParser` (fence, prose around the object), codes matched case-insensitively. Only a parsed empty list passes; any other shape or an undeclared code is `judge_unparseable`, an unreachable or slow judge `judge_unavailable` — `failMode` applies.
* **Closed-vocabulary feedback.** A finding is a `VIOLATION` with reason `judge_failed:<CODE>[,<CODE>…]` (declaration order) and a reprompt hint made of EDDI's frame and the author's fix texts for those codes only. `GuardrailService.correctiveMessage` is untouched, so its invariant — never the user's or the model's text — now also holds for judge output.
* **`GuardrailVerdict.issues`** — a sixth record component (the 5-argument constructor stays), plus `GuardrailVerdict.issues(...)` and `severity()` (0 = nothing found, the code count for a grading guardrail, 1 for any other finding).
* **`GuardrailConfig.onExhausted`** — `block` (default; also when unset) or `deliver-best`, plus `deliversBest()` (not a bean getter, never serialized). In `GuardrailService.runOutput`, a `deliver-best` reprompt guardrail records every attempt it rates; when it may not reprompt again (retries spent, no reprompter, or a reprompt that cannot start) the attempt with the lowest severity is delivered — ties to the later attempt, so a binary guardrail delivers the last — with a `warn` outcome, reason `<reason>:delivered_best`, `retryCount` = reprompts sent. That attempt is then **re-screened** by the output guardrails after the exhausted one, with no further reprompts — the ones before it already screened that attempt in the pass that rated it, so each guardrail sees it once and a model-backed one is called once: `redact` still rewrites, `warn` still records, `block` and `reprompt` findings block. The re-screen's outcomes are held back until it ends, so the `:delivered_best` warn is recorded only for an attempt that was actually delivered; a blocked one leaves the re-screen's records and the block, each counted once. A guardrail that could not decide is not "exhausted": its `failMode` applies as before. Because this lives in `runOutput`, it covers every mode output guardrails run in — plain, streaming (buffered), tool loop, cascade, HITL resume — and audit records, the ledger, SSE `guardrail_triggered` and `eddi.guardrail.triggered` stay on the one `emit` path.
* **Deploy time.** `GuardrailService.validate` refuses an unknown `onExhausted`, `deliver-best` on any action but `reprompt`, and `deliver-best` on input guardrails; `JudgeGuardrail.validate` refuses a missing `provider`/`promptTemplate`/`issues` and a malformed `issues`. New `GuardrailService.warnings` / `ContentGuardrail.warnings` (default none) are logged by `LlmTask.validateGuardrails`: `deliver-best` on a `classifier`, an unpriced judge, and a judge on the task's own provider and model (self-judging bias) — risks the plan's §8 lists.
* **Metric:** timer `eddi.guardrail.judge.duration{provider, outcome}` (`pass`, `fail`, `unparseable`, `unavailable`, `timeout`), mirroring the classifier's, with a panel on the Full Metrics dashboard next to it; `eddi.guardrail.triggered` counts the actions as before.
* **Docs:** [langchain.md](https://docs.labs.ai/agent-configuration/langchain.md#the-judge-type-grading-the-answer-with-issue-codes) (type row, `onExhausted` field row, the `judge` subsection, [When the retries run out](https://docs.labs.ai/agent-configuration/langchain.md#when-the-retries-run-out-onexhausted)), [security.md](https://docs.labs.ai/security-and-compliance/security.md) (closed vocabulary; a quality check never overrides a safety check), [metrics.md](https://docs.labs.ai/deployment-and-infrastructure/metrics.md).

### Design decisions

* **Deviations from the plan, and why.** (1) `onExhausted: "block"` is accepted on any action (it is the default and changes nothing); only `deliver-best` is refused outside `reprompt`, and also on input guardrails, where a reprompt blocks. (2) `deliver-best` also applies when no reprompt can run at all (no reprompter, out of time, open circuit), not only when `maxRetries` is spent — in each case the guardrail has nothing further to try. (3) An attempt the guardrail *passed* but another guardrail later sent back is still a candidate with severity 0; if chosen, the re-screen decides. (4) A per-guardrail `jsonResponseFormat` parameter was added as the escape hatch for providers the matrix does not know, mirroring the task setting. (5) The judge's default `timeoutMs` is 5000, not the classifier's 3000: a grading LLM is slower than a safety classifier. (6) The fix texts are also listed in the judge's instruction, so the judge knows what each code means. (7) The prices-missing and self-judging notes from §8 are WARN logs at deploy, not refusals.
* **The judge's free text never travels.** Extra keys in the reply object are ignored, never forwarded; only declared codes are kept, mapped to their declared spelling.
* **Unusable `issues` at run time** (a config that bypassed deploy validation) is `judge_unavailable`, before any model call.

### Manager

* The guardrail editor offers `judge` on the output side (`guardrails.ts`: type list, phases, no-rewrite set, row summary, type text) with its own settings panel: provider, base URL, model and API key (shared with the classifier panel through a new `ModelCallFields`, so both write the provider's own model and credential keys), the required prompt template, an **issue-code editor** (rows of code + fix text, written back as the `issues` JSON string; codes upper-cased; a stored value that is not an object of strings is shown raw rather than rewritten; duplicates stay visible and are reported), timeout (default 5000) and prices (shared `CallLimitFields`), retrieved context, and warnings mirroring the deploy checks (missing provider, template or codes, malformed codes, unpriced judge).
* **`onExhausted`** is a select under Max retries on an output `reprompt` guardrail: `block` is stored as absent, `deliver-best` as set, and switching the action away from `reprompt` drops it (as it drops `maxRetries`). `deliver-best` on a `classifier` shows the same warning the deploy logs.
* 28 new `llmEditor.*` keys in all 11 locales. Tests: `task-guardrails-section.test.tsx` (+11) and `guardrails-judge.test.ts` (5).

### Platform Operator

* `system-prompt.ts`: the guardrail bullet lists `judge` and `onExhausted` (what deliver-best delivers, that it is re-screened, what the deploy refuses and warns about); a new `judge` bullet covers its parameters, the `issues` format, the closed-vocabulary reprompt, the could-not-decide reasons and failMode, cost and the timer, and the self-judging note; the docs pointer names the new topics. No allow-list change: the operator already edits LLM configs through `PATCH`. `operator-revision.json` 36 → 37.

### Tests and checks

`JudgeGuardrailTest` (47: parsing — fenced, prose-wrapped, undeclared codes, wrong shapes, oversized replies; closed-vocabulary hint and corrective message; template data; native schema enum, provider matrix and override; parameter pass-through; cost; unavailable/timeout/deadline; failMode both ways; validate bounds; warnings), `GuardrailServiceDeliverBestTest` (13: selection, ties, default block, re-screen with redaction, block and reprompt, deploy refusals and the classifier warning), `LlmTaskGuardrailsTest` (+5: acceptance reprompt with the author's fix text and judge cost in `audit:cost`; deliver-best in plain chat with PII redaction, SSE and audit records; tool loop; cascade; configure refusals), `GuardrailConfigDeserializationTest` (+1). Mutation-checked: free judge text in the hint, an undeclared code accepted, a missing `issues` field read as a pass, the re-screen removed, and a reprompt finding let through the re-screen — each fails the suite.

* **End-to-end:** `JudgeGuardrailIT` (9, Mongo) runs a real agent against a WireMock OpenAI endpoint that plays both the task model and the judge (told apart by the request's `model`): a pass (judge reply in a code fence), fail-then-repair (the second task-model request carries only the author's fix text for the found code, never the judge's free text; call counts per model asserted), exhaustion with `deliver-best` (fewest codes wins) and with the default `block`, and bad judge output (unparseable reply, undeclared code, HTTP 500) under `failMode` closed and open. Outcomes are read back through the conversation REST API and the audit ledger.
* **Review fix (docs):** `deliver-best` is re-screened only by the guardrails after the exhausted one, so on a `classifier` it delivers what that classifier flagged. `docs/security.md`, `docs/langchain.md` and the operator prompt no longer claim a classifier is never bypassed; a safety classifier should keep `onExhausted: "block"`. Operator revision stays 37, fingerprint updated.
* **Merge with `main` (#1130, history-replay protection).** Conflicts in `GuardrailService` (both sides added methods next to `validate`: this branch's `onExhaustedProblem`/`warnings`, `main`'s `anySkipsHistory` — all kept), `LlmTaskGuardrailsTest` (an import) and `operator-revision.json`. Two semantic fixes the auto-merge did not show: #1130 taught `runOutput` to act on a fail-open guardrail's partial finding (`GuardrailUndecidedException.partialFinding`), and the deliver-best re-screen now does the same, so a pattern list that timed out part-way still applies its rewrite to the delivered attempt (`GuardrailServiceDeliverBestTest.partialFindingStillApplies`); and `ClassifierGuardrail` lost its last `TimeUnit` use to #1130's `RegexDeadline` switch, so the import went. The operator prompt keeps both sides' additions; `operator-revision.json` 37 → 38.

***

## feat(manager): Feedback page, rating triage and rating controls (2026-10-24)

**Repo:** EDDI (`feat/conversation-ratings`) — PR 3 of [`planning/conversation-rating-plan.md`](https://github.com/labsai/EDDI/tree/main/planning/conversation-rating-plan.md) (§8 and §0.1 "Admin — triage")

### What changed and why

The people running an agent can now see and triage what people said about it, in the Manager.

* **Feedback page** [`pages/feedback.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/pages/feedback.tsx) at `/manage/feedback` (route registry, sidebar, `SCREEN_ROLES` admin+editor). "Needs attention" first (NEW ratings that are low or commented, newest first) with per-row Mark reviewed / Reopen, internal note (≤ 2000), Open conversation (only when `canOpenTranscript`) and bulk review; "All ratings" with URL-synced filters, KPI tiles against the previous period, trend, distribution, top reasons, a by-version table greying buckets under 10 ratings, CSV export honouring `X-Ratings-Truncated`. A non-administrator is asked to pick an agent instead of hitting `AGENT_ID_REQUIRED`; a 409 `RATING_CHANGED` reloads and says so. Components under [`components/feedback/`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/components/feedback/README.md).
* **Attention badge** on the sidebar entry and a **dashboard tile**, administrators only, sharing one `ratingKeys.attention` query polled every 30 s.
* **Agent editor**: [`rating-config-section.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/components/editors/rating-config-section.tsx) for every `ratingConfig` field; [`lib/rating-config.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/rating-config.ts) mirrors `RatingConfigValidator` and the page refuses to save invalid values. **Agent detail** gets a 30-day feedback strip; **conversation detail** shows the conversation rating, review status and per-step reply thumbs.
* **Manager chat** gets the Chat UI's rating controls ([`chat-rating.tsx`](https://github.com/labsai/EDDI/tree/main/ui/packages/app-kit/src/components/chat/chat-rating.tsx), [`use-chat-ratings.ts`](https://github.com/labsai/EDDI/tree/main/ui/packages/app-kit/src/hooks/use-chat-ratings.ts), [`chat-rating-steps.ts`](https://github.com/labsai/EDDI/tree/main/ui/packages/core/src/rating-steps.ts)); snapshot messages now carry `stepIndex`.
* **API/hooks**: [`lib/api/ratings.ts`](https://github.com/labsai/EDDI/tree/main/ui/packages/app-kit/src/lib/api/ratings.ts), [`hooks/use-ratings.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/hooks/use-ratings.ts), `ratingKeys` in `query-keys.ts`. `ApiClientError` now carries the `code` of an `{error, message}` body (with tests), so callers branch on `AGENT_ID_REQUIRED` / `RATING_CHANGED` / `RATING_WINDOW_CLOSED` rather than on translated text.
* **Backend**: the `/ratings` endpoints take `conversationId` (filter + both stores + tests), so the conversation view does not list everything.
* MSW: [`test/mocks/rating-handlers.ts`](https://github.com/labsai/EDDI/tree/main/ui/packages/app-kit/src/test/mocks/rating-handlers.ts) with an in-memory store shaped like `RatingRow`; e2e spec `e2e/feedback.spec.ts`. i18n: 146 keys in all 11 locales.

### Design decisions

* No chart library is added: the trend and distribution are plain markup in the house style (as the Workforce analytics are), with numbers in text for screen readers. KPI tiles reuse `StatCard`.
* Bulk review of a *selection* PATCHes row by row (each conditional on the rating not having changed); "mark everything here" uses `POST /ratings/review` with the same filter.
* The CSV download uses raw `fetch` (blob body and a response header to read) with `api.getAuthHeader()`, like `backup.ts`.
* The Manager chat offers the card after *End conversation* (when `askOnEnd`) because it does not track the ENDED state otherwise; prompted-once state is per page, not persisted.

### Not done here

The Playwright spec could not run locally (the installed Chromium build is older than the one Playwright 1.64 expects); CI's `UI Manager E2E (MSW)` runs it. MCP tools and the Platform Operator are PR 4, alerts PR 5.

***

## feat(ratings): MCP rating tools and Platform Operator read access (2026-10-24)

**Repo:** EDDI (`feat/conversation-ratings`) — PR 4 of [`planning/conversation-rating-plan.md`](https://github.com/labsai/EDDI/tree/main/planning/conversation-rating-plan.md)

### What changed and why

Ratings can now be read and triaged from an MCP client, and the Platform Operator can answer questions about them.

* **MCP** — [`McpRatingTools`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/mcp/McpRatingTools.java): `list_conversation_ratings` (every `/ratings` filter incl. `needsAttention`, `reviewStatus`, `conversationId`; `sort`, `index`, `limit`), `summarize_conversation_ratings` (`groupBy`), `count_ratings_needing_attention` and `review_conversation_rating` (REVIEWED / NEW and a note). Registered in `McpToolFilter`; 89 → 93 tools, 292 arguments of which 128 are required.
* **Operator** — [`tool-scopes.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/operator/tool-scopes.ts) allow-lists `GET /ratings`, `GET /ratings/summary` and `GET /ratings/attention-count`; [`system-prompt.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/operator/system-prompt.ts) gains a ratings section (what a rating holds, `ratingConfig` and its defaults, needs-attention, `AGENT_ID_REQUIRED`, how to answer "how is agent X rated since version N"), gated on a new `grantsRatingReads` predicate. Operator revision 39 (37 when written; main had meanwhile claimed 37 too, so the merge made it 38, and clarifying the date-only `to` in the prompt made it 39).
* **Docs** — [MCP Server](https://docs.labs.ai/protocols-and-integration/mcp-server.md#rating-tools-4) (section, count, Author tier row), [Conversation Ratings](https://docs.labs.ai/conversations-and-orchestration/conversation-ratings.md#mcp-tools-and-the-platform-operator), and a "Feedback from users" section in the `eddi-admin` Claude Code skill.

### Design decisions

* **Access is the REST rule, run for the MCP caller.** The tools inject the in-process `IRestConversationRatingAdmin` bean — the pattern `McpAdminTools` uses with `IRestAgentAdministration` — not the loopback REST client, which sends no credentials (401 with authorization on, no scoping with it off). That bean's `ResourceAccessGuard` and `ConversationAccessGuard` read the request's `SecurityIdentity`, i.e. the MCP caller: admin sees everything, an editor names an agent it holds `EDIT` on, `userId` for admins only, `canOpenTranscript` as on REST. Nothing is re-implemented, so MCP cannot drift from the Feedback page.
* **Tier `McpRoles.AUTHOR`** (admin, editor) — equal to the REST `@RolesAllowed`, pinned by `McpRoleTierParityTest` (`IRestConversationRatingAdmin` added to the mirrors). `eddi-viewer` stays out.
* **Reviewer = the caller's plain principal** (`callerActor`), as on REST — not the HITL tools' `mcp:<principal>` form — so one person is one reviewer whichever surface they triage from.
* **Errors keep the REST codes** as `errorCode` (`AGENT_ID_REQUIRED`, `RATING_CHANGED`, `INVALID_PARAMETER`, …). A guard refusal (`io.quarkus.security.ForbiddenException`) is mapped to `FORBIDDEN` explicitly: left to `toolFailure` it is not "caller-facing" and would surface as `INTERNAL`.
* **No writes for the operator.** `PATCH /ratings/{ratingId}` and `POST /ratings/review` record the caller as the person who looked at the feedback, and a bulk review empties the queue in one call — that judgement stays with a human on the Feedback page. `GET /ratings/export` is a `text/csv` download of up to 100,000 rows (userIds included for an admin) that no chat answer needs. Both are documented as deliberate exclusions in the allow-list.
* MCP export and bulk review are left out too; both stay REST and Manager only.

### Tests

* `McpRatingToolsTest` (13) wires the real `RestConversationRatingAdmin` with mocked guards and store: role tier, `AGENT_ID_REQUIRED`, missing `EDIT`, userId redaction, admin cross-agent listing, grouping and the attention filter, reviewer from identity, `NOT_PERMITTED` for an agentless rating, `RATING_CHANGED` / `RATING_NOT_FOUND`, bad requests, non-leaking internal errors. Mutation-checked: 8 of 8 mutants killed by a test failure (role tier widened, role gate dropped, guard refusal not mapped to FORBIDDEN, agentId / needsAttention / conversationId not forwarded, REST code lost, empty review accepted).
* `McpRoleTierParityTest`, `McpToolContractTest`, `McpToolFilterCoverageTest` and `SkillToolReferencesTest` updated (`ratingConfig`, `canOpenTranscript` exempted as config/result fields).
* Manager: operator `tool-scopes` and `system-prompt` tests for the grant, the excluded writes/export and the gated section.

***

## ✨ feat(httpcalls): `forEach` — one call per element, every result collected (2026-10-24)

**Repo:** EDDI (`feat/step-checks-foreach`) — item E5 part A of the evaluated-generation plan

### What changed and why

`preRequest.batchRequests` only works with `fireAndForget`, so a call that needed one request per element of an array threw every response away. An httpcall now takes an optional `forEach` block that sends the call once per element and stores what each element produced — `index`, `ok`, `httpCode`, `body` or `error`, `timedOut`, `sent`, `attempts`, `bodyDropped` — as one array under `responseObjectName`, in source order whatever order the items finished in. `postResponse` runs once with `200` when every item succeeded and `207` (Multi-Status) when any failed, so property instructions gated on the default codes only see complete results unless the author opts in.

* **New field, not an extension of `batchRequests`.** A stored config with `batchRequests` on a call that waits for its response sends exactly one request today; reusing the field would have turned it into N requests silently. Without `forEach` nothing changes, and `forEach` is refused (400) together with `fireAndForget` or `batchRequests`.
* **Bounded four ways.** `maxItems` (the batch default 100 and ceiling 1000, refused as a whole before anything is sent), `maxConcurrency` (default 1 — the load the same calls written one after another would send; at most 16, on virtual threads), the turn deadline per item (an item whose turn comes after it is not sent), and memory: each body is capped by `maxResponseSizeInBytes` and all of them together by `maxTotalResponseSizeInBytes` (default the same value, so the array gets what one response would).
* **Never abandon paid work.** A failing item never cancels its siblings; the pool is shut down, never interrupted; `onItemFailure: "fail"` fails the step only after every item finished and the results are stored. When the step stops waiting, queued items are not started at all, so nothing is sent whose result nobody collects.
* **A request that threw is never retried** — a timeout above all, since the API may have processed (and billed) it. `retryApiCallInstruction` still applies per item to responses.
* **Security unchanged.** Every item's request is built on the turn's thread by the same `buildRequest` a single call uses (templating, vault/connection/caller resolution, SSRF check, approval scope); only sending is parallel. The element is bound as template data, never template source. A `forEach` call is unpinnable for HITL fingerprints, like a fire-and-forget batch.
* **Seams left for parallel work.** `BoundedFanOut.Admission` is asked before each item starts and told when it finished — where the per-conversation cost reservation (E4) plugs in. The fan-out runner is generic, so mcpcalls can reuse it. The deploy-time turn-budget warning counts a `forEach` call once per round.

**Files:** [`ForEachInstruction.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/apicalls/model/ForEachInstruction.java), [`ApiCall.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/apicalls/model/ApiCall.java), [`ApiCallExecutor.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/apicalls/impl/ApiCallExecutor.java), [`ForEachItems.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/apicalls/impl/ForEachItems.java), [`ForEachItemResult.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/apicalls/impl/ForEachItemResult.java), [`BoundedFanOut.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/runtime/BoundedFanOut.java), [`ApiCallsConfigurationValidator.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/apicalls/ApiCallsConfigurationValidator.java), [`RestApiCallsStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/apicalls/rest/RestApiCallsStore.java), [`TurnResilienceWarnings.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/TurnResilienceWarnings.java), [`docs/httpcalls.md`](https://docs.labs.ai/agent-configuration/httpcalls.md) (also drops a duplicated "Turn deadline" section), the Platform Operator prompt and revision.

### What's next

Part B of E5 — `checks` on httpcall and mcpcall results, reusing the output guardrail types — and `forEach` on mcpcalls are not in this change; the plan is in the PR description.

### End-to-end proof

`ForEachHttpCallsIT` drives a deployed agent over REST against WireMock: one request per element (templated into path and body, source order, read back from the stored conversation), a filter leaving index gaps, `maxItems` refusing the whole call before anything is sent, the total-size budget counting UTF-8 bytes of a non-ASCII payload, an empty list sending nothing, a 500 and a timeout not stopping or being retried, `207` gating of `postResponse`, `onItemFailure: "fail"` running every item first, and the concurrency bound (1 by default, 2 when configured) observed from WireMock's arrival times.

***

## ✨ feat(hitl,groups): humans and groups produce verdicts — revise with the note, rework within a run, stop on a verdict (2026-10-24)

**Repo:** EDDI (`feat/verdict-rework`) — item E2 of `planning/evaluated-generation-plan.md`.

### What changed and why

Three places where a check already ran but its verdict could not repair anything now can, each off by default.

**1. Single-agent HITL: `hitlConfig.onRejection: "REVISE"`** (decision 9.5: a `hitlConfig` policy, not a new verdict value). Under the default `SKIP` a rejected rule pause skips the remaining tasks, as before. Under `REVISE`, a rejection **with a human's note** has the same model revise the answer it gave before the pause: one tool-less re-ask over the frozen request that produced the draft (system prompt, history, retrieved context, tool results), the draft as the assistant turn and the note as the user turn, then the pipeline continues from the task after the model's, so a rule that paused on the draft pauses again on the revision. `maxRevisionsPerTurn` (1..10, default 3) bounds it.

* Scope: behavior-rule (`RULE`) pauses only. A rejected tool call (`TOOL_CALL`) is a rejected action, not a rejected answer, and already reaches the model as a tool result with the note; it is unchanged. A rejection without a note, an automated one (`system:*`), a Slack button (its note is its own attribution), a pause before any answer, an answer from a later task or workflow, an over-cap request, a spend refusal, a model failure, a failed `responseValidation` or a guardrail block all fall back to `SKIP`, and `hitl:revision:outcome` records which.
* The note is data: concatenated into the user message, never template source. The revision passes `responseValidation` and the output guardrails and asks the spend gate first; its tokens and cost are recorded like any answer's.
* The candidate (`HitlRevisionCandidate`) is recorded by `LlmTask` only while the policy is on, stamped with its pipeline position by `LifecycleManager`, and persisted by the RULE pause as step data `hitl:revision:candidate` — so it travels through both stores unchanged, is scrubbed of secret input and context with the step, is withheld from `returnDetailed` and from the approver's full snapshot, and is removed when the pause is decided. Cap `eddi.hitl.revision.transcript-max-bytes` (256 KB). The round count rides on the candidate, so the bound holds across re-pauses and reloads.
* New seam: `IAnswerRevisingTask` (implemented by `LlmTask`) and `ILifecycleManager.reviseAnswerAt`, which runs one task's revision with its audit entry and converts a later task's gated tool call into a TOOL\_CALL pause. Output that the draft and the tasks after it wrote is cut back before they run again.
* Records: `hitl.approval` carries `onRejection: REVISE`; meter `eddi_hitl_revision_total{outcome}`.

**2. TASK\_FORCE `maxReworks`** (group field, 0..5, default 0). A task that fails VERIFY returns to `ASSIGNED` with the verifier's feedback (`SharedTaskList.reworkTask`, the same transition and feedback channel as `onTaskRejection: RETRY`), the nearest EXECUTE phase runs it again inside the VERIFY phase and VERIFY checks it again, up to `maxReworks` times per task. Stopped by `maxTurns` (a round needs one turn per task plus the verifier's) and the cost ceiling; a rework that could not run ends `FAILED`, never stranded. Not applied when EXECUTE gates tasks for human approval. Counts persist in `taskList.reworkCounts` (additive, no schema bump: an older pod re-saving drops them, which fails soft). An unparseable verdict keeps the fail-open auto-verify but is now warned and counted (`eddi_group_verify_unparseable_total`); reworks are `eddi_group_task_reworks_total`.

**3. `convergence.mode: "VERDICT"`** on a repeating phase. The moderator reviews the latest repeat against the question and the phase ends once it passes (`{"passed": true}` as a JSON boolean; anything else keeps it going). `threshold` is unused and `minRepeats` may be 1. `"SIMILARITY"` stays the default, and an unknown mode is a save-time 400.

**Compatibility:** stored agent and group configs load and behave identically — `onRejection` absent is `SKIP` and captures nothing, `maxReworks` absent is 0, `convergence.mode` absent is `SIMILARITY` with the old `minRepeats` floor. Old pods ignore the new fields (`FAIL_ON_UNKNOWN_PROPERTIES` is off). The approval API (REST `/resume`, MCP `resume_conversation`, Slack buttons, Manager approvals) is unchanged in shape.

**Manager:** the agent HITL section gains "When a reviewer rejects" and "Revisions per turn"; the phase editor gains a convergence "Stop when" select (VERDICT hides the threshold, floor 1); Task force settings gain "Reworks after a failed verification". All 11 locales. **Platform Operator:** a cheatsheet entry for the three settings; revision 36 → 37. Four other open branches (E1c, E4, E5, #1121) also bump `operator-revision.json`, so whichever lands second must re-bump and refresh the fingerprint.

**Docs:** [`hitl.md`](https://docs.labs.ai/conversations-and-orchestration/hitl.md) (new "Revise with the reviewer's note"), [`group-conversations.md`](https://docs.labs.ai/conversations-and-orchestration/group-conversations.md) (rework within a run, `convergence.mode`), [`llm-resilience.md`](https://docs.labs.ai/agent-configuration/llm-resilience.md), [`metrics.md`](https://docs.labs.ai/deployment-and-infrastructure/metrics.md), [`configuration-reference.md`](https://docs.labs.ai/deployment-and-infrastructure/configuration-reference.md); three dashboard panels, synced to the Kubernetes copy.

### Verification

New tests: `LlmTaskHitlRevisionTest`, `ConversationHitlRevisionTest` (including a resume after a JSON and a BSON round trip of the paused snapshot), `LifecycleManagerRevisionTest`, `HitlRejectionPolicyConfigTest`, `TaskForceEngineReworkTest`, `ConvergenceVerdictModeTest`, plus Manager tests for the three editors. Nine mutants (revision bound, default policy, note requirement, automated decisions, per-task rework bound, `maxReworks` default, rework turn budget, convergence default mode, boolean-only verdict) are each killed.

* End-to-end ITs on MongoDB and PostgreSQL (`HitlRevisionIT`, `GroupVerdictIT` and their `postgres/` twins), with WireMock as the model: a rejection with a note revises over the frozen request (the note and the draft reach the model, the candidate and its round count survive the store across both pauses, approval delivers the revision only), `no_note` and `exhausted` skip; VERDICT convergence stops on a JSON `"passed": true` while prose, a string `"true"` or a failing judge run every repeat, and an unknown mode is a 400; TASK\_FORCE `maxReworks` sends a failed task back with the verifier's feedback and persists `taskList.reworkCounts`. Not persisting the candidate, dropping the rework feedback and never passing a verdict each fail them.
* **Fix — the raw read leaked the frozen request.** `GET /conversationstore/conversations/{id}` (the owner's and the Platform Operator's raw read) served the paused step's `hitl:revision:candidate` whole, so its `transcriptJson` — the compiled system prompt and every tool result — reached anyone allowed to read the conversation, in `result` and again in the `possibleResults` copy. `ConversationMemoryUtilities.redactRawPendingToolCallsForRead`, already the raw surface's single redaction point for the tool-call batch, now also withholds the candidate's frozen input (`REVISION_CANDIDATE_FROZEN_INPUT_FIELDS`) on every step and the redo cache, keeping the draft and bookkeeping. The other surfaces were already safe: `returnDetailed` (REST, MCP `read_conversation`, the Manager's inspector and the `/simple` read) drops the key, `approval-status?detail=full` (REST and MCP) removes the candidate, and the GDPR export carries only `conversationOutputs`. `ConversationMemoryUtilitiesRevisionRedactionTest`; `HitlRevisionIT` asserts no candidate entry carries the transcript or the system prompt while the revision request still carries it. **Not changed, and older than E2:** the raw read still serves `audit:compiled_prompt`, the LLM task's own audit step data (written on every answered turn while the audit ledger is on), which holds the same compiled system prompt; the IT pins that this is the only place it appears. Whether the raw read should drop `audit:*` like `returnDetailed` does is a separate decision. `hitl.md` now says `hitlDecision` reads `REJECTED` only until the revision is decided.

### What's next

The judge machinery of E1 (#1121) could serve as VERIFY's and VERDICT's verdict parser, and the agent-testing harness's LLM-as-judge expectation should reuse it. A failing VERDICT review is recorded but not shown to the members of the next repeat; feeding it back is a follow-up.

***

## 📝 docs(planning): white-labeling plan for every UI (2026-10-24)

**Repo:** EDDI (`feat/white-label-ui`)

### What changed and why

Added [`planning/white-label-ui-plan.md`](https://github.com/labsai/EDDI/tree/main/planning/white-label-ui-plan.md): an inventory of every place the Manager, the Chat UI, the backend-served pages, the Platform Operator and the Keycloak login theme show the EDDI brand, and a phased design to replace it with an admin-defined brand without a rebuild or restart.

### Design decisions

* The brand is one database document edited on a Manager **Settings → Branding** page. `eddi.branding.*` properties seed it, and `eddi.branding.locked=true` makes them authoritative for GitOps installs.
* Delivery stays same-origin: fixed `/branding/*` asset URLs with a bundled fallback, a runtime `/branding/__brand__.js` plus `/branding/brand.css`, and serve-time `<head>` substitution in the HTML shells. The CSP does not change.
* Technical identifiers (`eddi.*` properties, `X-EDDI-*` headers, storage keys, postMessage types) are contracts and are not renamed.
* "Powered by EDDI" is switchable and on by default. The update check stays opt-in, and its UI is hidden when branded. The docs link is parked.
* The branding endpoints are deliberately left off the Platform Operator's allow-list.

### Next

Phase 1 of the plan, the backend brand store and delivery.

***

## 🎨 feat(branding): brand store, admin REST and same-origin delivery — white-label phase 1 (2026-10-24)

**Repo:** EDDI (`feat/white-label-ui`)

### What changed and why

Phase 1 of the [white-labeling plan](https://github.com/labsai/EDDI/tree/main/planning/white-label-ui-plan.md): the backend brand store and its delivery to every UI. With no brand set, nothing visible changes. The page is [White-Labeling](https://docs.labs.ai/deployment-and-infrastructure/white-labeling.md).

* **Brand store.** `configs/branding`: one `BrandDocument` per deployment, behind `IBrandingStore`. It has a MongoDB `BrandingStore` (collections `branding` and `brandingassets`) and a `PostgresBrandingStore` (tables `branding` and `branding_assets`), picked in `DataStoreProducers`. Images are stored per slot (`logo`, `logoDark`, `icon`, `favicon`, `ogImage`, a closed enum); the document holds only their `sha256:` hashes. Writes are compare-and-set on the revision.
* **`BrandingConfig`** (`@ConfigMapping`, `eddi.branding.*`) seeds every field the stored document leaves unset. With `locked=true` the properties are authoritative.
* **`BrandingService`** is the single entry point (`current(BrandRequest)`). It resolves locked → document → seed → defaults field by field, and validates writes and the seed with one validator (`BrandValidator`, `BrandAssetValidator`); an invalid seed fails startup naming the property. It caches for 30 s with immediate local invalidation, answers 409 on a stale revision or when locked, and writes an INFO audit line.
* **Admin REST** `IRestBrandingAdmin` at `/administration/branding` (`eddi-admin`): `GET`, `PUT`, `DELETE`, and `PUT`/`DELETE /assets/{slot}`.
* **Public delivery** `IRestBranding` at `/branding/*` (`@PermitAll`, hidden from OpenAPI): the five images with a bundled fallback, plus `__brand__.js` and `brand.css`. `/branding/*` joins the static-assets permit list and the micrometer path patterns.
* **Head substitution.** The five shells (`manage`, `welcome`, `workforce`, `chat`, root `index.html`) carry `%BRAND_PRODUCT_NAME%`, `%BRAND_TAGLINE%` and `%BRAND_THEME_COLOR%`, `/branding/*` favicons, the brand script and the brand stylesheet. `BrandedShellRenderer` fills them in, HTML-escaped and cached per (shell, revision), for the four shell resources. `BrandedShellRoute`, a Vert.x route, does the same for the static `/`, `/index.html` and `/<shell>.html` paths.
* **One JS-string escaper,** `JsGlobalScript`. `__auth_config__.js` and `/chat/__config__.js` moved onto it with byte-identical output.
* **Dev server.** `scripts/vite-plugin-brand.mjs` in both UIs fills the defaults and serves `/branding/*` under `npm run dev` and MSW mode. A test in each UI runs a real `vite build` over the real shells and checks that the placeholders survive and that `brand.css` comes after the bundle's stylesheet. The MSW passthrough list gained `*/branding/*`.
* **Docs:** `docs/white-labeling.md`, a White-labeling section in `configuration-reference.md`, and `SUMMARY.md`. `ConfigurationReferenceCoverageTest` now reads `@ConfigMapping` interfaces, so mapped properties are held to the same documented-and-real rule as `@ConfigProperty` ones. `ReservedPrincipalsTest` classifies `sha256:` (the image hash) as a non-principal prefix.
* **Verified through the persistence boundary.** `BrandingStoreMongoIT` and `BrandingStorePostgresIT` share one contract (`BrandingStoreContract`). Their first run found `isEmpty()` serialized as an `"empty"` property that the reader then refused, so every stored brand was unreadable; `BrandingJsonTest` now pins the round trip without Docker.

### Design decisions

* **Field-wise merge, and a monotonic revision.** A `null` in the document means "the seed's value, else EDDI's". Reset writes an empty document under the next revision rather than deleting it, so caches keyed on the revision can never serve a stale page.
* **`brand.css` is linked as the first child of `<body>`, not in `<head>`.** Vite injects the bundle's stylesheet at the end of `<head>`, so a `<head>` link would come first and lose to the bundle's `.dark` block. The build test pins the order.
* **Per-shell default taglines** (`BrandedShell`) keep every unbranded description byte-identical. The welcome and chat descriptions differed before branding existed.
* **`/branding/favicon.ico` for the chat shell,** which already used an ICO. The favicon falls back to the icon, and the dark logo and og-image fall back to the logo, so a brand with only a logo and an icon leaves no EDDI image behind.
* **The SVG filter is stricter than the plan.** On top of `<script>`, `<foreignObject>`, `on…=`, `javascript:` and external `href`, it refuses namespace-prefixed elements, `<animate>`/`<set>`, entity declarations, character references (which would hide `javascript:` from a text check), `@import` and external CSS `url()`.
* **`brand.css` also sets `--color-sidebar-accent-foreground`**, so the sidebar accent keeps the brand's contrast pair.
* **Not on the Platform Operator's allow-list** (plan R9). `openapi-operations.json` gains the five admin operations.

### What's next

Phases 2–7 of the plan, starting with the Manager token cleanup.

***

## 🐛 fix(agent-tests): mocked httpcall tools keep their postResponse, runs can be cancelled, replicas stop aborting each other's runs (2026-10-24)

**Repo:** EDDI (`fix/agent-tests-fidelity`)

Review follow-ups to the agent regression harness (PR #1065).

### What changed and why

* **An httpcall mocked on the LLM tool path now runs its response handling.** `ToolLoopRunner` answered every mocked LLM tool call itself, before any executor, so for an httpcall tool `saveResponse`, retries and `postResponse` property instructions never ran: an agent that sets a property from a tool's response behaved differently mocked than live, and its `properties` expectations failed. The call is still decided and recorded once in `ToolLoopRunner` (`ToolMockRegistry.decideToolCall`); a `MOCKED` decision for an executor that implements the new `MockAwareToolExecutor` (the httpcall tools of `HttpCallToolsProvider`) is handed to it, and `ApiCallExecutor` answers the call with it — no request built — exactly as it already did for a rule-triggered call. Refusals (unmocked, fail-closed) and every other tool source short-circuit as before. A mocked call is uncached and unpriced.
* **A retried mocked call is recorded once.** `ApiCallExecutor` intercepted inside the retry loop, so each retry was recorded again and counted against `maxToolCalls` (and a retried unmocked call produced several `unmockedTool` failures). The decision is made once per call, as a retried live call is one call.
* **Cancel.** `POST /agenttests/runs/{runId}/cancel` and the MCP tool `cancel_agent_test_run` (author tier, EDIT on the agent — what starting one takes) stop a run cooperatively: no further turn starts, a waiting turn is abandoned, its conversations are ended and deleted, and the run ends with the new status `CANCELLED`. Before, a run of up to 2,000 turns × 900 s held one of two run slots until the node restarted. Manager: a **Cancel run** button on a running run, the `CANCELLED` badge and notice (11 locales).
* **Orphan recovery is owner- and heartbeat-aware.** At startup every `RUNNING` run was marked `ABORTED` and its conversations deleted — wrong when several replicas share one database without cluster mode. A run now records `ownerNode` (`<nodeId>/<bootId>`) and refreshes `heartbeatAt` every 30 s; a node aborts only a run of an earlier boot of itself or one whose heartbeat is older than three minutes, at startup and every three minutes.
* **Capacity before the deploy.** `AgentTestService` checked the run slots after deploying the version to `test`, so a request refused with 429 had already changed what the `test` environment serves.
* **Reserved test user ids.** A conversation started from outside as `agent-test:<liveRunId>:c:r` joined that run's mock session and wrote into its results. `OwnershipValidator.validateAndResolveUserId` now refuses any requested user id in that namespace (403), for an admin and with authorization off too.
* **A permanent delete removes memory checkpoints.** `ConversationPurgeService.purge` (every permanent conversation delete, not only test runs) left the checkpoints the tool loop writes before every tool call; only GDPR erasure removed them.
* **PostgreSQL IT and a two-turn case.** `PostgresAgentTestSuiteIT` runs the harness IT against PostgreSQL; `AgentTestSuiteIT` gained a two-turn case.
* **Docs.** `agent-testing.md`: the Manager page is shipped (not a follow-up), the "a mocked httpcall is still built" limitation was wrong and is replaced, cancel and the liveness rules are documented, and test conversations are noted to appear in listings and metrics while a run is in progress.

### Design decisions

* The mock rides into `ApiCallExecutor` in the template data (`ToolMockRegistry.TOOL_PATH_MOCK`), next to the existing `TOOL_PATH_MARKER`, rather than through a `ThreadLocal`: the executor runs on the tool-timeout thread.
* Cancel is node-local. A cancel arriving at another replica answers 409 naming the owner; a cross-node flag would race the heartbeat's whole-document writes.
* A run recorded before 6.6 (no owner, no heartbeat) counts from its `startedAt`.

**Files:** [`ToolLoopRunner.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/ToolLoopRunner.java), [`MockAwareToolExecutor.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/MockAwareToolExecutor.java), [`HttpCallToolsProvider.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/HttpCallToolsProvider.java), [`ApiCallExecutor.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/apicalls/impl/ApiCallExecutor.java), [`ToolMockRegistry.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/agenttests/ToolMockRegistry.java), [`AgentTestRunner.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/agenttests/AgentTestRunner.java), [`AgentTestService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/agenttests/AgentTestService.java), [`AgentTestRunRecovery.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/agenttests/AgentTestRunRecovery.java), [`ConversationPurgeService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/memory/ConversationPurgeService.java), [`OwnershipValidator.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/security/OwnershipValidator.java), [`agent-testing.md`](https://docs.labs.ai/conversations-and-orchestration/agent-testing.md)

***

## 🐛 fix(agent-tests): review follow-ups — skew-proof orphan detection, CAS heartbeats, reserved ids at schedules (2026-10-24)

**Repo:** EDDI (`fix/agent-tests-fidelity`)

### What changed and why

* **Recovery can no longer abort a live run.** Staleness compared another node's `heartbeatAt` with the local clock (clock skew or a short write outage aborted a live run and deleted its conversations), and the "earlier boot of this node" rule needed no heartbeat at all — two EDDI processes on one host share a host-derived node id and aborted each other's runs. Now a run is an orphan only when its heartbeat has not *changed* across this node's own sweeps for 3 minutes (90 s for the same node id, another boot), timed on the observer's monotonic clock; the sweep runs every minute.
* **Heartbeat, abort and final write are compare-and-swaps on `heartbeatAt`** (`IAgentTestRunStore.updateIfHeartbeat`, `storeIfFieldEquals`). An abort clears the heartbeat; the owner's next beat then fails, and the owner stops the run and writes nothing back — the record no longer flips from `ABORTED` to `RUNNING`.
* **Abandoned turns.** A turn given up on (timeout or cancel) can finish after its conversation was deleted; once it completes, the conversation is deleted again.
* **Tool calls are recorded after the loop's gates.** A mocked httpcall tool (or a live call) refused by the tool budget, tenant quota or turn deadline no longer counts as a call (`ToolMockRegistry.previewToolCall` / `recordToolCall`).
* **Reserved `agent-test:` ids** are also refused at REST schedule save and at every schedule fire — including a persistent schedule that reuses its stored conversation and a Dream consolidation fire, which never start one — and `OwnershipValidator` checks the resolved id as well as the requested one.
* **A non-`MockResult` under the tool-path mock key never mocks**: the call is treated as undecided — refused in a test conversation, sent in any other.
* **Permanent delete removes HITL tool-journal entries** too, as GDPR erasure does.
* **Platform Operator** may cancel a run (`POST /agenttests/runs/{runId}/cancel`, gated) and knows the terminal statuses; revision 37.
* **i18n:** `ABORTED` is "interrupted" in de, es, pt, hi, th and ar, so it no longer reads the same as `CANCELLED`.

**Files:** [`AgentTestRunRecovery.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/agenttests/AgentTestRunRecovery.java), [`AgentTestRunner.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/agenttests/AgentTestRunner.java), [`AgentTestRunStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/agenttests/AgentTestRunStore.java), [`ToolLoopRunner.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/ToolLoopRunner.java), [`ScheduleFireExecutor.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/runtime/internal/ScheduleFireExecutor.java), [`ConversationPurgeService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/memory/ConversationPurgeService.java), [`agent-testing.md`](https://docs.labs.ai/conversations-and-orchestration/agent-testing.md)

***

## 🐛 fix(tenancy): the cost gates fail closed on both datastores, and undo no longer refunds spend (2026-10-24)

**Repo:** EDDI (`fix/cost-gate-consistency`)

### What changed and why

Follow-ups to the tenant monthly cost budget and the per-conversation cost ceiling.

* **The pre-call cost gate answered a store outage differently per backend.** `PostgresTenantQuotaStore.getMonthlyCost` caught the `SQLException` and returned `0.0`, so the gate read "nothing spent" and allowed every model and tool call (fail open). `MongoTenantQuotaStore.getMonthlyCost` did not catch the `MongoException`, and `LlmTask` asks `LlmSpendGate` outside its guarded model phase, so the turn failed instead of serving the fallback answer. [`tenant-quotas.md`](https://docs.labs.ai/security-and-compliance/tenant-quotas.md) promised fail closed. Both stores now raise `QuotaAccountingUnavailableException`, as their `getQuota` already did ([`ITenantQuotaStore`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/tenancy/ITenantQuotaStore.java) documents the contract), and [`TenantQuotaService.checkCostBudget`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/tenancy/TenantQuotaService.java) turns it into a refusal flagged `accountingUnavailable`, counted on `eddi.tenant.quota.unavailable{type=cost}`. An exception that still escapes the check is a defect, not an outage. [`LlmSpendGate`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/LlmSpendGate.java) and the tool-call gate in [`ToolLoopRunner`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/ToolLoopRunner.java) both refuse it (the fallback answer, a tool error result) under a separate reason, `tenant_check_error`. It is counted on `eddi.llm.spend.refused` and logged at ERROR, with the stack trace at most once a minute. It does not pass for an outage on `eddi.tenant.quota.unavailable`.
* **say → undo → say discarded spend.** The ceiling summed `audit:cost` over the live steps. Undo moved the priced step to the redo cache, and the next say cleared it, so a public `/undo` reset what a conversation had spent. [`ConversationMemory.startNextStep()`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/memory/ConversationMemory.java) now carries the discarded steps' spend onto the new step as `audit:discarded_cost`, a new key in [`MemoryKeys`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/memory/MemoryKeys.java) that is persisted with the step. The ceiling counts `audit:discarded_cost` and the redo cache, which a rerun runs against. The snapshot's conversation total counts both as well, so it no longer drops between an undo and the next say; it is read by the Manager, the group cost ledger, Slack and schedule deltas. Redo leaves the total unchanged, and a rerun already added to the step's own `audit:cost`.
* **Undo and redo kept the wrong `audit:pending_cost`.** `TurnCostMeter` reads the owed tenant charge from the newest step that has one, and undo and redo reorder those steps. An undone step's pending charge was lost on the next say. A rerun after an undo re-charged an amount the undone step had already recovered. A rerun's own outage charge was then shadowed by the undone or redone step's older value. Undo and redo now copy the pending value of the step they move aside onto the step that becomes current, `0.0` included. That step always holds the newer of the two values, and both writes are full replaces, so the copy is persisted.
* **Dream charges lost to an outage** are carried in [`DreamService`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/runtime/internal/DreamService.java) (node-local, in-process) and added to the next priced consolidation charge. The docs say a restart loses it.
* **Manager quotas page.** The cost-budget status checked "unlimited" before "enforced", so a disabled tenant with no budget was told its spend was metered, although `recordCost` records nothing while enforcement is off. Enforcement is checked first, with a new `quotas.budgetDisabled` message in all 11 locales. Amounts under $1 keep up to four decimals, so $0.006 against a $0.01 cap no longer reads "$0.01 of $0.01 … $0.00 left".
* `TurnCostMeterTest`'s outage test claimed the marker is left untouched. It advances, as the class documents, and the test now says so and asserts it.
* `ReservedPrincipalsTest` (inherited from main) declared the `"sha256:"` prefix twice, once for brand image hashes and once for mail Message-IDs. `Map.ofEntries` rejects duplicate keys, so the class failed to initialise. The two entries are now one, whose description covers both uses.

### Decisions

* `LlmSpendGate.countMidLoop` stays on `Metrics.globalRegistry`. Its caller, `ToolLoopRunner`, is not a CDI bean and is built without a registry in `AgentOrchestrator` and a dozen tests. That is the same idiom as `LifecycleManager`, and Quarkus adds its registry to the global composite. The Javadoc now says so.
* The old-JSON round trip for `maxCostPerConversationUsd` already existed (`ConversationCostCeilingTest.storedConfigCompatibility`), so no test was added for it.
* Not added: an IT of the full deployment path, from a priced model through `ConversationService` to a refused tool call. The existing IT scaffolding has no priced model to drive through the service. The store-level halves are covered for both datastores in `TenantCostMeteringIT`: a monthly-cost read that fails at the gate, and say → undo → say persisted through the real conversation store.

**Docs:** [`tenant-quotas.md`](https://docs.labs.ai/security-and-compliance/tenant-quotas.md), [`langchain.md`](https://docs.labs.ai/agent-configuration/langchain.md#per-conversation-llm-cost-ceiling), [`metrics.md`](https://docs.labs.ai/deployment-and-infrastructure/metrics.md).

***

## 🔒 fix(guardrails): a blocked message no longer reaches the model on the next turn (2026-10-24)

**Repo:** EDDI (`fix/guardrail-history-replay`)

### What changed and why

Review of the input/output guardrails (#1064, #1112) found that a message the `classifier` guardrail **blocked** was sent to the main model on the following turn. An input block is served as a fallback; the history builder merges a fallback turn's question into the next user message so roles keep alternating; input guardrails treat that merged text as history, and history is only re-screened by guardrails with `screensHistory() == true` — which the classifier is not (one model call per history message would multiply its cost). So: an injection blocked on turn N, then "hi" on turn N+1, and the model received the injection. The same path undid a classifier `redact`.

* **A durable marker, not re-screening.** When an input guardrail blocks — or redacts with a guardrail that does not re-screen history — `LlmTask` flags the step `llm:input_withheld:<taskId>` (`MemoryKeys.LLM_INPUT_WITHHELD_PREFIX`). `ConversationLogGenerator.isInputWithheldStep` reads it (and, for steps written before it existed, an `audit:guardrail:input:*` record with action `block`). Both history paths (`ConversationLogGenerator.generate` with `skipFallbackOutputs`, `ConversationHistoryBuilder.generateMessagesFromOutputs`) replace that turn's user message — text, extracts and input files — with `[earlier message withheld by a guardrail]`, for every guardrail type. The rolling summarizer's input and the recall tool get the same view through `ConversationLogGenerator.modelFacingOutputs`. Memory and the human transcript keep the message.
* **Current-turn text is located structurally.** `AttachmentForwarder` appends extract/note text parts behind the typed text, so "the last text part" used to be the extract: a first-pass redaction was not applied to what the model saw, and the classifier screened the extract instead of the typed text. `LlmTask` now records the typed text's content index before forwarding; `GuardrailService.runInput` applies the (reused) first-pass result to it and screens each attachment text part after it as this turn's input — recorded, able to block.
* **Bounded author regexes.** `regex-filter` and `prompt-injection` patterns run through a shared deadline-checking matcher (the classifier `labelPattern` one, later folded into `RegexDeadline`) with 250 ms per text; past it the guardrail throws `GuardrailUndecidedException("pattern_timeout")`, so `failMode` applies — a `block` guardrail refuses the text instead of passing it. Both types now `validate()` their patterns, so an invalid one fails the deploy instead of being dropped (which left a block-only filter that never fires).
* **Spend gate first.** The spend gate is asked before the input guardrails and retrieval, so an over-budget turn pays no classifier call or embedding query; every guardrail reprompt asks it again.
* **`postResponse` after an input block.** It now runs, as after every other fallback (output block, spend refusal, `onError`), so a `convertToObject` + `addToOutput: false` task whose `postResponse` builds the reply answers the user instead of showing nothing — and the docs' claim that the `fallbackField` shape is what `postResponse` reads is now true for both sides.
* **History-screening cost** is recorded whether or not the guardrail fires.

### Review follow-ups

* **A withheld turn's files stay out too.** `AttachmentContextExtractor.attachmentsFromPreviousTurns` skips withheld steps (no re-inlined image, no "files shared earlier" note), and `ReadAttachmentTool` is built with `withheldStorageRefs` so `listAttachments`/`readAttachment` cannot hand a blocked file's content back as an unscreened tool result.
* **The current turn is not withheld by its own flag** — a second LLM task of the same turn decides it with its own guardrails (both history builders skip the last output index).
* **Spend gate asked twice**: before the input guardrails and again after them, so a classifier's price cannot carry the model call past a ceiling. A turn refused before screening is flagged withheld when a configured input guardrail does not re-screen history (it was never classified).
* **One regex deadline helper.** `BoundedRegex` is folded into `ai.labs.eddi.utils.RegexDeadline` (now with a deadline-preserving `subSequence` and `matcher(...)`); [`security.md`](https://docs.labs.ai/security-and-compliance/security.md#parser-and-matcher-bounds) lists the guardrail patterns' bound. A pattern timeout in a `regex-filter` keeps what the finished patterns found (`GuardrailUndecidedException.partialFinding`): failing open, a `redact` keeps those rewrites and a `block` that matched still blocks.
* **Docs**: template data (`{memory.last.input}`, `{memory.past}`, `{conversationLog}`, captured properties) is *not* filtered — don't template earlier user input into a guarded task's prompt or `httpCall` body; a turn on which the guarded task did not run was never classified.
* Persistence round trip and undo/redo of the flag through the real `ConversationMemory` (`InputWithheldRoundTripTest`); the Platform Operator's guardrail paragraph learned the pattern budget, the deploy-time pattern check and the withheld placeholder.

**Deferred:** a reprompted answer is still not re-run through `responseValidation` (its re-ask loop does not return to the output guardrails, so wiring the two together is not a small change); documented in [`langchain.md`](https://docs.labs.ai/agent-configuration/langchain.md#where-guardrails-run).

**Files:** [`GuardrailService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/guardrails/GuardrailService.java), [`LlmTask.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/LlmTask.java), [`ConversationLogGenerator.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/memory/ConversationLogGenerator.java), [`ConversationHistoryBuilder.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/ConversationHistoryBuilder.java), [`RegexDeadline.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/utils/RegexDeadline.java), `RegexFilterGuardrail`, `PromptInjectionGuardrail`, `PatternCache`, `ClassifierGuardrail`, `ConversationSummarizer`, `ContextualToolsProvider`, `MemoryKeys`; docs [`langchain.md`](https://docs.labs.ai/agent-configuration/langchain.md#input-and-output-guardrails).

***

## 🐛 fix(webhook): the replay-protection cache could evict live keys, was per node, and a few edges leaked or orphaned (2026-10-24)

**Repo:** EDDI (`fix/webhook-dedup-replay`)

### What changed and why

Review of the signed inbound webhook channel (#1059) found that its de-duplication - the only replay protection of the `github` and `generic-hmac` schemes, and a second line for `eddi-v1` - was weaker than documented.

* **Dedup cache sizing and admission.** `webhook-event-dedup` had no size entry in `CacheFactory`, so it inherited the 1,000-entry default and was shared by every webhook integration, each delivery storing up to two keys. About 500 deliveries in ten minutes from any one integration evicted another's keys, after which a captured request ran again. The cache now has its own entry and is rate-sized like the A2A nonce cache (100 keys per second over the 10-minute window, factor-two head-room: 120,000 entries), and the handler **refuses instead of evicting** (an evicted key is a replayable request, a refused delivery is only a retry), per integration so that one sender cannot push the others out:
  * Each integration has its own budget, `platformConfig.maxDeliveriesPerWindow` (default 3000 deliveries per 10 minutes, validated 1 to 100000 at save), counted over a rolling window of 11 one-minute buckets (longer than the 10-minute key lifetime, so a delivery is counted as long as its keys exist). A delivery that is not accepted (429, 503, ...) gives its slot back, so a sender looping on a quota refusal keeps seeing the real refusal. The counters are a bounded Caffeine cache that expires idle integrations.
  * From half capacity, an integration above its fair share (half the cache divided by the active integrations, counting only those with 50 or more deliveries in the window, so throwaway integrations cannot shrink anyone's share) is refused even inside its own budget.
  * From 90% of capacity every new delivery is refused, whatever its integration holds - a last resort that keeps the cache clear of eviction.
  * Repeats of remembered deliveries are always answered, and the repeat check runs only when a refusal is pending, so an admitted delivery costs no extra cache read (in a cluster, no extra NATS round trip).
  * Refusals are their own metric outcome, `refused_capacity` (`metrics.md`, dashboard), and the `WARN` is limited to once a minute per integration. `ICache.size()` stays a cheap estimate; the new `ICache.sizeExact()` sweeps expired entries and is read only once the estimate reaches the threshold, so a refusal cannot outlast the data.
  * In a cluster the budgets and the thresholds are per node: the counters are node-local and the cache size read is the node-local view (documented).
* **Cluster.** `webhook-event-dedup` joins `slack-event-dedup` in the shared `DEDUP` NATS KV bucket (same 10-minute TTL), so a replay is caught on whichever node it hits. With NATS unreachable each node falls back to its own cache, as for Slack.
* **Unsigned routing headers.** Binary-mode `ce-type`/`ce-id` and the plain-mode event-type header are outside every scheme's MAC. The replay key is already derived from the MAC alone, so within the window the same signed body is a duplicate whatever header it arrives with (now covered by tests at handler and endpoint level); the page now says plainly that routing headers are unsigned, what that means (tampering in transit can re-route a body without breaking the signature) and what to do (TLS, route on a field of the signed body). No wire-protocol change and no new signing scheme.
* **Orphaned conversations.** A `429` (or any refusal) from the turn after `startConversation` left one empty conversation per retried delivery. The conversation just created is now ended when its first turn is refused; a correlated conversation is kept, since the retry reuses it.
* **Weak or plaintext signing secrets.** Save-time validation already requires a vault reference, but a ZIP import or direct store write bypasses it, and no length was checked anywhere. The router now refuses to hand the verifier a plaintext secret, a reference that did not resolve (left unchanged by resolution, also with surrounding whitespace) or a resolved one shorter than 16 characters; the verifier independently rejects anything still containing a `${vault:` reference (the integration answers `401`, with one `WARN` per integration).
* **Id probing.** An unknown integration id answered `404` before the signature was looked at. It now answers `401` with the same body as a bad signature (the log keeps the distinction). The Slack endpoint likewise answers a uniform `403` for anything it cannot verify.
* **Two meanings of `409`.** The body now carries `reason`: `in_progress` (retry in 5 seconds) or `awaiting_approval` (a human has to decide). The status code is unchanged.
* **Behaviour change for 6.6.0 installs:** a webhook integration whose vault secret is shorter than 16 characters used to work and now answers `401` to every request (as does a plaintext secret that reached the store through import). Find them with the log line "signing secret is shorter than" (one WARN per integration version, repeated after a vault secret change) and rotate to 32 random bytes. Saving such a secret is now refused with 400 when it already exists in the default-tenant vault; references to another tenant are not resolved at save time (that would let any editor probe other tenants' secrets), so the router's runtime check is what covers them.
* The Platform Operator prompt now knows the new answers (unknown id 401, weak secret 401, capacity 503, 409 `reason`), operator revision bumped.
* Group targets still receive only the rendered input, not the event map; documented, not changed.

Files: [`CacheFactory.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/caching/CacheFactory.java), [`WebhookEventHandler.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/integrations/webhook/WebhookEventHandler.java), [`RestWebhookChannel.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/integrations/webhook/rest/RestWebhookChannel.java), [`ChannelTargetRouter.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/integrations/channels/ChannelTargetRouter.java), [`webhook-triggers.md`](https://docs.labs.ai/protocols-and-integration/webhook-triggers.md).

### Design decisions

* No new property: the capacity is derived from the window like the nonce cache's, and the refusal threshold follows from it. A property would let an operator size the cache below the traffic it must hold, which is the defect being fixed.
* The check for a quota refusal before creating the conversation was rejected: the API-call quota has only an atomic acquire, no read-only peek, and adding one would race. Ending the orphan is the safe equivalent (each attempt still spends a conversation slot).
* The shared bucket is not size-capped and the node-local cache that stands in for it is, so in a cluster the thresholds read each node's own view: a sender spread over N nodes may hold N times its budget in total. Reading the exact cluster-wide size is not possible (the bucket cannot enumerate its keys).
* Per-integration admission rather than a global refusal: a global threshold let one integration with a valid secret push every other integration to 503. The fair share counts only integrations with 50+ deliveries because the roles that can create integrations (`eddi-admin`, `eddi-editor`) could otherwise shrink everyone's share with many one-delivery integrations.

### Tests

* `WebhookEventHandlerTest`: an integration over its budget gets 503 while another still gets 202 (and a remembered repeat is answered); the window rolls over after 11 minutes and a delivery still counts at 10; from half full only the integration above its fair share is refused; the 90% hard stop refuses an idle integration; throwaway one-delivery integrations do not shrink another's share; an admitted delivery performs no extra cache read; refused deliveries do not spend the budget; the WARN is throttled to once a minute; `refused_capacity` is its own outcome; the refused turn ends its new conversation with its own reason; both `409` reasons; the same signed body under another event type is a duplicate.
* `RestWebhookChannelTest`: unknown or malformed id answers identically to a bad signature; rerouted replay is a duplicate; `reason` in the body and no `Retry-After` for `awaiting_approval`.
* `CacheFactoryTest`: explicit, window-derived size; shared through the `DEDUP` bucket with the matching TTL. `CacheImplTest`: `sizeExact()` ignores expired entries.
* `ChannelTargetRouterWebhookTest`: plaintext and 15-character secrets are stripped, a 16-character one is kept; the weak-secret warning is logged once per refresh cycle and again after a vault change.
* `RestChannelIntegrationStoreValidationTest`: a short existing vault secret is refused at save, other-tenant references are never resolved, `maxDeliveriesPerWindow` is validated.

***

## docs(llm): point self-hosted servers at `openai-compatible` everywhere (2026-10-24)

**Repo:** EDDI (`docs/openai-compatible-doc-nits`)

### Why

Two places written before or alongside the `openai-compatible` provider type (#1062) still sent self-hosted servers to `type: openai` + `baseUrl`, which inherits OpenAI's capability answers (JSON mode with tools, vision by model name) instead of the per-endpoint flags that type exists for.

### What changed

* [`docs/langchain.md`](https://docs.labs.ai/agent-configuration/langchain.md) — the Jlama note ("for a GPU or a larger model…") now points at type `openai-compatible` and its section instead of `openai` + `baseUrl`.
* [`docs/langchain.md`](https://docs.labs.ai/agent-configuration/langchain.md) — the `classifier` guardrail: the `provider` explanation names `openai-compatible` for vLLM / `llama-server`, and the Granite Guardian on vLLM example uses `"provider": "openai-compatible"` with `serverName: "vllm"`. Verified first that the classifier passes `provider` straight to `ChatModelRegistry`, where the type is registered, and that its builder delegates to the OpenAI builder, so `customParameters`, `maxTokens` and the rest of the example behave identically.
* Platform Operator system prompt ([`system-prompt.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/operator/system-prompt.ts)) carried the same classifier advice; corrected the same way. Operator revision bumped 36 → 37 ([`operator-revision.json`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/operator/operator-revision.json)).

### Verification

`vitest run src/lib/operator` — 16 files, 484 tests passed (run with Node 24; the machine's Node 22.14 cannot start the Vitest worker). `DocumentationLinksTest` and `ChangelogFragmentTest` green.

***

## 🐛 fix(ci): publish the `-b` image for a merge that does not touch `ui/` (2026-10-21)

**Repo:** EDDI (`fix/ci-docker-push-backend-only`)

### What changed and why

Since the monorepo split of 2026-09-15 (`4f19e4767`, "run each half only when it changed"), no merge to `main` that changed only backend code published a `-b` image. Build & Test, the integration tests and the E2E runs on the built image all passed, and **Docker Build & Push** was skipped.

The cause is GitHub's implicit `success()`. A job condition without a status function gets one added, and for a job with `needs` it grades every job upstream, not only the listed ones. Docker waits on `ui-gate`, which is written to pass when the UI did not change (`always()`, skipped ui-\* jobs accepted). On a backend-only push those ui-\* jobs are skipped, so the implicit `success()` of docker was false and it was skipped — and with it Smoke Test and Preflight Verify (Pushed Image), which depend on it. Of the last 25 merges, every backend-only one was affected; tag builds were not, because detect-changes forces `ui=true` for a tag.

[`ci.yml`](https://github.com/labsai/EDDI/tree/main/.github/workflows/ci.yml):

* `docker` starts its condition with `!cancelled()` and grades its own `needs` explicitly: no `failure`, `cancelled` or `skipped` result. That keeps the gate the job's NOTE insists on — every listed job must have succeeded, so a failed or skipped test job still blocks the push, and no `always()` is used.
* `smoke-test` gets `!cancelled() && needs.docker.result == 'success'`, and `preflight-push` gains `!cancelled()` in front of its existing condition, for the same reason.

The tag-only jobs (release, Red Hat publish, post-release) are unchanged: on a tag the ui-\* jobs always run.

### Verification

* The history check behind the diagnosis — Docker push outcome against the ui-\* jobs for the last 25 `main` pushes — lines up one to one.
* `BuildQualityGatesTest#jobsBehindUiGateGradeTheirNeedsExplicitly` fails on any job behind `ui-gate` that runs on a non-tag push without a status function, and on a docker condition that loses its explicit `needs` checks or gains `always()`. Against the old `ci.yml` it fails, naming docker, smoke-test and preflight-push.
* The merge of this branch does **not** prove the fix: it changes `ci.yml`, which the `ui` path filter counts as a UI change, so its ui-\* jobs run and it would publish anyway. The proof is the next backend-only push to `main` — it must publish a `-b` image and run Smoke Test.

***

## Fix: `eddi update` on a pre-#1034 Postgres install (2026-10-20)

**Repo:** EDDI, branch `fix/update-backfill-postgres-password`

An install made before `docker-compose.postgres-only.yml` required `POSTGRES_PASSWORD` has no such line in `.env`. `eddi update` refreshed the compose file, `docker compose pull` and `up` then failed to interpolate it, and the Windows wrapper still printed "EDDI updated."

* `install.sh` and `install.ps1` (the `eddi` wrapper): after refreshing the compose files, if one references `POSTGRES_PASSWORD` and `.env` lacks it, write the legacy `eddi` value and print a note. A fresh random value would lock EDDI out of the existing volume, because Postgres reads the variable only at initdb.
* `install.ps1` wrapper: `update` now stops with exit code 1 when `pull` or `up -d` fails instead of reporting success.
* New installs are unaffected: both installers already generate the password.

***

## 🐛 fix(hitl): a resume could not re-supply secret context, because loading a conversation dropped `secret` (2026-10-20)

**Repo:** EDDI (`fix/secret-context-survives-store-load`)

### What changed and why

Secret context on resume (#1114) refused every resume that re-supplied a secret with 400 — `context['userToken'] was not a secret context value in the paused turn` — although the paused step was stored with `"secret": true` and the placeholder. Both conversation stores rebuild a stored `context:*` entry as `new Context(type, value)` when they load a conversation, which dropped the flag, and `ConversationHitlService.validateResumeContext` and `Conversation.injectResumeSecretContext` both read it from that loaded memory. A resume always loads from the store, so the feature could not work in a deployment; the tests of #1114 and #1116 build the memory in process and never went through a load.

Both stores now keep the flag when they rebuild the entry. Nothing else changes: the stored value is still the placeholder, the re-supplied value lives for the resumed turn only, and that turn stores the placeholder again.

Files: [`ConversationMemoryStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/memory/ConversationMemoryStore.java) (`loadConversationMemorySnapshot`), [`PostgresConversationMemoryStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/datastore/postgres/PostgresConversationMemoryStore.java) (`fixContextTypes`).

### Tests

* `MongoConversationMemoryStoreTest`, `PostgresConversationMemoryStoreTest`: a secret entry keeps `secret: true` and the placeholder through a real store round trip; an ordinary entry stays unmarked.
* `ConversationMemoryStoreResilienceTest`: the same on the MongoDB load path with a mocked collection, so it also runs without Docker.
* Without the fix all three new tests fail (`expected: <true> but was: <null>`).
* End to end against an image built from this branch (MongoDB, an agent whose gated `POST` tool sends `Bearer {context.userToken}`): the resume that re-supplies the token now runs the approved call with it, where 6.6.0 answered 400; re-supplying a key that was not secret in the paused turn is still a 400 and leaves the pause; a resume without the token is still refused; neither token is stored in the conversation afterwards.

***

## 🔖 chore(release): after 6.6.0 (2026-10-20)

**Repo:** EDDI (`chore/post-release-6.6.0`, opened by `post-release.yml` after the release pipeline published the image)

### What

* Release pointers: 6.5.0 → 6.6.0 (Helm chart 2.10.0 → 2.11.0)
* Build version (pom.xml): 6.6.0 → 6.7.0

Generated by `python scripts/bump-version.py post-release 6.6.0`. Files:

* `pom.xml`
* `docs/build-reproducibility.md`
* `docs/developer-quickstart.md`
* `docs/getting-started.md`
* `docs/kubernetes.md`
* `docs/redhat-openshift.md`
* `docs/release-signing.md`
* `docs/setup-eddi-on-aws-with-mongodb-atlas.md`
* `k8s/base/kustomization.yaml`
* `k8s/quickstart.yaml`
* `helm/eddi/Chart.yaml`
* `src/test/java/ai/labs/eddi/deploy/DeploymentManifestsTest.java`

***

## 📦 chore(deps): Quarkus 3.40.1 → 3.40.1.1 (2026-10-20)

**Repo:** EDDI (`feat/compatible-import-sync`, carried on that PR so the patch reaches `main` with the next merge)

### What changed and why

* **Quarkus platform `3.40.1` → `3.40.1.1`** (`pom.xml` `quarkus.platform.version`, the only pin). It is a patch release of the 3.40 LTS line, published 2026-10-19, and contains only dependency and bug fixes:
  * Vert.x 4.5.35 and Netty 4.1.139.Final;
  * lz4-java 1.11.4, snappy-java 1.1.10.11 and Hibernate Validator 9.1.5.Final;
  * a fix that makes `rolesAllowed` in REST Data Panache `MethodProperties` inherit from `@ResourceProperties`, plus smaller REST Data Panache fixes.
* No EDDI code or configuration changes were needed.

### Verification

Compile with the style gates, the repo-wide guards, and an `@QuarkusTest` integration test that boots the application, all on the new platform. CI runs the full unit, integration and E2E suites.

***

## 📘 docs(integrations): Claude Code plugin with `eddi` and `eddi-admin` skills (2026-10-20)

**Repo:** EDDI (`docs/eddi-claude-skills`)

The MCP server gives an assistant EDDI's tools. It does not tell the assistant which tools to chain, which configuration mistakes deploy cleanly and then fail, or which calls need a person's approval. A new Claude Code plugin covers that, in [`integrations/claude-plugin/`](https://github.com/labsai/EDDI/tree/main/integrations/claude-plugin/README.md), with a marketplace entry at `.claude-plugin/marketplace.json` (`/plugin marketplace add labsai/EDDI`).

* **`eddi`** (every role) covers connecting and reading auth failures, `discover_agents`, keeping one conversation (`chat_managed` by intent, or passing `conversationId` back to `chat_with_agent`), group discussions (sync and async), approvals bound to the `pauseId` that was read, and the user's own memories.
* **`eddi-admin`** (editor and admin) covers orientation, `setup_agent` / `create_api_agent` into `test`, and the change path: `update_resource` → one `apply_agent_changes` → test → promote. It explains the `compatible` decision, and warns that undeploying with `endConversations` ends users' conversations, and that MCP cannot edit a workflow itself (adding a step is a Manager or REST change). It also covers agent test runs, intents, schedules, channels and groups. The references cover the change workflow, five config gotchas, a symptom-to-cause debugging table, groups, and the actions that need a yes, including the partial-result semantics of the GDPR tools.
* **Design:** the skills split along the MCP role tiers, so an `eddi-user` session never loads authoring tools it would get `FORBIDDEN` on. The skills treat everything EDDI returns as data, never as instructions. They point to the server's own `read_docs` instead of copying documentation, so a skill cannot contradict the running version.
* **No `.mcp.json` in the plugin:** each deployment has its own URL. The Claude Code docs also do not confirm `clientId` / `callbackPort` in a checked-in `.mcp.json`, and without them the client would try dynamic registration, which the shipped realm refuses. The README gives the `claude mcp add --client-id eddi-mcp` command instead.
* **Guard:** `SkillToolReferencesTest` (in `engine.mcp`, reusing `McpToolContractTest`'s tool scan) fails if a skill names an unregistered tool or a camelCase argument no tool takes, if it references a `read_docs` page that is missing or that the Dockerfile deletes from the image, if a SKILL.md frontmatter is incomplete, or if the marketplace entry and the plugin name disagree. Writing the skills against the source caught two stale names. `create_schedule`'s description said `cronExpression`, but the argument is `cron`: the description is fixed in [`McpAdminTools`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/mcp/McpAdminTools.java). And the first draft used the REST parameter `endAllActiveConversations` where `undeploy_agent`'s argument is `endConversations`. The argument check exists because of that one.
* **Docs:** [`mcp-server.md`](https://docs.labs.ai/protocols-and-integration/mcp-server.md) gains a "Claude Code plugin" subsection under Quick Start. The AGENTS.md §4.6 docs item now names the skills, because the guard catches renames but not new capabilities.

**Not verified:** the skills have not been run against a live server. Operator prompt unchanged: the only server change is one MCP tool description, which the operator (REST) never sees.

***

## feat(hitl): opt-in reply and unverified approver on resume (2026-10-20)

**Repo:** EDDI (`feat/hitl-resume-reply-and-approver`)

### What changed and why

* **Reply from resume.** `POST /agents/{conversationId}/resume` accepts the `say` query parameters (`returnCurrentStepOnly`, `returnDetailed`, `returningFields`). With any of them the request waits for the resumed turn (`AsyncResponse`, `agentTimeoutInSeconds`, 408 on timeout, `Retry-After` as on `say`) and returns it through the same snapshot conversion `say` uses, so secret context stays a placeholder. Without them the answer is the empty 200 it always was. `IConversationService.resumeConversation` gained a six-argument form; the three-argument form delegates with `(false, true, [])`.
* **Approver without authentication.** With no authenticated principal, a body `decidedBy` is recorded as `unverified:<value>` (trimmed, 128 characters, `[A-Za-z0-9._@:+-]` only). It is a claim by the caller, not an identity. An authenticated principal still wins and the body is ignored.
* **Tool-call path test.** `ResumeSecretContextApprovedCallTest` drives the real resume loop with the real httpcall provider and `ApiCallExecutor` resolution (HTTP client recorded): a pinned call using `Bearer {context.userToken}` runs with the real header when the token is re-supplied, is refused as before without it, and is still refused when the URI or a body value changed.

Files: [`RestAgentEngine.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/RestAgentEngine.java), [`IRestAgentEngine.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/api/IRestAgentEngine.java), [`ConversationHitlService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/ConversationHitlService.java), [`hitl.md`](https://docs.labs.ai/conversations-and-orchestration/hitl.md).

### Design decisions

* The endpoint is converted to `AsyncResponse` rather than blocking a worker: it is the same shape and timeout contract as `say`, and the no-flag path resumes the async response immediately.
* Presence of any `say` flag, not a particular value, is what asks for the reply, so `returnCurrentStepOnly=false` returns the whole conversation as it does on `say`.
* **Follow-up fixes.** `unverified:` is now a `ReservedPrincipals` prefix (no token may carry it). The resumed reply runs `recordTurnOutcome` like `say`, so an ERROR turn carries `error` and `Retry-After`. A waiting client is always answered: a resume dropped before it ran (cancelled/ended, or refused by the coordinator) is delivered as `onSkipped` (410 for ENDED, else 409, one mapping shared with `say`), and a resume that throws without rendering is delivered as the ERROR snapshot.
* **A reply is a read.** Resume admits approver-only callers (`eddi-approver`, neither owner nor admin), but a reply returns the conversation, and with `returnCurrentStepOnly=false` or `returnDetailed=true` that can be its whole history. A request carrying any reply flag therefore also needs the owner-or-admin access `say` needs; an approver-only caller asking for a reply gets `403` before the resume runs, so the pause is untouched. Raised by review as a Major authorization finding (CWE-863).
* **The watchdog path too.** A resume the runtime routes to its failure callback (the agent-timeout watchdog abandoned it, or a failure escaped the resume body) now answers a client waiting for the reply with the stored state (`EXECUTION_INTERRUPTED` or `ERROR`, the latter with its `error`), once, guarded by the same one-shot flag. Previously that client waited for its own `408`. On a watchdog abandonment the two usually coincide, since both run on `agentTimeoutInSeconds`; the answer matters for a failure that escapes the body early.

***

## feat(hitl): secret context on resume (2026-10-20)

**Repo:** EDDI (`feat/hitl-resume-secret-context`)

### What changed and why

A per-turn credential sent as secret context (`secret: true`) is replaced by a placeholder when a turn pauses, so every task after an approval that needed it (an approved HTTP tool call acting as the user) failed: a pinned call was refused as "the request changed after it was approved", an unpinned one failed at execution. `POST /agents/{conversationId}/resume` now accepts an optional `context` map in the same shape as a say request. Only entries marked `secret: true` whose key was a secret in the paused turn are accepted; anything else is a 400 before the pause is consumed. The values replace the placeholder for the resumed turn only and go through the same scrubbing as on `say` (shared `registerSecretContext`, `scrubSecretContextValues`, `TurnAuditBuffer` redaction), so the stored step holds the placeholder again afterwards.

Files: [`HitlDecision.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/lifecycle/model/HitlDecision.java) (write-only `context`), [`ConversationHitlService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/ConversationHitlService.java) (pre-CAS validation), [`Conversation.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/runtime/internal/Conversation.java) (injection and scrub), [`hitl.md`](https://docs.labs.ai/conversations-and-orchestration/hitl.md).

### Design decisions

* Timeout, Slack, MCP and group resumes pass no context and are unchanged. MCP deliberately does not get it: tool arguments are logged and audited.
* Approval binding is not weakened: headers are fingerprinted redacted, so an identical re-supplied token matches (as does a rotated one in a credential header such as `Authorization`); a different value in the URI, query, body or an unrecognised header changes the fingerprint and the call is refused (fail closed). Documented in `hitl.md`.

***

## Operator revision bump after #1112 (2026-10-20)

**Repo:** EDDI · **Branch:** `fix/operator-revision-36`

\#1112 (classifier guardrail) was squash-merged at a head whose `system-prompt.ts` edits were in, but whose matching `operator-revision.json` bump was pushed a moment later and never reached `main`. `operator-revision.test.ts` therefore fails on `main`. This sets `ui/manager/src/lib/operator/operator-revision.json` to revision 36 with the fingerprint the test computes for the current prompt, allow-list and gate (`d9679ddf62f6532a`). No behaviour change.

***

## feat(backup): declare a ZIP import or agent sync compatible (2026-10-19)

**Repo:** EDDI (`feat/compatible-import-sync`)

### What changed and why

A conversation runs on the newest ready version of its compatibility generation, so a compatible save lets running conversations follow and a breaking one pins them. ZIP import (`strategy=upgrade`, and the update half of `strategy=merge`) and agent sync always wrote a breaking version, so promoting an agent from staging to production pinned every running production conversation to the pre-promotion version, and operators ended those conversations to get the fix out.

* **`compatible` parameter** (default `false`, the safe default is unchanged) on `POST /backup/import` (merge and upgrade) and `POST /backup/import/sync`, and a per-request `compatible` field on `SyncRequest` for `POST /backup/import/sync/batch`. It is threaded to the agent write (`RestImportService.createOrUpdateAgent`, `UpgradeExecutor.updateAgentConfig`) and is ignored when a new agent is created or nothing is written. The old method forms remain as `default` overloads on `IRestImportService` and `UpgradeExecutor.executeUpgrade`, so existing callers are unchanged. No MCP tool exposes import or sync, so there is nothing to change there.
* **Merge rollback.** A failed merge writes the pre-import content back through the same agent write, so the restore carries the same declaration. Breaking import: aborted version G+1, restore G+2, so no later breaking save can share a generation with the aborted version (the original reasoning, still true). Compatible import: nothing bumped, aborted version and restore both keep G, so conversations that had already followed onto the aborted version follow on to the restored content, whereas a breaking restore would pin them to the aborted import's content. Generations never decrease along the version chain in either case. Both outcomes are tested.
* **Preview.** `ImportPreview.conversationImpact` (`PromotionImpact`) on the upgrade, merge and sync previews: the target's current version and generation, the generation each declaration would produce, the open conversations per compatibility generation and how many would follow if declared compatible. It answers for both declarations because the preview is read before the choice, so the Manager updates instantly without another round trip to the source. Counts only, by the conversations' own compatibility generation (a conversation follows the newest ready version of its generation whatever version it last ran on, so a count per deployed version missed idle conversations stored on undeployed versions): one grouped count, `IConversationMemoryStore.getActiveConversationCountsByGeneration` (Mongo `$group`, Postgres `GROUP BY`), never the active-conversation memory listing. Computed by `RestAgentAdministration.previewNextVersion` with the same follow rule as the deployment impact and the generation rule of `AgentStore.nextCompatibilityGeneration` (now public). Omitted when nothing would be written, there is no existing target, or the caller lacks EDIT on it.
* **Result.** `UpgradeResult` (upgrade, sync, batch) gains `compatible` and `compatibilityGeneration` of the written agent version; a merge import answers with `X-Agent-Compatible` and `X-Agent-Compatibility-Generation`. Additive.
* **Legacy edge.** A target whose current version has no generation still starts generation 1 on a compatible save; the preview reports `startsNewChain: true` and the Manager shows the existing `compatibleLegacyNote` text.
* **Manager.** `PromotionCompatibilityPanel` (reusing `CompatibleVersionCheckbox`, unticked by default) in the import dialog's preview step and in each agent's detail on the Sync page, with the impact sentence and `agentVersioning.promotionImpact*` keys in all 11 locales.
* **Docs.** `deployment-management-of-agents.md` (when to tick compatible on a promotion, both outcomes), `agent-sync-guide.md`, `import-export-an-agent.md`.

### Design decisions

* Merge shares the update path with the rollback in question, so it takes `compatible` as well as upgrade.
* Preview parameters were rejected in favour of returning both answers.
* Counting by deployed version was rejected: a conversation follows by its own generation, so idle conversations stored on undeployed versions were missed.

### Tests

New: `RestImportServiceCompatibleTest`, `RestAgentAdministrationPromotionImpactTest`, additions to `UpgradeExecutorSyncTest` and `RestImportServiceSyncCoverageTest`, and `promotion-compatibility.test.tsx`. The key backend tests were mutation-checked.

***

## feat(operator): the Platform Operator explains 408 Request Timeout and `caller_timed_out` (2026-10-19)

**Repo:** EDDI · **Branch:** `feat/operator-turn-timeout-408`

### What changed and why

PR #1101 changed what a `408` means under load, and left telling the Platform Operator for later, because the "Turn capacity" prompt section of #1091 had not landed yet. Without this an admin asking "why do my users get 408?" or "what is `eddi_turn_skipped_total`?" got an answer from the old behaviour, or none. AGENTS.md §4.6 asks for this check whenever behaviour changes.

* [`system-prompt.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/operator/system-prompt.ts), "Turn capacity":
  * A fourth `capacity_exceeded` cause: the database pool-wait timeout ("The database is busy: no connection was free in time"), now a `503` with `Retry-After` instead of a `500`.
  * How a `408` differs from a `503`: the turn was accepted but its caller's time (`systemRuntime.agentTimeoutInSeconds`, counted from the request's **arrival**) ran out. The prompt gives the three cases and whether the turn ran in each: rejected before queueing (`eddi_turn_rejected_total{reason="caller_timed_out"}`), dropped unrun from the queue with its input unconsumed (`eddi_turn_skipped_total{reason="caller_timed_out"}`, `eddi.conversation.skip-turns-of-timed-out-callers`; only then is a retry exactly-once, and with the setting off the queued turn still runs), or already started, whose outcome is unknown at the `408` because the execution watchdog times from the turn's submission to the executor (queue wait included), not the request's arrival.
  * What a rising `caller_timed_out` means: the node is overloaded. The fix is more nodes or a lower `max-in-flight-turns`, which turns a 60 s wait into a fast `503`. Raising the timeout does not help. Flat counters do not prove health: a turn that queued until just before its deadline and then started is counted by neither, so compare wait-before-start with run time.
  * `/q/metrics` answers on dedicated threads (`eddi.metrics.dedicated-scrape-threads`).
  * The logs section: pool-wait refusals are WARN lines, and both `408` paths log at DEBUG only, so the logs do not show them.
* No allow-list change. The meters are at `/q/metrics`, which is not in the OpenAPI spec and so cannot become a tool. The prompt already says the operator cannot read them.
* [`operator-revision.json`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/operator/operator-revision.json): revision bump, so existing deployments are offered the upgrade.
* [`system-prompt.test.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/operator/__tests__/system-prompt.test.ts): pins the pool-wait message, the 408/503 distinction, both counters, the "did it run" sentence, the overload advice and the DEBUG-only logging note.

***

## ✨ feat(engine): move already-pinned conversations onto the current agent version (2026-10-19)

**Repo:** EDDI (`feat/upgrade-conversation-generation`)

### What changed and why

A ZIP import and an agent sync write a breaking version unless declared compatible, a breaking save leaves the same result, and conversations that started before compatibility generations existed carry none, so after a promotion every running conversation stays pinned to the version it began on. Operators ended them, which is a bad experience for the user in the middle of a conversation. This adds an operator-declared, previewable repair: "this agent's conversations on an older generation (or none) are compatible with the current version, move them onto it."

* **Endpoint.** `POST /administration/{environment}/upgradeconversations/{agentId}` with `dryRun` (default `true`), repeatable `fromVersion`, `limit` (default 5000, so a call stays inside a proxy timeout) and `after` (the cursor: a truncated report carries `nextAfter`). Same path style, roles and EDIT access check as `undeploy`. The response has the same shape for dry and real runs: target version and generation, and per source version `matched`, `eligible`, `upgraded` and `skipped` by reason. MCP: `upgrade_conversations`, same dry-run default (86 tools now). The REST call is recorded by the existing administrative-action audit filter; deploy and undeploy over MCP write no audit record either, so the tool adds none.
* **Target.** The generation of the agent's latest version. A version of it must be `READY` in the environment on the serving node, else `409`; an agent whose latest version has no generation also gets `409`. A generation is never lowered, and conversations already on the target are not touched.
* **Only the generation is written.** The existing per-turn machinery (`resolveConversationAgent`, `recordAgentVersionMove`) then moves the conversation to the newest `READY` version of the generation and records the move, so `agentVersion`, steps and the descriptor are not rewritten here.
* **States.** `READY`, `ERROR` and `EXECUTION_INTERRUPTED` are moved. `ERROR` is included on purpose: `say` refuses only ended and paused conversations, so an errored conversation is live and the new version often repairs it. `ENDED`, `AWAITING_HUMAN` (a resume must finish on the version that paused it) and a persisted `IN_PROGRESS` are skipped and counted.
* **Concurrency.** A say turn never persists `IN_PROGRESS`, so the store cannot see a running turn. Each write is therefore a task in the conversation's own coordinator queue (cluster-wide lease in cluster mode) and never overlaps a turn. The write is one conditional update and also moves `_rev` and `_histRev`: a turn queued behind it is rebuilt over the new document by the existing stale-snapshot guard, and a writer holding an older load is refused (append: history revision; full write: revision) instead of putting the old generation back. Tasks that do not start within `eddi.conversation-upgrade.turn-wait-ms` (30 s) are withdrawn and reported as `busy`.
* **Scale.** Candidates are read as a keyset-paged projection (id, state, version, generation), 100 per round, never loaded in full and never via the active-conversation listing. Implemented for MongoDB (pipeline update) and PostgreSQL (`jsonb_set`).
* **Observability.** `eddi_conversation_generation_upgrade_count`; one INFO line per run with the counts.

### Tests

`ConversationUpgradeServiceTest` (selection, skips, target validation, never lower, dry run writes nothing, timeout withdrawal, real-coordinator ordering against a running turn), `RestAgentAdministrationUpgradeConversationsTest`, and a `GenerationUpgrade` group in both `MongoConversationMemoryStoreTest` and `PostgresConversationMemoryStoreTest` (Testcontainers), including the stale-append and stale-full-write interleavings.

### Docs

`docs/deployment-management-of-agents.md` ("Moving running conversations onto the current version") and `docs/mcp-server.md`.

### Design decisions

* Order of preference: save or promote compatibly where possible; this action is for conversations that are already pinned.
* Ended conversations are not scanned (they would stay candidates forever and crowd out the ones that can move); they are counted per version with one query. The cursor exists because conversations skipped without change (paused, in progress, busy) stay candidates.

***

## 🐛 fix(cluster): review follow-ups to #1089 — non-blocking heartbeat tick, drain/acquire race, one dead-letter budget (2026-10-19)

**Repo:** EDDI · **Branch:** `fix/cluster-resilience-review-followup`

### What changed and why

\#1089 merged before its last round of review fixes was pushed. This lands them on their own.

* **The lease scheduler never waits for a heartbeat pass** ([`KvLeaseManager`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/cluster/lease/KvLeaseManager.java)). The single lease-scheduler thread also runs every lease waiter's retry and deadline timer. `heartbeatAll` waits up to one interval for its renewals, so a stalled renewal delayed those timers by up to an interval. The tick (`dispatchHeartbeat`) now only starts the pass on the I/O executor; a tick that finds the previous pass still running skips.
* **A leader lease granted while a drain began is handed back.** `tryAcquireKey` checked `draining` before its KV create; a drain whose sweep ran during that create could not see the new lease, so the drained node kept renewing a leader lease no other node could take. It re-checks after the grant.
* **One budget for a dead-letter append** ([`JetStreamDeadLetterStore`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/cluster/JetStreamDeadLetterStore.java)). The \~2 s retry budget started only after the first publish and the provisioning, each of which can take a full request timeout against a NATS that stopped answering. It now covers the whole append.
* **Late on-connect hooks** (registered after the connection is up) also run on the hook executor ([`NatsConnectionManager`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/cluster/NatsConnectionManager.java)), not on the shared scheduler.
* **Cancellation in a mixed gated/allowed tool batch** ([`ToolLoopRunner`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/ToolLoopRunner.java)): the allowed calls of a batch that also pauses for approval now check the turn's cancel flag before each tool, like the main loop.

### Tests

`KvLeaseManagerTest.leaderAcquiredDuringADrainIsReleased`, `heartbeatTickNeverBlocksTheScheduler`, `JetStreamDeadLetterStoreTest.aFirstPublishThatUsedUpTheBudgetSkipsProvisioningAndRetries` — each fails with its fix reverted. The renewal-overlap test releases its gate in `finally`.

***

## fix(engine): the turn timeout and `/q/metrics` hold under overload (2026-10-19)

**Repo:** EDDI · **Branch:** `fix/turn-timeout-under-load`

### What changed and why

The collapse investigation of 2026-10-19 (PR #1098) found three overload behaviours in a 5,000-user burst against a node held to 2 CPUs: turns answered `200` after a median of 113 s although the REST timeout is 60 s, `/q/metrics` silent for about 110 s, and queued turns that still ran after their caller had been answered `408`. A reproduction with per-request timing ([results note](https://github.com/labsai/EDDI/tree/main/scripts/loadtest/results/overload-timeouts-2026-10-19.md)) traced the first two to one queue. `say` and the Prometheus endpoint ran on the Quarkus worker pool (200 threads), and in the burst every one of those threads was busy with conversation starts waiting on MongoDB. A turn request waited up to 79 s for a thread before its 60 s timeout was even armed, a finished turn waited up to 37 s more for a thread to write its answer, and the scrape queued behind both. The timeout timer itself fired on time.

* [`RequestArrivalStamp`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/RequestArrivalStamp.java): the router's first route records when each request arrived. [`TurnDeadlineHeaderReader`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/TurnDeadlineHeaderReader.java) puts it on the turn's `InputData`.
* [`RestAgentEngine`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/RestAgentEngine.java): the `408` fires at `systemRuntime.agentTimeoutInSeconds` after **arrival**. A request that has already used the whole budget is answered `408` at once and queues nothing (`eddi_turn_rejected_total{reason="caller_timed_out"}`). `say`, `sayWithinContext` and `rerun` are `@RunOnVirtualThread`, which also takes the response write off the worker pool. A database pool-wait timeout on a turn or a start is `503 capacity_exceeded` with `Retry-After: 5` instead of a `500` ([`ConnectionWaitTimeouts`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/datastore/ConnectionWaitTimeouts.java)).
* [`ConversationService`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/ConversationService.java) and [`ConversationStepRunner`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/ConversationStepRunner.java): the turn carries when its caller gives up. A turn still queued then is dropped before any read, its input unconsumed (`eddi.conversation.skip-turns-of-timed-out-callers`, default `true`, `eddi_turn_skipped_total{reason="caller_timed_out"}`). The caller is told through the new `ConversationResponseHandler.onCallerGone` (REST: `408`), and an idempotency key is released, so a retry runs the turn. A turn deadline (`turnDeadlineMs`, `X-EDDI-Turn-Deadline-Ms`) now counts from the request's arrival too.
* [`MetricsScrapeRoute`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/MetricsScrapeRoute.java): `GET`/`HEAD /q/metrics` is answered on two threads of its own, by a route at order −10: after the security filters (−200, −100), so the metrics permission still applies, and before the `/q` sub-router (`eddi.metrics.dedicated-scrape-threads`, default `true`).
* Docs: `conversations.md` (when a turn is answered `408` and whether it ran), `configuration-reference.md` (both properties), `metrics.md` (the `caller_timed_out` reasons), `application.properties`.

### Measured

Interleaved on a contended laptop (host CPU 72–79 %; other sessions' builds ran throughout), two runs per arm, burst of 5,000 users, limit 1,500:

* `/q/metrics`: 0 of 335 scrapes timed out, against 120 s blind in every baseline run.
* Slowest `200`: 60.4 s, against 94–105 s. Every `200` arrived within the caller's 60 s.
* `200`s within 60 s (estimated from percentiles): 24.7 and 27.9 per second, against 21.9 and 17.4. Fewer `200`s in all (3,297–3,734 against about 4,700), because the late answers became `408`s.

### Design decisions

* **Starts stay on the worker pool.** Measured with starts on virtual threads too, the node collapsed: 0 turns, connections refused, event loops blocked for up to 60 s. Two carriers at 2 CPUs could not absorb thousands of CPU-heavy starts admitted at once. The worker pool is the start path's only concurrency limit. `AgentEngineVirtualThreadIT` pins both halves of this.
* **A caller-gone skip, not a default turn deadline.** A default `turnDeadlineMs` would change how every agent's retries and fallbacks spend their time. The skip only stops work whose answer cannot reach anyone, and only for callers that stamped when they give up (REST `say`). Streams, schedules and group members carry no such time and are untouched.
* **The scrape route replaces Quarkus' handler rather than moving it.** A management interface would still use the same worker pool for its blocking route. A route of our own ahead of Quarkus' keeps the path, the content negotiation and the permission, and can be switched off.

### Not done (follow-ups)

* A request that cannot be dispatched within 60 s (up to 123 s on two saturated carriers) still gets its `408` only when it runs. The remedy is earlier load shedding: an in-flight limit sized to CPU.
* Conversation starts have no concurrency bound of their own.
* The Platform Operator learns about the `408` / `caller_timed_out` behaviour once the "Turn capacity" section of PR #1091 lands; changing the same prompt here would be a revision-bump conflict.

***

## 🛡️ feat(manager): LLM input/output guardrails editor and `guardrail_triggered` chat notice (2026-10-19)

**Repo:** EDDI (`feat/manager-llm-guardrails`, based on `feat/llm-input-output-guardrails`, PR #1064, because that PR had not merged when this was written)

The backend shipped input/output guardrails on LLM tasks with only a TypeScript type mirror in the Manager, so designers had to edit JSON. This adds the editor and surfaces the new SSE event.

### What changed

* **Guardrails section on the LLM task editor** ([`task-guardrails-section.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/components/editors/llm/task-guardrails-section.tsx)): two ordered lists, `inputGuardrails` and `outputGuardrails`. Each row shows type and action, and can be reordered (order is run order), edited or removed. Each guardrail is edited in a side sheet ([`guardrail-sheet.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/components/editors/llm/guardrail-sheet.tsx)) so the task editor itself stays one flat list.
* **The sheet** edits type, action (with a one-line explanation per action and phase; `reprompt` is not offered on the input side, where the engine treats it as `block`), `maxRetries` (only while the action is `reprompt`), `blockMessage`, `failMode`, `repromptMessage`, and the type's own parameters: `prompt-injection` (extra patterns, mode), `pii-redaction` (kinds, replacement), `regex-filter` (patterns, replacement), `max-length` (`maxChars`), `json-object` (none), and `classifier` (provider picker reusing `ProviderSelect`, base URL, model under the key the chosen provider reads, API key through `SecretKeyPicker` so it is a `${vault:…}` reference, risk, prompt template, unsafe/safe label, label pattern, timeout, prices, retrieved-context toggle on the output side). Warnings for: classifier without a provider, classifier `unsafeLabel` other than `yes` without a `safeLabel` (the deploy is refused), `redact` on a type with nothing to rewrite with, `failMode: open` on a blocking guardrail, a regex filter with no pattern, a type on the wrong side.
* **Streaming caveat**: an output guardrail whose action is `block`, `redact`, `reprompt` (or absent, which is `block`) makes the task buffer its answer; the section says so in amber while that is the case, and plainly otherwise.
* **Chat**: `guardrail_triggered` is handled in `use-chat` and attached to the agent bubble of the turn; [`ChatMessage`](https://github.com/labsai/EDDI/tree/main/ui/packages/app-kit/src/components/chat/chat-message.tsx) shows one quiet line per fired guardrail (phase, type, action). The payload carries no screened text. The standalone Chat UI (`ui/chat`) was left alone: it is an end-user widget whose block message already is the answer, and it surfaces no other internal pipeline events as notices.
* i18n: 109 keys (`llmEditor.gr*`, `chat.guardrail*`) in all 11 locales.

### Design decisions

* **Write only what the author sets.** A new guardrail is `{ "type": … }` with nothing else; blanking a field removes it, an emptied `parameters` map is dropped, an emptied list removes `inputGuardrails`/`outputGuardrails` rather than writing `[]`, and moving off `reprompt` drops `maxRetries`. An older server's strict parser refuses unknown fields (same rule as `task-tool-call-limits.tsx`).
* All `parameters` stay plain strings, as the backend reads them; an unknown `type` and any unknown parameter are preserved untouched.
* The classifier model key follows `modelParamSpec(provider)`, and switching provider moves the model and credential to the new provider's keys.
* Edits apply live (no draft/apply step) because the list behind the sheet reflects them and the editor already has its own save/dirty handling.

### Not done / next

* The `classifier` type exists on `feat/llm-classifier-guardrail`, not yet in a PR. Until that backend lands the editor does not offer it (it is left out of `GUARDRAIL_TYPES`); a stored `classifier` entry still shows as a custom type and keeps its settings panel. The classifier PR adds it back.
* The operator system prompt is unchanged: its guardrail text was already added with the backend PRs.
* Live-turn notices only: a conversation reloaded from history does not show them (the audit ledger holds the record).

***

## 📊 feat(ci): Slack digests estimate real Docker pulls next to the raw count (2026-10-19)

**Repo:** EDDI (`feat/metrics-sweep-filter`)

### What changed and why

The daily digest went from single-digit pull counts to +1,805 overnight. The arithmetic was right, but the source was not people. Since 2026-10-18 02:47 UTC, something has pulled all 198 tags of `labsai/eddi` at once, every \~2 hours. The workflow logs show pull\_count rising in steps of exactly 198–200, and Docker Hub's `tag_last_pulled` puts every tag's last pull within the same millisecond. The Oct 7 jump of +3,947 has the same shape. Outside those sweeps the counter rises by a few pulls a day.

The digests keep the absolute count and now add two lines:

* **Likely real pulls**: the pull\_count increase minus bot sweeps and our own CI pulls, with the number of sweeps filtered out.
* **Versions pulled**: the tags real pulls went to (e.g. `latest ×12, 6.5.0 ×3`). The number is how many runs saw that tag pulled, not a pull count, because Docker Hub does not publish per-tag counts.

How it works, in [`docker-pull-notify.yml`](https://github.com/labsai/EDDI/tree/main/.github/workflows/docker-pull-notify.yml):

* A new step, **Fetch Docker Hub tags**, reads every tag's `tag_last_pulled` after it reads pull\_count, and records when it finished. Both Docker Hub reads now have a 30-second deadline, so a stalled connection can't hold the job, and through the concurrency group every later run, until GitHub's 6-hour limit.
* **Persist metrics history** appends one line per run to `data/runs.csv` on the `metrics` branch. Each line splits the increase since the previous line three ways. An interval in which ≥ 20 tags were pulled is a sweep, costing one pull per tag. A long gap holding several sweeps is estimated from what is left once any carried debt is paid, divided by the tag count. Otherwise each `-b<N>` build tag pulled counts as one CI pull, because `ci.yml`'s post-push check pulls every build it publishes. The rest is real, and the other tags pulled are recorded.
* `bot_debt` / `debt_since` cover Docker Hub showing a sweep's timestamps before its pull\_count catches up, possibly by more than one run. Debt that can't be subtracted yet is always applied to the next interval, which holds the late count however long it is. Anything still unpaid carries further only while it is younger than 2 hours. The two failure modes are lopsided: dropping debt too early books a whole sweep (\~200) as real pulls, while holding it too long hides a few real ones. A malformed last line starts a new baseline instead of blocking the log.
* **Plan digests** sums the log over the same span as the raw delta beside it: every line after the first run of the `from` day, up to and including the first run of the `to` day (the daily rows are first-run-of-the-day snapshots). Consecutive windows share no line and miss none, so an interval crossing midnight is counted exactly once. If the log has no line on the `from` day, the window is empty rather than borrowing an interval from after it. A window that has to start after its first day (no line until later in a weekly window) is labelled partial from that line. A log younger than the window gives a figure labelled "counted since …". With no log, the line is left out and the digest is otherwise unchanged.

### Design decisions

* **The run log lives on the `metrics` branch, not in the Actions cache.** Each line's baseline is the previous line. The cache is evicted routinely, which is how the digest baselines broke before. One commit per run, about 70 a day, is acceptable on an orphan data branch.
* **A failed fetch writes no line.** The next interval just gets longer, and a failed push heals the same way.
* **Estimates, labelled as such.** A tag pulled by a person and then swept in the same interval is lost, and a short burst of real pulls in a sweep interval is only roughly separated. Exact per-tag counts would need Docker Hub's publisher analytics, e.g. via the Docker-Sponsored Open Source program.

### Verification

The changed step scripts were extracted from the workflow and run in `ubuntu:24.04` with the runner's tools. They were tested against the live Docker Hub tag API (198 tags) and a synthetic sequence: quiet interval, CI build-tag pull, one sweep, a sweep whose count lags one run and then two, two sweeps in one gap, a late count in the same interval as a new sweep, debt kept while young and dropped after 2 hours, a refused duplicate timestamp, a failed fetch, and a malformed last line. Mutants restoring one-run carry, no expiry, and sweeps counted from the raw delta each fail the suite. Every Slack payload variant was parsed as JSON. actionlint reports only the four SC2129 style notes `main` already had.

***

## fix(engine): price the conversation without converting every step on the current-step path (2026-10-19)

**Repo:** EDDI · **Branch:** `fix/security-review-authz` (carried by #1081 to repair `main`)

### What changed and why

\#1066 (group cost ledger) and #1093 (convert only the current step for a turn's response) merged within minutes of each other, each green on its own. Together they broke `main`: `ConversationMemoryUtilities.conversationCost` sums `audit:cost` over every step of the snapshot, and on the current-step path that list is the lazy view #1093 introduced, so pricing the conversation converted every step again. `ConversationMemoryCurrentStepConversionTest.convertsOnlyCurrentStep` failed, and the default turn response lost the saving #1093 was for.

* `LazyStepSnapshots.conversationCost()` sums the live steps' `audit:cost` entries with one `IConversationStepStack.getExactDataPerStep` read. Nothing is converted. A step holds at most one value per key, which is exactly what the full conversion sums per step, with the same non-finite and negative filtering.
* `conversationCost(List)` uses it when it is handed the lazy view; every other caller is unchanged.
* New test: with costs on every step, the current-step path returns the same total as the full conversion and still reads only the newest step.

***

## fix(runtime): refuse a conversation start at capacity before any read (2026-10-19)

**Repo:** EDDI · **Branch:** `feat/turn-admission-hardening` (PR #1085)

### What changed and why

A profile of a 5,000-user burst against a node held to 2 CPUs (JFR, 2026-10-19) found that turns got only about 17 % of the CPU. Starting conversations took 19 %, and the HTTP event loop took 27 %. Most of those starts were refused for capacity, and each client came back after `Retry-After`. #1085 already moved the capacity check before any read for `say`, `rerun` and streaming. A start, though, still ran the agent access check, resolved the user, read the GDPR restriction from `usermemories` and looked up the agent before `admitTurn` refused it.

* `RestAgentEngine.startConversationWithContext` now calls `refuseIfAtCapacity` first. A refused start answers the same 503 `capacity_exceeded` as before, now with no database read. `admitTurn` stays the authoritative check.
* `RestAgentEngineCapacityPrecheckTest` pins both cases: refused before the access guard and before `startConversation`, and going ahead when there is capacity. Removing the call fails both tests.
* [`docs/metrics.md`](https://docs.labs.ai/deployment-and-infrastructure/metrics.md) names the start path among the pre-checked entry points.

### Design decisions

* The internal starts (group members, schedules, sub-agents, A2A) do not pass through this method and are unchanged. They reach `admitTurn` as before.

***

## perf(audit): the audit ledger signs through signIfKeyPresent; burst-collapse investigation (2026-10-19)

**Repo:** EDDI · **Branch:** `perf/audit-signing-missing-key`

### What changed and why

An investigation of throughput collapses under a 5,000-user burst ([`scripts/loadtest/results/collapse-2026-10-19.md`](https://github.com/labsai/EDDI/tree/main/scripts/loadtest/results/collapse-2026-10-19.md)) found that every audit entry did a vault read that was certain to miss. `AuditLedgerService.submit` signs each entry with the agent's Ed25519 key, on the turn's own thread, and almost no agent has a key. This branch fixed that with a 60 s missing-key cache. Meanwhile #1055 landed an equivalent cache on `main` (`AgentSigningService.missingKeyUntil`, with a guard against a lookup racing a key generation), so the merge keeps `main`'s implementation. What this branch still adds:

* `AgentSigningService.signIfKeyPresent`, used by the audit ledger. While a "no key" answer is remembered it returns `null` without throwing. Through `sign`, a remembered miss still builds three exceptions per entry (`SecretNotFoundException`, `PrivateKeyLoadException`, `AgentSigningException`), about 8,000 of each in one profiled burst. `sign` keeps its contract.
* The investigation's results file. Host contention triggers the collapses; on 2026-10-18 that is stated as a hypothesis, since no host telemetry covers the worst runs. On scarce CPU, EDDI spent most of it outside turns. Its follow-ups are the unfired 60 s turn timeout, `/q/metrics` going unresponsive and turns that run after their caller has gone.
* [`docs/configuration-reference.md`](https://docs.labs.ai/deployment-and-infrastructure/configuration-reference.md) described `eddi.audit.agent-signing-enabled` as signing agent configurations. It signs audit entries, and the row now says so, including the 60 s re-check.

### Design decisions

* On the merge conflict with #1055, `main`'s cache won outright: it also guards the race in which a lookup that started before `generateKeyPair` publishes its miss afterwards. This branch's own cache, a Caffeine cache with a 10,000-key cap that came out of review, was dropped rather than merged in.
* Tests: three `signIfKeyPresent` cases in `AgentSigningServiceTest` (null without a second vault read, a present key, a vault failure still thrown), and `AuditLedgerServiceBranchTest` covering the unsigned-entry path.

***

## fix(security): the four leftovers of the 2026-10-17 security review (2026-10-18)

**Repo:** EDDI · **Branch:** `fix/security-review-leftovers`

The 2026-10-17 review was remediated in PRs #1079–#1094. Four items were left on purpose and are closed here, one commit each.

### 1. Keycloak refuses the admin/admin fallback off loopback

[`docker-compose.auth.yml`](https://github.com/labsai/EDDI/tree/main/docker-compose.auth.yml) falls back to `admin`/`admin` for the Keycloak bootstrap admin so the loopback quick start needs no `.env`. That was safe only while `KEYCLOAK_BIND` stayed on loopback, and nothing enforced it. A new one-shot `keycloak-guard` service, the same pattern as `docker-compose.yml`'s `bind-guard`, now exits 1 (and Keycloak, which waits for it with `service_completed_successfully`, never starts) when `KEYCLOAK_BIND` is not loopback while `KC_BOOTSTRAP_ADMIN_PASSWORD` is unset or `admin`. It reads both values from its own environment with the defaults the keycloak service uses. It runs on the Keycloak image the overlay pulls anyway, so it adds no image to either base stack (`docker-compose.postgres-only.yml`'s own guard avoids the mongo image for the same reason). The installers and `gcp/provision-vm.sh` already generate a password, so their paths pass unchanged.

* `ComposeStackTest` pins the wiring (dependency condition, same password expression, same bind variable as the published port) and runs the guard script itself through `sh` for five bind/password combinations; that test is skipped only where no POSIX `sh` is on `PATH`. `adminPasswordsAreOverridable` now checks that each admin-password variable appears at least once, since the guard repeats `KC_BOOTSTRAP_ADMIN_PASSWORD`.
* Verified by hand with `docker compose run keycloak-guard` against loopback, `0.0.0.0` with no password, with `admin`, with an empty one and with a real one.

### 3. The release signs `SHA256SUMS`, and the installers verify it

PR #1088 made the release publish a `SHA256SUMS` that `install.sh` / `install.ps1` check every download against, but the list itself was unsigned, so whoever could replace one release asset could replace both. The `release` job in [`ci.yml`](https://github.com/labsai/EDDI/tree/main/.github/workflows/ci.yml) now gets `id-token: write`, installs cosign with the same pinned installer as the image job, signs the list keyless (`cosign sign-blob --yes --bundle SHA256SUMS.sigstore.json SHA256SUMS`), verifies the bundle against the exact identity the installers demand, and attaches it to the release.

Both installers, when `cosign` is on `PATH`, fetch the bundle from the same release and run `cosign verify-blob` with `--certificate-identity https://github.com/labsai/EDDI/.github/workflows/ci.yml@refs/tags/<tag>` (exact, not a regexp: the certificate must name this release's own tag) and `--certificate-oidc-issuer https://token.actions.githubusercontent.com`, BEFORE any hash in the list is trusted. A list that fails stops the install. Without cosign they print one warning line, and a release from before the bundle existed is used unsigned with a warning. Releases cut before this change keep working.

* Tests: `InstallerReleaseRefTest.checksumListIsSignedAndVerified` checks the release job and both installers as text, including that verification precedes trust. `shellVerifiesTheChecksumSignature` runs install.sh's own functions with a stub curl and a stub cosign: one warning without cosign; the exact identity, issuer and bundle URL with it; refusal on a failed verification; the unsigned fallback when there is no bundle. It was mutation-checked by forcing verification to pass. The PowerShell function was run the same way by hand, with a stub `cosign.cmd`, in all four cases.
* Not verified end to end: keyless signing needs the GitHub OIDC token, so the first real signature appears on the next release tag. The job verifies it before publishing.
* Docs: `docs/security.md`, "Installer Downloads", with the manual `cosign verify-blob` command.

### 4. `read_audit_trail` no longer shows a USE-only owner the agent's prompt

Finding: yes, it did. `LlmTask` writes `audit:compiled_prompt` as the compiled system message, `---`, and the processed prompt template; `LifecycleManager.buildAuditEntry` copies it into `AuditEntry.llmDetail.compiledPrompt`, and the MCP `read_audit_trail` tool returned entries as stored to any `eddi-viewer` who owned the conversation. Under enforced workspaces an agent shared with `USE` lets the recipient chat with it but not read its configuration, so the audit trail of their own conversation was a way around that. (`/auditstore` over REST and the GDPR export are `eddi-admin` only and unaffected.)

[`McpConversationTools`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/mcp/McpConversationTools.java) now replaces `compiledPrompt` with a redaction marker unless `ResourceAccessGuard.hasAccess(agentId, VIEW)` holds. That answers OWN for an admin and whenever workspaces are not enforced, so nothing changes there. VIEW on the agent rather than on each LLM config: sharing materialises the agent's level onto its config graph (`ConfigGraphResolver`), so it is the same decision without a graph walk per entry. Model name, token usage, cost and the model's reply stay; the access lookup is made once per agent per call and skipped for entries with no prompt. Tests in `McpConversationToolsOwnershipTest` pin both halves (USE-only owner gets the marker and no prompt text; VIEW passes the entry through untouched), mutation-checked by reverting the call.

### 2. EDDI connects to MongoDB as its own user, not as root

Compose, Helm and the kustomize MongoDB overlay connected EDDI as the MongoDB root user with `authSource=admin`, so anything that could read EDDI's connection string held the whole server. EDDI now connects as `eddi_app`, defined in the `eddi` database with `readWrite` and `dbAdmin` there and nothing elsewhere (`dbAdmin` because `MongoResourceStorage` un-hides an index with `collMod`, which `readWrite` lacks).

* **Not an initdb script, deliberately.** The mongo image runs `/docker-entrypoint-initdb.d` only on an empty volume, so every existing deployment would have pointed EDDI at a user that does not exist. Instead a helper with the root credentials creates the user, or resets its password and roles, on every start: a one-shot `mongodb-app-user` service that `eddi` waits for in [`docker-compose.yml`](https://github.com/labsai/EDDI/tree/main/docker-compose.yml), `docker-compose.openwebui.yml` and `docker-compose.cluster.yml`, and an `ensure-mongodb-user` init container (restricted-PSS security context, bounded wait for MongoDB) in the Helm Deployment and in `k8s/overlays/mongodb`. Existing Compose and Helm installs migrate on the next `up` / `helm upgrade`, and changing the app password rotates it.
* **Defaults that do not break an existing install.** Compose's `MONGO_APP_PASSWORD` falls back to the root password (documented as "set a distinct one"). Helm's `mongodb.appPassword` falls back to `sha256("eddi-app:" + rootPassword)`: stable across renders without `lookup`, distinct from and not reversible to the root password. Kustomize's operator-created Secret gets two new keys in the documented command; for an old Secret the `MONGO_APP_*` references are optional and the init container does nothing, so EDDI keeps working as root until the documented patch is applied.
* The `mongodb` healthchecks no longer carry the root password (`ping` needs no auth).
* Helm chart `2.9.0` → `2.10.0` (new values `mongodb.appUsername`, `mongodb.appPassword`).
* Docs: `docs/upgrading-from-6.5.md` (new "MongoDB least-privilege user" section, plus the Keycloak guard from item 1), `docs/docker.md`, `docs/kubernetes.md`, `docs/troubleshooting.md`, `.env.example`.
* Tests: `ComposeStackTest.eddiDoesNotConnectAsMongoRoot` and `DeploymentManifestsTest.helmEddiDoesNotConnectAsMongoRoot` / `kustomizeEddiDoesNotConnectAsMongoRoot` (both mutation-checked); the CI manifest-lint step now checks the app password is URL-encoded and that the root password never reaches EDDI's connection string.
* Verified in Docker with `labsai/eddi:6.5.0`: a volume written by the old root-connected stack, restarted on the new compose file, keeps its data, EDDI writes as `eddi_app`, a second `up` updates rather than fails, `eddi_app` is refused on `admin`, and a fresh volume works. The init container's script was run as uid 185 on a read-only root filesystem with all capabilities dropped, against a MongoDB still starting up. `helm template`/`helm lint` (default, `existingSecret`, PostgreSQL-only, special-character password) and `kubectl kustomize` of every overlay and example render.
* Not changed: `scripts/loadtest/docker-compose.loadtest.yml` (a load-test harness, still root) and `k8s/quickstart.yaml` (its MongoDB runs without authentication at all).

### Review follow-ups (CodeRabbit on #1099)

* **Keycloak, an existing `admin`/`admin` volume.** `keycloak-guard` sees only the configured password, and Keycloak reads it on first boot only, so a volume first started with the default kept that login whatever `.env` said. A new one-shot `keycloak-admin-rotate` runs once Keycloak is healthy and before EDDI starts: when a non-default password is configured and `admin` still logs in, it resets the account to the configured password through `kcadm`, password on stdin. The window in which such a volume is published with the old login is now Keycloak's start-up, not indefinite. Verified live: `admin` accepted, rotation, `admin` refused, the new password (with a quote and a backslash) accepted, second run a no-op. `ComposeStackTest` pins the wiring.
* **MongoDB helper: root password off the command line.** All five copies (three compose files, Helm, kustomize) now authenticate with `db.auth(process.env…)` inside `--eval`, so the root password is no longer in mongosh's argv (`/proc/<pid>/cmdline`).
* **MongoDB helper: concurrent starts.** Several replicas starting at once could race between `getUser` and `createUser`; a `51003` (user already exists) now falls through to `updateUser`. Verified with four init containers started at the same moment: all exit 0.
* **Signed releases fail closed.** A missing `SHA256SUMS.sigstore.json` used to be taken for a release from before signing. From 6.6.0, the first signed release (pre-releases included), the installers refuse when cosign is installed and the bundle cannot be fetched; older tags keep the unsigned-with-warning path. Tested in `InstallerReleaseRefTest` (9.8.7 and 6.6.0-RC1 refused, 6.5.0 warned) and by hand for `install.ps1`.
* **Redacted audit entries carry no signature.** The copy `read_audit_trail` returns with the prompt redacted no longer keeps the original `hmac` and `agentSignature`, which covered the unredacted payload and would have made an intact entry look tampered.
* **Second review round.** `keycloak-admin-rotate` passes `-n` to `kcadm update … reset-password` (that endpoint has no GET; re-verified live). From 6.6.0 a missing `SHA256SUMS` stops the install too, with or without cosign, since without it no download is checked; older tags keep the warning. `mongodb-app-user` in `docker-compose.yml` warns when `MONGO_APP_PASSWORD` is unset or equals the root password. Failing in that case would break every existing install and the zero-config quick start. TLS between the compose services stays out of scope, as the review document records ("plaintext intra-service traffic").
* **No start-up window for an old Keycloak volume.** `keycloak-admin-rotate` now leaves a marker (`.eddi-admin-verified`) in `keycloak-data` once it has seen `admin` refused, and `keycloak-guard`, which mounts the volume read-only, refuses a non-loopback bind for an existing volume (one with an `h2` directory) without it. The default login of an old volume is therefore never published, not even for the seconds before the rotation; such a volume is started once on loopback. Verified live: old volume refused off loopback, rotated on loopback, then accepted; a fresh volume accepted at once. `ComposeStackTest` runs the guard against a volume with and without the marker.

***

## docs(loadtest): adaptive turn limit judged with Retry-After-honouring clients — dropped (2026-10-18)

**Repo:** EDDI · **Branch:** `docs/adaptive-limit-retry-measurement` (on top of `feat/turn-admission-hardening`)

### What changed and why

The adaptive turn limit parked on 2026-10-17 lowers `eddi.conversation.max-in-flight-turns` while the mean MongoDB pool wait exceeds 100 ms. It had been judged with k6 clients that ignore `Retry-After`. It has now been measured again with the benchmark suite's `--retry-503 10` clients (PR #1086): limiter off against on, `down -v` before every run, 2,500 conversations × 10 turns and a 5,000-user burst, 3 s mock LLM, three rounds. The results and the method are in [`scripts/loadtest/results/admission-2026-10-17.md`](https://github.com/labsai/EDDI/tree/main/scripts/loadtest/results/admission-2026-10-17.md). No code changes.

* **Not shipped.** On a quiet machine the limiter gained 12–15 % goodput in the steady scenario, cut its p99 and left the p95 even. But it abandoned turns in every burst run (603 and 102) and in the contended steady run (1,464), against 0 with it off. That fails the ship criterion: the limiter must beat "off" without raising abandoned turns.
* **The pool-wait signal does not track database saturation.** A per-second sampler put it next to mongod `opcounters`, `globalLock` queue and CPU. Pool wait correlated negatively with mongod ops/s in nine of ten runs. The wait was high while mongod ran at a fraction of its peak, with free pooled connections and an empty lock queue. It measures CPU contention in the EDDI JVM, which is why another stack's load test drove the limit down to 92. `mongodb_driver_pool_waitqueuesize` moves with it, so it is no better.

### Design decisions

* No replacement signal was built. A signal that really measured MongoDB saturation would not have fired in these runs (mongod stayed far below its peak), which is the same as "off". The steady gain points at CPU instead: a static `max-in-flight-turns` sized to CPU, rather than to heap, is the next thing to measure.

### What's next

* Delete the local branch `wip/adaptive-turn-limit` (commit `63659ba18`) once the user agrees.
* Measure a CPU-sized static in-flight limit against `auto` with the same retrying clients.

***

## docs(loadtest): static, CPU-sized in-flight turn limit measured against `auto` — default unchanged (2026-10-18)

**Repo:** EDDI · **Branch:** `docs/static-turn-limit-measurement` (on top of `feat/turn-admission-hardening`)

### What changed and why

The adaptive limiter measured earlier the same day gained steady goodput while it held in-flight turns at about 900–1,900. That suggested a static `eddi.conversation.max-in-flight-turns`, sized to CPU rather than heap, might keep the gain without a controller. This was measured against the default `auto` (2,602 at `-Xmx6g`) on 20 cores, with the benchmark suite's `--retry-503 10` clients (PR #1086). Scenarios: 2,500 conversations × 10 turns, and a 5,000-user burst, both with a 3 s mock LLM. Each run started from `down -v`, configurations were interleaved, and there were 2–7 uncontended rounds per configuration (36 runs). The results are in a new section of [`scripts/loadtest/results/admission-2026-10-17.md`](https://github.com/labsai/EDDI/tree/main/scripts/loadtest/results/admission-2026-10-17.md). No code changes.

* **Steady:** 2000 and 1500 tie with `auto` (median 228–234 turns/s, p95 including backoff about 20–22 s). 1000 and 600 abandon turns (45 and 619) without gaining throughput, and 600 loses a third. No static limit reproduces the adaptive limiter's 12–15 % gain.
* **Burst:** 2000 has the higher unpaired median (333 against 275 turns/s) and a narrower range (281–355 against 185–427). Paired by round it is a tie: three wins each, median difference +2.5 turns/s. It also abandons turns (9 over six runs against 0 over seven) and has 3–4 s worse p95 and p99 totals. 1500 and below abandon 70–2,000 turns per burst.

### Design decisions

* **No new default.** No candidate beats `auto` without raising abandoned turns, the same criterion the adaptive limiter failed. With closed-loop clients that honour `Retry-After`, a lower limit moves the waiting from EDDI's queue into client backoff while throughput stays where the CPU puts it.
* **About 2,000 is a deployment choice, not a default.** It is documented as an option for operators who want a predictable burst floor more than the best case.

### What's next

* Nothing on admission control. A CPU-aware limit would need EDDI's own share of each turn's latency, which EDDI cannot measure without timing every LLM call.

***

## ⚡ perf(startup): derive the audit keys while the vault derives its KEK (2026-10-18)

**Repo:** EDDI (`perf/startup-parallel-kdf`)

### What changed and why

Thread dumps of the main thread during boot showed it in PBKDF2 twice, one after the other: the audit ledger's HMAC key (`AuditKeyring.initialize` → `AuditHmac.deriveHmacKey`) and the vault KEK (`EnvelopeCrypto.deriveKeyFromString` from `VaultSecretProvider.onStartup`). Each is 600,000 iterations of HMAC-SHA256, a few hundred milliseconds, and they share no input.

* **`AuditKeyring.deriveEarly`** is a new `StartupEvent` observer at `APPLICATION - 100`, ahead of the vault's at `APPLICATION`. It starts `initialize()` on a virtual thread and returns, so the audit keys are derived while the main thread loads the vault salt and derives the KEK.
* **The join is the existing lock.** `AuditKeyring.onStartup` (`APPLICATION + 100`) and every key accessor call `initialize()`, which waits on the keyring's monitor until the derivation is done. The volatile `initialized` fast path and the `synchronized` double-check are unchanged, so the keys are complete before readiness and before the first entry is signed.
* **`initialize()` is no longer a `@PostConstruct`.** Arc instantiates the bean on the thread that first touches it — the observer's, the main one — so a `@PostConstruct` derivation would have run inline again. Every method that reads a key already called `initialize()` first; `fromMasterKey` still does.
* **Failure is not swallowed.** If the early derivation throws, `initialized` stays false and the next caller derives again on its own thread and sees the exception, as before.

The KDF, salts, iteration count and therefore every key are unchanged: existing signatures and vault entries verify as before.

### Tests

`StartupKeyDerivationTest` pins both derivations to known answers computed outside the JVM (Python `hashlib.pbkdf2_hmac`), checks that keys derived through `deriveEarly` equal those from an inline `initialize()`, and that `deriveEarly` returns without doing the work itself. Mutation-checked: 600,001 iterations in `AuditHmac` or in `EnvelopeCrypto`, and running the early derivation inline, each fail it.

### Measured

Fast-jar boots of `origin/main` and this branch, built with `-DskipUi=true`, against a local MongoDB 7 with a vault master key set, 8 runs each in alternating order after one discarded warm-up (Windows 11, JDK 25.0.1, a host shared with other work):

|        | `started in` median (min) | to `/q/health/ready` median (min) |
| ------ | ------------------------- | --------------------------------- |
| before | 4.03 s (3.51 s)           | 4.90 s (4.42 s)                   |
| after  | 3.52 s (3.17 s)           | 4.48 s (4.21 s)                   |

About 0.4–0.5 s off a \~4 s boot. The spread between runs is of the same order, so read it as "one PBKDF2 derivation leaves the critical path", not as a precise figure. On a cold, contended container the derivations are slower, and so is the saving.

***

## feat(loadtest): benchmark suite — streaming TTFT, cluster scaling, group discussions, DB-ops CI gate (2026-10-17)

**Repo:** EDDI · **Branch:** `feat/loadtest-benchmark-suite`

### What changed and why

EDDI leads on concurrent stateful conversations per node, but nobody — EDDI included — publishes numbers for stateful multi-turn load, time to first token overhead, scaling efficiency or multi-agent throughput. This extends the [load-test harness](https://github.com/labsai/EDDI/tree/main/scripts/loadtest/README.md) so those numbers can be published reproducibly and regressions caught. Nothing under `src/main` changed.

* **`stream`**: time to first token over EDDI's SSE endpoint (`POST /agents/{id}/stream`) and over `POST /v1/chat/completions` with `stream: true`, against the same streamed request sent straight to the mock as calibration; overhead = EDDI's TTFT minus the mock's, per percentile. The WireMock stub streams equal-length SSE events with `chunkedDribbleDelay`, so each slice is exactly one event, with a configurable first-chunk delay, token count and spacing. Driver: [`drivers/stream_driver.py`](https://github.com/labsai/EDDI/tree/main/scripts/loadtest/drivers/stream_driver.py), asyncio on the standard library, in a pinned `python` image on the compose network.
* **`--retry-503 N`** (k6 `RETRY_503`, off by default so earlier results stay comparable): a client that honours 503 + `Retry-After` (capped, jittered) and resends the same turn up to N attempts; reports latency including backoff, attempts per turn and abandoned turns. Requested by the admission-control work, whose shedding otherwise read as collapsed goodput. `LOADTEST_COMPOSE_EXTRA` adds compose overrides for EDDI settings under test ([`overrides/in-flight-100.yml`](https://github.com/labsai/EDDI/tree/main/scripts/loadtest/overrides/in-flight-100.yml)). Measured live (laptop, [`results/retry-2026-10-18-report.md`](https://github.com/labsai/EDDI/tree/main/scripts/loadtest/results/retry-2026-10-18-report.md)): 500 conversations against 100 in-flight turns, 1 s mock, fresh database each: the default client completed 339 of 2,500 turns (17.5 turns/s, 762 failed starts); the retrying client 2,404 (43.3 turns/s, 74 abandoned, 22 failed starts), with p95 including backoff of 18 s. The first live run showed refused *starts* were not retried, so starts now back off too.
* **Overhead as a first-class metric**: every turn run reports `turn_overhead` (latency minus the mock's delay) at p50/p95/p99.
* **Cluster scaling** is `main`'s cluster mode ([labsai/EDDI#1092](https://github.com/labsai/EDDI/pull/1092), `cluster-matrix`), which landed while this branch was open. This branch first had its own `up --nodes N` / `scaling` overlay for the same purpose; merging `main` removed it rather than keep two cluster paths (`cluster-*` is a full stack with a three-node NATS cluster and per-node metrics). The laptop sample's scaling section was measured with the removed path; `report` no longer renders scaling, `cluster-matrix` writes its own `results/cluster-scaling-<date>.md`.
* **`group`**: N-member group discussions (`POST /groups/{id}/conversations`, k6 [`groups.js`](https://github.com/labsai/EDDI/tree/main/scripts/loadtest/k6/groups.js)); member turns per second across members.
* **`gate`** and [`.github/workflows/loadtest-db-ops.yml`](https://github.com/labsai/EDDI/tree/main/.github/workflows/loadtest-db-ops.yml) (manual dispatch, nightly, PRs touching the harness): a fixed scenario on a GitHub runner fails when MongoDB operations per turn exceed [`thresholds/db-ops-mongo.json`](https://github.com/labsai/EDDI/tree/main/scripts/loadtest/thresholds/db-ops-mongo.json). Throughput and latency are artifacts, not gates.
* **`report`**: one Markdown benchmark page per label — hardware, image digests, build commit, JVM, method, every number, and the exact commands (with their `LOADTEST_*` variables) to reproduce it. Sample: [`results/laptop-2026-10-17-report.md`](https://github.com/labsai/EDDI/tree/main/scripts/loadtest/results/laptop-2026-10-17-report.md).
* **`up --db postgres`**: PostgreSQL with `pg_stat_statements`; database operations per turn are statement executions by verb.
* **Sharing a machine**: compose files are split (base, `mongo`, `postgres`, `app`, `cluster`) and `COMPOSE_PROJECT_NAME` keeps stacks apart. Before a measurement the driver waits while another stack's k6/SSE container runs, and a result measured while one appeared records `contended_by` (⚠ in the report).

### Design decisions

* **A Python SSE driver, not k6 + xk6-sse.** xk6-sse needs a custom k6 build (Go toolchain, xk6, a community extension, each to pin); one standard-library file in a pinned image has nothing to build or drift, and its definition of "first token" is readable in place.
* **What the gate gates.** Document counts for insert/update/delete and the operations on the collections a turn touches itself (conversation memory, descriptors, vault, user memory) are identical run to run. Reads of agents, workflows, quotas and the audit ledger follow the clock (cache refresh, batched flushes) and grow on a slower runner. The audit ledger flushes from a queue every 3 s, which first moved the insert total by a batch either way on short runner runs (3.8 and 2.66 vs 3.2 per turn); every measurement now waits for that queue to drain plus one flush interval before each snapshot. The clock-driven reads are reported and covered only by a loose total-query ceiling (5 ops of headroom). Measured: 3 runs on this laptop agreed to 0.01 per turn on every per-collection counter, and the first GitHub-runner run matched them exactly.
* **Ceilings in git, not the Actions cache**, which evicts entries at its size cap.

### Measured (laptop, not publishable)

See the sample report. On `4b83ffb8b`: about 22.5 MongoDB operations per turn (17 queries, 3.2 inserts, 2 updates); streamed tokens reach the client unbuffered on both paths (token spread equal to the mock's).

### Next

* Run the suite on dedicated hardware for publishable numbers.
* When a round-trip cut ([labsai/EDDI#1055](https://github.com/labsai/EDDI/pull/1055) and its follow-up) lands, the gate reports "well below": lower the ceilings with `gate --record` in that PR.
* Not diagnosed: at 10–50 conversations with a 0–100 ms mock the laptop shows EDDI overhead p50 135–190 ms and p95/p99 stalls of 1.5–5 s; check on an idle machine before reading anything into it.

***

## 🩹 fix(manager): self-hosted provider hints on the operator activation screen (2026-10-17)

**Repo:** EDDI (`feat/llm-openai-compatible-provider`)

Browser-checked the self-hosted provider in the agent wizard and operator activation. The wizard explained the required model id and Base URL; the operator activation screen showed both fields bare. It now shows the same hints (reusing the wizard's strings) and links them to the inputs with `aria-describedby`. Files: [`operator-activation.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/components/operator/operator-activation.tsx).

***

## 🩹 fix(manager): webhook channel — explain the options, label every field (2026-10-17)

**Repo:** EDDI (`feat/channels-signed-webhook`)

Browser-checked the webhook channel in the create dialog and on the detail page. Fixed: the signature scheme and conversation strategy were bare identifiers (now a one-line explanation of the chosen option); the generic-HMAC and event-type inputs had only placeholders and untranslated English `aria-label`s such as `signatureHeader` (now visible, translated labels); the last create step talked about trigger keywords, which a webhook does not have; those grids now stack on a narrow screen. A `Billing Webhook` entry was added to the mock channel store. Files: [`webhook-settings.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/components/channels/webhook-settings.tsx), [`create-channel-dialog.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/components/channels/create-channel-dialog.tsx).

***

## Fewer MongoDB round trips per turn, part 2 (2026-10-17)

**Repo:** EDDI · **Branch:** `perf/turn-db-roundtrips`, stacked on `perf/turn-mongo-roundtrips` (#1055)

What #1055 left of Phase 1 of the [throughput plan](https://github.com/labsai/EDDI/tree/main/planning/throughput-optimization-plan.md) (WS1, WS3a, WS3f). Measured with `scripts/loadtest` against #1055 merged with main: **MongoDB round trips per turn 9.4–10.6 → 6.3–6.8** (queries 7.1–8.2 → 4.2–4.5; 19.6 on main before #1055). `conversationmemories` reads per turn 4.1 → 2.1, `audit_ledger` up to 1.1 → 0.1, `agents` + `workflows` up to 0.3 → 0. Throughput and p95 improved in every run, but the laptop was shared with other load tests, so the latency numbers are indicative only. Details in [`scripts/loadtest/results/p1-roundtrips-2026-10-17.md`](https://github.com/labsai/EDDI/tree/main/scripts/loadtest/results/p1-roundtrips-2026-10-17.md).

**What changed**

* **Turn start reads state and revision once** (`ConversationStepRunner.runConversationStep`). The queued-say guard read the stored state and the stale-snapshot guard (`reloadIfSuperseded`) read the stored revision, two projection reads of the same document. `IConversationMemoryStore.getStateAndRevision` answers both in one read (MongoDB projection, PostgreSQL `SELECT`). Its default returns `null`, and then the caller asks the two old methods, so a store or a test double that predates it behaves exactly as before.
* **No committed-state read for a turn that was not paused.** The persist callback's `finally` passed `committedStateOrError(...)` to `DeferredDelivery.deliver`, a no-op unless a paused completion was deferred. Java evaluated the argument anyway: one state read per turn for nothing. It now reads only when a delivery is pending.
* **The audit collision check is one query per flush** (`AuditLedgerService.detectForeignSequenceAllocation`). It asked `maxSequence` once per conversation in every flushed batch, about one read per turn under load, on connections the turns wait for. `IAuditStore.maxSequences` answers the whole batch: MongoDB `$sort` on the `(conversationId, sequence)` index plus `$group/$first`, PostgreSQL one indexed `MAX` per id over `unnest`. The default loops `maxSequence`, as before. The seed itself was already once per conversation on both paths: the single-node counter table, and the NATS KV counter in cluster mode. The detector does not run in cluster mode, where positions come from the shared counter.
* **WS1: `WorkflowTraversal` no longer expires after 2 s.** Turns of one conversation are rarely 2 s apart, so practically every LLM turn re-read the agent, its workflows and their extension configs. Agent, workflow and extension versions are immutable, so the traversal cache is now a size-bounded Caffeine cache (1,000 entries) with no TTL. Entries for an agent are dropped by the same `AgentFactory` deploy/undeploy hook that clears #1055's `AgentConfigurationCache`. Only complete traversals are cached, as before. The callers only read the cached configs (checked: `LlmTask`, `HttpCallToolsProvider`, `McpToolsProvider`, `RagContextProvider`, `TurnBudgetValidator`); the 2 s cache already shared them between concurrent conversations.

**Looked at, not changed**

* **Inserts (3.1 per turn in `opcounters`) are already batched.** The counter counts documents: about 3 audit entries per turn, written as one `insertMany` per flush (the profiler showed 300 entries in one command). The only other inserts are one conversation document and one descriptor per new conversation.
* **`GdprComplianceService.isProcessingRestricted`** is the remaining usermemories read on every turn (about 1 per turn). Caching it needs a product and security decision about cluster invalidation, so it stays uncached by design. The existing opt-in TTL (`eddi.gdpr.restriction-cache-ttl-seconds`) is unchanged.

**Tests**: `ConversationServiceTurnStoreReadsTest` (a whole say turn through the real `BaseRuntime`, counting conversation-store calls, plus the fallback path and the superseded-turn reload), `AuditLedgerServiceTest.theCollisionCheckIsOneReadPerFlush`, `maxSequences` against real MongoDB and PostgreSQL, and `WorkflowTraversalCacheTest` (no expiry with time, per-agent invalidation, a degraded traversal is not cached). All were mutation-checked.

***

## chore(deploy): production-sized runtime defaults for the image, Helm and Kustomize (2026-10-17)

**Repo:** EDDI · **Branch:** `chore/enterprise-runtime-defaults`

### What changed and why

The defaults fitted a laptop demo, not the load profile the throughput work measured. EDDI waits on LLMs far more than it computes, so memory, not CPU, decides how many conversation turns a node runs at once. Each in-flight turn holds its conversation (about 1 MB for short conversations in the load-test harness). The old defaults were a 1 GiB limit at the image's 50 % heap ratio, i.e. a 512 MB heap, and ParallelGC, which stops every thread on a full collection.

* **Image** ([`Dockerfile`](https://github.com/labsai/EDDI/tree/main/src/main/docker/Dockerfile/README.md)):
  * `JAVA_MAX_MEM_RATIO=75`.
  * `GC_CONTAINER_OPTIONS=-XX:+UseG1GC`, replacing run-java's ParallelGC.
  * `-XX:+ExitOnOutOfMemoryError` on `JDK_JAVA_OPTIONS`, so the flag survives an operator's `JAVA_OPTS`. A JVM out of heap exits and is restarted, instead of holding its turns and leases.
* **Helm** `eddi.resources` and the **Kustomize base**: request 1 CPU / 3 GiB, limit 4 CPU / 3 GiB.
  * Memory request = limit, for Guaranteed QoS.
  * A CPU limit is kept because the JVM sizes its GC, carrier and Jlama threads from it.
* **Production overlay:** request 2 CPU / 4 GiB, limit 4 CPU / 4 GiB.
* **Quickstart:** 1 GiB request, 2 GiB limit (was 384 Mi / 1 Gi).
* **docker-compose.yml:** `ulimits.nofile` 65536.
* **Docs:** a "Sizing a node" section in [`docs/kubernetes.md`](https://docs.labs.ai/deployment-and-infrastructure/kubernetes.md#sizing-a-node), and the Jlama memory note in [`docs/langchain.md`](https://docs.labs.ai/agent-configuration/langchain.md). In-process Jlama weights are memory-mapped outside the heap, so lower the ratio and add the model size to the limit.

### Design decisions

* **G1, not ZGC, as the default.** G1 is the JDK's own server default and fits heaps of a few GB. ZGC is documented as the override for heaps of 8 GB and more.
* **Keep a CPU limit.** Removing it avoids CFS throttling, but the JVM would then size its threads for every core of a large node. The limit stays, set generously (4) with a request of 1.
* **No bump to the dependency charts** (MongoDB, PostgreSQL, Keycloak). Size them per installation.

### Not yet verified

* **The image's JVM command line** (heap ratio and GC through run-java) was not checked against a real container. Docker was unavailable when this was committed.
* **G1 vs ParallelGC under load** (p99 and the longest pause at 1000 conversations) is still to be measured with `scripts/loadtest`.

***

## 📦 chore(deps): dependency refresh before the 6.6.0 release (2026-10-17)

**Repo:** EDDI (`chore/release-6.6.0-deps`)

### What changed and why

A last pass over every pinned dependency before tagging 6.6.0. `pom.xml` already says `6.6.0` (the 6.5.0 post-release PR set it), so this changes no project version, only libraries and the Node toolchain.

* **Maven.** Every version literal in `pom.xml` was checked against Maven Central. Dependabot had already brought Quarkus (3.40.1), langchain4j (1.22.0 / 1.22.0-beta32), the Jackson overrides and the plugins to their latest releases. The only patch or minor still open was **classgraph 4.8.196 → 4.8.199**.
* **Node 24.21.0 → 24.22.0** (latest 24 LTS patch), moved in all the places `BuildQualityGatesTest` keeps equal: `pom.xml` `node.version`, `ci.yml` `NODE_VERSION` with `NODE_SHA256_LINUX_X64` (the linux-x64 `.tar.gz` line of the release's `SHASUMS256.txt`), and `mise.toml`. Both UI READMEs name the pinned version and were updated to match.
* **Manager and Chat UI.** `npm update --save` inside the existing semver ranges, run with Node 24.22.0 / npm 11.19.1. This includes React 19.3.1, Vite 8.3.4, Vitest 5.0.5 (covers the open Dependabot vitest-group PRs), eslint 10.13, typescript-eslint 8.71.2, Playwright 1.64.1, Radix UI minors, TanStack Query, i18next / react-i18next, lucide-react 1.59 (Manager), zustand and the fontsource packages. The Manager lockfile also deduplicates about 30 nested entries. The earlier advisory overrides still apply: the Chat UI ships a single `katex` 0.19.0 and the Manager resolves `postcss-selector-parser` 7.1.6.

### Deliberately not updated (majors that need their own migration)

| Dependency                                   | Current → available | Why not now                                                                    |
| -------------------------------------------- | ------------------- | ------------------------------------------------------------------------------ |
| `com.networknt:json-schema-validator`        | 1.5.9 → 3.0.8       | Rewritten API; the shared-artifact validators need porting                     |
| `de.undercouch:bson4jackson`                 | 2.18.0 → 3.x        | Built on Jackson 3, which the `ban-jackson3` enforcer rule blocks              |
| `com.github.victools:jsonschema-*`           | 4.38.0 → 5.0.0      | Also built on Jackson 3 (`tools.jackson`), so the same enforcer rule blocks it |
| `io.github.classgraph:classgraph`            | → 5.x / 6.x         | Major release; patch line taken instead                                        |
| `io.projectreactor.netty:reactor-netty-http` | 1.2.18 → 1.3.x      | Needs Netty 4.2; Quarkus still manages 4.1 (see the pom comment)               |
| `typescript`                                 | 5.9 → 7.0           | Native compiler port; its own PR                                               |
| `msw` (Manager)                              | 2.15 → 3.x          | Major release; the mock layer needs migrating                                  |
| `lucide-react` (Chat UI)                     | 0.577 → 1.x         | Major release with renamed icons                                               |
| `@types/node`                                | 24 → 26             | The runtime is Node 24; the types follow it                                    |

### Verification

`./mvnw clean compile`; Chat UI lint, typecheck, all tests and build; Manager typecheck, lint, `i18n:check`, build and the full vitest run (592 files, 8551 tests); `BuildQualityGatesTest` and the repo-wide guard tests (243 tests, three failures in `DeploymentManifestsTest`'s PowerShell `create-secrets.ps1` stub tests, which fail the same way on an untouched `origin/main` checkout on the Windows machine used, so they are environmental). The full backend unit suite, the integration tests and the E2E jobs were left to CI.

**Files:** [`pom.xml`](https://github.com/labsai/EDDI/tree/main/pom.xml), [`.github/workflows/ci.yml`](https://github.com/labsai/EDDI/tree/main/.github/workflows/ci.yml), [`mise.toml`](https://github.com/labsai/EDDI/tree/main/mise.toml), [`ui/manager/package.json`](https://github.com/labsai/EDDI/tree/main/ui/manager/package.json), [`ui/chat/package.json`](https://github.com/labsai/EDDI/tree/main/ui/chat/package.json), both `package-lock.json` files, both UI READMEs.

***

## docs(planning): conversation storage layout design, steps as records (2026-10-17)

**Repo:** EDDI · **Branch:** `docs/conversation-storage-design`

### What changed and why

[`planning/memory-architecture-plan.md`](https://github.com/labsai/EDDI/tree/main/planning/memory-architecture-plan.md) gains **§11, Conversation Storage Layout (Phase G)**. This is the long-term design the throughput plan's WS6/WS7 asked for. Today one conversation is one document (MongoDB) or one JSONB value (PostgreSQL), loaded in full twice per turn and, on PostgreSQL, rewritten in full on every append.

Load tests on the WS2 build measured the cost over 200-turn conversations:

* turns slow down 1.6–1.9× on MongoDB and 2.2–2.5× on PostgreSQL;
* PostgreSQL runs at 61–83 % of MongoDB's throughput;
* 62 % of PostgreSQL's database time goes to the append;
* PostgreSQL stores 256 kB of live data in 28 MB.

The design:

* **Layout:** a small header (CAS-updated every turn, with new `stepCount` and `lastInteraction` fields) and one record per step (MongoDB `conversationsteps`, keyed `{c, i}`; PostgreSQL `conversation_steps` with primary key `(conversation_id, step_index)`).
* **Reads:** a turn loads the header and a window derived from the agent's existing history/summary settings; older steps are fetched lazily by page, so every consumer keeps its semantics and absolute indexes.
* **Writes:** an append writes only new records, in one transaction on PostgreSQL and through a unique-key claim on MongoDB (no transactions needed). Undo, redo, rerun and HITL commits become narrow updates instead of full rewrites.
* **Data and rollout:** full history stays stored and readable through every surface (AGENTS.md §4.7). Migration is online behind `eddi.conversation.storage.layout`, with conversion on first write, a background sweep and its reverse for downgrades. Header digests later replace the commonest all-history scans.

Also:

* Phase G is added to §7 and its targets to §10.
* §3.4.1 now says that compaction changes what the LLM is given, not what is stored. It used to say the summary "replaces the raw history in `IConversationMemory`", which contradicted §4.7.

### Next

G1 (header counters) is small and independent. The rest waits for WS3a (one full load per turn).

***

## Manager UI for agent test suites ("golden conversations") (2026-10-17)

**Repo:** EDDI (`ui/manager`) · **Branch:** `feat/manager-agent-tests`, based on `feat/agent-test-harness` (labsai/EDDI#1065) — merge after it.

The regression harness from #1065 had no Manager UI; suites and runs were reachable only over REST and MCP. This adds it (WS6 phase 6.2, UI part).

**What changed**

* **Test suites are a resource type** (`testsuite`, store `/testsuitestore/testsuites`) in `RESOURCE_TYPES`, so list, create, edit, version history and delete come from the existing Resources pages. The form editor (`components/editors/test-suite-editor.tsx`, registered in `EDITOR_MAP`) covers defaults, tool mocks, cases, turns and every expectation field; the JSON tab stays available. Expectation fields are folded away per turn (progressive disclosure). Half-typed JSON never overwrites the last valid value.
* **Agent detail → "Golden conversations"** (`components/agent-tests/agent-tests-section.tsx`), collapsed by default and outside the draft fieldset: pick a suite, Run (`POST /agenttests/runs`, runs the saved agent version against the suite's current version), run history from `GET /agenttests/runs?agentId=`. The list polls while any run is `RUNNING`.
* **Run result side sheet** (`run-result-sheet.tsx`): per case → repetition → turn pass/fail, each failed expectation with expected and actual side by side, cost and duration, and tool calls that had no mock highlighted. `ABORTED`, `ERROR` and a cost-ceiling stop each get a notice saying the agent was *not judged* (or why the run stopped) and what to do.
* i18n: 129 keys in all 11 locales.
* Mocks: `test/mocks/agent-test-fixtures.ts` + `agentTestHandlers` (passing, failing, aborted, error and ceiling runs; a started run turns `PASSED` after 4 s). The OpenAPI contract test stays green with no new exemptions.

**Decisions**

* `ResourceTypeConfig` gains `duplicable: false` and `jsonSchema: false`: the suite store has no `POST /{id}` duplicate and no `GET /jsonSchema`, so the Manager does not offer or request them rather than shipping a 404 (the snippet/parser drift in the contract test's exemption list is the precedent we avoided repeating).
* **`api-client` keeps a 202 body when it parses.** It used to return `undefined` for every 202, which dropped the run id `POST /agenttests/runs` answers with. 202s with an empty or non-JSON body behave as before.
* `ClusterDrawer` gained an optional `widthClass` so the run sheet can be wider; no other caller changes.
* Operator prompt and allow-list now include agent test suite and run access, so `operator-revision.json` is bumped past main's revision with the new provisioning fingerprint.
* `en.json` and the other locales lose one duplicated block of `decisionSummary*` keys (the file already defined them twice; JSON keeps the last one) as a side effect of re-serialising — no value changes.

**Verified:** `npm run typecheck`, `lint`, `i18n:check`, and the unit suites for resources, editors, lib, hooks, i18n, mock contract and the new components; plus a headless-Chrome walkthrough in MSW mock mode (passing run, failing turn, aborted, error, run-in-progress → passed, suite editor, suite list). Screenshots are in the session notes folder.

**Not done / next:** generate-a-suite-from-a-conversation, an LLM-judge expectation and a deployment gate (all listed as follow-ups in `docs/agent-testing.md`); a Playwright e2e spec for the new screens.

***

## 💰 feat(manager): cost controls — per-conversation ceiling and a legible tenant budget (2026-10-17)

**Repo:** EDDI (`feat/manager-cost-controls`) — Manager UI for the backend in the tenancy cost-metering PR (`feat/tenancy-cost-metering`)

### What changed and why

Two cost settings shipped on the backend without a screen, and the tenant budget was still presented as a plain number.

* **Agent detail → new "Limits" section** ([`agent-config-sections.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/components/editors/agent-config-sections.tsx)) with `maxCostPerConversationUsd`. Empty means unlimited and **removes the field** from the document (never `null` or `-1`); `0` is kept as a real ceiling meaning no priced spend at all; a negative or half-typed value is flagged and not written. The section says that only priced models count. Parsing lives in [`cost-ceiling.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/cost-ceiling.ts).
* **Tenant quotas page.** The monthly-cost field now says what it counts (priced spend only), and the usage card gains a *Monthly cost budget* status that names which of four states the tenant is in: no budget, budget set but enforcement off, budget reached (models are serving fallback answers, tool calls refused), or spend versus remaining. It lists what is not metered and points at the `eddi.llm.spend.refused` metric — there is no REST endpoint for recent refusals, so none is shown.
* All 14 new strings are in all 11 locales.

### Design decisions

* A new section rather than a field inside an existing one: the ceiling bounds the whole agent whatever its memory, session or approval settings are.
* The budget block states the situation instead of leaving it to be inferred from a progress bar that turns red at 90%.

**Not done:** recent spend refusals on the quotas page need a backend endpoint; today they are only a metric and a per-step marker (`llm:spend_refused:<taskId>`).

***

## Platform Operator explains 503 capacity\_exceeded and node sizing (2026-10-17)

**Repo:** EDDI · **Branch:** `feat/operator-capacity-limits`

The 2026-10-17 throughput work made `eddi.conversation.max-in-flight-turns` (heap-derived with `auto`) the node's turn ceiling, but the Platform Operator knew nothing about it: asked why a turn came back 503 `capacity_exceeded`, or how big a node should be, it had no text and no tool to answer from.

**What changed**

* `ui/manager/src/lib/operator/system-prompt.ts` — a new "Turn capacity" section in the default body, in both scopes. It tells the three backend sources of `capacity_exceeded` apart by their `message` (the in-flight limit, `eddi.coordinator.max-active-conversations` for a new conversation, a node shutting down) and keeps an administrator drain apart, since that answers 409 with `Retry-After`, not 503. It states that the refusal is retryable backpressure with `Retry-After`, gives the `auto` formula as `InFlightTurnLimit` computes it ((max heap − 256 MB) ÷ `in-flight-turn-memory-mb`, floor 32), the 10–20 % headroom advice from the [configuration reference](https://docs.labs.ai/deployment-and-infrastructure/configuration-reference.md), the meters and alert (`eddi_conversation_max_in_flight_turns`, `eddi_turn_rejected_total{reason="in_flight_limit"}`, `EddiTurnCapacityReached`), and the remedies in order: turn latency, replicas ([clustering](https://docs.labs.ai/deployment-and-infrastructure/clustering.md)), heap, with the database pool kept in step.
* Two lines are added only when their tool is granted: what the coordinator status read shows (`activeConversations`, `queueDepths`, not the in-flight limit) and what the log read shows: a refused say/rerun is a WARN `Turn rejected for conversation …` carrying the refusal message, a refused new conversation under the coordinator cap is a WARN, and only a conversation start refused by the in-flight limit stays at DEBUG.
* `operator-revision.json` bumped to 20 (main took 18 for the model-catalogue refresh and 19 for #1079), so existing operators are offered the upgrade.
* Tests in `system-prompt.test.ts`.

**Decisions**

* **No allow-list change.** The numbers live at `/q/metrics`, which is not in EDDI's OpenAPI spec, so it cannot become a generated tool; the prompt says the operator cannot read them and names what the admin should look at. Exposing the limit and the in-flight count on `GET /administration/coordinator/status` would be the way to let the operator see them — a backend change, left as a follow-up.
* The per-conversation queue cap, the bounded MongoDB pool wait and the pool-wait meters (`feat/turn-admission-hardening`, PR #1085) are not described: that branch has not merged. They need a follow-up revision bump once it lands.
* Docs named in the prompt are top-level pages only: the image copies `docs/*.md`, so the monitoring guide is not served to the operator.

***

## perf(runtime): overload hardening — capacity check before any read, per-conversation queue cap, bounded MongoDB pool wait (2026-10-17)

**Repo:** EDDI · **Branch:** `feat/turn-admission-hardening`

### What changed and why

A load test and JProfiler session on 2026-10-17 (1,000 to 5,000 concurrent conversations, 3 s mock LLM) found that once turns run on virtual threads (#1045), the MongoDB connection pool is where a turn spends its time under load. Indexed single-document reads averaged 2.2–3.3 s inside the driver, while mongod's own profiler logged them at 15–20 ms.

* **Capacity check before any read.** `IConversationService.refuseIfAtCapacity` (a no-op default; `ConversationService` implements it against `eddi.conversation.max-in-flight-turns`). `RestAgentEngine` (`say`, `rerun`) and `RestAgentEngineStreaming` call it before the ownership check. Until now, a turn refused at the limit first read its descriptor and loaded its conversation. Admission in `admitTurn` stays the authoritative, atomic check.
* **`eddi.conversation.max-queued-turns-per-conversation` (default 20).** Turns of one conversation run one at a time, so a client that keeps sending without waiting for answers (a retry storm, a bot loop) only built a queue of turns, each holding a permit and a loaded conversation. One more than 20 waiting is now refused in `AbstractQueuedConversationCoordinator` with the existing 503 `capacity_exceeded`, counted as `eddi_turn_rejected_total{reason="conversation_queue"}`. The cap applies in both coordinators.
* **`eddi.mongodb.max-wait-time-ms` (default 10000).** The driver waited up to 120 s for a pooled connection, twice the turn timeout, so a saturated pool held turns long after their callers had given up. A `waitQueueTimeoutMS` in the connection string still wins.
* **`eddi.datastore.pool.wait` timer and `eddi.datastore.pool.wait.timeouts` counter** (MongoDB, `PoolWaitListener`). Micrometer's pool listener showed how many operations were waiting, never for how long. Both are on the Full Metrics dashboard's connection-pool panel. PostgreSQL already exports `agroal_blocking_time_*`.

### Measured

`scripts/loadtest`, 3 s mock LLM, 6 GB heap, everything on one Windows laptop (Docker Desktop), with its own compose project and ports. "Legacy" is this build with `eddi.mongodb.max-wait-time-ms=0`, i.e. the driver's 120 s.

| Scenario                                      | Legacy (120 s pool wait)                         | This change (10 s)                                                           |
| --------------------------------------------- | ------------------------------------------------ | ---------------------------------------------------------------------------- |
| 2,500 conversations × 10 turns                | 69 turns/s · p50 26.9 s · p95 65.7 s · 668 × 408 | **191 turns/s · p50 7.5 s · p95 21.9 s** · 73 × 408, 7 × 5xx, 1 × 503        |
| Burst: ramp to 5,000 users in 30 s, hold 60 s | 75 turns/s · p50 48.2 s · p95 73.7 s             | **240 turns/s · p50 13.3 s · p95 20.1 s** · 727 × 503 at the in-flight limit |

The bounded wait accounts for this difference: it is the only setting that differs between the two columns, and each run started on a fresh database. With the driver's 120 s, the p95 (66 s) ran past the 60 s turn timeout. Turns whose callers had already given up kept queueing for connections, and that abandoned work crowded out live turns. Each figure comes from a single run on a laptop, so read the ratio, not the absolute numbers. Details are in [`scripts/loadtest/results/admission-2026-10-17.md`](https://github.com/labsai/EDDI/tree/main/scripts/loadtest/results/admission-2026-10-17.md).

### Design decisions

* **No adaptive limit, yet.** A limiter that lowered the in-flight limit while the mean pool wait exceeded a target was built, tested and measured, then left out of this change. Under the harness, which drives clients that ignore `Retry-After`, it cut goodput (2,500 conversations: 191 → 27 turns/s; 5,000-user burst: 240 → 20 turns/s). In the burst, the pool-wait signal stayed around 470 ms while MongoDB served only about 500 operations/s. It is parked on a local branch, `wip/adaptive-turn-limit`. Judging it needs load-test clients that honour `Retry-After`; the benchmark-suite work adds them.
* **Queue cap default 20, not 5** (the throughput plan's WS4b proposal). Coordinator tests that queue 20 turns on one conversation are legitimate FIFO tests, and a chat channel can deliver several messages from a fast typist. 20 is beyond any human pace and still stops a loop.

### What's next

* The Platform Operator's prompt does not explain `capacity_exceeded`, nor any of the turn limits. A follow-up should add it, together with an operator revision bump.
* WS4a deadline gaps (skipping turns whose deadline expired while queued) touch `ConversationStepRunner`, which the per-turn round-trip follow-up to #1055 is changing; take them after that lands.

***

## 🐛 fix(cluster): leases that survive a busy node, turns that stop when they lose them, one turn per idempotency key across nodes (2026-10-17)

**Repo:** EDDI · **Branch:** `fix/cluster-resilience`

### What changed and why

An assessment of cluster mode (NATS leases with fencing, event bus, degraded mode) found the design sound and its failure scenarios tested. It also found a handful of places where a node under strain, or a NATS that hangs instead of refusing, does worse than the [clustering page](https://docs.labs.ai/deployment-and-infrastructure/clustering.md) promises. Per-turn database work is #1055's and node sizing is #1053's; neither is touched here.

* **Lease heartbeats get a thread of their own** ([`NatsConnectionManager`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/cluster/NatsConnectionManager.java), [`KvLeaseManager`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/cluster/lease/KvLeaseManager.java)). They shared a 2-thread scheduler with presence, the console's pollers, the HITL recovery sweep (a database scan) and every on-connect hook (up to 10,000 synchronous outbox publishes, bucket provisioning, the stale-lease sweep). Right after NATS came back, exactly when it is slowest, those hooks could hold both threads past the 20 s lease TTL and a live node lost every lease at once. Now the leases run on `leaseScheduler()` (one thread, nothing else on it) and the on-connect hooks on two threads of their own. A heartbeat pass also renews the held leases side by side on the virtual-thread I/O executor instead of one after another, so a NATS that answers in 2 s per call no longer stretches a pass over hundreds of leases past the TTL. The pass waits at most one heartbeat interval, so a stalled call never delays the next tick; a lease whose renewal is still in flight is skipped, never renewed twice at once.
* **A drained node hands its leader lease over** (`KvLeaseManager.setDraining`). It stopped running the leader's work (`tryAcquireKey` answers empty while draining) but kept the `leader.hitl-recovery` lease alive through its heartbeat, so no node ran HITL crash recovery for as long as the drain lasted — contrary to the method's own Javadoc.
* **Shutdown releases leases side by side, within a bound** (`releaseAll`): up to three NATS calls per lease, sequentially, could outlast the termination grace against a slow NATS. A lease it misses still expires by TTL.
* **A cancelled turn stops its tool loop** ([`ToolLoopRunner`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/ToolLoopRunner.java)). Lease loss, `/cancel`, a GDPR stop and the watchdog all raise the turn's cancel flag, but the loop only checked the thread's interrupt flag, so an agent loop ran all its remaining rounds — more model calls and side-effectful tools — for a turn whose result is discarded. It now checks the flag before every model call and every tool. The call already in flight finishes; interrupting it would also interrupt the persistence and dead-lettering that follow on the same thread.
* **Bounded NATS waits on the turn's thread.** A failed turn's dead letter retried its publish ten times; against a NATS that keeps the connection and answers nothing, each attempt ran into the 2 s request timeout — about 24 s on the failing turn's thread. The retry ([`JetStreamDeadLetterStore`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/cluster/JetStreamDeadLetterStore.java)) is now bounded by about 2 s and skipped when the client is disconnected or the stream answered with a refusal other than "not found" (a full stream is not re-provisioned on every refused publish); the entry stays in the node-local ring and is forwarded later. Audit position allocation ([`AuditClusterSupport`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/cluster/AuditClusterSupport.java)) stops asking NATS for one request timeout after a failure, so a turn's audit entries cost one timeout, not one each (they are recorded unsequenced meanwhile, as they already were on failure).
* **Dead-letter stream size cap**: new `eddi.coordinator.dead-letter.max-bytes` (1 GiB). The stream was bounded by age only, on the NATS volume the leases share. When full it refuses new entries (`DiscardPolicy.New`) rather than dropping the oldest an operator may still replay.
* **Event bus** ([`JetStreamEventBus`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/cluster/events/JetStreamEventBus.java)): the outbox is also flushed every 2 s while connected (an event whose async publish failed without a disconnect waited for a reconnect that might never come), at most one flush at a time; and resyncs coalesce — requests that arrive while one is queued join it, so N nodes asking for a resync after a long outage flush each node once more, not N times. Each flush is a wave of cache misses against the shared database.
* **`Idempotency-Key` holds across nodes** ([`ConversationService`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/ConversationService.java), [`TurnIdempotencyService`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/TurnIdempotencyService.java)). A duplicate that reached another node while the first request ran there missed that node's in-flight registry, became an owner, queued for the lease and, once it held it, ran the turn a second time over the newer document. The turn builder now re-checks the key when it rebuilds over a superseded document: under the lease, the check and the run are one step cluster-wide. The duplicate is answered as skipped (409 + `Retry-After`) and its retry is served the stored answer.
* **Autoscaling** (Helm chart 2.8.0 → **2.9.0**): `autoscaling.extraMetrics` and `autoscaling.behavior` are rendered as given, and each resource target may be `null`. A node waiting on LLMs runs hundreds of turns at little CPU, so a CPU-only HPA may never scale up; the docs show how to scale on in-flight turns (`eddi_runtime_executor_active{pool="turn"}`) through a custom-metrics adapter. The chart refuses an HPA with no metric at all, which CI's chart-guard step now asserts.
* **Docs**: [Clustering](https://docs.labs.ai/deployment-and-infrastructure/clustering.md) gains database-connection sizing (a stock PostgreSQL's `max_connections=100` is exhausted by a third replica at the default pool of 50; PgBouncer only in session mode, because EDDI takes session-level advisory locks), an Autoscaling section, a "NATS hangs" failure mode, and the behaviour above; [Kubernetes](https://docs.labs.ai/deployment-and-infrastructure/kubernetes.md) and the [configuration reference](https://docs.labs.ai/deployment-and-infrastructure/configuration-reference.md) list the new values. WS5 of `planning/throughput-optimization-plan.md` is marked superseded by cluster mode. The Platform Operator's prompt learns the dead-letter cap and that a drain hands over leadership (operator revision bump).

### Tests

* `KvLeaseManagerTest`: renewals side by side (6 leases at 300 ms each in well under the sequential 1.8 s), a lease with a renewal in flight is skipped, `releaseAll` side by side, a drain releases the leader lease but keeps conversation leases and the heartbeat does not take it back.
* `JetStreamDeadLetterStoreTest`: a hanging NATS holds the turn about 2 s, not 7+; a disconnected node does not retry or provision; the stream config carries the size cap and `DiscardPolicy.New`.
* `AuditClusterSupportTest`: after an outage, five more entries cost no NATS call; allocation resumes after the pause.
* `JetStreamEventBusTest`: five resync requests during a flush cause exactly one more flush; an outbox entry is flushed by the sampler without a reconnect.
* `ConversationServiceIdempotencyTest`: a duplicate queued on "another node" does not run again once the document holds its key; a queued turn with a different key still runs.
* `ToolLoopRunnerToolPolicyTest`: a turn cancelled during a tool runs neither the rest of the batch nor another model call.
* `DeploymentManifestsTest`: the HPA template's extra metrics, behavior, optional targets and no-metric refusal; chart version 2.9.0.

### Not done here

* Distributing one group discussion's member turns across nodes (today the whole discussion runs on the node that started it) — a design change, not a fix.
* A multi-node throughput benchmark — in progress separately (`scripts/loadtest`, 1→8 nodes).

***

## fix(test): two unit-test classes that failed on every Windows checkout (2026-10-17)

**Repo:** EDDI · **Branch:** `fix/flaky-local-unit-tests`

Both failures reproduced on a clean `origin/main` and on no CI run: each is a test that built its fixture in a form only Linux accepts. Neither is a product bug; in both cases the product code under test behaved correctly and the fixture never reached it.

### What changed and why

* **`McpApiToolBuilderExternalRefTest.oversizedJsonSpecWithEscapedKeyIsStillScanned`.** `specReferencing` spliced a `@TempDir` path into a JSON string unescaped. On Windows that path is `C:\Users\…`, and `\U` is not a legal JSON escape, so the spec was not JSON at all. The cases the raw-text pass catches still passed; this one rests on the decoded-tree pass alone (its `$ref` key is Unicode-escaped), which could not build a tree and refused the spec as "could not be parsed" instead of reporting the external reference. `rejectUnsafeInlineRefs` failing closed there is correct. The helper now JSON-escapes backslashes, so every case reaches the reference it is about.
* **`DeploymentManifestsTest` — "secret generator — fail-closed classification"** (three PowerShell cases). The Windows `kubectl.cmd` stand-in recognised the existence probe with a bare `find`. A Maven started from Git Bash hands its PATH down, with Git's Unix `find` ahead of `System32\find.exe`; that one rejects the argument, the stub's `errorlevel 1` branch took the error for "not the probe", and every probe exited 0. Every stub mode therefore read as "a Secret already exists", so the NotFound path refused to install and the unreachable/forbidden paths aborted with the wrong message. `create-secrets.ps1` classified each answer it was given correctly (checked by hand against the stub with a PowerShell-launched PATH). The stub now calls `%SystemRoot%\System32\find.exe` by full path. CI's ubuntu runner never takes this branch, which is why it stayed green.

### Design decisions

* Fix the fixtures, not the code: the guard and the generator were right, and loosening either to accommodate a malformed fixture would have weakened a security check.

***

## fix(groups): count every turn of a group member toward the group's cost ceiling (2026-10-17)

**Repo:** EDDI · **Branch:** `fix/group-cost-ledger-accumulation`

### What was wrong

`GroupCostLedger.accumulateMemberCost` fed a group's `totalCost`, which the `maxCostPerDiscussion` ceiling (I1) is checked against, through two faults:

* **It read the wrong value.** It took `audit:cost` from the last step of the member turn's snapshot and recorded it by replacement, on the assumption that the value was the conversation's running total. It is not: `LlmTask` accumulates `audit:cost` on the *current step*, and every new step starts without one. A member that spoke in several turns had only its latest turn counted. The comment in `MemberTurnExecutor` and the ledger's own Javadoc repeated the wrong assumption, and the tests stubbed the same wrong model (a growing "cumulative" `audit:cost`), so they passed.
* **Since 2026-09-26 it read nothing at all.** Member turns call `say` with `returnDetailed=true`, and the redaction of that projection (`f94036125`) withholds every `audit:*` key from the step data. From then on the ledger found no cost, so member spend counted $0 toward the ceiling. Only the discussion's own system costs (summarizer, stance summaries) still counted. Every unit test mocked `say` with a hand-built snapshot, so none of them went through the redaction.

### What changed

* `SimpleConversationMemorySnapshot` gains `conversationCost`, the sum of `audit:cost` over **every** step of the conversation, including the steps `returnCurrentStepOnly` leaves out. It is `@JsonIgnore` and in-process only, so it does not widen what any REST, MCP or SSE caller receives. The redaction is unchanged. `ConversationMemoryUtilities.convertSimpleConversationMemory` fills it, skipping NaN, infinite and negative values. It is `null` when no step carried a cost.
* `GroupCostLedger.accumulateMemberCost` records that total. It no longer reads step data. Replacement is now correct, because the value really is the conversation's running total. That holds in every case:
  * harvesting the same turn twice;
  * a skipped turn, whose snapshot shows the previous turn;
  * a HITL pause, whose resumed spend arrives with the member's next turn.
* `GroupCostLedger.retireConversation`: when `MemberTurnExecutor` swaps a member's ended private conversation for a fresh one under the same key, it first moves the ended conversation's entry to `key:endedConversationId`. That is the `key:child` shape nested groups already use, and the Manager's per-member digest already sums it. Before, the fresh conversation's first total overwrote the member's whole earlier spend.
* **Late callbacks from a retired conversation.** A turn that timed out on the ended conversation can still finish, and its callback arrives under the same key. The ledger compares the snapshot's conversation id with the member's active one and routes a mismatch to `key:<thatConversationId>`. That entry keeps the larger value, so the callback and the retirement can run in either order without double-counting or overwriting the replacement's total.
* **No window between retirement and replacement.** Retirement always leaves a retired entry, $0 if nothing was spent yet. A callback decides where its cost goes by whether that entry exists, and it reads and writes under the same monitor retirement holds. A late callback therefore lands correctly even before the replacement's id is published, while the member's conversation map still names the ended conversation.

### Design decisions

* **Not widening the redaction.** Letting `audit:cost` through, the way `audit:token_usage` is, would also expose the operator's configured pricing to any chatting user who sets `returnDetailed=true`. An in-process field gives the group engine what it needs and exposes nothing.
* **A conversation total, not per-turn deltas.** The snapshot carries no step index, so adding per-turn deltas could not tell a repeated harvest or a skipped turn's stale step apart from new spend. A total recorded by replacement is idempotent by construction.

### Tests

* `GroupCostLedgerTest` builds its snapshots through the real projection, with the flags a member turn uses. It checks that a two-turn member is counted in full ($0.05 + $0.07 = $0.12), and that two $0.06 turns trip a $0.10 ceiling that neither turn trips alone.
* `ConversationMemoryUtilitiesTest`: the sum covers steps outside `returnCurrentStepOnly`, poisoned values are skipped, and the field never reaches JSON.
* `MemberTurnExecutorTest`: an ended conversation's spend survives its replacement.
* Mutation-checked. Each of these reverts fails the new tests:
  * restoring the last-step read;
  * summing only the projected steps;
  * dropping the `retireConversation` call;
  * removing the late-callback routing;
  * recording a retired entry by plain replacement instead of the larger value;
  * routing by the conversation map alone;
  * skipping the $0 retired entry.

***

## 📱 fix(manager): every screen size, RTL, and state handling (2026-10-17)

**Repo:** EDDI (`fix/manager-layout-a11y`)

Half of a review of both UIs for click latency, every screen size and every state. This PR holds the Manager's layout, RTL, state-handling and accessibility fixes; the click-latency fixes and the Chat UI are in the companion PR on `fix/ui-click-responsiveness`. The two share no file and build independently.

### Every screen size and RTL (Manager)

* The chat drawer was a fixed 420px column, wider than a phone screen, and its Close button was unreachable. It is now a full-screen overlay below `md`, and Escape closes it. The operator panel no longer runs off the start edge on phones.
* Hover-only card and row actions (the kebab menus, deletes) did not exist on touch screens. The new `reveal-on-touch` utility in `index.css` shows them under `(hover: none)` and on keyboard focus, with 32px targets.
* Agent Studio rendered the mobile tabs and the desktop chat panel together at 768–1023px, mounting two chat panels. Both now switch at `lg`.
* The top-bar breadcrumb truncates instead of pushing the controls off screen. List tables scroll horizontally and hide their secondary columns below `md`. App shells use `h-dvh`, custom modals cap at `100dvh-2rem`, the main gutter is `p-4 md:p-6`, page headers wrap, and labelled three-column grids stack on phones.
* RTL: switch thumbs no longer slide out of their track, directional arrows and chevrons are mirrored, the toaster sits at the inline end, and the onboarding badge is centred.

### State handling and accessibility (Manager)

* The API-call header/query/body editor could silently overwrite a value: after a delete, Add reused an existing key name, and renaming on every keystroke merged rows. It now uses `nextFreeKey` and `RenamableKeyInput`, as the connection and rules editors already did.
* Escape inside the agent picker or a secret picker no longer closes and wipes the schedule form or the create-channel wizard (`defaultPrevented` is honoured). Neither form now discards edits on a backdrop click or Escape; the property-setter long-value modal does the same.
* Inline group-config edits are covered by the unsaved-changes guard. The version diff dialog uses `AccessibleDialog`.
* An Enter that confirms an IME composition (Chinese, Japanese, Korean) no longer commits half-typed text in the chip and tag inputs.
* The dashboard shows an error with a retry instead of "nothing here" when a load fails. Resource type counts no longer read "0" while loading. The A2A copy buttons report a clipboard failure.
* About 40 icon-only buttons gained accessible names. A count-plus-word concatenation was replaced with plural keys in all 11 locales (including `_many` and the Arabic categories).

***

## 🩹 fix(manager): long tool names wrap in a group member's "using …" line (2026-10-17)

**Repo:** EDDI (`feat/groups-member-tool-call-events`)

Browser-checked the member card during a streamed discussion. A long MCP tool name could not wrap and pushed the line out of the card, so it now breaks. The mock discussion stream emits a `member_tool_call` frame and holds it long enough to see. Files: [`agent-response-card.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/components/groups/agent-response-card.tsx).

***

## 🔒 fix(security): authorization gaps from the 2026-10-17 review — directory, workflow references, group USE checks, `platform.*` variables, strict group ownership, reserved principals, per-turn USE (2026-10-17)

**Repo:** EDDI (`fix/security-review-authz`)

Findings M2, M3, M5, L2, L3 and L4 of the 2026-10-17 security review. The authorization changes (M2, M3, M5, L2, L4) are no-ops for an administrator, and the workspace ones (M3, L4) are no-ops unless `eddi.workspaces.enabled=true` with authorization on. L3 is not an authorization check: a token whose principal is in a reserved namespace is refused whatever roles it carries.

### M2 — the user directory could be harvested by any editor

`GET /workspaces/directory` answered a one-character prefix with every matching person's name, username and e-mail, whether or not workspaces were enforced. Now:

* `eddi.workspaces.directory.enabled` has **no default**: unset, it follows workspace enforcement ([`UserDirectory`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/security/spaces/directory/UserDirectory.java) reads it as `Optional<Boolean>`, falling back to `WorkspaceSettings.isEnforcing()`). `application.properties` no longer sets it. A deployment without enforced workspaces records no one and suggests no one; shares are taken as typed, which is what an inactive directory always did.
* People are searched from **three** characters (`MIN_USER_QUERY` 1 → 3). Shorter queries return only the caller's own teams, not a 400, so the Manager's share box (which queries from the first keystroke) keeps working unchanged.
* A **non-administrator** is offered only their own teams and the people who share one of them. The restriction runs in the store — new `IUserDirectoryStore.searchWithinTeams` on MongoDB (`teams $in`) and PostgreSQL (`teams && ?`) — so a page is never filled with outsiders and then emptied. `eddi-admin` keeps the full search, known teams included.
* The **e-mail** (`detail`) is returned only to an administrator or to somebody who shares a team with the person — in suggestions and in a resource's grant list (`ResourceSharingService`, via `UserDirectory.detailFor(user, caller, isAdmin)`). Anyone else gets the username.
* Typing an exact username, verified e-mail or `team:<name>` still resolves (`resolveSubject` unchanged): only *suggestion* is narrowed.

Docs: [`workspaces.md`](https://docs.labs.ai/security-and-compliance/workspaces.md#finding-people-the-user-directory), [`configuration-reference.md`](https://docs.labs.ai/deployment-and-infrastructure/configuration-reference.md).

### M3.1 — a workflow could reference another space's private configuration

[`RestWorkflowStore`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/workflows/rest/RestWorkflowStore.java) now checks every `eddi://` reference a workflow names — each step's `config.uri` and each extension element's `config.uri` (parser dictionaries) — through `ResourceAccessGuard` on create, update (and so `updateResourceUri` and `AgentCascadeService`, which reach it over the loopback REST client with the caller's identity) and duplicate (deep or not). Configuration needs `VIEW`; an `ai.labs.agent`/`ai.labs.group` reference needs `USE`. An update need not re-justify a resource id the stored version already referenced — keeping (or re-versioning) a reference somebody with access made grants nothing new — but a new id must pass, including the prefix trick `updateResourceUri` allowed (a target id that is a prefix of the stored one replaces it with a different resource). References are keyed by type *and* id: `USE` grants nothing about a configuration, so an agent URI naming a configuration's id must not stand in for the configuration and get it the weaker check.

### M3.2 — moderator, facilitator, RECRUIT and duplicate skipped the USE check

* [`RestAgentGroupStore`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/groups/rest/RestAgentGroupStore.java)`.requireUseOnMembers` also checks `moderatorAgentId` and `facilitator.agentId`, skips `HUMAN` members (their id is a principal, not an agent), and `duplicateGroup` now runs it. MCP `create_group`, `update_group` and `create_group_from_template`, and `RestGroupTemplates`, all save through this store, so they are covered too.
* [`FacilitatorEngine`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/groups/FacilitatorEngine.java) takes the same `(agentId, principal) -> boolean` use check `RecruitAgentTool` has (M-A1) and asks it for the discussion owner before the deployment check, so a refusal does not reveal whether a private agent is deployed. `GroupConversationService` supplies it from a field-injected `ResourceAccessGuard` and the owner's own captured identity (`CallerIdentity.isAdminActingAs`).

### M5 — `platform.*` global variables were editor-writable

[`RestGlobalVariableStore`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/variables/rest/RestGlobalVariableStore.java) refuses a non-admin `PUT` or `DELETE` of any key starting with `platform.` (case-insensitive, any tenant) with a JSON `403` — `{"error": …, "reservedPrefix": "platform."}` — and a `[SECURITY]` WARN. `platform.operator` is what the Manager trusts for which agent is the Platform Operator and which prompt an Upgrade re-provisions. Reads are unchanged. No MCP tool writes variables. Every write and delete, refused or not, is already on the audit ledger through `AdminActionAuditFilter` (pinned by a test). Docs: [`global-variables.md`](https://docs.labs.ai/security-and-compliance/global-variables.md#rest-api).

### L2 — non-strict owner check on group-conversation reads and MCP group tools

`McpGroupTools.requireConversationOwner` (follow-up, continue, close, delete) and `read_group_conversation`, and `RestGroupConversation.readGroupConversation`, now use `requireOwnerOrAdminStrict`: a record with no owner is an administrator's alone. The lenient branch of `RestGroupConversation.validateGroupConversationOwnership` had no caller left (every call passed `hitlOperation=true`) and was removed with its parameter.

### L3 — reserved principal namespaces

New [`ReservedPrincipals`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/security/ReservedPrincipals.java) is the one list of principal prefixes EDDI makes up for itself — `openwebui:`, `slack:`, `webhook:`, `agent-test:`, `group:`, `system:`, `a2a:`, `mcp:`, `anonymous-`, `gdpr-erased:`, and the whole name `anonymous` — built from the existing constants where they exist. `NamelessPrincipalAugmentor` rejects an authenticated identity whose principal carries one (case-insensitively) with `401` and a throttled `[SECURITY]` WARN naming the prefix and issuer. `ReservedPrincipalsTest` scans `src/main/java` for `"<word>:" +` concatenations and `*PREFIX* = "<word>:"` constants and fails on any that is neither reserved nor listed in the test as not a principal. `webhook:` and `agent-test:` come from open PRs #1059 and #1065 and are reserved ahead of them. Docs: [`security.md`](https://docs.labs.ai/security-and-compliance/security.md#the-token-must-name-the-user).

### L4 — USE was checked only when a conversation started

New `ConversationAccessGuard.requireConversationTurnAccess`: the owner-or-admin check `requireConversationOwner` makes, plus — under enforced workspaces, for a non-admin — `requireAgentUseAccess` on the agent the conversation runs on (from the descriptor's `agentResource`, else the memory's `agentId`; a conversation that names neither is refused). Used by `RestAgentEngine.say`/`sayWithinContext`/`rerunLastConversationStep`, `RestAgentEngineStreaming.sayStreaming`, and MCP `talk_to_agent` and `chat_with_agent` (existing conversation). Nothing is cached across requests, so revoking a share stops the next turn. The service-level owner check inside `ConversationService.say` is unchanged — it also serves internal callers (Slack, schedules), which must not be USE-gated.

### Design decisions

* **Short directory queries return less, not 400.** The Manager searches from the first keystroke; an error there would surface as a failed request per keystroke.
* **Workflow updates check only newly referenced ids.** Checking every reference would lock a collaborator with `EDIT` out of a workflow whose owner referenced something only the owner may read; it would protect nothing, since the reference already exists.
* **L4 lives in `ConversationAccessGuard`**, next to the owner check it extends, so REST, streaming and MCP cannot drift apart; the workspace guard is reached through a lazy `Instance<ResourceAccessGuard>`.
* **Not done here:** the Manager is unchanged (it needs no change for M2; a hint to type three characters would help). The Platform Operator's prompt does not describe `platform.*` being admin-only; its writes run with the administrator's token, so nothing it does is refused.

**Tests:** `UserDirectoryTest` (new `Harvest` group), `UserDirectoryStoreContract.searchWithinTeams` (run against real MongoDB and PostgreSQL), `RestWorkspacesTest`, `RestWorkflowStoreReferenceAccessTest`, `RestAgentGroupStoreUseCheckTest`, `FacilitatorEngineTest` (two RECRUIT cases), `RestGlobalVariableStoreTest` (M5 cases), `AdminActionAuditFilterTest`, `McpGroupToolsTest` and `RestGroupConversationTest` (unowned records), `NamelessPrincipalAugmentorTest`, `ReservedPrincipalsTest`, `ConversationAccessGuardTest` (new `requireConversationTurnAccess` group), `RestAgentEngineTest`; `RestAgentEngineStreamingTest` updated for the new guard method.

***

## 🔒 fix(security): group-discussion attachments get an owner, quotas and a delete path (2026-10-17)

**Repo:** EDDI (`fix/security-review-data-lifecycle`) — security review 2026-10-17, finding M4 and its REST edge.

### What changed and why

A group discussion's inline attachments were stored with the five-argument `IAttachmentStore.store(...)`, which records no user. So no per-user quota counted them (one `eddi-user` could store 100 MB per discussion, without bound), deleting the discussion left the blobs behind with nothing pointing at them, and nothing keyed on the user could find them.

* **Owner.** `GroupAttachmentBinder` stores with the discussion's `userId`, so `eddi.attachments.max-per-user` and `max-total-bytes-per-user` count group uploads. A quota refusal no longer silently drops the file: the blobs the request had already stored are removed, the just-created discussion is failed, and the caller gets `400` (`GroupAttachmentRejectedException`; a `group_error` event on `/stream`). A blob the rollback could not remove is logged at ERROR and stays owned by the failed discussion, where its delete and the user's erasure still reach it.
* **REST edge.** `RestGroupConversation` re-checks the inline attachments against `eddi.attachments.max-size-bytes` per file and `max-per-conversation` / `max-total-bytes-per-conversation` for the discussion before anything is decoded or stored (`GroupAttachmentLimits`, computed from the base64 lengths), as it already re-checks its other request ceilings. The body itself stays bounded by `RequestBodyLimitGuard` before it is read. Human input (`submitHumanInput`) carries no attachments, so there was nothing to bound there.
* **Delete.** `GroupLifecycleOps.deleteGroupConversation` deletes the discussion's blobs before the document. A failure keeps the document (500, retryable) rather than orphaning the blobs.
* **`storageRef` guard.** `materializeAttachments` used to pass a `storageRef`-only attachment straight to `grantAccess` for every member. It now accepts one only from a trusted source conversation that can read the blob — the parent discussion, for a nested `GROUP` member, which `MemberTurnExecutor` passes through a new `discuss(...)` overload — and grants the child discussion access so the next level can repeat the check. A reference with no trusted source (anything a client could send) is refused. Unreachable from REST today; the guard keeps it that way.

### Files

[`GroupAttachmentBinder.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/groups/GroupAttachmentBinder.java), [`GroupAttachmentLimits.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/groups/GroupAttachmentLimits.java), [`GroupLifecycleOps.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/groups/GroupLifecycleOps.java), [`GroupConversationService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/GroupConversationService.java), [`MemberTurnExecutor.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/groups/MemberTurnExecutor.java), [`RestGroupConversation.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/RestGroupConversation.java), [`IGroupConversationService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/api/IGroupConversationService.java); docs [`attachments-guide.md`](https://docs.labs.ai/agent-configuration/attachments-guide.md), [`group-conversations.md`](https://docs.labs.ai/conversations-and-orchestration/group-conversations.md).

### Not done here

* Blobs stored by earlier releases still have no owner recorded, so they do not count towards a per-user quota. Deleting their discussion, or erasing its owner, now removes them.
* `close` still keeps the blobs (it keeps the transcript readable); only `delete` and erasure remove them.
* `McpGroupTools`' `delete_group_conversation` description and `docs/mcp-server.md` still name only artifacts and ephemeral agents (left to the workstream that owns the MCP group tools).

***

## 🔒 fix(gdpr): erasure and export reach group discussions; keyed database-log pseudonym (2026-10-17)

**Repo:** EDDI (`fix/security-review-data-lifecycle`) — security review 2026-10-17, findings M4 (erasure half) and L9.

### What changed and why

* **Erasure reaches group blobs (M4).** `GdprComplianceService.deleteUserData` resolved attachment owners from `getConversationIdsByUserId`, which returns 1:1 conversations only, so a discussion's shared files — stored under the group conversation's id — survived an Art. 17 erasure that reported success. The cascade now lists the user's group conversations (`GroupConversationStore.listAllForUser`, paged, exact-match re-check) before step 5c deletes them, and deletes the blobs of each discussion and of every member conversation it created. A failed lookup is reported as the step `groupConversationAttachments`. If that lookup fails, or a blob delete under a discussion or member id fails, step 5c keeps the discussion documents (reported as `groupConversations`, kept for a re-run) — they are the only record of the ids the blobs are stored under, the way step 4c keeps the snapshots on an incomplete vault sweep (review follow-up).
* **Export completeness (L9b).** The Art. 15/20 bundle now carries `groupConversations` (question, transcript, state, dates) and `sharedArtifacts` (content and revision history, via the new `ISharedArtifactStore.listAllForUser`), each capped at 1,000 with `groupConversationsTruncated` / `sharedArtifactsTruncated`, plus `failedCategories` for a store that failed. The group listing pages at the cap plus one row, not the storage maximum, since the store reads every row of a page in full. All three count against `complete()`. The attachment inventory covers the discussions' blobs and their member conversations'. `omittedCategories` shrinks to `schedules` and `journalEntries`, so the endpoint still answers 207 until those land. MCP `export_user_data` reports the same fields.
* **Keyed pseudonym (L9a).** The database-log pseudonym (and the pseudonym in GDPR log lines and compliance records) was `AuditHmac.pseudonymFor`, an unsalted SHA-256 any list of candidate e-mail addresses reverses. New `GdprPseudonymizer`: the audit ledger's keyed pseudonym (`gdpr-erased:k1:…`) when the ledger signs; otherwise `gdpr-erased:s1:…`, an HMAC under a random per-deployment salt kept with `ISecretPersistence.setMetaValueIfAbsent("gdpr-pseudonym-salt", …)` — the metadata store and insert-if-absent pattern `VaultSaltManager` uses for the KEK salt, present whether or not the vault is on; the unsalted form only if that store fails (WARN).

### Design decisions

* **No migration of old pseudonyms.** Rows erased earlier keep `gdpr-erased:<sha256>`: the raw id is gone from them, so they cannot be re-keyed, and a re-run erasure matches on the raw id only.
* **Audit-ledger step 7b keeps the unsalted token.** Its blanket update reaches only v1–v4 and unsigned rows (the store already gives v5 rows the keyed pseudonym of their signing key), and a v3/v4 row signs exactly the unsalted token; anything else would break its signature. In the default `redact` mode step 7a has already moved every reachable row to the keyed pseudonym.

### Files

[`GdprComplianceService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/gdpr/GdprComplianceService.java), [`GdprPseudonymizer.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/gdpr/GdprPseudonymizer.java), [`UserDataExport.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/gdpr/UserDataExport.java), [`AuditHmac.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/audit/AuditHmac.java), [`GroupConversationStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/groups/mongo/GroupConversationStore.java), [`ISharedArtifactStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/groups/ISharedArtifactStore.java), [`SharedArtifactStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/groups/mongo/SharedArtifactStore.java), [`McpGdprTools.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/mcp/McpGdprTools.java), [`IRestGdprAdmin.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/gdpr/IRestGdprAdmin.java); docs [`gdpr-compliance.md`](https://docs.labs.ai/security-and-compliance/gdpr-compliance.md), [`troubleshooting.md`](https://docs.labs.ai/getting-started/troubleshooting.md).

### Not done here

* `MongoUserMemoryStore` / `PostgresUserMemoryStore` still log the unsalted pseudonym in their erasure log lines (server log only, not stored data).
* The Manager's GDPR export view does not render the new sections yet.

***

## 🔒 fix(vault): a secret create says where the secret may go; discover-endpoints pinned as never resolving (2026-10-17)

**Repo:** EDDI (`fix/security-review-2026-10-17-h1-leftovers`, built on `fix/security-review-2026-10-17-high`). Covers the two **H1** leftovers from the 2026-10-17 security review.

### What changed and why

**1. `POST /apicallstore/apicalls/discover-endpoints`: checked, no fix needed.** The question was whether it resolves a `${vault:…}` or `${vars:…}` value from the request and sends it to a URL the caller picked, the way `discover-tools` did. It does not. `authHeaderRef` must already be a reference (a literal is a 400), and `McpApiToolBuilder.parseAndBuild` copies it verbatim into the generated calls' `Authorization` header. The spec fetch (`OpenApiSpecFetcher`) sends only `Accept` and `User-Agent`. The reference is resolved later, when an agent makes the call, and the secret's grant and `allowedHosts` are checked at that point. A new test in `RestApiCallsStoreBranchTest` pins this: discovery from an inline spec whose server is `https://attacker.example` returns both references exactly as written.

**2. A secret create needs `allowedHosts` under `enforce`. This is a breaking change.** `allowedAgents` limits which agents may reference a secret, but any editor can write a config that sends a referenced secret to a URL they choose. So a secret created without `allowedHosts` went wherever the next config edit pointed it. Under `eddi.vault.grant-enforcement=enforce` (the default), a create through `PUT /secretstore/secrets/{tenantId}/{keyName}` or `PUT /spacestore/secrets/{key}` now gets a **400** when `allowedHosts` is omitted or `[]`. `["*"]` (alone, never as a pattern) is the explicit opt-out and is stored as the empty list. `warn` and `off` keep the old behaviour, and a rotation may still omit the list. The user agreed to the break before it was made.

* `VaultGrantRequests.requireHostsOnCreate` is the host-side twin of `requireGrantOnCreate`, shared by both endpoints.
* `VaultHostAllowlist` gains `ANY_HOST`, `isExplicitlyUnrestricted` and `requestedHosts` (which maps `["*"]` to `[]`, and otherwise works like `validatedHosts`). `SetupSecretHosts` now delegates to it rather than keeping its own copy. The grant endpoint also accepts `["*"]` and treats it like `[]`, which clears the restriction.
* Space secrets could not carry `allowedHosts` at all. `SecretWrite` gains the field, and a 3-argument constructor is kept. `SpaceSecret` now returns the field.
* **Manager:** there is a shared `AllowedHostsField` with two choices, *Only these hosts* or *Any host*. It is used in Add Secret, in the secret picker's inline create, and on the Workspaces page, and the submit button stays disabled until one is chosen. The picker fills in the host from the config's URL for the MCP server URL, the A2A agent URL and the LLM `baseUrl`/provider default. The Workspaces page create now also sends `allowedAgents: ["*"]`: it sent no grant at all, so it already failed under `enforce`. Re-saving an existing space key sends no grant and no hosts, so the stored lists are kept. The MSW handlers model the `enforce` rules. The Operator prompt tells an admin a new secret needs its hosts. The operator revision is bumped.
* `seed-demo-agent.sh` sent neither list and failed under `enforce`. It now sends both, with the host taken from `EDDI_DEMO_LLM_TYPE`, or from `EDDI_DEMO_LLM_ALLOWED_HOST` when that is set (wired through `docker-compose.openwebui.yml` and `.env.example`). The cluster demo and `AuditAndSecurityIT` now send both lists too.
* Docs: `secrets-vault.md` (new *Required on a create* section), `workspaces.md`, `troubleshooting.md`, `upgrading-from-6.4.md` §7.1.

### Verification

* `./mvnw test` on `*Secret*Test,*Vault*Test,*Space*Test,AgentSetup*Test,SetupSecretHosts*Test,McpSetupToolsTest,ComposeStackTest,RestApiCallsStore*Test`: 6114 run, and one fails: `RestApiCallsStoreBranchTest.arbitraryPasswordInTheSpecUrlIsNotEchoed`. That test resolves a `.test` host over the network and fails locally with `UncheckedIOException`. This change does not touch it.
* Mutation check: with `requireHostsOnCreate` removed from both endpoints, `createWithoutHostsRefused`, `createWithEmptyHostsRefused` and `SpaceResourcesTest.createNeedsAllowedHosts` fail.
* Manager: `npm run typecheck`, `lint` and `i18n:check` pass, and so do the targeted vitest files (secrets, picker, workspaces, use-secrets, MSW handlers, i18n, operator-revision). The full vitest suite and the Playwright run are left to CI.

### Decisions

### Folded in when this branch was synced with `main` (2026-10-19)

\#1079 merged as a squash while this branch still carried its earlier commits, and `main` had moved on, so the sync merge resolves the overlap (operator revision 23 after later syncs past #1091, #1078 and #1056, `main`'s dialog sizing, `nameSeg` encoding in `space-resources.ts`) and carries the fixes below:

* **`main` was red** (#1066 against #1093: the response's cost sum converted every step that #1093 had made lazy). This branch fixed it first, but #1081 merged the same fix (`conversationCost` reads a lazy step list's total from the live steps), so the second sync takes `main`'s version and drops the duplicate.
* **`/setup-api` apiAuth was locked to the LLM host** by an explicit `allowedHosts` (#1079): the request's list names where the LLM key may go, so it no longer applies to `apiAuth`, which keeps the generated calls' target hosts; only an explicit `["*"]` carries over (`AgentSetupService.apiAuthRequestedHosts`).
* **Timing limits** in `ModelOutputParserFenceTest` and `ConversationRecallToolTest` rose from 100 ms to 1 s: the cubic case they guard against takes seconds, and 100 ms was a flake on a loaded CI runner.
* **Workspaces → space secret Save** stays disabled until the secret list has loaded: while it was loading or had failed, a save went out as a create with an open agent grant and could widen a key someone had narrowed.
* **The #1079 fragment** now says its decision about REST creates is superseded here, and that its operator revision landed as 19.

***

## 🔒 fix(vault): wizard-vaulted keys carry a destination list; discovery probes resolve no vault reference (2026-10-17)

**Repo:** EDDI (`fix/security-review-2026-10-17-high`) — security review 2026-10-17, finding **H1**

### What changed and why

Every key the setup wizard vaulted was stored with `allowedAgents ["*"]` and no `allowedHosts`. An `eddi-editor` can read the LLM configuration holding the `${vault:…}` reference, so they could copy it, set `baseUrl` to their own host, deploy, send one message, and receive the key (reproduced live). The MCP `discover-tools` probe was a second path needing no agent: it resolved a `${vault:…}` reference from the `X-Mcp-Authorization` header and sent the plaintext to the URL in the request body.

* **`AgentSetupService`** stores every secret it creates (the LLM `apiKey`; the `apiAuth` on `/setup-api`) with `allowedHosts`: the host of the base URL the request names, else the provider's own endpoint (new `SetupSecretHosts` — OpenAI, Anthropic, Gemini, Mistral, Hugging Face, jlama's model download, and the catalog of named OpenAI-compatible providers). For `apiAuth` it is the host of each generated httpcall's `targetServerUrl`.
* **New `allowedHosts` field** on `SetupAgentRequest` and `CreateApiAgentRequest` (appended last, positional constructors kept): an explicit list overrides the derived one, `["*"]` stores the secret open. Under `eddi.vault.grant-enforcement=enforce` an open secret is never created silently — when nothing can be derived and the request does not say `["*"]`, setup returns a 400 before writing anything. `warn`/`off` store it open with a `[SECURITY]` warning. Not exposed on the MCP setup tools.
* **Checksum reuse** now reuses an entry only when it is restricted to the same hosts, so a key an earlier release vaulted open is not handed to new agents.
* **`ISecretProvider.storeIfAbsent`** gained an `allowedHosts` overload, written in the same atomic insert by `VaultSecretProvider` (the default refuses a list rather than store the secret open).
* **`RestMcpCallsStore.discoverTools`** refuses a `${vault:…}`/`${eddivault:…}` or `${vars:…}` value in `X-Mcp-Authorization` with a 400 instead of resolving it.
* **Platform Operator** prompt: never set `allowedHosts`; ask for the endpoint when a setup is refused for an unknown destination. Revision 17 → 18 on this branch; `main` had moved to 18 in parallel, so the merge landed it as 19.
* Docs: `docs/secrets-vault.md` ("Where a wizard key may be sent"), `docs/mcp-client.md`.

### Design decisions

* **Derive, don't ask.** The wizard knows where the key is going. A required field would break every existing caller; a derived list closes the hole for all of them. The list only constrains a configuration that *names* an endpoint; one without uses the provider's built-in endpoint and is not checked (`ChatModelRegistry.ENDPOINT_KEYS`), so a slightly incomplete default list cannot break an agent.
* **Existing entries are not migrated.** A `vaultKeyName` or `${vault:…}` reference the admin names is used as it is. Keys already vaulted open stay open until an admin narrows them via `PUT …/grant`.
* **`allowedHosts ["*"]` is wizard-request syntax only.** The secrets REST API still rejects `*` in `allowedHosts`, and still accepts a create without the field. Refusing that under enforce too would be a breaking change for the Manager's Secrets page, so it is left as a follow-up. *Superseded by `2026-10-17-fix-security-review-h1-leftovers.md`: a REST create under enforce now requires `allowedHosts`, with `["*"]` as the explicit opt-out.*

### Tests

`AgentSetupAllowedHostsTest` (new, 11): derived and requested lists, enforce refusal, explicit wildcard, warn mode, reuse of open versus restricted entries, the named-key insert. `RestMcpCallsStoreTest`: a reference in the header is refused before the manager is called, and a literal still probes. `VaultSecretProviderAllowedHostsTest`: `storeIfAbsent` persists the list. `McpSetupToolsTest` now asserts the end-to-end `["api.openai.com"]`. Reverting the store argument or the probe check fails these tests (mutation-checked).

### Not done here

* `POST /apicallstore/apicalls/discover-endpoints` was not checked for the same probe pattern.
* The review's defence-in-depth items: requiring `eddi-admin` to save a non-default `baseUrl` next to a vault reference the caller did not create, and a Manager warning badge for "unrestricted destination".

***

## 🔒 fix(ssrf): the metadata guard refuses a host java.net.URI cannot read (2026-10-17)

**Repo:** EDDI (`fix/security-review-2026-10-17-high`) — security review 2026-10-17, finding **H2**

### What changed and why

`UrlValidationUtils.rejectCloudMetadataTarget` is the only check on the httpCalls path while `eddi.security.ssrf-protection.enabled=false` (the default). It read the host with `java.net.URI` and returned quietly when that host was null. `URI` gives a null host for any registry-style authority: an underscore (`x_y.attacker.com`), a percent-encoded host, or an IP literal with a trailing dot. The Vert.x client (`HttpClientWrapper`) parses the same string with `java.net.URL`, gets a host, resolves it and connects. An editor-written `targetServerUrl` naming such a host, with an A record of `169.254.169.254`, therefore reached the cloud metadata service.

* **`rejectCloudMetadataTarget`** now throws for an unparseable URL, and for an `http(s)` URL whose `URI` host is null or blank. When `java.net.URL` reads a different host, that host is checked as well. A URL with another scheme is still left to the caller.
* **`HttpClientModule.requireNotMetadataHop`** refuses a redirect hop with no host instead of following it. A hop with an unreadable host is refused through the same check.
* Docs: `docs/security.md`.

### Behaviour change

An httpCall, MCP server or A2A peer whose host contains an underscore (for example a Docker service name such as `my_api`) is now refused even with SSRF protection off. Give it a hyphenated alias. The JDK `HttpClient` used by every other path already refused such URLs.

### Tests

`UrlValidationUtilsTest.unreadableHostIsRefused` covers `x_y.example`, `169.254.169.254.`, `169%2e254%2e169%2e254`, a single-slash `http:/` and an unparseable URL. Its resolver answers "public" for everything, so only the new rule can refuse them. `HttpClientModuleTest` covers the same hosts as redirect hops, plus a hop with no host. The old assertion that an unparseable URL "is left to the caller" was inverted. Reverting the null-host throw fails both classes (mutation-checked).

***

## 🔒 fix(llm): linear JSON fence stripping; cap the recall tool's query (2026-10-17)

**Repo:** EDDI (`fix/security-review-2026-10-17-high`) — security review 2026-10-17, finding **H3**

### What changed and why

`ModelOutputParser.stripFence` ran every reply of a `convertToObject` LLM task (and every `FormatRetryRunner` retry) through a regex with three quantifiers competing for one whitespace run. A reply of three backticks, N spaces and a letter cost O(N³): 462 ms at 1,000 spaces, 3.7 s at 2,000, about an hour at 16,000. That CPU is spent on the turn thread, and any chat user can trigger it by prompt injection, as can a hostile model endpoint.

* **`stripFence`** is now `startsWith` / `endsWith` / `substring`, plus an ASCII case-insensitive check for the `json` tag. It returns the same result as the old regex for every input: the regex's leading `[ \t]*\r?\n?` and trailing `\s*` only moved whitespace that the `trim()` removed anyway.
* **`ConversationRecallTool`** reads only the first 500 characters of the model-written `query` (`MAX_QUERY_LENGTH`). Its range pattern was quadratic over a long digit run (10.9 s at 40,000 characters). A null query now means "the last summarized turns" instead of a `NullPointerException`.

### Tests

`ModelOutputParserFenceTest` (new, 24) keeps the old regex as an oracle and compares it with the new code on 23 fixtures, including non-ASCII look-alikes of `json` and a vertical tab. It also runs the 50,000-space input through `stripFence` and through `parse()`, each within 100 ms. `ConversationRecallToolTest` adds a 40,000-digit query (100 ms budget), a turn range followed by a 40,000-char tail, and a null query. Removing the cap fails the budget test at 10.4 s. The fence budget was not mutation-run: the old regex needs hours at 50,000 spaces.

### Not done here

The L14 alternation-loop regexes from the same review are untouched.

***

## 🔒 fix(security): outbound requests, parsers and templates from the 2026-10-17 review (2026-10-17)

**Repo:** EDDI (`fix/security-review-outbound-parsers`)

### What changed and why

One commit per finding of the 2026-10-17 security review (M8–M11, L13–L16). PR #1079 (`UrlValidationUtils`, `requireNotMetadataHop`, `ModelOutputParser`, `ConversationRecallTool`) is not redone here.

* **M9.1 — group artifact JSON schemas could `$ref` the network or the disk.** `ArtifactValidators` now builds its networknt factory with an `AllowSchemaLoader` in front that admits only the bundled meta-schemas (`classpath:draft/…`, `classpath:draft-0…`); an `http(s):`, `file:` or other `$ref` throws before anything connects or is read. Refs are resolved eagerly at save time, so the save fails with an actionable message, and a ref first reached at write time refuses the write. [`ArtifactValidators.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/groups/ArtifactValidators.java), [group-conversations.md](https://docs.labs.ai/conversations-and-orchestration/group-conversations.md)
* **M9.2 — pgvector host injection.** pgjdbc splices server names into its JDBC URL unencoded, so `host = "db/eddi?sslfactory=…&x="` injected driver properties and `a.com,10.0.0.5` dialled a host the metadata guard never saw. `EmbeddingStoreFactory.requirePlainHost` accepts one hostname (RFC 1123 labels, `_` allowed for Docker service names) or IP literal, nothing else, for pgvector and Qdrant. [`EmbeddingStoreFactory.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/EmbeddingStoreFactory.java), [rag.md](https://docs.labs.ai/agent-configuration/rag.md)
* **M9.3 — httpCall redirects with SSRF protection off.** A new redirect-handler guard (`HttpClientModule.refusingPrivateHops`) classifies each hop as public, private or loopback and follows a non-public hop only when the request that redirected (its connected address, else its resolved host) was in the same class, or the host is on `eddi.security.ssrf-protection.allowed-hosts`. A host-less `Location` is refused. Comparing with the previous hop is stricter than comparing with the first target. The DNS lookup of the hop and the client's own lookup are separate (JVM address cache); not pinned. [`HttpClientModule.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/httpclient/bootstrap/HttpClientModule.java), [httpcalls.md](https://docs.labs.ai/agent-configuration/httpcalls.md#redirects)
* **M9.4 — credential header detection.** `ApiCallExecutor` flagged a header as carrying a vault secret only when the resolved set grew, so a `${vault:k}` already resolved in the body did not disable redirects for a custom header reusing it. It now checks the header's own text for a reference. [`ApiCallExecutor.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/apicalls/impl/ApiCallExecutor.java)
* **M10 — templates.** (a) `str:fmt`/`str:format` and the `String.fmt`/`format` instance forms are served by new `BoundedFormat` resolvers registered ahead of the generated ones: an upper bound for the output is computed from the format specifiers and refused against `eddi.templating.max-output-chars` before `String.format` allocates (pre-check, not removal — formatting numbers is common in prompts). (b) `quarkus.qute.timeout` is now effective: the render's deadline is a template-instance attribute checked on every value resolution (the bounded resolvers) and every loop iteration. (c) `processTemplate` reports a `StackOverflowError` as a template error; `validateTemplate` too. Section nesting is not capped at parse time — Qute's parser is not recursive, the render is, and catching the overflow covers it. [`BoundedFormat.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/templating/impl/BoundedFormat.java), [`RuntimeTemplateEngineFactory.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/templating/impl/RuntimeTemplateEngineFactory.java), [`TemplatingEngine.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/templating/impl/TemplatingEngine.java), [security.md](https://docs.labs.ai/security-and-compliance/security.md#render-limits)
* **M11 — PDF budgets on the attachment and tool paths.** `AttachmentTextExtractor` runs every PDF operation under the ingestion path's `PdfStreamBudget` pre-scan and `PdfDecodeBudget` (64 MB per stream, 128 MB per document), now public for that reuse, and the `(startPage, endPage)` variant reads at most `eddi.attachments.extraction.max-pages` pages. [`AttachmentTextExtractor.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/tools/impl/AttachmentTextExtractor.java)
* **L14 — regex stack overflow on long JSON strings.** The `"((?:[^"\\]|\\.)*)"` alternation loop in `ConfidenceEvaluator` and `LifecycleManager.PROVIDER_ERROR_MESSAGE` recursed once per character; both now use `JsonStringField`, a linear scan. `summarizeException` and `reportFailureToCaller` no longer let a `StackOverflowError` escape the failure handler. [`JsonStringField.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/utils/JsonStringField.java)
* **M8 — export scrubbing and sync rebinding.** `SecretScrubber` judges structured strings part by part — a relative `request.path` query string, a form-encoded body, a JSON document inside a string (`request.body`, `serviceAccountJson`) — treats `Cookie`/`Set-Cookie` headers as credentials, and runs the full `SecretRedactionFilter.redact` (template expressions masked) over request material only — `path`, `body`, URLs/endpoints, header and query-parameter maps, embedded documents. Every other string (prompts, descriptions, outputs, rule values) gets only a credential-*shape* pass (`SecretRedactionFilter.redactCredentialShapes` plus export-side shapes: `AIza…`, `gh*_`/`github_pat_`, `xox?-`, `AKIA`/`ASIA`, `gsk_`, `xai-`, JWTs, the password of `mongodb(+srv)://user:pass@`), so prose such as "never echo the password: policy" round-trips byte-identical. Vault references and template expressions stay legible. For `/backup/import/sync*`, the facade cannot pin an address, so every request to the source now carries `SourceUrlValidator.connectPolicy`: `STRICT` when private targets are refused, `METADATA_ONLY` when they are allowed or the origin is allow-listed — re-checked by the facade right before each send. [`SecretScrubber.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/secrets/sanitize/SecretScrubber.java), [`SourceUrlValidator.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/backup/impl/SourceUrlValidator.java), [agent-sync-guide.md](https://docs.labs.ai/conversations-and-orchestration/agent-sync-guide.md)
* **L15 — `SharedKvCache.decode`.** The value class named in a NATS KV entry is matched against the exact classes the shared caches store (`Boolean`, `String`, `A2ATaskRecord`, `PrincipalIndex`, `PaginatedResponse`, `ChannelTarget`) instead of package prefixes; anything else is refused and logged at ERROR. [`SharedKvCache.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/caching/SharedKvCache.java)
* **L16 — templated JSON bodies.** Documented that a runtime value in a JSON body must go through `{json:serialize(...)}` without quotes of its own, and deployment now WARNs per httpCall whose JSON body has a `{…}` expression inside a string literal. [`ApiCallsTask.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/apicalls/impl/ApiCallsTask.java), [httpcalls.md](https://docs.labs.ai/agent-configuration/httpcalls.md#values-in-a-json-body-are-not-escaped)
* **L13 (partial) — LLM provider response size.** The OpenAI, Anthropic, Gemini, Mistral and Ollama builders use `BoundedJdkHttpClient`: the langchain4j `JdkHttpClient` built from an `HttpClient.Builder` whose client wraps every body subscriber with a byte cap (`eddi.llm.max-response-bytes`, 32 MB; over the whole stream for streaming). Not capped: MCP responses (`StreamableHttpMcpTransport` builds its own `HttpClient` and exposes no hook), Azure OpenAI and other SDK-based providers, and Jlama's Hugging Face download. [`BoundedJdkHttpClient.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/builder/BoundedJdkHttpClient.java)

### Review fixes (PR #1083)

* `SecretRedactionFilter`'s two `sk-` shape rules now start at a word boundary (`(?<![A-Za-z0-9_])`, the convention `EXPORT_CREDENTIAL_SHAPES` already used). Unanchored, `redactCredentialShapes` — which M8 made run over every exported prose string — turned `risk-assessment-workflow-handler` into `risk-<REDACTED>`; log redaction keeps its coverage since real keys start at a boundary.
* `SecretScrubber.scrubStructuredText` returns the original string, whitespace included, when an embedded JSON document comes back unchanged; it returned the trimmed text, so a body template ending in a newline exported trimmed and `containsCredential` reported it.
* `LifecycleManager`'s `StackOverflowError` fallback digest carries `taskType` and `errorType: stack_overflow` like the regular digest, so `TurnError.fromTaskError` keeps the task metadata. `LifecycleManagerFailureReportFallbackTest` drives it with an exception whose `getResponse()` overflows inside `LlmFailureClassifier.classify`.
* The scrubber test fixture uses AWS's documented example key `AKIAIOSFODNN7EXAMPLE` (gitleaks allowlists it) instead of a made-up `AKIA…` that Secret Scanning flagged.

### Not done / open

* M9.3 and M8 re-check rather than pin: the facade and the Vert.x client resolve names themselves, so a window remains between the guard's lookup and the client's (normally served by the same JVM address cache).
* L13: MCP tool results, Azure OpenAI and Jlama downloads remain uncapped; an httpCall whose `future.get(timeout)` expires is still not cancelled on the Vert.x side.
* M8 provider-key coverage in free text is whatever `SecretRedactionFilter` matches; `AIza…`-style keys in a query parameter named `key` are caught once those patterns land there.

***

## ✨ feat(channels): signed inbound webhook channel — CloudEvents over HTTP (2026-10-15)

**Repo:** EDDI (`feat/channels-signed-webhook`)

### What changed and why

Agents could react to chat turns and schedules, not to events. A new channel type, `channelType: "webhook"`, lets an external system (GitHub, a payment provider, a monitoring stack) start an agent turn or a group discussion by POSTing a signed event to `POST /integrations/webhook/{integrationId}`. It reuses the channel machinery rather than adding a trigger system: `ChannelIntegrationConfiguration`, its `targets` table and `ChannelTargetRouter` (Pillar 3).

* **Authentication is the HMAC signature**, verified over the raw body bytes against the addressed integration's one secret, fail-closed. Schemes: `eddi-v1` (default; `X-Eddi-Signature: t=…,v1=…`, 5-minute window, several `v1` for rotation), `github` (`X-Hub-Signature-256`), `generic-hmac` (header, hex/base64, prefix configurable). The HMAC/constant-time/freshness primitives moved into the shared `HmacSignatures`; `SlackSignatureVerifier` now uses them (behaviour unchanged).
* **Formats:** CloudEvents 1.0 structured and binary mode, and plain JSON (type from a header or JSON pointer, else `webhook`). All three yield the same `event` map, which reaches the conversation as the context value `event` — data, never a template. The input text is the author's `inputTemplate`, rendered by the restricted runtime Qute engine, default `event:<type>`.
* **Routing** by event type against `targets[].triggers` (exact or `prefix*`, most specific wins), else the default target; agents and groups.
* **Review fixes:** a repeat delivery that arrives while the first is still being processed answers a retryable `409` (`Retry-After: 5`), not `200 duplicate` — the first may still be refused, and a 200 would have lost the event; only a recorded `202` makes a repeat a duplicate. `HmacSignatures.isFresh` is overflow-safe (`subtractExact`/`absExact`; a timestamp of `Long.MIN_VALUE + now` used to read as fresh — also used by Slack). Events without an id are deduplicated on the signature value for every scheme, not only `eddi-v1`: for `github` and `generic-hmac`, which sign no timestamp, that window is the only replay protection, as the docs now say.
* **PR review (#1059):** deduplication is keyed by the event id AND by a canonical replay key the verifier derives from the MAC it computed (never from the sender's header — an extra `v1=` candidate or upper-case hex no longer yields a fresh key), so a captured request replayed under a new, unsigned delivery id is a duplicate. Trade-off, documented: byte-identical signed deliveries within the window count as one. Docs separate `eddi-v1`'s `t + "." + body` MAC input from the body-only schemes; the Manager labels the create-dialog secret field, names `X-Signature` as the generic-HMAC default, and promises stale-request refusal only for `eddi-v1`. A second `t=` entry in `X-Eddi-Signature` is refused as malformed (it let the verified timestamp and the replay key diverge), and `eddi.webhook.events` also counts refusals answered before dispatch.
* **Conversations:** `new` per event, or `correlate` — one conversation per value at `correlationKeyPath`, mapped through `IUserConversationStore` like Slack threads.
* **Identity:** turns run as `webhook:<integrationId>`.
* **Delivery:** 202 with the conversation id; repeated event id → 200 duplicate (10-minute Caffeine cache, released when an event is refused so retries work); 413 above 256 KB (`eddi.webhook.max-body-bytes`); 429 + `Retry-After` on tenant quota; 503 when the agent is not deployed.
* **Validation:** a webhook integration must have `platformConfig.signingSecret`, and it must be a `${vault:…}` reference (400 otherwise); unknown schemes, non-pointer paths, `correlate` without a key path and `observeMode` targets are refused.
* HTTP policy `quarkus.http.auth.permission.webhook` (POST, permit) plus `@PermitAll` on the resource, as for Slack.
* Manager: `webhook` in the channel type list, a create-dialog step and detail-page section for its settings, the endpoint URL and the signing format (11 locales). MCP `create_channel_integration` documents the type and returns `webhookEndpoint`. Platform Operator prompt knows the type (revision bump).
* Docs: new [`webhook-triggers.md`](https://docs.labs.ai/protocols-and-integration/webhook-triggers.md).

### Design decisions

* **Quota-consuming steps run before the response.** `startConversation` and `say` are called on the request thread: `say` only admits the turn and queues it on the conversation coordinator, so the agent's work is still asynchronous, but the 202 can carry the conversation id and a quota refusal can still be a 429. A separate executor (Slack's pattern) would have made the 429 unreportable. Cost: a new conversation's `CONVERSATION_START` turn runs inline — documented.
* **Body as bytes, not `String`.** The MAC covers what the sender signed; a charset round trip can alter invalid UTF-8. The body is read with a hard cap before any verification; nothing is parsed before the signature passes.
* **Webhook integrations are keyed by their resource id** in the router (no `channelId`), so the URL needs no extra configuration and cannot collide.
* **Signing secret must be a vault reference** — the endpoint is public, and a plaintext secret is returned by `GET /channelstore/channels/{id}` and exported. Slack only warns, for back-compat; the new type has none to keep.
* **Not reused:** `TurnIdempotencyService` is per-conversation and the event has no conversation yet; deduplication uses the cache factory, like Slack.

### Not done / next

* Deduplication is per node; a NATS cluster could run a replayed event once per node.
* A new integration is reachable only after the router's 60-second refresh.

**Files:** [`RestWebhookChannel.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/integrations/webhook/rest/RestWebhookChannel.java), [`WebhookEventHandler.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/integrations/webhook/WebhookEventHandler.java), [`WebhookEventParser.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/integrations/webhook/WebhookEventParser.java), [`WebhookSignatureVerifier.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/integrations/webhook/WebhookSignatureVerifier.java), [`HmacSignatures.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/integrations/channels/HmacSignatures.java), [`WebhookChannelSettings.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/channels/model/WebhookChannelSettings.java), `ChannelTargetRouter`, `RestChannelIntegrationStore`, `SlackSignatureVerifier`, `McpAdminTools`, `application.properties`, Manager channel pages + `webhook-settings.tsx`, operator prompt.

***

## ✨ feat(llm): `classifier` guardrail type — a safety-classifier model as configuration (2026-10-15)

**Repo:** EDDI (`feat/llm-classifier-guardrail`, stacked on `feat/llm-input-output-guardrails`) — WS4 Phase 4b.

### What changed and why

The 4a guardrails are deterministic heuristics. Phase 4b adds one generic model-backed type, `classifier` (input and output), that asks a safety-classifier model for a verdict, so Granite Guardian, ShieldGemma, a hosted moderation model or a TrustyAI-served detector are **configuration values, not code**. EDDI ships and endorses no model.

* **`ClassifierGuardrail`** (`modules/llm/guardrails/impl`) — a `ContentGuardrail` bean, picked up by `GuardrailService`'s type index like every other. Parameters: `provider` (an EDDI provider type) plus that provider's own model parameters in a task's vocabulary (`baseUrl`, `apiKey` — a `${vault:…}` reference, resolved and grant-checked as for a task — `modelName`/`model`, `customParameters`, `maxTokens`, …), and its own keys `promptTemplate`, `risk`, `unsafeLabel` (default `yes`), `safeLabel`, `labelPattern`, `timeoutMs` (default 3000, cap 60000), `includeRetrievedContext` (output), `inputPricePer1M`/`outputPricePer1M`, and the generic `failMode`.
* **Transport is `ChatModelRegistry.getOrCreate`** (made public), not `SafeHttpClient`: classifier endpoints are in-cluster private addresses, the same trust class as a task's model `baseUrl`; the registry also brings vault/global-variable resolution, the model cache and LLM telemetry. `timeoutMs` becomes the provider `timeout` (a stable cache key), and the call itself runs on a virtual thread bounded by `min(timeoutMs, turn deadline − reserve)` (#996); a turn already out of time does not call the classifier.
* **Prompt:** without `promptTemplate` the text goes as the model's native conversation (input: the user message; output: question + answer as an assistant message), which is what Granite Guardian on vLLM and ShieldGemma on Ollama expect — their chat templates build the classification prompt. With `promptTemplate`, the template is rendered by the restricted Qute engine with the screened text as **data** only (`{input}`, `{output}`, `{risk}`, `{context}`) — never as template source.
* **Verdict:** label = first capture group of the **last** `labelPattern` match (Granite's `<score> yes </score>`, after an optional `<think>` trace), else the first word with punctuation trimmed; compared case-insensitively with `unsafeLabel` / `safeLabel`.
* **Could not decide** → new `GuardrailUndecidedException(reason, costUsd)`: `GuardrailService.evaluate` now returns an internal `Evaluation` and the three failure sites (input, history, output) record the exception's reason (`classifier_unavailable`, `classifier_unparseable`) instead of `guardrail_error`, and add its cost. Everything else about failMode is 4a's single code path (closed by default for `block`/`reprompt`).
* **Cost:** priced with `TokenPricing` from the classifier's token usage into `GuardrailVerdict.costUsd`, which 4a's `accumulateCost` folds into `audit:cost` (WS2's tenant metering reads that key) — including the cost of an unparseable answer.
* **Context:** `GuardrailContext` gains `retrievedContext` (this turn's vector-store + `httpCallRag` context, output phase) and `deadline`; the old six-argument constructor stays. `LlmTask` collects the retrieved context it already appends to the system message and passes both. The HITL resume path has no retrieved context (null).
* **Metric:** timer `eddi.guardrail.classifier.duration{provider, outcome}` (provider tagged only after the registry accepted it, so bounded; outcome `safe|unsafe|unparseable|unavailable|timeout`); `eddi.guardrail.triggered` unchanged. Both now have panels on the Full Metrics dashboard — 4a's counter had none, which `MetricsDashboardCoverageTest` flagged.
* **Docs:** [langchain.md](https://docs.labs.ai/agent-configuration/langchain.md#the-classifier-type-a-safety-classifier-model) (parameters, template safety, could-not-decide, cost/latency, worked examples for Granite Guardian 3.3 on vLLM and ShieldGemma on Ollama), [security.md](https://docs.labs.ai/security-and-compliance/security.md) (the failMode availability trade-off, transport trust), [metrics.md](https://docs.labs.ai/deployment-and-infrastructure/metrics.md), [audit-ledger.md](https://docs.labs.ai/security-and-compliance/audit-ledger.md). Operator prompt explains configuring a classifier (it never writes the vault reference itself); revision stays 17 (main is at 16), fingerprint updated. Manager `GuardrailConfig` doc comment lists the type.

### Design decisions

* **`screensHistory()` is false**: a model call per earlier history message on every turn would multiply the cost by the window size; each message was classified on its own turn.
* **`promptTemplate` optional** (the plan had it required): the two documented models expect the raw conversation and build their own prompt; a wrapper prompt would be classified as content.
* **`labelPattern` added** (not in the plan): Granite Guardian answers inside a `<score>` tag, which first-token matching cannot read. It is author config, compiled through 4a's bounded `PatternCache`.
* **Safe is a positive match, never a default** (review follow-up). An answer is safe only when it matches `safeLabel`; a refusal, an HTML error body, `maybe` or a truncated reply is undecided and follows `failMode` (closed by default). `safeLabel` defaults to `no` when `unsafeLabel` is left at `yes`; a custom `unsafeLabel` without `safeLabel` fails the deploy — `LlmTask.configure` now asks each guardrail type to validate its parameters (`ContentGuardrail.validate`, default: nothing to check; unknown types still only WARN at run time). A missing `provider` is refused the same way.
* **`labelPattern` runs over the last 4 KB of the answer** (the first word over the first 4 KB), so an author regex never scans an unexpectedly huge reply.
* **Llama Guard:** not given a worked example. Meta's Llama 3.2/3.3/4 acceptable-use policies withhold the licence rights for their multimodal models from EU-domiciled companies, which covers Llama Guard 4 and Llama Guard 3 Vision; the text-only Llama Guard 3 is mentioned with that caveat, and ShieldGemma is the Ollama example. EDDI takes no position on any model's licence.
* **Provider error messages are never logged or propagated** (they can echo the screened text); only the exception class.

### Manager

* The guardrails editor from the merged Manager PR offers `classifier` again on both sides (`GUARDRAIL_TYPES`, phases, no-rewrite set and type text in `guardrails.ts`); its settings panel and warnings were already in place. The editor test that asserted it was not offered now asserts it is. `operator-revision.json` is bumped for the operator prompt change.

### Not done

* The Granite Guardian `chat_template_kwargs` example is per the model card and vLLM's request extension; it was not run against a live vLLM here.

***

## feat(llm): generic `openai-compatible` provider type for self-hosted servers (2026-10-15)

**Repo:** EDDI (`feat/llm-openai-compatible-provider`; backend, Manager, docs, Platform Operator)

### What changed and why

Production on-prem inference runs on vLLM, llama-server, TGI, KServe or LiteLLM. EDDI could reach them only as `type: openai` + `baseUrl`, and so judged them as OpenAI: JSON mode was sent alongside tools (a 400 on servers that do not support the combination), vision was decided by OpenAI model names (a self-hosted Qwen-VL was text-only), and telemetry reported the traffic as `OPEN_AI`. The named-provider catalog cannot describe these servers by design: it requires a fixed `https://` endpoint and a fixed default model.

* **New LLM type `openai-compatible`** (`OpenAiCompatibleEndpoint`, `SelfHostedOpenAiLanguageModelBuilder`, registered in `LlmModule` and reserved in `BUILT_IN_TYPES` so no catalog row can take the id). It runs on the OpenAI builder. `baseUrl` and `modelName` are required; `http://` is accepted and the cloud-metadata block stays. `apiKey` is optional: verified against langchain4j 1.22.0's `DefaultOpenAiClient`, a null key adds no `Authorization` header, and a blank key is now removed before it could become `Bearer` .
* **Per-endpoint capability flags**, in the catalog's own vocabulary (`OpenAiCompatibleProvider.Capabilities`): `jsonMode`, `jsonModeWithTools`, `vision`, all off by default. `JsonResponseFormatPolicy` gained an `endpoint` component, filled by a new `of(..., parameters)` overload at all three call sites: `LlmTask` live, `LlmTask` HITL resume, and `CascadingModelExecutor`, which passes the **step's** merged parameters. `ModelCapabilityService.visionOverride` places the endpoint's `vision=true` below the per-task `multimodal.vision` override and above the deployment override; the built-in default for the type is off.
* **Strict literal flags, lenient templated ones.** A literal flag that is neither `true` nor `false` fails the deploy (`OpenAiCompatibleConfigValidator`, run from `LlmTask.configure` for the task, each cascade step and the judge) with a message naming the parameter; so does a missing `baseUrl`/`modelName`. LLM parameters are rendered by Qute before the request is built, but `${vars:...}` is otherwise only resolved inside `ChatModelRegistry`, so the call sites resolve global variables in the three flags first (`OpenAiCompatibleEndpoint.withResolvedFlags`). A templated flag that still is not a boolean counts as `false` with one WARN per distinct value (bounded): it never fails the build or the turn. `customParameters` must parse to a JSON object for this type (the OpenAI builder only warns and drops it).
* **Telemetry.** `serverName` (default `openai-compatible`) is reported as `gen_ai.provider.name` and the `provider` meter tag in place of langchain4j's `OPEN_AI`, through a provider-name override on `LlmTelemetryListener.forModelType` and the observable model wrappers. It is bounded: lower-cased, 1-32 characters of `[a-z0-9._-]`, else the default.
* **Model cache.** The three capability flags are left out of `ChatModelRegistry`'s cache key for this type (they shape requests, not the model instance); `serverName` stays in, because the telemetry wrapper bakes it in.
* **Parameter catalog.** `model-parameters.json` has an `openai-compatible` row that inherits OpenAI's parameters without their model rules and adds `serverName` and the three flags; the Manager mirror and [`docs/llm-parameters.md`](https://docs.labs.ai/agent-configuration/langchain/llm-parameters.md) are regenerated. Its inherited `responseFormat` is overridden with a "do not use" note pointing at `convertToObject` / `jsonResponseFormat` and `jsonMode`, since the OpenAI builder bakes it into the cached model.
* **Setup.** `AgentSetupService` treats the type as keyless and requires `model` and `baseUrl`/`llmBaseUrl` up front instead of injecting the SaaS default model; the MCP `setup_agent` / `create_api_agent` descriptions name it.
* **Manager.** "Self-hosted (OpenAI-compatible)" in the local group of the provider picker (agent wizard, operator activation, LLM editor, cascade steps, summary provider): required model and base URL with examples, an optional API key, and a note that the capability flags are switched on under Model settings, where they render from the catalog with a one-line explanation each. Pickers with no base URL field do not offer it: the workforce team builder, the group wizard's members and moderator, the cascade judge and a group's summarizer. The rolling-summary provider offers it only when the task itself is `openai-compatible`, because the summarizer then inherits the task's `baseUrl` and key. 7 i18n keys in all 11 locales.
* **Docs and Operator.** A "Self-hosted OpenAI-compatible servers" section with a migration note in [`docs/langchain.md`](https://docs.labs.ai/agent-configuration/langchain.md), the provider matrix row, and notes in [`docs/metrics.md`](https://docs.labs.ai/deployment-and-infrastructure/metrics.md) and [`docs/model-cascade.md`](https://docs.labs.ai/agent-configuration/model-cascade.md). The Platform Operator prompt describes the type; `operator-revision.json` is bumped to 24 (one above main).

### Design decisions

* **`customParameters` is the extra-body mechanism**, not a new `extraBody` key: it already is a JSON object merged into the request body with the user winning, the Manager already renders it, and a second key with the same meaning would need a precedence rule. It is made strict for this type only, so `type: openai` behaviour does not change.
* **No `jsonSchema` flag yet.** Native `json_schema` support differs between servers and versions, and the plan ties it to the structured-output work (D5); schemaless JSON is sent when `jsonMode` allows it.
* **`vision=false` defers rather than vetoes**: absent or `false` both fall through to the deployment override and then to the off default, so an operator's `eddi.multimodal.openai-compatible.vision=on` still applies to endpoints that did not set it.
* **`type: openai` is untouched**, pinned by a regression test of its JSON-policy rows, its native schema, its vision decisions and an old `type: openai` + `baseUrl` config.

### Not done

* Model discovery via `GET /v1/models` and the deployment-level provider allow-list (C3) are out of scope.
* `CreateSubAgentTool` has no base URL parameter, so it refuses this type up front with a message telling the model to pick another provider or have an administrator create the agent.

***

## 🔒 fix(deploy): runtime and deployment findings of the 2026-10-17 security review (2026-10-17)

**Repo:** EDDI (`fix/security-review-runtime`)

### What changed and why

The runtime and deployment workstream of the 2026-10-17 security review — M6, M7, L7, L8 and the small L12/L13 items. One commit per finding.

* **M6 — the authenticated PostgreSQL install could not start, and two stacks had no bind-guard.** `docker-compose.auth.yml` overrides `bind-guard`, which only `docker-compose.yml` declared, so `-f docker-compose.postgres-only.yml -f docker-compose.auth.yml` — exactly what `install.sh --db=postgres --with-auth` and `install.ps1` compose — failed with "service bind-guard has neither an image nor a build context". Separately `docker-compose.postgres-only.yml` and `docker-compose.cluster.yml` publish on `${EDDI_BIND:-127.0.0.1}` with the three `*_ALLOW_UNAUTHENTICATED` defaults `true` and no guard, so `EDDI_BIND=0.0.0.0` published an open EDDI, MCP server and vault there. Both stacks now carry the same guard (on the database image each already pulls; in the cluster the load balancer waits for it). Design: the guard stays in every base rather than moving to an overlay — a base used on its own must still refuse — and `ComposeStackTest` makes the duplication safe: the copies must be byte-identical in script and inputs, every stack that publishes on `EDDI_BIND` must have one, every combination the installers can assemble (base × `--local` × `--with-auth` × `--with-monitoring`, read back out of both installers) and every multi-file command README/`docs/` print is checked structurally (every service and `depends_on` target resolves) and, where a Docker CLI exists, rendered with `docker compose config`. That sweep also found `docs/mcp-server.md` telling users to run `docker compose -f docker-compose.auth.yml down -v` on its own, which compose refuses; fixed. Files: [`docker-compose.postgres-only.yml`](https://github.com/labsai/EDDI/tree/main/docker-compose.postgres-only.yml), [`docker-compose.cluster.yml`](https://github.com/labsai/EDDI/tree/main/docker-compose.cluster.yml), [`docker-compose.auth.yml`](https://github.com/labsai/EDDI/tree/main/docker-compose.auth.yml), [`ComposeStackTest.java`](https://github.com/labsai/EDDI/tree/main/src/test/java/ai/labs/eddi/ComposeStackTest.java), [`docker.md`](https://docs.labs.ai/deployment-and-infrastructure/docker.md), [`mcp-server.md`](https://docs.labs.ai/protocols-and-integration/mcp-server.md)
* **M7 — the unauthenticated quick start had no `Host`/`Origin` check.** Loopback binding stops the network, not the browser: a DNS-rebinding page (`Host: evil.example` resolved to `127.0.0.1`) was same-origin with the whole API, MCP and `/secretstore`, and without rebinding a page could still send blind CORS "simple" `POST`s. The new `UnauthenticatedRequestGuard` (a Vert.x route filter registered like `HttpMethodGuard`, and only while `authorization.enabled=false`) answers **421** to a `Host` that is not `localhost`/`*.localhost`, an IP literal or an entry of the new `eddi.security.unauthenticated.allowed-hosts`, and **403** to a `POST`/`PUT`/`PATCH`/`DELETE` whose `Origin` is neither the request's own nor in `quarkus.http.cors.origins` (`null` included) or, without an `Origin`, whose `Sec-Fetch-Site` is `cross-site`/`same-site`. `/q/health` is exempt; one `[SECURITY]` WARN at boot states the policy. Design decision, deviating from the review's "loopback only": **IP literals are always answered**. Rebinding needs a DNS name the attacker controls, so an address cannot be its product, and kubelet probes, Prometheus scrapes (pod IPs) and `eddi.self.base-url` (`http://127.0.0.1:…` or a pod IP) address EDDI that way; the cross-site check still covers a page that posts to an address. The raw `Host` header is read, never a forwarded one — a rebound page is same-origin and may set `X-Forwarded-Host`. The compose stacks default the allow-list to `eddi` (Prometheus and Open WebUI reach EDDI by service name), the kustomize base and quickstart to the Service's in-cluster names, and the Helm chart (when OIDC is off) to the Service names plus any acknowledged ingress host. Chart `2.8.0` → `2.9.0`. Files: [`UnauthenticatedRequestGuard.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/security/UnauthenticatedRequestGuard.java), [`UnauthenticatedRequestGuardTest.java`](https://github.com/labsai/EDDI/tree/main/src/test/java/ai/labs/eddi/engine/security/UnauthenticatedRequestGuardTest.java), [`security.md`](https://docs.labs.ai/security-and-compliance/security.md#running-without-authentication), [`configuration-reference.md`](https://docs.labs.ai/deployment-and-infrastructure/configuration-reference.md)
* **L7 — runtime defaults.** Done:

  * **HSTS.** The GCP provisioner's nginx sends `Strict-Transport-Security: max-age=31536000` on both https servers (no `includeSubDomains` — sslip.io names are not ours), and EDDI gains an opt-in `HstsHeaderFilter` (`eddi.security.hsts.enabled`, default `false`; `eddi.security.hsts.max-age`). The Helm chart sets it when `ingress.enabled` and `ingress.tls` are both set.
  * **`/q/health` detail.** The cluster readiness check reports its details (mode, NATS state, node id, member count, drain state, `degradedSince`) only with the new `eddi.health.verbose=true`; by default the public endpoint carries the status alone. `GET /administration/cluster/overview` still has everything, authenticated. (Gated in `ClusterHealthCheck` itself, so the readiness data is gone, not merely moved behind a path.) `agentsInErrorCount` stays — it is a count, documented as deliberately public.
  * **Keycloak realm** (all three copies, kept in step): `passwordPolicy` (`length(12) and maxLength(128) and notUsername and notEmail and passwordHistory(3)` — the installers' generated one-time passwords are 32 characters), login and admin events on (30 days, admin event bodies off), `eddi-mcp` with `consentRequired: true` and `fullScopeAllowed: false` plus a `scopeMappings` entry for exactly the `eddi-*` roles, seeded users `emailVerified: false`. Verified by importing the realm into `quay.io/keycloak/keycloak:26.8.0` and generating an example `eddi-mcp` access token (roles and `aud` still present). Realm import is one-shot: existing realms keep their old settings (documented in security.md).
  * **GCP nginx** returns 404 for `/realms/master/` (the provisioner reaches it on localhost:8180, not through nginx).
  * **Kubernetes.** The production NetworkPolicy's ingress-controller rule is pinned to the `ingress-nginx` namespace by `kubernetes.io/metadata.name` instead of admitting a controller-labelled pod from any namespace. MongoDB, PostgreSQL and Keycloak pods (Helm, kustomize overlays, quickstart) run as their image's own uid from the start (Mongo 999, Postgres alpine 70 — Helm `postgres.runAsUser` — Keycloak 1000) with `allowPrivilegeEscalation: false`, `capabilities.drop: [ALL]` and the RuntimeDefault seccomp profile; both databases were started that way in Docker (`--user … --cap-drop ALL --security-opt no-new-privileges`) to confirm their entrypoints still initialise.
  * `quarkus.swagger-ui.oauth2-redirect-url` is no longer pinned to `http://localhost:7070`; Swagger UI derives it from the page's origin.
  * `docker-compose.yml`'s MongoDB healthcheck no longer carries the root password on its command line (`docker inspect`, host process list): `ping` needs no authentication.

  Deliberately **not** done here: Keycloak `start-dev` and the `admin/admin` compose fallback (the installers and the GCP provisioner already generate one; a production Keycloak mode needs a database and hostname design of its own), EDDI connecting to MongoDB as root, plaintext service-to-service traffic, NATS without auth and the unauthenticated MongoDB in the kustomize quickstart, and `quarkus.log.console.level=DEBUG` (the handler level only; categories stay at INFO). Files: [`HstsHeaderFilter.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/security/HstsHeaderFilter.java), [`ClusterHealthCheck.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/cluster/ClusterHealthCheck.java), [`eddi-realm.json`](https://github.com/labsai/EDDI/tree/main/keycloak/eddi-realm.json), [`provision-vm.sh`](https://github.com/labsai/EDDI/tree/main/gcp/provision-vm.sh), [`network-policy.yaml`](https://github.com/labsai/EDDI/tree/main/k8s/overlays/production/network-policy.yaml)
* **L8 — installer integrity (the minimal version).** The release job in `ci.yml` now checks out the tag, hashes every file the installers download (`docker-compose*.yml`, the realm, the login theme, `docs/monitoring/`) into `SHA256SUMS` and attaches it to the GitHub release. `install.sh` and `install.ps1` fetch that asset when `EDDI_BRANCH` is a release tag and refuse a downloaded file whose hash differs (the file is deleted); with no asset — `main`, a branch, every release before this one — they warn that only TLS vouches for the files and carry on, so existing installs do not break. Exercised with stubbed downloads for both scripts (accept, unlisted → warn, mismatch → refuse and delete, non-release ref → warn). `gcp/provision-vm.sh` defaults `--eddi-branch` to the `--eddi-version` tag or the newest stable release (GitHub API), falling back to `main` with a warning. `postgres:16-alpine` is pinned to `postgres:16.15-alpine` in the compose stack (database and bind-guard), the kustomize overlay and the Helm values. **Not done:** the installers cannot verify themselves (`curl | bash` from `main` stays TLS-only), the CLI's `eddi update` refresh path does not verify, there is no cosign signature on the asset, compose still defaults to `labsai/eddi:latest`, and `mcp-sidecar/Dockerfile`'s unpinned `nodejs npm` is untouched. Files: [`install.sh`](https://github.com/labsai/EDDI/tree/main/install.sh), [`install.ps1`](https://github.com/labsai/EDDI/tree/main/install.ps1), [`ci.yml`](https://github.com/labsai/EDDI/tree/main/.github/workflows/ci.yml), [`security.md`](https://docs.labs.ai/security-and-compliance/security.md#installer-downloads)
* **L12/L13 — small items.** `quarkus.http.cors.exposed-headers` now exposes `Mcp-Session-Id` and `Retry-After` next to `Location`, so a browser-based MCP client on an allowed origin can read its session id and a 429/503's back-off. The `7443` mapping the compose stacks publish is documented rather than removed: it is Quarkus' HTTPS port, opened only once a certificate is configured, and removing it would have touched every installer's port resolution for no security gain (nothing listens). Dependabot #716 was *not* stale, contrary to the review: it bumps the `eclipse-temurin:25-jre` digest in `src/main/docker/Dockerfile.demo` (the Open WebUI demo image), which still uses that base — nothing changed here. Files: [`application.properties`](https://github.com/labsai/EDDI/tree/main/src/main/resources/application.properties), [`docker-compose.yml`](https://github.com/labsai/EDDI/tree/main/docker-compose.yml), [`docker.md`](https://docs.labs.ai/deployment-and-infrastructure/docker.md)
* **M7 follow-up (live dev-mode test).** `host.docker.internal`, `gateway.docker.internal` and `host.containers.internal` are now answered built in — that is how a container reaches an EDDI on the host, the container runtime's resolver answers them, and `.internal` is a reserved TLD public DNS never delegates. Three unexpected `400`s from the live test (`Host: eddi.localhost:7070`, `Host: localhost.`, and `/q/health/live` with `Host: evil.example`) were traced to Quarkus 3.40's own `HostValidationFilter`, not this guard: it is switched on in dev and test mode because the server binds `localhost`, accepts only `localhost`/`127.0.0.1`/`[::1]` and ends anything else with an empty `400` (confirmed from its bytecode, and by the guard answering `evil.example` with its own `421` on a non-exempt path of the same instance). The released 6.5.0 image (binds `0.0.0.0`, filter off) answers all three with `200`. The guard's own decisions for the three are pinned in `UnauthenticatedRequestGuardTest`, and `docs/security.md` explains the dev-mode `400`.

### Design decisions

* `bind-guard` is duplicated into every base stack rather than moved to an overlay, and a test pins the copies together — moving it out would have left `docker compose up` on a base alone unguarded.
* The M7 guard answers any IP-literal `Host` (see above) and reads only the raw `Host` header; `*` in the allow-list switches the Host check off, logged at boot.
* `/q/health` detail is gated in the health check (`eddi.health.verbose`) instead of narrowing the public permit, because the sensitive data is in `/q/health/ready` itself.
* Installer checksum verification is warn-only when no `SHA256SUMS` exists, so every release before this one keeps installing.

### What's next

* The Platform Operator (`ui/manager/src/lib/operator/system-prompt.ts`, WS-F's area) does not yet know about `eddi.security.unauthenticated.allowed-hosts`, `eddi.health.verbose` or `eddi.security.hsts.enabled`; an admin asking "why 421?" will not get an answer from it.
* L7 and L8 items listed as not done above.
* **The review itself is now in the repository.** `planning/security-review-2026-10-17.md` is the report every `security review 2026-10-17, <id>` reference in code and fragments points to, with a status line, the live-probe results, what was verified clean and the remediation table; `docs/security-review.md` gains an entry for the October reviews.

***

## 🔒 fix(security): editors no longer read plaintext credentials in any config store (2026-10-17)

**Repo:** EDDI (`fix/security-review-secrets-redaction`)

### What changed and why

M1 of the 2026-10-17 security review. The 2026-10-15 fix (L12) redacted plaintext keys for non-admins in `tasks[].parameters` of LLM configurations only; editors still read them verbatim in `a2aAgents[].apiKey`, `modelCascade` step and judge parameters, the MCP-calls `apiKey`, a Slack integration's `botToken`/`signingSecret` (enough to forge `/integrations/slack/*` events), RAG `embeddingParameters`/`storeParameters`, and literal `Authorization` headers and keys in an httpcall's `request.path` and `request.body` — current and old (`?version=`) versions alike.

* **One shared read-redactor**, `ConfigSecretRedactor` (`secrets.sanitize`), walks the serialized document: credential-named fields are replaced whole, header and query-parameter maps are judged by header/parameter name, URLs lose their userinfo password and credential-named query values, and `body` fields go through `SecretRedactionFilter`. References (`${vault:}`, `${vars:}`, `${connection:}`, `${caller:}`) and templates pass unchanged, also beside a scheme word (`Bearer ${vault:k}`). `token` matches only singular, so `maxTokens` and `thinkingBudgetTokens` are untouched; `httpCalls[].parameters` (tool parameter descriptions) and `tasks[].toolCacheScopes` (keyed by tool name) are skipped.
* `RestLlmStore`, `RestMcpCallsStore`, `RestChannelIntegrationStore`, `RestRagStore` and `RestApiCallsStore` apply it for every caller who is not `eddi-admin`. MCP `read_resource`/`read_channel_integration` reach the same REST stores through the loopback client, which forwards the caller, so they are covered too.
* `RestLlmStore`'s write-time warning now uses the same detection, so it warns about exactly what an editor cannot read back.
* `RestRagIngestion` reads the knowledge base through the new `RestRagStore.readUnredacted` (same access check, no redaction): ingestion builds the embedding model from that document and must not send the marker.

**Design decision:** no merge-back of the stored literal when an editor saves a redacted document — the marker is saved and fails at the provider. Merging it back would let an editor move the marker next to a host of their choosing (H1 with extra steps).

Upgrade and sync read their targets unredacted, and the previews an editor sees are redacted at the REST boundary — see the last entry below.

**Files:** [`ConfigSecretRedactor.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/secrets/sanitize/ConfigSecretRedactor.java), [`RestLlmStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/llm/rest/RestLlmStore.java), [`RestMcpCallsStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/mcpcalls/rest/RestMcpCallsStore.java), [`RestChannelIntegrationStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/channels/rest/RestChannelIntegrationStore.java), [`RestRagStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/rag/rest/RestRagStore.java), [`RestRagIngestion.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/rag/rest/RestRagIngestion.java), [`RestApiCallsStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/apicalls/rest/RestApiCallsStore.java), [`security.md`](https://docs.labs.ai/security-and-compliance/security.md#editors-never-read-a-plaintext-credential-back), [`secrets-vault.md`](https://docs.labs.ai/security-and-compliance/secrets-vault.md#configuration-read-redaction)

**Tests:** `ConfigSecretRedactorTest` (rules, idempotence, a linear-time check on adversarial braces), one `*ReadRedactionTest` per store; each store test was mutation-checked by removing the redaction and watching it fail.

***

## 🔒 fix(security): resetting a tenant's vault requires confirm=true (2026-10-17)

**Repo:** EDDI (`fix/security-review-secrets-redaction`)

L11 of the 2026-10-17 security review. `POST /secretstore/secrets/{tenantId}/reset` deletes every secret and DEK of a tenant and had no confirmation, unlike `adopt-master-key`. It now requires `?confirm=true`; without it the answer is a `400` with `{"error": "confirm=true is required", "action": …}` and nothing is deleted. The Manager's reset dialog (which already makes the admin type the tenant id) sends the flag, and the `adopt-master-key` response names it.

**Files:** [`IRestSecretStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/secrets/rest/IRestSecretStore.java), [`RestSecretStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/secrets/rest/RestSecretStore.java), [`secrets.ts`](https://github.com/labsai/EDDI/tree/main/ui/packages/app-kit/src/lib/api/secrets.ts), [`secrets-vault.md`](https://docs.labs.ai/security-and-compliance/secrets-vault.md#lost-master-key)

***

## 🔒 fix(security): name the vault secrets that may still be sent anywhere (2026-10-17)

**Repo:** EDDI (`fix/security-review-secrets-redaction`)

The residual of H1 in the 2026-10-17 security review: PR #1079 makes the setup wizard set `allowedHosts` on every key it vaults from now on, but every secret vaulted before it keeps an open destination, so an editor can still exfiltrate it by pointing a copy of the LLM configuration at their own host.

* New `UnrestrictedSecretsCheck` (next to `VaultStartupBanner`): when the vault is enabled it scans, on a virtual thread after boot, the current version of every LLM, MCP-calls, RAG, httpcalls and channel configuration for `${vault:…}` references, reads each referenced secret's metadata, and logs **one** `[SECURITY]` WARN naming every secret without `allowedHosts` (`tenant/key`), the configurations that reference it, and the `PUT /secretstore/secrets/{tenantId}/{keyName}/grant` call that narrows it.
* `GET /secretstore/secrets/{tenantId}` (admin-only) now returns `SecretListing` entries: the same metadata fields as before plus `unrestrictedDestination` (live: `allowedHosts` empty) and `referencedBy` (from the last complete scan; absent before one).
* The scan says when it could not read every configuration: one `[SECURITY]` WARN, and `referencedBy` stays absent rather than claiming that nothing references a secret the unread configuration may use.

**Design decision:** no automatic migration. Only the admin knows which host a key belongs to; a wrong guess would break a working agent. `AgentSetupService` and `VaultSecretProvider` are untouched (PR #1079 changes them).

**Not covered:** references reached only through `${vars:…}` or `${connection:…}`, and old configuration versions that are still deployed. No Manager warning state yet (UI).

**Files:** [`UnrestrictedSecretsCheck.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/secrets/UnrestrictedSecretsCheck.java), [`SecretListing.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/secrets/rest/SecretListing.java), [`RestSecretStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/secrets/rest/RestSecretStore.java), [`secrets-vault.md`](https://docs.labs.ai/security-and-compliance/secrets-vault.md#destination-allow-list-allowedhosts)

***

## 🔒 fix(security): the free-text redaction filter knows more provider key shapes (2026-10-17)

**Repo:** EDDI (`fix/security-review-secrets-redaction`)

L6 of the 2026-10-17 security review. `SecretRedactionFilter` — which backs logs, dead letters, the audit scrub, HITL approval cards and now the config read-redaction — recognised only `sk-`, `sk-ant-`, `Bearer` and named fields. Patterns **added** (no existing rule changed): Google `AIza…`, xAI `xai-…`, Groq `gsk_…`, GitHub `gh[pousr]_…` and `github_pat_…`, Slack `xox[baprse]-…`, AWS `AKIA…`/`ASIA…` (exactly 16, not inside a longer run), bare JWTs, the credential after `Authorization: Basic|Token|Digest`, `…Subscription-Key:` headers, and the userinfo password of `mongodb(+srv)`, `postgres(ql)`, `mysql`, `redis(s)` and `amqp(s)` connection strings. (`api-key:`/`x-api-key:` were already matched by the API-key name rule.)

Every pattern is a literal prefix plus one possessive or bounded character class that admits no quote, backslash or brace, so a match cannot cross a JSON string or eat a `${vault:…}` reference. The JWT rule is the one that can fail after consuming a long run, so a lookbehind admits a start only where a token run begins — without it `eyJ` repeated 60,000 times is quadratic (the mutation check timed out at 30 s).

The connection-string rule had a 256-character ceiling on the user and on the password, and stopped at the first `@`, so a longer password — or a malformed one carrying a raw `@` (`u:abc@tail:pw@host`) — went through in part. The password is now walked by hand to the last `@` of the authority, in one pass. The labelled scheme rule lost its six-character floor (`Authorization: Basic YTpi` is `a:b`), and a quote escaped inside a JSON-carried Digest value no longer ends that credential early. Two gaps found in review: a `Digest` header lost only `username=` — the scheme rule took one unquoted token and left `response=`, the credential proper, legible — and now loses its whole directive list, walked by hand rather than by a pattern, since a quantified group recurses once per directive; and a bare `Basic <base64>` with no header name in front is redacted when the token decodes to `user:password`, so `Basic configuration` stays prose.

**Files:** [`SecretRedactionFilter.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/secrets/sanitize/SecretRedactionFilter.java), [`SecretRedactionFilterProviderShapesTest.java`](https://github.com/labsai/EDDI/tree/main/src/test/java/ai/labs/eddi/secrets/sanitize/SecretRedactionFilterProviderShapesTest.java), [`secrets-vault.md`](https://docs.labs.ai/security-and-compliance/secrets-vault.md#log-redaction)

***

## 🔒 fix(security): legacy no-AAD vault rows are re-sealed bound on first read (2026-10-17)

**Repo:** EDDI (`fix/security-review-secrets-redaction`)

L10 of the 2026-10-17 security review. `VaultSecretProvider.decryptSecretWithFallback` kept a permanent no-AAD fallback for rows written before row binding, so with database write access the ciphertexts of two such rows could be swapped and each still decrypted. Only a DEK rotation retired the fallback, and a deployment that never rotates kept it forever.

* `resolve()` now notices when a row opened only through the legacy path and re-seals it bound (`tenantId|keyName|dekId` AAD) under the **same** DEK generation, through the new `ISecretPersistence.resealSecretInPlace` (Mongo and Postgres). It rewrites only the ciphertext and IV — not `dekId`, not `lastRotatedAt` — and is guarded on the **IV** the row was read with: a dekId guard cannot see a concurrent `store` under the same generation and would write the old value back over the new one. A lost guard, a failure or an implementation without the method (the interface default writes nothing) leaves the row legacy and readable; the read never fails because of it — the write-back catches every `RuntimeException`, so a driver or pool error a store did not wrap cannot fail it either. Logged once per key per node.
* `openSealedData` (OAuth grants and other participant-owned sealed data) cannot write back — the provider does not own those rows — so it logs once per tenant that `POST /secretstore/secrets/{tenantId}/rotate-dek` re-seals them bound.

**Files:** [`VaultSecretProvider.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/secrets/impl/VaultSecretProvider.java), [`ISecretPersistence.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/secrets/persistence/ISecretPersistence.java), [`MongoSecretPersistence.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/secrets/persistence/MongoSecretPersistence.java), [`PostgresSecretPersistence.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/secrets/persistence/PostgresSecretPersistence.java), [`secrets-vault.md`](https://docs.labs.ai/security-and-compliance/secrets-vault.md#encryption)

**Tests:** `VaultLegacySealingRetirementTest` (re-seal on read, swap refused afterwards, a store racing the write-back wins, a failing write-back does not fail the read) and guard tests in the Mongo and Postgres persistence unit tests; mutation-checked.

***

## 🔒 fix(security): the read-redaction marker is never stored; upgrade and sync read targets unredacted (2026-10-17)

**Repo:** EDDI (`fix/security-review-secrets-redaction`)

Follow-up to the M1 read-redaction above, so it can never turn into stored corruption.

* **Writes refuse the marker.** New `RedactionMarkerGuard` (`configs/rest`): every create, update, JSON Patch and duplicate of the LLM, MCP-calls, channel, RAG and httpcalls stores, `RestImportService.createResourceDirect` and `UpgradeExecutor.createExtension` answer `400 {"error": "bad_request", "message": …, "fields": […]}` when any string in the document contains `<redacted:` , for administrators too. The import and upgrade paths create every resource type through one method, so there the check is scoped to those five document types (`requireNoneIfRedactedType`): a workflow or output set that merely mentions the marker text is content and imports. Before this, an editor who opened a configuration in the Manager and saved it replaced the stored key with the marker, and the agent broke at its next deploy.
* **One recognisable marker.** The in-string marker `ConfigSecretRedactor` writes into URLs, headers and bodies is now `<redacted: credential>` instead of the filter's generic `<REDACTED>`, which a prompt or output template may legitimately contain. Both markers share the `<redacted:` prefix the guard looks for.
* **Unredacted internal reads.** `RestLlmStore`, `RestMcpCallsStore`, `RestApiCallsStore` and `RestRagStore` expose `readUnredacted` (same access check; `readRagForIngestion` became `readUnredacted`). `StructuralMatcher` reads upgrade/sync targets through it instead of the loopback REST client, so an editor-run upgrade neither diffs against the marker nor writes it: the export's `${vault:REDACTED}` placeholder is replaced by the target's own key.
* A sync **source** read from a peer through a non-admin credential carries the peer's marker; such resources are now refused rather than stored.
* **Previews are redacted for editors.** The matcher's unredacted target content is also what the upgrade and sync previews return, and those endpoints admit `eddi-editor`, so `RestImportService` redacts `sourceContent` and `targetContent` for every caller who is not `eddi-admin` (`PreviewRedaction`, with the stores' redactor and skipped paths) before a preview leaves the server. The upgrade itself still writes from the unredacted read. (Review finding on the PR.)

**Tests:** a `*RedactionMarkerWriteTest` per store, a marker case in `RestImportServiceCallerTokenTest`, `EditorUpgradeKeepsTargetCredentialTest` (an editor-run upgrade of an agent whose LLM config holds a plaintext key keeps it and is not refused), `PreviewRedactionTest` and `RestImportServicePreviewRedactionTest`; each mutation-checked.

**Files:** [`RedactionMarkerGuard.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/rest/RedactionMarkerGuard.java), [`ConfigSecretRedactor.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/secrets/sanitize/ConfigSecretRedactor.java), [`PreviewRedaction.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/backup/impl/PreviewRedaction.java), [`StructuralMatcher.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/backup/impl/StructuralMatcher.java), [`UpgradeExecutor.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/backup/impl/UpgradeExecutor.java), [`RestImportService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/backup/impl/RestImportService.java), [`security.md`](https://docs.labs.ai/security-and-compliance/security.md#editors-never-read-a-plaintext-credential-back)

***

## 🔒 fix(manager,chat): UI findings from the 2026-10-17 security review (2026-10-17)

**Repo:** EDDI (`fix/security-review-ui`)

### What changed and why

The UI half of the 2026-10-17 review (L1, L5, and the Manager side of M5). The backend halves are separate branches.

* **L1, Chat `?apiServer=`.** `http.ts` builds request URLs by concatenating the base and the path, and the allow-list let `?` and `#` through, so `?apiServer=%2Fadministration%2Fcluster%2Fcaches%2Fresync%3F` made the widget's start call a state-changing request to another same-origin path, carrying the page's credentials. `sanitizeApiServer` now parses the value against the page origin and accepts it only when the origin is unchanged, `search` and `hash` are empty, the pathname is exactly the input (so `..` and `.` segments are refused), and it has no `%`. Documented in [`chat-ui-embedding.md`](https://docs.labs.ai/protocols-and-integration/chat-ui-embedding.md).
* **L5a, opt-in agent HTML.** `sanitizeAgentHtml` now forbids `class` (Tailwind utilities could paint a full-viewport fake prompt) and the `svg`, `math`, `image`, `feImage` and `use` elements (render-time fetches), and forces `target="_blank" rel="noopener noreferrer"` on every anchor through a hook registered only for the call.
* **L5b, ids in request paths.** New `lib/api/path-segment.ts`: `seg()` encodes an id and refuses `/`, `\`, `..`, whitespace, control characters and empty values; `nameSeg()` encodes a free-form name (connection name, tenant, secret key) and refuses only `.`, `..` and empty. Every id interpolated into a path under `lib/api/` now goes through one of them (about 160 call sites in 32 files). The chat panel drops an unsafe `?agentId=` / `?conversationId=` before issuing `GET /agents/<id>`.
* **L5c, `navigateAway`.** The OAuth link flow navigates only to an `https:` URL, or `http:` for localhost, 127.0.0.1 and \[::1], without embedded credentials (`lib/authorization-url.ts`). Anything else is a failed start with the existing "Could not start linking." toast.
* **L5d, pinned Workforce responses.** The `localStorage` key now names the signed-in principal (`workforce-pins-<principal>:<board>`), and sign-out removes every `workforce-pins-*` key.
* **M5, Platform Operator trust.** `platform.operator` is writable by `eddi-editor`. The Manager now opens the operator chat, history and conversation restore only when the agent's descriptor carries `[eddi-platform-operator]` **and** the approval gate verifies on every version (`useOperatorTrust`, `lib/operator/operator-trust.ts`). Otherwise the drawer and the operator page show an "operator could not be verified" panel with *Check again*, and fail closed when a check cannot be completed. Before an **Upgrade** that keeps the stored instructions, or a **Reconfigure** that carries them over, the admin sees a line diff against the default (and the full stored text) and must tick a confirmation. The Manager also does nothing *to* an agent it could not verify (review follow-up on PR #1082): the marker is read at the agent's **current** version from the store, never at `config.version` (that number sits in the same editor-writable variable as the id, so its author chose which descriptor would be inspected); an unverified agent gets no *Check connection*, *Deactivate* or upgrade notice, and a paused one no *Turn back on*; *Reconfigure* provisions the replacement with `retirePredecessor: false`, which leaves the old agent exactly as it was and reports that in the superseded banner; and *Delete operator* becomes *Unregister operator* (`useUnregisterOperator`), which drops `platform.operator` and touches no agent. 21 new strings in all eleven locales.

### Design decisions

* The marker is writable by anyone who can edit the descriptor, so the check is a tripwire, not a signature. The real fix is reserving `platform.*` for `eddi-admin` on the backend (other branch). It is stated in the docs.
* An unverified agent is left alone rather than retired on Reconfigure or deleted on Delete, even though the admin asked: `platform.operator` can name *any* agent, so a retire-and-replace flow would be the one-click way for an editor to have an admin permanently delete someone else's agent and its resources. The admin gets the Agents screen instead, where the agent is shown for what it is.
* `seg()` throws rather than sending a mangled request. Free-form names get the lighter `nameSeg()` because existing tests (and real tenants and secret keys) contain spaces and slashes that `encodeURIComponent` already makes inert.
* No change to `system-prompt.ts` or `tool-scopes.ts`, so `operator-revision.json` is not bumped.

### Not done / follow-up

* The Stryker scope includes `src/lib/operator/**`; the mutation run was not repeated for the two new files there (`operator-trust.ts`, `prompt-diff.ts`).

**Files:** [`ChatWidget.tsx`](https://github.com/labsai/EDDI/tree/main/ui/chat/src/components/ChatWidget.tsx), [`markdown-safe.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/markdown-safe.tsx), [`path-segment.ts`](https://github.com/labsai/EDDI/tree/main/ui/packages/app-kit/src/lib/api/path-segment.ts), [`authorization-url.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/authorization-url.ts), [`workforce-pins.ts`](https://github.com/labsai/EDDI/tree/main/ui/packages/app-kit/src/lib/workforce-pins.ts), [`operator-trust.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/operator/operator-trust.ts), [`operator-untrusted.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/components/operator/operator-untrusted.tsx)

***

## ⚡ fix(ui): clicks that never wait on I/O, and a Chat UI that holds up on phones (2026-10-17)

**Repo:** EDDI (`fix/ui-click-responsiveness`)

Half of a review of both UIs for click latency, every screen size and every state. Four read-only reviews (click responsiveness, layout/RTL, Manager state handling, Chat UI) produced about 100 verified findings. This PR holds the Manager's click-latency fixes and the whole Chat UI; the Manager's layout, RTL and state fixes are in the companion PR on `fix/manager-layout-a11y`. The two share no file and build independently. Agent cards here carry the `reveal-on-touch` class, which that PR defines; until it lands the class is inert.

### Clicks no longer wait on I/O (Manager)

* **Optimistic updates.** New [`lib/optimistic.ts`](https://github.com/labsai/EDDI/tree/main/ui/packages/app-kit/src/lib/optimistic.ts) (`patchQueries` / `restoreQueries`). The schedule enable toggle flips its row at once and rolls back on failure; only the clicked row is disabled, not every toggle on the page. Notification mark-read/dismiss update the badge and the list immediately, and busy state is per item.
* **Mutations no longer hold their pending state through a refetch.** `onSuccess`/`onSettled` arrows that *returned* `invalidateQueries(...)` made TanStack wait for the refetch before call-site callbacks ran (closing a dialog, navigating). Fixed in `use-cluster`, `use-group-templates`, `use-group-workspace` and `use-user-conversations`. The share dialog no longer awaits five invalidations one by one before re-enabling its controls.
* **Deploy no longer refetches every agent card.** Deploy and undeploy invalidated all of `agentKeys.all`, so every card's status query refired. `agentDeploymentQueries(agentIds)` in [`query-keys.ts`](https://github.com/labsai/EDDI/tree/main/ui/packages/app-kit/src/lib/query-keys.ts) matches only the deployed agent's entries and the environment listings, and refreshes any sub-key it does not recognise.
* **Filters stop blanking the list.** Search on agents and workflows, the cluster leases and dead-letter filters, and the logs instance filter are debounced (250–300 ms) and use `placeholderData: keepPreviousData`.
* **Fewer sequential round trips.** The "where is this used" scan after a resource save fetches workflows and agents with bounded concurrency (8), and fetches each agent once rather than once per matching workflow. Grant dry runs run in parallel, and so do the agent editor sheet's post-save invalidations.

### Chat UI

* Layout: a long code line or a wide table widened the bubble and scrolled the whole transcript sideways (`min-width: 0`, plus a table scroller). Inputs are 16px so iOS does not zoom on focus. The viewport meta adds `viewport-fit=cover` and `interactive-widget=resizes-content`, and the root height is `100dvh`, so the composer clears both the home indicator and the keyboard. Very wide screens cap line length. Lists, blockquotes and tables use logical properties, and messages carry `dir="auto"`.
* Scrolling: pressing Scroll to bottom during a reply turned following off again as soon as the smooth scroll began, because its own scroll events read as "left the bottom". Now only the reader moving up ends following. The view also re-pins for content that grows without a new message (the throttled trailing render, images, KaTeX, a shrinking viewport), and the button scrolls the transcript rather than the host page.
* Indicators: no more dots under a reply that is already streaming. Undo, redo, retry and cancel no longer show the typing dots or a Stop button. Pressing Stop then would have cancelled the conversation and raised a false "interrupted" banner.
* Focus and input: focus moves to the composer after a quick reply or Stop, and back to the New-conversation button when its confirmation is cancelled. Quick replies render disabled while a click would be dropped. On touch screens Enter inserts a newline. A refused draft regrows to its height. An agent-requested field no longer steals focus on page load.
* Undo and redo rebuild messages with position-derived ids, so unchanged bubbles keep their keys and are not re-animated and re-parsed. The status strings "Thinking…", "Using {tool}…" and the scroll button label are translated.

### Team setup, HITL and background polling

* **Group and Workforce wizards set their members up in parallel.** `runDeployManyWithGrants` deploys `DEPLOY_MANY_CONCURRENCY` (3) targets at a time instead of one after another, and both wizards create new agents three at a time. The grant dialog still asks one question at a time: a new request used to cancel the open one, which is why the loop was sequential, so the per-agent second-chance dialogs now go through `serializeGrantDecisions`. Every agent that was created is recorded before a failure is reported, because provisioning is not idempotent. The Workforce wizard raises one toast for the batch, and each failed row shows its own error.
* **HITL human-input submit is optimistic.** The cached group conversation leaves `AWAITING_HUMAN_INPUT` at once and is put back if the submit fails. It used to await two refetches, which kept the button pending for an extra round trip.
* **The Chat UI no longer polls approval status from a hidden tab.** The next read is parked and taken at once when the tab is visible again.

### Review fixes

* Optimistic rollbacks are scoped to their own operation. A failed schedule toggle undoes only its row, and a failed notification dismiss undoes only its items and its share of the badge, instead of restoring a whole snapshot over a later change. Every schedule row with a toggle in flight stays disabled (`useMutationState`), not just the latest one.
* The share dialog refreshes the agent's detail and descriptor queries as well as the lists. Those keys have their own roots, `agent` and `agent-descriptor`, not `agents`.
* Dead-letter paging is disabled while a page is still placeholder data, so a second click cannot push the same cursor twice.
* The logs instance box follows back/forward navigation.
* Schedule edits made through the trigger tabs, cron presets and the agent picker count as edits, so Escape or a backdrop click no longer discards them.
* The Chat composer takes a pending focus request only once the turn has finished, so the phone keyboard does not cover a reply as it arrives.

### Not done (follow-ups)

* A client-side idle watchdog for a stalled chat stream was considered and rejected. The conversation stream sends no keep-alives (only the log stream does), so a single slow tool or model call is legitimately silent for minutes, and a watchdog would cut real turns off as "connection lost". It needs a server-side heartbeat first.
* Workforce analytics and the skill registry still fire one request per group or skill; both need batch endpoints on the backend.

### Tests

New: [`responsiveness-review.test.tsx`](https://github.com/labsai/EDDI/tree/main/ui/chat/src/components/responsiveness-review.test.tsx) and a Scroll-to-bottom regression in `ChatWidget.ux.test.tsx` (Chat), and [`optimistic-mutations.test.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/hooks/__tests__/optimistic-mutations.test.tsx) (Manager), plus [`deploy-many-concurrency.test.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/hooks/__tests__/deploy-many-concurrency.test.ts) and a hidden-tab case in `useHitlPolling.test.ts`. Mutation-checked: restoring the old scroll handler, dropping the dialog queue (in the serializer or in its use), dropping the HITL cache patch and ignoring visibility each fail a test.

***

## feat(manager): model picker that always shows the whole catalog, and a refreshed model list (2026-10-17)

**Repo:** EDDI (`feat/manager-model-picker`)

### What changed and why

**The model field no longer hides the catalog.** The agent wizard, the LLM editor and the operator activation form used a native `<datalist>`, which filters its options by whatever the input holds. The field is pre-filled with the provider's default, so clicking it showed one option, the default, and read as "this provider has one model". The new `ModelCombobox` (`ui/manager/src/components/shared/model-combobox.tsx`) replaces all three:

* A click, the chevron or ArrowDown opens the whole list with the current value ticked and scrolled into view. The provider default carries a `default` badge.
* Typing puts matches under a "Matching …" heading and keeps every other suggestion below a divider under "Other models". Matching ignores case and separators, so `opus 5.5` finds `claude-opus-5-5`.
* When nothing matches, a note says the typed id is used as typed. A footer repeats that any id the provider supports can be typed. The suggestions are help, not a whitelist.
* It follows the ARIA combobox pattern (`aria-activedescendant`, grouped listbox). Escape closes only the list, not the dialog around it. A read-only field gets no list.

The grouping lives in `groupModelSuggestions` in `lib/model-suggestions.ts`. The 7 new `modelCombobox.*` strings are translated into all 11 locales.

**Catalog refresh.** Every id was checked against the provider's model and deprecation pages on 2026-10-17.

* **Added:**
  * `claude-haiku-5-5` (Anthropic, Vertex, Bedrock)
  * `gemini-4-argon` (Gemini, Vertex, OpenRouter)
  * The GPT-6 family on Azure and Bedrock
  * `mistral-large-4`
  * `grok-build-0.1`
  * Grok, Gemini and Llama 4 Scout on OCI
  * Gemma 4, Qwen 3.5/3.6, Ministral 3 and gpt-oss on Ollama
  * Popular OpenRouter slugs
* **Removed:**
  * OpenAI: `o3-mini` (shut down 2026-10-23), `gpt-5.4-nano`, the `gpt-5` family, and `gpt-5.4-thinking`, which was never an API id
  * Gemini: `gemini-3.7-flash` and `gemini-3.5-flash`, both deprecated on AI Studio
  * Vertex: `gemini-2.5-*`, retiring 2026-10-20
  * MiniMax: the M2.7 pair (retiring 2026-11-18). M3.1-Flash-Preview stays, because the parameter catalog has rules for it, though MiniMax currently offers it only on its subscription plans
  * Bedrock: models now Legacy or past end of life (Llama 3.x/4, MiniMax M2)
  * Azure: deprecated gpt-4o and gpt-4.1
* **Fixed ids that never existed:**
  * Hugging Face: `deepseek-ai/DeepSeek-V4`, `google/gemma-4-assistant` and `Qwen/Qwen3.5-7B`
  * Bedrock: `anthropic.claude-sonnet-4-6-v1:0`
  * OCI: the `openai/gpt-oss-*` ids, which take a dot after the vendor, not a slash
  * Vertex: `claude-haiku-4-5@20251001`
* **Bedrock** now suggests `global.` inference-profile ids. Most current models have no in-Region endpoint on `bedrock-runtime`.
* **Defaults:**
  * Gemini and Vertex: `gemini-3.5-flash` → `gemini-3.8-flash`
  * Hugging Face: `Qwen/Qwen3.5-7B`, which does not exist → `Qwen/Qwen3.8-27B`
* The named-compatible changes (xAI, MiniMax, OpenRouter) are made in both `openai-compatible-providers.json` and its Manager mirror.
* The operator's system prompt lists these suggestions, so the operator revision is bumped.

### Not done

`ModelCombobox` is not added to the design-sync mirror (`.design-sync/`).

***

## ⚡ perf(engine): convert only the current step for a turn's response, drop per-turn INFO logging (2026-10-17)

**Repo:** EDDI (`perf/hotpath-and-startup`)

### What changed and why

Part of the throughput work ([`planning/throughput-optimization-plan.md`](https://github.com/labsai/EDDI/tree/main/planning/throughput-optimization-plan.md), WS3b and WS8.5). A JProfiler run at 1,000 concurrent conversations put 9% of running time in Jackson and about 2% in per-turn `Logger.info` calls and `String.format`.

* **Current-step-only conversion (WS3b).** The memory overload of `ConversationMemoryUtilities.convertSimpleConversationMemorySnapshot` converted every step of the conversation and then returned only the last one, which is the default turn response (`returnCurrentStepOnly=true`) and the HITL replies. With `returnCurrentStepOnly` it now builds the snapshot through `convertConversationMemoryForCurrentStep`: same header, outputs, properties and redo cache, and a step list of the same size whose entries are converted only when read. The projection reads the last step and the list's size, so a turn converts one step instead of all of them. Redaction, secret-turn masking, the error field and the undo/redo flags are unchanged: they run in `convertSimpleConversationMemory`, which still does the work. A reader that walks every step still gets correct values, because each step converts on first access; it just gets no saving. Callers in `ConversationService` needed no change.
* **A quadratic loop in `convertConversationMemory`.** `IConversationMemory.getAllSteps()` copies the whole step list on every call, and the conversion called it twice per step. It is now called once. The persistence path uses this conversion too.
* **Per-turn INFO logs are now DEBUG.** Every turn logged four INFO lines, even for an agent with no tools: "Discovering httpcall tools…", "Discovered 0 httpcall tools…" and the two `mcpcalls` equivalents. Lines that fire on every turn when their feature is configured moved to DEBUG as well: built-in tool counts and lazy-tool loading (`AgentOrchestrator`, `ToolLoopRunner`), the contextual memory/recall/attachment tools, RAG and rolling-summary injection (`LlmTask`, `RagContextProvider`), the httpcall tool result line, and the cascade step lines. The string-concatenating ones now use `debugf`, so nothing is built while DEBUG is off.
* **No more `new ObjectMapper()` per discover\_tools result (WS8.5).** `ToolLoopRunner.activateDiscoveredTools` built a mapper for every result; it now uses a shared one.
* **Bound Jackson readers and writers.** The Mongo `JacksonCodec` binds an `ObjectReader` for its type and an `ObjectWriter` once, instead of resolving them through the mapper for every document. `JsonSerialization` does the same for its writer and untyped reader.

### Measurements

Conversion, single thread, best of five (memory with ten properties and twelve data per step):

| Steps | Full conversion (persist) before → after | Turn response before → after |
| ----- | ---------------------------------------- | ---------------------------- |
| 10    | 8.0 → 6.6 µs                             | ≥ 8 → 1.0 µs                 |
| 50    | 57.8 → 30.4 µs                           | ≥ 58 → 2.6 µs                |
| 200   | 376 → 113 µs                             | ≥ 376 → 2.5 µs               |

"Turn response before" is at least the old full conversion, which the projection ran first. End to end (`scripts/loadtest`, `origin/main` against this branch, alternating A/B/A/B on Docker Desktop on a shared machine, so treat the numbers as indicative): steady 50 conversations with a 0 ms mock LLM, 81.9 → 102.9 turns/s on average (the rounds overlap: 88.7 and 75.1 against 120.1 and 85.7); long-conversation (5 × 200 turns), p50 87 → 80 ms at the same throughput, since MongoDB dominates there. INFO lines per run: 16,043 → 43.

### Tests

`ConversationMemoryCurrentStepConversionTest`: 168 golden-equivalence cases compare the new path with the full conversion plus trim across six memories (plain, secret last turn, secret earlier turn, error, redo, single step) × `returnDetailed` × `returnCurrentStepOnly` × seven `returningFields` shapes. One test checks that the path still redacts credentials, drops `audit:*` and masks a secret turn. One guard checks that only the newest step is read. Mutation-checked: reading the steps in the wrong order fails 51 cases, converting eagerly fails the guard, and dropping the redo cache fails 14 cases.

### Not done here

PR #1066 adds a `conversationCost` sum over **all** steps to `convertSimpleConversationMemory`. It stays correct on this path, because the lazy list converts every step it is asked for, but it gives up most of the saving for the default response. Once both land, the cost sum should read `audit:cost` from the live steps (or from a running total) rather than from converted snapshots.

**Files:** [`ConversationMemoryUtilities.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/memory/ConversationMemoryUtilities.java), [`JacksonCodec.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/datastore/mongo/codec/JacksonCodec.java), [`JsonSerialization.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/datastore/serialization/JsonSerialization.java), [`ToolLoopRunner.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/ToolLoopRunner.java), [`HttpCallToolsProvider.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/HttpCallToolsProvider.java), [`McpToolsProvider.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/McpToolsProvider.java), `AgentOrchestrator`, `ContextualToolsProvider`, `LlmTask`, `RagContextProvider`, `CascadingModelExecutor`.

***

## test(loadtest): cluster mode for the turn load test, N replicas behind nginx (2026-10-17)

**Repo:** EDDI · **Branch:** `test/loadtest-cluster-scaling`

### What changed and why

Cluster mode (NATS leases with fencing, the cluster event bus, degraded mode) is well tested for correctness, but nothing measured multi-node throughput: the single-node WS2 report was the only data, and the sizing claims in [clustering.md](https://docs.labs.ai/deployment-and-infrastructure/clustering.md#sizing), including "the database is the shared bottleneck", were unverified.

* **`scripts/loadtest/docker-compose.cluster.yml`** (new): the topology of the repository's `docker-compose.cluster.yml` and `scripts/cluster-demo` (N EDDI replicas with `eddi.messaging.type=nats`, three NATS nodes at R3, one MongoDB, nginx round-robin), plus the WireMock LLM and k6. It has its own ports (75xx), so it runs next to the single-node stack.
* **`scripts/loadtest/nginx-cluster.conf`** (new): the cluster balancer's rules, sized for thousands of connections. It adds `X-Loadtest-Upstream` to every response, and only a refused connection moves on to the next replica, so 409s and 503s reach k6 and get counted.
* **`k6/turns.js`**: with `NODE_ADDRS` set, every turn metric is tagged with the replica that answered, and one no-op threshold per node makes k6 write the per-node submetrics into its summary.
* **`loadtest.py`**: new commands `cluster-up --nodes N`, `cluster-run`, `cluster-down`, `cluster-matrix --nodes 1,2,4,8 [--baseline]` and `cluster-report`. Every point starts from a fresh stack and gets a warm-up run that is thrown away. Each run collects, per node: turns/s, p50/p95/p99, 409/503, `eddi_cluster_lease_acquire_seconds` by outcome, `eddi_cluster_fence_rejected_total`, peak in-flight turns and leases held. Across the cluster it collects MongoDB ops per turn and per second, NATS messages per turn, and the CPU of every container (other stacks' too) plus the host's. `--baseline` adds one single node with `eddi.messaging.type=in-memory`, so the overhead of cluster mode at N=1 shows up.

### Design decisions

* **Comparability is explicit.** In-flight turns per node (`--max-in-flight`, 400), the MongoDB `maxPoolSize` (100), heap, memory and CPUs per node are passed on every point. None of them is left to `max-in-flight-turns=auto`, which depends on the heap.
* **Host CPU is measured, not assumed.** On Docker Desktop, the replicas, MongoDB, NATS, nginx and k6 share one VM with everything else on the machine. The report gives the host's CPU (typeperf on Windows) and other stacks' container CPU next to the efficiency column, because on one machine a falling efficiency can come from the host as easily as from the database.
* **Agent setup goes to a node directly.** Right after start, the balancer can still hold an address it resolved before the replica was up, and it answers the setup POST with a 502.
* **MongoDB gets `restart: on-failure`.** On a busy host the image's two-step first start can fail with exit 48 (address in use).

### Results

[`scripts/loadtest/results/cluster-scaling-2026-10-18.md`](https://github.com/labsai/EDDI/tree/main/scripts/loadtest/results/cluster-scaling-2026-10-18.md). The setup was 100 conversations per node, a 3 s mock LLM and 2 CPUs per node. The host was saturated (85–99 % CPU, shared with other sessions' work), so the report measures overhead and shape, not true horizontal scaling.

* **Errors:** none across 18k turns — no 409, no 503, no fence rejection.
* **Overhead at N=1:** cluster mode ran 16.1 turns/s against 21.3 in memory (−24 %, +1.4 s p50). Every turn paid an uncontended lease acquire of \~151 ms.
* **Lease contention:** round-robin without affinity makes 13–32 % of acquires contended (0.5–2.6 s extra) even with one sequential client per conversation. A turn holds its lease until persisted, which is after the reply.
* **Efficiency:** 1.11 at N=2 (a quiet re-run; the first N=2 run read 0.28), 0.65 at N=4, 0.40 at N=8.
* **Where it saturated:** node CPU at N=4, then host CPU at N=8. MongoDB peaked at 1.2k ops/s (23 ops/turn, flat in N, 2.25 of 4 CPUs) and NATS at 0.5 CPU per node, so neither was the limit. The expected database knee is untested here.
* **NATS cost:** about 14–22 ms of NATS CPU per turn across R3. That puts a 1-vCPU NATS node nearer 150–200 turns/s than the docs' "thousands", and needs a re-check on a quiet machine.

### Follow-ups

Profile the uncontended lease acquire. Decide between releasing the lease before post-reply persistence and routing by conversation in the reference nginx config. Re-measure NATS CPU and the database knee on separate machines.

***

## perf(engine): fewer MongoDB round trips per conversation turn (2026-10-16)

**Repo:** EDDI (`perf/turn-mongo-roundtrips`)

A JProfiler profile of the virtual-thread build (labsai/EDDI#1045) counted about 17 MongoDB reads per turn, each with a named caller, and found the driver's connection pool to be the ceiling once turns run on virtual threads (418 operations queued for a connection at 500 in-flight turns). This branch removes the redundant ones, one commit each, in the order the profile suggested.

### What changed and why

* **One conversation-descriptor read per request.** A REST turn read the same descriptor three times before it started: `RestAgentEngine`'s ownership check, the same check again in `ConversationService.say`, and the soft-delete check right after it. New `ConversationDescriptorMemo` (`@RequestScoped`) remembers the resolved descriptor (live, archived or none) for the rest of the request; `ConversationAccessGuard` and `ConversationService.isSoftDeleted` both resolve through it. Only the descriptor is shared, never a decision: each check still compares the owner against its own identity. Store failures are not remembered, every write through `ConversationDescriptorStore` forgets the conversation, and outside a request (worker threads, schedules) every lookup reads the store as before. Saves 2 reads per turn on the request thread, where the profile saw most of the pool waits.
* **`updateTimeStamp` is one update (WS3c).** It was `getCurrentResourceId` + `readDescriptor` + `ModifiableHistorizedResourceStore.set` (which reads again) + a version-checked full replace: 3 reads and a write on every turn's completion path. New storage SPI method `IResourceStorage.setNumberField(id, field, long)`: MongoDB `updateOne` with `$set`, PostgreSQL `UPDATE … SET data = jsonb_set(…, to_jsonb(?::bigint))`, both on the live row only (a soft-deleted or unknown id writes nothing). `DescriptorStore.touchLastModified` uses it; `ConversationDescriptorStore.updateTimeStamp` falls back to the old rewrite only for a backend without it. The value is stored as a number, exactly as the persistence mapper writes dates (epoch millis), so retention (`RestConversationStore` compares `getLastModifiedOn()`) and the listings' server-side sort see no difference — `DescriptorTouchParityTest` checks the read-back date, the stored type (BSON int64 / jsonb number), the sort position among fully written descriptors and that no other field or version changes, on a real MongoDB and PostgreSQL. A side benefit: the replace could overwrite a concurrent edit of any other descriptor field with the copy it had read; a single-field update cannot. A failure is now logged and swallowed instead of thrown into the completion callback, where it would have broken the response of a turn that was already stored.
* **Signing negative cache (WS8.1).** `AgentSigningService.loadPrivateKey` cached only keys it found, so with an active vault every audit entry of a keyless agent (three per turn) asked the vault — a `secretvault_secrets` read — only to hear "not found" again. A "not found" is now remembered for 60 s per key (`MISSING_KEY_TTL_NANOS`, bounded at 10 000 entries). A vault *failure* is never remembered. Generating or rotating a key on this node evicts the entry, so the new key signs at once — including when a lookup that started before the key was stored answers "not found" after the eviction: every eviction is counted, and a miss whose lookup saw the count move is withdrawn instead of remembered; a key created on another node is picked up within the TTL, and entries written meanwhile carry no signature, as they would have a moment earlier. This is also step 7 of PQ-5a in the PQC plan — implemented once, here.
* **Pinned agent configuration from memory.** `ConversationHitlService.lookupAgentConfigPinned` read the agent document at the conversation's pinned version on every turn, only to learn its tool-approval policy. New `AgentConfigurationCache` (`@ApplicationScoped`, Caffeine, 1 000 entries, 30 min after last access) keeps `(agentId, version)` configurations: a stored version never changes (edits write a new version; the only in-place writers are the descriptor stores and the startup migrations). Absence and store failures are not cached, so the HITL gate still fails closed on a read error and still falls back to the latest version when the pinned one is gone. `AgentFactory` drops an agent's entries on every deploy and undeploy. `WorkflowTraversal`'s own short-lived traversal cache is left as it is; WS1 should hang its invalidation off the same deployment hooks.
* **One full conversation load per turn (WS3a).** The conversation-id entry points (`say` / `sayStreaming` without an environment — REST, SSE, MCP, Slack, `/v1`) load the snapshot to find the agent and run the pre-turn checks, then called the environment-qualified overload, whose admission (`admitTurn`) loaded the same document again. That load is now handed down (`preloaded`) and converted instead of re-read. The idempotency admission (`admitOrServe`) still runs between the load and the turn, as before; a deferred duplicate re-enters the whole entry point and loads afresh. The environment-qualified overloads (A2A, group members, tests) still load on their own. Staleness is unchanged: the second load used to happen a moment after the first, and the step runner's `reloadIfSuperseded` revision check still guards the turn either way.

### Measured

Load-test harness from labsai/EDDI#1044 (`steady`, 50 conversations × 20 turns, mock LLM delay 0 ms, everything in Docker), `origin/main` (`aa8806c68`) against this branch, 1 000 turns each. MongoDB operations per successful turn (`serverStatus().opcounters`, per-collection from `top`):

|                                  | Before      | After       |
| -------------------------------- | ----------- | ----------- |
| **Queries per turn**             | **16.67**   | **6.65**    |
| `descriptors` queries            | 6.05        | 1.05        |
| `conversationmemories` queries   | 5.04        | 4.08        |
| `secretvault_secrets` queries    | 3.05        | 0.06        |
| `agents` queries                 | 1.09        | 0.09        |
| Updates / inserts per turn       | 2.05 / 3.11 | 2.05 / 3.11 |
| Turns/s (single run, indicative) | 117         | 146         |

On PostgreSQL (`pg_stat_statements`, `SELECT conversation_state, data FROM conversation_memories`), full conversation loads per turn went from 2.09 to 1.13 with short conversations, and from 2.74 to 1.88 in the `long-conversation` scenario (10 × 200 turns). An instrumented build traced the excess over MongoDB's 2.0 to `ConversationStepRunner.reloadIfSuperseded`: the reply is delivered before the turn is persisted, and on PostgreSQL the full-document append grows with the conversation, so the client's next turn is often admitted against the row as it was before the previous turn's write and reloaded when it runs (68 % of turns on `main`). That reload is what keeps the turn on the current document, so it stays; avoiding it means loading at run time when a turn is already in flight, or a cheaper PostgreSQL write (WS6/WS7).

The descriptor write stays one per turn, now a `$set` instead of a replace. Left on the turn path: one descriptor read (the ownership check), the full conversation load, the state and revision projections, and the GDPR restriction check on `usermemories`.

### Design decisions

* **A request-scoped memo, not new parameters.** The checks sit behind `IConversationService.say` / `sayStreaming`, which Slack, MCP, `/v1` and A2A also call; threading a resolved descriptor through all of them would have changed every signature for a saving that only the REST path needs twice.

***

## 🔒 fix(ui): clear three npm advisories reported by Scorecard (2026-10-16)

**Repo:** EDDI (`fix/ui-dependency-advisories`)

### What changed and why

OpenSSF Scorecard's Vulnerabilities check flagged three advisories. All three came from the UI lockfiles, not from the Maven build.

* **GHSA-238p-pmpm-9mq7, KaTeX prototype-pollution trust bypass (`katex` < 0.18.2).** The Chat UI's own `katex` was already 0.19.0. `rehype-katex@7.0.1` and `micromark-extension-math@3.1.0` each ask for `^0.16`, which gave them a nested 0.16.47 copy that ships in the chat bundle. Both are on their latest release, so an npm `overrides` entry now points both at the root version (`$katex`). Build, lint and all 480 chat tests pass, including the `MessageBubble` math-rendering tests.
* **GHSA-rj75-hqrm-r3gf, quadratic selector parsing in `postcss-selector-parser` (< 7.1.6).** `@tailwindcss/typography@0.5.20`, also on its latest release, pins exactly 6.0.10. The Manager now overrides it to `^7.1.6`. This is a build-time dev dependency. The Manager's generated CSS is byte-for-byte identical under 6.0.10 and 7.1.6, across all three stylesheets and 141 `.prose` rules.
* **GHSA-vfj7-8cjw-p6xm, `braces` stack exhaustion (all versions through 3.0.3, with no fixed release).** It reached the repo only through `ui/manager/.ds-sync/package-lock.json`, via `@tailwindcss/cli` → `@parcel/watcher` → `micromatch`. `.ds-sync` holds local design-sync tooling that is never shipped and is not inventoried in the SBOM. Its lockfile is removed and gitignored, and the Dependabot entry for that directory stays to keep the manifest's direct dependencies current.

Both lockfiles were regenerated with the pinned Node 24.21.0 (npm 11.19.0), so the diff holds only the dependency change, without `peer`-flag churn from a different npm. Each nested entry was deleted by hand before `npm install`, because npm does not apply a new override to an entry the lockfile has already resolved.

**Files:** [`ui/chat/package.json`](https://github.com/labsai/EDDI/tree/main/ui/chat/package.json), [`ui/manager/package.json`](https://github.com/labsai/EDDI/tree/main/ui/manager/package.json), both `package-lock.json` files, [`ui/manager/.gitignore`](https://github.com/labsai/EDDI/tree/main/ui/manager/.gitignore/README.md), [`.github/dependabot.yml`](https://github.com/labsai/EDDI/tree/main/.github/dependabot.yml)

### Next

Drop the two overrides once `rehype-katex`/`micromark-extension-math` accept KaTeX ≥ 0.18.2 and `@tailwindcss/typography` stops pinning `postcss-selector-parser` 6.

***

## docs(planning): human takeover / handoff design for review (2026-10-15)

**Repo:** EDDI (`docs/planning-human-takeover`; planning document only, no production code)

### What changed and why

WS7 of the competitor-research roadmap needs a maintainer-approved design before any code: a live 1:1 conversation handed to a person, who talks to the user while the pipeline is off and then hands it back. [`planning/human-takeover-design.md`](https://github.com/labsai/EDDI/tree/main/planning/human-takeover-design.md) is that design, written against `origin/main` @ `aa811c838`.

* **Inventory of every branch on `ConversationState`.** Engine, both conversation stores, cluster leases and fencing (#956), idempotent turns (#1000), the idle sweep and undeploy (#990), HITL, `/v1`, Slack, A2A, MCP, group members, schedules, Chat UI and Manager. Each entry gives the location, what it does today and what the new state needs. Allow-list sites are safe by default. The deny-list sites are listed as must-fix: `NON_APPENDABLE_STATES` in both stores, undo/redo, the admin state reset, the per-agent idle sweep, `TurnIdempotencyService.isReplayable`, and the A2A outcome `switch`, whose `default -> completed` would report an empty finished task.
* **Recommendations:** a new `HUMAN_CONTROL` state rather than reusing `AWAITING_HUMAN`; the reserved action `HANDOFF_TO_HUMAN`, applied at the end of the turn; an opt-in `request_human_agent` tool that is never selected by an empty built-in whitelist; operator endpoints under `/agents/{conversationId}/takeover`. Takeover writes run as coordinator tasks under the conversation lease, which is never held for the length of a takeover. One step per message, with the operator's identity kept out of user-visible output. `operator.*` audit entries with the actor set server-side and message text stored only as a digest (a content commitment, not a copy). Because `AuditLedgerService` writes asynchronously, each takeover write also records its audit entry in a journal inside the conversation document, and a reconciler submits any entry a crash lost. Operator turns go into LLM history annotated as a human's. A dedicated role that never admits the conversation owner and, by default, reaches only the agents whose desk the caller belongs to.
* **Separable first PR:** a property patch alongside a HITL `/resume` decision. It is allow-listed per agent, refuses `longTerm` and `secret` scopes, is audited by digest, and is validated before the resume CAS so a refused patch does not use up the pause.

### Design decisions

* `AWAITING_HUMAN` means "refuse input, then resume the pipeline at a bookmark", and HITL admits the owner. Takeover means "accept input, return to idle", and the owner must be excluded. Reusing the state would take a sub-branch at about 20 sites, and a missed one silently drops customer messages.
* Paths avoid the word "operator", because in the Manager the Operator is the Platform Operator LLM.

### What's next

Maintainer sign-off on the eleven questions in §11 of the design (Q11 confirms the secure default: desk scoping required, unrestricted access only by explicit opt-in), then PR 1 (property patch) and PR 2 (state and API) as laid out in §13.

***

## feat(agent-tests): agent regression harness — golden conversations (2026-10-15)

**Repo:** EDDI (`feat/agent-test-harness`; WS6 Phase 6.1)

### What changed and why

EDDI had thousands of tests and none that asserted what an *agent* does. A config-driven engine records every turn — actions, properties, output, tool calls, cost — so a suite can assert exactly that, independently of how an LLM words its answer.

* **`AgentTestSuite` config resource** (`configs/agenttests`): a versioned document like every other config — scripted cases of turns, per-turn expectations, tool mocks, defaults (`toolMode`, `unmockedTools`, `repetitions`, `passRate`, `turnTimeoutSeconds`) and a per-run dollar ceiling (`maxCostPerRun`, default $1). `AgentTestSuiteValidator` refuses at save time (400) what a run could not honour: unknown modes, invalid or over-long regexes (500 chars), more than 200 cases / 50 turns per case / 20 repetitions / 2,000 turns per run.
* **`AgentTestRun` records** (`engine/agenttests`, collection `agenttestruns`): one document per run through `IResourceStorageFactory` at a single version (the `GroupConversationStore` pattern), so it works on MongoDB and PostgreSQL alike; listed per agent newest-first, pruned to a bounded number per agent.
* **`AgentTestRunner`** runs a suite against an agent version deployed to the `test` environment: one conversation per case repetition as user `agent-test:<runId>:<case>:<repetition>`, each turn through the non-streaming `say` with a per-turn timeout, judged from the stored memory afterwards (`actions`, properties, output text, `audit:tool_calls`, `audit:cost`, state). Repetitions run on virtual threads, at most `eddi.agent-tests.max-parallel-cases` (4) at once; the summed `audit:cost` (start turns included) is checked against `maxCostPerRun` before every turn. A HITL pause is an observable `conversationState`, after which the conversation is ended — the runner never waits for a human. Every test conversation is ended and permanently deleted afterwards (`RestConversationStore.purgeConversation`, the guard-free half of the permanent delete) unless the run keeps them. One summary audit-ledger entry per run (`taskId: ai.labs.agenttest`).
* **`ExpectationEvaluator`**: `actionsContain`, `actionsExact`, `properties` (`equals` — representation-tolerant, `3` = `"3"` — `matches`, `exists`, `absent`), `outputContains`, `outputMatches`, `toolCalled` (+ `argsSubset`), `toolNotCalled`, `maxToolCalls`, `maxCostUsd`, `conversationState`. Every failing expectation is reported with the expected and actual value.
* **ReDoS guard (`BoundedRegex`)**: no safe-regex helper existed. Patterns are capped at 500 characters at save time and matched against a `CharSequence` that throws after 250 ms, so a catastrophically backtracking pattern fails its expectation instead of occupying a thread.
* **Long-term user memory is neither read nor written by test conversations**: `ConversationService.createPropertiesHandler` hands an `agent-test:` user no user-memory store (so `Conversation` skips both the init load and `storePropertiesPermanently`), and the undo/redo long-term sync skips them.
* **`AgentTestService`** (shared by REST and MCP): reading the suite needs VIEW; the version under test is deployed to `test` through `IRestAgentAdministration.deployAgent(test, …, autoDeploy=false, wait)`, so the deploy's own EDIT check, space-reference guard and agent quota apply to the starter; a run is refused (409) when a newer version is also deployed to `test`, because new conversations start on the newest ready version. At most `eddi.agent-tests.max-concurrent-runs` (2) runs execute per node (429 beyond).
* **Tool mocking (`ToolMockRegistry`), fail closed.** Consulted at the three places a pipeline reaches the outside world: `ToolLoopRunner.executeSingleToolCallResult` before executor dispatch (every LLM tool source; the HITL resume path goes through the same method), `ApiCallExecutor.execute` (rule-triggered httpcalls — the mock replaces the `IResponse`, so `saveResponse`, retries and `postResponse` property instructions run on the mocked `{httpCode, body}` unchanged; fire-and-forget calls are not dispatched) and `McpCallsTask` (rule-triggered MCP calls — no server contact at all, not even tool discovery, unless the suite runs live). An unmocked call returns `{"status":"NOT_EXECUTED","reason":"no mock defined in test mode"}` (a 501 for httpcalls) and fails the case; `toolMode: live` / `unmockedTools: live` are explicit opt-ins. A test conversation the registry does not know — a turn still running after its run gave up — is refused too. Memory-writing tools never run live in a test. For every other conversation the hook is one string prefix check on the user id. The LLM-path hook is a self-contained early return directly after the call is traced, so the pending split of that method merges trivially.
* **Tool expectations see all three paths**: the registry records every intercepted call per turn (mocked, refused or live), and `toolCalled` / `toolNotCalled` / `maxToolCalls` are judged against that record rather than the LLM-only `audit:tool_calls` trace.
* **REST.** Suites: `/testsuitestore/testsuites` (URI `eddi://ai.labs.testsuite/testsuitestore/testsuites/{id}?version=N`, the v6 store convention; registered with the workspace access-index backfill). Runs: `POST /agenttests/runs` (202 with the `RUNNING` record), `GET /agenttests/runs/{runId}`, `GET /agenttests/runs?agentId=`. Both `eddi-admin`/`eddi-editor`, the deploy tier.
* **MCP.** `run_agent_tests`, `get_agent_test_run`, `list_agent_test_runs` (`McpAgentTestTools`, AUTHOR tier like `deploy_agent`); tool count 85 → 88.
* **Metrics.** `eddi_agent_tests_runs_total{status}`, `eddi_agent_tests_turns_total`, `eddi_agent_tests_run_duration_seconds`, charted in the Scheduling row of the Full Metrics Reference dashboard.
* **Docs.** New [`agent-testing.md`](https://docs.labs.ai/conversations-and-orchestration/agent-testing.md) (concepts, JSON reference, mocking rules, CI `curl` recipe, EU AI Act evidence note); `mcp-server.md`, `metrics.md`, `configuration-reference.md` (`eddi.agent-tests.*`), `SUMMARY.md`.
* **Full-engine proof:** `AgentTestSuiteIT` (DevServices MongoDB) stores a suite over REST, starts a run against the deterministic rules-only `agentengine` fixture agent — the run deploys it to `test` itself — and reads back `PASSED` for a suite that holds and `FAILED` with the actual actions for one that does not. It found two defects the unit tests could not: MongoDB assigns a run's id only on its first write, and a turn's completion callback can run before the turn is stored, so a turn is now judged from the snapshot `say` completes with (detailed, current step) and only its internal `audit:cost`/model names — stripped from every client projection — are read from the stored step, waiting up to 5 s for it.
* **Platform Operator.** May read suites and runs and start a run (a gated write — it deploys to `test`, like the deploy it already has); it may not write suites. Prompt explains reading results and `unmockedTool`. `operator-revision.json` → 24.

### Review fixes

* **Unchecked purge moved out of the REST layer.** The permanent delete is now `ConversationPurgeService` (memory package); `RestConversationStore` calls `purge` only after its owner check and keeps no unchecked public method. The runner calls `purgeAgentTestConversation(conversationId, runId)`, which refuses any conversation whose user id is not `agent-test:<runId>:…` — the runner can only delete what it created. Nothing in the delete path reads a request identity (tested on an identity-less virtual thread, with a pending approval ended as a system actor).
* **Cluster mode is refused (409).** Mocks and runs live in one JVM and NATS cluster mode can route a test turn to another node. A call refused for want of a session on this node now says so (`no agent-test session on this node …`) instead of `no mock defined`.
* **PR review.** A run whose result cannot be stored (an oversized document, say) is replaced by a terminal `ERROR` record without the per-case detail, never left `RUNNING`; an output expectation's failure records the output cut at 2,000 characters like the turn's own; a suite read goes through the shared `RestVersionInfo.read` (`version=0` = current, null/negative checks); the purge treats the store's `null` for a missing conversation as already gone. A rule-triggered httpcall's mock is selected before the request is built, so a mocked call neither resolves `${vault:}`/`${connection:}`/`${caller:}` references nor fails for an unprovisioned credential.
* **Orphaned runs.** A new `ABORTED` status: at startup, `AgentTestRunRecovery` marks every `RUNNING` run (none can be live yet) aborted with the reason and deletes its test conversations, found by their deterministic user ids.

### Design decisions

* **The test marker is the user id** (`agent-test:` prefix), not a new memory field: the `CONVERSATION_START` turn runs inside `startConversation` before the conversation has an id, and the user id is the one thing every seam (user-memory handler, tool loop, httpcall executor, MCP task) already has. The prefix only ever takes capabilities away, so it need not be unforgeable. `agent-test:` rather than the plan's `test:`, which a real deployment could plausibly use for real users.
* **`ToolMockRegistry` is static**, because the LLM tool loop is plain classes built by `AgentOrchestrator`; threading a CDI bean through would have changed a dozen constructors (and the pending `executeToolCall` split).
* **Runs are not versioned config** and live in their own single-version collection, pruned per agent (`eddi.agent-tests.max-runs-per-agent`, 50).
* **A newer version deployed to `test` refuses the run** instead of being undeployed: the runner never changes a deployment it did not make.
* **Suites are not yet part of agent export ZIPs** (maintainer decision) — follow-up.

### Known gaps and follow-ups

* Phase 6.2: generate a suite from a conversation, LLM-as-judge expectation, Manager page. Phase 6.3: optional deploy gate.
* Suites in agent export/import ZIPs and in agent sync.
* A run lives on the node that started it; if that node stops, the run is marked `ABORTED` at the next startup and must be started again.

**Files:** [`AgentTestSuite.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/agenttests/model/AgentTestSuite.java), [`AgentTestSuiteValidator.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/agenttests/AgentTestSuiteValidator.java), [`AgentTestSuiteStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/agenttests/mongo/AgentTestSuiteStore.java), [`AgentTestRunStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/agenttests/AgentTestRunStore.java), [`AgentTestRunner.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/agenttests/AgentTestRunner.java), [`AgentTestService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/agenttests/AgentTestService.java), [`ExpectationEvaluator.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/agenttests/ExpectationEvaluator.java), [`ConversationService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/ConversationService.java), [`ToolMockRegistry.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/agenttests/ToolMockRegistry.java), [`IRestAgentTestRuns.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/agenttests/IRestAgentTestRuns.java), [`IRestAgentTestSuiteStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/agenttests/IRestAgentTestSuiteStore.java), [`McpAgentTestTools.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/mcp/McpAgentTestTools.java), [`agent-testing.md`](https://docs.labs.ai/conversations-and-orchestration/agent-testing.md)

***

## feat(groups): `member_tool_call` SSE event for group members (2026-10-15)

**Repo:** EDDI (`feat/groups-member-tool-call-events`)

### What changed and why

A group member's turn is not streamed, so an observer saw nothing between `speaker_start` and `speaker_complete`, however long the member's tool loop ran. The 1:1 stream already emits `tool_call` (name only); the group stream now emits `member_tool_call` `{agentId, displayName, tool}` with the same rule: the name travels, the arguments never do.

* `IConversationMemory` gains a name-only `toolCallObserver` (default null), deliberately **separate from the event sink**: a non-null sink switches the LLM task into its streaming path, which a member turn must not trigger. `ToolLoopRunner` notifies it next to the sink (observer failures are swallowed).
* `ConversationResponseHandler.toolCallObserver()` (default null) lets a plain `say` caller supply it; `ConversationService` installs it per turn. `MemberTurnExecutor` supplies one only when a listener exists, and drops events from a cancelled speaker (the callback runs on a coordinator thread).
* `GroupDiscussionEventListener.onMemberToolCall` (default no-op), emitted by `RestGroupConversation`. `SlackGroupDiscussionListener` keeps the no-op: Slack posts finished contributions, and a message per tool call would be noise.
* Manager: the speaking member's typing indicator reads "using X..." instead of "responding..." (i18n in all locales). Docs: SSE table gains `member_tool_call`, `cost_updated`, `stance_updated`, and `token` is marked as never emitted.

### Design decisions

* Observer on memory rather than a new `say` overload: keeps the 9-argument `say` signature (and every existing mock of it) intact.
* Absent observer or listener changes nothing.

***

## ✨ feat(llm): input and output guardrails on LLM tasks (2026-10-15)

**Repo:** EDDI (`feat/llm-input-output-guardrails`) — WS4 Phase 4a, executing the R0 spec of `planning/langchain4j-recommendations.md`.

### What changed and why

Only tool *results* were governed (`ToolResultGuardrail`). Nothing screened the user's message or the model's final answer — the largest governance gap (jailbreaks, PII leaking either way). An LLM task can now carry `inputGuardrails` and `outputGuardrails`: ordered lists of `{type, action, maxRetries, blockMessage, parameters}`. Actions are `block` (default), `redact`, `reprompt` (output: re-ask the same model, `maxRetries` default 2, clamped 0–5, then block) and `warn`. Built-in types: `prompt-injection` (input), `pii-redaction`, `regex-filter`, `max-length` (both), `json-object` (output). Nothing is on by default; a task without the lists never touches the guardrail service.

* **Input** guardrails screen the user's raw message **before retrieval** (a blocked message issues no RAG query or `httpCallRag` call; a redacted one is the retrieval query), then the assembled prompt before the model is built, `preRequest` runs or the circuit breaker is consulted — the second pass reuses the first result when the model-facing message is unchanged, so a finding is recorded once. A block answers the turn with the block message, served as a fallback (`LlmFallbackHandler.serveText`: the step's `llm:fallback:<taskId>` flag keeps it out of later history, `fallbackField` wrapping applies under `convertToObject`); the model is never called. Since the history builder merges a fallback turn's question into the next user message, only the last text part of the last user message is the current turn — earlier parts are screened as history, so a blocked injection cannot block every later turn. Redaction rewrites what the model sees; memory keeps the user's text. Earlier user messages of the history window are re-screened silently every turn, so a message blocked/redacted on its own turn is not replayed to the model later (a guardrail can opt out via `screensHistory()`, meant for model-backed types).
* **Output** guardrails run right after `responseValidation`, in every branch — plain, streaming, tool loop, cascade — and on the HITL resume path. A block is served through the same `serveText` path (flagged, wrapped, not parsed, not recorded as the model's response); the raw output stored under `langchain:<type>:<taskId>` is the wrapped content, as on every other fallback path, while the stream and the visible output carry only the message text. A reprompt runs on the branch that produced the answer: plain chat re-asks the model; the tool loop and a resumed loop re-ask only the final answer over the tool transcript (`reaskFinalAnswer` — no tool runs twice); the cascade re-asks the accepted step. Corrective shape is R5's (`FormatRetryRunner.withCorrective`): request, rejected answer as assistant turn, corrective user message. A reprompt needs `responseValidation.minAttemptMs` of turn time left (#996 deadline) and an admitting per-model circuit breaker (#1001: a fresh ticket per reprompt, settled with its own outcome; the HITL resume neither consults nor settles one, as for R12), else blocks. Reprompt tokens fold into the turn's token usage and cost (cascade: priced with the accepted step's prices into `cascadeCostUsd`).
* **Streaming:** an output guardrail with `block`/`redact`/`reprompt` forces the task onto the buffered path exactly like a `retry` response-validation policy (`bufferOutput = retryPolicy != null || guardrailBuffering` replaces every streaming decision that used `retryPolicy != null`); `warn` keeps streaming.
* **Evidence:** step key `audit:guardrail:<phase>:<type>` (a list of `{phase,type,action,reason,retryCount,taskId}`), collected by `LifecycleManager.buildAuditEntry` into `AuditEntry.output.guardrails` (LLM task only); SSE `guardrail_triggered` `{type,phase,action,taskId}` via `ConversationEventSink` → `StreamingResponseHandler` (both wrappers in `ConversationService`) → `RestAgentEngineStreaming`; counter `eddi.guardrail.triggered{phase,type,action}`.

### Design decisions

* **EDDI-native SPI instead of `dev.langchain4j.guardrail` types.** R0 chose the lc4j types; against langchain4j 1.22.0 (`javap`-verified) `OutputGuardrailRequest` still demands a `ChatExecutor` that a guardrail may call itself — a second model-call path outside the turn's budget, deadline and cost accounting — `GuardrailRequestParams` still NPEs without `userMessageTemplate`/`variables`, results are sealed, and `JsonExtractorOutputGuardrail` no longer exists. Reprompting is EDDI's loop through a `Reprompter` the branch supplies, so the executor would be dead weight or a hazard. `ContentGuardrail` (`type()`, `phases()`, `evaluate(text, context)` → `GuardrailVerdict` ALLOW/REWRITE/VIOLATION) keeps "a new type is just another bean": `GuardrailService` indexes every `@Any Instance<ContentGuardrail>` by type. `GuardrailVerdict.costUsd` and `GuardrailContext.messages` are the hooks Phase 4b's `classifier` type needs.
* **A block is a value, never an exception** (R0 T1): a guardrail message can quote user text and would otherwise reach the tool loop's retry classifier.
* **Fail closed** (Pillar 4, consistent with the 4b classifier): a guardrail that throws or returns no verdict blocks (reason `guardrail_error`) when its action is `block` or `reprompt`, and warns when it is `redact` or `warn`; per-guardrail `parameters.failMode` (`closed`/`open`) overrides. History messages a closed guardrail cannot check are withheld.
* **Find vs act:** guardrails only report; for `pii-redaction`/`regex-filter`/`max-length` a finding with `block` refuses, with `redact` applies the rewrite.
* **No new loop on top of `FormatRetryRunner`:** its triggers are a fixed enum tied to `responseValidation`; reusing its corrective shape, `Asker`, `turnBudget` and `minAttemptMs` keeps the semantics without entangling the two policies.
* **No `ExtensionDescriptor` entries** (R0 1.3 f): the descriptor describes the workflow step's `uri`, not the LLM resource; guardrails live in the resource.
* **Not extracted into `executeModel`** (T11): hooked at the existing seams instead, so the diff in `LlmTask` is additive plus the `retryPolicy != null` → `bufferOutput` substitutions.

### Known limits / follow-ups

* An `httpCallRag` template that reads `memory.current.input` directly (instead of `userInput`) still sees the stored, unredacted text (documented).
* Manager: only the `LlmTask` type mirror (`inputGuardrails`/`outputGuardrails`, `GuardrailConfig`); the guardrail list editor on the LLM task form came with #1077, merged into this branch. Platform Operator cheatsheet explains configuring guardrails; revision bumped.
* Phase 4b (`classifier` type) builds on this branch.
* SSE acceptance criterion 11 (`guardrail_triggered` before `done` over a real socket) is covered at unit level (handler → `sendJson`) only.

**Files:** [`GuardrailService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/guardrails/GuardrailService.java), [`ContentGuardrail.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/guardrails/ContentGuardrail.java), built-ins under [`guardrails/impl/`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/guardrails/impl/README.md), [`LlmTask.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/LlmTask.java), [`LlmConfiguration.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/model/LlmConfiguration.java), [`LifecycleManager.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/lifecycle/internal/LifecycleManager.java), SSE plumbing (`ConversationEventSink`, `IConversationService`, `ConversationService`, `RestAgentEngineStreaming`); docs [`langchain.md`](https://docs.labs.ai/agent-configuration/langchain.md#input-and-output-guardrails), [`security.md`](https://docs.labs.ai/security-and-compliance/security.md), [`audit-ledger.md`](https://docs.labs.ai/security-and-compliance/audit-ledger.md), [`metrics.md`](https://docs.labs.ai/deployment-and-infrastructure/metrics.md), [`rest-api-reference.md`](https://docs.labs.ai/conversations-and-orchestration/rest-api-reference.md).

***

## feat(llm): tool repeat guard refuses identical failing tool calls (2026-10-15)

**Repo:** EDDI (`feat/llm-tool-repeat-guard`)

### What changed and why

Inside the iteration cap a model could re-send the same failing call (a 403, a 404, a schema-rejected body) every round, burning cost and rate-limit budget and repeating side effects on non-idempotent endpoints. The tool loop now keeps a per-run `ToolRepeatGuard`: a call whose last identical call failed, with no other call succeeding since, is answered `NOT_EXECUTED` without running and traced as `tool_repeat_refused` (metric `eddi.tool.repeat.refused`, tags `source`, `reason`). After `maxRefusalsPerTurn` (default 3) refusals the loop stops asking the model and ends the turn with a fixed message.

**Behaviour change: the guard is ON by default.** An agent with no `toolRepeatGuard` now gets it with the defaults (`maxIdenticalFailures` 2, `maxIdenticalCalls` unlimited, `maxRefusalsPerTurn` 3). It only refuses calls that already failed identically with no progress in between. `"toolRepeatGuard": {"enabled": false}` restores the previous behaviour exactly. See [Repeated failing tool calls](https://docs.labs.ai/agent-configuration/langchain.md#repeated-failing-tool-calls).

* `ToolOutcomeClassifier` classifies the RAW tool result (before the provenance envelope): HTTP `httpCode` 2xx success, 408/425/429/5xx retryable, other statuses terminal; `Error:` strings and `{"error":...}` retryable, except rejected arguments and unknown tools (terminal); loop-level refusals (budget, tenant quota, expired deadline, `NOT_EXECUTED`/`DENIED`) never count as failures. MCP `isError` results reach the loop as an internal-error string and are retryable.
* `ToolLoopRunner.executeToolCall` returns governed and raw results; `executeSingleToolCallResult` still returns the governed string (resume path unchanged).
* Guard state is per run of the loop: a HITL resume and each cascade step start fresh. Failures were already never cached.
* Platform Operator prompt updated (revision bumped).

**Files:** [`ToolRepeatGuard.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/ToolRepeatGuard.java), [`ToolOutcomeClassifier.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/ToolOutcomeClassifier.java), [`ToolRepeatGuardConfig.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/model/ToolRepeatGuardConfig.java), [`ToolLoopRunner.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/ToolLoopRunner.java)

**Manager:** the LLM task editor's tool-call limits block has a "Repeated failing tool calls" control (toggle, thresholds, exempt tools); the field is written only when the author changes something.

***

## ✨ feat(observability): W3C trace propagation on outbound calls and execute\_tool spans (2026-10-15)

**Repo:** EDDI (`feat/observability-trace-propagation`)

### What changed and why

A trace used to stop at EDDI's edge: it showed that a turn spent four seconds in the LLM task, but not which MCP server or API made it slow. Two additions close that gap (pillar 6, observability).

* **`execute_tool {tool}` span per tool call** — opened in `ToolExecutionService.executeToolWrapped`, the one seam every tool source passes through (builtin, http, mcp, a2a, dynamic, memory, recall, plus the `mcpcalls` step). GenAI semconv attributes (`gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.tool.call.id`, `eddi.tool.source`, `error.type`), semconv revision pinned via `LlmTelemetryListener.SEMCONV_SCHEMA_VERSION`. The span is *current* while the tool runs — inline, and on the timeout worker through the existing `carryContext` — so outbound requests are its children. Cache hits (`eddi.tool.cache_hit=true`) and rate-limited calls (`error.type=rate_limited`) get a span too: cheap when OTel is off, and exactly what a slow-turn investigation needs to see.
* **W3C `traceparent`/`tracestate` on outbound calls**, via a new `TracePropagation` bean (`W3CTraceContextPropagator` only — never `baggage`): httpcalls (`HttpClientWrapper`, on a copy of the request so the memory record and the HITL approval fingerprint do not change per send), the `OutboundHttp` facade — built-in tools, A2A, the RAG crawler, OAuth, Slack, remote sync (first hop and same-origin hops; dropped on cross-origin hops like credentials — the Vert.x redirect handler drops them too) — and MCP (`params._meta` per SEP-414 through langchain4j's `metaSupplier`, plus the HTTP header).
* **Quarkus' Vert.x HTTP client tracer is off for the httpcalls client** (`TracingPolicy.IGNORE`). With the default policy it re-injected a fresh `traceparent` onto every redirect hop, including a cross-origin one the redirect handler had just stripped. The explicit header still carries the trace; the auto-instrumented client span for httpcalls is what is given up.
* **Config:** `eddi.tracing.propagate-outbound` (default `true`). Inert while `quarkus.otel.sdk.disabled=true` — a no-op span has an invalid context and produces no header, never an all-zero one.

### Design decisions

* **MCP threading.** Verified in the langchain4j-mcp 1.22.0-beta32 bytecode: `DefaultMcpClient` calls the meta supplier synchronously on the calling thread before the transport, but `StreamableHttpMcpTransport` rebuilds the request on an HTTP-client callback thread when it retries after session expiry. So the header supplier reads the trace context **from the message's `_meta`**, not from `Context.current()` — header and `_meta` cannot disagree, whichever thread builds the request.
* **Source and call id travel in the OTel `Context`** (`ToolCallTrace`), set by `ToolLoopRunner` around its one call into the service, rather than as two more parameters: they label the span and nothing else, `ToolInvocation`'s equality is a cost/cache identity, and a new overload would have broken the Mockito stubs of 17 test classes.
* **Merged onto the `OutboundHttp` facade (#1042/#1046).** `SafeHttpClient` was retired on `main` while this branch was open; propagation moved into the facade's `exchange`/`redirectHeaders`, so every caller of the facade gets it and A2A no longer needs its own injection.
* **Tracer:** lazily resolved `GlobalOpenTelemetry.getTracer("eddi.tools")`, same pattern as `LlmTelemetryListener`/`LifecycleManager`; package-private field so tests install an SDK tracer without mutating the JVM-wide global.

### Docs

Monitoring guide: `execute_tool` span, propagation rules, and a "Sending traces to Langfuse / Arize Phoenix / Jaeger / Tempo" section with endpoints verified against each project's docs (Phoenix Cloud left explicitly unverified). Configuration reference row; tracing note in `metrics.md`; Platform Operator prompt line on tracing a slow tool (revision 17 → 18).

**Files:** [`TracePropagation.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/tracing/TracePropagation.java), [`ToolExecutionService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/tools/ToolExecutionService.java), [`ToolCallTrace.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/tools/ToolCallTrace.java), [`OutboundHttp.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/httpclient/outbound/OutboundHttp.java), [`HttpClientWrapper.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/httpclient/impl/HttpClientWrapper.java), [`HttpClientModule.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/httpclient/bootstrap/HttpClientModule.java), [`McpToolProviderManager.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/McpToolProviderManager.java), [`A2AToolProviderManager.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/A2AToolProviderManager.java), [`monitoring-guide.md`](https://docs.labs.ai/deployment-and-infrastructure/monitoring-guide.md).

### Not verified

The acceptance check — one connected trace through the monitoring compose (pipeline task → gen\_ai span → execute\_tool → downstream span) — was not run end-to-end in a live stack; the unit tests pin each link.

***

## 💰 feat(tenancy): enforce the tenant monthly cost budget — meter settled turns and Dream runs, gate model calls (2026-10-15)

**Repo:** EDDI (`feat/tenancy-cost-metering`)

### What changed and why

`maxMonthlyCostUsd` was stored, validated, shown in the Manager quotas page and documented as **not enforced**: `TenantQuotaService.recordCost` had no production caller, so the monthly counter stayed at zero and the pre-call gate never tripped. It is now real.

* **Metering at the settle points.** New [`TurnCostMeter`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/tenancy/TurnCostMeter.java) charges the current step's `audit:cost` to the default tenant from the pipeline's completion callback — `ConversationService.admitTurn` (say, streamed say, rerun; group member turns and sub-agents go through it too), the inline `CONVERSATION_START` turn in `startConversation`, and `ConversationHitlService.resumeConversation` (now always passes a completion callback, also for an internally driven resume). Only the not-yet-metered part is charged: the step keeps `audit:metered_cost`, persisted with the turn, so a turn paused for approval and resumed is charged once in total. Skipped for a turn stopped by lease loss (nothing is stored; the new owner re-runs and meters it); a replayed idempotent turn never reaches the callback. A denied or unavailable `recordCost` never fails the turn — logged and counted on `eddi.tenant.cost.metering{outcome}`; a charge the store could not record is carried forward as `audit:pending_cost` on the newest step and charged by the conversation's next settle (review finding: an ordinary say turn starts a new step, and say turns are persisted as appends, so leaving it on the old step would have lost it).
* **The marker key is `audit:metered_cost`, not `audit:cost:metered`.** Step lookups are prefix matches, so a key starting with `audit:cost` would be read back as the step's cost by `getLatestData(AUDIT_COST)` (`LlmTask.accumulateCost`, `LifecycleManager`).
* **`audit:cost` no longer depends on the audit ledger.** `LlmTask` only wrote it with `eddi.audit.enabled=true`; token usage and cost are now recorded either way (`accumulateUsageAndCost`), since the tenant budget charges them.
* **Pre-model-call gate.** New [`LlmSpendGate`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/LlmSpendGate.java), asked once per LLM task before any model request (plain, tool loop, cascade, streaming). The existing `checkCostBudget` gate ran only before tool calls, so an agent without tools never stopped, and one with tools kept calling its model to be refused tool after tool. A refusal fails soft like the tool-call gate: the model is not called, the task's fallback answer (`responseValidation.fallbackMessage`, or the default sentence) is served regardless of `onError`, the step records `llm:spend_refused:<taskId>`, and `eddi.llm.spend.refused{reason}` counts it. Cheap: with quotas off it is a cache hit; on, one monthly-cost read per LLM task. The circuit breaker ticket is not acquired for a refused call, and the rolling summary is not updated.
* **Dream (A2).** `DreamService` charges each consolidation call at the dream config's own prices (`pricedCost` — never the upper-bound estimate it uses for `maxCostPerRun`, so an unpriced config meters $0) and stops consolidating once the tenant budget is spent (not a failed cycle).
* **Caveats removed.** The WARN in `RestTenantQuota`, the "not enforced" notes in `TenantQuota`, `checkCostBudget` (which also wrongly said `AgentOrchestrator` called it per LLM turn) and `recordCost`, and the note in [`tenant-quotas.md`](https://docs.labs.ai/security-and-compliance/tenant-quotas.md), replaced with an accurate section listing the call classes that are **not** metered: rolling summary, tool-response summarization, group window/stance summaries, embeddings, the pre-pause segment of a tool-call HITL pause, lease-lost turns. The `MemberTurnExecutor` comment calling `AUDIT_COST` a running total is corrected (it is per step).
* **Docs/Operator.** `tenant-quotas.md`, `langchain.md` (prices drive the budget), `metrics.md`, `configuration-reference.md`; the Platform Operator prompt says the cap is enforced and priced-only (operator revision bumped; 20 at merge time).

**Tests:** `TurnCostMeterTest` (delta, pause→persist→resume once, prefix trap, outage retry, exception swallowed, over-budget marked, in-memory end to end), `ConversationServiceCostMeteringTest` (settle point through the real say path, unpriced, idempotent replay, lease loss), `LlmTaskSpendGateTest`, `DreamServiceTest` additions, `ConversationServiceResumeTest` (resume callback meters), `RestTenantQuotaTest` (no "NOT enforced" warning), `LlmTaskAuditLedgerTest` (cost now bypasses the collector gate), `TenantCostMeteringIT` (Mongo + Postgres Testcontainers: two priced turns cross a $0.01 budget and the gate then refuses; and a priced turn that pauses, is persisted to and reloaded from the real conversation store, and resumes with further cost is charged exactly the step total, with `audit:metered_cost` on the persisted step).

### Group cost

`GroupCostLedger` used to read only the member conversation's last step's `audit:cost`; main fixed that independently (#1066, the snapshot now carries the conversation's summed cost). Tenant metering does not go through it either way — member turns settle through `say`.

***

## 💰 feat(llm): per-conversation LLM cost ceiling `maxCostPerConversationUsd` (2026-10-15)

**Repo:** EDDI (`feat/tenancy-cost-metering`)

### What changed and why

A new optional **agent-level** field, `maxCostPerConversationUsd` on [`AgentConfiguration`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/agents/model/AgentConfiguration.java), bounds the priced spend of one conversation — the sum of every step's `audit:cost`. Absent (every existing agent) means unlimited and behaviour is unchanged; `0` allows no priced spend; a negative value is unlimited. The task-level, tool-only `maxBudgetPerConversation` is untouched.

* **Carrier.** `AgentStoreClientLibrary` copies it onto the deployed `Agent`, which puts it on the memory in `startConversation` and in `continueConversation` (every say, rerun and HITL resume passes there, so the running version's value always wins and a version without one clears it). The memory carrier is transient and typed `OptionalDouble`, not a nullable `Double`: a mocked memory hands back `0.0` for a `Double`, which here means "no spend allowed".
* **Checks.** `LlmSpendGate` compares the conversation's spend with the ceiling before the tenant budget, once per LLM task before any model call (plain, streaming, tool loop, cascade); a refusal serves the fallback answer and records `llm:spend_refused:<taskId>` with `reason: conversation_ceiling`. Because that gate only sees a tool loop's cost when the loop ends, `ToolLoopRunner` repeats the check between rounds (prior spend + the loop's tokens at the task's prices + its tool cost) and ends the loop with a fixed answer saying the completed calls took effect. Counted on `eddi.llm.spend.refused{reason="conversation_ceiling"}`.
* **Docs.** [`langchain.md`](https://docs.labs.ai/agent-configuration/langchain.md#per-conversation-llm-cost-ceiling) (new section), `tenant-quotas.md`, `metrics.md`.

**Tests:** `ConversationCostCeilingTest` (old JSON without the field, round trip, carrier set and cleared, spend summed over steps without the metering marker, gate order and edge values), `LlmTaskSpendGateTest` (ceiling refuses without asking the tenant budget; no ceiling sums nothing), `ToolLoopRunnerCostCeilingTest` (stops at the ceiling, prior spend counts, no ceiling unchanged), `AgentStoreClientLibraryMemoryToolsTest` (deployed agent carries the value).

### Not done

No Manager field: the agent editor has no cost/limits section and no nullable-number input, and `turnDeadlineMs` — the nearest agent-level setting — is not editable there either. The value can be set through the agent JSON. Follow-up: a "Limits" section for both.

***

## perf(groups): run the blocking group endpoints on virtual threads (2026-10-15)

**Repo:** EDDI · **Branch:** `feat/group-endpoints-virtual-threads`

### What changed and why

This is the last part of the throughput plan's WS2 (item 5). Six group endpoints run discussion work inline, and each one held a Quarkus worker thread for an entire multi-agent discussion, every member turn and LLM call included:

* `discuss`
* `followUpWithMember`
* `continueDiscussion`
* `approveGroupPhase`
* `submitHumanInput`
* `approveGroupPhaseStreaming`, which calls `resumeDiscussion` on the request thread

The worker pool has about 200 threads and blocking REST endpoints share it, so a handful of long discussions could starve unrelated requests. Conversation turns already left that pool (PR #1045), and the member turns inside a discussion already run on virtual threads.

[`RestGroupConversation`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/RestGroupConversation.java) now marks those six methods `@RunOnVirtualThread`. The other streaming endpoints were already asynchronous and are unchanged: `discussStreaming` goes through `startAndDiscussAsync`, and `continueDiscussionStreaming` uses its own executor.

### Design decisions

* **The annotation is on the implementing methods, not on `IRestGroupConversation`.** The JAX-RS contract stays free of execution-model detail. Whether Quarkus REST honours the annotation there was the open question; `GroupEndpointsVirtualThreadIT` settles it over HTTP.
* **The proof is an IT, not a unit test.** The execution model is chosen when Quarkus dispatches the request, so calling the bean directly cannot observe it. The IT installs a Mockito stand-in for `GroupConversationService` with `QuarkusMock` (Mockito, not a JDK proxy, because `QuarkusMock` needs an instance of the bean class). The stand-in records `Thread.isVirtual()` for each service call and completes the streaming listener.

### Verification

* `GroupEndpointsVirtualThreadIT`: 6 tests, one per endpoint. With every annotation removed, all 6 fail with "a worker thread".
* `GroupConversationIT` and `GroupHitlIT`, which drive real discussions, approvals and human input through these endpoints, pass (12 tests).
* 1,106 group unit tests pass, along with `ImportStyleTest`, `BuildQualityGatesTest` and `ChangelogRotationTest`.

***

## Outbound HTTP callers moved onto the facade; `SafeHttpClient` retired — consolidation phase 2 (2026-10-15)

**Repo:** EDDI · **Branch:** `feat/outbound-http-callers` (stacked on `feat/outbound-http-facade`, labsai/EDDI#1042) · **Plan:** `planning/http-client-consolidation-plan.md`, Phase 2

**What changed**

Every EDDI-owned caller now sends through `OutboundHttp`, with its existing caps, timeouts and redirect rules unchanged:

| Caller                                                                                        | SSRF / redirects                                                                                                                          | Body                                                                                                                                                                                |
| --------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `WeatherTool`, `WebSearchTool`                                                                | `HOPS_ONLY` (fixed hosts), JDK-safe redirects                                                                                             | `bytes(1 MiB / 2 MiB, TRUNCATE)`; a truncated answer is refused as before                                                                                                           |
| `PdfReaderTool`, `WebScraperTool`                                                             | the tool's own URL check, then `HOPS_ONLY`                                                                                                | `bytes(eddi.tools.*, TRUNCATE)`                                                                                                                                                     |
| `AttachmentForwarder`                                                                         | `STRICT`                                                                                                                                  | `bytes(per-file cap, TRUNCATE)`                                                                                                                                                     |
| `SafeHttpPageFetcher` (crawler)                                                               | `STRICT`                                                                                                                                  | `bytes(cap, TRUNCATE)`; its hand-written bounded read and watchdog are gone (identical in the facade), and so is its `IRuntime` dependency                                          |
| `OAuthTokenClient`                                                                            | `NONE` (the credential-endpoint allowlist is the gate), `NEVER`                                                                           | `string(1 MiB, FAIL)`. **New cap**: a token answer was unbounded before; anything over 1 MiB is now a transient `TOKEN_ENDPOINT_UNAVAILABLE`                                        |
| `SlackWebApiClient`                                                                           | `NONE` (fixed host), `NEVER`                                                                                                              | `string(1 MiB, FAIL)`; its private `HttpClient` is gone. **Now bounded in time** — it had no request timeout at all, and gets the facade's 15 s per hop                             |
| `A2AToolProviderManager`                                                                      | `STRICT` or `METADATA_ONLY` per `eddi.security.ssrf-protection.enabled`, `NEVER`                                                          | `bytes(1 MiB, TRUNCATE)`; its lazy private client and its `a2a-body-watchdog` thread are gone                                                                                       |
| `OpenApiSpecFetcher` (MCP/httpcall OpenAPI discovery, added on `main` while this PR was open) | its own redirect loop with `OutboundTargetPolicy` on every hop, each hop one `NEVER` send with `SsrfPolicy.NONE` (the policy is the gate) | `stream(16 MiB, 4 × 30 s)`; its private `openapi-spec-body-watchdog` thread is gone. Its "did not arrive within" message now names the real budget (120 s), not the request timeout |
| `RemoteApiResourceSource` (+ the two static helpers)                                          | new profile `INTERNAL_PEER`: `NONE` (`SourceUrlValidator` stays the gate), `NEVER`                                                        | JSON `string(eddi.backup.sync.max-response-bytes, FAIL)` with the old refusal message; archives `bytes(256 MiB, FAIL)`                                                              |

* **`SafeHttpClient` is deleted** (internal API, no callers left), with `CappedStringBodyHandler` and the per-source client lifecycle (`close()`, `configure()`, the owned-client flag): sources share the application's facade. `BoundedBodyReader` moved into `engine/httpclient/outbound` as package-private.
* `RestImportService` gets the facade by setter injection, lazily falling back to a standalone one outside CDI, as `A2AToolProviderManager` does.
* AGENTS.md (§4.2 table, §4.4 Tool Security and its sample, Key Files), README, `architecture.md` (SSRF layers and sample), `connections.md`, `code-review-standards.md`, `security-review.md`, `a2a-protocol.md`, `configuration-reference.md` and `metrics.md` now name `OutboundHttp`.
* The `// codeql[java/ssrf]` suppressions moved with the sinks: they now sit on the `http.send(...)` calls in `RemoteApiResourceSource` (and its `sendJson` helper).

**Tests**

* The 22 server-backed `SafeHttpClient` tests were ported to `OutboundHttpServerTest` against the facade on the real JDK engine (a no-op `hopValidator` replaces the Mockito spy that let a redirect reach loopback). Their subjects, and a new cross-origin `Authorization` case, are all still covered over real sockets.
* New test helpers in `engine/httpclient/outbound` (test sources): `TestOutbound` (standalone facade, facade over any engine, canned responses), `ScriptedEngine` (records hops, replays answers), and `JdkClientEngine` (routes facade hops into a mocked JDK `HttpClient`). The last one let roughly 200 remote-sync test stubs stay as they were while the code under test runs through the real facade.
* The crawler, OAuth, A2A wiring and new Slack tests run the real facade over a scripted engine rather than mocking it. New: a loopback crawl seed is refused before anything is sent; an A2A peer's 307 and a Slack 302 are never followed; a sync source declaring a body over `eddi.backup.sync.max-response-bytes` is refused before it is read (the old size tests only simulated the refusal in a stub, so lifting the cap broke none of them).
* Mutation-checked: dropping `NEVER` from OAuth, A2A, Slack or remote sync, weakening the crawler to `HOPS_ONLY`, or lifting the remote-sync size cap each fails a test.

**Design decisions**

* `internal-peer` has its own connection pool but no configuration keys yet. Remote sync had nothing tunable, so it uses the `default` settings, and the configuration reference says so.
* Pass-through, not rewrite: every caller keeps its old checks (the tools' own `validateUrl`, A2A's pre-credential check, `SourceUrlValidator`). The facade's policy is added on top.

**Next:** Phase 3, the langchain4j adapter: shared LLM provider pools, plus `llm-provider` keys.

***

## Outbound HTTP facade — Phase 1 of the client consolidation (2026-10-15)

**Repo:** EDDI · **Branch:** `feat/outbound-http-facade` · **Plan:** `planning/http-client-consolidation-plan.md`, Phase 1

**What changed**

* New package `ai.labs.eddi.engine.httpclient.outbound`. `OutboundHttp` is the one place outbound policy lives: the SSRF policy per request (`STRICT`, `HOPS_ONLY`, `METADATA_ONLY`, `NONE`, `FOLLOW_GLOBAL_FLAG`); redirects followed hop by hop with a `MethodRule` (`JDK_SAFE`, the RFC 9110 rule `SafeHttpClient` always used, and `VERTX_COMPAT`, which matches what the `httpcalls` Vert.x client does); cross-origin stripping of the fixed `SENSITIVE_HEADERS` **plus any header the request marks caller-derived** (a `${caller:token}` can sit in any header name); one whole-exchange deadline; redirect bodies dropped after 64 KiB; body caps enforced while reading (`BodyMode.string/bytes/file/stream/discard`, `OnOverflow.TRUNCATE|FAIL`); refusal on a Vert.x event-loop thread; four meters (`eddi.http.outbound.requests|duration|blocked|bytes`) on a new **Outbound HTTP** dashboard row.
* `OutboundEngine` is a one-hop SPI; `JdkOutboundEngine` keeps one `java.net.http` client per `Profile` (`default`, `llm-provider`, `apicalls`, `internal-peer`), with an optional forward proxy (vault-resolvable credentials, answered to proxy challenges only, failing closed when unresolved) and an optional named `quarkus.tls` configuration.
* `SafeHttpClient` is now a `@Deprecated` adapter over the facade. Its API and behaviour are unchanged: all 22 server-backed `SafeHttpClientTest`/`SafeHttpClientBodyBoundsTest` cases pass as they were, apart from one import (`CallerFrames` moved). Its unit tests of moved internals were ported: the method rule to `MethodRuleTest`, the budget and redirect-body discard to `OutboundHttpTest`, and the `withDefaultTimeout` rebuild to a request-conversion test.
* New settings, documented in [configuration-reference.md](https://docs.labs.ai/deployment-and-infrastructure/configuration-reference.md#outbound-http-client): `eddi.http.outbound.engine`, `eddi.http.outbound.default.{connect-timeout,total-timeout,protocol,tls.configuration-name}`, `eddi.http.outbound.proxy.{host,port,non-proxy-hosts,credentials}`. The connect timeout falls back to `httpClient.connectTimeoutInMillis`, so a tuned deployment keeps its value.

**Design decisions**

* Only the `default` profile has keys. The others get theirs in the phase that moves their callers, so no documented setting is a silent no-op in the meantime.
* **`tls.named-groups` was dropped from this phase.** `java.net.http.HttpClient` copies the SSL parameters it is given and discards `namedGroups`: `client.sslParameters().getNamedGroups()` comes back `null`. A key would therefore be a no-op. PQC plan PQ-3 needs another route: an `SSLContext` wrapper that sets groups per engine, the global `jdk.tls.namedGroups`, or the Vert.x engine.
* `max-connections-per-host` was deferred to the Vert.x engine (Phase 4), because the JDK client has no per-host pool limit.
* `OutboundBlockedException` extends `IllegalArgumentException` and `OutboundTimeoutException` extends `HttpTimeoutException`, so every existing `catch` keeps working.
* The plan's table maps `send*` to `NONE`, but what `send` actually did was trust the initial URL and fully validate every redirect hop. That is `SsrfPolicy.HOPS_ONLY`, a policy the plan did not list.
* The event-loop guard was enabled after an audit: the only `Uni`/`@NonBlocking` code in `src/main/java` is `NamelessPrincipalAugmentor`, which makes no outbound call.
* Mutation-checked: removing caller-derived stripping, the `VERTX_COMPAT` RETURN, the redirect-hop check, the FAIL-mode cap probe and the redirect-body cap each fails a test.

**Next:** Phase 2 moves the callers (`OAuthTokenClient`, `SafeHttpPageFetcher`, `AttachmentForwarder`, the tools, `SlackWebApiClient`, `A2AToolProviderManager`, `RemoteApiResourceSource`) onto `OutboundHttp` and retires `SafeHttpClient`.

***

## docs(security): cryptography inventory and post-quantum readiness, guarded by a test (2026-10-15)

**Repo:** EDDI · **Branch:** `feat/pqc-crypto-inventory`

First step (PQ-1) of the post-quantum readiness work. It changes no runtime behaviour.

### What changed and why

* **New page** [**`docs/cryptography.md`**](https://docs.labs.ai/security-and-compliance/cryptography.md) lists every algorithm EDDI uses (vault AES-256-GCM and PBKDF2, the HMAC-SHA256 audit ledger and vault checksums, Ed25519 agent signing, SHA-256 hashing, and TLS), what each one protects, and whether it is post-quantum safe. It also covers the threat model (harvest-now-decrypt-later for TLS, future forgery of Ed25519 signatures) and the roadmap. The page is linked from [`security.md`](https://docs.labs.ai/security-and-compliance/security.md) (TLS section and See Also) and from `SUMMARY.md`.
* **Verified on JDK 25.0.1:** JSSE's default named groups are classical only (`x25519, secp256r1, secp384r1, secp521r1, x448, ffdhe*`), while `ML-DSA-65` and `ML-KEM-768` are available through the standard JCA (an ML-DSA-65 signature is 3309 B and its public key 1974 B). The page states only these verified facts about TLS.
* **New `CryptoInventoryTest`** scans `src/main/java` for the JCA engine `getInstance(...)` calls and `new SecretKeySpec(...)`. It resolves each algorithm from a literal or a same-file `static final String`, and fails the build in four cases:
  * the algorithm is not on its allowlist;
  * the argument cannot be resolved, so moving the string into a variable cannot bypass the check;
  * the call pins a JCA provider;
  * an allowlist entry is no longer used, or is not named in `docs/cryptography.md`.

### Design decisions

* Rather than scan only the per-class constants listed in the plan, the test resolves each call's argument, so a new call site cannot slip through by using an unfamiliar constant name.
* `TrustManagerFactory`, `KeyManagerFactory` and `KeyStore` are left out of the scan: they name PKIX and trust-store formats rather than primitives.
* The allowlist is two-way (unused entries fail as well) so the doc cannot drift from the code.

### Next

PQ-5a: make the existing agent signatures on audit entries versioned and verifiable (see `planning/pqc-readiness-plan.md`).

***

## ✨ feat(rag): live run progress, a knowledge-base inspector and schedule status for ingestion (2026-10-15)

**Repo:** EDDI (`feat/rag-ingestion-ux`)

### What changed and why

Ingestion ran blind: a run row was written as `RUNNING` with zeroes and only got its numbers when it ended, nothing said what a knowledge base actually held, and a source's schedule was a cron string with no word on whether it was armed, firing or failing. The backend now answers all three.

**Run visibility**

* `IIngestionStateStore.reportProgress(run)` writes a running run's counters onto its row, fenced on `status = RUNNING` in both stores, so a late write can neither reopen nor overwrite a finished or reaped run. `IngestionPipeline`'s collector calls it at most every two seconds (forced once at the start, so the trigger is on the row before the first document); a failed write is a stale number, never a failed run.
* `IngestionRun` gains `documentsSkipped`, `stopReason` and `trigger` (`MANUAL` / `SCHEDULED`), with a 13-argument constructor kept for the existing callers. Postgres gains the columns through `ADD COLUMN IF NOT EXISTS`; Mongo needs nothing. The skipped count and stop reason were already in `IngestionReport` and reached only the preview response and the log.
* `RagSourceIngestionService.runAsync` takes the trigger; `processScheduledFire` passes `SCHEDULED`. A run cancelled at shutdown is now closed with the counters its last progress write recorded rather than zeroes.
* `POST …/sources/{sourceId}/run` returns the `runId` it reserved.

**Inspector** — `KnowledgeBaseInspector`, read-only:

* `GET …/sources/{sourceId}/documents` (VIEW) — the source's document states, most recently embedded first, filterable and paged, labelled by file name for uploads; the orphan-sweep marker row is hidden.
* `GET …/sources/{sourceId}/chunks?documentId=` (EDIT) — one document's chunks in document order.
* `POST /ragstore/rags/{id}/search` (EDIT) — a test retrieval with the knowledge base's own `maxResults`/`minScore` as defaults, optionally narrowed to one source.
* The vector stores have no listing, so chunks are reached by a similarity search filtered on the metadata ingestion writes, and always ANDed with `EmbeddingStoreFactory.retrievalFilter` — the inspector sees exactly what retrieval would, and a per-id knowledge base in a shared table sees only its own chunks. A store that cannot filter answers 501; a failing provider or store 502 with the cause.

**Schedules**

* `IScheduleStore.readScheduleByName` (Mongo + Postgres), and `GET …/sources/{sourceId}/schedule` (VIEW) returning next/last fire, fire status, fail count, disable reason and the last five fires.
* `GET /ragstore/rags/cron/preview` applies the save-time checks — parseable, matches a real date, not more frequent than `eddi.schedule.min-interval-seconds` — and returns the next fire times in UTC.

### Design decisions

* **Chunks and search need EDIT, the document list VIEW.** A published knowledge base grants VIEW to everyone; the chunk text is the knowledge base's content and every call costs an embedding.
* **Progress is throttled in the pipeline, not in the store.** One small update per source every two seconds; the interval is an instance field only so a test can make every document report.
* **Search goes through the retrieval isolation filter unconditionally.** An inspector that could see another knowledge base's chunks in a shared table would be a cross-tenant read.

### Tests

`IngestionStateStoreContract` (three new cases, run against Mongo, Postgres and the in-memory double), `IngestionPipelineTest` (trigger + stop reason recorded; counters visible on the running row while it embeds), `RagSourceIngestionServiceTest` (shutdown keeps progress), `KnowledgeBaseInspectorTest` (real `InMemoryEmbeddingStore`: ordering, isolation, source narrowing, min score, file labels), `RestRagIngestionInspectionTest` (access levels, clamping, 400/404/501/502), `RagSourceScheduleViewTest`, and `readScheduleByName` in both schedule store container tests.

**Files:** [`IIngestionStateStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/ingestion/IIngestionStateStore.java), [`IngestionPipeline.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/ingestion/IngestionPipeline.java), [`KnowledgeBaseInspector.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/ingestion/KnowledgeBaseInspector.java), [`RagSourceIngestionService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/ingestion/RagSourceIngestionService.java), [`IRestRagIngestion.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/rag/IRestRagIngestion.java), [`RestRagIngestion.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/rag/rest/RestRagIngestion.java), [`IScheduleStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/schedule/IScheduleStore.java), both state and schedule stores, [`docs/rag.md`](https://docs.labs.ai/agent-configuration/rag.md).

### What's next

The cost controls planned in [`rag-ingestion-source-types-plan.md`](https://github.com/labsai/EDDI/tree/main/planning/rag-ingestion-source-types-plan.md) (§3.13) and run outcome/duration metrics. A cancel button for a running run would need a cancellation signal the worker polls; `isCancelled` is the natural hook.

***

## ✨ feat(manager): see ingestion while and after it runs — progress, run details, schedule, contents, test retrieval (2026-10-15)

**Repo:** EDDI (`feat/rag-ingestion-ux`)

### What changed and why

The knowledge-base editor showed a spinner during a run, "N ingested · M unchanged" after it, a bare cron string for the schedule, and nothing at all about what the knowledge base held. It now uses the endpoints added in the backend entry of the same date.

* **Live progress** (`ingestion-run-history.tsx` → `RunProgress`): documents looked at against what the last complete run saw (or the file count, for a Files source), every counter as it moves, the trigger, and elapsed time against the source's time budget. The run history polls every 2 s while a run is in flight (was 3 s).
* **Run history** opens each run to all it recorded — skipped, failed, removed, chunks, duration, estimated cost and how it ended, the stop reason said in words. A completed run that lost documents gets an amber icon instead of the green tick, and its summary says how many failed.
* **Errors say what the server said.** Run, Preview and Purge failures append the server's message to the generic line ("…A run may already be in flight." was shown for a disabled source and for a database fault alike).
* **Schedule** (`ingestion-schedule.tsx`): a preset picker (hand only, hourly, daily, weekly, monthly — UTC) or a custom cron checked against the server's rules while it is typed, with its next fire times in local time. Once saved, `ScheduleStatus` shows the next run, the last fire, recent fires with their errors, and says in words when a saved cron produced no schedule, when fires are failing, when the scheduler disabled it and when it was dead-lettered. The card header shows the preset's name with the raw cron on hover.
* **Ingested documents** (`ingestion-source-contents.tsx`): the source's documents, filterable and paged, each Live, Missed by the last N runs or Removed; opening one shows its chunks. Collapsed by default — each opened document is an embedding call on the server, so chunks are fetched only on demand, never retried, and kept for five minutes.
* **Test Retrieval** (`retrieval-tester.tsx`): a new editor section that searches the whole knowledge base or one source exactly as an agent would and shows each chunk with its score and origin.
* After a run ends the document list and schedule refetch (`useRefreshAfterRun`), keyed on the newest run's id and status rather than a timer.
* The legacy **Document Ingestion** section now says that pasted documents cannot be listed, updated or removed later, and points to a Files source.
* **Schedules page:** an ingestion schedule links to the knowledge base it is changed on.

### Design decisions

* **No `count` interpolation** in the new strings, so none of them needs per-locale plural categories; the numbers read naturally with neutral wording ("Missed by the last {{runs}} run(s)").
* **The source card observes the files query only while a run is in flight**, for the progress total. Observing it always refetched the list every time a card was opened — caught by the existing "reloads the file list" test.
* The run id `POST …/run` now returns is not used: `ApiClient` discards every 202 body, and the `RUNNING` row in the history identifies the run.

### Tests

`resource-detail-rag-insight.test.tsx` (9 cases: progress estimate and bar, run details and stop reason, server error text, schedule status / missing schedule, live cron check, documents → filter → chunks, retrieval request and result, retrieval failure), one case in `schedules-regressions.test.tsx`; the cron assertion in `resource-detail-rag-sources.test.tsx` now checks the preset label and the raw cron in its title. 87 new keys in all 11 locales; `npm run i18n:check`, `lint` and `typecheck` pass. The five new operations are added to `openapi-operations.json` (refreshed from a Maven-built spec), which the MSW contract test checks every handler against. Checked in the browser against the mock API.

***

## feat(loadtest): turn load-test harness and the throughput baseline (2026-10-15)

**Repo:** EDDI · **Branch:** `feat/throughput-loadtest-harness`

### What changed and why

WS0 of the [throughput plan](https://github.com/labsai/EDDI/tree/main/planning/throughput-optimization-plan.md): every later workstream must show before/after numbers, and until now there was nothing to measure with.

* **`scripts/loadtest/`** (new). A compose stack (MongoDB, a WireMock OpenAI-compatible LLM, EDDI, k6) with everything bound to `127.0.0.1`, plus `loadtest.py`, which uses only the standard library. `up` mounts this checkout's `target/quarkus-app` into the published image, the way `scripts/cluster-demo` does, and creates one deployed LLM agent through `POST /administration/agents/setup`. `run` and `matrix` set the mock's latency through WireMock's admin API, run k6 (scenarios `steady`, `burst`, `same-conversation`, `long-conversation`), sample the saturation gauges every second, and write turns/s, latency percentiles, errors by status, peak executor, coordinator, audit and pool gauges, and MongoDB operations per turn (`opcounters` and `top` per collection).
* **`scripts/loadtest/results/baseline-2026-10-15.md`**. Measured on `aa811c838` at 3 s LLM delay: 50 and 200 concurrent conversations run at the LLM's pace. At 500, throughput flattens at about 61 turns/s with the managed pool pinned at 199 active and up to 198 queued, and p50 rises from 3.1 s to 7.5 s. No request is rejected: overload shows up as latency. Each turn costs about 23 MongoDB operations, independent of load.

### Design decisions

* **One Python driver instead of the plan's `setup.sh` / `collect.sh`.** It matches the cluster demo and runs the same way from PowerShell and Git Bash.
* **No new meter.** The existing executor gauges explain the latency on their own, so the plan's optional `eddi.turn.queue_wait` timer is not added.
* **WireMock with async responses** and no request journal, so the mock is not the bottleneck at hundreds of concurrent delayed calls.

### Next

WS1 (configuration cache): re-measure with `--think-ms 3000`, because back-to-back turns hide the 2 s TTL. WS2 (thread ceiling and admission). Unexplained so far: about 3 vault reads per turn.

***

## perf(runtime): conversation turns on virtual threads, bounded by an in-flight limit (2026-10-15)

**Repo:** EDDI · **Branch:** `feat/throughput-virtual-thread-turns`

### What changed and why

WS2 of the throughput plan. Each in-flight turn held one `ManagedExecutor` platform thread, blocked on the pipeline's future for as long as the LLM took. The pool (\~200 threads), which blocking REST endpoints share, was therefore the node's turn ceiling. Past it, turns queued without bound in front of the pool, and overload showed up as latency for everything rather than as a rejection.

* **Turns run on virtual threads.** `IRuntime.ITurnExecution` is a marker sub-interface of the completion callback. Both coordinators (`AbstractQueuedConversationCoordinator.execute`, and `ClusterConversationCoordinator.runUnderLease`, which `submitNext` also goes through) now pass one, and [`BaseRuntime`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/runtime/BaseRuntime.java) runs those submissions on a dedicated virtual-thread executor (`eddi-turn-*`). The body is unchanged: thread bindings, the nested marker (so the pipeline still goes to the nested executor), the one-shot callback and the abandonment token. Deploys, retention sweeps and the parser endpoint stay on the pool. New gauge series: `eddi_runtime_executor_{active,queued}{pool="turn"}`.
* **Admission control: `eddi.conversation.max-in-flight-turns` (default `1000`).** The C11 `ProcessingTurn` token carries the permit. It is taken with one CAS against a permit counter, so concurrent admissions cannot overshoot, and given back exactly once by `finish()`. Only the turn's own exits call `finish()`: the turn task's `finally`, its discard hook, and the pre-submission rollback. The gauge's existing `release()` still fires as soon as the client has its answer, but persistence runs after that on the same thread, so the permit stays held until then. Releasing it with the gauge let the node run past its limit (1029 active at 1000 in the load test below). The permit is admitted after idempotency admission (a duplicate key answered from the stored result takes no permit) and **before the tenant quota slot**, so a capacity refusal does not spend quota. `startConversation` admits its CONVERSATION\_START turn the same way, because that turn runs inline and can call an LLM. A turn the watchdog abandons while its body keeps running (a swallowed interrupt) keeps its permit until that body really stops: the in-flight registration that already tracks such zombies returns it on `settle()`. A zombie that never ends therefore holds its permit, which `eddi_conversation_abandoned_running` shows. The refusal, `TurnCapacityExceededException`, extends `RejectedExecutionException`, so every surface answers it with the existing 503 `capacity_exceeded` + `Retry-After`. It is counted in `eddi_turn_rejected_total{reason="in_flight_limit"}`.
* **`/v1/chat/completions` runs on a virtual thread** (`@RunOnVirtualThread` instead of `@Blocking`). Both the sync wait and the streaming body held a second worker thread per request next to the turn's own.
* **Monitoring.** `EddiExecutorSaturated` no longer describes turns. The new `EddiTurnCapacityReached` alert fires when turns are refused at the limit for 5 minutes; it has a runbook entry and a promtool case. The full-metrics dashboard's "Coordinator throughput" panel charts the rejection rate. `docs/metrics.md` and the configuration reference cover the new series and property.

### Measured (load-test harness of the WS0 PR, 3 s mock-LLM delay, 10 turns per conversation)

| Concurrent conversations | Before: turns/s · p50 · p95   | After: turns/s · p50 · p95                                |
| ------------------------ | ----------------------------- | --------------------------------------------------------- |
| 200                      | 52–60 · 3.1–3.3 s · 3.5–4.4 s | 60 · 3.1 s · 3.6 s                                        |
| 500                      | 61 · 7.5 s · 9.8–10.1 s       | 131 · 3.3 s · 4.2 s                                       |
| 1000                     | (not run: past the ceiling)   | 269 · 3.2 s · 4.6 s                                       |
| 1500 (limit 1000)        | —                             | 182 · 3.6 s · 5.5 s; 8161 × 503, no timeout, no other 5xx |

Before, at 500 conversations, the managed pool was pinned at 199 active with up to 198 queued. After, it stays at 0: turns peaked at 1029 active on `pool="turn"` with 326 live JVM threads. That build still released the permit with the client's answer. The overshoot past 1000 is the persistence tail that review moved inside the permit, and the numbers were not re-measured after that change. MongoDB operations per successful turn are unchanged (≈ 22.7). A refused turn still costs its conversation loads, because admission sits after them. That is WS3a's single-load work.

### `/v1` answers capacity refusals as 503

Review found that the OpenAI-compatible bridge turned any `RejectedExecutionException` into a 500: the new in-flight limit, coordinator saturation and the shutdown drain alike. That applied to the sync response, the streaming error event and conversation start. It now answers 503 `capacity_exceeded` with `Retry-After: 5`, like every other surface. A quota-store outage gets 503 `quota_accounting_unavailable` (`OpenAiApiException.capacityExceeded`, `OpenAiConversationBridge.rejectionAsApiException`, and a `Retry-After` header from `OpenAiExceptionMapper`).

### `max-in-flight-turns=auto` (the default)

A fixed 1000 fitted only one container size. The Helm chart's 1 GiB limit gives a 512 MB heap at the image's default 50 %, so a busy node would run out of memory long before 1000 turns. `auto` ([`InFlightTurnLimit`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/InFlightTurnLimit.java)) derives the limit from the maximum heap: (max heap − 256 MB) ÷ `eddi.conversation.in-flight-turn-memory-mb` (new, default 2 MB per turn, twice the \~1 MB measured). That gives 128 at 512 MB, \~1400 at 3 GB and \~2900 at 6 GB.

* A number still sets the limit, and `0` still disables it.
* An invalid setting fails the boot (`@PostConstruct`), and the node logs the value it resolved.
* The value is exported as the gauge `eddi_conversation_max_in_flight_turns`, charted next to the in-flight count on the full-metrics dashboard. That panel's legend is now on.

### Sizing the limit

A later comparison run (the load-test harness, MongoDB and PostgreSQL, two rounds each) found that with exactly as many clients as the limit (1000 against 1000), 5–12 % of turns were refused. A turn keeps its place until it is persisted, which happens after its caller already has the answer, so a client's next turn can arrive first. The configuration reference and `application.properties` now say to leave roughly 10–20 % headroom above the expected number of concurrently active conversations. They also give the measured heap per in-flight turn (\~1 MB for short conversations) and PostgreSQL's pool default (50).

### Design decisions

* **A callback marker, not a new `IRuntime` method or a wrapped callable.** About 25 tests mock `IRuntime`, and a new method would return `null` there. The coordinator tests also assert callable identity (`eq(task)`) and `isNull()` bindings, which a wrapper would break. The coordinators already pass a callback; marking it changes nothing else.
* **`max-active-conversations` stays.** It caps how many conversations hold a turn queue and only ever refuses a *new* conversation; the new limit caps turns. Both are documented side by side.
* **Rejections log at DEBUG in `ConversationService`.** `RestAgentEngine` already logs one WARN per 503, and under overload a second line per refused turn only doubles the flood.

### Next

* `RestGroupConversation.discuss` and the other synchronous group endpoints still hold a worker for a whole discussion. Converting them is a JAX-RS-interface change; it is a separate piece.
* WS1 (configuration cache), then WS3a (one conversation load per turn, which also makes refused turns cheap).

***

## 🔒 fix(security): close the M9, M10, L6, L9, L10 and L12 findings of the 2026-10-15 review (2026-10-15)

**Repo:** EDDI (`fix/authz-lifecycle`)

### What changed and why

Six residual findings of the security review of `main` at `d49e855`, each a gap that the live RBAC/IDOR tests did not reach. One commit per finding; the code comments name the finding so a later reader can find this entry.

* **M9 — A2A JSON-RPC skipped the per-agent USE check.** `POST /a2a/agents/{agentId}` required a role, but not the `USE` grant that `POST /agents/{id}/start` and `/v1` apply under enforced workspaces, so any `eddi-user` could converse with any agent. `RestA2AEndpoint.handleJsonRpc` now calls `ResourceAccessGuard.requireAgentUseAccess` before dispatching `SEND` and `STREAM` — outside the method's catch-all, so the refusal is a 403 and not a JSON-RPC "internal error". `tasks/get` and `tasks/cancel` stay principal-scoped: they reach only a task this peer created after passing the gate. `A2aEndpointPermissionsTest` and `RestA2AEndpointTest` cover every send and stream method name in all three dialects.
* **M10 — GDPR erasure and export did not reach the A2A task store.** A peer's tasks hold the message it sent and the reply, keyed by its principal, and outlived an erasure until the cache expired. `IA2ATaskStore` gains `tasksOf` and `eraseForPrincipal` (the length-prefixed key makes a principal's prefix exact), and `A2ATaskGdprParticipant` registers both with `GdprComplianceService` as step `a2aTasks`. It also joins the cascade's stop phase: `beginErasure` closes the store to the principal's writes for five minutes, so a peer request admitted while the cascade runs cannot leave a task behind the sweep; on one node the check and the write are serialised against the sweep by a read/write lock, and in cluster mode the marker lives in a shared `A2A_ERASING` bucket so every node refuses the writes, while a shared per-principal `A2A_INDEX` lets a sweep or export on one node reach the records other nodes wrote (bucket keys are hashed, so nothing else can enumerate them). The index is kept with a compare-and-set loop — `SharedKvCache.replace(key, expected, next)` is now a revision-checked update on the bucket, not get-then-put — and caps a principal at 10,000 tasks: an id that falls off the end takes its record with it. The one narrow cross-node residual is in [`clustering.md`](https://docs.labs.ai/deployment-and-infrastructure/clustering.md#residual-limitations). [`gdpr-compliance.md`](https://docs.labs.ai/security-and-compliance/gdpr-compliance.md) lists it and now has a section naming what erasure does **not** reach — RAG knowledge bases, application log files, telemetry exports and LLM-provider retention — with why, and what bounds each.
* **L6 — dead letters kept the raw turn input for seven days.** `describeTurn` runs before the pipeline, so the `scope: secret` scrub could not help, and only a client that set `context.secretInput` was spared. The captured input and its string context values now pass through `SecretRedactionFilter` — string leaves inside object values included, with credential-named keys masked — an entry the client marked `secret` or whose key names a credential is dropped, and a turn addressed to an agent whose workflows carry any `scope: secret` property instruction is recorded as `secretInput: true` without input or context, like a client-flagged one. The fact is computed once at deployment: `PropertySetterConfiguration.hasSecretInstructions()`, carried by `IExecutableWorkflow` and aggregated on `IAgent`, and read from the agent `say` already resolved for the turn — no second lookup on the hot path. A turn with no resolved agent is treated as one that expects secrets.
* **L9 — three ownership gaps on the internal REST surface.** `RestAgentManagement` never bound the `{userId}` path segment to the caller (its only check asked whether the caller was anonymous), and `initUserConversation` deleted the ended-conversation mapping before the engine's transitive 403; every method now runs `OwnershipValidator.validateUserAccess` first. The group write paths `followUp`, `continue` and `continue/stream` used `requireOwnerOrAdmin`, which admits any authenticated caller to a legacy record with no owner; they use `requireOwnerOrAdminStrict`, as delete and close already did. And an `eddi-approver` could cancel any user's *executing* turn through `POST /agents/{id}/cancel`: a caller who is only an approver now goes through `cancelPausedConversation`, a single compare-and-set on `AWAITING_HUMAN` that never signals an executing turn, so the entitlement check and the cancel are one atomic operation (any other state is a 403; documented in [`hitl.md`](https://docs.labs.ai/conversations-and-orchestration/hitl.md#who-may-decide)); the MCP `cancel_conversation` tool applies the same rule through `HitlAccessGuard.mayCancelExecuting`; owner and admin are unchanged.
* **L10 — unbounded listings and unbounded per-user attachments.** `?limit=2147483647` returned every descriptor in one response (verified live on `/agentstore/agents/descriptors`). `PageBounds` applies one ceiling — `eddi.rest.listing.max-limit`, default 1000, the Manager's largest descriptor page — to every config store's descriptor listing, the cross-resource `/descriptors`, the conversation listing (which used to clamp silently at 100), the visible user memories and both `/administration/logs` listings; a limit above it, or a negative index, is a 400 with a JSON `{"error": …}` body. `eddi.attachments.max-per-user` and `eddi.attachments.max-total-bytes-per-user` default to 500 files and 1 GiB instead of off ([`attachments-guide.md`](https://docs.labs.ai/agent-configuration/attachments-guide.md#quotas)).
* **L12 (remaining) — legacy salt and request logging.** A boot that adopts the legacy fixed KEK salt (DEKs present, no per-deployment salt) records the fact in the vault metadata (`vault-kek-legacy-salt-seen`); every later boot still on it logs an **ERROR** naming `POST /secretstore/secrets/admin/rotate-kek` and the date the salt was first adopted, where before there was one WARN per boot. A persisted or migrated salt clears the record. `logRequests` on the LLM decorators wrote 200 characters of the last message — the user's own text — at INFO; the line is now DEBUG and both it and the `logResponses` line run through `LogRecordRedactor` (before truncation, so a key straddling the cutoff cannot leave its first characters behind), which is public for that.
* **Flaky test fixed at its cause.** `ClusterConversationCoordinatorTest.localDeadLettersPage` failed CI on this branch (and passes or fails locally by chance): the local dead-letter id was drawn outside the lock that appends the entry, so concurrent failures could append out of id order, and the cursor paging over local entries — which skips by id number — then dropped or repeated one. The id is now taken under the lock; `InMemoryConversationCoordinatorTest.concurrentDeadLettersAreRecordedInIdOrder` pins it.

**Files:** [`RestA2AEndpoint.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/a2a/RestA2AEndpoint.java), [`A2ATaskGdprParticipant.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/a2a/A2ATaskGdprParticipant.java), [`CachedA2ATaskStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/a2a/CachedA2ATaskStore.java), [`ConversationService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/ConversationService.java), [`WorkflowStoreClientLibrary.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/runtime/client/workflows/WorkflowStoreClientLibrary.java), [`RestAgentManagement.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/RestAgentManagement.java), [`RestGroupConversation.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/RestGroupConversation.java), [`RestAgentEngine.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/RestAgentEngine.java), [`PageBounds.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/utils/PageBounds.java), [`VaultSaltManager.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/secrets/crypto/VaultSaltManager.java), [`ObservableChatModel.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/ObservableChatModel.java), [`application.properties`](https://github.com/labsai/EDDI/tree/main/src/main/resources/application.properties), [`configuration-reference.md`](https://docs.labs.ai/deployment-and-infrastructure/configuration-reference.md), [`gdpr-compliance.md`](https://docs.labs.ai/security-and-compliance/gdpr-compliance.md), [`hitl.md`](https://docs.labs.ai/conversations-and-orchestration/hitl.md), [`secrets-vault.md`](https://docs.labs.ai/security-and-compliance/secrets-vault.md), [`langchain.md`](https://docs.labs.ai/agent-configuration/langchain.md).

***

## 🔒 fix(security): `?token=` opt-in for the Chat UI, Swagger UI gets its CSP, MCP discovery advertises the request's scheme (2026-10-15)

**Repo:** EDDI (`fix/chat-token-headers`)

Three findings of the 2026-10-15 security review of `main` at `d49e855`, verified live against the packaged 6.6.0 jar: M6, L11 and L3.

### What changed and why

**M6 — the Chat UI took a bearer token from `?token=` unconditionally.** A crafted link signs the widget in as whoever minted the token (login CSRF), and the first request writes the token into the access log before the widget has stripped it from the address bar. It is now an operator opt-in: `eddi.chat.url-token.enabled` (default `false`) reaches the widget as `window.__EDDI_CHAT__` from a new `GET /chat/__config__.js` on `RestHtmlChatResource`, loaded by `chat.html` before the widget — the way the Manager reads `/manage/__auth_config__.js`. Off, `readUrlToken` (new `ui/chat/src/api/chat-config.ts`) ignores the parameter and logs a console warning naming the property; the parameter is stripped from the address bar either way, and only a literal `true` switches it on. The `postMessage` hand-off (`?tokenOrigin=`) and `ChatConfig.authToken` are unchanged. `parseAllowedTokenOrigins` also warns about a plain-`http` `tokenOrigin` that is not loopback: the token the host posts is only as private as that page's transport. The Vite dev proxy forwards the config script so `npm run dev` sees the real value with a backend up.

**L11 — `/q/swagger-ui/` was served with no CSP and no X-Frame-Options.** The `csp-swagger` filter was configured but never ran. Quarkus hands a filter's `order` to Vert.x `Route.order()` unchanged, and Vert.x runs routes in *ascending* order (the Quarkus doc's "higher priority takes precedence" reads the other way); the `/q` sub-router — health, metrics, Swagger UI — is mounted on the same router as a route whose order is its creation sequence number. Live, that number sat between 10 and 20: `/q/health/ready` got `csp-default` (order 10) and `/q/swagger-ui/` got nothing from `csp-swagger` (order 20), because the sub-router had already answered. All three CSP filters now use negative orders (`-30`/`-25`/`-20`), which run before every sequence-ordered route; verified live both ways in dev mode. `CspPolicyTest` pins the orders negative, adds the Swagger paths and the other `/q` routes, and feeds the path tricks through Vert.x's own `HttpUtils.normalizePath` (what the regexes are matched against): `/chat/../manage`, `/%2Fchat`, `/CHAT`, `/chat;x=1/…` keep the strict default policy; `//chat` (folded to `/chat`) and `/chat/..;/manage` (not a dot segment; the chat catch-all serves `chat.html`) get the chat policy and nothing else, so the browser never enforces an intersection.

**L3 — with OIDC on, a plain-http instance advertised `https://localhost:7070/mcp`.** `quarkus.oidc.resource-metadata.force-https-scheme` was pinned `true` for the TLS-terminating-proxy case, so every plain-http deployment with authentication on had to remember to override it, and one that did not handed MCP clients an identifier nothing served. It is now `false`: the scheme follows the request — `http` on a plain-http instance, `https` over TLS, and behind a proxy that forwards it (`quarkus.http.proxy.proxy-address-forwarding`) the public one. A proxy that terminates TLS without forwarding the scheme gets every other absolute URL EDDI builds wrong too; the fix there is the proxy headers or the absolute `quarkus.oidc.resource-metadata.resource`, both already documented. `McpOAuthDiscoveryConfigTest` replaces the pinned-`true` assertion with one that drives quarkus-oidc's own `ResourceMetadataHandler` with the values from `application.properties` and proves an http request yields an http identifier and an https request an https one. The compose auth stacks, the k8s auth overlay and the Manager's Keycloak E2E compose keep their explicit `false` (now the default); only their comments changed. The one shipped stack that relied on the forced `https` was the GCP VM (`gcp/provision-vm.sh`): its nginx terminates TLS and proxies to EDDI over plain http, so its generated compose override now sets `QUARKUS_OIDC_RESOURCE_METADATA_RESOURCE` to the public `https://<domain>/mcp`, the absolute identifier [mcp-server.md](https://docs.labs.ai/protocols-and-integration/mcp-server.md) asks of every production deployment (CodeRabbit, outside-diff finding). [upgrading-from-6.4.md](https://docs.labs.ai/deployment-and-infrastructure/upgrading-from-6.4.md) no longer tells plain-http deployments to set `force-https-scheme=false`.

**Files:** [`application.properties`](https://github.com/labsai/EDDI/tree/main/src/main/resources/application.properties), `src/main/java/ai/labs/eddi/ui/{IRestHtmlChatResource,RestHtmlChatResource}.java`, `ui/chat/chat.html`, `ui/chat/vite.config.ts`, `ui/chat/src/api/chat-config.ts` (new), `ui/chat/src/api/embed-auth.ts`, `ui/chat/src/components/ChatWidget.tsx`, `CspPolicyTest`, `McpOAuthDiscoveryConfigTest`, `RestHtmlChatResourceTest`, the Chat UI tests, [`chat-ui-embedding.md`](https://docs.labs.ai/protocols-and-integration/chat-ui-embedding.md), [`security.md`](https://docs.labs.ai/security-and-compliance/security.md), [`mcp-server.md`](https://docs.labs.ai/protocols-and-integration/mcp-server.md), [`configuration-reference.md`](https://docs.labs.ai/deployment-and-infrastructure/configuration-reference.md), `docker-compose.auth.yml`, `k8s/overlays/auth/kustomization.yaml`, `ui/manager/docker-compose.integration-keycloak.yml`.

### Design decisions

* **A script global, not a fetch.** The widget needs the flag before its first request, synchronously, at mount — a fetched JSON would race the `?token=` read. The Manager already solves this with `/manage/__auth_config__.js`.
* **Strictly `true`.** A missing, malformed or string-valued global reads as off: a bundle served without the backend, or a stale cached script, must not turn the vector back on.
* **Scheme from the request rather than a smarter default.** There is no config signal that distinguishes "plain http" from "TLS terminated upstream without forwarded headers"; the request's scheme is right in every configured deployment and wrong only in the misconfigured one, where it is already wrong everywhere else.

***

## 🔒 fix(deploy): close the CI/CD, Helm, compose and installer findings of the 2026-10-15 security review (2026-10-15)

**Repo:** EDDI (`fix/cicd-deploy-hardening`)

Findings M4, M5, L4 and L7 of the full security review run against `origin/main` d49e855 on 2026-10-15. Config, workflows, manifests, installers and docs only; the one Java change is to the two tests that read those files.

### What changed and why

**M4 — `auto-approve-copilot.yml` stood in for a human reviewer.** `COLLABORATOR` is no longer a trusted author association (only `OWNER` and `MEMBER`): a collaborator is anyone granted repository access, including an outside account invited for one task. `PROTECTED_GLOBS` now also covers the security-critical code — `engine/security/**`, `secrets/**`, `engine/httpclient/**`, `connections/**`, `application.properties` and every `*Guard*.java` — because a change there stays green on every check and can still turn a control off. The workflow header states the assumption it runs under: branch protection on `main` still requires one *human* approval, and the bot only ever satisfies the second of two. That count is a repository setting the workflow cannot read, so [`code-review-standards.md`](https://docs.labs.ai/reference/code-review-standards.md) now says so under *Merge Policy*. `AutoApproveCopilotPolicyTest` moved `application.properties` from its "ordinary" list to the protected one and added the new paths. The review also named `.github/workflows/**`, `helm/**`, `k8s/**`, `docker-compose*.yml` and the installers; those were already covered by `.github/**`, `helm/**`, `k8s/**`, `**/docker-compose*.yml`, `install.sh` and `install.ps1`.

**M5 — Helm put the Keycloak bootstrap admin password in a plain pod env value.** [`keycloak.yaml`](https://github.com/labsai/EDDI/tree/main/helm/eddi/templates/keycloak.yaml) renders it into a `<release>-eddi-keycloak` Secret (key `password`, the kustomize overlay's shape) and the StatefulSet reads it through `secretKeyRef` without `optional`; `required` moved to the Secret, so the chart still ships no default. Every credential the chart renders can now come from a Secret the operator manages: `eddi.existingSecret`, `mongodb.existingSecret`, `postgres.existingSecret` and `keycloak.existingSecret` each skip the chart's own Secret and point the consumer at the named one (the keys each must carry are in [`values.yaml`](https://github.com/labsai/EDDI/tree/main/helm/eddi/values.yaml) and [`kubernetes.md`](https://docs.labs.ai/deployment-and-infrastructure/kubernetes.md#bringing-your-own-secrets-helm)). `mongodb.existingSecret` requires `eddi.existingSecret` alongside, because the chart cannot build EDDI's connection string without the root password — it refuses to render otherwise rather than booting EDDI against a database it cannot authenticate to. The chart also refuses `keycloak.enabled=true` together with `ingress.enabled=true` unless `keycloak.devModeAcknowledged=true`, since the in-chart Keycloak runs `start-dev`. NOTES.txt describes all of it, names the Secret the password landed in, and carries the `start-dev` warning. `DeploymentManifestsTest` asserts the new shape (secretKeyRef, no `value:`, no `optional`, `required` on the Secret). Chart version 2.7.0 → 2.8.0.

**L4 — defaults that were safe only on a laptop.** [`docker-compose.postgres-only.yml`](https://github.com/labsai/EDDI/tree/main/docker-compose.postgres-only.yml) requires `POSTGRES_PASSWORD` (it hard-coded `eddi`/`eddi`); [`docker-compose.cluster.yml`](https://github.com/labsai/EDDI/tree/main/docker-compose.cluster.yml) requires `MONGO_PASSWORD` the way it already required `NATS_PASSWORD` (it defaulted to `changeme`). Both installers generate `POSTGRES_PASSWORD` into `.env` for `--db=postgres` and carry a stored value forward, like the Keycloak password, because the postgres image reads it at initdb only. [`docker-compose.yml`](https://github.com/labsai/EDDI/tree/main/docker-compose.yml) keeps its laptop defaults but gains a one-shot `bind-guard` service that `eddi` depends on: it exits 1 when `EDDI_BIND` is not loopback while `EDDI_SECURITY_ALLOW_UNAUTHENTICATED` is `true`, unless `EDDI_I_UNDERSTAND_PUBLIC=true`. It runs on the `mongo` image the stack pulls anyway, so it costs no extra image and works offline and with the local build overlay; `install.sh` performs the same check before pulling images, and the GCP provisioner passes the acknowledgement for `--i-understand-public`. Documented in [`docker.md`](https://docs.labs.ai/deployment-and-infrastructure/docker.md#publishing-eddi-on-the-network). `k8s/quickstart.yaml` carries the same loud banner the vault key has. **Its three `*_ALLOW_UNAUTHENTICATED` flags stay `"true"`, deliberately:** the review asked for the MCP and secret-store opt-outs to be `false` "like Helm does", but with OIDC off `HighValueSurfaceGuard` refuses to boot unless both are opted in — Helm renders `false` *and then refuses to render that release*. `false` in the quickstart is not a safer manifest, it is a CrashLoopBackOff; the banner says so and tells the reader that turning OIDC on is the only way to close them.

**L7 — CI and docs.** In [`ci.yml`](https://github.com/labsai/EDDI/tree/main/.github/workflows/ci.yml) the `:latest` Docker alias and the GitHub release's `make_latest` follow `is-stable`, and a pre-release tag is published with `prerelease: true`; a `6.4.0-RC1` tag used to move both. [`base-image-check.yml`](https://github.com/labsai/EDDI/tree/main/.github/workflows/base-image-check.yml) opens its PR with `BASE_IMAGE_BOT_TOKEN || CHANGELOG_BOT_TOKEN || GITHUB_TOKEN` and carries the sibling workflows' PR-body note, because a PR opened with the default token never runs `Build & Test` — the one check a base-image bump needs. [`httpcalls.md`](https://docs.labs.ai/agent-configuration/httpcalls.md#running-behind-a-reverse-proxy) adds `quarkus.http.proxy.trusted-proxies` to the proxy guidance: without it every peer may send forwarded headers, which is the origin check `${caller:token}` relies on. With an Ingress and OIDC on, the chart defaults `QUARKUS_OIDC_RESOURCE_METADATA_RESOURCE` to `<scheme>://<ingress.hosts[0].host>/mcp` instead of trusting each request's `Host`. Setting `keycloak.publicOrigin` strips the `http(s)://localhost:*` redirect URIs and the `+` wildcard web origin from the realm's `eddi-frontend` client (the realm is parsed and re-serialised rather than string-edited; the `eddi-mcp` client keeps its loopback redirects). `install.ps1`'s `Protect-SensitiveFile` fails with the `icacls` fix instead of warning when the `.env` ACL cannot be set. `SECURITY.md`'s cosign regex uses the strict tag pattern CI and `release-signing.md` use.

### Verification

`helm lint` and `helm template` (dockerised `alpine/helm:3.17.3`, helm is not on PATH here) for the default, the CI shape with PostgreSQL and Keycloak, Keycloak behind an Ingress with and without the acknowledgement, every `existingSecret` combination and the `mongodb.existingSecret`-alone refusal; `docker compose config` for every edited compose file plus the auth and local overlays, and the bind guard run under each environment combination; `python -c "import yaml"` over every edited workflow and manifest; `bash -n` on the shell installers and a parser check on `install.ps1`; the deploy and docs unit tests via `./mvnw test`.

***

## test(coordinator): deterministic regression test for local dead-letter cursor paging (2026-10-15)

**Repo:** EDDI · **Branch:** `fix/dead-letter-cursor-paging`

### What changed and why

* **Background.** `ClusterConversationCoordinatorTest.localDeadLettersPage` failed CI twice on #1046 (`only the entry after the cursor: [] ==> expected: <1> but was: <0>`). The cause was in production: `recordLocalDeadLetter` took the local id before entering `deadLetterLock` but appended inside it, so two concurrent failures could land in the ring out of id order (`local-2` ahead of `local-1`). The cluster cursor skips local entries by number, so a page ending on `local-2` silently dropped `local-1` from the next page. The fix — taking the id under the lock — landed on `main` in #1040 (`fix(coordinator): record local dead letters in id order`) while this branch was open; this branch carried the same fix and now contributes only the test.
* **Why another test.** #1040's `InMemoryConversationCoordinatorTest.concurrentDeadLettersAreRecordedInIdOrder` races eight writers and checks ring order, so it catches a regression only when the scheduler happens to interleave them, and it never pages. `ClusterConversationCoordinatorTest.concurrentLocalDeadLettersPageInIdOrder` forces the interleaving with latches — one failure is held inside `describe()` while a second one is recorded to completion — and then pages one entry at a time through `getDeadLetters(limit, after)`, the path operators use. Mutation-checked: with the id taken outside the lock it fails every run with the CI message (ring `[local-2, local-1]`).

***

## fix(ci): unblock main — shaded jsoup CVE in jinjava, gitleaks false positives, a time-of-day schedules test flake (2026-10-15)

**Repo:** EDDI · **Branch:** `fix/main-ci-jsoup-gitleaks`

### What failed

* **Docker Build & Push** on main (`f3d0fa596`, `37f8292fd`): the Trivy image scan reported one HIGH, CVE-2026-75140 (GHSA-65r4-943x-97jj, quadratic memory in jsoup's `XmlTreeBuilder`, fixed in 1.23.2) in `org.jsoup:jsoup` 1.15.3 inside `com.hubspot.jinjava.jinjava-2.8.4.jar`.
* **Secret Scanning** on main (`775edae28`, the squash of PR #956): gitleaks 8.30.1 reported three `generic-api-key` findings.
* **UI Manager Checks** on main (`775edae28`): `schedules.test.tsx` "shows schedule names from mock data" threw "Found multiple elements" for `Daily Health Check`.

### What changed and why

* **`.trivyignore`** — the jsoup copy is *shaded*: jinjava's `maven-shade-plugin` bundles jsoup 1.15.3 into its own jar and relocates it to `jinjava.org.jsoup`, so a managed `org.jsoup:jsoup` version cannot replace it, and 2.8.4 is still the newest jinjava on Maven Central. jinjava is on the classpath only because `jlama-core` renders model chat templates with it, so it cannot be excluded without breaking the `jlama` provider. The vulnerable code is not reachable: jinjava's only jsoup users are the `closehtml`, `striptags` and `truncatehtml` filters, which use the HTML parser, and no jinjava or jlama class references the XML parser. EDDI's own direct jsoup is already 1.23.2. The entry carries `exp:2027-01-15` so it lapses and forces a re-check rather than silently outliving a jinjava fix.
* **`.gitleaksignore`** — the three findings are rows of the Manager's MSW cluster mock (`ui/manager/src/test/mocks/cluster-handlers.ts`, lines 83–85), whose `key` field is a NATS KV lease key made of `c.` and a made-up conversation id. Fingerprints for the squash commit `775edae28` were taken from a local run of gitleaks 8.30.1 (checksum verified against the release) over `37f8292fd..775edae28`, the range main's push scan checked. The `scripts/cluster-demo/demo.py` demo values were not flagged.
* **`ui/manager/src/pages/__tests__/schedules.test.tsx`** — a time-of-day flake, not a regression. The MSW mock gives Heartbeat Monitor `nextFire = now + 30 min` and Daily Health Check the next weekday 09:00 UTC, so from 08:30 to 09:00 UTC on a weekday Daily Health Check is the soonest schedule and its name renders a second time, in the Next Fire card. The test now uses `findAllByText`, like the Heartbeat Monitor line below it already did. The other tests naming either schedule were already safe (`schedules-features.test.tsx:171` reads an input inside the edit dialog; the Next Fire card test matches either name).

### Verification

* Trivy 0.70.0 (the version the pinned `trivy-action` installs) over the jinjava jar: 1 HIGH without the entry, exit 0 with it.
* gitleaks 8.30.1 over `37f8292fd..775edae28`: 3 leaks before, none after.
* `schedules.test.tsx` with the clock faked to a Wednesday 08:45 UTC: the old assertion fails with "Found multiple elements", the new one passes (50/50); it also failed unfaked at 08:57 UTC on the day of the fix, and both schedules test files pass with the fix (65/65). `npm run typecheck` and `npm run lint` are clean.

### Decision

The `.trivyignore` entry is the last resort, taken because there is no fixed jinjava, no override can reach a relocated copy, and dropping jinjava would remove the `jlama` provider. Remove the entry when a jinjava release shades jsoup >= 1.23.2.

**Node-local dead letters kept in id order.** `ClusterConversationCoordinatorTest.localDeadLettersPage` failed once in CI on this branch, and the cause was real. `AbstractQueuedConversationCoordinator.recordLocalDeadLetter` numbered an entry before taking the ring's lock. Two conversations failing at once could therefore add `local-3` before `local-2`, and the cluster coordinator's paging, which skips every local entry numbered at or below the cursor, then dropped `local-2` from the next page. The number is now taken inside the lock. `InMemoryConversationCoordinatorTest.localDeadLettersAreHeldInIdOrderUnderConcurrentFailures` forces that interleaving and fails without the fix.

***

## 🔒 fix(mcp): govern remote tool schemas, pin the MCP transport to no redirects, enforce tool budgets by default, give the HITL MCP tools a role tier, widen the self-ungating guard (2026-10-15)

**Repo:** EDDI (`fix/mcp-governance`)

Findings M7, M2 (MCP transport), M8, L5 and L13 of the 2026-10-15 security review.

### What changed and why

**M7 — remote tool parameter schemas were not governed.** `McpToolProviderManager.governDescription` redacted and capped a remote tool's *description* and rebuilt the spec with `parameters(spec.parameters())` verbatim, so every property description, title and enum value in the server's `inputSchema` reached the model unredacted and unbounded; `A2AToolProviderManager` had the same shape. New `modules/llm/governance/ToolSchemaGovernor` walks a langchain4j `JsonSchemaElement` tree — objects, arrays, enums, `anyOf`, `$defs`, raw JSON-Schema fragments — and governs every text with `RemoteTextGovernor`, bounds the serialised schema per tool (`eddi.mcp.tool-schema.max-bytes`, default 32 KB: descriptions are stripped first, a schema still over the cap drops its tool) and per server (`eddi.mcp.tool-schema.max-bytes-per-server`, default 512 KB), refuses nesting deeper than 32 levels, and reports `redacted` / `truncated` / `dropped` / `dropped_server_cap` in `eddi_mcp_tool_schema_governed_total`. The A2A manager applies the same walk with `eddi.a2a.tool-schema.max-bytes` / `…-per-agent` and `eddi_a2a_tool_schema_governed_total` — its schema is built locally today, so this is symmetry rather than a live hole, but a card-sourced `inputSchema` is now governed from day one.

**M2 (MCP part) — a 3xx from a validated MCP URL could be followed.** Only the configured URL was validated and langchain4j's `StreamableHttpMcpTransport` built its `HttpClient` with `Redirect.NORMAL` in earlier releases, so a `307 Location: http://10.0.0.5/…` carried the session and every tool call's `Authorization` header to a host nobody checked. The transport is now built with `followRedirects(false)` explicitly — langchain4j-mcp 1.22 happens to default to that, but the builder flag exists precisely so the caller decides, and `McpTransportRedirectTest` holds the line against an embedded redirecting server on the loopback interface: the handshake fails on the 307 and the `Location` is never requested. `docs/security.md`'s SSRF note no longer says the MCP client follows redirects while protection is off.

**M8 — tool cost ceilings were recorded, not enforced.** `maxBudgetPerConversation` only refused calls with `enforceBudget: true`, and the deployment-wide `eddi.tools.budget.enforce-by-default` was never declared in `application.properties`, so every stored ceiling was advisory. The reason for the opt-in — built-in tools priced at $0.00 until their pricing was repaired, so a default-on gate would have bound for the first time on upgrade — has passed. The key is now declared with `true`, `AgentOrchestrator.BUDGET_ENFORCE_DEFAULT` falls back to `true`, `warnAboutUnenforcedBudgets` names the *opt-out* (`"enforceBudget": false` on the task, or the deployment key set to `false`) once per task instead of the absence of an opt-in, and the MCP `get_agent` and `deploy_agent` outputs carry `toolBudgetEnforcedByDefault` so an operator reading a stored ceiling sees whether it refuses. `AgentOrchestratorToolCostTest` and `AgentOrchestratorCoverageTest` now pin the opt-out contract (an unflagged ceiling refuses the third call; an opted-out one is warned about; an enforced one is silent). Note: `docs/llm-parameters.md` is generated from `model-parameters.json` and carries provider parameters only, so the budget text lives in `langchain.md`, `security.md` and `configuration-reference.md`.

**L5 — the MCP HITL tools had no role tier.** `McpHitlTools` relied on `HitlAccessGuard` alone, so over MCP an `eddi-viewer` — a role every REST HITL endpoint refuses at `@RolesAllowed` — could decide its own gated tool calls. New `McpRoles.HITL` (`eddi-admin`, `eddi-editor`, `eddi-user`, `eddi-approver`) is checked first on all ten tools, mutations and reads alike; the per-conversation guard still runs after it. `McpRoleTierParityTest` now measures the HITL tools against that tier (the no-role caller passes nothing any more, `eddi-viewer` is refused by every HITL tool) and asserts the tier equals the method-level `@RolesAllowed` of the nine REST HITL endpoints on `IRestAgentEngine` and `IRestGroupConversation`; `McpHitlToolsTest` adds the viewer refusal and the auth-off no-op.

**L13 — the self-ungating guard knew only the agent id; the pagination store was process-global.** `SelfUngatingGuard` now takes a `Protection` (acting agent, the ids of its workflows and of every extension resource those workflows reference, whether that resolution failed, and a stored-gate lookup). New `modules/llm/impl/ActingAgentResources` resolves the ids from the agent and workflow stores once per resumed batch in `ToolLoopResumer`; a write to any of them is refused (`OWN_RESOURCE_REASON`), and if the stores cannot be read every configuration-store write in the batch is refused (`UNRESOLVED_RESOURCES_REASON`) rather than guessed at. Agent-store writes to *other* agents are compared against the stored `hitlConfig.toolApprovals`: a full `PUT` that drops, loosens or adds it, and a `PATCH` naming `hitlConfig` or `toolApprovals`, are refused (`GATE_REMOVAL_REASON`); a faithful copy runs; without a lookup a body touching either key is refused. `ApprovedCallScope` carries the `Protection` on its thread-local, so the rule applies to the request as finally sent. Both id patterns accept a 24-hex ObjectId and a canonical UUID, so PostgreSQL deployments are covered, and a parser step's `extensions.dictionaries[]`/`corrections[]` resource URIs are protected like `config.uri`. Review also added to `approve_group_phase` the group USE gate REST's approve endpoint has (`requireResumeUseAccess`: admins and approvers decide by role, an owner whose group access was revoked cannot resume the run). `PaginatedResponseStore` is keyed by `(conversationId, responseId)`; `FetchToolResponsePageTool` is handed to each turn `boundTo` its conversation by `BuiltinToolsProvider` (the unbound catalog bean refuses every fetch), and `ToolResponseTruncator.truncateIfNeeded` takes the conversation — without one, `paginate` falls back to truncation and stores nothing.

### Files

* `modules/llm/governance/ToolSchemaGovernor.java` (new), `McpToolProviderManager.java`, `A2AToolProviderManager.java` — M7
* `McpToolProviderManager.java` (`createTransport`), `McpTransportRedirectTest.java` (new) — M2
* `AgentOrchestrator.java`, `ToolLoopRunner.java`, `LlmConfiguration.java`, `ToolBudgetEnforcement.java` (new), `McpConversationTools.java`, `McpAdminTools.java`, `application.properties` — M8
* `McpRoles.java`, `McpHitlTools.java`, `McpRoleTierParityTest.java`, `McpHitlToolsTest.java`, `McpHitlToolsCoverageTest.java` — L5
* `engine/hitl/tools/SelfUngatingGuard.java`, `ApprovedCallScope.java`, `modules/llm/impl/ActingAgentResources.java` (new), `ToolLoopResumer.java`, `AgentOrchestrator.java`, `PaginatedResponseStore.java`, `FetchToolResponsePageTool.java`, `BuiltinToolsProvider.java`, `ToolResponseTruncator.java` — L13
* Docs: `configuration-reference.md`, `mcp-client.md`, `metrics.md`, `security.md`, `langchain.md`, `mcp-server.md`, `hitl.md`, `clustering.md`

### Design decisions

* A schema over the byte cap loses its descriptions before its tool is dropped: the prose is the untrusted bulk, the structure is what the model needs to call the tool at all, and a partial structure would make it call with the wrong arguments.
* `followRedirects(false)` is pinned in EDDI rather than trusted to the library default, which changed between langchain4j releases.
* Budget enforcement is an opt-out named in a WARN, not an opt-in named in a WARN: a ceiling someone wrote down should refuse unless someone else says otherwise.
* The HITL role tier is checked before the per-conversation guard so a role refusal is a role error, as on every other MCP tool, and the mocked guard in the unit tests is never consulted for a viewer.
* A resolution failure in `ActingAgentResources` fails closed for configuration-store writes only, so an approved call to an external API still runs when the config stores are briefly unavailable.

***

## 🔒 fix(security): bound the expression parser, dictionary regexes and template string ops; refuse `saveResponse` without a name (2026-10-15)

**Repo:** EDDI (`fix/parser-bounds`) — findings M3, L8 and L2 of the 2026-10-15 security review

### What changed and why

**M3 — the expression parser was unbounded and reachable by any chatting user.** `ExpressionProvider` recursed once per nesting level with no cap and copied the remainder of the string at every level. A `context` entry of type `expressions` reaches it through `PropertySetterTask` and every `contextmatcher` rule; verified live, 20,000 nested parentheses threw a `StackOverflowError` that escaped `LifecycleManager`'s task-failure accounting, and a 3 MB payload cost \~10 s of CPU per request.

* New [`ExpressionLimits`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/nlp/expressions/utilities/ExpressionLimits.java) bean: `eddi.expressions.max-length` (default 32,768 characters) and `eddi.expressions.max-depth` (default 32), checked in one linear scan before parsing; `0` disables a bound. Exceeding one throws `ExpressionLimitExceededException` (an `IllegalArgumentException`) with the measured value and the bound.
* [`ExpressionProvider`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/nlp/expressions/utilities/ExpressionProvider.java) now parses on index ranges of the one input string — no per-level `substring` — and re-checks the depth where it descends, so no entry point bypasses the scan. The grammar is unchanged, quirks included (`ExpressionProviderBoundsTest` pins them). The limit exception is explicitly not swallowed by the parser's own error logging.
* REST boundary: `ConversationService.requireInputWithinLimit` — the gate every conversationId entry point, A2A and the OpenAI adapter already run — now also checks `context` entries of type `expressions` and refuses them with the existing `413 input_too_large` (`InputTooLargeException` gained a message constructor), so every adapter answers it without new plumbing. Inside a turn the exception is a task failure.
* [`LifecycleManager`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/lifecycle/internal/LifecycleManager.java) catches `StackOverflowError` alongside `RuntimeException`, wraps it in an `IllegalStateException` and runs the unchanged failure accounting: error counter (`error.type=stack_overflow`), SSE `task_failed`, audit entry, strict-write rollback, `taskErrors` to the caller.

**L8 — editor-authored CPU cost.**

* Dictionary regexes: [`RegEx.match`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/nlp/model/RegEx.java) runs through a deadline-checking `CharSequence` (new [`RegexDeadline`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/utils/RegexDeadline.java), the pattern `ArtifactValidators` already used) with a 200 ms budget that `RegularDictionary.lookupTerm` shares across all the patterns of one lookup (`IRegEx.match(lookup, deadlineNanos)`), so N slow patterns cost one budget per token, not N; a timed-out match is a miss, logged at WARN. With the parser's `maxInputTokens` (default 200) that bounds a turn's dictionary matching at 200 × 200 ms in the pathological worst case. [`RestDictionaryStore`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/dictionary/rest/RestDictionaryStore.java) compiles every `regEx` on create, update, patch and duplicate and refuses an invalid one — or an entry with no `regEx` at all, which the provider used to drop silently — with `400` naming the problem, instead of failing the agent's deployment later.
* Template string ops: `str.replace` and `str.concat` in [`StringTemplateExtensions`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/templating/impl/extensions/StringTemplateExtensions.java) compute the size they would produce and refuse it against `eddi.templating.max-output-chars` *before* allocating (for `replace`, whenever the replacement grows or the source is already over the bound) (new [`TemplateOutputLimit`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/templating/impl/extensions/TemplateOutputLimit.java), a process-wide value the production `TemplatingEngine` publishes, since Qute invokes extensions statically). `TemplatingEngine.processTemplate` catches `OutOfMemoryError` with the exceptions and reports it — and a `TemplateLimitExceededException` anywhere in the cause chain — as a `TemplateEngineException` naming the bound.
* [`PathNavigator.evaluateExpression`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/utils/PathNavigator.java) caps an expression at 64 `+`/`-` operands (`MAX_OPERANDS`); `tokenize` stops at the cap rather than materialising every operand first, and the expression resolves to nothing. The vendored copy under `.clusterfuzzlite/` is synced. The longest-prefix search is quadratic in the operand count.

**L2 — `saveResponse: true` without `responseObjectName` was accepted and then failed every turn** with "Null key for a Map not allowed in JSON", leaving the conversation in ERROR. New [`ApiCallsConfigurationValidator`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/apicalls/ApiCallsConfigurationValidator.java) refuses it at save time (`400`, naming the call); it is wired with one call from `RestApiCallsStore.validateBatchLimits`, which create, update, patch and duplicate all run. `ApiCallExecutor` derives one `saveResponse` flag per call that is `false` when the name is missing (logged once per call at WARN), so a config stored before the check skips the save instead of failing the turn.

### Design decisions

* **413, not 400, for an over-long or over-deep `expressions` context.** It is the same class of refusal as a too-long input and the same exception, so the seven entry points that already map `InputTooLargeException` answer it with no new plumbing. The message names the bound and the property.
* **The expression bounds are deployment properties, not agent config**: they are a safety floor against a client, not agent behaviour.
* **The regex budget and the operand cap are constants**, documented in [security.md](https://docs.labs.ai/security-and-compliance/security.md#parser-and-matcher-bounds): nothing a dictionary legitimately matches takes 200 ms, and nobody writes 64 operands by hand.
* **The template pre-check is process-wide.** Qute calls extension methods statically, so the bound cannot travel with the engine instance; the production constructor publishes its configured value, tests get the shipped default. `BoundedResolvers.check` still enforces the per-engine value afterwards.

### Tests

`ExpressionProviderBoundsTest` (live payloads, both bounds at their boundary, every entry point, grammar parity), `LifecycleManagerStackOverflowTest`, `ConversationServiceTest` (expressions context), `RegExTest`, `RestDictionaryStoreRegExValidationTest`, `StringTemplateExtensionsOutputLimitTest`, `TemplatingEngineOutOfMemoryTest`, `PathNavigatorOperandCapTest`, `ApiCallsConfigurationValidatorTest`, `RestApiCallsStoreSaveResponseTest`, `ApiCallExecutorSaveResponseGuardTest`. Each bound was mutation-checked: with the fix reverted, its test fails. The one exception is the `OutOfMemoryError` catch clause itself: Qute hands the Error over wrapped in an exception, so the clause cannot be exercised from a unit test; the reporting it feeds is.

**Docs:** [configuration-reference.md](https://docs.labs.ai/deployment-and-infrastructure/configuration-reference.md) (two new properties), [security.md](https://docs.labs.ai/security-and-compliance/security.md#parser-and-matcher-bounds), [rest-api-reference.md](https://docs.labs.ai/conversations-and-orchestration/rest-api-reference.md), [httpcalls.md](https://docs.labs.ai/agent-configuration/httpcalls.md).

***

## 🔒 fix(security): `eddi.security.ssrf-protection.enabled` now covers LLM, embedding, vector-store and OpenAPI-discovery targets (2026-10-15)

**Repo:** EDDI (`fix/ssrf-coverage`; backend, docs)

Finding M2 of the 2026-10-15 security review.

### What changed and why

The SSRF switch governed httpcalls, MCP and A2A targets only. Every other endpoint an editor can write into a config — an LLM `baseUrl`, an Azure `endpoint`, an embedding endpoint, a pgvector `host`, a MongoDB `connectionString`, an OpenAPI spec location — was checked against the cloud instance-metadata service alone, protection on or off. With the switch on, an editor who could save an LLM config could still point it at any internal host; a knowledge base could open a raw connection to any host:port, EDDI's own MongoDB or PostgreSQL included, and pgvector would `CREATE TABLE` there. And `POST /apicallstore/apicalls/discover-endpoints` fetched the spec through swagger-parser's `RemoteUrl`, which follows up to five redirects with no check on where they lead.

* **One policy, `OutboundTargetPolicy`** ([`engine/httpclient/OutboundTargetPolicy.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/httpclient/OutboundTargetPolicy.java)): the metadata service is refused always, as before; with the switch on, `UrlValidationUtils.validateUrl` runs too — http(s) only, no loopback/private/link-local address — with one escape hatch: a URL on this deployment's own origin (`eddi.self.base-url`, or the derived loopback address, via `SelfUrlResolver`) passes, because it is operator configuration and an agent calling EDDI's own `/v1` API is a supported arrangement. `validateHost` is the same rule for a bare `host[:port]` opened as a raw connection (no self escape hatch: EDDI's listener is never a database); an unresolvable host counts as private. Hosts on `eddi.security.ssrf-protection.allowed-hosts` (the httpcalls allow-list from #1033, parsed the same way) skip the private-address check on both paths, never the metadata check.
* **Every LLM builder with an endpoint** — OpenAI (and the eight OpenAI-compatible providers through it), Anthropic, Ollama, Mistral, Azure OpenAI, Gemini, Hugging Face, Vertex Gemini — field-injects the policy and runs its `baseUrl`/`endpoint`/`apiEndpoint` through it. A builder constructed with `new` (tests) behaves as with protection off.
* **`EmbeddingModelFactory`**: OpenAI, Azure, Ollama, Gemini, Mistral and Vertex endpoints. **`EmbeddingStoreFactory`**: Elasticsearch `serverUrl` and Chroma `baseUrl` as URLs; pgvector and Qdrant `host`, and every host a MongoDB connection string names (parsed by the driver's own `ConnectionString`, `mongodb+srv` seed names included), as bare hosts. With the switch on, the default `localhost` of pgvector, Qdrant, Elasticsearch, Chroma and Ollama is refused too: such a deployment must name a public address.
* **OpenAPI spec fetch** ([`engine/mcp/OpenApiSpecFetcher.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/mcp/OpenApiSpecFetcher.java)): `McpApiToolBuilder.parseSpec` no longer calls swagger-parser's `readLocation`. The document is fetched by EDDI through `SafeHttpClient.sendNoRedirect`, redirects followed by hand (at most five, GET only, no credentials) with every hop held to the policy, the body read through `BoundedBodyReader` and refused above 16 MB while streaming. The text is handed to `readContents` with the location as its base, so a multi-file spec's relative `$ref`s resolve as before. `RestApiCallsStore` and `AgentSetupService` inject the fetcher; the fetcher-less `parseSpec`/`parseAndBuild` overloads remain for inline specs and tests and fetch with protection off.
* **`AgentSetupService.createApiAgent`**'s `llmBaseUrl` goes through the same policy, so a URL the model build would later refuse fails at the wizard, before any resource exists.
* **Docs**: [`security.md`](https://docs.labs.ai/security-and-compliance/security.md) SSRF section lists the covered paths and the residual; [`langchain.md`](https://docs.labs.ai/agent-configuration/langchain.md) OpenAI-compatible `baseUrl` note; [`configuration-reference.md`](https://docs.labs.ai/deployment-and-infrastructure/configuration-reference.md) row for the switch.

### Verified, no change needed

`EmbeddingStoreFactory.physicalName` cannot be coerced into another location at build time: a `${...}` reference in the raw `table`/`collectionName`/`indexName` is refused outright, a pgvector name must be a plain (optionally schema-qualified) identifier because the store puts it into SQL unquoted, and the `eddi_kb` prefix is refused at save time (`KnowledgeBaseStorageGuard`). A literal name equal to one of EDDI's own collections or tables is not refused — there is no central registry of those names to check against — but it only matters when the connection string names EDDI's own database, which is a private host and therefore refused when the switch is on. With the switch off, reaching internal databases is the documented choice.

### Residual

`$ref`s inside a fetched spec are still resolved by swagger-parser's own resolver (`setSafelyResolveURL(true)`), which checks each reference's initial URL but follows that URL's redirects itself. Disabling resolution would break multi-file specs; the spec document itself — the editor-controlled location — is now fetched safely.

***

## fix(security): refuse templated hosts without SSRF protection, and only admins may write `${caller:token}` (2026-10-15)

**Repo:** EDDI (`fix/ssrf-default-caller-token`; backend, docs)

### What changed and why

The two High findings of the 2026-10-15 security review.

**H1 — templated httpCall hosts with SSRF protection off.** `eddi.security.ssrf-protection.enabled` defaults to `false`, and an httpCall's authority may be a Qute template whose rendered value keeps dots and a port. A property is routinely captured from user input, so `https://{properties.apiHost}` let the chatting user steer a call to `127.0.0.1:7070` (EDDI's own admin API) or any RFC1918 address; the review reproduced the loopback reach live.

* **A templated scheme, host or port is refused while protection is off.** `ApiCallExecutor.rejectTemplatedAuthority` checks the URL before rendering (a `{` in the authority that is not part of a `${vars:…}`/`${vault:…}` reference); `ApiCallsTask.configure` calls it for `targetServerUrl` and every full-URL call path, so the agent fails to deploy with a `WorkflowConfigurationException` naming the flag, and `buildRequest` applies the same check per turn, which also covers httpcall tools. With protection on, templated hosts work as before and the rendered host is validated.
* **`eddi.security.ssrf-protection.allowed-hosts`.** Comma-separated exact `host` or `host:port` entries (case-insensitive, no wildcards, a bare host matches any port). With protection on, a listed host skips the private-address check but never the cloud-metadata check, and redirects stay off. Lets a self-hoster turn protection on and keep named internal APIs. httpCalls only; MCP and A2A are unchanged (review finding M2 covers them).
* **Default kept `false`, with a production WARN.** The rule-based reference agent and the integration tests target `http://localhost:7070`, so defaulting to `true` would break them. `AuthStartupGuard.ssrfDiagnostic()` logs a `[SECURITY]` WARN at production startup while protection is off, naming the flag and the allow-list.

**H2 — `${caller:token}` as a confused deputy.** `CallerIdentityResolver` releases the bearer token of whoever is chatting to the caller's origin or EDDI's own address, without regard to who authored the config. Editors may save `${caller:token}` and deploy, so an editor-authored call to `/administration/…` or `/secretstore/…` ran with the privileges of the next admin who chatted with the agent.

* **New `CallerTokenAuthorPolicy`.** With `authorization.enabled=true`, storing a document that contains `${caller:token}` (or `{caller:token}`) requires one of `eddi.caller-identity.author-roles` (default `eddi-admin`); anyone else gets a 403 with a JSON `error` naming the property. It scans the serialized document, so it covers httpcall headers, MCP `apiKey` and anything later added, without tracking fields. `${caller:userId}` stays open to editors.
* **Released only from the configuration as written.** `ApiCallExecutor` refuses a header whose `${caller:token}` arrives through a `${vars:…}` or `${vault:…}` value (`GlobalVariableResolver` allows a variable whose whole value is a reference). The save-time scan cannot see through a variable, and a variable can be edited after the config was saved, so this is enforced at execution. The MCP `apiKey` path never resolves a caller reference produced by a variable, so it needed no change.
* **Applied at every write.** `RestApiCallsStore` and `RestLlmStore` create/update/patch/duplicate, `RestMcpCallsStore` create/update/patch/duplicate, `RestImportService.createResourceDirect` (ZIP create/merge), and `UpgradeExecutor.createExtension` (upgrade and instance sync); merge and upgrade updates go through the REST stores. The check throws rather than returning a response, because the import treats a non-200 update as "create it directly instead". An import refusal fails the whole import with the 403 and rolls it back.
* **Docs.** [`security.md`](https://docs.labs.ai/security-and-compliance/security.md#ssrf-protection--urlvalidationutils), [`configuration-reference.md`](https://docs.labs.ai/deployment-and-infrastructure/configuration-reference.md), [`httpcalls.md`](https://docs.labs.ai/agent-configuration/httpcalls.md#who-may-write-callertoken) ("Who may write `${caller:token}`"), [`upgrading-from-6.5.md`](https://docs.labs.ai/deployment-and-infrastructure/upgrading-from-6.5.md).

### Design decisions

* **Refuse the templated authority, not the flag default.** Defaulting protection on breaks every configured internal target at once; refusing only the template closes the path the end user controls and leaves editor-written literals, which the WARN now surfaces.
* **Check at write time, not at release time.** The resolver knows the chatting user, not the author; the write is the only point where the author is known.
* **Whole-document text scan.** One rule for every config type, no field list to keep in step. A literal `{caller:token}` in, say, a prompt is refused for editors too; acceptable for a credential reference.
* **Platform Operator unchanged.** Its prompt does not discuss caller identity or SSRF, and it is provisioned by an admin, who passes the check.

### Known limitations

* A merge import by a non-author is refused before its first write when it would replace a stored version containing `${caller:token}` (`CallerTokenAuthorPolicy.requireMayRestore`): its rollback restores through the same stores, which would refuse that version and leave the import's content in place.
* An upgrade or instance sync reports a refusal as that resource failing rather than a 403, like every other per-resource failure there: an upgrade is not transactional, and aborting would leave earlier resources written.
* With protection off, editor-written literal internal targets remain reachable by design; turn protection on and use the allow-list to close that.

***

## 🔒 fix(vault): no default grant on create, per-secret `allowedHosts`, vault-backed `${vars:}` credentials, wider scrubbing (2026-10-15)

**Repo:** EDDI (`fix/vault-grants`)

Findings M1, L1 and L12 (partial) of the 2026-10-15 security review.

### M1 — vault secrets were granted to every agent by default, and `${vault:…}` had no destination allow-list

* **A create needs a grant.** `PUT /secretstore/secrets/{tenantId}/{keyName}` used to pass a missing `allowedAgents` straight through, and `VaultSecretProvider.storeIfAbsent` / the persistence layer turned it into `["*"]`. Under `eddi.vault.grant-enforcement=enforce` (the shipped default) a create without the list is now a **400** that tells the operator to pass the agent ids or `["*"]` explicitly — the rule `PUT …/grant` already had. `warn`/`off` keep the convenience, written out as `["*"]` at the REST layer instead of left to a default. A rotation may still omit the list and keeps the stored grant. The space-scoped store (`RestSpaceResources.storeSecret`) applies the same rule through the shared [`VaultGrantRequests`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/secrets/VaultGrantRequests.java). `VaultSecretProvider.store` (on an insert) and `storeIfAbsent` now throw `IllegalArgumentException` on a null grant in every mode, so no code path reaches the persistence default: the setup wizard already passed `List.of("*")` with its reason next to it, `SecretPropertyVault` passes the agent's id, `AgentSigningService` the agent's id.
* **Per-secret `allowedHosts`.** New optional field on `SecretMetadata`/`EncryptedSecret`, stored by Mongo (`allowedHosts`) and Postgres (`allowed_hosts JSONB`, added with `ALTER TABLE … ADD COLUMN IF NOT EXISTS`); null or empty is "any destination", which every existing row has. Set with the value on `PUT /{tenantId}/{keyName}` or without it on `PUT …/grant` (`ISecretProvider.updateAllowedHosts`, `ISecretPersistence.updateSecretAllowedHosts`). Entries are exact `host` or `host:port`, validated and lower-cased by `VaultHostAllowlist.validatedHosts`, at most 100. Enforced by the new [`VaultHostAllowlist`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/secrets/VaultHostAllowlist.java) at the two places a reference is resolved for an outbound destination: `ApiCallExecutor` collects every `${vault:…}` reference the request carried (path, body, headers, query) in a `ResolvedSecrets` accumulator and checks them against the fully resolved target URI just before `BuiltRequest` is returned — a field-injected hook, so the constructor the SSRF/caller-token session is editing is untouched — and `ChatModelRegistry` checks the builder parameters against the configured `baseUrl`/`endpoint`/`url`/`serverUrl`/`host` before resolving the vault references, on both the sync and the streaming path. A refusal names the reference, the destination and the list (never a value) and the grant call that fixes it; a list that cannot be read fails closed. Not covered: a configuration without an endpoint parameter (the vendor default, which an editor cannot choose), and the embedding/vector-store, MCP and A2A resolution paths — stated in the docs.
* The Manager's two create flows now send the grant explicitly: the Secrets page sends `["*"]` where it used to omit the list for "all agents", and the secret picker's inline create grants the agent it was opened for (`agentId`) or `["*"]`. The Manager does not edit `allowedHosts` yet.

### L1 — `${vars:…}` accepted wherever a vault reference is required

`ConnectionConfiguration` accepts `${vars:x}` for `oauth.clientSecret` and `staticAuth.passwordRef`, and `/variablestore/variables` is editor-readable, so an OAuth client secret could live in plaintext global variables. A variable in a credential field may now only hold a `${vault:…}` reference: `CredentialReferenceResolver.resolveVaultBacked` (used by `OAuthTokenService`, `RestConnectionAuthorization` and the BASIC password path of `ConnectionResolver`) refuses at use with `INVALID_CONFIGURATION` when the expansion is not exactly one vault reference, and `resolveRequired` (the `valueTemplate` path) refuses when a variable expands to anything `ConnectionConfiguration.isAcceptableValueTemplate` would not accept — scaffolding like `Bearer` is fine, a key is not. `RestConnectionStore` runs the same checks at save through `requireVaultBacked` and, for `staticAuth.valueTemplate`, `requireAcceptableTemplate` (a variable that does not exist yet is let through; the use-time check closes that). No message quotes the expansion.

### L12 (partial) — scrubber field names and LLM config read-back

* `SecretScrubber` now also treats `pwd`, `pass`, `passphrase`, `pin`, `otp`, `pem`, `privateKeyPem` as credential field names, and `pwd`, `passphrase`, `privateKey`/`private_key` as credential suffixes; `pin`/`otp`/`pem` are deliberately whole-name only (`spin`, `item`, `poem` stay). Tests use zero-entropy values so the name rule is what they exercise.
* `RestLlmStore.readLlm` returns a non-administrator a copy with plaintext credential parameters replaced by a marker, as `RestConnectionStore.readConnection` does; an administrator still reads the document as stored so the literal can be found and vaulted.

### Design decisions

* `allowedHosts` is enforced at resolution time, unlike `allowedAgents` (deploy time), because the destination is only known then. The ApiCallExecutor hook is field-injected and null-guarded only for direct construction in tests; under CDI it is always present.
* The grant endpoint writes the host list as a separate, unconditional write — it is independent of the agent grant, so `expectedAllowedAgents` does not cover it — and writes it **first**: if the grant write then fails, the row is left in its tighter state (narrowed hosts without the widened grant) rather than the reverse.
* `ChatModelRegistry` checks every endpoint key that is set (`baseUrl`, `endpoint`, `url`, `serverUrl`, `host`), not only the first: which one a builder reads depends on the provider.
* `RestLlmStore`'s read redaction treats a value as a reference or template only when it has that shape (`${scheme:…}` or `{name…}`), so a literal credential containing a brace is still redacted.
* The Platform Operator cannot create secrets (no `secretstore` PUT in its allow-list) and its prompt does not describe the grant default, so neither the prompt nor the revision changes.

**Tests:** `VaultHostAllowlistTest`, `RestSecretStoreGrantOnCreateTest`, `VaultSecretProviderAllowedHostsTest`, `ApiCallExecutorAllowedHostsTest`, `ChatModelRegistryAllowedHostsTest`, `CredentialReferenceResolverVaultBackedTest`, `RestConnectionStoreVaultBackedVarsTest`, `SecretScrubberFieldNamesTest`, `RestLlmStoreReadRedactionTest`; existing tests updated for the five-argument `store` and the explicit grant. The grant-on-create and scrubber tests were mutation-checked by reverting the fix.

**Docs:** [`secrets-vault.md`](https://docs.labs.ai/security-and-compliance/secrets-vault.md) (grant on create, new *Destination allow-list* section, endpoint table), [`connections.md`](https://docs.labs.ai/protocols-and-integration/connections.md) (vault-backed `${vars:}`).

***

## 🔒 fix(vault): enforce `allowedHosts` for embedding, vector-store, MCP and A2A references; edit it in the Manager (2026-10-15)

**Repo:** EDDI (`fix/vault-allowed-hosts-coverage`)

Follow-up to M1 of the 2026-10-15 security review. `fix/vault-grants` added a per-secret `allowedHosts` list but enforced it only where `ApiCallExecutor` and `ChatModelRegistry` resolve `${vault:…}`; [`secrets-vault.md`](https://docs.labs.ai/security-and-compliance/secrets-vault.md#destination-allow-list-allowedhosts) listed the other resolution paths, and the Manager, as gaps. This closes them.

### Backend

* **`EmbeddingModelFactory`** checks the embedding parameters against **every** endpoint key present (`baseUrl`, `endpoint`) before the references are resolved — checking only the first would let an Azure config carry an allowed `baseUrl` while the builder reads an off-list `endpoint` (CodeRabbit on #1043; #1037 made the same correction in `ChatModelRegistry`). No endpoint parameter means the vendor's own endpoint and is not checked.
* **`EmbeddingStoreFactory.resolveParams`** collects the references, resolves them, and checks every destination the store builder will connect to — `destinationsOf(storeType, params)`: pgvector and Qdrant `host:port` with the builders' defaults, the Elasticsearch `serverUrl`, the Chroma `baseUrl`, and each host of a MongoDB Atlas connection string. For `mongodb+srv://` that host is the SRV name: the driver only accepts SRV-resolved hosts under that name's parent domain, so listing the SRV name trusts whoever controls that DNS zone — stated in the docs rather than refusing SRV strings, which is how Atlas is normally addressed. *After* resolution on purpose: the connection string is commonly the secret itself, so its hosts are unknown until it is decrypted, and resolving is local — the check still runs before anything connects. An unparseable connection string yields a destination no list matches.
* **`McpToolProviderManager`**: new `validateSecretDestination`, run with the other pre-contact checks in `discoverTools` and `resourceBridgeTools`, so a refusal is reported as `INVALID_CONFIGURATION` and kept away from the circuit breaker (it rethrows `HostNotAllowedException` as `IllegalArgumentException`); `createTransport` checks again immediately before resolving, since a transport is also built for a tool call. Caller- and connection-bound keys are not vault references and are skipped.
* **`A2AToolProviderManager.applyCredential`** checks against the request's own `agentUrl` — for a task call that is the endpoint the peer's agent card announced, which need not be the configured host. Discovery already treats an `IllegalStateException` as a credential problem, not a breaker failure.
* All four field-inject `VaultHostAllowlist` (null only in tests that construct them directly) rather than adding a constructor parameter: `fix/ssrf-coverage` changes the embedding factories' constructors, and the MCP/A2A ones have several back-compat overloads.
* **`RestSecretStore.updateGrant`** now calls `secretResolver.invalidateCache(ref)` when `allowedHosts` is written. Models, embedding models/stores and MCP clients check the list when they are built and are then cached; without the eviction their invalidation listeners perform, a narrowed list would not reach a client already built. The agent-grant-only edit still does not invalidate (unchanged reasoning).

### Manager

* `SecretMetadata`, `SecretGrantRequest` and `SecretGrantResponse` carry an optional `allowedHosts`; `updateSecretGrant` and `useUpdateSecretGrant` pass it through only when given. `validateAllowedHost` mirrors the backend's shape check (no scheme, path or wildcard; `host` or `host:port`).
* The Secrets page shows a restricted secret's hosts under its agent chips (`allowed-hosts-<key>`); an unrestricted one shows nothing.
* The Access dialog (`EditGrantDialog`) edits the list with the shared `ChipInput`: entries are lower-cased, a URL is refused as it is typed, text still in the box is folded in on Save, and the field is sent only when it changed — removing every host sends `[]`, which lifts the restriction.
* **Narrowing warns.** Adding a first host or dropping a stored one can stop a deployed configuration at its next call, which the agent-impact dry run cannot see, so the dialog shows a warning and holds Save until the operator ticks it — keyed on the list it was given for, as the agent acknowledgement is. Widening or lifting the list needs no tick. The dialog's "only who may use it changes" line now also says where it may be sent.
* MSW: `google-gemini-key` is seeded with `allowedHosts`, and the grant handler stores and echoes it like the backend. Eight new keys under `secrets.*` and the revised `secrets.grantValueUntouched`, in all 11 locales.
* No operator change: the operator cannot create or edit secrets, and a refusal message names the grant call that fixes it.

### Tests

`VaultAllowedHostsCoverageTest` (13, one `@Nested` class per path, real `VaultHostAllowlist` over a mocked provider) and two assertions in `RestSecretStoreGrantOnCreateTest` (invalidation on a hosts write, none on a grant-only edit). Mutation check: with the five new calls disabled, 7 tests fail — every path's refusal test and the invalidation assertion. `secrets-grants.test.tsx` gains eight Manager tests. `VaultAllowedHostsCoverageTest.everyEndpointKeyChecked` fails with the first-key `return` put back.

***

## ✨ feat(operator): the operator can look up the running EDDI version and git commit (2026-10-13)

**Repo:** EDDI (`feat/operator-build-version`)

### What

An operator should always know which EDDI build it runs on, including after the deployment is upgraded. The Platform Operator's system prompt is written at activation and its tools are generated from the OpenAPI spec, so nothing it was given can say what is running *now*. It now has a live lookup:

* `BuildInfo` (`engine/runtime`) is the single source: version from `systemRuntime.projectVersion`, commit from `eddi.build.commit` (env `EDDI_BUILD_COMMIT`). Only a hex string is accepted as a commit; anything else reports `unknown`, because the value reaches an LLM through the tool.
* `GET /administration/version` (`IRestBuildInfo`, `eddi-admin`) returns `{version, commit, commitShort}`.
* `get_eddi_version` MCP tool (`McpVersionTools`, `eddi-admin`), added to the `McpToolFilter` whitelist and `McpToolFilterCoverageTest`.
* An `EDDI <version> (commit <sha>)` startup log line. (A Micrometer info gauge was left out: `MetricsDashboardCoverageTest` requires every meter on the generated dashboard and in `docs/metrics.md`, which is more than this change warrants.)
* Dockerfile: `ARG EDDI_COMMIT` -> `ENV EDDI_BUILD_COMMIT` and the `org.opencontainers.image.revision` label. `ci.yml` passes `--build-arg EDDI_COMMIT=${{ github.sha }}`.
* Manager: `GET /administration/version` added to the operator's `READ_ENDPOINTS`, and one line in its system prompt telling it to call the tool instead of answering from memory.

### Design decisions

* **Commit via Docker build arg, not a Maven git plugin.** The jar stays free of per-commit stamps (see `docs/build-reproducibility.md`) and no new build dependency is introduced. The cost: a jar run outside the image reports `commit: unknown` unless `EDDI_BUILD_COMMIT` is set.
* **Live endpoint rather than text in the operator's prompt.** An upgrade replaces the image; it does not rewrite the stored operator agent, so anything baked in at activation goes stale.
* Raising the Manager's backend floor: operator activation now requires an EDDI that serves `/administration/version`. Manager and backend ship in one jar, so this only matters for a Manager pointed at an older backend.

### Not done

* Manager vitest was not run locally (no `node_modules` in this checkout); CI runs it. Backend: `BuildInfoTest`, `McpToolFilterCoverageTest`, `ImportStyleTest` pass.

### Also in this change

* `ui/manager/src/test/mocks/openapi-operations.json` refreshed from the `OpenAPI Snapshot` job's artifact, and `operator-revision.json` bumped to revision 9 (the operator's prompt and allow-list changed, which is what makes an operator update reach existing deployments).

***

## Chat UI: recover from an unreadable `done`, cap the token-refresh timer (2026-10-13)

**Repo:** EDDI · **Branch:** `fix/chat-ui-review-followups`

Two CodeRabbit findings posted on #948 after its last push, and still open when it merged.

**What changed:**

* **An unreadable `done` payload** (`ui/chat/src/components/ChatWidget.tsx`). `parseDoneSnapshot` returns null for an empty or malformed body, for example when a proxy truncates the frame. The widget then applied it as an empty snapshot. A turn that had streamed no tokens ended with no reply and no quick replies, and nothing said so.
  * The `done` handling moved into `applyDoneSnapshot`.
  * A null payload now only marks the turn (`TurnContext.doneUnreadable`) and ends the read loop.
  * The re-read that already follows every stream (for undo/redo) asks for the current step, which carries the same two fields as `done`: `conversationState` and `conversationOutputs`. On an unreadable `done` that re-read is applied as the turn's outcome.
  * If the re-read fails too, the turn ends with the "response may be incomplete" notice. The draft is not handed back.
* **The token-refresh timer** (`ui/chat/src/api/embed-auth.ts`). Browsers store a `setTimeout` delay as a signed 32-bit value. A JWT whose `exp` was more than about 24.8 days away overflowed it, so the timer fired at once. The refresh request then went out immediately. A host that answered with the same token got the same instant timer back, and the two looped over `postMessage`. The delay is now capped at 2,147,483,647 ms. When a capped timer fires, it schedules again for the remainder instead of asking for a token.

**Design decisions:**

* CodeRabbit suggested throwing on a null `done`, so the stream-failure path handles it. That path treats the message as never consumed: with no tokens it withdraws the bubble and puts the text back in the composer as "could not be sent". A `done` means the server finished the turn, so a resend would run it twice. The re-read recovers the real outcome instead. A test pins this: the throwing variant fails both new tests.
* `parseSseFrame` stays generic. The `done` schema is still interpreted only in `sse-events.ts` and the widget.

**Tests:** `embed-auth.test.ts` adds a fake-timers test with an `exp` 60 days out. `ChatWidget.review-fixes.test.tsx` covers the re-read recovery and the re-read failure. Each test fails with its fix reverted.

***

## 🐛 fix(monitoring): one panel id per panel in the full metrics dashboard (2026-10-13)

**Repo:** EDDI (`fix/metrics-dashboard-panel-id-clash`)

### What changed and why

`main`'s Build & Test went red after #1000 and #951 merged in the same batch: each added a panel with id 182 to the full metrics dashboard ("Idempotent turn duplicates by outcome" and "Files refused by upload source"). Grafana keys panel state, links and repeats on the id, so two panels with one id behave as one. `MetricsDashboardCoverageTest.panelIdsAreUnique` caught it, and `DeploymentManifestsTest.splitDashboardPartsAddUpToTheSource` failed with it because the Kubernetes halves were no longer the source's panels.

The idempotent-turns panel is now id 201, the next free id. The Kubernetes halves are regenerated with `scripts/sync-monitoring-assets.py`. Nothing referenced panel 182 by id.

**Files:** [`eddi-full-metrics-dashboard.json`](https://github.com/labsai/EDDI/tree/main/docs/monitoring/eddi-full-metrics-dashboard.json), `k8s/overlays/monitoring/dashboards/eddi-full-metrics-dashboard-{1,2}.json`.

***

## feat(llm): every provider parameter, model-aware, with a Manager settings panel (2026-10-13)

**Repo:** EDDI (`feat/llm-provider-parameter-coverage`; backend, Manager, docs, Platform Operator)

### What changed and why

An audit of all 19 LLM integrations against the langchain4j builder APIs showed that EDDI read only a handful of parameters per provider (typically `temperature`, `maxTokens`, `timeout`) and silently dropped everything else: no `topP`, `seed`, `stopSequences`, no reasoning controls (`reasoningEffort`, Anthropic `thinkingType`/`effort`, Gemini `thinkingLevel`), no prompt caching, no Gemini safety settings, no custom headers or body fields. The task `parameters` map is string-only and nothing could reach a builder it did not name. Worse, newer models reject parameters older ones accept (OpenAI reasoning models reject `temperature`, newer Claude models reject non-default sampling settings and manual thinking budgets), so exposing parameters without knowing the model would only have made it easier to break an agent.

* **langchain4j 1.20.2 to 1.22.0 / 1.22.0-beta32.** The OCI GenAI community module caught up with the beta line, so its separate `langchain4j-community-oci.version` property and the `BuildQualityGatesTest` lagging-artifact exception are gone (the guard demands exactly that). 1.22.0 adds OpenAI `promptCacheKey` and Anthropic `cacheAutomatically`/`cacheTtl`; no builder API the code used changed.
* **Every builder reads the parameters its API accepts.** OpenAI/Azure OpenAI, Anthropic, Gemini, Vertex Gemini, Mistral, Ollama, Bedrock, Hugging Face, Oracle GenAI and, through the OpenAI builder, the eight OpenAI-compatible providers. Shared keys keep one name across providers (`topP`, `seed`, `stopSequences`, `reasoningEffort`, `customHeaders`, `customParameters`...). Each builder parses its settings once and applies them to the synchronous and the streaming client alike. The full list is the generated [`docs/llm-parameters.md`](https://docs.labs.ai/agent-configuration/langchain/llm-parameters.md).
* **Value parsing is lenient and never logs values.** New `ModelParameterValues` helpers (`stringList`: JSON array or comma list, `objectMap`/`stringMap`/`intMap` for JSON objects, `enumValue`, `booleanOrNull`): a malformed value falls back to the provider default with a warning naming only the key, because a header or body value can be a credential.
* **Model-aware parameter catalog** (`src/main/resources/llm/model-parameters.json`, `ModelParameterCatalog`). Per provider, every parameter with type, range, group and description, plus per-model-version rules (`rejected` or `ignored`, with `when`/`unless` conditions on other parameters). When a model is built, `ChatModelRegistry` removes the parameters the configured model is documented to reject and logs one WARN naming parameter, model and reason, instead of every turn failing with an HTTP 400. `ignored` parameters are kept and warned about. `eddi.llm.parameter-catalog.drop-rejected=false` only warns. Unknown providers and models fail open. A rule exists only where an official vendor source states the behaviour; conflicting or missing sources produce no rule.
* **OpenAI-compatible vendor fields.** xAI, DeepSeek, Moonshot, Qwen, Z.ai, MiniMax, OpenRouter and Groq get their own fields as catalog entries with a `wire` path (Qwen `enableThinking`/`thinkingBudget`, Z.ai `doSample`/`thinkingType`, OpenRouter provider routing and app attribution headers, Groq `reasoningFormat`...), translated into the request body (dotted path means nested object) by `OpenAiCompatibleLanguageModelBuilder`. The user's own `customParameters` still win.
* **A rejected `maxTokens` keeps its cap.** On OpenAI/Azure reasoning models (o-series, GPT-5 and later) `maxTokens` is rejected; instead of silently losing the output and cost limit, the catalog rule carries `migrateTo: maxCompletionTokens` and the value is sent as `maxCompletionTokens` (unless that is set). The truncation re-ask no longer counts a cap the model rejects (it would have sent `max_tokens` and been answered with a 400); for those models, which are capped through `maxCompletionTokens`, there is no base cap to raise and the re-ask is skipped, as for any task without a configured cap.
* **Hugging Face now uses the langchain4j default router** (`router.huggingface.co`) when `baseUrl` is unset, instead of the previous hard-coded inference host, and `modelId` is finally set on the client (langchain4j 1.22 requires it and builds `<baseUrl>models/<modelId>`). `baseUrl` is the service root without `models/`. Existing Hugging Face tasks therefore change endpoint.
* **Fixes found on the way.** Vertex had no `maxOutputTokens` at all; Hugging Face never set `modelId`, which langchain4j 1.22 requires; Bedrock only built its request parameters when `temperature` or `maxTokens` was set; Azure `endpoint` and Vertex `apiEndpoint` were not checked against the cloud metadata service. `FormatRetryRunner` now also reads `maxCompletionTokens` when sizing the truncation re-ask.
* **Manager: a Model settings panel** in the LLM task editor and in cascade steps, driven by a generated TypeScript mirror of the catalog (`npm run gen:llm-params`, drift-tested). Typed controls grouped as sampling, reasoning, output, tools, caching, safety, connection and advanced; filter box; configured count per group; reset to provider default. As the model or a related setting changes it shows, live, which settings the model will reject (control locked, one-click Remove) or ignore. The previous free-form grid remains as "Other parameters" for anything outside the catalog. 51 to 63 new i18n keys in all 11 locales.
* **Cascade steps and the judge model wrote `parameters.model` for every provider**, a key only Ollama reads; the OpenAI, Anthropic and other builders ignored it and ran the task's model. The step card and the judge editor now read and write the provider's own model key (legacy `model` values stay readable and are moved on first edit).
* **Two `main` CI breakages fixed so this PR can go green**: the split Grafana dashboard copies under `k8s/overlays/monitoring/` were stale, and `docs/monitoring/eddi-full-metrics-dashboard.json` carried panel id 182 twice (two merged PRs each added one); 'Idempotent turn duplicates by outcome' is now id 201 and the copies are regenerated.
* **Docs.** New generated [`docs/llm-parameters.md`](https://docs.labs.ai/agent-configuration/langchain/llm-parameters.md) (`scripts/gen-llm-parameters-doc.py`; `LlmParametersDocumentationTest` fails when a provider or parameter is missing), and a section in [`docs/langchain.md`](https://docs.labs.ai/agent-configuration/langchain.md).
* **Platform Operator.** The prompt now points admins' "why does my topP/temperature do nothing" questions at the `llm-parameters` docs page and explains that rejected parameters are dropped with a WARN; `operator-revision.json` bumped to 9 so existing deployments are told to upgrade their operator.

### Design decisions

* **Catalog as data, not code**: the Manager needs the same rules to warn before a request is ever made, and a data file can be mirrored, documented and vector-tested in both languages. `ModelParameterCatalogVectorsTest` and the Manager's `llm-parameter-catalog.test.ts` run the same 89 vectors (`src/test/resources/llm/parameter-rule-vectors.json`) so the two evaluators cannot drift.
* **Drop rejected, warn on ignored**: sending a parameter that is certain to produce a 4xx fails every turn of an agent; dropping it with a loud WARN keeps the agent answering. The switch exists because a vendor can change the rule before the catalog does.
* **Fail open**: no rule is written from an unverified or contradictory source, and an unknown model is never restricted.
* **`baseModel` on Azure**: the Azure `model` field is a deployment name that says nothing about the model, so gating needs the underlying id from the designer; it is never sent.
* **`includeThoughts` is not offered for Gemini**: thought parts interact with the thought-signature handling documented in `GeminiLanguageModelBuilder`; `thinkingLevel`/`thinkingBudget` steer effort without asking for the thoughts back.
* **`logprobs` is not offered**: EDDI never reads them, and the streaming OpenAI client has no setter.

### Upgrade notes

* **Keys that used to be ignored are now sent.** Before this change an unrecognised key such as `topK`, `seed`, `frequencyPenalty`, `presencePenalty` or `stopSequences` on Gemini, OpenAI, Azure OpenAI or Mistral was only warned about and never reached the provider. It now does. A config that carried such a key out of habit therefore starts to send it, and `eddi.llm.parameter-catalog.drop-rejected` only protects where the catalog has a documented rule for the model. The one known unverified case is Gemini `frequencyPenalty`/`presencePenalty`: some Gemini models are reported to reject them, no official source names which, so there is no rule and the parameter descriptions say so. Remove the key if the provider answers with an error.
* The startup log warns once per model build about every parameter that is dropped or has no effect; grep for `was not sent to` and `has no effect on`.

### Known gaps and follow-ups

* Mistral `reasoning_effort`, `service_tier`, `top_k`, `min_tokens` and `prompt_mode` cannot be set (no langchain4j setter, no `customParameters`); Ollama `think` is true/false only; Jlama `threadCount` is process-wide in the library and not exposed.
* No rules for Vertex Gemini and for several OpenAI/Qwen/xAI cases whose official sources were silent or contradictory (listed in the research notes of this change); they apply to every model until a source settles them.
* The panel's chrome is translated in all 11 locales, but the catalog's own prose (parameter labels, descriptions and rule notes, about 250 parameters) is English data in every locale. Translating it needs a localized label map and a review process; not part of this change.
* The Manager evaluates the model rules against the model value as typed, so a `${vars...}` reference is not resolved there (the panel says so); the server gates on the resolved id.
* The catalog JSON is hand-maintained; a scheduled check against vendor docs is not part of this change.

***

## NATS cluster stack brought up to main (2026-10-13)

**Repo:** EDDI · **Branch:** `feat/nats-cluster` (PR #956, with #957, #958 and #970 merged into it)

`origin/main` merged into the cluster stack after #937, #942–#954, #990, #993, #996, #999, #1001, #1008, #969, #936, #967, #1000, #951 and #1002 had landed on it.

### How the cluster code now sits on main's APIs

* **Lost lease → `abandonTurn` (#949).** The lease-lost hook in `ConversationStepRunner` raises the cancel flag through `abandonTurn`, the same seam `ITurnAbandonment` and the watchdog use, aimed at the turn's own memory rather than looked up by conversation id (a late callback must never hit a newer turn). The lease block now runs inside the guarded `try` around main's `InFlightRegistration`.
* **Lost lease vs `settleCancelledTurn` (#949).** Both the completion and the failure callback ask `discardLeaseLostTurn` first. A lease-lost turn therefore never gets the `EXECUTION_INTERRUPTED` CAS that a `/cancel` gets — that state would overwrite the one the new holder committed — and is still dead-lettered (`lease-lost`) and answered 409. Before, a lease-lost turn that *failed* (rather than completed) took the generic error path.
* **Lease-loss reporting on main's single turn path.** `ConversationService` lost its two copies of the turn code to `admitTurn` (#949); the lease check is now `TurnListener.leaseLost` — skipped/409 for a plain turn, an error event for a stream — and runs before `recordTurnOutcome` (#1000), so a turn that is not stored never records an idempotency key or a turn error.
* **Erasure redaction (#952).** `pseudonymiseIfErased(entry, queued)` keeps the `erasedElsewhere` check: a late entry of a user erased on another node is pseudonymised *and* redacted, as on the erasing node. Its drain counters are kept only for users erased on this node (nothing would report or clear the others).
* **A2A (#953).** `CachedA2ATaskStore` asks `CacheFactory` for `a2aTaskMapping` and `a2aTaskMapping:context`, which cluster mode backs with the `A2A_TASKS` and `A2A_CONTEXTS` buckets; a new test round-trips an `A2ATaskRecord` between two nodes. `A2A_STATES` is no longer used and is gone from the bucket map and the docs.
* **Undeploy (#990).** `IAgentFactory.undeployAgent` no longer throws checked exceptions; the cluster's local undeploy catches `RuntimeException` only.
* **Helm chart 2.7.0** (main is at 2.6.0, from #951). `eddi.updateStrategy` keeps the per-messaging-type default and accepts main's object shape; the chart still refuses `RollingUpdate` with in-memory messaging, which #938 had documented as an opt-in (see [Kubernetes](https://docs.labs.ai/deployment-and-infrastructure/kubernetes.md#upgrades-replace-the-pod-no-surge)).
* **Operator revision 9** (main is at 8, from #1002): the merged prompt carries both the cluster questions and main's admin-action / redaction text.
* **Turn deadline (#996).** [Clustering](https://docs.labs.ai/deployment-and-infrastructure/clustering.md#sizing) now says that a deadline counts from arrival, so time spent waiting for the lease is spent from it.

### Open for review

* `TurnIdempotencyService` (#1000) keeps in-flight keys per node. A duplicate of a running turn that reaches another node waits for the lease rather than getting a 409, and the persisted-key check happens at admission only, so that duplicate can run the turn a second time.

***

## fix(cluster): answer the code-scanning findings on the NATS cluster PR (2026-10-13)

**Repo:** EDDI · **Branch:** `feat/nats-cluster` (PR #956)

### What changed and why

* **Log injection (CodeQL).** `NatsClusterRpc.call` (operation and node id), `GroupConversationService` (the lease-less group discussion warning) and `AgentDeploymentManagement.awaitClusterDeployment` (agent id, twice) now pass the caller-supplied value through `LogSanitizer.sanitize`, like the rest of the codebase.
* **Unused lambda parameters.** The two `whenComplete` callbacks in `RestClusterAdmin` that only close the SSE sink use unnamed parameters (`(_, _)`). The `StartupEvent` parameter of `AgentDeploymentManagement.subscribeToCluster` stays: a CDI observer method needs it, and Java does not allow an unnamed method parameter.
* **Cluster demo scripts.** `scripts/cluster-demo/demo.py` and `mock_llm.py` open their files in `with` blocks, drop three unused locals (keeping the `start_conv` call whose side effect the undeploy scenario needs), comment their deliberate `except: pass` blocks (the log export reports a failed save on stderr), and no longer mix value returns with fall-through returns. `mock_llm.py` gains a `main()` that holds the request log open for the life of the server.
* `RestClusterAdmin` closes the activity stream after its last `busy` or `expired` event through one `closeAfter` helper. A failed send is logged at debug and the sink is still closed, so the callback no longer declares parameters it ignores.

Behaviour is unchanged apart from two diagnostics: a failed final SSE event is logged at debug, and the cluster demo prints a failed node-log export to stderr.

***

## 🐛 fix(monitoring): split the Kubernetes copy of the Full Metrics Reference (2026-10-13)

**Repo:** EDDI (`fix/observability`)

Merging `main` grew the Full Metrics Reference past what one ConfigMap can carry through a client-side `kubectl apply`: minified and escaped it reached 247,445 bytes against this PR's own 245,000-byte budget (the last-applied annotation is capped at 262,144). [`sync-monitoring-assets.py`](https://github.com/labsai/EDDI/tree/main/scripts/sync-monitoring-assets.py) now writes it to the monitoring component as two dashboards, split at the top-level row boundary that best balances their size (131 KB and 119 KB escaped). Part 1 keeps the uid `eddi-metrics-all`, so existing links and bookmarks still land; part 2 is `eddi-metrics-all-2`; each links to the other. `docs/monitoring/` keeps the single dashboard, which Compose and a manual import use.

`DeploymentManifestsTest` checks that the parts' panels, concatenated, are the source's panels and that nothing else differs beyond title, uid and links (verified by dropping a panel from part 2: the test fails). Panel ids 174-177 were also each held by two panels, from parallel PRs taking the next free id; the later holders now have ids above the maximum.

***

## A2A streaming uses the conversation-scoped `sayStreaming` (2026-10-13)

**Repo:** EDDI · **Branch:** `fix/a2a-streaming-after-990`

**What changed:**

* **The break:** main stopped compiling after two PRs that were green on their own were merged in parallel.
  * \#953 (A2A 1.0) called `IConversationService.sayStreaming(Environment, agentId, conversationId, …)`.
  * \#990 removed that environment-qualified overload, which had no other callers.
* **The fix:** `A2ATaskHandler` now calls `sayStreaming(conversationId, …)`, which reads the agent and environment from the stored conversation record. `A2ATaskHandlerTest` stubs that overload.

**Behaviour:** unchanged. An A2A conversation is always started as `startConversation(Environment.production, agentId, …)`, so the record holds exactly the agent and environment the old call passed explicitly. The non-streaming path still uses the environment-qualified `say`, which #990 kept.

***

## 🐛 fix(a2a): stream A2A turns through the agent-qualified `sayStreaming` again (2026-10-12)

**Repo:** EDDI (`fix/main-build-after-concurrent-merges`)

### What changed and why

\#949 removed the environment-qualified `sayStreaming(Environment, agentId, conversationId, …)` from `IConversationService` (no caller outside `ConversationService` at the time) while #953 (A2A 1.0 / 0.3) added one in `A2ATaskHandler`. Merged in parallel, `main` stopped compiling. #1008 made it compile by moving the A2A call onto the conversation-id overload — which runs the caller-facing checks, `requireConversationAccess` (the conversation-ownership guard) among them.

A2A is driven by a peer agent, not by the signed-in owner of a stored conversation, and A2A's non-streaming path still calls the qualified `say()` for exactly that reason. After #1008 the two paths disagreed: a streaming turn ran an ownership check the non-streaming turn skips. This restores the qualified overload on the interface (public on the implementation) and points A2A `message/stream` back at it, so both A2A paths go through the same entry point — the behaviour #953 was written and reviewed against.

`A2ATaskHandlerTest`'s streaming tests stub the qualified overload again, so they fail if the call drifts back to the conversation-id one.

**Files:** [`IConversationService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/api/IConversationService.java), [`ConversationService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/ConversationService.java), [`A2ATaskHandler.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/a2a/A2ATaskHandler.java), [`A2ATaskHandlerTest.java`](https://github.com/labsai/EDDI/tree/main/src/test/java/ai/labs/eddi/engine/a2a/A2ATaskHandlerTest.java)

***

## 🐛 fix(manager): the RAG editor invented vault keys and saved empty values (2026-10-12)

**Repo:** EDDI (`fix/rag-editor-defaults`)

### What changed and why

The knowledge-base editor's provider and store parameters misled users and broke configs in three ways:

1. **Invented vault references were saved as real values.** Switching the embedding provider or vector store pre-filled every parameter whose *example* was a `${vault:…}` placeholder with that placeholder. A knowledge base then referenced `${vault:openai-key}`, `${eddivault:gemini-key}`, `${vault:mongo-uri}` and so on, keys nobody had created; the setup wizard names its vault entries uniquely, so they never matched a real one. The Gemini example even used the legacy `eddivault` prefix.
2. **Empty fields were saved as `""`, which defeats the backend's defaults.** The same switch, and the "+ key" chips, created every other parameter with an empty string. `EmbeddingModelFactory` and `EmbeddingStoreFactory` default a parameter only when its key is *absent* (`params.getOrDefault`), so `{"model": ""}` reached the provider as an empty model name and failed at ingest, while the field looked defaulted.
3. **Placeholders mixed real defaults with invented samples.** `nomic-embed-text` (the real default) and `embeddings` (a sample) looked identical. pgvector's `table` showed `embeddings`, but the backend defaults to one table per knowledge base (`eddi_kb_<id>`); a user who copied the hint into several knowledge bases made them share one table. `user` showed `${vault:pg-user}` where the default is `eddi`.

The editor now:

* **never pre-fills anything** on a provider or store switch, and restores only what that provider had earlier in the session;
* **lists every parameter the backend knows**, each with what an empty field means: `Default: …` (copied from the factories), `e.g. …` (a sample), or `Required`. Credential fields say "pick a vault secret" rather than suggesting a key name;
* **never saves an empty value**: clearing a field removes the key. Unknown parameters (from an import, a hand edit, or "Add Parameter") stay on screen, in place and focused, until they have a value;
* **flags `""` values saved by the old editor** ("the default is not used") with a one-click "Use default";
* treats `connectionString` as a credential field (Atlas);
* follows the storage layout from #945 (knowledge bases isolated by id): the default table, collection or index shows as `eddi_kbid_<id>` for a per-id knowledge base (and for a new one, which the server stamps with that layout), and as the name-derived `eddi_kb_<name>` for a 6.5 knowledge base. OpenAI's now-honoured `baseUrl` shows its real default, `https://api.openai.com/v1`.

This is the first PR of [`planning/rag-embedding-ux-plan.md`](https://github.com/labsai/EDDI/tree/main/planning/rag-embedding-ux-plan.md) (P3, P4, P10, P11). The backend still uses `""` when it is sent. Normalising blank to absent server-side, and publishing the parameter catalogue so these hints stop being hand-copied, is WS1a in that plan.

**Files:** [`rag-editor.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/components/editors/rag-editor.tsx), [`rag-editor.test.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/components/editors/__tests__/rag-editor.test.tsx), 14 new `ragEditor.*` keys in all 11 locales, [`planning/rag-embedding-ux-plan.md`](https://github.com/labsai/EDDI/tree/main/planning/rag-embedding-ux-plan.md) (new).

***

## 🐛 fix(rag): in-memory knowledge bases no longer silently lose their data (2026-10-12)

**Repo:** EDDI (`fix/rag-inmemory-store-eviction`)

### What was wrong

`EmbeddingStoreFactory` kept every vector store in one Caffeine cache: 50 entries, a 30-minute idle TTL, and an `invalidateAll()` on any vault-secret or global-variable change. For an external store (pgvector, Qdrant, …) eviction drops a client and costs a reconnect. For `storeType: "in-memory"` the cached object *is* the data, so a knowledge base with no query for half an hour, a 51st knowledge base, or a credential rotation anywhere in the deployment emptied it, and retrieval returned no context rather than an error. A scheduled ingestion run did not refill it either: the pipeline skips a page whose content hash is unchanged, and the hashes outlived the vectors. Only "Purge state + Run now" recovered.

### What changed

* **Data and clients are kept apart.** In-memory stores live in their own registry in `EmbeddingStoreFactory`, with no TTL, no size eviction and no reaction to secret or variable changes. The registry is keyed exactly as knowledge-base isolation (#945) addresses every other store: the RAG configuration's id, plus the name for a knowledge base still in the 6.5.0 name layout (`inMemoryKey`). Two knowledge bases with one name never share an in-memory store, and deleting one cannot empty another. External stores stay in the evicting client cache, unchanged.
* **An entry is dropped only when the knowledge base goes, or its vectors stop being valid:** the last version is deleted (`RestRagStore.deleteRag`, same "no current version left" rule as the schedules); an update moves it to another key (a rename in the name layout, a switch to `storeNamespace: "id"`), to another `storeType`, or changes its embedding signature (`RestRagStore.updateRag`); or a write arrives under a different embedding signature (`getOrCreateForIngestion`, the safety net for imports and other write paths). Retrieval and removals (`getOrCreate`) never replace a store; `/ingest`, pipeline runs and scheduled runs write through `getOrCreateForIngestion`.
* **Embedding signature** (`embeddingSignature`): store type, provider, the model as `EmbeddingParameters.modelName` resolves it (`model` and its alias `modelName` are one setting), Azure `deploymentName`, the endpoint (`baseUrl`, or `endpoint`) and the vector size (`dimensions`/`outputDimensionality`). The endpoint counts because an OpenAI-compatible server decides for itself what a model name means; keys, timeouts, retries and task types do not.
* **Store epoch.** Every in-memory store gets an epoch at creation. Ingestion records the store fingerprint (`store-epoch=<uuid>`) per source in a new `rag_ingestion_sources` collection/table (`IIngestionStateStore.storeFingerprint` / `recordStoreFingerprint`, removed by `purgeSource`). At the start of a run, `IngestionPipeline.reconcileStoreFingerprint` compares it with the store the run writes to; on a mismatch it calls `invalidateContent` and records the new fingerprint, so every document is re-embedded and no conditional request is sent. After a restart a scheduled run therefore refills the store by itself. A preview reports the re-embedding and writes nothing.
* **Deployment-wide cap.** `eddi.rag.in-memory.max-segments` (default 50,000; `0` disables) bounds the segments all in-memory stores hold together, enforced in `CappedInMemoryEmbeddingStore` under one lock. A write past it throws `InMemoryStoreFullException` with an actionable message; an ingestion run stops and reports `FAILED` with that message. Nothing is evicted.
* **Replaced and dropped stores are retired.** A run takes its store at the start, so a store replaced (embedding signature changed) or dropped (delete, move) mid-run used to keep receiving that run's writes: an orphan nothing reads, outside the cap, which counts only registered stores. The factory now retires such a store; a later write throws `InMemoryStoreRetiredException` under the cap's lock, and the run stops `FAILED` saying the store was replaced or removed. The next run re-embeds into the current store, because its epoch no longer matches. (Raised in review.) A drop retires the store inside the registry's own atomic removal (`computeIfPresent`), so no write lands between "the cap stops counting it" and "it refuses writes"; holding the write lock around `remove()` instead would invert the lock order of the replacement path and could deadlock.
* **A run is bound to the store it checked.** The run takes its write store once, at the start, and compares that instance's fingerprint (`EmbeddingStoreFactory.fingerprintOf`). A later lookup could have returned a newer, empty store after a mid-run drop, with every document passing as "unchanged". A run whose bound store was retired by the end reports `FAILED` even if it wrote nothing.
* **The embedding signature compares resolved values.** `${vars:…}` references are resolved as `EmbeddingModelFactory` resolves them, so a global variable that switches the model replaces the in-memory store on the next write instead of mixing two models' vectors.

### Design decisions

* **A new version with the same store key and embedding signature keeps the data.** Versions are not part of the registry key: nothing else a version can change (chunking, retrieval settings, sources) invalidates stored vectors. A rotated embedding API key is not a new model.
* **Only writes replace a store whose embedding configuration differs.** An agent still pinned to an older knowledge base version keeps reading what is there; replacing on a read would let two live versions wipe each other's store in turn and re-embed on every run.
* **The fingerprint is per source, in its own row,** rather than a new field on every document row: it needs no change to `recordIngested` or `DocumentState`, and invalidating via the existing `invalidateContent` also clears the stored validators, so a 304 cannot skip a page the new store lacks. It is an opaque, named string so that a follow-up can append an embedding-model fingerprint (provider + model + dimension) to the same value.
* **Legacy state** (no fingerprint recorded) is "unknown → re-embed" only when the store has a fingerprint, i.e. only for in-memory stores. External stores report none and behave exactly as before.
* **The cap fails instead of evicting**, because eviction is the bug being fixed.

### What's next

* A durable built-in store, so the default `storeType` keeps its data across restarts.
* An embedding-model fingerprint in the same value, so changing the model of an external store also re-embeds instead of mixing vectors.

**Files:** [`EmbeddingStoreFactory.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/EmbeddingStoreFactory.java), [`CappedInMemoryEmbeddingStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/CappedInMemoryEmbeddingStore.java), [`InMemoryStoreFullException.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/InMemoryStoreFullException.java), [`IngestionPipeline.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/ingestion/IngestionPipeline.java), [`IIngestionStateStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/ingestion/IIngestionStateStore.java), [`MongoIngestionStateStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/ingestion/mongo/MongoIngestionStateStore.java), [`PostgresIngestionStateStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/datastore/postgres/PostgresIngestionStateStore.java), [`RestRagStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/rag/rest/RestRagStore.java), [`RagIngestionService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/rag/RagIngestionService.java), [`rag.md`](https://docs.labs.ai/agent-configuration/rag.md#vector-stores), [`configuration-reference.md`](https://docs.labs.ai/deployment-and-infrastructure/configuration-reference.md#knowledge-bases-rag), Platform Operator prompt (revision bump).

***

## Navigation guard: one app-level blocker wins over per-page blockers (2026-10-12)

**Repo/branch:** EDDI, `fix/manager-navigation-guard` (merge of `main`)

**What changed**

* \#939 (on `main`) and this branch both added in-app unsaved-changes protection. `main` called `useBlocker` from every page through `useUnsavedChangesGuard` and rendered an `UnsavedChangesPrompt` per page; this branch registers dirty state in a store and holds navigation with ONE blocker in `NavigationGuardDialog`.
* The merge keeps the single blocker. `connection-detail`, `workflow-detail`, `config-editor-layout` and `agent-editor-sheet` now just call `useUnsavedChangesGuard(isDirty)`, use the module-level `allowNextNavigation()` for deliberate navigations, and no longer render a prompt. `UnsavedChangesPrompt` and `main`'s per-page navigation test were removed.
* `main`'s role-aware navigation (`useMayOpenScreen`) is kept in the rebuilt sidebar and command palette; both PRs' stable-id section collapse state collapsed into the route-registry ids.

**Design decision:** a router consults only the most recently registered blocker, so a per-page blocker lets any clean guard mounted later silently unprotect a dirty page. Regression tests in `use-unsaved-changes-guard.router.test.tsx` cover a clean sibling mounting after the dirty page and the browser Back button; they fail if each hook registers its own `useBlocker`.

***

## 🐛 fix(hitl): deliver a paused turn only after the pause is persisted (2026-10-07)

**Repo:** EDDI (`fix/hitl-pause-persist-before-response`)

### What changed and why

A turn that ended `AWAITING_HUMAN` told its client "paused" **before** the pause was written. The completion callback fires from inside the pipeline callable and answered the sync `say` response / the streaming `done` event; the paused memory was only stored afterwards by `ConversationStepRunner.runGuardedConversationStep`'s runtime `onComplete` (`populateHitlTimeoutBookmark`, `storeConversationMemoryIfState`, cancel re-check, pause counter, timeout schedule). A client that reacted to the answer by reading `GET /agents/{id}/approval-status` (which reads the **stored** snapshot) could see `state != AWAITING_HUMAN`, `pauseId: ""` and `pauseDetails: null` — the Manager rendered an approvable card with no details, and the chat widget could treat the pause as already resolved. The same ordering applied to a `resume` that re-pauses, and to every consumer of `say` (MCP chat tools, the OpenAI-compatible `/v1` API, group member turns, the quarkus-eddi SDK).

The paused outcome is now delivered from the persistence step:

* `ConversationService.completeTurn` (new) decides when a turn may be answered. A turn whose snapshot is `AWAITING_HUMAN` hands its completion to a one-shot `DeferredDelivery` (new) instead of calling the handler. Every other turn is answered immediately, exactly as before, so ordinary latency is unchanged.
* `ConversationStepRunner.runGuardedConversationStep` flushes the deferral from a `finally` after the commit outcome is known, with the state the store holds: `AWAITING_HUMAN` only when the pause was durably committed and not cancel-raced; otherwise the stored state (lost compare-and-set, cancel conversion to `EXECUTION_INTERRUPTED`, store failure, stale-pause discard). The state cache is updated from the same value, so a lost commit no longer caches a phantom pause. `onFailure` and the task's own `finally` flush a still-pending delivery, so the stream always terminates exactly once.
* `ConversationHitlService.resumeConversation` gets the same treatment for a resume that re-pauses (`resumeDelivery` / `committedResumeState`), flushed from `resumeFinished.onComplete`/`onFailure` and the guarded resume's `finally`.

### Design decisions

* **Narrow: pause turns only.** An ordinary turn's snapshot already matches what the store will hold, and the coordinator serializes the next turn behind this one (a stale-snapshot guard rebuilds a queued turn over the committed document), so holding every response until persistence would add a store round-trip to every turn for no consistency gain. Only a pause is a promise the client acts on immediately.
* The delivery runs inside the same coordinator turn on the same thread, after the commit, so turn ordering and the `processingTurn` release point are preserved; handlers that only complete a future (group member turns, MCP) cannot deadlock on it.
* `DeferredDelivery.deliver` never throws: it runs from `finally` blocks, where an escaping exception would be reported through the Future and flip a healthy conversation to `ERROR`.

### Files

`ConversationService`, `ConversationStepRunner`, `ConversationHitlService`, new `DeferredDelivery`, new `PausedTurnDeliveryOrderTest`, `docs/hitl.md` (ordering guarantee).

### Platform Operator

No change: no endpoint, config field or default changed; only the order in which an already-documented response is sent.

***

## 🐛 fix(operator): approval card could be approved before its details existed; readable tool arguments; decision summary (2026-10-07)

**Repo:** EDDI (`fix/operator-approval-card`), `ui/manager`

### Root cause

The chat stream's `done` event (snapshot `conversationState: "AWAITING_HUMAN"` plus `hitlPausedAt`) is emitted from the completion callback inside `conversation.say()`. The paused memory is only persisted afterwards, in `ConversationStepRunner.runGuardedConversationStep` (`storeConversationMemoryIfState`). `GET /agents/{id}/approval-status` reads the stored snapshot, so the first read after `done` can return `state` other than `AWAITING_HUMAN`, `pauseId: ""`, `pausedAt: ""` and `pauseDetails: null`. `useApprovalStatus` treated that as loaded data and never polled again (global `staleTime` 30 s, no `refetchInterval`), so `ApprovalBanner` rendered the generic RULE layout with Approve enabled until a window-focus refetch happened to fix it. In that window an admin could approve a tool call they had never seen.

### What changed and why

* `describesPause(status, expectedPausedAt)` in [`hitl-pause-binding.ts`](https://github.com/labsai/EDDI/tree/main/ui/packages/app-kit/src/lib/hitl-pause-binding.ts) is the single rule for "this response describes this pause": state `AWAITING_HUMAN` and a matching identity (`Date.parse(hitlPausedAt) === Number(pauseId)`; a blank `pauseId` never matches; a backend without `pauseId` falls back to `pausedAt`).
* `useApprovalStatus` ([`use-hitl.ts`](https://github.com/labsai/EDDI/tree/main/ui/packages/app-kit/src/hooks/use-hitl.ts)) takes `{ verifyPause: true }`. While the response does not describe the pause it re-polls at 500 ms, 1 s, then 2 s, for up to 10 s; withholds the non-matching response from `data`; and returns `detailsPending`, `detailsError` (read failed, or the window ran out) and `retry` (restarts the window and refetches). The operator page uses it. Without the option the hook behaves as before.
* [`approval-banner.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/components/hitl/approval-banner.tsx): new optional `expectToolCall` prop, and a TOOL\_CALL detail with zero calls, both keep Approve disabled (Reject stays available) and show `approval-details-missing`. The operator chat passes `expectToolCall`.
* Approving on the operator surface takes at most two steps. Under `requireExplicitPerCall`, a pause with exactly one gated call hides the per-call buttons and the progress chip, and Approve plus the confirm dialog sends an explicit per-call `APPROVED` (with `amendedArguments` if amended). Two or more calls keep the required per-call verdicts, and once all are set the button (now "Submit decisions") submits directly, because the per-call review is the confirmation. Reject still confirms. The blocked, pending, error, missing-details and `expectToolCall` guards disable the button in every variant. The approvals inbox and conversation-detail also pass `requireExplicitPerCall`, so they get the same flow.
* Tool-call arguments are shown through [`hitl-format-args.ts`](https://github.com/labsai/EDDI/tree/main/ui/packages/app-kit/src/lib/hitl-format-args.ts): JSON-in-a-JSON-string (the `setupAgent` `requestBody`) is expanded and pretty-printed, with a Show raw / Show formatted toggle. Display only: the amend flow and the submitted decision still use the original `call.arguments`. A level is reformatted only when its parse is lossless (`minify(text) === JSON.stringify(JSON.parse(text))`), so big integers, `1.50`, `1e3`, duplicate keys and escape spellings are never altered; those levels, and truncated or non-JSON arguments, are shown verbatim.
* [`operator-chat.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/components/operator/operator-chat.tsx): once a decision is submitted the card is replaced by a compact summary (`approval-decision-summary`, per-call outcome, amended flag, note) while the resumed turn runs. The banner stays mounted but hidden so a failed resume brings it back with the per-call choices intact; it and the summary are keyed by the pause, so a re-pause renders fresh.

### Design decisions

* Fail closed: a response that cannot be matched to the pause is "not described". The cost is a Retry click; the opposite error approves a call nobody saw. The timeout becomes the existing `pauseDetailsError` state, never an endless spinner.
* `verifyPause` is opt-in. The approvals inbox and conversation-detail read the paused state and the status from the same store, so they do not have the stream-before-persist race, and a decision from them is still bound to `pauseId` by the pause-binding layer. The compact drawer surface has no Approve control (it only links to the full page), so it was left alone.
* The "request summary" for the operator's own tools was not added: the backend's resolved request preview plus the escalation flags already cover it, and `src/lib/operator/**` is under mutation testing. No operator revision bump: the prompt, allow-list and gate are untouched.
* The formatted view must never misrepresent the call: a lossy parse falls back to the raw text, the safe direction, even when that is a false "lossy".
* The permanent transcript decision entry was not changed.

### Tests

`hitl-pause-binding.test.ts` (`describesPause`), `hitl-format-args.test.ts`, `approval-card-pause-race.test.tsx` (not-yet-stored first read, different pause id, 10 s timeout and Retry, backoff, legacy backend), `approval-banner.test.tsx` (zero calls, `expectToolCall`, argument formatting and toggle, decision payload uses the original arguments), `operator.test.tsx` (page-level race), `operator-chat.test.tsx` (summary after approve and reject, failed resume restores the card, re-pause renders fresh).

***

## 🐛 fix(manager,chat): every approval surface behaves the same (2026-10-07)

**Repo:** EDDI (`fix/operator-approval-card`), `ui/manager` and `ui/chat`

### What changed and why

Phase 1 fixed the operator's approval card; this applies the same rules everywhere a pause is shown or decided, so no surface can drift.

* **One deciding experience.** `ApprovalCard` ([`approval-card.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/components/hitl/approval-card.tsx)) wraps `ApprovalBanner` and owns the lifecycle: pending, details, at most two steps, a `DecisionSummary` receipt while the resumed work runs, the card hidden but mounted so a failed resume brings it back with its choices. It is used by the operator chat, conversation-detail, the approvals inbox rows and the group transcript. `summariseDecision` ([`hitl-decision.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/hitl-decision.ts)) covers tool calls, group tasks and group phases.
* **Verify the pause everywhere.** conversation-detail and the inbox now use `useApprovalStatus(..., { verifyPause: true })`, so a not-yet-stored or different pause is never approvable. conversation-detail also re-reads for up to 10 s when opened from a pause link (`?awaiting=1`).
* **Read-only surfaces share `PauseNotice`** ([`pause-notice.tsx`](https://github.com/labsai/EDDI/tree/main/ui/packages/app-kit/src/components/hitl/pause-notice.tsx)): the Manager chat panel and the Workforce thread name the gated tools, link to that conversation's own review page, and clear when the pause is decided elsewhere (`onResolved`, 5 s watch). The chat store now remembers `pausedAt` to tell this pause from another.
* **Group transcript:** Approve is held while only the stream says `AWAITING_APPROVAL` and the persisted conversation has not caught up (no phase or task data yet). A discussion waiting on a human is re-read every 5 s. The Workforce board's review link opens the specific conversation.
* **ui/chat:** `useHitlPolling` took the first approval-status read of a pause that was not stored yet (READY) as "resolved", refreshed to the old snapshot and dropped the card. A READY read before the pause has been seen stored is now distrusted for 10 s (500 ms backing off to 2 s). `PausedCard` stays read-only, and shows tool names only, never arguments.

### Design decisions

* Client-side polling is defence in depth. The root cause (the stream's `done` is emitted before the pause is persisted) is being fixed on the backend separately; these windows then rarely trigger.
* For ui/chat the pause identity is not available to the client (no `pauseId` in its approval-status type, no `hitlPausedAt` tracked), so the signal is "has this pause ever been seen stored". A pause decided before the first read looks identical to a not-yet-stored one, so the doubt ends after 10 s.
* Every deciding 1:1 surface uses `requireExplicitPerCall`, so the single-call and multi-call flows are identical on all of them. Group cards have no tool calls and use Approve plus confirm.

### Tests

`approval-card.test.tsx`, `pause-notice.test.tsx`, `conversation-detail-pause-race.test.tsx`, additions to `approvals.test.tsx`, `discussion-transcript.test.tsx`, `use-groups.test.tsx`, and `useHitlPolling.test.ts` in `ui/chat`. Each safety fix was mutation-checked.

### Follow-up: parity gaps closed (2026-10-07)

* **Receipt scope:** `ApprovalCard` only shows a receipt for the submission that started the current resolution. A failed resume spends it, and a cancel clears it, so a later cancel never reads "You approved".
* **Group approve is bound:** the group page's approve goes through `currentGroupPauseOf` + `bindDecisionToPause` like the inbox. A changed pause refuses, refreshes and does not approve. Group test fixtures use a fixed pause start.
* **Group card keeps its choices:** the card stays mounted (hidden behind its receipt) while the stream takes over, and returns with the per-task toggles if the resume fails.
* **One rule for read-only notices:** the Manager chat panel shows the same review link under `/workforce` (one SPA, so a plain router link), because `PauseNotice` has no per-surface hiding.
* **ui/chat:** `PausedCard` renders at once from the stream's own news ("Waiting for approval", Cancel available, still read-only) and is enriched when approval-status arrives.
* **conversation-detail:** a successful resume re-reads the conversation immediately (explicit refetch plus the hook's invalidation); a test now pins that the receipt hands over to the settled state promptly.

***

## ✨ feat(operator): batched approvals and a REST cascade — a knowledge-base binding takes two approvals, not five (2026-10-07)

**Repo:** EDDI (`feat/operator-batched-changes`)

### What changed and why

The Platform Operator performed a multi-step change one gated call per turn, so the admin approved every step separately: connecting a knowledge base to an agent was five approvals (write the LLM config, write the workflow, repoint the workflow, repoint the agent, deploy). Approval binds to the exact resolved request ("request pinning"), so a step that depends on an earlier step's result cannot be pre-approved; steps that do not depend on each other can share one pause. Two changes use that:

1. **Parallel tool calls, planned first.** The operator's prompt now has a delimited block (`buildBatchingSection`) that tells it to set out the whole plan — every step, which go out together, how many approvals to expect — before the first gated call and to wait for agreement (a plan is a proposal, so it composes with "check / look / verify is read-only"), then to issue independent writes as parallel tool calls in one turn. Nothing in the engine needed to change for this to work: the tool-approval gate classifies every tool call a model emits in one message together and pauses the gated ones as a single batch (`ToolLoopRunner`, `toolApprovalGate.classify` over the whole `toolExecutionRequests()` list); no provider disables parallel calls. See [`hitl.md`](https://docs.labs.ai/conversations-and-orchestration/hitl.md#batching--several-calls-one-pause).
2. **`POST /agentstore/agents/{id}/cascade?version=N`** — the REST form of the MCP tool `apply_agent_changes`, so the operator (whose tools are generated from the REST spec) can use it. Body `{ resourceMappings:[{oldUri,newUri}], redeploy, environment, compatible }`; it swaps references through the agent's workflows and into the agent, saving every changed workflow and the agent **once**, optionally redeploying, and answers with the new agent version, the workflow versions written and the deployment outcome. The logic moved out of `McpAdminTools` into a shared `AgentCascadeService` that both surfaces call — no duplicated implementation. A mapping can now also name a workflow itself, so a workflow patched in the same batch is picked up instead of being overwritten by a rewrite of the version the agent still points at.

Result for the knowledge-base binding: batch 1 = LLM config write + workflow write (parallel), batch 2 = one cascade carrying both new versions plus the redeploy — **two approvals instead of five**. With the credential-safe JSON-Patch endpoints (#1009) batch 1 is the LLM-config PATCH plus the workflow write, which stays a `PUT /workflowstore/workflows/{id}` (the workflow store has no PATCH, and a workflow holds no credential references); the shape is unchanged.

### Behaviour changes worth knowing

* **Stricter than before, on both surfaces.** A mapping now must have a `?version=` on both URIs, name the same kind of resource (authority and store path), and its `oldUri` must be a reference the agent really holds. Anything else is refused whole (`400` over REST, an error result over MCP) and **nothing is written** — previously an unmatched pair was silently ignored and the call reported `cascaded`. A `version` that is not the agent's current one is a `409`, detected before any workflow is written (it used to surface only at the final agent update, after the workflows had already been saved).
* **Role.** `eddi-admin` or `eddi-editor`, the class-level gate every agent-store write already has and the same set the writes it composes require; the MCP tool stays `eddi-admin`.
* **Failures are explicit.** If the agent save (or a later workflow write) fails, the error says the agent was NOT changed and names the workflow versions already written (harmless, unreferenced); a store update that reports no new version is an error, never a guessed `version + 1`. A workflow referenced twice by one agent is written once. The agent's workflow reference may only move to another version of the same workflow (as `updateResourceUri` allows), never to a different workflow.
* **Redeploy** goes through the normal deploy path, so quota, EDIT access and the vault-grant check apply identically; a refused or failed deploy is reported in `deployment`, the documents being already written.

### Security decision

Added to the operator's `WRITE_ENDPOINTS`, gated like every write by `http.post:*`. It is not the agent-document PUT that `planning/operator-write-scope-plan.md` excludes: the body is URI pairs and two flags, the backend rewrites only `workflowStep.config.uri` and the agent's workflow list, and the agent is the stored document written back with that list replaced — so `hitlConfig` and every other field are carried forward unchanged. `AgentCascadeServiceTest` pins this by serializing an agent that carries a gate before and after and asserting every field except `workflows` is equal. Aimed at the operator's own agent it is the same self-ungating hinge as `updateResourceUri`; `self-guard.ts` blocks it (the id is a path segment), with a test. The reasoning, and the residual (a `newUri` naming a same-type resource the caller never created is not ownership-checked), is recorded in [the plan](https://github.com/labsai/EDDI/tree/main/planning/operator-write-scope-plan.md) in its correction style.

### Manager

* `tool-scopes.ts`: `POST /agentstore/agents/{id}/cascade` in `WRITE_ENDPOINTS`; `grantsAgentCascade` so the prompt names the tool only when it was generated.
* `system-prompt.ts`: plan-first, batching and cascade guidance (no `{…}` in it — the body is a Qute template).
* `cascade-preview.ts` + `cascade-summary.tsx`, shown by `RequestPreview`: each mapping as `llm <id> v1 → v2`, plus "Will redeploy to " and what `compatible` does to running conversations. The raw body stays below it; an unreadable or truncated body shows no summary rather than a partial one. New strings are translated in all eleven locales.
* `operator-revision.json` bumped (prompt and allow-list changed): existing operators get the upgrade banner.
* `ui/manager/AGENTS.md` (Platform Operator) and `docs/deployment-management-of-agents.md` ("Landing resource changes in one pass"), `docs/mcp-server.md`, `docs/hitl.md` updated.

### Tests

`AgentCascadeServiceTest` (mappings applied, each document saved once, workflow-then-step mapping keeps the rag step, unknown `oldUri` → nothing written, cross-type / versionless / smuggled-query URIs refused, stale version → conflict before any read, `hitlConfig` and all other agent fields unchanged, redeploy outcomes), `RestAgentStoreCascadeTest` (400/404/409 mapping, EDIT access first, role), the MCP suites adjusted for the stricter validation, and Manager tests for the prompt plan shape, `WRITE_ENDPOINTS`, `self-guard`, and the approval card.

**Files:** [`AgentCascadeService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/agents/AgentCascadeService.java), [`IRestAgentStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/agents/IRestAgentStore.java), [`RestAgentStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/agents/rest/RestAgentStore.java), [`McpAdminTools.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/mcp/McpAdminTools.java), [`tool-scopes.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/operator/tool-scopes.ts), [`system-prompt.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/operator/system-prompt.ts), [`cascade-preview.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/operator/cascade-preview.ts)

***

## feat(configs): PATCH (RFC 6902) on the LLM, HTTP-call and MCP-call stores (2026-10-07)

**Repo:** EDDI (`feat/operator-credential-safe-edits`)

### What changed and why

The Platform Operator could not edit an LLM configuration that has an API key — nearly all of them. It read the document (`"apiKey": "${vault:anthropic-api-key}"`), added a field, and sent the whole thing back with `PUT`; the call was refused because the body carried a vault reference its own configuration did not write (`ConfigReferenceGuard`). The refusal is correct and is unchanged. It also protects against something worse: had the guard allowed the echo, `ApiCallExecutor.buildRequest` resolves `${vault:…}` in the rendered body (`resolveSecrets`, immediately after the guard) and would have sent — and the store would have kept in a new, exportable version — the **plaintext** key.

The way through is to not send what does not change:

* `PATCH /llmstore/llms/{id}?version=N`, `PATCH /apicallstore/apicalls/{id}?version=N` and `PATCH /mcpcallsstore/mcpcalls/{id}?version=N`, with `Content-Type: application/json-patch+json`, apply an RFC 6902 patch to version `N`, validate the result exactly as `PUT` does and store it as a new version (returned in `Location`). `409` when `N` is not the current version, `400` for a failed `test` operation, a path that does not resolve, an unknown operation or a patched document the model rejects.
* A patch never mentions a credential it is not changing, so the stored reference is carried through untouched, and a patch that tries to *introduce* one is refused by `ConfigReferenceGuard` like any other call.
* `McpApiToolBuilder` only mapped `application/json` request bodies, so a PATCH declared as `application/json-patch+json` produced a tool with no body at all. It now maps `application/json-patch+json` too (plain JSON still wins when both are declared) and describes the parameter as an RFC 6902 patch.

### Design decisions

* **One implementation, three stores.** `RestVersionInfo.patch` (access check, version check, read, store write, `Location` — everything `update` does) plus `ConfigJsonPatcher` (parse, apply, strict re-parse). Each store contributes a three-line method and its own pre-write validation, the same function its `PUT` runs.
* **No new dependency.** `jakarta.json` (Parsson) is already on the classpath through `quarkus-rest`.
* **Own path/media type, no collision.** `output` and `dictionary` already have a `PATCH /{id}` with `application/json` and a different body (`PatchInstruction` SET/DELETE); neither holds credential references, so they are untouched. The three stores here had no PATCH, so the same path with `application/json-patch+json` cannot clash. OpenAPI allows one PATCH operation per path, so a store that already has the other PATCH would need a sub-path.
* **`PUT` stays.** It still works for documents without references and is what the Manager editors use.
* **Server-side approval guard.** `SelfUngatingGuard` (the check of an approved call before it executes, on the Slack, MCP and REST approval paths too) refused an llmstore write carrying `toolApprovals` as a key; a patch names the field in a path, which that test missed. It now also refuses a patch whose `path`/`from` names the field, whose `value` carries it, or that uses an operation other than add/replace/remove/test. The REST endpoint itself stays unrestricted: it cannot tell the operator from an admin with the same role.
* **Bounded.** A patch is limited to 256 KiB and 200 operations.

### Files

[`ConfigJsonPatcher.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/patch/ConfigJsonPatcher.java), [`RestVersionInfo.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/rest/RestVersionInfo.java), [`IRestLlmStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/llm/IRestLlmStore.java), [`IRestApiCallsStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/apicalls/IRestApiCallsStore.java), [`IRestMcpCallsStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/mcpcalls/IRestMcpCallsStore.java), [`McpApiToolBuilder.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/mcp/McpApiToolBuilder.java), [`secrets-vault.md`](https://docs.labs.ai/security-and-compliance/secrets-vault.md#editing-a-configuration-that-holds-a-reference-patch-not-echo)

***

## feat(operator): edit configs that hold vault references with PATCH (2026-10-07)

**Repo:** EDDI (`feat/operator-credential-safe-edits`)

### What changed and why

The operator's `llmstore` write grant was unusable for any LLM configuration with an API key: it read the document (`apiKey: ${vault:…}`), sent the whole thing back with `PUT`, and the backend refused the echoed reference. It then had to ask the admin to make the edit by hand. The backend now has `PATCH` (RFC 6902) on `llmstore`, `apicallstore` and `mcpcallsstore` (see the backend entry of this date), and the operator uses it:

* **Allow-list.** `PATCH /llmstore/llms/{id}`, `PATCH /apicallstore/apicalls/{id}` and `PATCH /mcpcallsstore/mcpcalls/{id}` are in `WRITE_ENDPOINTS` (`PATCHABLE_EXTENSION_STORES`). `PUT` stays granted: it still works for documents with no reference.
* **Gate guard.** `gate-guard.ts` reads patch operations. An operation whose `path` or `from` names `toolApprovals`, or whose `value` carries it at any depth (which covers replacing a whole task, `/tasks` or the root), is refused as `carries-gate`. `copy` and `move` are refused outright (`unsupported-patch-op`) — they can carry a stored gate override, or a stored credential reference, somewhere the body does not name. A body that is not a well-formed patch, is truncated, or is unpinned is refused like a `PUT` body. The `llmstore` grant is valid only together with this guard, as before.
* **Approval card.** A patch is listed operation by operation (op, path, value), with the document, the version it applies to and the version it will store; the raw body sits behind a toggle.
* **Prompt.** One delimited section tells the operator to edit with PATCH, never to send back a document it read, which operations exist, that copy/move, a written `${vault:…}` reference and `toolApprovals` are refused, and that a 409 means re-read. It is derived from the granted endpoints.
* **Revision.** `operator-revision.json` is bumped one past main's value (7 when this was written).
* **Snapshot.** `openapi-operations.json` gains the three operations.

### Design decisions

* **Server-side too.** `SelfUngatingGuard` now judges patches the same way `gate-guard.ts` does (see the backend entry), so the rule holds on the Slack, MCP and REST approval paths, not only in the Manager. The REST endpoint itself stays unrestricted (it cannot tell the operator from an admin).
* **`copy`/`move` are not reasoned about, they are refused.** Neither is needed to edit a configuration.
* **`ragstore` is not patchable** because it is not writable; it takes the same three-part change when it is.

### Files

[`gate-guard.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/operator/gate-guard.ts), [`json-patch.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/operator/json-patch.ts), [`tool-scopes.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/operator/tool-scopes.ts), [`system-prompt.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/operator/system-prompt.ts), [`request-preview.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/components/operator/request-preview.tsx), [`blocked-calls.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/operator/blocked-calls.ts), [`operator-revision.json`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/operator/operator-revision.json), [`operator-write-scope-plan.md`](https://github.com/labsai/EDDI/tree/main/planning/operator-write-scope-plan.md)

***

## 🐛 fix(operator): generated tools could not send text/plain bodies — repointing an agent always failed (2026-10-07)

**Repo:** EDDI (`fix/operator-tool-generation`)

### What happened

The Platform Operator called `updateResourceInAgent` (`PUT /agentstore/agents/{id}/updateResourceUri`) to repoint an agent at a new workflow version. The admin approved; the backend answered `400 resourceURI must carry a version`. The operator then reported that its tool "has no field for that URI, only the agent id, the version and a compatible flag". It was right: the endpoint consumes a `text/plain` body (one bare URI), and `McpApiToolBuilder` mapped only `application/json` request bodies. Any other media type was dropped without a trace, so the tool was generated with no way to send its body. Activation's `findMissingEndpoints` only checks that the path exists in the spec, so it passed.

A second observation from the same transcript: asked to "check" a document, the operator issued two unrequested workflow writes without describing them first (three approvals in one turn) and afterwards admitted it.

### What changed

* **`text/plain` bodies are supported** ([`McpApiToolBuilder`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/mcp/McpApiToolBuilder.java)). The body media type is now a small dispatch (`mapRequestBody`): JSON as before, `text/plain` as one declared `requestBody` parameter, sent verbatim with `Content-Type: text/plain`. The parameter description is built from the spec's body description, format and example. An operation offering both is sent JSON. The value is substituted as data into the authored `{requestBody}` placeholder, so `{…}` / `${…}` inside it is never rendered as a template, and a credential reference typed into it is refused by `ConfigReferenceGuard` like one in a JSON body. Request pinning needed no change: `IApiCallExecutor#resolve` and `execute` share `buildRequest`, so the preview and the fingerprint cover the text body.
* **Nothing is dropped silently any more.** An operation that *requires* an input the generator cannot send — a body of another type (`application/zip`, `multipart/form-data`, form-urlencoded) or a required header/cookie parameter — is no longer generated as a tool that can only fail. It is skipped and reported: `ApiBuildResult.unusableEndpoints`, a `WARN` log line, `resources.unusableEndpoints` in the `setup-api` response and `unusableEndpoints` in the API-discovery response. A spec where nothing is usable is rejected with those names. An optional body of an unsupported type is still generated without it. Both `setup-api` and the MCP `create_api_agent` tool call `AgentSetupService.createApiAgent`, which is the only caller of the generator on the provisioning path, so one fix covers both.
* **The OpenAPI spec now describes the two `updateResourceUri` bodies** ([`IRestAgentStore`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/agents/IRestAgentStore.java), [`IRestWorkflowStore`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/workflows/IRestWorkflowStore.java)): description, `format: uri`, example, and the mandatory `?version=`.
* **Manager: activation refuses an unusable allow-list** ([`operator.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/api/operator.ts), [`use-operator.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/hooks/use-operator.ts)). `findUnusableEndpoints` runs the same test against the fetched spec before anything is created, and activation also rolls back on the backend's `unusableEndpoints` report, naming the endpoints either way. A backend that predates the report is covered by the pre-flight.
* **Prompt** ([`system-prompt.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/operator/system-prompt.ts)): a request to check/look/verify/read is read-only — report, then propose any change in plain words (what, which document, from which version to which) and wait for agreement before the gated call; never chain an unrequested write onto a read request; when a write fails, say why before trying another. Rule 2 (describe, then call in the same turn) is amended to apply when the change was asked for. The repoint section now says the URI is the bare plain-text `requestBody` and must carry `?version=`, and that a `409` means a newer version was saved and the document must be re-read, never re-sent with a bumped version. Operator revision bumped.

### The failed `updateWorkflow`

The transcript was not available, so the cause is inferred from the code, not reproduced. The generated `updateWorkflow` tool is `PUT /workflowstore/workflows/{id}?version=N` with the whole document as one JSON string. A write there fails in three ways the operator can hit: **409** (`RestVersionInfo.update` → `ResourceModifiedException`: `N` is no longer the latest version — the admin had just "added it", i.e. saved a newer one, so a PUT against the version the operator had read loses); the **pre-send JSON guard** (`HttpCallToolsProvider.rejectUnparseableBody`: a raw newline or unescaped quote in a long document, refused with "re-send"); and `ConfigReferenceGuard` (a `${vault:…}`/`${vars:…}` reference inside the body — not normally present in a workflow document). The first fits "first attempt failed, second succeeded after a re-read" best. Template-escaping is not the cause: a substituted body is never re-evaluated as a template (pinned by `GeneratedTextBodyExecutionTest`). Nothing systematic to fix in the generator; the operator now has the 409 rule above.

**Files:** [`McpApiToolBuilder.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/mcp/McpApiToolBuilder.java), [`AgentSetupService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/setup/AgentSetupService.java), [`RestApiCallsStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/apicalls/rest/RestApiCallsStore.java), [`McpApiToolBuilderTextBodyTest.java`](https://github.com/labsai/EDDI/tree/main/src/test/java/ai/labs/eddi/engine/mcp/McpApiToolBuilderTextBodyTest.java), [`GeneratedTextBodyExecutionTest.java`](https://github.com/labsai/EDDI/tree/main/src/test/java/ai/labs/eddi/modules/apicalls/impl/GeneratedTextBodyExecutionTest.java), [`mcp-server.md`](https://docs.labs.ai/protocols-and-integration/mcp-server.md), [`architecture.md`](https://docs.labs.ai/architecture-and-concepts/architecture.md), [`operator-revision.json`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/operator/operator-revision.json)

***

## 🐛 fix(operator): a vault key goes in by name, and a call that cannot succeed is never put up for approval (2026-10-07)

**Repo:** EDDI (`fix/operator-vault-key-name`)

### What happened

An admin asked the Platform Operator for an agent on "the anthropic key available". As the admin reported it, the operator copied `${vault:anthropic-api-key}` out of its own LLM config into the `setupAgent` body and was refused (the report says before the approval step; that stage was not reproduced, and from the code a gated call takes the same path every time); told the admin that typing the reference themselves would make it acceptable (false); proposed the call, which the admin approved, and only then was it refused; and finally sent the admin to build the agent by hand. The refusal after an approval is confirmed from the code and is what this entry fixes.

### Why

`ConfigReferenceGuard` refuses any `${vault|eddivault|connection|caller:…}` in a rendered request value that the configuration did not itself write. That is the right control and is unchanged — it is about where a reference came from, not who typed it, so no amount of retyping can satisfy it. Two things around it were wrong:

* **The operator was taught to write references.** Its prompt said to pass `${vault:key-name}` in `apiKey`. The supported path was already there: `vaultKeyName` takes a bare name, leaves `apiKey` empty, requires the entry to exist, and still goes through the deploy-time grant check (`createApiAgent` already carries the same field).
* **The approval was spent before the refusal.** Gate time resolves each gated http call to pin it, which runs the same request build as execution, guard included. But pinning is never allowed to fail a pause, so the guard's refusal was swallowed as "approved unpinned" and the approver was shown a card for a call that was refused the moment they approved it.

### What changed

* **Gate-time refusal.** `ConfigReferenceGuard` now throws its own `ConfigReferenceRefusedException` (still an `IllegalArgumentException`). `ApiCallExecutor.resolve` lets it through unwrapped for a call whose resolution is what execution builds, and `ToolLoopRunner` drops such a gated call from the pending batch before the pause, returning the guard's message to the model as that call's tool result (trace `credential_reference_refused`). Other gated and ungated calls in the batch are unaffected. Any other resolve failure, and a call that can diverge between resolve and execute (pre-request property instructions, batching, retries), still pauses and is approved unpinned.
* **Clearer message.** The refusal now says retrying with the same text cannot succeed whoever typed it, and what to do instead, generically: send the credential's name in a field the endpoint documents (for example `vaultKeyName`), or edit with a partial update that does not repeat it. The guard still knows no endpoint.
* **Operator prompt** (`system-prompt.ts`, revision bumped): a "Credentials in tool-call bodies" section — never put a `${vault:…}`/`${connection:…}`/`${caller:…}` reference in any tool-call body whoever typed it; use `vaultKeyName` with a bare name and an empty `apiKey`; it cannot read the vault so it never claims a key exists; a new agent is not on a restricted key's grant, so its first deploy is refused with `VAULT_GRANT_MISSING` and an administrator grants it in the Manager's grant dialog (the vault-grant UX), while the operator never sets `grantReferencedSecrets`; on a refusal over a reference it explains the rule and, where the endpoint has a key-name field or the store a partial update, retries that way rather than sending the admin to do it by hand. The sentences that taught the opposite in the setup, cheatsheet and "making changes" sections are amended, not duplicated.
* **No approval-card flag.** A body carrying a credential reference can no longer reach the card for any call the operator's generated tools produce (they are always pinnable), so an `escalation-flags.ts` warning would be dead on that surface and would cost translations in every locale.

### Docs

[`secrets-vault.md`](https://docs.labs.ai/security-and-compliance/secrets-vault.md#where-vault-references-work) (the provenance rule is about origin, not author; the `vaultKeyName` path and its grant consequence) and [`hitl.md`](https://docs.labs.ai/conversations-and-orchestration/hitl.md#request-pinning--approval-binds-to-a-request-not-a-tool-name) (gate-time refusal).

**Files:** [`ConfigReferenceGuard.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/apicalls/impl/ConfigReferenceGuard.java), [`ConfigReferenceRefusedException.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/apicalls/impl/ConfigReferenceRefusedException.java), [`ApiCallExecutor.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/apicalls/impl/ApiCallExecutor.java), [`ToolLoopRunner.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/ToolLoopRunner.java), [`system-prompt.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/operator/system-prompt.ts), [`operator-revision.json`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/operator/operator-revision.json)

***

## ✨ feat(vault): new agents that use a restricted secret — say why a deploy is refused, and grant in one step (2026-10-06)

**Repo:** EDDI (`feat/vault-grant-ux`) · plan: [`planning/vault-grant-ux-plan.md`](https://github.com/labsai/EDDI/tree/main/planning/vault-grant-ux-plan.md)

### Why

A vault secret's grant (`allowedAgents`) lists agent ids, and an id exists only after the agent is created. So with `eddi.vault.grant-enforcement=enforce` (the default) **every new agent that uses a restricted secret fails its first deploy**, through every route: the Manager wizard, the setup API, MCP, an import, the Platform Operator's activation. The check is right and stays. What was wrong is how it met the user: the reason went to the server log only, the API answered `{"status":"ERROR"}`, and a retry (the setup API, the operator) created another agent that failed the same way.

### What changed (backend)

* **The refusal reason is kept and returned.** `VaultGrantGate.check()` returns a structured `GrantCheck` (`mayDeploy` is a thin wrapper, unchanged in behaviour). `AgentFactory` stores a `DeploymentFailure` (`VAULT_GRANT_MISSING` with the secret names and the exact grant call, or `DEPLOYMENT_FAILED` with a fixed message that points to the server log, since a cause's message can carry a credential or an internal path) next to the ERROR status; the next successful deploy clears it. The waited deploy returns it as `failure` (and `error`), `deploymentstatus?format=detailed` returns it to a caller with EDIT, and the log line names each secret, why a new agent hits this, and the fix.
* **An unchecked exception while building an agent no longer leaves it stuck IN\_PROGRESS** until a restart; it ends in ERROR with the cause.
* **Preflight:** `GET /administration/{env}/deploy/{agentId}/preflight?version=` (EDIT) lists the ungranted secrets before deploying; grant ids only for admins, counts for editors.
* **Append one agent to a grant:** `POST /secretstore/secrets/{tenant}/{key}/grant/agents/{agentId}` (`eddi-admin`, `dryRun`). Idempotent, never touches a `*` grant, compare-and-set with retry so concurrent appends both land, audit-ledger entry per change (`VaultGrantService`).
* **Setup API:** `grantReferencedSecrets` (admin only, 403 otherwise) grants the new agent between create and deploy; `SetupResult` gains `deploymentFailure` and `grantedSecrets`. Without the flag a refused setup now names the secret and tells the caller to grant and redeploy *this* agent instead of running the setup again.
* **MCP:** `deploy_agent` returns the failure code, secret names and fix with a note that a human administrator applies it. No MCP tool can grant, and the flag is not on any MCP tool (asserted by `McpDeployGrantFailureTest`).

**Files:** [`VaultGrantGate.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/secrets/VaultGrantGate.java), [`VaultGrantService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/secrets/VaultGrantService.java), [`DeploymentFailure.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/model/DeploymentFailure.java), [`DeploymentPreflight.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/model/DeploymentPreflight.java), [`AgentFactory.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/runtime/internal/AgentFactory.java), [`RestAgentAdministration.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/RestAgentAdministration.java), [`RestSecretStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/secrets/rest/RestSecretStore.java), [`AgentSetupService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/setup/AgentSetupService.java), [`McpAdminTools.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/mcp/McpAdminTools.java). Docs: [`secrets-vault.md`](https://docs.labs.ai/security-and-compliance/secrets-vault.md#new-agents-always-need-adding), [`agent-sync-guide.md`](https://docs.labs.ai/conversations-and-orchestration/agent-sync-guide.md).

### Design decisions

* **The waited deploy still answers 200, not 409.** Every other failed waited deploy answers 200 with the outcome in the body, all in-process callers and quarkus-eddi read that body, and `failure` carries everything a 409 would. See the plan, §5.1.
* **Granting stays an explicit administrator action** on every path (a dialog, an admin-only flag, an admin-only endpoint); enforcement and its default are unchanged.

***

## ✨ feat(manager): grant-then-deploy dialog, restricted-key badge, and an operator that never leaks an agent (2026-10-06)

**Repo:** EDDI (`feat/vault-grant-ux`), `ui/manager`

### What changed and why

* **One shared grant step wherever the Manager deploys** (`useDeployWithGrants` + `GrantRequiredDialog`): save-and-deploy, the agent card, agent detail, the resource page's deploy action and the agent wizard. It runs the preflight, then (for an administrator) a dry-run append, the append, and a waited deploy. A deploy that still comes back with `VAULT_GRANT_MISSING` reopens the same dialog, once. Non-administrators get the explanation and a copyable request for an admin. A failed deploy now shows its reason, with a **Fix** button for a missing grant. The agent wizard creates with `deploy: false` and settles grants before the first deploy, so a new agent never shows a failed first deploy.
* **Secret picker:** a lock badge "Restricted to N agents" on a restricted key, and a "not granted yet" note when the editor knows its owning agent (`useOwningAgent`, set by the resource page and Agent Studio).
* **Platform Operator:**
  * activation no longer leaks the created agent when its deploy fails. The old `assertProvisioned` threw before the rollback `try`.
  * a restricted model key is granted inside activation, on the same agent, and a retry reuses it.
  * operator agents the Manager did not register are listed with Adopt, Fix and Remove. The marker is `[eddi-platform-operator]` on the descriptor.
  * the preflight endpoint is on the operator's read allow-list. The append-grant endpoint is deliberately not, because no LLM may widen a grant. The prompt explains `failure`. The operator revision moved from 2 to 3.
* `ui/manager/src/test/mocks/openapi-operations.json` is refreshed from this branch's backend (6.6.0, the two new operations).
* `useDeployWithGrants` refreshes the agent queries once a deploy has an outcome (deployed, refused or cancelled), not on the way out of a deploy request that threw: nothing changed on the backend, and that refetch landed in the after-test toast drain on slow CI runners (`resource-detail-save-not-live.test.tsx` failed there about every other run).
* The shared "saved — not live yet" toast (`lib/save-not-live-toast.ts`, added on main meanwhile) deploys through the grant flow too, so the studio, workflow and agent-section saves ask about a restricted key before deploying.

### Still open

* `pages/group-wizard.tsx` and `pages/workforce/workforce-wizard.tsx` still create member agents with `deploy: true`. Their refused deploys now carry the reason, but they do not yet go through the grant dialog.
* Re-enabling a paused operator (`reactivateOperator`) deploys without the grant dialog. If that deploy is refused, the operator screen's banner shows the reason and a Fix button.

**Files:** [`use-deploy-with-grants.ts`](https://github.com/labsai/EDDI/tree/main/ui/packages/app-kit/src/hooks/use-deploy-with-grants.ts), [`grant-required-dialog.tsx`](https://github.com/labsai/EDDI/tree/main/ui/packages/app-kit/src/components/secrets/grant-required-dialog.tsx), [`secret-key-picker.tsx`](https://github.com/labsai/EDDI/tree/main/ui/packages/app-kit/src/components/shared/secret-key-picker.tsx), [`use-operator.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/hooks/use-operator.ts), [`operator-discovery.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/api/operator-discovery.ts), [`unregistered-operators.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/components/operator/unregistered-operators.tsx). Docs: [`architecture.md`](https://docs.labs.ai/architecture-and-concepts/architecture.md#a-restricted-model-key-and-operators-the-manager-did-not-register).

***

## ✨ feat(manager): group and Workforce wizards and operator re-enable go through the vault grant flow, one question per key (2026-10-06)

**Repo:** EDDI (`feat/vault-grant-wizards`, stacked on `feat/vault-grant-ux`), `ui/manager`

### Why

Under `eddi.vault.grant-enforcement=enforce` an agent that uses a restricted vault key is refused at deploy until it is on the key's grant, and a brand-new agent never is. The agent wizard already created with `deploy: false` and deployed through the grant dialog; three other Manager paths still created or deployed in one step and so hit a failed first deploy: the group wizard (members and moderator), the Workforce wizard (advisors), and re-enabling a deactivated Platform Operator (`reactivateOperator` called a plain `deployAgent`).

### What changed

* **Batch entry point** `runDeployManyWithGrants` / `useDeployWithGrants().deployMany` in [`use-deploy-with-grants.ts`](https://github.com/labsai/EDDI/tree/main/ui/packages/app-kit/src/hooks/use-deploy-with-grants.ts): preflights every target in parallel, merges the grant issues by `(tenantId, keyName)` (the raw reference when it is not a plain vault reference), opens **one** dialog listing each key once with every agent that needs it, then deploys each target with the waited deploy. The tail (deploy, one second chance on an unexpected `VAULT_GRANT_MISSING`, outcome mapping) is now shared by the single and the batch flow (`deployAndSettle`). Returns a per-target outcome; a transport error on one target is that target's `failed`, not a throw that hides the others.
* **Dialog** ([`grant-required-dialog.tsx`](https://github.com/labsai/EDDI/tree/main/ui/packages/app-kit/src/components/secrets/grant-required-dialog.tsx)): `GrantRequest.agents` / `GrantIssue.agentIds` make it show several agents per key (own title, key line, question and non-admin text). One confirmation appends every listed agent to every key it needs; the copy-for-an-admin request lists all the calls. A one-agent request renders exactly as before.
* **Group wizard:** members and moderator are created with `deploy: false`, then deployed together through the batch flow before the group is saved. The per-card "create agent" buttons deploy through the single flow. A member that is created but not live keeps a `pendingDeploy` marker, so the next Create deploys it instead of treating it as done.
* **Workforce wizard:** advisors are created with `deploy: false` and deployed as one batch before the group is saved; advisors a previous attempt created but could not deploy are remembered (`pendingDeployRef`) and deployed on Try Again.
* **`reactivateOperator`** goes through `runDeployWithGrants` like activation: a cancelled grant or a failed deploy is an error and the operator stays off; the config is written only after a READY deploy.
* New `resolveSetupVersion` (agent-setup.ts) and `describeUndeployed` (deploy-outcome.ts); 8 new i18n keys in all 11 locales.

### Design decisions

* **Cancel deploys nothing, for the whole batch** (including members that needed no grant) and the wizard does not save the group around members that are not live. It says the agents were created, that Create again retries the grant and deploy, and that they can be deployed from their agent pages. The wizards stop rather than report success.
* **One confirmation, an append per (key, agent).** The backend's atomic append (compare-and-set) is per agent; replacing a key's whole list with one PUT from here would drop an agent an administrator added a moment ago. "Allow every agent" is still a single PUT per key. Dry runs run first, as for one agent.
* **Targets are deployed one after another**, not in parallel: a second-chance dialog would replace the first, and a waited deploy is not something to fan out.
* **Platform Operator prompt and allow-list unchanged** (no endpoint or behavior the operator describes changed), so `operator-revision.json` is not bumped.

**Tests:** `use-deploy-many-with-grants.test.tsx` (merge per key, one dialog for N agents, an append per agent only after confirm, cancel deploys nothing, second chance per agent, failed target isolated), `group-wizard-grants.test.tsx`, `workforce-wizard-grants.test.tsx` (created undeployed, no deploy before the grant, cancel then retry), and reactivation cases in `use-operator-grants.test.tsx` / `operator.test.ts`. Each was mutation-checked by reverting the behavior it guards.

***

## 🐛 fix(manager): agent detail saves on Save, not on every edit — with review, discard and Save & leave (2026-10-06)

**Repo:** EDDI (`fix/manager-agent-detail-explicit-save`)

### What changed and why

**Agent detail no longer auto-saves.** Every toggle, select and (after a 600 ms debounce) every keystroke in the agent detail page's ten config sections — workflows, A2A, security, capabilities, user memory, memory policy, session management, conversation review, HITL, channels — PUT the whole agent document on its own. Each PUT creates a new agent version, so one sitting of edits made a dozen versions, there was no way to back out of a change, and the page behaved unlike every other editor in the Manager. It now works like the workflow and resource editors:

* Sections edit one page-level **draft**; nothing reaches the backend until **Save**, which writes it as one version and follows it ("Saved as version N"). **Discard** (confirmed) restores the stored version. Ctrl/Cmd+S saves.
* **Seeing what changed:** an *Unsaved changes* badge in the header, a **Modified** pill on every section whose fields differ from the stored version, a floating bar at the bottom of the (long) page with the count, Discard and Save, and **Review changes** — a diff of the draft against the stored version (`ResourceDiffViewer`).
* While there are edits, the version picker and Deploy/Undeploy are disabled (deploying acts on the *saved* version; the tooltip says so).
* A **409** keeps the edits, moves the page onto the newer version and re-applies only the blocks the user changed (`applyChangedFields`), so another client's change survives the next Save.
* The debounce timers and the per-agent save queue that existed only to make auto-save survivable are gone (`use-agent-section-save.ts` removed).
* Merged with #967: Save shows its "Saved as vN — not live yet" toast with the Deploy action (once per Save instead of once per edit); removing a workflow no longer opens a confirmation, since it only changes the draft and Discard restores it; #967's rename-in-place, live-version header, workflow names and accessibility changes are kept.

**Leaving with unsaved edits.** The app holds in-app navigation with one router blocker and one prompt (`NavigationGuardDialog`, #968); a page only calls `useUnsavedChangesGuard`. This adds an optional `onSave` to that hook: when every dirty page can save on demand, the prompt also offers **Save & leave** and lets the navigation through only once the save landed. Agent detail and the workflow editor pass it. (This branch first carried its own app-wide guard, written while the app was still on `<BrowserRouter>`, then a per-page prompt after #939; both were dropped as #939 and #968 landed.) While a placeholder document from the previous version is on screen (#939's `configPending`), the draft takes no edits.

**Also:** the "compat. gen 1" badge left the monospace id line, where it inherited the code font and duplicated the version chip; it now sits beside the version picker at the same height as "Generation 1", with the explanation in its tooltip. The secret access ("Who may use …") dialog's body had no padding against the dialog border; it now has the `p-5` every other dialog body has.

**Dependency:** `source-map-js` 1.2.1 → 1.2.2 in `ui/manager/.ds-sync/package-lock.json` (CVE-2026-93749, HIGH — `Trivy Filesystem Scan`). Edited by hand rather than via `npm install`, which on Windows prunes the Tailwind wasm dependencies from the lock.

### Design decisions

* One draft of the whole document rather than per-section drafts: one Save, one version, one diff, and the same shape as the workflow editor.
* Save & leave lives in the shared guard and prompt, not on the agent page, so any editor whose save resolves to success can opt in with one argument.

**Files:** [`agent-detail.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/pages/agent-detail.tsx), [`agent-config-sections.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/components/editors/agent-config-sections.tsx), [`agent-draft.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/agent-draft.ts), [`unsaved-changes-dialog.tsx`](https://github.com/labsai/EDDI/tree/main/ui/packages/app-kit/src/components/ui/unsaved-changes-dialog.tsx), [`use-unsaved-changes-guard.ts`](https://github.com/labsai/EDDI/tree/main/ui/packages/app-kit/src/hooks/use-unsaved-changes-guard.ts), [`navigation-guard-dialog.tsx`](https://github.com/labsai/EDDI/tree/main/ui/packages/app-kit/src/components/shared/navigation-guard-dialog.tsx), [`edit-grant-dialog.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/components/secrets/edit-grant-dialog.tsx), [`compatibility-generation-badge.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/components/agents/compatibility-generation-badge.tsx)

***

## feat(llm): recovery observability, resume-path parity and the resilience guide (2026-10-06)

**Repo:** EDDI (`feat/llm-resilience-observability-docs`, the capstone of the LLM turn-resilience series, on top of `feat/llm-circuit-breaker` and `feat/turn-idempotency-structured-errors`)

### What changed and why

R11, R12 and R13 of the LLM turn-resilience plan ([`planning/llm-turn-resilience-plan.md`](https://github.com/labsai/EDDI/tree/main/planning/llm-turn-resilience-plan.md)), and the plan's status block. The seven items before it each added a recovery; this one makes them readable and keeps the HITL resume path from being the one place they do not apply.

**R11 - observability**

* **Resolved model names.** `audit:model_name`, the cascade trace's `model` and the circuit-breaker key recorded the literal `${vars:gemini-model}` (the registry resolves global variables late, after the task has recorded its name). `LlmTask.resolveModelName(params, type, resolver)` and the cascade's `resolveVariables` now resolve `${vars:...}` through `GlobalVariableResolver` for everything that records or keys on the model, including the new `eddi.llm.failure` tag. An unresolvable reference (unknown variable, resolver error) keeps the configured text instead of failing the turn over a label. The raw template is not kept in a separate field (not trivial: the audit has one name slot).
* **One structured line per recovery.** New `LlmRecoveryLog` (`modules/llm/impl`) writes `LLM recovery conversationId=... agentId=... class=... action=... outcome=... attempt=... durationMs=...` at INFO, once per repair, same-model re-ask, cascade escalation, skipped (open-circuit) model and served fallback. The call site that performs the action emits it; the failures that triggered it keep their own WARN/ERROR lines. The ad-hoc INFO lines it replaces: the `FormatRetryRunner` "Re-asking the same model" line (now written from `ReaskListener.onReaskDone`, where outcome and duration are known), the cascade's WARN for a skipped circuit and its INFO "escalating: confidence" line (kept at DEBUG, it carries the scores). Values are stripped of whitespace and control characters.
* **Metrics gap-fill** (only what was missing): `eddi.llm.recovery` gains `action=repair` (a reply that parsed only after fence stripping or extraction), `action=circuit_skip`, and `action=escalate` for every escalation reason (`timeout`, `error`, `retryable_error`, `low_confidence`, besides the existing `invalid_output`); `eddi.llm.failure{class,model}` is now also counted for a failed single-model task (a cascade still counts per step, and its overall failure is not counted twice; the circuit's own refusal and control flow such as a HITL pause are not model failures). `eddi.llm.output` and `eddi.llm.turn.deadline.exceeded` already existed. The tag keys of `eddi.llm.recovery` stay `action, outcome, trigger` so Prometheus sees one consistent meter.

**R12 - resume parity.** `LlmTask.executeResume` now applies, to the resumed final answer: the `onError: fallback` guard (the approved tools already ran exactly once through the journal, so only the answer is replaced), `responseValidation` actions (it applied none before), and the R5 same-model re-ask of an empty, invalid-JSON or schema-mismatch reply. The re-ask is one model call over the resumed transcript through `reaskFinalAnswer`; `ToolLoopResumer` records that transcript on a new `ExecutionResult.resumeTranscript` (the loop's final messages without the answer), so no tool can run twice. A task that may re-ask is buffered on resume, as on a live turn. **Not applied on resume, and why:** the circuit breaker (the resume pins the model whose loop paused and settles no ticket), the cascade (the escalation decision was made before the pause), truncation and context-too-long re-asks (the loop reports no finish reason; shrinking after tools ran would replay them), and a turn deadline (a resume starts a turn without one). A resume that recorded no transcript cannot re-ask and goes to `fallbackAction`. Parsing and shape validation (R3, R4) were already shared.

**R13 - docs.** New [`docs/llm-resilience.md`](https://docs.labs.ai/agent-configuration/llm-resilience.md): failure taxonomy, recovery order, the full configuration surface with defaults (verified against the config classes), a complete `langchain.json` recipe for a JSON agent behind a 60-second caller, how to read step keys, trace, log line and metrics, the resume table and the known limits. [`langchain.md`](https://docs.labs.ai/agent-configuration/langchain.md), [`model-cascade.md`](https://docs.labs.ai/agent-configuration/model-cascade.md) (new "Cascade as failover") and [`metrics.md`](https://docs.labs.ai/deployment-and-infrastructure/metrics.md) link to it and no longer say the resume path has no recovery. `docs/SUMMARY.md` lists it.

**Platform Operator.** An admin will ask "why did my agent answer 'Sorry...'" and "why is model X skipped". The operator prompt's docs map now names `llm-resilience`, and its how-to-work section says which step keys to read (`llm:fallback`, `llm:error`, `llm:output:outcome|reason`, a trace status `circuit_open`) and that the log carries one `LLM recovery` line per recovery. No allow-list change (it can already read conversations, logs and the audit trail). `operator-revision.json` 2 to 3.

**Plan status.** The status block of the plan now marks R1 to R16 implemented with the branch and PR of each, where the implementation differs from the plan text, and the known gaps below.

### Review fixes on the stacked PR

* **Fallback turns in the model's history.** The step-wide `llm:fallback` flag dropped the whole output of a step, including another LLM task's good answer in the same step. Now only output items marked `fallback: true` are dropped (`ConversationOutputExtractor.withoutFallbackItems`, both history paths); a flagged step with no marked item (a `postResponse`-rendered fallback) is still dropped whole, since nothing says which text it wrote.
* **Configured `prompt` after a fallback turn** replaced the whole merged user message and lost the fallback turn's unanswered question; it now replaces only the current input's contents.
* **Re-ask budget** now spends from the turn deadline (plain, cascade, tool-mode and resume re-asks): a re-ask no longer starts with less than `minAttemptMs` left. A cascade whose time left is already inside the reserve gives step 0 the remaining turn time instead of a 1 ms timeout.
* **Interrupt on the deadline-bounded retry path** is restored on the thread and surfaces as `LifecycleInterruptedException` instead of being classified `UNKNOWN` (which let a cancelled step pay a second provider call).
* Keyed streaming requests now forward `llm_retry`; dashboard panels in the cascade row no longer overlap and the circuit-transition series is a `rate`.
* Not changed: the Manager editor's selectors still omit `retry` (types only, as documented): adding it is UI work with three i18n gates and is a follow-up.

### Design decisions

* One helper rather than six `LOGGER.infof` calls, so the line has one shape and tests can assert "exactly one line per recovery" through an observer hook (`LlmRecoveryLog.observer`, null in production).
* The retry line is written by a `ReaskListener` default method (`onReaskDone`), not by `FormatRetryRunner`, because only the caller knows the conversation and agent ids.
* `ExecutionResult` grew a fifth component rather than reusing `toolExchange`: the exchange is "tools only" by contract, the resume transcript is "everything the model saw".
* `circuit_skip` is a fifth `action` value next to the plan's four: it is a recovery (the engine avoided a call) and an operator counting escalations should not have to subtract it.

### Known gaps and follow-ups

* The streaming path is still not bounded by the turn deadline and uses the plain backoff.
* R15's `onInvalidJson: "retry"` with `maxRetries: 0` warning is not implemented, and its `onError` check still reads the field reflectively.
* The R14 WireMock cascade IT was not written.
* No dashboard panel dedicated to `action=repair` / `circuit_skip`; the full-metrics dashboard has pre-existing duplicate panel ids (158/159, 168 to 172) on `main` that this change leaves alone. Ids 174 to 181 (this series) are unique.
* Manager UI has types only for the new task fields.

***

## fix+feat(migration): carry 5.x LLM defaults over, unencoded URL hosts, deploy-time compatibility check (2026-10-06)

**Repo:** EDDI (`feat/v5-compat-deploy-checks`)

### What changed and why

Findings from a production 5.x to 6.x migration: valid 5.x configuration that 6.x accepts, deploys READY, and then handles differently on the first real turn.

* **JSON mode (#7).** A migrated LLM task with `parameters.responseFormat: "json"` and no `convertToObject` gets `convertToObject: "true"`; `responseFormat` stays. Without it the model wrapped its JSON in a Markdown code fence.
* **Tools default (#8).** A migrated LLM task without `enableHttpCallTools` / `enableMcpCallTools` gets both written as `false`, which is what 5.x did (6.x defaults them to `true`, turning a chat task into a tool-calling one, which on Gemini also silently drops JSON mode). One transform, `LegacyDocumentMigrations.llm()`, runs in the V6 collection sweep (`llms` and `llms.history`, a database 5.x wrote) and in the import of a ZIP whose workflow still references the 5.x LLM authority. Tasks authored in 6.x are never touched. Idempotent.
* **Templated URL host (#9).** `https://{properties.apiHost}` was rendered as `api%2Eexample%2Ecom` because every substituted value was percent-encoded as a path segment. The authority is now rendered separately and keeps letters, digits, `.`, `-`, `_`, `:`; `/ @ ? #`, spaces and `%` are still encoded, so a value cannot add a path, userinfo or query to the host. The resolved URL is unchanged for the SSRF checks (private/loopback refused with `eddi.security.ssrf-protection.enabled`, cloud metadata always).
* **Deploy-time compatibility check (#6, #11).** `AgentCompatibilityLint` runs when an agent is deployed, reads its LLM, API-call, property-setter and output configs, and reports: a template in an LLM `apiKey` (task, cascade steps, judge model; vault/vars/connection references are fine), `responseFormat: json` without `convertToObject`, `convertToObject` with tools on a provider that cannot combine them (from `JsonResponseFormatPolicy`), strings that do not parse with the restricted runtime Qute engine, and left-over `[[${...}]]` Thymeleaf. Warnings only: one WARN line per finding, and a new additive `warnings` list on each entry of the deployment-status listing (`AgentDeploymentStatus`, `IAgent.getDeploymentWarnings()`). It never changes the status or blocks a deployment, and a failing lint is swallowed.
* `docs/upgrading-from-5x.md` section 6.1: every behaviour change with before/after config.

### Design decisions

* The 5.x origin of an LLM document is known, not guessed: the V6 sweep runs once over a database 5.x wrote, and an import counts as 5.x only when the workflow names its LLM step by the 5.x authority. A v6 document with an absent flag keeps meaning "on".
* The lint does not report a templated URL host (#9, now supported) or `fromObjectPath` naming `responseObjectName` (#5, handled in the engine).
* `LlmTask.TEMPLATE_SKIP_PARAMS` and `CONFIG_REF_MENTION` became public so the lint shares the engine's own definition of "credential" and "reference".
* A templated host is a trust decision: whoever controls the substituted value chooses where the call goes. Documented; the metadata address stays refused regardless.

### Follow-ups

* `GET /administration/preflight` for an unmigrated 5.x database (out of scope here).
* Showing `warnings` in the Manager's deployment view.
* The Postgres backend has no 5.x data, so the sweep has no Postgres twin; only ZIP import applies.

**Files:** [`LegacyDocumentMigrations.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/migration/LegacyDocumentMigrations.java), [`V6RenameMigration.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/migration/V6RenameMigration.java), [`RestImportService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/backup/impl/RestImportService.java), [`ApiCallExecutor.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/apicalls/impl/ApiCallExecutor.java), [`AgentCompatibilityLint.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/compat/AgentCompatibilityLint.java), [`CompatibilityRules.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/compat/CompatibilityRules.java), [`upgrading-from-5x.md`](https://docs.labs.ai/deployment-and-infrastructure/upgrading-from-5x.md)

***

## fromObjectPath now keeps an object or list, so an LLM response object can be stored as a property (2026-10-06)

* Repo: EDDI, branch `fix/fromobjectpath-llm-response-object`.
* **Symptom (reported from a production 5.x deployment moved to 6.x).** An LLM task with `responseObjectName: "aiOutput"`, `convertToObject: "true"` and a `postResponse` property instruction `{ name: "aiOutputObject", fromObjectPath: "aiOutput", convertToObject: true }` left `{properties.aiOutputObject.htmlResponseText}` empty.
* **Root cause.** The path itself resolved fine: `PathNavigator` reads the template data, which the LLM task fills with the converted response (a Map) under `responseObjectName`. The loss was in `PrePostUtils.executePropertyInstructions`: only a `String` was carried forward, and every other value reached through `fromObjectPath` fell into an `else` branch that replaced it with `""`. A Map or List therefore became an empty-string property. The same applied to httpcalls and MCP calls, which share the helper, but their responses are usually strings that `convertToObject` parses, so it went unnoticed. Workaround that worked: `valueString: "{json:serialize(aiOutput)}"` with `convertToObject: true`.
* **Fix.** An object or list found through `fromObjectPath` is now stored as it is (`PrePostUtils`). Strings (including `convertToObject` parsing), numbers and booleans behave as before, a path that resolves to nothing still stores an empty string, and `scope: "secret"` still refuses a non-string value. Tests: `PrePostUtilsFromObjectPathObjectTest`. Docs: `docs/langchain.md`, `docs/httpcalls.md`.
* **Follow-up (not done).** A number or boolean read through `fromObjectPath` is still stored as `""`; changing it is a separate compatibility decision.

***

## Idle sweep no longer loads every open conversation; bulk "end inactive conversations" (2026-10-06)

**Repo:** EDDI | **Branch:** `fix/idle-conversation-sweep-oom`

**Problem.** `AgentDeploymentManagement.endOldConversationsWithOldAgents` (the daily idle sweep, first run five minutes after boot) called `loadActiveConversationMemorySnapshot`, which deserializes every open conversation of an agent version in full. A production 5.x deployment with tens of thousands of open conversations of several hundred KB each ran out of heap shortly after boot. `GET /conversationstore/conversations/active/{agentId}` had the same shape, and so did `POST /administration/{env}/undeploy/{agentId}?endAllActiveConversations=true`, which lists through it.

**What changed.**

* `IConversationMemoryStore` gets `loadOpenConversationActivity` (keyset-paged projection: id, state, agent, version, last-interaction time), `loadConversationActivity` (the same for one id) and `endIdleConversations` (the bulk end), implemented for MongoDB and PostgreSQL. The last-interaction time is computed by the database as the newest `conversationSteps[].workflows[].lifecycleTasks[].timestamp`, the same quantity the sweep always aged conversations by. MongoDB converts each timestamp with `$convert`, because the persistence mapper stores dates as ISO-8601 strings while older documents can hold BSON dates or epoch milliseconds; PostgreSQL reads numeric epoch millis and ISO strings.
* The idle sweep reads batches of 200 projections, re-checks one conversation's projection (not a full load) right before ending it, and keeps every existing rule: `AWAITING_HUMAN` is spared, the agent descriptor is the fallback age, "cannot prove it is idle" never ends a conversation, state compare-and-set, the `LocalDate` arithmetic. It now also records the end reason `idle` (new `IConversationService.END_REASON_IDLE`), best-effort.
* `RestConversationStore.getActiveConversations` is built from the projection, so `/active/{agentId}` no longer loads a conversation in full (contract unchanged). Undeploy-with-end lists straight from the store projection (`RestAgentAdministration.openConversationsOf`), skipping the `/active` listing's per-conversation descriptor read for a last-interaction time it does not use.
* New `POST /conversationstore/conversations/end-inactive?inactiveForDays=N[&agentId=...][&dryRun=true]`, `eddi-admin` only (like the bulk delete; there is no REST role hierarchy): ends every `READY` conversation idle for longer than N days with end reason `idle`, returns `{"count": n, "dryRun": bool}`, validates `inactiveForDays >= 1`, and writes an audit-ledger entry. MongoDB: one `updateMany` with a server-side `$expr`; PostgreSQL: batched `UPDATE` (500 rows per statement and transaction) so a 22 GB backlog does not become one transaction.
* `undeployThisAndAllPreviousAgentVersions` no longer aborts on the first failing or refused version: every version is attempted, then a `500` naming the failed versions (or a `409` for refusals) is returned.

**Design decisions.**

* *Descriptors are not touched by the bulk end.* Retention deletes ended conversations by the descriptor's `lastModifiedOn`; rewriting descriptors would be one write per conversation (defeating the single operation) and would restart the retention clock at "now". The existing sweep never touched descriptors either, so retention keeps counting from the last interaction for both. The listing re-derives state from the conversation, so it shows `ENDED` immediately. Consequence, documented: a conversation idle for longer than the retention is deleted by the next retention run.
* *The bulk end only touches `READY`.* `AWAITING_HUMAN` needs the HITL-aware end (timeout schedule, bookmark, oversight audit), `IN_PROGRESS` is running, and a conversation with no timestamp cannot be proven idle. Conversation-state cache entries (30 s TTL) are not invalidated, as for the sweep.
* *The sweep stays per-conversation* (projection + compare-and-set) rather than calling the bulk method, because it must keep the descriptor age fallback and the `AWAITING_HUMAN` accounting; both use the same server-side last-interaction computation.
* *Undeploy schedules:* `disableSchedulesForAgent` is already gated on the call leaving no deployed version of the agent in the environment (main already had this, with tests); nothing to change.
* *Platform Operator:* the new endpoint is a destructive deployment-wide bulk mutation, so it is deliberately not added to the operator allow-list; no operator revision bump.

**Operators.** Anyone who disabled the sweep with `maximumLifeTimeOfIdleConversationsInDays=-1` because of the out-of-memory failure can re-enable it. See [Upgrading from EDDI 5](https://docs.labs.ai/deployment-and-infrastructure/upgrading-from-5x.md#ending-a-backlog-of-idle-conversations-in-one-call).

**Follow-ups.** The listing behind `/active/{agentId}` still reads one descriptor per conversation (slow on very large backlogs, memory-safe). The idle sweep's check-then-act window between its re-check and the compare-and-set remains (a revision-conditional narrow update would close it).

***

## ✨ feat(llm): per-model circuit breaker for systemic failures (2026-10-06)

**Repo:** EDDI (`feat/llm-circuit-breaker`, stacked on `feat/llm-recovery-policies`)

### What changed and why

Item R8 of the LLM turn-resilience plan ([`planning/llm-turn-resilience-plan.md`](https://github.com/labsai/EDDI/tree/main/planning/llm-turn-resilience-plan.md)). Retries and re-asks fix an unlucky turn; they do nothing for a model that cannot answer at all (a revoked key, a retired model id, a prompt it always answers in prose). Every turn then spent a full attempt, and the re-asks, to arrive at the same failure, and a cascade kept paying its first step's deadline before reaching a step that works.

New opt-in task field `circuitBreaker: { enabled, window, threshold, coolDownMs }` (defaults `false`, 10, 8, 60000), mirrored in the Manager's `editors/llm/types.ts`. Without it nothing changes.

* **New `LlmCircuitBreakers`** (`modules/llm/impl`, `@ApplicationScoped`): one in-memory breaker per (agent, agent version, provider, model), in a bounded (10,000) Caffeine cache that forgets idle keys after an hour. The model is the name the model was built with, after `${vars:…}`/templating (the cascade's own `resolveModelName`).
* **What counts:** `INVALID_OUTPUT` (a `convertToObject` reply still invalid JSON or off-shape after the re-asks), `BAD_REQUEST`, `MODEL_NOT_FOUND` when `threshold` of the last `window` counted turns share the class; `AUTH` and `QUOTA_EXHAUSTED` at once. Transient, rate-limited, timeout, context-too-long, unknown and uncounted outcomes are not recorded at all, so they neither fill nor drain the window.
* **Open:** the model is not called. `CascadingModelExecutor` skips the step (trace `status: circuit_open`, `eddi.llm.cascade.escalations{reason=circuit_open}`, `cascade_escalation` SSE event) and the next step runs; with no step left it returns the best response so far or throws `LlmCircuitOpenException` (a `LifecycleException` carrying the class that opened the circuit). On the non-cascade path `LlmTask` throws the same exception inside the `onError` guard, so `onError: fallback` serves the fallback with no model call.
* **Half-open:** after the cool-down exactly one probe turn is let through (a concurrent turn is denied); success closes, a counted failure re-opens, an uncounted outcome (a transient error, a HITL pause) releases the probe, and a probe whose result never arrives is abandoned after one more cool-down. A late result from a turn that started before the circuit opened cannot move it.
* **R5 hook:** the `ReaskGate` is now live. A circuit that is open or half-open for invalid output refuses the same-model re-ask (`eddi.llm.recovery{outcome=skipped_breaker}`), so a probe asks once and the cascade moves on. Each cascade step carries its own gate (`StepRecovery.gate`), because the old gate did not know which model it was asked about.
* **Invalid output is looked at directly** (`FormatRetryRunner.classifyJsonReply`) for tasks with no re-ask policy, so a model that never returns valid JSON is seen whatever the `responseValidation` settings are.
* **Alerting:** one ERROR log line per circuit **open** (agent, version, provider, model, class, EDDI's reason; never model output); half-open and closed are INFO. Metrics: `eddi.llm.circuit{state,class}` (transitions), `eddi.llm.circuit.skipped{class}`, gauge `eddi.llm.circuit.open`; two panels on the Full Metrics dashboard and a section in `docs/metrics.md`.

### Design decisions

* **A new class rather than reusing the MCP/A2A breakers.** Both are private fields of their managers: a consecutive-failure counter per server URL, no half-open state, no probe, no per-class accounting. "N of the last M failed the same way" plus a single concurrent probe could not be added without rewriting both, so `LlmCircuitBreakers` is the reusable one; migrating the other two onto it is a separate, behaviour-visible change.
* **A ticket per turn** (`acquire` then `success` / `failure` / `release`, settle-once) instead of a bare "record" call, so a probe is tied to the turn that holds it and late results from other turns are ignored. A disabled breaker hands out a no-op ticket, so callers have no `if (enabled)`.
* **Transition-based, not state-gauge-only, metric,** plus a gauge of circuits not closed: the counter drives alerting on "just opened", the gauge answers "is anything open now".
* **ERROR only for open.** The plan says one ERROR line per state change; a recovery logged at ERROR would page an operator for good news, so half-open and closed are INFO.
* **Registry is injected by an initializer method** on `LlmTask` (the same reason `attachmentForwarder` is a field): the many direct-construction tests are untouched, and a null registry means no guard.
* **"A fallback is configured"** is read as `onError: fallback`. A `responseValidation` `fallbackAction` still applies to a reply that was produced; an open circuit produces none, so it ends in the `onError` path (default `error`: fail fast with the class).

### Not done / follow-ups

* **Webhook / Slack notification.** There is no generic operator-notification hook: the only notifier infrastructure is the HITL approval channel, which is bound to a conversation's pending approval. Alerting is the ERROR log line and the metric; a generic hook would be a separate change.
* The breakers are per node. A shared (NATS/DB) state would make a cluster open at once; not needed for the failure modes here, each node sees the same failures within a window.
* The Platform Operator prompt is unchanged: it points the operator at the `langchain` and `model-cascade` docs for LLM troubleshooting, and both now describe the breaker.

***

## feat(llm): classify provider failures, honour retry delays, one retry owner (2026-10-06)

**Repo:** EDDI (`feat/llm-error-classification`)

### What changed and why

LLM retries decided on the HTTP status alone, so a Gemini or OpenAI **daily quota** 429 was retried like a per-minute rate limit (wasted attempts that cannot succeed), the provider's own retry delay was ignored, an HTTP 500 was never retried, and langchain4j's built-in client retries stacked underneath EDDI's (`maxAttempts: 3` could mean nine provider calls). This is R2 of the LLM turn-resilience plan.

* **Failure classes.** New `FailureClass` (`TRANSIENT`, `RATE_LIMITED`, `QUOTA_EXHAUSTED`, `AUTH`, `BAD_REQUEST`, `CONTEXT_TOO_LONG`, `MODEL_NOT_FOUND`, `TIMEOUT`, `UNKNOWN`), `LlmFailure(cls, retryAfterMs, reason)` and `LlmFailureClassifier` ([`LlmFailureClassifier.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/shared/LlmFailureClassifier.java)). It walks the whole cause chain and reads the provider error **body** that langchain4j keeps as the `HttpException` message: Gemini `error.status` and `details[]` (`QuotaFailure` per-day vs per-minute, `RetryInfo.retryDelay`), OpenAI `insufficient_quota` / `rate_limit_exceeded` / `context_length_exceeded`, Anthropic `overloaded_error` / `rate_limit_error` / "prompt is too long". `RetryConfiguration.isRetryableError` is now a wrapper: retryable = `TRANSIENT`, `RATE_LIMITED`, `TIMEOUT`. The existing "typed verdict beats an outer message" ordering is preserved.
* **Bug fix: HTTP 500 is now retried** (and Gemini `INTERNAL`, `UNAVAILABLE`, `DEADLINE_EXCEEDED`, Anthropic 529). Side effect: on the native-JSON-mode path a gateway that answers an unsupported `response_format` with a **500** used to fall back to a plain request; it now fails the turn like any other 5xx. Set `jsonResponseFormat: "off"` on such a gateway.
* **Quota 429s are not retried** and escalate the cascade immediately (`QUOTA_EXHAUSTED`).
* **Retry delay honoured.** New optional `retry` fields `honorRetryAfter` (default `true`) and `maxRetryAfterMs` (default `10000`, engine ceiling 30000). The provider's delay replaces the configured backoff when it is larger; a delay above `maxRetryAfterMs` stops retrying **without sleeping** so the cascade escalates at once. An HTTP `Retry-After` header is not reachable: langchain4j's `HttpException` keeps only the status and the body.
* **Single retry owner.** `maxRetries(0)` on the synchronous OpenAI, Anthropic, Gemini, Vertex Gemini, Mistral, Ollama, Azure OpenAI and Bedrock clients; `executeWithRetry` is the only loop. Hugging Face and OCI GenAI expose no setting, streaming clients have none (EDDI's own streaming loop retries). The judge model, tool-response summariser and `SummarizationService` call models with no task retry policy, so they now go through `RetryConfiguration.executeWithDefaultRetry` (default policy, original exception rethrown unwrapped): every model call has exactly one retry owner. The Azure OpenAI and Vertex Gemini builders use the same constant but are not asserted in tests (Azure exposes no retry field; Vertex needs GCP credentials to build).
* **Cascade.** Failed steps carry `failureClass` (and `retryAfterMs`) in the trace entry, additively, and count `eddi.llm.failure{class,model}`. `status` / `error` / escalation reason strings are unchanged.
* Docs: [`langchain.md`](https://docs.labs.ai/agent-configuration/langchain.md#retry-configuration) (the default is 3 attempts even without a `retry` block, classification table), [`model-cascade.md`](https://docs.labs.ai/agent-configuration/model-cascade.md), [`metrics.md`](https://docs.labs.ai/deployment-and-infrastructure/metrics.md).

### Design decisions

* `honorRetryAfter` defaults to `true`: it only lengthens a sleep that would have happened anyway, and retrying a rate limit earlier than the provider asked just burns an attempt.
* The classifier lives in `configs.shared` because `RetryConfiguration` (shared with MCP calls) is its main caller.
* No new model parameter for `maxRetries`: a configurable library retry count would recreate the double loop.

### Follow-ups

* Streaming retry loop (`StreamingLegacyChatExecutor`) still uses the plain backoff, not the provider delay.
* Manager's retry editor does not expose `honorRetryAfter` / `maxRetryAfterMs` (settable in JSON).
* R8 (circuit breaker) and R5 (`onContextTooLong`) can now key on `FailureClass`.

***

## ✨ feat(llm): configurable, JSON-aware fallback answer and task-level `onError` (2026-10-06)

**Repo:** EDDI (`feat/llm-fallback-and-onerror`, based on `feat/llm-output-parsing-never-throws`)

### What changed and why

Items R6 and R7 of the LLM turn-resilience plan ([`planning/llm-turn-resilience-plan.md`](https://github.com/labsai/EDDI/tree/main/planning/llm-turn-resilience-plan.md)). A production 5.x deployment showed that when a model call fails after its retries, the user gets an HTTP 500 and a conversation in `ERROR`, and that the one fallback the engine had (the `responseValidation` `fallback` action) was a fixed English sentence, not JSON-shaped under `convertToObject`, and was fed back to the model on the next turn.

**R6 — the fallback is configurable.** `responseValidation` gains:

* `fallbackMessage`: a Qute template (author-written config, so it is rendered) with the task's template data — `{#if properties.language == 'de'}…`, `{snippets.x}`. Default is the old sentence; a template that fails to render or renders blank degrades to it.
* `fallbackField`: under `convertToObject` the fallback is stored under `responseObjectName` as `{"<fallbackField>": "<message>"}`, so `{properties.aiOutputObject.htmlResponseText}` in a `postResponse` output template renders it unchanged. The raw `langchain:<type>:<taskId>` slot holds the same JSON.
* `fallbackQuickReplies`: stored the way `OutputGenerationTask` stores quick replies (`quickReplies:<…>` entry plus the `quickReplies` conversation-output list); `value`/`expressions` are templates.

The existing `fallback` action of `responseValidation` goes through the same code (new `LlmFallbackHandler`), so it is wrapped and flagged too.

**The model never sees the fallback.** The step gets `llm:fallback:<taskId>` = `true`, and `ConversationHistoryBuilder` (via `ConversationLogGenerator.generate(…, skipFallbackOutputs)` and the summarized-window loop) leaves out the assistant message of such a turn. The user's input stays; the following user message is merged into it so the history keeps strictly alternating roles (Anthropic rejects consecutive user messages). The transcript returned by the REST log and the UI is unaffected. `OutputItem` gains an optional `fallback` field (omitted from JSON unless set) which the task sets on the output item it adds under `addToOutput`; the step flag is the authoritative signal because a fallback rendered by a `postResponse` never passes through an `OutputItem` the task controls.

**R7 — `onError`.** Task-level `onError: {"action": "fallback" | "error"}`, default `error` (today). With `fallback`, any exception from the model phase (model construction, `preRequest`, cascade, tool loop, plain chat, and a `responseValidation` action of `error`) produces the fallback; the task returns normally, so the turn completes with 200 and the conversation is not `ERROR`. Never absorbed: `ToolApprovalRequiredException` (HITL tool pause), `ConversationPauseException`, `LifecycleInterruptedException`, cancelled group member turns, `CancellationException`/`InterruptedException` (looked for through the whole cause chain), a cancelled conversation, an interrupted thread.

* `llm:error:<taskId>` = `{class, message}`: root-cause simple class name; message redacted with `SecretRedactionFilter`, URLs replaced by `[url]`, cut at 200 characters. Kept in one helper (`LlmFallbackHandler.describe`) so R2's failure classes can replace it.
* Commit Flags: data the failed phase wrote to the step is marked uncommitted (same rule as strict write discipline). The model phase writes little before it succeeds, so in practice this guards partial data from `preRequest` and tool traces.
* Metric `eddi.llm.recovery{action=fallback,outcome=served,trigger=onError|validation}`; charted on the Full Metrics dashboard, listed in `docs/metrics.md`.

### Design decisions

* The guard wraps from model construction to the end of the model-phase branches; a few declarations moved above it (no behaviour change). With `onError` absent the guard rethrows unchanged.
* A served fallback is not run through response validation (an author's apology could match a refusal prefix) and not parsed (it would count as `invalid`/`valid` in `eddi.llm.output`). The audit ledger's `audit:model_response` is not written for it: it records what the model said.
* `fallbackField` only applies under `convertToObject`; otherwise the fallback stays a plain string.
* The audit ledger has no error field, and `LifecycleManager` still writes the task's normal audit entry; the failure is on the step as `llm:error:<taskId>`. Extending `AuditEntry` was out of scope.

### Not done / follow-ups

* The HITL resume continuation (`executeResume`) does not apply `onError` (R12).
* The rolling summary and the recall tool still include fallback turns.
* Manager: only the TypeScript types were extended; no form fields.
* Platform Operator prompt unchanged: it does not cover LLM response-validation troubleshooting today.

### Docs

[`docs/langchain.md`](https://docs.labs.ai/agent-configuration/langchain.md) — "Fallback answers and `onError`"; [`docs/metrics.md`](https://docs.labs.ai/deployment-and-infrastructure/metrics.md).

**Files:** [`LlmFallbackHandler.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/LlmFallbackHandler.java), [`LlmTask.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/LlmTask.java), [`LlmConfiguration.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/model/LlmConfiguration.java), [`ConversationLogGenerator.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/memory/ConversationLogGenerator.java), [`ConversationHistoryBuilder.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/ConversationHistoryBuilder.java), [`OutputItem.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/output/model/OutputItem.java)

***

## 🐛 fix(llm): malformed model JSON no longer fails the turn; fenced/prefixed JSON is recovered (2026-10-06)

**Repo:** EDDI (`feat/llm-output-parsing-never-throws`)

### What changed and why

First step of the LLM turn-resilience plan ([`planning/llm-turn-resilience-plan.md`](https://github.com/labsai/EDDI/tree/main/planning/llm-turn-resilience-plan.md), items R3 and R14). A production 5.x deployment with `convertToObject: "true"` showed turns failing or rendering empty bubbles whenever the model wrapped its JSON in a markdown fence, added a sentence around it, or ran out of tokens mid-object.

**Bug fix (behaviour change):** under `convertToObject`, output that is not valid JSON **no longer fails the turn**. The raw string is stored under `responseObjectName` with the existing WARN, exactly as plain-text replies always were. Before this, a reply that merely started with `{` and was malformed or truncated threw out of `LlmTask` on both the live and the HITL-resume path.

* New `ModelOutputParser` (`modules/llm/impl`) used by both paths in `LlmTask`: trim, strip one surrounding fence (` ``` ` / ` ```json `, tag case-insensitive), then extract the outermost balanced `{...}` / `[...]` (string- and escape-aware). No other repair. An extracted fragment is trusted only if it is a JSON object with at least one key, and a top-level array only as the whole reply, so prose such as `Pick option [1] or [2].` or `The empty set {} is...` stays the raw string. A fenced or prose-wrapped reply that used to be stored as a string now becomes an object.
* Result is `VALID` (flag `repaired`), `INVALID(reason)` or `EMPTY`. Reasons are EDDI-generated constants (`not JSON`, `truncated JSON`, `unbalanced braces`, `invalid JSON syntax`) and never contain model output, so a later corrective re-ask (R16) can quote them safely.
* Outcome recorded on the step under `llm:output:outcome:<taskId>` (`valid|repaired|invalid|empty`; not a public snapshot key because of its `llm:` prefix) and counted in `eddi.llm.output{outcome}` (charted on the Full Metrics dashboard, listed in `docs/metrics.md`).

**R14 (test scope only):** `FaultInjectingChatModel` (`src/test/.../modules/llm/testing`), a scripted langchain4j `ChatModel` for later resilience work: per call it returns text, an empty reply, a finish reason (`LENGTH`, `CONTENT_FILTER`), throws a simulated HTTP status (mapped through langchain4j's own `ExceptionMapper`, so `RetryConfiguration.isRetryableError` classifies it like a real provider error), throws any exception, or delays. It is not registered as a model type and nothing in `src/main` knows about it.

### Design decisions

* One parser class rather than two inline copies, so the live and resume paths cannot drift.
* Successive top-level balanced candidates are tried in order, so `Use {name} here: {"a":1}` still yields the object.
* Not done: the optional WireMock cascade IT from the plan (not trivial); retry/corrective re-ask (R5), schema validation (R4) and the fallback answer (R6/R7) build on this and follow.

### Docs

[`docs/langchain.md`](https://docs.labs.ai/agent-configuration/langchain.md) Structured Output: parsing steps, "never throws", outcome key and metric.

**Files:** [`ModelOutputParser.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/ModelOutputParser.java), [`LlmTask.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/LlmTask.java), [`FaultInjectingChatModel.java`](https://github.com/labsai/EDDI/tree/main/src/test/java/ai/labs/eddi/modules/llm/testing/FaultInjectingChatModel.java)

***

## ✨ feat(llm): recovery policies — re-ask the same model before escalating (2026-10-06)

**Repo:** EDDI (`feat/llm-recovery-policies`, stacked on `feat/llm-fallback-and-onerror` and `feat/llm-error-classification`)

### What changed and why

Item R5 of the LLM turn-resilience plan ([`planning/llm-turn-resilience-plan.md`](https://github.com/labsai/EDDI/tree/main/planning/llm-turn-resilience-plan.md)), plus the cost and injection guards of R16 that belong to it. A one-off format slip (prose around the JSON, an empty reply, a cut-off object) is usually fixed by the model that made it; escalating first pays for a different, possibly slower or pricier model on every hiccup. `responseValidation` gains a `retry` action and the engine now recovers in cost order: **answer → local repair (the R3 parser) → up to `maxRetries` same-model corrective re-asks → escalate to the next cascade step (which repeats this with its own re-asks) → `fallbackAction`.**

New `responseValidation` fields: `onInvalidJson` (default `ignore`), `onSchemaMismatch` (a reply that parses but breaks `responseSchema` / `nonBlankFields`, detected by R4; handled exactly like `onInvalidJson`, the R4 violation being the corrective message's reason), `onContextTooLong` (default `error`), `maxRetries` (default 1, clamped 0..3), `truncationRetryFactor` (default 2, clamped 1..4, never above 32768 tokens), `correctiveMessage`, `maxRetryCostUsd`, `minAttemptMs` (default 3000), `fallbackAction` (default `fallback`). `retry` is also accepted by `onEmpty`, `onTruncation`, `onContentFilter`. A cascade step gets `maxFormatRetries` (null inherits). Every default keeps today's behaviour: a task without a `retry` action is untouched.

* **New `FormatRetryRunner`** owns the same-model recovery for all three call sites: plain chat (`LlmTask`), each cascade step (`CascadingModelExecutor`, escalation reason `invalid_output` in the trace, in `eddi.llm.cascade.escalations` and in the `cascade_escalation` SSE event), and the final answer of a tool loop.
* **Truncation:** one re-ask with `maxOutputTokens` × factor, set on the `ChatRequest` (the cached model is not touched). The base cap comes from `maxTokens` / `maxOutputTokens` (Gemini) or Anthropic's built-in default; unknown base means no re-ask.
* **Context too long (B3):** one re-send with the history window halved (`maxContextTokens` / 2, else `conversationHistoryLimit` / 2, else half the conversation), rebuilt through `ConversationHistoryBuilder`, anchored first steps kept. Not available in tool mode.
* **Tool mode:** only the final model call is re-asked (`IAgentOrchestrator.reaskFinalAnswer`, a single request over system + history + the loop's tool exchange + corrective). `ToolLoopRunner` is never re-entered; a tool request in the re-asked answer is ignored. Proven by tests that count tool executions.
* **Time:** a re-ask starts only if the step's remaining time (its `timeoutMs`) is at least `minAttemptMs`; otherwise the cascade escalates at once. The budget is a `RemainingBudget` (`UNBOUNDED` by default, combined with the step timeout via `min`) — the hook the turn deadline (R1) feeds through the new `CascadingModelExecutor.execute(..., contextShrinker, turnBudget)` overload.
* **Breaker hook:** `FormatRetryRunner.ReaskGate` (`CascadingModelExecutor.setReaskGate`) lets R8 skip the re-ask for a model that has been failing the same way for most recent turns. Nothing sets it yet.
* **Streaming:** a task that may re-ask is buffered, not streamed; a new SSE event `llm_retry` `{reason, attempt}` (via `ConversationEventSink.onLlmRetry`) precedes each re-ask.
* **Observability:** `eddi.llm.recovery{action=retry|escalate, outcome, trigger}` (R6's meter) with outcomes `recovered`, `still_invalid`, `failed`, `skipped_budget|no_time|cost|breaker` and `invalid_output`; a panel on the Full Metrics dashboard; `llm:retry:<taskId>` = `{reasks, unresolved}` on the step. Token usage of every attempt is summed into the turn's usage, so re-asks appear in the audit ledger and in `maxCostPerRun`.

### Design decisions

* **What a re-ask sends.** Invalid JSON: original messages + the model's own bad reply as an **assistant** turn (cut at 16,000 chars) + one corrective **user** message. Echoing the reply is standard corrective prompting and keeps model text in the model's role. The user-role text is the configured template with `{reason}` replaced literally by `ModelOutputParser`'s own constant reason — no Qute, no model output, no user input (R16). Empty / truncated / filtered replies are re-asked with the original request unchanged (a corrective sentence adds nothing there).
* **Escalation vs the confidence ladder.** An unusable step is a candidate of last resort (confidence 0 in the best-so-far ranking); if the last step is unusable and an earlier step produced a usable answer, that answer wins.
* **`retry` after exhaustion.** The final `responseValidation` pass resolves a `retry` that is still failing to `fallbackAction`. `retry` on `onRefusal` / `onStreamingTimeout` is not supported and is treated as `warn`.
* **Bug fix on the way:** `LegacyChatExecutor`'s "provider may not support JSON mode" fallback re-sent the identical request after *any* non-retryable failure; a context-too-long, auth, quota or unknown-model refusal now propagates instead (the retry could not help, and the context recovery needs to see the failure).
* **`maxRetryCostUsd`** is priced from the task's / step's configured per-1M prices (zero when none). It does not consult the per-conversation `ToolCostTracker`.

### Not done / follow-ups

* The breaker (R8); the R1 deadline plumbing (only the `RemainingBudget` hook exists).
* Tool mode: no truncation or context-too-long re-ask (no finish reason from the loop; shrinking after tools ran would replay them).
* The HITL resume path (`executeResume`) keeps R3's local repair but has no re-asks.
* Manager: TypeScript types only (`responseValidation`, `CascadeStep.maxFormatRetries`); no form fields yet.
* Platform Operator prompt unchanged: it does not cover LLM response-validation troubleshooting today.

### Docs

[`docs/langchain.md`](https://docs.labs.ai/agent-configuration/langchain.md) — "Recovery policies: retry where it helps"; [`docs/model-cascade.md`](https://docs.labs.ai/agent-configuration/model-cascade.md) — "Format recovery and escalation"; [`docs/metrics.md`](https://docs.labs.ai/deployment-and-infrastructure/metrics.md).

**Files:** [`FormatRetryRunner.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/FormatRetryRunner.java), [`CascadingModelExecutor.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/CascadingModelExecutor.java), [`LlmTask.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/LlmTask.java), [`LegacyChatExecutor.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/LegacyChatExecutor.java), [`AgentOrchestrator.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/AgentOrchestrator.java), [`LlmConfiguration.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/model/LlmConfiguration.java), [`ConversationEventSink.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/lifecycle/ConversationEventSink.java)

***

## ✨ feat(llm): response shape validation and native JSON schema (2026-10-06)

**Repo:** EDDI (`feat/llm-response-schema-validation`, stacked on `feat/llm-output-parsing-never-throws`)

### What changed and why

R4 of the LLM turn-resilience plan ([`planning/llm-turn-resilience-plan.md`](https://github.com/labsai/EDDI/tree/main/planning/llm-turn-resilience-plan.md)). Valid JSON of the wrong shape (the field the template reads is missing, has the wrong type, or is `""`) used to render an empty bubble with no signal. This change produces the verdict; the recovery policy that acts on it (`onSchemaMismatch`, retry) is R5.

* **`ResponseShapeValidator`** (`modules/llm/impl`): in-house validator for a JSON-Schema subset (`type` incl. type arrays, `required`, `properties`, `items`, `enum`, `minLength`, optional `additionalProperties: false`). `networknt` is on the classpath but deliberately not used: it evaluates `pattern` (ReDoS from model output) and resolves `$ref` (remote fetch). Unknown keywords are ignored. An unparseable or malformed schema logs one `WARN` per distinct schema and skips validation; it never fails the turn.
* **`nonBlankFields`** (new `LlmConfiguration.Task` field, list of top-level or dotted names that must be non-blank strings). Placed on the task next to `jsonResponseFormat`, not in `responseValidation`, so it is independent of `responseValidation.enabled` and does not touch the class R5 extends.
* **New outcome `schema_mismatch`** (`ModelOutputParser.Kind.SCHEMA_MISMATCH`, parse overload `parse(raw, convert, schema, nonBlankFields, taskId)`). **The parsed object is kept** (not the raw string): templates that worked on a partially valid object keep working, which a plain `INVALID` would break. The reason is recorded on the step under `llm:output:reason:<taskId>` (also now written for `invalid`), counted in `eddi.llm.output{outcome=schema_mismatch}`. Reasons are built from the failed keyword and the schema's own path (`schema: $.htmlResponseText required`, `nonBlank: $.a.b`), never a model value and never a key taken from the reply (`additionalProperties` names the object, not the key). R5 consumes `Kind.SCHEMA_MISMATCH` / `outcome.reason()`.
* **Native schema enforcement** via `JsonResponseFormatPolicy` (new `responseSchema` record component, `of(..., schema)`, `supportsNativeSchema`) and `ResponseSchemaConverter`: for `openai`, `azure-openai`, `mistral` and `gemini` the request carries the `responseSchema` as a `JSON_SCHEMA` format, per request, never on the cached model. The Gemini no-JSON-with-tools rule is unchanged. `gemini-vertex` and all other providers keep schemaless JSON plus the prompt block (the Vertex binding only takes a schema on the model builder). Conversion is all-or-nothing: an inexpressible schema falls back to schemaless JSON.

### Design decisions

* **Strict mode is not sent.** In langchain4j 1.20.2 `strict` is a model-builder flag (`strictJsonSchema`), not part of `ChatRequest`; setting it would bake it into a cached model, which this codebase avoids (the historical Gemini 400). The schema goes out non-strict and EDDI's validation is the actual gate. Documented in `docs/langchain.md`.
* A `responseSchema` written as an *example object* (`{"answer": "string - ..."}`, as in older docs) is not a JSON Schema: it stays prompt-only and is neither validated nor sent natively, so existing agents are unaffected. With neither a JSON-Schema `responseSchema` nor `nonBlankFields` set, behaviour is identical to before apart from the key `llm:output:reason:<taskId>` on `invalid` replies.
* Shape checks run whenever a schema or `nonBlankFields` is configured; there is no master switch because the only effect is an outcome label, a log line and a metric until R5 adds an action.

### Docs

[`docs/langchain.md`](https://docs.labs.ai/agent-configuration/langchain.md) Structured Output (native schema matrix, shape validation, reason table, outcome table), [`docs/metrics.md`](https://docs.labs.ai/deployment-and-infrastructure/metrics.md), Full Metrics dashboard panel description. Manager type `nonBlankFields` in `ui/manager/src/components/editors/llm/types.ts`.

### Follow-ups

* R5: `onSchemaMismatch` action and corrective retry consume `SCHEMA_MISMATCH`.
* Not verified against live provider APIs: the native-schema matrix comes from the langchain4j 1.20.2 bindings, and the native request is checked at the `ChatRequest` level only.
* Manager UI has the type only; no editor control for `nonBlankFields` yet.

***

## feat(llm): turn deadline end to end, cancellation hygiene, deploy-time warnings (2026-10-06)

**Repo:** EDDI (`feat/llm-turn-deadline`, based on `feat/llm-error-classification`)

### What changed and why

Retries, cascade steps and HTTP calls each carried their own timeouts, and they multiply: a caller with a 60-second timeout could give up while the engine was still working, and the late answer was stored but never seen. This is R1, R10 and R15 of the LLM turn-resilience plan.

* **One deadline per turn (R1).** New agent-level `turnDeadlineMs` (default unset = today's behaviour) and `turnDeadlineReserveMs` (default 1500), and a per-request header `X-EDDI-Turn-Deadline-Ms` on `say`, the managed-conversation endpoint, the streaming `say` and the OpenAI-compatible `/v1` adapter. The deadline is `arrival + min(config, header)`. **Decision:** a header alone enables a deadline when the agent configures none (the caller knows how long it will wait), capped at 10 minutes; when the agent configures one the header can only shorten it. A malformed, negative or zero header is ignored with a debug line, never an error. The value is carried on `IConversationMemory#getTurnDeadline()` as a **transient** field (never persisted), set by `ConversationService` before every `say`/`rerun` turn and always overwritten, so a reused memory never carries a previous turn's deadline. `TurnDeadline` ([`TurnDeadline.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/shared/TurnDeadline.java)) takes an injectable `Clock`.
* **Consumers.**
  * `RetryConfiguration.executeWithRetry(…, TurnDeadline)`: the first attempt always runs while time remains; a retry starts only if at least 3000 ms plus the reserve remain; each attempt runs on a virtual thread and is abandoned and cancelled when it overruns what is left after the reserve (a cached model carries a fixed provider timeout, so this is the only per-attempt bound available); a backoff or a provider `Retry-After` that would leave no room for the next attempt is not slept - the loop stops and rethrows the classified failure.
  * `CascadingModelExecutor`: `maxTotalDurationMs = min(config, remaining - reserve)`, step timeouts clamped to the remaining budget, no new step under 3 s plus the reserve (best answer so far is returned).
  * `ApiCallExecutor`: the per-call timeout is clamped to the remaining budget; `retryApiCallInstruction` retries that cannot fit are skipped; the first call is never skipped unless the deadline has already passed, when it fails fast with a clear message.
  * `LlmTask` only passes `memory.getTurnDeadline()` into the three non-cascade `LegacyChatExecutor` calls; the tool loop does the same from the memory it already holds.
* **Cancellation hygiene (R10).** The model built for a cascade step has its request `timeout` clamped to the step's `timeoutMs` (rounded up into coarse buckets - whole seconds to 10 s, 5 s above - so a shrinking deadline does not mint a cached model per millisecond; the registry cache key already includes `timeout` and stays bounded). A streamed step keeps its own bound. New counter `eddi.llm.cancelled{scope=attempt|cascade_step}`.
* **Deploy-time warnings (R15), never blocking.** Logged once per agent deployment: a model `timeout` longer than its cascade step's `timeoutMs`; `convertToObject` with no fallback path; for agents with `turnDeadlineMs`, a static worst case (LLM retries x timeout, cascade budget, slowest httpcall of each httpcalls step with its retries) above the deadline minus the reserve. The `onError: fallback` half of the fallback check is read reflectively because that field ships in a parallel change.
* **Metrics.** `eddi.llm.turn.deadline.exceeded{stage}` and `eddi.llm.cancelled{scope}`, with two dashboard panels and entries in `docs/metrics.md`.
* **Docs.** `docs/langchain.md` (Turn Deadline), `docs/model-cascade.md`, `docs/httpcalls.md`, `docs/conversations.md`, `docs/metrics.md`.

### Follow-ups

* The SSE streaming model path (`StreamingLegacyChatExecutor`) keeps its own timeout and is not yet bounded by the deadline; a HITL resume starts a turn without one.
* Warning "onInvalidJson retry with maxRetries 0" lands with the format-retry change (R5).
* The Platform Operator prompt does not document agent-level resilience settings today, so it is unchanged.

***

## Missing quick-reply array no longer fails the turn; managed calls answer 503 while no agent is ready (2026-10-06)

Repo: EDDI, branch `fix/quick-reply-orempty-and-not-ready-503`. Both found migrating a production 5.x deployment to 6.x.

* `PrePostUtils.renderPerIteration` now iterates `<pathToTargetArray>.orEmpty`, so a response without the array (e.g. an LLM reply with no `quickReplies`) yields zero quick replies / output items instead of `Iteration error - {...} not found` (5.x behaviour). Not appended when the path already ends in `.orEmpty` or uses `?:`, `??`, `or` or a range. This also covers `batchRequests` iteration, which shares the renderer. Tested against the real Qute engine with strict rendering off.
* `RestAgentManagement`: when `RestAgentEngine` refuses to start a conversation because no agent version is ready (404; or 503 while draining), the managed endpoints (`loadConversationMemory`, `sayWithinContext`) now answer 503 with `Retry-After: 5` and a clear message instead of an NPE on the missing user conversation and a 500. The concurrent-creation fallback also no longer dereferences a null conversation.
* Design: `RestAgentEngine` keeps its 404 for the start endpoint (public contract); the translation to 503 happens in the managed layer. Undo/redo/end endpoints only act on existing conversations and cannot hit this.
* Docs: `docs/httpcalls.md`, `docs/managed-agents.md`.

***

## Qute migration parses what it converts, and converts nested conditionals (2026-10-06)

* **Repo / branch:** EDDI, `fix/qute-migration-validate-output`.
* **Problem:** on a production 5.x deployment the Thymeleaf-to-Qute migration turned a nested conditional (`[[${a > 0 ? 'x ' + a + (b > 0 ? 'y' : 'z') : 'w'}]]`) into text Qute cannot parse, counted the document as migrated, and logged "migration complete". Every render of it then failed with `Parser error: invalid identifier found`.
* **What changed:**
  * `TemplateSyntaxMigrator.quteParseError` parses a converted template with a plain Qute engine (parse only, nothing rendered; namespaces such as `vars:`, `json:`, `vault:` are resolved at render time and do not fail a parse). `V6QuteMigration` runs it on every converted string. A template that does not parse keeps its original, makes the document unconvertible and takes the existing path: one ERROR, the boot summary, the migration not marked complete, the document not counted as migrated. The archive import runs the same check and imports the original with a WARN instead.
  * New `OgnlTernaryConverter`, a small recursive-descent parser: `cond ? a : b`, nested to any depth, with `'lit' + path + 'lit'` concatenation in the branches, becomes `{#if cond}a{#else}b{/if}`. Conditions are paths, string and number comparisons, `&&`/`||`/`!` (and `and`/`or`/`not`) and parentheses. A comparison against a number is guarded (`x && x > 0`), because Qute throws when it compares a missing value.
  * `migrateCloseTags` now pops its stack on a Qute `{/if}` / `{/for}`, so a converted conditional inside a Thymeleaf `[# th:if]…[/]` element does not steal the `[/]`.
* **Design decisions:** the converter answers "not sure" rather than guessing, and the caller then falls back to the previous conversion, whose result is judged by the parse check. Comparisons such as `x >= 0` or `x < 5` are not converted by it, because the zero-is-false guard would change the answer for `x == 0`; they fall back and, if Qute rejects the result, are reported. Plain Elvis (`a ?: b`) and safe navigation (`a?.b`) are not conditionals and are unchanged.
* **Follow-ups:** none required. A stray string in an imported archive that is not valid Qute now also blocks the conversion of the resource it sits in (the original is imported, with a WARN).

***

## feat(conversations): structured turn errors and idempotent turns (2026-10-06)

**Repo:** EDDI (`feat/turn-idempotency-structured-errors`, based on `feat/llm-turn-deadline`)

### What changed and why

R9 of the LLM turn-resilience plan: the caller contract. A production 5.x deployment's backend timed out at 60 s, retried, met `409 IN_PROGRESS`, and never saw the answer the engine finished a few seconds later; and a failed turn gave the caller no machine-readable reason.

* **Structured errors.** A failed task now records `code` / `retryable` / `retryAfterMs` / `message` in its `taskErrors` entry (classified by `LlmFailureClassifier`; unrecognised failures are `TURN_FAILED`), and the `say` response gains a top-level `error` object for a turn in `ERROR`, plus a `Retry-After` header when the provider gave a hint. Streaming `done` carries it too. An unexpected server fault is a `500` with `{"error":{"code":"INTERNAL_ERROR",...}}` and no exception text. (`TurnError`, `LifecycleManager`, `ConversationService`, `RestAgentEngine`.)
* **Idempotent turns.** `Idempotency-Key` / `X-EDDI-Request-Id` on `say`, managed and streaming `say` (`TurnIdempotencyService`, `IdempotencyKeyHeaderReader`): a duplicate during the turn waits for it (bounded by the R1 header, capped at the agent timeout) and returns its result; a duplicate after completion within `eddi.turns.idempotency.ttl-seconds` (default 600, `0` = off) returns the stored answer. The key is stored on the step (`idempotency:key`, persisted); an in-memory map (Caffeine, bounded and expiring) holds in-flight turns plus a 30 s copy that bridges the moment before the persist. Keys are per conversation, <= 128 printable ASCII characters, else `400`.

### Design decisions

* **One `error` object.** Main's #946 already put a `{taskId, taskType, errorType, message}` object under `error` on every snapshot in the `ERROR` state; R9 adds `{code, retryable, retryAfterMs, message}` on the say response. They are one top-level `ai.labs.eddi.engine.model.TurnError` carrying the union (`taskId`, `taskType`, `errorType` are omitted from the JSON when unknown; `retryAfterMs: null` is always emitted), built from the same `taskErrors` entry by `TurnError.fromTaskError` on both paths. `message` is #946's digest text (`Task 'x' failed: ...`). No field was removed or renamed.
* **The status is unchanged.** A failed turn was already `200` with `conversationState: "ERROR"` (not a bare 500), so `error` is added to that body rather than replacing it; clients that parse the snapshot keep working. The `/v1` adapter and the existing `409/429/503` bodies are untouched. The endpoints produce JSON only, so there is no text/plain variant to negotiate.
* **A failed turn is never replayed**, or the retry the error invites would return the same failure.
* **Multi-node:** waiting for a running turn only works on the node running it; the persisted lookup works everywhere.

### Follow-ups

* A duplicate of a running turn on another node (NATS) still meets `409`; a cross-node wait would need the event bus.

***

## 5.x migration: background properties migration, progress logging, operations guidance (2026-10-06)

Repo: EDDI, branch `fix/v5-migration-startup-ops`.

**Why.** A production 5.x to 6.x upgrade blocked HTTP for minutes at startup (liveness failed), logged nothing during long migration steps, and printed the database connection string into the container log.

**What changed.**

* `PropertiesMigrationService` no longer runs from a `StartupEvent` observer on the main thread. Its public `runIfNeeded()` is called by `AgentDeploymentManagement` on the scheduler thread, right after the V6 rename migration and before the readiness callback and the first deployment. Readiness therefore stays DOWN until it finishes, liveness stays UP, and no agent (so no conversation, so no property load) exists before it completes. A failure is logged and retried on next start, as before.
* New `ai.labs.eddi.utils.ProgressLogger`: at most one INFO line per interval (10 s), driven by `advance()` in per-document loops or by a daemon `startHeartbeat()` around a single long `updateMany`. Wired into `V6RenameMigration` (agents, workflow/descriptor/other document loops, triggers, and the four server-side `updateMany` steps including the conversation step reshape) and `PropertiesMigrationService`. Tested with a fake clock.
* Docs: new section 9 in `upgrading-from-5x.md` (health checks and start period, rollback, memory, vault for former property keys, never-ended conversation clean-up, rehearsal, connection string), a "Secrets in the Container Environment" section in `security.md`, and the AWS setup page now uses `MONGODB_CONNECTIONSTRING` from a secret and the liveness endpoint.

**Decisions.**

* The UBI `run-java.sh` logs the exec line unconditionally and its logging helpers have no off switch, so no Dockerfile environment variable can silence it; the image is unchanged and the guidance is documentation. A custom logging module via `JBOSS_CONTAINER_UTIL_LOGGING_MODULE` would work but replaces base-image code, so it was not done.
* The migration is injected into `AgentDeploymentManagement` as a field `Instance`, not a constructor argument, to keep the constructor stable for its many tests.

**Follow-up.** The end-inactive conversation endpoint is described generically in the upgrade guide and should get a literal path once its PR is merged.

***

## Regression test: outbound httpcalls client keeps no cookie jar (2026-10-05)

**Repo/branch:** EDDI, `fix/httpclient-no-cookie-jar`

**What changed**

* The shared Vert.x client behind every agent's httpcalls was already switched from an application-scoped `WebClientSession` (cookie store, replayed `Set-Cookie` across agents, users and tenants) to a plain `WebClient` in #862. No production code changed here.
* Added `HttpClientModuleCookieTest`: the real producer against a loopback server proves a `Set-Cookie` from one call is not sent on the next call to the same host. Mutation-checked by restoring `WebClientSession.create(...)`, which fails the test.
* Documented the behaviour in `docs/httpcalls.md` ("Cookies are not kept between calls"). Corrected a stale comment in `ApiCallExecutorBranchCoverageTest` that still described a cookie-aware session.

**Behaviour note:** httpcalls never persisted cookies across calls after #862; an API that relied on a session cookie between two calls must carry the credential explicitly (header or property). Nothing in the tests, `docs/agent-configs/` or `docs/httpcalls.md` relies on session cookies.

***

## Cluster console — health, leases, dead letters, activity and safe recovery actions (2026-10-04)

**Repo:** EDDI · **Branch:** `feat/nats-cluster-console` (part 4 of the NATS stack, into `feat/nats-cluster-deploy`)

The Manager's coordinator screen targeted the single-node API and ignored every cluster datum. It is now a cluster console built for an on-call admin: is the cluster healthy, which node is doing what, what went wrong, and what can safely be done about it.

### Backend — `/administration/cluster` (`IRestClusterAdmin`, `ClusterAdminService`)

* **Overview**: a verdict (`HEALTHY`, `DEGRADED`, `PARTITIONED`, `SINGLE_NODE`) with reason codes; one card per node — live, `STALE`, `LOST` (expired without leaving) or `LEFT` (clean shutdown), kept for 15 minutes by `ClusterWatcher`; host, version, uptime, heartbeat age, NATS RTT, running turns, leases, queue, locally kept dead letters, drained, HITL leader; NATS and JetStream as the answering node sees them (server, known servers, every stream and KV bucket of the deployment with replicas, peer state and consumer lag, the leases-bucket generation).
* **Leases**: one KV watch lists every lease with holder, age, revision (fencing token), the server's renewal time and flags (`HOLDER_GONE`, `HOLDER_RESTARTED`, `NOT_RENEWED`, `LONG_RUNNING`, `CONTENDED`), suspicious first, agent and state read in one query.
* **Dead letters** now record `reason` (`fenced`, `lease-lost`, `timeout`, `failed`), `nodeId` and, for a fenced write, both tokens; `notReplayableReason` says why one cannot be replayed (`SECRET_INPUT`, `INPUT_NOT_CAPTURED`, `NOT_A_TURN`). Filtered, cursor-paged listing (scan bounded at 2,000 per call), a content-free summary, and bulk replay/discard (≤ 100 ids) with one outcome per id.
* **Activity timeline**: the new `<prefix>_ACTIVITY` JetStream stream (`eddi.cluster.activity.max-age`, 24 h, ≤ 10,000 entries) read back by every node, so any node answers with the same history; deterministic ids collapse the same observation from several nodes. Node joined/left/lost/stale, degraded on/off, lease takeovers, fenced writes, dead letters, deployment propagation per node with its delay, cache invalidations per minute, every admin action. SSE stream with a 15 s ping, at most 16 subscribers per node.
* **Diagnosis** of one conversation: lease and holder, turns queued per node (RPC scatter), state, dead letters, findings with a suggested action.
* **Recovery actions** (admin only, audited in the `cluster-admin` audit trail, recorded on the timeline, counted on `eddi_cluster_admin_actions_total`): force-release a lease (CAS delete, refused as `RENEWED` when the holder renewed since the admin looked; safe because of the fence), resync caches cluster-wide, reconcile deployments on every node, drain/undrain a node (no new leases, 409 + `Retry-After`, readiness DOWN; refused for the last undrained node), forward locally kept dead letters (now serialised per node).
* **Roles**: overview, leases, activity, diagnosis and the dead-letter summary are `eddi-admin` + `eddi-viewer`; the dead-letter listing (captured input) and every action are `eddi-admin`.

### Manager

`/manage/coordinator` is the **Cluster** screen: tabs Overview, Leases, Dead letters, Activity, Stuck conversation (deep-linkable with `?tab=` and `?conversation=`). Verdict card with the degraded-mode banner explaining the `local`/`reject` policy, node cards with drain/undrain, NATS & JetStream panel, recovery actions with consequence-stating confirmations, the audit trail of those actions, a filterable live activity feed that buffers while paused and backfills after a reconnect, a dead-letter table with filters, selection, bulk actions with per-item results and a focus-trapped detail drawer (fence tokens, masked secret input, "not replayable" with the reason). Single-node mode explains what cluster mode adds. `eddi-viewer` sees insights only; other roles see why the screen is closed. All strings in the 11 locales.

**Platform Operator** (revision 3): reads overview, leases, activity, diagnosis and the dead-letter summary; a new prompt section explains verdicts, degraded policies and orphaned leases. The dead-letter listing (user input) and every recovery action stay off the allow-list.

### Found on the live 3-node cluster, fixed on this branch

* A refused action answered `503` while NATS was down; the shipped nginx configuration retries the next node on `503`, so every node got marked down and the whole API (turns included) answered `502` for the fail timeout. Refusals are `409` with a code now.
* After a NATS outage the watcher reported every node — itself included — as lost, because their presence records had expired meanwhile. It now waits two presence intervals after a reconnect and never reports itself.
* Activity entries recorded during an outage stayed in the outbox when the first publish after the reconnect hit a stream still electing its leader; the outbox is now retried every 5 s.
* Without NATS the other nodes were shown "heartbeat late"; they are `UNKNOWN` now, and this node's card uses its live numbers (it hid the dead letters kept locally).
* A paused node behind the load balancer froze the console's numbers (its requests hung for the proxy's read timeout); console reads fail after 8 s and show the stale-data notice.
* `NOT_RENEWED` now flags two missed heartbeats instead of three — with a 20 s TTL and a 5 s heartbeat, three left almost no window before the lease expired by itself.
* A restarted node's sweep of its previous boot's leases now shows up as a takeover.

### Decisions

***

## Cluster console review: exactly-once replay, atomic drain, viewer privacy, admin SSE slots (2026-10-04)

**Repo:** EDDI · **Branch:** `feat/nats-cluster-console` (review follow-up)

* **The read-only viewer no longer sees who an administrator is** in the activity timeline (`an administrator` instead of the principal name), nor the error text of a dead letter (an exception message can quote user input or a configuration value); `IRestClusterAdminRoleGateTest` pins the exact set of endpoints open to `eddi-viewer`.
* **Replay runs a dead letter at most once.** Two administrators replaying one entry both ran its turn (get, say, delete). The entry is now claimed first — a create of `replay.<id>` in the new shared `<prefix>_ADMIN` KV bucket (TTL 60 s), which only one caller wins — and read only after the claim; the loser gets `IN_PROGRESS`. The entry is deleted before the claim is dropped, so a late replay finds it gone. Nothing is lost: a rejected turn keeps the entry, a dead node's claim expires.
* **Draining is decided one at a time, cluster-wide.** The last-node guard counted drained nodes from presence records up to 5 s old, so two administrators could drain the last two nodes at once. A `gate.drain` create in the same bucket serialises drain decisions, and the guard counts the `drain.<node>` keys (kept by each drained node, removed on undrain or restart) instead of presence; a second decision while one is being applied answers `409 BUSY`.
* **Viewers cannot lock administrators out of the live feed:** at most 12 of the 16 activity streams per node go to read-only callers. A stream is closed when the access token it was opened with expires (`expired` event); the Manager reopens it with the refreshed token.
* **A clean shutdown is said, not guessed:** a leaving node writes a `left.<node>` marker before it removes its presence record; a record that vanishes without one is `LOST` (timing alone misread a clean shutdown under scheduler jitter).
* **Found on the live re-check, fixed:** the service tested the injected coordinator with `instanceof ClusterConversationCoordinator`, but it is the producer's client proxy — so the shared dead-letter count read 0, the per-conversation dead-letter lookup and paging used the single-node path, and *Forward local dead letters* reported 0 with a local entry waiting. It is resolved by type now. The first dead letter on a fresh cluster fell back to the node-local ring (its stream was still electing a leader: "no responders"); the publish now retries for \~2 s, and node-local dead letters are forwarded every 30 s while connected, not only on a reconnect. The `ADMIN` bucket is provisioned at start: two nodes creating it on first use made the loser of a replay race answer `UNAVAILABLE` instead of `IN_PROGRESS`.
* **Recovery actions report what actually happened.** A cache resync while the node is cut off from NATS answered `DONE`, though only this node had flushed and the request sat in the outbox. It now answers `QUEUED` and says the others get it on reconnect (`requestResyncAll` reports whether it was sent). Reconcile and forward-local answer `PARTIAL` when a member did not answer (an RPC reply carrying an `error` no longer counts) or, for forward, when entries are still kept locally; `details.missing` and `details.remaining` say which. Drain already refused with a `409` rather than half-doing it. The console shows the outcome in words and warns, instead of a success toast, for anything but `DONE`; audit and activity carry the same outcome.
* **Dead-letter reasons the console does not know** are shown by their code with a generic explanation, no longer as "Failed". `lease-lost` has its label, help text, filter option and timeline wording.
* **Merged the deploy branch's lease-lost fix** (`4f221dd9d`). The step runner records why it stopped a turn in the turn descriptor (`reason`, `fence`, `storedFence`); the coordinator now classifies from that first, so a lease-lost turn is stored with `reason: lease-lost` and its token in `fence`, shared or node-local, rather than as `failed`. A stream entry that carries the reason only in its turn (written by a node without the classifier) is read back the same way. The two branches had each added a retry for the first dead letter on a new stream; the deploy branch's is kept, as is its 10 s forward after a local fallback.
* **Losing a KV create race is a conflict, not an outage (found live).** The NATS server answers the loser of two concurrent creates of one key with error 10164 as well as 10071; only 10071 was recognised, so in 8 of 15 live drain races the loser answered `409 NATS_UNREACHABLE` instead of `BUSY`, and a double replay could answer `UNAVAILABLE` instead of `IN_PROGRESS`. `NatsSharedKv` treats both codes as a conflict for create, compare-and-set and guarded delete, which every caller of the shared KV (leases included) relies on. After the fix, 20 of 20 races answered `BUSY` or ran one after the other. A failed replay claim or drain gate now logs its cause.
* **The drain guard reads presence now (found live, 1 race in 40).** It used the cached member list the status views use, which after a failed read answers with the last or an empty list, and once refused a drain as `LAST_NODE` with two other nodes serving. It now reads `ClusterPresence.currentMembers()` (merged from the deploy branch, together with its port of the 10164 fix) and answers `409 NATS_UNREACHABLE` when that read fails.
* **PR #970 review (CodeRabbit).**
  * A drain could miss a turn that registered as a lease waiter just after the drain swept the waiters; that turn could then take a lease on the drained node. Each attempt now re-checks the drain before it creates the lease key (an attempt already past the check is refused by the sweep, and `grant` hands back a lease whose waiter was completed meanwhile).
  * Reconcile no longer reports a slow sweep as a node that did not answer: the handler answers within half the RPC timeout, `running` when the sweep is still going, and the action answers `STARTED` with `details.running` instead of `PARTIAL`.
  * The dead-letter summary (up to 5,000 entries scanned per poll, per open console) is shared for 12 s and concurrent requests wait for one scan; replay, discard and forward on this node drop it, and a scan that overlapped one of them is not kept.
  * The live activity feed recovers after a `busy` refusal or after its reconnects gave up: it is opened again 30 s later (the console tabs never remounted it).
  * A dead letter kept locally is announced with the id it was recorded under, not the ring's last entry, which under concurrent failures could be another one.
  * `lease-lost` is listed among the reasons in `clustering.md`, the Platform Operator prompt (revision 4) and the feature fragment; two `ClusterCoordinatorIT` tests got unique `@Order`s.
* **The shared dead-letter count no longer stops at 100,000 conversations** (PR #970 review, round 2). NATS sends a stream's subjects in pages of 100,000; jnats 2.26.3 requests the later pages but appends them only to `StreamState.getSubjects()`, while `getSubjectMap()` keeps the first page. `countTurns` summed the map; it sums the list now. Checked against NATS 2.11 with 100,050 subjects: the list holds 100,050, the map 100,000.
* **A node that answers a cluster action with an error is named as failed** (PR #970 review, round 3). Reconcile skipped such a reply, so the node was reported as "did not answer", or not at all (and the action as `DONE`) when presence did not list it. Forward-local counted it as having forwarded nothing. Both now report `PARTIAL` with `details.failed` (node and error), in the audit entry and the message too, and keep the node out of `missing`. Drain answers `409 NODE_FAILED` with the error for such a reply instead of `NODE_UNREACHABLE`.
* **A drained node rewrites its drain key at least every 20 s** (round-3 review body), not only every presence interval: an interval configured near or above the 60 s bucket TTL let the key expire, and the last-node guard then counted the drained node as serving.
* **The audit trail shows what a bulk replay or discard did** ("1 of 2 done", a warning when any failed) instead of a blank outcome: those entries record counts, not one outcome.
* **Fencing tokens and lease revisions are JSON strings** in the console API, exact beyond 2^53.
* **Cluster drawer focus:** an inline `onClose` re-ran the focus-return effect on every refresh and pulled focus out of the dialog; Tab no longer counts disabled controls as the last stop.

***

## ✨ feat(manager): UI for the 6.6 backend fixes — tool-call caps, typed property values, schedule disable reasons, one seat per agent, admin-action log, honest GDPR result, RAG store isolation (2026-10-04)

**Repo:** EDDI (`feat/manager-backend-gaps`)

### What changed and why

The open backend PRs of the 6.5 review (#944, #945, #946, #947, #950, #952) added fields, refusals and endpoints that the Manager could not show or set. Every new field is optional here and absent unless the author sets it — an older backend's strict configuration parser refuses unknown fields, so the Manager never writes one on its own — and every new response field degrades to "not reported" when an older EDDI does not send it.

* **LLM editor — tool-call caps (#946).** `maxToolCallsPerIteration` (default 20) and `maxToolCallsPerTurn` (default 100) in the Execution section, with the defaults as placeholders, what happens past a cap (`NOT_EXECUTED`, never reaches the approval gate, approval pauses counted), and a warning when `-1`/`0` switches a cap off. [`task-tool-call-limits.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/components/editors/llm/task-tool-call-limits.tsx)
* **Typed property values (#944).** Property-setter rows and every httpcall/MCP/LLM `preRequest`/`postResponse` instruction get a value-type select: text/template, integer, long integer (`valueLong`), decimal (`valueDouble`), float, boolean; objects and lists are shown and left to the JSON tab. Before, a typed row rendered an **empty** value field, and typing into it wrote `valueString` next to the typed slot — which the engine lets win. Choosing a type now leaves exactly one value slot; a row carrying several says which one runs. Out-of-range integers and longs past 2^53 are flagged. [`property-value-field.tsx`](https://github.com/labsai/EDDI/tree/main/ui/packages/app-kit/src/components/editors/property-value-field.tsx), [`property-value-utils.ts`](https://github.com/labsai/EDDI/tree/main/ui/packages/app-kit/src/components/editors/property-value-utils.ts)
* **MCP calls editor (#944).** `maxResponseSizeInBytes` (characters stored in memory, default 2,000,000), shown when the response is saved.
* **Schedules (#947).** A disabled schedule says why: *Agent undeployed* (comes back by itself at the next successful deploy) or *Access revoked* (names the creator and the fix). No reason means a person disabled it — including a schedule a 6.5 undeploy switched off, which needs one manual Enable; the row says so. The `400 {"error":"invalid_schedule","message"}` reason is shown inside the create/edit dialog instead of a generic toast.
* **Groups (#950).** The create dialog, the group wizard and the Workforce wizard no longer offer an agent another member already holds (keyed by `agentId` across member types, as the server keys seats); a repeated member is a pre-save problem, and the server's 400 is shown in the dialog.
* **Import (#950).** The merge preview explains the 6.6 merge scope when workspaces are enforced, and imports now send `X-EDDI-Space` — they bypass `ApiClient` for the zip body and never carried the selected space, so every import landed in the default space whatever the switcher said; with the merge scoped to the importing space that decided which copy a merge updated. Malformed-archive 400 reasons were already surfaced; they are now announced (`role="alert"`).
* **Audit page (#952).** A second tab, *Administrative actions*, over `GET /auditstore/admin-actions`: actor filter (server-side), method and time filters over the loaded rows, *Load older* paging, and explicit 403 (admins only) / 404 (older EDDI) / empty / error states. `?view=admin` deep-links to it. [`admin-actions-view.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/components/audit/admin-actions-view.tsx)
* **GDPR erasure result (#952).** `auditEntriesRedacted` tile, a plain-language paragraph on what happened to the audit ledger (redacted / kept under `erasure-mode=pseudonymize` / older EDDI that only pseudonymises), what *complete* now means, and a sentence per failed step (`auditRedaction` and others).
* **RAG editor (#945).** A `${…}` store location, a reserved `eddi_kb…` name and a non-plain pgvector table are flagged with the server's reasoning; the storage layout (own store by id vs. 6.5 name-based) is shown with its location; *Move to its own store…* sets `storeNamespace: "id"` only after a warning that the store starts empty, sources re-ingest and `/ingest` documents must be re-ingested. The store placeholders no longer suggest reserved `eddi_kb_…` names.
* **Review follow-ups.**
  * A failed `auditRedaction` step is no longer described as the `erasure-mode=pseudonymize` legal hold.
  * A finished one-time schedule reads "ran and is finished" instead of "disabled by a person". It is recognised by its shape (`oneTimeAt`, `lastFired` set, no `nextFire`), because `markCompleted` resets `fireStatus` to `PENDING`.
  * A saved 6.5 store location the 6.6 rules would refuse, such as `eddi_kb_…`, is shown as "keeps working as saved, would be refused if changed". The server re-checks a location only when it changes.
  * The *Administrative actions* tab is shown only to `eddi-admin` (`useHasRole`); its 401/403 state stays as the fallback. The pipeline trail is now a labelled `tabpanel`.
* **Platform Operator.** The cheat sheet now covers the tool-call caps and `NOT_EXECUTED`, the typed `value*` fields and MCP `maxResponseSizeInBytes`, and one seat per agent in groups. Revision 2 → 3. The admin-actions read is **not** added to the allow-list here: #952 adds it, and `findMissingEndpoints` would refuse operator activation on any backend without that endpoint if this PR merged first.
* **i18n:** 99 new keys in all 11 locales.
* **E2E (MSW):** `e2e/schedules.spec.ts` › "disabled schedule shows disabled status" asserted `getByText(/disabled/i).first().or(getByText(/dead.lettered/i).first())`. The new "Disabled by a person" note made the two halves match different elements, and `or` failed Playwright's strict mode. The test now checks sched-4's "Disabled" badge and `disabled-reason-sched-4`, and sched-3's `disabled-by-person-sched-3`.

### Design decisions

* **Never write a default.** Placeholders show server defaults; a blank field is absent from the JSON. That is what keeps every new field safe against a 6.5 backend's strict parser.
* **Client checks mirror the server, the server stays authoritative.** Duplicate members, RAG location rules and value ranges are checked as the backend checks them, and the backend's own refusal is still rendered where it can arrive.
* **Method/time filters are client-side.** The endpoint filters by actor only; the view says the other filters narrow the loaded rows and stops offering *Load older* once nothing further back can match the time window.

### Not done

* **#953 (A2A in-flight bound / 503):** no Manager surface. The bound is a server setting (`eddi.a2a.max-concurrent-requests`) observed through metrics, and the Manager has no A2A traffic view to hang it on; a one-off counter would duplicate the Grafana panel.
* **GDPR `resealed` / `keptUnverified`:** computed by the backend but only logged, not returned by `DELETE /admin/gdpr/{userId}`; the result paragraph explains re-signing in words instead.

***

## 💬 fix(chat): UX review of the standalone Chat UI (2026-10-04)

**Repo:** EDDI (`fix/chat-ui-ux`) — `ui/chat`, [`ui/chat/README.md`](https://github.com/labsai/EDDI/tree/main/ui/chat/README.md), [`security.md`](https://docs.labs.ai/security-and-compliance/security.md)

### What changed and why

A review of the standalone chat widget found a run of problems that cost users text, orientation or accessibility. Fixed in `ui/chat`:

* **Reading while it streams.** Auto-scroll fired on every token with smooth scrolling, fighting anyone who scrolled up. The view now follows only while the reader is at the bottom (an instant jump), a send re-engages it, and the scroll-to-bottom button shows when it is not following. Streaming bubbles re-parse markdown at most every 50 ms instead of per token.
* **`postMessage` token vs auto-start.** With `?tokenOrigin=` the conversation used to start before the host could send the token, so the start (and the review-notice lookup) went out unauthenticated. The widget now posts `{"type":"eddi-chat-ready"}` to each allowed origin by name (never `*`, repeated every second), holds the start until `eddi-chat-token` arrives, and gives up after 5 seconds and starts without one. Documented in the README and [`security.md`](https://docs.labs.ai/security-and-compliance/security.md).
* **A failed send no longer eats the message.** Any 4xx, a server error or a dropped connection before the first token withdraws the user bubble and puts the text back in the composer. If tokens had already arrived, the partial answer stays, "Connection lost — the response may be incomplete" is appended, and the conversation is re-read so the next send does not 409. The streaming, non-streaming and managed transports behave the same.
* **Typed failures have their own copy**: 409 (the backend's operator text, naming `POST /agents/<id>/resume`, is no longer shown), 401 ("session has expired"), 403, 404 (agent not ready), 413, 429, 503, and 410, which now always sets ENDED.
* **Stop works on every transport.** An `AbortSignal` is passed through `sendMessage` and `sendManagedAgentMessage`; a late reply for a stopped turn is ignored and stopping is not reported as a failure.
* **Start/empty states.** A failed start offers "Try again". An agent with no greeting shows "Say hello to get started" instead of "Starting conversation…" forever. A paused conversation whose approval status has not arrived shows an indicator.
* **Header.** `?title=` is rendered (and sets the tab title), and `?hideLogo=true` shows the text title instead of an empty bar, as the README always promised.
* **Safer controls.** "New conversation" asks first when the conversation has messages; an agent-requested input field has "Type a message instead"; the secret toggle has a fixed label with `aria-pressed`, is disabled mid-turn, and its tooltip now says what the vault does (hidden in the chat, masked in stored history) rather than "encrypted".
* **Accessibility.** IME composition (CJK, mobile keyboards) no longer sends on the confirming Enter, in the composer and the requested field. Avatars are `aria-hidden` and each bubble says who spoke ("You said:" / " said:"). The composer textarea has a label. Focus returns to the composer after a secret send or leaving the requested field. The paused card is no longer a nested live region and its minute-by-minute countdown is hidden from assistive technology in favour of a fixed clock time.
* **Look.** Inputs are 16px on phones (no iOS zoom), long quick replies wrap, accent tints use `color-mix()` so any CSS colour works, `?theme=` beats a remembered preference and the toggle cycles dark, light, system.
* **Notices are not agent bubbles.** Text the widget wrote (failed sends, undo failures, cancellations, upload problems) renders as a system notice.
* **Undo/redo** now rebuild quick replies and the requested input field from the snapshot, and undoing to an empty conversation clears the old bubbles.
* **Copy buttons** on agent messages and code blocks.
* **i18n.** The widget's own text is a small string table (`src/i18n.ts`: English, German, French, Spanish), chosen by `?lang=` or the browser language, falling back per key to English; `<html lang>` follows. Documented in the README.

### Design decisions

* One module-level locale rather than React context: the SSE and HITL copy helpers live outside React and must translate too.
* Notices are a `kind: "notice"` flag on `ChatMessage`, so existing transcript code is untouched.
* The restart confirmation is inline, not a modal, because the widget is often a small iframe; an untouched conversation restarts without asking.
* The ready-signal repeats until the token arrives because the parent's listener may not exist when the iframe's first message goes out.

### Deliberately not done

* `button` output items stay bold text: `onPress` is a free-form map for clients that implement it, with no contract this widget could honour, so there is nothing safe to click.
* The 403 on start cannot be told apart as an origin rejection (the response does not say), so its copy names both causes without accusing the user.
* Only English, German, French and Spanish are translated; the Manager's other seven locales (ar, hi, ja, ko, pt, th, zh) fall back to English until their tables are added.

**Files:** [`ChatWidget.tsx`](https://github.com/labsai/EDDI/tree/main/ui/chat/src/components/ChatWidget.tsx), [`i18n.ts`](https://github.com/labsai/EDDI/tree/main/ui/chat/src/i18n/index.ts), [`MessageBubble.tsx`](https://github.com/labsai/EDDI/tree/main/ui/packages/conversation/src/components/Message.tsx), [`ChatInput.tsx`](https://github.com/labsai/EDDI/tree/main/ui/packages/conversation/src/components/Composer.tsx), [`SecretInput.tsx`](https://github.com/labsai/EDDI/tree/main/ui/packages/conversation/src/components/SecretInput.tsx), [`PausedCard.tsx`](https://github.com/labsai/EDDI/tree/main/ui/packages/conversation/src/components/PausedCard.tsx), [`ChatHeader.tsx`](https://github.com/labsai/EDDI/tree/main/ui/chat/src/components/ChatHeader.tsx)

***

## fix(manager): config editors and the Agent wizard (2026-10-04)

**Repo:** EDDI (`fix/manager-editors-wizard`), `ui/manager`

### What changed and why

Findings from a UX review of the Manager's config editors and the Agent setup wizard.

**LLM editor.** `modelName` (`deploymentName` for Azure OpenAI), `apiKey` and `temperature` were only reachable through a collapsed generic key/value grid. They now have their own "Model" section above the prompt: a model field with the provider's suggestions, the existing vault/secret picker for the key (no connection references, which the backend refuses in model parameters), and a temperature field that validates its input. The model key, credential key and temperature come from a per-provider table checked against the backend builders (`components/editors/llm/model-params.ts`): `model` for Ollama, `modelId` for Bedrock, Hugging Face and Vertex, `deploymentName` for Azure, `modelName` otherwise; the credential is `apiKey`, `accessToken` (Hugging Face) or `authToken` (Jlama, optional), and is not offered for Ollama, Bedrock, Vertex and Oracle GenAI, which authenticate elsewhere. Only the keys the section surfaces for the provider leave the generic grid, and a grid row cannot be renamed onto them. A new task starts with the `send_message` action and the default provider's model instead of no actions and no model; a task with no actions or no model shows a warning. Changing the provider swaps the model only when it is exactly the previous provider's default.

**Shared components.** `ActionTags` existed four times (LLM, rules, API calls, property setter) and none of them kept text typed but not yet added, so an edit was lost on blur and the dirty check never saw it. One component in `components/editors/action-tags.tsx` now commits on Enter, comma, blur and the Add button, splits a pasted comma list, ignores Enter during IME composition, and suggests actions emitted elsewhere in the same config. `components/editors/editor-field.tsx` adds a `Field` that wires `id`/`htmlFor`/`aria-describedby`.

**Rules editor.** New condition configs use `nextFreeKey` (`key${count}` overwrote `key1` after `key0` was deleted). `occurrence` (inputmatcher, actionmatcher), `contextType` and the capability `strategy` are selects; a stored custom value stays selectable. Changing a condition's type asks first when the user entered something beyond the type's presets. Lint warnings: a rule with no `actionmatcher` on `lastStep`, and a comma list in `actionmatcher.actions` (AND semantics). Rules and groups can be moved up and down, since order decides which rule fires first.

**Accessibility.** Labels tied to inputs in the LLM, rules, API-calls, MCP-calls, output and property-setter editors (`htmlFor`/`id` where the label is visible, `aria-label` in compact rows); names on the icon-only remove and expand buttons.

**Output editor.** Invalid JSON in the onPress / fallback field was silently reverted on blur; it now stays in the field with an inline error until fixed or cleared.

**Agent wizard.** There is now one deploy mechanism: the Review step has a deploy target (default **Test**, was Production) and two buttons, "Create without deploying" and "Create & deploy to test/production". The Auto-Deploy toggle on the Features step is gone. Review lists the API key as "None", "Not needed", "Vault reference X" or "Entered here", never the key. The model field is prefilled with the provider's default (also after a provider switch). Step circles have an accessible name and `aria-current`; the API-key label points at the field; the Model step is a `<form autocomplete="off">` so the browser stops warning about a password field outside a form.

**Agents list.** The card footer wraps instead of clipping "Undeploy from production" and wrapping the timestamp at 375px.

### Design decisions

* Deploy is decided by the button, not a switch, because a switch on an earlier step could disagree with the button pressed later.
* A comma list in an actionmatcher is warned about, not blocked: AND is legitimate for an action sequence.
* Labels in dense rows use `aria-label` with the visible text rather than a layout rewrite.

### Deliberately skipped

* The `<label>` elements used as captions over groups of controls in the LLM editor (they label no single control) were left as they are.
* Index-keyed rule and condition components keep their expanded state by position when reordered; only group expansion follows the group.

***

## fix(manager): error surfacing, session handling and shared dialogs (2026-10-04)

**Repo:** EDDI (`fix/manager-errors-auth-dialogs`), `ui/manager`

### What changed and why

From a UX review of the Manager:

* **Auth.** A failed Keycloak init used to render the whole app unauthenticated, so every page read "Something went wrong". It now shows a "Sign-in failed" screen with **Sign in again**. The API client renews the token before each request (`updateToken(30)`, so a token that expired in a throttled tab is not sent), and on a 401 forces one refresh and retries once. When that fails the Manager shows a non-destructive "session expired" banner over the still-mounted app instead of calling `keycloak.logout()` immediately, which dropped unsaved work.
* **ErrorState** accepts the error object and says 401 / 403 / 404 / "can't reach EDDI" in its own words, with the server's message beneath. About 25 callers now pass `error`.
* **Global mutation fallback** (`lib/query-client.ts`): a failed mutation that nobody reported is toasted with the server message. It stays quiet for `meta: { silent: true }`, for mutations with a hook-level `onError`, and when the caller toasted an error within 50 ms (call-site handlers cannot be introspected, so this is how double toasts are avoided). 401s are left to the session banner.
* **Dashboard** no longer shows zeros for failed reads: all-failed is an error state, a partial failure shows "—" on the affected card plus a retry notice. The vault strip says "checking" while loading, the skeleton draws 3 cards (as many as render) and conversation states are translated.
* **Orphans**: a failed scan renders the error, a refused purge shows the server's reason (409), each orphan links to its detail page, and Purge All is an `AlertDialog` that needs the orphan count typed.
* **AlertDialog** ignores Escape / backdrop / X while its action is pending, and its default labels and the sr-only "Close" are translated. "Authenticating…" is translated too.
* **Capabilities** shows agent names instead of raw ids (no external-link icon), has an explanatory empty state, labelled search / strategy controls and `aria-expanded` on rows.

### Decisions

* The QueryClient moved into `lib/query-client.ts` (a `MutationCache` needs to be built with it); `main.tsx` only imports it.
* Not done: the `404 GET /variablestore/variables/default/platform.operator` console line. `readOperatorConfig` already treats the 404 as "not configured"; the line is the browser's own network log and cannot be suppressed without a backend change (e.g. a 200 with an empty body).
* Raw-`fetch` modules (SSE, `text/plain` chat) still read `api.getAuthHeader()` without a pre-flight refresh.

***

## 🐛 fix(manager): group page, approvals inbox and Platform Operator drawer UX review (2026-10-04)

**Repo:** EDDI (`fix/manager-group-approvals-operator`) — `ui/manager` only, no backend change.

### What changed and why

Findings from the Manager UX review, for the group detail page, the Workforce board hand-offs, the approvals inbox and the Platform Operator drawer.

**Approvals**

* The nav badge counted only 1:1 approvals, so it disagreed with the page it links to. It now counts the same merged, de-duplicated set the inbox shows: 1:1 pauses, group phase approvals and HUMAN members' turns.
* Inbox rows lead with the agent's or group's name (the id is the second line, under a translated "Conversation" header, no longer a bare "ID"). Names, group ids, member ids and tool names are searchable. A HUMAN-turn row shows the member's display name instead of the raw id.
* A group phase approval can be reviewed in place: a "Review" row shows the question, the paused phase, the last entries of the transcript and the same `ApprovalBanner` the 1:1 tool-call rows use (note field, per-task verdicts), so the decision is no longer made on the pause reason alone.
* On a phone the table lays out as cards (labelled cells) instead of scrolling sideways, so Approve/Reject sit with their row.
* Workforce "Review it" now carries `&conversation=<id>` so the group page opens the paused discussion, not the newest.

**Composers**

* The discussion composer, the Workforce board composer and the follow-up composer keep the typed text (and files) until the request is accepted, and restore it when it is not. "Streaming live" toasts fire on the first SSE frame, not on the click. New store field `GroupStreamState.connected` and `whenStreamAccepted()` / `streamErrorOf()` in `use-group-discussion-stream.ts` make "accepted" observable.
* The group page composer defaults to a NEW discussion; an explicit New / Continue toggle appears when the selected discussion can be continued. Picking a discussion from the history (or arriving by link) means continue.
* The follow-up target list offers AGENT members only (HUMAN members have no agent to ask).

**Group page**

* A dropped live connection shows the same `role=status` notice as the Workforce board.
* The transcript only follows new entries while the reader is at the bottom, with a "New messages" button otherwise; the body is a polite `role=log` region, a pause is announced, and focus/scroll moves to the approval or human-turn banner. The HTML toggle reports `aria-pressed`.
* The history list loads older discussions ("Load older discussions", 20 at a time); the mobile history button is labelled, reports `aria-expanded` and closes on Escape.
* SYNTHESIZING discussions can be cancelled; deleting a running discussion stops it first (and says so). Escape leaves fullscreen unless a dialog or the history dropdown owns it.
* Opening one config editor no longer discards another's draft (the other Edit buttons are disabled while one is open); hiding the panel, going fullscreen or closing the sheet asks before discarding an open editor. A link to the Workforce settings (where name, members, moderator, style and rounds are editable) was added to the panel.
* After a human-turn submit the page says the discussion is resuming. The backend resumes it asynchronously and has no stream to reattach to, so the page keeps following the persisted conversation (polling); the mutation now stays pending until the refetched conversation lands.

**Platform Operator**

* Escape no longer closes the drawer when a dialog is open over it or the key was already consumed; the unsent draft lives in the operator chat store, so it survives closing the drawer; Enter during an IME composition no longer sends.

### Design decisions

* "Edit basics / members" is a link to Workforce settings rather than a second editor on the group page: that screen already edits every core field through `update_group`, and a second one would have to keep step with it.
* Draft restore is done by holding the draft until a promise settles (`onSubmit` / `onSend` / `onFollowup` may return `Promise<boolean | void>`; only `false` or a rejection keeps it), so the composers stay usable by callers that return nothing.
* Not changed: `system-prompt.ts` / `tool-scopes.ts` (nothing the Platform Operator documents moved), so `operator-revision.json` is untouched.

### Deliberately skipped

* Attachments chosen with a refused Workforce board start are not restored (the question text is); files are re-staged from `File` objects the board no longer holds once its view is replaced by the error screen.

***

## fix(manager): in-app navigation no longer discards unsaved edits; shell, tour, palette and top-bar fixes (2026-10-04)

**Repo:** EDDI (`fix/manager-navigation-guard`), `ui/manager`

### What changed and why

Workstream A1 of the Manager/Chat UX review: routing, navigation chrome and the unsaved-changes guard.

* **Unsaved-changes guard now covers in-app navigation.** The app moved from `<BrowserRouter>` to a data router (`createBrowserRouter` + `RouterProvider`, `src/app-router.tsx`), so a router blocker is available. There is exactly ONE blocker for the whole app, mounted by `NavigationGuardDialog`; `useUnsavedChangesGuard(isDirty)` only registers a dirty token (keyed by `useId()`) in a store, and the blocker holds a path change while any token is registered. (A router consults only the last registered blocker, so one blocker per guard let a later clean guard unprotect a dirty page.) A sidebar link, breadcrumb, command-palette jump or the Back button on a dirty page now asks Stay / Discard (`NavigationGuardDialog`); only a path change is held, so switching a tab through a query parameter is not. The hook's signature is unchanged, so every page that already calls it is protected. `allowNextNavigation()` is the one-shot escape hatch for programmatic navigation whose edits are already resolved (delete, confirmed discard); it is wired into the connection, workflow and resource detail pages.
* **A crashing page no longer wipes the shell.** `SuspendedOutlet` carries an `ErrorBoundary` keyed on the location, so the sidebar and top bar survive and any navigation recovers.
* **Mobile navigation drawer**: closes on route change, is a modal `dialog` with a focus trap, takes focus on open, closes on Escape and gives focus back. The language selector, hidden in the top bar below `sm`, is reachable in the drawer. `isMobile` starts from the real width (no desktop-sidebar flash); sidebar collapse state is now remembered.
* **Guided tour**: keys and the body scroll lock attach only while the target is on screen; Enter on a focused Back / Skip button no longer advances; the chapter ends (not marked done) on route change; a missing target is waited for with a `MutationObserver`, then the step is skipped after 8 s (the chapter is abandoned only if it was the last step), so the dashboard tour still works on a phone where the sidebar target sits in the closed drawer; the Help-menu replay waits for the page instead of a fixed 300 ms; the tooltip takes focus.
* **Unknown routes** show a Page not found screen inside the shell (`/manage/*`, `/workforce/*`, top level) instead of silently redirecting to `/welcome`. `/welcome?choose` shows the chooser even when a landing preference is saved.
* **One route-label registry** (`src/lib/route-registry.ts`) now feeds the breadcrumb, document title, command palette and sidebar. `/manage/groups/wizard` no longer reads "Agent Wizard", nine sections no longer show raw lowercase segments, and an agent detail page shows the agent's name.
* **Command palette**: built on cmdk's `Command.Dialog` (modal, focus trap, focus return); Create New Agent opens the wizard (the old `?action=create` target was read by nothing); lists every page; agents are searched on the server (30 rows, one per agent, debounced, only while open); Ctrl+K is left alone inside Monaco.
* **Top bar**: language selector has an accessible name; the user menu is a Radix `DropdownMenu` (arrow keys, Escape, focus return); the current page name and a compact status dot show on phones; breadcrumb label is translated.
* **Toasts follow the resolved theme.** `ThemeProvider` storage access is wrapped in try/catch.
* **Mode switcher** is a pair of links, not an ARIA tablist, and no longer rewrites the saved landing preference (only the chooser's explicit choice does).
* **Stacked dialogs**: the unsaved-changes dialog handles Escape in the capture phase and stops it, and `AccessibleDialog` ignores an already-handled Escape, so one press closes one dialog.
* Smaller: collapse state per section is stored by stable id (old index saves are still read); Help-menu completion is announced; the untranslated "Checking version...", "Expand/Collapse sidebar" and "Breadcrumb" strings are translated in all 11 locales.

### Design decisions

* `<App />` keeps its `<Routes>` table under a single catch-all data route rather than converting every route to route objects: no route, lazy page or layout changed, and every existing `MemoryRouter`-based test still renders `<App />`.
* `NavigationGuardDialog` mounts the blocker only when a data router is present (`UNSAFE_DataRouterContext`), so component tests with a bare `MemoryRouter` keep working (the hook still registers its token and `beforeunload`); the data-router behaviour has its own tests, including a clean guard mounted after a dirty one.
* The dirty-page prompt reuses `UnsavedChangesDialog` with a "Stay" label.

### Deliberately skipped / follow-ups

* Server-side agent search relies on the descriptor listing's existing `filter` text match.
* The workforce shell keeps its own responsive handling; only its not-found route was added.

***

## Manager: conversations, monitoring, user data, GDPR and chat UX fixes (2026-10-04)

Repo: EDDI (`ui/manager`), branch `fix/manager-conversations-userdata-chat`. Fixes from the Manager UX review.

**Destructive actions**

* User Memory: the row trash button now opens an `AlertDialog` naming the key before the permanent delete, and only the row being deleted is disabled (previously one pending delete disabled every row). "Delete All" shows the user id and entry count, and deletes the id it was opened for, not the debounced input.
* GDPR erasure requires typing the user id back (same pattern as the vault reset). An erasure whose counters are all zero, which is what a mistyped id produces, shows a neutral "No data found for this user id" instead of a green "Erasure Complete".
* Monitoring: the purge of ended conversations is now its own bordered section whose title, description and confirmation say it applies to all agents (the backend purge has no agent scope; there is no count or dry-run endpoint, so none is shown). The days field can be emptied while typing and is validated on Purge.

**Conversations list and detail**

* Filters, search, agent, version, page and page size live in the URL (`q`, `state`, `agent`, `version`, `page`, `size`); the detail page's Back link returns to that exact list (passed via router state, validated to a `/manage/conversations` path). Monitoring keeps `agent` and `version` in the URL.
* A later page that comes back empty shows "No more results" with a way back instead of the "deploy an agent" empty state; deleting the last row of a later page steps back automatically. The backend still reports no total, so Next stays enabled on a full page.
* Card delete button is no longer nested inside the card link (stretched-link overlay on the id); the detail delete button has an accessible name. Agent names resolve for up to 1000 agents through one memoised map instead of the first 50 and a per-row regroup.
* Detail page polls every 3 s while `IN_PROGRESS`, the transcript search is labelled and announces a match count, and the Markdown export carries per-step timestamps.

**User data**

* One user id is shared by the Memories, Properties and Conversations tabs and kept in `?user=`; tabs have ids and accessible names on mobile (the panel's `aria-labelledby` pointed at nothing).
* The create-binding dialog uses the shared `AccessibleDialog`, an `AgentPicker` for the agent, and `htmlFor` labels.

**Chat**

* The transcript is a polite `role="log"`; Enter no longer sends mid-IME-composition in the chat panel, the drawer and the secret field; the secret-mode toggles are named and expose `aria-pressed`; the agent selector is keyboard-operable (search box, arrows, Home/End, Enter, Escape returning focus).

**Deliberately skipped**

* "New chat opens with a user message before the welcome": a mock artefact. The MSW handler's `conv1` fixture is the conversation the panel reopens (most recent READY one) and it carries a user turn; the logic that builds messages is correct, and the handler already returns welcome-only for freshly started conversations.
* Conversation state "shown raw": every list/detail/monitoring surface in this stream already localises it.
* No export or count preview for GDPR erasure: the existing export endpoint is the full bundle, and the memory count covers one category only.

***

## Manager: group and workforce wizards, group templates and workspaces UX fixes (2026-10-04)

**Repo / branch:** EDDI, `fix/manager-group-wizards` (UX review stream C1; Manager only, no backend change).

**Group wizard (`pages/group-wizard.tsx`)**

* **No duplicate agents on retry.** When creating the moderator failed, the wizard returned without writing the members it had already provisioned back into its state, so clicking Create again provisioned and deployed every member a second time. Every failure path now persists members and moderator progress (one `abort` helper). Regression test `group-wizard-ux.test.tsx` fails (12 setup calls instead of 7) with the fix reverted.
* **API keys and providers.** A new advisor on a provider that needs a key is now blocked on the Members step with a per-member sentence (the same `providerNeedsKey` rule the Workforce wizard uses), instead of the backend rejecting the setup request after earlier members were deployed. Keys for keyless providers are no longer sent. A "same provider and key for all new agents" block applies one provider/model/key to every advisor still to be created. Provider pickers (members, moderator, bulk, and the Workforce wizard's team builder) offer only providers `isProvisionableBySetup` accepts, so Vertex AI is no longer offered.
* **Why Next is disabled.** The wizard lists what is missing under the step (name, HITL phases and timeout, style, member count, each member's name / principal id / group / agent / key, turn timeout). The same list gates Next.
* **Unsaved work.** Both wizards guard reload and tab close once anything is configured, and ask before Back, Cancel and "Back to groups" discard it (`useLeaveConfirm`, built on `useUnsavedChangesGuard` plus the existing `UnsavedChangesDialog`). After a confirmed leave or a successful create the guard is released first, so a router-level block never prompts twice.
* **Stepper and styles.** Visible step titles (sm and up), per-step `aria-label`, `aria-current`. Style cards are a `radiogroup` of `role="radio"` / `aria-checked`, carry a "best for" line, and the selected style shows its full flow. Max Rounds explains what a round is and shows an estimated call count (members x rounds, plus one for a moderator).
* **Turn timeout** is a number plus a minutes/hours/days picker that serialises to ISO-8601 (`DurationField`, `lib/iso-duration-parts.ts`).
* **i18n and labels.** Default member and moderator prompts and placeholders are translated and no longer say "a Engineering expert"; member name, role, prompt and model inputs have labels; the Agent/Group type toggle is localised and exposes `aria-pressed`. The Guided Setup card on the Groups page has group-specific copy.
* **Two template systems** are now named: the wizard's client presets are "starter presets" with a link to the packaged Group Templates, and the templates page links back to the wizard. Role chips are humanised and de-duplicated (`Forecasting x4`, `Devil advocate`, `lib/role-labels.ts`).

**Other pages**

* **Group templates:** the selected template is a `?template=` search param, so browser Back returns to the gallery, a reload keeps the selection, and the error view's Back link goes somewhere different from where the user is.
* **Group workspace:** subject, description and prompt-template inputs are labelled; `P{n}` has a tooltip and the priority field says higher numbers are picked first; the cadence time zone is a select defaulting to the browser zone instead of free text defaulting to UTC.
* **Workspaces:** deleting a variable asks for confirmation, like deleting a secret.

**Decisions / deliberately skipped**

* Backlog task edit/delete was **not** added: there is no per-task update or delete endpoint on REST or MCP (`lib/api/group-workspace.ts` documents it). The page now says tasks cannot be edited or removed once added. Needs a backend change if wanted.
* The Workforce wizard stepper already has visible labels, `role="list"` and `aria-current`; nothing to change there.
* The key requirement is checked client-side only for AGENT slots in Create New mode; a slot already created by an earlier attempt is not re-validated.
* Existing group wizard tests that walk to the Review step now apply a bulk key first, because the Members step no longer lets a keyless Anthropic advisor through.

***

## Manager ops/admin pages: logs, audit, schedules, triggers, secrets, connections, channels, quotas (2026-10-04)

Repo: EDDI (`ui/manager`), branch `fix/manager-ops-admin-pages`. Workstream D2 of the UX review.

**Logs.** History rows show the date (year only when not the current one); every timestamp carries its ISO-8601 time with offset in its title, and the Live export and per-row copy now write `[2026-10-04T11:11:05.123+02:00] [LEVEL] message` instead of a bare time. The "1 errors / 2 warns" counters are real plurals (`logs.errorCount`, `logs.warnCount`, all 11 locales with their plural categories). When the SSE retry budget is spent (`onexhausted`) the Live tab now says "Disconnected" with a Reconnect button instead of pulsing "Connecting…" forever (`session-log-store` and `use-logs` expose `exhausted` / `reconnect`; `StreamBadge` gained an `exhausted` prop). History filters and the active tab live in the URL (`?tab=history&agent=&conversation=&instance=&level=`). A text search that matches nothing shows a "no loaded entries match" state and the box says it searches loaded entries only. The per-row copy button is visible on keyboard focus and on touch, copy failures toast, and agent columns show names (new `useAgentNames` hook; id in the title). The debugger's `LiveLogViewer` is no longer an `aria-live` region over a 500-line stream: it announces a throttled error count through a separate status region.

**Audit.** Timestamps show full date, seconds and UTC offset with the ISO form in the title (new `lib/date-format.ts`). "By Agent" lists every agent, deployed ones in their own group, instead of only deployed ones. The search (mode, agent, version, conversation) is in the URL.

**Schedules.** The one-time Date & time is read as wall-clock time in the selected Time Zone (Intl-based `zonedLocalInputToIso`, DST-safe) instead of the browser's zone, with help text naming the zone; the list shows `oneTimeAt` in the schedule's zone with the zone name. Last Fired now carries the same zone label as Next Fire. Error toasts append the server's reason. Every form label is tied to its control; the agent field is the shared `AgentPicker`; the agent column shows names; the active tab is `?tab=failed`.

**Secrets / Variables.** The hand-rolled delete overlay (focus never moved in, so Escape did nothing and Tab reached the page) is the shared Radix `AlertDialog`; the delete error path goes through `secretsErrorMessage`; Allowed Agents shows names; clipboard failures toast.

**Channels / Connections / Quotas / Triggers.** Channel delete no longer leaves an unhandled rejection and an open dialog on failure (toast + close, as connections). `channel-detail` and `quotas` call `useUnsavedChangesGuard`; channel-detail computes dirtiness against the stored configuration. Quota fields keep their text while typing, treat empty as unlimited (`-1`, the backend sentinel) rather than `Number("") === 0`, reject negatives (other than -1) and fractional counts, and block Save with an inline error; labels tied to inputs. The trigger dialog disables Save and says why when no agent is chosen. Connection delete names the connection and toasts success. Channel-detail labels tied to inputs.

Decisions: new strings use inline plural keys per locale (zh/ja/ko/th carry `_one` equal to `_other`, as elsewhere). `schedules.oneTimeHelp` and `logs.errors`/`logs.warnings` are now unused keys, left in place. The MSW Daily Health Check fixture (`nextFire = now + 12h`) was the source of the "Sunday 8:51 PM" next fire for a weekday cron; the display logic was correct, so only the fixture was fixed. The Logs "Reconnecting…" beside live entries in mock mode is the MSW SSE stub not holding a stream open (entries come from the REST seed); not a display bug, not changed.

Documented in `docs/scheduling.md` (one-time input zone).

***

## NATS cluster mode, independent review: lease, fence and dead-letter fixes (2026-10-03)

**Repo:** EDDI · **Branch:** `review/p11a` (on `feat/nats-cluster`)

An adversarial review of the runtime-selectable cluster mode (leases, fencing, dead letters) turned up eight defects. Each is fixed here with a test that fails without the fix.

### What changed

* **A fence is raised when a turn starts, not only when it writes** — [`IConversationMemoryStore.raiseFence`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/memory/IConversationMemoryStore.java) (MongoDB `$max`, PostgreSQL guarded `jsonb_set`; neither touches the revision) runs from [`ConversationStepRunner`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/ConversationStepRunner.java) and the HITL resume as soon as the lease is bound. The stores refuse a write whose token is older than the stored `_fence`, but the stored value only moved when some write landed: a holder whose lease had expired (a paused JVM, a pipeline thread the watchdog had abandoned) could still write in the gap between its successor acquiring the lease and the successor's first write, persisting a turn that never saw the successor's. Found by pausing a node's container past the lease TTL.
* **A turn that lost its lease no longer stamps a state on the conversation** — it was cancelled, and the cancel path then moved the conversation to `EXECUTION_INTERRUPTED` by an unfenced state write, so a conversation whose successor turn had just committed read as interrupted until its next turn. The cancelled turn now leaves the state to whoever holds the lease. Found live by pausing a node past the lease TTL.
* **A holder is no longer robbed because its presence record could not be read** — [`KvLeaseManager`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/cluster/lease/KvLeaseManager.java) treated an unreadable presence bucket (a different bucket from the leases, so it can fail alone) as "node gone" and, for any lease older than three presence intervals by the *holder's own clock*, deleted a live lease by compare-and-set — so any turn longer than 30 s could be taken over under a presence blip or a skewed clock. An unreadable lookup is now unknown, and a holder with no presence record is taken over only after this node has watched the lease revision stay unchanged for three heartbeat intervals (a live holder rewrites it every one).
* **A release racing the heartbeat no longer holds the conversation for the whole TTL** — the release deleted at the last revision it knew; if the heartbeat had renewed the key between, the delete missed and the key stayed until it expired (20 s without a turn on that conversation anywhere). The release now re-reads and deletes its own key at the current revision.
* **Two deployments on one NATS no longer share the dead-letter stream** — every other stream and bucket is named after `eddi.nats.prefix`, the dead-letter stream was not, so a second prefix rewrote the first one's stream subjects on every reconnect. The default name now follows the prefix (`EDDI_DEAD_LETTERS` stays for the default prefix; an explicit `eddi.nats.dead-letter-stream-name` is used as given).
* **Discarding a dead letter by sequence can no longer delete an audit dead letter** — the stream also holds audit-ledger entries that could not be stored; `get` already hid them, `delete` did not.
* **NATS credentials in a server URL are not logged** — `nats://user:secret@host` is logged as `nats://***@host`.
* **The lease wiring of a turn has a unit test** — [`ConversationStepRunnerLeaseTest`](https://github.com/labsai/EDDI/tree/main/src/test/java/ai/labs/eddi/engine/internal/ConversationStepRunnerLeaseTest.java) covers the fence token on the memory, the raise, the lost-lease cancel and the unfenced paths; removing the wiring used to fail nothing below the integration test.

### Design decisions

* The raise costs one small update per clustered turn (none in `in-memory` mode, where the default `raiseFence` does nothing and no lease is ever bound).
* It does not bump the revision, so the turn that is about to write on the revision it loaded does not conflict with it.

### Fixed after the review

* **A recreated leases bucket no longer locks conversations out.** The fence is the lease's KV revision, and a recreated `<prefix>_LEASES` bucket (after NATS lost its data, or to change its replica count — which the log line suggested) restarted at 1, below every `_fence` already stored: every write to those conversations was refused for good. A new leases bucket is now created with its first sequence at its creation time in microseconds ([`NatsSharedStateFactory`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/cluster/NatsSharedStateFactory.java)), so a later bucket starts above everything an earlier one handed out unless that one averaged more than a million lease operations a second over its whole life. The replica-count log line now says recreating it is safe, and how. `ClusterCoordinatorIT` deletes and recreates the bucket against a real NATS server and checks the next fence is higher. A bucket created by an earlier build still counts from 1 until it is recreated once.
* **Dead letters kept on a node while NATS was down are forwarded on reconnect** to the shared stream, so every node lists them and they survive that node's restart.
* **PR #956 review fixes.** A turn whose lease binding throws is now answered, its lease released and the queue drained, instead of wedging the conversation. A dead letter of a turn flagged `secretInput` keeps neither the input nor its context (it is marked and cannot be replayed). Paging dead letters past a node-local entry no longer repeats the local ring. An outbox flush that hits a closing connection puts the event back instead of dropping it, and flushed events count in `eddi.cluster.events.published`. Node RPC tolerates one unreadable scatter reply and logs a failed subscribe instead of throwing into the connect listener. `ClusterCoordinatorIT` picks a free host port instead of a fixed 4319.
* **CodeRabbit reviews stacked PRs.** A new [`.coderabbit.yaml`](https://github.com/labsai/EDDI/tree/main/.coderabbit.yaml) lets auto-review run on PRs into any base branch, not only `main`, because the stacked NATS PRs were being skipped as "base/target branches other than the default branch".
* **A turn stopped by a lost lease is dead-lettered and its caller told (console live re-check).** When a node lost a conversation's lease mid-turn, whether through a partition, a long pause, a NATS blip or an administrator force-releasing it, the turn was cancelled at its next task boundary. The client still got HTTP 200, but the turn was neither stored nor dead-lettered: it never reached a write. Now it is dead-lettered with its input (none for a `secretInput` turn), with `reason: lease-lost` and its fencing token added to the dead letter's turn record, and `failedOn` naming the node. If the reply has not gone out yet, the caller is answered as not processed: 409 with `Retry-After` over REST, an error event on a stream. The turn still stamps no state.
* **The first dead letter of a new cluster reaches the shared stream.** It was seen live while checking the lease-lost fix. The dead-letter stream is created by the first dead letter that needs it, and a publish right after the creation got "no responders" while the replicated stream elected its leader. The entry fell back to the node-local ring, and that ring was forwarded only on a reconnect, so it stayed on one node. Now the publish after a creation retries for up to 2 s, and a dead letter kept locally while NATS is connected is forwarded again after 10 s.
* **A lost KV race is a conflict whichever code NATS answers with (ported from the console branch).** The loser of two concurrent creates of one key can get JetStream error 10164 as well as 10071. `NatsSharedKv` recognised only 10071, so two nodes racing for one lease could report NATS as unreachable. Create, compare-and-set and guarded delete now treat both as a lost race. `ClusterPresence.currentMembers()` reads the member list uncached and throws on a read error, for decisions that must not be taken on a stale or empty list; `members()` keeps answering from its cache.
* **A dead letter is stored once (PR #956 review).** Every attempt to store one dead letter now carries one JetStream `Nats-Msg-Id`: the retries after a stream creation, and a later forward from the node-local ring. The id is derived from the node, conversation, time and error. The dead-letter stream de-duplicates within a 2-minute window, so a publish the server stored but whose acknowledgement was lost is not stored a second time. `ClusterCoordinatorIT` checks it against real NATS.

### Known and not fixed here

* A fenced-out turn's caller still gets the reply it was rendered (HTTP 200), where the design says 409: the output is handed to the caller from inside the pipeline, before the write the fence then refuses — the same path the pre-existing concurrent-modification refusal takes, and changing it means holding every reply until its write commits. The turn is dead-lettered with its input and counted in `eddi.cluster.fence.rejected`, which is the signal.

***

## Cluster mode, review of the shared-state and delivery branches (2026-10-03)

**Repo:** EDDI · **Branch:** `review/p11b` (on `feat/nats-cluster-deploy`)

An independent review of `feat/nats-cluster-state` and `feat/nats-cluster-deploy`. Each fix below belongs to the branch named in its commit body.

### What changed

* **Helm and Kustomize (deploy):**
  * The in-chart NATS user could not publish to `$O.*.>`, so the exported-archive object store never worked on Kubernetes (a permission violation in the NATS log, the archive silently kept on one node).
  * NATS probes were inverted: liveness was the strict `/healthz` and readiness the weakest check, so a rolling update could restart the next node before the first had caught up its R3 streams. Startup is now strict, readiness is `js-server-only`, liveness `js-enabled-only` (chart and `k8s/overlays/nats`).
  * With `networkPolicy.enabled` and `nats.externalUrl` every replica was cut off from NATS (the HTTPS rule excludes private ranges): the policy now opens the URL's port, narrowable with `networkPolicy.natsEgressTo`.
  * `eddi.updateStrategy` accepts the Deployment's own strategy object as well as a string, so a values file written for the other shape no longer renders `type: map[type:Recreate]`.
* **Shared state (state):** a `WorkflowFactory` build that dies with an `Error` no longer leaves an incomplete future in the cache that blocks every later caller; two concurrent downloads of one exported archive no longer write the same partial file; an unrecorded (`autoDeploy=false`) redeploy of a version that was recorded once is no longer undeployed by the reconciliation sweep; the HITL recovery sweep forgets conversations that left IN\_PROGRESS.
* **Docs:** NATS as a trust boundary, the nonce degraded behaviour as it actually is, moving from one node to a cluster and back, and the residual limits the review found (audit chain gap after a node crash, cache staleness bounds, the undeploy convergence window).

### Design decisions

* Docs describe the audit gap instead of reserving ranges: the design rejects ranges, and the window is the audit flush interval.
* Cache staleness bounds are documented, not shortened: prompt snippets have no event and rely on their 5-minute TTL.

### Merge notes for the open PRs

* `eddi.updateStrategy` (#938) is an object there and a string here; the chart now accepts both, but #938 also documents `RollingUpdate` with in-memory messaging as an opt-in, which this branch refuses.
* `helm/eddi/Chart.yaml` and `EXPECTED_CHART_VERSION` conflict with #938 and #951 (both 2.4.0).
* `AuditLedgerService`: #952 changes `pseudonymiseIfErased` to take a flag and redact content; a user erased on another node (`gdpr.user-erased`, by hash) is pseudonymised here but must also be redacted there. #952 still takes the `Instance<Connection>` constructor parameter.
* \#953 (`CachedA2ATaskStore`) composes with the KV-backed `A2A_TASKS`/`A2A_CONTEXTS` caches (`A2ATaskRecord` round-trips through Jackson); `A2A_STATES` becomes unused, and the task record carries the user's and the agent's text into the KV bucket for the task TTL, which the GDPR erasure does not purge.

***

## Cluster mode — Helm, Kubernetes, Compose, docs and a live demo (2026-10-02)

**Repo:** EDDI · **Branch:** `feat/nats-cluster-deploy` (stacked on `feat/nats-cluster-state`)

The delivery half of horizontal scaling: every shipped way to run EDDI can now run it as a cluster, and every one still refuses to run several in-memory replicas.

### What changed

* **Helm chart 2.7.0** — `eddi.messagingType=nats` unlocks `eddi.replicas > 1`, a real HorizontalPodAutoscaler and a `RollingUpdate`; each stays refused with in-memory messaging. `eddi.updateStrategy` defaults per mode (Recreate for in-memory, RollingUpdate with maxSurge 1 / maxUnavailable 0 for nats); `eddi.terminationGracePeriodSeconds` and `eddi.shutdownDrainTimeoutSeconds` default to 75 s / 65 s in cluster mode and the chart refuses a grace that does not exceed the drain. The PDB uses `minAvailable` once there is more than one replica. Pods get `EDDI_CLUSTER_NODE_ID` from their name and a topology spread. The in-chart NATS is a three-node routed JetStream cluster with a non-root, read-only container, anti-affinity, a PDB, user/password authentication limited to EDDI's subjects (password required, never defaulted) and optional TLS; `nats.externalUrl` points at your own. `nats.buildProfileImage` is gone — the published image selects the mode at runtime.
* **Kustomize** — `k8s/overlays/nats` is now the cluster-mode component (three NATS nodes, three EDDI replicas, rolling updates, node ids, drain), composed in `k8s/examples/postgres-ha`; the NetworkPolicies cover the route port.
* **Compose** — new standalone `docker-compose.cluster.yml` (three replicas, three NATS nodes with a required password, MongoDB, nginx round robin from `docker/cluster/nginx.conf`); `docker-compose.nats.yml` is documented as the one-replica overlay it is, on NATS 2.11.
* **Docs** — Kubernetes scaling section rewritten (plus the `eddi-secrets` volume name and the seeded realm roles, `eddi-viewer` included); architecture, coordinator admin (status `nodeId`/`cluster`, paging, honest replay, the status SSE), Slack, monitoring guide, audit ledger and GDPR pages updated for cluster mode; README; Prometheus rules in `docs/monitoring/eddi-cluster-alerts.yml`.
* **Demo** — [`scripts/cluster-demo/`](https://github.com/labsai/EDDI/tree/main/scripts/cluster-demo/README.md) builds three nodes of one build, three NATS nodes, MongoDB or PostgreSQL, nginx and a mock LLM in Docker and runs every failure scenario of [`clustering.md`](https://docs.labs.ai/deployment-and-infrastructure/clustering.md) with a verdict.
* **CI** — `manifest-lint` renders the cluster shapes and asserts that the chart still refuses multi-replica, autoscaled and rolling in-memory installs, an in-chart NATS without a password, both NATS sources at once and a drain longer than the grace.

### Design decisions

* `eddi.updateStrategy` reuses the key and null-fallback semantics of the build-hygiene PR (#938, chart 2.5.0), extended by the messaging-type default; this chart is 2.7.0 (#951 took 2.6.0). Its default is now empty (per messaging type) rather than #938's `{type: Recreate}`, and both shapes render. One deliberate difference: #938 let an in-memory deployment opt into `RollingUpdate`; this chart refuses that, because cluster mode is now the way to roll without downtime and an in-memory rollout runs two uncoordinated JVMs on one database.
* The Kustomize component carries no NATS authentication (it would need a Secret the operator has to create first); it restricts both NATS ports with NetworkPolicies and points to the Helm chart for authentication and TLS.

### Fixed after the PR #958 review

* **NATS routes authenticate.** The in-chart NATS cluster now gives its routes their own credentials. `cluster.authorization` takes `nats.cluster.routeUsername`, default `route`, and `nats.cluster.routePassword`, which is required whenever the chart runs more than one NATS node. Every route URL carries those credentials, percent-encoded. Client authorization never covered routes, and the chart's NetworkPolicy is off by default, so anything that reached port 6222 could join the cluster. Checked on three real `nats:2.11-alpine` containers running the rendered config: the routes form, and a server without the credentials is refused. With the old block, the same server joined. CI renders the credentials and refuses a clustered NATS without them. The chart version is unchanged (2.5.0 is not released yet).
* **PDB under autoscaling.** The PDB picks `minAvailable` only when the release never runs fewer than two replicas. With autoscaling, that floor is `autoscaling.minReplicas`. `minReplicas: 1` now gets `maxUnavailable`, so `kubectl drain` does not hang. CI covers both cases.
* **nginx 1.27.3.** The demo and `docker-compose.cluster.yml` now pin `nginx:1.27.3-alpine`. Open-source nginx accepts `server ... resolve` in an upstream only from 1.27.3: 1.27.2 refuses the demo config with `invalid parameter "resolve"`.
* The dead-letter alert description in the monitoring guide now says what the expression counts. The demo's `--reuse` no longer sets a context file it never read.
* **Docs (second #958 review):** the demo claims now cover only the scenarios its README lists. `clustering.md` and `gdpr-compliance.md` separate two retentions: the dead-letter stream expires audit dead letters after `eddi.coordinator.dead-letter.max-age` and holds their only copy, while the JSONL fallback never expires. They also name the actual subject, `eddi.<prefix>.dlq.audit`.
* **nginx no longer ejects a node for answering 503 (console review).** `max_fails=0` on the upstream servers of `docker/cluster/nginx.conf` and the demo config, plus a 2 s connect timeout. EDDI answers 503 with `Retry-After` for ordinary load shedding, and with nginx's default one 503 per node took every node out of rotation. Checked on `nginx:1.27.3-alpine` with the shipped config in front of stub replicas. Before: three nodes answering 503 gave 503, then 502 for every later request. After: every request gets the 503 with `Retry-After: 5`. A GET still moves on to a healthy node, and a node refusing connections is skipped. A POST that lands on a shedding node now returns its 503 instead of being hidden by the ejection; `clustering.md` explains why the compose config does not re-send POSTs.
* **Docs:** the residual-limitations list now separates the lease-lost cases. A turn whose reply already went out is dead-lettered after a 200. An earlier lease loss is answered 409. Replaying a dead letter whose client has already retried would run the turn twice.
* **From the third #958 review.**
  * The demo's nginx no longer re-sends a POST turn. `non_idempotent` with `timeout` would run a turn twice after a read timeout. Scenario 4 now counts a 503 from a draining node as a retried "not now", like a 409.
  * `gdpr-compliance.md` says the dropped-entries counter is per process, so a zero after a restart proves nothing; it tells operators to check the JSONL file and the `dlq.audit` subject.
  * `clustering.md`: the paginated-tool-response limitation now names who can fetch the pages, and the NATS permission text is the corrected set from the state branch.

***

## Cluster mode — shared state, invalidation and cross-node control (2026-10-02)

**Repo:** EDDI · **Branch:** `feat/nats-cluster-state` (stacked on `feat/nats-cluster`)

The second half of horizontal scaling: everything a replica used to keep to itself — caches of deployed workflows, secrets, rate limits, replay nonces, tool pages — is now either shared through NATS JetStream KV or invalidated on every node when it changes, and the operations that must reach the node running a turn (cancel, GDPR stop, HITL, undeploy) do. With `eddi.messaging.type=in-memory` none of it is wired: every path below falls back to the single-node behaviour it had before.

### What changed

* **Caches** — [`CacheFactory`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/caching/CacheFactory.java) decides centrally: state caches (A2A tasks, replay nonces, paginated tool responses, Slack dedup and channel locks) become [`SharedKvCache`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/caching/SharedKvCache.java)s backed by KV buckets with TTLs; derived caches (trigger, user-conversation, conversation state, GDPR restriction) become [`ClusterInvalidatingCache`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/caching/ClusterInvalidatingCache.java)s that publish `cache.evict` / `cache.clear` events keyed by a hash, never the raw key.
* **Config propagation** — `WorkflowFactory` now builds each workflow once per key outside its lock (no double build, failures not cached, the `WorkflowId.equals` NPE gone) and announces evictions; `SecretResolver`, `GlobalVariableResolver`, `ConnectionRegistry` and the `ChatModelRegistry` (plus a max-age) drop entries when another node changes them. Undeploy on one node stops the others within seconds, with a two-sweep reconciliation against the store as the safety net for a missed event. A request that reaches a node for an agent another node has only just deployed no longer answers 404: the node deploys it on demand and waits, bounded, for it to become ready (found by the shared live harness through a round-robin load balancer). A deploy with `autoDeploy=false` — which is deliberately not recorded — is announced too, so every node serves it, and an exported agent archive is copied to a JetStream object store ([`ClusterArchiveStore`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/cluster/ClusterArchiveStore.java)), so its download works through any node.
* **Rate limits and costs** — `ToolRateLimiter` keeps its global and per-tool buckets in KV ([`KvRateLimitBackend`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/tools/KvRateLimitBackend.java), CAS token bucket); `ToolCostTracker` sums budgets cluster-wide. While NATS is down both degrade to the local limit and count the decision.
* **Replay nonces fail closed** — `NonceCacheService` rejects a signed envelope it cannot check against the shared bucket (`eddi.agent.nonce.unavailable`).
* **Audit ledger** — sequence numbers come from one CAS counter per conversation ([`AuditClusterSupport`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/cluster/AuditClusterSupport.java)), so replicas no longer collide; the dead `Instance<Connection>` is gone and the collision WARN prints its node id instead of a literal `{2}`.
* **Cross-node control** — [`ClusterControlHandlers`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/ClusterControlHandlers.java) answers `conversation-cancel`, `group-control`, `gdpr-stop` and `coordinator-status` requests; cancel, end-conversation, group cancel and GDPR erasure reach the node that runs the work, and erasure purges the user's dead letters.
* **HITL crash recovery** — in cluster mode the startup sweep is replaced by a leader-run sweep ([`ClusterHitlRecovery`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/hitl/ClusterHitlRecovery.java)) that only touches a conversation nobody holds a lease on and that it has seen unchanged for a minimum age, so a rolling restart cannot "recover" a turn another node is running.
* **Coordinator admin** — `GET /administration/coordinator/status?scope=cluster` gathers every node; dead letters page with `limit`/`after`; replay rebuilds the turn from its captured input (409 and the entry kept when there is none).
* **Slack** — event deduplication is one atomic `putIfAbsent` on the shared cache.

### Design decisions

* One generic `cache.evict` / `cache.clear` event instead of one event type per cache: the factory is the only place that knows which caches are derived, so no cache can be forgotten when a new one is added.
* HITL takeover is a leader sweep, not inline recovery in the turn runner: a `say` turn that crashed leaves the document `READY`, and recovering inline would have broken resumes queued behind it.
* Not fixed here, documented in [`clustering.md`](https://docs.labs.ai/deployment-and-infrastructure/clustering.md): tool-response pages are not bound to their conversation (the tool has no conversation context; the id is a random UUID), and Slack follow-ups to a group discussion running on another node are not routed.

### Fixed after the PR #957 review

* **Erasure marks the user on every node before the audit scrub.** `AuditLedgerService` now takes part in the cluster `gdpr-stop`, so each node that answers marks the erased user before the erasing node pseudonymises the stored rows. Before, a late entry from another node kept the raw id unless the `gdpr.user-erased` event happened to arrive first.
* **Shared caches:** one `SharedKvCache` wrapper per local cache, so every caller sees which keys live on this node only. A `putIfAbsent` that wins the bucket clears an old local-only marker. A lost race still reports the key as present when the stored value cannot be read, which is the fail-closed answer for replay nonces.
* **Archive bucket:** a bucket deleted after the first check is created again on the next export or download, instead of failing every download through another node.
* **Group lease:** a discussion that cannot take its group lease logs it. A cancel forwarded to a holder that answers "not running here" now falls back to the database path instead of reporting `false`.
* **Deployment sweep:** a local undeploy forgets the version's record history, so an unrecorded redeploy whose event overtook the undeploy is not undeployed again.
* **Docs (PR #958 review):** `clustering.md` no longer says that losing NATS loses no audit entry. An entry the database refused waits only in the dead-letter stream. The page also no longer says the demo covers every failure scenario on it.
* **KV reads come from the stream leader (console review).** Every bucket is created with direct get off, and a bucket that still has it on is switched in place. The switch starts from the bucket's own stream configuration, so a fenced bucket keeps its first sequence; starting from the desired configuration reset it to 1, which `ClusterCoordinatorIT` caught. A KV handle drops itself after any failed call, so a handle opened before the switch recovers on its next call instead of at the next reconnect.
* **Docs:** `clustering.md` describes the lease-lost turn: it is dead-lettered (`reason: lease-lost`) and its caller is answered 409, instead of the turn vanishing. The code is on `feat/nats-cluster`.
* **Docs (PR #957 review):** the NATS permission list in `clustering.md` named `$KV.EDDI_>`, which matches no KV subject because a wildcard matches whole tokens only. On NATS 2.11 every KV write was refused with it. The list is now the full publish and subscribe set the Helm chart grants, plus how to narrow it per bucket.
* **From the PR #957 review bodies.** A node that cannot stop an erased user's running work now reports it. Its `gdpr-stop` reply carries an error, and the erasing node records `clusterStop` as a failed step instead of a clean erasure; a discussion that finished meanwhile is not a failure. A clustered audit sequence whose seed cannot be read leaves the entry unsequenced, as on a single node, instead of failing `submit`. The tool budget counts the larger of the shared and the local total, so a charge whose shared update lost every compare-and-set still counts. An on-demand deployment that fails answers "not ready" to the caller instead of an exception.

***

## Horizontal scaling on NATS JetStream — runtime cluster mode (2026-10-02)

**Repo:** EDDI · **Branch:** `feat/nats-cluster`

EDDI now scales horizontally from the one published image: `eddi.messaging.type=nats` is read at runtime, and any number of replicas run behind a plain round-robin load balancer, sharing one database and one NATS JetStream cluster. `in-memory` stays the zero-dependency default and behaves exactly as before — no NATS class is instantiated, no meter is registered and nothing about NATS is logged.

### What changed

* **Runtime selection** — [`ClusterProducers`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/cluster/ClusterProducers.java) picks the coordinator, lease manager, shared state, event bus and RPC by `eddi.messaging.type` (any other value fails the boot). The build-profile `NatsConversationCoordinator`, `NatsHealthCheck` and `NatsMetrics` are gone with their tests: the coordinator published to JetStream under the per-conversation lock (10/20/30 s stacking when NATS was slow), made every turn of a node booted without NATS fail, took readiness DOWN on any NATS blip, leaked its connection on a partial start, and its dead letters could not be listed, discarded or replayed.
* **One NATS connection** — [`NatsConnectionManager`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/cluster/NatsConnectionManager.java) connects asynchronously (boot never waits), fails every call fast while disconnected, supports user/password, token, creds and nkey auth and TLS/mTLS, and drains on shutdown without leaking a half-open connection.
* **Cluster-wide conversation leases with fencing** — a turn still runs on the node that received it, but only while it holds the conversation's lease ([`KvLeaseManager`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/cluster/lease/KvLeaseManager.java), KV `create` + heartbeat + server-side TTL, release notifications, presence-based takeover, handoff fairness). The lease revision is a fencing token: both conversation stores refuse a write carrying an older token than the document has seen (`_fence`, [`ConversationFencedException`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/memory/ConversationFencedException.java)), so a node that lost its lease cannot overwrite the turn that ran after it.
* **Coordinator** — the in-memory coordinator's queue logic moved verbatim into [`AbstractQueuedConversationCoordinator`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/runtime/internal/AbstractQueuedConversationCoordinator.java); [`ClusterConversationCoordinator`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/runtime/internal/ClusterConversationCoordinator.java) acquires the lease asynchronously (no NATS I/O under the queue monitor), answers a turn that waited past `eddi.cluster.lease.acquire-timeout` with 409 + `Retry-After` (not a dead letter — its input was never consumed), and dead-letters failed turns to a JetStream stream every node can read, with the turn's input captured for replay. Both coordinators now register `eddi.coordinator.total_dead_lettered` and `eddi.coordinator.dead_letters`.
* **Rolling updates without failed turns** — the MongoDB client was closed by a JVM shutdown hook, which runs concurrently with Quarkus' shutdown: SIGTERM closed it the moment the graceful drain began, so every turn still running failed with "state should be: open" and the drain waited out its timeout for turns that could no longer finish (a single node was affected exactly the same way). It is now closed by the bean's `@PreDestroy`, after the drain. The drain also brackets the coordinator: `beginShutdown` answers the turns still waiting for a conversation lease with 409 + `Retry-After` at once, and `completeShutdown` releases the leases still held so those conversations move on without waiting out the TTL. Found by the live rolling-restart demo.
* **The node RPC and the event bus actually start** — both were `@Typed` to their own class, which hid them from `ClusterBootstrap`'s `Instance<ClusterStartable>`, so neither ever subscribed: cross-node calls answered "no responders" and no node consumed another's events. The unit tests call `startCluster()` themselves and could not see it; `ClusterStartableTypingTest` now checks every startable's bean types. Found by the live cross-node cancel demo.
* **Replicas can boot together on PostgreSQL** — every PostgreSQL store creates its tables with `CREATE TABLE IF NOT EXISTS`, which is not safe against a concurrent copy of itself: three replicas starting against an empty database (a Deployment's first install) raced, and the loser died on `duplicate key value violates unique constraint "pg_type_typname_nsp_index"`. [`PostgresStartupSchemaLock`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/datastore/postgres/PostgresStartupSchemaLock.java) holds an advisory lock from the first to the last startup observer, bounded by `eddi.datastore.postgres.startup-lock-timeout`. Found by the live PostgreSQL demo.
* **Discarding a dead letter twice answers 404** — a replicated (R3) stream reports an already-deleted entry as 10043 ("sequence not found"), which surfaced as a 500. The stream itself is provisioned asynchronously after connecting, so its first use can come first: a missing stream now reads as empty (a GDPR erasure reported its dead-letter step failed), and the first dead letter creates it instead of being lost.

### Design decisions

* Execution stays on the receiving node (SSE, caller identity, live group discussions and HITL are unchanged); only mutual exclusion moved to NATS. Routing turns to an owner node was rejected — it would have meant serializing caller identities and every response channel.
* In-memory replay keeps its coordinator contract (remove the entry) so its tests stay untouched. Every dead letter now carries the turn's input, which is what lets the admin replay in the follow-up `feat/nats-cluster-state` rebuild the turn instead of only dropping the entry.
* Shared state beyond leases and dead letters (caches, rate limits, nonces, audit sequences, cross-node cancel/GDPR/HITL) follows in `feat/nats-cluster-state`; Helm, Kubernetes, Compose and the demo in `feat/nats-cluster-deploy`.

***

## fix(manager): save, version and deploy flows no longer lose edits or save nothing silently (2026-10-04)

**Repo:** EDDI (`fix/manager-version-save-flows`) — Manager only, no backend change.

### What changed and why

A UX review of the Manager found flows that discarded work, wrote versions that changed nothing, or reported success while doing neither. Each is fixed at its cause.

**Edits are no longer discarded silently**

* Agent Studio: choosing another pipeline stage (or another workflow) replaced the editor and dropped what was typed. The page now asks — Save, Discard or Cancel — when the editor has unsaved edits. `ConfigEditorLayout` reports its working copy (`onDraftChange`) and `StudioEditorPanel` registers a saver, so "Save" in the prompt keeps the edit and stays on the stage if the save fails.
* Workflow editor: Discard asks first, and offers to delete configs that "Add Task → Create new" wrote during the edit and that the discarded workflow state no longer references.
* The config editor refuses an invalid-JSON save out loud (toast, inline error, jump to the JSON tab) instead of doing nothing, for Save and Save & Test.

**"Add step, then configure it" works**

* A step added in this session is not in the saved workflow, so its resource editor could not cascade into it (`workflowMissingResource`, after the resource was already written). Such steps show "Not saved yet" and a "Save workflow & edit" action instead of an Edit link; it saves (and repoints the agent), then opens the resource against the new workflow version.
* "Create new" asks for a name (required) and stores it; it no longer writes unnamed orphan resources.
* Edit links now carry the version the step references (`?version=`), and the resource editor opens it, with a "Switch to latest" notice when it is not the newest.

**An agent pinned to an older workflow version**

* Agent → workflow links carry the referenced version. The workflow page opens that version and warns when the agent uses another one, with "Open version N" and "Point agent at version M".
* Save in an agent context now cascades into the agent like the resource editor does (new agent version, "Saved as vN — not live yet" with a Deploy action). Save and Save & Test read and check the agent first and refuse before writing anything when it would not change (previously an unchanged agent version was created and deployed).
* The resource editor's "agent changed since this page was opened — reload" error, which reloading could not fix, now says what is wrong and offers "Update agent and save".

**Studio test loop**

* Studio gets Save & Test (save, deploy, wait for READY, open the chat beside the editor on the new version) and the same "Saved as vN — not live yet" wording as the resource editor. The chat panel is bound to the studio's agent instead of whichever agent the global chat store last held. A workflow switcher appears for agents with more than one workflow.

**Agent page**

* Section toggles (Security, Capabilities, Memory, A2A, ...) each write a whole agent version with no feedback: they now toast "Saved as vN — not live yet" with a Deploy action. The dead `saveMessage` path is gone.
* The header badge no longer reads "Not deployed" while an older version is live: "Live: v5 · Viewing v6 (not deployed)". Header Undeploy names production when more than one environment is live. "Deploy & Chat" stops with an error when the deployment never becomes ready. The duplicate "v1" is gone.
* Removing a workflow asks first and has an accessible name; workflow rows show names.
* Collapsible sections expose `aria-expanded`/`aria-controls`, with the heading wrapping the button (not the reverse); A2A skill "+" and the version selects have names, A2A labels are tied to their inputs, and the Agent Card preview no longer hard-codes the name and "6.0.0".
* The Session Management note showed an unresolved placeholder in its endpoint path (i18next read `{{id}}` as an interpolation); the locale strings now say `:id`, and the dead disabled "Max Forks" field is removed.

**Smaller**

* Viewers (no EDIT level) get read-only editors on the resource and workflow pages: no save/discard/add controls.
* Agents, workflows and resources can be renamed in place (name and description on the detail header, `EditableTitle`).
* Workflow save errors show the real reason (`describeSaveError`) instead of a generic message. Ctrl/Cmd+S saves in the config editor and the workflow editor.
* The saved tick clears once there are unsaved edits again; the version picker explains why it is locked while dirty; the resource editor keeps its tab, scroll and state across a save (`placeholderData` on `useResource`).
* Agent create requires a name, and a failed descriptor PATCH after the POST is treated as created with a warning (no duplicate on retry).
* Agents list: a name/version sort loads the remaining pages first (the API has no sort parameter), with a hint while it does.

### Design decisions

* **Not-live feedback is one shared toast** (`lib/save-not-live-toast.ts`, a stable toast id) for the workflow page, Studio and agent section saves. The resource editor keeps its own inline copy of the same toast, unchanged.
* **Unsaved steps are blocked, not auto-saved.** Auto-saving the workflow behind an Edit click would write versions the user did not ask for.
* **"Update agent and save"** reuses the cascade's existing `agentWorkflowVersion` escape hatch (written for the partial-failure retry), so no new backend call.
* Renames patch the descriptor of the newest version (the list reads it) and of the viewed one when they differ.

### Deliberately skipped / follow-ups

* Server-side sort of the agents list: the descriptor API takes no sort parameter, so the UI loads every page instead.
* An older resource version opened from a pipeline link is editable but a save from it 409s (the backend only accepts the current version); the notice offers "Switch to latest" rather than blocking the editor.
* Removing a just-created step (rather than discarding the whole edit) does not offer to delete its resource.

**Files:** [`workflow-detail.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/pages/workflow-detail.tsx), [`agent-studio.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/pages/agent-studio.tsx), [`agent-detail.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/pages/agent-detail.tsx), [`resource-detail.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/pages/resource-detail.tsx), [`config-editor-layout.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/components/editors/config-editor-layout.tsx), [`pipeline-builder.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/components/editors/pipeline-builder.tsx), [`workflow-step-links.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/workflow-step-links.ts), [`save-not-live-toast.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/save-not-live-toast.ts)

***

## 🐛 fix(monitoring): shipped and loaded alert rules, no structurally empty panels, the blind spots instrumented (2026-10-03)

**Repo:** EDDI (`fix/observability`) — REVIEW-2026-10-02 §3.3 and §4.9.

### What changed and why

The 6.5.0 review evaluated all 360 panel queries of the three dashboards against a live Prometheus and found no alert rule shipped or loaded anywhere, about eight panels that could never show data, ratio KPIs that read "No data" on a healthy system, and duplicate panel ids. On a stock 6.5.0 after a 170-check harness run, **92 of 227 panels were empty**. On this branch, after the same harness plus steady LLM traffic, **14 of 240 are**, none of them structurally: they are latencies of features the run never exercised (cascade, Dream, summarisation, `/v1`, connections, the operator canary, NATS) and top-N tables with nothing in the window, each saying so through `noValue`, plus the Agroal panel on a MongoDB deployment.

* **Alert rules.** [`docs/monitoring/eddi-alerts.yml`](https://github.com/labsai/EDDI/tree/main/docs/monitoring/eddi-alerts.yml): 25 rules in nine groups. They cover `up`/absent/restart loop, the 5xx ratio, the coordinator backlog and capacity, dead-lettered turns, pipeline task errors, executor saturation, the LLM error ratio and p95, the tool failure ratio, the vault, audit drops/queue fill/collisions, quota-store failures, schedule and NATS dead letters, and heap after GC.
  * The operator gate rule fires on a verified → unverified transition. The gauge reads 0 on a deployment that never activated the operator, so alerting on the value would page every fresh install.
  * Every rule has a runbook under [Alert runbooks](https://docs.labs.ai/deployment-and-infrastructure/monitoring-guide.md#alert-runbooks).
  * Loaded by the compose stack (mounted and listed under `rule_files`; both installers download the file), by the Kubernetes component, and by Helm as an opt-in `PrometheusRule`.
  * [`eddi-alerts.test.yml`](https://github.com/labsai/EDDI/tree/main/docs/monitoring/eddi-alerts.test.yml) holds `promtool test rules` cases, which CI runs.
* **Dashboards.**
  * HTTP latency is mean/peak: a histogram would multiply each of up to `max-uri-tags` series by about seventy, and #933 is busy bounding that number.
  * The DB pool panels now have data. EDDI builds its own MongoDB client, so `quarkus.mongodb.metrics.enabled` never applied: a Micrometer pool listener was added in `PersistenceModule`, and `quarkus.datasource.metrics.enabled=true` turns on the Agroal meters.
  * The NATS dead-letter query reads `_total`.
  * Ops "Cost / hr" is `increase([1h])`; `rate()` was dollars per second.
  * Tool-success and cache-hit KPIs count a never-registered failure series as zero.
  * "Top missing skills" grouped by a label that does not exist and is now "Capability misses (1h)". The counter is untagged on purpose: the skill string is caller-supplied.
  * Ops gained `$datasource`/`$job` and an `up` KPI. Counter panels fall back to `or on() vector(0)`, cumulative counters are shown as increases, and ratios/latencies say why they are empty.
  * Full: duplicate ids renumbered, the LLM row moved below Overview, `$job` sourced from `process_uptime_seconds`. The old source, `jvm_info`, is scraped as `jvm_info_total`.
* **New meters.**
  * `eddi_coordinator_dead_lettered_total` and `eddi_coordinator_dead_letters_retained`.
  * `eddi_audit_queue_depth` and `eddi_audit_queue_capacity`.
  * `eddi_hitl_pending` and `eddi_hitl_pending_oldest_age_seconds`. `HitlPendingMetrics` reads them from the store on a timer, never on the scrape thread. They read `NaN` when unknown and come with the new property `eddi.hitl.metrics.refresh-interval`.
  * `eddi_runtime_executor_{active,queued,max_threads}{pool}`. `BaseRuntime` counts work queued for and running on the worker pool, which Quarkus' `worker_pool_*` meters do not see.
* **Vault errors.** `VaultSecretProvider` no longer counts "no such key" on `eddi_vault_errors_count_total`. `AgentSigningService` probes for a signing key on every signing attempt, so the counter rose by about one per turn on a healthy deployment: 925 of 927 resolves in the harness run. An alert on it could only ever fire.
* **Kubernetes / Helm** (chart **2.4.0**).
  * The monitoring component loads the rules, gives the Grafana datasource uid `prometheus`, and provisions all three dashboards from generated ConfigMaps.
  * Helm has opt-in `serviceMonitor.*` (relabels the job to `eddi`) and `prometheusRule.*`. They are not under `monitoring.*`, which chart 2.0.0 removed.
  * The new `eddi.tracing.otlpEndpoint` turns tracing on and, with `networkPolicy.enabled`, opens OTLP egress (`networkPolicy.otlpEgressTo`).
  * `scripts/sync-monitoring-assets.py` writes the copies Helm and kustomize can read.
* **Tests and CI.**
  * `MetricsDashboardCoverageTest` now parses every dashboard. It checks every query against the series a scrape can contain (`MonitoringSeries`), panel-id uniqueness, the `$datasource`/`$job` variables, and rate KPIs that can go blank. It also finds meters registered through a name constant: `eddi.tool.costs.accrued` was invisible to it.
  * New `AlertRulesTest`.
  * `DeploymentManifestsTest` covers the component, the chart objects and copy drift.
  * CI's Deployment Manifests job runs promtool and the copy check, and `docs/monitoring/**` now triggers the tests that read it.
* **Docs.**
  * Panel and row counts (the docs said 138/19, the dashboard had 160/22; it now has 166/22).
  * The traced operations: no MongoDB spans and no raw LLM HTTP spans; LLM calls appear as `gen_ai.client.inference`.
  * `COLLECTOR_OTLP_ENABLED` is removed from the compose file. It is a Jaeger 1.x switch, and Jaeger 2.7 received traces without it.
  * Two timers publish buckets, not one.
  * The cost-per-hour PromQL is fixed.
  * The new settings are in the [configuration reference](https://docs.labs.ai/deployment-and-infrastructure/configuration-reference.md#metrics--tracing).
* **Eager counters for one-shot alerts.** A counter created by its first increment is first scraped at 1, so `increase()` never saw the first canary failure or the first quota-store outage. `OperatorMetricsService` is now `@Startup` and registers every canary outcome at 0, and `TenantQuotaService` registers `eddi.tenant.quota.unavailable` at 0 for the default tenant. The monitoring guide states the remaining limitation.
* **Review fixes.** `EddiOperatorGateRegressed` no longer pages after a restart. The review's first fix (6h lookback plus 6h of uptime) also hid a real regression during a process's first six hours. The rule now reads the new `eddi_operator_gate_last_verified_timestamp_seconds`: the epoch of the last verified report received by the running process, 0 after boot. Ops "Top 10 Slowest Endpoints" divides summed rates. `BaseRuntime` releases the queued count when `submit` throws an `Error`. The Kubernetes docs and Helm values say to list a cross-namespace Prometheus in `networkPolicy.allowedIngressNamespaces`.
* **Pending approvals are listed oldest first** (PR review). Both stores applied the listing limit to an arbitrary order, so past 1000 pending approvals the oldest could be dropped. That made `eddi_hitl_pending_oldest_age_seconds` under-report and could let the retention sweep miss the approvals it exists to expire. MongoDB reads the dated pauses ascending, then fills the remaining room with undated ones. PostgreSQL orders by the pause time normalised from either JSON representation, with undated and malformed values last. The inbox listings now come back in that order too.

### Design decisions

* **"Silently drops" a second tag shape is accurate and was kept.** The review said the registry throws. Registering `foo` and then `foo{tenant}` on `micrometer-registry-prometheus-simpleclient` 1.17.1, the registry in the 6.5.0 image, returns normally both directly and behind a `CompositeMeterRegistry`. Quarkus registers no `onMeterRegistrationFailed` listener. The page now says which registry was verified.
* **No HTTP histogram.** Mean and peak need no new series. A percentile alert on HTTP latency would have needed the buckets, so the latency alert is on LLM calls, which already publish them.
* **The pending-approval gauge reads the store** rather than computing pauses minus resumes, which resets with every restart. It is capped at 1000 rows, and every replica reports the store-wide number, so the dashboards use `max`.

### Platform Operator

No change. Nothing the operator calls changed: there is no REST or MCP change, and `/q/metrics` and Prometheus are outside its allow-list by design.

### Expected conflicts

* `helm/eddi/Chart.yaml` and `EXPECTED_CHART_VERSION`: P11 (`feat/nats-cluster-deploy`) bumps the chart too.
* `docs/metrics.md`: #933 adds two lines.
* `application.properties`: #933 edits the `# Micrometer` block. This branch adds its properties elsewhere on purpose.

### Follow-ups

* `AgentSigningService` resolves a missing signing key from the store on every signing attempt, uncached.
* Under the PostgreSQL profile a MongoDB client is still created, against `mongodb:27017`; the new pool gauge shows it.

***

## ✨ feat(a2a): A2A 1.0 conformance — honest task states, an in-flight bound, restart-safe tasks (2026-10-03)

**Repo:** EDDI (`feat/a2a-spec-conformance`)

### What changed and why

The A2A surface spoke a pre-0.2 dialect no current SDK can parse — a bare-enum `status`, `type` instead of `kind`, and only `tasks/send` — so the official `a2a-sdk` client could neither resolve an EDDI Agent Card nor send to it. It also reported every turn as `completed`: a failing LLM, a HITL pause and a turn dropped behind a pause all came back `completed`, the last one with the *previous* turn's answer as its result. There was no bound on concurrent tasks, and tasks lived only in a node-local 1,000-entry cache.

* **Pinned to A2A 1.0** (specification release v1.0.1). One endpoint serves three dialects, chosen by method name and answered in kind: `SendMessage` / `SendStreamingMessage` / `GetTask` / `CancelTask` (1.0), `message/send` / `message/stream` / `tasks/get` / `tasks/cancel` (0.3), and the deprecated `tasks/send`. Unimplemented spec methods get their spec error codes (`-32003`, `-32004`, `-32007`); an unsupported `A2A-Version` gets `-32009`. Rendering lives in the new `A2AWireFormat`; the task model is dialect-neutral.
* **Agent Card** at `/.well-known/agent-card.json` and `/a2a/agents/{id}/.well-known/agent-card.json` (the old paths stay), readable by 1.0 and 0.3 clients alike: `supportedInterfaces` for both versions, 1.0-shaped `securitySchemes`, the 0.3 connection fields, the real EDDI version, `streaming: true`.
* **Task states come from the task's own turn**: ERROR → `failed`, a HITL pause → `input-required`, a turn dropped behind a pause → `input-required`, dropped while busy → `rejected`, cancelled → `canceled`, still running when a blocking send stops waiting → `working`. Each turn carries its task id in the input context and an output is returned only if it carries that id, so a stale previous answer can no longer be returned.
* **A task queued behind a sibling's turn is not cancelable** (`-32002`) until that turn settles: cancelling the conversation would have stopped the sibling's turn instead. The in-flight bound's lease timer is cancelled on a normal release rather than left queued for task timeout + 30 s.
* **A reused legacy task id belongs to the newest send**: an earlier turn's late outcome is no longer recorded over it. Streams write an SSE keepalive comment every 15 s while idle, and calls to a disabled A2A surface are counted in `eddi_a2a_requests_total` (`method="disabled"`).
* **`CancelTask` cancels the turn**, not the conversation (it used to end the whole context), and a terminal task answers `TaskNotCancelable`.
* **In-flight bound** `eddi.a2a.max-concurrent-requests` (default 64): the excess is refused with HTTP 503 + `Retry-After` before any conversation starts. Meters `eddi_a2a_requests_total`, `eddi_a2a_tasks_total`, `eddi_a2a_in_flight`, on the full-metrics dashboard.
* **Tasks behind `IA2ATaskStore`** (default `CachedA2ATaskStore`, the same node-local caches). Server-issued task ids are `<conversationId>_<random>` and server-issued context ids are the conversation id, so `GetTask` and context continuation re-derive from the conversation store after a restart or on another node — peer-scoped by conversation ownership.
* **Outbound client** (`A2AToolProviderManager`) reads the dialect off the peer's card — `SendMessage` + `A2A-Version: 1.0`, `message/send`, or `tasks/send` for a stock EDDI up to 6.5 — tries the well-known card paths, reads results in all three shapes, and reports a failed, rejected, input-required or still-working task to the model as such instead of as an answer. The configured URL stays the endpoint; a card cannot redirect it (when the configured URL is the card document itself, the card's endpoint must be on the card's origin, since the credential is sent there).

Verified live with the official `a2a-sdk` 1.2.1 Python client (1.0 transport and its 0.3 compatibility transport) against a jar of this branch, and compared with a stock `labsai/eddi:6.5.0`.

### Compatibility

`tasks/send` results are now the 0.3 task shape: `status` is an object (`status.state`), parts carry `kind` next to `type`. EDDI's own client up to 6.5 reads only the artifacts and keeps working against this server; this branch's client keeps working against a 6.5 server.

### Docs

[`a2a-protocol.md`](https://docs.labs.ai/protocols-and-integration/a2a-protocol.md) (methods per dialect, state mapping, task store, streaming, the bound, deprecations; the disabled endpoint answers 200 + a JSON-RPC error, which the page now says), [`configuration-reference.md`](https://docs.labs.ai/deployment-and-infrastructure/configuration-reference.md), [`metrics.md`](https://docs.labs.ai/deployment-and-infrastructure/metrics.md), [`security.md`](https://docs.labs.ai/security-and-compliance/security.md).

The Platform Operator holds no A2A endpoint and cannot change A2A settings, so its prompt and allow-list are unchanged.

The two new card paths, `GET /.well-known/agent-card.json` and `GET /a2a/agents/{agentId}/.well-known/agent-card.json`, are added to the Manager's `ui/manager/src/test/mocks/openapi-operations.json`; without them the `OpenAPI Snapshot` and `Backend E2E` checks (and so `E2E Gate`) failed on this branch.

**Files:** [`A2AModels.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/a2a/A2AModels.java), [`A2AWireFormat.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/a2a/A2AWireFormat.java), [`A2ATaskHandler.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/a2a/A2ATaskHandler.java), [`IA2ATaskStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/a2a/IA2ATaskStore.java), [`CachedA2ATaskStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/a2a/CachedA2ATaskStore.java), [`A2AInFlightLimiter.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/a2a/A2AInFlightLimiter.java), [`RestA2AEndpoint.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/a2a/RestA2AEndpoint.java), [`AgentCardService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/a2a/AgentCardService.java), [`A2AToolProviderManager.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/A2AToolProviderManager.java)

### What's next

* A shared `IA2ATaskStore` for clustered deployments (owned by the NATS cluster work); peer-chosen ids (legacy task ids, made-up context ids) are the only ones that do not survive a restart today.
* `ListTasks`, `SubscribeToTask` and push notifications are answered with their spec errors, not implemented.
* The outbound client does not poll a task that came back `working`.

***

## 🐛 fix(chat-ui): embedded token hand-off works with auth on, designer images render, stale turns stay out (2026-10-03)

**Repo:** EDDI (`fix/chat-ui-review`), the Chat UI findings of the 2026-10-02 review (report card "Chat UI", §4.11).

### What changed and why

**postMessage token hand-off (Medium).** The widget accepted `{type: "eddi-chat-token"}` from an allow-listed parent, but it started the conversation the moment it mounted, before any host could have answered. With OIDC on, that first `POST /agents/{id}/start` went out without a token, came back `401`, and was never retried. A token arriving a moment later was installed but never used, so an embedded widget showed "You are not allowed to start a conversation" for good. Tokens also expired after the realm's lifespan with no way to renew them. Reproduced live against `labsai/eddi:6.5.0`.

The new [`embed-auth.ts`](https://github.com/labsai/EDDI/tree/main/ui/chat/src/api/embed-auth.ts) is a small protocol:

* **Ready.** The widget posts `eddi-chat-ready` to its parent once it is listening.
* **Token requests.** It posts `eddi-chat-token-request` a minute before a JWT's `exp`, and again on any `401`.
* **Retry.** [`http.ts`](https://github.com/labsai/EDDI/tree/main/ui/packages/core/src/http.ts) gets one 401 hook: ask the host for a token, wait up to 10 s, repeat the request once.
* **Exact targets.** Every outgoing message uses an exact `?tokenOrigin=` origin as its `targetOrigin`, never `*`.
* **Strict acceptance.** A token is accepted only from `window.parent` at an allow-listed origin. The widget drops a wildcard, a path or `null` from the list.
* **Memory only.** The token is never put in the URL or in storage.

A `?token=` or `ChatConfig` token no longer clears a token that arrived by `postMessage`. The full contract, with a host-page example, is the new page [chat-ui-embedding.md](https://docs.labs.ai/protocols-and-integration/chat-ui-embedding.md).

**CSP blocked designer image outputs (Low-Medium).** `/chat`'s `img-src 'self' data: blob:` refused every `image` output item hosted elsewhere. `img-src` now appends `eddi.chat.img-sources` (`EDDI_CHAT_IMG_SOURCES`), default `https:`. Markdown images in model text are still rendered as links, so a model still cannot pick a URL for the browser to fetch. The trade-off, and the strict alternatives (a host list or `'self'`), are in [configuration-reference.md](https://docs.labs.ai/deployment-and-infrastructure/configuration-reference.md) and the embedding page. Only `/chat` changes: [`CspPolicyTest`](https://github.com/labsai/EDDI/tree/main/src/test/java/ai/labs/eddi/configs/CspPolicyTest.java) pins both halves.

**Low items.**

* **Generation guard.** A send's 409/401/403 branches now bail when the user started a new conversation while the request was in flight. Before, they withdrew a bubble, restored a draft and posted a warning into the replacement. Item 4 of the review brief found the same gap in undo, redo, retry, cancel and stop, so those are guarded too, including their `finally` that lowered `isProcessing` under a newer turn.
* **Attachment uploads across New conversation.** Found in review. An attachment upload that finished after New conversation was staged into the new conversation, so its next message carried a `storageRef` from the abandoned one. [`ChatInput.tsx`](https://github.com/labsai/EDDI/tree/main/ui/packages/conversation/src/components/Composer.tsx) now drops such an upload and deletes it from the old conversation, which frees its quota. The ref that holds the current conversation id is updated in a layout effect: not during render, and not in a passive effect. A passive effect left a gap between the commit and the update, and an upload settling in that gap still staged its file into the new conversation (CodeRabbit on #948). The delete is a background cleanup, `discardAttachment`: one retry after a transient failure (network, 5xx, 429), no retry on a 4xx, a console warning when the file is still left, and no UI. What is left is removed with its conversation: on delete, by the ended-conversation retention sweep, or by GDPR erasure. The user's own chip removal now goes through the same path. The ref belongs to the `ChatProvider`, not to one `ChatInput` instance (CodeRabbit on #948, round 2). `ChatWidget` swaps the composer out for `SecretInput` while an agent's input field is open. With an instance-owned ref, an upload that settled meanwhile was judged against the dead instance's conversation, so when the composer came back for a new conversation the old file was staged into it. The ref is deliberately not cleared on unmount: if the composer returns to the same conversation, the file is still the user's and its chip is waiting.
* **URL parameters.** `?theme=` accepts only `dark`, `light` or `system`. An unknown value used to be written into `data-theme` and left the widget unstyled. Each colour parameter must now be a plain colour, and `fontFamily` a plain font list. Before, any token sequence went into a CSS custom property, so a link could carry `url(...)`.
* **Vite dev proxy.** It now proxies `/conversations`, so attachments work under `npm run dev`. A test checks that every path prefix the API layer calls is proxied.
* **SSE parser.** It now yields a final frame that has no trailing blank line instead of dropping it. That frame is usually `done` or `error`.

**Platform Operator.** The docs map names `chat-ui-embedding`, so "how do I embed the chat?" goes straight to the page. Revision 2 → 3.

### Verification

* **Chat UI checks:** `npm run typecheck`, `npm run lint` and `vitest` (417 tests, 45 of them new) all pass. 23 mutants were applied to the new behaviour and all 23 were killed.
* **Backend:** `CspPolicyTest` and the repo guards pass. Removing the `img-src` append fails the new test.
* **Live:** stock `labsai/eddi:6.5.0` compared with this branch's jar, both with Keycloak on, using a host page on another origin. Evidence is attached to the PR.

**Files:** [`embed-auth.ts`](https://github.com/labsai/EDDI/tree/main/ui/chat/src/api/embed-auth.ts), [`http.ts`](https://github.com/labsai/EDDI/tree/main/ui/packages/core/src/http.ts), [`chat-api.ts`](https://github.com/labsai/EDDI/tree/main/ui/packages/core/src/conversation.ts), [`ChatWidget.tsx`](https://github.com/labsai/EDDI/tree/main/ui/chat/src/components/ChatWidget.tsx), [`vite.config.ts`](https://github.com/labsai/EDDI/tree/main/ui/chat/vite.config.ts), [`application.properties`](https://github.com/labsai/EDDI/tree/main/src/main/resources/application.properties), [`chat-ui-embedding.md`](https://docs.labs.ai/protocols-and-integration/chat-ui-embedding.md).

### Follow-ups

* Helm has no `eddi.chat.imgSources` value yet. Set `EDDI_CHAT_IMG_SOURCES` through `extraEnv`; a chart value means a chart version bump, which is out of this PR's scope.
* `?token=` remains a login-CSRF vector, as before. It is kept for compatibility, and the docs steer users to the hand-off.

***

## 🐛 fix(gdpr,audit,memory): erasure redacts the audit ledger, admin actions are audited, log retention is real, Dream stops losing concurrent writes (2026-10-03)

**Repo:** EDDI (`fix/gdpr-audit-memory`)

### What changed and why

**GDPR erasure left verbatim PII in the audit ledger and still said `complete: true`.** Reproduced on MongoDB, PostgreSQL and the NATS build: a social-security number typed into a conversation was still in 6 of 6 audit rows after `DELETE /admin/gdpr/{userId}` answered `complete: true`. The erasure replaced the `userId` and nothing else; the `input`, `output`, `llmDetail` and `toolCalls` maps kept the prompt, the response and the tool arguments. And because it ran a store-side `updateMany`, entries still in the ledger's 3-second write queue landed afterwards and were missed by it — the `auditEntriesPseudonymized: 0` seen on fast erasures.

`AuditLedgerService.eraseUser` now does the ledger part of the cascade:

1. marks the user erased and **flushes the write queue synchronously**; an entry that cannot be stored stays queued and is redacted as it leaves the queue, and entries produced afterwards by cancelled work are redacted before they are signed;
2. finds every row of the user — under the raw id **and** under any pseudonym an earlier erasure gave it, so re-running an erasure after upgrading cleans up rows an older release only pseudonymised;
3. verifies each row, then rewrites it through the new `IAuditStore.redactEntry` (conditional on the stored HMAC, on both backends): keyed pseudonym for `userId`, a `gdprRedaction` marker (reason, time, the original HMAC, the verdict before) for `input`, and `output`/`llmDetail`/`toolCalls` removed. Ids, timing, cost, actions, timestamp and `sequence` stay, so **the chain stays gap-free**;
4. **re-signs only what verified.** A valid row gets a v5 HMAC over its redacted form and still verifies as `VALID`; a row that was already failing keeps its old HMAC and keeps failing — redaction never launders tampering.

`GdprDeletionResult` gains `auditEntriesRedacted`; a row that cannot be redacted (or a store that cannot redact) fails the new `auditRedaction` step, so `complete` is false. GDPR compliance events and admin-action records are pseudonymised, not redacted. `eddi.audit.erasure-mode=pseudonymize` keeps the old behaviour for a deployment whose legal hold requires the content, with a startup WARN. `PostgresDatabaseLogs.pseudonymizeByUserId` no longer swallows a SQL failure as "0 rows" (which also reported a complete erasure).

**"Every API call is audited" was false.** The ledger recorded pipeline tasks, HITL decisions and the four GDPR operations — nobody who changed a prompt, deployed an agent, replaced a vault secret, imported a backup or erased a user was on record (the GDPR event had no actor). The new `AdminActionAuditFilter` writes one HMAC-signed record per `POST`/`PUT`/`PATCH`/`DELETE` outside the conversational data plane (excluded by list, so a new admin endpoint is covered by default): caller, method, path, endpoint, status — never the body or query string, and a person's id in the path is pseudonymised. Calls an endpoint refused (`@RolesAllowed` 403, 404, 409) are recorded too; requests turned away by an HTTP path policy before resource matching are not. `GET /auditstore/admin-actions?actor=` lists them (new task-id index on both backends). `eddi.audit.admin-actions.enabled` switches it off. On PostgreSQL the two whole-ledger indexes, `idx_audit_user` and the new `idx_audit_task`, are no longer built with a plain `CREATE INDEX` on the audit-writer thread (which blocked audit inserts for the length of the build on a large ledger): they are built `CONCURRENTLY` in the background under an advisory lock, an index an interrupted build left INVALID is dropped and rebuilt, and failures retry. The docs now say exactly what is and is not recorded (reads are not; MCP memory tools are not).

**Database-log retention was documented as configurable and was not.** New `eddi.logs.db-retention-days` (default `-1`, kept) with a daily sweep in the same shape as the existing conversation/user-memory retention sweeps (Quarkus `@Scheduled`, idempotent per replica — not a new scheduler; interval and initial delay configurable), `deleteOlderThan` on both log stores, a timestamp index, and `eddi_logs_db_retention_deleted_total`.

**Dream deleted or overwrote facts updated during its run.** It read the user's memories, spent seconds in the LLM call, then deleted and upserted by id. New `IUserMemoryStore.deleteEntryIfUnchanged` / `replaceIfUnchanged` (one conditional statement on `updatedAt`, MongoDB and PostgreSQL) back every prune, in-place overwrite and original delete; a group whose originals changed during the LLM call is skipped untouched. Skips are counted in `DreamResult.conflictsSkipped` and `eddi_dream_conflicts_skipped_total`.

**Dream's "conservative" $0.01/1K estimate undercounted premium models 2–7×.** Input and output are priced separately: the model's price from the new `dream.inputPricePer1M`/`outputPricePer1M`, otherwise a documented upper bound ($15/$75 per 1M, Claude Opus list price); the no-usage fallback assumes 3 characters per token.

**`enforceCapacity` race.** Concurrent `rememberFact` inserts at `maxEntriesPerUser - 1` all passed the count check. The count is re-checked after the insert, and the overshoot settled deterministically — the newest inserts over the cap are undone (`reject`) or each evicts one distinct oldest own entry (`evict_oldest`).

**Compliance docs.** `compliance-data-flow.md` is now the canonical data inventory and the single "What reaches the LLM provider" list — conversation content leaves the deployment on every LLM call, and `global` user memories other agents wrote (the default for a `longTerm` property of an agent without `userMemoryConfig`) can reach the prompt; GDPR, HIPAA, PRIVACY.md and incident-response link to it instead of repeating drifted copies. Corrected: erasure (redaction, not "pseudonymised only"; the CCPA section no longer contradicts the GDPR one — the export is not complete and the erasure keeps two stores), audit coverage ("every API call"), HIPAA "✅ built-in" signing and authentication that are off until configured, database-log retention. The Dream schedule examples in `architecture.md` are corrected by docs PR #936 and are not touched here.

### Design decisions

* **Redact and re-seal, not a content-digest canonical form.** A v6 form signing digests of the payload would let anyone with DB access redact a row without the key. Re-sealing needs the key, keeps every redacted row verifiable with the existing v5 verifier (no new version), and the marker — with the original HMAC — sits inside the new signature. Re-sealing is preceded by verification, which is what keeps it from laundering.
* **The queue is flushed, not just watched.** The 1-hour erased-user rewrite stays as the backstop for work still unwinding, but the erasure itself writes and redacts what was queued, so the response counts it.
* **Admin auditing by exclusion.** An allow-list of admin paths would silently miss the next admin endpoint; the data-plane exclusion list is short and stable.
* **Log retention off by default.** Starting to delete history on the first boot after an upgrade is the surprise the EDDI 5 conversation-retention hold exists to prevent.
* **Dream conflicts lose to the user.** On a CAS miss the newer write wins and the consolidation is skipped or the original kept; a duplicate is reconciled next cycle, a lost fact is not recoverable.

### Live verification

Stock `labsai/eddi:6.5.0` vs a jar from this branch, MongoDB and PostgreSQL, mock LLM: a conversation containing an SSN, erased while its second turn was still queued. Stock: 6 of 6 rows still contain the SSN, `complete: true`. Branch: 0 of 6, `auditEntriesRedacted: 6`, `/auditstore/verify` VALID 6/6, chain INTACT. Evidence: `scratchpad/evidence/fix-gdpr-audit-memory.md` (pasted into the PR).

### Out of scope

Audit chain allocation across replicas (P11), the watchdog / GDPR `stopInFlightWork` reachability (P7), MCP `isError` (#937), the Manager's GDPR cache and a Manager tile for `auditEntriesRedacted` (#940), the PostgreSQL retention hold (#943).

**OpenAPI snapshot.** The new `GET /auditstore/admin-actions` is added to the Manager's `ui/manager/src/test/mocks/openapi-operations.json`; without it the `OpenAPI Snapshot` and `Backend E2E` checks (and so `E2E Gate`) failed on this branch.

**Files:** [`AuditLedgerService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/audit/AuditLedgerService.java), [`IAuditStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/audit/IAuditStore.java), [`AdminActionAuditFilter.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/audit/rest/AdminActionAuditFilter.java), [`GdprComplianceService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/gdpr/GdprComplianceService.java), [`DatabaseLogRetention.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/runtime/DatabaseLogRetention.java), [`DreamService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/runtime/internal/DreamService.java), [`UserMemoryTool.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/tools/UserMemoryTool.java), [`compliance-data-flow.md`](https://docs.labs.ai/security-and-compliance/compliance-data-flow.md), [`audit-ledger.md`](https://docs.labs.ai/security-and-compliance/audit-ledger.md), [`gdpr-compliance.md`](https://docs.labs.ai/security-and-compliance/gdpr-compliance.md), [`hipaa-compliance.md`](https://docs.labs.ai/security-and-compliance/hipaa-compliance.md)

***

## 🐛 fix(groups,backup,secrets): duplicate members, workspace create race, scoped merge import, malformed-archive 400, bound sealed data (2026-10-03)

**Repo:** EDDI (`fix/groups-import-secrets`) — review 2026-10-02 scope P9 (top issue #12; §4.5 `McpGroupTools`; §4.7 groups/backup/secrets rows; harness checks 4–6).

### What changed and why

**Duplicate group members (Medium, live on every backend).** A group listing the same agent twice was accepted, and both "independent" seats spoke through one member conversation — the second panelist read the first one's answer as its own history. The engine keys a seat by `agentId` everywhere (member conversation, display names, vote weights, `participants`, facilitator), so a second seat for one agent cannot exist without re-keying all of it. `AgentGroupStore` now refuses a repeated member (same `agentId` and member type) at save time — `400` naming both positions, on REST create/update, MCP and templates. Stored configs that already hold one keep loading: `AgentGroupStore.read` drops each repeat (first seat wins) and logs a warning, so the discussion runs the agent once and a GET → PUT round trip saves cleanly. Docs: [group-conversations.md](https://docs.labs.ai/conversations-and-orchestration/group-conversations.md#member-roles).

**`GroupWorkspaceStore` survivor race (Medium).** Each concurrent creator inserted its own workspace and they converged afterwards on the lexicographically smallest id — which is not the first insert (ObjectIds are minted client-side, UUIDs are random). A caller whose re-query ran before a second insert landed returned its own document, wrote a backlog task into it, and later reads elected the other one: the task reported success and vanished. Workspaces are now stored under the group id itself with an insert-only `createNew`, so the primary key admits exactly one creator on Mongo and Postgres and every other caller adopts that document. `find` reads the canonical id first and falls back to the `groupId` query for workspaces created by earlier releases; a group id the backend cannot use as a storage id keeps the old path. Container tests race 8 creators × 10 groups on real Mongo and Postgres and require one document and zero lost writes.

**Merge import resolved by global `originId` (Low-Medium, workspaces).** With workspaces enforced, a merge into one workspace matched another workspace's copy of the same archive and wrote into it (or failed its access check). `RestImportService.isMergeTarget` now admits a candidate only if the importer may EDIT it and, when the import writes into a definite space, it lives in that space; the preview, the merge and the live-sync "promoted from this source" lookup all use it. Workspaces off: unchanged.

**Malformed archives answered 500.** Zip-slip was rejected correctly but as a server fault. `ZipArchive` now raises `MalformedArchiveException` for an entry escaping the target directory, a name that is not a path, and corrupt or truncated data (`ZipException`/`EOFException`); `RestImportService` maps it to `400 {"error":"Invalid import archive: …"}`. A configuration file inside the archive that is not valid JSON is a `400` as well (it was `500`).

**Secrets.**

* *One bad grant halted DEK rotation:* `ConnectionGrantResealer` ended its sweep at the first grant whose re-seal threw, stranding every grant after it. It now skips that grant, logs it by connection name, counts it in the new `eddi.vault.reseal.failures{participant=connection-grants}` counter and in the rotation's "at least N rows" — and every other grant still moves.
* *One dekId, two seals:* `OAuthTokenService` sealed access and refresh tokens in two `seal()` calls, each picking the active DEK, but the row records one `dekId`; a rotation committing between them left the refresh token under a generation the row did not name, and that grant could never refresh. New `ISecretProvider.sealAll` seals every field of a row under one generation.
* *Generic `seal()` had no AAD:* new `seal/unseal(tenantId, …, context)` bind the ciphertext with `eddi-sealed-data|v1|tenant|dekId|<len>:context`. Grant tokens are bound to connection, principal and field. Backward compatible: the bound form is tried first, then the unbound one, so every existing grant still opens; new writes are bound, and the next DEK rotation re-seals the rest bound (the `SealedDataRotationParticipant` resealer now takes the context). Migration needs nothing; documented in [secrets-vault.md](https://docs.labs.ai/security-and-compliance/secrets-vault.md#envelope-encryption).
* *Remote sync bodies uncapped:* every JSON response live sync reads from the source went through `BodyHandlers.ofString()`. New `CappedStringBodyHandler` refuses a declared `Content-Length` over `eddi.backup.sync.max-response-bytes` (default 16 MiB) before reading and cancels an undeclared body at the cap; the sync fails with 502.

**`McpGroupTools` returned raw `e.getMessage()`.** New `McpToolUtils.toolFailure`: a failure the caller can fix (4xx, validation `IllegalArgumentException`, not-found/modified, an engine-authored `GroupDiscussionException`) is described; anything else is logged with its stack under an 8-hex reference and the client gets `{"errorCode":"INTERNAL","details":{"reference":…}}`. Merged with main's per-tool `failure()` from #937: its messages and `NOT_FOUND` code stay, its caller-facing test is now `isCallerFacing` (plus unparseable JSON arguments), and its `INTERNAL` answer carries the reference.

**Review follow-ups.**

* `McpToolUtils.isCallerFacing` passed every `IllegalArgumentException` through verbatim; a library's (Jackson naming model classes, `java.nio` quoting a server path, `NumberFormatException` quoting its input) could leak. Only an IAE constructed by EDDI's own code (top stack frame in `ai.labs.eddi`) is described now; the rest get the reference id.
* Upgrade by ZIP or live sync with a `targetAgentId`: the guarded agent write was the *last* step, so a caller holding only VIEW/USE on the target had snippets, extensions and workflows written first, then a refused agent write — reported as `500`. `UpgradeExecutor` now requires EDIT on the target before reading or writing anything; a refusal (there, or VIEW in the preview) answers `403` instead of being wrapped into `500`.
* The DEK-rotation `500` said "nothing is lost", which is untrue for a row that could not be opened at all. It now says which rows a re-run moves and what an operator does with an unopenable one (store the secret again; have the grant's user reconnect).

**PR #950 review.**

* Duplicate detection keys a seat by its trimmed `agentId` alone, not `memberType:agentId`: the runtime keys member conversations, speakers and weights by the id only, so an AGENT and a GROUP seat sharing an id collide too. A legacy DEBATE with one agent as PRO and CON loses its CON seat on read; the save then names the missing role, and the read-time warning names the dropped role, so the required roster change is explicit.
* Live sync: a response refused by the size cap is no longer swallowed by the catch blocks that tolerate one unreadable workflow, extension, snippet or descriptor listing — the sync fails (502) instead of upgrading from incomplete source data, where a missing workflow reads as removed.
* Import: an upload cut off after its last complete entry (no central directory) unpacked "successfully" because `ZipInputStream` reads local headers only. The raw archive is now copied aside while streaming and opened with `ZipFile`, which requires the central directory and end record; refused with 400. Docs narrowed: archive-level errors write nothing, an invalid agent/workflow/extension file rolls the import back, an invalid snippet or connection file is skipped with a warning.
* MCP `create_group`: invalid `tasks` JSON returns a curated message instead of Jackson's text (CWE-209).
* Sealed-data AAD prefixes the context with its UTF-8 byte length (was UTF-16 code units); nothing has been released in this format yet.
* Dashboard: the reseal-failures query uses `rate()` to match the panel's per-second unit.
* Round 2: the raw-archive copy (and the drain after the last entry) is bounded at `max-uncompressed-bytes` plus 1 KiB per allowed entry, so a stream that keeps sending — not every caller is behind the HTTP body limit — is refused with 413 instead of being copied to disk without end. A packaged group template that will not convert is now an internal failure without the mapper's text, and `create_group_from_template` routes every failure through `toolFailure`. The duplicate-member docs separate REST's 400 from the MCP tools' JSON error payload.

### Design decisions

* Reject duplicates rather than give each seat its own conversation: every group structure is keyed by `agentId`, and a second seat for one agent would need a seat id threaded through votes, participants, the facilitator, stances and the transcript. A second agent is the supported way to get a second seat.
* Legacy duplicate configs are de-duplicated on read rather than rewritten by a migration: nothing in the database changes until the group is next saved.
* Workspace atomicity uses the primary key both backends already have, rather than a new unique index on a JSON field.
* AAD for sealed data keeps a legacy fallback (same rule as named secrets) instead of a forced re-encryption: no downtime, and a DEK rotation closes the window on demand.

### Not changed

* Manager create-group UI (owned by P13): it should surface the new 400 for a repeated member (and could stop offering an already-picked agent). The Platform Operator prompt was not changed — the 400 message names both positions and says what to do; no endpoint or allow-list change.

***

## 🐛 fix(manager): operator teardown addressed a stale agent version (2026-10-03)

**Repo:** EDDI (`fix/operator-superseded-stale-version`)

### Symptom

Reconfiguring the Platform Operator left the previous operator deployed, with the banner "The new operator agent (…) is live, but the one it replaced (…) could not be removed (eddi://ai.labs.agent/agentstore/agents/…?version=2)".

### Cause

The operator config records the agent's version once, at activation, and never refreshes it. Any in-place edit of the operator afterwards, such as a model or prompt change through Studio or the resource editors, repoints the agent and writes version N+1. Every teardown then addressed the recorded version:

* A permanent delete is refused with a 409 unless it names the live version (the backend's guard against a stale tab erasing a resource that moved on, in `RestVersionInfo.requireCurrentVersion`). The 409's body is only the current URI, and the Manager quoted it as the reason.
* An undeploy of the recorded version left a newer deployed version running.

This affected three teardown paths: retiring the superseded operator on reconfigure, **Delete operator** (`resetOperator`), and the write probe's emergency teardown of an operator with a proven gate breach (`tearDownBreachedOperator`). The kill switch (`deactivateOperator`) had the same undeploy gap. The backend behaved as designed; the bug was the Manager's.

### What changed

* `retireOperatorAgent` in [`operator.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/api/operator.ts) is now the single teardown path. It reads `/currentversion`, undeploys that version and every earlier one (ending their conversations), then deletes permanently at the live version. It retries once on 409, in case the agent moved between the lookup and the delete, and treats an agent that is already gone (404) as retired. If the lookup fails it falls back to the recorded version, so it is never worse than before.
* `deactivateOperator` undeploys every version up to the live one.
* The undeploy never targets a version lower than the recorded one.
* A 409 on retirement is reported as a version conflict instead of a bare URI.

### Design decisions

* **Reactivate still deploys the recorded version, and the status panel still reads it.** The recorded version is the one whose approval gate activation verified. Re-enabling an operator at an edited version nobody verified is a separate decision, so it is left for a follow-up.
* Deleting at the live version destroys nothing extra: a permanent delete is ID-scoped and drops every version anyway.

**Files:** [`operator.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/api/operator.ts), [`use-operator.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/hooks/use-operator.ts), [`write-canary.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/operator/write-canary.ts), plus tests in [`operator.test.ts`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/lib/api/__tests__/operator.test.ts) and [`use-operator-supersede.test.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/hooks/__tests__/use-operator-supersede.test.tsx). The new tests fail with the version lookup reverted (5 failures).

***

## 🐛 fix(openai,attachments): per-chat /v1 conversations, one stream terminator, OpenAI-shaped errors; MIME false positives and atomic quotas (2026-10-03)

**Repo:** EDDI (`fix/v1-attachments`)

Review 2026-10-02 §4.6, the `/v1` and attachment findings.

### What changed and why

* **`/v1` chat key.** A request naming no chat used to land in one `:default` conversation per user and agent, so every SDK/LangChain chat shared context and one document grew towards MongoDB's 16 MB limit. The key is now, in order: `X-OpenWebUI-Chat-Id`, the new `X-EDDI-Chat-Id` header, `metadata.chat_id`, `user` — and otherwise `h:` plus a SHA-256 of the first system and first user message, which an OpenAI client resends unchanged on every turn of a chat. A history-keyed request without history is an opening turn and always starts a fresh conversation (the earlier one is abandoned, not ended). `eddi.openai-compat.chat-key-fallback=shared` restores the old behaviour. Explicit keys over 128 characters are stored as their hash.
* **Bounded growth.** Optional `eddi.openai-compat.max-conversation-steps` (off) ends an idle mapped conversation and continues the chat in a fresh one; LLM context was already bounded by memory windowing.
* **Streaming terminator.** `OpenAiSseWriter` is synchronized and drops every write after its terminator, so tokens from a pipeline still running after the request timeout can no longer follow `[DONE]` (seen live on 6.5.0 / Postgres).
* **Errors.** An ERROR turn is HTTP 500 `{"error":{…,"code":"agent_error"}}` carrying the failing task's sanitized `taskErrors` digest, and on a stream an OpenAI error event before `[DONE]` — never `_The agent produced no text output._` with `finish_reason: "stop"`. Busy, concurrency-cap and timeout failures stream as error events too. `LlmTask` records `llm:finish_reason` (`length`/`content_filter`) and `/v1` reports it as `finish_reason`. Builds on conversation state only, so it does not depend on #946's top-level turn `error`.
* **MIME false positives.** Text declared as a text type and reading as text is compatible whatever signature it starts with (`BMI,…` CSV, Markdown quoting `%PDF-1.7`); BMP detection needs a plausible header; a PDF header past offset 0 counts only at a line start or after a BOM.
* **Quotas.** Checked and inserted under one lock per scope — `pg_advisory_xact_lock` in a transaction on Postgres, a lease document in `attachments.quota_locks` on MongoDB. Live, 12 concurrent uploads against a limit of 3 stored 12 on 6.5.0 and 3 here, on both backends. New optional per-user quota (`eddi.attachments.max-per-user`, `max-total-bytes-per-user`, off), counted against the conversation owner now recorded on each blob.
* **Metrics:** `eddi.openai.chat_keys{source}`, `eddi.openai.conversations.rolled_over`, `eddi.attachments.quota.rejected{scope}` — on the full metrics dashboard.

**Files:** [`OpenAiConversationBridge.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/integrations/openai/OpenAiConversationBridge.java), [`OpenAiSseWriter.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/integrations/openai/OpenAiSseWriter.java), [`MimeValidator.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/attachments/MimeValidator.java), [`GridFsAttachmentStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/datastore/mongo/GridFsAttachmentStore.java), [`PostgresAttachmentStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/datastore/postgres/PostgresAttachmentStore.java); docs [`open-webui-integration.md`](https://docs.labs.ai/protocols-and-integration/open-webui-integration.md), [`attachments-guide.md`](https://docs.labs.ai/agent-configuration/attachments-guide.md), [`configuration-reference.md`](https://docs.labs.ai/deployment-and-infrastructure/configuration-reference.md), [`metrics.md`](https://docs.labs.ai/deployment-and-infrastructure/metrics.md).

* **`/v1`** **`usage` now reports.** The adapter reads `audit:token_usage` from the detailed snapshot, but that snapshot withheld every `audit:` key, so `usage` was never sent (live, on 6.5.0 and on this branch before the fix). `audit:token_usage` — three counts, no prompt text — is now exempt from that denylist; the rest of `audit:*` stays withheld.
* **No internal detail in an unclassified `/v1` failure.** The message of an unexpected exception is logged, not returned to the caller — on the plain path, in a stream's error event, and when a conversation cannot be started. A failed turn still reports its sanitized task digest.
* **`usage` without the audit ledger.** `LlmTask` wrote `audit:token_usage` only with an audit collector attached, so `eddi.audit.enabled=false` silently dropped `/v1` `usage`. The token counts are now recorded either way; the rest of the audit evidence stays behind the collector gate.
* **Mapping rows are swept with their conversation.** The ended-conversation retention sweep (`RestConversationStore.permanentlyDeleteEndedConversationLogs`) now deletes the `(intent, userId)` channel mappings — `/v1` and Slack — that point at a conversation it deletes. A `/v1` client sending only its latest message leaves one mapping per distinct message, and nothing removed them.

### Next

* Same-opening collision (one user, two chats with an identical first system + user message, including few-shot prompts) stays documented, not fixed: nothing in the request separates the chats until their histories diverge. Telling them apart would mean matching the client's resent history against stored transcripts.
* `GroupAttachmentBinder` stores group attachments without an owner, so they do not count towards the per-user quota.

***

## 🐛 fix(audit,logs): review follow-ups to the GDPR audit erasure (2026-10-03)

**Repo:** EDDI (`review/p10`, on top of `fix/gdpr-audit-memory`)

* **Erasure never reports `complete` on trust.** The redaction sweep pages by offset over a timestamp-sorted filter that its own writes shrink; a row stepped over (identical timestamps swapping places between reads) was neither redacted nor counted as failed. A final read of the rows still under the raw id now fails the `auditRedaction` step if any is neither redacted nor a kept compliance record.
* **Admin-action records pseudonymise whole path segments.** A user id that is also a path word (`admin`) or one letter rewrote the rest of the path; only segments after the resource root that equal the id are replaced now.
* **Database-log retention deletes in batches** of 10 000 rows on PostgreSQL, instead of one transaction over the whole history on the first sweep.
* Docs: another replica's audit write queue is not flushed by an erasure (re-run it to redact late entries); the PostgreSQL upgrade check covers `idx_audit_task`; the log-retention metric section no longer splits the audit-metrics explanation.
* **PR #952 review.** The admin-action filter's failure WARN sanitizes the request method, path and exception text (CWE-117, CodeQL log injection). A queued entry redacted on its way out of the write queue is verified before it is re-signed, and the marker records the observed verdict rather than `VALID`. The concurrent-insert cap refusal reports `count/cap`. Docs: LLM transport security depends on the configured base URL (`http://` is not refused); the ledger is described as append-only with the erasure-redaction exception rather than "immutable"; the log-retention sweep runs every `eddi.logs.db-retention-interval`; the export summaries no longer imply a complete bundle; the retention-sweeps dashboard panel shows its legend.

***

## 🐛 fix(hitl,schedule): review follow-ups — ABORT and human-turn timeouts survive, legacy store path guarded, pre-upgrade schedules not disabled (2026-10-03)

**Repo:** EDDI (`review/p4`, on `fix/hitl-scheduling`)

### What changed and why

**Every HITL timeout is re-armed, not only approve/reject.** The retry-later handling covered `AUTO_APPROVE`/`AUTO_REJECT`; an `ABORT` whose cancel failed, and an expired human turn (`SKIP_TURN`) whose skip failed, still logged the failure and completed the fire, so a finite policy became wait-forever on a store blip. `HitlTimeoutHandler` now treats all of them alike — retried while the pause is still waiting, done once it is not — and `GroupHitlCoordinator.skipHumanTurnOnTimeout` no longer swallows its own failure (the handler could never see it). `ConversationHitlService.cancelConversation` also deleted the timeout schedule *before* its state write, so an ABORT whose write failed was re-armed onto a row that no longer existed (seen live with the conversation collection made read-only); the schedule is now dropped only after the write went through, as the group cancel already did.

**The v5 LLM-store path no longer slips past `SelfUngatingGuard`.** `/langchainstore/langchains` is rewritten onto `/llmstore/llms` by `LegacyPathRewriteFilter` before routing, so an approved write through the old spelling carrying `toolApprovals` was not recognised. Both spellings are guarded; a call whose request cannot be resolved (an MCP tool aimed at this server) is refused on the bare `toolApprovals` key.

**Schedules created before the creator snapshot are not disabled on their first fire.** The USE re-check ran against an empty team set for a row that has no snapshot, which would have disabled every team-shared and administrator-created schedule after an upgrade with workspaces enforced. A row with no snapshot (`creatorTeams` absent) is now left alone; Postgres stores an empty team list as `[]` so "no teams" stays distinct from "no snapshot".

**Docs:** [`scheduling.md`](https://docs.labs.ai/conversations-and-orchestration/scheduling.md) says what happens to schedules an older release disabled on undeploy (they carry no `disabledReason`; enable them once by hand), [`hitl.md`](https://docs.labs.ai/conversations-and-orchestration/hitl.md) the wider retry scope.

***

## Review of the LLM tool-execution hardening: HITL resume count, internal retries (2026-10-03)

**Repo:** EDDI · **Branch:** `fix/llm-tool-execution` (review follow-up).

**What changed**

* **The per-turn tool-call cap survives a HITL resume.** `ToolLoopResumer` ran the continuation with a fresh trace and merged the pre-pause trace in only afterwards, so `maxToolCallsPerTurn` was counted from the resumed part alone: a turn could make `maxToolCallsPerTurn` calls before the pause and again after it. The continuation's trace is now seeded with the pre-pause trace, which also means a second pause freezes the whole turn (it used to freeze only the resumed part) into its batch.
* **Model calls outside a task's retry policy keep one retry.** Turning provider SDK retries off removed the only retry the shared summarizer (rolling and stance summaries, Dream), the tool-response summarizer and the cascade judge had. `TransientFailureRetry` gave each one retry after 500 ms, for transient failures only. *Superseded when main was merged in:* #994 runs these calls through `RetryConfiguration.executeWithDefaultRetry` and builds the clients with `NO_LIBRARY_RETRIES`, so `TransientFailureRetry` and `PROVIDER_MAX_RETRIES` were removed.
* **The web-scraper parse pool no longer answers "busy" with a free worker.** Admission is a semaphore with one permit per worker, released by the parse itself when it ends (or by the caller for a parse that never started); the `SynchronousQueue` hand-off refused a call in the instant between a worker finishing and taking its next task. A runaway that ignores the interrupt still holds its permit until it really ends.
* **Refused tool calls are answered after the executed ones**, so tool results follow the order of the calls (the refused ones are always the tail of the response).
* Documented that under a model cascade `maxToolCallsPerTurn` applies per cascade step.

***

## 🧪 test(secrets) + docs(backup): review of the groups, import and secrets fixes (2026-10-03)

**Repo:** EDDI (`review/p9`, on top of `fix/groups-import-secrets`).

### What changed and why

* **Grant contexts, real vault, real resealer.** New `ConnectionGrantVaultRoundTripTest` runs the three places that must agree on a grant's AAD context — sealing, opening and the DEK-rotation sweep — together over real AES-GCM, instead of each against a stand-in. It proves that legacy and bound grants both open after a rotation, that a token moved into another user's row, another connection's row or the other token field no longer opens, and that one unopenable grant leaves every other grant moved.
* **Import docs.** [import-export-an-agent.md](https://docs.labs.ai/getting-started/import-export-an-agent.md#how-merge-tracking-works) now says what the scoped merge lookup means for an administrator: the import writes into the caller's own space unless `X-EDDI-Space` names a team they belong to, so re-importing to update a team's copy needs that header.
* **`RemoteApiResourceSource`.** The new size-cap helpers had been inserted between `configure`'s Javadoc and `configure`; moved above it.

***

## 🔒 fix(rag): review of the knowledge base isolation — disguised reserved names, layout switch under a run, Atlas default collection (2026-10-03)

**Repo:** EDDI (`fix/rag-kb-isolation`)

### What changed and why

An independent review of the isolation change found six gaps; all are fixed on the branch.

* **The `eddi_kb` guard could be walked round.** It compared `startsWith("eddi_kb")` on the raw value, so `"eddi_kb_alpha"` (quoted, which PostgreSQL reads as exactly that table), `public.eddi_kb_alpha` or a `/**/`-prefixed name pointed a new knowledge base at another one's default store and passed. A reserved name is now any whose dot-separated part starts with the prefix (case-insensitive), and a pgvector `table` must be a plain, optionally schema-qualified identifier: the store puts the value into SQL unquoted, so anything else was either a way round the check or SQL an editor could run. A `${vars:…}` / `${vault:…}` reference is refused as the location (see the PR #945 follow-up below). The same-location collision check now treats `public.t` and `t` as one table.
* **A run in flight across a switch to `storeNamespace: "id"`** kept writing into the old store and recorded its documents as ingested, so the next run found them "unchanged" and never filled the new store. `RagSourceIngestionService.cleanUpAfterRun` compared names; it now compares where the vectors live, the same test the save uses to clear the state.
* **An archive imported over an existing knowledge base** carried its own `storeNamespace` into the update — an `"id"` from another instance would silently move a 6.5.0 knowledge base to an empty store, and a `"name"` failed the import. The archive's value is now dropped for an update, and the fallback create (local knowledge base gone) goes through the same storage rules as every other create.
* **Atlas, default collection.** Atlas Vector Search refuses a filter on a field its index does not declare, and the index is the operator's, per collection — so every new Atlas knowledge base failed to retrieve until its index was edited, for a filter that protects nothing on a collection nobody else may name. Atlas is now filtered only when an explicit `collectionName` is set.
* **Vertex `endpoint`** is held to the cloud-metadata guard like every other endpoint parameter.

Tests: guard (disguised names, references, public-schema collision), `KnowledgeBaseStorage` (spellings, identifier pattern, collision key, Atlas filter rule), source ingestion (layout switch purged, id-layout rename keeps state), import (storage rules on create). Docs: `rag.md`.

### Design decisions

* **Refuse by shape, not by normalising.** Quoted pgvector identifiers could be unquoted and compared, but the store does not escape them either; refusing everything but a plain identifier removes the whole class.
* **Not changed, noted:** switching a knowledge base that has an explicit location to `"id"` leaves the old chunks in the shared table, untagged and no longer retrieved.

**Files:** [`KnowledgeBaseStorage.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/rag/model/KnowledgeBaseStorage.java), [`KnowledgeBaseStorageGuard.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/rag/rest/KnowledgeBaseStorageGuard.java), [`RagSourceIngestionService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/ingestion/RagSourceIngestionService.java), [`RestImportService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/backup/impl/RestImportService.java), [`EmbeddingModelFactory.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/EmbeddingModelFactory.java), [`rag.md`](https://docs.labs.ai/agent-configuration/rag.md).

***

## 🔒 fix(rag): a knowledge base's location may not be a reference (2026-10-03)

**Repo:** EDDI (`fix/rag-kb-isolation`, PR #945 review)

CodeRabbit found that the pgvector identifier check skipped any value containing `${`, so `x${vars:a}; DROP TABLE y --` reached the store, which interpolates the table into SQL unquoted. The earlier reasoning ("variables are set by administrators") was wrong: `/variablestore` admits `eddi-editor`, so even a whole `${vars:t}` could be pointed at another knowledge base's table, or at SQL, after the save-time checks had passed on the reference text.

* `KnowledgeBaseStorageGuard` refuses a `${...}` reference as `table` / `collectionName` / `indexName` on create or change, so every location rule is judged on the literal value.
* `EmbeddingStoreFactory` refuses a stored `${...}` location when the store is built, whatever it currently resolves to (round 3 of the review: judging the resolved value still let an editor re-point the variable at another knowledge base's ordinary table, which a 6.5.0-layout knowledge base reads unfiltered). Such a knowledge base works again once it is saved with the literal name. A pgvector table must be a plain identifier; a literal reserved name stored before the rule existed keeps working.
* The Vertex embedding `endpoint` is trimmed once, and that value is both checked and used.

**Files:** [`KnowledgeBaseStorageGuard.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/rag/rest/KnowledgeBaseStorageGuard.java), [`EmbeddingStoreFactory.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/EmbeddingStoreFactory.java), [`EmbeddingModelFactory.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/EmbeddingModelFactory.java), [`rag.md`](https://docs.labs.ai/agent-configuration/rag.md).

**Integration Tests fix (same branch):** `RagIngestionIT.replaceAccepted` still expected the `202` response's `kbId` to be the configuration's name (`ingestion-it-kb`); since this branch the response names the knowledge base by its id, as `docs/rag.md` documents. The IT now asserts the id, and a new `foreignKbIdRefused` case drives the `?kbId=` refusal through the real filter chain: another knowledge base's name is a `400`, this knowledge base's own name is still accepted. File: [`RagIngestionIT.java`](https://github.com/labsai/EDDI/tree/main/src/test/java/ai/labs/eddi/integration/RagIngestionIT.java).

***

## 🧹 chore(build,deploy): auto-approve gaps, pinned Keycloak/MongoDB, no surge pod, installer refs, repo hygiene (2026-10-02)

**Repo:** EDDI (`chore/build-deploy-hygiene`)

Fixes the Build/CI, Deploy and Hygiene findings of the 2026-10-02 review (§4.11).

### Auto-approve (`.github/workflows/auto-approve-copilot.yml`)

* **A Copilot review with findings only in its body counted as clean.** `REQUIRE_CLEAN_COPILOT` counted inline comments, but Copilot folds low-confidence findings into a collapsed section of the review body (`Suppressed comments (2)`), where no inline comment and no thread exists — PR #672 got three such reviews, each of which this job would have approved. The body now has to say in Copilot's own words that nothing was found — legacy format: "generated no (new) comments"; the overview-v2 format Copilot has used since 2026-09: "Approval recommended" with "**Findings:** None" — and carry no collapsed section with a non-zero count (suppressed comments, v2's `Open (n)` list of unresolved findings) and no could-not-review notice. An empty body or an unknown format fails closed: it costs a human review, never a silent approval. The rule was checked against every Copilot review body on the last 120 PRs plus a sample of older ones (one clean v2 review, #866, approves; every other is refused).
* **The never-auto-approve list covered `.github/**` only.** It is now a glob list (`PROTECTED_GLOBS`): scripts, every `pom.xml`, the Maven wrapper, Checkstyle and formatter config, every Dockerfile, `mcp-sidecar/`, ClusterFuzzLite, Helm, Kustomize, `gcp/`, the Keycloak realm, every `docker-compose*.yml`, both installers, `mise.toml`, `.gitleaksignore`, `.trivyignore`, and the UI `package*.json`, `.npmrc` and `scripts/`, and the configs the UI checks run against (`vite`, `vitest`, `playwright`, `eslint`, `stryker`, `tsconfig*`) and every `.dockerignore`. Renames are checked on both paths, as before.
* [`AutoApproveCopilotPolicyTest`](https://github.com/labsai/EDDI/tree/main/src/test/java/ai/labs/eddi/deploy/AutoApproveCopilotPolicyTest.java) lifts both policy blocks out of the workflow and runs them under `node`.

### Third-party images

* **Keycloak `26.0` → `26.8.0`** in `docker-compose.auth.yml`, the Helm chart, `k8s/overlays/auth` and the Manager's two Keycloak compose stacks (which ran a floating `26.7`, so the auth E2E tier tested a different IdP from the one users ran). Verified live: the realm imports, the login theme renders, a token is issued and EDDI accepts it, the `eddi-mcp` PKCE/redirect rules hold.
* **MongoDB: one pin, `mongo:7.0.43`,** everywhere: compose (was `7.0.14`), CI and `ContainerBaseIT` (`7.0.14`), Helm and Kustomize (a floating `7.0`), the Manager's compose stacks (end-of-life `6.0`). `7.0.14` is also inside the CVE-2025-14847 range, fixed in `7.0.28`.
* [`ThirdPartyImagePinsTest`](https://github.com/labsai/EDDI/tree/main/src/test/java/ai/labs/eddi/deploy/ThirdPartyImagePinsTest.java) requires one full `MAJOR.MINOR.PATCH` version of each across compose, `ui/*` compose, Kustomize, Helm values and (for MongoDB) the workflows.

### No surge pod during upgrades

The EDDI Deployment rolled with `maxSurge: 1`, so every upgrade ran **two EDDI JVMs against one database** for the length of the rollout, with every node-local mechanism (turn lock, replay nonces, rate limits, caches, HITL crash recovery) diverging between them. The Helm chart gains `eddi.updateStrategy` (default `Recreate`; `RollingUpdate` documented as an opt-in in [`kubernetes.md`](https://docs.labs.ai/deployment-and-infrastructure/kubernetes.md#upgrades-replace-the-pod-no-surge)), and the Kustomize base and `quickstart.yaml` use `Recreate`. Chart version **2.4.0**.

### Installers

* **`latest` fetched the compose files from `main`.** `install.sh` and `install.ps1` now resolve `EDDI_VERSION=latest` to the newest release tag through the GitHub releases API and download the files from that tag; when the API cannot be reached they fall back to `main` and say so. The reason is recorded as `EDDI_BRANCH_SOURCE` in `.eddi-config`, and `eddi update` (both the bash and the `eddi.cmd` wrapper) looks `latest` up again, so an update never pulls a new image with old files. `install.ps1` now honours `EDDI_VERSION` too, and writes it to `.env` like `install.sh`.
* **The "prevent path traversal" check did not.** It was a character class that admits `.` and `/`, so `EDDI_BRANCH=../../someone/else/main` passed and curl, which resolves dot segments, fetched another repository's files. Both installers and both wrappers now also refuse `..`, `//`, a leading or trailing `/`, a component starting with `.`, a trailing `.` and `.lock` — none of which git allows in a ref name.
* New `install.sh --dry-run` / `install.ps1 -DryRun` print the image tag, the ref and why, and exit.
* The `eddi update` wrapper writes `.env`/`.eddi-config` without `sed -i`, whose syntax differs on macOS.
* **`eddi.cmd` checked the ref through a pipe, which cmd.exe re-parses.** Each side of a pipe runs in a child `cmd.exe` that parses the expanded value again, so `EDDI_BRANCH=x&<command>&rem /../../../other/repo/main` ran `<command>` and was then checked as the harmless `x` — and the traversal behind it was downloaded. The check now writes the value to a temp file and runs `findstr` on the file, and the release lookup keeps only a `MAJOR.MINOR.PATCH` tag inside PowerShell, so no API text reaches a cmd.exe parser.
* An install from before `EDDI_BRANCH_SOURCE` existed, on a ref set by hand, keeps that ref on `eddi update` (bash and `eddi.cmd`) instead of being moved to the newest release: the old installers only ever chose `main` or the version tag themselves.
* `install.sh` validates `EDDI_VERSION` against Docker's tag grammar, as `install.ps1` and `eddi update` already did; `install.ps1`'s ref, tag and version checks anchor with `\z`, since .NET's `$` also matches before a trailing newline.
* Helm: `strategy` falls back to `Recreate` when `eddi.updateStrategy` is absent — `helm upgrade --reuse-values` from chart 2.3.0 carries no such value, and the template rendered `strategy: null`, which Kubernetes reads as a 25% `RollingUpdate`.
* [Upgrading from 6.4](https://docs.labs.ai/deployment-and-infrastructure/upgrading-from-6.4.md) now says how to keep the 6.4 and 6.5 pods from overlapping with the manifests 6.5.0 shipped (scale to zero first), and lists the three changes after 6.5.0 an operator sees: `Recreate`, Keycloak 26.8.0 (forward-only database migration; the *Full scope allowed* deprecation warning on `eddi-frontend`) and MongoDB 7.0.43.
* [`InstallerReleaseRefTest`](https://github.com/labsai/EDDI/tree/main/src/test/java/ai/labs/eddi/deploy/InstallerReleaseRefTest.java) runs `install.sh --dry-run`, the installed `eddi update` and `install.ps1 -DryRun` against a stand-in `curl`.

### Stargazer roster (`docker-pull-notify.yml`)

The metrics job stored every stargazer's login and star time on the `metrics` branch daily, so its history recorded who unstarred and when, kept forever. Collection has stopped (data minimisation — the aggregate star count answers the project-health question); the step removes `data/stargazers.csv` from the branch tip and the branch README gives the `git filter-repo` recipe to purge the history. Nothing else read the file; `data/metrics.csv` and the digests are unchanged.

### Repo hygiene

* Removed the AI-tool leftovers `ui/chat/docs/superpowers/**` and `ui/manager/docs/superpowers/**` (design specs and a task plan for features that shipped). The one with open items, the Chat UI follow-ups, moved to [`planning/chat-ui-followups.md`](https://github.com/labsai/EDDI/tree/main/planning/chat-ui-followups.md).
* Removed the Medium articles `planning/eddi-6.1-medium-article.md` and `eddi-6.2-medium-article.md` (published elsewhere; nothing linked them).
* Plan status headers that contradicted what shipped now say so: `hitl-framework-plan.md` (implemented; added to the shipped-plans guard), `multi-tenancy-plan.md`, `saas-connectors-plan.md`, `rag-ingestion-source-types-plan.md`, `multi-agent-ux-improvements.md`, `documentation-updates-plan.md`, `agentic-improvements-plan.md`, `manager-ui-handoff.md`.
* The test count was "about 18,000" in AGENTS.md, "21,000+" on the README badge and "\~19,800" in `ci.yml`. Measured: 20,241 `@Test`/`@ParameterizedTest` methods in `src/test/java`. All three now say "20,000+", and AGENTS.md gives the command that counts them.
* `ui/manager/HANDOFF.md` is kept: it is the Manager's documented pre-monorepo history log, marked "no longer appended to" and pointed at from `ui/manager/AGENTS.md`.

***

## 📘 docs: correct what the 2026-10-02 review found wrong, and add a REST reference, troubleshooting and release-notes index (2026-10-02)

**Repo:** EDDI · **Branch:** `docs/review-corrections`

The documentation pass of the 2026-10-02 review (§5). Every corrected claim was checked against the code, and every copy-pasteable command on the touched install, tutorial and reference pages was run against a jar built from this branch.

### Install paths that did not boot

* [`getting-started.md`](https://docs.labs.ai/getting-started/getting-started.md): the manual `docker run labsai/eddi` exited at startup — `AuthStartupGuard` and `HighValueSurfaceGuard` refuse a production boot without OIDC unless opted out. The command now sets the three `EDDI_*_ALLOW_UNAUTHENTICATED` flags the compose file sets, binds to `127.0.0.1`, names the Mongo container the image's default connection string expects, and carries a local-only warning. Dev mode does not build the Manager, which the page now says.
* [`setup-eddi-on-aws-with-mongodb-atlas.md`](https://docs.labs.ai/deployment-and-infrastructure/setup-eddi-on-aws-with-mongodb-atlas.md): no `JAVA_OPTS_APPEND` override (it replaced the image's own flags), the Mongo URI is fixed, and `MONGODB_CONNECTIONSTRING` and `EDDI_VAULT_MASTER_KEY` come from Secrets Manager. [`redhat-openshift.md`](https://docs.labs.ai/deployment-and-infrastructure/redhat-openshift.md): the quick start has a MongoDB and binds to loopback; the OIDC client is `eddi-backend`; the `redhat-certify` and OpenSSF-level claims say only what the repository shows. [`docker.md`](https://docs.labs.ai/deployment-and-infrastructure/docker.md): `mongo:7.0.43`.
* [`security.md`](https://docs.labs.ai/security-and-compliance/security.md): EDDI does not "run open" — the two startup guards are described.

### Examples that did not compile or misbehaved

* [`developer-quickstart.md`](https://docs.labs.ai/getting-started/developer-quickstart.md): the Java snippets now use the real API (`Property`, `new Data<>`, `getId`/`getType`, null-checked `getLatestData`); a custom task needs a bootstrap module registering it in `@LifecycleExtensions`; the rule fragments are wrapped in `behaviorGroups`; the context example no longer expects a start-call context on a later turn (shown live: it renders blank).
* [`creating-your-first-agent/`](https://docs.labs.ai/getting-started/creating-your-first-agent.md): the two GitBook-era tutorials (numbering 1, 4, 5, 6, `packages`, `RuleChild.values`, the legacy inline property setter, a Postman list, "Your Welcome") are folded into one tutorial that was run end to end.
* [`conversations.md`](https://docs.labs.ai/conversations-and-orchestration/conversations.md): the redo cache **is** cleared by the next message (shown live); the page said the opposite.
* [`architecture.md`](https://docs.labs.ai/architecture-and-concepts/architecture.md): no native image is shipped; Jackson, not JSON-B; the vault DEK is per tenant; `logSizeLimit`, not `sendConversation`; a Dream schedule needs no `message`; the ToC covers every section and the Summary closes the page; unsourced performance figures removed.
* [`conversation-memory.md`](https://docs.labs.ai/architecture-and-concepts/conversation-memory.md) (only conversation *state* is cached, for 30 s; the real init flow and stored document; the `secret` scope), [`memory-policy.md`](https://docs.labs.ai/architecture-and-concepts/memory-policy.md) (`task_failed_<lifecycle task id>`; the 200-character cap excludes the prefix), [`managed-agents.md`](https://docs.labs.ai/conversations-and-orchestration/managed-agents.md) (`undoAvailable`/`redoAvailable`, not `redoCacheSize`; the list-all trigger endpoint), [`langchain.md`](https://docs.labs.ai/agent-configuration/langchain.md), [`how-to....md`](https://docs.labs.ai/reference/how-to....md), [`prompt-snippets-guide.md`](https://docs.labs.ai/agent-configuration/prompt-snippets-guide.md), [`capability-match-guide.md`](https://docs.labs.ai/conversations-and-orchestration/capability-match-guide.md) (the real group tools instead of `createGroupConversation`), [`code-review-standards.md`](https://docs.labs.ai/reference/code-review-standards.md) (two required checks).

### `PUT`, not `POST`, stores a secret — in the docs and in the product

[`agent-sync-guide.md`](https://docs.labs.ai/conversations-and-orchestration/agent-sync-guide.md), [`connections.md`](https://docs.labs.ai/protocols-and-integration/connections.md) and seven validation messages in `ConnectionConfiguration` and `RestApiCallsStore` told admins to `POST /secretstore/secrets`, which answers 404 (and `POST` on a key's path, 405). They now name `PUT /secretstore/secrets/{tenantId}/{keyName}`; new tests in `ConnectionConfigurationValidationTest` and `RestApiCallsStoreBranchTest` pin it.

### New and rewritten pages

* [`rest-api-reference.md`](https://docs.labs.ai/conversations-and-orchestration/rest-api-reference.md): every conversation endpoint and the streaming SSE event contract (`task_start`, `task_complete`, `task_failed`, `token`, `tool_call`, `cascade_*`, `done`, `error` with its `code`s), with captured requests and responses. Before, the contract existed only in `ui/chat/AGENTS.md`.
* [`troubleshooting.md`](https://docs.labs.ai/getting-started/troubleshooting.md): startup guards, datastores, LLM providers, HITL, groups, vault, connections, scheduling, GDPR, deployment and auth, each with the exact message the code emits.
* [`release-notes.md`](https://docs.labs.ai/deployment-and-infrastructure/release-notes.md): an index of 6.0–6.5 pointing at the GitHub release notes, the upgrade guides and the changelog archive.
* [`agent-manager-gui.md`](https://docs.labs.ai/getting-started/agent-manager-gui.md): rewritten for the Manager that ships, including the Platform Operator; [`README.md`](https://docs.labs.ai/readme.md) loses its overpromising headings and its quick start no longer assumes a compose file.
* [`configuration-reference.md`](https://docs.labs.ai/deployment-and-infrastructure/configuration-reference.md): a "settings operators set first" section — MongoDB and PostgreSQL connection settings, OIDC, CORS, body size, bind address, `QUARKUS_CONFIG_LOCATIONS`.

### Corrections from the independent review of this branch

* [`rest-api-reference.md`](https://docs.labs.ai/conversations-and-orchestration/rest-api-reference.md): the streaming `done` event carries a reduced snapshot (`conversationState`, `conversationOutputs`, `hitlPausedAt`), not the full one; `POST /conversationstore/conversations/end` takes an array of `{"conversationId": …}` objects (an array of id strings is a 400); a read of an unknown conversation answers `No conversation found! (…)`.
* [`creating-your-first-agent/`](https://docs.labs.ai/getting-started/creating-your-first-agent.md): the JSON-with-context example was sent to the conversation the tutorial had just ended (410); it now starts a new one. `returnDetailed=true` alone returns only the last turn, so the "full memory" call adds `returnCurrentStepOnly=false`.
* [`getting-started.md`](https://docs.labs.ai/getting-started/getting-started.md) no longer says the compose file pins a release (it defaults to `latest`); [`developer-quickstart.md`](https://docs.labs.ai/getting-started/developer-quickstart.md) drops release-tooling wording from user guidance; [`README.md`](https://docs.labs.ai/readme.md) says the compose quick start runs with the vault off until `EDDI_VAULT_MASTER_KEY` is set; [`configuration-reference.md`](https://docs.labs.ai/deployment-and-infrastructure/configuration-reference.md) states which value wins when `QUARKUS_CONFIG_LOCATIONS` and an environment variable set the same key (the file's, checked against `labsai/eddi:6.5.0`).
* `ConnectionConfigurationValidationTest` now also pins the vault hint of a literal `oauth.clientSecret` and of a credential-shaped `extraAuthParams` value, the two of the seven messages no test covered.

**Added while merging `main`:** [`upgrading-from-6.5.md`](https://docs.labs.ai/deployment-and-infrastructure/upgrading-from-6.5.md) gains an **Authorization defaults** section listing what #942 (authorization hardening) changes for a running 6.5 deployment — the metrics role, API docs, `/v1`, triggers, owner-less conversations and unannotated JAX-RS resources. #942's description deferred these notes to whichever of #937 and #942 merged second, and neither added them.

***

## 🔒 fix(security): conversation owner can no longer be stripped; role gates on /v1, metrics, OpenAPI; deny-by-default JAX-RS (2026-10-02)

**Repo:** EDDI (`fix/authz-hardening`)

Answers the authorization findings F1–F7 of the 6.5.0 review (`REVIEW-2026-10-02.md` §2 #1 and #9, §3.4, §4.2).

### F1 (Critical) — conversation owner stripped through the generic descriptor API

Conversation descriptors share the `descriptors` collection with configuration descriptors. `GET /descriptorstore/descriptors?type=ai.labs.conversation&filter=<user>` enumerated them, and `PATCH /descriptorstore/descriptors/{conversationId}` read one as a configuration descriptor and replaced it whole — without `userId`, `agentResource`, `environment` or `conversationState`. `ConversationAccessGuard` then admitted every authenticated caller ("legacy, unowned"), and a viewer and a role-less token read another user's conversation. Fixed in depth:

* **Configuration only.** New [`ConfigResourceTypes`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/descriptors/ConfigResourceTypes.java) derives the configuration descriptor types from the configuration stores themselves (every `IRestVersionInfo` store's resource URI) — no hand-kept list. `RestDocumentDescriptorStore` refuses a listing whose `type` is not one of them (`400`; a blank type or a prefix used to match every descriptor) and answers `404` for a read, simple read or patch of a non-configuration id. `ResourceSharingService` does the same for every `/shares/**` operation (and cascade targets), and the access-request endpoint checks it too.
* **No lossy write.** `DocumentDescriptorStore.setDescriptor`/`updateDescriptor` refuse to write a conversation descriptor through the configuration shape, whatever the caller — the whole-document replace is what dropped the fields. Same code path on MongoDB and PostgreSQL.
* **Fail closed.** `ConversationAccessGuard` resolves the owner from the descriptor, else from the conversation memory snapshot (the pre-v5.1.6 fallback the listing already used, now the projected `loadListingSummaries` read), and refuses a conversation with no owner anywhere to everyone but an admin — on every read, write and listing path (`requireConversationOwner`, `requireExistingConversationOwner`, the strict variant, `canAccessConversation`). The legacy-open rule existed for pre-v5.1.6 descriptors, whose memory records the owner; EDDI never writes a conversation without one.

### F2 — agent-trigger hijack

`RestAgentTriggerStore` create, update and delete now require **EDIT** (was USE) on the agents the trigger routes to — the stored ones and the new ones. A `PUT` whose body names another intent is a `400` (MongoDB used to rename the trigger, PostgreSQL kept the row under the old key with the new intent inside). Create on an existing intent was already refused by both stores (unique index / primary key); a test now pins that it is not a takeover. The trigger cache is untouched (the NATS PR owns it).

Review follow-ups (PR #942):

* A trigger written through the API must route to at least one agent, with no blank `agentId` (otherwise `400`). A stored targetless trigger — nothing to derive an EDIT right from — is an administrator's to change while workspaces are enforced.
* Update and delete are bound to the version they were authorized against: the new `IAgentTriggerStore.updateAgentTriggerIfUnchanged` / `deleteAgentTriggerIfUnchanged` write only if the trigger still routes the same way. MongoDB filters on the stored document itself; PostgreSQL uses `AND data = ?::jsonb`. A re-point that lands between the check and the write turns the request into a `409` instead of being overwritten.
* Filtered capability searches (workspaces enforced, public A2A discovery) are now counted and timed like unfiltered ones.

### F3 — `/v1` had no role gate in OIDC mode

`OpenAiAuthFilter` requires `eddi-admin`, `eddi-editor` or `eddi-user` in `http-policy=authenticated` mode (with authorization on) and answers `403 insufficient_permissions` otherwise. The default shared-key `permit` mode is unchanged.

### F4 — team memories readable by naming a group

New [`GroupMemoryAccessGuard`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/security/GroupMemoryAccessGuard.java) for `GET /usermemorystore/memories/{userId}/visible?groupId=` and MCP `get_visible_memories`: USE on the group under workspaces (as before), and — the gap — with workspaces off the caller must take part in the group (own one of its group conversations, or be a `HUMAN` member). Admins and auth-off deployments are unaffected.

### F5 — listings ignoring workspace scope

`GET /deploymentstore/deployments` and `GET /capabilities` (search and skills) list only agents the caller may USE (the capability filter runs before the selection strategy); `GET /administration/{env}/deploymentstatus/{agentId}` requires USE; `GET /a2a/agents` requires `eddi-admin`/`eddi-editor`/`eddi-user` instead of any token; `/.well-known/capabilities` (and `/skills`) name only A2A-enabled agents — `CapabilityRegistryService` now tracks which registered agents are `a2aEnabled`.

### F6 — legacy group-conversation delete

`RestGroupConversation` delete and close use `requireOwnerOrAdminStrict`: a record without an owner is an admin's to delete, not every caller's.

### F7 — role-less tokens reached metrics, OpenAPI and unannotated endpoints

* `quarkus.security.jaxrs.deny-unannotated-endpoints=true`. Audited every resource; the public ones now say `@PermitAll` explicitly (SPA shells, `/connections/callback`, the Slack webhook, the `/v1` adapter, whose gate is its filter), the per-conversation `/conversationstore` operations require any EDDI role on top of the owner check. New `EndpointSecurityAnnotationsTest` walks every compiled resource and fails on an unannotated method — it found the `/v1` adapter, which the deny-default would otherwise have shut for everyone. The live run found one more: `…/{id}/currentversion` on every configuration store is a default method of the `IRestVersionInfo` mixin, and Quarkus takes the class-level annotation from the *declaring* type, so the store interface's `@RolesAllowed` never applied — it was open to any token, and the deny-default refused it to everybody. Both methods now carry `@RolesAllowed({"eddi-admin", "eddi-editor"})`, and the test models the declaring-type rule.
* `/q/metrics` defaults to the new named policy `eddi-metrics-reader` (`eddi.metrics.roles-allowed`, default `eddi-admin,eddi-metrics`); `authenticated` and `permit` stay selectable through the existing `eddi.metrics.http-policy`. **Upgrade note:** a scrape that authenticated without a role gets `403` until its service account has the `eddi-metrics` realm role (create it; the shipped realm does not define it), or set `EDDI_METRICS_HTTP_POLICY=authenticated`.
* `/openapi`, `/q/openapi`, `/q/swagger-ui` require any EDDI role (`eddi.api-docs.http-policy`, `eddi.api-docs.roles-allowed`).
* Helm: only the comment on `eddi.metrics.httpPolicy` in `values.yaml` changed (it named the old default). The chart version is deliberately not bumped here: nothing renders differently, and the chart's next version is taken by a concurrent change.

### Docs

[`security.md`](https://docs.labs.ai/security-and-compliance/security.md) (permissions table, new "Deny by default" and "Conversations are not configuration" sections), [`workspaces.md`](https://docs.labs.ai/security-and-compliance/workspaces.md), [`managed-agents.md`](https://docs.labs.ai/conversations-and-orchestration/managed-agents.md), [`monitoring-guide.md`](https://docs.labs.ai/deployment-and-infrastructure/monitoring-guide.md), [`open-webui-integration.md`](https://docs.labs.ai/protocols-and-integration/open-webui-integration.md), [`configuration-reference.md`](https://docs.labs.ai/deployment-and-infrastructure/configuration-reference.md) (four new properties).

**Platform Operator:** unchanged. Its allow-list holds `PATCH /descriptorstore/descriptors/{id}` and `GET /administration/{env}/deploymentstatus/{agentId}`; it uses both on configuration and as an admin, which this change leaves as it was, and its prompt says nothing about metrics, `/v1` roles or triggers that became wrong.

***

## 🐛 fix(engine): watchdog really stops a timed-out turn; client errors get 400s with a message; readable, fail-fast startup (2026-10-02)

**Repo:** EDDI (`fix/engine-runtime-hardening`) — review findings of 2026-10-02 (§4.1 engine core, top issue #13 part 2, harness defects 2 and 3).

### What changed and why

**Agent-timeout watchdog** ([`ConversationStepRunner`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/internal/ConversationStepRunner.java))

* On `systemRuntime.agentTimeoutInSeconds` the watchdog only cancelled the future: an interrupt, which any layer below can swallow, plus the token that suppresses the final persist. A pipeline that swallowed the interrupt kept running every remaining lifecycle task — model calls, tool calls, long-term property writes — and, because the turn left `inFlightConversations` the moment the watchdog returned, neither `/cancel` nor the GDPR `stopInFlightWork` sweep could reach it.
* The watchdog now raises the memory's cooperative-cancel flag before the interrupt, through one small method, `ConversationStepRunner.abandonTurn(memory)` (meant to be the single entry point for every "this turn is no longer wanted" signal that does not come from a caller — a lost cluster lease can call it too). `LifecycleManager` checks the flag before every task, and `Conversation.isTurnDiscarded` before the long-term write-back.
* An abandoned turn stays registered until its body actually returns (`InFlightRegistration`): the body unregisters itself; a body that never started is unregistered at once. Removal stays value-conditional. The HITL resume path's watchdog sets the flag too.
* A dispatcher that dies in the watchdog's own abandon branch (a datastore outage is the likeliest cause of a timeout) no longer unregisters a body that is still running, and an abandoned turn's failure repairs the conversation-state cache, which the pipeline's own error handling had left at `ERROR` while the store said `EXECUTION_INTERRUPTED`.
* A turn already flagged cancelled no longer writes `ERROR` from its failure callback. Live, the interrupt aborts the model call and the next store access on the interrupted thread throws; on 6.5.0 that `ERROR` write raced the watchdog's `EXECUTION_INTERRUPTED` and sometimes won.
* A cancelled turn that fails is now settled like one that completes (`settleCancelledTurn`): `EXECUTION_INTERRUPTED` by CAS from READY/IN\_PROGRESS, and the state cache made to agree. Before, only the watchdog recorded a state; a `/cancel` or GDPR stop of a running say turn that then failed left the conversation READY (the say path never persists IN\_PROGRESS).
* Public seam `ITurnAbandonment.abandonInFlightTurn(conversationId)` (removed again on 2026-10-31, unused), implemented by `ConversationService`, for callers outside `engine.internal` — the NATS coordinator's lost-lease hook in particular.
* New gauge `eddi_conversation_abandoned_running`: turns the dispatcher gave up on whose body still runs. Normally 0; on the Full Metrics dashboard's "Conversations in flight" panel and in [`metrics.md`](https://docs.labs.ai/deployment-and-infrastructure/metrics.md).
* Test against the real `BaseRuntime` and a real `LifecycleManager`: [`ConversationWatchdogAbandonTest`](https://github.com/labsai/EDDI/tree/main/src/test/java/ai/labs/eddi/engine/internal/ConversationWatchdogAbandonTest.java) — a task that swallows the interrupt, a task after it that must never run, the GDPR sweep reaching the zombie while it runs and not after.

**Client errors** ([`engine/exception`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/exception/README.md))

* `POST /agents/{malformed-id}` answered 500 with an ERROR stack trace (the say path is resumed through an `AsyncResponse`, so `IllegalArgumentExceptionMapper` never saw it); it is now 400, like `GET` on the same id. `ConversationService` no longer logs it at ERROR either.
* A query or path parameter of the wrong type (`?conversationState=BOGUS`, `?version=abc`, `?limit=x`) answered the JAX-RS-mandated `404 Not Found`. `ParameterConversionExceptionMapper` recognises exactly those 404s (raised by the framework's parameter handler with the conversion failure as cause) and answers 400 naming the value and, for an enum, the legal ones. Every other 404 is unchanged.
* Bodies the JSON reader cannot read — malformed JSON, a value of the wrong shape (an invalid `context`), nesting past the parser's depth limit — answered 400 with an empty body. `UnreadableBodyExceptionMapper` and `MismatchedJsonInputExceptionMapper` now give the line/column or JSON path and what belongs there, never a Java type.
* All of these, and `IllegalArgumentExceptionMapper`, use one JSON body, `{"error": "bad_request", "message": "…"}` ([`ErrorResponses`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/exception/ErrorResponses.java)) — the keys the quota and capacity mappers already use. The IAE mapper used to send the bare message under the endpoint's `application/json` type, which did not parse.
* Under `/v1` (the OpenAI-compatible API) the same mappers answer in the OpenAI envelope, `{"error": {"message", "type", "code"}}`, so SDKs keep reading `error.message`; `ErrorResponses.badRequest(message, uriInfo)` chooses by path.
* **Only EDDI's own `IllegalArgumentException` messages reach the client** (review, CWE-209). One raised inside a library or the JDK — the MongoDB driver's `state should be: hexString has 24 characters`, a `UUID` or `java.nio` parser — is answered with `The request contains an invalid value (reference <uuid>)`, and the original message is logged at INFO under that reference. The deciding fact is the throwing frame (`ai.labs.eddi.*`), so EDDI code that merely lets a library exception through does not make its text caller-facing. Same idea as the MCP side's caller-facing check, decided independently.
* `ConversationService.readConversationLog` lowercased `outputType` before its null check. Over REST the `@DefaultValue` covers an empty parameter, so this was only reachable from code; it is null-safe now, and a blank type means text like an empty one.

**Startup**

* The vault and compliance banners reached container logs as one line full of literal `\n`: the console filter escapes line breaks inside a record (CWE-117). [`LogBanner`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/utils/LogBanner.java) logs them one record per line.
* `AuthStartupGuard` and `HighValueSurfaceGuard` now observe `StartupEvent` at `PLATFORM_BEFORE`. At the default priority the vault/index observers ran first, so a bare start with no reachable database spent 30 s per operation on MongoDB and exited with a MongoDB error — the guard's own message never appeared.
* `HV000271` (×3 per boot): `@Valid` moved from `DiscussRequest.attachments`' list to its type argument.
* `OpenTelemetry API usage issue detected` at every boot came from Quarkus' Prometheus exemplar sampler, which hands `Span.fromContextOrNull` a null context on any thread without one. [`NullSafeExemplarSamplerProducer`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/runtime/NullSafeExemplarSamplerProducer.java) replaces it (`@Alternative`) with the same sampler minus the null.

**Cleanups**

* `ConversationService.say` and `sayStreaming` were two copies of \~170 lines. One admission path, `admitTurn`, now serves both; what differs (where the outcome goes, the progress-event sink, the streaming error callback) is a small `TurnListener`.
* The environment-qualified `IConversationService` overloads with no caller outside the service (`readConversation`, `getConversationState`, `sayStreaming`, undo/redo and their availability checks) left the interface; `say(Environment, …)` stays (schedules and A2A use it).
* `undo`/`redo`/`isUndoAvailable`/`isRedoAvailable` by conversation id loaded the snapshot twice; once now.
* Removed `DeepCopyUtil` (used only by its own test). Moved `ACCEPTED_END_REASONS` out from between `endActiveConversations` and its Javadoc.

### Verified, not changed

* **Secret input** (`secretInput` context flag): verified live against 6.5.0 and this branch — the stored conversation (all collections), REST snapshots, the conversation log, the audit trail, the next turn's LLM history and the server log never contain it. Residual, by design: the model receives the plaintext in the current turn (documented: tasks see it while the turn runs), so a model that echoes it echoes it into that turn's live SSE `token` frames, to the caller who sent it; nothing of it is persisted.
* **Live, the watchdog's interrupt is honoured** by EDDI's own model path (the body ends at once with "Chat request interrupted"), so on a default deployment the swallowed-interrupt case is the exception the flag guards against, proven by the unit test. What does keep running is the langchain4j request on its `eddi-chat-timeout` thread: it times out at 60 s and retries, so an abandoned turn still costs a second model call (seen identically on 6.5.0 and this branch). That belongs to the LLM module and is left to its PR.

### Not done here (and why)

* Postgres: a malformed conversation id still answers 500 on the Postgres backend (id parsing differs; owned by the datastore PR).
* `ThreadContext` and the unused `threadBindings` parameter of `IRuntime.submitCallable`: the removal touches \~40 files, including `RestAgentAdministration`'s deploy path (fix/hitl-scheduling) and the NATS coordinator (the cluster PR). Left for after those merge.
* `IAgentFactory`'s never-thrown checked exceptions: owned by fix/hitl-scheduling.
* Other REST catch-alls that turn an `IllegalArgumentException` into 500 sit in schedules, groups and import (other PRs' areas); see the evidence file for the probe.

***

## 🐛 fix(hitl,schedule): approvals bind to the call, timeouts survive and bind to their pause, self-ungating refused in the engine, schedule lifecycle fixes (2026-10-02)

**Repo:** EDDI (`fix/hitl-scheduling`)

### What changed and why

**HITL — an approval clears one call, not an id.** `ToolLoopResumer` used to add every approved (or replayed / outcome-unknown) call id to a set the gate consulted on every later iteration, so a *different* call that reused the id — OpenAI-compatible servers that number `call_1` on every turn, or send `""` — ran unapproved. Live on stock 6.5.0: approving `calculate` let a following `getCurrentDateTime` under the same id run. The new `ClearedToolCalls` binds a clearance to call id + tool name + canonical-JSON argument fingerprint and is consumed by the first match; a blank id never clears. `ToolApprovalGateSupport.normalizeToolCallIds` now re-mints empty-string ids and an id repeated within one model message, so per-call verdicts never cover two calls.

**HITL timeouts.** A timeout decision that could not be applied *yet* (store blip loading the conversation, node draining for shutdown, a concurrent decision in flight) restored the pause, but the fire was logged `COMPLETED` and the one-shot disabled — a finite `AUTO_REJECT`/`AUTO_APPROVE` never fired again until a restart. `HitlTimeoutHandler` now throws `RetryLaterException` while the pause is still waiting; the fire is recorded `FAILED` with the reason and `SchedulePollerService` re-arms HITL timeouts at `eddi.schedule.hitl-timeout-retry-interval` (default `2m`), never dead-lettering them. Timeout schedules now carry the `pauseId` they were armed for (all producers go through `HitlSchedules.timeoutMetadata`) and the decision names it, so a stale fire is refused as a pause mismatch instead of deciding a newer pause. An undeploy no longer disables an agent's HITL timeouts.

**Operator self-ungating is refused server-side.** `SelfUngatingGuard`, checked in `ToolLoopResumer` next to the self-conversation rule, refuses an approved non-read request whose URI names the acting agent (`updateResourceUri`, deploy, self-start) and an `llmstore` write whose body carries `toolApprovals` (or cannot be parsed). Every approval surface — Manager, Slack, MCP `resume_conversation`, REST `/resume` — executes through it; live on stock 6.5.0 both writes executed after a plain REST `/resume`. The Manager guards stay. Operator prompt updated (revision 3).

**Scheduler.** The batch deadline was the lease (5 m each), so a fire running to the deadline was interrupted exactly when its claim became stealable — long fires double-ran (live on stock: one one-shot fire reached the LLM three times with `lease-timeout=20s`). The batch now waits `fire-timeout` + 30 s, the lease defaults to `10m` and is raised at startup (with a WARN) when it does not outlast that; an interrupted fire records "exceeded eddi.schedule.fire-timeout" and counts `eddi.schedule.fire.timedout`. A validation failure on schedule create/update now answers `400 {"error":"invalid_schedule","message":"<reason>"}` instead of a bare "Invalid schedule configuration".

**Deploy lifecycle.** `RestAgentAdministration` announced READY and re-enabled schedules even when `AgentFactory.deployAgent` had marked the deployment `ERROR` (it reports failure through the callback, it does not throw); it also re-enabled every disabled schedule — user-disabled ones included — on any deploy. READY and the schedule hook now fire only on an actual READY, and only schedules the undeploy disabled (`disabledReason: agent-undeployed`) come back. `IAgentFactory.deployAgent`/`undeployAgent` no longer declare checked exceptions they never throw; the impossible catches and the tests that stubbed them are gone.

**Schedule fires re-check USE (workspaces).** Schedules record the creator's team subjects and admin flag at creation (`creatorTeams`, `creatorAdmin`); each agent fire asks `ResourceAccessGuard.principalMayUse(agent, creator, teams, admin)`, which honours team shares (the bare-principal form would have disabled every schedule on a team-shared agent). A refused fire is `FAILED` and the schedule disabled with `disabledReason: access-revoked`.

**Docs:** [`hitl.md`](https://docs.labs.ai/conversations-and-orchestration/hitl.md), [`scheduling.md`](https://docs.labs.ai/conversations-and-orchestration/scheduling.md) (Dream examples: no `agentConfiguration` wrapper, a schedule is required, `batchSize`/`maxUsersPerRun` are not read).

***

## LLM tool execution: cache, failures, caps, retries and dead code (2026-10-02)

**Repo:** EDDI · **Branch:** `fix/llm-tool-execution` · Review 2026-10-02 §2 #14, #20, §4.3.

**What changed**

* **Conversation-bound tools are never cached** (`ToolCacheService.isConversationBound`). Derived from the tool class — a tool object that is not a shared CDI bean is built per turn with one conversation's state — replacing the hand-kept `STATEFUL_TOOL_NAMES`. `ReadAttachmentTool` was missing from that list, so `listAttachments` in conversation B of a user returned conversation A's files for five minutes.
* **Failures are typed and never cached.** New `ToolFailureException`; the web search, web scraper, weather and PDF tools throw it for upstream failures instead of returning `"Error: …"` strings that were cached (up to 1 h for the scraper). Reflected built-ins now propagate exceptions (`ToolObjectReflector.executorFor`), and an unexpected exception reaches the model only as `Error: tool '<name>' failed with an internal error (reference <id>)` — the detail is logged.
* **jsoup ReDoS:** `extractWithSelector` refuses regex pseudo-selectors and `~=`, caps selectors at 256 characters, and parses on a bounded platform pool with a hard deadline (`eddi.tools.web-scraper.parse-threads`, `…parse-timeout-ms`). `ToolExecutionService`'s javadoc no longer claims an abandoned worker is free — a CPU-bound one holds a virtual-thread carrier.
* **Tool-call caps:** `maxToolCallsPerIteration` (20) and `maxToolCallsPerTurn` (100) on the LLM task; refused calls get a `NOT_EXECUTED` result. `maxToolIterations` is clamped to 100.
* **Token estimator:** an OpenAI-family model unknown to jtokkit (Azure deployment names, compatible endpoints) falls back to the approximate estimator instead of failing every turn with `maxContextTokens`; the estimator cache is bounded.
* **One retry layer:** provider SDK retries are off (`maxRetries = 0`) on every non-streaming builder, so a provider 500 costs `retry.maxAttempts` requests (3) instead of 9.
* **Non-streaming errors:** an ERROR turn's REST response carries a top-level `error` (`taskId`, `taskType`, `errorType`, `message`) matching the streaming `task_failed` event.
* **MCP client:** the client cache key includes `timeoutMs`.
* **Telemetry / LAZY:** cascade steps carry the OpenTelemetry context; `discover_tools` is parsed before truncation.
* **Logs:** model-controlled values in built-in tool logs are sanitized and at DEBUG.
* **Schemas:** every built-in parameter has a real `@P` description; optional parameters are `required = false`. To allow this, `quarkus.mcp.server.support-langchain4j-annotations=false` — the extension read a langchain4j `@P` value as the MCP argument *name*, and these tools were never MCP tools.
* **Dead code removed:** `EddiToolBridge` (and its ThreadLocal hand-off), the uncalled / reflection-only `AgentOrchestrator` delegators (tests now target `ToolLoopRunner`, `ToolLoopResumer`, `ToolApprovalGateSupport`, `HttpCallToolsProvider`), the `executeSingleToolCall` seams, and the `ToolCostTracker.trackToolCall(String,String)` / `ToolRateLimiter.tryAcquire(String)` overloads. The two live self-conversation guards in `ToolLoopRunner` share one helper.

Docs: [langchain.md](https://docs.labs.ai/agent-configuration/langchain.md) (caps, retry/error semantics, tool cache, web scraper, built-in schemas), [configuration-reference.md](https://docs.labs.ai/deployment-and-infrastructure/configuration-reference.md), [mcp-server.md](https://docs.labs.ai/protocols-and-integration/mcp-server.md).

**Not changed:** the MCP discovered-tool cache stays keyed per config, not per caller — discovery never carries a caller-bound or `PER_USER` credential (`authorizationHeader` sends it unauthenticated), so the tool list does not vary by caller. The resume-path self-conversation check in `ToolLoopResumer` keeps its own copy (it audits a human approval); P4 owns those lines.

***

## 🐛 fix(manager): live streams survive a token refresh, editors keep what was typed (2026-10-02)

**Repo:** EDDI (`fix/manager-streams-and-editors`) — Manager only (`ui/manager`); no Java changed.

The second of three PRs answering the Manager findings of the 2026-10-02 review (§4.10): the fixes that need no new user-facing strings. Independent of `fix/manager-ui-review` and `refactor/manager-dead-exports`. Each behavioural fix has a regression test that was mutation-checked.

### Streams and state

* **SSE token:** `BearerEventSource` accepts a header *provider*, asked again on every reconnect; the log and coordinator streams pass one. A reconnect after a token refresh used to resend the expired token, get a 401 on every attempt and stop — the live streams died roughly one token lifetime after the page was opened.
* **Logs:** a reseed fetched for the previous filter no longer merges into the new filter's view (and the unused `useRecentLogs` hook is gone from the same file).
* **`useAgent`** keeps the previous document as placeholder only for the same agent: with a blanket `keepPreviousData`, navigating from agent A to agent B showed A's configuration under B's id.
* **Operator:** Stop files the trace of what the stopped turn had already done under its answer.
* **GDPR:** an erasure invalidates every cached read it can make stale — user memories, properties, conversations (and the dashboard's recent-conversations card), user conversations, group conversations, schedules, audit and the restriction badge; the restriction lookup waits for typing to pause instead of firing per keystroke.
* **Versions:** group detail resolves the current version when the URL has none (it used to open version 1 and 409 on every save); resource detail writes the versions a cascade save created back into the URL (`replace`), so a reload or the back link no longer address stale versions.

### Editors

* **Number fields:** `parseFloat(raw) || fallback` turned a typed `0` into the fallback (`pruneStaleAfterDays: 0`, `maxWritesPerTurn: 0`). The debounced inputs moved to `debounced-inputs.tsx` (since deleted as unreferenced), parse with `Number.isFinite`, respect `min`, and **flush** a pending edit on blur and unmount instead of dropping it when a section collapses. The test that re-implemented and asserted the bug is gone.
* Review follow-ups on the inputs: `min` now clamps the fallback too (a cleared `min={1}` field never commits `0`); the field shows the value it actually committed when clamping changed it; and a `commitKey` (the agent id) binds a pending edit to the agent it was typed for — when an in-app navigation reuses the input for another agent, the edit is flushed through the previous agent's save first instead of being saved into the new one, and the field then shows the new agent's value even when both agents hold the same one. The capability attribute rows now use the same input and apply its (already debounced) edit directly — a second timer in the editor lost an edit flushed on collapse and could write back an attribute removed mid-edit; an edit for a key that is no longer there is dropped.
* Group detail: a failed current-version lookup shows a retryable error instead of loading version 1. GDPR erasure removes the erased user's inactive cache entries (invalidation alone left them to paint on the next mount) and refetches active ones. Operator Stop also drops stream frames that were already buffered.
* **Rules editor:** config keys rename through `RenamableKeyInput` (commit on blur, refuse a taken key) and "Add config" picks a free `keyN` — renaming on every keystroke merged two rows.
* **Editor registry:** `EXTENSION_TO_SLUG` gained the snippet store's real extension, the singular `ai.labs.snippet`; its test now checks every resource type's own extension instead of listing them.
* Channel targets are keyed by a stable id, so removing one no longer hands its half-typed trigger to the card that slides into its place.
* Schedule toasts carry the backend's reason; remove buttons have translated, named labels.

### Dev mode and wording

* `keycloak.init()` ran twice under StrictMode and the second call threw, so `npm run dev` with Keycloak never finished signing in; both effect runs now share one init promise.
* The Vite proxy lacked `/usermemorystore`, `/workspaces`, `/spacestore` and `/llm`; `EDDI_BACKEND_URL` points the dev proxy at another backend.
* `gate-guard.ts`, `self-guard.ts`, `tool-scopes.ts` and `ui/manager/AGENTS.md` now say the operator guards run in the Manager's approval UI only — defence in depth; an approval over REST, MCP or Slack never reaches them and the server's own check is the enforcement there. Comments only: the operator prompt, allow-list and revision are unchanged.

***

## 🐛 fix(manager): safe deletes, an in-app unsaved-changes guard, role-aware UI and the review's UI findings (2026-10-02)

**Repo:** EDDI (`fix/manager-ui-review`) — Manager only (`ui/manager`); no Java changed.

The first of three PRs answering the Manager findings of the 2026-10-02 review (§2 #7, §3.4 Manager row, §4.10). This one carries the behavioural fixes that change what the user reads, and with them every locale; `fix/manager-streams-and-editors` carries the fixes that need no new strings, and `refactor/manager-dead-exports` the dead-code removal. The three do not depend on each other. Each behavioural fix has a regression test that was mutation-checked (the fix reverted, the test seen to fail).

### Deletes are soft unless the user says otherwise

* `deleteGroup` and `deleteConnection` defaulted to `permanent=true`, the opposite of the backend. The grey **Delete Group Only** was therefore the unrecoverable one, and a permanent group delete also removes the group's standing workspace — backlog, cadences and their schedules (`RestAgentGroupStore.deleteGroup`) — while the red **Delete Group + All Agents** was the recoverable one. The Workforce card, settings page and bulk delete all hard-deleted too.
* Both API functions now default to soft. Every delete dialog (groups list, group panel, Workforce card / settings / bulk, connections list and detail) offers one unticked `PermanentDeleteOption` that names what a hard delete removes and relabels the confirm button. `deleteGroupWithMembers` applies the same choice to the group and every member agent.
* A member that cannot be deleted is no longer swallowed (`GroupMembersDeleteError`, a 404 counts as already gone). On the permanent path the group is checked against its current version first, the members go next, and the group is purged **last** — only once every member is gone — so a failed member leaves a group to retry from instead of orphaned agents and an unrecoverable group.
* Review follow-up: the sidebar stores collapsed sections by `labelKey` (positions shift when a role hides a section; old numeric state is migrated), and the command palette no longer offers a recent page the current role cannot open.

### Unsaved changes are guarded inside the app too

* `main.tsx` mounts a data router (`createBrowserRouter`, one catch-all route around the existing `<Routes>`), so `useUnsavedChangesGuard` now holds in-app navigation (links, `navigate()`, Back) with `useBlocker`, and the config editor, workflow detail, connection detail and the Workforce agent sheet render `UnsavedChangesPrompt`. Only a change of path is blocked (a save moving the page to `?version=` is not); `allowNextNavigation()` lets a deliberate navigation through.
* Config editor: a save no longer overwrites what was typed while it was in flight (the reset decision runs in an effect, not inside a state updater that moved the refs it read), and Save on invalid JSON says why and opens the JSON tab instead of doing nothing.
* Agent detail disables its sections while another version's document stands in as placeholder.

### Role-aware UI

[`lib/roles.ts`](https://github.com/labsai/EDDI/tree/main/ui/packages/app-kit/src/lib/roles.ts) maps the screens whose backend admits only some roles to the `@RolesAllowed` of the resources they call — eddi-admin for logs, coordinator, audit, secrets, quotas, orphans and GDPR; eddi-admin and eddi-editor for connections (the connection store lets an editor list and read them); eddi-admin and eddi-user for user data. The sidebar, command palette and dashboard quick actions hide what the user's role cannot open; the dashboard no longer requests coordinator status or vault health for a non-admin and says "requires admin" (also on a 401/403) instead of "Vault unavailable" / "Coordinator —"; the platform probe uses `/administration/docs` (every role) for them. With auth off, or a token carrying no EDDI role at all (roles mapped from another claim), everything stays offered and the backend decides.

### Other findings

* Chat: a failed send clears the typing indicator and shows a translated error flagged `isError` (Retry no longer matches on translated text); End Conversation reports errors and clears only the conversation it was clicked for.
* Workforce **Duplicate** linked to `/workforce/{id}?version=1/settings`; `parseIdFromLocation` strips the query. The group wizard keeps the members it created when the moderator fails, so a retry no longer creates every member agent again.
* Audit "Load more" with auto-refresh: one list deduplicated by entry id, the newest page always refreshed, the next offset taken from the rows loaded.
* Quotas: a cleared field saves `-1` (unlimited), never `0` (which blocks the tenant); text that is not a number yet blocks Save; labels are bound to their inputs.
* Approvals: a notice when the 200-entry cap of the 1:1 list is reached (the endpoint has no offset — see [`hitl.md`](https://docs.labs.ai/conversations-and-orchestration/hitl.md)).
* Errors now carry the backend's reason: group panel deletes, Workforce history delete, the orphan scan (and the purge's `409 incomplete_scan`). The coordinator's refresh selector drives both polls.
* Confirmations for deleting a space variable and a memory entry; the memory row toggle is a real button; workspace settings can leave the legacy visibility unset ("default applies") instead of storing the default's value on every save.
* Dev mode: the MSW auto-start read the pre-sign-in 401 as "backend unreachable" and served mocks.
* Hard-coded strings and two literal colours moved to i18n keys and theme tokens; all 11 locales.
* Dead code in the files this PR touches anyway: `useStartDiscussion`, `getGroupJsonSchema`, `STANCE_SUMMARY_DEFAULT_MAX_CHARS`, `RESUME_KIND_HUMAN_TURN*` and `PROPOSAL_OPEN`/`_SUPERSEDED`.

**Not done:** splitting the 36 files over 800 lines; a global `MutationCache` error fallback (it cannot see per-call `onError`, so it would double-toast every site already fixed). A soft-deleted group keeps its workspace, so its cadence schedules stay enabled and each fire fails until the group is purged or deleted permanently — a backend follow-up, not something the Manager can fix.

***

## 🐛 fix(mcp): honest tool contract — optional arguments, real defaults, isError, one role matrix with REST (2026-10-02)

**Repo:** EDDI (`fix/mcp-tool-contract`) — review 2026-10-02 §2 #4, #17, §3.4 (MCP rows), §4.5

### What changed and why

**Required-argument contract (High, live-verified).** quarkus-mcp-server 2.x makes every `@ToolArg` required unless it says `required = false`, and refuses a call that omits one (or passes `null`) with "Missing required argument". 75 of the 84 tools therefore declared *every* argument required — 235 of 244 arguments, including 100 whose own descriptions said "optional" or "default: …". `list_agents {}` failed, `chat_with_agent` could not be called without the `conversationId` it promises to create, and `setup_agent` demanded all 14 arguments. Every optional argument is now `required = false`, literal defaults are published as the schema `default` (`environment` → `production`, limits, booleans, `style` → `ROUND_TABLE`), and descriptions say what the code does. 122 arguments remain required — the identifiers, messages, bodies and verdicts a tool cannot work without.

**Defaults that lied.** `get_agent` promised "default: latest" and read version 1; it now resolves the current version, as do `read_workflow`, `read_resource` and `list_agent_resources` (which said "default: 1"). `list_conversations` without `agentVersion` lists every version and now says so. The duplicated "'production' (default), 'production', or 'test'" is gone from every tool and from `mcp-server.md`.

**Errors are tool errors.** Tools reported failures by *returning* `errorJson(…)`, which the server sends as a successful result: "Access denied", "not found" and validation failures all arrived with `isError: false`, and a missing role escaped as a JSON-RPC internal error naming `io.quarkus.security.ForbiddenException`. A new interceptor (`@McpErrorResults` → `McpErrorResultInterceptor`) rethrows an error payload as `ToolCallException` — `isError: true`, same JSON body — and maps a role refusal to `errorCode: FORBIDDEN`. The tools' return types, and the unit tests that compare their strings, are unchanged.

**`McpGroupTools`.** `create_group` with no `memberAgentIds` threw an NPE that reached the caller as `{"error":"null"}`, and an unknown `style` silently became `ROUND_TABLE`; both are now `BAD_REQUEST` (the latter lists the valid styles). The 13 tools that returned `errorJson(e.getMessage())` go through one `failure(…)`: caller mistakes (`IllegalArgumentException`, 4xx) are described, not-found is `NOT_FOUND`, anything else is logged and answered with a fixed message and `INTERNAL`.

**Role tiers (Medium, live-verified).** MCP and REST disagreed in three directions: editors could run `setup_agent`/`create_api_agent` (REST setup is admin-only), editors could *not* deploy (REST deploy admits them), and viewers could read agent configurations REST refuses them. And because a role check is a literal `hasRole`, an admin or editor without `eddi-viewer` was refused all 27 read tools. One matrix now lives in `McpRoles` — Docs, Converse (admin/editor/user + viewer, ownership-guarded), Observe (admin + viewer, for `read_audit_trail` and conversation-scoped `read_agent_logs`), Author (admin/editor), Admin, plus the unchanged HITL guard — each tier enumerating its roles, which gives `admin ⊇ editor ⊇ viewer` for the conversation tools. Observe is not Converse because the REST audit and log endpoints are admin-only: an audit entry carries the agent's system prompt and tool-call arguments, which `eddi-user` cannot read over REST, so putting those two tools in the conversation tier would have handed them to every user and editor. Deliberately narrower than REST and documented: the schedule tools and the memory writes stay admin-only, because they act on any user's data without the per-owner scoping REST applies.

**Breaking for MCP clients**, listed in the new [Upgrading from 6.5](https://docs.labs.ai/deployment-and-infrastructure/upgrading-from-6.5.md#mcp-role-tiers): a viewer-only account loses `list_agents`, `list_agent_configs`, `get_agent`, `list_team_backlog` and `list_group_templates`; an editor-only account loses `setup_agent` and `create_api_agent`; refusals arrive as `isError: true` instead of a successful result or a JSON-RPC error.

**Docs resources and dead code.** The `eddi://docs/*` resources had no role check (the docs tools and REST do); they now require the docs tier and refuse with JSON-RPC `-32005`. Neither resources nor tools name the server's docs directory any more, and `DocsService.docsDirectory()`, which existed only to name it, is removed. In `McpGroupTools`, unparseable JSON in an argument (`roleAssignments`) is described to the caller rather than answered as `INTERNAL`. `McpSetupTools`' test-only delegates (`buildPromptResponseJson`, `isLocalLlmProvider`, `getService()`) are removed; the test calls `AgentSetupService` directly.

**Platform Operator:** unchanged — it describes no MCP roles and reads `mcp-server.md` through the docs endpoint, which carries the new matrix.

**Files:** [`McpRoles.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/mcp/McpRoles.java), [`McpErrorResultInterceptor.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/mcp/McpErrorResultInterceptor.java), [`McpErrorResults.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/mcp/McpErrorResults.java), every `Mcp*Tools` class, [`McpDocResources.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/mcp/McpDocResources.java); tests [`McpToolContractTest`](https://github.com/labsai/EDDI/tree/main/src/test/java/ai/labs/eddi/engine/mcp/McpToolContractTest.java), [`McpRoleTierParityTest`](https://github.com/labsai/EDDI/tree/main/src/test/java/ai/labs/eddi/engine/mcp/McpRoleTierParityTest.java) (measures all 84 tools × 5 roles and compares each tier with the REST `@RolesAllowed` it mirrors), [`McpErrorResultInterceptorTest`](https://github.com/labsai/EDDI/tree/main/src/test/java/ai/labs/eddi/engine/mcp/McpErrorResultInterceptorTest.java); docs [`mcp-server.md`](https://docs.labs.ai/protocols-and-integration/mcp-server.md) (argument contract, role mapping), [`security.md`](https://docs.labs.ai/security-and-compliance/security.md#role-tiers), [`user-memory.md`](https://docs.labs.ai/architecture-and-concepts/user-memory.md), [`upgrading-from-6.5.md`](https://docs.labs.ai/deployment-and-infrastructure/upgrading-from-6.5.md) (new).

***

## 🐛 fix(pipeline): typed postResponse properties, one property-instruction engine (2026-10-02)

**Repo:** EDDI (`fix/pipeline-properties-parser`) — review 2026-10-02 §2 #5, §4.4

### What changed and why

* **`postResponse` property instructions stored `""` for every non-string.** `PrePostUtils` replaced any number, boolean, object or list read through `fromObjectPath` with an empty string (live: a GitHub repository's `stargazers_count` and `private` came back empty). It also ignored `override`, `toObjectPath` and the typed `value*` fields, and overwrote a property with `""` when the path resolved to nothing. Its tests asserted only `any(Property.class)`.
* **`PropertySetterTask` silently dropped `Double` and `Long`** — the types Jackson gives a JSON decimal and a whole number beyond the `int` range — and an inline `property.json` `valueFloat: 1.5` (a `Double` after Jackson) was dropped at configure time.
* **One engine.** Both now run every instruction through the new [`PropertyInstructionExecutor`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/properties/impl/PropertyInstructionExecutor.java), so `property.json` and httpcall / MCP / LLM `preRequest` / `postResponse` instructions behave identically (typed values, `override`, `toObjectPath`, `convertToObject`, typed fields, scrub-placeholder guard, `scope: secret`). The mapping of a value to a property slot lives in [`PropertyValues`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/properties/model/PropertyValues.java), also used by `ConversationProperties`, `UserMemoryEntry`, `Conversation` (a `longTerm` `Double` reloaded from the user-memory store used to come back as a string) and `MemoryCheckpoint`.
* **`Property` gains `valueLong` and `valueDouble`** (additive JSON fields; existing documents are unchanged). A `Long` that fits an `int` is stored as `valueInt`, so the type survives a MongoDB/PostgreSQL round trip; a `Double`/`BigDecimal` keeps full precision instead of being rounded to a `Float`.
* **Failures are visible.** A failing `preRequest`/`postResponse` instruction used to be one `LOGGER.error` line. It is now logged with the conversation id and recorded in the step under `propertyInstructions:errors`; the remaining instructions still run. `scope: secret` still fails closed.
* **Behaviour change:** a `postResponse` `fromObjectPath` that resolves to nothing now sets nothing (it used to store `""`), the same as `property.json`.
* `PrePostUtils.verifyHttpCode` no longer writes default lists into the shared, cached `HttpCodeValidator`.

**Docs:** [`properties.md`](https://docs.labs.ai/architecture-and-concepts/properties.md) (wrong `httpCalls.` root in both `fromObjectPath` examples, "stored exactly as found" is now true, visibility table contradicted the prose — the default is `global` without a `userMemoryConfig`), [`httpcalls.md`](https://docs.labs.ai/agent-configuration/httpcalls.md) (model table and sample brought up to date, `actions` is a list, `{userInfo.userId}`, nonexistent `stemming` correction removed, hard-coded OpenWeatherMap key replaced by a `${vault:…}` reference, broken anchors, "package"), [`architecture.md`](https://docs.labs.ai/architecture-and-concepts/architecture.md) and [`conversation-memory.md`](https://docs.labs.ai/architecture-and-concepts/conversation-memory.md) examples (the response object they read was never saved).

***

## 🔒 fix(nlp): parser steps honour parserstore documents; client quick replies mint no expressions (2026-10-02)

**Repo:** EDDI (`fix/pipeline-properties-parser`) — review 2026-10-02 §4.4 N1, N3

### What changed and why

* **N1 — a parser step referencing a `parserstore` document ran with no dictionaries.** `InputParserTask.configure` never read the step's `config.uri`, which is exactly the shape `AgentSetupService`, the MCP setup tools and the Manager's pipeline builder write. It now loads the document; the step's `config` keys override the document's, and the step's `extensions` are appended after the document's per extension point. An unreadable `uri` fails the deployment instead of running empty. The extension descriptor lists the optional `uri`.
* **N3 — a client could mint any expression.** `OutputGenerationTask` copied client-supplied `context.quickReplies` (and `quickReply` items in a client `context.output`) into the step like the agent's own, and the next turn's parser turned them into a temporary dictionary — so a client offering itself `{"value":"Approve","expressions":"approve_refund"}` got `approve_refund` parsed, and on every setup- or MCP-created agent (which forced `expressionsAsActions: true`) that became an **action**. The parser now builds the temporary dictionary from the previous step's `quickReplies:*` data, which only the agent's own quick replies get: client ones are displayed (without expressions) but never stored as data. Quick replies a `postResponse` builds are marked server-generated on their `Context` (a `@JsonIgnore` flag a client cannot set) and keep working.
* `AgentSetupService.createBehaviorConfig` no longer forces `expressionsAsActions: true`; its single rule (`inputmatcher *`) does not need it. Existing setup-created agents keep the flag in their stored rule set; N3 is closed for them by the parser change.
* The parser read the quick-reply flag under `"default"` (never written; `QuickReply` serializes `isDefault`), a quick reply without `value` threw an NPE, and `OutputGenerationTask.convertQuickRepliesConfig` dropped `isDefault`. All fixed. `OutputGenerationTask.configure` sorted the cached output set in place; it now sorts a copy.

**Docs:** [`semantic-parser.md`](https://docs.labs.ai/agent-configuration/semantic-parser.md), [`agent-config-authoring.md`](https://docs.labs.ai/agent-configuration/agent-config-authoring.md), [`output-configuration.md`](https://docs.labs.ai/agent-configuration/output-configuration.md), [`behavior-rules.md`](https://docs.labs.ai/agent-configuration/behavior-rules.md) (`appendActions`, `expressionsAsActions`, the special `empty` matcher value), [`putting-it-all-together.md`](https://docs.labs.ai/getting-started/putting-it-all-together.md) (the booking flow read `{context.*}` where the values live in properties, hard-coded `contextmatcher` values, a stray `$`, a wrong parser result, "packages"), [`extensions.md`](https://docs.labs.ai/architecture-and-concepts/extensions.md), [`output-templating.md`](https://docs.labs.ai/agent-configuration/output-templating.md) (`_count` is the 1-based index in Qute), and the rule-based reference fixture (a quick reply used the reserved `CONVERSATION_END` as an expression; a rule now ends the conversation).

***

## 🐛 fix(pipeline): config validation, shared-config mutation, deep path encoding, MCP result cap, Slack mrkdwn escaping (2026-10-02)

**Repo:** EDDI (`fix/pipeline-properties-parser`) — review 2026-10-02 §4.4 (Low/Low-Medium rows)

### What changed and why

* **Config validation.** A behavior step without `config.uri` threw a `NullPointerException` from `RulesEvaluationTask.configure`; a malformed `uri` threw `IllegalArgumentException` from `URI.create` in the behavior, httpcalls, LLM, MCP, output and parser steps. All go through the new [`ResourceUris.require`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/lifecycle/ResourceUris.java) and fail the deployment with a `WorkflowConfigurationException` naming the step.
* **Shared configuration no longer mutated at run time** (stateless-task rule): `ApiCallExecutor` defaulted `executeCallsSequentially` into the cached batch instruction; `OutputGenerationTask.configure` sorted the cached output set; `PrePostUtils.verifyHttpCode` wrote default lists into the cached validator (first entry).
* **Deep path encoding.** `ApiCallExecutor.encodePathValue` passed a map or list nested beyond its depth bound of 10 into the request path unencoded; past the bound a container is now replaced by an empty one (fail closed). A string at any depth is still encoded.
* **MCP rule-call results are capped.** `McpCallsTask` stored a rule-triggered tool result in conversation memory whatever its size. New `mcpCalls[].maxResponseSizeInBytes` (default 2 MB, like httpcalls): a longer result is truncated with a warning and stored as text. Documented in [`mcp-client.md`](https://docs.labs.ai/protocols-and-integration/mcp-client.md).
* **Slack: model and member output is mrkdwn-escaped.** Agent replies (`SlackEventHandler`), HITL continuations (`SlackHitlResumeObserver`) and every group-discussion message (`SlackGroupDiscussionListener`, escaped once in its `postSafe`) were posted raw, so `<!channel>` / `<!here>` in an LLM reply pinged the channel. New [`SlackMrkdwn.escape`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/integrations/slack/SlackMrkdwn.java) replaces the two duplicated per-field helpers; it escapes `&`, `<` and `>` everywhere (Slack renders the entities inside code too) except a line-leading `>`, the blockquote marker. EDDI's own notices keep their intended `<@U…>` mentions. Not verified against a live Slack workspace (none available) — unit-level only.
* **Dead/wasteful rule code.** `RulesEvaluator` is immutable (the no-arg constructor and setters were used only by a test). `Dependency` deep-cloned the referenced rules on every evaluation for a reason that did not hold (its comment said rules live in conversation memory). `dynamicvaluematcher`, `sizematcher` and `capabilityMatch` converted the whole memory to template data once per condition per turn; a rule-set evaluation now converts it once ([`TemplateDataScope`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/rules/impl/conditions/TemplateDataScope.java), a `ScopedValue`).

***

## 🐛 fix(pipeline): review follow-ups — wide inline ints, non-JSON paths, plain decimals, MCP cut, Slack approver (2026-10-02)

**Repo:** EDDI (`fix/pipeline-properties-parser`) — independent review of the three commits above

* **Inline `valueInt` wrapped around.** `PropertySetterTask` narrowed an inline `valueInt` with `intValue()`, so `3000000000` became `-1294967296`; a whole number beyond the `int` range now goes to `valueLong`.
* **A non-JSON `fromObjectPath` value failed the turn.** The unified executor threw for a value no property slot holds (a live output item, `conversationLog`) — in `property.json` that had always been a silent no-op, so such an agent would have started failing every turn. It now sets nothing and logs a warning on both paths.
* **Decimals rendered in E-notation.** With typed values, `{properties.price}` of `12500000.5` printed `1.25000005E7` and `0.00025` printed `2.5E-4`. `RuntimeTemplateEngineFactory` now renders `Double`/`Float` in plain digits where JavaScript does (`1e-7 <= |x| < 1e21`); see [`properties.md`](https://docs.labs.ai/architecture-and-concepts/properties.md#reading-the-different-value-types).
* **Legacy `value` migration** now maps a `Long` beyond the `int` range to `valueLong` (it was left unmigrated) and a `Double` to `valueDouble` (it went to `valueFloat`, read back at seven digits).
* **MCP result cap** no longer ends a truncated result on the first half of a surrogate pair.
* **Slack HITL summary**: a non-Slack `decidedBy` (an IdP principal name) is escaped, and a `slack:` id is only turned into a `<@…>` mention when it is a Slack user id.

### Review follow-up (PR #944, CodeRabbit)

* **Slack messages are split after escaping.** Escaping can lengthen a message, and the group-discussion and HITL-resume paths posted one unbounded `text` that Slack truncates past 40,000 characters. All three Slack paths (agent replies, group discussion, HITL continuation) now share `SlackMrkdwn.escapeInChunks`: messages of at most 3,900 characters, preferably at a line break, never inside an entity or a surrogate pair. The HITL decision summary, with its intentional approver mention, stays at the head of the first message.
* **A failed Slack chunk ends the message, and one message is at most 20 chunks.** All three paths stop at the first chunk Slack does not accept (the rest would read as a complete message without its beginning); the event handler's `postMessage` now reports delivery. `escapeInChunks` escapes only the prefix that can be posted, searches for cut points inside the current chunk only (a newline-free 2 MB reply made the old whole-prefix search quadratic), and cuts a text that needs more than `SlackMrkdwn.MAX_MESSAGES` (20) messages with a `[message truncated]` marker.
* **Line-break cuts no longer waste message capacity.** A line break is still the preferred cut, but when cutting there would leave more text than the remaining messages can hold, the chunk is filled to the length limit (at an entity- and surrogate-safe point) instead — 25 lines of 2,500 characters used to take one message each and be truncated at message 20 although they fit.
* **Chunking truncates only when no safe partition exists.** Each chunk is filled to its last safe boundary (greedy, which needs the fewest chunks because entities and surrogate pairs are indivisible); a line break is taken instead only when the rest still fits the remaining chunks packed that way. The earlier length estimate could still truncate `"x "` plus nine `&amp;` in 3 chunks of 24. The truncation marker's re-cut no longer leaves half an entity when the last chunk starts with one. A randomized property test checks exact reassembly, safe boundaries and truncation-only-when-infeasible over 3,000 inputs.
* **Inline `valueInt` / `valueLong` are converted exactly.** `Number.longValue()` truncated `3.7` to `3`, saturated `1e20` and kept only the low bits of a larger `BigInteger`; such a value is now refused at configure time with a message naming the property (`3.0` is still `3`).
* Docs: `conversation-memory.md` no longer suggests a `postResponse` instruction cleans a saved response up (it adds a property; `maxResponseSizeInBytes` is what bounds the response); the booking request body in `putting-it-all-together.md` was double-escaped and sent invalid JSON; link texts in `extensions.md` and `httpcalls.md` name their target instead of "here".

***

## 🗄️ fix(datastore): one id contract, no MongoDB on PostgreSQL, parser-safe orphan purge (2026-10-02)

**Repo:** EDDI (`fix/postgres-parity`)

### Why

Running the same 170-check live suite against a MongoDB and a PostgreSQL-only deployment (review of 2026-10-02, §2 #10/#11, §3.1, §4.7) left six checks that only PostgreSQL failed, and a handful of places where the two backends answered the same request differently:

* **Unknown or malformed ids answered 500 on PostgreSQL** — `GET /rulestore/rulesets/xyz?version=1`, an id of dashes, a 24-hex ObjectId, `GET /agents/xyz`, `GET /agents/000000000000000000000000`, `POST /agents/xyz`, `GET /groups/{id}/conversations/------------------`. The id was bound into `?::uuid`, PostgreSQL raised SQLSTATE 22P02, and the store wrapped it in a `RuntimeException`. MongoDB answered 404 on some of them and **400** (or 500 on a POST) on others, because `new ObjectId(id)` throws `IllegalArgumentException` — including for a UUID, a perfectly good id on the other backend. The one place that tolerated a bad id on PostgreSQL did so by matching the English text "invalid input syntax for type uuid", which changes with `lc_messages`.
* **The retention sweep was held for ever on PostgreSQL.** `V6RenameMigration.holdsRetention()` asked MongoDB whether the EDDI 5 `bots` collection held documents, also when `eddi.datastore.type=postgres`. Its `MongoDatabase` is a lazy client proxy, so the call created a MongoClient against `mongodb://mongodb:27017`, waited 30 s, and the fail-safe catch answered "hold": no ended conversation was ever deleted, and the log claimed the database came from EDDI 5.
* **User-memory search** matched PostgreSQL's `value::text` — the value's JSON text — so `true` found every boolean, a number matched by its digits and the field names of an object value matched; MongoDB's `$regex` matched string values only. Nothing capped the result, and an LLM tool calls it.
* **Sorted listings put documents without the sort field first on PostgreSQL** (`DESC` is `NULLS FIRST` there) and last on MongoDB.
* **The orphan purge deleted dictionaries that parser documents reference.** It collected references from agent → workflow → workflow step only; `extensions.dictionaries[n].config.uri` of an `ai.labs.parser` document — the shape `/parserstore/parsers` documents — was never read, so such a dictionary was listed as an orphan and erased, leaving the parser naming a dictionary that no longer exists. None of the 43 safety tests modelled a parser document.

### What changed

* **One id contract, both backends: an id the backend cannot store is an unknown id.** Every lookup answers "not found", every write or delete of it is a no-op, and no query is sent, so REST answers 404 exactly as for a well-formed id that does not exist.
  * `PostgresIds` (new): `isStorableId` (the canonical 8-4-4-4-12 UUID, either case) and `isInvalidTextRepresentation` (SQLSTATE `22P02`, replacing the English-message match in `PostgresResourceStorage.getCurrentVersion`).
  * `PostgresResourceStorage`: `read`, `readMany` (skips the bad id, keeps the rest), `readHistory`, `readHistoryLatest`, `getCurrentVersion`, `remove`, `removeAllPermanently`.
  * `PostgresConversationMemoryStore` and the MongoDB `ConversationMemoryStore`: `loadConversationMemorySnapshot`, `getConversationState`, `getRevision`, `compareAndSetState`, `setConversationState`, `setConversationEndReason`, `clearHitlBookmark`, `deleteConversationMemorySnapshot`.
  * `MongoResourceStorage`: `readMany`, `remove`, `removeAllPermanently` (the reads were already guarded).
  * `MongoUserMemoryStore`: `findEntryById`, `deleteEntry` (the PostgreSQL store keys entries by text, so it already answered "not found").
  * `RestUtilities.isValidId` no longer accepts dashes anywhere: an id segment is hex (18+ characters) or a canonical UUID. Eighteen dashes used to count as an id.
  * Group conversations, attachments, audit, schedules and user memory on PostgreSQL either go through `PostgresResourceStorage` or key by text; none binds an id into a `uuid` cast any more.
  * Found by the new parity test, fixed with it: `PostgresConversationMemoryStore.loadConversationMemorySnapshot` was the one read that did not create the table first, so on a fresh database a GET of an unknown conversation failed with "relation does not exist" (a 500). The schema check is now lock-free once the table exists. And `MongoResourceStorage.findResources` with no filter groups sent `$and: []`, which MongoDB rejects; it now means "everything", as on PostgreSQL.
* **No MongoDB on a PostgreSQL deployment.** `V6RenameMigration` and `V6QuteMigration` read `eddi.datastore.type` (exact match, as `DataStoreProducers` does) and on `postgres` are inert: not pending, never holding retention, never touching their `MongoDatabase`. EDDI 5 ran on MongoDB only. `PropertiesMigrationService` and `GridFsIndexInitializer` already had this guard; with these two, a PostgreSQL boot creates no MongoClient at all.
* **User-memory search** (`IUserMemoryStore.filterEntries`) has one meaning on both backends: every term in the key, in a string value, or in a string element of an array value — numbers, booleans and object values are not searched — newest first, at most `IUserMemoryStore.MAX_FILTER_RESULTS` (200). The `forgetFact` tool used this search to find the agent's own entry by exact key; it now reads the user's entries instead, so the cap cannot hide an older entry. Documented in [`user-memory.md`](https://docs.labs.ai/architecture-and-concepts/user-memory.md#searchmemory).
* **MCP `delete_user_memory`** answers an error for an id that names no entry, as the REST endpoint answers 404. It reported `"status": "deleted"` — for any unknown id on both backends, and, with the id contract above, for a malformed id on MongoDB that used to fail.
* **Sort order:** `PostgresResourceStorage.findResources` sorts `DESC NULLS LAST`. So the sorted page is still read off an index, the field indexes are now built in that order (`idx_resources_fdesc_<field>`, `(collection_name, (data ->> field) DESC NULLS LAST)`); the old ascending `idx_resources_field_<field>` is dropped once its replacement exists **and is valid**. On a database an earlier release built, the replacement is not built at boot: a plain `CREATE INDEX` holds a SHARE lock on the shared `resources` table — one descriptor per conversation, nine hinted descriptor fields — and would stop every write on every instance until all were built. `PostgresFieldIndexSwaps` builds them with `CREATE INDEX CONCURRENTLY` on a background thread once boot has settled (as the `pg_trgm` indexes are built), one advisory lock per index so two booting instances never build the same one, repairs an index an interrupted build left INVALID, and drops the old index `CONCURRENTLY` only after that. Until then the old index still serves equality filters; a refused build (no privilege) logs one warning and keeps it. A fresh database builds the new index at boot.
* **Orphan purge:** `RestOrphanAdmin` reads every parser document's current version and the parser version each workflow step pins, and counts their `extensions.dictionaries[n].config.uri` as references. The pre-delete re-check asks parser documents too, and fails closed. An unreadable parser document makes the scan incomplete, so the purge refuses (409). A parser that is itself an orphan keeps its dictionaries until it is gone; the next purge reaches them. A step pinning a parser with an unparsable version (`?version=abc`) names no readable version: it is skipped with a warning, not counted as an unreadable document, so it cannot hold every purge at 409.
* **Dead code removed** (no reference in `src/main`): `datastore/mongo/DescriptorStore` (legacy, with the `eq(deleted, includeDeleted)` bug), `datastore/mongo/ResourceFilter`, `datastore/mongo/HistorizedResourceStore`, `datastore/mongo/ModifiableHistorizedResourceStore`, `datastore/mongo/AbstractMongoResourceStore`, `IResourceFilter.readResources` (the interface is now only the namespace of the filter types) and `StringUtilities.convertToSearchString`, with their tests. The live `datastore.HistorizedResourceStore` / `ModifiableHistorizedResourceStore` stay.
* **Docs:** [`configuration-reference.md`](https://docs.labs.ai/deployment-and-infrastructure/configuration-reference.md) — `eddi.datastore.type` says it is matched exactly, needs the `postgres` profile and the datasource settings, and that a PostgreSQL deployment opens no MongoDB connection; `eddi.migration.v6-rename.retention-confirmed` says a PostgreSQL deployment is never held.

### Tests

* `MalformedIdContractTest` (new): the same malformed and foreign ids through both resource storages and both conversation stores — "not found", and no statement or query sent. `MongoUserMemoryStoreTest` does the same for user-memory entry ids.
* `DatastoreParityTest` (new, Testcontainers MongoDB + PostgreSQL): the id contract, the sort position of a document without the sort field, the user-memory search semantics and its cap — each case run against both real databases.
* `V6MigrationsOnPostgresTest` (new) and `RestConversationStoreTest.runsOnPostgresWithoutMongo`: on PostgreSQL the sweep deletes as configured and the migration never touches an unreachable MongoDB.
* `RestOrphanAdminSafetyTest.ParserDocumentReferences` (7 new): parser-document references in the scan, at the current and at the pinned version, the re-check, and failing closed.
* `PostgresResourceStorageTest`, `RestUtilitiesTest`: the SQLSTATE match (a German message still counts, an English one with another SQLSTATE does not), the index order, that an upgraded database builds nothing blocking at boot, `isValidId`.
* `PostgresFieldIndexSwapsTest` (new) and `PostgresResourceStorageContainerTest.FieldIndexReplacement` (real PostgreSQL): the concurrent swap, its lock, its repair of an INVALID index, and that the old index survives a refused or invalid build.
* `UserMemoryToolScopingTest.forgetFactDoesNotDependOnTheCappedSearch`, `McpMemoryToolsBranchCoverageTest.unknownEntryIsNotReportedAsDeleted`.

***

## 🔒 fix(rag): every knowledge base gets a store of its own, and `openai` embeddings honour `baseUrl` (2026-10-02)

**Repo:** EDDI (`fix/rag-kb-isolation`)

### What changed and why

Two High findings of the 6.5.0 review, both reproduced live before the fix.

**Cross-knowledge-base poisoning.** `POST /ragstore/rags/{ownKb}/ingest?kbId=<other KB's name>` checked EDIT on the knowledge base in the path and then wrote into the store the `kbId` named — another knowledge base's; with `replace=true` it deleted that one's documents. Stores were keyed by the knowledge base's *name* (cache key, default pgvector table / Atlas collection / ES index / Qdrant and Chroma collection), names are not unique (`duplicateRag` copies them), and retrieval read by name with no filter, so two knowledge bases with one name shared one store, and an explicit `table`/`collectionName`/`indexName` could point at anyone's.

* The store is now addressed by the RAG configuration's **id**, everywhere: `EmbeddingStoreFactory.getOrCreate(ragConfigId, config)` replaces `getOrCreate(config, kbId)`, and ingestion, ingestion sources (`IngestionPipeline`) and retrieval (`RagContextProvider`, which takes the id from the workflow step's URI) all pass it.
* **`kbId` no longer selects anything.** It is accepted only when it names the path's knowledge base (its id, or its name — the old default); anything else is a `400` and nothing is ingested.
* **Two layouts, chosen by the new `storeNamespace` field** ([`KnowledgeBaseStorage`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/rag/model/KnowledgeBaseStorage.java)): `"id"` — default location `eddi_kbid_<id>`, chunks tagged `kbId=<id>`, retrieval filtered on it — for every knowledge base created, duplicated or imported from now on; absent/`"name"` — the 6.5.0 layout, reproduced byte for byte per store type, so an upgraded knowledge base keeps reading the pgvector table it was written to. Retrieval is not filtered there, because 6.5.0 chunks carry no id.
* **Write-time rules** ([`KnowledgeBaseStorageGuard`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/rag/rest/KnowledgeBaseStorageGuard.java), used by `RestRagStore` create/update/duplicate and by the import's create path): a new KB gets `"id"` (`"name"` on create is a 400); an update without the field keeps the stored one; `"id"` → `"name"` is refused; renaming a 6.5.0 KB moves it to `"id"` (in 6.5.0 a rename already moved it to a new store — the one named after the new name, possibly someone else's); an explicit location may not start with `eddi_kb` and may only equal another KB's if the caller may EDIT that one too. Source ingestion state is now cleared when the *location* changes rather than on every rename, so renaming an `"id"` KB no longer forces a full re-crawl.
* Replace-by-document-name deletes only chunks tagged with the ingesting KB's own `kbId`, and the pipeline tags every crawled/uploaded chunk with it.

**`openai` embeddings ignored `baseUrl`.** `buildOpenAi` passed only `model` and `apiKey`, so a knowledge base configured for a private OpenAI-compatible endpoint sent its documents to api.openai.com. Every provider was audited against its langchain4j builder ([`EmbeddingParameters`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/rag/model/EmbeddingParameters.java)): `openai` now honours `baseUrl`, `timeout` (ms), `organizationId`, `projectId`, `dimensions`, `maxRetries`; `mistral`, `cohere` and `gemini` honour `baseUrl` and `timeout`; Azure `endpoint`, Vertex `endpoint`, Bedrock `dimensions` and `maxRetries` where the builder has it. `modelName` is an alias of `model` everywhere (a conflict is a 400). An endpoint-like parameter a provider cannot honour is refused at save time and again at build time, never silently dropped; other unknown parameters are logged. Vault references in embedding parameters resolve as before (verified live).

Docs: `rag.md` — new "Knowledge base isolation" section with the upgrade/migration path, per-provider parameter table, `kbId` semantics, the Atlas `metadata.kbId` filter-field requirement, and the non-upload body limit (about 27.7 MB with default attachment settings, not 25 MB). The Platform Operator's knowledge-base section explains layouts, the empty-after-rename case and the endpoint rule (revision bump). The Manager's RAG editor suggests `baseUrl` for `openai`.

### Design decisions

* **Mode field rather than a data migration.** Rewriting stored configs or moving vectors at startup would touch customer data stores EDDI does not own (external pgvector, Atlas, ES). An absent field means "as 6.5.0", which keeps every existing deployment working with no action; isolation for the old layout is one save away.
* **Filter at retrieval only in the `"id"` layout.** Filtering legacy KBs would hide every chunk 6.5.0 wrote.
* **Collision check by store type + name, not host.** Raw connection strings cannot be compared reliably (`localhost` vs `127.0.0.1`, vault references); a false positive only asks for EDIT on both.

**Files:** [`KnowledgeBaseStorage.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/rag/model/KnowledgeBaseStorage.java), [`KnowledgeBaseStorageGuard.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/rag/rest/KnowledgeBaseStorageGuard.java), [`EmbeddingParameters.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/rag/model/EmbeddingParameters.java), [`EmbeddingStoreFactory.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/EmbeddingStoreFactory.java), [`EmbeddingModelFactory.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/EmbeddingModelFactory.java), [`RagContextProvider.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/llm/impl/RagContextProvider.java), [`RagIngestionService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/rag/RagIngestionService.java), [`RestRagIngestion.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/rag/rest/RestRagIngestion.java), [`RestRagStore.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/configs/rag/rest/RestRagStore.java), [`IngestionPipeline.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/modules/ingestion/IngestionPipeline.java), [`RestImportService.java`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/backup/impl/RestImportService.java), [`rag.md`](https://docs.labs.ai/agent-configuration/rag.md).

***

## ♻️ refactor(manager): remove dead exports, make vacuous tests and MSW fixtures real (2026-10-02)

**Repo:** EDDI (`refactor/manager-dead-exports`) — Manager only (`ui/manager`); no behaviour change.

The third of three PRs answering the Manager findings of the 2026-10-02 review (§4.10, "Quality"). Independent of `fix/manager-ui-review` and `fix/manager-streams-and-editors`.

* **Dead exports removed** — nothing in `src/`, `e2e/` or the docs called them (checked across the whole repository): the unused hooks `useAuditEntryCount`, `useExportAgent`, `useRawConversation`, `useConversationStepCount`, `useAgentJsonSchema`, `useWorkflowJsonSchema`, `useQuotas`, `useUpdateResource`, `useSchedule`, `useToolRateLimit`, `useCacheStats`, `useToolHistory`, `useSearchMemories`, `useCountMemories`; the API functions and types behind only them (`getEntryCount`, `exportAgent`, `exportAndDownloadAgent`, `getRawConversationLog`, `ConversationMemorySnapshot`, `getDescriptors`, `listQuotas`, `getAgentJsonSchema`, `getWorkflowJsonSchema`, `getToolRateLimit`, `getCacheStats`, `getToolHistory`, `getToolCosts` and their types, `getTrigger`, `searchMemories`, `getMemoriesByCategory`, `getMemoryByKey`, `upsertMemory`, `countMemories`); `createAuthEventSource` (the SSE parser inventory in `sse-utils.ts` now lists only the readers that exist); unused constants (`TOUR_CHAPTER_ORDER`, `SLACK_PLATFORM_KEYS`, three `WORKSPACE_*` caps kept as a comment, `RESOURCE_VISIBILITIES`, `AUTH_REFERENCE_EXAMPLES`) and the `AddAgentCard` component. Their tests and MSW handlers went with them, and the `count` audit query key that only the removed hook used.
* **Vacuous tests made real:** `resource-detail-core` error tests assert the error state (they only checked that the back link rendered, which it does either way); `use-save-and-deploy` stubs the routes the hook actually calls and asserts the deploy and status reads (its handlers sat on `/deploymentstore/…`, which the hook never requests).
* **MSW fixtures backend-shaped:** the generic store handlers answer descriptors with the store's real `eddi://` extension, epoch dates and `deleted: false`, and a config GET with the store's empty configuration in its Java model's shape — not `{ type, config: {} }`, which no store returns.

The other group-API dead constants (`STANCE_SUMMARY_DEFAULT_MAX_CHARS`, `RESUME_KIND_*`, `PROPOSAL_*`, `getGroupJsonSchema`), `useStartDiscussion` and `useRecentLogs` are removed in the two fix PRs, whose files they share.

***

## 📈 fix(metrics): static files no longer exhaust the HTTP metrics URI tags (2026-10-02)

**Repo:** EDDI (`fix/http-metrics-uri-cardinality`)

### The bug

`http.server.requests` tags each request with its URI, and Micrometer registers at most `quarkus.micrometer.binder.http-server.max-uri-tags` distinct values. After that, every new URI is denied and gets no request metrics, with a single WARN to show for it. REST endpoints are tagged by template, but Quarkus tags a static file by its literal path, and the image ships 816 content-hashed Manager chunks under `/assets` plus 65 fonts. A few minutes of clicking through the Manager on the 6.5.0 release candidate used up the cap of 200. Every API endpoint first called after that went unmeasured.

The cap was also too small without the assets: the API has 265 distinct paths (the Manager's OpenAPI snapshot). The value came in with an unrelated commit in 2022 and had never been sized.

### What changed

* [`application.properties`](https://github.com/labsai/EDDI/tree/main/src/main/resources/application.properties): `match-patterns` folds `/assets/*`, `/fonts/*`, `/scripts/*` and `/img/*` into one tag per directory (`/assets/{file}` …). `max-uri-tags` goes from 200 to 500.
* `HttpMetricsUriTagsConfigTest` (new) parses the patterns the way Quarkus 3.40 does (first `=`, trimmed, whole-path `matches()`, read from the bytecode of `HttpBinderConfiguration` and `RequestMetricInfo`). It checks that representative asset, font, script and image paths fold, that REST and UI-shell paths are left alone, and that the cap stays at least 100 above the path count in `ui/manager/src/test/mocks/openapi-operations.json`. As the API grows into the headroom, this test fails before production does.
* [`metrics.md`](https://docs.labs.ai/deployment-and-infrastructure/metrics.md) explains the `uri` values and the cap.

### Verified

On the CI image of 1150bc1e1, with the two settings passed as environment variables, I requested all 881 static files the jar ships and then the UI shells and an API call. That produced 13 distinct `uri` tags and no cap warning. Without the settings, a handful of Manager pages produced 95.

***

## 🖱️ fix(manager): the Workforce onboarding page, confirm dialogs and the command palette scroll again (2026-10-02)

**Repo:** EDDI (`fix/workforce-onboarding-scroll`)

### What was broken

* **The Workforce landing page could not be scrolled** (reported against 6.5.0). `workforce-main` clips its content on purpose: every Workforce page brings its own scroll container (the scroll contract in `workforce-scroll-contract.test.tsx`). `WorkforceDashboard` wrapped its populated view in one, but returned the empty state, `<OnboardingHero />`, bare. The hero is 1406px tall, so on a 1280×640 window everything below the how-it-works cards was out of reach, including the templates a first-time user needs to create a task force. The contract test missed it twice: its mock always returns task forces, and an empty render was accepted as "cannot overflow". The loading and error states had no scroller either.
* **`AlertDialog`, the shared confirm dialog, had no height cap.** It is fixed and centred with a transform, so content taller than the window ran off both edges with nothing able to scroll it. In a 375px landscape-phone window the Undeploy prompt measured −40px to 416px: Close above the screen, Cancel and Undeploy cut off at the bottom. Every confirm dialog shares the primitive; the ones with extra content (undeploy, agent delete, conversations, groups, operator upgrade) hit it first.
* **The command palette's list was a fixed 360px** below a 15% offset. With the search row, footer and borders (86px, measured), the palette ran past the bottom of any window under about 525px tall: its footer at 310px in a 300px window, where scrolling the list cannot reach it.

### What changed

* [`workforce-dashboard.tsx`](https://github.com/labsai/EDDI/tree/main/ui/workforce/src/pages/workforce/workforce-dashboard.tsx): the empty, loading and error states are each a `flex-1 min-h-0 overflow-y-auto` scroller, like the populated view.
* [`alert-dialog.tsx`](https://github.com/labsai/EDDI/tree/main/ui/packages/app-kit/src/components/ui/alert-dialog.tsx): `max-h-[calc(100dvh-2rem)] overflow-y-auto`, the same cap `AccessibleDialog` already had.
* [`command-palette.tsx`](https://github.com/labsai/EDDI/tree/main/ui/manager/src/components/shared/command-palette.tsx): the list is capped at `min(360px, calc(85dvh - 6rem))`. The dialog starts at 15%, so 85dvh remain for all of it, and 6rem covers the 86px of fixed parts with a 10px margin. Measured in Chromium: the palette fits at 200px (30–189px), 300px (45–289px) and 800px (unchanged at 360px). A first attempt at `min(360px, 60dvh)` ignored the footer and still overflowed below about 370px; CodeRabbit caught it in review.
* Tests: the scroll contract gains a case that renders the dashboard with **zero** task forces and requires the onboarding hero (new `data-testid="workforce-onboarding-hero"`) to sit inside a scroller. A second case holds the request pending and requires the same of the loading skeleton (`workforce-dashboard-skeleton`); the page table never holds that state still. A new `alert-dialog.test.tsx` pins the dialog's cap and scroller, and the palette test pins its list cap. The last two were added at CodeRabbit's suggestion. Each was mutation-checked: removing the fix fails it.

### How the rest was ruled out

A detector run in the browser against the 6.5.0 image, over all 48 Manager and Workforce routes at 1280×640, 375×812 and 1280×480, with seeded data (two agents, a group, a conversation). For every visible element below the fold, it checks whether some scroll container, or the document, can bring it into view. The only page-level failure was the onboarding hero, and the detector caught it as a positive control (65 unreachable elements under `#workforce-main`). Dialogs and sheets were checked by reading the overlay primitives: `AccessibleDialog`, the agent performance sheet, the mobile sidebar and the version diff already cap and scroll. Both fixes were then confirmed live: the patched Manager ran against the same backend, the hero scrolled to its last template, and the Undeploy dialog fit the 375px window and scrolled to its buttons.

Not covered: states the seed data does not produce, such as a Workforce board with a long discussion or analytics with data. Those render inside scrollers the contract test already requires.

***

## 🔖 chore(release): after 6.5.0 (2026-10-01)

**Repo:** EDDI (`chore/post-release-6.5.0`, opened by `post-release.yml` after the release pipeline published the image)

### What

* Release pointers: 6.4.0 → 6.5.0 (Helm chart 2.3.0 → 2.4.0)
* Build version (pom.xml): 6.5.0 → 6.6.0

Generated by `python scripts/bump-version.py post-release 6.5.0`. Files:

* `pom.xml`
* `docs/build-reproducibility.md`
* `docs/developer-quickstart.md`
* `docs/kubernetes.md`
* `docs/redhat-openshift.md`
* `docs/release-signing.md`
* `k8s/base/kustomization.yaml`
* `k8s/quickstart.yaml`
* `helm/eddi/Chart.yaml`
* `src/test/java/ai/labs/eddi/deploy/DeploymentManifestsTest.java`

***

## 🐛 fix(conversations): filtered listings page exactly, and a listing page no longer loads whole conversations (2026-10-01)

**Repo:** EDDI (`fix/conversation-listing-pagination`)

### The bug

`GET /conversationstore/conversations` treated `index` as a page of *descriptors*, filtered the rows in Java afterwards, and kept adding whole descriptor pages until it had `limit` rows. With any filter — `agentId`, `agentVersion`, `conversationState`, `viewState`, or the owner filter every non-admin gets — that went wrong two ways:

* **Overshoot.** The size was checked only after a whole descriptor page had been added, so a page could hold up to `2*limit - 1` rows. On a rehearsal of real 5.5.1 data, `agentId=…&limit=100` returned 189 rows and `limit=20` returned 39.
* **Overlap.** `index=1` started at descriptor page 1, which `index=0` had often already consumed. 90 of the 90 rows on `index=1` were on `index=0` too; paging to an empty page saw 279 rows for 189 conversations. Not a 6.5 regression: 6.4 showed 1,499 rows for 852 conversations.

### The fix

[`RestConversationStore.readConversationDescriptors`](https://github.com/labsai/EDDI/tree/main/src/main/java/ai/labs/eddi/engine/memory/rest/RestConversationStore.java):

* **`index` is a page of results.** The listing reads descriptor pages from the start, counts off the `index*limit` rows that pass every filter, and stops at `limit` exactly — mid-page if need be.
* **The descriptor-field filters are pushed into the query**, for MongoDB and PostgreSQL alike, so the descriptors read are mostly results: the agent (`agentResource` names it, *or names no agent* — a descriptor an earlier 6.x rewrote without its agent gets it from the conversation), `viewState` (equality), and for a non-admin the owner (`userId` is the caller, *or no owner is recorded* — a pre-v5.1.6 conversation). The owner is not pushed when an agent is named, because a reviewer of that agent may list conversations they do not own. Each pushed group admits a superset of what the per-row check accepts; that check still runs on every row and stays the authority.
* **What stays in Java** is what only the conversation knows: its state (the descriptor's copy is not maintained), whether it still exists (orphans, still counted in `eddi.conversations.listing.orphaned_descriptors`), and the owner or agent of a legacy descriptor.
* **A ceiling for every caller:** `index * limit` above 10,000 is refused with a 400 before any query. A page counts off every match before it, and an admin — or anyone when authorization is disabled — never reaches the owner-scan budget, so `index=2000000000` would otherwise have read the whole descriptor collection. (Raised in review.) A deep page also reads the rows it counts off in batches sized to that work, up to 1,000: each batch makes the database walk past the batches before it again, so fixed batches of 100 made a deep page quadratic. The owner budget is checked once per batch, never mid-batch: which rows of a batch are counted off — and so exempt from the budget — is known only after its summary read, and stopping mid-batch let the next batch start after rows nobody had examined (with batches larger than the budget, rows 500–599 of a deep page went missing).
* **The owner-scan budget** (`MAX_OWNER_SCAN`, 500) counts the descriptors a page examines, minus the matches it counts off for earlier pages: those are the caller's own conversations, and charging them would put a caller's older conversations out of reach. The reviewer exception is unchanged.

### Performance

Every listed row used to be a full conversation-memory load — one round trip per row, deserializing every step, property and output — to read six small fields; the agent's display name was another read per row. Counting off earlier pages would have multiplied that.

* New `IConversationMemoryStore.loadListingSummaries(ids)`: one projected query per descriptor page. MongoDB: `$in` with a projection that counts the steps server-side (`$size`). PostgreSQL: `id = ANY(?)`, the state/agent columns plus three JSONB fields and `jsonb_array_length`. A page now costs two small queries per descriptor page and loads no conversation in full. A row whose descriptor records another owner is still rejected from the descriptor alone, before any conversation read; a legacy descriptor that records no owner is decided from its conversation's summary.
* Page 0 reads descriptors in pages of `limit`; a later page, which first counts off the rows of the pages before it, reads them in batches of 100 to 1,000 sized to that work, so `index=50&limit=20` costs 4 queries (two batches of 1,000, each with its summary read) rather than 102.
* An agent's display name is read once per agent version per listing, and only for returned rows.
* If a page's summary read fails, the page's ids are read one at a time, so a conversation the store cannot read costs only its own row (logged, sanitized, and not counted as an orphan) — as a failed per-row load did before.

### Store plumbing

* `DescriptorStore.readDescriptorsRestricted(…, List<QueryFilters>)` takes any number of AND-ed filter groups; the two-group overload delegates to it.
* `IConversationDescriptorStore.readDescriptors(…, restrictions)` exposes it for conversations.

### Tests

* `RestConversationStoreTest.FilteredPagination`: a filtered page stops at `limit`; consecutive filtered pages list every match once, in order; an orphan before the page does not shift it; a state filter pages through matching states; a page reads one summary batch per descriptor page and never loads a conversation in full; an agent name is read once; the agent/view-state groups and their patterns; the state is not pushed down.
* `RestConversationStoreOwnershipTest`: an owner's pages are exact and disjoint with foreign rows interleaved; page 5 of 650 own conversations is reachable (the budget is not spent on counted-off rows); the owner group is pushed for a non-admin, not for an agent listing, not for an admin.
* `MongoConversationMemoryStoreTest` / `PostgresConversationMemoryStoreTest` (real databases): a summary equals the summary of the full load, including step count and a narrow `ENDED` write; unknown and malformed ids have no entry.
* `V6RenameMigrationConversationDescriptorsTest` already ran the listing over a real MongoDB and covers the agent pushdown, including the "descriptor names no agent" fallback; `PostgresResourceStorageContainerTest` now checks the same agent group on a real PostgreSQL.
* An unreadable conversation costs only its row and is not counted as an orphan.
* Mutation-checked: 12 mutants (no stop at `limit`, no counting-off, budget charged for counted-off rows, nothing pushed down, owner pushed for agent listings, no agent-name cache, orphans kept, scan batch ignored, and four in the two `loadListingSummaries` implementations), all killed.

### Docs

The listing's paging contract is on `IRestConversationStore.readConversationDescriptors`; [`upgrading-from-5x.md`](https://docs.labs.ai/deployment-and-infrastructure/upgrading-from-5x.md) says to page until empty and that earlier versions over-counted.

***

## ⚡ perf(search): descriptor search is a literal substring test, not a `.*text.*` regex (2026-10-01)

**Repo:** EDDI (`fix/conversation-listing-pagination`)

Every descriptor listing's search box — conversations, agents, every config type — sent the escaped term as the regex `.*<text>.*`, ORed over five fields (`userId`, `name`, `agentName`, `description`, `resource`). An unanchored regex already matches anywhere, so the wrapping changed no result and only added backtracking; PostgreSQL then ran it as `~`, which costs more per row than a literal test.

* New filter value `IResourceFilter.Contains(text)`: the field contains the text as a literal, case-sensitive substring; an absent field does not match. `DescriptorStore` builds the search from it (`StringUtilities.searchText` keeps the old quoted-term handling).
* **MongoDB** renders it as a bare escaped regex — no `.*` wrapping.
* **PostgreSQL** renders it as `LIKE '%…%' ESCAPE '\'` with `%`, `_` and `\` escaped. `LIKE` rather than `strpos()` (which measures the same) because a `pg_trgm` GIN index serves `LIKE` and never `strpos()`.

Measured on 300k descriptors (250k conversations) in throwaway `mongo:7` and `postgres:16-alpine` containers, back to back on an otherwise idle machine, medians of 5 (MongoDB) and 7 (PostgreSQL) runs:

| Query                  | MongoDB before → after   | PostgreSQL before → after                |
| ---------------------- | ------------------------ | ---------------------------------------- |
| selective search (hit) | 276 → 121 ms (2.3×)      | 443 → 295 ms, cached plan 453 → 349 ms   |
| search with no hit     | 405 → 411 ms (no change) | 491 → 407 ms, cached plan 1,253 → 914 ms |

The PostgreSQL figures are for one prepared statement executed repeatedly, as the JDBC driver runs it: the first five executions are planned for their value, later ones use PostgreSQL's cached generic plan. A search that matches nothing still examines every descriptor on both databases, and on a long-running PostgreSQL that cached plan makes it take about a second — before and after this change.

Results are unchanged: same rows, same case sensitivity, same quoted-term handling. Real-database tests on both backends (`MongoContainsFilterTest`, `PostgresResourceStorageContainerTest`) assert the same rows for literal metacharacters (`+`, `(`, `%`, `_`, `\`, `'`), case, an absent field and an empty search.

PostgreSQL search is indexed too — see the next entry. MongoDB has no index that serves a substring search; a text index would change matching to whole words.

### The "nothing matched, list everything" fallback keeps its meaning

A search that matches no conversation lists everything instead. That was decided from the first unfiltered descriptor page; with the listing's filters now pushed into the query, an empty first page no longer means the search matched nothing — "Billing" within agent A comes back empty when it matches agent B's conversations. A one-row probe without the pushed-down filters now decides it, so that search lists nothing (as before) instead of falling back to all of agent A.

### Verified against a running EDDI on both databases

The packaged jar, run against fresh `mongo:7` and `postgres:16-alpine` containers and driven only through its REST API (two database edits aside: orphaning three conversations and marking four `SEEN`). 67 conversations on two agents, some ended:

| Run                                                                                                                                                                                                                                                                    | MongoDB | PostgreSQL |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | ---------- |
| Paging at limits 3/7/10/20 for every filter (none, agent, agent+version, state, agent+state, view state), row content, orphans, search (by id, metacharacters, `%`/`_`, quoted, case, inside a filter), the orphan counter                                             | 293/293 | 293/293    |
| With Keycloak: two `eddi-user`s and an admin, 50 conversations, one legacy descriptor without an owner — each user pages through exactly their own (the legacy one by its conversation's owner), the admin through all, searches never leak or fall back across owners | 121/121 | 121/121    |

The same unauthenticated checks against `labsai/eddi:latest` (6.4.0, before this fix) fail 98 times — agent A's 45 conversations came back as 88 rows — so they do detect the bug.

Mutation-checked: nine more mutants in the search and fallback code (LIKE wildcards unescaped, ILIKE, MongoDB text unescaped, back to a regex string, quotes kept, fallback always / never, a failed batch dropping the page, an unreadable row counted as an orphan), all killed.

***

## ⚡ perf(postgres): index the descriptor search with pg\_trgm, and plan it per execution (2026-10-01)

**Repo:** EDDI (`fix/conversation-listing-pagination`)

A search on PostgreSQL scanned every descriptor. On a long-running instance it was slower still: the JDBC driver server-prepares a statement it sees repeatedly, PostgreSQL then reuses one generic plan, and a search that matched nothing took about a second on 300k descriptors.

* **`PostgresSubstringSearchIndexes`**: GIN `gin_trgm_ops` indexes on the five searched fields, partial to the `descriptors` collection. `DescriptorStore` asks for them through the new optional `ISubstringSearchIndexing`, which only the PostgreSQL storage implements. The indexes are a fixed catalogue: every index name and `CREATE`/`DROP` statement is a compile-time constant, so no runtime string reaches the DDL (which takes no bind parameters); a field or collection outside the catalogue is not indexed. (CodeQL flagged the first version, which built the DDL from validated names.)
* **Built in the background**, 15 s after boot, with `CREATE INDEX CONCURRENTLY`: a large deployment neither waits at startup nor stops writing (300k descriptors took \~8 s for all five). One builder across replicas via an advisory lock. An index an interrupted build left INVALID — which `IF NOT EXISTS` would skip for ever while it still costs every write — is dropped and rebuilt.
* **Retries transient failures.** The first live boot deadlocked: the concurrent build ran into the other storages' schema setup and PostgreSQL aborted it, leaving an index INVALID. The build now waits for boot to settle and retries a deadlock, serialization failure, lock timeout or cancellation (after 30 s, 2 min, 10 min); a refused privilege is reported once and not retried.
* **Planned per execution, once the indexes are ready.** The search statement is sent with a prepare threshold of 0, so PostgreSQL plans it for its actual pattern and can use the indexes. Only that statement, and only when every index is valid: without the indexes, per-execution planning made a common term \~170× slower than the cached plan, which happens to stop early on the date index. Until they are ready, the search asks the catalogue at most once a minute (one caller, atomically), on the connection it already holds — a second checkout per search could stall concurrent searches in an exhausted pool (raised in review).
* **`eddi.datastore.postgres.substring-search-index`** (default `true`) turns it off. If `CREATE EXTENSION pg_trgm` is refused, a warning is logged and search runs unindexed, as before.

Measured live: the packaged jar on PostgreSQL 16 with 300k conversation descriptors and memories, through `GET /conversationstore/conversations?filter=…`, 120 requests per term, median of the last 60 (after the connection pool's plan caching settled), identical rows with the feature off and on:

| Search                      | off (as before) | on    |
| --------------------------- | --------------- | ----- |
| matches a few conversations | 393 ms          | 39 ms |
| matches nothing             | 375 ms          | 23 ms |
| matches many (common term)  | 14 ms           | 18 ms |

Cost: each descriptor write maintains five GIN indexes — measured at the database, a descriptor rewrite (one per conversation turn) went from \~60 µs to 130–200 µs — and \~50 MB per 300k descriptors.

Verified live on that boot: the build waited, repaired the INVALID index the deadlocked run had left, built the rest and reported ready 29 s after start, with EDDI serving from 4 s. The 293-check listing script passed on PostgreSQL with the feature on (indexes ready) and on MongoDB, where nothing changes.

Tests: `PostgresSubstringSearchIndexesTest` (real PostgreSQL: the index definitions, a planned search uses the index, an INVALID index is rebuilt, another builder's lock is respected), `PostgresSubstringSearchIndexesRetryTest` (a deadlock is retried to success, a privilege failure is not, retries are bounded, the SQLState classification), and `PostgresResourceStorageTest` (planned per execution only for a substring search with ready indexes; the build starts only when enabled). Mutation-checked: ten mutants — never planned per execution, planned before ready, nothing transient, no repair, lock ignored, privilege retried, a field outside the catalogue indexed, any collection indexed, readiness checked on a second connection, no re-check throttle — all killed.

***

## 🐛 fix: conversation listings leave out descriptors whose conversation is gone (2026-10-01)

**Repo:** EDDI (`fix/6.5-release-readiness`)

A rehearsal on real 5.5.1 data found that 1,106 of 1,301 conversation descriptors had no conversation memory left. They were already orphans on 5.x, never marked deleted. Once the v6 rename gave them an `agentResource`, `GET /conversationstore/conversations?agentId=` returned them as conversations that cannot be opened: 852 entries for an agent with 189 conversations. It also logged one WARN per orphan per page, about 51,000 lines for seven listings.

`RestConversationStore`:

* `populateDataToDescriptor` now reports a missing snapshot, and the listing skips that descriptor instead of returning it.
* The per-orphan message is DEBUG. A listing that skipped any counts them once in the new metric `eddi.conversations.listing.orphaned_descriptors`.
* A snapshot that exists but names an agent whose descriptor is gone is still listed, as before.
* The counter is in [`metrics.md`](https://docs.labs.ai/deployment-and-infrastructure/metrics.md) and charted as a second series on the Full Metrics Reference panel for listings, beside `owner_scan_exhausted`.

The test that pinned the old behaviour ("descriptor with null snapshot should still be added") is replaced by a by-agent case: an orphan and a live conversation for the same agent, where only the live one is listed. Mutation-checked: listing the orphan anyway, or not counting it, fails it.

[`upgrading-from-5x.md`](https://docs.labs.ai/deployment-and-infrastructure/upgrading-from-5x.md) §6 says to compare the by-agent listing with `conversationmemories`, and names the metric.

The idle sweep's message now reads "has been idle for N days, longer than the maximum idle time of M days". Before, it said the conversation was "N days older than" the limit, which gave the idle time as if it were the excess over the limit.

***

## 📝 docs: upgrade guides cover the 6.5 fixes; stale Open WebUI and RAG claims; two names the reference guard wrongly refused (2026-10-01)

**Repo:** EDDI (`fix/6.5-release-readiness`)

### Upgrade guides

[`upgrading-from-5x.md`](https://docs.labs.ai/deployment-and-infrastructure/upgrading-from-5x.md):

* a configuration row and a section on the idle sweep, which first runs five minutes after boot. From 6.5 a limit below 1 disables idle-ending; before 6.5, `-1` ended every conversation;
* the conversation-descriptor rename;
* the new reporting of unconvertible templates (one ERROR, then one WARN per boot);
* the by-agent listing as a check;
* a precise description of which legacy properties are held back.

[`upgrading-from-6.4.md`](https://docs.labs.ai/deployment-and-infrastructure/upgrading-from-6.4.md):

* the two one-time catch-ups a 6.4-migrated database gets (step shape, descriptor fields and their backfill), with count queries to confirm them;
* the idle-limit `-1` change;
* the NEGOTIATION fix, which changes the outcome of stored groups: a real verdict instead of a summary recorded as one.

### Stale claims corrected

* [`open-webui-integration.md`](https://docs.labs.ai/protocols-and-integration/open-webui-integration.md) and `docker-compose.openwebui.yml` said the `/v1` adapter "is not in any published image yet". It has shipped since 6.4.0; the demo builds from the working tree so it runs the checkout's adapter.
* [`rag.md`](https://docs.labs.ai/agent-configuration/rag.md) called `web` "the only type implemented", above its own `upload` section.
* A Manager comment in `ui/manager/src/lib/hitl-config.ts` said the backend runs the generic synthesis prompt for a NEGOTIATION group missing its arbitration prompt. Since 6.5 the backend restores the prompt itself, with the same matching rule.

### `ConfigurationReferenceCoverageTest`

The guard refused two real settings in any document:

* `EDDI_BIND`, the Compose variable that sets the address EDDI's ports are published on. It's now in the non-property list beside `EDDI_PORT`.
* `EDDI_CHAT_FRAME_ANCESTORS`. Its property is read through a `${...}` expression rather than by Java, so the guard's scan of the code couldn't see it. The environment names of the properties in `DECLARED_BUT_UNREAD` now count as valid.

The README now names `EDDI_BIND` directly, where it had to describe the variable's location instead. The 6.4 guide names `EDDI_CHAT_FRAME_ANCESTORS`. Both changes were mutation-checked: removing either one fails `documentedEnvironmentVariablesMapToRealProperties` on those docs.

***
