Skip to content

Feature/task context planner#60

Merged
mohanagy merged 17 commits into
mainfrom
feature/task-context-planner
May 8, 2026
Merged

Feature/task context planner#60
mohanagy merged 17 commits into
mainfrom
feature/task-context-planner

Conversation

@mohanagy
Copy link
Copy Markdown
Owner

@mohanagy mohanagy commented May 8, 2026

Summary

  • wire planner-derived task intent and plan metadata into CLI pack and MCP context_pack
  • add MCP context_expand so expandable handles can be executed within the active session
  • make compare/benchmark proof reporting distinguish real provider cache-read tokens from zero-cache provider usage
  • preserve impact target file_type so semantic coverage does not falsely miss implementation
  • align CLI pack output with MCP metadata and add a shared pickImpactTarget() helper so CLI/MCP impact selection stays consistent
  • extend tests for planner-aware packs, semantic coverage, executable expansion, tool gating, and provider-proof wording

Testing

  • npm run test:run
  • npm run typecheck
  • npm run build
  • npm pack --dry-run

Checklist

  • I updated docs for any user-visible change
  • I added or updated tests when behavior changed
  • I did not commit secrets, private corpora, or accidental generated artifacts
  • I kept this PR focused on a single change or tightly related set of changes

Related issues

Addresses the PR #60 review blockers around planner wiring, executable expandable refs, honest provider proof reporting, impact semantic coverage, and CLI/MCP output alignment.

Summary by CodeRabbit

  • New Features

    • Task-intent classification and planner-driven task context plans; intent-driven evidence recipes and selection.
    • Semantic coverage buckets and richer expandable previews with stable handles and follow-up payloads.
    • Context inventory schema plus input validation/normalization and session-stored expandable handles enabling focused expansions.
    • Provider/runtime proof reporting surfaced in benchmark/compare/review outputs.
    • Impact target selection and reporting of target file type.
  • Documentation

    • Expanded docs and examples for semantic coverage, provider proof, planner behavior, and context_expand.
  • Tests

    • Expanded unit tests covering semantics, proofs, planners, and expansion flows.

mohanagy and others added 12 commits May 8, 2026 15:48
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Fallback review plans to primary evidence when only focus paths are available, so review seeds no longer request change evidence without changed files.

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

coderabbitai Bot commented May 8, 2026

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR adds a task-intent taxonomy and runtime, context-inventory contracts and normalizers, task-evidence recipes and a deterministic task-context planner, semantic coverage and stable expandable references in context packs with focused expansion tooling, provider/runtime token-source proof tracking across benchmark/compare/review-compare, and extensive test/docs updates.

Changes

Task Intent Classification System

Layer / File(s) Summary
Intent Contract
src/contracts/task-intent.ts
Exports TASK_INTENT_KINDS, TaskIntentKind, TaskIntentContextKind, TaskIntentConfidence, and interfaces for signal rules, intent definitions, scores, and classification payloads plus TASK_INTENT_DEFINITIONS.
Intent Runtime
src/runtime/task-intent.ts
Implements prompt normalization, phrase/keyword/keyword-group matching, rule validation (single matcher enforcement), cached definition validation, rule evaluation, scoring and deterministic tie-breaking, and exports classifyTaskIntent, normalizeTaskIntentPrompt, and validateTaskIntentDefinitions.
Intent Tests
tests/unit/task-intent.test.ts
Validates taxonomy stability/serialization, prompt normalization, deterministic classification and tie-breaking, fallback to explain, caching behavior, and rule validation error cases.

Context Inventory System

Layer / File(s) Summary
Inventory Contract
src/contracts/context-inventory.ts
Defines ContextInventorySourceKind, ContextInventorySourceMetadata, ContextInventorySourceDescriptor, recursive ContextInventoryValue, and versioned ContextInventoryEntry.
Inventory Runtime
src/runtime/context-inventory.ts
Provides SOURCE_KIND_ALIASES, validation helpers, normalizeSourceMetadata, tag normalization, attribute deep-normalization with cycle detection and finite-number checks, and exports normalizeContextInventorySource and createContextInventoryEntry.
Inventory Tests
tests/unit/context-inventory.test.ts
Covers docs source normalization, diff ref preservation, invalid-kind/invalid-diff/line-range failure cases, serializability, and rejection of circular or non-finite attributes.

Task Evidence Recipes and Planner

Layer / File(s) Summary
Evidence Recipes
src/runtime/task-evidence-recipes.ts
Defines TaskEvidenceRecipe, TASK_EVIDENCE_RECIPES, dedup/clone helpers, and review-fallback remapping (changeprimary, semantic changesimplementation).
Context Plan Contracts
src/contracts/task-context-plan.ts
Exports TASK_CONTEXT_PLAN_VERSION and types for plan input, scope, evidence, step, and full TaskContextPlan.
Planner Runtime
src/runtime/task-context-planner.ts
Implements planner shapes for task kinds, input normalization, deterministic budget allocation with rebalancing, scope selection logic, integrates intent classification and recipe resolution, and exports buildTaskContextPlan.
Planner Tests
tests/unit/task-context-planner.test.ts
Validates stable plans, changed-path prioritization, fallback behaviors, recipe-driven evidence selection, minimum budget allocations, and input validation errors.

Context Pack Semantic Coverage & Expandables

Layer / File(s) Summary
Contract Extensions
src/contracts/context-pack.ts
Adds ContextPackSemanticCategory, extends ContextPackTaskContract (task_intent, evidence_recipe_id, preferred_evidence, semantic_required/optional), introduces structured expandable preview/line-range/follow-up types, and extends ContextPackCoverage with semantic fields and entries.
Runtime
src/runtime/context-pack.ts
Computes semantic coverage alongside evidence coverage, classifies nodes into semantic categories, materializes and sorts candidates by evidence priority, stabilizes expandable handle IDs, normalizes preview line ranges, deduplicates follow-up focus ranges, and integrates resolveTaskEvidenceRecipe into classification and compilation.
Retrieve Integration
src/runtime/retrieve.ts
Propagates attributes.source_location as sourceLocation, adds expandableLineRange() helper, includes expandable_ref with optional line_range on node candidates, extends fallback coverage with semantic fields, and forwards taskIntent into task_contract.
Tests
tests/unit/context-pack.test.ts, tests/unit/retrieve.test.ts
Extensive test updates to assert semantic coverage fields (semantic_required, semantic_optional, semantic_entries, missing_semantic), deterministic expandable handle_ids, structured preview and follow_up shapes, and source_location-derived line ranges.

Provider / Runtime Proof Tracking

Layer / File(s) Summary
Benchmark
src/infrastructure/benchmark.ts
Extends BenchmarkSuccessResult with provider_proof, computes per-question aggregates in finalizeBenchmarkResult, derives categorical bases/provider list, adds benchmarkProviderProofSummary, and prints a "Provider/runtime proof" line in summaries.
Compare & Native Agent
src/infrastructure/compare.ts
Adds ComparePromptProviderProofEntry/ComparePromptProviderProof, optional provider_proof on compare reports, helpers to map usage→provider and token-source labels, formatCompareProviderProof, and extends native-agent reports to capture provider/token-source provenance and reduction_basis.
Review Compare
src/infrastructure/review-compare.ts
Adds optional provider_proof with verbose/compact sources and reduction_basis, populates it in artifact generation, and appends proof line in summaries.
Tests
tests/unit/benchmark.test.ts, tests/unit/compare.test.ts, tests/unit/review-compare.test.ts
Updated assertions validating provider_proof payload shapes and the consolidated "Provider/runtime proof" summary lines across scenarios.

Stdio Tools & Context Expansion

Layer / File(s) Summary
Tool Definition
src/runtime/stdio/definitions.ts
Adds new MCP tool context_expand (inputs: handle_id, budget?).
Server & Tools Runtime
src/runtime/stdio-server.ts, src/runtime/stdio/tools.ts
Session state now stores contextPackHandles, provides getContextPackHandle/setContextPackHandle with capped eviction, stores task_intent in handles, builds focused expansion payloads filtered by focus files/ranges, compiles packs with task_intent, and implements context_expand handler returning expanded pack payloads.
Tests
tests/unit/stdio-server.test.ts, tests/unit/stdio-tool-profile.test.ts
Tests updated to exercise context_expand flow, validate expanded payloads and handle usage, and include context_expand in the full MCP tool profile while blocked in core.

CLI Command & Metadata

Layer / File(s) Summary
Context Pack Command
src/infrastructure/context-pack-command.ts
runContextPackCommand builds a task plan (via buildTaskContextPlan), threads task_intent into retrieval/impact, returns plan and structured context-plane metadata, and converts impact/review bundles into ContextPlaneMetadata; dependency interfaces updated to accept optional taskIntent.
Tests
tests/unit/context-pack-command.test.ts
Tests updated to parse JSON outputs, assert task_intent and evidence recipe ids, verify analyze/retrieve calls include taskIntent, and assert target_file_type in impact tests.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

🐰 I sniffed the prompt and found intent,
Plans and packs in tidy descent,
Handles hold previews neat and small,
Coverage counts and proofs for all,
A rabbit hops — the code stands content.

✨ 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 feature/task-context-planner

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

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/runtime/context-pack.ts (1)

584-593: 💤 Low value

Minor: Inconsistent indentation in function call.

The indentation within the coverageEntriesForCandidates call is inconsistent - some arguments are indented more than others.

🔧 Suggested formatting fix
     coverage: coverageEntriesForCandidates(
-        input.task_contract,
-        materializedNodes,
-        selectedMaterialized,
-        selectedCounts,
-        {
+      input.task_contract,
+      materializedNodes,
+      selectedMaterialized,
+      selectedCounts,
+      {
         available: input.relationships?.length ?? 0,
         selected: relationships.length,
       },
     ),
🤖 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/context-pack.ts` around lines 584 - 593, The call to
coverageEntriesForCandidates has inconsistent indentation for its arguments;
reformat the invocation so all top-level arguments (input.task_contract,
materializedNodes, selectedMaterialized, selectedCounts, and the object literal)
are aligned consistently and the object literal keys (available, selected) are
indented one level inside the object; adjust the closing parentheses and comma
so they line up with the start of the function call. Ensure you modify the
coverageEntriesForCandidates(...) invocation and the object literal containing
available and selected to use consistent indentation throughout.
🤖 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/retrieve.ts`:
- Around line 454-458: The current fallback uses node.lineNumber > 0 which will
accept Infinity and fractional values; change the guard to ensure a finite
positive integer (e.g., Number.isFinite(node.lineNumber) &&
Number.isInteger(node.lineNumber) && node.lineNumber > 0) before returning
start_line/end_line so expandable_ref.line_range is only emitted for valid
integer line numbers.

---

Nitpick comments:
In `@src/runtime/context-pack.ts`:
- Around line 584-593: The call to coverageEntriesForCandidates has inconsistent
indentation for its arguments; reformat the invocation so all top-level
arguments (input.task_contract, materializedNodes, selectedMaterialized,
selectedCounts, and the object literal) are aligned consistently and the object
literal keys (available, selected) are indented one level inside the object;
adjust the closing parentheses and comma so they line up with the start of the
function call. Ensure you modify the coverageEntriesForCandidates(...)
invocation and the object literal containing available and selected to use
consistent indentation throughout.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 9b450c0f-0e48-4bd7-a07d-701738a61a97

📥 Commits

Reviewing files that changed from the base of the PR and between bb60857 and 9fea72c.

📒 Files selected for processing (23)
  • src/contracts/context-inventory.ts
  • src/contracts/context-pack.ts
  • src/contracts/task-context-plan.ts
  • src/contracts/task-intent.ts
  • src/infrastructure/benchmark.ts
  • src/infrastructure/compare.ts
  • src/infrastructure/review-compare.ts
  • src/runtime/context-inventory.ts
  • src/runtime/context-pack.ts
  • src/runtime/pr-impact.ts
  • src/runtime/retrieve.ts
  • src/runtime/stdio/tools.ts
  • src/runtime/task-context-planner.ts
  • src/runtime/task-evidence-recipes.ts
  • src/runtime/task-intent.ts
  • tests/unit/benchmark.test.ts
  • tests/unit/compare.test.ts
  • tests/unit/context-inventory.test.ts
  • tests/unit/context-pack.test.ts
  • tests/unit/retrieve.test.ts
  • tests/unit/review-compare.test.ts
  • tests/unit/task-context-planner.test.ts
  • tests/unit/task-intent.test.ts

Comment thread src/runtime/retrieve.ts Outdated
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
examples/mcp-tool-examples.md (1)

147-147: ⚡ Quick win

Consider clarifying the agent workflow description.

The updated explanation accurately describes the new fields but packs multiple concepts into one long sentence. Consider splitting it for clarity:

-**What the agent does with this:** Uses the compact pack as a coverage contract: answer with the selected evidence now, inspect `semantic_entries` to see whether implementation/structure/tests are sufficiently covered, and use the stable `handle_id` + `follow_up` metadata only when omitted context is still needed.
+**What the agent does with this:** Uses the compact pack as a coverage contract: answer with the selected evidence now and inspect `semantic_entries` to see whether implementation/structure/tests are sufficiently covered. When omitted context is still needed (e.g., `status: "missing"` in semantic_entries), use the stable `handle_id` + `follow_up` metadata to expand those specific areas.

This makes the conditional logic clearer—agents should expand when they see missing/incomplete coverage.

🤖 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 `@examples/mcp-tool-examples.md` at line 147, The sentence describing the agent
workflow is too long and combines several behaviors; rewrite it into 2–3 clear
sentences that map to the symbols in the diff: state that the agent uses the
compact pack as a coverage contract and should answer now using the selected
evidence, then say the agent must inspect semantic_entries to determine whether
implementation/structure/tests are sufficiently covered (and only expand when
coverage is missing/incomplete), and finally specify that the stable handle_id
and follow_up metadata should be used only when omitted context still needs to
be requested.
🤖 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 `@docs/proof-workflows.md`:
- Line 55: The document uses two inconsistent phrases for the same feature:
"provider/runtime proof block" and "provider/runtime proof note"; standardize to
a single term (pick either "provider/runtime proof block" or "provider/runtime
proof note") and replace all occurrences so the language is consistent (search
for the exact phrases "provider/runtime proof block" and "provider/runtime proof
note" and update them), including the mention alongside `compare` and any other
references that describe the provider/runtime proof output. Ensure the chosen
term is used everywhere in the file.
- Line 55: Split the long sentence about compare's behavior into 3–4 concise
sentences: first state that when Gemini emits structured JSON with
usageMetadata, compare records reported input and total tokens in report.json
and the terminal summary; second explain that if the runner returns only answer
text or malformed JSON, compare falls back to labeled local cl100k_base prompt
estimates; third describe that recent reports add a "provider/runtime proof"
block showing whether counts are provider-reported or local estimates plus
session-reuse accounting; and finally clarify the use case by replacing
"customer-proof" with "customer-facing proof" (or "proof for stakeholders") and
note that compare may consume paid model tokens like benchmark and eval but
saves paired answers while benchmark and eval score labeled sets.

---

Nitpick comments:
In `@examples/mcp-tool-examples.md`:
- Line 147: The sentence describing the agent workflow is too long and combines
several behaviors; rewrite it into 2–3 clear sentences that map to the symbols
in the diff: state that the agent uses the compact pack as a coverage contract
and should answer now using the selected evidence, then say the agent must
inspect semantic_entries to determine whether implementation/structure/tests are
sufficiently covered (and only expand when coverage is missing/incomplete), and
finally specify that the stable handle_id and follow_up metadata should be used
only when omitted context still needs to be requested.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: b9c4b77a-6814-4b88-809d-568e6f42888f

📥 Commits

Reviewing files that changed from the base of the PR and between 9fea72c and 6d731c2.

📒 Files selected for processing (4)
  • README.md
  • docs/proof-workflows.md
  • examples/mcp-tool-examples.md
  • examples/why-graphify.md
✅ Files skipped from review due to trivial changes (2)
  • README.md
  • examples/why-graphify.md

Comment thread docs/proof-workflows.md Outdated
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (1)
src/runtime/stdio/tools.ts (1)

760-783: 💤 Low value

Consider adding shape validation for the stored handle.

The validation at lines 770-772 confirms the stored value is a non-null object, but doesn't verify it has the expected StoredContextPackHandle shape (prompt, task, task_intent, follow_up). If a malformed object were somehow stored, buildFocusedExpansionPayload could fail with unclear errors when accessing properties.

Since handles are only stored internally via storeExpandableHandles, this is low risk, but defensive validation would improve robustness.

🤖 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 760 - 783, The stored handle
returned by getContextPackHandle needs explicit shape validation before calling
buildFocusedExpansionPayload: check that stored is an object and has the
required StoredContextPackHandle properties (e.g., prompt, task, task_intent,
follow_up) with expected types (strings or arrays as appropriate), and if
validation fails return helpers.failure(...) with a clear message; update the
case 'context_expand' block (referencing getContextPackHandle,
StoredContextPackHandle, buildFocusedExpansionPayload and
storeExpandableHandles) to perform this defensive field/type checks and only
call buildFocusedExpansionPayload when the shape is valid.
🤖 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/infrastructure/context-pack-command.ts`:
- Around line 173-183: plannerBudget is computed via Math.max(options.budget, 3)
but only used to build the plan; calls like analyzePrImpact and other
retrieve/review/impact calls still pass options.budget causing mismatch. Update
all usages of options.budget in this function (e.g., the call to
dependencies.analyzePrImpact and the top-level budget fields around
buildTaskContextPlan, the review/retrieve/impact calls referenced in the diff
ranges ~173-183, 198-223, 227-235) to use plannerBudget instead so the plan and
subsequent requests use the same normalized budget value.

In `@src/runtime/context-pack-target.ts`:
- Around line 4-13: The helper currently validates node.label with
node.label.trim().length but returns the raw label, causing downstream lookups
to fail on whitespace; update the returns to return trimmed strings: when a
directMatch is found return directMatch.label.trim(), and for bestMatch return
bestMatch.label.trim() (falling back to result.question unchanged), ensuring you
locate the logic around result.matched_nodes, directMatch, bestMatch, and
match_score.

In `@src/runtime/impact.ts`:
- Around line 313-315: compactImpactResult() currently omits the newly emitted
target_file_type field from analyzeImpact(), causing the compacted pack to drop
that metadata; update compactImpactResult() to carry target_file_type through
the compaction step by copying impact.target_file_type (when present/non-empty)
into the returned compact object's corresponding property (the pack or compact
payload builder) so the compact output stays in sync with analyzeImpact().

---

Nitpick comments:
In `@src/runtime/stdio/tools.ts`:
- Around line 760-783: The stored handle returned by getContextPackHandle needs
explicit shape validation before calling buildFocusedExpansionPayload: check
that stored is an object and has the required StoredContextPackHandle properties
(e.g., prompt, task, task_intent, follow_up) with expected types (strings or
arrays as appropriate), and if validation fails return helpers.failure(...) with
a clear message; update the case 'context_expand' block (referencing
getContextPackHandle, StoredContextPackHandle, buildFocusedExpansionPayload and
storeExpandableHandles) to perform this defensive field/type checks and only
call buildFocusedExpansionPayload when the shape is valid.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 0971da01-ea31-4fb8-a71b-9770bacff117

📥 Commits

Reviewing files that changed from the base of the PR and between 6d731c2 and 0b73d0f.

📒 Files selected for processing (16)
  • src/infrastructure/benchmark.ts
  • src/infrastructure/compare.ts
  • src/infrastructure/context-pack-command.ts
  • src/runtime/context-pack-target.ts
  • src/runtime/impact.ts
  • src/runtime/pr-impact.ts
  • src/runtime/retrieve.ts
  • src/runtime/stdio-server.ts
  • src/runtime/stdio/definitions.ts
  • src/runtime/stdio/tools.ts
  • tests/unit/benchmark.test.ts
  • tests/unit/compare.test.ts
  • tests/unit/context-pack-command.test.ts
  • tests/unit/context-pack-target.test.ts
  • tests/unit/stdio-server.test.ts
  • tests/unit/stdio-tool-profile.test.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • tests/unit/benchmark.test.ts
  • tests/unit/compare.test.ts
  • src/infrastructure/benchmark.ts
  • src/infrastructure/compare.ts

Comment thread src/infrastructure/context-pack-command.ts
Comment thread src/runtime/context-pack-target.ts Outdated
Comment thread src/runtime/impact.ts
mohanagy and others added 3 commits May 8, 2026 18:22
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
tests/unit/stdio-server.test.ts (1)

919-929: ⚡ Quick win

Assert expandable handle presence before dereferencing it

explainPackPayload.expandable[0].handle_id is used before any shape assertion, so regressions can fail with a generic TypeError instead of a clear expectation failure.

Suggested change
 const explainPackPayload = JSON.parse((explainPack?.result as { content: Array<{ text: string }> }).content[0]!.text)
+expect(explainPackPayload.expandable).toEqual(
+  expect.arrayContaining([expect.objectContaining({ handle_id: expect.any(String) })]),
+)
+const explainHandleId = explainPackPayload.expandable[0]!.handle_id
 const expandedPack = await Promise.resolve(handleStdioRequest(graphPath, {
   id: 12,
   method: 'tools/call',
   params: {
     name: 'context_expand',
     arguments: {
-      handle_id: explainPackPayload.expandable[0].handle_id,
+      handle_id: explainHandleId,
     },
   },
 }, sessionState))
🤖 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 `@tests/unit/stdio-server.test.ts` around lines 919 - 929, The test
dereferences explainPackPayload.expandable[0].handle_id without asserting the
shape; update the test to first assert that explainPackPayload.expandable is an
array with length > 0 and that explainPackPayload.expandable[0] has a defined
handle_id before calling handleStdioRequest; locate the variables
explainPackPayload and the subsequent call to handleStdioRequest(graphPath, {
id: 12, method: 'tools/call', params: { name: 'context_expand', arguments: {
handle_id: ... } } }, sessionState) and add an explicit expectation (e.g.,
expect(Array.isArray(...)) and expect(...[0].handle_id).toBeDefined()) so
failures produce clear assertion messages instead of a TypeError.
src/runtime/retrieve.ts (1)

1096-1104: 💤 Low value

Consider simplifying the IIFE pattern.

The inline IIFE for conditionally spreading line_range works but is slightly harder to read. A local variable would be cleaner.

♻️ Optional simplification
       expandable_ref: {
         node_id: node.id,
         label: node.label,
         source_file: relativizeSourceFile(node.sourceFile, rootPath),
-        ...(() => {
-          const lineRange = expandableLineRange(node)
-          return lineRange ? { line_range: lineRange } : {}
-        })(),
+        ...(expandableLineRange(node) ? { line_range: expandableLineRange(node) } : {}),
       },

Or compute once:

const lineRange = expandableLineRange(node)
// then in expandable_ref:
...(lineRange ? { line_range: lineRange } : {}),
🤖 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/retrieve.ts` around lines 1096 - 1104, The inline IIFE inside the
expandable_ref object is unnecessary and reduces readability; compute const
lineRange = expandableLineRange(node) before constructing the object (near where
expandable_ref is built) and then conditionally spread ...(lineRange ? {
line_range: lineRange } : {}) into the expandable_ref instead of using the
immediate function; keep other fields (node_id, label, source_file using
relativizeSourceFile(node.sourceFile, rootPath)) unchanged.
🤖 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.

Nitpick comments:
In `@src/runtime/retrieve.ts`:
- Around line 1096-1104: The inline IIFE inside the expandable_ref object is
unnecessary and reduces readability; compute const lineRange =
expandableLineRange(node) before constructing the object (near where
expandable_ref is built) and then conditionally spread ...(lineRange ? {
line_range: lineRange } : {}) into the expandable_ref instead of using the
immediate function; keep other fields (node_id, label, source_file using
relativizeSourceFile(node.sourceFile, rootPath)) unchanged.

In `@tests/unit/stdio-server.test.ts`:
- Around line 919-929: The test dereferences
explainPackPayload.expandable[0].handle_id without asserting the shape; update
the test to first assert that explainPackPayload.expandable is an array with
length > 0 and that explainPackPayload.expandable[0] has a defined handle_id
before calling handleStdioRequest; locate the variables explainPackPayload and
the subsequent call to handleStdioRequest(graphPath, { id: 12, method:
'tools/call', params: { name: 'context_expand', arguments: { handle_id: ... } }
}, sessionState) and add an explicit expectation (e.g.,
expect(Array.isArray(...)) and expect(...[0].handle_id).toBeDefined()) so
failures produce clear assertion messages instead of a TypeError.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: d2be88c3-5fe0-42d5-b847-07d327524cfd

📥 Commits

Reviewing files that changed from the base of the PR and between 61e9716 and 64fa00a.

📒 Files selected for processing (14)
  • docs/proof-workflows.md
  • examples/mcp-tool-examples.md
  • src/infrastructure/context-pack-command.ts
  • src/runtime/context-pack-target.ts
  • src/runtime/context-pack.ts
  • src/runtime/impact.ts
  • src/runtime/retrieve.ts
  • src/runtime/stdio/tools.ts
  • tests/unit/context-pack-command.test.ts
  • tests/unit/context-pack-target.test.ts
  • tests/unit/impact.test.ts
  • tests/unit/retrieve.test.ts
  • tests/unit/stdio-server.test.ts
  • tests/unit/why-graphify-doc.test.ts
✅ Files skipped from review due to trivial changes (1)
  • tests/unit/impact.test.ts
🚧 Files skipped from review as they are similar to previous changes (7)
  • tests/unit/context-pack-target.test.ts
  • tests/unit/retrieve.test.ts
  • src/runtime/context-pack-target.ts
  • examples/mcp-tool-examples.md
  • docs/proof-workflows.md
  • src/runtime/stdio/tools.ts
  • src/runtime/context-pack.ts

@mohanagy mohanagy merged commit 90f1f04 into main May 8, 2026
7 checks passed
@mohanagy mohanagy mentioned this pull request May 8, 2026
4 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