Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(ui): show the Do next and Fix first agent prompts that core renders (#2859)
Raghav Chamadiya6ca0485b7f6b
diff --git a/packages/core/src/repowise/core/agent_prompts/__init__.py b/packages/core/src/repowise/core/agent_prompts/__init__.pyindex 35adb4706..e8873d749 100644--- a/packages/core/src/repowise/core/agent_prompts/__init__.py+++ b/packages/core/src/repowise/core/agent_prompts/__init__.py@@ -1,9 +1,8 @@"""Agent prompts rendered in core: plain wire dicts in, prompt text out.No session and no store: a caller loads the item the way it already does and-hands over its ``as_dict()``. The web builders in-``packages/ui/src/health/ai-prompts`` render the same bytes, which the goldens in-``tests/fixtures/agent_prompts`` check from both sides.+hands over its ``as_dict()``. The only renderer of these prompts: the web shows+them from the server, and ``tests/fixtures/agent_prompts`` pins the bytes."""from __future__ import annotationsdiff --git a/packages/core/src/repowise/core/agent_prompts/action.py b/packages/core/src/repowise/core/agent_prompts/action.pyindex 134c8cc7c..806d4a97c 100644--- a/packages/core/src/repowise/core/agent_prompts/action.py+++ b/packages/core/src/repowise/core/agent_prompts/action.py@@ -2,7 +2,7 @@the rest, and what finished looks like.Takes the action's wire dict (``Action.as_dict()``), so the evidence is already-capped the way every surface sees it. Port of ``buildActionPrompt``.+capped the way every surface sees it."""from __future__ import annotationsdiff --git a/packages/core/src/repowise/core/agent_prompts/fix_first.py b/packages/core/src/repowise/core/agent_prompts/fix_first.pyindex d2a874918..66434b168 100644--- a/packages/core/src/repowise/core/agent_prompts/fix_first.py+++ b/packages/core/src/repowise/core/agent_prompts/fix_first.py@@ -2,8 +2,7 @@order, and how to verify it.Takes the item's wire dict (``FixItem.as_dict()``) and only arranges fields core-already worded; the sentences themselves come from ``fix_first.text``. Port of-``buildFixItemPrompt`` and ``fixVerifyLines``.+already worded; the sentences themselves come from ``fix_first.text``."""from __future__ import annotationsdiff --git a/packages/core/src/repowise/core/agent_prompts/sections.py b/packages/core/src/repowise/core/agent_prompts/sections.pyindex 853a48dd2..13e86fd48 100644--- a/packages/core/src/repowise/core/agent_prompts/sections.py+++ b/packages/core/src/repowise/core/agent_prompts/sections.py@@ -1,7 +1,8 @@"""The section helpers every agent prompt is written with.-Ports of ``packages/ui/src/health/ai-prompts/shared.ts``; the parity goldens in-``tests/fixtures/agent_prompts`` hold the two to the same bytes.+Written to match ``packages/ui/src/health/ai-prompts/shared.ts``, which the web's+own prompt builders use; the goldens in ``tests/fixtures/agent_prompts`` pin+core's output."""from __future__ import annotationsdiff --git a/packages/ui/__tests__/health/__snapshots__/action-prompt.test.ts.snap b/packages/ui/__tests__/health/__snapshots__/action-prompt.test.ts.snapdeleted file mode 100644index 85bfd7c30..000000000--- a/packages/ui/__tests__/health/__snapshots__/action-prompt.test.ts.snap+++ /dev/null@@ -1,117 +0,0 @@-// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html--exports[`buildActionPrompt > keeps every flavor's text unchanged > claude-code 1`] = `-"You are Claude Code in this repository. Repowise, a code-intelligence index, produced the action below from its stored analysis. Treat each evidence item as a lead: read the code with Read and Grep, confirm it, and use TodoWrite to track the files you work through.-## Action (\`repo\`)-**Clean up what this week's commits left: 3 serious findings in 2 files**-2 commits in the last 7 days added or worsened them.-## Why it is on the list-- critical: 1-- Effort estimate: M; confidence in the facts: high-## Evidence (1 of 3, worst first)-- \`src/a.py:40\`: \`build\`, Complex method, critical (commit abc1234def)- - build has cyclomatic complexity 31--…and 2 more. The first call under "Look closer" returns them.-## Look closer (Repowise CLI)-- Every open finding in these files:- \`repowise health --file src/a.py\`-## Done when-The findings close on the next update.-## Hard constraints-- **Confirm each item before changing anything.** The analysis is stored, not live; the code may have moved since it ran.-- **Stay inside what the action names.** Work only on the files and functions listed. If the right fix is elsewhere, stop and say where and why.-- **Keep behaviour unless the action is about behaviour.** Refactors and test additions must not change what the code does; run the tests that cover each file before and after.-- **Say when an item is wrong.** If a finding does not hold, or its fix would cost more than it saves, report that rather than forcing an edit.-## What I expect back-1. For each item you looked at: whether it held, and what you changed or why you left it.-2. The tests you ran, before and after.-3. What remains against the done condition."-`;--exports[`buildActionPrompt > keeps every flavor's text unchanged > claude-code-mcp 1`] = `-"You are Claude Code in this repository, which Repowise indexes and serves over MCP. The action below comes from Repowise's stored analysis. Use the MCP calls listed under "Look closer" before reading files by hand: they return the full evidence with line numbers, reasons and history. Treat each item as a lead to confirm against the code.-## Action (\`repo\`)-**Clean up what this week's commits left: 3 serious findings in 2 files**-2 commits in the last 7 days added or worsened them.-## Why it is on the list-- critical: 1-- Effort estimate: M; confidence in the facts: high-## Evidence (1 of 3, worst first)-- \`src/a.py:40\`: \`build\`, Complex method, critical (commit abc1234def)- - build has cyclomatic complexity 31--…and 2 more. The first call under "Look closer" returns them.-## Look closer (Repowise MCP)-- Every open finding in these files:- \`get_health(targets=["src/a.py", "src/b.py"], include=["biomarkers"])\`-## Done when-The findings close on the next update.-## Hard constraints-- **Confirm each item before changing anything.** The analysis is stored, not live; the code may have moved since it ran.-- **Stay inside what the action names.** Work only on the files and functions listed. If the right fix is elsewhere, stop and say where and why.-- **Keep behaviour unless the action is about behaviour.** Refactors and test additions must not change what the code does; run the tests that cover each file before and after.-- **Say when an item is wrong.** If a finding does not hold, or its fix would cost more than it saves, report that rather than forcing an edit.-## What I expect back-1. For each item you looked at: whether it held, and what you changed or why you left it.-2. The tests you ran, before and after.-3. What remains against the done condition."-`;--exports[`buildActionPrompt > keeps every flavor's text unchanged > cursor 1`] = `-"Work in this repository. Repowise, a code-intelligence index, produced the action below from its stored analysis. Treat each evidence item as a lead: open the file with @file, confirm it, then act.-## Action (\`repo\`)-**Clean up what this week's commits left: 3 serious findings in 2 files**-2 commits in the last 7 days added or worsened them.-## Why it is on the list-- critical: 1-- Effort estimate: M; confidence in the facts: high-## Evidence (1 of 3, worst first)-- \`src/a.py:40\`: \`build\`, Complex method, critical (commit abc1234def)- - build has cyclomatic complexity 31--…and 2 more. The first call under "Look closer" returns them.-## Look closer (Repowise CLI)-- Every open finding in these files:- \`repowise health --file src/a.py\`-## Done when-The findings close on the next update.-## Hard constraints-- **Confirm each item before changing anything.** The analysis is stored, not live; the code may have moved since it ran.-- **Stay inside what the action names.** Work only on the files and functions listed. If the right fix is elsewhere, stop and say where and why.-- **Keep behaviour unless the action is about behaviour.** Refactors and test additions must not change what the code does; run the tests that cover each file before and after.-- **Say when an item is wrong.** If a finding does not hold, or its fix would cost more than it saves, report that rather than forcing an edit.-## What I expect back-1. For each item you looked at: whether it held, and what you changed or why you left it.-2. The tests you ran, before and after.-3. What remains against the done condition."-`;--exports[`buildActionPrompt > keeps every flavor's text unchanged > generic 1`] = `-"You are a senior engineer in this repository. Repowise, a code-intelligence index, produced the action below from its stored analysis of the repository (git history, code health, the dependency graph). Its evidence is listed in full or in part; treat each item as a lead to verify against the code, not as ground truth.-## Action (\`repo\`)-**Clean up what this week's commits left: 3 serious findings in 2 files**-2 commits in the last 7 days added or worsened them.-## Why it is on the list-- critical: 1-- Effort estimate: M; confidence in the facts: high-## Evidence (1 of 3, worst first)-- \`src/a.py:40\`: \`build\`, Complex method, critical (commit abc1234def)- - build has cyclomatic complexity 31--…and 2 more. The first call under "Look closer" returns them.-## Look closer (Repowise CLI)-- Every open finding in these files:- \`repowise health --file src/a.py\`-## Done when-The findings close on the next update.-## Hard constraints-- **Confirm each item before changing anything.** The analysis is stored, not live; the code may have moved since it ran.-- **Stay inside what the action names.** Work only on the files and functions listed. If the right fix is elsewhere, stop and say where and why.-- **Keep behaviour unless the action is about behaviour.** Refactors and test additions must not change what the code does; run the tests that cover each file before and after.-- **Say when an item is wrong.** If a finding does not hold, or its fix would cost more than it saves, report that rather than forcing an edit.-## What I expect back-1. For each item you looked at: whether it held, and what you changed or why you left it.-2. The tests you ran, before and after.-3. What remains against the done condition."-`;diff --git a/packages/ui/__tests__/health/__snapshots__/fix-first.test.tsx.snap b/packages/ui/__tests__/health/__snapshots__/fix-first.test.tsx.snapdeleted file mode 100644index a95516c3e..000000000--- a/packages/ui/__tests__/health/__snapshots__/fix-first.test.tsx.snap+++ /dev/null@@ -1,419 +0,0 @@-// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html--exports[`Fix first agent prompt > keeps every flavor's text unchanged > fix1_2b0e5c0acbb469f46aa9 claude-code 1`] = `-"You are Claude Code in this repository. Repowise, a code-intelligence index, ranked the change below first among the work it found. Confirm each fact with Read and Grep before editing, and track the steps with TodoWrite.-## Fix first (\`repo\`)-**Extract lines 60-122 of quick_repo_scan into compute_info**-quick_repo_scan: CCN 15, 44 lines, nests 3 deep; 4 files import it, changed 5 times in 90 days.-## Facts-- Target: \`packages/cli/src/repowise/cli/ui/repo_scanner.py:60\` (\`quick_repo_scan\`)-- Gain: +1.7 health on this file-- Effort: S (sized by the stored plan)-- Risk: Touches 1 file; 4 files import it.-- Confidence: high. 1 of 1 step proven mechanical by the plan-- health recoverable: +1.7 (inferred)-- steps: 1 (1 mechanical)-- files that import it: 4-- changes in 90 days: 5-- file size: 149 lines-## Steps, in order-1. Extract lines 60-122 of quick_repo_scan into compute_info(repo_path) -> info (\`packages/cli/src/repowise/cli/ui/repo_scanner.py:60\`) [mechanical]-## Verify-- \`tests/unit/cli/test_repo_scanner.py\`: reaches the changed code through the call-graph-- \`tests/unit/cli/test_edenai_reachability.py\`: reaches the changed code through the call-graph-- \`tests/unit/cli/test_file_page_volume_prompt.py\`: reaches the changed code through the call-graph-- \`tests/unit/cli/test_ui_package.py\`: reaches the changed code through the call-graph--Run: \`pytest tests/unit/cli/test_edenai_reachability.py tests/unit/cli/test_file_page_volume_prompt.py tests/unit/cli/test_repo_scanner.py tests/unit/cli/test_ui_package.py\`-## Hard constraints-- **Confirm before changing.** The analysis is stored, not live; the code may have moved since it ran.-- **Keep behaviour.** This is a structural or performance change; what the code returns must not change.-- **Run Verify before and after.** If no guarding test exists, write one that pins today's behaviour first.-- **Say when it is wrong.** If the problem does not hold, or the change costs more than it saves, report that and stop.-## What I expect back-1. Whether the problem held, and what you changed.-2. The Verify run, before and after, with its result.-3. Anything you left undone, and why."-`;--exports[`Fix first agent prompt > keeps every flavor's text unchanged > fix1_2b0e5c0acbb469f46aa9 claude-code-mcp 1`] = `-"You are Claude Code in this repository, which Repowise indexes and serves over MCP. Repowise ranked the change below first among the work it found. Call the MCP lookup under "Look closer" for the full record before reading files by hand, then confirm each fact against the code.-## Fix first (\`repo\`)-**Extract lines 60-122 of quick_repo_scan into compute_info**-quick_repo_scan: CCN 15, 44 lines, nests 3 deep; 4 files import it, changed 5 times in 90 days.-## Facts-- Target: \`packages/cli/src/repowise/cli/ui/repo_scanner.py:60\` (\`quick_repo_scan\`)-- Gain: +1.7 health on this file-- Effort: S (sized by the stored plan)-- Risk: Touches 1 file; 4 files import it.-- Confidence: high. 1 of 1 step proven mechanical by the plan-- health recoverable: +1.7 (inferred)-- steps: 1 (1 mechanical)-- files that import it: 4-- changes in 90 days: 5-- file size: 149 lines-## Steps, in order-1. Extract lines 60-122 of quick_repo_scan into compute_info(repo_path) -> info (\`packages/cli/src/repowise/cli/ui/repo_scanner.py:60\`) [mechanical]-## Verify-- \`tests/unit/cli/test_repo_scanner.py\`: reaches the changed code through the call-graph-- \`tests/unit/cli/test_edenai_reachability.py\`: reaches the changed code through the call-graph-- \`tests/unit/cli/test_file_page_volume_prompt.py\`: reaches the changed code through the call-graph-- \`tests/unit/cli/test_ui_package.py\`: reaches the changed code through the call-graph--Run: \`pytest tests/unit/cli/test_edenai_reachability.py tests/unit/cli/test_file_page_volume_prompt.py tests/unit/cli/test_repo_scanner.py tests/unit/cli/test_ui_package.py\`-## Look closer (Repowise MCP)-\`get_health(opportunity_id="refop3_8ba13d978db910d160b1")\`-## Hard constraints-- **Confirm before changing.** The analysis is stored, not live; the code may have moved since it ran.-- **Keep behaviour.** This is a structural or performance change; what the code returns must not change.-- **Run Verify before and after.** If no guarding test exists, write one that pins today's behaviour first.-- **Say when it is wrong.** If the problem does not hold, or the change costs more than it saves, report that and stop.-## What I expect back-1. Whether the problem held, and what you changed.-2. The Verify run, before and after, with its result.-3. Anything you left undone, and why."-`;--exports[`Fix first agent prompt > keeps every flavor's text unchanged > fix1_2b0e5c0acbb469f46aa9 cursor 1`] = `-"Work in this repository. Repowise, a code-intelligence index, ranked the change below first among the work it found. Open the target with @file, confirm each fact, then make the change.-## Fix first (\`repo\`)-**Extract lines 60-122 of quick_repo_scan into compute_info**-quick_repo_scan: CCN 15, 44 lines, nests 3 deep; 4 files import it, changed 5 times in 90 days.-## Facts-- Target: \`packages/cli/src/repowise/cli/ui/repo_scanner.py:60\` (\`quick_repo_scan\`)-- Gain: +1.7 health on this file-- Effort: S (sized by the stored plan)-- Risk: Touches 1 file; 4 files import it.-- Confidence: high. 1 of 1 step proven mechanical by the plan-- health recoverable: +1.7 (inferred)-- steps: 1 (1 mechanical)-- files that import it: 4-- changes in 90 days: 5-- file size: 149 lines-## Steps, in order-1. Extract lines 60-122 of quick_repo_scan into compute_info(repo_path) -> info (\`packages/cli/src/repowise/cli/ui/repo_scanner.py:60\`) [mechanical]-## Verify-- \`tests/unit/cli/test_repo_scanner.py\`: reaches the changed code through the call-graph-- \`tests/unit/cli/test_edenai_reachability.py\`: reaches the changed code through the call-graph-- \`tests/unit/cli/test_file_page_volume_prompt.py\`: reaches the changed code through the call-graph-- \`tests/unit/cli/test_ui_package.py\`: reaches the changed code through the call-graph--Run: \`pytest tests/unit/cli/test_edenai_reachability.py tests/unit/cli/test_file_page_volume_prompt.py tests/unit/cli/test_repo_scanner.py tests/unit/cli/test_ui_package.py\`-## Hard constraints-- **Confirm before changing.** The analysis is stored, not live; the code may have moved since it ran.-- **Keep behaviour.** This is a structural or performance change; what the code returns must not change.-- **Run Verify before and after.** If no guarding test exists, write one that pins today's behaviour first.-- **Say when it is wrong.** If the problem does not hold, or the change costs more than it saves, report that and stop.-## What I expect back-1. Whether the problem held, and what you changed.-2. The Verify run, before and after, with its result.-3. Anything you left undone, and why."-`;--exports[`Fix first agent prompt > keeps every flavor's text unchanged > fix1_2b0e5c0acbb469f46aa9 generic 1`] = `-"You are a senior engineer in this repository. Repowise, a code-intelligence index, ranked the change below first among the work it found. Its facts come from stored analysis; treat them as leads to confirm against the code, not as ground truth.-## Fix first (\`repo\`)-**Extract lines 60-122 of quick_repo_scan into compute_info**-quick_repo_scan: CCN 15, 44 lines, nests 3 deep; 4 files import it, changed 5 times in 90 days.-## Facts-- Target: \`packages/cli/src/repowise/cli/ui/repo_scanner.py:60\` (\`quick_repo_scan\`)-- Gain: +1.7 health on this file-- Effort: S (sized by the stored plan)-- Risk: Touches 1 file; 4 files import it.-- Confidence: high. 1 of 1 step proven mechanical by the plan-- health recoverable: +1.7 (inferred)-- steps: 1 (1 mechanical)-- files that import it: 4-- changes in 90 days: 5-- file size: 149 lines-## Steps, in order-1. Extract lines 60-122 of quick_repo_scan into compute_info(repo_path) -> info (\`packages/cli/src/repowise/cli/ui/repo_scanner.py:60\`) [mechanical]-## Verify-- \`tests/unit/cli/test_repo_scanner.py\`: reaches the changed code through the call-graph-- \`tests/unit/cli/test_edenai_reachability.py\`: reaches the changed code through the call-graph-- \`tests/unit/cli/test_file_page_volume_prompt.py\`: reaches the changed code through the call-graph-- \`tests/unit/cli/test_ui_package.py\`: reaches the changed code through the call-graph--Run: \`pytest tests/unit/cli/test_edenai_reachability.py tests/unit/cli/test_file_page_volume_prompt.py tests/unit/cli/test_repo_scanner.py tests/unit/cli/test_ui_package.py\`-## Hard constraints-- **Confirm before changing.** The analysis is stored, not live; the code may have moved since it ran.-- **Keep behaviour.** This is a structural or performance change; what the code returns must not change.-- **Run Verify before and after.** If no guarding test exists, write one that pins today's behaviour first.-- **Say when it is wrong.** If the problem does not hold, or the change costs more than it saves, report that and stop.-## What I expect back-1. Whether the problem held, and what you changed.-2. The Verify run, before and after, with its result.-3. Anything you left undone, and why."-`;--exports[`Fix first agent prompt > keeps every flavor's text unchanged > fix1_8ac4c08f700f837e9087 claude-code 1`] = `-"You are Claude Code in this repository. Repowise, a code-intelligence index, ranked the change below first among the work it found. Confirm each fact with Read and Grep before editing, and track the steps with TodoWrite.-## Fix first (\`repo\`)-**Break up GraphFlow (CCN 260, 1,094 lines)**-GraphFlow: CCN 260, 1,094 lines, nests 7 deep; 4 files import it, changed 13 times in 90 days.-## Facts-- Target: \`packages/ui/src/graph/graph-flow.tsx:198\` (\`GraphFlow\`)-- Gain: up to +1.8 health on this file-- Effort: M (not sized; no stored plan covers this finding)-- Risk: Touches 1 file; 4 files import it.-- Confidence: medium. Measured from the code; no stored plan has checked a fix.-- finding: nested_complexity-- severity: critical-- files that import it: 4-- changes in 90 days: 13-## Steps, in order-1. Flatten the control flow. (\`packages/ui/src/graph/graph-flow.tsx:198\`) [judgment]-## Verify-No guarding tests found. Write a test that pins the current behaviour before you change anything.-## Hard constraints-- **Confirm before changing.** The analysis is stored, not live; the code may have moved since it ran.-- **Keep behaviour.** This is a structural or performance change; what the code returns must not change.-- **Run Verify before and after.** If no guarding test exists, write one that pins today's behaviour first.-- **Say when it is wrong.** If the problem does not hold, or the change costs more than it saves, report that and stop.-## What I expect back-1. Whether the problem held, and what you changed.-2. The Verify run, before and after, with its result.-3. Anything you left undone, and why."-`;--exports[`Fix first agent prompt > keeps every flavor's text unchanged > fix1_8ac4c08f700f837e9087 claude-code-mcp 1`] = `-"You are Claude Code in this repository, which Repowise indexes and serves over MCP. Repowise ranked the change below first among the work it found. Call the MCP lookup under "Look closer" for the full record before reading files by hand, then confirm each fact against the code.-## Fix first (\`repo\`)-**Break up GraphFlow (CCN 260, 1,094 lines)**-GraphFlow: CCN 260, 1,094 lines, nests 7 deep; 4 files import it, changed 13 times in 90 days.-## Facts-- Target: \`packages/ui/src/graph/graph-flow.tsx:198\` (\`GraphFlow\`)-- Gain: up to +1.8 health on this file-- Effort: M (not sized; no stored plan covers this finding)-- Risk: Touches 1 file; 4 files import it.-- Confidence: medium. Measured from the code; no stored plan has checked a fix.-- finding: nested_complexity-- severity: critical-- files that import it: 4-- changes in 90 days: 13-## Steps, in order-1. Flatten the control flow. (\`packages/ui/src/graph/graph-flow.tsx:198\`) [judgment]-## Verify-No guarding tests found. Write a test that pins the current behaviour before you change anything.-## Look closer (Repowise MCP)-\`get_health(targets=["packages/ui/src/graph/graph-flow.tsx"], include=["biomarkers"])\`-## Hard constraints-- **Confirm before changing.** The analysis is stored, not live; the code may have moved since it ran.-- **Keep behaviour.** This is a structural or performance change; what the code returns must not change.-- **Run Verify before and after.** If no guarding test exists, write one that pins today's behaviour first.-- **Say when it is wrong.** If the problem does not hold, or the change costs more than it saves, report that and stop.-## What I expect back-1. Whether the problem held, and what you changed.-2. The Verify run, before and after, with its result.-3. Anything you left undone, and why."-`;--exports[`Fix first agent prompt > keeps every flavor's text unchanged > fix1_8ac4c08f700f837e9087 cursor 1`] = `-"Work in this repository. Repowise, a code-intelligence index, ranked the change below first among the work it found. Open the target with @file, confirm each fact, then make the change.-## Fix first (\`repo\`)-**Break up GraphFlow (CCN 260, 1,094 lines)**-GraphFlow: CCN 260, 1,094 lines, nests 7 deep; 4 files import it, changed 13 times in 90 days.-## Facts-- Target: \`packages/ui/src/graph/graph-flow.tsx:198\` (\`GraphFlow\`)-- Gain: up to +1.8 health on this file-- Effort: M (not sized; no stored plan covers this finding)-- Risk: Touches 1 file; 4 files import it.-- Confidence: medium. Measured from the code; no stored plan has checked a fix.-- finding: nested_complexity-- severity: critical-- files that import it: 4-- changes in 90 days: 13-## Steps, in order-1. Flatten the control flow. (\`packages/ui/src/graph/graph-flow.tsx:198\`) [judgment]-## Verify-No guarding tests found. Write a test that pins the current behaviour before you change anything.-## Hard constraints-- **Confirm before changing.** The analysis is stored, not live; the code may have moved since it ran.-- **Keep behaviour.** This is a structural or performance change; what the code returns must not change.-- **Run Verify before and after.** If no guarding test exists, write one that pins today's behaviour first.-- **Say when it is wrong.** If the problem does not hold, or the change costs more than it saves, report that and stop.-## What I expect back-1. Whether the problem held, and what you changed.-2. The Verify run, before and after, with its result.-3. Anything you left undone, and why."-`;--exports[`Fix first agent prompt > keeps every flavor's text unchanged > fix1_8ac4c08f700f837e9087 generic 1`] = `-"You are a senior engineer in this repository. Repowise, a code-intelligence index, ranked the change below first among the work it found. Its facts come from stored analysis; treat them as leads to confirm against the code, not as ground truth.-## Fix first (\`repo\`)-**Break up GraphFlow (CCN 260, 1,094 lines)**-GraphFlow: CCN 260, 1,094 lines, nests 7 deep; 4 files import it, changed 13 times in 90 days.-## Facts-- Target: \`packages/ui/src/graph/graph-flow.tsx:198\` (\`GraphFlow\`)-- Gain: up to +1.8 health on this file-- Effort: M (not sized; no stored plan covers this finding)-- Risk: Touches 1 file; 4 files import it.-- Confidence: medium. Measured from the code; no stored plan has checked a fix.-- finding: nested_complexity-- severity: critical-- files that import it: 4-- changes in 90 days: 13-## Steps, in order-1. Flatten the control flow. (\`packages/ui/src/graph/graph-flow.tsx:198\`) [judgment]-## Verify-No guarding tests found. Write a test that pins the current behaviour before you change anything.-## Hard constraints-- **Confirm before changing.** The analysis is stored, not live; the code may have moved since it ran.-- **Keep behaviour.** This is a structural or performance change; what the code returns must not change.-- **Run Verify before and after.** If no guarding test exists, write one that pins today's behaviour first.-- **Say when it is wrong.** If the problem does not hold, or the change costs more than it saves, report that and stop.-## What I expect back-1. Whether the problem held, and what you changed.-2. The Verify run, before and after, with its result.-3. Anything you left undone, and why."-`;--exports[`Fix first agent prompt > keeps every flavor's text unchanged > fix1_26c2da3b4c98f8fdef56 claude-code 1`] = `-"You are Claude Code in this repository. Repowise, a code-intelligence index, ranked the change below first among the work it found. Confirm each fact with Read and Grep before editing, and track the steps with TodoWrite.-## Fix first (\`repo\`)-**Batch the database calls loops make through ensure_repo_registration**-ensure_repo_registration makes a database call once per loop iteration; 2 call sites in 2 files reach it, an entry point reaches it, the loop grows with the data.-## Facts-- Target: \`packages/server/src/repowise/server/repo_db.py\` (\`ensure_repo_registration\`)-- Gain: one database call per loop iteration, grows with the data-- Effort: M (sized by the stored plan)-- Risk: Touches 2 files.-- Confidence: medium. The shared I/O sink is proven; no concrete batch API or result-equivalence proof is available.-- call sites: 2-- files: 2-- reachable from an entry point: Yes (inferred)-- loop size: grows with data (inferred)-## Steps, in order-1. Add a form of ensure_repo_registration that takes every key at once (\`packages/server/src/repowise/server/repo_db.py\`) [judgment]-2. Collect the keys before the loop and call the batched form once (rediscover_repo_dbs) (\`packages/server/src/repowise/server/repo_db.py:274\`) [judgment]-3. Collect the keys before the loop and call the batched form once (sync_workspace) (\`packages/server/src/repowise/server/routers/workspace.py:920\`) [judgment]-## Verify-- \`tests/unit/server/test_app_lifespan.py\`: reaches the changed code through the call-graph-- \`tests/unit/server/test_app_workspace_registry.py\`: reaches the changed code through the call-graph-- \`tests/unit/server/test_workspace_search_postgres.py\`: reaches the changed code through the call-graph-- \`tests/unit/server/test_workspace_router.py\`: reaches the changed code through the call-graph--Run: \`pytest tests/unit/server/test_app_lifespan.py tests/unit/server/test_app_workspace_registry.py tests/unit/server/test_workspace_router.py tests/unit/server/test_workspace_search_postgres.py\`-## Hard constraints-- **Confirm before changing.** The analysis is stored, not live; the code may have moved since it ran.-- **Keep behaviour.** This is a structural or performance change; what the code returns must not change.-- **Run Verify before and after.** If no guarding test exists, write one that pins today's behaviour first.-- **Say when it is wrong.** If the problem does not hold, or the change costs more than it saves, report that and stop.-## What I expect back-1. Whether the problem held, and what you changed.-2. The Verify run, before and after, with its result.-3. Anything you left undone, and why."-`;--exports[`Fix first agent prompt > keeps every flavor's text unchanged > fix1_26c2da3b4c98f8fdef56 claude-code-mcp 1`] = `-"You are Claude Code in this repository, which Repowise indexes and serves over MCP. Repowise ranked the change below first among the work it found. Call the MCP lookup under "Look closer" for the full record before reading files by hand, then confirm each fact against the code.-## Fix first (\`repo\`)-**Batch the database calls loops make through ensure_repo_registration**-ensure_repo_registration makes a database call once per loop iteration; 2 call sites in 2 files reach it, an entry point reaches it, the loop grows with the data.-## Facts-- Target: \`packages/server/src/repowise/server/repo_db.py\` (\`ensure_repo_registration\`)-- Gain: one database call per loop iteration, grows with the data-- Effort: M (sized by the stored plan)-- Risk: Touches 2 files.-- Confidence: medium. The shared I/O sink is proven; no concrete batch API or result-equivalence proof is available.-- call sites: 2-- files: 2-- reachable from an entry point: Yes (inferred)-- loop size: grows with data (inferred)-## Steps, in order-1. Add a form of ensure_repo_registration that takes every key at once (\`packages/server/src/repowise/server/repo_db.py\`) [judgment]-2. Collect the keys before the loop and call the batched form once (rediscover_repo_dbs) (\`packages/server/src/repowise/server/repo_db.py:274\`) [judgment]-3. Collect the keys before the loop and call the batched form once (sync_workspace) (\`packages/server/src/repowise/server/routers/workspace.py:920\`) [judgment]-## Verify-- \`tests/unit/server/test_app_lifespan.py\`: reaches the changed code through the call-graph-- \`tests/unit/server/test_app_workspace_registry.py\`: reaches the changed code through the call-graph-- \`tests/unit/server/test_workspace_search_postgres.py\`: reaches the changed code through the call-graph-- \`tests/unit/server/test_workspace_router.py\`: reaches the changed code through the call-graph--Run: \`pytest tests/unit/server/test_app_lifespan.py tests/unit/server/test_app_workspace_registry.py tests/unit/server/test_workspace_router.py tests/unit/server/test_workspace_search_postgres.py\`-## Look closer (Repowise MCP)-\`get_health(opportunity_id="perf2_5ca551b7b7c3293951d0")\`-## Hard constraints-- **Confirm before changing.** The analysis is stored, not live; the code may have moved since it ran.-- **Keep behaviour.** This is a structural or performance change; what the code returns must not change.-- **Run Verify before and after.** If no guarding test exists, write one that pins today's behaviour first.-- **Say when it is wrong.** If the problem does not hold, or the change costs more than it saves, report that and stop.-## What I expect back-1. Whether the problem held, and what you changed.-2. The Verify run, before and after, with its result.-3. Anything you left undone, and why."-`;--exports[`Fix first agent prompt > keeps every flavor's text unchanged > fix1_26c2da3b4c98f8fdef56 cursor 1`] = `-"Work in this repository. Repowise, a code-intelligence index, ranked the change below first among the work it found. Open the target with @file, confirm each fact, then make the change.-## Fix first (\`repo\`)-**Batch the database calls loops make through ensure_repo_registration**-ensure_repo_registration makes a database call once per loop iteration; 2 call sites in 2 files reach it, an entry point reaches it, the loop grows with the data.-## Facts-- Target: \`packages/server/src/repowise/server/repo_db.py\` (\`ensure_repo_registration\`)-- Gain: one database call per loop iteration, grows with the data-- Effort: M (sized by the stored plan)-- Risk: Touches 2 files.-- Confidence: medium. The shared I/O sink is proven; no concrete batch API or result-equivalence proof is available.-- call sites: 2-- files: 2-- reachable from an entry point: Yes (inferred)-- loop size: grows with data (inferred)-## Steps, in order-1. Add a form of ensure_repo_registration that takes every key at once (\`packages/server/src/repowise/server/repo_db.py\`) [judgment]-2. Collect the keys before the loop and call the batched form once (rediscover_repo_dbs) (\`packages/server/src/repowise/server/repo_db.py:274\`) [judgment]-3. Collect the keys before the loop and call the batched form once (sync_workspace) (\`packages/server/src/repowise/server/routers/workspace.py:920\`) [judgment]-## Verify-- \`tests/unit/server/test_app_lifespan.py\`: reaches the changed code through the call-graph-- \`tests/unit/server/test_app_workspace_registry.py\`: reaches the changed code through the call-graph-- \`tests/unit/server/test_workspace_search_postgres.py\`: reaches the changed code through the call-graph-- \`tests/unit/server/test_workspace_router.py\`: reaches the changed code through the call-graph--Run: \`pytest tests/unit/server/test_app_lifespan.py tests/unit/server/test_app_workspace_registry.py tests/unit/server/test_workspace_router.py tests/unit/server/test_workspace_search_postgres.py\`-## Hard constraints-- **Confirm before changing.** The analysis is stored, not live; the code may have moved since it ran.-- **Keep behaviour.** This is a structural or performance change; what the code returns must not change.-- **Run Verify before and after.** If no guarding test exists, write one that pins today's behaviour first.-- **Say when it is wrong.** If the problem does not hold, or the change costs more than it saves, report that and stop.-## What I expect back-1. Whether the problem held, and what you changed.-2. The Verify run, before and after, with its result.-3. Anything you left undone, and why."-`;--exports[`Fix first agent prompt > keeps every flavor's text unchanged > fix1_26c2da3b4c98f8fdef56 generic 1`] = `-"You are a senior engineer in this repository. Repowise, a code-intelligence index, ranked the change below first among the work it found. Its facts come from stored analysis; treat them as leads to confirm against the code, not as ground truth.-## Fix first (\`repo\`)-**Batch the database calls loops make through ensure_repo_registration**-ensure_repo_registration makes a database call once per loop iteration; 2 call sites in 2 files reach it, an entry point reaches it, the loop grows with the data.-## Facts-- Target: \`packages/server/src/repowise/server/repo_db.py\` (\`ensure_repo_registration\`)-- Gain: one database call per loop iteration, grows with the data-- Effort: M (sized by the stored plan)-- Risk: Touches 2 files.-- Confidence: medium. The shared I/O sink is proven; no concrete batch API or result-equivalence proof is available.-- call sites: 2-- files: 2-- reachable from an entry point: Yes (inferred)-- loop size: grows with data (inferred)-## Steps, in order-1. Add a form of ensure_repo_registration that takes every key at once (\`packages/server/src/repowise/server/repo_db.py\`) [judgment]-2. Collect the keys before the loop and call the batched form once (rediscover_repo_dbs) (\`packages/server/src/repowise/server/repo_db.py:274\`) [judgment]-3. Collect the keys before the loop and call the batched form once (sync_workspace) (\`packages/server/src/repowise/server/routers/workspace.py:920\`) [judgment]-## Verify-- \`tests/unit/server/test_app_lifespan.py\`: reaches the changed code through the call-graph-- \`tests/unit/server/test_app_workspace_registry.py\`: reaches the changed code through the call-graph-- \`tests/unit/server/test_workspace_search_postgres.py\`: reaches the changed code through the call-graph-- \`tests/unit/server/test_workspace_router.py\`: reaches the changed code through the call-graph--Run: \`pytest tests/unit/server/test_app_lifespan.py tests/unit/server/test_app_workspace_registry.py tests/unit/server/test_workspace_router.py tests/unit/server/test_workspace_search_postgres.py\`-## Hard constraints-- **Confirm before changing.** The analysis is stored, not live; the code may have moved since it ran.-- **Keep behaviour.** This is a structural or performance change; what the code returns must not change.-- **Run Verify before and after.** If no guarding test exists, write one that pins today's behaviour first.-- **Say when it is wrong.** If the problem does not hold, or the change costs more than it saves, report that and stop.-## What I expect back-1. Whether the problem held, and what you changed.-2. The Verify run, before and after, with its result.-3. Anything you left undone, and why."-`;diff --git a/packages/ui/__tests__/health/action-prompt.test.ts b/packages/ui/__tests__/health/action-prompt.test.tsdeleted file mode 100644index dcf726bdb..000000000--- a/packages/ui/__tests__/health/action-prompt.test.ts+++ /dev/null@@ -1,73 +0,0 @@-import { describe, expect, it } from "vitest";-import type { NextAction } from "@repowise-dev/types/actions";--import { buildActionPrompt } from "../../src/health/ai-prompts/action-prompt";--const rollup: NextAction = {- id: "act_1",- rule: "fresh_regressions",- tier: "act_now",- horizons: ["week"],- severity: "critical",- title: "Clean up what this week's commits left: 3 serious findings in 2 files",- impact: "2 commits in the last 7 days added or worsened them.",- why: [{ label: "critical", value: "1", basis: "measured" }],- target: { kind: "repo", path: "", symbol: null },- surface: "commits",- effort: "M",- confidence: "high",- done_when: "The findings close on the next update.",- command: null,- marker: null,- evidence_ids: ["abc1234def"],- evidence_total: 3,- includes: ["src/a.py", "src/b.py"],- fingerprint: "fp",- details: [- {- path: "src/a.py",- line: 40,- symbol: "src/a.py::build",- marker: "complex_method",- severity: "critical",- reason: "build has cyclomatic complexity 31",- ref: "abc1234def5678",- },- ],- details_total: 3,- commands: [- {- purpose: "Every open finding in these files",- mcp: 'get_health(targets=["src/a.py", "src/b.py"], include=["biomarkers"])',- cli: "repowise health --file src/a.py",- },- ],-};--describe("buildActionPrompt", () => {- it("carries the findings themselves, not just file names", () => {- const text = buildActionPrompt({ action: rollup });- expect(text).toContain("`src/a.py:40`: `build`");- expect(text).toContain("build has cyclomatic complexity 31");- expect(text).toContain("commit abc1234def");- expect(text).toContain("## Evidence (1 of 3, worst first)");- expect(text).toContain("…and 2 more.");- });-- it("gives an MCP agent the MCP call and anyone else the CLI line", () => {- expect(buildActionPrompt({ action: rollup, flavor: "claude-code-mcp" })).toContain(- 'get_health(targets=["src/a.py", "src/b.py"], include=["biomarkers"])',- );- const generic = buildActionPrompt({ action: rollup, flavor: "generic" });- expect(generic).toContain("repowise health --file src/a.py");- expect(generic).not.toContain("working on one file");- });-- // The core renderer is parity-tested against this text, so a change to the- // shared preamble must not move a byte of it.- it("keeps every flavor's text unchanged", () => {- for (const flavor of ["generic", "claude-code", "claude-code-mcp", "cursor"] as const) {- expect(buildActionPrompt({ action: rollup, flavor, repoName: "repo" })).toMatchSnapshot(flavor);- }- });-});diff --git a/packages/ui/__tests__/health/agent-prompt-parity.test.ts b/packages/ui/__tests__/health/agent-prompt-parity.test.tsdeleted file mode 100644index 6ec2c5162..000000000--- a/packages/ui/__tests__/health/agent-prompt-parity.test.ts+++ /dev/null@@ -1,64 +0,0 @@-/**- * The web prompt builders and core's `repowise.core.agent_prompts` render the- * same bytes. Both sides check `tests/fixtures/agent_prompts/golden.json`; this- * side also writes it.- *- * Regenerate after a deliberate wording change (from packages/ui):- * UPDATE_AGENT_PROMPT_GOLDENS=1 npx vitest run __tests__/health/agent-prompt-parity.test.ts- * then run tests/unit/agent_prompts/test_parity.py, which must pass unchanged.- */-import { readFileSync, writeFileSync } from "node:fs";-import { join } from "node:path";-import { describe, expect, it } from "vitest";-import type { NextAction } from "@repowise-dev/types/actions";-import type { FixItem } from "@repowise-dev/types/fix-first";--import { buildActionPrompt } from "../../src/health/ai-prompts/action-prompt";-import { buildFixItemPrompt, fixVerifyLines } from "../../src/health/ai-prompts/fix-first-prompt";-import type { AiPromptFlavor } from "../../src/health/ai-prompts/shared";--const DIR = join(__dirname, "../../../../tests/fixtures/agent_prompts");-const FLAVORS: AiPromptFlavor[] = ["generic", "claude-code", "claude-code-mcp", "cursor"];--interface Case {- name: string;- repo_name?: string;-}--function read<T>(file: string): T {- return JSON.parse(readFileSync(join(DIR, file), "utf8")) as T;-}--const actions = read<{ cases: (Case & { action: NextAction })[] }>("actions.json").cases;-const items = read<{ cases: (Case & { item: FixItem })[] }>("fix_items.json").cases;--function perFlavor(render: (flavor: AiPromptFlavor) => string): Record<string, string> {- return Object.fromEntries(FLAVORS.map((f) => [f, render(f)]));-}--const repo = (c: Case) => (c.repo_name ? { repoName: c.repo_name } : {});--const rendered = {- action: Object.fromEntries(- actions.map((c) => [- c.name,- perFlavor((flavor) => buildActionPrompt({ action: c.action, flavor, ...repo(c) })),- ]),- ),- fix_item: Object.fromEntries(- items.map((c) => [- c.name,- perFlavor((flavor) => buildFixItemPrompt({ item: c.item, flavor, ...repo(c) })),- ]),- ),- verify: Object.fromEntries(items.map((c) => [c.name, fixVerifyLines(c.item)])),-};--describe("agent prompt goldens", () => {- it("the web builders render golden.json", () => {- if (process.env.UPDATE_AGENT_PROMPT_GOLDENS) {- writeFileSync(join(DIR, "golden.json"), `${JSON.stringify(rendered, null, 2)}\n`, "utf8");- }- expect(rendered).toEqual(read("golden.json"));- });-});diff --git a/packages/ui/__tests__/health/ai-prompt-modal.test.tsx b/packages/ui/__tests__/health/ai-prompt-modal.test.tsxindex 1b8cf1d19..efcf0e87b 100644--- a/packages/ui/__tests__/health/ai-prompt-modal.test.tsx+++ b/packages/ui/__tests__/health/ai-prompt-modal.test.tsx@@ -112,3 +112,81 @@ describe("AiPromptModal Ask in chat", () => {expect(screen.queryByRole("button", { name: "Ask in chat" })).toBeNull();});});++describe("AiPromptModal with a built prompt", () => {+ it("shows the text at once with its size, and no loading state", () => {+ render(<AiPromptModal open onOpenChange={() => undefined} getPrompt={(f) => `Built for ${f}`} />);+ expect(screen.getByRole("dialog").querySelector("pre")?.textContent).toMatch(/^Built for /);+ expect(screen.getByText(/chars, approx/)).toBeTruthy();+ expect(screen.queryByRole("status")).toBeNull();+ expect(screen.getByRole("button", { name: "Copy prompt" })).toBeEnabled();+ });+});++describe("AiPromptModal with a fetched prompt", () => {+ const CONTEXT = fileChatContext("src/a.py")!;++ function renderFetched(promptSource: (flavor: string) => Promise<string>, onHandoff = vi.fn()) {+ render(+ <ChatHandoffProvider onHandoff={onHandoff}>+ <AiPromptModal+ open+ onOpenChange={() => undefined}+ getPrompt={null}+ promptSource={promptSource}+ chatContext={CONTEXT}+ />+ </ChatHandoffProvider>,+ );+ }++ it("shows a skeleton with Copy and Ask disabled until the prompt arrives", async () => {+ let resolve!: (text: string) => void;+ renderFetched(() => new Promise((r) => (resolve = r)));+ expect(screen.getByRole("status").textContent).toBe("Loading the prompt");+ expect(screen.getByRole("button", { name: "Copy prompt" })).toBeDisabled();+ expect(screen.getByRole("button", { name: "Ask in chat" })).toBeDisabled();+ expect(screen.getByRole("dialog").querySelector("pre")).toBeNull();++ resolve("Fetched prompt");+ expect(await screen.findByText("Fetched prompt")).toBeTruthy();+ expect(screen.getByRole("button", { name: "Copy prompt" })).toBeEnabled();+ });++ it("copies and asks in chat with exactly the text on screen", async () => {+ const writeText = vi.fn().mockResolvedValue(undefined);+ Object.assign(navigator, { clipboard: { writeText } });+ const onHandoff = vi.fn();+ renderFetched(async (flavor) => `Fetched for ${flavor}`, onHandoff);+ const shown = (await screen.findByText(/^Fetched for /)).textContent;++ fireEvent.click(screen.getByRole("button", { name: "Copy prompt" }));+ await waitFor(() => expect(writeText).toHaveBeenCalledWith(shown));+ fireEvent.click(screen.getByRole("button", { name: "Ask in chat" }));+ expect(onHandoff).toHaveBeenCalledWith({ context: CONTEXT, question: shown, autoSend: false });+ });++ it("says when the prompt failed to load and fetches again on Retry", async () => {+ const source = vi+ .fn()+ .mockRejectedValueOnce(new Error("down"))+ .mockResolvedValueOnce("Second try");+ renderFetched(source);+ expect((await screen.findByRole("alert")).textContent).toContain("Couldn't load the prompt.");+ fireEvent.click(screen.getByRole("button", { name: "Retry" }));+ expect(document.activeElement).not.toBe(document.body);+ expect(screen.getByRole("dialog").contains(document.activeElement)).toBe(true);+ expect(await screen.findByText("Second try")).toBeTruthy();+ expect(screen.getByRole("dialog").contains(document.activeElement)).toBe(true);+ expect(source).toHaveBeenCalledTimes(2);+ });++ it("fetches again for another target agent", async () => {+ const source = vi.fn(async (flavor: string) => `Fetched for ${flavor}`);+ renderFetched(source);+ await screen.findByText(/^Fetched for /);+ fireEvent.click(screen.getByRole("button", { name: "Cursor" }));+ expect(await screen.findByText("Fetched for cursor")).toBeTruthy();+ expect(source).toHaveBeenLastCalledWith("cursor");+ });+});diff --git a/packages/ui/__tests__/health/fix-first.test.tsx b/packages/ui/__tests__/health/fix-first.test.tsxindex 7ef69477d..2f55b614e 100644--- a/packages/ui/__tests__/health/fix-first.test.tsx+++ b/packages/ui/__tests__/health/fix-first.test.tsx@@ -10,7 +10,6 @@ import type { FixFirstQueue, FixItem } from "@repowise-dev/types/fix-first";import { FixFirstList } from "../../src/health/fix-first/fix-first-list";import { fixFirstScopeSentence, fixPlanLabel } from "../../src/health/fix-first/scope";-import { buildFixItemPrompt } from "../../src/health/ai-prompts/fix-first-prompt";import { FIX_FIRST_QUEUE } from "./fixtures/fix-first";const [REFACTOR, FINDING, PERF] = FIX_FIRST_QUEUE.items as [FixItem, FixItem, FixItem];@@ -127,26 +126,16 @@ describe("Fix first items", () => {});describe("Fix first agent prompt", () => {- it("carries the steps and the Verify block", () => {- const prompt = buildFixItemPrompt({ item: REFACTOR, flavor: "claude-code-mcp" });- expect(prompt).toContain("## Verify");- expect(prompt).toContain(`Run: \`${REFACTOR.verify.command}\``);- expect(prompt).toContain("[mechanical]");- expect(prompt).toContain('get_health(opportunity_id="refop3_8ba13d978db910d160b1")');- });-- it("tells the agent to pin behaviour when no test guards the change", () => {- const prompt = buildFixItemPrompt({ item: FINDING });- expect(prompt).toContain("No guarding tests found.");+ it("is offered only when the host can load it", () => {+ renderList();+ expect(screen.queryByRole("button", { name: "Copy prompt for an agent" })).toBeNull();});- // The core renderer is parity-tested against this text, so a change to the- // shared preamble must not move a byte of it.- it("keeps every flavor's text unchanged", () => {- for (const flavor of ["generic", "claude-code", "claude-code-mcp", "cursor"] as const) {- for (const item of [REFACTOR, FINDING, PERF]) {- expect(buildFixItemPrompt({ item, flavor, repoName: "repo" })).toMatchSnapshot(`${item.id} ${flavor}`);- }- }+ it("shows the prompt the host loads for the item", async () => {+ const loadPrompt = vi.fn().mockResolvedValue("Prompt from core");+ renderList({ loadPrompt });+ fireEvent.click(screen.getByRole("button", { name: "Copy prompt for an agent" }));+ expect(await screen.findByText("Prompt from core")).toBeTruthy();+ expect(loadPrompt).toHaveBeenCalledWith(REFACTOR, expect.any(String));});});diff --git a/packages/ui/__tests__/overview/next-actions.test.tsx b/packages/ui/__tests__/overview/next-actions.test.tsxindex c2e521269..f074f5795 100644--- a/packages/ui/__tests__/overview/next-actions.test.tsx+++ b/packages/ui/__tests__/overview/next-actions.test.tsx@@ -129,7 +129,14 @@ describe("NextActions", () => {describe("the action drawer", () => {it("opens on a row click with the evidence link, the facts and the prompt", async () => {- render(<NextActions data={response([], [action()])} hrefFor={() => "/repos/r/files/src/a.py"} />);+ const loadPrompt = vi.fn().mockResolvedValue("Prompt from core");+ render(+ <NextActions+ data={response([], [action()])}+ hrefFor={() => "/repos/r/files/src/a.py"}+ loadPrompt={loadPrompt}+ />,+ );fireEvent.click(screen.getByRole("listitem", { name: /Open Raise test coverage/ }));const dialog = await screen.findByRole("dialog");expect(within(dialog).getByRole("link", { name: /Open the file/ })).toHaveAttribute(@@ -138,8 +145,17 @@ describe("the action drawer", () => {);expect(within(dialog).getByText("Why it is on the list")).toBeInTheDocument();expect(within(dialog).getByText("Not measured.")).toBeInTheDocument();- expect(within(dialog).getByRole("button", { name: /Copy prompt/ })).toBeInTheDocument();- expect(within(dialog).getAllByText(/Line coverage on this file reaches 80%/).length).toBe(2);+ expect(await within(dialog).findByText("Prompt from core")).toBeInTheDocument();+ expect(loadPrompt).toHaveBeenCalledWith(action(), expect.any(String));+ expect(within(dialog).getByRole("button", { name: /Copy prompt/ })).toBeEnabled();+ });++ it("leaves the prompt out when the host cannot load one", async () => {+ render(<NextActions data={response([], [action()])} hrefFor={() => null} />);+ fireEvent.click(screen.getByRole("listitem", { name: /Open Raise test coverage/ }));+ const dialog = await screen.findByRole("dialog");+ expect(within(dialog).queryByText("Hand it to an agent")).toBeNull();+ expect(within(dialog).queryByRole("button", { name: /Copy prompt/ })).toBeNull();});});@@ -227,16 +243,13 @@ describe("the fix_first rule", () => {expect(within(row).getByText("+1.7 health on this file")).toBeInTheDocument();});- it("hands the item to an agent with its steps and lookup, and no hot-path copy remains", async () => {- render(<NextActions data={response([fixFirst], [])} hrefFor={() => null} />);+ it("hands the item to the host's prompt, and no hot-path copy remains", async () => {+ const loadPrompt = vi.fn().mockResolvedValue("Extract lines 60-122 of quick_repo_scan");+ render(<NextActions data={response([fixFirst], [])} hrefFor={() => null} loadPrompt={loadPrompt} />);fireEvent.click(screen.getByRole("listitem", { name: /Open Extract lines 60-122/ }));const dialog = await screen.findByRole("dialog");- expect(within(dialog).getByRole("button", { name: /Copy prompt/ })).toBeInTheDocument();- // The prompt is the last preformatted block; the commands above it are earlier ones.- const blocks = dialog.querySelectorAll("pre");- const prompt = blocks[blocks.length - 1]!.textContent ?? "";- expect(prompt).toContain("Extract lines 60-122 of quick_repo_scan into compute_info");- expect(prompt).toContain("repo_scanner.py:60");+ await within(dialog).findByText("Extract lines 60-122 of quick_repo_scan");+ expect(loadPrompt).toHaveBeenCalledWith(fixFirst, expect.any(String));expect(document.body.textContent).not.toMatch(/hot path/i);});diff --git a/packages/ui/__tests__/workspace/workspace-next-actions.test.tsx b/packages/ui/__tests__/workspace/workspace-next-actions.test.tsxindex eb23cbe7b..173bb8c06 100644--- a/packages/ui/__tests__/workspace/workspace-next-actions.test.tsx+++ b/packages/ui/__tests__/workspace/workspace-next-actions.test.tsx@@ -1,5 +1,5 @@-import { describe, expect, it } from "vitest";-import { render, screen } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";+import { fireEvent, render, screen, within } from "@testing-library/react";import type { NextAction, WorkspaceActionsResponse } from "@repowise-dev/types/actions";import { WorkspaceNextActions } from "../../src/workspace/workspace-next-actions.js";@@ -94,4 +94,21 @@ describe("WorkspaceNextActions", () => {expect(screen.getByText(/Not included: docs \(not indexed yet\)/)).toBeInTheDocument();expect(screen.getByText(/5 things worth doing this week/)).toBeInTheDocument();});++ it("loads an opened action's prompt from its own repository", async () => {+ const loadPrompt = vi.fn().mockResolvedValue("Prompt from core");+ render(+ <WorkspaceNextActions+ data={data}+ hrefFor={() => null}+ repoHref={(id) => `/repos/${id}/overview`}+ contractsHref="/workspace/contracts"+ loadPrompt={loadPrompt}+ />,+ );+ fireEvent.click(screen.getByRole("listitem", { name: /Open Clean up/ }));+ const dialog = await screen.findByRole("dialog");+ expect(await within(dialog).findByText("Prompt from core")).toBeInTheDocument();+ expect(loadPrompt).toHaveBeenCalledWith("f1", expect.objectContaining({ id: "y" }), expect.any(String));+ });});diff --git a/packages/ui/src/health/ai-prompt-builder.ts b/packages/ui/src/health/ai-prompt-builder.tsindex 47d5c9277..a2b11c463 100644--- a/packages/ui/src/health/ai-prompt-builder.ts+++ b/packages/ui/src/health/ai-prompt-builder.ts@@ -8,12 +8,6 @@export type { AiPromptFlavor } from "./ai-prompts/shared";export { buildAiPrompt, type BuildPromptOptions } from "./ai-prompts/refactor-prompt";-export { buildActionPrompt, type BuildActionPromptOptions } from "./ai-prompts/action-prompt";-export {- buildFixItemPrompt,- fixVerifyLines,- type BuildFixItemPromptOptions,-} from "./ai-prompts/fix-first-prompt";export {buildCoverageAiPrompt,type BuildCoveragePromptOptions,diff --git a/packages/ui/src/health/ai-prompt-modal.tsx b/packages/ui/src/health/ai-prompt-modal.tsxindex b98dbf0cf..8a7d3f224 100644--- a/packages/ui/src/health/ai-prompt-modal.tsx+++ b/packages/ui/src/health/ai-prompt-modal.tsx@@ -1,6 +1,6 @@"use client";-import { useEffect, useMemo, useState } from "react";+import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";import { Check, Copy, MessageCircleQuestion, Sparkles } from "lucide-react";import type { ChatContext } from "@repowise-dev/types/chat";import {@@ -10,6 +10,7 @@ import {DialogHeader,DialogTitle,} from "../ui/dialog";+import { Skeleton, SkeletonRegion } from "../ui/skeleton";import { useChatHandoff } from "../chat/chat-handoff";import { ViewToggle } from "./code-health-controls";import type { AiPromptFlavor } from "./ai-prompt-builder";@@ -19,6 +20,9 @@ export interface AiPromptModalProps {onOpenChange: (open: boolean) => void;/** Pure builder that returns the prompt string for the chosen flavor. */getPrompt: ((flavor: AiPromptFlavor) => string) | null;+ /** Fetches the prompt instead, e.g. one core renders; overrides `getPrompt`.+ * Pass a stable function: a new one fetches again. */+ promptSource?: PromptSource | undefined;/** Path or other one-line identifier shown next to the title. */filePath?: string | null;/** Section heading (e.g. "AI fix prompt", "AI test prompt"). */@@ -49,6 +53,83 @@ const FLAVORS: { value: AiPromptFlavor; label: string; hint: string }[] = [{ value: "cursor", label: "Cursor", hint: "Uses @file context and Cursor editing conventions." },];+/** Where a server-rendered prompt comes from, one request per flavor. */+export type PromptSource = (flavor: AiPromptFlavor) => Promise<string>;++type PromptLoad =+ | { status: "loading" }+ | { status: "ready"; text: string }+ | { status: "failed"; retry: () => void };++/** The prompt `source` returns for `flavor`, refetched on a flavor switch or a retry. */+function usePromptSource(source: PromptSource | undefined, flavor: AiPromptFlavor): PromptLoad | null {+ const [load, setLoad] = useState<PromptLoad>({ status: "loading" });+ const [attempt, setAttempt] = useState(0);++ useEffect(() => {+ if (!source) return;+ let live = true;+ setLoad({ status: "loading" });+ source(flavor).then(+ (text) => {+ if (live) setLoad({ status: "ready", text });+ },+ () => {+ if (live) setLoad({ status: "failed", retry: () => setAttempt((n) => n + 1) });+ },+ );+ return () => {+ live = false;+ };+ }, [source, flavor, attempt]);++ return source ? load : null;+}++/** The text, or while a fetched prompt is pending or failed, a stand-in for it. */+function PromptText({ text, load }: { text: string; load: PromptLoad | null }) {+ const pre = (+ <pre className="min-w-0 max-w-full whitespace-pre-wrap [overflow-wrap:anywhere] font-mono text-xs leading-relaxed text-[var(--color-text-primary)]">+ {text}+ </pre>+ );+ return load ? <FetchedPromptText load={load} pre={pre} /> : pre;+}++/** A fetched prompt's states in one wrapper that outlives them, so Retry can+ * park focus on it before the button unmounts rather than drop it to the page. */+function FetchedPromptText({ load, pre }: { load: PromptLoad; pre: ReactNode }) {+ const pane = useRef<HTMLDivElement>(null);+ return (+ <div ref={pane} tabIndex={-1} className="min-w-0 outline-none">+ {load.status === "loading" ? (+ <SkeletonRegion className="space-y-2" label="Loading the prompt">+ <Skeleton className="h-3 w-3/4" />+ <Skeleton className="h-3 w-full" />+ <Skeleton className="h-3 w-5/6" />+ <Skeleton className="h-3 w-2/3" />+ </SkeletonRegion>+ ) : load.status === "failed" ? (+ <p role="alert" className="text-xs text-[var(--color-text-secondary)]">+ Couldn't load the prompt.{" "}+ <button+ type="button"+ onClick={() => {+ pane.current?.focus();+ load.retry();+ }}+ className="rounded font-medium text-[var(--color-accent-primary)] hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"+ >+ Retry+ </button>+ </p>+ ) : (+ pre+ )}+ </div>+ );+}+const FLAVOR_STORAGE_KEY = "repowise:ai-prompt-flavor";function loadStoredFlavor(): AiPromptFlavor {@@ -102,11 +183,14 @@ function AskPromptInChat({*/export function AiPromptBlock({getPrompt,+ promptSource,bleed = "px-6",chatContext,onAsked,}: {getPrompt: ((flavor: AiPromptFlavor) => string) | null;+ /** See {@link AiPromptModalProps.promptSource}. */+ promptSource?: PromptSource | undefined;/** Horizontal padding that matches the host's own, so the hairlines run edge to edge. */bleed?: string;/** What "Ask in chat" asks about; the control is hidden without it. */@@ -126,7 +210,13 @@ export function AiPromptBlock({}};- const prompt = useMemo(() => (getPrompt ? getPrompt(flavor) : ""), [getPrompt, flavor]);+ const load = usePromptSource(promptSource, flavor);+ const built = useMemo(+ () => (getPrompt && !promptSource ? getPrompt(flavor) : ""),+ [getPrompt, promptSource, flavor],+ );+ // Empty until a fetched prompt arrives, which keeps Copy and Ask disabled.+ const prompt = load ? (load.status === "ready" ? load.text : "") : built;useEffect(() => setCopied(false), [prompt]);@@ -163,16 +253,18 @@ export function AiPromptBlock({</div><div className={`min-w-0 max-w-full max-h-[420px] overflow-x-hidden overflow-y-auto py-4 ${bleed}`}>- <pre className="min-w-0 max-w-full whitespace-pre-wrap [overflow-wrap:anywhere] font-mono text-xs leading-relaxed text-[var(--color-text-primary)]">- {prompt}- </pre>+ <PromptText text={prompt} load={load} /></div></div><div className={`flex min-w-0 flex-wrap items-center justify-between gap-2 text-xs text-[var(--color-text-tertiary)] ${bleed}`}><span className="min-w-0 tabular-nums">- {prompt.length.toLocaleString()} chars, approx{" "}- {Math.round(prompt.length / 4).toLocaleString()} tokens+ {load && !prompt ? null : (+ <>+ {prompt.length.toLocaleString()} chars, approx{" "}+ {Math.round(prompt.length / 4).toLocaleString()} tokens+ </>+ )}</span><div className="flex shrink-0 flex-wrap items-center gap-2"><AskPromptInChat prompt={prompt} context={chatContext} onAsked={onAsked} />@@ -207,6 +299,7 @@ export function AiPromptModal({open,onOpenChange,getPrompt,+ promptSource,filePath,title = "AI fix prompt",description = "A ready-to-paste prompt that gives your AI coding agent every detail needed to make this change in one focused pass.",@@ -232,6 +325,7 @@ export function AiPromptModal({{open ? (<AiPromptBlockgetPrompt={getPrompt}+ promptSource={promptSource}chatContext={chatContext}onAsked={() => onOpenChange(false)}/>diff --git a/packages/ui/src/health/ai-prompts/action-prompt.ts b/packages/ui/src/health/ai-prompts/action-prompt.tsdeleted file mode 100644index e7edcc539..000000000--- a/packages/ui/src/health/ai-prompts/action-prompt.ts+++ /dev/null@@ -1,144 +0,0 @@-import type { ActionDetail, NextAction } from "@repowise-dev/types/actions";--import { biomarkerLabel } from "../biomarker-glossary";-import {- bulletList,- closingSections,- joinSections,- preamble,- repoSuffix,- type AiPromptFlavor,-} from "./shared";--// ─────────────────────────────────────────────────────────────────────-// Next action prompt: one action from "Do next", handed to an agent cold-// ─────────────────────────────────────────────────────────────────────--export interface BuildActionPromptOptions {- action: NextAction;- flavor?: AiPromptFlavor;- repoName?: string;-}--/**- * The opening after the shared role. Not the file preamble: an action can span- * many files and is built from stored analysis, so the agent is told both- * before it reads a line.- */-const OPENING: Record<AiPromptFlavor, string> = {- generic:- "Repowise, a code-intelligence index, produced the action below from its stored analysis of the repository (git history, code health, the dependency graph). Its evidence is listed in full or in part; treat each item as a lead to verify against the code, not as ground truth.",- "claude-code":- "Repowise, a code-intelligence index, produced the action below from its stored analysis. Treat each evidence item as a lead: read the code with Read and Grep, confirm it, and use TodoWrite to track the files you work through.",- "claude-code-mcp":- "The action below comes from Repowise's stored analysis. Use the MCP calls listed under \"Look closer\" before reading files by hand: they return the full evidence with line numbers, reasons and history. Treat each item as a lead to confirm against the code.",- cursor:- "Repowise, a code-intelligence index, produced the action below from its stored analysis. Treat each evidence item as a lead: open the file with @file, confirm it, then act.",-};--const CONSTRAINTS = [- "**Confirm each item before changing anything.** The analysis is stored, not live; the code may have moved since it ran.",- "**Stay inside what the action names.** Work only on the files and functions listed. If the right fix is elsewhere, stop and say where and why.",- "**Keep behaviour unless the action is about behaviour.** Refactors and test additions must not change what the code does; run the tests that cover each file before and after.",- "**Say when an item is wrong.** If a finding does not hold, or its fix would cost more than it saves, report that rather than forcing an edit.",-];--const EXPECTED = [- "1. For each item you looked at: whether it held, and what you changed or why you left it.",- "2. The tests you ran, before and after.",- "3. What remains against the done condition.",-];--function detailLine(d: ActionDetail): string {- const where = `\`${d.path}${d.line ? `:${d.line}` : ""}\``;- const what = [- d.symbol ? `\`${d.symbol.split("::").pop()}\`` : null,- d.marker ? biomarkerLabel(d.marker) : null,- d.severity,- ]- .filter(Boolean)- .join(", ");- const ref = d.ref && /^[0-9a-f]{7,40}$/.test(d.ref) ? ` (commit ${d.ref.slice(0, 10)})` : "";- return `- ${where}${what ? `: ${what}` : ""}${ref}${d.reason ? `\n - ${d.reason}` : ""}`;-}--/**- * Hand one next action to an agent: the claim, the evidence itself, how to get- * the rest, and what finished looks like. Written so an agent with no prior- * context can start work from this text alone.- */-export function buildActionPrompt({- action,- flavor = "generic",- repoName,-}: BuildActionPromptOptions): string {- const useMcp = flavor === "claude-code-mcp";- const shownDetails = action.details.length;- const moreDetails = action.details_total - shownDetails;- const target = action.target.symbol- ? `\`${action.target.path}\` (\`${action.target.symbol.split("::").pop()}\`)`- : action.target.path- ? `\`${action.target.path}\``- : null;-- const commands = action.commands- .map((c) => {- const line = useMcp ? (c.mcp ?? c.cli) : (c.cli ?? c.mcp);- return line ? `- ${c.purpose}:\n \`${line}\`` : null;- })- .filter((l): l is string => l !== null);-- return joinSections([- preamble(flavor, { body: OPENING }),- "",- `## Action${repoSuffix(repoName)}`,- "",- `**${action.title}**`,- "",- action.impact,- "",- "## Why it is on the list",- "",- bulletList([- target ? `Target: ${target}` : null,- ...action.why.map(- (w) => `${w.label}: ${w.value}${w.basis === "measured" ? "" : ` (${w.basis})`}`,- ),- `Effort estimate: ${action.effort}; confidence in the facts: ${action.confidence}`,- ]),- "",- shownDetails- ? joinSections([- `## Evidence (${shownDetails.toLocaleString()} of ${action.details_total.toLocaleString()}${- moreDetails > 0 ? ", worst first" : ""- })`,- "",- action.details.map(detailLine).join("\n"),- moreDetails > 0- ? `\n…and ${moreDetails.toLocaleString()} more. The first call under "Look closer" returns them.`- : "",- "",- ])- : action.includes.length- ? joinSections([- "## Files",- "",- action.includes.map((p) => `- \`${p}\``).join("\n"),- "",- ])- : "",- commands.length- ? joinSections([- useMcp ? "## Look closer (Repowise MCP)" : "## Look closer (Repowise CLI)",- "",- commands.join("\n"),- "",- ])- : "",- "## Done when",- "",- action.done_when + (action.command ? `\n\nCommand: \`${action.command}\`` : ""),- "",- ...closingSections(CONSTRAINTS, EXPECTED),- ]);-}diff --git a/packages/ui/src/health/ai-prompts/fix-first-prompt.ts b/packages/ui/src/health/ai-prompts/fix-first-prompt.tsdeleted file mode 100644index 9de1132c4..000000000--- a/packages/ui/src/health/ai-prompts/fix-first-prompt.ts+++ /dev/null@@ -1,124 +0,0 @@-import type { FixItem } from "@repowise-dev/types/fix-first";--import {- bulletList,- closingSections,- joinSections,- preamble,- repoSuffix,- type AiPromptFlavor,-} from "./shared";--// ─────────────────────────────────────────────────────────────────────-// Fix first: one ranked item, handed to an agent with its Verify block-// ─────────────────────────────────────────────────────────────────────--export interface BuildFixItemPromptOptions {- item: FixItem;- flavor?: AiPromptFlavor;- repoName?: string;-}--/** The opening after the shared role. */-const OPENING: Record<AiPromptFlavor, string> = {- generic:- "Repowise, a code-intelligence index, ranked the change below first among the work it found. Its facts come from stored analysis; treat them as leads to confirm against the code, not as ground truth.",- "claude-code":- "Repowise, a code-intelligence index, ranked the change below first among the work it found. Confirm each fact with Read and Grep before editing, and track the steps with TodoWrite.",- "claude-code-mcp":- "Repowise ranked the change below first among the work it found. Call the MCP lookup under \"Look closer\" for the full record before reading files by hand, then confirm each fact against the code.",- cursor:- "Repowise, a code-intelligence index, ranked the change below first among the work it found. Open the target with @file, confirm each fact, then make the change.",-};--const CONSTRAINTS = [- "**Confirm before changing.** The analysis is stored, not live; the code may have moved since it ran.",- "**Keep behaviour.** This is a structural or performance change; what the code returns must not change.",- "**Run Verify before and after.** If no guarding test exists, write one that pins today's behaviour first.",- "**Say when it is wrong.** If the problem does not hold, or the change costs more than it saves, report that and stop.",-];--const EXPECTED = [- "1. Whether the problem held, and what you changed.",- "2. The Verify run, before and after, with its result.",- "3. Anything you left undone, and why.",-];--function where(item: FixItem): string {- const { file_path, symbol, line_start } = item.target;- const loc = `\`${file_path}${line_start ? `:${line_start}` : ""}\``;- return symbol ? `${loc} (\`${symbol.split("::").pop()}\`)` : loc;-}--/** The Verify block, worded the way the card words it. */-export function fixVerifyLines(item: FixItem): string {- const { tests, tests_total, command } = item.verify;- if (tests.length === 0) {- return "No guarding tests found. Write a test that pins the current behaviour before you change anything.";- }- const listed = tests.map((t) => `- \`${t.path}\`${t.reason ? `: ${t.reason}` : ""}`);- const more = tests_total - tests.length;- return joinSections([- listed.join("\n"),- more > 0 ? `- …and ${more.toLocaleString()} more` : "",- command ? `\nRun: \`${command}\`` : "",- ]);-}--/**- * Hand one Fix-first item to an agent: the change, why it ranks, the steps in- * order, and how to verify it. Written so an agent with no prior context can- * start from this text alone.- */-export function buildFixItemPrompt({- item,- flavor = "generic",- repoName,-}: BuildFixItemPromptOptions): string {- const useMcp = flavor === "claude-code-mcp";- const call = item.next_call.mcp;- const steps = item.action.steps.map(- (s) =>- `${s.order}. ${s.text} (\`${s.file_path}${s.line ? `:${s.line}` : ""}\`)${- s.mechanical ? " [mechanical]" : " [judgment]"- }`,- );- const moreSteps = item.action.steps_total - item.action.steps.length;-- return joinSections([- preamble(flavor, { body: OPENING }),- "",- `## Fix first${repoSuffix(repoName)}`,- "",- `**${item.title}**`,- "",- item.why,- "",- "## Facts",- "",- bulletList([- `Target: ${where(item)}`,- `Gain: ${item.gain.text}`,- `Effort: ${item.effort.bucket} (${item.effort.basis})`,- `Risk: ${item.risk.text}`,- `Confidence: ${item.confidence.level}. ${item.confidence.reason}`,- ...item.facts.map((f) => `${f.label}: ${f.value}${f.basis === "measured" ? "" : ` (${f.basis})`}`),- ]),- "",- steps.length- ? joinSections([- "## Steps, in order",- "",- steps.join("\n"),- moreSteps > 0 ? `…and ${moreSteps.toLocaleString()} more; the lookup below returns them.` : "",- "",- ])- : "",- "## Verify",- "",- fixVerifyLines(item),- "",- useMcp ? joinSections(["## Look closer (Repowise MCP)", "", `\`${call}\``, ""]) : "",- ...closingSections(CONSTRAINTS, EXPECTED),- ]);-}diff --git a/packages/ui/src/health/fix-first/fix-first-list.tsx b/packages/ui/src/health/fix-first/fix-first-list.tsxindex 8de3a9d51..dd76dc6a9 100644--- a/packages/ui/src/health/fix-first/fix-first-list.tsx+++ b/packages/ui/src/health/fix-first/fix-first-list.tsx@@ -7,7 +7,7 @@* host fetches, routes and writes, this renders.*/-import { useState, type ElementType } from "react";+import { useCallback, useState, type ElementType } from "react";import type { FixFirstQueue, FixItem, FixScope } from "@repowise-dev/types/fix-first";import { Skeleton, SkeletonRegion } from "../../ui/skeleton";@@ -15,7 +15,7 @@ import { ApiError } from "../../shared/api-error";import { toFriendlyMessage } from "../../lib/errors";import { OverviewSection } from "../../overview/section";import { AiPromptModal, fileChatContext } from "../ai-prompt-modal";-import { buildFixItemPrompt } from "../ai-prompts/fix-first-prompt";+import type { AiPromptFlavor } from "../ai-prompt-builder";import { FixFirstItem, type FixTriageStatus } from "./fix-first-item";import { fixFirstScopeSentence, fixLocation } from "./scope";@@ -30,7 +30,8 @@ export interface FixFirstListProps {fileHref?: ((path: string, line: number | null) => string | undefined) | undefined;planHref?: ((item: FixItem) => string | null) | undefined;onTriage?: ((item: FixItem, status: FixTriageStatus) => Promise<void>) | undefined;- repoName?: string | undefined;+ /** An item's agent prompt as core renders it, for this `scope`. Omit to hide the prompt. */+ loadPrompt?: ((item: FixItem, flavor: AiPromptFlavor) => Promise<string>) | undefined;LinkComponent?: ElementType | undefined;/** Drop the section's top hairline when it opens the page. */flush?: boolean | undefined;@@ -46,7 +47,7 @@ export function FixFirstList({fileHref,planHref,onTriage,- repoName,+ loadPrompt,LinkComponent,flush = true,}: FixFirstListProps) {@@ -60,6 +61,11 @@ export function FixFirstList({setOpen(next);};const [promptFor, setPromptFor] = useState<FixItem | null>(null);+ // Only fetched while the modal is open on an item; stable per item.+ const promptSource = useCallback(+ (flavor: AiPromptFlavor) => loadPrompt!(promptFor!, flavor),+ [loadPrompt, promptFor],+ );const toggleTests = onScopeChange ? (<label className="inline-flex cursor-pointer items-center gap-1.5 text-xs text-[var(--color-text-secondary)]">@@ -111,7 +117,7 @@ export function FixFirstList({onToggle={() => toggle(item.id)}fileHref={fileHref}planHref={planHref}- onAiPrompt={setPromptFor}+ onAiPrompt={loadPrompt ? setPromptFor : undefined}onTriage={onTriage}LinkComponent={LinkComponent}/>@@ -124,16 +130,8 @@ export function FixFirstList({onOpenChange={(next) => {if (!next) setPromptFor(null);}}- getPrompt={- promptFor- ? (flavor) =>- buildFixItemPrompt({- item: promptFor,- flavor,- ...(repoName ? { repoName } : {}),- })- : null- }+ getPrompt={null}+ promptSource={promptSource}filePath={promptFor ? fixLocation(promptFor) : null}chatContext={fileChatContext(promptFor?.target.file_path)}title="Prompt for an agent"diff --git a/packages/ui/src/overview/action-drawer.tsx b/packages/ui/src/overview/action-drawer.tsxindex a32f5c0cf..5daa3ce20 100644--- a/packages/ui/src/overview/action-drawer.tsx+++ b/packages/ui/src/overview/action-drawer.tsx@@ -1,6 +1,6 @@"use client";-import { useState, type ElementType, type ReactNode } from "react";+import { useCallback, useState, type ElementType, type ReactNode } from "react";import { ArrowUpRight, BellOff, Check, X } from "lucide-react";import type {ActionDetail,@@ -10,7 +10,7 @@ import type {} from "@repowise-dev/types/actions";import { AiPromptBlock } from "../health/ai-prompt-modal";-import { buildActionPrompt } from "../health/ai-prompts/action-prompt";+import type { AiPromptFlavor } from "../health/ai-prompt-builder";import { biomarkerLabel } from "../health/biomarker-glossary";import { EFFORT_LABEL } from "../health/labels";import { SeverityMark } from "../health/severity-mark";@@ -51,7 +51,8 @@ export interface ActionDrawerProps {fileHref?: ((path: string) => string | null) | undefined;/** Omit to hide the done, snooze and dismiss verbs. */onAnswer?: ((state: ActionStateValue, message: string) => void) | undefined;- repoName?: string | undefined;+ /** The agent prompt for an action, as core renders it. Omit to hide the prompt. */+ loadPrompt?: ((action: NextAction, flavor: AiPromptFlavor) => Promise<string>) | undefined;LinkComponent?: ElementType | undefined;renderTitle: (title: string) => ReactNode;}@@ -79,10 +80,15 @@ export function ActionDrawer({evidenceHref,fileHref,onAnswer,- repoName,+ loadPrompt,LinkComponent,renderTitle,}: ActionDrawerProps) {+ // Only rendered with both set; stable per action so the block fetches once per flavor.+ const promptSource = useCallback(+ (flavor: AiPromptFlavor) => loadPrompt!(action!, flavor),+ [loadPrompt, action],+ );const Link = LinkComponent ?? "a";const linkCls ="rounded text-[var(--color-accent-primary)] hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]";@@ -226,16 +232,13 @@ export function ActionDrawer({</Section>) : null}- <Section title="Hand it to an agent">- <div className="-mx-5">- <AiPromptBlock- bleed="px-5"- getPrompt={(flavor) =>- buildActionPrompt({ action, flavor, ...(repoName ? { repoName } : {}) })- }- />- </div>- </Section>+ {loadPrompt ? (+ <Section title="Hand it to an agent">+ <div className="-mx-5">+ <AiPromptBlock bleed="px-5" getPrompt={null} promptSource={promptSource} />+ </div>+ </Section>+ ) : null}</div>{onAnswer ? (diff --git a/packages/ui/src/overview/next-actions.tsx b/packages/ui/src/overview/next-actions.tsxindex 0865390e6..be408900e 100644--- a/packages/ui/src/overview/next-actions.tsx+++ b/packages/ui/src/overview/next-actions.tsx@@ -16,7 +16,7 @@ import { SeverityMark } from "../health/severity-mark";import { CLICKABLE_ROW_CLS, clickableRowProps } from "../shared/responsive-table";import { RowOverflow } from "../shared/row-overflow";import { Segmented } from "../shared/segmented";-import { ActionDrawer } from "./action-drawer";+import { ActionDrawer, type ActionDrawerProps } from "./action-drawer";import { OverviewSection } from "./section";/** Rows shown before "Show all"; the response carries up to 20 per horizon. */@@ -36,7 +36,8 @@ export interface NextActionsProps {fileHref?: ((path: string) => string | null) | undefined;/** Persist a dismissal, snooze, done, or (null) an undo. Omit to hide those verbs. */onSetState?: (action: NextAction, state: ActionStateValue | null) => Promise<void>;- repoName?: string | undefined;+ /** An action's agent prompt as core renders it. Omit to hide the prompt. */+ loadPrompt?: ActionDrawerProps["loadPrompt"];LinkComponent?: ElementType | undefined;}@@ -106,7 +107,7 @@ export function NextActions({hrefFor,fileHref,onSetState,- repoName,+ loadPrompt,LinkComponent,}: NextActionsProps) {// Open on the week unless it holds no work and the quarter does: a lone@@ -253,7 +254,7 @@ export function NextActions({? (state, message) => answer(opened, state, message): undefined}- repoName={repoName}+ loadPrompt={loadPrompt}LinkComponent={LinkComponent}renderTitle={renderActionTitle}/>diff --git a/packages/ui/src/workspace/workspace-next-actions.tsx b/packages/ui/src/workspace/workspace-next-actions.tsxindex 478e53956..967ad0aa3 100644--- a/packages/ui/src/workspace/workspace-next-actions.tsx+++ b/packages/ui/src/workspace/workspace-next-actions.tsx@@ -1,6 +1,6 @@"use client";-import { useState, type ElementType } from "react";+import { useCallback, useState, type ElementType } from "react";import type {ActionHorizonKey,NextAction,@@ -8,6 +8,7 @@ import type {WorkspaceRepoActions,} from "@repowise-dev/types/actions";+import type { AiPromptFlavor } from "../health/ai-prompt-builder";import { ActionDrawer } from "../overview/action-drawer";import { ActionRow, renderActionTitle } from "../overview/next-actions";import { OverviewSection } from "../overview/section";@@ -23,6 +24,10 @@ export interface WorkspaceNextActionsProps {fileHref?: ((repoId: string, path: string) => string | null) | undefined;/** Where cross-repository contract changes are listed. */contractsHref: string;+ /** An action's agent prompt as core renders it, given its repository's id. Omit to hide the prompt. */+ loadPrompt?:+ | ((repoId: string, action: NextAction, flavor: AiPromptFlavor) => Promise<string>)+ | undefined;LinkComponent?: ElementType | undefined;}@@ -46,15 +51,21 @@ export function WorkspaceNextActions({repoHref,fileHref,contractsHref,+ loadPrompt,LinkComponent,}: WorkspaceNextActionsProps) {const [horizon, setHorizon] = useState<ActionHorizonKey>(data.repos.some((r) => work(r, "week") > 0) ? "week" : "quarter",);- const [opened, setOpened] = useState<{ action: NextAction; repo: string; repoId: string } | null>(+ const [opened, setOpened] = useState<{ action: NextAction; repoId: string } | null>(null,);const Link = LinkComponent ?? "a";+ const openedRepoId = opened?.repoId;+ const loadActionPrompt = useCallback(+ (action: NextAction, flavor: AiPromptFlavor) => loadPrompt!(openedRepoId!, action, flavor),+ [loadPrompt, openedRepoId],+ );const available = data.repos.filter((r) => r.status === "available");const withWork = available@@ -142,7 +153,7 @@ export function WorkspaceNextActions({key={action.id}action={action}selected={opened?.action.id === action.id && opened.repoId === repoId}- onOpen={() => setOpened({ action, repo: repo.alias, repoId })}+ onOpen={() => setOpened({ action, repoId })}/>))}</ul>@@ -168,7 +179,7 @@ export function WorkspaceNextActions({onClose={() => setOpened(null)}evidenceHref={opened ? hrefFor(opened.repoId, opened.action) : null}fileHref={opened && fileHref ? (path) => fileHref(opened.repoId, path) : undefined}- repoName={opened?.repo}+ loadPrompt={loadPrompt ? loadActionPrompt : undefined}LinkComponent={LinkComponent}renderTitle={renderActionTitle}/>diff --git a/packages/web/src/app/repos/[id]/overview/page.tsx b/packages/web/src/app/repos/[id]/overview/page.tsxindex 7be8fd356..c8668bf38 100644--- a/packages/web/src/app/repos/[id]/overview/page.tsx+++ b/packages/web/src/app/repos/[id]/overview/page.tsx@@ -141,7 +141,7 @@ export default async function OverviewPage({ params }: Props) {// A server that predates actions returns 404; the page then keeps the// attention areas in their old place rather than showing an empty list.actions: actions ? (- <NextActionsPanel repoId={id} repoName={repo.name} data={actions} />+ <NextActionsPanel repoId={id} data={actions} />) : undefined,}}/>diff --git a/packages/web/src/app/workspace/workspace-next-actions-panel.tsx b/packages/web/src/app/workspace/workspace-next-actions-panel.tsxindex d5860c0c1..61ead1cd4 100644--- a/packages/web/src/app/workspace/workspace-next-actions-panel.tsx+++ b/packages/web/src/app/workspace/workspace-next-actions-panel.tsx@@ -1,10 +1,16 @@"use client";import Link from "next/link";-import type { WorkspaceActionsResponse } from "@repowise-dev/types/actions";+import type { NextAction, WorkspaceActionsResponse } from "@repowise-dev/types/actions";+import type { AgentPromptFlavor } from "@repowise-dev/types/agent-prompts";import { actionHref } from "@repowise-dev/ui/overview";import { fileEntityPath } from "@repowise-dev/ui/shared/entity";import { WorkspaceNextActions } from "@repowise-dev/ui/workspace/workspace-next-actions";+import { getActionPrompt } from "@/lib/api/actions";++async function loadPrompt(repoId: string, action: NextAction, flavor: AgentPromptFlavor) {+ return (await getActionPrompt(repoId, action.id, { flavor })).text;+}/** The local app's routes for the workspace "Do next"; the list is shared. */export function WorkspaceNextActionsPanel({ data }: { data: WorkspaceActionsResponse }) {@@ -16,6 +22,7 @@ export function WorkspaceNextActionsPanel({ data }: { data: WorkspaceActionsResprepoHref={(repoId) => `/repos/${repoId}/overview`}fileHref={(repoId, path) => fileEntityPath(`/repos/${repoId}`, path)}contractsHref="/workspace/contracts"+ loadPrompt={loadPrompt}/>);}diff --git a/packages/web/src/components/code-health/fix-first-section.test.tsx b/packages/web/src/components/code-health/fix-first-section.test.tsxindex 3d3c405bd..a2e3dbe7c 100644--- a/packages/web/src/components/code-health/fix-first-section.test.tsx+++ b/packages/web/src/components/code-health/fix-first-section.test.tsx@@ -1,19 +1,23 @@// @vitest-environment jsdom-import { describe, expect, it, vi } from "vitest";-import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";import { SWRConfig } from "swr";import type { FixFirstQueue, FixItem } from "@repowise-dev/types/fix-first";const getFixFirst = vi.fn();const updateFindingStatus = vi.fn();+const getFixFirstItemPrompt = vi.fn();vi.mock("@/lib/api/code-health", () => ({getFixFirst: (...args: unknown[]) => getFixFirst(...args),+ getFixFirstItemPrompt: (...args: unknown[]) => getFixFirstItemPrompt(...args),updateFindingStatus: (...args: unknown[]) => updateFindingStatus(...args),}));import { FixFirstSection, fixPlanHref } from "./fix-first-section";+afterEach(cleanup);+function item(overrides: Partial<FixItem>): FixItem {return {id: "fix1_a",@@ -117,4 +121,16 @@ describe("FixFirstSection", () => {expect(updateFindingStatus).toHaveBeenCalledWith("r1", "finding_1", "resolved");expect(updateFindingStatus).toHaveBeenCalledWith("r1", "finding_2", "resolved");});++ it("shows the prompt core renders for the item, in the list's scope", async () => {+ getFixFirst.mockResolvedValue(queue([item({})]));+ getFixFirstItemPrompt.mockResolvedValue({ flavor: "generic", text: "Core prompt text" });+ renderSection();+ fireEvent.click((await screen.findAllByRole("button", { name: "Copy prompt for an agent" }))[0]!);+ expect(await screen.findByText("Core prompt text")).toBeTruthy();+ expect(getFixFirstItemPrompt).toHaveBeenCalledWith("r1", "fix1_a", {+ flavor: expect.any(String),+ scope: "production",+ });+ });});diff --git a/packages/web/src/components/code-health/fix-first-section.tsx b/packages/web/src/components/code-health/fix-first-section.tsxindex 8d753e530..ca837b1e7 100644--- a/packages/web/src/components/code-health/fix-first-section.tsx+++ b/packages/web/src/components/code-health/fix-first-section.tsx@@ -12,7 +12,8 @@ import useSWR, { useSWRConfig } from "swr";import { FixFirstList } from "@repowise-dev/ui/health";import { fileEntityPath } from "@repowise-dev/ui/shared/entity";import type { FixFirstQueue, FixItem, FixScope } from "@repowise-dev/types/fix-first";-import { getFixFirst, updateFindingStatus } from "@/lib/api/code-health";+import type { AgentPromptFlavor } from "@repowise-dev/types/agent-prompts";+import { getFixFirst, getFixFirstItemPrompt, updateFindingStatus } from "@/lib/api/code-health";/** Items the section lists. The server caps the route at 50. */const LIMIT = 10;@@ -26,7 +27,7 @@ export function fixPlanHref(repoId: string, item: FixItem): string | null {return null;}-export function FixFirstSection({ repoId, repoName }: { repoId: string; repoName?: string }) {+export function FixFirstSection({ repoId }: { repoId: string }) {const [scope, setScope] = useState<FixScope>("production");const key = `code-health-fix-first:${repoId}:${scope}`;const { data, error, isLoading, mutate } = useSWR<FixFirstQueue>(@@ -52,6 +53,12 @@ export function FixFirstSection({ repoId, repoName }: { repoId: string; repoName[repoId, mutateAll],);+ const loadPrompt = useCallback(+ async (item: FixItem, flavor: AgentPromptFlavor) =>+ (await getFixFirstItemPrompt(repoId, item.id, { flavor, scope })).text,+ [repoId, scope],+ );+const prefix = `/repos/${repoId}`;return (<FixFirstList@@ -64,8 +71,8 @@ export function FixFirstSection({ repoId, repoName }: { repoId: string; repoNamefileHref={(path) => fileEntityPath(prefix, path)}planHref={(item) => fixPlanHref(repoId, item)}onTriage={onTriage}+ loadPrompt={loadPrompt}LinkComponent={Link}- {...(repoName ? { repoName } : {})}/>);}diff --git a/packages/web/src/components/overview/next-actions-panel.tsx b/packages/web/src/components/overview/next-actions-panel.tsxindex c9b8e5f3b..947bd1a38 100644--- a/packages/web/src/components/overview/next-actions-panel.tsx+++ b/packages/web/src/components/overview/next-actions-panel.tsx@@ -1,30 +1,29 @@"use client";import Link from "next/link";-import type { ActionsResponse } from "@repowise-dev/types/actions";+import { useCallback } from "react";+import type { ActionsResponse, NextAction } from "@repowise-dev/types/actions";+import type { AgentPromptFlavor } from "@repowise-dev/types/agent-prompts";import { NextActions } from "@repowise-dev/ui/overview/next-actions";import { actionHref } from "@repowise-dev/ui/overview";import { fileEntityPath } from "@repowise-dev/ui/shared/entity";-import { setActionState } from "@/lib/api/actions";+import { getActionPrompt, setActionState } from "@/lib/api/actions";/*** The local app's binding for "Do next": its routes and its write path. The* list itself, and every word on it, is the shared component.*/-export function NextActionsPanel({- repoId,- repoName,- data,-}: {- repoId: string;- repoName: string;- data: ActionsResponse;-}) {+export function NextActionsPanel({ repoId, data }: { repoId: string; data: ActionsResponse }) {const base = `/repos/${repoId}`;+ const loadPrompt = useCallback(+ async (action: NextAction, flavor: AgentPromptFlavor) =>+ (await getActionPrompt(repoId, action.id, { flavor })).text,+ [repoId],+ );return (<NextActionsdata={data}- repoName={repoName}+ loadPrompt={loadPrompt}LinkComponent={Link}hrefFor={(action) => actionHref(action, base)}fileHref={(path) => fileEntityPath(base, path)}diff --git a/tests/fixtures/agent_prompts/actions.json b/tests/fixtures/agent_prompts/actions.jsonindex 004e5cd02..e654bba0f 100644--- a/tests/fixtures/agent_prompts/actions.json+++ b/tests/fixtures/agent_prompts/actions.json@@ -1,5 +1,5 @@{- "_comment": "Representative next actions in their wire shape (Action.as_dict()). buildActionPrompt and repowise.core.agent_prompts.render_action must both render golden.json from them; see packages/ui/__tests__/health/agent-prompt-parity.test.ts.",+ "_comment": "Representative next actions in their wire shape (Action.as_dict()). repowise.core.agent_prompts.render_action renders golden.json from them; see tests/unit/agent_prompts/test_golden.py.","cases": [{"name": "evidence_over_cap",diff --git a/tests/fixtures/agent_prompts/fix_items.json b/tests/fixtures/agent_prompts/fix_items.jsonindex f9d674686..50ac0c850 100644--- a/tests/fixtures/agent_prompts/fix_items.json+++ b/tests/fixtures/agent_prompts/fix_items.json@@ -1,5 +1,5 @@{- "_comment": "Representative Fix-first items in their wire shape (FixItem.as_dict()). buildFixItemPrompt/fixVerifyLines and repowise.core.agent_prompts must both render golden.json from them; see packages/ui/__tests__/health/agent-prompt-parity.test.ts.",+ "_comment": "Representative Fix-first items in their wire shape (FixItem.as_dict()). repowise.core.agent_prompts renders golden.json from them; see tests/unit/agent_prompts/test_golden.py.","cases": [{"name": "no_tests_mixed_args",diff --git a/tests/unit/agent_prompts/test_parity.py b/tests/unit/agent_prompts/test_golden.pysimilarity index 57%rename from tests/unit/agent_prompts/test_parity.pyrename to tests/unit/agent_prompts/test_golden.pyindex 6579265fa..2f339701c 100644--- a/tests/unit/agent_prompts/test_parity.py+++ b/tests/unit/agent_prompts/test_golden.py@@ -1,13 +1,16 @@-"""Core's agent prompts render the bytes the web builders do.+"""Core's agent prompts render ``tests/fixtures/agent_prompts/golden.json``.-``tests/fixtures/agent_prompts/golden.json`` is written by the web side-(``packages/ui/__tests__/health/agent-prompt-parity.test.ts``); this checks core-against the same file, so a wording change on one side fails on the other.+Core is the one renderer: the web shows these prompts from the server. The+golden pins every flavor's bytes, so a wording change shows up as a diff here.++Regenerate after a deliberate wording change:+ UPDATE_AGENT_PROMPT_GOLDENS=1 pytest tests/unit/agent_prompts/test_golden.py"""from __future__ import annotationsimport json+import osimport pathlibimport pytest@@ -26,11 +29,34 @@ def _load(name: str) -> dict:return json.loads((_DIR / name).read_text(encoding="utf-8"))-_GOLDEN = _load("golden.json")_ACTIONS = _load("actions.json")["cases"]_ITEMS = _load("fix_items.json")["cases"]+def _render_all() -> dict:+ def per_flavor(render) -> dict[str, str]:+ return {flavor: render(flavor) for flavor in FLAVORS}++ return {+ "action": {+ c["name"]: per_flavor(lambda f, c=c: render_action(c["action"], f, c.get("repo_name")))+ for c in _ACTIONS+ },+ "fix_item": {+ c["name"]: per_flavor(lambda f, c=c: render_fix_item(c["item"], f, c.get("repo_name")))+ for c in _ITEMS+ },+ "verify": {c["name"]: render_verify_lines(c["item"]) for c in _ITEMS},+ }+++if os.environ.get("UPDATE_AGENT_PROMPT_GOLDENS"):+ (_DIR / "golden.json").write_text(+ json.dumps(_render_all(), indent=2, ensure_ascii=False) + "\n", encoding="utf-8", newline="\n"+ )+_GOLDEN = _load("golden.json")++@pytest.mark.parametrize("flavor", FLAVORS)@pytest.mark.parametrize("case", _ACTIONS, ids=lambda c: c["name"])def test_action_matches_golden(case: dict, flavor: str) -> None: