Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(code): dynamic status verbs — one LLM call per session, chat stays static
Salman Qureshie1193377cd8d
diff --git a/src/channels/cli.ts b/src/channels/cli.tsindex cbbb7fa8..0ee30d09 100644--- a/src/channels/cli.ts+++ b/src/channels/cli.ts@@ -311,6 +311,13 @@ export interface TuiState {exitEscArmed: boolean;/** Real-time activity phase (what the agent is doing right now), or null when idle. */liveActivity: LiveActivityState | null;+ /**+ * Mercury Code status-verb pool for the live status row. null until the+ * agent's one-shot LLM refinement lands (session start shows the plain+ * static label); populated with LLM verbs (or the keyword fallback after a+ * failed generation) and cleared on exitMercuryCode.+ */+ statusVerbs: string[] | null;/** TUI frame freeze (scroll lock): all frame writes stop so the user can* scroll/copy freely while the chat continues underneath. Ctrl+S toggles. */tuiFrozen: boolean;@@ -348,6 +355,7 @@ const defaultState: TuiState = {mercuryCode: null,exitEscArmed: false,liveActivity: null,+ statusVerbs: null,tuiFrozen: false,updateAvailable: null,};@@ -1740,6 +1748,16 @@ export class CLIChannel extends BaseChannel {this.update({ updateAvailable: latestVersion });}+ /**+ * Push the Mercury Code status-verb pool (agent's one-shot LLM refinement,+ * or the keyword fallback when that failed). Empty lists are ignored — they+ * would fall through to the static label anyway.+ */+ setStatusVerbs(verbs: string[]): void {+ if (!Array.isArray(verbs) || verbs.length === 0) return;+ this.update({ statusVerbs: verbs });+ }+exitMercuryCode(): void {if (this.state.mercuryCode) {this.setMouseEnabled(false);@@ -1752,6 +1770,7 @@ export class CLIChannel extends BaseChannel {projectContext: null,planProgress: null,exitEscArmed: false,+ statusVerbs: null,});try {process.stdout.write('\x1b[2J\x1b[H');diff --git a/src/core/agent.ts b/src/core/agent.tsindex daa15dfd..cbb52078 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -79,6 +79,8 @@ import { compactConversation, memoryGovernorThresholds, memoryGovernorVerdict }import { classifyStreamCompletion, isLengthTruncation, truncationContinuationPrompt, toolTruncationContinuationPrompt } from './stream-completion.js';import { MAX_EXECUTE_CONTINUATIONS, MAX_VERIFICATION_CONTINUATIONS, executeContinuationPrompt, shouldForceExecuteContinuation, isFailedToolResult, shouldRequireVerification, verificationPrompt, responseAsksUser, isTextDeliverableRequest, EXECUTE_MUTATING_TOOLS, VERIFICATION_COMMAND_PATTERN, wakeUpPrompt } from './execute-guard.js';import { classifyTurnEnd, stepsExhaustedPrompt, STEPS_PAUSED_BANNER, WORK_NOT_STARTED_BANNER, type LoopEndCause } from './completion-verdict.js';+import { buildStatusVerbPrompt, parseStatusVerbs, shouldRefreshStatusVerbs } from './status-verbs.js';+import { verbPoolFor } from '../ui/status-word.js';import { StallWatchdog } from './stall-watchdog.js';import { buildFileChangePreview } from '../utils/file-preview.js';import { whatsNewText } from '../utils/whats-new.js';@@ -491,6 +493,11 @@ export class Agent {private skillLoader?: SkillLoader;readonly backgroundTasks: BackgroundTaskManager;private titleGenerationInFlight = new Set<string>();+ // Mercury Code status-verb refresh (see core/status-verbs.ts): per-session+ // turn counter + in-flight/disabled markers keep the one-shot LLM call rare.+ private statusVerbTurnCount = 0;+ private statusVerbsInFlight = false;+ private statusVerbsDisabled = false;private sessionSyncEnabled = false;private readonly workLedger: WorkLedger;private currentWorkKey: string | null = null;@@ -3897,6 +3904,7 @@ export class Agent {this.extractMemory(msg.content, finalText).catch(err => {logger.warn({ err }, 'Memory extraction failed');});+ this.scheduleStatusVerbRefresh(channel, msg.content);}if (this.currentWorkKey) this.workLedger.markCompleted(this.currentWorkKey, finalText);@@ -6641,6 +6649,83 @@ Is this productive iteration or a stuck loop?`,}}+ /**+ * Mercury Code only: at turn end, maybe fire the one-shot LLM status-verb+ * refresh (cadence in core/status-verbs.ts). Fire-and-forget and unref'd —+ * the turn is already done; a slow call must never stall anything. Non-code+ * surfaces are skipped entirely: chat keeps its plain static labels.+ */+ private scheduleStatusVerbRefresh(channel: import('../channels/base.js').Channel | null | undefined, userText: string): void {+ const cliChannel = channel instanceof CLIChannel ? channel : null;+ if (!cliChannel || cliChannel.getTuiState().mode !== 'mercury-code') return;+ this.statusVerbTurnCount += 1;+ const gate = shouldRefreshStatusVerbs({+ turnCount: this.statusVerbTurnCount,+ inFlight: this.statusVerbsInFlight,+ disabled: this.statusVerbsDisabled,+ });+ if (!gate.refresh) return;+ this.statusVerbsInFlight = true;+ const timer = setTimeout(() => {+ void this.refreshStatusVerbs(cliChannel, userText).finally(() => {+ this.statusVerbsInFlight = false;+ });+ }, 0);+ timer.unref?.();+ }++ private async refreshStatusVerbs(cliChannel: CLIChannel, userText: string): Promise<void> {+ try {+ if (this.tokenBudget.canAfford(500)) {+ const provider = this.providers.getDefault();+ if (provider && provider.isAvailable()) {+ const tui = cliChannel.getTuiState();+ const requests = tui.chatMessages+ .filter((m) => m.role === 'user' && m.content.trim())+ .slice(-4)+ .map((m) => m.content);+ const { system, prompt } = buildStatusVerbPrompt({+ userRequests: requests.length > 0 ? requests : [userText],+ projectName: path.basename(tui.projectContext ?? '') || 'this project',+ recentActivity: tui.lastStepLog?.map((s) => s.label),+ });+ const result = await generateText({+ model: provider.getModelInstance(),+ system,+ messages: [{ role: 'user', content: prompt }],+ maxOutputTokens: 400,+ });+ this.tokenBudget.recordUsage({+ provider: provider.name,+ model: provider.getModel(),+ inputTokens: result.usage?.inputTokens ?? 0,+ outputTokens: result.usage?.outputTokens ?? 0,+ totalTokens: (result.usage?.inputTokens ?? 0) + (result.usage?.outputTokens ?? 0),+ channelType: 'internal',+ agentId: this.config.cloud.agentId || undefined,+ });+ const verbs = parseStatusVerbs(result.text ?? '');+ if (verbs) {+ cliChannel.setStatusVerbs(verbs);+ return;+ }+ }+ }+ this.failStatusVerbRefresh(cliChannel, userText);+ } catch (err) {+ logger.debug({ err }, 'Status-verb refresh failed');+ this.failStatusVerbRefresh(cliChannel, userText);+ }+ }++ /** Push the keyword-engine pool once, then the LLM layer is off this session. */+ private failStatusVerbRefresh(cliChannel: CLIChannel, userText: string): void {+ this.statusVerbsDisabled = true;+ // Never downgrade an LLM pool that already landed.+ if (cliChannel.getTuiState().statusVerbs) return;+ cliChannel.setStatusVerbs(verbPoolFor(userText));+ }+private async handleWorkspaceNaturalLanguage(content: string, channelType: string, channelId: string): Promise<boolean> {const channel = this.channels.get(channelType as any);if (!channel || channelType !== 'cli' || !(channel instanceof CLIChannel)) return false;diff --git a/src/core/status-verbs.test.ts b/src/core/status-verbs.test.tsnew file mode 100644index 00000000..9335e7e9--- /dev/null+++ b/src/core/status-verbs.test.ts@@ -0,0 +1,108 @@+import { describe, expect, it } from 'vitest';+import {+ FIRST_REFRESH_AFTER_TURNS,+ REFRESH_INTERVAL_TURNS,+ buildStatusVerbPrompt,+ parseStatusVerbs,+ shouldRefreshStatusVerbs,+} from './status-verbs.js';++/**+ * Mercury Code's dynamic status verbs: the cadence gate keeps the one-shot+ * LLM call rare (first refresh after turn 2, then ≤1 per 5 turns, one+ * failure = off for the session) and the parser rejects exactly the generic+ * filler the user complained about ("building", "crafting", "noodling" for+ * work that isn't happening).+ */+describe('status-verb cadence gate', () => {+ const base = { inFlight: false, disabled: false };++ it('never fires on turn 1 — the session has no persona yet', () => {+ expect(shouldRefreshStatusVerbs({ ...base, turnCount: 1 }).refresh).toBe(false);+ expect(shouldRefreshStatusVerbs({ ...base, turnCount: 1 }).reason).toBe('too-early');+ });++ it('fires first after turn 2, then only every 5 turns', () => {+ expect(shouldRefreshStatusVerbs({ ...base, turnCount: FIRST_REFRESH_AFTER_TURNS }).refresh).toBe(true);+ for (let t = FIRST_REFRESH_AFTER_TURNS + 1; t < FIRST_REFRESH_AFTER_TURNS + REFRESH_INTERVAL_TURNS; t++) {+ const gate = shouldRefreshStatusVerbs({ ...base, turnCount: t });+ expect(gate.refresh).toBe(false);+ expect(gate.reason).toBe('not-due');+ }+ expect(shouldRefreshStatusVerbs({ ...base, turnCount: FIRST_REFRESH_AFTER_TURNS + REFRESH_INTERVAL_TURNS }).refresh).toBe(true);+ });++ it('skips while a refresh is in flight', () => {+ expect(shouldRefreshStatusVerbs({ turnCount: 2, inFlight: true, disabled: false }).reason).toBe('in-flight');+ });++ it('a failure disables the LLM layer for the session — no retry churn', () => {+ for (const turn of [2, 5, 7, 12, 100]) {+ const gate = shouldRefreshStatusVerbs({ turnCount: turn, inFlight: false, disabled: true });+ expect(gate.refresh).toBe(false);+ expect(gate.reason).toBe('disabled');+ }+ });+});++describe('status-verb prompt', () => {+ it('carries the requests, the project name, and recent activity', () => {+ const { system, prompt } = buildStatusVerbPrompt({+ userRequests: ['Improve the UI design of the download manager', 'Fix the flaky auth test'],+ projectName: 'download-manager',+ recentActivity: ['Reading src/auth.ts', 'Running tests'],+ });+ expect(prompt).toContain('download-manager');+ expect(prompt).toContain('Improve the UI design');+ expect(prompt).toContain('Fix the flaky auth test');+ expect(prompt).toContain('Running tests');+ // The contract the model must obey — no generic filler, -ing phrases, JSON.+ expect(system).toContain('present-participle');+ expect(system).toContain('do NOT write "building"');+ expect(system).toContain('JSON array');+ });++ it('truncates long requests and omits the activity line when absent', () => {+ const { prompt } = buildStatusVerbPrompt({+ userRequests: ['x'.repeat(500)],+ projectName: 'p',+ });+ expect(prompt).not.toContain('Recent activity');+ expect(prompt.length).toBeLessThan(600);+ });+});++describe('status-verb parsing', () => {+ it('accepts a good JSON pool of -ing phrases', () => {+ const good = [+ 'Extracting the parser',+ 'Rerouting the auth flow',+ 'Wiring the contract tests',+ 'Trimming the bundle',+ 'Untangling the widget state',+ 'Threading the queue worker',+ 'Polishing the transcript',+ ];+ expect(parseStatusVerbs(JSON.stringify(good))).toEqual(good);+ // Tolerates markdown fences around the array.+ expect(parseStatusVerbs('```json\n' + JSON.stringify(good) + '\n```')).toEqual(good);+ });++ it('rejects the generic filler words the user complained about', () => {+ const filler = ['Building the thing', 'Crafting the solution', 'Noodling around', 'Working on it', 'Cooking something up', 'Brewing ideas', 'Processing data', 'Doodling shapes'];+ expect(parseStatusVerbs(JSON.stringify(filler))).toBeNull();+ });++ it('rejects non--ing leads, over-long phrases, and wrong shapes', () => {+ expect(parseStatusVerbs('["Fix the parser", "a", "b", "c", "d", "e"]')).toBeNull();+ expect(parseStatusVerbs(JSON.stringify(['Fix the parser', 'Run the tests', 'Read the file', 'Write the docs', 'Test the flow', 'Sort the list']))).toBeNull();+ expect(parseStatusVerbs('"just a string"')).toBeNull();+ expect(parseStatusVerbs('no json here')).toBeNull();+ });++ it('dedupes case-insensitively and requires the minimum pool size', () => {+ const six = ['Extracting the parser', 'Rerouting the auth flow', 'Wiring the tests', 'Trimming the bundle', 'Untangling the state', 'Threading the queue'];+ expect(parseStatusVerbs(JSON.stringify([...six, 'extracting the parser']))).toEqual(six);+ expect(parseStatusVerbs(JSON.stringify(six.slice(0, 5)))).toBeNull(); // below minimum+ });+});\ No newline at end of filediff --git a/src/core/status-verbs.ts b/src/core/status-verbs.tsnew file mode 100644index 00000000..7c7272c0--- /dev/null+++ b/src/core/status-verbs.ts@@ -0,0 +1,123 @@+/**+ * Mercury Code's dynamic status verbs — the LLM layer over the keyword+ * engine (consumers live in core/agent.ts, channels/cli.ts + ui/App.tsx).+ * One tiny generateText call per session: after the session has progressed+ * enough to see the project's persona, the agent asks the model for a pool+ * of short -ing phrases describing the ACTUAL work ("Extracting the+ * parser", "Rerouting the auth flow") — never generic filler like+ * "building" or "noodling" for work that isn't happening.+ *+ * Cadence is deliberately rare (the user's explicit concern): first refresh+ * after the 2nd completed turn, then at most one per 5 turns. One failure+ * disables the LLM layer for the session (the keyword fallback is pushed+ * once) — no retry churn. The keyword engine remains the fallback and never+ * gets replaced by anything less specific.+ */++/** Completed turns before the first refresh (turn 1 is too thin a signal). */+export const FIRST_REFRESH_AFTER_TURNS = 2;++/** Minimum turns between two refreshes — the pool must not churn. */+export const REFRESH_INTERVAL_TURNS = 5;++const MIN_VERBS = 6;+const MAX_VERBS = 10;++export interface StatusVerbGateInput {+ /** Completed Mercury Code turns so far (1-based count, incremented before the call). */+ turnCount: number;+ /** A refresh is currently in flight. */+ inFlight: boolean;+ /** A previous refresh failed — the LLM layer is off for the session. */+ disabled: boolean;+}++export interface StatusVerbGate {+ refresh: boolean;+ reason: 'disabled' | 'too-early' | 'in-flight' | 'not-due' | 'due';+}++/**+ * Decide whether this turn's end should fire the one-shot LLM verb refresh.+ * Pure — the agent owns the counters; this only encodes the cadence.+ */+export function shouldRefreshStatusVerbs(input: StatusVerbGateInput): StatusVerbGate {+ if (input.disabled) return { refresh: false, reason: 'disabled' };+ if (input.inFlight) return { refresh: false, reason: 'in-flight' };+ if (input.turnCount < FIRST_REFRESH_AFTER_TURNS) return { refresh: false, reason: 'too-early' };+ // First refresh at exactly FIRST_REFRESH_AFTER_TURNS, then every REFRESH_INTERVAL_TURNS.+ const sinceAnchor = (input.turnCount - FIRST_REFRESH_AFTER_TURNS) % REFRESH_INTERVAL_TURNS;+ if (sinceAnchor !== 0) return { refresh: false, reason: 'not-due' };+ return { refresh: true, reason: 'due' };+}++export interface StatusVerbPromptInput {+ /** The last few user requests — the project's persona lives here. */+ userRequests: string[];+ /** Project directory name (e.g. "download-manager"). */+ projectName: string;+ /** Labels of recent tool steps, if any (what the agent has been doing). */+ recentActivity?: string[];+}++/**+ * Build the one-shot verb-generation prompt. The system prompt hard-codes the+ * contract; the user prompt carries only the session evidence (≤ a few+ * hundred tokens).+ */+export function buildStatusVerbPrompt(input: StatusVerbPromptInput): { system: string; prompt: string } {+ const system = [+ 'You write the live status labels for an AI coding agent working in a project.',+ 'Given the recent requests in the session, produce a pool of short status phrases describing what the agent is ACTUALLY doing in this session.',+ 'Rules:',+ '- Each phrase: a present-participle verb (+ short object), 2-6 words, e.g. "Extracting the parser", "Rerouting the auth flow".',+ '- Only work that is actually happening in these requests. If nothing is being built, do NOT write "building" or "crafting" or "noodling".',+ '- Specific to this project and these requests — no generic filler, no metaphors, no emoji.',+ `- Exactly ${MIN_VERBS}-${MAX_VERBS} distinct phrases.`,+ '- Output ONLY a JSON array of strings, nothing else.',+ ].join('\n');+ const requests = input.userRequests.map((r, i) => `${i + 1}. ${r.slice(0, 240)}`).join('\n');+ const activity = input.recentActivity && input.recentActivity.length > 0+ ? `\nRecent activity: ${input.recentActivity.slice(-5).join('; ').slice(0, 300)}`+ : '';+ const prompt = `Project: ${input.projectName}\nRecent requests:\n${requests}${activity}`;+ return { system, prompt };+}++/**+ * Parse and validate the model output. Returns the verb pool, or null when+ * unusable (wrong shape, too few usable phrases, or generic/off-work words).+ * The pool is small (a few hundred bytes), so the caller pushes it verbatim.+ */+export function parseStatusVerbs(raw: string): string[] | null {+ const text = (raw ?? '').trim();+ const start = text.indexOf('[');+ const end = text.lastIndexOf(']');+ if (start === -1 || end === -1 || end <= start) return null;+ let parsed: unknown;+ try {+ parsed = JSON.parse(text.slice(start, end + 1));+ } catch {+ return null;+ }+ if (!Array.isArray(parsed)) return null;+ const verbs = parsed+ .filter((v): v is string => typeof v === 'string')+ .map((v) => v.trim().replace(/\.$/, ''))+ .filter((v) => {+ if (v.length < 4 || v.length > 48) return false;+ if (v.split(/\s+/).length > 6) return false; // ≤ 6 words per phrase+ return true;+ })+ .filter((v) => {+ const first = v.split(/\s+/)[0].toLowerCase();+ return first.endsWith('ing') && !GENERIC_FORBIDDEN.has(first);+ })+ // Case-insensitive dedupe, keep the first occurrence.+ .filter((v, i, all) => all.findIndex((o) => o.toLowerCase() === v.toLowerCase()) === i)+ .slice(0, MAX_VERBS);+ return verbs.length >= MIN_VERBS ? verbs : null;+}++/** Leading verbs that are exactly the generic filler the prompt forbids. */+const GENERIC_FORBIDDEN = new Set(['building', 'crafting', 'noodling', 'doodling', 'cooking', 'brewing', 'working', 'processing']);\ No newline at end of filediff --git a/src/ui/App.tsx b/src/ui/App.tsxindex 0382d95f..16c50979 100644--- a/src/ui/App.tsx+++ b/src/ui/App.tsx@@ -1232,7 +1232,7 @@ function ChatBody({ state, maxDynamicLines }: { state: TuiState; maxDynamicLines</Static><ChatMessagesView messages={dynamicMessages} agentName={state.agentName} maxLines={maxDynamicLines} />{state.toolSteps.length > 0 && !state.isThinking && <ToolStepsView steps={state.toolSteps} viewMode={state.viewMode} idle />}- {state.isThinking && <ThinkingIndicator agentName={state.agentName} steps={state.toolSteps} mode={state.mode} liveActivity={state.liveActivity} thinkingPreview={state.thinkingPreview} statusWord={pickStatusWord({ userText: lastUserText(state.chatMessages) })} />}+ {state.isThinking && <ThinkingIndicator agentName={state.agentName} steps={state.toolSteps} mode={state.mode} liveActivity={state.liveActivity} thinkingPreview={state.thinkingPreview} />}{state.subAgents.length > 0 && <AgentPanelView agents={state.subAgents} />}</Box></Box>@@ -1282,7 +1282,7 @@ function CodingBody({ state, maxDynamicLines }: { state: TuiState; maxDynamicLin</Static><ChatMessagesView messages={dynamicMessages} agentName={state.agentName} maxLines={maxDynamicLines} />{state.toolSteps.length > 0 && !state.isThinking && <ToolStepsView steps={state.toolSteps} viewMode={state.viewMode} idle />}- {state.isThinking && <ThinkingIndicator agentName={state.agentName} steps={state.toolSteps} mode={state.mode} liveActivity={state.liveActivity} thinkingPreview={state.thinkingPreview} statusWord={pickStatusWord({ userText: lastUserText(state.chatMessages) })} />}+ {state.isThinking && <ThinkingIndicator agentName={state.agentName} steps={state.toolSteps} mode={state.mode} liveActivity={state.liveActivity} thinkingPreview={state.thinkingPreview} />}<Box paddingX={1} marginTop={1}><Text dimColor>Mode shortcuts: Ctrl+P Plan · Ctrl+X Execute (Auto runs by default)</Text></Box>@@ -1986,7 +1986,7 @@ function ToolStepsView({ steps, viewMode, idle }: { steps: ToolStep[]; viewMode:);}-function ThinkingIndicator({ agentName, steps, mode, liveActivity, thinkingPreview, frozen, statusWord }: { agentName: string; steps: ToolStep[]; mode: AppMode; liveActivity?: LiveActivityState | null; thinkingPreview?: string | null; frozen?: boolean; statusWord?: string }) {+function ThinkingIndicator({ agentName, steps, mode, liveActivity, thinkingPreview, frozen }: { agentName: string; steps: ToolStep[]; mode: AppMode; liveActivity?: LiveActivityState | null; thinkingPreview?: string | null; frozen?: boolean }) {const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];const [frame, setFrame] = React.useState(0);const [elapsed, setElapsed] = React.useState(0);@@ -2036,7 +2036,7 @@ function ThinkingIndicator({ agentName, steps, mode, liveActivity, thinkingPrevi<Box><Text color={actionTone === 'white' ? 'cyan' : actionTone}>{spinner}</Text><Text> </Text>- <Text color="cyan" bold>{statusWord ?? 'Processing'}</Text>+ <Text color="cyan" bold>Processing</Text><Text dimColor>{totalSteps > 0 ? ` · step ${totalSteps} · ${timeStr}` : ` · ${timeStr}`}</Text></Box><Box marginLeft={4}>@@ -2411,14 +2411,17 @@ function MercuryLiveFeedback({ state }: { state: TuiState }): React.ReactNode {const mins = Math.floor(elapsedSec / 60);const secs = elapsedSec % 60;const timeStr = mins > 0 ? `${mins}m${String(secs).padStart(2, '0')}s` : `${secs}s`;- // Status word: a contextual, playful -ing verb keyed on the user's request- // ("Painting the UI") replaces the generic phase labels — informative- // phases (provider calls, real tool labels) stay as-is. Zero LLM tokens:- // pure keyword matching, rotating slowly so the status feels alive.+ // Status word: Mercury Code's live status row. Session start has no+ // persona yet, so it shows the plain static label; once the agent's+ // one-shot LLM refinement lands (statusVerbs), the row rotates verbs+ // written for THIS project's actual work. Informative phases (provider+ // calls, real tool labels) always win over any of these.const tick = Date.now();const statusWord = state.programmingMode === 'plan'? PLANNING_VERBS[Math.floor(tick / 12_000) % PLANNING_VERBS.length]- : pickStatusWord({ userText: lastUserText(state.chatMessages) }, tick);+ : state.statusVerbs && state.statusVerbs.length > 0+ ? pickStatusWord({ userText: lastUserText(state.chatMessages), dynamicVerbs: state.statusVerbs }, tick)+ : 'Working';const phase = (activity?.phase && !GENERIC_PHASES.has(activity.phase) ? activity.phase : null)?? (running? running.labeldiff --git a/src/ui/status-word.test.ts b/src/ui/status-word.test.tsindex 1f5231cb..80f1bec0 100644--- a/src/ui/status-word.test.ts+++ b/src/ui/status-word.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest';-import { GENERIC_PHASES, PLANNING_VERBS, lastUserText, pickStatusWord } from './status-word.js';+import { GENERIC_PHASES, PLANNING_VERBS, lastUserText, pickStatusWord, verbPoolFor } from './status-word.js';import type { ChatMessage } from './types.js';/**@@ -63,4 +63,37 @@ describe('contextual status words', () => {expect(GENERIC_PHASES.has('Working')).toBe(true);expect(GENERIC_PHASES.has('Calling deepseek')).toBe(false);});++ it('a dynamic (LLM) pool fully replaces the keyword pools', () => {+ const dynamic = ['Extracting the parser', 'Rerouting the auth flow', 'Wiring the contract tests'];+ // Even a strongly keyword-matched request ("fix the flaky test") must NOT+ // pull from the keyword pools while the LLM pool is live.+ const a = pickStatusWord({ userText: 'fix the flaky test', dynamicVerbs: dynamic }, 0);+ const b = pickStatusWord({ userText: 'fix the flaky test', dynamicVerbs: dynamic }, 12_000);+ expect(dynamic).toContain(a);+ expect(dynamic).toContain(b);+ expect(a).not.toBe(b); // the 12s bucket rotates within the pool+ // And it is stable within a bucket (no flicker), as with keyword pools.+ expect(a).toBe(pickStatusWord({ userText: 'fix the flaky test', dynamicVerbs: dynamic }, 11_999));+ });++ it('dynamic pool rotates deterministically and never returns outside it', () => {+ const dynamic = ['A', 'B', 'C'];+ for (let i = 0; i < 10; i++) {+ expect(dynamic).toContain(pickStatusWord({ userText: 'anything', dynamicVerbs: dynamic }, i * 3_141));+ }+ });++ it('empty dynamic pool falls back to the keyword engine', () => {+ const word = pickStatusWord({ userText: 'fix the flaky test in auth', dynamicVerbs: [] }, 1_000);+ expect(word).toMatch(/bug|culprit|knot|trace|gauntlet|edge|test|suite/i);+ });++ it('verbPoolFor returns the matched keyword pool (the failure fallback)', () => {+ expect(verbPoolFor('improve the UI design of the download manager')).toEqual(+ verbPoolFor('improve the UI design of the download manager'),+ );+ expect(verbPoolFor('improve the UI design').every((v) => /UI|layout|pixels|interface|screens/i.test(v))).toBe(true);+ expect(verbPoolFor('do the thing with the widgets').length).toBeGreaterThan(0);+ });});\ No newline at end of filediff --git a/src/ui/status-word.ts b/src/ui/status-word.tsindex 277121b6..296ecc5b 100644--- a/src/ui/status-word.ts+++ b/src/ui/status-word.ts@@ -2,12 +2,16 @@ import type { ChatMessage } from './types.js';/*** Contextual status words for the live spinner rows ("Processing" →- * "Painting the UI"). Pure string matching against the user's request text —- * ZERO LLM tokens, zero latency, deterministic per task with slow rotation- * so the word feels alive without flickering.+ * "Painting the UI"). Mercury Code only — the chat surfaces stay static.*- * One-shot LLM generation could layer on top later (one tiny call per task,- * overriding the keyword pick); the keyword engine stays the fallback.+ * Two layers:+ * - LLM-generated session verbs (dynamicVerbs): one tiny call per session,+ * phrases written for the project's actual work. Preferred when present.+ * - This keyword engine: pure string matching, ZERO LLM tokens — the+ * fallback when the LLM call never happened or failed.+ *+ * Both rotate deterministically with a slow tick so the word feels alive+ * without flickering.*/interface VerbGroup {@@ -83,16 +87,17 @@ function hash(text: string): number {export interface StatusWordContext {/** The user's request for the current task (keyword-matching source). */userText?: string;+ /**+ * LLM-generated verb pool for the session (Mercury Code only). When+ * non-empty it fully replaces the keyword pools — these verbs were written+ * for THIS project's actual work, so they are always more specific than a+ * keyword guess. The keyword engine stays the fallback when no pool exists.+ */+ dynamicVerbs?: string[];}-/**- * Pick a playful -ing status word for the current work. Deterministic per- * (task text, rotation bucket): different tasks start on different verbs, and- * the verb rotates slowly within its pool so the status feels alive. Never- * throws, never empty, always suitable as a spinner label.- */-export function pickStatusWord(ctx: StatusWordContext = {}, tick = Date.now()): string {- const text = (ctx.userText ?? '').toLowerCase();+/** Keyword-group match shared by pickStatusWord and verbPoolFor. */+function matchVerbGroup(text: string): VerbGroup | null {let best: VerbGroup | null = null;let bestHits = 0;for (const group of VERB_GROUPS) {@@ -105,7 +110,30 @@ export function pickStatusWord(ctx: StatusWordContext = {}, tick = Date.now()):bestHits = hits;}}- const pool = best?.verbs ?? GENERIC_VERBS;+ return best;+}++/**+ * The keyword pool for a request — the static fallback the agent pushes as+ * `statusVerbs` when the one-shot LLM refinement fails, so the session keeps+ * contextual (if less specific) words instead of nothing.+ */+export function verbPoolFor(userText: string): string[] {+ const best = matchVerbGroup((userText ?? '').toLowerCase());+ return best?.verbs ?? GENERIC_VERBS;+}++/**+ * Pick a playful -ing status word for the current work. Deterministic per+ * (task text, rotation bucket): different tasks start on different verbs, and+ * the verb rotates slowly within its pool so the status feels alive. Never+ * throws, never empty, always suitable as a spinner label.+ */+export function pickStatusWord(ctx: StatusWordContext = {}, tick = Date.now()): string {+ const text = (ctx.userText ?? '').toLowerCase();+ const pool = (ctx.dynamicVerbs && ctx.dynamicVerbs.length > 0 ? ctx.dynamicVerbs : null)+ ?? matchVerbGroup(text)?.verbs+ ?? GENERIC_VERBS;return pool[(hash(text) + Math.floor(tick / ROTATE_MS)) % pool.length];}