Repository navigation
feat(memory): ADR-012 Phase 1 — system_exchanges + DM conversational frame - #288
Conversation
…frame
Implements ADR-012 Phase 1: system-driven exchange records as a typed
section on the AgentMemory envelope, three platform-side triggers that
write to it, the read-only enforcement at the agent tool surface, and
(folded in via §9 after the FakeSam ↔ Tarik smoke test) an inline DM
conversational frame on chat.mention payloads.
## Schema (§1, §5)
- `AgentMemoryEnvelope.sections.system_exchanges` typed sub-document with
`entries: SystemExchangeEntry[]`, hard-coded `visibility: 'private'`
enforced via single-valued enum, `updatedAt` + `byteSize`.
- New top-level `AgentMemory.revision` + `lastSeenRevision` (default 0).
The revision is the monotone counter consumed by Phase 2's memoryDigest.
- `SYSTEM_EXCHANGE_KINDS` whitelist + `SYSTEM_EXCHANGE_TAKEAWAY_MAX = 280`
+ `SYSTEM_EXCHANGE_ENTRY_CAP = 50` + `AGENT_WRITABLE_SECTIONS` allow-list,
all exported for cross-module reuse.
## Service (§1, §4, §8 invariant 8a)
- `agentMemoryService.appendSystemExchange()` — single atomic Mongo update
using `$push + $position:0 + $slice:50 + $inc:revision + $currentDate`.
Concurrent calls serialize at the doc level. Carve-out: does NOT clear
`lastSyncKey`/`lastSyncAt` (ADR-003 invariant 8a — system writes are
exempt because drivers don't promote `system_exchanges`).
- `truncateTakeaway()` — pure helper, head-truncates with single `…` suffix
guaranteed never to exceed the schema cap.
- `isAgentWritableSection()` — allow-list test for the agent tool surface.
## Triggers (§4)
New `backend/services/systemExchangeTriggers.ts`:
- `recordAgentDmConclusion` — fires on NO_REPLY in agent-dm pod. Writes
to BOTH peers' envelopes (peers list excludes self). Takeaway derives
from the sender's preceding non-NO_REPLY message via PG, head-
truncated to 280 chars.
- `recordAgentDmLoopTrip` — fires when the bot-loop guard returns. Both
peers get a literal "8 consecutive bot turns within 30 min — guard
tripped" entry.
- `recordTaskCompleted` — fires on tasks/:taskId/complete. Only the
assignee gets an entry; takeaway is `<title> → <prUrl|status>`.
All three are fire-and-forget — triggered alongside the parent operation,
errors logged not propagated.
Wired in:
- agentMessageService.postMessage silent_or_empty early-return →
maybeRecordAgentDmConclusion
- agentMentionService.enqueueDmEvent bot-loop-guard return →
recordAgentDmLoopTrip
- tasksApi /:taskId/complete success →
recordTaskCompleted
## Read-only enforcement (§1)
agentsRuntime PUT /memory and POST /memory/sync return **403** with
`reason: 'system_exchanges_is_read_only'` when the section name appears
in the payload. validateSectionsPayload now returns a tagged error so
the route can map shape errors to 400 and access errors to 403.
## §9 DM conversational frame
Folded into Phase 1 after the FakeSam ↔ Tarik smoke (verified autonomous
a2a DM round-trip) showed Tarik composing broadcast-style "has anyone
seen…" replies inside a 1:1 DM. The platform already shipped `dmKind` as
a structured payload field but the LLM deprioritized it.
agentMentionService.enqueueDmEvent now prepends an inline narrative cue
to `payload.content` based on dmKind:
agent-agent: "[1:1 agent-DM with @<peer> (<peerDisplay>) — talk
directly to them, not a broadcast room. Reply only when
your message materially advances the work; return
NO_REPLY when the exchange reaches a natural conclusion.
Surface anything shareable to a team pod via
commonly_post_message there.]"
user-agent: "[1:1 DM with @<peer> (<peerDisplay>, human) — they are
asking you directly. Reply to every new message;
responsiveness matters even when there's little to add.]"
Peer label resolution mirrors agentIdentityService.resolveAgentDisplayLabel
(botMetadata.displayName → identity-bearing instanceId → username) so
recipients see "@FakeSam (FakeSam)" not "@FakeSam (openclaw)".
The cue is part of `content`, so every CAP-compliant runtime sees it
through the existing `event.payload.content` path — no extension change
needed.
## Tests
- backend/__tests__/unit/services/agentMemoryService.systemExchanges.test.ts
(new, 13 tests): pure helpers, append ordering, cap eviction at 50,
peer-isolation, invariant 8a (system writes don't clear
lastSyncKey/lastSyncAt), schema rejection of non-private visibility +
unknown kinds, default revision/lastSeenRevision.
- backend/__tests__/service/agent-memory-envelope.test.js (4 new tests):
403 on PUT /memory + POST /memory/sync to system_exchanges, GET
surfaces appended entries, agent writes to long_term don't clobber
system_exchanges siblings.
## Deferred to next phases (per the ADR)
- Phase 2: AgentEvent.memoryRevisionAtDelivery field, fetch-time atomic
status-claim, idempotent acknowledge, memoryDigest computation. Not
in this PR.
- Phase 3: PLATFORM_SOUL_FOOTER + AGENT_RUNTIME.md updates.
- Phase 4: Per-runtime adoption of memoryDigest reads (openclaw
extension, webhook SDK, claude-code shim). Each parallelizable.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
samxu01
left a comment
There was a problem hiding this comment.
ADR-012 Phase 1 — review
Solid Phase 1 land — the schema-level read-only enforcement, the atomic $push + $position:0 + $slice + $inc shape, the carve-out from invariant 8 (preserving lastSyncKey/lastSyncAt), and the test coverage on cap eviction + revision monotonicity all match the ADR. The 403-with-tagged-reason for system_exchanges writes is a nice touch over a generic 400.
Things to address before merge
- Hot-path cost on
postMessageearly-return (agentMessageService.ts:789): the trigger doesPod.findById+User.findfor every sanitize-empty post, including the common heartbeat-NO_REPLY case in non-DM pods. Cheap projection check would gate this. - Duplicated NO_REPLY stripping (systemExchangeTriggers.ts:109): a second copy of
sanitizeAgentContent's regex is now in scope. Drift risk; reuse the static helper. senderHandledoesn't filter'default'(agentMentionService.ts:745): inline DM cue will render@default (DisplayName)for any agent on the literal'default'instanceId. The siblingsenderDisplaychain right above already filters this; mirror it.agentNameresolution usesbotMetadata.agentName(systemExchangeTriggers.ts:61–64): the CLAUDE.md DM-label rule warns this is the runtime, not the identity, for OpenClaw agents. The (agentName,instanceId) tuple still uniques in practice, but worth pinning toresolveAgentDisplayLabelsemantics so a future change can't collapse two peers.
Worth considering
- Same-takeaway-both-peers (systemExchangeTriggers.ts:170): the listener's record reads as if they spoke. Either prefix
"@<peer> said:"or split into two kinds. - Limit=30 PG scan (systemExchangeTriggers.ts:95): an active dm can push the prior substantive turn past the window. Filter PG by
user_iddirectly, or paginate. byteSizepermanently 0 (AgentMemory.ts:50): drop until Phase 2's digest builder needs it, or maintain it on push. Currently a column that lies-by-omission.- DM frame is event-only (agentMentionService.ts:749): future poll/replay surfaces will see un-framed content. Either document or move framing into
AgentEventService.enqueue.
Inline comments cover details. None of these are blockers — most are smell-level; the hot-path cost and the agentName-vs-runtime confusion are the two I'd want a response on before merge.
Generated by Claude Code
| // agent-dm, both peers get a system_exchanges entry whose takeaway is | ||
| // the SENDER's preceding non-NO_REPLY message. Fire-and-forget — never | ||
| // delays the silent return; failures are swallowed inside the helper. | ||
| void AgentMessageService.maybeRecordAgentDmConclusion({ |
There was a problem hiding this comment.
This trigger fires on every sanitize-empty postMessage call, not just agent-dms — recordAgentDmConclusion only checks podType === 'agent-dm' after a Pod.findById + User.find round-trip. For team pods / agent-room / agent-admin where bots commonly emit pure NO_REPLY heartbeats, that's two extra Mongo reads per silent post on a hot path. Worth gating with a cheap pod.type check (or passing pod.type from the caller — at this point in postMessage we haven't loaded the pod yet, but we do know the route called agentRuntime.postMessage after agentRuntimeAuth, and we could attach pod-type during a single shared lookup later in this function and short-circuit the trigger when not agent-dm).
At minimum, add a quick Pod.findById(podId).select('type') projection in the trigger before doing the full member resolution.
Generated by Claude Code
| // Skip pure NO_REPLY rows (matches sanitizeAgentContent's logic without | ||
| // round-tripping the regex). A row that's NO_REPLY-only collapses to | ||
| // empty after stripping the token. | ||
| const stripped = trimmed.replace(/\bNO_REPLY\b/g, '').trim(); |
There was a problem hiding this comment.
Drift risk: this re-implements AgentMessageService.sanitizeAgentContent's NO_REPLY stripping (/\bNO_REPLY\b/g) inline. If sanitize logic ever changes (e.g. adds a NO_RESPONSE alias, handles fenced-NO_REPLY, etc.) this path silently disagrees and starts surfacing non-substantive content as takeaways.
Either import and call AgentMessageService.sanitizeAgentContent here, or extract a shared isPureNoReply(s: string): boolean helper. The comment ("matches sanitizeAgentContent's logic without round-tripping the regex") acknowledges the duplication — making it a referenced helper costs one import and removes the future-drift footgun.
Generated by Claude Code
| // Limit: 30 — the NO_REPLY post itself is typically the last row, and we | ||
| // want the last substantive turn from the sender. 30 covers ~10 back-and- | ||
| // forths without scanning the whole pod. | ||
| const recent = await PGMessage.findByPodId(podId, 30); |
There was a problem hiding this comment.
limit: 30 is fine in a quiet 1:1 DM, but agent-DMs can interleave with other agents' fan-out (e.g. a commonly_open_dm initiated mid-stream, the speaker @-mentioned in the same pod, etc.) and 10–15 turns of back-and-forth where the silent agent's last substantive message is older than 30 rows back. When that happens we silently fall through to the 'agent-dm concluded (no prior content captured)' literal — losing the only data ADR-012 §4 promised to capture.
Two cheap improvements:
- Filter the PG query by
user_id = senderUserIdinstead of fetching 30 rows and post-filtering — that gets you the last N from this sender directly. - If you keep the current shape, bump the limit to ~100 or paginate until a match is found.
Generated by Claude Code
| // Write to BOTH peers. Each peer's `peers` field lists the OTHER agents. | ||
| const writes = agents.map((a) => { | ||
| const peers = agents | ||
| .filter((p) => !(p.agentName === a.agentName && p.instanceId === a.instanceId)) | ||
| .map((p) => p.instanceId); | ||
| // From sender's perspective: takeaway describes what THEY just said and concluded. | ||
| // From recipient's perspective: takeaway describes what the other agent said | ||
| // before going silent. v1 records the same takeaway both ways — the kind | ||
| // ('agent-dm-conclusion') + peers list disambiguate role on read. | ||
| return appendSystemExchange({ | ||
| agentName: a.agentName, | ||
| instanceId: a.instanceId, |
There was a problem hiding this comment.
Recording the same takeaway in both peers' envelopes is going to read confusingly later. From the listener's POV, an entry of kind agent-dm-conclusion whose takeaway is "shipped the auth patch" looks like they said it; the comment acknowledges this depends on the reader correlating peers[] to figure out role.
Two lower-cost fixes for v1 that don't require multi-turn condensation:
- Prefix the listener's takeaway with
"@<peer> said: "(peer resolved via thepeers[]you already compute) so role is in-band. - Or split into two kinds (
agent-dm-conclusion-spoken/agent-dm-conclusion-heard) and let the digest serializer render them differently.
Either avoids a future "why does my memory say I shipped X when I didn't?" bug when an agent regresses to reading takeaway as first-person.
Generated by Claude Code
| || sender?.username | ||
| || username | ||
| || 'peer').trim(); | ||
| const senderHandle = senderMeta.instanceId?.trim() || sender?.username || username || 'peer'; |
There was a problem hiding this comment.
senderHandle doesn't filter instanceId === 'default', so for any agent whose botMetadata.instanceId is the literal 'default' (which is the convention everywhere else in the codebase for unclaimed identity) the cue renders as @default (FakeSam) — a meaningless handle.
The senderDisplay chain three lines above already filters instanceId !== 'default'; mirror the same logic here:
const senderHandle = (senderMeta.instanceId && senderMeta.instanceId !== 'default'
? senderMeta.instanceId
: sender?.username || username || 'peer').trim();Also worth pulling this and senderDisplay through agentIdentityService.resolveAgentDisplayLabel (which the CLAUDE.md DM display-label rule mandates as the single source of truth) rather than re-implementing the chain inline — would prevent drift if the resolution rules change again.
Generated by Claude Code
| entries: ISystemExchangeEntry[]; // most recent first; cap at 50 (ADR-012 §5) | ||
| visibility: 'private'; // hard-coded; widening is closed | ||
| updatedAt: Date; | ||
| byteSize: number; |
There was a problem hiding this comment.
byteSize is declared on the section + schema but never written to (appendSystemExchange explicitly calls out that it leaves it at 0 and "recompute[s] lazily when the digest builder serializes"). Right now nothing reads it either — it's a permanently-zero column.
Either drop the field for Phase 1 and re-add it when the digest builder lands in Phase 2 (cleaner — no risk of a reader trusting it), or wire appendSystemExchange to maintain it via $set (the cost objection in the comment is overstated for a single-doc update with the new entry's length already in hand). Carrying a field that's permanently lying-by-omission invites a Phase 2 author to read it without recomputing.
Generated by Claude Code
| const dmFrame = dmKind === 'agent-agent' | ||
| ? `[1:1 agent-DM with @${senderHandle} (${senderDisplay}) — talk directly to them, not a broadcast room. Reply only when your message materially advances the work; return NO_REPLY when the exchange reaches a natural conclusion. Surface anything shareable to a team pod via commonly_post_message there.]` | ||
| : `[1:1 DM with @${senderHandle} (${senderDisplay}, human) — they are asking you directly. Reply to every new message; responsiveness matters even when there's little to add.]`; | ||
| const framedContent = `${dmFrame}\n\n${content}`; |
There was a problem hiding this comment.
A subtle persistence asymmetry: the chat.mention event payload now carries the framed content, but the message persisted to PG (and what humans see in the chat UI, what findPreviousNonSilentMessage will later read for agent-dm-conclusion takeaway derivation) is the un-framed content. Good — that's the right call.
But this means the cue is only delivered through this one event-enqueue path. If a different driver later picks up the same DM via a different surface (e.g. a webhook re-delivery, a re-enqueue after a reconnect, a poll endpoint), it'll see un-framed content and fall back to the structured dmKind field — which §9 of ADR-012 explicitly says was insufficient. Worth a comment here noting the cue is event-only and any future polling/re-delivery surface needs to re-apply it (or moving the framing into AgentEventService.enqueue itself so it's a single chokepoint).
Generated by Claude Code
| return { agentName: String(agentName).toLowerCase(), instanceId }; | ||
| }) | ||
| .filter((a) => a.agentName); | ||
|
|
There was a problem hiding this comment.
agentName: u.botMetadata?.agentName || u.username || '' — for OpenClaw-driven agents, the CLAUDE.md DM-label rule explicitly warns that botMetadata.agentName is the runtime ('openclaw'), not the identity. Using it here means two openclaw agents in an agent-dm both resolve to agentName: 'openclaw', which the senderKey equality test in recordAgentDmConclusion will then collapse into a single member and short-circuit the "sender isn't a recognized agent member" guard incorrectly. Same risk in recordTaskCompleted where the assignee is matched against a.agentName.
If the intent is "stable identity per agent in this pod," prefer instanceId (or the resolveAgentDisplayLabel chain) as the discriminator and either drop agentName or qualify it with instanceId. The current shape works in practice today only because each openclaw instance happens to have a unique instanceId, and the equality test happens to use the agentName|instanceId tuple — but that's an accident worth pinning down with a comment if not changing the code.
Generated by Claude Code
- TypeScript: skip system_exchanges in stampSectionsForWrite + mergePatchSections (validateSectionsPayload already rejects upstream; this is defense-in-depth + lets the IMemorySection branch type-narrow). Use top-level User import in systemExchangeTriggers to drop the lazy require()-with-generic that triggered TS2347. - Hot-path gate: podIsAgentDm pre-flight projection check on recordAgentDmConclusion / recordAgentDmLoopTrip — non-DM postMessage NO_REPLY no longer pays User.find round-trip per heartbeat. - Reuse sanitizeAgentContent: findPreviousNonSilentMessage lazy-requires AgentMessageService.sanitizeAgentContent instead of re-implementing the NO_REPLY regex; future drift in sanitize stays in sync automatically. - senderHandle filters instanceId === 'default' to mirror senderDisplay, so an agent on the literal 'default' instanceId no longer renders as "@default (DisplayName)" in the inline DM cue. - PG window filtered by user_id at SQL: avoids the noisy-DM scenario where 30 turns of cross-talk push the sender's prior substantive turn outside the scan window. Limit dropped to 20 since the WHERE clause prunes. - Listener takeaway prefixed with "@<peer>:" so an agent-dm-conclusion entry on the listener's envelope reads as "what the other side said" rather than as if they spoke. Speaker still gets the verbatim takeaway. - Drop ISystemExchangesSection.byteSize for Phase 1 — appendSystemExchange doesn't maintain it under concurrent $push and no Phase 1 reader consumes it. Phase 2's digest builder can recompute from entries. - Document the DM conversational frame as event-only delivery: future poll/replay surfaces must re-apply or move framing into AgentEventService.enqueue. - CodeQL hardening: typeof guards on podId before mongoose.isValidObjectId on all three triggers; identity comment on resolveAgentMembers (the (agentName, instanceId) tuple is the discriminator for OpenClaw peers, agentName alone collapses to runtime). CI: backend tsc:check + backend build both clean. Unit + integration tests both green (17/17 + 46/46).
…ack-gate (#293) Closes the read-and-write loop on the memory layer. Builds on Phase 1 (PR #288) and the §10 amendment. Three additions land in one PR: - New `cycles[]` section (§10.1): heartbeat-cadence agent journal, agent-writable, cap 40 / ≤500 chars / hard-private. Mirrors system_exchanges shape with inverted read/write roles. Whole-array overwrite returns 403 + cycles_append_only. - Broader event payload injection (§10.2): list() now mutates-on-claim (status-gated findOneAndUpdate per candidate), captures memoryRevisionAtDelivery from a single AgentMemory read, and spreads a four-field digest bundle into the returned payload — memoryDigest (system_exchanges delta), cyclesDigest (last 5), longTermDigest (head ≤800 chars), recentDailyDigest (last 2 within 7 days, ≤400 chars each). Each sub-field is independently emit-gated. - Inline HEARTBEAT cue (§10.3): ~80-token narrative directive prepended to scheduler heartbeat payload.content instructing the agent to extract one takeaway per cycle and append to cycles[]. Same lesson as the §9 DM frame — narrative wins over structured metadata. Lifecycle change: AgentEvent.status now `pending → delivered → acked`. `delivered` is intermediate (claimed, awaiting explicit ack). The status-gated acknowledge rewrite + $max-bumped lastSeenRevision make first-ack monotone and dup-ack a noop. memoryRevisionAtDelivery is captured on the doc at claim time so the bump survives the fetch→ack window without trusting the client. Tests: 32 cycles + digest unit (new file), 9 event-service unit (6 new), 6 cycles integration (new). 32+9+52 = 93 green locally; CI clean across Test & Coverage, E2E, Service Tests, Analyze. Rate-limit hardening: phase4RateLimit applied to PUT /memory and POST /memory/sync (matches /pods/:podId/messages from PR #290). CodeQL js/missing-rate-limiting still flags those routes as a false-positive (the middleware IS applied identically to the cleared route), accepted per PR #290 precedent — not a merge blocker.
Summary
Implements ADR-012 Phase 1: system-driven exchange records as a typed section on the AgentMemory envelope, three platform-side triggers that write to it, read-only enforcement at the agent tool surface, and (folded in via §9 after the live a2a smoke test) an inline DM conversational frame on chat.mention payloads.
What's in this PR
Schema (§1, §5)
AgentMemoryEnvelope.sections.system_exchanges— typed sub-document, hard-codedvisibility: 'private'.AgentMemory.revision+lastSeenRevision(default 0) — monotone counter for Phase 2's memoryDigest.SYSTEM_EXCHANGE_TAKEAWAY_MAX = 280,SYSTEM_EXCHANGE_ENTRY_CAP = 50.Service (§1, §4, §8 invariant 8a)
appendSystemExchange()— single atomic$push + $position:0 + $slice:50 + $inc:revision + $currentDate. Carve-out: does NOT clearlastSyncKey/lastSyncAt.truncateTakeaway()— head-truncates with…suffix, schema-cap-safe.isAgentWritableSection()— allow-list for the agent tool surface.Triggers (§4) —
backend/services/systemExchangeTriggers.tsrecordAgentDmConclusion— fires onNO_REPLYin agent-dm. Writes to BOTH peers; takeaway = sender's preceding non-NO_REPLY message, head-truncated.recordAgentDmLoopTrip— fires when bot-loop guard returns. Both peers get a literal entry.recordTaskCompleted— fires on tasks complete. Assignee only; takeaway =<title> → <prUrl|status>.All three are fire-and-forget, errors logged not propagated.
Read-only enforcement (§1)
PUT
/memoryand POST/memory/syncreturn 403 withreason: 'system_exchanges_is_read_only'when the section name appears in the payload.§9 DM conversational frame
Smoke test (FakeSam ↔ Tarik, 2026-05-04) showed Tarik composing broadcast-style "has anyone seen…" replies in a 1:1 DM. The platform shipped
dmKindas a structured payload field but the LLM deprioritized it.enqueueDmEventnow prepends an inline narrative cue topayload.contentbased ondmKind:agent-agent: "[1:1 agent-DM with @<peer> (<display>) — talk directly... return NO_REPLY when the exchange reaches a natural conclusion. Surface shareable results to a team pod.]"user-agent: "[1:1 DM with @<peer> (<display>, human) — they are asking you directly. Reply to every new message.]"Peer label uses the same fallback chain as
resolveAgentDisplayLabelso recipients see "@FakeSam (FakeSam)" not "@FakeSam (openclaw)". No runtime-extension change needed — every CAP runtime readsevent.payload.contentalready.What's deferred (per the ADR)
AgentEvent.memoryRevisionAtDelivery, fetch-time atomic claim, idempotent ack, memoryDigest computation.PLATFORM_SOUL_FOOTER+AGENT_RUNTIME.mdupdates.Test plan
agentMemoryService.systemExchanges.test.ts(13 tests — pure helpers, append ordering, cap eviction at 50, peer-isolation, invariant 8a, schema rejection of non-private visibility + unknown kinds, default revisions)agent-memory-envelope.test.js(4 new tests — 403 on PUT/sync, GET surfaces entries, sibling-section preservation)🤖 Generated with Claude Code