Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(transcripts): import a submitted Hermes clarify form's answers as user messages (#7396)

garrytan70bd95645987
diff --git a/docs/architecture/key-files/core-services-3.md b/docs/architecture/key-files/core-services-3.md
index a656eef192..3dfb44560f 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]`; 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 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/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/transcripts/hermes.ts b/src/core/transcripts/hermes.ts
index 5b10aa39d1..a5a514b188 100644
--- a/src/core/transcripts/hermes.ts
+++ b/src/core/transcripts/hermes.ts
@@ -38,12 +38,15 @@ export const HERMES_SPEC_TARGET: HostSpecTarget = {
'installed hermes-agent v0.20.0 hermes_state_common.py SCHEMA_SQL (schema source of truth)',
'hermes-agent hermes_state.py DEFAULT_DB_PATH = <hermes home>/state.db',
'test/fixtures/transcripts/hermes-fixture-builder.ts (synthetic, schema-matched)',
+ 'hermes-agent tools/clarify_tool.py _result (clarify result shape; #7396)',
],
note:
'SQLite store, WAL mode. sessions: id TEXT PK, source, display_name, ' +
'title, started_at REAL (epoch seconds), ended_at, cwd, model. messages: ' +
- 'session_id, role, content TEXT, timestamp REAL. The import keeps role ' +
- "user/assistant rows with non-empty content; content that looks like a " +
+ 'session_id, role, content TEXT, timestamp REAL, tool_call_id, tool_name. ' +
+ 'The import keeps role user/assistant rows with non-empty content, and ' +
+ 'the answered responses of a submitted clarify form (role tool, tool_name ' +
+ 'clarify) as user rows; other tool rows are dropped. Content that looks like a ' +
'JSON block array (bare or json:-prefixed) is unwrapped to its text ' +
'blocks, image blocks as an [image] placeholder. active/compacted ' +
'flags are IGNORED (the archive wants full history, not the live ' +
@@ -107,6 +110,35 @@ interface MessageRow {
role: string;
content: string | null;
timestamp: number | null;
+ tool_call_id: string | null;
+}
+
+/**
+ * #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.
+ */
+function clarifyAnswers(content: string | null): Array<{ question: string; text: string }> {
+ let result: unknown;
+ try { result = JSON.parse(content ?? ''); } catch { return []; }
+ if (typeof result !== 'object' || result === null || Array.isArray(result)) return [];
+ 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 [];
+ const answers: Array<{ question: string; text: string }> = [];
+ for (const response of responses) {
+ if (typeof response !== 'object' || response === null) continue;
+ const { question, status, user_response: answer } = response as Record<string, unknown>;
+ if (statusShape ? status !== 'answered' : status !== undefined) continue;
+ const values = Array.isArray(answer) ? answer : [answer];
+ if (!values.length || !values.every(v => typeof v === 'string' && v.trim())) continue;
+ answers.push({ question: typeof question === 'string' ? question : '', text: values.join('\n') });
+ }
+ return answers;
}
export const hermesAdapter: TranscriptAdapter = {
@@ -169,14 +201,36 @@ export const hermesAdapter: TranscriptAdapter = {
};
}
+ // Older stores have no tool columns; they import user/assistant rows as before.
+ const columns = new Set(db.query<{ name: string }, []>('PRAGMA table_info(messages)').all().map(c => c.name));
+ const toolColumns = columns.has('tool_name') && columns.has('tool_call_id');
const msgQuery = db.query<MessageRow, [string]>(
- "SELECT role, content, timestamp FROM messages WHERE session_id = ? " +
- "AND role IN ('user','assistant') ORDER BY timestamp, id",
+ toolColumns
+ ? "SELECT role, content, timestamp, tool_call_id FROM messages WHERE session_id = ? " +
+ "AND (role IN ('user','assistant') OR (role = 'tool' AND tool_name = 'clarify')) ORDER BY timestamp, id"
+ : "SELECT role, content, timestamp, NULL AS tool_call_id FROM messages WHERE session_id = ? " +
+ "AND role IN ('user','assistant') ORDER BY timestamp, id",
);
for (const row of sessionRows) {
if (typeof row.id !== 'string' || !row.id) continue;
const messages: TranscriptMessage[] = [];
+ const raw: Record<string, unknown> = {
+ session_id: row.id,
+ source: row.source ?? null,
+ cwd: row.cwd ?? null,
+ source_path: path,
+ };
+ let clarified = 0;
for (const m of msgQuery.all(row.id)) {
+ if (m.role === 'tool') {
+ for (const answer of clarifyAnswers(m.content)) {
+ raw[`clarify_${clarified}_tool_call_id`] = m.tool_call_id;
+ raw[`clarify_${clarified}_question`] = answer.question;
+ raw[`clarify_${clarified++}_message_index`] = messages.length;
+ messages.push({ role: 'user', timestamp: epochToIso(m.timestamp), text: answer.text });
+ }
+ continue;
+ }
const role = m.role === 'user' || m.role === 'assistant' ? m.role : null;
if (!role) continue;
const text = contentToText(m.content);
@@ -193,12 +247,7 @@ export const hermesAdapter: TranscriptAdapter = {
cwd: row.cwd ?? undefined,
model: row.model ?? undefined,
startedAt: epochToIso(row.started_at) || messages[0].timestamp || undefined,
- raw: {
- session_id: row.id,
- source: row.source ?? null,
- cwd: row.cwd ?? null,
- source_path: path,
- },
+ raw,
},
messages,
};
diff --git a/test/hermes-clarify-transcripts-7396.test.ts b/test/hermes-clarify-transcripts-7396.test.ts
new file mode 100644
index 0000000000..a37afc090a
--- /dev/null
+++ b/test/hermes-clarify-transcripts-7396.test.ts
@@ -0,0 +1,198 @@
+/**
+ * #7396: Hermes stores a user's answer to a native clarification form as a
+ * `role=tool`, `tool_name=clarify` result, never as a `role=user` row, so the
+ * adapter's `role IN ('user','assistant')` filter dropped the answer and the
+ * imported conversation kept the assistant's interpretation without the
+ * user's intervening correction.
+ *
+ * Protects: an answered response of a submitted form (hermes-agent
+ * 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
+ * (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.
+ * Seams: none; the ingest case runs on PGLite always, Postgres when DATABASE_URL is set.
+ */
+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
+import { Database } from 'bun:sqlite';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { hermesAdapter } from '../src/core/transcripts/hermes.ts';
+import { runTranscriptsIngest } from '../src/core/transcripts/ingest.ts';
+import { buildTranscriptSlug, type ParsedSession } from '../src/core/transcripts/types.ts';
+import { buildHermesFixture } from './fixtures/transcripts/hermes-fixture-builder.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+
+const SESSION = 'clarify-session-example';
+const STARTED = 1786057199;
+const ANSWERED_AT = 1786057201;
+
+const submitted = {
+ outcome: 'submitted',
+ responses: [
+ { question: 'Which rollout?', choices_offered: ['Broad', 'Canary'], status: 'answered', user_response: 'Canary' },
+ { question: 'Which regions?', choices_offered: ['East', 'West', 'North'], status: 'answered', user_response: ['East', 'West'] },
+ ],
+};
+
+let dirs: string[] = [];
+afterEach(() => { for (const dir of dirs) rmSync(dir, { recursive: true, force: true }); dirs = []; });
+
+/** A synthetic store with the current hermes-agent messages columns (tool_call_id, tool_calls, tool_name). */
+function clarifyStore(result: unknown, toolName = 'clarify'): string {
+ const dir = mkdtempSync(join(tmpdir(), 'hermes-clarify-'));
+ dirs.push(dir);
+ const path = join(dir, 'state.db');
+ const db = new Database(path);
+ try {
+ db.exec(`
+ CREATE TABLE sessions (id TEXT PRIMARY KEY, source TEXT NOT NULL, display_name TEXT, model TEXT,
+ started_at REAL NOT NULL, ended_at REAL, cwd TEXT, title TEXT);
+ CREATE TABLE messages (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL REFERENCES sessions(id),
+ role TEXT NOT NULL, content TEXT, tool_call_id TEXT, tool_calls TEXT, tool_name TEXT, timestamp REAL NOT NULL);
+ `);
+ db.prepare('INSERT INTO sessions (id, source, started_at) VALUES (?, ?, ?)').run(SESSION, 'cli', STARTED);
+ const insert = db.prepare('INSERT INTO messages (session_id, role, content, tool_call_id, tool_calls, tool_name, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?)');
+ insert.run(SESSION, 'user', 'Plan the widget rollout.', null, null, null, STARTED);
+ insert.run(SESSION, 'assistant', '', null, JSON.stringify([{ id: 'call-clarify-1', type: 'function',
+ function: { name: toolName, arguments: JSON.stringify({ questions: [{ question: 'Which rollout?' }] }) } }]), null, STARTED + 1);
+ insert.run(SESSION, 'tool', typeof result === 'string' ? result : JSON.stringify(result), 'call-clarify-1', null, toolName, ANSWERED_AT);
+ insert.run(SESSION, 'assistant', 'Proceeding with the rollout you chose.', null, null, null, ANSWERED_AT + 1);
+ } finally {
+ db.close();
+ }
+ return path;
+}
+
+async function parseSession(path: string): Promise<ParsedSession> {
+ for await (const session of hermesAdapter.parse(path)) if (session.meta.sessionId === SESSION) return session;
+ throw new Error('synthetic session missing');
+}
+const texts = (session: ParsedSession) => session.messages.map(m => [m.role, m.text]);
+const UNANSWERED = [['user', 'Plan the widget rollout.'], ['assistant', 'Proceeding with the rollout you chose.']];
+
+describe('Hermes clarify answers (#7396)', () => {
+ test('a submitted form imports each answered value as the user, at the result time, with provenance', async () => {
+ const session = await parseSession(clarifyStore(submitted));
+ expect(texts(session)).toEqual([
+ ['user', 'Plan the widget rollout.'],
+ ['user', 'Canary'],
+ ['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.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,
+ });
+ 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);
+ });
+
+ test('a typed answer is kept exactly', async () => {
+ 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 });
+ });
+
+ test('the earlier batch shape (no status/outcome) imports non-empty answers of a form that did not time out', async () => {
+ const batch = { responses: [
+ { question: 'Which rollout?', choices_offered: ['Broad', 'Canary'], user_response: 'Canary' },
+ { 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.'],
+ ]);
+ 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 => {
+ const session = await parseSession(clarifyStore({ ...submitted, outcome }));
+ expect(texts(session)).toEqual(UNANSWERED);
+ });
+
+ 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: [
+ response('skipped', 'NOT-SPEECH-1'), response('unanswered', 'NOT-SPEECH-2'), response('answered', null),
+ response('answered', ''), response('answered', ' '), response('answered', []), response('answered', ['East', 7]),
+ 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.'],
+ ]);
+ });
+
+ test.each([
+ ['legacy single-question shape', JSON.stringify({ question: 'Which rollout?', choices_offered: ['Broad'], user_response: 'None' })],
+ ['tool error', JSON.stringify({ error: 'Clarify tool is not available in this execution context.' })],
+ ['plain text', 'The user did not provide a response within the time limit.'],
+ ['malformed JSON', '{"outcome":"submitted","responses":['],
+ ['non-array responses', JSON.stringify({ outcome: 'submitted', responses: 'Canary' })],
+ ])('a %s result imports nothing', async (_label, content) => {
+ expect(texts(await parseSession(clarifyStore(content)))).toEqual(UNANSWERED);
+ });
+
+ test('another tool with the same envelope is never user speech', async () => {
+ expect(texts(await parseSession(clarifyStore(submitted, 'terminal')))).toEqual(UNANSWERED);
+ });
+
+ test('a store without the tool columns imports as before', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'hermes-clarify-legacy-'));
+ dirs.push(dir);
+ const sessions: ParsedSession[] = [];
+ for await (const session of hermesAdapter.parse(buildHermesFixture(dir))) sessions.push(session);
+ expect(sessions.map(s => [s.meta.sessionId, s.messages.length])).toEqual([['hermes-fixture-1', 2], ['hermes-fixture-2', 2]]);
+ expect(JSON.stringify(sessions)).not.toContain('TOOL-ONLY-TEXT');
+ });
+});
+
+describe('Hermes clarify answers through ingest (#7396)', () => {
+ const engines: Array<{ backend: string; engine: BrainEngine; close: () => Promise<void> }> = [];
+ beforeAll(async () => {
+ for (const backend of testBackends()) {
+ if (backend === 'pglite') {
+ const engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ engines.push({ backend, engine, close: () => engine.disconnect() });
+ } else {
+ const isolated = await isolatedPersistencePostgres(requirePostgresTestDatabase());
+ engines.push({ backend, engine: isolated.engine, close: isolated.close });
+ }
+ }
+ }, 120_000);
+ afterAll(async () => { for (const { close } of engines) await close(); });
+
+ test('the answer lands as a User turn, provenance rides raw_data, and replay is a no-op', async () => {
+ const slug = buildTranscriptSlug('hermes', new Date(STARTED * 1000).toISOString(), { sessionId: SESSION });
+ for (const { backend, engine } of engines) {
+ const path = clarifyStore(submitted);
+ const opts = { paths: [path], sourceId: 'default', userPatternsPath: '/nonexistent-patterns.txt' };
+ 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).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?' });
+
+ const again = await runTranscriptsIngest(engine, opts);
+ expect(again.pages.imported, backend).toBe(0);
+ expect(again.pages.skipped, backend).toBe(1);
+ expect((await engine.getPage(slug, { sourceId: 'default' }))!.compiled_truth, backend).toBe(page.compiled_truth);
+ expect((await engine.getRawData(slug, 'transcript:hermes', { sourceId: 'default' }))[0].data, backend).toEqual(raw[0].data);
+ }
+ }, 120_000);
+});