Refactoring Conversation Archiving and Export: A Five-Layer Design

    This article walks through a practical refactor of a conversation archiving and export tool, breaking the export workflow into five independently evolving stages: data fetching, filtering, deduplication, rendering, and disk writes. It covers a five-layer architecture, a finite state machine for the terminal UI, cursor-based pagination for on-demand loading, credential handling boundaries, fingerprint-based idempotent exports, layered Markdown rendering, monthly storage layout, and distribution across platforms. Readers will find Go code examples, design constraints, and an evolution roadmap for building predictable, incremental, and reusable exports.

    1. Background: Why Export Needed a Refactor

    As AI coding tools and conversational assistants become part of daily development workflows, valuable technical context accumulates in chat history: debugging paths, option comparisons, code snippets, and root-cause conclusions. When that content stays inside a web session list, three practical problems appear.

    First, it is not controllable. Platform-side export usually offers only a full bulk download. Users cannot extract just the segments they care about, and they cannot confirm what was actually exported.

    Second, it is not incremental. Running the export again re-fetches and re-writes content that is already on disk, wasting network request quota and breaking local file modification times and version continuity.

    Third, it is not reusable. The raw data is deeply nested semi-structured text. Dropping it into a notes library produces broken hierarchy, fragmented code blocks, and reasoning mixed with final answers, which makes search and backlink organization nearly impossible.

    So the goal of the refactor is not “a different button.” It is to split export behavior into five independently evolving stages — fetch, filter, deduplicate, render, persist — and to provide predictable feedback at the interaction layer.

    2. Overall Architecture: Five Layers of Responsibility

    A maintainable export tool should be layered by responsibility, so networking, state, and rendering are not coupled inside one large function.

    1. ┌─────────────────────────────────────┐
    2. │ Interaction TUI render / keys / paging │
    3. ├─────────────────────────────────────┤
    4. │ Session Auth / list / detail fetch │
    5. ├─────────────────────────────────────┤
    6. │ Domain Models / selection / dedup │
    7. ├─────────────────────────────────────┤
    8. │ Rendering Markdown mapping / layout │
    9. ├─────────────────────────────────────┤
    10. │ Storage Monthly dirs / atomic write │
    11. └─────────────────────────────────────┘

    The interaction layer only cares about what is displayed and what the user pressed. The session layer handles credentials and pagination cursors for the remote API. The domain layer maintains immutable data structures and the selection set. The rendering layer maps the internal model to the target document format. The storage layer guarantees atomic and traceable writes. With this separation, swapping the transport (for example, moving from local file import to API fetching) does not affect rendering or storage.

    3. Interaction Layer: A State Machine for the Terminal UI

    The point of a terminal UI is not looking good; it is predictable state. Define an explicit finite state machine rather than scattered boolean flags.

    1. type Mode int
    2. const (
    3. ModeLoading Mode = iota // fetching the list
    4. ModeBrowse // browsing and paging
    5. ModePicking // selecting conversations
    6. ModeExporting // running the export
    7. ModeDone // result summary
    8. )
    9. type Model struct {
    10. mode Mode
    11. cursor string // pagination cursor
    12. items []Item // current page
    13. selected map[string]struct{}
    14. err error
    15. }

    Three constraints matter. First, the loading state must be visible: show progress during batched fetching instead of a blank screen. Second, keep the selection set separate from the list, so paging never loses checked items, because the set is keyed by conversation unique ID. Third, unify the exit path: any state can be interrupted safely and resources reclaimed, avoiding half-written files.

    4. On-Demand Loading: Batched Fetching with Cursor Pagination

    History is usually ordered newest first and can exceed several hundred entries. Fetching everything at once causes two problems: a long first-screen wait, and a single oversized response that may time out. On-demand loading keeps a cursor and pulls a fixed count each time.

    1. type Page struct {
    2. Items []Item
    3. NextCursor string
    4. HasMore bool
    5. }
    6. func (c *Client) List(cursor string, size int) (Page, error) {
    7. // size of 20~50 is recommended; larger values give diminishing returns and time out easily
    8. // retry with exponential backoff on failure, keeping the original cursor to resume
    9. }

    Two engineering details matter: if a page fetch fails, keep the original cursor and already loaded data so the user can retry in place; and debounce repeated “load more” triggers so concurrent requests cannot corrupt the list.

    5. Credential Handling and Security Boundaries

    Reading an access credential from a browser session is a common approach, but the security boundary must be explicit: the credential is held in memory only — never written to logs, never persisted to disk, never included in error messages. Inject it via an environment variable or interactive input; it becomes invalid when the process exits.

    1. # Inject via environment variable to keep it out of shell history
    2. export SESSION_TOKEN='<your-token>'
    3. tool export --page-size 30

    Also provide a clear “credential expired” branch that guides the user to obtain a new one, instead of throwing an obscure parse error. Under no circumstances should credentials be persisted by default or appended to launch arguments that log collection may capture.

    6. Smart Deduplication: Local Fingerprints and Idempotent Export

    Deduplication makes the export idempotent: exporting the same conversation repeatedly yields the same result with no side effects. Use a normalized “date + title” filename as the primary key, with a content digest as a check.

    1. func Key(c Conversation) string {
    2. title := sanitize(c.Title) // strip illegal path characters, collapse whitespace
    3. return c.Date.Format("20060102") + "-" + title
    4. }
    5. func ShouldExport(dir string, c Conversation) (bool, error) {
    6. path := filepath.Join(dir, c.Month(), Key(c)+".md")
    7. if _, err := os.Stat(path); err == nil {
    8. return false, nil // already exists, skip and save a request
    9. }
    10. return true, nil
    11. }

    Deduplication only saves quota when it happens before fetching details: pull the lightweight list first, compare against local fingerprints, and request detail content only for missing items. Filename sanitization must also handle cross-platform illegal characters and length limits to avoid write failures on some systems.

    7. Rendering Layer: Separating Reasoning from the Final Answer

    Conversation data usually contains both reasoning and the final answer; interleaving them hurts readability badly. Map them to a fixed structure: a level-1 heading for the conversation title, level-2 headings separating “Reasoning” from “Answer,” a language tag on every code block, and preserved nesting for lists and quotes.

    1. # 2026-05-01 Build Cache Invalidation Investigation
    2. ## Reasoning
    3. - Observed: incremental build hit rate dropped sharply
    4. - Hypothesis: the cache key does not include environment variables
    5. ## Answer
    6. ```bash
    7. # Inspect the cache key composition
    8. printenv | sort | sha256sum
    1. Layout normalization includes: consistent blank-line counts, repairing truncated code fences, collapsing consecutive blank lines into one, and adding blank lines before and after tables so they parse correctly. Once rendering is decoupled from storage, the same model can be emitted to different target formats.
    2. ## 8. Storage Layout and Traceability
    3. Persist files in per-month directories, with filenames containing the date and title, so note-taking software can build hierarchical indexes and backlinks.
    4. ```text
    5. conversations_export/
    6. ├── 2026-05/
    7. │ ├── 20260501-build-cache-invalidation.md
    8. │ └── 20260517-api-idempotency-retro.md
    9. └── 2026-06/
    10. └── 20260603-log-sampling-strategy.md

    Writes use “temp file + atomic rename” so an interruption cannot leave a partial file. Maintain a lightweight index inside the directory recording export time and a content digest, leaving an interface for later incremental sync and full-text search. For long-term archiving, layer object storage with versioning on top, keeping the local directory as a plain-text layer that can be committed to a code repository.

    9. Compatibility and Distribution

    Given differences in user environments, ship two forms: a single-file compiled executable covering mainstream operating systems and two instruction set architectures; and an equivalent implementation in an interpreted language for users who cannot install a runtime. Both share the same data model and file naming convention, so the exported directory structure is identical and users can migrate seamlessly between machines.

    10. Evolution Roadmap and Summary

    The refactor pays off in four ways: predictable interaction, incremental fetching, idempotent export, and reusable content. Three lines of future work are recommended: make the selection set and export policy configurable, supporting automatic filtering by tag or time range; add a full-text index so archived content is quickly searchable; and extend the rendering layer with more target formats, letting one data source serve both a document library and a static site.

    One reminder: this kind of tool only handles data under the user’s own account that they are authorized to access. Exported content may contain sensitive information, so evaluate storage and sharing boundaries after archiving. Writing this constraint into the design premises is what makes the solution both usable and sound.