Skip to content

Fix core profile prompt contract - #411

Merged
mohanagy merged 2 commits into
mainfrom
issue-405-context-pack-first-contract
May 29, 2026
Merged

mohanagy merged 2 commits into
mainfrom
issue-405-context-pack-first-contract

Conversation

@mohanagy

@mohanagy mohanagy commented May 29, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • make the native-agent compare prompt use retrieve-first guidance on core installs and keep context_pack-first on full installs
  • read the installed MCP profile from .mcp.json so prompt-contract checks validate against the tool actually exposed
  • add regressions for default core retrieve-first behavior and full-profile context_pack enforcement

Closes #405

Verification

  • npm run test:run -- tests/unit/compare.test.ts tests/unit/compare-native-agent.test.ts
  • npm run typecheck
  • npm run build
  • CI=1 npm run test:run

Summary by CodeRabbit

  • New Features
    • Native agent detects MCP tool profiles from project config and adjusts prompt generation and contract validation per profile (defaults to "core").
  • Bug Fixes
    • Prompt-contract validation now enforces profile-specific required first-tool behavior and updates generated prompt wording accordingly.
  • Tests
    • Unit tests and snapshots updated to cover core vs full profile behaviors and corresponding prompt-contract outcomes.

Review Change Stack

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@mohanagy

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented May 29, 2026 •

Copy link
Copy Markdown

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 2aaa7809-7732-4cb4-80cc-36cecd4548e9

📥 Commits

Reviewing files that changed from the base of the PR and between b73ea37 and cde20ea.

📒 Files selected for processing (2)
  • src/infrastructure/compare.ts
  • tests/unit/compare-native-agent.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/infrastructure/compare.ts

📝 Walkthrough

Walkthrough

This PR detects the MCP tool profile from .mcp.json, records it during install inspection, and uses it to generate profile-aware native-agent prompts and to validate the first Madar call against profile-specific entry tools (retrieve-first for core, context_pack-first for full).

Changes

Tool-Profile-Aware Native-Agent Prompt and Contract

Layer / File(s) Summary
MCP Tool Profile Detection & Storage
src/infrastructure/compare.ts
Import McpToolProfile and resolution utilities; extend NativeAgentInstallCheck with tool_profile; implement readMadarMcpEntry, hasMadarMcpEntry, and readInstalledToolProfile to parse .mcp.json madar env and default to 'core'; populate tool_profile during inspectClaudeNativeAgentInstall.
Profile-Aware Prompt Generation
src/infrastructure/compare.ts
Add MADAR_CORE_ENTRY_TOOL_NAMES and helpers (getRequiredEntryToolForProfile, getEntryToolNamesForProfile, profile evidence helpers); update buildNativeAgentPrompt(question, profile = 'core') to render retrieve-first instructions for core and context_pack-first for full.
Profile-Aware Contract Assessment & Orchestration
src/infrastructure/compare.ts
Change assessNativeAgentPromptContract to accept toolProfile; validate the first Madar trace tool against the profile-specific entry-tool set; generate profile-specific success/violation evidence; in executeNativeAgentCompare, write prompt via buildNativeAgentPrompt(question, installCheck.tool_profile) and pass installCheck.tool_profile into the assessor.
Test Coverage for Profile-Specific Behavior
tests/unit/compare-native-agent.test.ts, tests/unit/compare.test.ts
Extend makeFixtureProject to accept profile and thread it into fixture installs; replace default prompt-contract test with core retrieve-first assertions; add full-profile test preserving context_pack-first contract; update snapshots for buildNativeAgentPrompt; add summary assertions for followed/violated per profile behavior.

Sequence Diagram

sequenceDiagram
  participant Install as inspectClaudeNativeAgentInstall
  participant ReadProfile as readInstalledToolProfile
  participant BuildPrompt as buildNativeAgentPrompt
  participant AssessContract as assessNativeAgentPromptContract
  participant Execute as executeNativeAgentCompare
  
  Execute->>Install: check install state
  Install->>ReadProfile: derive tool profile from .mcp.json
  ReadProfile-->>Install: return 'core' or 'full'
  Install-->>Execute: return NativeAgentInstallCheck with tool_profile
  
  Execute->>BuildPrompt: pass question + detected profile
  BuildPrompt-->>Execute: return profile-aware prompt text
  Note over BuildPrompt: core → retrieve-first<br/>full → context_pack-first
  
  Execute->>AssessContract: evaluate trace with profile
  AssessContract->>AssessContract: validate first Madar call<br/>matches profile entry tool
  AssessContract-->>Execute: return contract state (followed/violated)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related PRs

  • mohanagy/madar#391: Introduced native-agent prompt generation and prompt-contract assessment; this PR makes that mechanism tool-profile-aware.
  • mohanagy/madar#352: Modified native-agent install inspection; this PR extends the install check with a tool_profile used for prompt generation and validation.
  • mohanagy/madar#343: Previously threaded .mcp.json data into install checks and prompt handling; this PR continues by detecting and using the tool profile.

Poem

🐰 I sniffed the MCP, then hopped with cheer,
Threaded profile whispers so agents hear,
Retrieve on core, pack on full at start,
No more contract grief to break the heart,
Hoppity tests pass — prompt and trace in art. ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Fix core profile prompt contract' directly and specifically addresses the main change: updating the native-agent compare prompt to use profile-aware contract logic for core vs. full profiles.
Description check ✅ Passed The description includes all key sections: a clear summary of the three main changes, verification commands covering test, typecheck, and build, and issue closure reference (#405). The checklist is implicitly satisfied through the verification approach.
Linked Issues check ✅ Passed The PR comprehensively addresses all acceptance criteria from issue #405: retrieve is now the canonical core entry tool, buildNativeAgentPrompt generates profile-aware instructions, prompt-contract validates against the installed profile, unit tests cover both core retrieve-first and full context_pack-first scenarios, and no regressions occur in existing fixtures.
Out of Scope Changes check ✅ Passed All changes are directly scoped to issue #405 requirements: profile-aware prompt contract logic, installed profile resolution, and corresponding test updates. No unrelated refactoring or scope creep is present.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch issue-405-context-pack-first-contract

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint skipped: no ESLint configuration detected in root package.json. To enable, add eslint to devDependencies.


Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai

coderabbitai Bot commented May 29, 2026

Copy link
Copy Markdown
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/infrastructure/compare.ts (1)

3572-3584: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Preserve definite contract violations before falling back to not_measured.

If Lines 3572-3579 already establish a deterministic violation, Lines 3580-3584 currently overwrite it with not_measured as soon as there is later broad exploration. On a full-profile trace like retrieve -> Glob, that hides the clear "first Madar call was not context_pack" failure this PR is meant to surface. Worth adding a regression test for that shape too.

Suggested fix
   if (report.madar_trace.broad_exploration_tool_call_count > 0) {
+    if (evidence.length > 0) {
+      evidence.push('broad exploration occurred after the first Madar call, but the trace does not show whether missing_context justified it')
+      return {
+        status: 'violated',
+        evidence,
+      }
+    }
     return {
       status: 'not_measured',
       evidence: ['broad exploration occurred after the first Madar call, but the trace does not show whether missing_context justified it'],
     }
   }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/infrastructure/compare.ts` around lines 3572 - 3584, The code currently
pushes a deterministic contract violation via
nativeAgentPromptContractViolationEvidence (using
nativeAgentPromptContractEntryToolNames and canonicalTraceToolName) but then
unconditionally returns a 'not_measured' result when
report.madar_trace.broad_exploration_tool_call_count > 0, which overwrites the
earlier violation; change the branching so that before returning the
'not_measured' object you check whether evidence already contains the
deterministic violation (the object produced by
nativeAgentPromptContractViolationEvidence) or whether a non-null violation was
previously recorded and, if so, return that violation/status instead of
'not_measured'—i.e., only fall back to the not_measured return when no prior
deterministic violation was appended to evidence.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@src/infrastructure/compare.ts`:
- Around line 3572-3584: The code currently pushes a deterministic contract
violation via nativeAgentPromptContractViolationEvidence (using
nativeAgentPromptContractEntryToolNames and canonicalTraceToolName) but then
unconditionally returns a 'not_measured' result when
report.madar_trace.broad_exploration_tool_call_count > 0, which overwrites the
earlier violation; change the branching so that before returning the
'not_measured' object you check whether evidence already contains the
deterministic violation (the object produced by
nativeAgentPromptContractViolationEvidence) or whether a non-null violation was
previously recorded and, if so, return that violation/status instead of
'not_measured'—i.e., only fall back to the not_measured return when no prior
deterministic violation was appended to evidence.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 6585b12f-ca15-4a30-b7c8-a47b9cfeb204

📥 Commits

Reviewing files that changed from the base of the PR and between c104c63 and b73ea37.

📒 Files selected for processing (3)
  • src/infrastructure/compare.ts
  • tests/unit/compare-native-agent.test.ts
  • tests/unit/compare.test.ts

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@mohanagy

Copy link
Copy Markdown
Owner Author

Fixed the deterministic full-profile violation case that CodeRabbit flagged.

  • preserve the first-tool contract violation even when later broad exploration makes justification ambiguous
  • add a regression covering full-profile retrieve -> Glob traces

@coderabbitai review

@coderabbitai

coderabbitai Bot commented May 29, 2026

Copy link
Copy Markdown

@mohanagy Thanks for the update! The fix to preserve the first-tool contract violation regardless of later exploration patterns sounds like the right approach — eager-violation semantics are much cleaner for contract enforcement. Triggering a fresh review now.

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[P1] prompt_contract + native-agent prompt require context_pack-first, but the default core tool profile excludes context_pack

1 participant