Refactoring a Terminal Data Export Tool: Pagination, Deduplication, and Structured Output
This article walks through the refactoring of a terminal-based export tool for conversation history from AI chat and coding assistants. It explains the layered architecture (credential, transport, domain, and presentation layers), credential handling and security constraints, on-demand loading with a cursor-based pagination state machine, three export modes with selection interaction, local deduplication keys, structured Markdown document generation, cross-platform delivery practices, and compliance reminders. Readers will learn how to turn ephemeral in-app history into searchable, versionable local knowledge assets.
1. Background: Why Conversation History Needs a Reliable Export Path
In day-to-day use of AI coding assistants and conversational applications, users accumulate large volumes of historical sessions with the model. This data often captures requirement gathering, solution exploration, code snippets, and debugging notes, and it has clear reuse value: it can be distilled into a team knowledge base, imported into note-taking software for structured organization, or used as source material for later search and retrospectives.
However, most online services only offer limited in-app browsing and lack a bulk, structured, versionable export mechanism. This leads to three typical pain points:
- Incomplete data ownership: Content lives on the server, users have no local copy, and a change in service policy can make the material inaccessible.
- Non-reusable formats: Even when an official packaged download exists, the output is usually a generic interchange format with redundant fields and messy hierarchy, making it hard to map directly to readable documents.
- High cost of repeated work: Exporting again and again reprocesses already-archived content, wasting time and generating unnecessary network requests.
The refactoring goal is therefore clear: without relying on server-side export files, build a complete pipeline of “obtain token → fetch list → fetch details on demand → deduplicate locally → generate structured documents,” with a terminal interface carrying the interaction experience.
2. Overall Architecture
The refactored tool can be abstracted into four layers, decoupled through well-defined interfaces so they can be tested and replaced independently.
- Credential layer: Handles token input, validation, and in-memory storage; never persisted to disk, never printed.
- Transport layer: Wraps paginated requests, retries, and rate limiting, hiding differences in the underlying API shape.
- Domain layer: Session list model, detail model, pagination cursor state machine, deduplication rules.
- Presentation layer: Full-screen terminal UI responsible for list rendering, selection, scroll pagination, and status messages.
A schematic module breakdown:
type Exporter interface {FetchList(cursor string, size int) (Page, error)FetchDetail(id string) (Conversation, error)}type Deduper interface {Exists(key string) (bool, error)Mark(key string) error}type Runner struct {api Exporterdedup Deduperwriter DocumentWriter}
The key benefit of this layering: the transport layer can adapt to API changes without touching interaction logic; the deduplication strategy can be swapped for a database or an object-storage manifest; document writing can be swapped for a different template engine.
3. Credential Acquisition and Security Constraints
The tool needs the user’s own session credential to read private history, which is a shared prerequisite for all similar approaches. To reduce risk, the design should follow these constraints:
- Memory-only holding: The token stays in process memory and is released on exit; it is never written to config files or logs.
- Minimal output: The terminal never echoes token fragments, and error messages mask them.
- Clear authorization boundary: Only requests necessary to read historical sessions are issued; no write operations are performed.
- User-obtained: The user inspects the request header field in the browser developer tools’ network panel and copies it; the tool includes no automated scraping logic.
It is worth stressing that a credential is equivalent to partial account permissions, and leaking it may allow data to be read. It is therefore advisable to invalidate the credential on the account side after use, and to avoid exposing the value in shared terminals, screen recordings, or screenshots.
4. On-Demand Loading and the Pagination State Machine
The number of historical sessions can reach hundreds or even thousands, and fetching everything at once causes first-screen latency and memory pressure. The core of on-demand loading is splitting “list fetching” and “detail fetching” into two phases:
- The list phase fetches only lightweight fields such as title, update time, and session identifier, appending page by page at a fixed page size.
- The detail phase triggers only when the user selects items or confirms export, fetching bodies one by one.
Cursor-based pagination is recommended over page-number offsets, because server-side data sees insertions and ordering changes, and offset pagination easily produces gaps and duplicates. A reusable state machine:
Idle -> LoadingFirst -> ReadyReady -> LoadingMore (scroll to bottom)LoadingMore -> Ready | EndReady -> Exporting (press Enter to confirm)Exporting -> ReadyAny state -> Quitting (press Q)
Three engineering details matter: serialize requests to avoid triggering risk controls; retry failed requests with a limited number of exponential backoffs; and continuously show “loaded/total” plus the current phase at the bottom of the UI so users do not think it has frozen.
5. Three Export Modes and Selection Interaction
The refactored tool offers three complementary export strategies covering different scenarios:
- Recent export: Processes only the most recent page or the most recent N items, suitable for daily incremental backups.
- Full export: Traverses all pages, suitable for a first full archive.
- Manual selection export: Marks items one by one in the paginated list, suitable for picking sessions on specific topics.
Terminal interaction follows common conventions to lower the learning curve: arrow or page keys move and scroll, Space toggles selection, Enter ends selection and starts export, Q quits. The selection state must be stored decoupled from scroll position, otherwise paging causes a “selection lost” defect. Implementation can record selected items in a set of identifiers and decide rendering by set membership rather than relying on list indices.
6. Local Deduplication
Deduplication is key to saving requests and guaranteeing idempotency. The decision key should combine “session identifier + content digest”: the session identifier alone cannot detect later additions to the same session, while the content digest alone may misjudge when titles repeat. In practice, compute a short hash over the normalized body with a digest algorithm and use it as a filename suffix or index key.
key = conversation_id + ":" + short_hash(normalize(markdown_body))if exists(key) { skip } else { write(); mark(key) }
Index storage options scale with volume: for small scale, use local file existence checks; for medium scale, use a single manifest file; for larger scale, use an embedded key-value store. Note that deduplication must happen after detail fetching and before writing to disk to actually save requests.
7. Structured Document Generation
The goal of export is “documents that can be read and searched directly,” so formatting quality determines the tool’s value. Recommended normalization rules:
- File names use “date + title,” with illegal characters replaced to avoid cross-platform path issues.
- Build directory hierarchy by month, forming a natural time index.
- In the body, separate “reasoning” and “final answer” blocks, presenting the former with quote or collapsed blocks to keep the main thread readable.
- Code snippets uniformly use fenced code blocks with the language annotated; tables and lists keep standard syntax.
- Write metadata in the header (export time, session identifier, message count) to ease later incremental comparison.
Sample directory shape:
conversations_export/2026-05/2026-05-18_refactoring-discussion_ab12.md2026-05-20_debugging-notes_c34d.md
8. Cross-Platform Delivery and Engineering Practices
The terminal program should ship as a single-file executable covering mainstream operating systems and common processor architectures, so users need no runtime environment setup. Engineering recommendations:
- Let the interaction library handle screen state and key events, and fully separate business logic from rendering, making a headless batch mode easy.
- Provide an equivalent script implementation for users without a graphical terminal, as a fallback path.
- Key logic (pagination cursor, deduplication key, filename sanitization) must have unit tests to avoid format regressions.
- Logging is off by default; if diagnostics are needed, output only phase information and counts, never credentials or bodies.
9. Risk and Compliance Reminders
Exporting one’s own historical data is reasonable use of one’s own data, but boundaries still apply: do not bypass the service’s access controls or rate limits; do not cache other people’s data in multi-user shared environments; if exported documents contain sensitive information, apply redaction and tighten access permissions. If a team needs long-term archiving, the safer approach is to place export artifacts into a controlled storage and backup system with versioning and periodic verification, rather than scattering them across personal terminal directories.
In summary, the technical substance of such a tool lies not in “scraping” itself but in four things: pagination state management, idempotent deduplication, format normalization, and security boundaries. Doing these four solidly turns volatile in-app conversation data into searchable, versionable, long-term reusable personal knowledge assets.
