Skip to content

Harden SDK context integrity, merge safety, and agent-efficient output - #783

Merged
unbraind merged 2 commits into
mainfrom
feat/sdk-context-integrity-primitives
Jul 28, 2026
Merged

unbraind merged 2 commits into
mainfrom
feat/sdk-context-integrity-primitives

Conversation

@unbraind

@unbraind unbraind commented Jul 27, 2026 •

Copy link
Copy Markdown
Owner

Summary

This broad SDK and CLI bundle strengthens project management = context management across merge safety, history integrity, extension authoring, agent-token efficiency, and fresh-clone governance.

  • generalizes the generated PM JSON merge fence to every nested tracker JSON document
  • conservatively reconciles independent additive JSON array changes while preserving conflict semantics for removals and edits
  • recognizes portable, package-owned merge drivers without trusting lookalike executables
  • invalidates history drift and derived item-metadata caches across append, rewrite, rollback, and bulk repair boundaries
  • makes bulk repair source-authoritative so stale indexes cannot manufacture integrity failures
  • shrinks lean structured output to decision-relevant data while retaining actionable pagination
  • preserves legacy output override compatibility and exports ServiceOverrideDecision for SDK authors
  • distinguishes required tracker structure from optional empty type folders in fresh-clone health
  • documents the contracts and regenerates the package-owned changelog with pm-changelog 2026.7.27

Why

Parallel agents need PM state to merge semantically across branches and clones, integrity checks must reflect the current source of truth immediately after mutation, and SDK extension authors need explicit typed ownership contracts. Agent-facing reads also need to spend context on project decisions instead of derivable request echoes.

PM lineage

Verification

  • pnpm lint
  • pnpm typecheck
  • pnpm contracts:check
  • docs/skills, context-evaluation, secret, dependency, and package-boundary gates
  • pnpm changelog:pm:check
  • pm health --check-only --skip-vectors --brief with zero warnings
  • pm validate --check-history-drift with zero drift
  • full sandboxed coverage: 380 files and 6,436 tests, exactly 100% statements/branches/functions/lines
  • fresh unrelated packed consumer: package-owned CLI resolution, npm/npx/bunx execution, lifecycle commands, lean output, health, validation, merge installation, and a real two-branch managed-extension merge

Dependency and security disposition

  • pnpm audit reports zero vulnerabilities
  • GitHub vulnerability and security alert inventories were empty at orientation
  • @sentry/node 10.68.0 was evaluated and rejected because its transitive declaration graph fails the mandatory packed TypeScript consumer boundary; 10.67.0 remains the latest compatible version
  • Node-floor-incompatible npm-package-arg 14 and the TypeScript 7 ecosystem transition remain linked to their canonical PM deferrals

Summary by Sourcery

Strengthen merge safety, history-drift cache invalidation, SDK service override contracts, and lean CLI JSON output, while generalizing JSON merge fences and updating health semantics and documentation.

Bug Fixes:

  • Ensure derived history drift caches are invalidated after history appends, rewrites, rollbacks, and bulk repairs.
  • Treat empty item-type directories as optional and warn only under strict directory health checks.
  • Accept portable, package-owned merge driver commands without trusting arbitrary executables, and continue flagging malformed or stale definitions.
  • Preserve output service-override compatibility by formalizing decisions, treating legacy payload echoes as safe declines with deprecation warnings, and exporting the decision type for SDK authors.
  • Compact lean JSON output to omit CLI request echoes and inactive pagination metadata while keeping actionable cursors.
  • Extend JSON merge fences and drivers to cover all nested authoritative JSON documents and conservatively compose additive JSON arrays without masking edit/removal conflicts.

Enhancements:

  • Add SDK-level tests for context-integrity primitives across merge behavior, health checks, output formatting, and merge driver configuration.
  • Document new SDK contracts for lean envelopes, service overrides, history/cache coherence, and fresh-clone directory semantics, and update merge safety documentation to cover generalized JSON fences and portable drivers.

Documentation:

  • Update SDK and merge safety documentation to describe lean JSON envelopes, service override decisions, mutation-aware drift-cache invalidation, fresh-clone directory semantics, and generalized JSON merge fences.

Tests:

  • Introduce comprehensive unit tests for SDK and CLI context integrity, including JSON merge semantics, managed-extension merges, lean output projection, history drift cache invalidation, directory health, and portable merge drivers.

Chores:

  • Regenerate PM agents, issues, histories, and changelog entries to track the new merge, cache, output, and dependency evaluation work.
  • Record evaluation of Sentry 10.68.0 compatibility and retain 10.67.0 as the supported version.

Summary by cubic

Hardens SDK/CLI merge safety, history integrity, and agent-friendly output. Adds full JSON fence coverage, portable merge drivers, lean reads, mutation-aware cache invalidation, clearer fresh-clone health, and stricter reconcile previews.

  • New Features

    • Generalized PM JSON merge fence to .agents/pm/**/*.json; .managed-extensions.json now uses pm-json.
    • Recognizes portable, package-owned merge drivers and installs stable commands; health audits identity without trusting paths.
    • Adds conservative three-way reconciliation for additive JSON arrays; preserves multiplicity and keeps conflicts for edits/removals.
    • Lean JSON reads omit filters, projection, sorting, now; include next_cursor only when paginating.
    • Exports ServiceOverrideDecision; treats legacy output_format payload echo as a safe decline with a deprecation warning.
    • Invalidates history drift cache on append/rewrite/rollback and bulk repair; runs before optional index work, surfaces non-missing cache failures, and forces source scans during bulk repair to avoid stale indexes.
    • Merge-reconcile dry-run now fails closed on drift, pending receipts, or non-green validation.
    • Fresh-clone health distinguishes required tracker structure from optional empty type folders and guards against custom-folder collisions.
  • Dependencies

    • Evaluated @sentry/node 10.68.0 and retained 10.67.0 due to packed TypeScript consumer boundary failure.
    • pnpm audit reports zero vulnerabilities.

Written for commit 613278d. Summary will update on new commits.

Review in cubic

Generalize the PM JSON merge fence, reconcile conservative additive arrays, and recognize portable package-owned merge drivers. Invalidate drift and metadata caches across authoritative history mutations, tighten lean output and service override contracts, and make fresh-clone health distinguish required structure from optional type folders. Add exact regression, manual consumer, PM lineage, SDK documentation, and generated changelog evidence.
@unbraind
unbraind marked this pull request as ready for review July 27, 2026 23:36

@sourcery-ai sourcery-ai 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.

Sorry @unbraind, you have reached your weekly rate limit of 500000 diff characters.

Please try again later or upgrade to continue using Sourcery

@unbraind

Copy link
Copy Markdown
Owner Author

@greptileai please review this complete SDK/CLI context-integrity bundle.

@unbraind

Copy link
Copy Markdown
Owner Author

@coderabbitai full review

@gemini-code-assist

Copy link
Copy Markdown

Caution

The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased.

1 similar comment
@gemini-code-assist

Copy link
Copy Markdown

Caution

The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased.

@coderabbitai

coderabbitai Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
✅ Action performed

Full review finished.


Your included review limit is currently reached under our Fair Usage Limits Policy. This review may still proceed through usage-based billing if eligible. Your next included review will be available in 59 minutes.

@coderabbitai

coderabbitai Bot commented Jul 27, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@unbraind, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 17 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Repository UI (base), Organization UI (inherited)

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 339b8aa5-0072-4326-8a9c-66cc8c2c98f0

📥 Commits

Reviewing files that changed from the base of the PR and between 9949042 and 613278d.

📒 Files selected for processing (42)
  • .agents/pm/chores/pm-e9zh.toon
  • .agents/pm/chores/pm-r31390.toon
  • .agents/pm/extensions/.managed-extensions.json
  • .agents/pm/history/pm-ajaskl.jsonl
  • .agents/pm/history/pm-e9zh.jsonl
  • .agents/pm/history/pm-gjicmx.jsonl
  • .agents/pm/history/pm-oi4zs3.jsonl
  • .agents/pm/history/pm-r31390.jsonl
  • .agents/pm/history/pm-u2tqn6.jsonl
  • .agents/pm/history/pm-w91mvg.jsonl
  • .agents/pm/history/pm-xyuhh7.jsonl
  • .agents/pm/history/pm-ysqb6n.jsonl
  • .agents/pm/issues/pm-ajaskl.toon
  • .agents/pm/issues/pm-gjicmx.toon
  • .agents/pm/issues/pm-oi4zs3.toon
  • .agents/pm/issues/pm-u2tqn6.toon
  • .agents/pm/issues/pm-w91mvg.toon
  • .agents/pm/issues/pm-xyuhh7.toon
  • .agents/pm/issues/pm-ysqb6n.toon
  • .gitattributes
  • CHANGELOG.md
  • docs/MERGE_SAFETY.md
  • docs/SDK.md
  • sdk/public-surface.json
  • src/core/extensions/extension-hook-runtime.ts
  • src/core/history/drift-cache.ts
  • src/core/history/history-rewrite.ts
  • src/core/history/history.ts
  • src/core/output/output.ts
  • src/core/store/item-store.ts
  • src/sdk/authoring.ts
  • src/sdk/governance/health.ts
  • src/sdk/history-repair.ts
  • src/sdk/merge/install.ts
  • src/sdk/merge/reconcile.ts
  • src/sdk/merge/three-way.ts
  • tests/unit/commands/history-repair-command.spec.ts
  • tests/unit/commands/init-command.spec.ts
  • tests/unit/commands/merge-reconcile-command.spec.ts
  • tests/unit/core/history/history-append-overrides.spec.ts
  • tests/unit/sdk/context-integrity-primitives.spec.ts
  • tests/unit/sdk/merge-reconcile.spec.ts
📝 Walkthrough

Walkthrough

This PR updates merge safety, JSON output contracts, history drift-cache invalidation, directory health classification, regression tests, documentation, changelog entries, and project-management records.

Changes

Merge safety and JSON reconciliation

Layer / File(s) Summary
Merge fencing and reconciliation
.gitattributes, src/sdk/merge/*, docs/MERGE_SAFETY.md
Nested tracker JSON receives merge-driver coverage, portable installed CLI commands are validated, and qualifying additive arrays are composed during three-way merges.
Merge validation and records
tests/unit/sdk/context-integrity-primitives.spec.ts, .agents/pm/history/*, CHANGELOG.md
Merge behavior, branch composition, and portable-driver auditing are covered by tests and documented in project records.

Output and extension contracts

Layer / File(s) Summary
Service override compatibility
src/core/extensions/extension-hook-runtime.ts, src/core/output/output.ts, src/sdk/authoring.ts, sdk/public-surface.json
ServiceOverrideDecision is exported, while legacy payload echoes decline with deprecation warnings.
Lean JSON projection
src/core/output/output.ts, docs/SDK.md, tests/unit/sdk/context-integrity-primitives.spec.ts
Lean read envelopes omit request echoes and inactive cursors while preserving non-read payloads.

History and health integrity

Layer / File(s) Summary
History drift-cache invalidation
src/core/history/*, src/sdk/history-repair.ts, src/core/store/item-store.ts
History append, rewrite, rollback, and non-dry-run bulk repair paths invalidate derived drift-cache data and can force source scans.
Directory health semantics
src/sdk/governance/health.ts, tests/unit/commands/init-command.spec.ts, tests/unit/sdk/context-integrity-primitives.spec.ts
Registered item-type folders are optional on fresh clones in normal mode and remain warnings under strict checks.

Project-management records

Layer / File(s) Summary
Validation and compatibility records
.agents/pm/{chores,history,issues}/*, .agents/pm/extensions/.managed-extensions.json, CHANGELOG.md
Project records document drift validation, compatibility retention, issue closure metadata, and updated validation evidence.

Estimated code review effort: 4 (Complex) | ~60 minutes

Possibly related issues

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 46.88% 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
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title is concise and accurately summarizes the PR’s main focus on SDK context integrity, merge safety, and output efficiency.
Description check ✅ Passed The description is clearly aligned with the changeset and covers the major implemented and documented behaviors.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@sourcery-ai

sourcery-ai Bot commented Jul 27, 2026

Copy link
Copy Markdown

Reviewer's Guide

Strengthens merge/context integrity and SDK contracts by generalizing JSON merge fencing and drivers, adding additive-array JSON semantics, tightening portable merge-driver validation, invalidating history drift caches on all mutations, making bulk history repair source-authoritative, refining health directory requirements, introducing lean JSON read envelopes, and formalizing service override decisions and compatibility, with tests and docs updated accordingly.

Sequence diagram for history mutations invalidating the drift cache

sequenceDiagram
  participant HistoryClient as appendHistoryEntry
  participant HistoryRewrite as writeHistoryRawWithRollback
  participant HistoryRepair as runHistoryRepairAll
  participant DriftCachePath as invalidateHistoryDriftCacheForPath
  participant DriftCacheRoot as invalidateHistoryDriftCache

  HistoryClient->>HistoryClient: appendLineAtomic
  HistoryClient->>DriftCachePath: invalidateHistoryDriftCacheForPath(historyPath)
  DriftCachePath->>DriftCacheRoot: invalidateHistoryDriftCache(pmRoot)

  HistoryRewrite->>HistoryRewrite: writeHistoryRaw
  HistoryRewrite->>DriftCachePath: invalidateHistoryDriftCacheForPath(historyPath)
  DriftCachePath->>DriftCacheRoot: invalidateHistoryDriftCache(pmRoot)

  HistoryRepair->>HistoryRepair: listAllItemMetadataWithBody(forceSourceScan true)
  HistoryRepair->>HistoryRepair: scanHistoryDrift
  HistoryRepair-->>HistoryRepair: apply history repairs
  HistoryRepair-->>DriftCacheRoot: invalidateHistoryDriftCache(pmRoot)
Loading

Sequence diagram for service override decisions and lean JSON output

sequenceDiagram
  actor User
  participant Output as formatEffectiveOutput
  participant ServiceOverride as runActiveServiceOverrideSync
  participant HookRuntime as runServiceOverrideSync
  participant Extension as extension_service_override

  User->>Output: formatEffectiveOutput(effectiveResult, options)
  Output->>Output: resolveOutputFormat
  Output->>ServiceOverride: runActiveServiceOverrideSync(output_format, context)
  ServiceOverride->>HookRuntime: runServiceOverrideSync(services, context)
  HookRuntime->>Extension: extension_service_override(serviceContext)
  Extension-->>HookRuntime: ServiceOverrideDecision
  HookRuntime-->>ServiceOverride: ServiceOverrideDecision
  ServiceOverride-->>Output: { handled, result, warnings }
  Output->>Output: projectLeanJsonValue when options.lean
  Output-->>User: JSON string
Loading

Sequence diagram for portable merge driver configuration audit

sequenceDiagram
  participant Audit as auditMergeDriverConfiguration
  participant Git as git_config
  participant Portable as isPortableMergeDriverCommand
  participant Reader as readSingleQuotedArgument
  participant Fs as pathExists

  Audit->>Git: execFileAsync(git, config --get merge.*.driver)
  Git-->>Audit: configured driver
  Audit->>Audit: build expectedSuffix
  Audit->>Portable: isPortableMergeDriverCommand(configured, expectedSuffix)
  Portable->>Reader: readSingleQuotedArgument(configured, 0)
  Portable->>Reader: readSingleQuotedArgument(configured, nodeOffset)
  Portable->>Fs: pathExists(nodeArgument.value)
  Portable->>Fs: pathExists(cliArgument.value)
  Portable-->>Audit: boolean
  Audit-->>Audit: record driftedKeys when portable check fails
Loading

File-Level Changes

Change Details Files
Add additive-aware JSON merge behavior and extend merge fencing to all nested tracker JSON documents.
  • Extract object merge into a reusable helper and add mergeAdditiveJsonArrays to compose JSON arrays when both branches preserve all base entries and only add elements.
  • Update mergeJsonValue to try additive-array merging first, then object merging, falling back to scalar three-way semantics while tracking conflict and paths-from-theirs.
  • Broaden buildMergeAttributePatterns to fence all nested JSON documents with a **/*.json rule and document the new coverage and pm-json array semantics in MERGE_SAFETY.md.
src/sdk/merge/three-way.ts
src/sdk/merge/install.ts
docs/MERGE_SAFETY.md
.gitattributes
tests/unit/sdk/context-integrity-primitives.spec.ts
Harden portable merge-driver identity while accepting valid relocated @unbrained/pm-cli installations.
  • Introduce readSingleQuotedArgument and isPortableMergeDriverCommand to parse git merge.driver commands, validate node and cli.js locations, and confirm they belong to an @unbrained/pm-cli package that owns the pm bin.
  • Change auditMergeDriverConfiguration to compare configured commands against either the exact expected string or a semantically equivalent portable invocation and report drift otherwise.
  • Add tests that rewrite merge.driver config to various valid and invalid portable commands and assert audit behavior.
src/sdk/merge/install.ts
docs/MERGE_SAFETY.md
tests/unit/sdk/context-integrity-primitives.spec.ts
Introduce history drift-cache invalidation and make history repair source-authoritative across append, rewrite, rollback, and bulk repair flows.
  • Add core/history/drift-cache.ts with helpers to remove the history-drift-cache.json file globally or by conventional history path.
  • Wire invalidateHistoryDriftCacheForPath into appendHistoryEntry and writeHistoryRawWithRollback so any history write or rollback invalidates derived drift state without affecting committed mutations.
  • Update listAllItemMetadataWithBody and runHistoryRepairAll to force source scans during bulk repair and clear the drift cache on successful non-dry-run repairs; extend history-repair tests to assert cache deletion semantics.
src/core/history/drift-cache.ts
src/core/history/history.ts
src/core/history/history-rewrite.ts
src/core/store/item-store.ts
src/sdk/history-repair.ts
tests/unit/commands/history-repair-command.spec.ts
tests/unit/sdk/context-integrity-primitives.spec.ts
Refine health directory semantics to treat core tracker dirs as required and type folders as optional/strict-only, and validate pending receipts.
  • Change resolveHealthDirectoryLists to always require core tracker directories but treat all registered type folders as optional by default, only warning when strictDirectories is enabled.
  • Adjust init and health tests to expect ok status with missing_optional entries for absent type folders on fresh clones and warn when strictDirectories is true.
  • Extend MERGE_SAFETY and SDK docs to describe fresh-clone directory semantics and pending receipt validation contracts.
src/sdk/governance/health.ts
tests/unit/commands/init-command.spec.ts
docs/SDK.md
docs/MERGE_SAFETY.md
tests/unit/sdk/context-integrity-primitives.spec.ts
Make JSON output leaner for list-like envelopes while preserving full SDK results and pagination actionability.
  • Add LEAN_READ_ENVELOPE_ECHO_KEYS and projectLeanJsonValue to compact values via compactToonValue, strip request-echo keys from list envelopes, and drop next_cursor when has_more is not true.
  • Update formatEffectiveOutput to apply projectLeanJsonValue when options.lean is true and ensure defaults for native-output service overrides include an empty warnings array.
  • Add tests covering lean envelope projection, pagination behavior, and non-envelope passthrough.
src/core/output/output.ts
docs/SDK.md
tests/unit/sdk/context-integrity-primitives.spec.ts
Formalize service override decisions, preserve legacy output_format compatibility, and surface deprecations for payload echoes.
  • Export ServiceOverrideDecision from sdk/authoring and recommend explicit { handled, result } / { handled: false } decisions in SDK docs, updating guidance to use declineServiceOverride rather than returning the payload.
  • Introduce isLegacyOutputPayloadEcho and wire it into runServiceOverrideSync and runServiceOverride to convert output_format payload echoes into declined overrides plus structured warnings.
  • Teach formatEffectiveOutput to surface extension_output_format_payload_echo_deprecated warnings as stderr messages while continuing to fall back to native JSON/toon formatting; update docs and tests accordingly.
src/sdk/authoring.ts
src/core/extensions/extension-hook-runtime.ts
src/core/output/output.ts
docs/SDK.md
tests/unit/sdk/context-integrity-primitives.spec.ts
sdk/public-surface.json
Update changelog, PM lineage artifacts, and Sentry evaluation metadata to reflect new contracts and compatibility decisions.
  • Append new Fixed and Other entries to CHANGELOG.md for merge fencing, portable merge drivers, drift/cache invalidation, lean output, service override compatibility, fresh-clone semantics, pending receipt validation, and Sentry 10.68 evaluation.
  • Add or update .agents/pm history and issue records for the new PM tasks and chores, including pm-gjicmx, pm-w91mvg, pm-ajaskl, pm-ysqb6n, pm-xyuhh7, pm-u2tqn6, pm-oi4zs3, and pm-r31390.
  • Ensure .gitattributes and related artifacts stay in sync with the broadened merge fence.
CHANGELOG.md
.agents/pm/issues/pm-gjicmx.toon
.agents/pm/issues/pm-w91mvg.toon
.agents/pm/issues/pm-ajaskl.toon
.agents/pm/issues/pm-ysqb6n.toon
.agents/pm/issues/pm-xyuhh7.toon
.agents/pm/issues/pm-u2tqn6.toon
.agents/pm/issues/pm-oi4zs3.toon
.agents/pm/chores/pm-r31390.toon
.agents/pm/history/pm-gjicmx.jsonl
.agents/pm/history/pm-w91mvg.jsonl
.agents/pm/history/pm-ajaskl.jsonl
.agents/pm/history/pm-ysqb6n.jsonl
.agents/pm/history/pm-xyuhh7.jsonl
.agents/pm/history/pm-u2tqn6.jsonl
.agents/pm/history/pm-oi4zs3.jsonl
.agents/pm/history/pm-r31390.jsonl
.agents/pm/chores/pm-e9zh.toon
.agents/pm/extensions/.managed-extensions.json
.gitattributes

Possibly linked issues

  • #unknown: PR widens buildMergeAttributePatterns to **/*.json and adds tests, protecting .managed-extensions.json as requested.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@codspeed

codspeed Bot commented Jul 27, 2026 •

Copy link
Copy Markdown

Merging this PR will improve performance by 2.12%

⚡ 1 improved benchmark
✅ 10 untouched benchmarks

Performance Changes

Benchmark BASE HEAD Efficiency
⚡ createQueryFingerprint 532.9 µs 521.8 µs +2.12%

Tip

Curious why this is faster? Comment @codspeedbot explain why this is faster on this PR, or directly use the CodSpeed MCP with your agent.


Comparing feat/sdk-context-integrity-primitives (613278d) with main (9949042)

Open in CodSpeed

@greptile-apps

greptile-apps Bot commented Jul 27, 2026 •

Copy link
Copy Markdown

Greptile Summary

Hardens PM SDK/CLI context integrity across merge safety, history caches, lean output, and fresh-clone health.

  • Generalizes JSON merge fences to nested tracker JSON and adds conservative additive array three-way merge
  • Recognizes portable package-owned merge drivers; fail-closes merge-reconcile dry-run on non-green validation
  • Invalidates history drift cache on append/rewrite/rollback/bulk repair; bulk repair forces source scans
  • Lean JSON omits request-echo fields; legacy output_format payload echo declines with deprecation warning
  • Fresh-clone health treats empty type folders as optional; exports ServiceOverrideDecision

Confidence Score: 5/5

This follow-up pass finds no remaining blocking failures tied to prior Greptile threads, so the PR appears safe to merge from that scope.

No blocking failure remains from the prior-thread follow-up scope; previous inline findings could not be loaded, and no incomplete or unsafe fix was established against current HEAD.

Important Files Changed

Filename Overview
src/sdk/merge/three-way.ts Adds conservative additive JSON array merge and recursive object merge helpers for tracker JSON documents.
src/sdk/merge/install.ts Accepts portable package-owned node+dist/cli.js merge-driver commands and fences all nested **/*.json.
src/core/history/drift-cache.ts Best-effort removal of runtime history-drift-cache after mutations without failing the write path.
src/sdk/merge/reconcile.ts Dry-run and apply both require merge-critical validation checks to be green for ok.
src/core/output/output.ts Projects lean JSON envelopes and surfaces legacy output_format payload-echo deprecation warnings.
src/sdk/governance/health.ts Treats registered item-type folders as optional empty dirs instead of required structure.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  subgraph Mutations["History mutations"]
    A[appendHistoryEntry]
    R[writeHistoryRawWithRollback]
    B[runHistoryRepairAll]
  end
  I[invalidateHistoryDriftCache]
  A --> I
  R --> I
  B --> I
  subgraph Merge["Merge path"]
    T[mergeJsonDocuments / additive arrays]
    D[portable merge-driver audit]
    C[runMergeReconcile ok = repair + validation green]
  end
  T --> C
  D --> C
Loading

Reviews (3): Last reviewed commit: "fix(review): close context-integrity edg..." | Re-trigger Greptile

@codecov

codecov Bot commented Jul 27, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ All tests successful. No failed tests found.

📢 Thoughts on this report? Let us know!

@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/core/history/history.ts (1)

271-276: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Invalidate immediately after each committed append.

Each branch calls appendLineAtomic before index maintenance. If removeHistoryEventIndexForHistoryPath or updateHistoryEventIndexAfterAppend fails, the history line remains committed but drift-cache invalidation is never reached. Move invalidation directly after the append, or place index maintenance inside a try/finally that always invalidates the cache. This conflicts with the PR objective of keeping derived governance evidence coherent with mutations.

Also applies to: 294-300, 302-307, 311-313

🤖 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/core/history/history.ts` around lines 271 - 276, Ensure every history
mutation branch invalidates the drift cache immediately after its successful
append: update the append flows around appendLineAtomic, including the branches
at the referenced locations, so invalidateHistoryDriftCacheForPath runs before
removeHistoryEventIndexForHistoryPath or updateHistoryEventIndexAfterAppend.
Alternatively, wrap index maintenance in try/finally with invalidation
guaranteed after each committed append.
🤖 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 @.agents/pm/history/pm-ysqb6n.jsonl:
- Line 10: The resolved fields do not explicitly preserve the required
pending-receipt blocking contract. Update .agents/pm/history/pm-ysqb6n.jsonl at
lines 10-10 and .agents/pm/issues/pm-ysqb6n.toon at lines 19-21 so the
resolution and actual result name the enforced strict validation gate/assertion
that rejects pending receipts; if that blocking behavior is not implemented,
reopen the item instead of marking it verified.

In `@src/core/history/drift-cache.ts`:
- Around line 18-23: Update the cache removal error handling around fs.rm in the
drift-cache invalidation flow to suppress only expected missing-file errors,
while surfacing permission and other I/O failures through the established
error-reporting path without rolling back the committed history mutation. Keep
force: true and the best-effort post-commit behavior intact.

In `@src/sdk/merge/three-way.ts`:
- Around line 726-754: Update mergeAdditiveJsonArrays to preserve
duplicate-entry counts rather than only unique stableStringify identities:
compare base, ours, and theirs as multisets and return null whenever either side
has fewer occurrences of any base entry. Keep additive entries from theirs
merged onto ours only after those count checks pass, and add a regression test
covering one side removing a single duplicate entry.

---

Outside diff comments:
In `@src/core/history/history.ts`:
- Around line 271-276: Ensure every history mutation branch invalidates the
drift cache immediately after its successful append: update the append flows
around appendLineAtomic, including the branches at the referenced locations, so
invalidateHistoryDriftCacheForPath runs before
removeHistoryEventIndexForHistoryPath or updateHistoryEventIndexAfterAppend.
Alternatively, wrap index maintenance in try/finally with invalidation
guaranteed after each committed append.
🪄 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: Repository UI (base), Organization UI (inherited)

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 96548dcf-75ac-4f5d-8069-428072bbbba5

📥 Commits

Reviewing files that changed from the base of the PR and between 9949042 and 1f88846.

📒 Files selected for processing (38)
  • .agents/pm/chores/pm-e9zh.toon
  • .agents/pm/chores/pm-r31390.toon
  • .agents/pm/extensions/.managed-extensions.json
  • .agents/pm/history/pm-ajaskl.jsonl
  • .agents/pm/history/pm-e9zh.jsonl
  • .agents/pm/history/pm-gjicmx.jsonl
  • .agents/pm/history/pm-oi4zs3.jsonl
  • .agents/pm/history/pm-r31390.jsonl
  • .agents/pm/history/pm-u2tqn6.jsonl
  • .agents/pm/history/pm-w91mvg.jsonl
  • .agents/pm/history/pm-xyuhh7.jsonl
  • .agents/pm/history/pm-ysqb6n.jsonl
  • .agents/pm/issues/pm-ajaskl.toon
  • .agents/pm/issues/pm-gjicmx.toon
  • .agents/pm/issues/pm-oi4zs3.toon
  • .agents/pm/issues/pm-u2tqn6.toon
  • .agents/pm/issues/pm-w91mvg.toon
  • .agents/pm/issues/pm-xyuhh7.toon
  • .agents/pm/issues/pm-ysqb6n.toon
  • .gitattributes
  • CHANGELOG.md
  • docs/MERGE_SAFETY.md
  • docs/SDK.md
  • sdk/public-surface.json
  • src/core/extensions/extension-hook-runtime.ts
  • src/core/history/drift-cache.ts
  • src/core/history/history-rewrite.ts
  • src/core/history/history.ts
  • src/core/output/output.ts
  • src/core/store/item-store.ts
  • src/sdk/authoring.ts
  • src/sdk/governance/health.ts
  • src/sdk/history-repair.ts
  • src/sdk/merge/install.ts
  • src/sdk/merge/three-way.ts
  • tests/unit/commands/history-repair-command.spec.ts
  • tests/unit/commands/init-command.spec.ts
  • tests/unit/sdk/context-integrity-primitives.spec.ts

Comment thread .agents/pm/history/pm-ysqb6n.jsonl Resolved
Comment thread src/core/history/drift-cache.ts Resolved
Comment thread src/sdk/merge/three-way.ts Resolved
Apply Greptile and CodeRabbit feedback by preserving JSON array multiplicity, protecting structural health directories from custom-folder collisions, invalidating drift state before optional index maintenance, surfacing non-missing cache failures, and making merge-reconcile previews fail closed on drift or pending receipts. Add SDK and real CLI regressions and refresh PM/changelog evidence at exact 100% coverage.
@unbraind

Copy link
Copy Markdown
Owner Author

Feedback audit for Gemini sunset notice 1: acknowledged; no review is available from this retired integration, so no code action was possible.

@unbraind

Copy link
Copy Markdown
Owner Author

Feedback audit for Gemini sunset notice 2: acknowledged as a duplicate retirement notice; no code action was possible.

@unbraind

Copy link
Copy Markdown
Owner Author

Feedback audit for CodeRabbit command response: the full review did complete and its three actionable findings were implemented in 613278d with exact 100% coverage.

@unbraind

Copy link
Copy Markdown
Owner Author

Feedback audit for CodeRabbit summary: all inline and outside-diff findings were verified, implemented, covered, and answered; a fresh full review is being requested for 613278d.

@unbraind

Copy link
Copy Markdown
Owner Author

Feedback audit for Sourcery reviewer guide: reviewed as useful orientation; the separate rate-limit response prevented actionable Sourcery findings in this round.

@unbraind

Copy link
Copy Markdown
Owner Author

Feedback audit for CodSpeed report: acknowledged; the report found no performance change. Token, SDK import-cost, and CLI transport floors also remain green.

@unbraind

Copy link
Copy Markdown
Owner Author

Feedback audit for Greptile summary: both P2 findings were implemented in 613278d. Structural folders can no longer be demoted by type-folder collisions, and additive JSON merge now uses multiplicity-aware multiset semantics.

@unbraind

Copy link
Copy Markdown
Owner Author

Feedback audit for Codecov report: acknowledged. After review fixes the local exact suite remains 100% at 44,702 statements, 31,811 branches, 9,149 functions, and 43,418 lines.

@unbraind

Copy link
Copy Markdown
Owner Author

Feedback audit for Sourcery review: acknowledged; the weekly diff-character limit prevented a substantive review, so there were no findings to implement.

@unbraind

Copy link
Copy Markdown
Owner Author

Feedback audit for CodeRabbit review: all three inline findings plus the outside-diff post-append ordering finding were implemented in 613278d. The three inline threads have detailed replies; immediate cache invalidation before event-index maintenance has a forced-failure regression.

@unbraind

Copy link
Copy Markdown
Owner Author

@greptileai please perform a fresh full review of commit 613278d after all first-round findings were addressed.

@unbraind

Copy link
Copy Markdown
Owner Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
✅ Action performed

Full review finished.


Your included review limit is currently reached under our Fair Usage Limits Policy. This review may still proceed through usage-based billing if eligible. Your next included review will be available in 17 minutes.

@unbraind

Copy link
Copy Markdown
Owner Author

Second-round feedback audit for CodeRabbit command response: acknowledged; the rate-limited full review produced no new actionable finding on 613278d, while its three thread acknowledgments confirm the first-round fixes.

@unbraind

Copy link
Copy Markdown
Owner Author

Second-round feedback audit for the updated CodeRabbit summary: reviewed after its 613278d refresh. The repository-owned docstring gate is green at 100%; CodeRabbit’s generic 46.88% warning does not use this project’s complete source/docstring contract and is superseded by the required CI static gate.

@unbraind

unbraind commented Aug 4, 2026

Copy link
Copy Markdown
Owner Author

This was referenced Aug 5, 2026
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