Skip to content

[FEAT] Rebuilds cell mappings from scratch - #1

Merged
Avni2000 merged 5 commits into
mainfrom
build-nb-from-scratch
Jan 21, 2026
Merged

Avni2000 merged 5 commits into
mainfrom
build-nb-from-scratch

Conversation

@Avni2000

@Avni2000 Avni2000 commented Jan 21, 2026 •

Copy link
Copy Markdown
Owner

Problem:

Previously, we were attempting to amend local cells with the correct branch or edit, but this didn't correctly take into account a) indices changing due to addition/removal of cells, nor b) the cell matching process, which could result in duplicates and false matches.

Solution:

We now iterate through cellMappings in order where each mapping represents one row of cells in the merge view.

That is, the notebook's metadata is saved, and rebuilt from scratch each time we "apply & save" now.

TODO for a different PR:

  • Ordering of cells still needs to be addressed. Our cell matching algorithm needs to be heavily improved here.

Summary by CodeRabbit

  • New Features

    • Enhanced notebook merge resolution: builds final notebook from mappings, supports creating previously deleted cells, preserves metadata, and prefers automated resolutions when available.
    • Improved resolution actions: bulk accept/skip already-applied, and consistent handling of deletions.
  • Bug Fixes

    • More robust handling of missing or empty resolution content and execution-count renumbering propagation.
  • Style/Chores

    • Added development-mode debug logging to aid diagnostics without affecting production.

✏️ Tip: You can customize this high-level summary in your review settings.

- We now iterate through cellMappings in order - each mapping represents one row of cells in the merge view.
- Indices were being corrupted on cell deletion/addition. There were duplicates, false matches, etc.
@coderabbitai

coderabbitai Bot commented Jan 21, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Rebuilds semantic merge logic to construct resolved notebooks from cell mappings instead of in-place patching; adds verbose logging, deletion handling, and metadata preservation. UI panel gains debug-guarded logging and consistent deletion/content handling. A new logger module centralizes debug/info/warn/error output.

Changes

Cohort / File(s) Summary
Semantic Conflict Resolution Engine
src/resolver.ts
Replaces in-place patching with building a new notebook from cellMappings; introduces conflictMap keyed by base-local-remote indices; selects auto/local/remote/base cell content with support for deletions (empty custom content) and creation of new cells; preserves metadata from best source; adds verbose logging and imports SemanticConflict.
Resolution UI Panel & Rendering
src/webview/ConflictResolverPanel.ts
Replaces console logs with centralized logger and debug-mode gated logging; standardizes content emptiness checks to length-based; propagates isDeleted through resolution state to control outputs and rendering; skips already-applied resolutions and auto-applies remaining ones; logs payloads with content-length and preview.
Logging Utility
src/logger.ts
Adds a new logging module exporting debug, info, warn, error; debug output is gated by extension development mode and attempts safe VSCode API access when available; all logs prefixed with [MergeNB].

Sequence Diagram

sequenceDiagram
    participant Panel as ConflictResolverPanel
    participant Logger as Logger
    participant Resolver as Resolver Engine
    participant Notebook as Notebook Builder
    participant Git as Git Handler

    Panel->>Logger: log(debug) resolution intent
    Panel->>Resolver: send resolution payload (content, isDeleted, mapping)
    activate Resolver
    Resolver->>Logger: log(verbose) received resolutions & metadata
    Resolver->>Resolver: build conflictMap (base/local/remote indices)
    loop per cellMapping
        Resolver->>Resolver: pick source (autoResolved → local → remote → base)
        alt custom content provided
            Resolver->>Notebook: create or replace cell with custom content
        else deletion
            Resolver->>Notebook: skip / mark deleted
        end
    end
    Resolver->>Resolver: assemble resolvedCells + preserve metadata
    Resolver->>Logger: log(info) final resolved notebook summary
    deactivate Resolver
    Resolver->>Panel: return resolvedNotebook
    Panel->>Logger: log(debug) rendering decision (isDeleted awareness)
    Panel->>Git: propagate mark-as-resolved
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 I stitched the cells with careful paws,
From maps and logs and tiny laws,
Empty lines that vanish true,
Metadata kept, and conflicts few —
A notebook mended, hopped anew.

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically summarizes the main architectural change—rebuilding cell mappings from scratch instead of patching in-place—which is the primary focus of the changeset.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

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

@Avni2000 Avni2000 changed the title [MAJOR] [FEAT] Rebuilds cell mappings from scratch [FEAT] Rebuilds cell mappings from scratch Jan 21, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 Fix all issues with AI agents
In `@src/resolver.ts`:
- Around line 276-283: The current logs in the resolution application (the
console.log calls referencing uri.fsPath and resolution.textualResolutions)
print raw cell content which can leak sensitive data; change the logging to
exclude raw text by only emitting metadata (e.g., index, choice,
hasCustomContent as boolean, contentLength as number) or wrap the detailed
content output behind a debug flag so raw customContent is never logged in
normal operation; update the log that maps
Array.from(resolution.textualResolutions.entries()) to remove
contentPreview/customContent and only include safe fields (index, choice,
hasCustomContent, contentLength) or gate it on a debug mode flag used by the
extension.
- Around line 564-606: The resolver currently treats empty customContent as a
delete by using customContent.trim() === '' to set isDeleted; update the logic
to read an explicit isDeleted flag from the resolution payload (e.g., from the
object returned by resolutions.get(conflictInfo.index) alongside choice and
customContent) and only mark deletion when that isDeleted flag is true or when
the chosen side has no cell (cellToUse is null/undefined); also update the
resolution type/payload to include isDeleted so the UI can signal “empty but
keep” vs “delete,” and remove the customContent.trim() checks that trigger
deletion (retain customContent handling for creating/editing cells only when
isDeleted is false).

In `@src/webview/ConflictResolverPanel.ts`:
- Around line 1995-2000: The console.log in ConflictResolverPanel.ts that prints
full cell content (using resolutions[index].customContent) should be changed to
avoid exposing raw content: log only metadata such as resolutions[index].choice
and content length (resolutions[index].customContent?.length) or wrap the
detailed preview behind an explicit debug flag; update both the shown call (the
one referencing index and resolutions[index]) and the similar log around the
other occurrence (the block near the 2245-2250 region) to remove or gate
contentPreview output so only non-sensitive metadata is emitted by the
apply-resolution logging.

Comment thread src/resolver.ts Resolved
Comment thread src/resolver.ts
Comment on lines +564 to +606
let isDeleted = false;

switch (choice) {
case 'base':
cellToUse = conflict.baseContent;
break;
case 'local':
cellToUse = conflict.localContent;
break;
case 'remote':
cellToUse = conflict.remoteContent;
break;
}
if (conflictInfo) {
// This mapping corresponds to a conflict - check if user resolved it
const res = resolutions.get(conflictInfo.index);

if (res) {
// User provided a resolution
const choice = res.choice;
const customContent = res.customContent;

// Get the cell based on choice
switch (choice) {
case 'base':
cellToUse = baseCell;
break;
case 'local':
cellToUse = localCell;
break;
case 'remote':
cellToUse = remoteCell;
break;
}

// If custom content was provided (user edited the result), apply it to the cell
if (customContent !== undefined && cellToUse) {
const editedCell: NotebookCell = JSON.parse(JSON.stringify(cellToUse));
// Convert source to the same format (string or string[]) as original
if (Array.isArray(editedCell.source)) {
// Split by newlines, preserving them at the end of each line
if (customContent === '') {
editedCell.source = [];
} else {
editedCell.source = customContent.split(/(?<=\n)/);
// Check if this is a deletion (empty custom content or no cell for chosen side)
if (customContent !== undefined && customContent.trim() === '') {
isDeleted = true;
} else if (!cellToUse) {
isDeleted = true;
}
} else {
editedCell.source = customContent;
}
cellToUse = editedCell;
}

// Apply the resolution based on conflict type
if (conflict.type === 'cell-modified' || conflict.type === 'outputs-changed' ||
conflict.type === 'execution-count-changed' || conflict.type === 'metadata-changed') {
// Replace the cell at the local index with the chosen version
if (conflict.localCellIndex !== undefined) {
if (cellToUse) {
// Replace with the chosen cell
resolvedNotebook.cells[conflict.localCellIndex] = JSON.parse(JSON.stringify(cellToUse));
} else {
// Chosen side has no cell - mark for deletion
cellsToRemove.add(conflict.localCellIndex);
// If custom content was provided and not deleted, apply it to the cell
if (customContent !== undefined && customContent.trim() !== '' && cellToUse) {
const editedCell: NotebookCell = JSON.parse(JSON.stringify(cellToUse));
// Convert source to the same format (string or string[]) as original
if (Array.isArray(editedCell.source)) {
editedCell.source = customContent.split(/(?<=\n)/);
} else {
editedCell.source = customContent;
}
cellToUse = editedCell;
} else if (customContent !== undefined && customContent.trim() !== '' && !cellToUse) {
// User added content to a deleted cell - create a new cell

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Empty custom content is treated as deletion and will drop valid empty cells.
If a cell is intentionally empty, the current logic deletes it because customContent.trim() === ''. This risks data loss. Use an explicit isDeleted flag from the UI (already tracked) and only delete when that flag is set or when the chosen side has no cell.

✅ Proposed fix: use explicit delete signal instead of empty content
-            let cellToUse: NotebookCell | undefined;
-            let isDeleted = false;
+            let cellToUse: NotebookCell | undefined;
+            let isDeleted = false;
@@
-                    const customContent = res.customContent;
+                    const customContent = res.customContent;
+                    const explicitDelete = res.isDeleted === true;
@@
-                    if (customContent !== undefined && customContent.trim() === '') {
-                        isDeleted = true;
-                    } else if (!cellToUse) {
-                        isDeleted = true;
-                    }
+                    if (explicitDelete) {
+                        isDeleted = true;
+                    } else if (!cellToUse) {
+                        isDeleted = true;
+                    }

Also update the resolution payload/type to include isDeleted so the resolver can distinguish “empty but kept” vs “delete.”

🤖 Prompt for AI Agents
In `@src/resolver.ts` around lines 564 - 606, The resolver currently treats empty
customContent as a delete by using customContent.trim() === '' to set isDeleted;
update the logic to read an explicit isDeleted flag from the resolution payload
(e.g., from the object returned by resolutions.get(conflictInfo.index) alongside
choice and customContent) and only mark deletion when that isDeleted flag is
true or when the chosen side has no cell (cellToUse is null/undefined); also
update the resolution type/payload to include isDeleted so the UI can signal
“empty but keep” vs “delete,” and remove the customContent.trim() checks that
trigger deletion (retain customContent handling for creating/editing cells only
when isDeleted is false).

Comment thread src/webview/ConflictResolverPanel.ts Resolved
Avni2000 and others added 4 commits January 21, 2026 10:58
- Address "Whitespace custom content is treated as deletion and will drop valid empty cells." by not trimming content.
[LOGGER] [FEAT] Implement debug logging system
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