Greptile review on #887 (slice 3, merged):
- BuiltinEngine.Query bounds Limit across the whole result, not per scope
it is given. renderMemory passed one Limit for all of subject.Scopes()
combined, so an early scope (agent-user, queried first) could exhaust
the whole budget and starve later, wider scopes. Now queries each scope
separately, each capped at memoryRecordsPerScope.
- memoryBlockByteCap was checked against each line's raw size, but
BuildSystemPrompt's {{xml .Memory}} escapes &/</> afterward, expanding
a byte up to fivefold. The cap is now measured against the escaped
size (escapeXML, extracted from prompt.go's template func) while the
block itself still accumulates raw lines, since the template escapes
once on render -- escaping here too would double-escape it.
Wires the durable-memory engine into the chat turn: prepareTurn resolves a
per-channel Subject (BotUser as AgentID, TurnRunnerConfig.UserIdentity for
the user), runs a scope-only Query over Subject.Scopes(), and renders the
result into a new <memory purpose="durable_context" trust="data"> block
between <tools> and <env>, following the same untrusted-data framing as
those two blocks. The read is synchronous, total, and never surfaces an
error: a nil engine, a failing Query, or a panicking provider all degrade to
no memory block (recovered in gateway.renderMemory).
UserIdentity is supplied per channel by the composition
(userIdentityResolver in internal/app/archied): telegram and email resolve
their native SenderID, the dashboard ("web") and webhook resolve nothing, so
a webhook's route-path SenderID can never become a user identity and the
dashboard's shared bearer token can never impersonate a person.
Fixes the composition-ordering bug that left every turn runner holding a nil
memory engine: setupMemoryAll now runs before setupGateways in main.go, and
before setupGatewayChat in gateway.go's startGatewayRuntime, so
boot.memoryStore() has a live engine at every turn-runner construction site.
Named constants bound the read: memoryRecordsPerScope per scope, and
memoryBlockByteCap on the rendered block, which drops (and logs) trailing
records rather than truncating one mid-line.