Skip to content

feat(agent-memory): ADR-003 Phase 1 — v2 envelope schema + backfill - #188

Merged
lilyshen0722 merged 1 commit into
mainfrom
feat/adr-003-phase1-memory-schema
Apr 14, 2026
Merged

lilyshen0722 merged 1 commit into
mainfrom
feat/adr-003-phase1-memory-schema

Conversation

@lilyshen0722

Copy link
Copy Markdown
Contributor

Summary

ADR-003 Phase 1: extend the `AgentMemory` kernel primitive with an optional, typed v2 section envelope alongside the existing v1 `content` blob. Strictly additive — v1 callers are untouched. Phase 2 (new `/memory/sync` endpoint + `commonly_ask_agent` / `commonly_read_my_memory` tools) is a separate change.

50 new tests; 664/664 backend tests pass locally.

Why

Per ADR-003, agent memory is a CAP kernel primitive. Phase 1 shapes the storage layer so every future runtime driver — OpenClaw, native, webhook, Vercel cloud agent, BYO — can promote into the same envelope without reshuffling the kernel schema later.

What's in

Model (`backend/models/AgentMemory.ts`)

  • Optional `sections` sub-document: `soul | long_term | daily[] | dedup_state | relationships[] | shared | runtime_meta`
  • Each section: `content`, `visibility` (`private | pod | public`, default `private`), `updatedAt`, `byteSize`
  • Optional `sourceRuntime`, `schemaVersion` scalars
  • `(agentName, instanceId)` unique index unchanged — ADR-003 invariant Add basic unit tests for backend functions #1
  • Every section uses `default: undefined` so fresh records don't auto-insert empty sub-docs
  • `VISIBILITY_VALUES` exported as single source of truth

Service (`backend/services/agentMemoryService.ts`) — new

  • Pure parser: `parseContentIntoSections`, `buildSectionsFromLegacyContent`, `mirrorContentFromSections`
  • Splits legacy `content` on `## ` headers; known dedup names (Commented/Replied/RepliedMsgs/PodVisits/StaleRevivalAt, sourced from registry heartbeat templates) bucket into `dedup_state`

Routes (GET/PUT `/memory`)

  • GET always returns `{ content, sections, sourceRuntime, schemaVersion }`
  • PUT accepts v1 or v2 or both. Sections merge per-key via dotted `$set` paths — partial writes preserve siblings. `content` is mirrored from `sections.long_term.content` only when the caller explicitly supplied `long_term` AND didn't also send an explicit `content`
  • `schemaVersion` server-set to 2 when sections are written (not client-supplied — Phase 2's `/memory/sync` adds explicit mode flags)
  • Rejects unknown section names, empty `sections: {}`, invalid visibility, malformed entries
  • Structured log line per write for kernel-surface observability

Backfill (`backend/scripts/backfill-agent-memory-sections.ts`) — new

  • One-shot, idempotent, cursor-based. Parses v1 content into sections for records without any concrete section field. Preserves the v1 blob
  • `--dry` flag. Returns `{ total, migrated, skipped, empty }`
  • Leaves `sourceRuntime` unset; first real post-migration write populates with the driver's own identifier (ADR-003 §Runtime driver expectations — `'legacy'` is not an ADR-recognized runtime)

Code review

Reviewed by the `code-reviewer` subagent against `docs/REVIEW.md` before commit. Critical finding: the initial PUT handler did a full `$set` on `sections`, which would have silently wiped sibling sections and blanked `content` on any partial-sections write. Fixed by switching to per-key dotted `$set` paths and gating the `content` mirror on the presence of `long_term` in the request. Five regression tests added to lock the fix.

Other review feedback addressed in the same commit:

  • Reject empty `sections: {}` and unknown section names (validation gaps)
  • Server-set `schemaVersion` instead of client-supplied (reduces surface area)
  • Shared `VISIBILITY_VALUES` between model and route (drift prevention)
  • Kernel-surface observability log on every write
  • Backfill skip check on specific section keys, not `Object.keys` length (robustness if stray empty sections ever land)
  • Dropped `sourceRuntime: 'legacy'` default from backfill

Changes

  • `backend/models/AgentMemory.ts` (extended — backwards compatible)
  • `backend/routes/agentsRuntime.ts` (GET/PUT /memory handlers)
  • `backend/services/agentMemoryService.ts` (new)
  • `backend/scripts/backfill-agent-memory-sections.ts` (new)
  • `backend/tests/unit/models/AgentMemory.test.ts` (11 tests)
  • `backend/tests/unit/services/agentMemoryService.test.ts` (15 tests)
  • `backend/tests/integration/agent-memory-envelope.test.js` (24 tests)

Test plan

  • All 50 new tests pass locally
  • Full backend suite 664/664 passing
  • Lint: no new errors introduced by Phase 1 files (baseline unchanged)
  • TypeScript: no new errors in modified/new files
  • Reviewer agent pass with fixes applied
  • CI green
  • Post-merge: run backfill on dev (`node backend/scripts/backfill-agent-memory-sections.js --dry` first)

🤖 Generated with Claude Code

Extends the AgentMemory kernel primitive with an optional, typed v2 section
envelope alongside the existing v1 `content` blob. Phase 1 is strictly
additive per ADR-003 §Migration path; v1 callers are untouched. Phase 2
(new /memory/sync endpoint + tools) is a separate change.

## What's in

**Model (`backend/models/AgentMemory.ts`)**
- Adds optional `sections` sub-document: `soul | long_term | daily[] |
  dedup_state | relationships[] | shared | runtime_meta`
- Each section carries `content`, `visibility` (`private | pod | public`,
  default `private`), `updatedAt`, `byteSize`
- Adds optional `sourceRuntime`, `schemaVersion` scalars
- `(agentName, instanceId)` unique index unchanged — ADR-003 invariant #1
- Every sub-field uses `default: undefined` so GET on a fresh record
  returns only what was explicitly written
- `VISIBILITY_VALUES` exported as single source of truth for the enum

**Service (`backend/services/agentMemoryService.ts`)** — new, pure functions
- `parseContentIntoSections` splits a legacy `content` blob on `## `
  headers; known dedup header names (Commented/Replied/RepliedMsgs/
  PodVisits/StaleRevivalAt — sourced from registry heartbeat templates)
  bucket into `dedup_state`, everything else into `long_term`
- `buildSectionsFromLegacyContent` wraps the parse output in section
  envelopes with default visibility + utf-8 byteSize
- `mirrorContentFromSections` derives the v1 `content` string from
  `sections.long_term.content` for backward reads

**Routes (`backend/routes/agentsRuntime.ts` — GET/PUT /memory)**
- GET always returns `{ content, sections, sourceRuntime, schemaVersion }`
- PUT accepts v1 (`{ content }`), v2 (`{ sections, sourceRuntime? }`), or
  both. **Sections merge per-key via dotted `$set` paths** — a partial
  write (e.g. `{ sections: { dedup_state: {...} } }`) preserves the sibling
  sections the caller didn't include. Writing both `content` and `sections`
  stores both verbatim
- `content` is mirrored from `sections.long_term.content` only when the
  caller actually supplied `long_term` AND didn't also supply an explicit
  `content`; otherwise existing `content` is untouched
- `schemaVersion` is server-set to 2 whenever sections are written; not
  client-supplied (Phase 2's /memory/sync will add explicit mode flags)
- Rejects unknown section names, empty sections objects, invalid visibility
  values, non-string content, malformed daily/relationships entries
- Emits a structured log line on every write for kernel-surface observability

**Backfill (`backend/scripts/backfill-agent-memory-sections.ts`)** — new
- One-shot, idempotent, cursor-based. Parses v1 `content` into
  `sections.long_term` + `sections.dedup_state` for records that don't yet
  have any concrete section field. Sets `schemaVersion: 2`. Leaves
  `sourceRuntime` unset — the first real post-migration write populates it
  with the driver's own identifier (ADR-003 §Runtime driver expectations;
  'legacy' is not an ADR-recognized runtime)
- Supports `--dry` and returns `{ total, migrated, skipped, empty }`
- Preserves the v1 `content` blob verbatim — Phase 1 is additive

**Tests** — 50 new tests, all passing locally. 664/664 backend pass.
- `backend/__tests__/unit/models/AgentMemory.test.ts` (11) — schema shape,
  unique index, visibility default + enum enforcement, required subfields
- `backend/__tests__/unit/services/agentMemoryService.test.ts` (15) —
  parser edge cases: empty input, preamble preservation, case-insensitive
  dedup match, unknown-header pass-through, utf-8 byteSize
- `backend/__tests__/integration/agent-memory-envelope.test.js` (24) —
  real auth pipeline (install → runtime token → /memory); v1 compat, v2
  envelope, partial-sections preserves siblings, sections-without-long_term
  doesn't stomp content, empty/unknown section rejection, server-set
  schemaVersion, backfill idempotence + dry-run

## Code review

Reviewed by the `code-reviewer` subagent against `docs/REVIEW.md` before
commit. Critical finding: the initial PUT handler did a full `$set` on
`sections`, which would have silently wiped sibling sections and blanked
`content` on any partial-sections write. Fixed by switching to per-key
dotted `$set` paths and gating the `content` mirror on the presence of
`long_term` in the request payload. Five regression tests added to lock
the fix. Other review feedback addressed: empty-sections rejection,
server-set `schemaVersion`, shared VISIBILITY enum, kernel-surface log,
backfill skip check by specific section keys (not `Object.keys` length),
dropped `sourceRuntime: 'legacy'` default.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@lilyshen0722
lilyshen0722 merged commit de666af into main Apr 14, 2026
9 checks passed
@lilyshen0722
lilyshen0722 deleted the feat/adr-003-phase1-memory-schema branch April 14, 2026 18:02
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.

1 participant