Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(memory): pasted content is never captured as facts about the user (#5812)

garrytan6934f9d11acb
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 2ea539adb5..d38d6adfcd 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -15,7 +15,7 @@ src/core/ai/gateway.ts 4365 ratchet +7 fix wave 5 (#5137): provider-key redactor
src/commands/sync.ts 473 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals)
src/core/cycle.ts 3221 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge
src/core/cycle/synthesize.ts 3291 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge
-src/core/cycle/extract-atoms.ts 1802 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts)
+src/core/cycle/extract-atoms.ts 1803 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut
src/core/engine.ts 2674 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option
src/core/import-file.ts 2230 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode)
src/core/migrate.ts 599 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3)
diff --git a/src/core/context/checkpoint-harvest.ts b/src/core/context/checkpoint-harvest.ts
index 23fbdee0db..38681dd312 100644
--- a/src/core/context/checkpoint-harvest.ts
+++ b/src/core/context/checkpoint-harvest.ts
@@ -34,7 +34,7 @@ import type { BrainEngine } from '../engine.ts';
import type { CapabilityReport } from '../capability.ts';
import { acquireCorpusClaim, CORPUS_CLAIM_SUFFIX, CORPUS_INGESTED_SUFFIX } from '../sweep.ts';
import { appendCheckpointManifest } from './session-state.ts';
-import { readSegmentLedger, HARVEST_RECEIPT_SUFFIX } from './corpus-segments.ts';
+import { corpusTextForExtraction, readSegmentLedger, HARVEST_RECEIPT_SUFFIX } from './corpus-segments.ts';
import { writeHeartbeat } from './hook-heartbeat.ts';
/** Bounded queue — overflow is a typed skip; the sweep backstop extracts later. */
@@ -298,7 +298,7 @@ async function runOne(job: HarvestJob): Promise<{
currentAbort = abort;
let r: Awaited<ReturnType<typeof runFactsPipeline>>;
try {
- r = await runFactsPipeline(raw, {
+ r = await runFactsPipeline(corpusTextForExtraction(job.file, raw), {
engine: job.engine,
sourceId: job.sourceId,
sessionId: job.sessionId,
@@ -438,7 +438,7 @@ async function runWritebackTurn(job: HarvestJob, full: string, ingestedPath: str
currentAbort = abort;
let r: Awaited<ReturnType<typeof runFactsPipeline>>;
try {
- r = await runFactsPipeline(raw, {
+ r = await runFactsPipeline(corpusTextForExtraction(job.file, raw), {
engine: job.engine,
sourceId: job.sourceId,
sessionId: job.sessionId,
diff --git a/src/core/context/corpus-segments.ts b/src/core/context/corpus-segments.ts
index 8aa95ec3fe..ce3467c55b 100644
--- a/src/core/context/corpus-segments.ts
+++ b/src/core/context/corpus-segments.ts
@@ -31,10 +31,11 @@
import { createHash } from 'node:crypto';
import { closeSync, existsSync, openSync, readdirSync, readFileSync, readSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
-import { join } from 'node:path';
+import { basename, join } from 'node:path';
import type { WindowTurn } from './entity-salience.ts';
import { toCorpusText, type ToolCallRecord } from '../transcripts/claude-code-jsonl.ts';
import { mapOpenclawLine } from '../transcripts/openclaw.ts';
+import { stripPastedContent, stripPastedContentFromCorpus } from '../transcripts/pasted-content.ts';
/** Length of the hex content-hash slice in segment filenames. */
/**
@@ -334,6 +335,16 @@ export function corpusFileSessionId(name: string): string {
return parseSegmentFileName(name)?.sessionId ?? parseWbFileName(name)?.sessionId ?? name.replace(/\.txt$/, '');
}
+/**
+ * #5812 — the text a fact extractor may see from a session-corpus file: paste
+ * blocks removed (someone else's words), the file itself unchanged. A
+ * writeback turn file is one user turn; every other corpus file is
+ * `toCorpusText` blocks, stripped per `[user]` block.
+ */
+export function corpusTextForExtraction(path: string, text: string): string {
+ return parseWbFileName(basename(path)) ? stripPastedContent(text).text : stripPastedContentFromCorpus(text);
+}
+
/** The TERMINAL writeback_off `.ingested` sidecar payload — the wb state
* machine's one terminal skip, written identically by the serve harvest and
* the sweep backstop (shape drift between the two writers would be invisible
diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.ts
index 614025eac6..11cc65fda2 100644
--- a/src/core/cycle/extract-atoms.ts
+++ b/src/core/cycle/extract-atoms.ts
@@ -68,6 +68,7 @@ import { createGlobalLlmHaltTracker, haltedClassOf, type GlobalLlmErrorClass } f
import { importFromContent } from '../import-file.ts';
import { serializeMarkdown } from '../markdown.ts';
import { truncateUtf8 } from '../text-safe.ts';
+import { corpusTextForExtraction } from '../context/corpus-segments.ts';
import { BudgetExhausted, BudgetTracker, loadPricingOverrides } from '../budget/budget-tracker.ts';
import { resolveExtractAtomsCostGate, resolveEmbedModelForCostGate } from './extract-atoms-cost-gate.ts';
import { writeReceipt } from '../extract/receipt-writer.ts';
@@ -1087,8 +1088,8 @@ export async function runPhaseExtractAtoms(
// and quote provenance is verified against THIS rather than the full
// item, so a quote can only verify against text the model actually saw.
// #4529/#4540: configurable input cap, cut UTF-8-safely (a bare .slice()
- // can split a surrogate pair at the boundary).
- const promptContent = truncateUtf8(item.content, maxInputChars);
+ // can split a surrogate pair at the boundary); #5812 strips pastes first.
+ const promptContent = truncateUtf8(item.kind === 'transcript' ? corpusTextForExtraction(item.filePath, item.content) : item.content, maxInputChars);
try {
const origin: AtomOrigin | null = managed ? await readAtomOrigin(engine, managed, item) : null;
const visibility = origin?.visibility ?? effectiveVisibility(item.kind === 'transcript' ? { kind: 'transcript' } // #5525
diff --git a/src/core/facts/writeback-gate.ts b/src/core/facts/writeback-gate.ts
index b7d1cd2bfa..3492b7760f 100644
--- a/src/core/facts/writeback-gate.ts
+++ b/src/core/facts/writeback-gate.ts
@@ -18,6 +18,7 @@
*/
import { createHash } from 'node:crypto';
+import { stripPastedContent } from '../transcripts/pasted-content.ts';
/** Every gate skip is a BY-DESIGN filter outcome, not a failure — heartbeat
* writers classify these `outcome: 'ok'` so alerting on 'degraded' never
@@ -31,6 +32,7 @@ export const WRITEBACK_SKIP_REASONS = [
'question_only',
'quoted_or_tool_output',
'bulk_paste',
+ 'pasted_content',
] as const;
export type WritebackSkipReason = (typeof WRITEBACK_SKIP_REASONS)[number];
@@ -105,18 +107,27 @@ export function gateWritebackTurn(text: unknown): WritebackGateResult {
// single length compare rejects it.
if (trimmed.length > MAX_TURN_CHARS) return { ok: false, reason: 'bulk_paste' };
- // 4. ack_or_greeting: ≤6 words AND the whole text is lexicon-matched.
- const bare = trimmed.toLowerCase().replace(/[.!?,;:~……]+$/gu, '').replace(/[\u{1F300}-\u{1FAFF}\u{2600}-\u{27BF}]/gu, '').trim();
+ // 4. pasted_content (#5812): Claude Code paste blocks are someone else's
+ // words, so every later rule and the banked text see only the user's
+ // own words. A turn that was only pasted text banks nothing.
+ const own = stripPastedContent(trimmed).text.trim();
+ if (own.length === 0) return { ok: false, reason: 'pasted_content' };
+ if (own.length < (CJK_RE.test(own) ? MIN_TURN_CHARS_CJK : MIN_TURN_CHARS)) {
+ return { ok: false, reason: 'too_short' };
+ }
+
+ // 5. ack_or_greeting: ≤6 words AND the whole text is lexicon-matched.
+ const bare = own.toLowerCase().replace(/[.!?,;:~……]+$/gu, '').replace(/[\u{1F300}-\u{1FAFF}\u{2600}-\u{27BF}]/gu, '').trim();
if (bare.split(/\s+/).length <= 6 && ACK_RE.test(bare)) {
return { ok: false, reason: 'ack_or_greeting' };
}
- // 5. slash_command (harness command, operational)
- if (trimmed.startsWith('/')) return { ok: false, reason: 'slash_command' };
+ // 6. slash_command (harness command, operational)
+ if (own.startsWith('/')) return { ok: false, reason: 'slash_command' };
- // 6. question_only: every non-empty sentence ends with a question mark.
+ // 7. question_only: every non-empty sentence ends with a question mark.
// Precision-biased — a fact embedded in a question is an accepted miss.
- const sentences = trimmed
+ const sentences = own
.split(/(?<=[.!?。!?])\s+|\n+/)
.map((s) => s.trim())
.filter((s) => s.length > 0);
@@ -124,13 +135,13 @@ export function gateWritebackTurn(text: unknown): WritebackGateResult {
return { ok: false, reason: 'question_only' };
}
- // 7. quoted_or_tool_output: strip fences / '>' quotes / indent runs; if the
+ // 8. quoted_or_tool_output: strip fences / '>' quotes / indent runs; if the
// residue is not substantive on its own, the turn was quoted material.
- const residue = stripQuotedAndToolOutput(trimmed).trim();
+ const residue = stripQuotedAndToolOutput(own).trim();
if (residue.length < (CJK_RE.test(residue) ? MIN_TURN_CHARS_CJK : MIN_TURN_CHARS)) {
return { ok: false, reason: 'quoted_or_tool_output' };
}
- const normalized = normalizeTurnText(trimmed);
+ const normalized = normalizeTurnText(own);
return { ok: true, normalized, hash24: turnHash24(normalized) };
}
diff --git a/src/core/sweep.ts b/src/core/sweep.ts
index 0bce8f3c62..7d02c73457 100644
--- a/src/core/sweep.ts
+++ b/src/core/sweep.ts
@@ -576,7 +576,7 @@ async function runCorpusIngestPass(
// OFF retires banked turns even when the brain cannot extract — otherwise
// the files linger eligible and a later re-enable would extract turns the
// operator already revoked (codex re-review, this wave).
- const { parseWbFileName, writebackOffSidecarJson, corpusFileSessionId } = await import('./context/corpus-segments.ts');
+ const { parseWbFileName, writebackOffSidecarJson, corpusFileSessionId, corpusTextForExtraction } = await import('./context/corpus-segments.ts');
const { resolveWritebackConfig } = await import('./facts/writeback-config.ts');
const { loadConfig: loadFileCfg } = await import('./config.ts');
const { isValidSourceId } = await import('./source-id.ts');
@@ -705,7 +705,8 @@ async function runCorpusIngestPass(
const wbSourceId = wbMeta?.sourceId && isValidSourceId(wbMeta.sourceId)
? wbMeta.sourceId
: sourceId;
- const r = await runFactsPipeline(raw, {
+ // #5812: pasted blocks never reach the extractor (file unchanged).
+ const r = await runFactsPipeline(corpusTextForExtraction(name, raw), {
engine,
sourceId: wbMeta ? wbSourceId : sourceId,
sessionId: wbMeta ? wbMeta.sessionId : `sweep:corpus:${name}`,
diff --git a/src/core/transcripts/claude-code-jsonl.ts b/src/core/transcripts/claude-code-jsonl.ts
index 382ed59121..41c58b125a 100644
--- a/src/core/transcripts/claude-code-jsonl.ts
+++ b/src/core/transcripts/claude-code-jsonl.ts
@@ -31,6 +31,7 @@
import { closeSync, lstatSync, openSync, readFileSync, readSync, statSync } from 'node:fs';
import { isPathContained } from '../path-confine.ts';
import { detectWslMountRoot, translateWindowsPath } from '../wsl-paths.ts';
+import { stripPastedContent } from './pasted-content.ts';
import { claudeProjectsDir, type HostSpecTarget } from '../bootstrap/host-specs.ts';
import type { WindowTurn } from '../context/entity-salience.ts';
@@ -384,11 +385,12 @@ function entryToInjectedBlock(entry: unknown): string | null {
* Claude Code writes slash-command bookkeeping (`/clear`, its stdout) as
* `user` records whose content is ONLY harness tags. They stay in the window
* (archival) but are not something the human said, so they never count as a
- * genuine user prompt for the writeback lane.
+ * genuine user prompt for the writeback lane. A turn that is only pasted
+ * content (#5812) is classified the same way; its text is never rewritten.
*/
const HARNESS_TAG_RE = /<(local-command-stdout|local-command-stderr|command-name|command-message|command-args)>[\s\S]*?<\/\1>/g;
function isGenuineUserText(text: string): boolean {
- return text.replace(HARNESS_TAG_RE, '').trim().length > 0;
+ return stripPastedContent(text.replace(HARNESS_TAG_RE, '')).text.trim().length > 0;
}
function isSkippedTurnEntry(e: Record<string, unknown>): boolean {
diff --git a/src/core/transcripts/pasted-content.ts b/src/core/transcripts/pasted-content.ts
new file mode 100644
index 0000000000..82265b0edc
--- /dev/null
+++ b/src/core/transcripts/pasted-content.ts
@@ -0,0 +1,115 @@
+/**
+ * #5812 — Claude Code paste blocks. When a user pastes a block into the
+ * Claude Code prompt, the harness records the expanded text in the session
+ * transcript wrapped as
+ *
+ * <pasted_content id="2830">
+ * …pasted text…
+ * </pasted_content id="2830">
+ *
+ * (observed on Claude Code 2.1.287; the closing tag repeats the id). This
+ * module depends on that harness tag format: if Claude Code changes it, the
+ * fixtures in test/transcripts/pasted-content.test.ts stop matching.
+ *
+ * Pasted text is usually someone else's words (an email, an article, a log),
+ * so it must never become a fact about the user. The ONE detector lives here:
+ * the writeback gate strips pastes from the banked turn, the transcript
+ * parser uses it only to decide whether a user turn is genuine (turn text is
+ * never rewritten — recall, the session corpus and transcript ingest keep the
+ * paste with its tags), and the fact-extraction lanes strip pastes per user
+ * turn before the extractor sees the text. Engine-free, node builtins only:
+ * the Stop hook child imports it.
+ */
+
+const OPEN = '<pasted_content';
+const CLOSE = '</pasted_content';
+/** An unclosed paste is stripped to the end of its turn only when the
+ * opening tag has the harness's exact attribute shape. */
+const HARNESS_OPEN_RE = /^<pasted_content id="[^"<>\r\n]*">$/;
+const MAX_TAG_CHARS = 256;
+
+/** Index just past the `>` of a tag whose name ends at `from`, or -1 when the
+ * text at `from` does not continue a tag (name boundary, single line). */
+function tagEnd(text: string, from: number): number {
+ const first = text[from];
+ if (first !== '>' && first !== ' ' && first !== '\t') return -1;
+ const limit = Math.min(text.length, from + MAX_TAG_CHARS);
+ for (let i = from; i < limit; i++) {
+ const c = text[i];
+ if (c === '>') return i + 1;
+ if (c === '<' || c === '\n' || c === '\r') return -1;
+ }
+ return -1;
+}
+
+function findClose(text: string, from: number): number {
+ for (let at = text.indexOf(CLOSE, from); at >= 0; at = text.indexOf(CLOSE, at + CLOSE.length)) {
+ const end = tagEnd(text, at + CLOSE.length);
+ if (end >= 0) return end;
+ }
+ return -1;
+}
+
+/**
+ * Remove every paste block (`<pasted_content …>…</pasted_content …>`) from
+ * one turn's text, plus an unclosed harness-shaped tail. Each removed block
+ * leaves one space so the words around it never merge. `stripped` counts the
+ * removed blocks; a malformed tag is left as text.
+ */
+export function stripPastedContent(text: string): { text: string; stripped: number } {
+ if (!text.includes(OPEN)) return { text, stripped: 0 };
+ let out = '';
+ let pos = 0;
+ let stripped = 0;
+ let at = text.indexOf(OPEN, pos);
+ while (at >= 0) {
+ const openEnd = tagEnd(text, at + OPEN.length);
+ if (openEnd < 0) {
+ at = text.indexOf(OPEN, at + OPEN.length);
+ continue;
+ }
+ const closeEnd = findClose(text, openEnd);
+ if (closeEnd >= 0) {
+ out += text.slice(pos, at) + ' ';
+ pos = closeEnd;
+ stripped++;
+ at = text.indexOf(OPEN, pos);
+ continue;
+ }
+ if (HARNESS_OPEN_RE.test(text.slice(at, openEnd))) {
+ out += text.slice(pos, at) + ' ';
+ pos = text.length;
+ stripped++;
+ break;
+ }
+ at = text.indexOf(OPEN, openEnd);
+ }
+ return { text: out + text.slice(pos), stripped };
+}
+
+/** True when the text held at least one paste block and nothing else. */
+export function isPasteOnly(text: string): boolean {
+ const r = stripPastedContent(text);
+ return r.stripped > 0 && r.text.trim().length === 0;
+}
+
+const CORPUS_BLOCK_RE = /(?:^|\n\n)(?=\[(?:user|assistant)\]\n)/;
+
+/**
+ * Strip pastes from session-corpus text (`toCorpusText`'s `[role]\n<text>`
+ * blocks) inside each `[user]` block, never across the flattened corpus: an
+ * unclosed paste in one turn ends with that turn, so later turns survive.
+ * Assistant blocks are unchanged.
+ */
+export function stripPastedContentFromCorpus(corpus: string): string {
+ if (!corpus.includes(OPEN)) return corpus;
+ return corpus
+ .split(CORPUS_BLOCK_RE)
+ .map((block) => {
+ if (!block.startsWith('[user]\n') || !block.includes(OPEN)) return block;
+ const body = block.slice('[user]\n'.length);
+ const trailing = body.endsWith('\n') ? '\n' : '';
+ return `[user]\n${stripPastedContent(body).text.trim()}${trailing}`;
+ })
+ .join('\n\n');
+}
diff --git a/test/checkpoint-harvest.serial.test.ts b/test/checkpoint-harvest.serial.test.ts
index 16a922d0b7..f97e06ed64 100644
--- a/test/checkpoint-harvest.serial.test.ts
+++ b/test/checkpoint-harvest.serial.test.ts
@@ -19,6 +19,7 @@ import { RECIPES } from '../src/core/ai/recipes/index.ts';
import { __resetFactsQueueForTests } from '../src/core/facts/queue.ts';
import type { CapabilityReport } from '../src/core/capability.ts';
import { CORPUS_CLAIM_SUFFIX, CORPUS_INGESTED_SUFFIX } from '../src/core/sweep.ts';
+import { toCorpusText } from '../src/core/transcripts/claude-code-jsonl.ts';
import {
__drainCheckpointHarvestForTests,
__resetCheckpointHarvestForTests,
@@ -673,3 +674,49 @@ describe('writeback lane (ambient memory backstop)', () => {
await __drainCheckpointHarvestForTests();
});
});
+
+/** A chat stub that records every prompt the extractor sends. */
+function recordingChatStub(): string[] {
+ const prompts: string[] = [];
+ __setChatTransportForTests(async (opts): Promise<ChatResult> => {
+ prompts.push(opts.messages.map((m) => (typeof m.content === 'string' ? m.content : JSON.stringify(m.content))).join('\n'));
+ return {
+ text: JSON.stringify({ facts: [{ fact: 'prefers dark roast coffee', kind: 'preference', entity: null, confidence: 1.0, notability: 'high' }] }),
+ blocks: [], stopReason: 'end',
+ usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'test:stub', providerId: 'test',
+ };
+ });
+ return prompts;
+}
+
+const PASTE = '<pasted_content id="2830">\nForwarded email: the offsite moves to March and the budget is final.\n</pasted_content id="2830">';
+
+describe('pasted content never reaches the extractor (#5812)', () => {
+ test('compact lane: a paste inside a [user] block is stripped before extraction; the segment file is unchanged', async () => {
+ const prompts = recordingChatStub();
+ const text = toCorpusText([
+ { role: 'user', text: `Please remember this note I got:\n\n${PASTE}\n\nand also I prefer dark roast coffee.` },
+ { role: 'assistant', text: 'Saved both.' },
+ ]);
+ const seg = bankSegment('sess-paste-compact', text);
+ scheduleCheckpointHarvest({ engine, sourceId: 'default', sessionId: 'sess-paste-compact', corpusDir, file: seg.file, capabilities: KEYED });
+ await __drainCheckpointHarvestForTests();
+ expect(prompts.length).toBeGreaterThan(0);
+ expect(prompts.join('\n')).not.toContain('offsite moves to March');
+ expect(prompts.join('\n')).toContain('I prefer dark roast coffee');
+ expect(readFileSync(join(corpusDir, seg.file), 'utf8')).toContain('offsite moves to March');
+ });
+
+ test('writeback lane: a turn file banked with a paste (older binary) is extracted without it', async () => {
+ await engine.setConfig('memory.auto_writeback', 'salient');
+ const prompts = recordingChatStub();
+ const file = 'sess-paste-wb.wb-0123456789abcdef01234567.txt';
+ writeFileSync(join(corpusDir, file), `Please remember this note I got: ${PASTE} and also I prefer dark roast coffee.\n`);
+ scheduleCheckpointHarvest({ engine, sourceId: 'default', sessionId: 'sess-paste-wb', corpusDir, file, capabilities: KEYED, lane: 'writeback' });
+ await __drainCheckpointHarvestForTests();
+ expect(prompts.length).toBeGreaterThan(0);
+ expect(prompts.join('\n')).not.toContain('offsite moves to March');
+ expect(prompts.join('\n')).toContain('I prefer dark roast coffee');
+ });
+});
diff --git a/test/extract-atoms-pasted-content.test.ts b/test/extract-atoms-pasted-content.test.ts
new file mode 100644
index 0000000000..6f22f3764d
--- /dev/null
+++ b/test/extract-atoms-pasted-content.test.ts
@@ -0,0 +1,66 @@
+/**
+ * #5812: the dream extract_atoms phase reads session-corpus transcripts, so a
+ * paste (someone else's words) must not reach the model there either. The
+ * strip runs per `[user]` block and before the input cap, so the cut and the
+ * quote-grounding text are the stripped text.
+ *
+ * Pins, asserted on the message sent through the chat seam: a corpus built
+ * through `toCorpusText` from a real Claude Code transcript carries none of
+ * its paste; an unclosed paste in one user turn does not erase the next user
+ * turn.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { createHash } from 'node:crypto';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runPhaseWithStoredPageFixtures as runPhaseExtractAtoms } from './helpers/extract-atoms-page-fixtures.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { parseTranscript, toCorpusText } from '../src/core/transcripts/claude-code-jsonl.ts';
+import type { ChatOpts, ChatResult } from '../src/core/ai/gateway.ts';
+
+let engine: PGLiteEngine;
+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 60000);
+afterAll(async () => { await engine.disconnect(); });
+beforeEach(async () => { await resetPgliteState(engine); });
+
+function reply(): ChatResult {
+ const text = '{"atoms":[]}';
+ return { text, blocks: [{ type: 'text', text }], stopReason: 'end',
+ usage: { input_tokens: 100, output_tokens: 50, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'anthropic:claude-haiku-4-5', providerId: 'anthropic' } as ChatResult;
+}
+
+async function sentFor(content: string): Promise<string> {
+ const sent: string[] = [];
+ await runPhaseExtractAtoms(engine, {
+ sourceId: 'default', _pages: [],
+ _transcripts: [{ filePath: '/corpus/sess-paste.txt', content, contentHash: createHash('sha256').update(content).digest('hex') }],
+ _chat: async (opts: ChatOpts) => { sent.push(String(opts.messages[0]?.content ?? '')); return reply(); },
+ });
+ expect(sent.length).toBe(1);
+ return sent[0];
+}
+
+describe('extract_atoms never sees pasted content (#5812)', () => {
+ test('a corpus from a real Claude Code transcript reaches the model without its paste', async () => {
+ const corpus = toCorpusText(parseTranscript(join(import.meta.dir, 'fixtures', 'claude-code-paste', 'session.jsonl')).turns);
+ expect(corpus).toContain('pasted third-party email');
+ const user = await sentFor(corpus);
+ expect(user).not.toContain('pasted third-party email');
+ expect(user).not.toContain('pasted_content');
+ expect(user).toContain('I prefer dark roast coffee');
+ expect(user).toContain('[assistant]');
+ });
+
+ test('an unclosed paste in one user turn keeps the next user turn', async () => {
+ const corpus = toCorpusText([
+ { role: 'user', text: 'Keep this for reference: <pasted_content id="5">\nForwarded thread that never closes, quoting a vendor contract.' },
+ { role: 'assistant', text: 'Noted.' },
+ { role: 'user', text: 'I decided we ship the reversible pricing change first and measure it for two weeks.' },
+ ]);
+ const user = await sentFor(corpus);
+ expect(user).not.toContain('vendor contract');
+ expect(user).toContain('Keep this for reference:');
+ expect(user).toContain('I decided we ship the reversible pricing change first');
+ });
+});
diff --git a/test/facts/writeback-gate.test.ts b/test/facts/writeback-gate.test.ts
index 5ac451a53a..3943cea814 100644
--- a/test/facts/writeback-gate.test.ts
+++ b/test/facts/writeback-gate.test.ts
@@ -89,3 +89,43 @@ describe('gateWritebackTurn — ok path: normalization + idempotency hash', () =
expect(turnHash24(normalizeTurnText('I prefer dark mode in every editor.'))).toBe(a.hash24);
});
});
+
+describe('gateWritebackTurn — Claude Code paste blocks (#5812)', () => {
+ const PASTE = (body: string, id = '2830') => `<pasted_content id="${id}">\n${body}\n</pasted_content id="${id}">`;
+ const EMAIL = 'The offsite moves to March and the budget is final, per the finance team.';
+
+ test('a paste-only turn → pasted_content (nothing banked)', () => {
+ expect(gateWritebackTurn(`\n\n${PASTE(EMAIL)}\n`)).toEqual({ ok: false, reason: 'pasted_content' });
+ expect(gateWritebackTurn(`${PASTE(EMAIL, '1')}\n\n${PASTE(EMAIL, '2')}`)).toEqual({ ok: false, reason: 'pasted_content' });
+ });
+
+ test('a mixed turn banks only the user\'s own words', () => {
+ const r = gateWritebackTurn(`Please remember this note I got: \n\n${PASTE(EMAIL)}\n\n and also I prefer dark roast coffee.`);
+ if (!r.ok) throw new Error(`expected ok, got ${r.reason}`);
+ expect(r.normalized).toBe('Please remember this note I got: and also I prefer dark roast coffee.');
+ expect(JSON.stringify(r)).not.toContain('finance team');
+ expect(JSON.stringify(r)).not.toContain('pasted_content');
+ });
+
+ test('an unclosed paste tail is stripped too', () => {
+ const r = gateWritebackTurn(`I moved our weekly sync to Tuesdays at 10am.\n\n<pasted_content id="9">\n${EMAIL}`);
+ if (!r.ok) throw new Error(`expected ok, got ${r.reason}`);
+ expect(r.normalized).toBe('I moved our weekly sync to Tuesdays at 10am.');
+ });
+
+ test('the remaining rules run on the user\'s own words', () => {
+ expect(gateWritebackTurn(`thanks ${PASTE(EMAIL)}`)).toEqual({ ok: false, reason: 'too_short' });
+ expect(gateWritebackTurn(`Can you summarize this email for me please? ${PASTE(EMAIL)}`)).toEqual({ ok: false, reason: 'question_only' });
+ });
+
+ test('CJK own words keep the CJK floor after the strip', () => {
+ const r = gateWritebackTurn(`我对花生严重过敏,随身带肾上腺素笔 ${PASTE(EMAIL)}`);
+ if (!r.ok) throw new Error(`expected ok, got ${r.reason}`);
+ expect(r.normalized).toBe('我对花生严重过敏,随身带肾上腺素笔');
+ });
+
+ test('a multi-megabyte paste is still bulk_paste (length check before any scan)', () => {
+ const big = `I prefer dark roast coffee. ${PASTE('x'.repeat(3 * 1024 * 1024))}`;
+ expect(gateWritebackTurn(big)).toEqual({ ok: false, reason: 'bulk_paste' });
+ });
+});
diff --git a/test/fixtures/claude-code-paste/session.jsonl b/test/fixtures/claude-code-paste/session.jsonl
new file mode 100644
index 0000000000..05b1931ee7
--- /dev/null
+++ b/test/fixtures/claude-code-paste/session.jsonl
@@ -0,0 +1,5 @@
+{"parentUuid":null,"isSidechain":false,"promptId":"257d7b4d-9a07-4b4c-89b9-020dddcbe840","type":"user","message":{"role":"user","content":"Please remember this note I got: \n\n<pasted_content id=\"2830\">\nLine 1 of a pasted third-party email: the offsite moves to March and the budget is final.\nLine 2 of a pasted third-party email: the offsite moves to March and the budget is final.\nLine 3 of a pasted third-party email: the offsite moves to March and the budget is final.\nLine 4 of a pasted third-party email: the offsite moves to March and the budget is final.\nLine 5 of a pasted third-party email: the offsite moves to March and the budget is final.\nLine 6 of a pasted third-party email: the offsite moves to March and the budget is final.\nLine 7 of a pasted third-party email: the offsite moves to March and the budget is final.\nLine 8 of a pasted third-party email: the offsite moves to March and the budget is final.\nLine 9 of a pasted third-party email: the offsite moves to March and the budget is final.\nLine 10 of a pasted third-party email: the offsite moves to March and the budget is final.\nLine 11 of a pasted third-party email: the offsite moves to March and the budget is final.\nLine 12 of a pasted third-party email: the offsite moves to March and the budget is final.\nLine 13 of a pasted third-party email: the offsite moves to March and the budget is final.\nLine 14 of a pasted third-party email: the offsite moves to March and the budget is final.\n</pasted_content id=\"2830\">\n\n and also I prefer dark roast coffee."},"uuid":"5b8640d6-a68e-412c-b724-9f186dec1666","timestamp":"2026-10-01T21:00:52.824Z","permissionMode":"default","origin":{"kind":"human"},"promptSource":"typed","turnOrigin":"human","turnPosition":{"promptIndex":1,"turnIndex":1},"userType":"external","entrypoint":"cli","cwd":"/home/user/project","sessionId":"c232648c-d3bb-4908-ad78-3f62e078ed45","version":"2.1.287","gitBranch":"HEAD"}
+{"parentUuid":"a1bd1945-2223-4e2f-b208-680c89bdb935","isSidechain":false,"message":{"model":"claude-haiku-4-5-20251001","id":"msg_011CfcC2qFD3xyoZH2KNxAdu","type":"message","role":"assistant","content":[{"type":"text","text":"I'll save both of those for you."}],"container":null,"stop_reason":"tool_use","stop_sequence":null,"stop_details":null,"usage":{"input_tokens":10,"cache_creation_input_tokens":7422,"cache_read_input_tokens":16493,"output_tokens":507,"output_tokens_details":{"thinking_tokens":276},"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":7422},"inference_geo":"not_available","iterations":[{"input_tokens":10,"output_tokens":507,"cache_read_input_tokens":16493,"cache_creation_input_tokens":7422,"cache_creation":{"ephemeral_5m_input_tokens":7422,"ephemeral_1h_input_tokens":0},"type":"message"}],"speed":"standard","fallback_credit":null},"input_transformations":[],"diagnostics":null,"context_management":null},"apiBlockIndex":1,"requestId":"req_011CfcC2q25SK2tC8L7nrBZJ","type":"assistant","uuid":"b9d72489-4949-46f5-81ba-d0f8700eaba1","timestamp":"2026-10-01T21:00:56.261Z","perTurnEffort":null,"session_id":"c232648c-d3bb-4908-ad78-3f62e078ed45","userType":"external","entrypoint":"cli","cwd":"/home/user/project","sessionId":"c232648c-d3bb-4908-ad78-3f62e078ed45","version":"2.1.287","gitBranch":"HEAD"}
+{"parentUuid":"1dff990f-73e9-4045-956a-dbbfe76725ec","isSidechain":false,"message":{"model":"claude-haiku-4-5-20251001","id":"msg_011CfcC3YCpdDudPNJB4TRDg","type":"message","role":"assistant","content":[{"type":"text","text":"Got it — saved both:\n- **Team offsite moving to March 2027** with finalized budget\n- **Your dark roast coffee preference**\n\nThese are now in your project memory and will carry forward to future conversations."}],"container":null,"stop_reason":"end_turn","stop_sequence":null,"stop_details":null,"usage":{"input_tokens":8,"cache_creation_input_tokens":303,"cache_read_input_tokens":25004,"output_tokens":119,"output_tokens_details":{"thinking_tokens":64},"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":303},"inference_geo":"not_available","iterations":[{"input_tokens":8,"output_tokens":119,"cache_read_input_tokens":25004,"cache_creation_input_tokens":303,"cache_creation":{"ephemeral_5m_input_tokens":303,"ephemeral_1h_input_tokens":0},"type":"message"}],"speed":"standard","fallback_credit":null},"input_transformations":[],"diagnostics":null,"context_management":null},"apiBlockIndex":1,"requestId":"req_011CfcC3XwgXaySmCoGWi5Gj","type":"assistant","uuid":"826b9fbc-5101-47a5-8124-04837d52a2c5","timestamp":"2026-10-01T21:01:04.027Z","perTurnEffort":null,"session_id":"c232648c-d3bb-4908-ad78-3f62e078ed45","userType":"external","entrypoint":"cli","cwd":"/home/user/project","sessionId":"c232648c-d3bb-4908-ad78-3f62e078ed45","version":"2.1.287","gitBranch":"HEAD"}
+{"parentUuid":"68535e66-b069-437a-99dc-cd8c0e757df0","isSidechain":false,"promptId":"4a07bb08-c3e3-43fe-8470-91044b48cf8d","type":"user","message":{"role":"user","content":"\n\n<pasted_content id=\"2830\">\nLine 1 of a pasted third-party email: the offsite moves to March and the budget is final.\nLine 2 of a pasted third-party email: the offsite moves to March and the budget is final.\nLine 3 of a pasted third-party email: the offsite moves to March and the budget is final.\nLine 4 of a pasted third-party email: the offsite moves to March and the budget is final.\nLine 5 of a pasted third-party email: the offsite moves to March and the budget is final.\nLine 6 of a pasted third-party email: the offsite moves to March and the budget is final.\nLine 7 of a pasted third-party email: the offsite moves to March and the budget is final.\nLine 8 of a pasted third-party email: the offsite moves to March and the budget is final.\nLine 9 of a pasted third-party email: the offsite moves to March and the budget is final.\nLine 10 of a pasted third-party email: the offsite moves to March and the budget is final.\nLine 11 of a pasted third-party email: the offsite moves to March and the budget is final.\nLine 12 of a pasted third-party email: the offsite moves to March and the budget is final.\nLine 13 of a pasted third-party email: the offsite moves to March and the budget is final.\nLine 14 of a pasted third-party email: the offsite moves to March and the budget is final.\n</pasted_content id=\"2830\">\n"},"uuid":"51e02f5b-bedd-44b9-9747-4ef1cf6d16ec","timestamp":"2026-10-01T21:01:26.856Z","permissionMode":"default","origin":{"kind":"human"},"promptSource":"typed","turnOrigin":"human","turnPosition":{"promptIndex":2,"turnIndex":2},"userType":"external","entrypoint":"cli","cwd":"/home/user/project","sessionId":"c232648c-d3bb-4908-ad78-3f62e078ed45","version":"2.1.287","gitBranch":"HEAD"}
+{"parentUuid":"298f6520-9030-48f8-9079-e7162caafbfb","isSidechain":false,"message":{"model":"claude-haiku-4-5-20251001","id":"msg_011CfcC5LadXxgqYPT19DmtP","type":"message","role":"assistant","content":[{"type":"text","text":"I see you've pasted the same third-party email again — it's the same offsite/budget information I just saved to your project memory. \n\nDid you mean to ask me to do something with this, or was this pasted by accident?"}],"container":null,"stop_reason":"end_turn","stop_sequence":null,"stop_details":null,"usage":{"input_tokens":9,"cache_creation_input_tokens":418,"cache_read_input_tokens":25431,"output_tokens":161,"output_tokens_details":{"thinking_tokens":102},"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":418},"inference_geo":"not_available","iterations":[{"input_tokens":9,"output_tokens":161,"cache_read_input_tokens":25431,"cache_creation_input_tokens":418,"cache_creation":{"ephemeral_5m_input_tokens":418,"ephemeral_1h_input_tokens":0},"type":"message"}],"speed":"standard","fallback_credit":null},"input_transformations":[],"diagnostics":null,"context_management":null},"apiBlockIndex":1,"requestId":"req_011CfcC5LK1Cj1PHh8DNf6D3","type":"assistant","uuid":"c4fa496d-45be-4b17-9c73-7b7c3b93d9c1","timestamp":"2026-10-01T21:01:28.574Z","perTurnEffort":null,"session_id":"c232648c-d3bb-4908-ad78-3f62e078ed45","userType":"external","entrypoint":"cli","cwd":"/home/user/project","sessionId":"c232648c-d3bb-4908-ad78-3f62e078ed45","version":"2.1.287","gitBranch":"HEAD"}
diff --git a/test/hook-writeback-stop.serial.test.ts b/test/hook-writeback-stop.serial.test.ts
index 4197d6c570..bc0730824d 100644
--- a/test/hook-writeback-stop.serial.test.ts
+++ b/test/hook-writeback-stop.serial.test.ts
@@ -7,7 +7,7 @@
* hook child.
*/
import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
-import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import type net from 'node:net';
@@ -111,6 +111,26 @@ function writeTranscriptWithToolResult(userText: string, resultChars: number): {
return { path: p, root };
}
+/** A claude-code JSONL transcript of alternating turns under `<root>/<project>/session.jsonl`. */
+function writeTurns(turns: Array<{ role: 'user' | 'assistant'; text: string }>, project = 'app'): { path: string; root: string } {
+ const root = join(tmp, 'projects-root');
+ mkdirSync(join(root, project), { recursive: true });
+ const p = join(root, project, 'session.jsonl');
+ writeFileSync(p, turns.map((t, i) => JSON.stringify({
+ parentUuid: i === 0 ? null : `t-${i - 1}`, isSidechain: false, type: t.role,
+ message: { role: t.role, content: t.role === 'user' ? t.text : [{ type: 'text', text: t.text }] },
+ uuid: `t-${i}`, sessionId: 's-wb', timestamp: `2026-09-01T10:00:0${i}.000Z`,
+ })).join('\n') + '\n');
+ return { path: p, root };
+}
+
+const PASTE = '<pasted_content id="2830">\nForwarded: the offsite moves to March and the budget is final.\n</pasted_content id="2830">';
+
+function bankedTexts(): string[] {
+ if (!existsSync(corpus())) return [];
+ return readdirSync(corpus()).filter((f) => f.includes('.wb-')).map((f) => readFileSync(join(corpus(), f), 'utf8'));
+}
+
const io = { write: () => {} };
async function wbHeartbeats() {
@@ -284,3 +304,34 @@ describe('hook stop — ambient writeback banking', () => {
expect(hb.some((e) => e.reason === 'wb_scheduled' && e.outcome === 'ok')).toBe(true);
});
});
+
+describe('hook stop — pasted content (#5812)', () => {
+ const OWN = 'I prefer dark roast coffee and I want it on every order.';
+
+ test('a mixed last turn banks only the user\'s own words', async () => {
+ writeConfig({ writeback: 'salient' });
+ const t = writeTurns([{ role: 'user', text: `Please remember this note I got: \n\n${PASTE}\n\n ${OWN}` }, { role: 'assistant', text: 'Saved.' }]);
+ expect(await runHook(['stop'], { ...io, transcriptRoot: t.root, stdin: JSON.stringify({ session_id: 's-wb', transcript_path: t.path }) })).toBe(0);
+ expect(bankedTexts()).toEqual([`Please remember this note I got: ${OWN}\n`]);
+ });
+
+ test('a paste-only last turn banks nothing new: the previous genuine turn is the candidate (wb_dup)', async () => {
+ writeConfig({ writeback: 'salient' });
+ const first = [{ role: 'user' as const, text: OWN }, { role: 'assistant' as const, text: 'Saved.' }];
+ let t = writeTurns(first);
+ const payload = () => JSON.stringify({ session_id: 's-wb', transcript_path: t.path });
+ expect(await runHook(['stop'], { ...io, transcriptRoot: t.root, stdin: payload() })).toBe(0);
+ t = writeTurns([...first, { role: 'user', text: `\n\n${PASTE}\n` }, { role: 'assistant', text: 'Is this the same email?' }]);
+ expect(await runHook(['stop'], { ...io, transcriptRoot: t.root, stdin: payload() })).toBe(0);
+ expect(bankedTexts()).toEqual([`${OWN}\n`]);
+ expect((await wbHeartbeats()).map((e) => e.reason)).toEqual(['no_serve', 'wb_dup']);
+ });
+
+ test('a session whose only user turn is a paste → no_user_turn, no file', async () => {
+ writeConfig({ writeback: 'salient' });
+ const t = writeTurns([{ role: 'user', text: PASTE }, { role: 'assistant', text: 'Got it.' }]);
+ expect(await runHook(['stop'], { ...io, transcriptRoot: t.root, stdin: JSON.stringify({ session_id: 's-wb', transcript_path: t.path }) })).toBe(0);
+ expect(bankedTexts()).toEqual([]);
+ expect((await wbHeartbeats())[0]?.reason).toBe('no_user_turn');
+ });
+});
diff --git a/test/sweep-writeback-corpus.test.ts b/test/sweep-writeback-corpus.test.ts
index 3eab70c9df..62fdaebb5a 100644
--- a/test/sweep-writeback-corpus.test.ts
+++ b/test/sweep-writeback-corpus.test.ts
@@ -12,7 +12,7 @@
* Hermetic in-memory PGLite + chat-transport stub (sweep.test.ts harness).
*/
import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';
-import { mkdtempSync, existsSync, readFileSync, rmSync } from 'node:fs';
+import { mkdtempSync, existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
@@ -25,6 +25,7 @@ import type { CapabilityReport } from '../src/core/capability.ts';
import { detectCapabilities } from '../src/core/capability.ts';
import { RECIPES } from '../src/core/ai/recipes/index.ts';
import { withEnv, emptyHome } from './helpers/with-env.ts';
+import { parseTranscript, toCorpusText } from '../src/core/transcripts/claude-code-jsonl.ts';
const KEYED: CapabilityReport = {
embeddings: { available: false },
@@ -258,3 +259,31 @@ describe('runMaintenanceSweep — ambient-writeback turn files (OV2-11)', () =>
expect(typeof sidecar.skipped).toBe('string'); // malformed_output/refusal class — recorded, never a silent zero
});
});
+
+describe('runMaintenanceSweep — pasted content never reaches the extractor (#5812)', () => {
+ test('a session corpus built from a real Claude Code transcript is extracted without its pastes; the file is unchanged', async () => {
+ const prompts: string[] = [];
+ __setChatTransportForTests(async (opts): Promise<ChatResult> => {
+ prompts.push(opts.messages.map((m) => (typeof m.content === 'string' ? m.content : JSON.stringify(m.content))).join('\n'));
+ return {
+ text: JSON.stringify({ facts: [{ fact: 'prefers dark roast coffee', kind: 'preference', entity: null, confidence: 0.9, notability: 'high' }] }),
+ blocks: [], stopReason: 'end',
+ usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'anthropic:test-stub', providerId: 'anthropic',
+ };
+ });
+ const parsed = parseTranscript(join(import.meta.dir, 'fixtures', 'claude-code-paste', 'session.jsonl'));
+ const corpus = toCorpusText(parsed.turns);
+ expect(corpus).toContain('pasted third-party email');
+ writeFileSync(join(corpusDir, 'sess-paste.txt'), corpus);
+
+ const r = await runMaintenanceSweep(engine, { sourceId: 'default', capabilities: KEYED });
+ expect(r.corpusIngested).toBe(1);
+ expect(prompts.length).toBeGreaterThan(0);
+ const seen = prompts.join('\n');
+ expect(seen).not.toContain('pasted third-party email');
+ expect(seen).not.toContain('pasted_content');
+ expect(seen).toContain('I prefer dark roast coffee');
+ expect(readFileSync(join(corpusDir, 'sess-paste.txt'), 'utf8')).toBe(corpus);
+ });
+});
diff --git a/test/transcripts-pasted-content.test.ts b/test/transcripts-pasted-content.test.ts
new file mode 100644
index 0000000000..70b20a9e1c
--- /dev/null
+++ b/test/transcripts-pasted-content.test.ts
@@ -0,0 +1,120 @@
+/**
+ * #5812 — Claude Code paste blocks. The fixture is a real Claude Code 2.1.287
+ * session (paths generalized): a mixed turn (the user's words around a
+ * pasted email) and a paste-only turn, exactly as the harness wrote them.
+ *
+ * Pins: the shared helper strips closed blocks and only a harness-shaped
+ * unclosed tail; corpus stripping is per `[user]` block, so an unclosed paste
+ * never erases a later turn; the parser classifies a paste-only turn as not
+ * genuine while every rendered text (turns, corpus, segments) keeps the paste
+ * byte for byte.
+ */
+import { describe, expect, test } from 'bun:test';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import {
+ isPasteOnly,
+ stripPastedContent,
+ stripPastedContentFromCorpus,
+} from '../src/core/transcripts/pasted-content.ts';
+import { parseTranscript, toCorpusText } from '../src/core/transcripts/claude-code-jsonl.ts';
+import { corpusTextForExtraction, renderSegmentText } from '../src/core/context/corpus-segments.ts';
+
+const FIXTURE = join(import.meta.dir, 'fixtures', 'claude-code-paste', 'session.jsonl');
+const lines = readFileSync(FIXTURE, 'utf8').trim().split('\n').map((l) => JSON.parse(l));
+const userTexts: string[] = lines
+ .filter((l) => l.type === 'user')
+ .map((l) => l.message.content as string);
+const [MIXED, PASTE_ONLY] = userTexts;
+const PASTE_MARK = 'pasted third-party email';
+const OWN_WORDS = 'I prefer dark roast coffee';
+
+describe('stripPastedContent — the one paste detector', () => {
+ test('a real mixed turn keeps only the user\'s own words', () => {
+ expect(MIXED).toContain('<pasted_content id="');
+ const r = stripPastedContent(MIXED);
+ expect(r.stripped).toBe(1);
+ expect(r.text).not.toContain(PASTE_MARK);
+ expect(r.text).not.toContain('pasted_content');
+ expect(r.text).toContain('Please remember this note I got:');
+ expect(r.text).toContain(OWN_WORDS);
+ expect(isPasteOnly(MIXED)).toBe(false);
+ });
+
+ test('a real paste-only turn is paste-only', () => {
+ expect(isPasteOnly(PASTE_ONLY)).toBe(true);
+ expect(stripPastedContent(PASTE_ONLY).text.trim()).toBe('');
+ });
+
+ test('an unclosed harness-shaped tail is stripped; an unclosed non-harness tag is text', () => {
+ expect(stripPastedContent('I moved the sync to Tuesdays. <pasted_content id="7">\nthird party text').text.trim())
+ .toBe('I moved the sync to Tuesdays.');
+ const odd = 'I like tea. <pasted_content source="mail">not the harness shape';
+ expect(stripPastedContent(odd)).toEqual({ text: odd, stripped: 0 });
+ });
+
+ test('several blocks, words around them never merge, look-alike tags are text', () => {
+ const r = stripPastedContent('alpha<pasted_content id="1">x</pasted_content id="1">beta <pasted_content id="2">y</pasted_content id="2"> gamma');
+ expect(r.stripped).toBe(2);
+ expect(r.text.replace(/\s+/g, ' ')).toBe('alpha beta gamma');
+ const lookAlike = 'see <pasted_contents> and <pasted_content_x id="1">kept</pasted_content_x>';
+ expect(stripPastedContent(lookAlike)).toEqual({ text: lookAlike, stripped: 0 });
+ });
+
+ test('text without a paste is returned unchanged', () => {
+ expect(stripPastedContent('plain words')).toEqual({ text: 'plain words', stripped: 0 });
+ });
+});
+
+describe('stripPastedContentFromCorpus — per [user] block', () => {
+ test('an unclosed paste in one user turn does not erase the next turns', () => {
+ const corpus = toCorpusText([
+ { role: 'user', text: 'Note for later: <pasted_content id="3">\nforwarded text that never closes' },
+ { role: 'assistant', text: 'Noted.' },
+ { role: 'user', text: 'I decided to move the standup to 9am every weekday.' },
+ ]);
+ const out = stripPastedContentFromCorpus(corpus);
+ expect(out).not.toContain('forwarded text');
+ expect(out).toContain('[assistant]\nNoted.');
+ expect(out).toContain('[user]\nI decided to move the standup to 9am every weekday.');
+ expect(out).toContain('[user]\nNote for later:');
+ });
+
+ test('assistant blocks are unchanged, and a corpus built from the real transcript loses every paste', () => {
+ const parsed = parseTranscript(FIXTURE);
+ const corpus = toCorpusText(parsed.turns);
+ expect(corpus).toContain(PASTE_MARK);
+ const out = stripPastedContentFromCorpus(corpus);
+ expect(out).not.toContain(PASTE_MARK);
+ expect(out).toContain(OWN_WORDS);
+ for (const t of parsed.turns.filter((turn) => turn.role === 'assistant')) expect(out).toContain(t.text);
+ expect(stripPastedContentFromCorpus('[assistant]\nquoting <pasted_content id="1">x\n')).toBe('[assistant]\nquoting <pasted_content id="1">x\n');
+ });
+
+ test('a writeback turn file is one user turn; other corpus files are stripped per block', () => {
+ const wbText = 'I prefer dark roast coffee. <pasted_content id="2830"> forwarded email </pasted_content id="2830">\n';
+ expect(corpusTextForExtraction('s1.wb-0123456789abcdef01234567.txt', wbText)).not.toContain('forwarded email');
+ expect(corpusTextForExtraction('s1.wb-0123456789abcdef01234567.txt', wbText)).toContain('I prefer dark roast coffee.');
+ expect(corpusTextForExtraction('s1.txt', wbText)).toBe(wbText);
+ });
+});
+
+describe('parser — a paste-only turn is not genuine; rendered text is unchanged', () => {
+ test('genuineUserTurnIndexes skips the paste-only turn', () => {
+ const parsed = parseTranscript(FIXTURE);
+ const userIdx = parsed.turns.flatMap((t, i) => (t.role === 'user' ? [i] : []));
+ expect(userIdx.length).toBe(2);
+ expect(parsed.genuineUserTurnIndexes).toEqual([userIdx[0]]);
+ });
+
+ test('turn text, corpus text and segment text keep the paste byte for byte', async () => {
+ const parsed = parseTranscript(FIXTURE);
+ const users = parsed.turns.filter((t) => t.role === 'user').map((t) => t.text);
+ expect(users).toEqual(userTexts.map((t) => t.trim()));
+ const corpus = toCorpusText(parsed.turns);
+ expect(corpus).toBe(parsed.turns.map((t) => `[${t.role}]\n${t.text}`).join('\n\n') + '\n');
+ expect(corpus).toContain(MIXED.trim());
+ expect(corpus).toContain(PASTE_ONLY.trim());
+ expect((await renderSegmentText(parsed.turns))?.text).toBe(corpus);
+ });
+});