Files
Termind/Memory/REFACTOR.md
T
2026-09-13 22:19:31 +08:00

96 lines
20 KiB
Markdown

# Termind Refactoring Backlog
This English-only document is the durable record of completed redundancy removal and deliberately retained boundaries; append new findings, require a net code reduction unless the item is explicitly structural, verify references with `rg`, and preserve SwiftUI/AppKit and platform-specific lifecycle boundaries.
## Completed Items
1. **Delete the obsolete SwiftUI transcript tree (2026-08-30):** Removed the unreachable legacy transcript, message, command-card, compaction, and plan presentation subgraph while retaining live timestamp and risk components; the build and targeted Transcript tests passed.
2. **Merge repeated ListView hosting bridges (2026-08-30):** Introduced `HostingListRow` and `HostingListContent` for ordinary SwiftUI-backed rows while retaining dedicated Transcript and Assistant conversation lifecycles; the app build passed before the final parser-verified Connection Log migration.
3. **Consolidate `SSHSessionModel` initializers (2026-08-30):** Routed the two terminal entry points through one private initializer without changing temporary-host semantics; the build passed.
4. **Merge SSH and Serial terminal appearance configuration (2026-08-30):** Centralized shared appearance application in `TerminalViewState.applyAppearance`; the build passed.
5. **Delete redundant SFTP store overloads (2026-08-30):** Removed four `TransferLibraryModel` forwarding overloads in favor of the existing `RemoteSessionHostStore` entry points; the build passed.
6. **Reuse the Jump Host configuration builder (2026-08-30):** Made final SSH configuration reuse `sshJumpConfigurations` instead of duplicating route validation and error wrapping; the build passed.
7. **Share remote-session connection interaction (2026-08-30):** Moved host-key prompts, acceptance, route progress, prompt cleanup, and reconnect presentation into `RemoteSessionConnectionController` while preserving transport-specific teardown; the Debug build and targeted connection/SFTP tests passed.
8. **Merge short tool-free model text collectors (2026-08-30):** Centralized streamed text collection and tool-call rejection for command, title, and compaction services; their targeted tests passed.
9. **Merge provider authorization and session configuration (2026-08-30):** Added shared request authorization and ephemeral-session construction while retaining catalog-specific Vertex and empty-secret rules; targeted Provider and ChatProbe tests passed.
10. **Consolidate SwiftData save/rollback templates (2026-08-30):** Added a narrow `ModelContext.commit` helper while retaining semantic two-stage history commits; targeted Connection and SFTP History tests passed.
11. **Merge libssh2 queue/continuation bridges (2026-08-30):** Shared the byte-identical serial worker bridge between SSH Exec and SFTP workers; the build passed.
12. **Delete remaining legacy Transcript helpers (2026-08-30):** Removed dead streaming, edit-binding, and SwiftUI activity helpers as part of Item 1; targeted Transcript verification passed.
13. **Finish `ConversationComposerState` migration (2026-08-30):** Migrated callers to `conversation.composer` and deleted four compatibility accessors while preserving attachment mutation hooks; the build and Chat Composer tests passed.
14. **Delete the unreachable toolbar search-menu pipeline (2026-08-30):** Removed unused menu-item plumbing, `NSMenuDelegate` behavior, and the unread find-context kind while preserving query and keyboard behavior; the build passed.
15. **Share Agent SSH prompt conversion (2026-08-30):** Moved Journey prompt and passphrase derivation onto `AgentSSHAuthenticationRequest` for both presentation paths; the build passed.
16. **Extract atomic SFTP remote writes (2026-08-30):** Centralized temporary-path creation, handle cleanup, failure unlinking, atomic rename, and progress sampling while keeping data-source loops separate; the build and SFTP tests passed.
17. **Merge remote transfer conflict resolution (2026-08-30):** Shared Keep Both selection, remote-directory handling, and file conflict policy without merging distinct job types; the Debug build and targeted SFTP tests passed.
18. **Consolidate SFTP client leases (2026-08-30):** Centralized saved-versus-borrowed client acquisition and conditional disconnect while retaining coordinator reservation state; the build and SFTP tests passed.
19. **Centralize legacy tool-presentation metadata (2026-08-30):** Replaced scattered historical name mappings with one compatibility table while preserving generic MCP fallback semantics; targeted presentation tests passed.
20. **Delete the test-only presentation action path (2026-08-30):** Removed unused automatic action-message construction and compressed English verb forms around production `actionKind` semantics; targeted presentation tests passed.
21. **Merge tool-detail input unpacking (2026-08-30):** Added narrow object/array helpers in `AgentToolDetailFormatting` while keeping field-specific presenters local; the build passed.
22. **Merge Agent idle sweepers (2026-08-30):** Replaced two timer loops with `AgentIdleSweeper` while callers retain their own registry and emptiness policy; targeted tests passed.
23. **Reuse `SidebarSectionHeader` (2026-08-30):** Extended the shared header for count and collapse state and removed duplicate Assistant/Snippet layouts; the build passed.
24. **Unify Host deletion entry points (2026-08-30):** Routed group deletion through the repository/outbox saga and removed direct snapshot-persistence deletion; the Debug build and targeted repository, Snippet, and Port Forwarding tests passed.
25. **Remove uncalled wrappers and constants (2026-08-30):** Deleted confirmed-unused Agent preflight, settings, metrics, reconnect, and SSH-status declarations after reference scans; the build passed.
26. **Delete `SettingsCollectionPage` (2026-08-30):** Replaced its two construction sites with the byte-identical `SettingsFormPage`; the build and focused Settings tests passed.
27. **Merge fixed-height cursor lists (2026-08-30):** Shared the adapter used by Snippet Target, Host Chooser, and Export Host lists while excluding dynamic and specialized rows; the build and focused list/chooser tests passed.
28. **Share Agent Exec/SFTP authentication retries (2026-08-30):** Extracted a generic authenticated-open loop while preserving explicit connection kinds and result types; the build and all 21 Agent Host Authentication tests passed.
29. **Deduplicate native Transcript risk and confirmation helpers (2026-08-30):** Routed both row implementations through one risk-color function and one destructive-command confirmation function; the build passed.
30. **Merge Glass shape modifiers (2026-08-30):** Replaced three copied implementations with one shape-parameterized private modifier while preserving public APIs and fallbacks; the build passed.
31. **Consolidate Vault envelope persistence (2026-08-30):** Added one helper for insertion/update and upload-state indexing while leaving versioning and merge policy in callers; the build and Vault Sync tests passed.
32. **Share SFTP remote-conflict preflight (2026-08-30):** Centralized remote-directory ordering, descendant skipping, and target-kind lookup while retaining separate prepared job types; the build and focused SFTP tests passed.
33. **Centralize effective Vertex mode and credential selection (2026-09-04):** Added `usesVertexEndpoint` and `effectiveCredentialRef` to `ModelProvider`, later adapting the former to API-format-based providers; build and Provider verification passed.
34. **Delete newly confirmed dead declarations and decoded metadata (2026-08-30):** Removed unused onboarding, Agent, color, trial-test, and runtime Linux-catalog fields while retaining provenance in generated JSON; the build passed.
35. **Derive Conversation run presentation (2026-09-01):** Replaced manually synchronized run/streaming state with derivation from one reported state and outstanding queues; state-focused tests, localization, and diff checks passed.
36. **Delete tests that freeze user-facing copy (2026-09-02):** Removed 20 copy-only tests and isolated literal assertions while retaining behavioral, persistence, localization-selection, and protocol coverage; the affected target compiled and focused tests passed.
37. **Share checked provider HTTP execution (2026-09-02):** Centralized transport-error translation, HTTP validation, and non-2xx handling for model catalogs and probes while keeping request construction and parsing local; the build and all 12 focused tests passed.
38. **Delete the Finder-only native drop wrapper (2026-09-02):** Removed the unconstructed `NativeFileURLDropTarget` while retaining the generalized target and test-facing AppKit initializer; the build and all five File Drop tests passed.
39. **Centralize Context Chip recovery rules (2026-09-02):** Shared payload-boundary detection and fallback filename derivation between live attachments and restored references; the build and focused recovery tests passed.
40. **Finish save-or-rollback reuse (2026-09-02):** Added `ModelContext.savePendingChanges` and reused `commit` for staged Agent, Outbox, AI snapshot, and conversation mutations without changing semantic save boundaries; all 46 focused tests passed.
41. **Share transient overlay chrome (2026-09-02):** Replaced three identical surface modifier chains with `termindTransientOverlaySurface` while keeping content and transitions local; the Debug build passed.
42. **Share SSH form chrome (2026-09-02):** Replaced two identical conditional padding/glass/border branches with `connectionFormChrome` while preserving separate form behavior; formatting and the Debug build passed.
43. **Share Snippet card content (2026-09-02):** Extracted `SnippetCardContent` for the normal card and drag ghost while keeping their interaction and outer chrome distinct; formatting and the Debug build passed.
44. **Share SFTP read-handle lifecycle (2026-09-02):** Routed inline reads and both download paths through `withRemoteReadHandle` while preserving their distinct loops and destination policies; the build and all 47 focused SFTP tests passed.
45. **Share select/deselect-all helpers (2026-09-02):** Added `ManagedChooserState.allChecked(in:)` and `toggleAll(in:)` for the three identical-enabled-set callers while leaving restricted selection unchanged; the build, localization, and diff checks passed.
46. **Extract AgentKit (2026-09-02):** Moved the platform-neutral Agent runtime into the separately versioned package after introducing host-tool, interaction, prompt, and presentation seams; package build/tests/formatting and the app build/full suite passed.
47. **Collapse Workspace navigation commands (2026-09-02):** Removed commands shadowed by AppKit, kept the standard workspace shortcuts, and moved split shortcuts off system-owned keys with terminal routing coverage; the build, formatting, and localization checks passed.
48. **Address providers by one URL and API type (2026-09-04):** Replaced vendor-kind/default-path branching with explicit inference/base URLs and `ModelAPIFormat`, migrated persisted schemas safely, and shipped AgentKit 0.4.0/0.5.0; package checks, all 994 app tests, localization, and site build passed.
## Later Completed Work
- **StoreKit trial consolidation (2026-09-09):** Replaced the local HMAC/Keychain/CloudKit trial system with StoreKit purchasing and a transaction-scoped clock watermark, producing a net 121-line production reduction with commerce checks passing apart from one unrelated catalog expectation.
- **Remove the unused Show Recents preference (2026-09-09):** Deleted the unread preference, its toggle/group, and unused labels while retaining the shared Sidebar accessibility localization; builds, formatting, localization, and relevant tests passed.
- **Remove low-value test assertions (2026-09-11):** Deleted five redundant tests and literal/enum/catalog snapshots for a net 77-line test reduction while retaining behavioral coverage; all relevant checks passed aside from an intermittent unchanged focus test that passed on rerun.
- **Remove the duplicate screenshot window host (2026-09-11):** Deleted `ScreenshotDemoWindow` and reused the production `WindowGroup` with demo restoration disabled; the full pinned test run, native capture, formatting, and localization checks passed.
- **Share SFTP permission controls (2026-09-11):** Moved permission draft behavior to Domain and a shared SwiftUI grid to Presentation for both editors; regression verification is recorded in `MOBILE_ROLLOUT.md`.
- **Share mobile settings and terminal behavior (2026-09-11):** Moved CloudKit, settings transaction/journal, terminal settings, and command-history behavior into their owning frameworks with only desktop adapters retained; shared/mobile tests passed and full macOS verification retained known Agent timing failures.
- **Share Metrics and connection presentation (2026-09-11):** Moved monitoring/Journey state to Application and portable panels/forms to Presentation while retaining native keyboard and log handling; shared/mobile and 127 focused macOS tests passed.
- **Share AI settings business logic (2026-09-11):** Moved the skill library, importer, and role form into Application, Infrastructure, and Presentation respectively while retaining native editors and panels; the isolated build and 81 mobile/shared tests passed.
- **Share Assistant execution (2026-09-12):** Moved runtime, tool adapters, attachments, speech, conversation projection, and transcript list behavior into owning frameworks for both apps; builds, Assistant/navigation tests, localization, and formatting passed apart from an unrelated mobile Metrics race that passed on rerun.
- **Remove app-target forwarding aliases (2026-09-12):** Deleted 86 pure-forwarder files, 224 app aliases, and 20 Persistence compatibility aliases while preserving six responsibility-named adapters; both builds, architecture guards, and the complete TFI test action passed.
- **Align the mobile target with desktop layers (2026-09-12):** Reorganized TFI into the shared layer model, moved connection construction to Infrastructure, and centralized interface-idiom policy; both builds, architecture tests, and the complete TFI tests passed.
- **Share terminal draft and generation lifecycles (2026-09-12):** Extracted `TerminalCommandDraftController` and `CommandGenerationCoordinator` with shared timeouts, cancellation, and protocol constants; focused mobile and desktop tests passed.
- **Separate remote-directory policy from SFTP transport (2026-09-12):** Moved `RemoteFile` to Domain, introduced an Application `RemoteFileSystem` port, and extracted `MobileSFTPSessionModel`, accepting a structural net increase to enforce the dependency boundary; builds, architecture guards, and SFTP tests passed.
- **Finish mobile adoption of shared connection policy (2026-09-12):** Made `RemoteSessionConnectionController` own mobile Host Key decisions and route progress and shared temporary-key preparation between Workspace and Metrics; focused connection, Journey, Metrics, and recovery tests passed.
- **Share terminal Find state (2026-09-12):** Replaced three desktop/mobile query state machines with one Application `TerminalFindController` while retaining platform binding closures; direct and platform tests passed.
- **Derive remote distributions once (2026-09-12):** Centralized Linux distribution detection in Domain with explicit unavailable-versus-conclusive results; Domain, Host projection, and mobile Workspace tests passed.
- **Share platform-neutral Connection Journey sections (2026-09-12):** Moved header and status sections to Presentation while retaining native logs, failures, backgrounds, and keyboard handling, reducing production code by 98 lines; builds and Journey tests passed.
- **Own Ghostty appearance in Presentation (2026-09-12):** Replaced duplicated desktop/mobile theme conversion with one shared bridge while retaining desktop preference storage; both builds and terminal theme tests passed without dependency changes.
- **Share terminal-upload availability and notices (2026-09-12):** Centralized readiness policy and notice presentation while retaining distinct desktop and mobile execution; direct policy tests and both builds passed.
- **Share Known Host presentation titles (2026-09-12):** Moved hashed-address versus endpoint title selection to Presentation while leaving platform cards distinct; direct presentation tests and both builds passed.
- **Restrict ListViewKit to native-list workloads (2026-09-12):** Removed eight unnecessary macOS adapters and eleven mounts, later retaining narrow UIKit transcript/history uses, for a net 611-line macOS reduction; builds, focused tests, formatting, localization, and boundary checks passed.
- **Share Assistant transcript presentation (2026-09-12):** Moved platform-neutral tool/result, disclosure, timestamp, and Markdown policy into Presentation while retaining native renderers and viewport ownership; architecture records and both builds verify the boundary.
- **Remove Periphery-confirmed dead code (2026-09-12):** Deleted 34 imports, three empty files, and confirmed-unused declarations for a net 150-line production reduction while preserving dynamic and protocol entry points; builds, focused tests, formatting, localization, and diff checks passed.
- **Remove UI implementation-type assertions (2026-09-12):** Deleted tests and helpers that pinned concrete AppKit/UIKit/ListViewKit types while retaining behavioral rendering, identity, reuse, interaction, and environment coverage.
- **Remove obsolete app localizations (2026-09-13):** Deleted 81 compiler-confirmed unused catalog entries and three obsolete test expectations and cleared only verified stale metadata; both builds and all localization/language checks passed.
- **Register cross-platform Assistant slash commands (2026-09-13):** Replaced duplicate desktop/mobile command catalogs and execution switches with `ChatSlashCommandRegistry` and explicit platform registration; both builds and focused registry, desktop, and mobile tests passed.
- **Register mobile feature destinations (2026-09-13):** Replaced separate tab/sidebar metadata and destination switches with an injected `MobileFeatureRegistry` while keeping it app-owned; the iOS build and all 28 focused navigation tests passed.
- **Share remaining mobile and desktop policies (2026-09-13):** Centralized tree layout, route planning, Host deletion, display projections, Snippet/model rules, SFTP drag values, and service composition in their owning layers while retaining native UI and transport lifecycles; both builds and focused shared/mobile tests passed.
- **Move trials to annual-subscription introductory offers (2026-09-13):** Retired the zero-price trial product for new sales, retained it only as a legacy entitlement, and made offer presence, eligibility, duration, price, period, and expiration come entirely from StoreKit annual-subscription metadata.
- **Remove brittle and redundant unit tests (2026-09-13):** Removed 27 source-text UI snapshots from `MobileNavigationParityTests`, seven more app source snapshots, real Keychain and status-item integration tests coupled to host state, and duplicated shared permission/history coverage while retaining architecture, persistence, behavioral, and opt-in screenshot checks. Shared credential-storage compatibility, permission defaults, and History limits now live in `FrameworkTests`; the change removes a net 1,303 lines. All 1,079 macOS app tests, 13 focused shared tests, 218 iOS tests, strict formatting, localization, and diff checks passed; the pre-existing `SpeechWaveformViewTests` bitmap-equality failure remains outside this cleanup.
## Deliberately Retained Boundaries
- Native Transcript/AppKit rendering, Assistant conversation rows, and specialized dynamic or drag/drop lists keep dedicated lifecycles instead of being forced through generic SwiftUI hosting abstractions.
- SSH, SFTP, Serial, desktop, and mobile implementations share only platform-neutral policy; transport startup, credential persistence, teardown, logs, interaction, and native presentation remain separate where behavior differs.
- SwiftData historical schemas remain frozen migration contracts, small structurally similar repositories and views remain separate when abstraction would not reduce code, and `RuntimeVersions` stays platform-local to avoid introducing an invalid Ghostty dependency.
The 2026-09-02 completion and re-verification scans found no further independent dead-code or exact-duplication change that met the backlog's reduction and boundary-preservation rules; later work should be appended only after a fresh reference scan.