Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(facts): ambient writeback no longer saves lines the user quoted as the user's own
garrytana7e995ffd7be
diff --git a/docs/architecture/key-files/agent-bootstrap-continued.md b/docs/architecture/key-files/agent-bootstrap-continued.mdindex a00c137d02..749ac36861 100644--- a/docs/architecture/key-files/agent-bootstrap-continued.md+++ b/docs/architecture/key-files/agent-bootstrap-continued.md@@ -15,7 +15,7 @@- `src/core/facts/writeback-settings.ts` — GBRA-219: the DB-only `memory.agent_writeback` override (inherit | off | salient | all) of the mode AGENTS are told to follow. `resolveAgentWriteback` wraps the operator resolver and is what the three initialize transports render; an unreadable or invalid override, or an operator read failure with no last-known-good, fails closed to off (never inherits a wider mode). It never feeds `captureGateDecision`, so the capture lanes stay on `memory.auto_writeback`. `writeAgentWriteback` writes the setting and a `memory_setting_change` request-log row in one transaction under an advisory lock. Kept out of writeback-config.ts because the engine-free hook children import that file.- `src/core/ops/memory-settings.ts` — `get_memory_settings` (read), `set_memory_writeback` (admin scope + `mcp.publish_memory_settings` publish gate; writes only the override), `memory_conversation_mode` (write scope, callable where `remember` is; stores nothing; no enum auto-repair because `mutating` is unset). Guide: `docs/guides/ambient-writeback.md#reading-and-changing-it-remotely`.- `src/core/facts/writeback-instructions.ts` — the ONE ~15-line instruction-section builder feeding BOTH the MCP `instructions` composition and the bootstrap-managed harness blocks (surfaces structurally cannot drift). Mode-conditional candidate policy, literal resolved TTL, surface-honest extract_facts mention, visibility posture with the "world = agents on this brain, not the public internet / never widen" rule; the private posture states its consequence to the agent (it and every other MCP/HTTP session cannot recall or forget a fact it saves as private).- - `src/core/facts/writeback-gate.ts` — the engine-free zero-LLM Stop-hook salience gate: frozen skip-reason vocabulary (`empty`/`too_short` [CJK-aware 20→10 floor]/`ack_or_greeting`/`slash_command`/`question_only`/`quoted_or_tool_output`/`bulk_paste` >8KB/`pasted_content`), first hit wins; after the length checks every Claude Code paste block is stripped (`pasted-content.ts`) and the remaining rules plus the banked text see only the user's own words (a paste-only turn is `pasted_content`); ok returns the NFC/collapsed normalized text + sha256-hash24 — the turn's idempotency key (same turn ⇒ same `.wb-` filename ⇒ embedding-free dedup that works keyless).+ - `src/core/facts/writeback-gate.ts` — the engine-free zero-LLM Stop-hook salience gate: frozen skip-reason vocabulary (`empty`/`too_short` [CJK-aware 20→10 floor]/`ack_or_greeting`/`slash_command`/`question_only`/`quoted_or_tool_output`/`bulk_paste` >8KB/`pasted_content`), first hit wins; after the length checks every Claude Code paste block is stripped (`pasted-content.ts`) and the remaining rules plus the banked text see only the user's own words (a paste-only turn is `pasted_content`); an accepted turn banks without its `>` quote lines outside backtick or tilde fences (#8410); ok returns the NFC/collapsed normalized text + sha256-hash24 — the turn's idempotency key (same turn ⇒ same `.wb-` filename ⇒ embedding-free dedup that works keyless).- `src/core/facts/writeback-audience.ts` — personal-vs-shared classifier for the consent nudge. Declaration (`brain.audience`, stamped by company-brainify's Phase-5 handoff, the bootstrap interview's SURFACE_MULTIUSER answer — applied the moment `interview --set` records it, BEFORE the agent runs init — or the operator) BEATS the conservative heuristic (≥3 distinct non-automation MCP clients active 30d via `mcp-usage.ts`, `likely_automation` excluded); `reasons[]` always names the evidence. The machine-global file-mirror declaration speaks for the HOST brain only — a mounted/selected brain falls through to its own DB row or heuristic. Fail directions: config read failure → `unknown` (nudge stays silent), usage-read failure with a reachable DB → `personal` (missing multi-client infra is personal-shaped). Never enables anything.- `src/core/onboard/writeback-nudge.ts` — the fire-once consent ASK (init epilogue + `runPostUpgrade`): double gate (sentinel `memory.auto_writeback_notice_shown` + setting unset), personal-audience only, suppressed on mounts/thin-clients/env bypass, `[AGENT]`-relayed disclosure + ask (non-TTY IS the relay path — deliberately unlike runInitNudge), sentinel stamped AFTER printing (a decline is permanent; a shared classification does NOT burn the sentinel), whole body try/caught (init/upgrade must survive a crashing nudge). The recurring reminder is `src/core/advisor/collect-writeback-consent.ts` (info, `ask_user`, NO dispatch_id — consent is never `--apply`-able; local-only; fires only AFTER the sentinel so the advisor is never the first ask).- `src/core/bootstrap/instructions-block.ts` — the managed harness block (`<!-- gbrain:ambient-writeback:begin/end -->`): spliceCompiledBlock discipline verbatim (idempotent replace-interior, THROW on damaged markers, marker-equal body lines neutralized), header names mode + serve endpoint (multi-brain last-wins stays visible), remove/strip helpers never delete a user file. Harness lane (`src/core/bootstrap/harness.ts`): `kind:'instructions'` targets (additive under receipt version 1 — old binaries won't unwire them, documented) for user-scope CLAUDE.md + `$CODEX_HOME/AGENTS.md` (paths + the AGENTS.override.md exclusivity probe are dated PROVISIONAL spec entries in `host-specs.ts`); enabled ⇒ install, disabled ⇒ CONVERGE (strip blocks + receipt targets + advisory line; a strip FAILURE is recorded as a failed `instructions` receipt target so --status/--remove/the next converge keep tracking the orphan); registrar mode (non-loopback --url) NEVER installs blocks — the local mirror speaks for the local brain, and the remote brain's own MCP instructions carry the contract when its operator opts in; a block installs only when the SAME host's MCP target confirmed (both lanes — a foreign-registration refusal or failed write must not leave a block directing saves at a server this run never registered), and a failed final smoke STRIPS the blocks this run installed (targets marked failed) so no block outlives its rolled-back registration; `--remove`/`--status` wired.diff --git a/src/core/facts/writeback-gate.ts b/src/core/facts/writeback-gate.tsindex 3492b7760f..11cb605233 100644--- a/src/core/facts/writeback-gate.ts+++ b/src/core/facts/writeback-gate.ts@@ -58,9 +58,12 @@ const ACK_PHRASE ='(thanks|thank you|thx|ty|ok(ay)?|k+|sure|yes|yep|yeah|no|nope|got it|sounds good|great|perfect|nice|cool|awesome|good (morning|afternoon|evening|night)|hi|hello|hey|bye|goodbye|see you|lgtm|will do|done|please (do|continue)|go ahead|continue|proceed|stop|cancel|never ?mind|nvm|please|so much|a lot)';const ACK_RE = new RegExp(`^${ACK_PHRASE}((\\s|,)+${ACK_PHRASE})*$`);+/** A '>' quote line; '>90%' or '>= 3' is the user's own comparison, not a quote. */+const QUOTE_LINE_RE = /^\s*>(?:\s|>|$)/;+function stripQuotedAndToolOutput(text: string): string {// Fenced code blocks.- let out = text.replace(/```[\s\S]*?(```|$)/g, ' ');+ let out = text.replace(/(```|~~~)[\s\S]*?(\1|$)/g, ' ');const lines = out.split('\n');const kept: string[] = [];let indentRun: string[] = [];@@ -71,7 +74,7 @@ function stripQuotedAndToolOutput(text: string): string {indentRun = [];};for (const line of lines) {- if (line.trimStart().startsWith('>')) continue; // quoted material+ if (QUOTE_LINE_RE.test(line)) continue; // quoted materialif (/^\s{4,}\S/.test(line)) { indentRun.push(line); continue; }flushRun();kept.push(line);@@ -80,6 +83,24 @@ function stripQuotedAndToolOutput(text: string): string {return kept.join('\n');}+const FENCE_RE = /^ {0,3}(`{3,}|~{3,})(.*)$/;++function dropQuotedLines(text: string): string {+ let fence = '';+ return text.split('\n').filter((line) => {+ const m = FENCE_RE.exec(line);+ if (fence) {+ if (m && m[1][0] === fence[0] && m[1].length >= fence.length && m[2].trim() === '') fence = '';+ return true;+ }+ if (m && !(m[1][0] === '`' && m[2].includes('`'))) {+ fence = m[1];+ return true;+ }+ return !QUOTE_LINE_RE.test(line);+ }).join('\n');+}+/** NFC + trim + collapse whitespace runs — the canonical form the hash and* downstream extraction both see. */export function normalizeTurnText(text: string): string {@@ -142,6 +163,7 @@ export function gateWritebackTurn(text: unknown): WritebackGateResult {return { ok: false, reason: 'quoted_or_tool_output' };}- const normalized = normalizeTurnText(own);+ // Quoted lines are someone else's words (#8410): bank only the rest.+ const normalized = normalizeTurnText(dropQuotedLines(own));return { ok: true, normalized, hash24: turnHash24(normalized) };}diff --git a/test/facts/writeback-gate.test.ts b/test/facts/writeback-gate.test.tsindex 3943cea814..cbd26c8a75 100644--- a/test/facts/writeback-gate.test.ts+++ b/test/facts/writeback-gate.test.ts@@ -64,6 +64,26 @@ describe('gateWritebackTurn — skip rules, first hit wins', () => {expect(gateWritebackTurn(withResidue).ok).toBe(true);});+ test('#8410: an accepted turn banks and hashes only the unquoted lines; fenced lines stay', () => {+ const own = 'No, we deploy on Tuesdays and staging uses Postgres 17.';+ const quoted = gateWritebackTurn(`> The deploy moves to Fridays.\n\n${own}`);+ expect(quoted).toEqual({ ok: true, normalized: own, hash24: turnHash24(own) });++ const backtick = gateWritebackTurn(`${own}\n\`\`\`\`\n> code line\n\`\`\`\n> still code\n\`\`\`\`\n> quoted after`);+ expect(backtick.ok && backtick.normalized).toBe(`${own} \`\`\`\` > code line \`\`\` > still code \`\`\`\``);++ const tilde = gateWritebackTurn(`${own}\n~~~text\n> tilde code\n~~~\n> quoted after`);+ expect(tilde.ok && tilde.normalized).toBe(`${own} ~~~text > tilde code ~~~`);++ const comparison = gateWritebackTurn(`${own}\n>90% of our traffic is EU.\n>> The deploy moves to Fridays.`);+ expect(comparison.ok && comparison.normalized).toBe(`${own} >90% of our traffic is EU.`);+ });++ test('#8410: a turn that is only quoted lines plus a tilde-fenced paste is quoted material', () => {+ const turn = '> Alice wrote: the deploy failed\n~~~\nERROR: connection refused at db.example:5432\nstack trace line line line\n~~~';+ expect(gateWritebackTurn(turn)).toEqual({ ok: false, reason: 'quoted_or_tool_output' });+ });+test('bulk paste over the cap → bulk_paste (imported text needs an explicit ask)', () => {const big = 'a decision was made. '.repeat(500); // > 8000 charsexpect(big.length).toBeGreaterThan(MAX_TURN_CHARS);