Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,8 @@ Latest runtime-pack refinement: **runtime-generation prompts stay compact** by f

Single-prompt backend benchmark snapshot: in one real GoValidate `compare --baseline-mode native_agent` run for `"Explain how idea report is getting generated"`, madar reduced Anthropic-reported input tokens from **1,653,307** to **498,280** (~**69.9%** lower). Multi-question native-agent compare runs now also roll up suite wins/losses for input tokens, turns, and latency, report mean/median input-token reduction, call out comparable-question counts when some runs are excluded from the aggregate, and highlight the best win and worst regression prompt. Details and caveats: [`docs/benchmarks/2026-05-12-govalidate-report-generation/`](docs/benchmarks/2026-05-12-govalidate-report-generation/).

FounderCommandCenter auth-flow contrast note: one non-SPI run dropped **19 → 4 turns**, while an earlier SPI run for a similar auth prompt regressed from **2 → 19 turns**. The point is not a headline win; it is that strict context-pack-first guidance has to reduce exploration instead of merely adding context. Notes: [`docs/benchmarks/2026-05-25-founder-command-center-auth-flow/`](docs/benchmarks/2026-05-25-founder-command-center-auth-flow/).

[Reproduce them](docs/benchmarks/2026-04-30-govalidate/verify.sh) with one shell script against the committed evidence files.

---
Expand All @@ -188,7 +190,7 @@ madar produces local context packs that any modern coding agent can consume —

These are local installers that write project instructions and, when the platform supports it, local MCP config or plugin files that point at the madar subprocess. No code is uploaded.

For Claude, Cursor, Copilot, and Gemini, `--profile strict` keeps the lean core MCP tool surface but rewrites the generated guidance into a compact flow: call `context_pack` once for the task before broader exploration, answer from the pack when coverage is complete, expand only when diagnostics show missing evidence, and avoid raw file search unless the pack is insufficient.
For Claude, Cursor, Copilot, and Gemini, `--profile strict` keeps the lean core MCP tool surface but rewrites the generated guidance into a compact flow: call `context_pack` once for the task before broader exploration, answer after one high- or medium-confidence pack when `diagnostics.quality_score >= 0.5` and `missing_context` is empty, expand only when `missing_context` / `missing_semantic` or diagnostics justify it (or the user asks for deeper verification), and avoid raw file search unless the pack is insufficient.

Aider and OpenCode are intentionally context-pack-first: run `madar generate .`, install the profile, and start broad codebase work with `madar pack "<task>" --task explain` before raw file search. `madar aider install` writes an AGENTS.md profile only; remove it with `madar aider uninstall`. `madar opencode install` writes the AGENTS.md profile, `.opencode/plugins/madar.js`, and the madar MCP entry in `opencode.json` or `opencode.jsonc`; remove only madar-owned content with `madar opencode uninstall`. Manual verification does not require either agent binary: inspect the generated files after install, then confirm uninstall removes only the madar entries.

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# 2026-05-25 — FounderCommandCenter auth-flow contrast note

This note captures two real auth-flow compare outcomes from FounderCommandCenter:

- **Good run:** non-SPI graph, baseline **19 turns** → madar **4 turns**
- **Bad run:** earlier SPI graph, baseline **2 turns** → madar **19 turns**

The point is not to publish a flashy benchmark headline. The point is to document that Madar can still fail the product promise when the agent treats the pack as extra context and keeps exploring anyway.

## Why keep both runs

The good run showed the intended behavior: one context pack became the starting authority, follow-up exploration stayed narrow, and the answer completed with fewer turns.

The bad run showed the opposite failure mode: Madar added context, but the agent continued broad exploration and burned more turns than the baseline. That regression made it clear that **pack quality alone was not enough**. The install/profile guidance also had to push the agent toward a strict context-pack-first flow.

## What changed after the contrast

The fix direction for issue #314 is:

1. Tell installed agents to answer after one high- or medium-confidence pack instead of treating the pack as optional extra context.
2. Tell agents to expand only when `missing_context` / `missing_semantic` or diagnostics explicitly justify it, or when the user asks for deeper verification.
3. Record in compare/trace artifacts whether Madar **reduced exploration** or **only added context**.

That is why the current issue focuses on strict context-pack-first guidance and trace classification, not only on retrieval quality.

## Validation commands

```bash
npm run typecheck
npm run build
CI=1 npm run test:run
madar pack "How auth flow is working?" --task explain --why
madar compare "How auth flow is working?" --baseline-mode native_agent
```

Manual validation:

- install the strict Claude/Copilot/Cursor/Codex profile
- run the simple explain prompt
- confirm the agent uses one pack first
- confirm any extra exploration is explicitly justified and stays targeted

## Safe interpretation

The contrast shows a workflow problem, not a universal benchmark claim. This does not prove universal token reduction. One good run and one bad run are enough to justify stricter guidance and better trace reporting, but they do **not** prove universal token reduction.

## Unsafe claims

- "Madar always reduces turns on auth-flow prompts"
- "SPI is always worse"
- "Once a pack exists, verification is never needed"
- "A context pack automatically prevents broad exploration"
145 changes: 144 additions & 1 deletion src/infrastructure/compare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,12 +104,20 @@ export interface CompareMadarTraceTurnSummary {
tools: string[]
}

type CompareMadarTraceOutcome = 'reduced_exploration' | 'added_context_only' | 'no_context_pack'

export interface CompareMadarTrace {
source: 'claude_messages_tool_use'
summary: string
tool_call_count: number
tool_calls_by_name: Record<string, number>
per_turn: CompareMadarTraceTurnSummary[]
context_pack_call_count: number
focused_follow_up_tool_call_count: number
broad_exploration_tool_call_count: number
broad_exploration_tool_calls_by_name: Record<string, number>
exploration_outcome: CompareMadarTraceOutcome
exploration_summary: string
}

export interface ComparePromptReport {
Expand Down Expand Up @@ -763,6 +771,115 @@ function parseTraceToolName(value: unknown): string | null {
return trimmedValue.length > 0 ? trimmedValue : null
}

const MADAR_CONTEXT_PACK_TOOL_NAMES = new Set(['context_pack'])
const MADAR_FOCUSED_FOLLOW_UP_TOOL_NAMES = new Set([
'context_expand',
'retrieve',
'impact',
'relevant_files',
'feature_map',
'risk_map',
'implementation_checklist',
'graph_summary',
'graph_stats',
'community_overview',
'call_chain',
'pr_impact',
])

function canonicalTraceToolName(toolName: string): string {
return toolName.startsWith('mcp__madar__') ? toolName.slice('mcp__madar__'.length) : toolName
}

function traceToolCountSummary(toolCallsByName: Record<string, number>): string {
return Object.entries(toolCallsByName)
.sort(([leftName], [rightName]) => leftName.localeCompare(rightName))
.map(([toolName, count]) => `${toolName}×${count}`)
.join(', ')
}

function analyzeMadarTraceExploration(toolCallsByName: Record<string, number>): {
context_pack_call_count: number
focused_follow_up_tool_call_count: number
broad_exploration_tool_call_count: number
broad_exploration_tool_calls_by_name: Record<string, number>
exploration_outcome: CompareMadarTraceOutcome
exploration_summary: string
} {
let contextPackCallCount = 0
let focusedFollowUpToolCallCount = 0
let broadExplorationToolCallCount = 0
const broadExplorationToolCallsByName: Record<string, number> = {}

for (const [toolName, count] of Object.entries(toolCallsByName)) {
const canonicalName = canonicalTraceToolName(toolName)
if (MADAR_CONTEXT_PACK_TOOL_NAMES.has(canonicalName)) {
contextPackCallCount += count
continue
}

if (MADAR_FOCUSED_FOLLOW_UP_TOOL_NAMES.has(canonicalName)) {
focusedFollowUpToolCallCount += count
continue
}

broadExplorationToolCallCount += count
broadExplorationToolCallsByName[toolName] = count
}

const sortedBroadExplorationToolCallsByName = Object.fromEntries(
Object.entries(broadExplorationToolCallsByName).sort(([leftName], [rightName]) => leftName.localeCompare(rightName)),
)

if (contextPackCallCount === 0) {
return {
context_pack_call_count: 0,
focused_follow_up_tool_call_count: focusedFollowUpToolCallCount,
broad_exploration_tool_call_count: broadExplorationToolCallCount,
broad_exploration_tool_calls_by_name: sortedBroadExplorationToolCallsByName,
exploration_outcome: 'no_context_pack',
exploration_summary: 'no context_pack call recorded',
}
}

const contextPackSummary = `${contextPackCallCount} context_pack ${contextPackCallCount === 1 ? 'call' : 'calls'}`
const focusedSummary =
focusedFollowUpToolCallCount > 0
? `${focusedFollowUpToolCallCount} focused follow-up ${focusedFollowUpToolCallCount === 1 ? 'call' : 'calls'}`
: null

if (contextPackCallCount === 1 && broadExplorationToolCallCount === 0) {
return {
context_pack_call_count: contextPackCallCount,
focused_follow_up_tool_call_count: focusedFollowUpToolCallCount,
broad_exploration_tool_call_count: 0,
broad_exploration_tool_calls_by_name: {},
exploration_outcome: 'reduced_exploration',
exploration_summary:
focusedSummary === null
? `${contextPackSummary}; no broad exploration recorded`
: `${contextPackSummary}; ${focusedSummary}; no broad exploration recorded`,
}
}

const broadSummary =
broadExplorationToolCallCount === 0
? 'no broad exploration recorded'
: `${broadExplorationToolCallCount} broad exploration ${broadExplorationToolCallCount === 1 ? 'call' : 'calls'}${Object.keys(sortedBroadExplorationToolCallsByName).length > 0 ? ` (${traceToolCountSummary(sortedBroadExplorationToolCallsByName)})` : ''}`

return {
context_pack_call_count: contextPackCallCount,
focused_follow_up_tool_call_count: focusedFollowUpToolCallCount,
broad_exploration_tool_call_count: broadExplorationToolCallCount,
broad_exploration_tool_calls_by_name: sortedBroadExplorationToolCallsByName,
exploration_outcome: 'added_context_only',
exploration_summary:
focusedSummary === null
? `${contextPackSummary}; ${broadSummary}`
: `${contextPackSummary}; ${focusedSummary}; ${broadSummary}`,
}
}

function parseTraceTurnNumber(value: unknown, fallbackTurn: number): number {
if (typeof value === 'number' && Number.isInteger(value) && value > 0) {
return value
Expand Down Expand Up @@ -827,6 +944,7 @@ function extractMadarTrace(stdout: string): CompareMadarTrace | undefined {
}

const sortedTurns = [...perTurnIndex.keys()].sort((leftTurn, rightTurn) => leftTurn - rightTurn)
const exploration = analyzeMadarTraceExploration(toolCallsByName)

return {
source: 'claude_messages_tool_use',
Expand All @@ -836,6 +954,7 @@ function extractMadarTrace(stdout: string): CompareMadarTrace | undefined {
Object.entries(toolCallsByName).sort(([leftName], [rightName]) => leftName.localeCompare(rightName)),
),
per_turn: sortedTurns.map((turn) => perTurnIndex.get(turn)!),
...exploration,
}
}

Expand Down Expand Up @@ -1592,14 +1711,28 @@ function formatCompareMadarTraceSummary(result: GenerateCompareArtifactsResult):
return total + trace.tool_call_count
}, 0)
const totalTurns = traces.reduce((total, trace) => total + trace.per_turn.length, 0)
const reducedExplorationRuns = traces.filter((trace) => trace.exploration_outcome === 'reduced_exploration').length
const addedContextOnlyRuns = traces.filter((trace) => trace.exploration_outcome === 'added_context_only').length
const noContextPackRuns = traces.filter((trace) => trace.exploration_outcome === 'no_context_pack').length
const topTools = [...toolCallsByName.entries()]
.sort((leftEntry, rightEntry) => rightEntry[1] - leftEntry[1] || leftEntry[0].localeCompare(rightEntry[0]))
.slice(0, 3)
.map(([toolName, count]) => `${toolName}×${count}`)
const traceCoverage = traces.length === result.reports.length ? '' : ` · traces for ${traces.length}/${result.reports.length} madar runs`
const topToolsSummary = topTools.length > 0 ? ` · top tools: ${topTools.join(', ')}` : ''
const outcomeParts: string[] = []
if (reducedExplorationRuns > 0) {
outcomeParts.push(`${reducedExplorationRuns} reduced exploration`)
}
if (addedContextOnlyRuns > 0) {
outcomeParts.push(`${addedContextOnlyRuns} added context only`)
}
if (noContextPackRuns > 0) {
outcomeParts.push(`${noContextPackRuns} without context_pack`)
}
const outcomeSummary = outcomeParts.length > 0 ? ` · outcomes: ${outcomeParts.join(', ')}` : ''

return `Madar trace: ${totalToolCalls} tool call${totalToolCalls === 1 ? '' : 's'} across ${totalTurns} turn${totalTurns === 1 ? '' : 's'}${traceCoverage}${topToolsSummary}`
return `Madar trace: ${totalToolCalls} tool call${totalToolCalls === 1 ? '' : 's'} across ${totalTurns} turn${totalTurns === 1 ? '' : 's'}${traceCoverage}${topToolsSummary}${outcomeSummary}`
}

export function formatCompareSummary(result: GenerateCompareArtifactsResult): string {
Expand Down Expand Up @@ -1752,6 +1885,7 @@ export interface NativeAgentCompareReport {
exec_command: CompareExecCommandSummary
baseline: NativeAgentRunStatus
madar: NativeAgentRunStatus
madar_trace?: CompareMadarTrace
reductions: {
input_tokens: number | null
num_turns: number | null
Expand Down Expand Up @@ -2447,6 +2581,12 @@ export async function executeNativeAgentCompare(
ensureCompareAnswerFile(madarAnswerPath, '')
}
if (madarRun !== null) {
const madarTrace = extractMadarTrace(madarRun.stdout)
if (madarTrace) {
reportShell.madar_trace = madarTrace
} else {
delete reportShell.madar_trace
}
const event = parseAnthropicResultEvent(madarRun.stdout)
if (event !== null) {
reportShell.madar = {
Expand Down Expand Up @@ -2666,6 +2806,9 @@ export function formatNativeAgentCompareSummary(result: NativeAgentCompareResult
` answer quality: baseline ${report.answer_quality.baseline.passed ? 'PASS' : `FAIL (${baselineFindings.join(', ')})`} · madar ${report.answer_quality.madar.passed ? 'PASS' : `FAIL (${madarFindings.join(', ')})`}${report.answer_quality.manual_review_notes.length > 0 ? ` · manual review: ${formatCount(report.answer_quality.manual_review_notes.length, 'note', 'notes')}` : ''}`,
)
}
if (report.madar_trace) {
lines.push(` madar_trace: ${report.madar_trace.exploration_outcome} · ${report.madar_trace.exploration_summary}`)
}
lines.push(` provider/runtime proof: Anthropic reported input, cache, and total tokens for both runs`)
}
return lines.join('\n')
Expand Down
3 changes: 3 additions & 0 deletions src/infrastructure/install-skill-templates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,9 @@ madar pack "<task or question>" --task explain
# Use --task review, --task debug, or --task impact when that better matches the work.
${CODE_BLOCK_END}

If the first pack is a high- or medium-confidence pack (diagnostics.quality_score >= 0.5, missing_context is empty, and diagnostics contain no error-severity gaps), answer from it before broader exploration.
Only expand when missing_context or missing_semantic is non-empty, diagnostics show warn/error gaps, or the user asks for deeper verification.

Install or remove the always-on Codex project profile with:

${CODE_BLOCK_START}bash
Expand Down
Loading
Loading