Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(facts): paid conversation fix preview names its targets; envelope fixture at zero price (#6764)

garrytan6346a49287b5
diff --git a/.wave18-fragments/lane3.md b/.wave18-fragments/lane3.md
index 82186b9680..89967552a5 100644
--- a/.wave18-fragments/lane3.md
+++ b/.wave18-fragments/lane3.md
@@ -2,7 +2,7 @@
Lane 3 branch: capy/wave18-lane3. Each section names the target file, the place and the exact text. Version strings use `<WAVE>` for the wave's stamped version.
-## #6740 mention scan masks HTML comments
+## [S2] #6740 mention scan masks HTML comments
### src/core/behavior-change-notice.ts (append to BEHAVIOR_CHANGES)
@@ -18,7 +18,7 @@ Lane 3 branch: capy/wave18-lane3. Each section names the target file, the place
- #6740: cleanup of stale "Discussed in" timeline bullets already written; preview-first repair, next wave.
-## #6742 question type in gbrain-base-v2 (pack 1.4.0)
+## [S2] #6742 question type in gbrain-base-v2 (pack 1.4.0)
### src/core/behavior-change-notice.ts (append to BEHAVIOR_CHANGES)
@@ -36,7 +36,7 @@ Lane 3 branch: capy/wave18-lane3. Each section names the target file, the place
- Pinning a question no longer makes doctor warn about an undeclared `question` page type on the default schema pack (#6742). `gbrain-base-v2` is now 1.4.0.
-## #6720 atom pages inherit the source page's content date
+## [S2] #6720 atom pages inherit the source page's content date
### src/core/behavior-change-notice.ts (append to BEHAVIOR_CHANGES)
@@ -57,7 +57,7 @@ Lane 3 branch: capy/wave18-lane3. Each section names the target file, the place
- No row change: `src/core/cycle/extract-atoms.ts` is 1653 of its 1654 ceiling after this commit.
-## #6731 conversation extractor entity hints
+## [S2] #6731 conversation extractor entity hints
### src/core/behavior-change-notice.ts (append to BEHAVIOR_CHANGES)
@@ -77,7 +77,7 @@ Lane 3 branch: capy/wave18-lane3. Each section names the target file, the place
- `src/commands/extract-conversation-facts.ts` shrinks from 2087 to 2078 in this commit (the two extractor call sites share one input object). Lower its ceiling when the integrator settles the TSV after the later lane 3 commits (the #6764 commit adds a few lines back; see that section).
-## #6764 conversation facts: write-time subject inference and a doctor fix that can act on them
+## [S2] #6764 conversation facts: write-time subject inference and a doctor fix that can act on them
### src/core/behavior-change-notice.ts (append to BEHAVIOR_CHANGES)
@@ -97,7 +97,7 @@ Lane 3 branch: capy/wave18-lane3. Each section names the target file, the place
- New exported symbols (no registry rows needed): `CONVERSATION_FIX_SLUGS` (doctor/checks/unlinked-facts.ts), `inferConversationSubjects` (core/facts/conversation-subject-infer.ts). The `replaces_cross_page_derived` suggestion lives in core/persistence/verb-errors.ts beside the existing `replaces_cross_page` text; no error-registry code was added.
-## #6764 free conversation relink as the doctor's primary fix (decision d1b)
+## [S2] #6764 free conversation relink as the doctor's primary fix (decision d1b)
### src/core/behavior-change-notice.ts (append to BEHAVIOR_CHANGES)
@@ -121,7 +121,7 @@ Lane 3 branch: capy/wave18-lane3. Each section names the target file, the place
- gstack pregate `literals` reports ~643 test locations "still carrying" MENTION_EXTRACTOR_VERSION 5. Every hit except test/mentions-pass.test.ts (fixed to use the symbol) is an unrelated literal 5 (array indexes, model names, counts); no test pins the mention version as a number. The `lanes` check flags this fragment file, which the integrator deletes.
-## #6764 follow-up (v3 review r2-d1)
+## [S2] #6764 follow-up (v3 review r2-d1)
- The free path is `gbrain facts relink --conversation` (a flag on the existing verb). It stays a receipted, database-only linkage of the derived row: `entity_slug` plus the `entity relinked from mention` note on the row itself, one maintenance transaction per page (a `managed_maintenance_conversation_relink` request on a managed brain). Conversation ownership, fact id, provenance and trust are kept and no Markdown is edited, so the doctor envelope asks no consent (`[]`, actor agent; `host_admin` on the remote path). Conversation pages have no `## Facts` fence (canonical projection and the extract_facts reconcile skip extractor rows, #1928), so `FACTS_FENCE_COLUMNS` having no entity column does not matter here.
- `extract-conversation-facts --force` keeps the link: `clearConversationFacts` expires relinked rows instead of deleting them and the replacement row of the same claim inherits the entity (new module `src/core/facts/conversation-relink-carry.ts`). Tested unmanaged and managed with write-time inference off, plus the extract_facts reconcile.
@@ -133,3 +133,11 @@ Lane 3 branch: capy/wave18-lane3. Each section names the target file, the place
- In both #6764 rows, the paid fallback is "capped at the amount the user approves (`--max-cost-usd <N>`)", not "`--max-cost-usd 1`", and the second row should add: "A re-extraction of the page keeps a relinked fact's entity on the claim's new row. Rows the free pass could not resolve no longer count toward doctor's 25% new-fact warning."
+## [S2] #6764 follow-up (final v3 Eng review)
+
+- Paid-fix envelope fixture: test/conversation-reextract-envelope-6764.test.ts runs the free pass, takes doctor's paid fix, runs its preview_argv through the CLI (output names the target page, no model call, facts unchanged), then the real argv with N=1 against a zero-price stubbed provider (pricing.overrides 0/0), and asserts unlinked_facts clears.
+- \`extract-conversation-facts --dry-run --slugs ...\` now prints \`Targets: <slugs>\` (one line; src/commands/extract-conversation-facts.ts is 2080 of its 2087 ceiling, no TSV change).
+- test/trust-write-gate-drift.test.ts gains an EXEMPT row for src/core/facts/conversation-relink.ts (it writes entity_slug and a context note on existing rows, never claim text). The RELINK_REASONS.fence_owned text avoids a hand-built gbrain command (check:agent-contract).
+- The free relink is the trusted-local intent \`managed_maintenance_conversation_relink\` (database-only, no files, no model) on a managed brain; an unmanaged brain has no maintenance coordinator, so it uses the same writeDerivedFacts maintenance transaction as the extractor itself.
+- All Lane 3 rows in this file are S2.
+
diff --git a/docs/guides/facts-relink.md b/docs/guides/facts-relink.md
index 0ad12e0d22..4000669053 100644
--- a/docs/guides/facts-relink.md
+++ b/docs/guides/facts-relink.md
@@ -154,7 +154,7 @@ so doctor `unlinked_facts` then offers a paid re-extraction of its page
| `fence_malformed` | no | The entity page has a ## Facts fence that cannot be normalized. Preview the fence repair of that page (`repair fences --slug <entity-slug>` on the brain host; read-only, and it names the exact edit for anything it will not repair), apply it, then rerun. |
| `claim_unfenceable` | no | The claim text cannot be written to a fence row unchanged (for example it is wrapped in ~~). Forget it and remember a cleaned-up claim with --entity. |
| `visibility_conflict` | no | The entity already has the same claim from the same source with the other visibility, and a page indexes only one. Forget the copy you do not want, then rerun. |
-| `fence_owned` | no | The fact lives in another page fence or is a conversation page's extracted fact. Relink does not move fence-owned facts; link conversation facts with gbrain facts relink --conversation (free, preview with --dry-run). |
+| `fence_owned` | no | The fact lives in another page fence or is a conversation page's extracted fact. Relink does not move fence-owned facts; conversation facts are linked by relink with --conversation (free, preview with --dry-run). |
| `budget_exhausted` | no | The model tier reached --max-usd. Raise --max-usd (or pass off) and rerun with the printed continuation command. |
| `revision_conflict` | no | The fact or the entity page changed while relink ran. Rerun. |
diff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.ts
index 46eb291397..5012e048f3 100644
--- a/src/commands/extract-conversation-facts.ts
+++ b/src/commands/extract-conversation-facts.ts
@@ -1974,6 +1974,7 @@ export async function runExtractConversationFacts(
`in ${sourceIds.length} source(s). ` +
`Spent ~$${totalSpent.toFixed(4)}.`,
);
+ if (parsed.dryRun && parsed.slugs?.length) console.log(` Targets: ${parsed.slugs.join(', ')}`); // #6764: the preview names what the paid run would re-extract
if (aggregate.pages_skipped > 0) {
console.log(` Skipped ${aggregate.pages_skipped} page(s) without eligible segments or outside the selected types:`);
console.log(` ${aggregate.pages_skipped_unparsed} with no parseable speaker turns (retryable); ${aggregate.pages_skipped_type_mismatch} with a type mismatch; ${aggregate.pages_skipped_insufficient_turns} with insufficient turns; ${aggregate.pages_skipped_since} with no eligible segments after --since; ${aggregate.pages_skipped_unrecognized_speaker} declined for speaker attribution.`);
diff --git a/src/core/facts/relink-reasons.ts b/src/core/facts/relink-reasons.ts
index 3aaa0cc3c6..c2662731d5 100644
--- a/src/core/facts/relink-reasons.ts
+++ b/src/core/facts/relink-reasons.ts
@@ -18,7 +18,7 @@ export const RELINK_REASONS = {
fence_malformed: { memoized: false, fix: 'The entity page has a ## Facts fence that cannot be normalized. Preview the fence repair of that page (`repair fences --slug <entity-slug>` on the brain host; read-only, and it names the exact edit for anything it will not repair), apply it, then rerun.' },
claim_unfenceable: { memoized: false, fix: 'The claim text cannot be written to a fence row unchanged (for example it is wrapped in ~~). Forget it and remember a cleaned-up claim with --entity.' },
visibility_conflict: { memoized: false, fix: 'The entity already has the same claim from the same source with the other visibility, and a page indexes only one. Forget the copy you do not want, then rerun.' },
- fence_owned: { memoized: false, fix: 'The fact lives in another page fence or is a conversation page\'s extracted fact. Relink does not move fence-owned facts; link conversation facts with gbrain facts relink --conversation (free, preview with --dry-run).' },
+ fence_owned: { memoized: false, fix: 'The fact lives in another page fence or is a conversation page\'s extracted fact. Relink does not move fence-owned facts; conversation facts are linked by relink with --conversation (free, preview with --dry-run).' },
budget_exhausted: { memoized: false, fix: 'The model tier reached --max-usd. Raise --max-usd (or pass off) and rerun with the printed continuation command.' },
revision_conflict: { memoized: false, fix: 'The fact or the entity page changed while relink ran. Rerun.' },
} as const satisfies Record<string, { memoized: boolean; fix: string }>;
diff --git a/test/conversation-reextract-envelope-6764.test.ts b/test/conversation-reextract-envelope-6764.test.ts
new file mode 100644
index 0000000000..c22884a4ed
--- /dev/null
+++ b/test/conversation-reextract-envelope-6764.test.ts
@@ -0,0 +1,95 @@
+/**
+ * #6764 envelope fixture for the paid conversation fix: after the free
+ * conversation relink has tried a page's unlinked facts and could not resolve
+ * one, doctor `unlinked_facts` offers the paid re-extraction. Its
+ * `preview_argv` names the target page and writes nothing (no model call);
+ * its real `argv`, with the approved amount `N` filled in, runs through the
+ * CLI against a zero-price stubbed provider and the verify check clears.
+ * Hermetic: PGLite plus gateway test transports; no network or keys.
+ */
+import { afterAll, beforeAll, expect, spyOn, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { __setChatTransportForTests, configureGateway, resetGateway, type ChatResult } from '../src/core/ai/gateway.ts';
+import { runExtractConversationFacts } from '../src/commands/extract-conversation-facts.ts';
+import { runConversationRelink } from '../src/core/facts/conversation-relink.ts';
+import { unlinkedFactsStats, unlinkedFactsVerdict } from '../src/commands/doctor/checks/unlinked-facts.ts';
+import { cliRenderContext, renderAction } from '../src/core/agent-output.ts';
+
+const MODEL = 'litellm:zero-price-chat';
+const MEETING = 'meetings/2026-08-12-lease-review';
+const TRANSCRIPT = [
+ '**Owner Example** (2026-08-12 10:00 AM): Alice Example signed the lease renewal yesterday.',
+ '**Beta Example** (2026-08-12 10:01 AM): Good, she starts in September.',
+].join('\n');
+const config = { engine: 'pglite', embedding_disabled: true } as never;
+
+let engine: PGLiteEngine;
+let chatCalls = 0;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ resetGateway();
+ configureGateway({ chat_model: MODEL, embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536,
+ base_urls: { litellm: 'http://localhost:4000' }, env: { LITELLM_BASE_URL: 'http://localhost:4000', OPENAI_API_KEY: 'test' } });
+ __setChatTransportForTests(async (): Promise<ChatResult> => {
+ chatCalls++;
+ return { text: JSON.stringify({ facts: [{ fact: 'Alice Example signed the lease renewal', kind: 'event', entity: 'people/alice-example', confidence: 1, notability: 'high' }] }),
+ blocks: [], stopReason: 'end', usage: { input_tokens: 100, output_tokens: 50, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: MODEL, providerId: 'litellm' };
+ });
+ await engine.setConfig('facts.extraction_enabled', 'true');
+ await engine.setConfig('facts.extraction_model', MODEL);
+ await engine.setConfig('conversation_parser.llm_fallback_enabled', 'false');
+ await engine.setConfig('pricing.overrides', JSON.stringify({ [MODEL]: { input: 0, output: 0 } }));
+ await engine.setConfig('embedding.disabled', 'true');
+ await engine.putPage(MEETING, { type: 'meeting' as never, title: 'Lease review', compiled_truth: TRANSCRIPT, timeline: '', frontmatter: { date: '2026-08-12' } });
+ await engine.putPage('people/alice-example', { type: 'person' as never, title: 'Alice Example', compiled_truth: '# Alice Example', timeline: '', frontmatter: {} });
+ // An older extractor stored this fact with no entity; no entity page is named in it, so the free relink cannot resolve it.
+ await engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, source, context, row_num, source_markdown_slug, created_at, valid_from)
+ VALUES ('default', NULL, 'She signed the lease renewal', 'cli:extract-conversation-facts', $1, 0, $2, now(), now())`, [`from ${MEETING} segment 2026-08-12`, MEETING]);
+}, 60_000);
+
+afterAll(async () => {
+ __setChatTransportForTests(null);
+ resetGateway();
+ await engine.disconnect();
+});
+
+const facts = () => engine.executeRaw<{ id: number; fact: string; entity_slug: string | null; expired_at: string | null }>(
+ 'SELECT id, fact, entity_slug, expired_at FROM facts ORDER BY id');
+
+async function run(argv: string[]): Promise<string> {
+ const lines: string[] = [];
+ const log = spyOn(console, 'log').mockImplementation((s: unknown) => { lines.push(String(s)); });
+ const err = spyOn(process.stderr, 'write').mockImplementation(() => true);
+ const exit = spyOn(process, 'exit').mockImplementation(((code?: number) => { throw new Error(`process.exit(${code})`); }) as never);
+ try { await runExtractConversationFacts(engine, argv); } finally { log.mockRestore(); err.mockRestore(); exit.mockRestore(); }
+ return lines.join('\n');
+}
+
+test('free pass, then the paid fix: preview names its target and writes nothing; the filled argv runs at zero price and verify clears', async () => {
+ expect(await runConversationRelink(engine, config, { sourceId: 'default' })).toMatchObject({ linked: 0, unresolved: 1 });
+ const before = unlinkedFactsVerdict(await unlinkedFactsStats(engine, ['default']));
+ const fix = before.fix!;
+ expect(before.details).toMatchObject({ conversation: { fix: 'reextract', slugs: [MEETING] } });
+ expect(fix).toMatchObject({ consent: ['paid', 'egress'], ask_user: true, inputs: [{ name: 'N' }] });
+ expect(renderAction(fix as never, cliRenderContext()).next).toBe('ask_user');
+
+ const untouched = await facts();
+ const preview = await run(fix.preview_argv!.slice(2));
+ expect(preview).toContain('(dry run)');
+ expect(preview).toContain(`Targets: ${MEETING}`);
+ expect(chatCalls).toBe(0);
+ expect(await facts()).toEqual(untouched);
+
+ const out = await run(fix.argv!.slice(2).map(a => a === '<N>' ? '1' : a));
+ expect(out).toContain('Spent ~$0.0000');
+ expect(chatCalls).toBeGreaterThan(0);
+ const live = (await facts()).filter(f => f.expired_at === null && !f.fact.startsWith('EXTRACTION_'));
+ expect(live.map(f => [f.fact, f.entity_slug])).toEqual([['Alice Example signed the lease renewal', 'people/alice-example']]);
+
+ const after = unlinkedFactsVerdict(await unlinkedFactsStats(engine, ['default']));
+ expect(after.fix).toBeUndefined();
+ expect((after.details as { conversation: unknown }).conversation).toBeNull();
+});
diff --git a/test/trust-write-gate-drift.test.ts b/test/trust-write-gate-drift.test.ts
index 4dad52a54f..f4bc3fb3d5 100644
--- a/test/trust-write-gate-drift.test.ts
+++ b/test/trust-write-gate-drift.test.ts
@@ -68,6 +68,7 @@ const EXEMPT: Record<string, string> = {
'src/core/trust/owner-actions.ts': 'owner release publishes a held row the owner confirmed (CEO-9); the gate already held it',
'src/core/trust/supersede-handlers.ts': 'owner accept/undo re-tiers existing rows inside the checked supersede',
'src/core/repair/conversation-labels.ts': 'owner repair of existing conversation labels',
+ 'src/core/facts/conversation-relink.ts': 'free conversation relink sets entity_slug and a context note on existing derived rows; no claim text is written, so there is nothing for the gate to judge',
'src/commands/extract-conversation-facts.ts': 'extracted rows go through insertDerivedFacts (persistence/derived-facts.ts), which gates them; its direct writes are gbrain audit outcome rows',
'src/core/cycle/dream-taint.ts': 'the dream summary index page lists the run\'s output pages (gbrain-generated), stamped at their taint',
'src/core/facts/fence-write.ts': 'callers decide the gate (backstop, loops-extract) and pass the decision; it records the flag receipt on the new row',