Tactical Plan: Nx-Enhanced Smart Monorepo for Optimal AI & Developer Context
This document outlines the step-by-step tactical plan to refactor the ton-arcana monorepo (to be potentially renamed kaido-monorepo) into an Nx-Enhanced Smart Monorepo. The goal is to achieve a "holy grail" state: a well-structured single repository, managed by Nx, optimized for efficient context recovery by both human developers and AI assistants (Cursor), ultimately enhancing productivity and reducing errors by leveraging precise AI contexting and clear project boundaries.
This plan draws heavily from the concepts in toma/docs/repo_refactoring/2_smart_monorepo_with_domain_workspaces.md.
Core Principles Guiding This Plan:
- Nx-Powered Monorepo: Utilize Nx for robust project boundary definition, dependency management, and efficient tooling within a single Git repository.
- Cursor-Native AI Workflow: Leverage Cursor 0.50.7+ features (Background Agent,
@folders, Multi-root Workspaces, Path-based Rules, Rules Generation) in synergy with Nx. - Intel-Driven Context: A custom "Intel Script" (e.g.,
tools/intel/intel.ts) will use the Nx graph to generate precise@folderscommands for AI context. - Iterative Refinement: Progress domain by domain, integrating each into the Nx structure and refining AI interaction.
- Safety First: Implement robust recovery mechanisms (git tags) and approach automation with caution.
- Energy Optimization: Sequence tasks so that earlier completions reduce the effort for subsequent ones.
Repository Name:
- The current monorepo
ton-arcanawill be structured as an Nx monorepo. We can rename the Git repository itself tokaido-monorepoif desired; Nx manages projects internally regardless of the top-level repo name. For this plan, we'll refer to it askaido-monorepo.
Phase 0: Nx Setup, Intel Script & Cursor Bootcamp (The New Foundation)
This phase focuses on installing Nx, creating the basic monorepo structure, developing the initial "Intel Script," and empowering the user with foundational Nx and Cursor knowledge.
Task 0.1: Solidify Recovery & Context Mechanisms (Standard)
- Action: This document (
TACTICAL_PLAN.md) serves as the primary guide. - Action: Ensure
CURSOR_MIGRATION_CONTEXT.md(overall goals, risks, key decisions) andMIGRATION_PROGRESS.md(changelog/journal of migration activities) are actively maintained. - Action: Verify or create a script (e.g.,
tools/recover-context.sh) for easily checking out git tags and restoring specific migration states. - Rationale: Establishes a safety net and clear documentation.
Task 0.2: Nx Initialization & Basic Workspace Configuration
- Action: Install Nx globally and/or locally:
pnpm add -D nx. - Action: Initialize Nx within the
kaido-monorepo:npx nx init. Choose an appropriate setup (e.g., "integrated" or "package-based monorepo" - "package-based" might be simpler for an existing pnpm setup, "integrated" offers more Nx features out-of-the-box). - Action: Configure
nx.jsonwith initial settings. - Action: Define the high-level directory structure as per Plan B (
domains/,libs/,platform/,tools/). - Action: Create placeholder
project.jsonfiles or use Nx generators for initial "domains" (e.g.,mercury,arcana) and "libs" (e.g.,core-utils) to establish the structure for Nx. - Rationale: Lays the groundwork for Nx to manage the monorepo.
Task 0.3: Develop Initial "Intel Script" (tools/intel/intel.ts)
- Action: Create the
tools/intel/directory. - Action: Implement the first version of the
intel.tsscript as detailed in Plan B. This script should:- Use
nx graph(orprojectGraphAsync()) to get project dependencies. - Generate a list of file/folder paths relevant to a specified domain.
- Output a ready-to-copy
@folderscommand for Cursor.
- Use
- Action: Test the script with the placeholder projects (e.g.,
pnpm run intel mercury). - Rationale: This script is CRITICAL for providing precise AI context. Getting a working version early is key.
Task 0.4: User's "Cursor Mastery Bootcamp" (Nx + Cursor Synergy)
- Action: User to dedicate time to master:
- Nx Core Concepts: Workspace structure,
project.json,nx graph, basic Nx commands (build,test,lint,affected:commands). - Multi-root Workspaces with Nx:
- Setting up
.code-workspacefiles that include relevantdomains/,libs/, andplatform/folders for specific tasks (e.g.,workspaces/mercury.code-workspace).
- Setting up
- Intel Script +
@folders:- Running
pnpm run intel <domain>. - Copying the generated
@folderscommand into Cursor chat to set precise context.
- Running
- Path-based
.cursor/rules: Understanding how rules indomains/mercury/.cursor/ruleswill apply. - Background Agents with Precise Context: Using the
intelscript output to provide context for Background Agent tasks. - AI-Manifest Files: Understanding their role for high-level domain description (
domains/mercury/ai-manifest.md).
- Nx Core Concepts: Workspace structure,
- Rationale: Equips the user with the skills to leverage the Nx + Cursor synergy effectively.
Phase 1: Mercury Domain - Nx Integration & AI Context Refinement
This phase focuses on fully integrating the primary product, Mercury, into the Nx-managed monorepo and refining its AI context mechanisms.
Task 1.1: Archive Obsolete Code (Pre-Migration Cleanup)
- Action: Systematically identify and move code from the current monorepo to
archive/(e.g., oldk8sconfigs,mercury-ta,mcp-task-warrior, etc.). - Action: Document reasons in
MIGRATION_PROGRESS.md. - Rationale: Reduces clutter before migrating active code into the Nx structure.
Task 1.2: Migrate Mercury Code into Nx Structure
- Action: If not already placeholders, create
domains/mercury/backend/anddomains/mercury/dashboard/. - Action: Move existing Mercury backend code (
apps/mercury) intodomains/mercury/backend/. - Action: Move existing Mercury dashboard code (
apps/mercury-dashboard) intodomains/mercury/dashboard/. - Action: Update all internal imports, paths, and
package.jsonfiles within Mercury to reflect new locations. - Rationale: Places Mercury code into its designated Nx domain.
Task 1.3: Create Nx project.json for Mercury Components
- Action: Create/update
project.jsonfiles for:domains/mercury/backend(as an Nx "application")domains/mercury/dashboard(as an Nx "application")- Any Mercury-specific libraries that might emerge (e.g., under
domains/mercury/packages/if any).
- Action: Define appropriate Nx
tags(e.g.,domain:mercury,type:backend,scope:production) for each project. - Rationale: Formally registers Mercury components with Nx.
Task 1.4: Configure Mercury Workspace & AI Context Files
- Action: Create/refine
workspaces/mercury.code-workspaceto includedomains/mercury/and initially relevantlibs/orplatform/paths. - Action: Create
domains/mercury/ai-manifest.mdwith high-level descriptions, tech stack, key modules, and AI instructions for Mercury, as per Plan B. - Action: Create initial
domains/mercury/.cursor/ruleswith critical Mercury-specific rules (e.g., disallowingmercury-ta, mythological naming conventions). - Rationale: Sets up the development environment and AI context parameters for Mercury.
Task 1.5: Refine and Test intel Script for Mercury
- Action: Run
pnpm run intel mercury. - Action: Verify the
intelscript correctly identifies all Mercury backend, dashboard, and their direct dependencies (initially, these might be few iflibs/isn't populated yet). - Action: Test the generated
@folderscommand in Cursor with a simple query related to Mercury. - Rationale: Ensures the core AI context mechanism works correctly for the primary domain.
Task 1.6: Test Mercury Build & Functionality with Nx
- Action: Use Nx commands to build, lint, and test Mercury components (e.g.,
nx build domains-mercury-backend,nx test domains-mercury-dashboard). - Action: Perform basic functional testing of Mercury.
- Rationale: Validates that Mercury is correctly integrated into the Nx build system.
Phase 2: Shared Libraries (libs/) - Nx Integration & Dependency Management
This phase focuses on structuring shared code into Nx libraries and defining dependencies.
Task 2.1: Structure and Migrate Shared Code to libs/
- Action: Create the
libs/subdirectory structure as outlined in Plan B (e.g.,libs/core/common-utils/,libs/integrations/kaido-telegram/,libs/domain/kaido-talib/). - Action: Move existing shared packages from
packages/into their respective new locations inlibs/. - Action: Update their internal
package.jsonfiles and paths. - Rationale: Organizes shared code into logical Nx libraries.
Task 2.2: Create Nx project.json for Shared Libraries
- Action: For each shared library (e.g.,
libs/core/common-utils,libs/domain/kaido-talib), create aproject.jsonfile, defining it as an Nx "library". - Action: Assign appropriate
tags(e.g.,scope:shared-core,scope:shared-integration,scope:shared-domain-specific). - Rationale: Registers shared libraries with Nx.
Task 2.3: Define Nx Dependency Constraints
- Action: In
nx.json, definedepConstraintsto enforce boundaries. For example:domain:mercurycan only depend on libs taggedscope:shared-core,scope:shared-integration,scope:shared-domain-specific(if applicable to Mercury).- Prevent domains from depending directly on each other unless explicitly intended.
- Rationale: Enforces architectural rules and prevents unwanted coupling.
Task 2.4: Update Mercury (and other domains) to Use Nx Libs
- Action: Update
package.jsonfiles indomains/mercury/(and other domains as they are migrated) to correctly depend on the newly structuredlibs/via workspacepnpmlinking (Nx helps manage this). - Action: Update import paths within Mercury code to reflect the new library locations (e.g.,
@kaido-monorepo/core-utilsor similar, depending on your pnpm/Nx setup). - Rationale: Integrates domains with the shared libraries through Nx's dependency management.
Task 2.5: Validate intel Script with Shared Libraries
- Action: Run
pnpm run intel mercury. - Action: Verify that the
intelscript now correctly includes paths to dependent shared libraries fromlibs/in the@foldersoutput for Mercury. - Action: Check
nx graphto visualize dependencies. - Rationale: Ensures AI context includes necessary shared code.
Phase 3: Platform Components & Other Domains - Nx Integration
Repeat the core integration steps for platform/ components and other business domains (Arcana, AnyTracker, Maschine).
Task 3.1 (Per Component/Domain): Migrate, Configure Nx, and Setup AI Context
- Action: For each platform area (
platform/tools/,platform/infra/,platform/docs/) and each remaining domain (arcana,anytracker):- Move code into the appropriate
domains/orplatform/subdirectory. - Create/update
project.jsonfiles with appropriate types and tags. - Create/update
ai-manifest.mdand.cursor/rules. - Create/update domain-specific
.code-workspacefiles (e.g.,workspaces/arcana.code-workspace). - Update and test the
intelscript for these new domains/components. - Define any new
depConstraintsinnx.json. - Test builds and functionality using Nx commands.
- Move code into the appropriate
- Rationale: Systematically brings the rest of the monorepo under Nx management and AI context readiness.
Task 3.2 (Lower Priority): Contract-Driven Grafana Dashboards (Pilot in Mercury)
- Action: If desired, implement the contract-driven Grafana approach for Mercury, now within its Nx structure. Metrics contracts could be defined in a shared
libs/package or withindomains/mercury/. - Rationale: Addresses dashboard drift, kept as lower priority.
Phase 4: Optimization, Full Agentic Integration & Validation
This final phase focuses on fine-tuning the system, fully integrating AI agent capabilities, and validating the setup.
Task 4.1: User's "Cursor Mastery Bootcamp" - Part 2 (Advanced Agentic Features)
- Action: User to learn, experiment with, and develop proficiency in:
- Background Agent with Nx Context:
- Crafting effective prompts for the Background Agent, always including the
@foldersoutput frompnpm run intel <domain>. - Assigning parallelizable refactoring or development tasks.
- Crafting effective prompts for the Background Agent, always including the
- "Auto-run Mode" (Conceptual YOLO Mode):
- Exploring Cursor's settings for configuring automatic execution of (safe) terminal commands (e.g., Nx commands suggested by AI).
- Defining a clear policy for auto-run commands.
- Rules Generation: Using
/Generate Cursor Rulesfor successful interactions to populate domain-specific.cursor/rulesfiles.
- Background Agent with Nx Context:
- Rationale: Maximizes AI leverage.
Task 4.2: "Second Laptop" / Fresh Context Validation
- Action: For each primary domain (e.g., Mercury, Arcana):
- Simulate a fresh setup: Close all files, perhaps even restart Cursor or use a different profile.
- Open the domain-specific
.code-workspace(e.g.,workspaces/mercury.code-workspace). - In a terminal, run
pnpm run intel mercuryto get the context command. - In a new Cursor chat session, paste the generated
@folders ...command. - Provide a moderately complex task to the AI (or Background Agent) related to that domain, referencing its
ai-manifest.md. - Evaluate:
- Does the AI understand the context quickly?
- Does it respect domain-specific rules from
.cursor/rules? - Does it correctly use information from
ai-manifest.md? - Is the generated code high quality and within Nx boundaries?
- Rationale: Critically validates the core goal of rapid and accurate context recovery for AI.
Task 4.3: CI/CD Integration with Nx
- Action: Configure CI/CD pipelines to use Nx
affected:commands (nx affected:build,nx affected:test,nx affected:lint) to only process projects impacted by changes. - Rationale: Optimizes CI/CD performance.
Task 4.4: Implement a Continuous Improvement & Learning Cycle
- Action: Schedule regular reviews to:
- Assess effectiveness of Nx structure and
depConstraints. - Evaluate and refine Cursor rules and
ai-manifest.mdfiles. - Review and update
intelscript if needed. - Update documentation.
- Assess effectiveness of Nx structure and
- Rationale: Ensures the system remains optimized and effective long-term.
Risk Mitigation Reminders (Constant Vigilance)
- Nx Learning Curve: Initial setup and understanding Nx can take time.
- Intel Script Complexity: Ensuring the
intelscript is robust and accurate is vital. - Background Agent Stability: Start with non-critical, reversible tasks for Background Agents.
- Rules Chaos: Prioritize manually crafted rules; use AI generation as suggestions.
- Initial Productivity Dip: Acknowledge that learning new tools (Nx, advanced Cursor features) will temporarily slow things down.
This tactical plan, centered around Nx and the "Intel Script," provides a robust roadmap for achieving the "Sacred Grail" of efficient AI-assisted development in your monorepo. It should be treated as a living document.