Skip to content

feat: add pack governance receipts - #448

Merged
mohanagy merged 4 commits into
nextfrom
issue-434-agent-governance
Jun 1, 2026
Merged

mohanagy merged 4 commits into
nextfrom
issue-434-agent-governance

Conversation

@mohanagy

@mohanagy mohanagy commented Jun 1, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • add versioned, source-safe governance receipts to CLI pack JSON and MCP context_pack responses
  • summarize graph freshness, agent directives, follow-up expansion metadata, and MCP cache/delta state without exposing prompts, source content, or file paths
  • add regression coverage and agent governance documentation for audit-review workflows

Verification

  • npm run typecheck
  • npm run build
  • CI=1 npm run test:run

Closes #434

Summary by CodeRabbit

  • New Features

    • Context pack outputs (CLI and API) now include a versioned, source-safe governance receipt with graph freshness, request/task metadata, directive/coverage summary, follow-up expansion summary, and cache/MCP call status (delta-session hash when applicable).
    • Cached explain responses are rewrapped to reflect updated cache status.
  • Privacy

    • Receipts exclude sensitive content (prompts, answers, source snippets, file paths, confidence reasons, workflow owners).
  • Documentation

    • Added governance docs describing receipt fields and audit guidance.
  • Tests

    • Added/updated tests validating receipt emission, cache behavior, and delta flows.

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

coderabbitai Bot commented Jun 1, 2026 •

Copy link
Copy Markdown

Review Change Stack

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: e50807dc-0d8a-4bc5-8fb9-c822eb8b358a

📥 Commits

Reviewing files that changed from the base of the PR and between 72cee72 and 48228ac.

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

📝 Walkthrough

Walkthrough

This PR implements source-safe governance receipts for context-pack JSON outputs, adding a versioned receipt (v1) with graph freshness, request/task metadata, directive/coverage summary, follow-up expansion summaries, and optional MCP call cache/delta metadata while excluding prompts, answers, source snippets, and file paths.

Changes

Governance Receipt Implementation

Layer / File(s) Summary
Governance contract and documentation
src/contracts/context-pack.ts, docs/agent-governance.md, tests/unit/agent-governance-doc.test.ts, tests/unit/answer-ready-explain-pack.test.ts, tests/unit/handoff-command.test.ts
New ContextPackGovernanceReceipt types and docs define versioned receipts with surface, privacy boundary, graph freshness, request, directive/coverage, and follow-up metadata; tests and fixtures updated to include governance.
Governance receipt building
src/runtime/context-pack-governance.ts
buildContextPackGovernanceReceipt assembles receipts from inputs, computes truncated SHA-256 delta session hashes when present, and derives follow-up summary counts from expandable refs.
Answer-ready pack trimming with governance integration
src/infrastructure/context-pack-command.ts, tests/unit/context-pack-command.test.ts
Extends answer-ready compaction with selection-diagnostics-aware node culling, promotes primary-path previews into expandable entries, performs governance field compaction/CLI trimming, and injects a compact governance receipt into buildPackSchemaV1 outputs.
MCP/CLI context-pack handler governance wrapping
src/runtime/stdio/tools.ts, tests/unit/stdio-slice-surface.test.ts
Introduces withContextPackGovernance and withUpdatedContextPackGovernanceCacheStatus, wraps cached, review, impact, delta, and non-delta context_pack responses with governance receipts, updates cache-status handling, computes evidence (coverage/workflow owners), and handles delta session hashing.
Governance flow test coverage
tests/unit/handoff-command.test.ts, tests/unit/stdio-slice-surface.test.ts, tests/unit/context-pack-command.test.ts
Adds tests asserting cache miss/hit/bypass semantics, delta session hash format, privacy boundary exclusions (no prompt/paths/delta id), and updates fixtures to include pack.governance in handoff/answer-ready tests.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • mohanagy/madar#380: Modifies context pack JSON shaping and handler wrapping; overlaps with governance wrapping and pack shaping changes.
  • mohanagy/madar#302: Related contract/schema edits to ContextPackSchemaV1 that intersect with adding a governance section.
  • mohanagy/madar#355: Changes to evidence/agent_directive plumbing used by governance receipts and compaction.

Poem

🐰 I hopped through packs to leave a tiny trace,

A hashed little token—keeps the source in place;
No prompts, no snippets, just freshness and cues,
Directives and counts in a tidy, safe fuse;
A rabbit’s nod to audits—quiet and true.

🚥 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 'feat: add pack governance receipts' accurately describes the main feature addition of versioned governance receipts to pack outputs.
Description check ✅ Passed The PR description includes all required template sections: summary of changes, verification commands, and related issue reference; documentation updates and test coverage are properly noted.
Linked Issues check ✅ Passed The PR fulfills all acceptance criteria from issue #434: implements an audit envelope with governance receipts, maintains source-safety by excluding prompts/source/answers, adds documentation and comprehensive test coverage.
Out of Scope Changes check ✅ Passed All changes are directly aligned with implementing governance receipts: contract definitions, runtime implementation, CLI/MCP integration, documentation, and regression tests; no unrelated modifications 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-434-agent-governance

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)

242-252: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Cache validator allows governance-less payloads on cache hits

isCachedExplainContextPackPayload does not validate governance, so stale pre-governance cache entries can still be served (Line 1209 onward), bypassing the new receipt contract.

Proposed fix
 function isCachedExplainContextPackPayload(value: unknown): value is CachedExplainContextPackPayload {
@@
   const candidate = value as Record<string, unknown>
+  const governance = candidate.governance
+  const mcpCall = governance && typeof governance === 'object' && !Array.isArray(governance)
+    ? (governance as Record<string, unknown>).mcp_call
+    : null
   return candidate.task === 'explain'
     && typeof candidate.prompt === 'string'
     && typeof candidate.task_intent === 'string'
     && Array.isArray(candidate.expandable)
     && candidate.expandable.every((entry) => isContextPackExpandableRef(entry))
+    && !!governance
+    && typeof governance === 'object'
+    && !Array.isArray(governance)
+    && !!mcpCall
+    && typeof mcpCall === 'object'
+    && !Array.isArray(mcpCall)
 }

Also applies to: 1209-1222

🤖 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 242 - 252, The cache validator is
missing governance validation: modify isCachedExplainContextPackPayload to
require and validate candidate.governance (e.g., ensure candidate.governance is
a non-null object and either pass it through an existing helper like
isGovernanceReceipt/isValidGovernanceReceipt or explicitly check the governance
receipt fields required by the new receipt contract), and return false if
governance is absent/invalid; apply the same governance check to the other copy
of this validator used elsewhere so stale pre-governance cache entries cannot be
served.
🤖 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/contracts/context-pack.ts`:
- Line 520: The new required field `governance: ContextPackGovernanceReceipt`
breaks schema v1 compatibility; either make `governance` optional in the
ContextPack type (change to `governance?: ContextPackGovernanceReceipt`) so
existing v1 artifacts remain valid, or bump the schema version (increment
`schema_version` to 2 and update any migration/versioning docs/tests) to signal
a breaking wire-format change; update the declaration in
src/contracts/context-pack.ts (the ContextPack/interface where `governance` is
defined) and ensure tests/consumers reflect the chosen approach.

In `@src/infrastructure/context-pack-command.ts`:
- Around line 598-601: The code currently removes governance metadata for the
CLI-ready path by deleting governance.request when surface === 'cli_pack' and
later deleting payload.governance, which strips receipts; to fix, stop removing
governance.request in the 'cli_pack' branch and avoid deleting
payload.governance for CLI outputs (only remove truly sensitive fields if
needed). Locate the branch that checks surface === 'cli_pack' and the later code
that deletes payload.governance and remove or guard those deletions so
governance.request and payload.governance are preserved for CLI JSON output (use
trimmedFields only for fields you still want to hide, and keep receipts intact),
leaving the request.budget check logic unchanged.
- Around line 958-965: The buildAnswerReadyPackSchema flow never calls
enforceAnswerReadyBudget, so selection-based node-culling isn't applied; update
the return path in buildAnswerReadyPackSchema to invoke
enforceAnswerReadyBudget(payload, maxTokens, trimmedFields) (using the same
payload/maxTokens/trimmedFields symbols) before finalizing the payload and
attaching/returning the serialized budget; ensure you still call
attachSerializedBudget after enforcement and then return the payload so
_selectionDiagnostics and node-culling take effect.

---

Outside diff comments:
In `@src/runtime/stdio/tools.ts`:
- Around line 242-252: The cache validator is missing governance validation:
modify isCachedExplainContextPackPayload to require and validate
candidate.governance (e.g., ensure candidate.governance is a non-null object and
either pass it through an existing helper like
isGovernanceReceipt/isValidGovernanceReceipt or explicitly check the governance
receipt fields required by the new receipt contract), and return false if
governance is absent/invalid; apply the same governance check to the other copy
of this validator used elsewhere so stale pre-governance cache entries cannot be
served.
🪄 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: b6dc4b57-32a2-4242-9998-2299f1cfa994

📥 Commits

Reviewing files that changed from the base of the PR and between 249843e and 0ccaae8.

📒 Files selected for processing (10)
  • docs/agent-governance.md
  • src/contracts/context-pack.ts
  • src/infrastructure/context-pack-command.ts
  • src/runtime/context-pack-governance.ts
  • src/runtime/stdio/tools.ts
  • tests/unit/agent-governance-doc.test.ts
  • tests/unit/answer-ready-explain-pack.test.ts
  • tests/unit/context-pack-command.test.ts
  • tests/unit/handoff-command.test.ts
  • tests/unit/stdio-slice-surface.test.ts

Comment thread src/contracts/context-pack.ts Resolved
mohanagy and others added 2 commits June 1, 2026 06:02
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

@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: 1

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)

251-261: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Redacted answer-ready packs will self-invalidates in cache.

buildAnswerReadyPackSchema(...) can remove top-level prompt and task_intent to stay source-safe, but this validator still requires both and the cache-hit path uses them to rebuild expandable handles. Any explain pack that crosses that trim threshold will be cached once, then treated as malformed and evicted on the next read.

Cache an internal envelope that keeps the handle-restoration metadata out-of-band, or skip caching redacted answer-ready payloads entirely.

🤖 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 300-315: The current logic removes governance.request.task_intent
and governance.request.retrieval_strategy whenever surface === 'cli_pack',
stripping audit metadata; change the conditions so that request.task_intent and
request.retrieval_strategy are not deleted for the CLI governance receipt (i.e.,
only delete these fields for non-cli_pack surfaces), and likewise avoid removing
request.resolution/task_intent here if those are meant to be preserved for later
cleanup (reference variables: surface, request, trimmedFields and the blocks
that delete task_intent, retrieval_strategy, and resolution).
🪄 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: b5607ba8-e343-4dde-8454-4ac645635b21

📥 Commits

Reviewing files that changed from the base of the PR and between 709d229 and 72cee72.

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

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@mohanagy
mohanagy merged commit 56074fa into next Jun 1, 2026
7 checks passed
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