PLAN - nself-org/nchat GitHub Wiki
nself-chat Refactor Plan (Private, Gitignored)
1) Purpose
Define an end-to-end, AI-executable migration plan to evolve nself-chat into a clean, durable monorepo shape:
root/
├── backend/
└── frontend/
This plan is planning-only and is designed so a future agent can execute with minimal ambiguity.
2) Required Outcomes
- Keep nSelf CLI as the backend infrastructure foundation.
- Preserve ability to run nChat independently.
- Preserve ability to integrate nChat into ecosystem deployments (
nself-family,nself-tv). - Keep "code once, deploy everywhere" as the default engineering strategy.
- Support platform-specific behavior/skins where required (especially iOS/Android push/background behavior).
- Maintain strict test discipline:
- unit tests for every changed/new function/hook/lib/API handler
- 100 percent changed-file coverage (statements/branches/functions/lines)
- contract/integration/security tests for touched boundaries
3) Decision Summary (Recommended Architecture)
3.1 Backend Decision
Use public backend/ in repo (not only gitignored local backend), plus gitignored local runtime state.
backend/stays versioned and public for reproducibility..backend/stays gitignored for local generated state/secrets.READMEdocuments both local standalone mode and shared-backend ecosystem mode.
3.2 Frontend Decision
Use one unified frontend/ workspace with app targets and shared packages:
frontend/
├── apps/
│ ├── web/ # Next.js
│ ├── mobile/ # React Native (Expo)
│ └── desktop/ # Tauri wrapper + shared web/core packages
├── packages/
│ ├── core/ # domain models, use-cases, business logic
│ ├── api/ # typed API/GraphQL clients + SDK wrappers
│ ├── state/ # shared state contracts and sync primitives
│ ├── ui/ # reusable design tokens and component primitives
│ ├── config/ # shared lint/ts/build configs
│ └── testing/ # shared test utilities and fixtures
└── tooling/
Rationale:
- Best balance of code reuse + native capability.
- Better mobile background/push reliability than pure Capacitor for chat-critical behavior.
- Preserves existing Next.js investment for web.
- Allows platform-specific override layers without forking business logic.
3.3 Platform-Specific Override Model
Use layered UI and capability adapters:
packages/core: no platform code.packages/api: no platform code.packages/state: no platform code.packages/ui: common primitives + token system.- Per-app adapters in each target app:
frontend/apps/mobile/src/adapters/ios/*frontend/apps/mobile/src/adapters/android/*frontend/apps/web/src/adapters/*frontend/apps/desktop/src/adapters/*
Rule:
Platform overrides are allowed only for device APIs, OS UX conventions, and performance constraints. Core domain logic must remain shared.
4) Repo Target State
4.1 Target Root Tree
nself-chat/
├── README.md
├── backend/
├── frontend/
├── docs/
├── .claude/ # gitignored agent planning/control
├── .backend/ # gitignored local nSelf runtime
├── package.json
├── pnpm-workspace.yaml
└── ...tooling files
4.2 Backend Target Tree
backend/
├── apps/
├── services/
├── db/
│ ├── migrations/
│ ├── schemas/
│ └── seed/
├── hasura/
├── infra/
├── scripts/
└── docs/
4.3 Frontend Target Tree
frontend/
├── apps/
│ ├── web/
│ ├── mobile/
│ └── desktop/
├── packages/
│ ├── core/
│ ├── api/
│ ├── state/
│ ├── ui/
│ ├── config/
│ └── testing/
├── tooling/
└── docs/
5) Migration Constraints (Non-Negotiable)
- No feature freeze without explicit release note.
- No schema/API breaking changes without versioned contract migration plan.
- No untested moved code.
- No partial cutover per app surface without adapter compatibility layer.
- No secrets in repo (including temporary migration scripts).
- Keep CI green at each migration slice.
6) Execution Strategy (Phased)
Phase 0: Discovery and Freeze
- Inventory current root folders and runtime commands.
- Inventory all backend entry points and nSelf init/build dependencies.
- Inventory frontend runtime surfaces (web/mobile/desktop/platforms).
- Freeze current contracts (API schema snapshots, event schemas).
- Define migration rollback points.
Done when:
- inventory doc is complete
- contract snapshots exist
- rollback plan is approved
- baseline test suite is passing
Phase 1: Workspace Skeleton
- Create
frontend/with target subtrees. - Keep existing app code intact; add bridge scripts so old commands still work.
- Introduce workspace package boundaries (
apps/*,packages/*). - Wire root scripts to support both legacy and new paths during transition.
Done when:
- both legacy and new command aliases work
- no feature behavior changes shipped yet
- CI runs in dual-mode (legacy + new skeleton)
Phase 2: Shared Package Foundations
- Extract domain models/use-cases into
frontend/packages/core. - Extract typed API clients/contracts into
frontend/packages/api. - Extract shared state logic into
frontend/packages/state. - Extract reusable test fixtures into
frontend/packages/testing.
Done when:
- extracted packages have unit tests
- changed-file coverage is 100 percent
- legacy apps consume packages without regressions
Phase 3: Web App Migration
- Move current Next.js web app into
frontend/apps/web. - Keep routing and SEO behavior stable.
- Replace local relative imports with workspace package imports.
- Validate auth/session, real-time messaging, and notifications behavior parity.
Done when:
- web parity matrix passes
- performance baseline unchanged or improved
- no contract regressions
Phase 4: Mobile Strategy Cutover (Expo RN)
- Establish
frontend/apps/mobilewith Expo RN baseline. - Implement shared core/state/api package consumption.
- Add push/background adapters (iOS/Android specific).
- Implement platform-specific overrides for device-native capabilities.
Done when:
- critical flows pass on iOS + Android
- background/push behavior passes test matrix
- shared logic coverage remains enforced
Phase 5: Desktop Strategy Cutover (Tauri)
- Establish
frontend/apps/desktopwith Tauri host. - Reuse shared core/api/state and UI system.
- Add desktop-specific capability adapters (notifications/filesystem/deep links).
- Validate IPC boundaries and security constraints.
Done when:
- desktop core chat flows pass
- Tauri security checklist passes
- desktop packaging pipeline is reproducible
Phase 6: UI System and Theme Layer
- Create
frontend/packages/uitoken and primitive system. - Define base theme + brand override slots.
- Add platform-specific style adapters for iOS/Android/desktop/web differences.
- Prevent logic leakage into UI package.
Done when:
- all apps use shared token system
- theme override examples exist
- visual regression tests are passing
Phase 7: Backend Contract Hardening
- Align backend contracts with extracted frontend packages.
- Add/refresh schema versioning and migration checks.
- Validate nSelf init/build/update flows for local and CI.
- Add explicit standalone and shared-backend mode docs.
Done when:
- contract compatibility tests pass
- migration rollback tests pass
- standalone/shared mode docs are complete
Phase 8: CI/CD and Release Gate Hardening
- Update CI to run per-surface test matrices (web/mobile/desktop/backend).
- Enforce changed-file 100 percent coverage.
- Enforce security scans (SAST/dependencies/secrets/infra).
- Add release artifact checks for each app target.
Done when:
- all gates block unsafe merges
- flaky tests are triaged and policy-enforced
- release candidate checklist is executable
Phase 9: Legacy Path Removal and Final Cutover
- Remove temporary bridge scripts and legacy import patterns.
- Remove obsolete top-level app paths once parity is confirmed.
- Finalize docs and onboarding around canonical
backend/frontendmodel. - Lock repo conventions and add guardrails to prevent architecture drift.
Done when:
- no legacy path dependencies remain
- all tests and contract checks pass
- full migration sign-off is recorded
7) Detailed Task/Ticket Matrix
7.1 PM-Level Tickets (Top Layer)
NC-001Architecture freeze and baseline inventory.NC-002Workspace skeleton and compatibility shims.NC-003Shared package extraction (core/api/state/testing).NC-004Web app migration tofrontend/apps/web.NC-005Mobile app establishment infrontend/apps/mobile.NC-006Desktop app establishment infrontend/apps/desktop.NC-007Shared UI/token/theming system rollout.NC-008Backend contract hardening and docs completion.NC-009CI/CD release gate hardening.NC-010Legacy cleanup and final cutover.
Each ticket must include:
- scope paths
- out-of-scope paths
- dependencies
- completion criteria
- test plan
- security impact
- rollback strategy
7.2 Definition of Done (Per Ticket)
- all ticket acceptance criteria met
- all required tests added/updated
- changed-file coverage = 100 percent
- security and contract tests pass
- docs updated in same change set
- dual code review approved
- dual QA pass recorded
- residual risks documented
8) Testing Plan (Detailed)
8.1 Unit Tests
- domain models and validation
- reducers/state transitions
- API client serialization/deserialization
- adapter behavior per platform
8.2 Integration Tests
- frontend package -> backend contract validation
- auth/session refresh/reconnect behavior
- message send/receive/order/read-state semantics
- offline queue + resync behavior
8.3 E2E Tests
- web critical user journeys
- mobile critical user journeys (real device/simulator)
- desktop critical user journeys
- cross-device continuity (send on one, read on another)
8.4 Security Tests
- token abuse (stale/replay/revoked)
- unauthorized resource access
- multi-tenant boundary abuse
- secrets scan gate verification
9) Risk Register and Mitigation
-
Risk: migration stalls active feature delivery. Mitigation: enforce short slices and compatibility shims.
-
Risk: mobile push/background regressions. Mitigation: dedicated adapter tests and device matrix gate.
-
Risk: API contract drift during extraction. Mitigation: schema snapshot tests + generated client contract checks.
-
Risk: package boundary violations. Mitigation: lint rules and import boundary enforcement.
-
Risk: CI duration explosion. Mitigation: changed-scope test partitioning with nightly full matrix.
10) Rollback Strategy
- Keep legacy entry points until phase parity is proven.
- Gate deletions to Phase 9 only.
- Tag pre-cutover states and maintain reversible migration commits.
- If major regression appears, revert to last parity tag and reopen only failed ticket scope.
11) Documentation Deliverables
- root README architecture section rewrite (
backend/frontendcanonical) - frontend architecture doc (
apps + packages) - backend contract doc (standalone/shared modes)
- contributor guide for package boundaries and test obligations
- release checklist for multi-target app builds
12) Final Recommendation
Proceed with:
- public
backend/+ gitignored.backend/ - unified
frontend/workspace withapps/*andpackages/* - Next.js (web) + Expo RN (mobile) + Tauri (desktop)
- strict shared-core logic with platform adapter overrides
This delivers the clean root shape you want, keeps nSelf backend promotion strong, and supports "code once, deploy everywhere" without sacrificing native platform quality.