Skip to content

AI Code Stitcher v2.20

Choose a tag to compare

@ue-patcher ue-patcher released this 15 Jun 15:07
· 4 commits to main since this release
0573334

Paste AI-generated code. It just works.

Copy output from Claude, Cursor, ChatGPT, Aider or any other LLM and AI Code Stitcher intelligently applies it to the correct locations in your existing codebase.

ai_code_stitcher_in_action.mp4

STITCH VIEWER VERSION 2.00 --- --- --- MICRO-IDE. --- --- --- TOTAL FILE EDITING CONVENIENCE

Just press [F11] to run!

  • The Stitch Viewer operates as an event-driven comparative file/diff viewer that parses directory structures to rebuild and analyze revision histories.

  • The application initializes a low-latency rendering pipeline with hardware-batching to ensure responsive draw calls on modern displays.

  • It retrieves historical backup files alongside live project code and feeds them into an index-matching comparative engine. This comparative engine processes the files line-by-line, translating differences into logical blocks (equal, delete, insert, or replace) and aligning them side-by-side onto a unified virtual line index.

  • This alignment allows developers to inspect alterations across different historical runs and selectively merge or discard localized code segments through dynamic gutter controls.

example_stitch_viewer

AI Code Stitcher + Diff Viewer/File Editor

What's new in v2.12?

  • AIDER patch manual rescue interface over-haul. Interactive match for the AIDER search block with intuitive overlay

  • Decorators in Python (@) now handled intelligently.

  • Fuzzy Match Engine Early-Exits: Optimized best match by index searching by introducing an early-exit math heuristic. If the remaining possible lines cannot mathematically achieve the confidence threshold, the search loop aborts immediately. Also added a boundary breakout if the first 15 lines of a search block fail to find any anchor.

  • Heuristic String Pre-Filtering: Integrated fast length-ratio checks along with quick ratio filters to skip expensive SequenceMatcher evaluations on dissimilar lines.

  • Match Window Short-Circuiting: Added an early breakout for unique candidate windows. Once a high-confidence match (≥0.98) is resolved in the highest-density window, evaluations on remaining lower-scoring windows are skipped.

  • Step-Size Fallback Tuning: Adjusted the fallback exact sequence matcher to step through search windows at a wider interval, dropping overall execution times on large files.

  • Indentation & Alignment Safety

  • Copy-Paste Indentation Repairer: Refactored dedenting mechanism to automatically detect when a block header (ending in :) has nested body statements indented disproportionately deeper (>8 spaces). The engine now automatically dedents the body block to a standard 4-space alignment relative to the header.

  • Visual Preview Synchronization: Integrated the indentation repair algorithm directly into headless snippet alignment so that terminal previews match the final on-disk output.

  • Structural Gap/Span Penalty: Introduced a file-span density penalty to filter out false-positives that span across huge sections of unrelated code. The penalty is automatically bypassed if explicit lazy comments (...) are present in the patch.

The Anti-Agentic Approach

While the industry chases increasingly autonomous AI agents...
Code Stitcher is built on a simpler, more reliable philosophy:

You remain in control.

AI Code Stitcher excels at precisely integrating AI code output into real projects — with smart elastic matching, preview, and undo capabilities.

No mysterious black-box changes. No waiting hours to see what an agent did. Just fast, surgical updates under your direct supervision.

Key Features

  • Intelligent context matching (even when AI uses wrong filenames or incomplete context)
  • Safe preview before applying changes
  • Support for partial updates, function replacements, and larger refactors
  • Works with any editor (VS Code, Neovim, JetBrains, etc.)
  • Runs locally and privately

+---------------------------------------------------------------------------------------------------------------------------------------------------+

STITCH VIEWER TECHNICAL SPECIFICATION & USER MANUAL

Classification: Technical Documentation / System Integration & Operations Manual

SECTION 1: Architectural Philosophy & Core Processing Pipelines

The Stitch Viewer is a low-latency, highly specialized graphical comparative
utility designed to reconstruct, analyze, and modify file revision histories in
a non-destructive manner. Engineered as a lightweight comparative environment,
it operates independently of bloated IDE frameworks, providing instantaneous
load times and zero-allocation execution paths.

1.1 Rendering Pipeline Architecture

The application runs on a customized Pygame rendering pipeline optimized for
modern high-DPI displays. By setting the environment variable
SDL_HINT_RENDER_BATCHING to 1 and forcing DPI awareness through permonitorv2,
the rendering engine bypasses typical software-blitting bottlenecks.

+---------------------------------------------------------------------------------+
| Pygame Canvas |
+---------------------------------------------------------------------------------+
| |
| +--------------------+ +---------------------------------------------------+ |
| | Left Tree | | Comparative Panes | |
| | Explorer | | | |
| | | | +-------------------+ +-------------------+ | |
| | [File Header] | | | Historical Pane | | Current Pane | | |
| | └─ Run ID | | | (Read-only, dark) | | (Active/Edit) | | |
| | └─ Revision | | +-------------------+ +-------------------+ | |
| +--------------------+ +---------------------------------------------------+ |
| |
+---------------------------------------------------------------------------------+

Graphics rendering is strictly event-driven. A state-dirtying flag prevents
redundant recalculations, ensuring redrawing only occurs during:

  1. Active user mouse actions or dragging.
  2. Viewport and scroll-offset adjustments.
  3. Active real-time text input.
  4. Active transition animations (sliding layouts).
  5. Polled filesystem change detections.

1.2 The Opcode comparative Engine

The comparative algorithm relies on the sequence matching of lines. By executing
standard sequence matching, the system translates comparative differences into
distinct action blocks:

  • equal: Interleaved lines matching exactly, rendered with syntax-specific
    colors.
  • delete: Line ranges existing inside historical revisions but absent in
    current versions.
  • insert: Line ranges added to the current file but missing from the history.
  • replace: Multi-line blocks transformed or updated between versions.

These blocks map directly onto unified virtual line indices. This ensures that
comparative sections align side-by-side, regardless of offset variations or line
insertions.

SECTION 2: Environment Configuration & Host Integration

The Stitch Viewer integrates natively with host applications (such as the main
CodeStitcher parent program) using low-level operating system APIs,
single-instance mutex locks, and standard input/output structures.

2.1 Command-Line Interface (CLI) Specification

The execution binary accepts several parameters to initialize window positions,
load appropriate monitored directories, and establish secure process-to-process
communication links:

stitch_viewer.exe --from-stitcher --parent-pid 10424 --monitor "C:\Project" --pos "150,150" --height 800 --font "consolas" --font-size 13 --pro

CLI Argument Reference:

  • --from-stitcher: Mandatory. Failsafe validation flag. If absent, the viewer
    instantly terminates execution to prevent orphaned loop execution.
  • --parent-pid : Specifies the Process ID of the calling application.
  • --monitor : Specifies directories to scan for backups and unversioned
    assets. Multiple directories are scanned sequentially.
  • --pos <x,y>: Assigns the default spawning coordinates on the desktop
    workspace.
  • --height : Sets the physical pixel height of the program frame.
  • --font : Overrides the default system typeface for code rendering.
  • --font-size : Configures baseline font sizes.
  • --pro: Unlocks directory tree traversal paths.

2.2 Process Heartbeat & Failsafe Shutdown

To prevent orphaned processes in the memory space, the viewer maintains a
non-blocking parent-process heartbeat monitored on a 120-tick interval (~2
seconds). The background loop uses the Win32 API to check process states:

process = ctypes.windll.kernel32.OpenProcess(0x1000, False, parent_pid)

If the Win32 query return value flags that the parent process has terminated,
the comparative window closes immediately to free hardware assets.

2.3 Single-Instance Mutex Locking

To enforce single-instance comparative execution, the application attempts to
acquire an OS-level Mutex lock:

self.mutex = ctypes.windll.kernel32.CreateMutexW(None, False, "Global\CodeStitcherCodeStitcher_MUTEX")

If the system returns error code 183 (ERROR_ALREADY_EXISTS), a pre-existing
instance of the comparative environment is already running. The new instance
terminates immediately, preventing memory collisions.

SECTION 3: Comparative View Interface & Gutter Mechanics

The layout divides the screen into four functional zones: the directory explorer
tree, the historical revision pane, the interactive current version pane, and
the minimap navigation gutter.

+-----------------------------------------------------------------------------------------+
| Title Bar _ X |
+-----------------------------------------------------------------------------------------+
| Tree Explorer | Comparative View Header: Old File vs New File |
+---------------+-------------------------------------+-----------------------------------+
| | [Line numbers on right] | [Bookmarks] [Line numbers] |
| | | |
| File.py | (Def / Code Text) | (Def / Code Text) |
| └─ Run 01 | | |
| └─ 12:00 | | |
| | | |
| | | |
+---------------+-------------------------------------+-----------------------------------+
| | (Dynamic Status Bar / Linter Warnings) |
+-----------------------------------------------------------------------------------------+

3.1 Compact Directory Explorer Tree

Rendered on the far left, the file explorer uses a compact structure to display
version control nodes:

  1. File Nodes: Base targets sorted chronologically by their last modification
    timestamp.
  2. Run Nodes: Grouped clusters representing a logical sequence of internal
    edits.
  3. Entry Nodes: Direct pointers to physical backup assets. These entries
    display line metadata using distinct indicators, such as +12 -4 representing
    lines added versus lines removed.

The tree maintains expand/collapse state memory. When reloading directories,
directories do not collapse randomly, preserving the user's focus.

3.2 Splitting & Parsing of Sub-Chunks

Standard comparative engines often group long sequences of edits into single
massive block offsets, which are difficult to parse visually. The Stitch Viewer
breaks up long insertion/deletion chains into distinct logical "sub-chunks"
whenever they cross signature patterns, such as:

  • def function declarations.
  • class definitions.
  • @ decorators.

By parsing code files this way, users can merge or discard individual functions
independently without being forced to accept or reject adjacent changes.

3.3 Dynamic Merge Gutters & Unified Multi-Merge Controls

The gutter channel between the comparative panes acts as an interactive control
panel. Depending on the changes detected, the gutter renders specific action
items:

  • All Merge Arrow (ALL →): Displayed on multi-segment change blocks. Merges
    all sub-chunks within that block in a single step.
  • Single Merge Arrow (→): Restores selected deleted lines from historical
    records directly into the live file.
  • Discard Cross (×): Erases newly inserted lines from the current file.

SECTION 4: The Real-Time Text Editor (Interactive Sandbox)

For rapid revisions, the Stitch Viewer provides a built-in text editor that can
be activated instantly, avoiding the need to open a heavy, separate development
environment.

4.1 Transition Animation Mechanics

To transition smoothly between side-by-side comparative viewing and editing, the
interface uses an exponential interpolation curve based on a transition
variable, t:

\text{Target } t = \begin{cases} 1.0 & \text{if Editing Mode is Active} \ 0.0 & \text{if Standard Mode is Active} \end{cases}

The animation system updates t each frame:

t_{\text{next}} = t_{\text{curr}} + (t_{\text{target}} - t_{\text{curr}}) \times 0.15

This transition shifts layout coordinates dynamically to expand the editor pane
over the screen:

Normal Mode: [ Old Pane ] |Gap| [ New Pane ]
Transitioning: [ Old Pane ] |G| [ Expanding Editor Box ]
Fully Expanded: [Old] [ Active Red Editor Box ]

To prevent the code text from shifting abruptly when entering edit mode, the
editor uses a dynamic text margin calculation:

\text{Text Offset} = 25 + \lfloor 30 \times t \rfloor \text{ pixels}

As t approaches 1.0, the code shifts right, smoothly creating space for line
numbers and bookmarks without any sudden visual jumps.

4.2 Vertical Tools Sidebar & Action Buttons

When t > 0, a tools sidebar appears on the left of the editor pane, displaying
keyboard shortcuts. The sidebar elements use an alpha value linked to the
transition variable:

\text{Alpha} = \lfloor 255 \times t \rfloor

This ensures the tools fade in smoothly as the editor box slides open.

4.3 Red-Tinged Action Button Toggle

The top action button changes context dynamically to match the current state:

  • Edit State Off: Button displays "Edit Current File" in soft red. Clicking it
    opens the editor.
  • Edit State On: Button displays "Save Changes" in bright red. Clicking it
    writes all buffer modifications to the live file and exits the editor.

4.4 Bookmarks, Margin Control & Fluid Viewport Lerping

The editor gutter contains a dedicated 12px column that holds custom bookmarks,
keeping layout spacing compact.

+-----------------------------------------------------------+
| Gutter Column | Line Number Column | Code text ... |
| (12px wide) | (33px wide) | |
| | | |
| ● | 102 | def process_data(): |
| | 103 | val = fetch() |
| | | |
+-----------------------------------------------------------+

  • Placing Bookmarks: Clicking the far-left bookmark margin sets a green dot
    centered vertically on that line.
  • Navigating Bookmarks: Clicking the line numbers column cycles the cursor and
    viewport scroll position to the next bookmark.
  • Camera Lerping: When jumping between bookmarks, the viewport scrolls
    smoothly to the target line using floating-point interpolation rather than
    snapping instantly:

y_{\text{scroll_float}} \leftarrow y_{\text{scroll_float}} + (y_{\text{target}} - y_{\text{scroll_float}}) \times 0.15

y_{\text{scroll}} = \lfloor y_{\text{scroll_float}} \rfloor

  • Visual Flash Feedback: Jumping to a bookmark triggers a bright warm flash
    over the line numbers column that fades over 10 frames, providing clear
    visual feedback of the jump.

SECTION 5: Real-Time Syntax Linter Pipeline

To help prevent syntax errors during quick edits, the editor includes a
background syntax-checking pipeline.

User Typing Input


┌───────────────────┐
│ Buffer Update │
└─────────┬─────────┘
│ (Auto-triggered)

┌────────────────────────────────────────────────────────┐
│ Linter Routing Engine │
└────┬──────────────────────┬───────────────────────┬────┘
│ .py │ .json │ All other formats
▼ ▼ ▼
┌──────────────┐ ┌─────────────┐ ┌───────────────┐
│ AST Compiler │ │ JSON Parser │ │ Stack-Based │
│ Syntax Check │ │ Schema Check│ │ Bracket Match │
└────┬─────────┘ └─────┬───────┘ └───────┬───────┘
│ │ │
└──────────────────────┼───────────────────────┘

Line Error Array Generation

┌─────────────┴─────────────┐
▼ ▼
Red Zigzag Underlines Bottom Error Banner

5.1 Python Compilation Checks

For Python files (.py), the linter attempts to compile the active edit buffer:

compile(code_text, "", "exec")

If compilation fails, the linter catches the raised SyntaxError or
IndentationError, parses the line number (e.lineno), and extracts the error
message (e.msg).

2.2 JSON Validation

For JSON files (.json), the linter parses the text buffer using the native
json.loads module. If parsing fails, it extracts the target line number and
structural issue, such as trailing commas or unquoted keys.

5.3 Fallback Bracket Matcher

For other file types (like JS, C++, HTML, or text), the linter uses a
stack-based bracket-matching fallback:

  1. It scans the file character by character, pushing open brackets (, [, and {
    onto a tracking stack.
  2. If it encounters a mismatched closing bracket, it immediately flags that
    line.
  3. If unclosed brackets remain at the end of the file, it flags the line where
    the first opening bracket was declared.

5.4 Visual Error Indicators

Detected errors are displayed inside the editor workspace in two places:

  1. Wavy Line Underline: The editor draws a red zigzag line under the error
    line. This line is drawn dynamically inside the text rendering loop:

for z_x in range(start_x, start_x + text_width, 4):
z_y = y + line_height - (1 if (z_x // 4) % 2 == 0 else 3)
points.append((z_x, z_y))

  1. Footer Error Banner: The active error description is displayed in a warning
    banner at the bottom left of the screen, underneath the editor box.

SECTION 6: Complete Control Matrix

6.1 Standard Comparative View Shortcuts

These controls are active when viewing side-by-side comparative views.

Action Key System Execution Behavior
Ctrl + E Disabled. Edit mode must be entered strictly using the red action button.
Escape Exits the comparative viewer environment immediately.
Page Up Scrolls comparative panels up by 20 lines.
Page Down Scrolls comparative panels down by 20 lines.
Up Arrow Scrolls comparative panels up by 1 line.
Down Arrow Scrolls comparative panels down by 1 line.
Alt + Up Jumps the comparative scroll target up to the previous active change block.
Alt + Down Jumps the comparative scroll target down to the next active change block.
Home Instantly scrolls comparative panels to line 1 of the file.
End Instantly scrolls comparative panels to the final line of the file.
Left Arrow Cycles historical revision selection back by 1 entry.
Right Arrow Cycles historical revision selection forward by 1 entry.
Ctrl + F Activates the search bar focus loop.
Ctrl + G Opens the line jump modal overlay.
Ctrl + C Copies any active text selection across comparative views.
Right-Click Opens the context menu (Copy function, replace code, revert entire file).

6.2 Real-Time Text Editor Shortcuts

These controls are active inside the text editor pane.

Action Key System Execution Behavior
Ctrl + X Primary Exit: Saves all changes and exits edit mode.
Escape Locked Action: Does not exit edit mode. Flashes the Save and Discard buttons, and shows the Discard option.
Up Arrow Moves the text cursor up 1 line.
Down Arrow Moves the text cursor down 1 line.
Left Arrow Moves the text cursor left 1 character.
Right Arrow Moves the text cursor right 1 character.
Ctrl + Left Moves the text cursor left by 1 entire word.
Ctrl + Right Moves the text cursor right by 1 entire word.
Home Moves the text cursor to index 0 of the current line.
Ctrl + Home Moves the text cursor to line 1, column 0 of the document.
End Moves the text cursor to the final character of the current line.
Ctrl + End Moves the text cursor to the final character of the document.
Page Up Moves the text cursor and viewport up by 20 lines.
Page Down Moves the text cursor and viewport down by 20 lines.
Shift + [Nav] Extends or shrinks the active text selection range.
Ctrl + A Selects all text inside the edit buffer.
Ctrl + C Copies the active selection to the system clipboard.
Ctrl + V Pastes the system clipboard text at the cursor position.
Backspace Erases the character behind the cursor.
Ctrl + Backspace Erases the entire word to the left of the cursor.
Delete Erases the character in front of the cursor.
Ctrl + Delete Erases the entire word to the right of the cursor.
Enter Inserts a newline and matches the indentation level of the previous line.
Tab Inserts 4 spaces (or indents selected lines by 4 spaces).
Shift + Tab Removes 4 spaces of indentation from the selected lines.
Ctrl + Z Reverts the last buffer modification (Undo).
Ctrl + Y Re-applies the last undone modification (Redo).

SECTION 7: Configuration Management & Live INI Synchronization

The application reads and writes system variables from a shared configuration
file:

%APPDATA%\CodeStitcher\cs_settings.ini

7.1 Configuration Keys

The INI parser monitors several core variables:

CONF_VIEWER_ALWAYS_ON_TOP = "True"
CONF_DIFF_WINDOW_X = "120"
CONF_DIFF_WINDOW_Y = "140"
CONF_WINDOW_HEIGHT = "750"
CONF_FONT_NAME = "consolas"
CONF_FONT_SIZE = "13"
CONF_LAST_DIFF_FILE = "main.py"

  • CONF_VIEWER_ALWAYS_ON_TOP: Keeps the comparative window floating above all
    other applications.
  • CONF_DIFF_WINDOW_X / CONF_DIFF_WINDOW_Y: Stores the last position of the
    application window to restore it on the next launch.
  • CONF_WINDOW_HEIGHT: Stores the last height of the comparative window.

7.2 Hot-Reload Engine

To dynamically update configurations without needing to restart the program, a
filesystem watcher monitors the INI file. Every 3 seconds, the background thread
checks the file's last modified time:

curr_mtime = os.path.getmtime(ini_path)

If the modification time changes, the program re-reads the configuration,
updating settings like Always On Top instantly while preserving all active
editor buffers, scroll positions, and navigation history.

1. System Architecture & Operating System Integration

The application operates as a background polling engine paired with a hardware-accelerated, transparent, topmost graphical user interface overlay. It acts as an intermediary between the system clipboard, the local filesystem, and the developer's workflow.

+-------------------------------------------------------------------+
|                     OPERATING SYSTEM KERNEL                       |
|  +--------------------+   +-------------------+   +------------+  |
|  | Win32 Message Loop |   | Clipboard Manager |   | File System|  |
|  +---------+----------+   +---------+---------+   +-----+------+  |
+------------|------------------------|-------------------|---------+
             | Virtual Keys           | Shared Text       | I/O
             v                        v                   v
+------------|------------------------|-------------------|---------+
|            |                        |                   |         |
|  +---------v----------+   +---------v---------+   +-----v------+  |
|  |  Hotkey Intercept  |   | Asynchronous Poll |   | Safe I/O   |  |
|  |  & Event Dispatch  |   |   & Deduplicate   |   | & Backups  |  |
|  +---------+----------+   +---------+---------+   +-----+------+  |
|            |                        |                   |         |
|            +------------------+     |     +-------------+         |
|                               |     |     |                       |
|                             +-v-----v-----v-+                     |
|                             |  Core Engine  |                     |
|                             +-------+-------+                     |
|                                     | Graphics Pipelines          |
|                                     v                             |
|                             +-------+-------+                     |
|                             | GPU-Accelerated|                    |
|                             | Double-Buffer |                     |
|                             +---------------+                     |
|                                                                   |
|                       APPLICATION BOUNDARY                        |
+-------------------------------------------------------------------+

1.1 Layered Graphics Pipeline & Double-Buffered Render Layout

To achieve responsive UI updates without impacting host computer processing units (CPUs), the system employs a GPU-accelerated graphics stack built on double-buffered surface structures:

  • Asynchronous Buffer Flipping: All drawing operations—including glyph rendering, glass panels, alpha-blended glowing borders, and terminal lists—are compiled onto an offscreen back-buffer. Once a frame is constructed, it is flipped atomically to the physical display buffer to prevent tearing.
  • OS Window Transparency (Chroma-Keying): Using native system-level library hooks, the windowing system assigns the frame window an extended window style (WS_EX_LAYERED). It registers a custom transparent color key alongside a configurable global opacity ratio. Pixels matching the color key are rendered completely transparent by the OS desktop window manager, producing smooth anti-aliased margins for custom floating visual assets.
  • Topmost Level Enforcement: To ensure that notifications, prompts, and status readouts are never hidden by full-screen IDEs or text editors, a persistent background daemon thread monitors the window's visual layer. It uses native OS window-positioning flags to keep the window at the topmost index (HWND_TOPMOST), locking it above the visual stack.

1.2 System-Wide Hotkey Interception & Win32 Event Processing

The application intercepts key inputs globally to allow hands-free workflow activation:

  • Isolated Hotkey Listeners: Spawns a dedicated thread to registers unique, system-wide key bindings with the OS kernel. This thread runs an active, low-overhead Win32 message loop that intercepts incoming virtual key inputs before they reach target windows.
  • Dynamic Modifiers & Keys: Supports standard keyboard modifier states (such as Control, Alt, and Shift) mapped to standard hardware interrupts (like F6, F9, and F11).
  • Thread-Safe Event Dispatching: When a hotkey is pressed, the listener thread translates the OS message and pushes an asynchronous event callback to the main thread's processing queue, preventing input-handling lag from blocking the user interface.
  • Temporary Hotkey Masking: During interactive text prompts or selection lists, the hotkey system temporarily registers targeted overlays to capture specific single-key inputs (such as numbers or letter choices) and passes them directly to the active prompt, ignoring standard key mappings.

1.3 Asynchronous Clipboard Polling & State Verification

The engine's main processing loop uses an optimized polling routine to monitor the system clipboard:

  • Differential State Tracking: The background poll engine samples the clipboard buffer at high frequency, comparing the current payload against an active memory hash to prevent duplicate processing cycles.
  • Asynchronous Handoff: When a new, non-empty text string is detected, the poll engine verifies if the application is currently "Armed". If it is, the engine captures the clipboard buffer, wipes the system clipboard to prevent duplicate operations, and hands the text lines off to the processing queue.
  • Anti-Feedback Safeguards: Captures and analyzes clipboard actions originating from within the program itself. If the user copies text from the custom log terminal, the engine temporarily disarms the clipboard monitor, preventing the program from repeatedly parsing its own output.

2. Lexical Heuristics & Multi-Language Parsing

Before merging code, the engine analyzes the payload to determine the language and structure of the patch.

                      +-----------------------------+
                      |   Incoming Raw Clipboard    |
                      +--------------+--------------+
                                     |
                                     v
                       +-------------+-------------+
                       |    Statistical Classifier  |
                       +-------------+-------------+
                                     |
             +-----------------------+-----------------------+
             |                                               |
             v                                               v
+------------+------------+                     +------------+------------+
|   Indent-Based Profile  |                     |    Brace-Based Profile  |
|  (Python, GDScript, etc) |                     |  (C++, JS, TS, Java, Go)|
+------------+------------+                     +------------+------------+
| - Colon-bounded blocks  |                     | - Curly brace matching  |
| - Space-to-tab checks   |                     | - Multiline template lit|
+-------------------------+                     +-------------------------+

2.1 The Multi-Language Profiling Registry

The parsing system supports multiple languages by categorizing them into three core paradigms:

  1. Indent-Based Paradigms (e.g., Python, GDScript, Nim, YAML): Scopes are determined by visual indentation depths following structural block definitions ending in a colon (:).
  2. Brace-Based Paradigms (e.g., JS, TS, C++, Java, Rust, Go, C#): Scopes are defined by balanced pairs of open and close curly braces ({ ... }), ignoring intermediate indentation.
  3. Keyword-Based Paradigms (e.g., Ruby, Bash): Scopes are defined by language-specific keyword boundaries (such as def ... end or if ... fi).

2.2 Heuristic Language Classifier

When a patch lacks file hints or extensions, the classifier runs a scoring pass over the first 150 non-empty lines:

  • Syntax Marker Scoring: Tracks the frequency of specific language structures (such as ; terminators, lambda arrows =>, Python self. and __init__ references, and C++ template brackets <T>).
  • Visual Indent Scanning: Looks for trailing colons (:) that do not contain trailing comment blocks. If a significant percentage of lines end with colons and are followed by deeper indents, the engine classifies the code as indent-based.
  • Brace Balancing: Tallies curly braces outside of comments and strings. If braces are present and balanced, it prioritizes the brace-based profile.

2.3 Syntactic Masking & Code-String Neutralization

To prevent inline strings, comments, and regular expressions from throwing off structural analysis, the engine creates a "masked" copy of the lines before parsing:

  • Python Masking: Analyzes the line character-by-character to identify single-line quotes, escape sequences, and multiline triple-quoted strings (""" or '''). It replaces the contents of these blocks with neutral spaces, leaving brackets and indents in place.
  • Brace Masking: Uses a custom parser for C-style and JS languages that masks double-quoted strings, backtick templates, single-line comments (//), and block comments (/* ... */).
  • Comment Truncation: Standardizes line comments (such as # or //) to ensure they are ignored during structural and indentation analysis.

2.4 Indentation Diagnostics & Structural Indent Analysis

  • Visual Indent Resolution: Computes the exact indentation of a line by converting tabs to 4 spaces, providing a consistent baseline for analysis.
  • Structural Indent Isolation: Scans a block of code to find the first line containing executable statements—skipping decorators, comments, and docstrings—to determine the block's true indentation level.

3. Structural Repair & Normalization Subsystems

LLM-generated code often suffers from formatting issues due to browser copy-paste errors or truncations. The engine uses several subsystems to repair these structural anomalies before merging.

3.1 Browser UI Copy-Paste Repair (Rejoining Fractured Lines)

When copying code from web browser interfaces, long lines are often wrapped, resulting in syntax errors. The rejoining system fixes these issues:

  • Unbalanced State Scanning: Scans lines character-by-character to track open brackets ([ and string quotes.
  • Seamless Rejoining: If a line ends while a string quote or bracket is still open, and the next line begins at 0 indentation without any standard language keywords, the engine merges the lines into a single, cohesive statement.

3.2 Indentation Step Calibration

  • Indent Correction: Scans for lines ending in a colon (:) followed by an excessively deep indent on the next non-empty line (such as a jump from 4 to 12 spaces).
  • Inner Indentation Normalization: If a mismatch is detected, the engine calculates the offset difference and shifts the inner block back to a standard +4 space format.

3.3 Flat Signature Reconstruction

  • Flat Signature Detection: Detects cases where class or function signatures are pasted "flat" at 0 indentation while the body is correctly indented.
  • Relative Indentation Repair: It calculates the correct baseline indentation for the signature, repositions any decorators sitting above it, and updates the signature's indent to match the body.

4. The Merging & Alignment Pipeline

Once the patch is cleaned and normalized, it is merged into the codebase using a multi-tiered alignment pipeline.

                              [Incoming Patch Block]
                                        |
                          Does it contain class/method
                             definition signatures?
                                 /          \
                              [Yes]         [No]
                               /              \
                    Extract candidates         Is it a Unified Diff
                    & unwrap classes            or Aider Patch?
                           /                      /         \
                 Overwite existing             [Yes]        [No]
                 blocks if matched              /             \
                                          Apply Diff      Run Accordion
                                          heuristics      Fuzzy Matcher

4.1 Sliding-Window Context Scanner

If target line numbers are missing or incorrect, the context scanner uses a sliding-window search to locate the correct insertion point:

  • Fuzzy Line Normalization: Normalizes lines by removing spaces and comments, and converts tabs to spaces to compare lines by structure rather than exact formatting.
  • Weighted Search Algorithm: Assigns higher weights to complex lines (such as signatures, loops, or logic statements) while giving less weight to simple lines (like return, pass, or braces).
  • Sliding-Window Scoring: Slides the patch over the target file, calculating a similarity score at each position.
  • Gap Penalties: Penalizes matches that contain unexpected line gaps, ensuring the patch is merged in a tight, continuous block.

4.2 Accordion Stitching (Truncation Handling)

When patches contain truncation markers (such as ... or # rest of code), the accordion stitcher merges them while preserving local changes:

  • Anchor Identification: Finds stable, non-truncated matching blocks at the top ("head") and bottom ("tail") of the patch.
  • Fuzzy Anchor Expansion: If an exact match fails, it uses a fuzzy matcher to find the closest matching boundary lines.
  • Context Preservation: Replaces the truncation markers in the patch with the original code from the target file, ensuring local code is preserved.

4.3 Structural Class/Method Wrapper Unwrapping

  • Wrapper Detection: Detects if a patch wraps a modified method in a parent class signature (e.g. class MyClass: followed by a single modified method and truncation markers).
  • Sub-Candidate Extraction: Instead of replacing the entire class, the engine automatically extracts the nested method as a standalone candidate, locates the target class in the file, and merges the method into the correct class scope.

5. File Resolution & Nuclear Token Analysis

If a patch does not specify a target file, the engine uses indexing and keyword analysis to locate the correct file.

5.1 Token Extraction and Frequency Mapping

  • Identifier Extraction: Extracts all alphanumeric tokens longer than 4 characters from the patch, focusing on unique class, variable, and function names.
  • Boilerplate Filtering: Filters out common language keywords (such as import, return, or public).
  • Frequency Mapping: Maps each unique token to determine its density within the patch.

5.2 Heuristic Codebase Scanner

  • Index-Based Search: Scans the codebase index, searching file contents for the extracted tokens.
  • Heuristic Scoring: Ranks candidate files based on token match density, prioritizing files located in standard directories like /src/, /main/, or /app/.

5.3 Manual Resolution and Interactive Routing

  • Ambiguity Handling: If the search returns multiple candidates with similar scores, the engine displays an interactive list of matches sorted by score and file paths.
  • Manual Target Entry: Allows the user to select the correct target file, entry index, or create a new file if none exists.

6. Post-Patch Diagnostics & Abnormality Sanitization

After applying a patch, the engine runs a post-patch scan on the target file to clean up formatting issues and catch potential errors.

6.1 Character Sanitization

  • Tab-to-Space Conversion: Converts hard tabs to 4 spaces, providing a consistent layout across standard editors.
  • Hidden Character Removal: Removes non-breaking spaces (\xa0), zero-width spaces, and byte-order marks (\ufeff) that can cause compiler or runtime issues.

6.2 Comment and Boilerplate Cleanup

  • LLM Directive Removal: Removes LLM-specific comments, banners, and placeholders (such as // FIXED:, // UPDATED:, or ---).
  • Visual Line Normalization: Keeps standard inline code comments while cleaning up visual dividers and markdown formatting.

6.3 Misplaced Import Hoisting & Deduplication

  • Import Extraction: Identifies imports (such as Python import/from, C++ #include, or JS require/import) that have been nested inside function bodies or placed mid-file.
  • Safe-Zone Hoisting: Moves these imports to the file's safe zone (the top of the file, after shebangs and file encoding declarations). Any duplicate imports are removed.

6.4 Duplicate Function Detection and Resolution

  • Scope Tracking: Scans the file to map the start, end, and name of all class and function scopes.
  • Duplicate Detection: Flags cases where the same function is defined multiple times within the same scope.
  • User Conflict Resolution: Displays a visual comparison of the duplicate definitions and prompts the user to select which version to keep.

6.5 Structural Flow Auditing

  • Orphan Structure Validation: Checks if any function or class definitions have been placed after the __main__ entry point. If it finds any, it issues a warning.

7. Fail-Safe Backups & Version Control Interop

The engine implements a session-locked backup and restoration system to protect files against corruption.

7.1 Session-Locked Differential Backups

  • Pre-Flight Backups: Before applying any changes, the engine creates a copy of the target file in a local subfolder named ep_backups.
  • Backup Naming Scheme: Backups are named using the pattern [filename]_[session]_[letter]_[index].bak.
  • Space Optimization: Compares the target file against existing backups. If an identical backup already exists for the current session, it avoids creating a duplicate.

7.2 Safe Transactional Restore Engine

  • Checkpoint Rolling: Allows the user to roll back the entire codebase to previous states within the current session.
  • Transactional Restores: When a rollback is requested, the engine copies the current modified files to a hidden .redo folder before restoring the original backups. This allows the user to re-apply the undone patch using Ctrl+Y without re-copying it to the clipboard.

8. User Interface, Prompter Modals, & Test Suites

The user interface is an overlay terminal built on Pygame that displays logs, prompts, and code previews.

+-------------------------------------------------------------+
|                     PyTerminal Interface                    |
+-------------------------------------------------------------+
|                                                             |
|  [00:15] Monitoring Folder: C:\Project                      |
|                                                             |
|  +-------------------------------------------------------+  |
|  |             Glass Panel Layout Engine                 |  |
|  |                                                       |  |
|  |  [MATCH FOUND] Line 45                                |  |
|  |  - self.active = False                                |  |
|  |  + self.active = True                                 |  |
|  +-------------------------------------------------------+  |
|                                                             |
+-------------------------------------------------------------+

8.1 Performance-Tuned Rendering

  • Double-Buffered Flip: Draws all UI components to an offscreen surface before flipping it to the screen to prevent tearing and flickering.
  • Surface Caching: Caches rendered text strings as individual Pygame surfaces. This minimizes the overhead of font rendering, allowing the overlay to display hundreds of lines of styled text at 60 FPS.
  • Focus-Based Throttling: Detects when the window loses focus and slows down the redraw rate to minimize CPU and GPU usage.

8.2 Glass Panel Layout Engine

  • Aura Glow Rendering: Creates glowing border effects using alpha-blended radial draws and smoothed scaled boxes.
  • Symmetrical Highlights: Draws colored, double-lined borders around panels, giving the UI a modern, high-contrast look.

8.3 Interactive Prompters & Modals

  • Multiline Word-Wrap: Implements a real-time word-wrap layout engine that calculates word wrapping based on the font width and window size.
  • Asynchronous File Dialogs: Spawns OS-level file and folder dialogs in isolated threads, keeping the main Pygame rendering loop responsive.

8.4 Automated Regression Testing Suite

  • 77-Stage Headless Diagnostics: Includes a comprehensive test suite containing 77 automated diagnostics that test the system against extreme formatting, indentation, comments, and language edge cases.
  • Test Isolation: Runs each test in a sandboxed, temporary environment to ensure the user's actual codebase remains safe.

9. Code Stitcher Testing Blueprint

This table maps the core modules to the diagnostic tests that validate their stability.

Module System Target Behavior Tested Diagnostic Test Name
Diff & Hunk Engines Unified Diff Hunk Application test_unified_diff
Aider Search/Replace Parsing test_aider_patch
Duplicate Match Avoidance test_aider_duplicate_match_avoidance
Malformed Unified Headers test_diabolical_aider_malformed_headers
Missing Trailing Newlines test_diabolical_diff_no_trailing_newline
Whitespace-Only Hunk Scrubbing test_diabolical_aider_whitespace_only_hunk
Lexical Parsers Braced language parsing (C, C++, Java, JS) test_braced_lang_candidate_extraction
JS Arrow function nesting test_diabolical_js_arrow_nesting
TS generic bracket parsing test_diabolical_typescript_generics_bracket
Go struct tags test_diabolical_go_struct_tags
C++ initializer lists test_diabolical_cpp_initializer_lists
C++ namespace scopes test_diabolical_cpp_namespaced_class
Rust pattern matching braces test_diabolical_rust_pattern_matching_braces
PHP string variables test_diabolical_php_dollar_curly_braces
Jinja curly braces test_diabolical_jinja_curly_braces
Indentation & Formatting Flat Signature Dedenting test_flat_signature_dedent
Multiline signature dedenting test_diabolical_python_async_def_multiline_args
Inner-indent step calibration test_diabolical_python_dedent_healing
Consecutive comment indentation test_diabolical_consecutive_comments_indentation
Tabs to spaces conversion test_diabolical_mixed_indentation_tab_space
Blank line collapsing test_consecutive_blank_line_collapse
Intended blank line preservation test_diabolical_multiple_blank_lines_preservation
Fuzzy Accordion Stitcher Headless Alignment Failsafe test_headless_alignment_failsafe
Nested try/except alignment test_diabolical_nested_try_except_alignment
Omission/Ellipsis merging (...) test_diabolical_lazy_stitching
Inline truncation cleanup test_diabolical_inline_truncation_vaporization
HTML component alignment test_html_headless_component_alignment
String & Comment Masking Python raw and f-string masking test_diabolical_string_masking
Nested braces in f-strings test_diabolical_fstring_nested_braces
JS template literals test_diabolical_js_template_literals
Unclosed comments test_diabolical_c_comment_unclosed
Escaped quotes inside strings test_diabolical_escaped_quotes_in_python
Multi-line decorators test_diabolical_decorator_multiline
Clipboard, UI, & Sanity Rejoining fractured browser copy-paste lines test_diabolical_bracket_repair_ui_fracture
Chat log code-block extraction test_diabolical_markdown_extraction
Top-level import hoisting & cleanup test_top_level_imports_hoisting
Shebang header preservation test_diabolical_shebang_preservation
Duplicate function elimination test_diabolical_duplicate_function_scrubbing

Head to https://sharples3.gumroad.com/l/codestitcher for Pro Edition.

Please note that Windows Defender SmartScreen may flag this program/install as 'potentially dangerous'. This is due to the tool being new and limited install base. We promise there is no spy/malware in this program.