Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(ui): one shared prompt preamble, a Verify block everywhere, and Ask in chat from the prompt modal (#2848)

Raghav Chamadiya58acf90d6057
diff --git a/packages/ui/__tests__/health/__snapshots__/action-prompt.test.ts.snap b/packages/ui/__tests__/health/__snapshots__/action-prompt.test.ts.snap
new file mode 100644
index 000000000..85bfd7c30
--- /dev/null
+++ b/packages/ui/__tests__/health/__snapshots__/action-prompt.test.ts.snap
@@ -0,0 +1,117 @@
+// 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__/file-health-prompt.test.tsx.snap b/packages/ui/__tests__/health/__snapshots__/file-health-prompt.test.tsx.snap
new file mode 100644
index 000000000..031155d1b
--- /dev/null
+++ b/packages/ui/__tests__/health/__snapshots__/file-health-prompt.test.tsx.snap
@@ -0,0 +1,10 @@
+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+
+exports[`FLAVOR_PREAMBLE > keeps every flavor's opening 1`] = `
+{
+ "claude-code": "You are Claude Code working in this repository. The findings below were detected by repowise's static analyzer. Treat each item as a lead, not ground truth. Use Read, Grep and Glob on the file, its callers, its tests and its neighbors before planning edits, and flag any false positive. Use TodoWrite for non-trivial steps.",
+ "claude-code-mcp": "You are Claude Code working in this repository, which is indexed by repowise and exposes its MCP tools. The findings below were detected by repowise's static analyzer. Treat each item as a lead, not ground truth. Before re-reading files by hand, pull the context repowise already computed: call \`get_context([...])\` for the file skeleton (every signature + the bodies of the most central symbols, ~37% of a full Read), \`get_symbol("file::Name")\` for the exact bytes of one function, \`get_risk([...])\` before editing to see blast radius, co-change partners, and test gaps, and \`get_why(...)\` for the decision behind the current shape. Fall back to Read / Grep / Glob only for what the index cannot serve, and flag any false positive. Use TodoWrite for non-trivial steps.",
+ "cursor": "Work on the file referenced below. The findings below were detected by repowise's static analyzer. Treat each item as a lead, not ground truth. Use @file and @codebase to read the file, its callers, its tests and its neighbors before editing, and call out any false positive.",
+ "generic": "You are a senior engineer working on one file in this repository. The findings below were detected by repowise's static analyzer. Treat each item as a lead, not ground truth. Open the file, its callers, its tests and its neighbors, then confirm each item in the code before you act. If one is a false positive, say so and skip it.",
+}
+`;
diff --git a/packages/ui/__tests__/health/__snapshots__/fix-first.test.tsx.snap b/packages/ui/__tests__/health/__snapshots__/fix-first.test.tsx.snap
new file mode 100644
index 000000000..a95516c3e
--- /dev/null
+++ b/packages/ui/__tests__/health/__snapshots__/fix-first.test.tsx.snap
@@ -0,0 +1,419 @@
+// 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.ts
index a4921ffc7..dcf726bdb 100644
--- a/packages/ui/__tests__/health/action-prompt.test.ts
+++ b/packages/ui/__tests__/health/action-prompt.test.ts
@@ -62,4 +62,12 @@ describe("buildActionPrompt", () => {
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/ai-prompt-modal.test.tsx b/packages/ui/__tests__/health/ai-prompt-modal.test.tsx
index 27a9a28e1..1b8cf1d19 100644
--- a/packages/ui/__tests__/health/ai-prompt-modal.test.tsx
+++ b/packages/ui/__tests__/health/ai-prompt-modal.test.tsx
@@ -1,6 +1,9 @@
-import { describe, expect, it } from "vitest";
-import { render, screen } from "@testing-library/react";
-import { AiPromptModal } from "../../src/health/ai-prompt-modal.js";
+import { useState } from "react";
+import { describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import type { ChatHandoff } from "@repowise-dev/types/chat";
+import { AiPromptModal, fileChatContext } from "../../src/health/ai-prompt-modal.js";
+import { ChatHandoffProvider } from "../../src/chat/chat-handoff.js";
describe("AiPromptModal overflow containment", () => {
it("contains long unbroken prompt text and keeps its actions inside the dialog", () => {
@@ -27,3 +30,85 @@ describe("AiPromptModal overflow containment", () => {
expect(screen.getByRole("button", { name: "Copy prompt" }).className).toContain("shrink-0");
});
});
+
+describe("AiPromptModal Ask in chat", () => {
+ const CONTEXT = fileChatContext("src/a.py")!;
+
+ function renderModal({
+ onHandoff = vi.fn(),
+ onOpenChange = vi.fn(),
+ askEnabled = true,
+ withContext = true,
+ }: {
+ onHandoff?: (handoff: ChatHandoff) => void;
+ onOpenChange?: (open: boolean) => void;
+ askEnabled?: boolean;
+ withContext?: boolean;
+ } = {}) {
+ render(
+ <ChatHandoffProvider onHandoff={onHandoff} askEnabled={askEnabled}>
+ <AiPromptModal
+ open
+ onOpenChange={onOpenChange}
+ getPrompt={(flavor) => `Prompt for ${flavor}`}
+ {...(withContext ? { chatContext: CONTEXT } : {})}
+ />
+ </ChatHandoffProvider>,
+ );
+ }
+
+ it("seeds chat with the prompt on screen and closes the modal", () => {
+ const onHandoff = vi.fn();
+ const onOpenChange = vi.fn();
+ renderModal({ onHandoff, onOpenChange });
+
+ const shown = screen.getByRole("dialog").querySelector("pre")!.textContent;
+ fireEvent.click(screen.getByRole("button", { name: "Ask in chat" }));
+
+ expect(onHandoff).toHaveBeenCalledWith({ context: CONTEXT, question: shown, autoSend: false });
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ });
+
+ it("is absent for a prompt with no single subject", () => {
+ renderModal({ withContext: false });
+ expect(screen.queryByRole("button", { name: "Ask in chat" })).toBeNull();
+ expect(screen.getByRole("button", { name: "Copy prompt" })).toBeTruthy();
+ });
+
+ it("is absent when the host has chat controls off", () => {
+ renderModal({ askEnabled: false });
+ expect(screen.queryByRole("button", { name: "Ask in chat" })).toBeNull();
+ });
+
+ // The chat dock focuses its composer a frame after the handoff; a focus
+ // restore to the opener on close would race it. The modal is opened by host
+ // state, not a Radix Dialog.Trigger, so Radix restores nothing; pin that.
+ it("does not hand focus back to the opener after Ask in chat", async () => {
+ function Harness() {
+ const [open, setOpen] = useState(false);
+ return (
+ <ChatHandoffProvider onHandoff={() => undefined}>
+ <button type="button" onClick={() => setOpen(true)}>
+ Open prompt
+ </button>
+ <AiPromptModal open={open} onOpenChange={setOpen} getPrompt={() => "p"} chatContext={CONTEXT} />
+ </ChatHandoffProvider>
+ );
+ }
+ render(<Harness />);
+ const opener = screen.getByRole("button", { name: "Open prompt" });
+ opener.focus();
+ fireEvent.click(opener);
+ fireEvent.click(await screen.findByRole("button", { name: "Ask in chat" }));
+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
+ await new Promise((r) => setTimeout(r, 0));
+ expect(document.activeElement).not.toBe(opener);
+ });
+
+ it("is absent outside a chat host", () => {
+ render(
+ <AiPromptModal open onOpenChange={() => undefined} getPrompt={() => "p"} chatContext={CONTEXT} />,
+ );
+ expect(screen.queryByRole("button", { name: "Ask in chat" })).toBeNull();
+ });
+});
diff --git a/packages/ui/__tests__/health/file-health-prompt.test.tsx b/packages/ui/__tests__/health/file-health-prompt.test.tsx
index 0dcfc1a50..fead460ea 100644
--- a/packages/ui/__tests__/health/file-health-prompt.test.tsx
+++ b/packages/ui/__tests__/health/file-health-prompt.test.tsx
@@ -12,6 +12,7 @@ import {
buildFileHealthAiPrompt,
type FileHealthPromptFinding,
} from "../../src/health/ai-prompt-builder.js";
+import { FLAVOR_PREAMBLE } from "../../src/health/ai-prompts/shared.js";
import {
HealthFileDrawer,
type HealthDrawerMetric,
@@ -58,7 +59,7 @@ describe("buildFileHealthAiPrompt", () => {
// The whole point of handing over a static report. A prompt that reads as
// a work order gets a file edited to satisfy an analyzer.
const out = buildFileHealthAiPrompt({ file, findings: [finding()] });
- expect(out).toMatch(/leads/i);
+ expect(out).toMatch(/as a lead, not ground truth/i);
expect(out).toMatch(/false positive/i);
expect(out).toMatch(/which findings share a root cause/i);
});
@@ -143,6 +144,14 @@ describe("buildFileHealthAiPrompt", () => {
});
});
+// Every single-file prompt opens on this text, so pin each flavor of it.
+describe("FLAVOR_PREAMBLE", () => {
+ it("keeps every flavor's opening", () => {
+ expect(FLAVOR_PREAMBLE).toMatchSnapshot();
+ expect(FLAVOR_PREAMBLE["claude-code-mcp"]).toContain("Fall back to Read / Grep / Glob only");
+ });
+});
+
describe("the drawer's prompt affordance", () => {
const m: HealthDrawerMetric = {
file_path: "packages/cli/doctor_cmd.py",
diff --git a/packages/ui/__tests__/health/fix-first.test.tsx b/packages/ui/__tests__/health/fix-first.test.tsx
index 268c10d66..7ef69477d 100644
--- a/packages/ui/__tests__/health/fix-first.test.tsx
+++ b/packages/ui/__tests__/health/fix-first.test.tsx
@@ -139,4 +139,14 @@ describe("Fix first agent prompt", () => {
const prompt = buildFixItemPrompt({ item: FINDING });
expect(prompt).toContain("No guarding tests found.");
});
+
+ // 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}`);
+ }
+ }
+ });
});
diff --git a/packages/ui/__tests__/workspace/co-change-ai-prompt.test.ts b/packages/ui/__tests__/workspace/co-change-ai-prompt.test.ts
index 74e0599c1..3c5aeaf61 100644
--- a/packages/ui/__tests__/workspace/co-change-ai-prompt.test.ts
+++ b/packages/ui/__tests__/workspace/co-change-ai-prompt.test.ts
@@ -146,6 +146,28 @@ describe("buildCoChangeRepoPairAiPrompt", () => {
});
});
+describe("co-change prompt Verify", () => {
+ it("asks for the tests over both files of the pair", () => {
+ const p = buildCoChangePairAiPrompt({ pair: pair() });
+ expect(p).toContain("Treat each item as a lead, not ground truth.");
+ expect(p).toContain(
+ "## Verify\n\nNo test data came with this prompt. Find the tests that exercise `app/models/schemas/repos.py`, `src/lib/api/types.ts`",
+ );
+ expect(p.indexOf("## Verify")).toBeLessThan(p.indexOf("## Hard constraints"));
+ });
+
+ it("points the read-first flavors at the files and at `git log` in each repository", () => {
+ for (const flavor of ["generic", "claude-code", "cursor"] as const) {
+ const opening = buildCoChangePairAiPrompt({ pair: pair(), flavor }).split("\n")[0]!;
+ expect(opening).toContain("Run `git log` on each file in its own repository");
+ expect(opening).not.toContain("the commits that touched them before");
+ }
+ expect(buildCoChangePairAiPrompt({ pair: pair(), flavor: "claude-code" })).toContain(
+ "Use Read, Grep and Glob on the files it names before planning edits",
+ );
+ });
+});
+
describe("capRule", () => {
it("names the cap the server says applied", () => {
expect(capRule({ truncatedBy: null, perRepoPairCap: 50, totalCap: 200 })).toBeNull();
diff --git a/packages/ui/__tests__/workspace/contract-ai-prompt.test.ts b/packages/ui/__tests__/workspace/contract-ai-prompt.test.ts
index fb701da0d..fbf644c78 100644
--- a/packages/ui/__tests__/workspace/contract-ai-prompt.test.ts
+++ b/packages/ui/__tests__/workspace/contract-ai-prompt.test.ts
@@ -89,6 +89,20 @@ describe("buildContractAiPrompt", () => {
expect(prompt).toContain("get_blast_radius");
expect(prompt).toContain("search_codebase");
});
+
+ it("ends the MCP flavor on a closer, like its sibling prompts", () => {
+ const closer = "Start with `search_codebase` for `http::GET::/users/{param}`";
+ const mcp = buildContractAiPrompt({ contract: contract(), links: [LINK], flavor: "claude-code-mcp" });
+ expect(mcp.trimEnd().split("\n").pop()).toContain(closer);
+ expect(mcp).toContain("`get_context(['src/routes/users.py'])` in `users-api`");
+ expect(buildContractAiPrompt({ contract: contract(), links: [LINK] })).not.toContain(closer);
+ });
+
+ it("names the contract file and its counterparts in Verify", () => {
+ const prompt = buildContractAiPrompt({ contract: contract(), links: [LINK] });
+ expect(prompt).toContain("Find the tests that exercise `src/routes/users.py`, `src/api/users.ts`");
+ expect(prompt.indexOf("## Verify")).toBeLessThan(prompt.indexOf("## Hard constraints"));
+ });
});
describe("buildUnmatchedConsumersAiPrompt", () => {
diff --git a/packages/ui/__tests__/workspace/system-map-ai-prompt.test.ts b/packages/ui/__tests__/workspace/system-map-ai-prompt.test.ts
index 89b119ba4..1afe25d5f 100644
--- a/packages/ui/__tests__/workspace/system-map-ai-prompt.test.ts
+++ b/packages/ui/__tests__/workspace/system-map-ai-prompt.test.ts
@@ -249,5 +249,13 @@ describe("system map AI prompts", () => {
expect(text).toContain("## Will break (structural)");
expect(text).toContain("## May drift (co-change only)");
expect(text).toContain("**ui** (`ui`, repo repowise): 2 hops, impact 0.10");
+ expect(text).toContain("## Verify\n\nNo test data came with this prompt. Find the tests that exercise `backend`");
+ });
+
+ it("opens on the shared lead sentence and keeps a blank line between sections", () => {
+ const text = buildCycleAiPrompt({ names: ["a", "b"], ids: ["a", "b"], edges: [] });
+ expect(text).toContain("Treat each item as a lead, not ground truth.");
+ expect(text).toContain("\n\n## Dependency cycle: a -> b -> a\n\n- Services:");
+ expect(text).toContain("\n\n## Verify\n\n");
});
});
diff --git a/packages/ui/src/decisions/decision-detail.tsx b/packages/ui/src/decisions/decision-detail.tsx
index a086f7849..14823c437 100644
--- a/packages/ui/src/decisions/decision-detail.tsx
+++ b/packages/ui/src/decisions/decision-detail.tsx
@@ -22,6 +22,7 @@ import {
Flame,
GitCommitHorizontal,
} from "lucide-react";
+import type { ChatContext } from "@repowise-dev/types/chat";
import type {
DecisionRecord,
DecisionStatus,
@@ -110,6 +111,13 @@ export function DecisionDetail({ decision, adapter }: DecisionDetailProps) {
// Which AI-prompt flavor the modal shows: verification ("is this decision
// still true?") or enforcement ("make the code conform to it").
const [promptMode, setPromptMode] = React.useState<"verify" | "enforce" | null>(null);
+ // One subject for both the chat control and the prompt modal's "Ask in chat".
+ const chatContext: ChatContext = {
+ kind: "decision",
+ label: stripMarkdown(decision.title),
+ target: decision.id,
+ targetKind: "decision",
+ };
// Read from `decision.affected_files` and not from `linkedFiles`, which the
// editor below mutates locally. `staleness_score` is a proportion the server
@@ -290,12 +298,7 @@ export function DecisionDetail({ decision, adapter }: DecisionDetailProps) {
<VerificationBadge verification={decision.verification} />
)}
<AskAboutThis
- context={{
- kind: "decision",
- label: stripMarkdown(decision.title),
- target: decision.id,
- targetKind: "decision",
- }}
+ context={chatContext}
question={`Why was this decision made, what evidence supports it, and has later work conflicted with it?`}
label="Ask about this decision"
/>
@@ -575,6 +578,7 @@ export function DecisionDetail({ decision, adapter }: DecisionDetailProps) {
})
}
filePath={stripMarkdown(decision.title)}
+ chatContext={chatContext}
title={
promptMode === "enforce"
? "AI decision enforcement"
diff --git a/packages/ui/src/doc-drift/doc-drift-view.tsx b/packages/ui/src/doc-drift/doc-drift-view.tsx
index 7f2dfd43d..7dd23a1ff 100644
--- a/packages/ui/src/doc-drift/doc-drift-view.tsx
+++ b/packages/ui/src/doc-drift/doc-drift-view.tsx
@@ -41,7 +41,7 @@ import { OverviewSection } from "../overview/section";
import { toFriendlyMessage } from "../lib/errors";
import { AiPromptButton } from "../health/ai-prompt-button";
-import { AiPromptModal } from "../health/ai-prompt-modal";
+import { AiPromptModal, fileChatContext } from "../health/ai-prompt-modal";
import { buildDocDriftAiPrompt } from "../health/ai-prompt-builder";
import { DocDriftLede } from "./doc-drift-lede";
@@ -286,6 +286,9 @@ export function DocDriftView({
? `${promptFindings[0]!.file_path}:${promptFindings[0]!.line_number}`
: null
}
+ chatContext={
+ promptFindings?.length === 1 ? fileChatContext(promptFindings[0]!.file_path) : undefined
+ }
getPrompt={
promptFindings
? (flavor) =>
diff --git a/packages/ui/src/health/ai-prompt-modal.tsx b/packages/ui/src/health/ai-prompt-modal.tsx
index 7a5558183..b98dbf0cf 100644
--- a/packages/ui/src/health/ai-prompt-modal.tsx
+++ b/packages/ui/src/health/ai-prompt-modal.tsx
@@ -1,7 +1,8 @@
"use client";
import { useEffect, useMemo, useState } from "react";
-import { Check, Copy, Sparkles } from "lucide-react";
+import { Check, Copy, MessageCircleQuestion, Sparkles } from "lucide-react";
+import type { ChatContext } from "@repowise-dev/types/chat";
import {
Dialog,
DialogContent,
@@ -9,6 +10,7 @@ import {
DialogHeader,
DialogTitle,
} from "../ui/dialog";
+import { useChatHandoff } from "../chat/chat-handoff";
import { ViewToggle } from "./code-health-controls";
import type { AiPromptFlavor } from "./ai-prompt-builder";
@@ -23,6 +25,14 @@ export interface AiPromptModalProps {
title?: string;
/** One-line subtitle below the title. */
description?: string;
+ /** The one thing this prompt is about. With it the prompt can also be asked
+ * in chat; without it (a table-wide prompt) it can only be copied. */
+ chatContext?: ChatContext | undefined;
+}
+
+/** The chat context for a prompt about one file, or none without a path. */
+export function fileChatContext(path: string | null | undefined): ChatContext | undefined {
+ return path ? { kind: "file", label: path, target: path, targetKind: "path" } : undefined;
}
/** The four target agents, in the order the segmented control renders them.
@@ -54,6 +64,37 @@ function loadStoredFlavor(): AiPromptFlavor {
return "generic";
}
+/**
+ * Hands the prompt on screen to chat, seeded in the composer rather than sent.
+ * Neutral beside the primary Copy pill, and absent when there is no single
+ * subject or the host has chat controls off.
+ */
+function AskPromptInChat({
+ prompt,
+ context,
+ onAsked,
+}: {
+ prompt: string;
+ context: ChatContext | undefined;
+ onAsked: (() => void) | undefined;
+}) {
+ const { request, askEnabled } = useChatHandoff();
+ if (!context || !askEnabled) return null;
+ return (
+ <button
+ type="button"
+ onClick={() => {
+ request({ context, question: prompt, autoSend: false });
+ onAsked?.();
+ }}
+ disabled={!prompt}
+ className="inline-flex shrink-0 items-center gap-1.5 rounded-md border border-[var(--color-border-default)] px-3 py-1.5 text-xs font-medium text-[var(--color-text-primary)] transition-colors hover:border-[var(--color-border-hover)] hover:bg-[var(--color-bg-elevated)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] disabled:opacity-50 motion-reduce:transition-none"
+ >
+ <MessageCircleQuestion className="h-3.5 w-3.5" aria-hidden /> Ask in chat
+ </button>
+ );
+}
+
/**
* The prompt itself: which agent it is written for, the text, and a copy
* button. Shared by the modal and by drawers that show the prompt inline, so
@@ -62,10 +103,16 @@ function loadStoredFlavor(): AiPromptFlavor {
export function AiPromptBlock({
getPrompt,
bleed = "px-6",
+ chatContext,
+ onAsked,
}: {
getPrompt: ((flavor: AiPromptFlavor) => string) | null;
/** 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. */
+ chatContext?: ChatContext | undefined;
+ /** Called after the prompt is handed to chat, e.g. to close the host. */
+ onAsked?: () => void;
}) {
const [flavor, setFlavorState] = useState<AiPromptFlavor>(loadStoredFlavor);
const [copied, setCopied] = useState(false);
@@ -127,27 +174,30 @@ export function AiPromptBlock({
{prompt.length.toLocaleString()} chars, approx{" "}
{Math.round(prompt.length / 4).toLocaleString()} tokens
</span>
- <button
- type="button"
- onClick={handleCopy}
- disabled={!prompt}
- className={
- "inline-flex shrink-0 items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-semibold transition-colors " +
- (copied
- ? "bg-[var(--color-success)] text-[var(--color-text-inverse)]"
- : "bg-[var(--color-model)] text-[var(--color-text-on-model)] hover:bg-[var(--color-model-hover)]")
- }
- >
- {copied ? (
- <>
- <Check className="h-3.5 w-3.5" /> Copied
- </>
- ) : (
- <>
- <Copy className="h-3.5 w-3.5" /> Copy prompt
- </>
- )}
- </button>
+ <div className="flex shrink-0 flex-wrap items-center gap-2">
+ <AskPromptInChat prompt={prompt} context={chatContext} onAsked={onAsked} />
+ <button
+ type="button"
+ onClick={handleCopy}
+ disabled={!prompt}
+ className={
+ "inline-flex shrink-0 items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-semibold transition-colors " +
+ (copied
+ ? "bg-[var(--color-success)] text-[var(--color-text-inverse)]"
+ : "bg-[var(--color-model)] text-[var(--color-text-on-model)] hover:bg-[var(--color-model-hover)]")
+ }
+ >
+ {copied ? (
+ <>
+ <Check className="h-3.5 w-3.5" /> Copied
+ </>
+ ) : (
+ <>
+ <Copy className="h-3.5 w-3.5" /> Copy prompt
+ </>
+ )}
+ </button>
+ </div>
</div>
</div>
);
@@ -160,6 +210,7 @@ export function AiPromptModal({
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.",
+ chatContext,
}: AiPromptModalProps) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
@@ -178,7 +229,13 @@ export function AiPromptModal({
</DialogHeader>
{/* The block's hairlines run to the modal's edge (`-mx-6` against its `p-6`). */}
<div className="-mx-6 min-w-0">
- {open ? <AiPromptBlock getPrompt={getPrompt} /> : null}
+ {open ? (
+ <AiPromptBlock
+ getPrompt={getPrompt}
+ chatContext={chatContext}
+ onAsked={() => onOpenChange(false)}
+ />
+ ) : null}
</div>
</DialogContent>
</Dialog>
diff --git a/packages/ui/src/health/ai-prompts/action-prompt.ts b/packages/ui/src/health/ai-prompts/action-prompt.ts
index 8631501f5..e7edcc539 100644
--- a/packages/ui/src/health/ai-prompts/action-prompt.ts
+++ b/packages/ui/src/health/ai-prompts/action-prompt.ts
@@ -1,7 +1,14 @@
import type { ActionDetail, NextAction } from "@repowise-dev/types/actions";
import { biomarkerLabel } from "../biomarker-glossary";
-import { bulletList, closingSections, joinSections, repoSuffix, type AiPromptFlavor } from "./shared";
+import {
+ bulletList,
+ closingSections,
+ joinSections,
+ preamble,
+ repoSuffix,
+ type AiPromptFlavor,
+} from "./shared";
// ─────────────────────────────────────────────────────────────────────
// Next action prompt: one action from "Do next", handed to an agent cold
@@ -14,19 +21,19 @@ export interface BuildActionPromptOptions {
}
/**
- * The opening. Not the fix-prompt preamble: an action can span many files and
- * is built from stored analysis, so the agent is told both before it reads a
- * line.
+ * 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:
- "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.",
+ "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":
- "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.",
+ "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":
- "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.",
+ "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:
- "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.",
+ "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 = [
@@ -82,7 +89,7 @@ export function buildActionPrompt({
.filter((l): l is string => l !== null);
return joinSections([
- OPENING[flavor],
+ preamble(flavor, { body: OPENING }),
"",
`## Action${repoSuffix(repoName)}`,
"",
diff --git a/packages/ui/src/health/ai-prompts/fix-first-prompt.ts b/packages/ui/src/health/ai-prompts/fix-first-prompt.ts
index 8bb068d70..9de1132c4 100644
--- a/packages/ui/src/health/ai-prompts/fix-first-prompt.ts
+++ b/packages/ui/src/health/ai-prompts/fix-first-prompt.ts
@@ -1,6 +1,13 @@
import type { FixItem } from "@repowise-dev/types/fix-first";
-import { bulletList, closingSections, joinSections, repoSuffix, type AiPromptFlavor } from "./shared";
+import {
+ bulletList,
+ closingSections,
+ joinSections,
+ preamble,
+ repoSuffix,
+ type AiPromptFlavor,
+} from "./shared";
// ─────────────────────────────────────────────────────────────────────
// Fix first: one ranked item, handed to an agent with its Verify block
@@ -12,15 +19,16 @@ export interface BuildFixItemPromptOptions {
repoName?: string;
}
+/** The opening after the shared role. */
const OPENING: Record<AiPromptFlavor, string> = {
generic:
- "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.",
+ "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":
- "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.",
+ "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":
- "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.",
+ "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:
- "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.",
+ "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 = [
@@ -78,7 +86,7 @@ export function buildFixItemPrompt({
const moreSteps = item.action.steps_total - item.action.steps.length;
return joinSections([
- OPENING[flavor],
+ preamble(flavor, { body: OPENING }),
"",
`## Fix first${repoSuffix(repoName)}`,
"",
diff --git a/packages/ui/src/health/ai-prompts/refactoring-plan-steps.ts b/packages/ui/src/health/ai-prompts/refactoring-plan-steps.ts
index 3bfabbfdc..3a6299419 100644
--- a/packages/ui/src/health/ai-prompts/refactoring-plan-steps.ts
+++ b/packages/ui/src/health/ai-prompts/refactoring-plan-steps.ts
@@ -148,15 +148,6 @@ export function refactoringPlanSteps(plan: RefactoringPlan): string {
return render ? render(plan) : "Apply the refactoring described above.";
}
-/** The validation fields the Verify block reads; refactoring plans, opportunity
- * profiles and the performance queue all carry them. */
-export interface VerifyValidation {
- total: number;
- tests: string[];
- reasons?: Record<string, string> | null | undefined;
- commands: string[];
-}
-
/** What a missing test should exercise: the changed symbol, or the file for a
* plan that changes a whole file (a split, a cycle). Stored ids lose their path. */
export function verifySubject(plan: RefactoringPlan): string {
@@ -165,42 +156,3 @@ export function verifySubject(plan: RefactoringPlan): string {
}
return plan.target_symbol.split("::").pop() || plan.file_path;
}
-
-/** The tests to run after the change, most direct first, each with why it is
- * listed, then the command. With no guarding test, the instruction to add one. */
-export function verifyLines(validation: VerifyValidation, subjects: string[]): string[] {
- if (validation.tests.length === 0) {
- return validation.total > 0
- ? [`Guarding tests: ${validation.total}, but none were included in this payload.`]
- : [
- `No guarding tests found: add a test for ${subjects.map((s) => `\`${s}\``).join(", ")} before changing it.`,
- ];
- }
- const rows = validation.tests.map((test) => {
- const reason = validation.reasons?.[test];
- return `- \`${test}\`${reason ? ` (${reason})` : ""}`;
- });
- const shown =
- validation.total > validation.tests.length
- ? [`${validation.tests.length} of ${validation.total} guarding tests shown.`]
- : [];
- const run = validation.commands.length
- ? ["", "Run:", "", "```", ...validation.commands, "```"]
- : [];
- return [
- "Run these after the change. The tests that exercise it most directly come first:",
- "",
- ...rows,
- ...shown,
- ...run,
- ];
-}
-
-/** A `## Verify` section, or nothing when the payload carries no validation. */
-export function verifySection(
- validation: VerifyValidation | null | undefined,
- subjects: string[],
-): string {
- if (!validation) return "";
- return ["## Verify", "", ...verifyLines(validation, subjects)].join("\n");
-}
diff --git a/packages/ui/src/health/ai-prompts/refactoring-prompts.ts b/packages/ui/src/health/ai-prompts/refactoring-prompts.ts
index 24cefc8b1..057644202 100644
--- a/packages/ui/src/health/ai-prompts/refactoring-prompts.ts
+++ b/packages/ui/src/health/ai-prompts/refactoring-prompts.ts
@@ -11,8 +11,6 @@ import { blastFiles } from "../../refactoring/types";
import {
planSourceLink,
refactoringPlanSteps,
- verifyLines,
- verifySection,
verifySubject,
} from "./refactoring-plan-steps";
import {
@@ -23,6 +21,8 @@ import {
joinSections,
pluralS,
repoSuffix,
+ verifyLines,
+ verifySection,
type AiPromptFlavor,
} from "./shared";
@@ -55,7 +55,8 @@ export function buildPerformanceOpportunityPrompt({
)
.split("::")
.pop() ?? opportunity.file_path;
- const verify = verifySection(opportunity.validation, [subject]);
+ // An older payload carries no validation; it keeps no Verify block.
+ const verify = opportunity.validation ? verifySection(opportunity.validation, [subject]) : "";
return [
FLAVOR_PREAMBLE[flavor],
diff --git a/packages/ui/src/health/ai-prompts/shared.ts b/packages/ui/src/health/ai-prompts/shared.ts
index 2a8a8193d..d5af1c676 100644
--- a/packages/ui/src/health/ai-prompts/shared.ts
+++ b/packages/ui/src/health/ai-prompts/shared.ts
@@ -1,6 +1,6 @@
/**
* The parts every agent prompt shares: the per-flavor opening and closing
- * instructions and the bullet formatter the sections are written in.
+ * instructions and the formatters the sections are written in.
*/
export type AiPromptFlavor =
@@ -9,17 +9,91 @@ export type AiPromptFlavor =
| "claude-code-mcp"
| "cursor";
-export const FLAVOR_PREAMBLE: Record<AiPromptFlavor, string> = {
- generic:
- "You are a senior engineer working on one file in this repository. The findings below were detected by a static analyzer — treat them as **leads, not ground truth**. Open the file, read its callers, tests, and neighbors, and verify each finding against the actual code before you act. If a finding is a false positive given the broader context, say so and skip it.",
- "claude-code":
- "You are Claude Code working in this repository. The findings below were detected by a static analyzer — treat them as leads to investigate, not commands to execute. Use Read, Grep, and Glob to explore the file, its callers, its tests, and any related modules before planning edits. Verify each finding against the actual code; flag any that turn out to be false positives. Use TodoWrite for non-trivial steps.",
+const FLAVORS: AiPromptFlavor[] = ["generic", "claude-code", "claude-code-mcp", "cursor"];
+
+/** Who the agent is, per flavor: the first sentence of every prompt. */
+export type PromptRole = Record<AiPromptFlavor, string>;
+
+export const REPO_ROLE: PromptRole = {
+ generic: "You are a senior engineer in this repository.",
+ "claude-code": "You are Claude Code in this repository.",
+ "claude-code-mcp":
+ "You are Claude Code in this repository, which Repowise indexes and serves over MCP.",
+ cursor: "Work in this repository.",
+};
+
+const FILE_ROLE: PromptRole = {
+ generic: "You are a senior engineer working on one file in this repository.",
+ "claude-code": "You are Claude Code working in this repository.",
+ "claude-code-mcp":
+ "You are Claude Code working in this repository, which is indexed by repowise and exposes its MCP tools.",
+ cursor: "Work on the file referenced below.",
+};
+
+export const WORKSPACE_ROLE: PromptRole = {
+ generic: "You are a senior engineer working across the repositories of one workspace.",
+ "claude-code": "You are Claude Code working across the repositories of one workspace.",
"claude-code-mcp":
- "You are Claude Code working in this repository, which is indexed by repowise and exposes its MCP tools. The findings below were detected by repowise's static analyzer — treat them as leads to investigate, not commands to execute. Before re-reading files by hand, pull the context repowise already computed: call `get_context([...])` for the file skeleton (every signature + the bodies of the most central symbols, ~37% of a full Read), `get_symbol(\"file::Name\")` for the exact bytes of one function, `get_risk([...])` before editing to see blast radius, co-change partners, and test gaps, and `get_why(...)` for the decision behind the current shape. Fall back to Read / Grep / Glob only for what the index can't serve. Verify each finding against the real code; flag false positives. Use TodoWrite for non-trivial steps.",
- cursor:
- "Work on the file referenced below. The findings below were detected by a static analyzer — treat them as leads, not ground truth. Use @file and @codebase to read the file, its callers, its tests, and neighboring modules before editing. Verify each finding against the real code; skip and call out any false positives.",
+ "You are Claude Code working across the repositories of one workspace indexed by repowise, with its MCP tools available.",
+ cursor: "Work across the repositories referenced below.",
};
+const LEAD = "Treat each item as a lead, not ground truth.";
+
+/** How each non-MCP flavor checks the evidence; `open` is what it names. */
+const READ_FIRST: Record<Exclude<AiPromptFlavor, "claude-code-mcp">, (open: string) => string> = {
+ generic: (open) =>
+ `Open ${open}, then confirm each item in the code before you act. If one is a false positive, say so and skip it.`,
+ "claude-code": (open) =>
+ `Use Read, Grep and Glob on ${open} before planning edits, and flag any false positive. Use TodoWrite for non-trivial steps.`,
+ cursor: (open) =>
+ `Use @file and @codebase to read ${open} before editing, and call out any false positive.`,
+};
+
+const MCP_FALLBACK =
+ "Fall back to Read / Grep / Glob only for what the index cannot serve, and flag any false positive. Use TodoWrite for non-trivial steps.";
+
+export type PreambleParts =
+ | {
+ role?: PromptRole;
+ /** What the evidence is and where it came from. */
+ source: string;
+ /** What the agent should read first, e.g. "the files it names". */
+ open: string;
+ /** The repowise MCP calls worth making before reading by hand. */
+ mcpTail: string;
+ }
+ | {
+ role?: PromptRole;
+ /** Per-flavor text after the role, for a prompt whose wording is pinned
+ * elsewhere (the core renderer is parity-tested against it). */
+ body: Record<AiPromptFlavor, string>;
+ };
+
+/** The opening every agent prompt starts on: who the agent is, what the
+ * evidence is, that it is a lead, and how this flavor checks it. */
+export function preamble(flavor: AiPromptFlavor, parts: PreambleParts): string {
+ const role = (parts.role ?? REPO_ROLE)[flavor];
+ if ("body" in parts) return `${role} ${parts.body[flavor]}`;
+ const check =
+ flavor === "claude-code-mcp" ? `${parts.mcpTail} ${MCP_FALLBACK}` : READ_FIRST[flavor](parts.open);
+ return `${role} ${parts.source} ${LEAD} ${check}`;
+}
+
+/** The opening of every single-file prompt. */
+export const FLAVOR_PREAMBLE = Object.fromEntries(
+ FLAVORS.map((flavor) => [
+ flavor,
+ preamble(flavor, {
+ role: FILE_ROLE,
+ source: "The findings below were detected by repowise's static analyzer.",
+ open: "the file, its callers, its tests and its neighbors",
+ mcpTail:
+ "Before re-reading files by hand, pull the context repowise already computed: call `get_context([...])` for the file skeleton (every signature + the bodies of the most central symbols, ~37% of a full Read), `get_symbol(\"file::Name\")` for the exact bytes of one function, `get_risk([...])` before editing to see blast radius, co-change partners, and test gaps, and `get_why(...)` for the decision behind the current shape.",
+ }),
+ ]),
+) as Record<AiPromptFlavor, string>;
+
/** The surface a closer is written for; each names its own tools and risks. */
type CloserKind = "refactor" | "coverage" | "security" | "hotspot" | "file-health";
@@ -122,3 +196,62 @@ export function closingSections(
export function joinSections(sections: string[]): string {
return sections.filter((s) => s !== "").join("\n");
}
+
+export function numbered(items: string[]): string {
+ return items.map((s, i) => `${i + 1}. ${s}`).join("\n");
+}
+
+/** The validation fields the Verify block reads; refactoring plans, opportunity
+ * profiles and the performance queue all carry them. */
+export interface VerifyValidation {
+ total: number;
+ tests: string[];
+ reasons?: Record<string, string> | null | undefined;
+ commands: string[];
+}
+
+function codeList(subjects: string[]): string {
+ return subjects.map((s) => `\`${s}\``).join(", ");
+}
+
+/** The tests to run after the change, most direct first, each with why it is
+ * listed, then the command. With no guarding test, the instruction to add one. */
+export function verifyLines(validation: VerifyValidation, subjects: string[]): string[] {
+ if (validation.tests.length === 0) {
+ return validation.total > 0
+ ? [`Guarding tests: ${validation.total}, but none were included in this payload.`]
+ : [`No guarding tests found: add a test for ${codeList(subjects)} before changing it.`];
+ }
+ const rows = validation.tests.map((test) => {
+ const reason = validation.reasons?.[test];
+ return `- \`${test}\`${reason ? ` (${reason})` : ""}`;
+ });
+ const shown =
+ validation.total > validation.tests.length
+ ? [`${validation.tests.length} of ${validation.total} guarding tests shown.`]
+ : [];
+ const run = validation.commands.length
+ ? ["", "Run:", "", "```", ...validation.commands, "```"]
+ : [];
+ return [
+ "Run these after the change. The tests that exercise it most directly come first:",
+ "",
+ ...rows,
+ ...shown,
+ ...run,
+ ];
+}
+
+/** A `## Verify` section. Without test data it still says what to cover, so
+ * every prompt ends its change on a test run. */
+export function verifySection(
+ validation: VerifyValidation | null | undefined,
+ subjects: string[],
+): string {
+ const lines = validation
+ ? verifyLines(validation, subjects)
+ : [
+ `No test data came with this prompt. Find the tests that exercise ${subjects.length ? codeList(subjects) : "what you change"}, run them before and after the change, and add one that pins today's behaviour if none does.`,
+ ];
+ return ["## Verify", "", ...lines].join("\n");
+}
diff --git a/packages/ui/src/health/ai-prompts/work-queue-prompt.ts b/packages/ui/src/health/ai-prompts/work-queue-prompt.ts
index 626044c27..60d89bba8 100644
--- a/packages/ui/src/health/ai-prompts/work-queue-prompt.ts
+++ b/packages/ui/src/health/ai-prompts/work-queue-prompt.ts
@@ -3,7 +3,9 @@ import {
closingSections,
joinSections,
pluralS,
+ preamble,
repoSuffix,
+ verifySection,
type AiPromptFlavor,
} from "./shared";
@@ -11,15 +13,12 @@ import {
// Work-queue prompt (repo-level: the Attention Needed backlog)
// ─────────────────────────────────────────────────────────────────────
-const WORK_QUEUE_PREAMBLE: Record<AiPromptFlavor, string> = {
- generic:
- "You are a senior engineer triaging a backlog of issues repowise flagged across this repository. Work through them in priority order, one focused change at a time. Each item is a lead from static + git analysis — verify it against the real code before acting, and skip anything that turns out to be a false positive (say why).",
- "claude-code":
- "You are Claude Code clearing a backlog of issues repowise flagged across this repository. Use TodoWrite to track the queue, and Read / Grep / Glob to investigate each item before editing. Work in priority order, one focused, independently-revertible change at a time. Verify each item against the real code; flag false positives instead of forcing a change.",
- "claude-code-mcp":
- "You are Claude Code clearing a backlog of issues repowise flagged across this repository, which is indexed by repowise and exposes its MCP tools. Use TodoWrite to track the queue. For each item, pull the context repowise already computed — `get_context([target])` for the skeleton, `get_risk([target])` before editing, `get_why(...)` for decision items, `get_health([target])` for code-health items — instead of re-exploring by hand. Work in priority order, one focused, independently-revertible change at a time. Verify each item; flag false positives.",
- cursor:
- "You are clearing a backlog of issues repowise flagged across this repository. Work through them in priority order, one focused change at a time. Use @file and @codebase to investigate each item before editing. Verify each against the real code and skip false positives, saying why.",
+const WORK_QUEUE_PARTS = {
+ source:
+ "Repowise flagged the backlog below from static and git analysis. Work through it in priority order, one focused, independently-revertible change at a time.",
+ open: "the target each item names",
+ mcpTail:
+ "For each item, pull the context repowise already computed instead of re-exploring by hand: `get_context([target])` for the skeleton, `get_risk([target])` before editing, `get_why(...)` for decision items, `get_health([target])` for code-health items.",
};
const WORK_QUEUE_GUIDANCE: Record<string, string> = {
@@ -91,7 +90,7 @@ export function buildWorkQueueAiPrompt({
const hidden = ranked.length - shown.length;
return joinSections([
- WORK_QUEUE_PREAMBLE[flavor],
+ preamble(flavor, WORK_QUEUE_PARTS),
"",
`## Repository backlog${repoSuffix(repoName)}`,
"",
@@ -107,6 +106,8 @@ export function buildWorkQueueAiPrompt({
? `\n…and ${hidden} more lower-priority item${pluralS(hidden)} in the panel — handle these after the above.`
: "",
"",
+ verifySection(null, []),
+ "",
...closingSections(CONSTRAINTS, EXPECTED),
flavor === "claude-code-mcp"
? "Start by calling `get_overview()` to orient, then take the queue top-down — `get_context` / `get_risk` / `get_why` per item before you touch anything. repowise already did the exploration; lean on it."
diff --git a/packages/ui/src/health/coverage-view.tsx b/packages/ui/src/health/coverage-view.tsx
index 9a9fcde67..e72ac0a71 100644
--- a/packages/ui/src/health/coverage-view.tsx
+++ b/packages/ui/src/health/coverage-view.tsx
@@ -36,7 +36,7 @@ import { ResponsiveTable, type ResponsiveColumn } from "../shared/responsive-tab
import { ResultsFooter } from "../shared/results-footer";
import { OverviewSection } from "../overview/section";
-import { AiPromptModal } from "./ai-prompt-modal";
+import { AiPromptModal, fileChatContext } from "./ai-prompt-modal";
import { CoverageLede } from "./coverage-lede";
import { CoverageBar } from "./coverage-bar";
import { ModuleCoverageList } from "./module-coverage-list";
@@ -119,6 +119,7 @@ export function CoverageView({ adapter }: { adapter: CodeHealthAdapter }) {
if (!open) setPromptRow(null);
}}
filePath={promptRow?.file_path ?? null}
+ chatContext={fileChatContext(promptRow?.file_path)}
title="AI test prompt"
description="A ready-to-paste prompt that asks your AI coding agent to add tests for this file's uncovered lines and branches."
getPrompt={
diff --git a/packages/ui/src/health/findings-view.tsx b/packages/ui/src/health/findings-view.tsx
index 0d9c0145b..51af2717d 100644
--- a/packages/ui/src/health/findings-view.tsx
+++ b/packages/ui/src/health/findings-view.tsx
@@ -27,7 +27,7 @@ import { Skeleton } from "../ui/skeleton";
import { Button } from "../ui/button";
import { EmptyState } from "../shared/empty-state";
-import { AiPromptModal } from "./ai-prompt-modal";
+import { AiPromptModal, fileChatContext } from "./ai-prompt-modal";
import { HotFunctionsPanel } from "./hot-functions-panel";
import { HiddenCouplingList } from "./hidden-coupling-list";
import {
@@ -734,6 +734,7 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {
if (!open) setPromptTarget(null);
}}
filePath={promptTarget?.file_path ?? null}
+ chatContext={fileChatContext(promptTarget?.file_path)}
title="AI fix prompt"
description="A ready-to-paste prompt that gives your AI coding agent every marker, line range, score deduction, and constraint needed to refactor this file in one focused pass."
getPrompt={
diff --git a/packages/ui/src/health/fix-first/fix-first-list.tsx b/packages/ui/src/health/fix-first/fix-first-list.tsx
index e07b1cef1..8de3a9d51 100644
--- a/packages/ui/src/health/fix-first/fix-first-list.tsx
+++ b/packages/ui/src/health/fix-first/fix-first-list.tsx
@@ -14,7 +14,7 @@ import { Skeleton, SkeletonRegion } from "../../ui/skeleton";
import { ApiError } from "../../shared/api-error";
import { toFriendlyMessage } from "../../lib/errors";
import { OverviewSection } from "../../overview/section";
-import { AiPromptModal } from "../ai-prompt-modal";
+import { AiPromptModal, fileChatContext } from "../ai-prompt-modal";
import { buildFixItemPrompt } from "../ai-prompts/fix-first-prompt";
import { FixFirstItem, type FixTriageStatus } from "./fix-first-item";
import { fixFirstScopeSentence, fixLocation } from "./scope";
@@ -135,6 +135,7 @@ export function FixFirstList({
: null
}
filePath={promptFor ? fixLocation(promptFor) : null}
+ chatContext={fileChatContext(promptFor?.target.file_path)}
title="Prompt for an agent"
description="The change, why it ranks first, the steps in order, and how to verify it."
/>
diff --git a/packages/ui/src/health/health-file-drawer.tsx b/packages/ui/src/health/health-file-drawer.tsx
index d1f95cd0b..fc0b38f3f 100644
--- a/packages/ui/src/health/health-file-drawer.tsx
+++ b/packages/ui/src/health/health-file-drawer.tsx
@@ -21,7 +21,7 @@ import {
import { BiomarkerDetails, type BiomarkerDetailsRecord } from "./biomarker-details";
import { ScoreBreakdown, type ScoreBreakdownCategory } from "./score-breakdown";
import { AiPromptButton } from "./ai-prompt-button";
-import { AiPromptModal } from "./ai-prompt-modal";
+import { AiPromptModal, fileChatContext } from "./ai-prompt-modal";
import { buildFileHealthAiPrompt } from "./ai-prompt-builder";
import { FileSignalsPanel } from "./file-signals-panel";
import { FindingOpportunityLink } from "./file-opportunity";
@@ -637,6 +637,7 @@ export function HealthFileDrawer({
open={promptOpen}
onOpenChange={setPromptOpen}
filePath={metric?.file_path ?? null}
+ chatContext={fileChatContext(metric?.file_path)}
title="AI prompt for this file"
description="Every scored finding, category ceiling, open performance cause and change signal this drawer holds, written up so an agent can triage the file before it edits anything."
getPrompt={
diff --git a/packages/ui/src/workspace/co-change-ai-prompt.ts b/packages/ui/src/workspace/co-change-ai-prompt.ts
index df2ae1fe4..f045fe9ed 100644
--- a/packages/ui/src/workspace/co-change-ai-prompt.ts
+++ b/packages/ui/src/workspace/co-change-ai-prompt.ts
@@ -9,7 +9,16 @@
* type or a generated client should replace the manual lockstep.
*/
-import type { AiPromptFlavor } from "../health/ai-prompt-builder";
+import {
+ bulletList,
+ closingSections,
+ joinSections,
+ preamble,
+ verifySection,
+ WORKSPACE_ROLE,
+ type AiPromptFlavor,
+ type PreambleParts,
+} from "../health/ai-prompts/shared";
import type { WorkspaceCoChangeEntry } from "@repowise-dev/types/workspace";
import {
gapPhrase,
@@ -25,26 +34,27 @@ import {
/** File pairs listed in a repository-pair prompt before the rest become a count. */
export const MAX_PROMPT_PAIRS = 15;
-const PREAMBLE: Record<AiPromptFlavor, string> = {
- generic:
- "You are a senior engineer working across the repositories of one workspace. The evidence below is a work pattern repowise mined from git history: files in different repositories that the same author changed in the same work sessions. It is a lead, not a verified dependency. Open the files it names and read the commits before you conclude anything.",
- "claude-code":
- "You are Claude Code working across the repositories of one workspace. The evidence below is a work pattern repowise mined from git history: files in different repositories that the same author changed in the same work sessions. Treat it as a lead, not a verified dependency. Use Read, Grep and Glob on the files it names, and `git log` in each repository, before planning edits. Use TodoWrite for non-trivial steps.",
- "claude-code-mcp":
- "You are Claude Code working across the repositories of one workspace indexed by repowise, with its MCP tools available. The evidence below is a work pattern repowise mined from git history: files in different repositories that the same author changed in the same work sessions. Treat it as a lead, not a verified dependency. Pull what repowise already computed before re-reading by hand: `get_context([...])` for a file's skeleton, `get_risk([...])` for its co-change partners and test gaps, `get_why(...)` for the decision behind its shape, `search_codebase` to find a type or route by name, and `get_blast_radius` for which services a change reaches. Fall back to Read / Grep only for what the index cannot serve.",
- cursor:
- "Work across the repositories referenced below. The evidence is a work pattern repowise mined from git history: files in different repositories that the same author changed in the same work sessions. Treat it as a lead, not a verified dependency. Use @file and @codebase to read every file it names before editing.",
+const PREAMBLE_PARTS: PreambleParts = {
+ role: WORKSPACE_ROLE,
+ source:
+ "The evidence below is a work pattern repowise mined from git history: files in different repositories that the same author changed in the same work sessions. It is not a verified dependency.",
+ open: "the files it names",
+ mcpTail:
+ "Pull what repowise already computed before re-reading by hand: `get_context([...])` for a file's skeleton, `get_risk([...])` for its co-change partners and test gaps, `get_why(...)` for the decision behind its shape, `search_codebase` to find a type or route by name, and `get_blast_radius` for which services a change reaches.",
};
-function bullets(items: (string | null | undefined | false)[]): string {
- return items
- .filter(Boolean)
- .map((s) => `- ${s}`)
- .join("\n");
-}
+/** Co-change evidence lives in history, so the read-first flavors also read
+ * the commits; the MCP flavor gets them from `get_risk`. */
+const GIT_LOG: Record<AiPromptFlavor, string> = {
+ generic: "Run `git log` on each file in its own repository and read the commits that touched it before you conclude anything.",
+ "claude-code": "Run `git log` on each file in its own repository to read the commits that touched it.",
+ "claude-code-mcp": "",
+ cursor: "Run `git log` on each file in its own repository to read the commits that touched it.",
+};
-function join(sections: (string | null | undefined | false)[]): string {
- return sections.filter((s) => s !== null && s !== undefined && s !== false && s !== "").join("\n");
+function coChangePreamble(flavor: AiPromptFlavor): string {
+ const lead = preamble(flavor, PREAMBLE_PARTS);
+ return GIT_LOG[flavor] ? `${lead} ${GIT_LOG[flavor]}` : lead;
}
function where(repo: string, file: string): string {
@@ -126,12 +136,12 @@ export function buildCoChangePairAiPrompt({
? `Call \`get_context(['${pair.source_file}'])\` in \`${pair.source_repo}\` and \`get_context(['${pair.target_file}'])\` in \`${pair.target_repo}\`, \`get_risk([...])\` on each for its other co-change partners and test gaps, \`get_why(...)\` for any decision that governs either file, and \`get_blast_radius\` for what else in the workspace a change to either reaches. Don't restructure until you can name why they move together.`
: `Read both files, then run \`git log\` for each in its own repository around the shared dates. The session count is a symptom; find the shared concept driving it before you change anything.`;
- return join([
- PREAMBLE[flavor],
+ return joinSections([
+ coChangePreamble(flavor),
"",
"## Two files that change together across repositories",
"",
- bullets([
+ bulletList([
`File A: ${a}${factsTail(sourceFacts)}`,
`File B: ${b}${factsTail(targetFacts)}`,
`Shared work sessions: **${pair.frequency}** (the same author changed both, with commits in the two repositories no more than ${SESSION_WINDOW_HOURS} hours apart)`,
@@ -142,10 +152,10 @@ export function buildCoChangePairAiPrompt({
]),
"",
shownCommits.length > 0
- ? join([
+ ? joinSections([
"## Commits close together",
"",
- bullets(shownCommits.map((c) => commitLine(c, pair))),
+ bulletList(shownCommits.map((c) => commitLine(c, pair))),
"",
"Reconstructed from each file's recent significant commits: the miner does not record which sessions it counted, so some may be missing.",
"",
@@ -157,23 +167,23 @@ export function buildCoChangePairAiPrompt({
"2. Is the lockstep manual? If one file restates what the other defines (a schema retyped by hand, a route described in prose, a client written against a server), decide whether a declared contract, a shared type package, or a generated client or document should own it so the second edit disappears.",
"3. If the coupling is legitimate and cheap to keep (documentation that must track code), say so and propose the lightest guard: a test, a CI check, or a note in each file naming its partner.",
"",
- "## Hard constraints",
- "",
- bullets([
- "**Diagnose before changing.** Name the shared concept and cite the lines on both sides before proposing anything.",
- "**When you edit either file, check the other in the same change.** Until the coupling is removed, a change to one is half a change.",
- "Keep the contract between the repositories stable. Do not move code across a repository boundary without saying why the boundary is wrong.",
- "Preserve behavior. Add or update a test or check that fails when the two drift apart.",
- "If the evidence turns out to be coincidence (unrelated work in one sitting), say so and stop.",
- ]),
- "",
- "## What I expect back",
- "",
- "1. A verdict: the shared concept, and whether the coupling is accidental, legitimate but manual, or legitimate and fine.",
- "2. If manual: what should own the shared concept (contract, shared type, generated client or doc), where it would live, and the smallest safe first step.",
- "3. The first change, scoped, with the test or check that guards it.",
- "4. If the coupling stays: the one-line note to add to each file naming its partner.",
+ verifySection(null, [pair.source_file, pair.target_file]),
"",
+ ...closingSections(
+ [
+ "**Diagnose before changing.** Name the shared concept and cite the lines on both sides before proposing anything.",
+ "**When you edit either file, check the other in the same change.** Until the coupling is removed, a change to one is half a change.",
+ "Keep the contract between the repositories stable. Do not move code across a repository boundary without saying why the boundary is wrong.",
+ "Preserve behavior. Add or update a test or check that fails when the two drift apart.",
+ "If the evidence turns out to be coincidence (unrelated work in one sitting), say so and stop.",
+ ],
+ [
+ "1. A verdict: the shared concept, and whether the coupling is accidental, legitimate but manual, or legitimate and fine.",
+ "2. If manual: what should own the shared concept (contract, shared type, generated client or doc), where it would live, and the smallest safe first step.",
+ "3. The first change, scoped, with the test or check that guards it.",
+ "4. If the coupling stays: the one-line note to add to each file naming its partner.",
+ ],
+ ),
closer,
]);
}
@@ -235,12 +245,12 @@ export function buildCoChangeRepoPairAiPrompt({
? `Start with \`get_blast_radius\` on \`${repo1}\` and \`${repo2}\` to see what already connects them, then \`get_context\` and \`get_risk\` on the recurring files above. \`search_codebase\` for the type or route names you find on both sides. repowise already mapped the contracts and history; use it before grepping.`
: "Start with the recurring files: they are usually where the shared concept lives. Read them in both repositories and the commits that changed them together before proposing anything.";
- return join([
- PREAMBLE[flavor],
+ return joinSections([
+ coChangePreamble(flavor),
"",
"## Two repositories that change together",
"",
- bullets([
+ bulletList([
`Repositories: \`${repo1}\` and \`${repo2}\``,
`File pairs: **${ranked.length}**${capped ? ` (${rule}, so there are likely more)` : ""}`,
ranked[0] ? `Strongest pair: ${pct(ranked[0].strength)}` : null,
@@ -259,10 +269,10 @@ export function buildCoChangeRepoPairAiPrompt({
hidden > 0 ? `...and ${hidden} more file pairs not listed.` : "",
"",
hubs.length > 0
- ? join([
+ ? joinSections([
"## Files that recur across pairs",
"",
- bullets(hubs.map((h) => `${where(h.repo, h.file)} appears in ${h.n} pairs`)),
+ bulletList(hubs.map((h) => `${where(h.repo, h.file)} appears in ${h.n} pairs`)),
"",
])
: "",
@@ -272,21 +282,21 @@ export function buildCoChangeRepoPairAiPrompt({
"2. For each group, check whether a declared contract, shared package or generated client already covers it. If not, say whether one should, and what it would replace.",
"3. Rank the groups by payoff: how often they force a second edit, and how bad a missed edit would be.",
"",
- "## Hard constraints",
- "",
- bullets([
- "**Diagnose before changing.** Cite the lines on both sides for every group you name.",
- "Keep the contract between the repositories stable, and do not move code across the boundary without saying why the boundary is wrong.",
- "One group per change, each independently revertible, each with a test or check that fails when the two sides drift.",
- "Some groups will be coincidence or legitimate documentation upkeep. Say so and leave them.",
- ]),
- "",
- "## What I expect back",
- "",
- "1. The groups, each with its shared concept and the pairs that belong to it.",
- "2. For each: accidental, legitimate but manual, or legitimate and fine, with the reason.",
- "3. A ranked plan for the manual ones: what should own the concept, where, and the first step.",
+ verifySection(null, hubs.map((h) => h.file)),
"",
+ ...closingSections(
+ [
+ "**Diagnose before changing.** Cite the lines on both sides for every group you name.",
+ "Keep the contract between the repositories stable, and do not move code across the boundary without saying why the boundary is wrong.",
+ "One group per change, each independently revertible, each with a test or check that fails when the two sides drift.",
+ "Some groups will be coincidence or legitimate documentation upkeep. Say so and leave them.",
+ ],
+ [
+ "1. The groups, each with its shared concept and the pairs that belong to it.",
+ "2. For each: accidental, legitimate but manual, or legitimate and fine, with the reason.",
+ "3. A ranked plan for the manual ones: what should own the concept, where, and the first step.",
+ ],
+ ),
closer,
]);
}
diff --git a/packages/ui/src/workspace/contract-ai-prompt.ts b/packages/ui/src/workspace/contract-ai-prompt.ts
index e76ce294f..b7f64d80b 100644
--- a/packages/ui/src/workspace/contract-ai-prompt.ts
+++ b/packages/ui/src/workspace/contract-ai-prompt.ts
@@ -9,7 +9,17 @@
* "no caller here" is not "dead".
*/
-import type { AiPromptFlavor } from "../health/ai-prompt-builder";
+import {
+ bulletList,
+ closingSections,
+ joinSections,
+ numbered,
+ preamble,
+ verifySection,
+ WORKSPACE_ROLE,
+ type AiPromptFlavor,
+ type PreambleParts,
+} from "../health/ai-prompts/shared";
import {
contractHeading,
contractMetaEntries,
@@ -22,34 +32,20 @@ import { contractTypeLabel } from "./contract-type-label";
/** Rows listed in a group prompt before the rest are summarised as a count. */
export const MAX_PROMPT_ROWS = 40;
-const PREAMBLE: Record<AiPromptFlavor, string> = {
- generic:
- "You are a senior engineer working across the repositories of one workspace. The contract evidence below was extracted statically by repowise: treat it as leads, not ground truth. Open the files it names and verify each item against the real code before you act. If an item is a false positive, say so and skip it.",
- "claude-code":
- "You are Claude Code working across the repositories of one workspace. The contract evidence below was extracted statically by repowise: treat it as leads to investigate, not commands. Use Read, Grep and Glob on the files it names, in every repository involved, before planning edits. Flag anything that turns out to be a false positive. Use TodoWrite for non-trivial steps.",
- "claude-code-mcp":
- "You are Claude Code working across the repositories of one workspace indexed by repowise, with its MCP tools available. The contract evidence below was extracted statically: treat it as leads, not commands. Pull what repowise already computed before re-reading by hand: `search_codebase` to find a route, table or symbol by name, `get_context([...])` for a file's skeleton, `get_symbol` for one body, `get_risk([...])` before editing, `get_why(...)` for the decision behind the current shape, and `get_blast_radius` for which services a change reaches. Fall back to Read / Grep only for what the index cannot serve. Flag false positives.",
- cursor:
- "Work across the repositories referenced below. The contract evidence was extracted statically by repowise: treat it as leads, not ground truth. Use @file and @codebase to read every file it names before editing, and skip and call out any false positives.",
+const PREAMBLE_PARTS: PreambleParts = {
+ role: WORKSPACE_ROLE,
+ source: "The contract evidence below was extracted statically by repowise.",
+ open: "the files it names in every repository involved",
+ mcpTail:
+ "Pull what repowise already computed before re-reading by hand: `search_codebase` to find a route, table or symbol by name, `get_context([...])` for a file's skeleton, `get_symbol` for one body, `get_risk([...])` before editing, `get_why(...)` for the decision behind the current shape, and `get_blast_radius` for which services a change reaches.",
};
-function bullets(items: (string | null | undefined | false)[]): string {
- return items
- .filter(Boolean)
- .map((s) => `- ${s}`)
- .join("\n");
-}
-
-function join(sections: (string | null | undefined | false)[]): string {
- return sections.filter((s) => s !== null && s !== undefined && s !== false && s !== "").join("\n");
-}
-
function where(repo: string, file: string, line?: number | null): string {
return `\`${repo}\` \`${file}${line != null ? `:${line}` : ""}\``;
}
-function more(hidden: number, noun: string): string | null {
- return hidden > 0 ? `...and ${hidden} more ${noun} not listed. Handle these after the above.` : null;
+function more(hidden: number, noun: string): string {
+ return hidden > 0 ? `...and ${hidden} more ${noun} not listed. Handle these after the above.` : "";
}
// ---------------------------------------------------------------------------
@@ -78,120 +74,156 @@ export interface BuildContractPromptOptions {
flavor?: AiPromptFlavor;
}
-export function buildContractAiPrompt({
- contract,
- links,
- unmatchedReason = null,
- breakingChanges = [],
- flavor = "generic",
-}: BuildContractPromptOptions): string {
- const isProvider = contract.role === "provider";
- const heading = contractHeading(contract);
+function contractIdentity(contract: ContractEntry): string {
const found = contractMetaEntries(contract.meta).map(
([k, v]) => `${contractMetaLabel(k)}: \`${v}\``,
);
-
- const identity = bullets([
- `Contract: \`${contract.contract_id}\` (${contractTypeLabel(contract.contract_type)}, ${isProvider ? "provider" : "consumer"})`,
+ return bulletList([
+ `Contract: \`${contract.contract_id}\` (${contractTypeLabel(contract.contract_type)}, ${contract.role === "provider" ? "provider" : "consumer"})`,
`Where: ${where(contract.repo, contract.file_path, contract.line)}${contract.service ? `, service \`${contract.service}\`` : ""}`,
contract.symbol_name ? `Symbol: \`${contract.symbol_name}\`` : null,
`Extraction confidence: ${Math.round(contract.confidence * 100)}%`,
found.length > 0 ? `How it was found: ${found.join(", ")}` : null,
]);
+}
- const counterparts = links.map((l) =>
+/** The other side of each link: the callers of a provider, the providers of a call. */
+function counterpartLines(links: ContractPromptLink[], isProvider: boolean): string[] {
+ return links.map((l) =>
isProvider
? `${where(l.consumer_repo, l.consumer_file)} \`${l.consumer_symbol}\` (${l.match_type} match, ${Math.round(l.confidence * 100)}%)`
: `${where(l.provider_repo, l.provider_file)} \`${l.provider_symbol}\` (${l.match_type} match, ${Math.round(l.confidence * 100)}%)`,
);
+}
- let state: string;
- let tasks: string[];
- if (links.length > 0) {
- state = isProvider
- ? `${links.length} call ${links.length === 1 ? "site resolves" : "sites resolve"} to this contract:`
- : `This call resolves to ${links.length === 1 ? "this provider" : `these ${links.length} providers`}:`;
- tasks = isProvider
- ? [
- "Confirm each caller above really calls this contract (method, path or name, and payload).",
- "Before changing the contract's shape or behaviour, list what each caller sends and expects back, and say which change would break which caller.",
- "Name the tests in the calling repositories that exercise these calls, or say that none do.",
- ]
- : [
- "Confirm the provider above is the endpoint this call is meant to reach.",
- "Compare what the call sends and expects with what the provider accepts and returns; report any mismatch in fields, types, status codes or auth.",
- ];
- } else if (isProvider) {
- state =
- "Nothing in this workspace resolves to this contract. That is not proof it is unused: it may be called from outside the workspace, from the same service (excluded from matching), or by code written in a form extraction cannot follow (a dynamic URL, a generated client, reflection).";
- tasks = [
- "Search every repository for callers, including dynamic ones: string-built URLs, generated clients, config-driven routes, other packages importing it.",
- "Check whether it is public API or consumed by something outside this workspace (a mobile app, a partner, a scheduled job).",
- "Only if no caller exists and it is not public: propose deprecating or removing it, with the evidence. Do not delete anything in this pass.",
+interface ContractState {
+ state: string;
+ tasks: string[];
+}
+
+function linkedState(n: number, isProvider: boolean): ContractState {
+ if (isProvider) {
+ return {
+ state: `${n} call ${n === 1 ? "site resolves" : "sites resolve"} to this contract:`,
+ tasks: [
+ "Confirm each caller above really calls this contract (method, path or name, and payload).",
+ "Before changing the contract's shape or behaviour, list what each caller sends and expects back, and say which change would break which caller.",
+ "Name the tests in the calling repositories that exercise these calls, or say that none do.",
+ ],
+ };
+ }
+ return {
+ state: `This call resolves to ${n === 1 ? "this provider" : `these ${n} providers`}:`,
+ tasks: [
+ "Confirm the provider above is the endpoint this call is meant to reach.",
+ "Compare what the call sends and expects with what the provider accepts and returns; report any mismatch in fields, types, status codes or auth.",
+ ],
+ };
+}
+
+const UNCALLED_PROVIDER: ContractState = {
+ state:
+ "Nothing in this workspace resolves to this contract. That is not proof it is unused: it may be called from outside the workspace, from the same service (excluded from matching), or by code written in a form extraction cannot follow (a dynamic URL, a generated client, reflection).",
+ tasks: [
+ "Search every repository for callers, including dynamic ones: string-built URLs, generated clients, config-driven routes, other packages importing it.",
+ "Check whether it is public API or consumed by something outside this workspace (a mobile app, a partner, a scheduled job).",
+ "Only if no caller exists and it is not public: propose deprecating or removing it, with the evidence. Do not delete anything in this pass.",
+ ],
+};
+
+/** What to do about a call that matched no provider, by the matcher's reason. */
+function unmatchedTasks(reason: string | null, host: string | null): string[] {
+ if (reason === "external_host") {
+ return [
+ `Confirm ${host ? `\`${host}\`` : "the host"} is a third party and not one of this workspace's own services behind a literal URL.`,
+ "If it is your own service, say which repository serves it so it can be added to the workspace; otherwise there is nothing to fix.",
+ ];
+ }
+ if (reason === "internal_only") {
+ return [
+ "Confirm the call is served from the same service that makes it. If so there is nothing to fix; say so and stop.",
];
- } else {
- const copy = unmatchedReasonCopy(unmatchedReason);
- const host = typeof contract.meta?.host === "string" ? contract.meta.host : null;
- state = `This call matched no provider. Recorded reason: \`${unmatchedReason ?? "none"}\` (${copy.title}). ${copy.meaning}${host ? ` Host: \`${host}\`.` : ""}`;
- tasks =
- unmatchedReason === "external_host"
- ? [
- `Confirm ${host ? `\`${host}\`` : "the host"} is a third party and not one of this workspace's own services behind a literal URL.`,
- "If it is your own service, say which repository serves it so it can be added to the workspace; otherwise there is nothing to fix.",
- ]
- : unmatchedReason === "internal_only"
- ? [
- "Confirm the call is served from the same service that makes it. If so there is nothing to fix; say so and stop.",
- ]
- : [
- "Find the endpoint this call intends. Search the providers for the same path with a different prefix, version, method or spelling.",
- "If it was renamed, fix the call. If it was removed, say whether the call is dead and can go. If a service outside the workspace serves it, name it.",
- "If a provider exists but is declared in a form extraction did not read (an unusual framework, a mounted router, a generated route), name the file and the pattern.",
- ];
}
+ return [
+ "Find the endpoint this call intends. Search the providers for the same path with a different prefix, version, method or spelling.",
+ "If it was renamed, fix the call. If it was removed, say whether the call is dead and can go. If a service outside the workspace serves it, name it.",
+ "If a provider exists but is declared in a form extraction did not read (an unusual framework, a mounted router, a generated route), name the file and the pattern.",
+ ];
+}
+
+function unmatchedState(contract: ContractEntry, reason: string | null): ContractState {
+ const copy = unmatchedReasonCopy(reason);
+ const host = typeof contract.meta?.host === "string" ? contract.meta.host : null;
+ return {
+ state: `This call matched no provider. Recorded reason: \`${reason ?? "none"}\` (${copy.title}). ${copy.meaning}${host ? ` Host: \`${host}\`.` : ""}`,
+ tasks: unmatchedTasks(reason, host),
+ };
+}
+
+function contractState(
+ contract: ContractEntry,
+ links: ContractPromptLink[],
+ reason: string | null,
+): ContractState {
+ const isProvider = contract.role === "provider";
+ if (links.length > 0) return linkedState(links.length, isProvider);
+ return isProvider ? UNCALLED_PROVIDER : unmatchedState(contract, reason);
+}
- const breaking =
- breakingChanges.length > 0
- ? join([
- "",
- "## Breaking changes in the latest update",
- "",
- bullets(
- breakingChanges.map(
- (b) => `${b.severity}: \`${b.kind}\`${b.detail ? `: ${b.detail}` : ""}`,
- ),
- ),
- ])
- : null;
+function breakingSection(changes: { severity: string; kind: string; detail: string }[]): string {
+ if (changes.length === 0) return "";
+ return joinSections([
+ "## Breaking changes in the latest update",
+ "",
+ bulletList(changes.map((b) => `${b.severity}: \`${b.kind}\`${b.detail ? `: ${b.detail}` : ""}`)),
+ ]);
+}
+
+export function buildContractAiPrompt({
+ contract,
+ links,
+ unmatchedReason = null,
+ breakingChanges = [],
+ flavor = "generic",
+}: BuildContractPromptOptions): string {
+ const isProvider = contract.role === "provider";
+ const { state, tasks } = contractState(contract, links, unmatchedReason);
+ const counterpartFiles = links.map((l) => (isProvider ? l.consumer_file : l.provider_file));
- return join([
- PREAMBLE[flavor],
+ return joinSections([
+ preamble(flavor, PREAMBLE_PARTS),
"",
- `## Contract: ${heading}`,
+ `## Contract: ${contractHeading(contract)}`,
"",
- identity,
+ contractIdentity(contract),
"",
"## State",
"",
state,
- counterparts.length > 0 ? bullets(counterparts) : null,
- breaking,
+ bulletList(counterpartLines(links, isProvider)),
+ breakingSection(breakingChanges),
"",
"## What to do",
"",
- tasks.map((t, i) => `${i + 1}. ${t}`).join("\n"),
- "",
- "## Hard constraints",
- "",
- bullets([
- "Verify in the code before acting. The evidence above is static extraction and can be wrong.",
- "Keep the public contract stable unless the task explicitly calls for changing it.",
- "Do not delete code on the strength of a missing caller alone.",
- ]),
+ numbered(tasks),
"",
- "## What I expect back",
+ verifySection(null, [...new Set([contract.file_path, ...counterpartFiles])]),
"",
- "1. What you verified, with file and line for each claim.\n2. The change you made or propose, or why none is needed.\n3. Anything the extraction got wrong.",
+ ...closingSections(
+ [
+ "Verify in the code before acting. The evidence above is static extraction and can be wrong.",
+ "Keep the public contract stable unless the task explicitly calls for changing it.",
+ "Do not delete code on the strength of a missing caller alone.",
+ ],
+ [
+ "1. What you verified, with file and line for each claim.",
+ "2. The change you made or propose, or why none is needed.",
+ "3. Anything the extraction got wrong.",
+ ],
+ ),
+ flavor === "claude-code-mcp"
+ ? `Start with \`search_codebase\` for \`${contract.contract_id}\` to find every side of it, then \`get_context(['${contract.file_path}'])\` in \`${contract.repo}\` and \`get_risk\` before you edit. \`get_blast_radius\` shows which services a change reaches.`
+ : "",
]);
}
@@ -238,12 +270,12 @@ export function buildUnmatchedConsumersAiPrompt({
"Group calls that share a cause; one mount prefix or base URL often explains many.",
];
- return join([
- PREAMBLE[flavor],
+ return joinSections([
+ preamble(flavor, PREAMBLE_PARTS),
"",
`## ${calls} that ${n === 1 ? "resolves" : "resolve"} to no provider: ${copy.title.toLowerCase()}`,
"",
- bullets([
+ bulletList([
`Reason recorded by the matcher: \`${reason}\`. ${copy.meaning}`,
"Source: repowise workspace contract extraction and matching.",
]),
@@ -260,21 +292,22 @@ export function buildUnmatchedConsumersAiPrompt({
"",
"## What to do",
"",
- tasks.map((t, i) => `${i + 1}. ${t}`).join("\n"),
+ numbered(tasks),
"",
- "## Hard constraints",
- "",
- bullets([
- "Verify each call in the code before acting. A path built from variables may not be what extraction recorded.",
- "Do not delete a call unless you have confirmed the endpoint it targets no longer exists anywhere.",
- ]),
+ verifySection(null, []),
"",
- "## What I expect back",
- "",
- "A table with one row per call: the contract id, the verdict (renamed, removed, external, undetected provider, false positive), the evidence (file and line), and the fix you made or propose.",
+ ...closingSections(
+ [
+ "Verify each call in the code before acting. A path built from variables may not be what extraction recorded.",
+ "Do not delete a call unless you have confirmed the endpoint it targets no longer exists anywhere.",
+ ],
+ [
+ "A table with one row per call: the contract id, the verdict (renamed, removed, external, undetected provider, false positive), the evidence (file and line), and the fix you made or propose.",
+ ],
+ ),
flavor === "claude-code-mcp"
? "Use `search_codebase` with the path's distinctive segments to find near-miss providers before reading files by hand."
- : null,
+ : "",
]);
}
@@ -324,12 +357,12 @@ export function buildOrphanProvidersAiPrompt({
const n = Math.max(total ?? 0, rows.length);
const noun = providerNoun(contractType, n);
- return join([
- PREAMBLE[flavor],
+ return joinSections([
+ preamble(flavor, PREAMBLE_PARTS),
"",
`## ${n} ${noun} in \`${repo}\` with no caller in this workspace`,
"",
- bullets([
+ bulletList([
"No consumer in any repository of this workspace was resolved to these providers.",
"That is not proof they are unused. A caller may live outside the workspace, in the same service (excluded from matching), or in code extraction cannot follow: string-built URLs, generated clients, raw SQL assembled at runtime, dynamic imports.",
]),
@@ -343,25 +376,26 @@ export function buildOrphanProvidersAiPrompt({
"",
"## What to do",
"",
- [
- "1. For each provider, search every repository for callers, including the dynamic forms above.",
- "2. Mark each as used (name the caller and why extraction missed it), public or external (name the consumer), or unused (no caller anywhere).",
- "3. For the unused ones, propose deprecation or removal with the evidence. Do not delete anything in this pass.",
- "4. If many were missed for one reason (a client wrapper, a base URL, an ORM pattern), name the pattern so extraction can learn it.",
- ].join("\n"),
- "",
- "## Hard constraints",
- "",
- bullets([
- "Never remove a provider on the strength of this list alone.",
- "Treat anything public, versioned or documented as used until shown otherwise.",
+ numbered([
+ "For each provider, search every repository for callers, including the dynamic forms above.",
+ "Mark each as used (name the caller and why extraction missed it), public or external (name the consumer), or unused (no caller anywhere).",
+ "For the unused ones, propose deprecation or removal with the evidence. Do not delete anything in this pass.",
+ "If many were missed for one reason (a client wrapper, a base URL, an ORM pattern), name the pattern so extraction can learn it.",
]),
"",
- "## What I expect back",
+ verifySection(null, []),
"",
- "A table with one row per provider: the contract id, the verdict (used, external, unused), the evidence, and the proposed action.",
+ ...closingSections(
+ [
+ "Never remove a provider on the strength of this list alone.",
+ "Treat anything public, versioned or documented as used until shown otherwise.",
+ ],
+ [
+ "A table with one row per provider: the contract id, the verdict (used, external, unused), the evidence, and the proposed action.",
+ ],
+ ),
flavor === "claude-code-mcp"
? `Start with \`get_dead_code\` and \`get_context\` on \`${repo}\` to see what the index already knows about these files, and \`get_why\` before proposing to remove anything.`
- : null,
+ : "",
]);
}
diff --git a/packages/ui/src/workspace/system-map/system-map-ai-prompt.ts b/packages/ui/src/workspace/system-map/system-map-ai-prompt.ts
index e1ca2cd18..853bf7f61 100644
--- a/packages/ui/src/workspace/system-map/system-map-ai-prompt.ts
+++ b/packages/ui/src/workspace/system-map/system-map-ai-prompt.ts
@@ -8,30 +8,28 @@
* and tell the agent to confirm each relationship in code before acting on it.
*/
-import type { AiPromptFlavor } from "../../health/ai-prompt-builder";
+import {
+ bulletList,
+ joinSections,
+ numbered,
+ preamble,
+ verifySection,
+ WORKSPACE_ROLE,
+ type AiPromptFlavor,
+ type PreambleParts,
+} from "../../health/ai-prompts/shared";
/** Evidence rows listed in full before the prompt says how many it left out. */
export const SYSTEM_MAP_PROMPT_MAX_ROWS = 25;
-const PREAMBLE: Record<AiPromptFlavor, string> = {
- generic:
- "You are a senior engineer working across the repositories of one workspace. The facts below come from repowise's system graph, which is built from code and git history. Treat them as leads, not ground truth: open the files, confirm each relationship in code, and say plainly when one is wrong.",
- "claude-code":
- "You are Claude Code working across the repositories of one workspace. The facts below come from repowise's system graph, which is built from code and git history. Treat them as leads: use Read, Grep and Glob in each repository to confirm every relationship before you rely on it, and say plainly when one is wrong. Use TodoWrite for multi-step work.",
- "claude-code-mcp":
- "You are Claude Code working across the repositories of one workspace, indexed by repowise and exposed through its MCP tools. The facts below come from repowise's system graph. Pull what repowise already computed before reading files by hand: `get_blast_radius` for cross-repo impact, `search_codebase` to find a route, table or symbol by name, `get_context([...])` for a file's skeleton, `get_symbol(\"file::Name\")` for one body, `get_risk([...])` before editing, and `get_why(...)` for the decision behind the current shape. Confirm each relationship in code and say plainly when one is wrong.",
- cursor:
- "Work across the repositories of this workspace. The facts below come from repowise's system graph, which is built from code and git history. Treat them as leads: use @file and @codebase to confirm each relationship in code before acting on it, and say plainly when one is wrong.",
+const PREAMBLE_PARTS: PreambleParts = {
+ role: WORKSPACE_ROLE,
+ source: "The facts below come from repowise's system graph, which is built from code and git history.",
+ open: "the files behind each relationship in each repository",
+ mcpTail:
+ "Pull what repowise already computed before reading files by hand: `get_blast_radius` for cross-repo impact, `search_codebase` to find a route, table or symbol by name, `get_context([...])` for a file's skeleton, `get_symbol(\"file::Name\")` for one body, `get_risk([...])` before editing, and `get_why(...)` for the decision behind the current shape.",
};
-function bullets(items: (string | null | undefined | false)[]): string {
- return items.filter(Boolean).map((s) => `- ${s}`).join("\n");
-}
-
-function numbered(items: string[]): string {
- return items.map((s, i) => `${i + 1}. ${s}`).join("\n");
-}
-
function countsLine(counts: Record<string, number>): string {
const entries = Object.entries(counts).sort((a, b) => b[1] - a[1]);
return entries.length === 0 ? "none" : entries.map(([t, n]) => `${n} ${t}`).join(", ");
@@ -43,10 +41,6 @@ function capped<T>(rows: T[], render: (row: T) => string, noun: string): string
return hidden > 0 ? `${shown}\n- ...and ${hidden} more ${noun} not listed here.` : shown;
}
-function assemble(sections: (string | null | false)[]): string {
- return sections.filter((s): s is string => Boolean(s)).join("\n\n");
-}
-
// ---------------------------------------------------------------------------
// Service
// ---------------------------------------------------------------------------
@@ -116,10 +110,12 @@ export function buildServiceAiPrompt(o: BuildServicePromptOptions): string {
const reasons = o.unmatchedByReason ? countsLine(o.unmatchedByReason) : null;
- return assemble([
- PREAMBLE[flavor],
- `## Service: ${s.name} (\`${s.id}\`)`,
- bullets([
+ // These prompts keep a blank line between sections, so each section after
+ // the preamble carries its own leading newline.
+ return joinSections([
+ preamble(flavor, PREAMBLE_PARTS),
+ `\n## Service: ${s.name} (\`${s.id}\`)`,
+ `\n${bulletList([
`Location: \`${location}\``,
o.health ? `Repository health: ${o.health.value} out of 10 (${o.health.label})` : null,
o.role
@@ -133,23 +129,23 @@ export function buildServiceAiPrompt(o: BuildServicePromptOptions): string {
o.unusedProviders > 0
? `Providers no workspace consumer calls: ${o.unusedProviders}. They may still be called from outside the workspace.`
: null,
- ]),
+ ])}`,
o.cycles.length > 0
- ? `## Dependency cycles through this service\n\n${bullets(o.cycles.map((c) => `${c.join(" -> ")} -> ${c[0]}`))}`
- : null,
- `## Depends on\n\n${o.dependsOn.length ? bullets(o.dependsOn.map(neighbourLine)) : "Nothing in the workspace."}`,
- `## Depended on by\n\n${o.dependedOnBy.length ? bullets(o.dependedOnBy.map(neighbourLine)) : "Nothing in the workspace."}`,
- `## Contracts (most linked first)\n\n${contractsBlock}`,
- "## Task\n\nBefore anyone changes this service, map what it exposes and who would feel a change. Do not edit code.",
- `## What I expect back\n\n${numbered([
+ ? `\n## Dependency cycles through this service\n\n${bulletList(o.cycles.map((c) => `${c.join(" -> ")} -> ${c[0]}`))}`
+ : "",
+ `\n## Depends on\n\n${o.dependsOn.length ? bulletList(o.dependsOn.map(neighbourLine)) : "Nothing in the workspace."}`,
+ `\n## Depended on by\n\n${o.dependedOnBy.length ? bulletList(o.dependedOnBy.map(neighbourLine)) : "Nothing in the workspace."}`,
+ `\n## Contracts (most linked first)\n\n${contractsBlock}`,
+ "\n## Task\n\nBefore anyone changes this service, map what it exposes and who would feel a change. Do not edit code.",
+ `\n## What I expect back\n\n${numbered([
"The public surface: each provided contract that has consumers, with the consuming service and file.",
"Which dependents would break on a change (structural) and which only tend to change alongside it (co-change).",
"Any relationship above that the code does not support, with the file you checked.",
"The riskiest contract to change, and the tests in the consuming repositories that would catch a break.",
])}`,
flavor === "claude-code-mcp"
- ? `Start with \`get_blast_radius(target="${s.id}")\`, then \`get_context\` on the provider files listed above and \`get_risk\` on the ones with the most links.`
- : "Start from the provider files listed above, then search each dependent repository for the routes, symbols and tables they name.",
+ ? `\nStart with \`get_blast_radius(target="${s.id}")\`, then \`get_context\` on the provider files listed above and \`get_risk\` on the ones with the most links.`
+ : "\nStart from the provider files listed above, then search each dependent repository for the routes, symbols and tables they name.",
]);
}
@@ -214,23 +210,23 @@ export function buildEdgeAiPrompt(o: BuildEdgePromptOptions): string {
? `Verify this dependency exists in code and document it. For each piece of evidence, find the call, import or query in \`${o.source.name}\` and the declaration in \`${o.target.name}\` it resolves to. Flag any link that is a false match.`
: `Check whether this co-change hides a real dependency. Files that change together without a declared contract often share an undocumented format, a copied type or a coordinated release. Decide which it is for the pairs above.`;
- return assemble([
- PREAMBLE[flavor],
- `## Relationship: ${o.source.name} -> ${o.target.name} (\`${e.id}\`)`,
- bullets([
+ return joinSections([
+ preamble(flavor, PREAMBLE_PARTS),
+ `\n## Relationship: ${o.source.name} -> ${o.target.name} (\`${e.id}\`)`,
+ `\n${bulletList([
o.sentence,
`Kind: ${e.kind}. Match: ${e.match_type}. Confidence: ${Math.round(e.confidence * 100)}%.`,
`Weight: ${o.weightLabel}.`,
e.structural
? "Structural: built from a contract or import in code. Changing the provider side can break the consumer."
: "Behavioral: built from git history. It says the files change together, not that one calls the other.",
- ]),
+ ])}`,
o.cycles && o.cycles.length > 0
- ? `## This edge closes a dependency cycle\n\n${bullets(o.cycles.map((c) => `${c.join(" -> ")} -> ${c[0]}`))}`
- : null,
- `## Evidence\n\n${evidence}`,
- `## Task\n\n${task}`,
- `## What I expect back\n\n${numbered(
+ ? `\n## This edge closes a dependency cycle\n\n${bulletList(o.cycles.map((c) => `${c.join(" -> ")} -> ${c[0]}`))}`
+ : "",
+ `\n## Evidence\n\n${evidence}`,
+ `\n## Task\n\n${task}`,
+ `\n## What I expect back\n\n${numbered(
e.structural
? [
"Each confirmed link as consumer file and symbol, provider file and symbol.",
@@ -244,8 +240,8 @@ export function buildEdgeAiPrompt(o: BuildEdgePromptOptions): string {
],
)}`,
flavor === "claude-code-mcp"
- ? `Use \`search_codebase\` for each contract id in both repositories, \`get_context\` on the files above, and \`get_blast_radius(target="${o.target.id}")\` to see what else rides on the provider.`
- : "Open both sides of each piece of evidence before you write anything.",
+ ? `\nUse \`search_codebase\` for each contract id in both repositories, \`get_context\` on the files above, and \`get_blast_radius(target="${o.target.id}")\` to see what else rides on the provider.`
+ : "\nOpen both sides of each piece of evidence before you write anything.",
]);
}
@@ -282,29 +278,30 @@ export function buildCycleAiPrompt(o: BuildCyclePromptOptions): string {
})
.join("\n");
- return assemble([
- PREAMBLE[flavor],
- `## Dependency cycle: ${loop}`,
- bullets([
+ return joinSections([
+ preamble(flavor, PREAMBLE_PARTS),
+ `\n## Dependency cycle: ${loop}`,
+ `\n${bulletList([
`Services: ${o.ids.map((id) => `\`${id}\``).join(", ")}`,
"A cycle means none of these services can change its contract, build or deploy without the others. It counts against the workspace architecture score.",
- ]),
- `## Edges in the cycle\n\n${edges}`,
- "## Task\n\nPropose how to break this cycle. Usually one edge is the odd one out: a callback, a webhook, a shared type or a revalidation hook that points the wrong way. Find it, confirm it in code, and pick a fix: invert it (events or a callback interface), move the shared piece into a package both depend on, or route it through a service already downstream of both.",
- `## Hard constraints\n\n${bullets([
+ ])}`,
+ `\n## Edges in the cycle\n\n${edges}`,
+ "\n## Task\n\nPropose how to break this cycle. Usually one edge is the odd one out: a callback, a webhook, a shared type or a revalidation hook that points the wrong way. Find it, confirm it in code, and pick a fix: invert it (events or a callback interface), move the shared piece into a package both depend on, or route it through a service already downstream of both.",
+ `\n${verifySection(null, o.ids)}`,
+ `\n## Hard constraints\n\n${bulletList([
"Preserve behavior. Keep every public contract stable until its consumers have moved.",
"Change one edge at a time so each step is reviewable and revertible.",
"Do not break the cycle by deleting a feature.",
])}`,
- `## What I expect back\n\n${numbered([
+ `\n## What I expect back\n\n${numbered([
"The edge you would cut, with the exact files and symbols that create it.",
"The fix and why it beats the alternatives.",
"The change plan across repositories, in merge order.",
"Tests that would catch the cycle coming back.",
])}`,
flavor === "claude-code-mcp"
- ? `Run \`get_blast_radius\` on each of ${o.ids.map((id) => `\`${id}\``).join(", ")} and \`search_codebase\` for the contract ids above before choosing the edge to cut.`
- : "Locate the code behind each edge before choosing which one to cut.",
+ ? `\nRun \`get_blast_radius\` on each of ${o.ids.map((id) => `\`${id}\``).join(", ")} and \`search_codebase\` for the contract ids above before choosing the edge to cut.`
+ : "\nLocate the code behind each edge before choosing which one to cut.",
]);
}
@@ -336,26 +333,27 @@ export function buildBlastRadiusAiPrompt(o: BuildBlastRadiusPromptOptions): stri
const row = (n: PromptImpacted) =>
`- **${n.name}** (\`${n.id}\`, repo ${n.repo}): ${n.distance} ${n.distance === 1 ? "hop" : "hops"}, impact ${n.score.toFixed(2)}, via ${n.edge_kinds.join(", ")}`;
- return assemble([
- PREAMBLE[flavor],
- `## Blast radius of ${o.target.name} (\`${o.target.id}\`)`,
- bullets([
+ return joinSections([
+ preamble(flavor, PREAMBLE_PARTS),
+ `\n## Blast radius of ${o.target.name} (\`${o.target.id}\`)`,
+ `\n${bulletList([
`${o.impacted.length} downstream ${o.impacted.length === 1 ? "service is" : "services are"} reachable: ${structural.length} through structural dependencies, ${behavioral.length} only through co-change.`,
o.includeBehavioral
? "Co-change paths are included at half weight. They mean the files change together, not that one calls the other."
: "Co-change paths are excluded; every service below is reached through contracts or imports.",
"Impact is 0 to 1, with distance decay: nearer and structural ranks higher.",
- ]),
- structural.length ? `## Will break (structural)\n\n${capped(structural, row, "services")}` : null,
- behavioral.length ? `## May drift (co-change only)\n\n${capped(behavioral, row, "services")}` : null,
- `## Task\n\nA change to ${o.target.name} is planned. For each structurally impacted service, find the exact contracts it uses from ${o.target.name} and the tests that exercise them. For co-change services, say whether they need a coordinated change or can be left alone.`,
- `## What I expect back\n\n${numbered([
+ ])}`,
+ structural.length ? `\n## Will break (structural)\n\n${capped(structural, row, "services")}` : "",
+ behavioral.length ? `\n## May drift (co-change only)\n\n${capped(behavioral, row, "services")}` : "",
+ `\n## Task\n\nA change to ${o.target.name} is planned. For each structurally impacted service, find the exact contracts it uses from ${o.target.name} and the tests that exercise them. For co-change services, say whether they need a coordinated change or can be left alone.`,
+ `\n${verifySection(null, [o.target.id])}`,
+ `\n## What I expect back\n\n${numbered([
"Per impacted service: the contracts it depends on, with consumer files.",
"The tests to run in each repository before merging.",
"The order to land changes across repositories so nothing breaks in between.",
])}`,
flavor === "claude-code-mcp"
- ? `Confirm with \`get_blast_radius(target="${o.target.id}")\`, then \`search_codebase\` and \`get_context\` in each impacted repository.`
- : "Search each impacted repository for the routes, symbols and tables it takes from the target before planning.",
+ ? `\nConfirm with \`get_blast_radius(target="${o.target.id}")\`, then \`search_codebase\` and \`get_context\` in each impacted repository.`
+ : "\nSearch each impacted repository for the routes, symbols and tables it takes from the target before planning.",
]);
}
diff --git a/packages/web/src/components/code-health/hotspots-section.tsx b/packages/web/src/components/code-health/hotspots-section.tsx
index fae55f42c..668522579 100644
--- a/packages/web/src/components/code-health/hotspots-section.tsx
+++ b/packages/web/src/components/code-health/hotspots-section.tsx
@@ -27,7 +27,7 @@ import { useState } from "react";
import useSWR from "swr";
import { OverviewSection, SectionLink } from "@repowise-dev/ui/overview";
import { HotspotTable } from "@repowise-dev/ui/git/hotspot-table";
-import { AiPromptModal, buildHotspotAiPrompt } from "@repowise-dev/ui/health";
+import { AiPromptModal, buildHotspotAiPrompt, fileChatContext } from "@repowise-dev/ui/health";
import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
import { hotspotToFileCard } from "@repowise-dev/ui/shared/file-card";
import type { Hotspot } from "@repowise-dev/types/git";
@@ -133,6 +133,7 @@ export function HotspotsSection({ repoId }: { repoId: string }) {
: null
}
filePath={promptHotspot?.file_path}
+ chatContext={fileChatContext(promptHotspot?.file_path)}
title="AI stabilization prompt"
description="A ready-to-paste prompt that has your AI agent diagnose why this file churns and propose changes that make it cheaper to maintain."
/>
diff --git a/packages/web/src/components/commits/commit-detail-sheet.tsx b/packages/web/src/components/commits/commit-detail-sheet.tsx
index d16d8d2c1..5f2057eab 100644
--- a/packages/web/src/components/commits/commit-detail-sheet.tsx
+++ b/packages/web/src/components/commits/commit-detail-sheet.tsx
@@ -111,6 +111,11 @@ export function CommitDetailSheet({ repoId }: { repoId: string }) {
: null
}
filePath={detail ? detail.short_sha : null}
+ chatContext={
+ detail
+ ? { kind: "commit", label: detail.short_sha, target: detail.sha, targetKind: "commit" }
+ : undefined
+ }
title="AI commit review"
description="A ready-to-paste prompt that has your AI agent review this commit's change-risk, flag what to scrutinize, and suggest reviewers."
/>
diff --git a/packages/web/src/components/risk/security-tab.tsx b/packages/web/src/components/risk/security-tab.tsx
index 0cdd20312..5da48b480 100644
--- a/packages/web/src/components/risk/security-tab.tsx
+++ b/packages/web/src/components/risk/security-tab.tsx
@@ -6,7 +6,7 @@ import { RotateCw } from "lucide-react";
import { toast } from "sonner";
import { SecurityFindingsTable } from "@repowise-dev/ui/security/findings-table";
import { SeverityDirectoryMatrix } from "@repowise-dev/ui/security/severity-directory-matrix";
-import { AiPromptModal, buildSecurityAiPrompt } from "@repowise-dev/ui/health";
+import { AiPromptModal, buildSecurityAiPrompt, fileChatContext } from "@repowise-dev/ui/health";
import { Button } from "@repowise-dev/ui/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";
import { CollapsibleSection } from "@repowise-dev/ui/shared/collapsible-section";
@@ -108,6 +108,7 @@ export function SecurityTab({ repoId }: { repoId: string }) {
: null
}
filePath={promptFinding?.file_path}
+ chatContext={fileChatContext(promptFinding?.file_path)}
title="AI fix prompt"
description="A ready-to-paste prompt that walks your AI agent through confirming and remediating this security finding."
/>