Skip to content

docs(adr-012): §10 Phase 2 amendment — cycles section + broader injection + heartbeat cue - #293

Closed
samxu01 wants to merge 6 commits into
mainfrom
feat/adr-012-phase-2
Closed

samxu01 wants to merge 6 commits into
mainfrom
feat/adr-012-phase-2

Conversation

@samxu01

@samxu01 samxu01 commented May 4, 2026

Copy link
Copy Markdown
Contributor

Summary

Phase 1 of ADR-012 shipped today (PR #288). The on-cluster snapshot of all 25 deployed agents showed only 2/25 writing substantive content into long_term — the other 23 carry only the provisioner-injected boilerplate. The platform-write triggers landed correctly; the bottleneck is the agent-write loop, which the original ADR underweighted.

This is a docs-only PR proposing a §10 amendment that broadens Phase 2 to close that loop. No code change yet — landing the design first.

Three additions

  1. New cycles[] section — agent-writable, cap 40 / ≤500 chars, append-only. Mirrors system_exchanges[] shape with opposite read/write roles. Closes the cadence gap: today's daily[] is YYYY-MM-DD but heartbeats fire every 10–30 min.
  2. Broaden Phase 2 injection — payload carries { memoryDigest, cyclesDigest, longTermDigest, recentDailyDigest } instead of just memoryDigest. ~1.5KB combined budget, each sub-field independently emit-gated. Surfaces the agent's own writes back to it so writing pays off.
  3. Inline HEARTBEAT cue — parallel to the §9 DM frame. Structured metadata isn't enough (the §9 lesson). Narrative directive at the start of payload.content is what moves behavior.

Non-changes

  • system_exchanges keeps its shape and role (deterministic safety net, platform-written, read-only from agent).
  • revision / lastSeenRevision semantics unchanged — they track system_exchanges only.
  • §9 DM frame unchanged.

Test plan

  • Sam reviews and signs off on the §10 design before any code lands
  • Phase 2 implementation lands in a follow-up PR against this branch (or a fresh one off main once the amendment is merged)

🤖 Generated with Claude Code

samxu01 added 2 commits May 3, 2026 20:15
…tion + heartbeat cue

Phase 1 cluster snapshot revealed the agent-write loop is the
bottleneck, not the platform-write triggers we just added. Of 25
deployed agents, only 2 author substantive long_term content; the
other 23 carry boilerplate. Two diagnoses: (1) no read-back signal
makes writing feel pointless, (2) no schema bucket matches heartbeat
cadence — daily[] is YYYY-MM-DD, but heartbeats fire every 10-30 min.

Amendment additions:

§10.1 — New `cycles[]` section, agent-writable, cap 40 / ≤500 chars,
append-only via the existing $push+$position+$slice pattern. Mirrors
system_exchanges shape; opposite write/read roles (agent writes,
platform reads). No revision bump — that field tracks
system_exchanges only.

§10.2 — Broaden Phase 2 event payload injection from memoryDigest-only
to four sub-fields: memoryDigest + cyclesDigest + longTermDigest +
recentDailyDigest. ~1.5KB combined budget, each sub-field
independently emit-gated. Surfaces the agent's own writes back to it
every event so writing pays off.

§10.3 — Inline HEARTBEAT cue, parallel to §9 DM frame. Structured
metadata is not enough (the §9 lesson) — narrative directive at the
start of payload.content is what moves agent behavior.

§Phasing — Phase 2 rewritten to ~4 days reflecting the broader scope.
Schema + injection + cue + ack-gate ship in one PR.

system_exchanges keeps its existing shape and role: deterministic
safety net for narrow events, platform-written, read-only from agent.
The amendment adds the broader voluntary-write loop alongside.
…load digest + ack-gate

Closes the read-and-write loop on top of Phase 1's substrate. Implements
§10.1 (cycles section), §10.2 (broader injection), §10.3 (inline HEARTBEAT
cue), and the ack-gate from §3.

What lands:

Schema (backend/models/):
- New `cycles` typed section in AgentMemory: agent-writable, cap 40 /
  ≤500 chars / hard-private, mirrors system_exchanges shape with inverted
  read/write roles. No revision bump on write — revision tracks
  system_exchanges only.
- New `memoryRevisionAtDelivery: number | null` on AgentEvent, captured
  at the pending → delivered claim.
- AgentEventStatus extended with terminal `'acked'` state. Lifecycle:
  pending → delivered (on list-claim) → acked (on explicit ack).
  Existing legacy callers ack-from-pending still accepted.

Service (backend/services/agentMemoryService.ts):
- `appendCycle({agentName, instanceId, content, podId?, ts?})` — atomic
  $push + $position:0 + $slice:40, no revision bump, preserves
  lastSyncKey/lastSyncAt (invariant 8a-style carve-out — drivers don't
  sync cycles).
- Four emit-gated digest builders:
  - `buildMemoryDigest` — system_exchanges delta vs lastSeenRevision,
    capped at 10 entries.
  - `buildCyclesDigest` — last 5 cycles entries (always emit if non-empty,
    no delta-gating).
  - `buildLongTermDigest` — head-truncated long_term.content (≤800 chars).
  - `buildRecentDailyDigest` — last 2 daily entries within 7 days,
    content ≤400 chars each.
- `buildMemoryDigestBundle` — aggregator that returns undefined for empty
  fields so the consumer's spread omits them.

Routes (backend/routes/agentsRuntime.ts):
- `validateSectionsPayload` adds `cycles_append_only` tagged error and
  the `{append: {content, ts?, podId?}}` shape contract. Whole-array
  overwrite (`{entries: [...]}` or bare array) is rejected with 403 +
  `cycles_append_only`. Sibling-key combos (e.g. `{append, entries}`)
  also rejected.
- `extractCyclesAppend` splits cycles out of the sections payload before
  the standard write path runs; both PUT /memory and POST /memory/sync
  branch to appendCycle for cycles, then proceed with the rest of
  sections through stampSectionsForWrite as usual.
- Cycles-only PUT skips the dedup-cache invalidating $set/$unset round-
  trip; cycles-only sync skips the dedup pipeline entirely.
- Defense-in-depth: stampSectionsForWrite + mergePatchSections both
  skip `cycles` (matches existing system_exchanges guard).

Event service (backend/services/agentEventService.ts):
- `list()` rewrites the polling path to mutate-on-claim. For each
  candidate _id, status-gated findOneAndUpdate flips
  `pending → delivered`, captures memoryRevisionAtDelivery from a single
  AgentMemory read, and injects the four-field digest bundle into the
  returned payload. Lost races (returns null) are filtered out.
- `acknowledge()` rewritten to flip `delivered/pending → acked` with
  status-gate; on first ack, fires `$max` bump on AgentMemory
  .lastSeenRevision using the captured memoryRevisionAtDelivery.
  Dup-ack short-circuits (returns null, no bump). Legacy callers that
  ack from pending are accepted.
- Cleanup deleteMany scope expanded from `delivered` only to
  `{$in: ['delivered', 'acked']}` — both are terminal-ish for retention.

Heartbeat cue (backend/services/schedulerService.ts):
- §10.3 inline cue prepended to scheduler-heartbeat payload.content,
  ~80 tokens, narrative directive instructing the agent to extract a
  per-cycle takeaway and append to cycles[]. Same shape lesson as the §9
  DM frame — structured metadata is not enough, narrative wins.

Tests:
- Unit (agentMemoryService.cycles.test.ts): 32 cases covering
  truncateCycleContent, appendCycle (DB-backed), schema validation,
  and all four digest builders + the bundle aggregator.
- Unit (agentEventService.test.js): 6 new cases — list mutate-on-claim
  + memoryRevisionAtDelivery capture + digest spread, no-candidates
  short-circuit, lost-race filter, acknowledge happy/dup/null paths.
- Integration (agent-memory-envelope.test.js): 6 new cases for cycles
  append-mode acceptance + three rejection shapes (whole-array,
  bare-array, sibling-key) + cycles-only sync + mixed payload.

All TS clean (tsc:check + tsc:build), 32+9+52 = 93 tests green.
samxu01 added 2 commits May 3, 2026 20:42
- agentEventService: explicit String() coercion on all query-bound
  identifiers (agentName, instanceId, eventId, candidate._id) before
  they hit Mongo. Closes the four js/sql-injection CodeQL alerts
  introduced by the new list-mutate-on-claim and acknowledge $max
  paths. Functionally a no-op — these values are already strings in
  practice; the casts are explicit sanitizers CodeQL can see.
- Update three pre-existing integration tests that asserted post-ack
  status === 'delivered'. ADR-012 §3 promotes 'acked' to terminal;
  'delivered' is now intermediate (claimed, awaiting ack). Updated
  assertions to expect 'acked' with explanatory comment.
  Files: integrations-e2e.test.js (one assertion), clawdbot-e2e.test.js
  (two assertions).

All targeted tests still pass (93/93). tsc:check clean.
CodeQL js/missing-rate-limiting on POST /memory/sync (the only remaining
alert after the SQL-injection coercions). Same pattern as PR #290's
earlier fix on /pods/:podId/messages — phase4RateLimit (120 req/60s,
keyed per agent) brings these inline with /room, /agent-dm, /pods/:podId/ask.

Also pre-empted PUT /memory which I touched substantively in Phase 2
(cycles append-mode wiring) — adding rate-limit before CodeQL flags it
on the next scan.
* `stampSectionsForWrite`; client-supplied values are discarded.
*/
router.put('/memory', agentRuntimeAuth, async (req: any, res: any) => {
router.put('/memory', agentRuntimeAuth, phase4RateLimit, async (req: any, res: any) => {
* v1 `content` is mirrored from `long_term.content` (same rule as PUT).
*/
router.post('/memory/sync', agentRuntimeAuth, async (req: any, res: any) => {
router.post('/memory/sync', agentRuntimeAuth, phase4RateLimit, async (req: any, res: any) => {
samxu01 added 2 commits May 3, 2026 20:57
ADR-012 §3 mutate-on-claim flips status pending → delivered at the
GET /events route. The clawdbot poll test asserted status === 'pending'
on the response payload, which is the OLD non-mutating fetch behavior.
Updated to expect 'delivered' (claimed, awaiting ack).
ADR-012 §3 mutate-on-claim: a single poll claims ALL pending events
atomically. Subsequent polls return []. Test was polling once per
ack-iteration expecting decreasing length — that was the old
non-mutating-fetch semantic. New shape: poll once, ack each event
individually.
samxu01 added a commit that referenced this pull request May 4, 2026
…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.
@samxu01

samxu01 commented May 4, 2026

Copy link
Copy Markdown
Contributor Author

Squash-merged to main as d7e5118.

@samxu01 samxu01 closed this May 4, 2026
@samxu01
samxu01 deleted the feat/adr-012-phase-2 branch May 4, 2026 04:11
lilyshen0722 added a commit that referenced this pull request Aug 5, 2026
)

* fix(ax): the tool-contract guard skipped the strongest cue surface

The guard reads the presets.ts cycles trailer and the inline mention cues.
It did not read backend/services/heartbeatCue.ts — which by ADR-012 s10.3's
own reasoning is the strongest agent-facing surface we ship, reaching every
agent on every tick.

That gap had already been paid for. The heartbeat cue named
commonly_save_my_memory for a `cycles` write from 2026-05-03 (#293) to
2026-08-04 (#804/#818) — a tool that refuses the section by design — and
neither repo's suite could see the other, so both stayed green for three
months. A peer re-derived the same contradiction from source on 2026-08-05,
hours after it was fixed, which is what surfaced the omission.

Adds the cue as a required-tool source. The constant interpolates
${CYCLES_WRITER_TOOL}, so it is resolved from the same file rather than
restated here — a restated name is the drift this script exists to catch.
No namedForOtherDrivers exemption: #840 reconciled the lineages and the pin
declares commonly_log_cycle, so this is a hard requirement and a future bump
that drops it goes red instead of the fleet going quiet.

Two assertions the name-matching check cannot make, because existence is not
capability — the #295 cue would PASS a declares-the-tool check against
today's pin, since commonly_save_my_memory is declared at :526 right above a
description saying `cycles` is intentionally unavailable there:

  - the cue names exactly one writer tool, so a cue that also names a second
    (the #295 shape, and the shape a well-meaning "mention both" edit
    reproduces) fails
  - the escape-hatch clause survives. It looks redundant now that the pin has
    the tool and would be the first thing an editor cuts; deleting it re-arms
    the turn-burn that forced the #296 rollback the next time a bump drops it.

Mutation-verified: each of the three fails exactly its own assertion, with
measured anchors and byte-identical restores.

CLAUDE.md's pin-skew entry described the divergence in the present tense and
prescribed the fix #840 had already executed. It cost a wrong claim in the
sprint pod nine hours later. Dated, struck, and led with the resolution;
verified against the running gateway container rather than the source tree.

AX entry 21: remediation text quotes the defect verbatim, so a repo
accumulates copies of what is no longer true in the surfaces agents grep
first. Six verbatim copies of the dead cue, zero live ones — and the only two
queued events matching it were the peer's own reports about it.

Co-Authored-By: Claude Opus 5 <[email protected]>

* docs: the cycles silence is moltbot-scoped, and dated by measurement

The pin-skew entry asserted the skew caused "the fleet's" cycles silence
with an undocumented ~87-day figure. Measured against the memory collection
2026-08-05:

  moltbots (agentName=openclaw)  22 docs with entries, newest 2026-05-24T08:49:56Z
  non-moltbot seats              13 docs with entries, newest same evening

The moltbot cutoff falls on the exact day of the d6e63b2 bundled-skills
bump that dropped commonly_log_cycle — so the root cause is corroborated by
a source independent of the submodule log, rather than inferred from it.

Two corrections this forces. The silence is moltbot-scoped, not fleet-wide:
MCP and wrapper seats wrote cycles throughout, including during the outage
being debugged. And every moltbot array sits at the 40-entry cap — they are
FULL, not empty — so a recovery check looking for "cycles appear" reads
healthy off both the cap and the unaffected seats. It has to filter to
agentName=openclaw and require an entry newer than 05-24.

Co-Authored-By: Claude Opus 5 <[email protected]>

---------

Co-authored-by: Claude Opus 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants