Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: review follow-ups for the wave (#7405 #7396)
garrytan4c4493455e6c
diff --git a/docs/architecture/key-files/core-services-3.md b/docs/architecture/key-files/core-services-3.mdindex 3dfb44560f..13887b09b6 100644--- a/docs/architecture/key-files/core-services-3.md+++ b/docs/architecture/key-files/core-services-3.md@@ -13,7 +13,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/think/intent.ts` + `src/core/think/entity-extract.ts` — pure `classifyIntent(question)` returns `'temporal' | 'knowledge_update' | 'other'` (regex-first, no LLM, `'other'` fast path short-circuits with zero SQL). `extractCandidateEntities(question, retrievedSlugs)` pulls high-precision candidates from retrieved entity-prefix slugs (`people/`, `companies/`, `organizations/`) and medium-precision noun phrases. Stop-word boundaries + leading-verb stripper handle "When did I last meet Marco" → `marco`. Both consumed by `runThink` and the LongMemEval harness so the two paths cannot drift. Pinned by `test/think-intent.test.ts` and `test/think-entity-extract.test.ts`.-- `src/core/transcripts/` (directory) — the transcript-adapter seam. `types.ts`: the `TranscriptAdapter` contract — `parse(path): AsyncGenerator<ParsedSession, FileDiagnostics>` (one FILE may hold many sessions; the generator RETURN value carries bytes/skipped-lines/zero-session diagnostics so an empty file explains itself), format-specific byte caps (JSONL 50MB hard cap — the 10MB default in `claude-code-jsonl.ts` belongs to the hook-lane tail reader, not imports; monolithic export JSON rejects-not-truncates at 200MB), and the ONE `buildTranscriptSlug` helper (per-provider dirs matching the conversation-archive layout; id suffixes are sha256 prefixes of the session id — hash12 in slugs, hash16 for the dedup identity — never a cleaned prefix of the source id, which would let same-prefix session ids collide). `detect.ts`: adapter registry + head-sample detection (filesystem admission first for every path, explicit format included: symlinks lstat-rejected, an unreadable path carries its `errno`, which ingest copies to the file outcome with a per-cause next step; then the explicit format wins without sniffing) + injectable `harnessRoots` (the confined discovery surface). Adapters, each with a DATED `SPEC_TARGET` + scrubbed fixture + `bytes>0 && sessions==0` drift alarm: `claude-code.ts` (thin wrapper over the shipped `claude-code-jsonl.ts`, which also exposes the full-file `parseClaudeSessionFile` with real per-message timestamps — hook-lane `parseTranscript` output is pinned byte-identical; owns `isClaudeCodeSubagentFile` (a literal `subagents` path segment at ANY depth + `agent-*.jsonl` basename — both `<session>/subagents/agent-*.jsonl` and the workflow-nested `<session>/subagents/workflows/<wf>/agent-*.jsonl` are all-sidechain, zero-turn files carrying the PARENT session id; a project slug containing "subagents" is one segment and never matches) and `isClaudeCodeWorkflowArtifactFile` (everything under `<session>/subagents/workflows/<wf>/` — the agent logs plus the `journal.jsonl` run log that matches no adapter format; a UUID-named session directly under `subagents/` stays discoverable); `discover.ts` and the CLI's `expandPaths` skip both, so they never read as gap-table backlog, drift, or `unknown format` errors that hold the since-last watermark frozen; the adapter sets `expectedEmpty` when zero accepted turn-shaped records and zero skipped lines remain after root metadata/sidechain and explicit non-human user-text filtering. Metadata-only, non-human-text-only, and all-subagent files are understood empties and do not freeze the watermark; accepted turn records that yield no text and unparseable lines still signal drift. Pinned by `test/claude-code-jsonl-origin.test.ts`), `codex.ts` (turn selection is STRUCTURAL: user turns from `event_msg` user_message (through 0.152) or `event_msg` item_completed with item.type UserMessage, text blocks only (0.153+, #5163; a turn recorded in both shapes is kept once, other item types incl. AgentMessage skipped), assistant from `response_item` output_text; a file with assistant turns and zero user turns sets `FileDiagnostics.userTurnsMissing` (codex and claude-code; E-N4), which ingest counts as drift and the session-end hook heartbeats as `degraded`/`no_user_turns` on whole-file reads (pinned by `test/codex-rollout-0154.serial.test.ts`); role user/developer response_items are injected preambles and never leak; identity is `payload.id` — the per-thread id codex embeds in the rollout filename — with `payload.session_id` (the ROOT session shared by every forked/subagent thread) only as the legacy fallback, and the FIRST `session_meta` header wins because a child rollout carries its inherited parent header later in the file; the hook lane's `parseCodexHookTranscript` follows the same two rules), `openclaw.ts` (session header + message lines; `.checkpoint.*.jsonl` snapshots rejected), `hermes.ts` (COPY-THEN-READ of state.db + wal/shm sidecars — readonly WAL opens need -shm write access and lock against a live writer; schema from the installed hermes-agent source; `json:`-prefixed and bare block arrays unwrap to text, image blocks to `[image]`; #7396: the answered responses of a submitted `clarify` tool result (`role=tool`, `tool_name=clarify`; `outcome: submitted` + `status: answered`, or the earlier batch shape without `timed_out`) import as user turns at the result's timestamp, with the question and tool-call id as flat `clarify_<n>_*` raw keys, while offered choices, unanswered/cancelled forms, the legacy single-question shape and other tool rows never do; pinned by `test/hermes-clarify-transcripts-7396.test.ts`; PROVISIONAL), `grok.ts` (Grok Build session dirs — structural turn selection, sidecar-aware discovery; see its own entry), `chatgpt-export.ts` (the `mapping`-tree current_node walk; branches dropped by design, orphaned parents terminate quietly, latest-leaf fallback; extracted conversations.json only) + `claude-export.ts` (flat chat_messages); both export adapters load through the shared `export-json.ts` (monolithic JSON over the cap REJECTS with a split hint; a zip or wrong-shape file gets the unzip-first hint) and give id-less conversations content-derived fallback ids so two id-less exports cannot dedup-skip or overwrite each other. `render.ts`: session → part pages — imessage-slack line format with the regex IMPORTED from `conversation-parser/builtins.ts` (round-trip pinned), REAL timestamps (missing ones carry forward; zero-timestamp sessions refused — provenance is never fabricated), anchor-shaped BODY lines backslash-escaped (hostile message content cannot forge speakers), quoted facts/takes fence-marker tokens backslash-escaped at the same per-message seam (`gbrain\:facts:begin` — a session that read another page cannot plant a live or unbalanced fence on the transcript page; every fence consumer is a substring matcher, so the escape lands inside the token), fail-closed redaction (secret-scan + `harvest-private-patterns.txt` user patterns, slack-channel default excluded because it eats issue refs; imperatives COUNTED into hash-covered `transcript_import` frontmatter, never content_flag), message-boundary splitting at `PART_TARGET_BYTES` = 45,000 bytes (0.9 × the 50,000-byte content-sanity warn line, so no part takes the oversize-warn branch; far under the embed-skip threshold) with 2-message overlap, part 1 keeps the base slug, `frontmatter.id` unique per part. `ingest.ts`: the engine-facing core — a session whose part-1 `frontmatter.id` already has a live page imports at that page's slug (a renamed or re-dated conversation updates in place instead of being skipped as a cross-slug duplicate), SESSION atomicity (a failed session records its `classifyItemFailure` code and the run continues; a part the coordinator accepted but has not published leaves the session pending under a request id derived from source, slug, revision and content, so a rerun waits on that write and a write that ended without committing is retried under the next attempt id; only run-scoped failures and the `item_failures_systemic` breaker abort the run, GBRA-130 A-2, pinned by `test/pathological/a2-transcripts-ingest.test.ts`), stale-part reconciliation (deletes `part > of` leftovers), session metadata banked in the base page's raw_data as the REDACTED copy and healed by content-compare even on hash-skipped re-runs (a run that died before `putRawData`, or a private pattern added after first import, repairs on the next pass), `cleanScan`/`maxSessionTs` for the watermark. `ingest-facts.ts`: ONE `runExtractConversationFactsCore` invocation (batch `slugs` selector) inside ONE `withBudgetTracker`, `isFactsExtractionEnabled` pre-checked. Pinned by `test/transcript-adapters.test.ts`, `test/transcript-render.test.ts`, `test/transcripts-retitle.test.ts`, `test/transcripts-ingest-pglite.test.ts`, `test/e2e/transcripts-writeback-fidelity.test.ts` (raw files through the adapters into the gold-extractor facts path).+- `src/core/transcripts/` (directory) — the transcript-adapter seam. `types.ts`: the `TranscriptAdapter` contract — `parse(path): AsyncGenerator<ParsedSession, FileDiagnostics>` (one FILE may hold many sessions; the generator RETURN value carries bytes/skipped-lines/zero-session diagnostics so an empty file explains itself), format-specific byte caps (JSONL 50MB hard cap — the 10MB default in `claude-code-jsonl.ts` belongs to the hook-lane tail reader, not imports; monolithic export JSON rejects-not-truncates at 200MB), and the ONE `buildTranscriptSlug` helper (per-provider dirs matching the conversation-archive layout; id suffixes are sha256 prefixes of the session id — hash12 in slugs, hash16 for the dedup identity — never a cleaned prefix of the source id, which would let same-prefix session ids collide). `detect.ts`: adapter registry + head-sample detection (filesystem admission first for every path, explicit format included: symlinks lstat-rejected, an unreadable path carries its `errno`, which ingest copies to the file outcome with a per-cause next step; then the explicit format wins without sniffing) + injectable `harnessRoots` (the confined discovery surface). Adapters, each with a DATED `SPEC_TARGET` + scrubbed fixture + `bytes>0 && sessions==0` drift alarm: `claude-code.ts` (thin wrapper over the shipped `claude-code-jsonl.ts`, which also exposes the full-file `parseClaudeSessionFile` with real per-message timestamps — hook-lane `parseTranscript` output is pinned byte-identical; owns `isClaudeCodeSubagentFile` (a literal `subagents` path segment at ANY depth + `agent-*.jsonl` basename — both `<session>/subagents/agent-*.jsonl` and the workflow-nested `<session>/subagents/workflows/<wf>/agent-*.jsonl` are all-sidechain, zero-turn files carrying the PARENT session id; a project slug containing "subagents" is one segment and never matches) and `isClaudeCodeWorkflowArtifactFile` (everything under `<session>/subagents/workflows/<wf>/` — the agent logs plus the `journal.jsonl` run log that matches no adapter format; a UUID-named session directly under `subagents/` stays discoverable); `discover.ts` and the CLI's `expandPaths` skip both, so they never read as gap-table backlog, drift, or `unknown format` errors that hold the since-last watermark frozen; the adapter sets `expectedEmpty` when zero accepted turn-shaped records and zero skipped lines remain after root metadata/sidechain and explicit non-human user-text filtering. Metadata-only, non-human-text-only, and all-subagent files are understood empties and do not freeze the watermark; accepted turn records that yield no text and unparseable lines still signal drift. Pinned by `test/claude-code-jsonl-origin.test.ts`), `codex.ts` (turn selection is STRUCTURAL: user turns from `event_msg` user_message (through 0.152) or `event_msg` item_completed with item.type UserMessage, text blocks only (0.153+, #5163; a turn recorded in both shapes is kept once, other item types incl. AgentMessage skipped), assistant from `response_item` output_text; a file with assistant turns and zero user turns sets `FileDiagnostics.userTurnsMissing` (codex and claude-code; E-N4), which ingest counts as drift and the session-end hook heartbeats as `degraded`/`no_user_turns` on whole-file reads (pinned by `test/codex-rollout-0154.serial.test.ts`); role user/developer response_items are injected preambles and never leak; identity is `payload.id` — the per-thread id codex embeds in the rollout filename — with `payload.session_id` (the ROOT session shared by every forked/subagent thread) only as the legacy fallback, and the FIRST `session_meta` header wins because a child rollout carries its inherited parent header later in the file; the hook lane's `parseCodexHookTranscript` follows the same two rules), `openclaw.ts` (session header + message lines; `.checkpoint.*.jsonl` snapshots rejected), `hermes.ts` (COPY-THEN-READ of state.db + wal/shm sidecars — readonly WAL opens need -shm write access and lock against a live writer; schema from the installed hermes-agent source; `json:`-prefixed and bare block arrays unwrap to text, image blocks to `[image]`; #7396: the answered responses of a `clarify` tool result (`role=tool`, `tool_name=clarify`; `status: answered` under `outcome: submitted` or `timed_out`, whose locked answers Hermes keeps, or the earlier batch shape without `timed_out`) import as user turns at the result's timestamp, each after its question as an assistant turn, with the question and tool-call id as flat `clarify_<n>_*` raw keys, while offered choices, unanswered responses, cancelled/undelivered forms, the legacy single-question shape and other tool rows never do; pinned by `test/hermes-clarify-transcripts-7396.test.ts`; PROVISIONAL), `grok.ts` (Grok Build session dirs — structural turn selection, sidecar-aware discovery; see its own entry), `chatgpt-export.ts` (the `mapping`-tree current_node walk; branches dropped by design, orphaned parents terminate quietly, latest-leaf fallback; extracted conversations.json only) + `claude-export.ts` (flat chat_messages); both export adapters load through the shared `export-json.ts` (monolithic JSON over the cap REJECTS with a split hint; a zip or wrong-shape file gets the unzip-first hint) and give id-less conversations content-derived fallback ids so two id-less exports cannot dedup-skip or overwrite each other. `render.ts`: session → part pages — imessage-slack line format with the regex IMPORTED from `conversation-parser/builtins.ts` (round-trip pinned), REAL timestamps (missing ones carry forward; zero-timestamp sessions refused — provenance is never fabricated), anchor-shaped BODY lines backslash-escaped (hostile message content cannot forge speakers), quoted facts/takes fence-marker tokens backslash-escaped at the same per-message seam (`gbrain\:facts:begin` — a session that read another page cannot plant a live or unbalanced fence on the transcript page; every fence consumer is a substring matcher, so the escape lands inside the token), fail-closed redaction (secret-scan + `harvest-private-patterns.txt` user patterns, slack-channel default excluded because it eats issue refs; imperatives COUNTED into hash-covered `transcript_import` frontmatter, never content_flag), message-boundary splitting at `PART_TARGET_BYTES` = 45,000 bytes (0.9 × the 50,000-byte content-sanity warn line, so no part takes the oversize-warn branch; far under the embed-skip threshold) with 2-message overlap, part 1 keeps the base slug, `frontmatter.id` unique per part. `ingest.ts`: the engine-facing core — a session whose part-1 `frontmatter.id` already has a live page imports at that page's slug (a renamed or re-dated conversation updates in place instead of being skipped as a cross-slug duplicate), SESSION atomicity (a failed session records its `classifyItemFailure` code and the run continues; a part the coordinator accepted but has not published leaves the session pending under a request id derived from source, slug, revision and content, so a rerun waits on that write and a write that ended without committing is retried under the next attempt id; only run-scoped failures and the `item_failures_systemic` breaker abort the run, GBRA-130 A-2, pinned by `test/pathological/a2-transcripts-ingest.test.ts`), stale-part reconciliation (deletes `part > of` leftovers), session metadata banked in the base page's raw_data as the REDACTED copy and healed by content-compare even on hash-skipped re-runs (a run that died before `putRawData`, or a private pattern added after first import, repairs on the next pass), `cleanScan`/`maxSessionTs` for the watermark. `ingest-facts.ts`: ONE `runExtractConversationFactsCore` invocation (batch `slugs` selector) inside ONE `withBudgetTracker`, `isFactsExtractionEnabled` pre-checked. Pinned by `test/transcript-adapters.test.ts`, `test/transcript-render.test.ts`, `test/transcripts-retitle.test.ts`, `test/transcripts-ingest-pglite.test.ts`, `test/e2e/transcripts-writeback-fidelity.test.ts` (raw files through the adapters into the gold-extractor facts path).- `src/core/verbs.ts` — MEMORY_VERBS v1: the four frozen protocol verbs (`remember`, `entity`, `synthesize`, `forget`) as first-class Operations, plus `MEMORY_VERBS_VERSION` (single source of truth, =1), `VERB_NAMES`, the hand-authored `RESPONSE_SCHEMAS` registry (Operation carries input params only; response shapes live here and conformance validates LIVE responses against them), and `ERROR_SCHEMA`. The extended `recall` op is defined in ops/facts.ts and registered through operations.ts. Its response registry advertises optional `budget_packing` policy/applied/reason and per-arm integer accounting without changing required default fields or protocol version; `test/protocol-document.test.ts` pins discovery and malformed metadata rejection. The `context_pack` and `delta` fact items advertise optional `fact_id` and `provenance` (#6146). The recall registry advertises optional `facts_order`, `facts_degraded` and per-fact `relevance` (question ranking). RUNTIME LEAF invariant: operations.ts spreads `verbOperations` into its array at module-eval time, so this file must never statically import operations.ts VALUES (type-only imports fine; handlers use dynamic import) — violating it causes a TDZ crash on whichever module evaluates second. Every verb error carries a populated `suggestion` + `protocol_version` (via `verbError` in operations.ts). The `forget` verb deliberately has NO cliHints (CLI_ONLY `forget` dispatches first and would shadow it). Frozen contract: docs/protocol/MEMORY_VERBS_v1.md; pinned by test/memory-verbs-conformance.test.ts.- `src/core/verbs/conformance.ts` + `src/core/verbs/conformance-fixtures.ts` — the conformance runner core (transport-agnostic: minimal `ConformanceClient` = list_tools + call_tool) and the embedded fixture set. Deterministic by construction: shape/enum/behavior/round-trip checks only, never ranking quality. Validation is NON-STRICT on extra fields (additive-forever means unknown fields are always legal). Entity-card cases seed via put_page when the target exposes it and skip honestly on verbs-only targets; synthesize is cost-gated behind --synthesize. `validateAgainstSchema` is a minimal JSON-Schema-subset validator (type unions, required, properties, enum, const, items). Fixtures mirror to `test/fixtures/memory-verbs/cases.json` (BrainBench seeds; drift-guarded by the conformance test). The negative self-test (test/memory-verbs-conformance.test.ts) proves the runner FAILS a lying server.diff --git a/src/core/facts/subject-infer.ts b/src/core/facts/subject-infer.tsindex 0bf1b445d7..7c4bd1d634 100644--- a/src/core/facts/subject-infer.ts+++ b/src/core/facts/subject-infer.ts@@ -105,9 +105,14 @@ const SENTENCE_OPENERS = new Set(['not', 'no', 'yes', 'after', 'before', 'during', 'since', 'until', 'while', 'per', 'via', 're', 'fyi', 'update', 'updated','lunch', 'dinner', 'breakfast', 'coffee', 'drinks', 'call', 'sync', 'standup', 'interview', 'demo', 'pitch', 'board','favorite', 'favourite', 'birthday', 'anniversary', 'allergic', 'vegetarian', 'vegan', 'lives', 'lived', 'works', 'worked',- 'work', 'invoice', 'invoiced', 'billed', 'receipt', 'payment',]);+/**+ * #7405: record-label openers ("Invoice total ...", "Work session ..."). Like SENTENCE_OPENERS they are no name evidence+ * when they open a sentence and resolve to no page, but they are never shed from a candidate, so "Work Example" stays a name.+ */+const LABEL_OPENERS = new Set(['work', 'invoice', 'invoiced', 'billed', 'receipt', 'payment']);+/** #7405: ISO 4217 codes; one counts as a unit (not a name) only where every use sits next to an amount ("CHF 80", "80 CHF"). */const CURRENCY_CODES = new Set(Intl.supportedValuesOf('currency'));@@ -156,7 +161,7 @@ export async function inferFactSubject(engine: BrainEngine, sourceId: string, in// a real competing reference.if (r.miss === 'not_entity') continue;if (r.miss === 'no_page' && (isNonName(candidate.query) || isAmountUnit(input.fact, candidate.query)- || (candidate.sentenceStart && SENTENCE_OPENERS.has(candidate.query.toLowerCase())))) continue;+ || (candidate.sentenceStart && (SENTENCE_OPENERS.has(candidate.query.toLowerCase()) || LABEL_OPENERS.has(candidate.query.toLowerCase()))))) continue;vetoed = true;}@@ -198,11 +203,15 @@ function isAmountUnit(fact: string, query: string): boolean {/^\s*\d/u.test(fact.slice(m.index! + m[0].length)) || /\d\s*$/u.test(fact.slice(0, m.index)));}-/** #7405: an entity named only as an example ("... including Automation Example notes") resolves, but cannot be the subject. */+/**+ * #7405: an entity named only as an example ("... including Automation Example notes", "for example, Automation Example")+ * resolves, but cannot be the subject. The example phrase must introduce the mention: only other names of the same list+ * may sit between them, so "notes including weekly items belong to Alice Example" keeps Alice.+ */+const EXAMPLE_LIST_LEAD = /(?:^|[^\p{L}])(?:[Ii]ncluding|[Ss]uch as|[Ff]or example|[Ff]or instance|[Ee]\.g\.)[,:]?\s+(?:\p{Lu}[\p{L}\p{N}'’./-]*(?:\s+\p{Lu}[\p{L}\p{N}'’./-]*)*\s*(?:,\s*(?:and\s+|or\s+)?|\s+(?:and|or)\s+))*$/u;function onlyExampleUses(fact: string, query: string): boolean {const uses = referenceUses(fact, query);- return uses.length > 0 && uses.every(m =>- /\b(?:including|such as|for example|for instance|e\.g\.)\s+[^.!?;]*$/iu.test(fact.slice(0, m.index)));+ return uses.length > 0 && uses.every(m => EXAMPLE_LIST_LEAD.test(fact.slice(0, m.index)));}async function liveFactEntityPage(engine: BrainEngine, sourceId: string, slug: string, excludePrivate?: boolean): Promise<string | null> {diff --git a/src/core/transcripts/hermes.ts b/src/core/transcripts/hermes.tsindex a5a514b188..02e8c0c2d2 100644--- a/src/core/transcripts/hermes.ts+++ b/src/core/transcripts/hermes.ts@@ -115,11 +115,14 @@ interface MessageRow {/*** #7396: the user's answers in a clarify tool result (hermes-agent- * tools/clarify_tool.py `_result`), in question order. Only a form that ended- * in a submit counts: `outcome: 'submitted'` with `status: 'answered'`, or the- * earlier batch shape (no `outcome`, no `status`, unanswered as "") without- * `timed_out`. The legacy single-question shape is never read: it serializes a- * timeout into `user_response` as text. Offered choices are never returned.+ * tools/clarify_tool.py `_result`), in question order. A `status: 'answered'`+ * response counts when the form was submitted or timed out part-way (Hermes+ * keeps the answers the user already locked under `outcome: 'timed_out'`), or,+ * in the earlier batch shape (no `outcome`, no `status`, unanswered as ""), a+ * non-empty response of a form without `timed_out`. Cancelled and undelivered+ * forms count for nothing. The legacy single-question shape is never read: it+ * serializes a timeout into `user_response` as text. Offered choices are never+ * returned.*/function clarifyAnswers(content: string | null): Array<{ question: string; text: string }> {let result: unknown;@@ -128,7 +131,7 @@ function clarifyAnswers(content: string | null): Array<{ question: string; text:const { outcome, responses, timed_out: timedOut } = result as Record<string, unknown>;if (!Array.isArray(responses)) return [];const statusShape = outcome !== undefined;- if (statusShape ? outcome !== 'submitted' : timedOut === true) return [];+ if (statusShape ? outcome !== 'submitted' && outcome !== 'timed_out' : timedOut === true) return [];const answers: Array<{ question: string; text: string }> = [];for (const response of responses) {if (typeof response !== 'object' || response === null) continue;@@ -224,6 +227,8 @@ export const hermesAdapter: TranscriptAdapter = {for (const m of msgQuery.all(row.id)) {if (m.role === 'tool') {for (const answer of clarifyAnswers(m.content)) {+ // The question the assistant asked comes first, so the answer reads in context; it is never user speech.+ if (answer.question.trim()) messages.push({ role: 'assistant', timestamp: epochToIso(m.timestamp), text: answer.question });raw[`clarify_${clarified}_tool_call_id`] = m.tool_call_id;raw[`clarify_${clarified}_question`] = answer.question;raw[`clarify_${clarified++}_message_index`] = messages.length;diff --git a/test/facts-subject-infer-7405.test.ts b/test/facts-subject-infer-7405.test.tsindex da5c041ee1..17b95e82c6 100644--- a/test/facts-subject-infer-7405.test.ts+++ b/test/facts-subject-infer-7405.test.ts@@ -39,10 +39,15 @@ beforeAll(async () => {for (const sourceId of ['default', 'source-a']) {await page(engine, 'people/alice-example', 'Alice Example', 'person', sourceId);await page(engine, 'companies/acme-example', 'Acme Example', 'company', sourceId);- await page(engine, 'ideas/automation-example', 'Automation Example', 'concept', sourceId);+ await page(engine, 'concepts/automation-example', 'Automation Example', 'concept', sourceId);}// source-a also holds real entities named like a currency code and two label words.for (const title of ['CHF', 'Invoice', 'Work']) await page(engine, `companies/${title.toLowerCase()}`, title, 'company', 'source-a');+ // source-b holds names that start with a label word.+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('source-b', 'source-b') ON CONFLICT DO NOTHING`);+ await page(engine, 'companies/work-example', 'Work Example', 'company', 'source-b');+ await page(engine, 'companies/work-acme-example', 'Work Acme Example', 'company', 'source-b');+ await page(engine, 'companies/acme-example', 'Acme Example', 'company', 'source-b');}}, 120_000);@@ -62,10 +67,13 @@ const CASES: Array<{ id: string; fact: string; expect: string | null }> = [{ id: 'unknown-issuer', fact: 'Northstar Example issued an invoice to Alice Example', expect: null },{ id: 'incidental-example', fact: 'Has a venture research folder with 17 enrolled documents including Automation Example notes', expect: null },{ id: 'such-as-example', fact: 'Has research notes on concepts such as Automation Example', expect: null },- { id: 'example-literal', fact: 'Has research notes including ideas/automation-example', expect: null },+ { id: 'for-example-comma', fact: 'Has research notes on several concepts, for example, Automation Example', expect: null },+ { id: 'eg-comma', fact: 'Has research notes on several concepts (e.g., Acme Example and Automation Example)', expect: null },+ { id: 'including-not-introducing', fact: 'Has notes including weekly sync items that belong to Alice Example', expect: ALICE },+ { id: 'example-literal', fact: 'Has research notes including concepts/automation-example', expect: null },{ id: 'currency-without-amount', fact: 'CHF billed Alice Example CHF 80', expect: null },{ id: 'label-mid-sentence', fact: 'Alice Example joined Work Example last year', expect: null },- { id: 'subject-also-named-as-example', fact: 'ideas/automation-example lists 17 documents including ideas/automation-example notes', expect: 'ideas/automation-example' },+ { id: 'subject-also-named-as-example', fact: 'concepts/automation-example lists 17 documents including concepts/automation-example notes', expect: 'concepts/automation-example' },];describe('#7405 fact subject inference: currency amounts, label openers and incidental examples', () => {@@ -85,6 +93,11 @@ describe('#7405 fact subject inference: currency amounts, label openers and inci})).toMatchObject({ slug: null, reason: 'ambiguous' });});+ test(`[${backend}] ${mode}: a name that starts with a label word keeps it`, async () => {+ expect((await inferFactSubject(engineFor(), 'source-b', { fact: 'Work Example raised a seed round', mode })).slug).toBe('companies/work-example');+ expect((await inferFactSubject(engineFor(), 'source-b', { fact: 'Work Acme Example raised a seed round', mode })).slug).toBe('companies/work-acme-example');+ });+test(`[${backend}] ${mode}: real entities named CHF, Invoice or Work still compete`, async () => {for (const fact of ['Alice Example paid CHF 80 for gardening',diff --git a/test/hermes-clarify-transcripts-7396.test.ts b/test/hermes-clarify-transcripts-7396.test.tsindex a37afc090a..663021b1de 100644--- a/test/hermes-clarify-transcripts-7396.test.ts+++ b/test/hermes-clarify-transcripts-7396.test.ts@@ -9,9 +9,10 @@* tools/clarify_tool.py `_result`: `{responses: [{question, choices_offered,* status, user_response}], outcome}`, and the earlier batch shape without* `status`/`outcome`) imports as the user's message at the result's event- * time, with the question and tool-call id kept as provenance in raw metadata;- * unselected choices, the question text, skipped/unanswered/empty responses,- * cancelled/timed-out/undelivered forms, the legacy single-question shape+ * time, after the question as the assistant's turn, with the question and+ * tool-call id kept as provenance in raw metadata; the answers a timed-out+ * form already locked import too; unselected choices, skipped/unanswered/empty+ * responses, cancelled/undelivered forms, a timed-out earlier batch shape, the legacy single-question shape* (which serializes a timeout as text) and every other tool's output never* become user speech; a store without the tool columns imports as before;* replay is idempotent.@@ -84,16 +85,18 @@ describe('Hermes clarify answers (#7396)', () => {const session = await parseSession(clarifyStore(submitted));expect(texts(session)).toEqual([['user', 'Plan the widget rollout.'],+ ['assistant', 'Which rollout?'],['user', 'Canary'],+ ['assistant', 'Which regions?'],['user', 'East\nWest'],['assistant', 'Proceeding with the rollout you chose.'],]);const at = new Date(ANSWERED_AT * 1000).toISOString();- expect(session.messages[1].timestamp).toBe(at);expect(session.messages[2].timestamp).toBe(at);+ expect(session.messages[4].timestamp).toBe(at);expect(session.meta.raw).toMatchObject({- clarify_0_tool_call_id: 'call-clarify-1', clarify_0_question: 'Which rollout?', clarify_0_message_index: 1,- clarify_1_tool_call_id: 'call-clarify-1', clarify_1_question: 'Which regions?', clarify_1_message_index: 2,+ clarify_0_tool_call_id: 'call-clarify-1', clarify_0_question: 'Which rollout?', clarify_0_message_index: 2,+ clarify_1_tool_call_id: 'call-clarify-1', clarify_1_question: 'Which regions?', clarify_1_message_index: 4,});const userText = session.messages.filter(m => m.role === 'user').map(m => m.text).join('\n');for (const unselected of ['Broad', 'North', 'Which rollout?']) expect(userText).not.toContain(unselected);@@ -103,7 +106,7 @@ describe('Hermes clarify answers (#7396)', () => {const answer = 'No — use the canary.\nKeep 日本語 intact.';const session = await parseSession(clarifyStore({ outcome: 'submitted', responses: [{ question: 'Which rollout?', choices_offered: null, status: 'answered', user_response: answer }] }));- expect(session.messages[1]).toEqual({ role: 'user', timestamp: new Date(ANSWERED_AT * 1000).toISOString(), text: answer });+ expect(session.messages[2]).toEqual({ role: 'user', timestamp: new Date(ANSWERED_AT * 1000).toISOString(), text: answer });});test('the earlier batch shape (no status/outcome) imports non-empty answers of a form that did not time out', async () => {@@ -112,16 +115,26 @@ describe('Hermes clarify answers (#7396)', () => {{ question: 'Which regions?', choices_offered: ['East', 'West'], user_response: '' },] };expect(texts(await parseSession(clarifyStore(batch)))).toEqual([- ['user', 'Plan the widget rollout.'], ['user', 'Canary'], ['assistant', 'Proceeding with the rollout you chose.'],+ ['user', 'Plan the widget rollout.'], ['assistant', 'Which rollout?'], ['user', 'Canary'], ['assistant', 'Proceeding with the rollout you chose.'],]);expect(texts(await parseSession(clarifyStore({ ...batch, timed_out: true, notice: 'user did not respond' })))).toEqual(UNANSWERED);});- test.each(['cancelled', 'timed_out', 'undelivered', ''])('a %s form imports nothing', async outcome => {+ test.each(['cancelled', 'undelivered', ''])('a %s form imports nothing', async outcome => {const session = await parseSession(clarifyStore({ ...submitted, outcome }));expect(texts(session)).toEqual(UNANSWERED);});+ test('a form that timed out part-way keeps the answers the user already locked', async () => {+ const session = await parseSession(clarifyStore({ outcome: 'timed_out', notice: '[user did not respond within 5m]', responses: [+ { question: 'Which rollout?', choices_offered: ['Broad', 'Canary'], status: 'answered', user_response: 'Canary' },+ { question: 'Which regions?', choices_offered: ['East', 'West'], status: 'unanswered', user_response: null },+ ] }));+ expect(texts(session)).toEqual([+ ['user', 'Plan the widget rollout.'], ['assistant', 'Which rollout?'], ['user', 'Canary'], ['assistant', 'Proceeding with the rollout you chose.'],+ ]);+ });+test('skipped, unanswered, empty and malformed responses import nothing; answered siblings survive', async () => {const response = (status: string, user_response: unknown) => ({ question: 'Which rollout?', choices_offered: ['Broad'], status, user_response });const session = await parseSession(clarifyStore({ outcome: 'submitted', responses: [@@ -130,7 +143,7 @@ describe('Hermes clarify answers (#7396)', () => {response('answered', { text: 'NOT-SPEECH-3' }), null, 'NOT-SPEECH-4', response('answered', 'Canary'),] }));expect(texts(session)).toEqual([- ['user', 'Plan the widget rollout.'], ['user', 'Canary'], ['assistant', 'Proceeding with the rollout you chose.'],+ ['user', 'Plan the widget rollout.'], ['assistant', 'Which rollout?'], ['user', 'Canary'], ['assistant', 'Proceeding with the rollout you chose.'],]);});@@ -183,7 +196,7 @@ describe('Hermes clarify answers through ingest (#7396)', () => {const first = await runTranscriptsIngest(engine, opts);expect(first.pages.imported, backend).toBe(1);const page = (await engine.getPage(slug, { sourceId: 'default' }))!;- expect(page.compiled_truth, backend).toMatch(/\*\*User\*\* \([^)]*\): Canary/);+ expect(page.compiled_truth, backend).toMatch(/\*\*Assistant\*\* \([^)]*\): Which rollout\?\n+\*\*User\*\* \([^)]*\): Canary/);expect(page.compiled_truth, backend).not.toContain('Broad');const raw = await engine.getRawData(slug, 'transcript:hermes', { sourceId: 'default' });expect(raw[0].data, backend).toMatchObject({ clarify_0_tool_call_id: 'call-clarify-1', clarify_0_question: 'Which rollout?' });diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex eb7f861202..557d5fde77 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -44,6 +44,7 @@ test/company-brain-policy.test.tstest/company-brain-runtime.test.tstest/consolidate-same-instant-6023.test.tstest/conversation-facts-oversized-sidecar.test.ts+test/conversation-facts-purged-claim-7438.test.tstest/cycle/synthesize-concepts-merge.test.tstest/db-lock-reconnect.test.tstest/decide/conflict-proposals-managed.test.ts@@ -60,6 +61,7 @@ test/embedding-completion-atomic.serial.test.tstest/engine-sql-facts-keyset.test.tstest/extract-all-stamp-intersection.serial.test.tstest/extract-atoms-input-truncated-6503.test.ts+test/extract-atoms-raised-cap-drain-7391.test.tstest/extract-endpoint-revision.serial.test.tstest/extract-entities-managed.test.tstest/extract-timeline-from-meetings-managed.test.ts@@ -70,6 +72,7 @@ test/fact-purge-lookup-timeout-6511.test.tstest/facts-absorb-stalled-receipt-7439.test.tstest/facts-insert-guards-7105.test.tstest/facts-publication-large-fence-6898.test.ts+test/facts-subject-infer-7405.test.tstest/fence-repair-receipts.test.tstest/file-drift-soft-delete-hold-release-gbra133.test.tstest/forecast-journal.test.ts@@ -89,6 +92,7 @@ test/graduation-verify.test.tstest/grandfather-managed.test.tstest/harness-skills-epoch.test.tstest/held-read-signals.test.ts+test/hermes-clarify-transcripts-7396.test.tstest/hold-action-chain-6712.test.tstest/import-file-result-callback-gbra130.test.tstest/import-frontmatter-key-order-5158.test.ts@@ -252,6 +256,7 @@ test/page-prepare-shared-origin-6517.test.tstest/page-purge-batch-sweep-6884.test.tstest/page-purge-journal-timeout-6511.test.tstest/page-state-engine.test.ts+test/pages-source-created-idx-7379.test.tstest/pages-status-7179.test.tstest/pathological/a-36-facts-batch-partial-refusal.test.tstest/pathological/a-42-atom-dot-led-slug.test.ts