CTXSPLICE / DOCUMENTATIONView Markdown source
Run CtxSplice locally to process archives or connect a destination. This documentation site does not accept files or credentials.

CtxSplice technical walkthrough

A guide for users who want to understand CtxSplice and contributors extending it. Examples use synthetic data. Source links are relative to this repository; code excerpts are intentionally partial where noted.

For installation and first use, start with the README. For the API-key workflow, see Connected migration. For tested versions and remaining validation gaps, see Compatibility.

1. What the application does

CtxSplice converts a ChatGPT conversation export into a platform-independent conversation graph, applies explicit project mapping and privacy rules, removes conservative exact duplicates, and produces local files. You can run it through a command-line interface or a browser interface served by Python on your own machine.

The core is a local transformation pipeline with an optional connected migration workflow. The browser sends the chosen file to a loopback Python server. Offline processing needs no account credentials or outbound API calls. Connected mode uses an Open WebUI API credential to discover folders, prepare a read-only destination plan, and execute approved folder creation and conversation imports. It does not connect to the ChatGPT account or fetch its history. Durable migration manifests support recovery without a CtxSplice database or cloud account.

Canonical JSON and Markdown preserve all graph nodes accepted by the source adapter. This does not mean every original export field or attachment is preserved: the current parser primarily carries text, graph structure, timestamps, project references, and provenance. Open WebUI serialization is a destination-specific representation with further limitations. The connected profile targets v0.13.4; its API connection, creation of named folders, associated conversation transfer, and readback checks have been verified with synthetic data. Production recovery and zero-import rerun are validated for the preserved checkpoint. Connected target-container restart persistence remains unverified.

2. Architecture and code map

CLI (cli.py)                         Browser (web/app.js)
     |                                     |
     |                              Local HTTP API (ui.py)
     +------------------+------------------+
                        |
                 ingestion.read_export
                        |
                ChatGPTSource.parse
                        |
              Canonical Archive graph
                        |
                 pipeline.process
         exclusions -> mapping -> dedup -> redaction
                        |
             select_archive (when selecting)
                        |
                  render_files
          +-------------+----------------+
          |             |                |
       Markdown    canonical.json   Open WebUI candidate
                      report.json       (optional)
          +-------------+----------------+
                        |
           CLI directory / browser ZIP download

Selected canonical archive + explicit project names
                        |
       migration.engine.build_plan (destination reads)
                        |
            exact plan review and approval
                        |
       execute_plan -> OpenWebUIClient -> Open WebUI
             |                        |
     ManifestStore checkpoints   folder/chat readback
             +----------+-------------+
                        |
                 verified report
File or directory Responsibility
models.py Canonical dataclasses, graph validation, stable JSON, hashes
ingestion.py Bounded ZIP/JSON reading and archive safety checks
adapters/__init__.py Source and destination interface contracts
adapters/chatgpt.py ChatGPT-shaped records into canonical models
privacy.py Configurable regular expressions and exclusion lists
pipeline.py Project mapping, exact deduplication, redaction, aggregate report
exports.py Validate selected IDs, prune unused projects, render outputs
adapters/markdown.py Human-readable graph export with inert source text
adapters/openwebui.py Experimental chat JSON, per-project files, import guide
connectors/base.py Destination client protocol used by the migration engine
connectors/openwebui.py Version-pinned HTTP transport, authentication, bounded responses, GET retries
migration/engine.py Plan construction, approved execution, reconciliation, readback verification
migration/verification.py Strict field diagnostics and explicit lossy NUL transformation reporting
migration/audit.py Read-only graph/folder/marker integrity audit shared by CLI and Studio
connectors/ndjson.py Bounded byte-LF export framing that preserves Unicode line separators
migration/manifest.py Private atomic state and exclusive execution lock
migration/studio.py Backend-owned credentials, plan routes, background worker and progress
migration/cli.py ctxsplice migrate options and approval handling
cli.py Offline CLI arguments, orchestration, private output files
ui.py Loopback HTTP server, temporary uploads, preview cache, ZIP responses
web/index.html Page structure and controls
web/app.css Layout, responsive styling, focus and motion behavior
web/app.js Upload flow, filters, selection state, API requests
web/demo.json Bundled synthetic sample for trying the UI
tests/ Synthetic fixtures and behavioral tests
pyproject.toml Package metadata, entry points, dependencies, bundled assets
.github/workflows/ci.yml Automated test and package checks

The src/ layout keeps importable application code separate from tests and repository documents. There is no React build or frontend dependency installation: the UI is plain HTML, CSS, and JavaScript shipped inside the Python package.

3. Canonical models: why a graph matters

A conversation is not always one straight list. Editing a prompt or regenerating a response can produce alternate descendants. The canonical model represents each message with an ID and parent ID, so alternate paths survive.

root (structural)
  └─ user-1
       ├─ assistant-a
       └─ assistant-b  <- current_node

Both assistant responses are stored. current_node identifies the currently selected node; it does not delete the other path. The UI's “branches” count is actually the number of graph leaves, rather than the number of branching decisions.

Python dataclasses give these records explicit fields and default values without a separate database schema.

From src/ctxsplice/models.py:

@dataclass(frozen=True)
class Provenance:
    adapter: str
    artifact_sha256: str
    record_index: int
    source_id: str
    source_member: str | None = None


@dataclass
class Message:
    id: str
    parent_id: str | None
    role: str
    text: str
    created_at: float | None = None
    structural: bool = False
    provenance: list[Provenance] = field(default_factory=list)


@dataclass
class Project:
    id: str
    name: str
    provenance: str = "explicit-mapping"


@dataclass
class Conversation:
    id: str
    title: str
    messages: list[Message]
    current_node: str | None
    source_project_id: str | None = None

Archive wraps conversations, project definitions, and schema_version=1. source_project_id is an association observed in the source export. project_id is the destination project selected by your mapping. They serve different purposes and can differ.

Provenance records the adapter, source payload SHA-256, record index, original conversation ID, and optional ZIP member name. It is a trace back to an input record, not a copy of the original file. A hash is useful for identity checks; it is not encryption or a guarantee of authenticity.

Conversation.validate() rejects duplicate node IDs, an unknown current node, missing parents, and cycles. It follows parent chains iteratively with per-path and completed-node sets. Keeping structural roots allows this validation to preserve links through nodes without visible message text.

4. Ingestion: reading a large export safely

read_export(Path) accepts .json and .zip. It returns parsed records and an input digest. JSON parsing rejects duplicate object keys, invalid UTF-8, invalid syntax, and non-finite numeric values.

The current limits are:

Limit Current value Meaning
ZIP file size 8 GiB Compressed archive on disk / accepted UI upload
JSON payload 256 MiB Combined uncompressed selected conversation JSON
ZIP member count 100,000 Number of archive entries
Selected JSON compression ratio 200:1 Maximum declared expansion ratio per selected part

A 1.75 GB ZIP can therefore be accepted if its conversation JSON is within the JSON budget. The application skips attachment payloads; it does not decompress the entire ZIP. The UI still uploads the whole ZIP to a temporary local file before the parser can seek through it.

ZIP selection supports exactly one conversations.json, or numbered files such as conversations-000.json, conversations-001.json, and so on. Numbered parts must share a directory and start at zero with no gaps or duplicate numeric indices. Mixed single-file and numbered layouts are rejected as ambiguous.

All ZIP entries are checked for unsafe paths, duplicate names, symlinks, and encryption. Members are never extracted to their embedded filesystem paths. Only selected JSON members are opened.

From src/ctxsplice/ingestion.py:

                selected, split = _select_conversations(members)
                if sum(member.file_size for member in selected) > MAX_BYTES:
                    raise BridgeError("Conversation JSON payloads exceed the combined 256 MiB JSON limit")
                records = ExportRecords()
                parts = []
                total_read = 0
                for member in selected:
                    if member.file_size / max(member.compress_size, 1) > 200:
                        raise BridgeError("Selected JSON exceeds compression ratio limit")
                    # Skip attachment bytes entirely and read one bounded part at a time.
                    with archive.open(member) as stream:
                        raw = stream.read(MAX_BYTES - total_read + 1)
                    total_read += len(raw)
                    if total_read > MAX_BYTES:
                        raise BridgeError("Conversation JSON payloads exceed the combined 256 MiB JSON limit")

Split records carry a hash and record index for their own source part through ExportRecords, a list subclass with provenance metadata. A combined digest uses the numerically ordered filenames and part hashes, so physical ZIP entry order does not determine identity.

The parser can detect a missing middle part, but cannot prove that the final part is present. It does not currently interpret an export manifest to verify completeness. The JSON byte limit is also not a total memory limit: decoded Python objects, copies, rendered strings, and ZIP buffers need additional memory.

5. Source adapter: translating ChatGPT fields

Adapters isolate platform-specific schemas from the rest of the code. Python Protocol describes the methods an adapter should provide; there is no dynamic plugin discovery or automatic runtime registration.

From src/ctxsplice/adapters/init.py:

"""Adapter contracts keep platform schemas outside the processing engine."""
from typing import Protocol
from ..models import Archive


class SourceAdapter(Protocol):
    def parse(self, data: object, artifact_sha256: str) -> tuple[Archive, list[str]]: ...


class DestinationAdapter(Protocol):
    def render(self, archive: Archive) -> dict[str, str]: ...

ChatGPTSource.parse() expects a list of conversations, each containing a mapping dictionary of nodes. It sorts node IDs, builds messages, preserves structural nodes, joins string content parts with newlines, and validates the resulting graph. Non-text parts trigger an omission warning. It does not migrate attachment bytes or preserve every original metadata field.

Project membership comes from project_id, or a conversation_template_id beginning with g-p-. A generic custom GPT identifier beginning with g- is not treated as a project. Conflicting project references are rejected.

From src/ctxsplice/adapters/chatgpt.py:

            title = record.get("title", "Untitled")
            project = record.get("project_id")
            template = record.get("conversation_template_id")
            # Observed export metadata: project references use g-p-, while g-
            # custom GPT references must not be treated as project membership.
            template_project = template if isinstance(template, str) and template.startswith("g-p-") else None
            if project is not None and template_project is not None and project != template_project:
                raise BridgeError("Conflicting exported project references")
            if project is None:
                project = template_project
            if not isinstance(title, str) or (project is not None and not isinstance(project, str)):
                raise BridgeError("Invalid conversation metadata")

The source adapter does not fetch project names from your account. Numbered labels such as “Source project 09” are local placeholders assigned to sorted source IDs. They are not actual project names and should not be used as permanent mapping keys. A missing exported association means no supported link was found; it does not prove the chat was never part of a project.

6. Explicit project mapping

This invented configuration defines destination project names, routes source projects, and overrides individual conversations:

{
  "projects": {
    "garden": "Garden planning",
    "learning": "Learning"
  },
  "source_projects": {
    "g-p-example-garden": "garden"
  },
  "conversations": {
    "original-chat-example": "learning",
    "original-chat-to-unmap": null
  }
}

projects defines canonical destination IDs and display names. source_projects maps source IDs into those definitions. conversations uses original source conversation IDs, before the pipeline assigns hashed output IDs. A conversation override takes precedence over its source project, including an explicit null override. References to undefined destination projects are rejected.

The runtime only uses the mapping you provide through the CLI or UI. An account-specific map prepared separately is an input file, not an embedded lookup service. The browser's “Load project map” control reads a local JSON file into the configuration textarea; it does not synchronize with ChatGPT.

The UI names a source group only when every surviving conversation in that group agrees on one mapped destination with a known name. A source group split across several destinations retains its placeholder group label; individual conversation rows can still show their destination names.

7. Processing order, IDs, and deduplication

process() first validates the mapping and deep-copies the input archive so transformation does not mutate the caller's original graph. It then:

  1. Sorts conversations deterministically by source ID and graph fingerprint.
  2. Applies conversation and source-project exclusions.
  3. Resolves the explicit destination project.
  4. Deduplicates by (graph fingerprint, destination project).
  5. Merges provenance for duplicates.
  6. Assigns a deterministic c-... output ID to each retained conversation.
  7. Redacts conversation titles and message text.
  8. Creates mapped project definitions and redacts their names.
  9. Calculates aggregate counters.

Deduplication is deliberately conservative. Node IDs, parent links, roles, text, timestamps, structural status, current node, and source project participate in the fingerprint. Titles and provenance do not. Two semantically identical chats with different node IDs may remain separate. Equal content routed to different destinations remains separate.

From src/ctxsplice/models.py:

def fingerprint(self):
    # Conservative deduplication: graph identity, text, timestamps and source
    # project must all agree. Titles and provenance do not define identity.
    return digest({"nodes": [
        {k: v for k, v in asdict(m).items() if k != "provenance"}
        for m in sorted(self.messages, key=lambda m: m.id)
    ], "current": self.current_node, "project": self.source_project_id})

From src/ctxsplice/pipeline.py:

        explicit = mapping.get("conversations", {})
        source = mapping.get("source_projects", {})
        target = explicit.get(conversation.id, source.get(conversation.source_project_id))
        key = (conversation.fingerprint(), target)
        if key in unique:
            existing = unique[key]
            existing.provenance.extend(p for p in conversation.provenance if p not in existing.provenance)
            by_id = {m.id: m for m in existing.messages}
            for message in conversation.messages:
                by_id[message.id].provenance.extend(p for p in message.provenance if p not in by_id[message.id].provenance)
            report["duplicates"] += 1
            continue
        conversation.id = "c-" + digest(key)
        conversation.project_id = target
        if target is None:
            report["unmapped"] += 1

Deduplication happens before redaction so two different originals that both become [REDACTED] are not accidentally merged. Output IDs are also assigned before redaction. Changing privacy patterns can change exported text without changing that ID. Changing graph content or destination mapping can change the ID.

Deterministic JSON serialization sorts object keys, uses consistent separators, and rejects NaN. Repeated equivalent inputs and configuration produce stable IDs and rendered file content. This does not imply byte-identical ZIP containers: ZIP timestamps and compression metadata are a separate concern.

8. Privacy filtering

The default policy matches email-like text, certain sk-... strings, and simple password/API-key/token assignments. Each regular expression replaces matches with [REDACTED]; the report counts matches across all passes.

From src/ctxsplice/privacy.py:


    def redact(self, text):
        count = 0
        for pattern in self.patterns:
            text, matches = re.subn(pattern, "[REDACTED]", text)
            count += matches
        return text, count

Example custom policy:

{
  "exclude_conversations": ["original-chat-example"],
  "exclude_projects": ["g-p-example-private"],
  "patterns": ["(?i)private-example-value"]
}

Providing patterns replaces the defaults. An empty list disables text redaction. Omitting it keeps the defaults. UI custom policy JSON takes precedence over the privacy toggle.

Exclusions happen before deduplication; excluded conversations never enter rendered outputs. Excluded project IDs are source project IDs. Redaction covers titles, message text, and mapped project names. Opaque IDs, provenance, and timestamps remain, and patterns do not detect every possible secret. Treat custom regex configurations as trusted: a pathological regex can be slow.

9. Selection: what you see versus what you transfer

Preview produces the processed archive. Selection chooses a subset of that archive afterward. The browser stores selected canonical conversation IDs in a JavaScript Set, which preserves selection across pagination and filtering.

UI action Effect on selected conversations
Project filter or title search Changes visible rows only
Individual checkbox Adds/removes that conversation
Select project-linked only Replaces selection with chats having a source project link
Add filtered conversations Adds all matching rows across all pages
Remove filtered conversations Removes all matching rows across all pages
Select all / Clear all Replaces selection with every chat / none

A manually mapped conversation without an exported source project link does not qualify for “project-linked only.” That button tests the source association, not whether a destination name was supplied.

From src/ctxsplice/web/app.js:

selectedConversationIds = new Set(data.conversations.map(c => c.id));

This excerpt from preview rendering initializes selection to all processed conversations. Later controls add or remove IDs; they do not edit the canonical message graph.

The connected plan also uses these selected canonical IDs. At download time, the browser sends selected IDs to /api/export. Python independently rejects empty selections, duplicate IDs, non-string IDs, and IDs absent from the current preview. Client-side checkboxes alone are not trusted. select_archive() also removes project definitions unused by the selected conversations.

The selection report includes selected counts and a nested preview_report. Redaction, exclusion, and deduplication counters in that nested report cover the full preview, not just selected chats. Changing selection does not re-run privacy processing.

10. CLI execution

The package installs two commands:

[project.scripts]
ctxsplice = "ctxsplice.cli:main"
ctxsplice-ui = "ctxsplice.ui:main"

A dry run reads, parses, maps, deduplicates, and redacts, then prints a report. It does not create export files:

ctxsplice /path/to/export.zip --project-map /path/to/project-map.json --dry-run

Writing requires --write, an output path whose parent exists, and a new destination directory:

ctxsplice /path/to/export.zip   --project-map /path/to/project-map.json   --project-linked-only   --destination openwebui-candidate   --write --output /path/to/new-export

Optional --privacy-policy provides custom exclusions and patterns. Optional --openwebui-folder-map requires the candidate destination. The CLI supports bulk project-linked selection; individual checkbox selection is a UI feature. CLI policy exclusions can exclude particular original conversation IDs.

The writer renders into a private staging directory, creates files with mode 0600 and directories with 0700, reserves the destination, and moves staged entries into it. Existing destinations are rejected. Cleanup handles ordinary failures; the multi-entry move is not one atomic filesystem transaction across a hard process interruption. These permissions are filesystem access controls, not encryption.

Expected validation failures use BridgeError with content-free messages. Other anticipated input/output errors return a generic message. CLI success returns exit code 0; handled failure returns 2.

11. Local web server and browser flow

ctxsplice-ui starts a standard-library ThreadingHTTPServer at http://127.0.0.1:8765. Connected execution runs in a backend worker thread while the browser polls progress. Session locks prevent archive/reset/reconnection changes during execution. The server is intended for one local user. It does not expose a multi-user deployment model.

Session state

StudioServer holds a random token, a processed preview_archive, a preview_report, and a full-preview ZIP bundle. This is in process memory, not a database. Reset or server shutdown clears the preview references. Connected migration has separate durable checkpoint files; clearing a preview does not delete that state. Multiple tabs share the same server-side preview state.

API routes

Method and route Purpose
GET / Serve HTML with this launch's session token
GET /app.js, /app.css, /demo.json Serve allowlisted bundled assets
POST /api/preview Upload raw ZIP/JSON, process it, cache archive, return summaries
POST /api/export Validate selected IDs and return a newly rendered selection ZIP
POST /api/reset Clear cached preview/archive/report
GET /api/download Legacy route returning the cached full-preview ZIP
POST /api/migration/connect, /disconnect Establish or clear the backend destination client
POST /api/migration/plan Read destination state and build a plan for selected IDs
POST /api/migration/execute Start the exact approved ready plan
GET /api/migration/status Connection/progress/result polling
GET /api/migration/report, /manifest Read result or back up stopped execution state

The current UI download button uses POST /api/export, not the legacy full-preview route. A custom client must use the selection endpoint if it wants only selected chats.

Preview request

The browser sends the original File as the request body, with format and percent-encoded configuration headers. The server reads the upload in 64 KiB chunks into a temporary directory. read_export() parses the file; the temporary upload is removed before canonical processing continues. Parsed objects and prepared ZIP buffers remain in session memory.

The response contains aggregate counters, redacted conversation titles, message/leaf counts, source groups, and mapped project definitions. It does not send full message bodies for the conversation table. The preview currently renders a full archive ZIP even when you intend to select a small subset afterward, which adds time and memory overhead.

Download request

The browser submits JSON containing conversation_ids, candidate, and optional folder_map. The server selects from the cached processed archive, renders that subset, and builds a ZIP in BytesIO. The browser receives a Blob and triggers its standard save/download flow. It does not upload the original archive a second time.

Browser state and stale results

revision tracks settings changes so an older asynchronous response does not replace a newer state. busy disables upload/configuration controls during preview work. Choosing a file resets cached server data. Mapping/privacy edits invalidate the visible preview and require another preview. Candidate and folder-map choices are applied when generating the selected download.

No browser localStorage persistence is implemented for the map or selections. Reloading the page resets browser controls; stopping the server discards cached processing state.

Local request protections

The server checks the exact loopback Host, rejects foreign Origin values, checks cross-site fetch metadata for API calls, and requires X-CtxSplice-Token for ordinary API calls. The native credential form instead supplies a body CSRF token so frontend JavaScript does not read the API key. A Content Security Policy restricts resource/network loading to the local origin. Responses use no-store and nosniff headers. The root document uses same-origin referrers to support native form Origin handling; other responses use no-referrer. The connection response alone permits same-origin framing for its result iframe. HTTP request logging is disabled to avoid writing conversation-related paths or data into access logs.

These controls support a local tool. They do not turn the server into an authenticated public hosting service or protect against every process already running as your local user.

12. What each exported file contains

selected-export/
├── canonical.json
├── report.json
├── markdown/
│   └── c-<hash>.md                 # one per selected conversation
├── openwebui-candidate.json        # optional combined candidate
└── openwebui/                      # optional
    ├── candidate-report.json
    ├── project-index.json
    ├── IMPORT-GUIDE.md
    └── projects/
        └── garden-planning--<hash>.json

render_files() is the shared export composition point.

From src/ctxsplice/exports.py:

def render_files(archive, report, candidate=False, folder_map=None):
    result = MarkdownDestination().render(archive)
    result['canonical.json'] = stable_json(archive.to_dict()) + '\n'
    result['report.json'] = stable_json(report) + '\n'
    if candidate:
        result.update(OpenWebUICandidate(folder_map).render(archive))
    return result

Canonical JSON

Contains the schema version, selected conversations, their complete accepted canonical graph, provenance, and used destination project definitions. It is the richest current output representation. The current source parser is a ChatGPT parser; there is no dedicated canonical JSON input adapter for round-tripping this output.

Markdown

Lists every canonical node with ID, parent, role, structural flag, and text. Source text is indented as code blocks so embedded HTML, image links, and Markdown are treated as inert content. This favors safe inspection over reproducing the original rich formatting. Filenames use generated conversation IDs rather than untrusted titles.

Open WebUI candidate

The candidate serializer retains only non-structural user and assistant nodes. It rebuilds children lists from parent links and reconnects surviving nodes through omitted ancestors. System/tool/other roles remain in canonical JSON and Markdown, but are omitted from the candidate. Chats with no retained nodes are omitted entirely. Candidate timestamps are integers; assistant messages include done: true.

This is why candidate counts can be lower than selected canonical counts. candidate-report.json reports omitted chats/nodes and folder assignments.

Project names appear in metadata and the project index. An invented folder map looks like:

{
  "garden": "existing-openwebui-folder-id"
}

Keys are canonical destination project IDs from your project map. Values must be IDs of folders that already exist on the target. Offline export validates the map's shape without contacting Open WebUI. Connected mode separately discovers and verifies actual destination folders.

The serializer adds folder_id from this map. It does not create folders, restore project instructions, upload knowledge, or configure memory. Metadata names alone cannot guarantee visible named folders after import. Without a verified folder map, the generated guide describes importing one project file at a time and moving the batch manually.

Use either the combined candidate JSON or the individual project JSON files for a given set of chats. Importing both can duplicate chats. Per-project files contain only mapped destination projects; selected unmapped chats can still appear in the combined candidate.

The candidate toggle remains an offline file generator; enabling it does not perform an import and is not required for connected migration. Offline synthetic imports and connected folder/chat creation have been validated against v0.13.4. Other installed versions require independent contract review and tests.

Connected migration internals

From preview to approved writes

The Studio opens with a Field guide callout and preparation steps. After archive preview, the connected panel becomes visible. Users select canonical conversations, enter the destination URL and Open WebUI API key, test read access, preview a plan, and approve it. Connection testing alone never creates folders or chats. The CLI exposes the same engine through ctxsplice migrate; see the command examples.

OpenWebUIClient.connect() checks the exact supported version and authenticated account using /api/version and /api/v1/users/user/status. It then discovers writable folders. HTTPS certificate validation is enabled, redirects and environment proxies are disabled, and only GET requests have bounded retries. HTTP requires an explicit private-network testing opt-in. The client holds credentials in backend memory; reports and checkpoints do not include them.

build_plan() resolves each selected canonical project using an explicit folder choice, trusted recorded mapping, or an unambiguous same-name folder. Missing named folders can be proposed for creation. Duplicate names, inaccessible folders, changed tracked payloads and source-linked chats lacking names can become conflicts. No project name is guessed from conversation text.

The plan binds the destination account, source fingerprint, selected archive fingerprint and manifest revision. execute_plan() rejects stale or mismatched approval. Its initial checks include this excerpt from migration/engine.py:

if not plan['ready'] or digest(archive.to_dict()) != plan['archive_fingerprint']:
    raise BridgeError('Migration plan has conflicts or the selected archive changed')
if plan['counts']['reimports'] and not confirm_reimport:
    raise BridgeError('Explicit reimport requires separate confirmation; duplicates may be created')

The engine captures real folder IDs returned by the destination and supplies them to the existing candidate serializer. It reuses that serializer rather than maintaining an independent connected format:

def candidate_chats(archive, folder_map=None):
    # Reuse the offline adapter rather than maintaining a second target format.
    return OpenWebUICandidate(folder_map).chats(archive)

Verification and recovery

Before non-idempotent operations, ManifestStore saves pending state. It uses private files, temporary-file replacement, filesystem flushes, and an exclusive sidecar lock. Studio state defaults to $XDG_STATE_HOME/ctxsplice/migrations or ~/.local/state/ctxsplice/migrations; --migration-state-dir overrides it. Checkpoints contain identifiers, hashes, statuses and attempt history, not message text or credentials. Protect these identifiers nonetheless.

After import, authenticated reads check account ownership, actual folder ID, title, supported message IDs/text/roles/timestamps, parent and children links, current branch and project metadata. HTTP 200 alone is not verification. Canonical JSON and Markdown retain the richer accepted graph; connected imports still omit structural/system/tool nodes and attachment bytes.

For uncertain imports, migration markers in metadata support bounded account-export reconciliation. Exactly one verified match can recover the operation; missing or ambiguous matches require review. POST requests are not blindly retried. On rerun, trusted manifest destination IDs are checked before skipping verified records. Losing the manifest, replacing the destination database, editing marker metadata, or using separate concurrent manifests can defeat duplicate prevention. Explicit reimports require separate approval and can create duplicates.

Automated mocks exercise these failure and rerun cases. Live v0.13.4 synthetic acceptance confirmed two named folders, associated conversations and API readback. Production recovery and zero-import rerun are validated; connected target-container restart persistence remains unverified. See the compatibility matrix for the validation boundary.

13. Tests and GitHub Actions

Tests use synthetic input rather than personal exported data.

Test file Main concerns
test_bridge.py Graph validation, parsing, split ZIPs, limits, provenance, deduplication, privacy, mapping, CLI writes
test_selection.py Selected-only output, unknown/duplicate IDs, unused-project pruning, candidate grouping and folder IDs
test_ui.py Real local HTTP requests, headers, tokens, origins, preview/reset/export behavior
test_web_controls.py JavaScript controls in a Node-based fake DOM; map loading, selection, approval and guide navigation
test_openwebui_v0134.py Version-specific candidate envelopes, folder assignment and importer contracts
test_migration.py Mock HTTP planning/execution, conflicts, checkpoints, reconciliation and reruns
test_migration_ui.py Connected routes, native credential form, approval and progress
test_openwebui_live.py Explicitly gated disposable live migration and repeat-run acceptance

The fake-DOM tests do not replace actual responsive-layout or browser usability inspection. Python HTTP tests may require permission to bind loopback sockets in a restricted execution environment.

For local development:

python3 -m venv .venv
source .venv/bin/activate
python -m pip install -e '.[dev]'
python -m pytest -q
python -m build
ctxsplice tests/fixtures/chatgpt-synthetic.json --dry-run
ctxsplice-ui --help

-e means an editable installation: Python imports this checkout's source. .[dev] adds pytest and the build tool. The application itself declares no external runtime dependencies.

The GitHub Actions workflow runs on pushes and pull requests using Ubuntu with a Python 3.11–3.14 matrix. Each job installs the package, runs tests, builds distributions, exercises a synthetic CLI dry run, and checks that the UI command starts far enough to print help. Repository token permissions are read-only. The workflow does not publish a package or deploy the UI.

Packaging explicitly includes web/*.html, web/*.css, web/*.js, and web/*.json, because installed UI commands need these assets after installation outside the source tree. A successful source checkout alone would not prove that a built wheel includes the UI.

The optional live test requires explicit disposable-instance configuration and credentials; an ordinary test run does not authorize live destination writes. See the connected migration guide for its environment variables and repeat-run procedure.

14. How to extend the application

Add a source format

Implement a class with parse(data, artifact_sha256) that returns an Archive plus warnings. Translate source relationships into canonical parent links, preserve structural nodes where needed, attach provenance, and call graph validation. Add synthetic fixtures for branches, missing fields, invalid parents, role/content variants, and project associations.

Then wire explicit source selection into the CLI and local server. The existing protocol provides an architectural boundary; adding a class alone does not register it. If a format needs different file discovery, extend ingestion as well.

Add a destination

Implement render(archive) returning a dictionary of safe relative filenames to text. Keep platform-specific field conversion in the destination adapter and add it through render_files() and the relevant command/UI choice. Never use untrusted raw titles as filesystem paths. The current CLI writer assumes its bundled renderers return safe paths; a future plugin system would need stronger output-path validation.

Test both what the destination preserves and what it omits. A valid JSON file is not proof that an external application can successfully import it. Validate a synthetic import against the actual target version before declaring compatibility.

Change selection behavior

Browser selection belongs in selectedConversationIds; view filtering belongs in currentFiltered. Keep server validation in select_archive() so new client controls cannot bypass selection constraints. Verify the downloaded file contents, not only the button's displayed count.

15. Troubleshooting from the code's behavior

Symptom Explanation / next check
“Source project 09” instead of a name Source link exists, but a destination name is missing or the group has multiple destinations. Check exact source-ID mapping, then preview again.
More rows visible than the download count Filters control visibility; selected IDs control the ZIP. Check the selection summary.
Project-linked-only excludes a manually mapped chat The action tests the exported source link, not destination mapping. Add that chat individually if desired.
Offline candidate import has no named folders Offline metadata does not create folders. Use connected migration for approved folder creation, or explicitly map existing target folder IDs for offline imports.
Candidate contains fewer chats/messages Unsupported roles/structural nodes are omitted. Compare candidate-report with canonical output.
Large ZIP accepted but processing fails on JSON size The 8 GiB compressed ZIP cap and combined 256 MiB conversation JSON cap are separate.
Redaction count seems larger than selected content Nested preview counters cover all previewed conversations.
Newly edited code does not appear in the UI Confirm which checkout/package starts the command. Reinstall with python -m pip install . or use an editable development install; stop/restart that server and refresh the browser.
API connector is missing First generate a preview, then find the connected panel. If absent, confirm the installed package is current rather than only running git pull.
Port 8765 is occupied Stop the existing Studio in its terminal or choose ctxsplice-ui --port 8770. A bind failure can currently also produce a secondary cleanup AttributeError.
API key returns 403 Check destination API-key permissions, allowed endpoints and the user-status feature. Do not paste the credential into an issue or log.
“Selection does not match this preview” Selected IDs belong to a different or reset preview. Preview again before exporting.
A missing final numbered part is not reported Current ingestion checks continuity of present parts, not manifest-backed final completeness.

16. Practical boundaries to remember

This is a local text-and-graph migration utility with explicit mappings and optional approved Open WebUI API imports. It does not provide a full account backup, attachment migration, automatic project-name discovery, guaranteed privacy sanitization, or project instruction/knowledge restoration. Source and target compatibility labels remain conservative. Large exports are supported through bounded input reads, but canonical processing and output rendering still hold substantial data in memory.

For a focused code-reading order, start with models.py, then adapters/chatgpt.py, pipeline.py, exports.py, and the destination adapters. Read cli.py to see the short command-line orchestration path, then ui.py and web/app.js for session caching and interactive selection. Follow migration/studio.py into migration/engine.py, connectors/openwebui.py, and migration/manifest.py for the connected execution path.

Connected source entry points: client, engine, manifest, Studio routes, CLI.

Read-only audit and production follow-up

migration/audit.py independently checks the selected archive against the preserved checkpoint and authenticated destination readback, then streams markers with connectors/ndjson.py. The audit never imports, creates folders or saves checkpoints. Studio runs it in a worker and keeps its report separate from migration results; the CLI exposes --audit. Interrupted or bounded-out marker scans cannot pass. See troubleshooting and compatibility for precise limits, loss reporting and recovery rules. Production results validate the observed 252-chat/15-folder case, not universal lossless conversion.

Conversation dates and folder ordering (future imports)

New imports preserve ChatGPT conversation create_time and update_time as optional canonical created_at and updated_at, with source-field provenance and the conversation's artifact/member/record provenance. Fractional seconds are truncated to integer Unix seconds. Missing/null values remain absent from the Open WebUI envelope; invalid, non-positive or out-of-range values fail validation. The v0.13.4 import API accepts these fields at envelope level. Folder ordering uses the row updated_at; unread chats can be prioritized ahead of read chats. Message dates alone do not determine folder order.

Existing graph IDs and deduplication fingerprints are unchanged: row dates are metadata, not graph identity. New payload fingerprints include supplied row dates. For a tracked legacy import, only an exact match of its previous envelope with row dates omitted retains the legacy contract. Its saved fingerprint, marker and destination ID are not rewritten. Missing legacy dates are not fabricated or backfilled. Independent auditing and unknown recovery use the same contract. When row dates were supplied at import, readback checks them strictly; a changed destination date blocks reconciliation instead of overwriting newer activity.

This change does not reorder the completed production migration. New-activity conflicts require review; do not reimport to resolve them. Automated HTTP tests cover ordering inputs, recovery and checkpoint compatibility. The opt-in live historical-ordering test requires a disposable v0.13.4 target. Authenticated live validation of this timestamp extension is pending; earlier production validation does not establish historical row-date preservation.