# Generated Project Configuration

> **Auto-generated by `analyze_project`** (deep analysis)
> **Project:** codeops-mcp
> **Type:** library

---

## 🚨 MANDATORY: Load CodeOps Rules Before Any Work

**Before ANY planning or implementation, the AI agent MUST load these rules
using the codeops-mcp tools:**

1. `get_rule("agents")` — Load agent behavior rules **(REQUIRED FIRST)**
2. `get_rule("code")` — Load coding standards
3. `get_rule("testing")` — Load testing workflows
4. `get_rule("git-commands")` — Load git commit protocols

These rules are **mandatory** and must be consulted before every task.
**Do NOT skip this step. Do NOT proceed without reading these documents.**

---

## Project Overview

- **Name:** codeops-mcp
- **Description:** MCP (Model Context Protocol) server providing AI coding agents with universal, language-agnostic development rules. Includes coding standards, testing workflows, git conventions, plan creation/execution protocols, and intelligent project analysis for auto-generating project configurations.
- **Type:** library (MCP server, published to npm)
- **Author:** blendsdk
- **License:** MIT
- **Node Engine:** >=18.0.0
- **Module System:** ESM (`"type": "module"`)

## Toolchain

- **Language(s):** TypeScript (ES2022 target, Node16 module resolution)
- **Framework(s):** MCP SDK (`@modelcontextprotocol/sdk`)
- **Package Manager:** yarn (v1, lockfile: `yarn.lock`)
- **Test Framework:** Vitest (v2.x, `vitest run`)
- **Build:** `tsc` (TypeScript compiler, outputs to `dist/`)
- **Release:** semantic-release (with changelog, git, github, npm plugins)
- **TypeScript Config:** Strict mode enabled (`strict: true`, `noUnusedLocals`, `noUnusedParameters`, `noImplicitReturns`, `noFallthroughCasesInSwitch`)

**Manifest files found:** package.json, tsconfig.json, vitest.config.ts, .releaserc.json, yarn.lock

## Commands

All commands assume execution from the project root. Prefix all shell commands with `clear &&`.

### Build

```bash
clear && yarn build
```

### Test

```bash
# Run all tests (107 tests across 4 test files)
clear && yarn test

# Run tests in watch mode
clear && yarn test:watch

# Run tests with coverage
clear && yarn test:coverage
```

### Verify (before commit)

```bash
# Full verification — run this before any git commit
clear && yarn build && yarn test
```

### Other Commands

```bash
# Watch mode (recompile on change)
clear && yarn watch

# Start the server
clear && yarn start

# Clean dist/
clear && yarn clean

# Update all dependencies
clear && yarn ncu
```

## Project Structure

### Type: Single repository

### Directory Layout

```
docs/                    # Rule markdown documents (12 files, shipped with npm package)
  agents.md              #   AI agent behavior rules
  code.md                #   Coding standards (DRY, architecture, type safety)
  git-commands.md        #   Git commit protocols (gitcm/gitcmp)
  grill_me.md            #   Deep disambiguation protocol (grill_me)
  make_plan.md           #   Plan creation, execution protocol & implementation plan formatting
  preflight.md           #   Preflight review protocol — multi-dimensional quality audit (preflight)
  project-template.md    #   Project configuration template
  requirements.md        #   Requirements gathering & documentation (make_requirements)
  retro_requirements.md  #   Reverse requirements engineering (retro_requirements)
  techdocs.md            #   Technical architecture documentation (make_techdocs)
  testing.md             #   Testing standards & workflows
  upgrade_plan.md        #   Plan & requirements upgrade protocol (upgrade_plan, upgrade_requirements)
src/                     # TypeScript source code
  index.ts               #   Main entry point — MCP server bootstrap
  config.ts              #   Configuration resolution (CLI/env/defaults)
  types/                 #   Type definitions
    index.ts             #     All interfaces, types, constants, and metadata
  store/                 #   Data layer
    rule-store.ts        #     In-memory document store with O(1) lookup + fuzzy matching
    search-engine.ts     #     TF-IDF search engine with field weighting
  tools/                 #   MCP tool implementations (5 tools)
    get-rule.ts          #     get_rule — Retrieve a rule document by name/alias
    list-rules.ts        #     list_rules — List all rules grouped by category
    search-rules.ts      #     search_rules — Full-text search across rules
    analyze-project.ts   #     analyze_project — Scan project + generate/merge project.md
    get-setup-guide.ts   #     get_setup_guide — Setup instructions for new projects
  __tests__/             #   Test files (Vitest)
    store/               #     Store layer tests
      rule-store.test.ts
      search-engine.test.ts
    tools/               #     Tool layer tests
      tools-setup.ts     #       Shared test fixture (lazy-loaded store + engine)
      core-tools.test.ts #       Tests for get_rule, list_rules, search_rules, get_setup_guide
      analyze-project-merge.test.ts  # Tests for analyze_project + merge engine
dist/                    # Compiled output (git-ignored)
```

### Architecture Layers

```
┌─────────────────────────────────────────┐
│  MCP Protocol (stdio transport)          │
│  index.ts — Server + tool dispatcher     │
├─────────────────────────────────────────┤
│  Tools Layer (5 pure functions)          │
│  get-rule, list-rules, search-rules,     │
│  analyze-project, get-setup-guide        │
├─────────────────────────────────────────┤
│  Store Layer                             │
│  RuleStore (in-memory Map<id, doc>)      │
│  SearchEngine (TF-IDF inverted index)    │
├─────────────────────────────────────────┤
│  Types Layer                             │
│  Interfaces, constants, metadata         │
├─────────────────────────────────────────┤
│  Config Layer                            │
│  CLI args → env vars → bundled defaults  │
└─────────────────────────────────────────┘
```

## Coding Conventions

### Naming

- **Files:** kebab-case (e.g., `rule-store.ts`, `get-rule.ts`, `analyze-project.ts`)
- **Exception:** `make_plan` uses underscore in ID (matches the doc filename `make_plan.md`)
- **Classes:** PascalCase (e.g., `RuleStore`, `SearchEngine`, `StdioServerTransport`)
- **Functions/Methods:** camelCase (e.g., `getRule`, `findByName`, `resolveConfig`, `analyzeProject`)
- **Interfaces/Types:** PascalCase (e.g., `RuleDocument`, `SearchResult`, `ProjectAnalysis`, `ServerConfig`)
- **Constants:** UPPER_SNAKE_CASE (e.g., `STOP_WORDS`, `FIELD_WEIGHTS`, `AUTO_UPDATE_SECTIONS`, `RULE_METADATA`)
- **Inline constants (objects):** UPPER_SNAKE_CASE (e.g., `TOOL_DEFINITIONS`, `CATEGORY_INFO`)
- **Module-scoped privates:** camelCase (e.g., `cachedStore`, `cachedEngine`)
- **Test fixtures:** UPPER_SNAKE_CASE prefixed with `FIXTURE_` or `SAMPLE_` (e.g., `FIXTURE_FULL_PROJECT_MD`, `SAMPLE_ANALYSIS`)

### Code Style

- **Module format:** ESM with `.js` import extensions (required by Node16 resolution)
- **Imports:** Type-only imports use `import type { ... }` syntax
- **JSDoc:** Every exported function, class, and interface has JSDoc comments with `@param`, `@returns`, `@module` tags
- **Section separators:** `// ============` comment blocks separate logical sections within files
- **Error handling:** Errors caught and returned as formatted markdown strings (`**Error:** message`), never thrown to caller
- **Console output:** All log output goes to `stderr` (stdout reserved for MCP protocol)
- **Access modifiers:** Class members use `protected` for internal/overridable, `public` for API surface
- **Const assertions:** `as const` used for object literals that define fixed shapes (e.g., `FIELD_WEIGHTS`, `type: 'object' as const`)

### Patterns

- **Pure function tools:** Each tool is a standalone exported function taking (store/engine, args) → string
- **Formatter pattern:** Private `format*()` functions handle all markdown output generation
- **Lazy caching:** Test setup uses lazy singleton pattern (`cachedStore ?? build()`)
- **Mutation-in-place:** Project analysis functions mutate the `analysis` object directly (passed by reference)
- **Strategy pattern:** Merge engine uses `SectionMergeStrategy` classification (`auto-update`, `preserve`, `static`)
- **Fuzzy matching chain:** RuleStore.findByName tries 5 strategies in priority order (exact → alias → case-insensitive → partial → title)

## Git & Commit Conventions

### Commit Scope

```
# Use module/feature as scope:
# feat(tools): add new MCP tool
# fix(store): correct fuzzy matching
# test(merge): add merge engine tests
# refactor(types): reorganize interfaces
# docs(rules): update coding standards

# Common scopes: tools, store, types, config, docs, merge, search, rules
```

### Branch Strategy

- **Main branch:** `master` (used by semantic-release, see `.releaserc.json`)
- **Feature branches:** `feature/[name]`
- **Release:** Automated via semantic-release on `master` branch

### Release Process

- **Automated:** semantic-release handles versioning, changelog, npm publish, and GitHub releases
- **Commit convention:** Conventional Commits (feat, fix, chore, etc.)
- **Version:** Currently `1.2.0`
- **Published files:** `dist/`, `docs/`, `README.md`, `LICENSE`
- **Binary:** `codeops-mcp` CLI command (from `dist/index.js`)

## Special Rules (Project-Specific)

```
1. The docs/ directory contains the core rule documents that are SHIPPED with the npm
   package. Changes to docs/ files affect ALL users of codeops-mcp. Treat them as public API.

2. stdout is RESERVED for MCP protocol communication. All logging MUST go to stderr
   (use console.error, not console.log, except for --version output).

3. Tool functions return formatted markdown strings — they never throw errors.
   All error conditions are returned as "**Error:** message" formatted strings.

4. The analyze_project tool has TWO paths:
   - Fresh generation: No existing .clinerules/project.md → generate from scratch
   - Incremental merge: Existing file found → parse sections, merge with fresh scan,
     preserve user customizations (Coding Conventions, Git Conventions, Special Rules),
     update auto-detectable sections (Toolchain, Commands, Structure)

5. Tests use the REAL docs/ directory for integration testing (not mocks).
   The test setup (tools-setup.ts) uses lazy caching to avoid repeated file I/O.

6. Import paths MUST include .js extension (e.g., './config.js', '../types/index.js')
   because of Node16 module resolution with ESM.

7. The 12 rule document IDs are hardcoded in RULE_METADATA and RULE_ALIASES in types/index.ts.
   Adding a new rule document requires updating both maps.

8. All test files live under src/__tests__/ mirroring the src/ structure.
   Test files are excluded from TypeScript compilation (tsconfig.json exclude).
```

## Test Structure

```
4 test files, 107 total tests:

src/__tests__/store/rule-store.test.ts        — 22 tests (loading, lookup, fuzzy matching, categories, metadata)
src/__tests__/store/search-engine.test.ts     — 12 tests (indexing, search, scoring, filtering, excerpts)
src/__tests__/tools/core-tools.test.ts        — 28 tests (get_rule, list_rules, search_rules, get_setup_guide)
src/__tests__/tools/analyze-project-merge.test.ts — 45 tests (parser, classifier, merge engine, integration)

Test style:
- Integration tests using real docs/ directory
- Temp directory tests for filesystem operations (mkdtemp + cleanup)
- Fixture constants for merge tests (FIXTURE_FULL_PROJECT_MD, SAMPLE_ANALYSIS, etc.)
- beforeAll for shared setup, beforeEach/afterEach for temp dirs
```

## Cross-References

The generic rule files that read this `project.md`:

- **make_plan.md** — Uses verify command, file paths, commit scope, task file path patterns
- **code.md** — Uses language conventions, architecture rules
- **testing.md** — Uses test commands, test locations, test framework
- **git-commands.md** — Uses commit scope, verify command
- **agents.md** — Uses shell commands, verify command
- **requirements.md** — Uses project type, tech stack, and conventions for requirements discovery
- **retro_requirements.md** — Uses project type, tech stack for codebase analysis adaptation
