Repository navigation
Harden SDK context integrity, merge safety, and agent-efficient output - #783
Conversation
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.
|
@greptileai please review this complete SDK/CLI context-integrity bundle. |
|
@coderabbitai full review |
|
Caution The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased. |
1 similar comment
|
Caution The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased. |
✅ Action performedFull 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. |
|
Warning Review limit reached
Next review available in: 17 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the 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 configurationConfiguration used: Repository UI (base), Organization UI (inherited) Review profile: ASSERTIVE Plan: Pro Plus Run ID: 📒 Files selected for processing (42)
📝 WalkthroughWalkthroughThis PR updates merge safety, JSON output contracts, history drift-cache invalidation, directory health classification, regression tests, documentation, changelog entries, and project-management records. ChangesMerge safety and JSON reconciliation
Output and extension contracts
History and health integrity
Project-management records
Estimated code review effort: 4 (Complex) | ~60 minutes Possibly related issues
Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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. Comment |
Reviewer's GuideStrengthens 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 cachesequenceDiagram
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)
Sequence diagram for service override decisions and lean JSON outputsequenceDiagram
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
Sequence diagram for portable merge driver configuration auditsequenceDiagram
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
File-Level Changes
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Merging this PR will improve performance by 2.12%
Performance Changes
Tip Curious why this is faster? Comment Comparing |
Greptile SummaryHardens PM SDK/CLI context integrity across merge safety, history caches, lean output, and fresh-clone health.
Confidence Score: 5/5This 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.
|
| 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
Reviews (3): Last reviewed commit: "fix(review): close context-integrity edg..." | Re-trigger Greptile
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
There was a problem hiding this comment.
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 winInvalidate immediately after each committed append.
Each branch calls
appendLineAtomicbefore index maintenance. IfremoveHistoryEventIndexForHistoryPathorupdateHistoryEventIndexAfterAppendfails, the history line remains committed but drift-cache invalidation is never reached. Move invalidation directly after the append, or place index maintenance inside atry/finallythat 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
📒 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.gitattributesCHANGELOG.mddocs/MERGE_SAFETY.mddocs/SDK.mdsdk/public-surface.jsonsrc/core/extensions/extension-hook-runtime.tssrc/core/history/drift-cache.tssrc/core/history/history-rewrite.tssrc/core/history/history.tssrc/core/output/output.tssrc/core/store/item-store.tssrc/sdk/authoring.tssrc/sdk/governance/health.tssrc/sdk/history-repair.tssrc/sdk/merge/install.tssrc/sdk/merge/three-way.tstests/unit/commands/history-repair-command.spec.tstests/unit/commands/init-command.spec.tstests/unit/sdk/context-integrity-primitives.spec.ts
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.
|
Feedback audit for Gemini sunset notice 1: acknowledged; no review is available from this retired integration, so no code action was possible. |
|
Feedback audit for Gemini sunset notice 2: acknowledged as a duplicate retirement notice; no code action was possible. |
|
Feedback audit for CodeRabbit command response: the full review did complete and its three actionable findings were implemented in 613278d with exact 100% coverage. |
|
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. |
|
Feedback audit for Sourcery reviewer guide: reviewed as useful orientation; the separate rate-limit response prevented actionable Sourcery findings in this round. |
|
Feedback audit for CodSpeed report: acknowledged; the report found no performance change. Token, SDK import-cost, and CLI transport floors also remain green. |
|
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. |
|
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. |
|
Feedback audit for Sourcery review: acknowledged; the weekly diff-character limit prevented a substantive review, so there were no findings to implement. |
|
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. |
|
@greptileai please perform a fresh full review of commit 613278d after all first-round findings were addressed. |
|
@coderabbitai full review |
✅ Action performedFull 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. |
|
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. |
|
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. |
Summary
This broad SDK and CLI bundle strengthens
project management = context managementacross merge safety, history integrity, extension authoring, agent-token efficiency, and fresh-clone governance.ServiceOverrideDecisionfor SDK authorspm-changelog2026.7.27Why
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 lintpnpm typecheckpnpm contracts:checkpnpm changelog:pm:checkpm health --check-only --skip-vectors --briefwith zero warningspm validate --check-history-driftwith zero driftDependency and security disposition
pnpm auditreports zero vulnerabilities@sentry/node10.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 versionnpm-package-arg14 and the TypeScript 7 ecosystem transition remain linked to their canonical PM deferralsSummary 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:
Enhancements:
Documentation:
Tests:
Chores:
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
.agents/pm/**/*.json;.managed-extensions.jsonnow usespm-json.filters,projection,sorting,now; includenext_cursoronly when paginating.ServiceOverrideDecision; treats legacyoutput_formatpayload echo as a safe decline with a deprecation warning.Dependencies
@sentry/node10.68.0 and retained 10.67.0 due to packed TypeScript consumer boundary failure.pnpm auditreports zero vulnerabilities.Written for commit 613278d. Summary will update on new commits.