Skip to content

Commit 9d9dc31

Browse files
authored
feat(memory): session provenance, admission policy, and openclaw memory forget (#130151)
* feat(state): add memory entry origins and session tombstone tables with session-aware write provenance Additive same-version per-agent tables (memory_entry_origins, memory_session_tombstones) declared canonically with lazy idempotent ensure; read-only agent DB access exposed through the SDK; memory-write observers and the session-memory hook record the authoring session; archived narrative transcripts classified by authoritative run identity. * feat(memory): admission policy, entry provenance, and openclaw memory forget memoryPolicy.excludeSessions keeps configured sources out of the dreaming pipeline with recorded exclusions; promotion writes are marker-addressable and carry per-session origins through consolidation; memory forget purges whole entries and every derived artifact (corpus lines, diary quotes, index/FTS/vec/cache, short-term state, backups), reports curated agent writes from transcripts, and tombstones purged sessions so ingestion, backfill, and transcript indexing never re-admit them. * docs(memory): document admission policy, memory forget, and provenance boundaries * fix(memory): open the vec probe through openNodeSqliteDatabase Kysely guardrail forbids direct node:sqlite constructors in production; the in-memory extension probe now uses the canonical opener. * fix(memory): resolve archived and explicit sessions in memory forget Explicit --session selectors union live session windows, transcript archives, and exact unresolved ids so an operator-named session always purges and tombstones instead of silently no-oping after lifecycle archival; reports carry per-session resolution sources. ClawSweeper P1 on #130151. * fix(memory): reconcile consolidation origins for every workspace agent Shared workspaces record entry origins per source agent; consolidation now re-keys and prunes origins in each participating agent's database (membership from the authoritative dreaming workspace mapping), so a non-owner agent's later memory forget still finds the live consolidated entry. ClawSweeper re-review P1 on #130151.
1 parent f1491a2 commit 9d9dc31

51 files changed

Lines changed: 4256 additions & 66 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎docs/cli/memory.md‎

Lines changed: 87 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,17 @@
11
---
2-
summary: "CLI reference for `openclaw memory` (status/index/search/promote/promote-explain/rem-harness/rem-backfill/session-backfill)"
2+
summary: "CLI reference for `openclaw memory` (status/index/search/forget/promote/promote-explain/rem-harness/rem-backfill/session-backfill)"
33
read_when:
44
- You want to index or search semantic memory
55
- You're debugging memory availability or indexing
66
- You want to promote recalled short-term memory into `MEMORY.md`
7+
- You need to delete provenance-tracked memories derived from specific sessions or participants
78
title: "Memory"
89
---
910

1011
# `openclaw memory`
1112

12-
Manage semantic memory indexing, search, and promotion into `MEMORY.md`.
13+
Manage semantic memory indexing, search, promotion into `MEMORY.md`, and
14+
provenance-based deletion.
1315
Provided by the bundled `memory-core` plugin, available when
1416
`plugins.slots.memory` selects `memory-core` (the default). Other memory
1517
plugins expose their own CLI namespaces.
@@ -54,6 +56,13 @@ extra-path details before showing indexing progress. The completion message
5456
reports the indexed file count. An empty corpus is a successful no-op: the
5557
command reports the resolved workspace path and that nothing was indexed, and
5658
leaves the missing `memory/` directory for the first memory write to create.
59+
Internal dreaming-narrative, cron, and heartbeat session transcripts are
60+
excluded from indexing, including retained compressed narrative archives whose
61+
original sessions are no longer active. Sessions previously selected by
62+
`memory forget` also remain excluded. `--force` removes stale index records for
63+
both groups without reindexing their retained transcripts. Ordinary retained,
64+
reset, and deleted user-session archives remain eligible until explicitly
65+
targeted.
5766

5867
## `memory search`
5968

@@ -73,6 +82,76 @@ warns that matches may be incomplete. With `--json`, the response adds
7382
index. Treat an empty `results` array as authoritative only when `stale` is
7483
absent.
7584

85+
## `memory forget`
86+
87+
Delete provenance-tracked durable memory entries derived from selected
88+
sessions, together with their indexed and short-term copies. Select sessions by
89+
ID or session key, their external-content hook source, or a participant's actor
90+
ID:
91+
92+
```bash
93+
openclaw memory forget --session <id-or-key> [--session <id-or-key> ...]
94+
openclaw memory forget --hook-source gmail [--since 2026-01-01]
95+
openclaw memory forget --participant <actor-id> [--agent <id>] [--dry-run] [--json]
96+
```
97+
98+
`--session`, `--hook-source`, and `--participant` are repeatable. At least one
99+
selector is required. `--agent` selects one agent and otherwise defaults to the
100+
default agent. Explicit session IDs and keys match both live sessions and
101+
retained archived sessions. An unknown explicit value is still treated as an
102+
exact session ID, purged where matching artifacts exist, and durably excluded
103+
from future memory ingestion. The report identifies each selected session as
104+
`live`, `archived`, or `unresolved`. Hook-source and participant selectors only
105+
match sessions whose corresponding metadata still exists; archived sessions do
106+
not retain those facts, so select them by ID or key instead. `--since <date>`
107+
filters live sessions by their creation time and archived sessions by their
108+
archive creation time; unresolved explicit IDs have no timestamp and remain
109+
selected.
110+
111+
Run with `--dry-run` before deleting. It computes the same complete report as
112+
the real purge without changing memory files, SQLite indexes, plugin state, or
113+
durable deletion records. `--json` prints that report as machine-readable JSON.
114+
115+
A purge removes matching pipeline-promoted entries, session-corpus lines,
116+
selected-session transcript index chunks, full-text and vector index records,
117+
embedding-cache entries, short-term recall, seen-hash scopes, dreaming rewrite
118+
backups, and recorded origins. It also clears stale index records for internal
119+
dreaming-narrative, cron, or heartbeat sessions. An entry derived from both
120+
selected and unselected sessions is deleted whole and reported as a
121+
mixed-lineage entry; dreaming can regenerate supported facts from surviving
122+
sessions later. Entries without recorded origins remain searchable and are not
123+
deleted by an unrelated selector; the report lists them as untargetable.
124+
125+
A real purge records each selected session as forgotten in the agent's SQLite
126+
database. Future dreaming sweeps record that session as excluded with reason
127+
`forgotten`; `memory session-backfill` and transcript indexing, including
128+
`memory index --force`, also reject it. Repeating the purge is safe and does
129+
not undo this exclusion.
130+
131+
Dream diaries and other workspace memory files can quote source-session corpus
132+
lines without retaining a session reference. The purge removes any whole line
133+
containing an exact purged corpus-line snippet from files such as
134+
`memory/dreaming/**/*.md` and `DREAMS.md`, as well as matching dreaming
135+
backups. `artifacts.memoryLines` reports the number of these additional removed
136+
memory-file lines. Model-paraphrased prose that does not contain the exact
137+
source text cannot be attributed reliably and is not removed automatically.
138+
139+
Direct agent edits to memory files are tracked at the file level, not per
140+
entry. When such a write happened during a selected session, `curatedWrites`
141+
lists its `relativePath` and `observedAt` without modifying the file. Evidence
142+
comes from native write-observer records and the selected sessions' live or
143+
archived transcripts, including writes performed by external agent harnesses.
144+
Review those files separately: a freeform edit cannot be attributed to
145+
individual lines safely enough for automatic deletion.
146+
147+
<Warning>
148+
`memory forget` removes selected-session transcript chunks from the memory
149+
index and permanently prevents their memory-pipeline readmission, but does not
150+
delete the original source session transcripts. The report identifies the
151+
selected sessions so you can remove transcript data separately through its
152+
owning session-management workflow when required.
153+
</Warning>
154+
76155
## `memory promote`
77156

78157
Rank short-term candidates from `memory/YYYY-MM-DD.md` and optionally append
@@ -177,7 +256,10 @@ tracked message hashes and per-run caps as live session ingestion, so repeated
177256
canonical store are eligible; tool output, web or non-owner input, and turns
178257
without trustworthy owner provenance are excluded. Foreign archive files have
179258
no authenticated owner-provenance contract, so their embedded ownership fields
180-
remain untrusted and cannot be staged.
259+
remain untrusted and cannot be staged. Sessions previously purged with
260+
[`memory forget`](/cli/memory#memory-forget) remain durably excluded, including
261+
when their original transcripts still exist or their tracked hashes were
262+
cleared.
181263

182264
`--apply` drains the selected history to completion in one invocation while
183265
keeping each bounded batch in its own transaction. Human and JSON output report
@@ -193,7 +275,8 @@ commands use the same grounded-only staging class and diary markers. Run
193275
`session-backfill --rollback` only when you intend to clear both commands'
194276
grounded backfill artifacts from that workspace. Rollback also removes the
195277
tracked hashes added by session backfill and rewinds the affected transcript
196-
cursors, so the same candidates can be previewed and applied again.
278+
cursors, so surviving eligible candidates can be previewed and applied again.
279+
Rollback does not remove forgotten-session records or readmit purged sessions.
197280

198281
## Dreaming
199282

‎docs/plan/memory-provenance.md‎

Lines changed: 234 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,234 @@
1+
---
2+
summary: Memory provenance and selective deletion — pipeline-promoted entries record source sessions, admission policy excludes configured sources, and `memory forget` durably blocks reingestion while purging attributable artifacts and reporting agent-curated writes.
3+
title: Memory provenance plan
4+
read_when:
5+
- Changing dreaming ingestion, consolidation, promotion, or memory deletion
6+
- Adding session-derived data to durable memory files or the memory index
7+
- Reviewing enterprise memory-policy, GDPR-deletion, or taint requirements
8+
---
9+
10+
## Status
11+
12+
Accepted (operator decision, 2026-08-25). Single-PR implementation: admission
13+
policy, entry origins, durable forgotten-session records, `memory forget`.
14+
15+
## Problem
16+
17+
Enterprise operators need two guarantees the built-in memory system cannot give
18+
today:
19+
20+
1. **Admission**: content from named sources (email connectors, specific
21+
channels, specific counterparties) must be excludable from the durable
22+
memory pipeline by policy, deterministically — not by prompting. This does
23+
not restrict an agent's direct file edits during the excluded session.
24+
2. **Deletion**: "purge every memory derived from X" — where X is a session, a
25+
person, or a source class (e.g. all Gmail-derived sessions) — must be
26+
executable and auditable after the fact. Employee-exit and GDPR erasure are
27+
the driving cases.
28+
29+
Today the session id is available at every memory write site but is never
30+
recorded as a queryable fact: it is encoded in chunk paths
31+
(`sessions/<agentId>/<sessionId>`), in session-corpus line prefixes
32+
(`[<agentId>/sessions/<agentId>/<sessionId>#L<n>]`), and in daily-note prose
33+
headers — never as a column. Consolidation (dreaming) merges entries across
34+
sessions, so lineage is a DAG; after one dream cycle no deterministic join from
35+
memory text back to source sessions exists.
36+
37+
## Design
38+
39+
### Invariants
40+
41+
- Entry lineage is recorded at the producer, at write time, in the per-agent
42+
SQLite DB (`agents/<agentId>/agent/openclaw-agent.sqlite`). Direct-write file
43+
provenance remains in its existing bounded core-owned SQLite plugin state.
44+
No prose parsing on the read path.
45+
- Lineage survives consolidation: a merged entry's origin set is the union of
46+
its parents' origin sets, maintained deterministically in code around the
47+
consolidation LLM call — the model never carries provenance.
48+
- Deletion is whole-entry: an entry with any origin in the purge set is
49+
removed entirely. No LLM-mediated "subtract one source" rewriting.
50+
- A purge sweeps every derived artifact: memory files, index chunks (FTS +
51+
vec + recall metadata + provenance via cascade), session-corpus lines,
52+
short-term recall state, and dreaming memory backups. Verbatim copies of
53+
purged corpus snippets are removed whole-line from derived memory files and
54+
backups. A deletion that survives in a backup namespace is not a deletion.
55+
- Forgetting a session records a durable per-agent tombstone. Later dreaming
56+
ingestion, explicit session backfill, and transcript indexing honor that
57+
recorded fact, so clearing seen-hash scopes cannot turn purged sessions
58+
back into new work.
59+
- Internal dreaming-narrative, cron, and heartbeat session transcripts never
60+
enter the memory transcript index, including retained compressed narrative
61+
archives without live session-window rows. Structured session or run
62+
identity remains authoritative; quoted memory content is never used as a
63+
classifier. Forced reindex and purge remove stale index records from
64+
earlier runs without readmitting forgotten sessions.
65+
- Direct agent edits carry file-level source-session evidence from native
66+
write-observer records or the selected sessions' live and archived harness
67+
transcripts, not invented entry lineage. Matching files are reported as
68+
`curatedWrites`, never edited automatically when affected lines cannot be
69+
identified.
70+
- Missing provenance never blocks recall or changes retrieval behavior; it
71+
only limits what `memory forget` can target (reported, not silent).
72+
73+
### 1. Admission policy (no schema change)
74+
75+
Config under the `memory-core` plugin entry:
76+
77+
```jsonc
78+
"memoryPolicy": {
79+
"excludeSessions": {
80+
"hookExternalContentSources": ["gmail"], // matches session_windows.hook_external_content_source
81+
"channels": ["email"], // matches session_windows.channel
82+
"chatTypes": [] // direct | group | channel
83+
}
84+
}
85+
```
86+
87+
Enforcement point: session corpus building / `scanSessionIngestionSource`
88+
(`extensions/memory-core/src/session-ingestion.ts` already exposes
89+
`acceptProvenance`; extend the corpus entry with the session-window facts so
90+
the predicate can act on them). An excluded session is recorded as excluded in
91+
ingestion state (visible non-outcome), never scanned into the corpus, and
92+
therefore can never reach candidates, consolidation, or promotion.
93+
94+
Forgotten sessions are also excluded regardless of policy configuration. Their
95+
recorded ingestion non-outcome carries `excludedReason: "forgotten"`; explicit
96+
session backfill and the transcript index consult the same durable fact
97+
before processing live sessions or retained archives.
98+
99+
This policy governs pipeline ingestion only. An agent running in an excluded
100+
session can still write `MEMORY.md`, `USER.md`, or another memory file during
101+
its turn; native write-observer records and harness tool calls in that
102+
session's transcript supply evidence for report-only deletion review.
103+
104+
### 2. Entry origins and forgotten sessions (additive schema, same version)
105+
106+
New tables in the per-agent DB, following the retired
107+
`skill_workshop_proposal_origin_runs` child-table pattern:
108+
109+
```sql
110+
CREATE TABLE IF NOT EXISTS memory_entry_origins (
111+
entry_key TEXT NOT NULL, -- stable claim key (claimHash / candidateKey)
112+
agent_id TEXT NOT NULL,
113+
session_id TEXT NOT NULL, -- logical session id
114+
session_key TEXT, -- when known
115+
origin_class TEXT NOT NULL CHECK (origin_class IN ('owner','agent','untrusted','system')),
116+
observed_at INTEGER NOT NULL,
117+
PRIMARY KEY (entry_key, agent_id, session_id)
118+
) STRICT;
119+
120+
CREATE TABLE IF NOT EXISTS memory_session_tombstones (
121+
session_id TEXT NOT NULL PRIMARY KEY,
122+
agent_id TEXT NOT NULL,
123+
reason TEXT NOT NULL,
124+
created_at INTEGER NOT NULL
125+
) STRICT;
126+
```
127+
128+
Additive: new tables only, declared in the canonical schema plus a one-time
129+
idempotent lazy ensure on first feature use, folded into the migration path at
130+
the next natural bump (per `docs/reference/database-schemas.md`). Tombstones
131+
are written only by a real purge, use reason `forgotten`, and are idempotent;
132+
`--dry-run` does not initialize tombstone storage or write a deletion record.
133+
134+
Writers:
135+
136+
- **Ingestion → corpus**: each session-corpus line already carries its session
137+
ref; when a promotion candidate is formed from session-derived lines, record
138+
`(claimHash, agentId, sessionId)`.
139+
- **Consolidation**: the LLM returns
140+
`{candidateKey, action: added|merged|superseded, resultEntry, priorEntries}`.
141+
Code unions the parents' origin rows onto the result entry's key on `merged`,
142+
re-keys on `superseded`, inserts fresh rows on `added`. Origin rows for keys
143+
no longer referenced by any live entry are pruned by the same pass. Shared
144+
workspaces reconcile every participating agent's existing origin rows.
145+
146+
Operator-curated `MEMORY.md`/`USER.md` edits have no origin rows. Direct agent
147+
edits also lack deterministic entry lineage, but their existing bounded
148+
memory-artifact provenance record carries `sessionId` and, when known,
149+
`sessionKey`; `memory forget` reports matching files without rewriting them.
150+
151+
### 3. `memory forget` (purge command)
152+
153+
CLI surface (memory-core owns it): resolve a session set, then purge.
154+
155+
```
156+
openclaw memory forget --session <id-or-key> [...]
157+
openclaw memory forget --hook-source gmail [--since <date>]
158+
openclaw memory forget --participant <actor-id>
159+
[--dry-run] [--json]
160+
```
161+
162+
Explicit session IDs and keys resolve against live `session_windows` and
163+
retained `session_transcript_archives`; an unmatched explicit value remains an
164+
exact-ID purge target rather than silently disappearing. The report identifies
165+
each target as `live`, `archived`, or `unresolved`. Hook-source and participant
166+
selectors only match facts recorded in `session_windows` /
167+
`session_participants`; archived sessions no longer retain that metadata and
168+
must be selected explicitly. `--since` compares live-session creation times or
169+
archive creation times; unresolved explicit IDs remain eligible.
170+
171+
Purge steps, in order, reported per step:
172+
173+
1. Session-corpus files: identify lines whose rendered prefix matches the
174+
purged sessions and retain their exact text for deterministic cleanup;
175+
rewrite corpus files without those lines.
176+
2. Origin join → entry keys → remove matching entries from memory files
177+
(promotion-written blocks are hash-addressable; daily-note session sections
178+
carry session ids in headers). Remove any other whole memory-file line that
179+
contains an exact purged corpus snippet, including dream diaries and
180+
`DREAMS.md`; report those lines as `artifacts.memoryLines`.
181+
3. Index: delete chunks for removed content and the selected sessions' own
182+
transcripts (cascades take recall metadata, provenance, FTS, vec); clear
183+
stale internal narrative/cron/heartbeat transcript debris, including
184+
metadata-less retained narrative archives; drop `memory_index_sources`
185+
rows for fully removed files; bump revision.
186+
4. Plugin state: purge `short-term-recall` snippets and seen-hash scopes for
187+
the sessions; purge matching entries and exact snippets inside
188+
`dreaming-memory-backups`.
189+
5. Origins and tombstones: delete origin rows for the purged sessions; report
190+
entries whose origin set became empty vs. mixed-lineage entries that were
191+
removed whole. Record each selected session with reason `forgotten` so
192+
later ingestion, session backfill, indexing, and forced reindex cannot
193+
resurrect its content.
194+
6. Curated writes: report `{ relativePath, observedAt }` for agent-written
195+
memory files recorded by the write observer or matching mutation tool calls
196+
in the selected sessions' live and archived transcripts. Deduplicate files
197+
across both sources and leave their contents unchanged because file-level
198+
provenance cannot identify affected entries.
199+
200+
`--dry-run` prints the full report without writing. Mixed-lineage entries are
201+
deleted whole and listed, so the operator can re-run dreaming to regenerate
202+
what clean sessions still support; forgotten sessions remain excluded from
203+
that sweep. Repeating a purge is idempotent. A future legal-hold flag can
204+
refuse purges with a named reason; out of scope for this PR beyond leaving the
205+
report shaped to carry refusals.
206+
207+
## Non-goals
208+
209+
- Purging session transcripts themselves (session store owns that; `forget`
210+
removes their memory-index copies and reports the source sessions so the
211+
operator can act on retained transcripts separately).
212+
- Automatically redacting direct agent-written memory files without
213+
deterministic entry-level lineage (`curatedWrites` is report-only).
214+
- Removing LLM-paraphrased diary prose that no longer contains an exact
215+
purged corpus snippet.
216+
- Sub-entry source subtraction or model-mediated rewriting; attributable
217+
promoted entries are removed whole and exact corpus quotes whole-line.
218+
- Legal-hold enforcement (report shape only).
219+
- Cross-agent purge orchestration (per-agent DB; callers iterate agents).
220+
221+
## Proof
222+
223+
Live test with a real OpenAI-backed agent in an isolated `OPENCLAW_STATE_DIR`:
224+
seed synthetic sessions (some flagged as email-derived), run dreaming, verify
225+
origin rows exist and admission excluded the tainted session; run
226+
`memory forget --dry-run` then real purge; verify memory files, FTS, vec,
227+
embedding cache, session-corpus, short-term state, and backups no longer
228+
contain the purged facts; verify internal narrative transcripts remain
229+
unindexed even when only retained compressed archives remain, exact diary
230+
quotes are removed, matching direct agent writes are reported without
231+
modification, and recall still works for surviving entries. Run another
232+
dreaming sweep and forced reindex to verify tombstoned sessions remain
233+
excluded and their transcript chunks are not recreated; verify explicit session
234+
backfill also refuses to regenerate their candidates.

0 commit comments

Comments
 (0)