Skip to content

Tighten runtime pack confidence gating - #393

Merged
mohanagy merged 2 commits into
nextfrom
issue-388-pack-confidence
May 28, 2026
Merged

mohanagy merged 2 commits into
nextfrom
issue-388-pack-confidence

Conversation

@mohanagy

@mohanagy mohanagy commented May 28, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • make runtime-generation pack confidence account for scope quality, workflow locality, answer-containedness, and phase completeness
  • add confidence reasons to pack evidence and require explicit answer-containedness before answer_from_pack
  • thread graph-path context through prompt/evidence builders and cover the new gating with regressions

Closes #388

Summary by CodeRabbit

  • New Features

    • Prompt generation now includes an explicit graph path for more targeted context.
    • Evidence assessment upgraded to produce richer confidence reasons and a computed confidence score.
    • Improved answer-containment detection to better guide agent directives.
    • Tools now attach graph-path-aware evidence for more accurate provenance.
  • Tests

    • Added unit tests covering confidence reasons, containment behavior, and graph-path scoped evidence.

Review Change Stack

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

coderabbitai Bot commented May 28, 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: 6cc9e72d-ee18-4ab2-b219-c5b8d26c52b3

📥 Commits

Reviewing files that changed from the base of the PR and between 6db672a and 6cbafce.

📒 Files selected for processing (5)
  • src/runtime/mcp-response-evidence.ts
  • src/runtime/stdio/tools.ts
  • tests/unit/context-pack-command.test.ts
  • tests/unit/mcp-response-evidence.test.ts
  • tests/unit/stdio-slice-surface.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • tests/unit/context-pack-command.test.ts
  • src/runtime/mcp-response-evidence.ts

📝 Walkthrough

Walkthrough

This PR enhances the evidence model to account for scope quality, workflow locality, answer-containedness, and phase completeness. It introduces assessMadarResponseEvidence to compute confidence with reasons, threads graph path through infrastructure and runtime tool calls, and surfaces confidence reasoning in pack outputs.

Changes

Graph-Path-Aware Confidence Assessment and Evidence Threading

Layer / File(s) Summary
Evidence Assessment Model
src/runtime/mcp-response-evidence.ts
Introduces MadarResponseEvidenceAssessment with computed score, extends MadarResponseEvidence to include confidence_reasons and agent_directive, and implements assessMadarResponseEvidence that factors scope alignment, workflow locality, phase completeness, runtime containedness, and answer-completeness into confidence scoring. Rewrites buildMadarResponseEvidence to use the assessment pipeline.
Infrastructure Graph Path Threading
src/infrastructure/compare.ts, src/infrastructure/benchmark/runner.ts, src/infrastructure/context-prompt-command.ts
Adds optional graphPath field to BuildMadarPromptPackInput and threads it through benchmark runner, compare artifacts, and context-prompt commands.
Context Pack Command Integration
src/infrastructure/context-pack-command.ts
Updates buildExplainPackPayloadCore to accept graphPath, switches to assessMadarResponseEvidence, uses the computed score for confidence_score, and extends whyExplanation to format and append confidence_reasons. Wires graphPath through the entire pack-building chain.
Tool Runtime Evidence Wiring
src/runtime/stdio/tools.ts
Updates evidenceForRetrievePayload and evidenceForPathPayload helpers to accept and forward graphPath into evidence builders. Threads graphPath through all tool-response evidence calls: context-pack delta mode, retrieve tool, context-prompt tool, and path-based tools.
Confidence Assessment and Integration Tests
tests/unit/mcp-response-evidence.test.ts, tests/unit/context-pack-command.test.ts, tests/unit/stdio-slice-surface.test.ts
Adds unit tests verifying confidence downgrade behavior for weak scope quality and incomplete answer-containedness, and assertions for high-confidence fully-contained answers. Tests validate agent_directive, confidence_reasons, and evidence fields.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • mohanagy/madar#351: Both PRs modify the explain-pack payload construction in src/infrastructure/context-pack-command.ts, specifically buildExplainPackPayloadCore/buildPackSchemaV1 for explain packs—main adds graphPath + confidence/reason evidence wiring, while the retrieved PR changes guidance compatibility fields/payload core used by compare.
  • mohanagy/madar#381: The retrieved PR changes runtime execution-slice spine ranking (which determines the executionSlice chosen for explain/report prompts), and the main PR’s new evidence/confidence scoring logic consumes that executionSlice to populate pack_confidence, agent_directive, and confidence_reasons, so they’re directly connected via the executionSlice data flow.
  • mohanagy/madar#320: Both PRs modify src/infrastructure/context-pack-command.ts around pack “confidence”/evidence handling—main PR changes how confidence_score/confidence_reasons (via assessMadarResponseEvidence and graphPath) are produced, while the retrieved PR gates the Claude/Copilot directive wording off pack quality/confidence—so the directive output logic in the main PR’s confidence evidence is directly implicated.

Poem

🐰 A rabbit hops through graphs with glee,
Scoring packs with confidence and reason—
Scope and slice and locality,
Answer-bound for every season.
From runtime tools to context packs,
The path flows true, no looking back! 🌿

🚥 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 'Tighten runtime pack confidence gating' accurately captures the main objective of the PR: improving and restricting pack confidence logic by incorporating scope quality, answer-containedness, and phase completeness.
Description check ✅ Passed The PR description clearly outlines the changes with specific objectives and closes issue #388. However, it lacks the optional Testing section with the build/test verification checklist, though this is non-critical.
Linked Issues check ✅ Passed The PR implements all required objectives from issue #388: scope quality gating [388], workflow locality checks [388], answer-containedness validation [388], phase completeness verification [388], confidence reasons exposure [388], and agent_directive alignment [388]. All coding requirements are met.
Out of Scope Changes check ✅ Passed All changes are directly scoped to implementing issue #388 requirements: evidence assessment logic, confidence gating, graph-path threading, and regression test coverage. No unrelated changes detected.

✏️ 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-388-pack-confidence

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 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.

Actionable comments posted: 3

Caution

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

⚠️ Outside diff range comments (1)
src/runtime/stdio/tools.ts (1)

1314-1318: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Pass graphPath into the remaining direct buildMadarResponseEvidence calls.

These two context_pack evidence paths still omit graphPath, so scope-aware confidence can diverge from the updated retrieve/path flows.

💡 Suggested fix
           evidence: buildMadarResponseEvidence({
             coverage: deltaResult.delta_pack.coverage,
+            graphPath,
             missingPhases: missingPhasesFromPayload(deltaResult.delta_pack),
             coveredWorkflowOwners: collectWorkflowOwners(resolvedDeltaNodes.nodes.map((node) => node.source_file)),
           }),
@@
         evidence: buildMadarResponseEvidence({
           coverage: fullPack.coverage,
+          graphPath,
           missingPhases: missingPhasesFromPayload(fullPack),
           coveredWorkflowOwners: collectWorkflowOwners(resolvedNodes.nodes.map((node) => node.source_file)),
         }),

Also applies to: 1338-1342

🤖 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/runtime/stdio/tools.ts` around lines 1314 - 1318, The two direct calls to
buildMadarResponseEvidence (the one using deltaResult.delta_pack.coverage /
missingPhasesFromPayload(deltaResult.delta_pack) /
collectWorkflowOwners(...resolvedDeltaNodes...) and the other occurrence later)
must include the graphPath argument so scope-aware confidence matches the
updated retrieve/path flows; update both call sites to pass the relevant
graphPath value (the same variable used elsewhere in this module) as an
additional parameter to buildMadarResponseEvidence so the evidence objects
include graphPath.
🧹 Nitpick comments (1)
src/runtime/stdio/tools.ts (1)

333-334: ⚡ Quick win

Make graphPath required in helper signatures.

Keeping it optional weakens the new confidence contract and allows silent regressions.

♻️ Suggested refactor
 function evidenceForRetrievePayload(
   payload: Partial<Pick<RetrieveResult, 'coverage' | 'answer_contract' | 'execution_slice'>> & {
     matched_nodes?: Array<{ source_file: string }>
   },
-  graphPath?: string,
+  graphPath: string,
 ) {
@@
 function evidenceForPathPayload(
   payload: Partial<Pick<RetrieveResult, 'coverage' | 'answer_contract' | 'execution_slice'>> & {
     relevant_files?: Array<{ path: string }>
     starter_files?: Array<{ path: string }>
     edit_steps?: Array<{ path: string }>
   },
-  graphPath?: string,
+  graphPath: string,
 ) {

Also applies to: 351-352

🤖 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/runtime/stdio/tools.ts` around lines 333 - 334, Make the graphPath
parameter required wherever it's currently declared optional (graphPath?:
string) in the helper signatures in this module: change to graphPath: string,
update any related parameter destructuring or defaulting, and adjust all call
sites (including the two other occurrences referenced around lines 351–352) to
always pass a non-null string; ensure any type annotations, overloads, and tests
reflect the new required string type so the confidence contract is enforced.
🤖 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.

Inline comments:
In `@src/runtime/mcp-response-evidence.ts`:
- Around line 290-293: The code currently applies runtimeConfidence to update
confidenceCap (runtimeConfidence, moreRestrictiveConfidence, confidenceCap) but
does not record a matching entry in the confidence reasons; change the block so
that after computing the new cap you also append a reason object/string to the
existing confidence_reasons (or confidenceReasons) collection describing the
downgrade (include source "runtime", the runtimeConfidence value, and previous
vs new cap), and only append when the cap actually becomes more restrictive so
the reasons explain the change.
- Around line 128-133: candidateScopes generation is dropping real scopes when
paths start with generic prefixes (e.g. "packages/spi/...") because the code
only takes the first segment; update the mapping over
coveredWorkflowOwners/normalizeSourcePath so that when the first segment is in
GENERIC_SCOPE_SEGMENTS it uses the second segment as the candidate scope (fall
back to the first if no second), otherwise use the first; keep the existing
filters (non-empty and not in GENERIC_SCOPE_SEGMENTS) and the Set dedupe logic
so candidateScopes includes subproject scopes like "spi".

In `@tests/unit/context-pack-command.test.ts`:
- Around line 764-767: The negated regex assertions on
payload.evidence.pack_confidence and payload.evidence.agent_directive can pass
when those fields are missing; update the tests to first assert the fields exist
and are of expected type/value before applying the "not" regex checks: add
explicit presence checks (e.g.
expect(payload.evidence).toHaveProperty('pack_confidence') and expect(typeof
payload.evidence.pack_confidence).toBe('string')) or assert allowed enum values,
then keep the expect.not.stringMatching checks on pack_confidence and
agent_directive; apply the same strengthening to the duplicate assertions around
the block that mentions lines 890-893 (the other payload.evidence assertions for
confidence_reasons).

---

Outside diff comments:
In `@src/runtime/stdio/tools.ts`:
- Around line 1314-1318: The two direct calls to buildMadarResponseEvidence (the
one using deltaResult.delta_pack.coverage /
missingPhasesFromPayload(deltaResult.delta_pack) /
collectWorkflowOwners(...resolvedDeltaNodes...) and the other occurrence later)
must include the graphPath argument so scope-aware confidence matches the
updated retrieve/path flows; update both call sites to pass the relevant
graphPath value (the same variable used elsewhere in this module) as an
additional parameter to buildMadarResponseEvidence so the evidence objects
include graphPath.

---

Nitpick comments:
In `@src/runtime/stdio/tools.ts`:
- Around line 333-334: Make the graphPath parameter required wherever it's
currently declared optional (graphPath?: string) in the helper signatures in
this module: change to graphPath: string, update any related parameter
destructuring or defaulting, and adjust all call sites (including the two other
occurrences referenced around lines 351–352) to always pass a non-null string;
ensure any type annotations, overloads, and tests reflect the new required
string type so the confidence contract is enforced.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: b617dc81-6693-4542-9f0e-4ad2f34325f7

📥 Commits

Reviewing files that changed from the base of the PR and between 55c8088 and 6db672a.

📒 Files selected for processing (8)
  • src/infrastructure/benchmark/runner.ts
  • src/infrastructure/compare.ts
  • src/infrastructure/context-pack-command.ts
  • src/infrastructure/context-prompt-command.ts
  • src/runtime/mcp-response-evidence.ts
  • src/runtime/stdio/tools.ts
  • tests/unit/context-pack-command.test.ts
  • tests/unit/mcp-response-evidence.test.ts

Comment thread src/runtime/mcp-response-evidence.ts Resolved
Comment thread src/runtime/mcp-response-evidence.ts Resolved
Comment thread tests/unit/context-pack-command.test.ts Resolved
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@coderabbitai

coderabbitai Bot commented May 28, 2026

Copy link
Copy Markdown

Actionable comments posted: 0

@mohanagy
mohanagy merged commit c9b5f2d into next May 28, 2026
7 checks passed
@coderabbitai coderabbitai Bot mentioned this pull request May 28, 2026
8 tasks
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.

1 participant