Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
140 changes: 140 additions & 0 deletions docs/ai/design/feature-lint-command.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
---
phase: design
title: System Design & Architecture
description: Define the technical architecture, components, and data models
---

# System Design & Architecture

## Architecture Overview
**What is the high-level system structure?**

```mermaid
graph TD
User --> CLI[ai-devkit lint command]
CLI --> ArgParser[Feature and output argument parser]
ArgParser --> LintService[Lint validation service]
LintService --> BaseCheck[Base docs checker]
LintService --> FeatureCheck[Feature docs checker]
LintService --> GitCheck[Worktree and branch checker]
BaseCheck --> FS[(File System)]
FeatureCheck --> FS
GitCheck --> Git[(Git metadata)]
CLI --> Reporter[Terminal and JSON reporter]
```

- Key components and responsibilities
- `lint` command handler: parse options and orchestrate checks.
- Name normalizer: convert `--feature` input into canonical `<name>` and `feature-<name>` (accept `foo` and `feature-foo`).
- Base docs checker: validate required phase template files (`docs/ai/*/README.md`).
- Feature docs checker: validate `docs/ai/{phase}/feature-<name>.md` across lifecycle phases.
- Git/worktree checker: evaluate feature branch/worktree convention used by `dev-lifecycle` Phase 1 prerequisite.
- Reporter (command-owned): consistent output rows (`[OK]`, `[MISS]`, `[WARN]`) and final summary with exit code.
- Technology stack choices and rationale
- TypeScript within existing CLI package for shared UX and testability.
- Extract shell script checks into reusable TS utilities to avoid behavior drift.
- Git checks via lightweight git commands (`git worktree list`, branch existence checks) to preserve compatibility.

## Data Models
**What data do we need to manage?**

- Core entities and their relationships
- `LintOptions`: parsed CLI options.
- `LintTarget`: normalized feature identity (`name`, `branchName`, `docSlug`).
- `LintCheckResult`: result of individual check.
- `LintSummary`: aggregate counts and final status.
- Data schemas/structures
- `LintOptions`
- `{ feature?: string, json?: boolean }`
- `LintTarget`
- `{ rawFeature: string, normalizedName: string, branchName: string, docFilePrefix: string }`
- `LintCheckResult`
- `{ id: string, level: 'ok' | 'miss' | 'warn', category: 'base-docs' | 'feature-docs' | 'git-worktree', required: boolean, message: string, fix?: string }`
- `LintSummary`
- `{ checks: LintCheckResult[], hasRequiredFailures: boolean, warningCount: number }`
- Data flow between components
- Parse args -> normalize feature -> run applicable checks -> collect results -> render terminal or JSON output -> return exit code.

## API Design
**How do components communicate?**

- External APIs (if applicable)
- CLI invocations:
- `ai-devkit lint`
- `ai-devkit lint --feature <name>`
- `ai-devkit lint --feature <name> --json`
- Internal interfaces
- `runLintChecks(options, dependencies?): LintReport`
- `renderLintReport(report, options): void` (in `commands/lint`)
- `normalizeFeatureName(input): string`
- `isInsideGitWorkTreeSync(cwd): boolean`
- `localBranchExistsSync(cwd, branchName): boolean`
- `getWorktreePathsForBranchSync(cwd, branchName): string[]`
- Request/response formats
- Input: CLI flags and current working directory.
- Output:
- Default: human-readable checklist and summary.
- `--json`: structured JSON object for CI parsing (checks, counts, normalized feature, pass/fail state).
- Exit code policy:
- `0`: no required failures.
- `1`: one or more required failures.
- Warnings (including missing dedicated worktree) do not change exit code when required checks pass.
- Authentication/authorization approach
- Read-only operations only (filesystem + git metadata queries).

## Component Breakdown
**What are the major building blocks?**

- Frontend components (if applicable)
- Terminal output formatter using existing CLI conventions.
- JSON formatter for machine-readable mode.
- Backend services/modules
- `commands/lint` command entry.
- `services/lint/lint.service.ts` for orchestration and business rules only.
- `services/lint/rules/*` for modular validation rules (base docs, feature docs, feature-name, git worktree).
- `util/git` sync helpers for git/worktree checks.
- `util/terminal-ui` for consistent terminal output formatting.
- Database/storage layer
- None.
- Third-party integrations
- Local git executable.

## Design Decisions
**Why did we choose this approach?**

- Key architectural decisions and trade-offs
- Re-implement shell checks in TypeScript while keeping output semantics:
- Pros: testable, reusable, cross-command integration.
- Cons: initial duplication until script is retired/repointed.
- Classify checks as required vs warning:
- Pros: keeps lifecycle gating strict for missing docs while allowing advisory worktree guidance.
- Cons: users may ignore warnings if not enforced in team policy.
- Normalize feature names automatically:
- Pros: better UX (`foo` and `feature-foo` both accepted).
- Cons: requires clear messaging of normalized value.
- Include `--json` output in v1:
- Pros: CI-friendly parsing and automated reporting.
- Cons: requires stable output schema maintenance.
- Alternatives considered
- Keep shell script only and wrap it from CLI:
- Rejected due to weaker cross-platform consistency and lower unit-test coverage.
- Hard-fail when dedicated worktree is missing:
- Rejected; requirement is warning-only behavior for this condition.
- Patterns and principles applied
- Single-responsibility check modules.
- Deterministic output for CI and humans.
- Collect-all-results reporting to surface all issues in one run.
- Avoid shell interpolation for git operations by using argument-based command execution.

## Non-Functional Requirements
**How should the system perform?**

- Performance targets
- Complete typical checks in under 1 second on standard repositories.
- Scalability considerations
- Check implementation should be extensible for additional lifecycle validations later.
- Security requirements
- No file writes or mutations.
- No network access required.
- Reliability/availability needs
- Command should gracefully handle missing git repo context and provide actionable fixes.
95 changes: 95 additions & 0 deletions docs/ai/implementation/feature-lint-command.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
---
phase: implementation
title: Implementation Guide
description: Technical implementation notes, patterns, and code guidelines
---

# Implementation Guide

## Development Setup
**How do we get started?**

- `npm install` at repository root.
- CLI package local validation commands:
- `npm run lint` (from `packages/cli`)
- `nx run cli:test -- --runInBand lint.test.ts` (from repo root)

## Code Structure
**How is the code organized?**

- `packages/cli/src/cli.ts`
- Registers new `lint` command and options (`--feature`, `--json`).
- `packages/cli/src/commands/lint.ts`
- Command entrypoint that runs checks, renders output, and sets process exit code.
- `packages/cli/src/services/lint/lint.service.ts`
- Core lint orchestration and business logic only (no terminal rendering).
- `packages/cli/src/services/lint/rules/`
- Rule modules split by concern (`base-docs`, `feature-name`, `feature-docs`, `git-worktree`).
- `packages/cli/src/__tests__/services/lint/lint.test.ts`
- Unit coverage for normalization and check outcomes.
- `packages/cli/src/__tests__/commands/lint.test.ts`
- Command-level coverage for orchestration and exit-code behavior.

## Implementation Notes
**Key technical details to remember:**

### Core Features
- Base readiness checks validate `docs/ai/{requirements,design,planning,implementation,testing}/README.md`.
- Feature mode normalizes `feature-<name>` and `<name>` into a shared `normalizedName`.
- Feature names are validated as kebab-case before running feature-level checks.
- Feature mode validates lifecycle docs:
- `docs/ai/{phase}/feature-<normalizedName>.md`
- Git validation behavior:
- Missing git repository => required failure.
- Missing `feature-<name>` branch => required failure.
- Missing dedicated worktree for branch => warning only.
- Command rendering supports:
- human-readable checklist output
- JSON report output with summary and per-check metadata

### Patterns & Best Practices
- `runLintChecks` accepts injected dependencies (`cwd`, `existsSync`, `execFileSync`) for testability.
- Shared phase-doc rule helper keeps base/feature doc checks consistent while avoiding duplication.
- Check results use a normalized shape (`LintCheckResult`) so rendering and JSON use one source of truth.
- Required failures drive exit code; warnings are advisory only.

## Integration Points
**How do pieces connect?**

- CLI wiring: Commander action in `packages/cli/src/cli.ts` calls `lintCommand`.
- `lintCommand` delegates to `runLintChecks` then `renderLintReport`.
- `lint.service` composes rule modules and uses `util/git` sync helpers to query `git rev-parse`, `git show-ref`, and `git worktree list --porcelain`.
- `commands/lint` owns `renderLintReport` and uses `util/terminal-ui` for consistent user-facing output.

## Error Handling
**How do we handle failures?**

- Git command failures are converted into deterministic lint results (miss or warn), not thrown errors.
- Missing files are reported with explicit path and remediation guidance.
- Output includes suggested fixes (for example `npx ai-devkit init`, `git worktree add ...`).

## Performance Considerations
**How do we keep it fast?**

- Uses direct existence checks and small git commands only.
- No recursive repository scans or network calls.

## Security Notes
**What security measures are in place?**

- Read-only filesystem and git metadata checks only.
- No mutation of repository state.
- Git commands use argument-based process execution (`execFileSync`) to avoid shell interpolation risks from user input.

## Phase 6 Check Implementation

- Design/requirements alignment: aligned for command surface, normalization, check categories, and exit behavior.
- Deviations and gaps:
- Full CLI binary execution via `npm run dev -- lint ...` is currently blocked by unrelated pre-existing TypeScript errors in `src/commands/memory.ts`.

## Phase 8 Code Review

- Blocking issue found and resolved:
- `packages/cli/src/services/lint/lint.service.ts`: replaced shell-command interpolation with argument-based git execution and added feature-name validation.
- Remaining non-blocking gap:
- Full CLI binary execution remains blocked by unrelated pre-existing TypeScript issues outside this feature.
95 changes: 95 additions & 0 deletions docs/ai/planning/feature-lint-command.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
---
phase: planning
title: Project Planning & Task Breakdown
description: Break down work into actionable tasks and estimate timeline
---

# Project Planning & Task Breakdown

## Milestones
**What are the major checkpoints?**

- [x] Milestone 1: Lint requirements/design approved
- [x] Milestone 2: `ai-devkit lint` base + feature checks implemented
- [x] Milestone 3: Tests, docs, and rollout complete

## Task Breakdown
**What specific work needs to be done?**

### Phase 1: Foundation
- [x] Task 1.1: Audit current CLI command registration and identify insertion point for `lint`
- [x] Task 1.2: Extract/reimplement `check-docs.sh` base and feature doc checks in TypeScript utilities
- [x] Task 1.3: Implement feature-name normalization utility (`foo` and `feature-foo` -> `foo`)
- [x] Task 1.4: Define shared lint result model and formatter (`ok/miss/warn`, remediation hints)

### Phase 2: Core Features
- [x] Task 2.1: Add `ai-devkit lint` command handler with base workspace checks
- [x] Task 2.2: Add `--feature <name>` mode with feature doc checks across all lifecycle phases
- [x] Task 2.3: Add git checks for `feature-<name>` branch/worktree presence and mapping
- [x] Task 2.4: Ensure proper exit codes and summary output for CI compatibility

### Phase 3: Integration & Polish
- [x] Task 3.1: Update help text and README command documentation
- [x] Task 3.2: Decide whether to keep `skills/dev-lifecycle/scripts/check-docs.sh` as wrapper or migrate references to `ai-devkit lint`
- [x] Task 3.3: Add actionable remediation guidance in failures (`npx ai-devkit init`, worktree creation command)
- [x] Task 3.4: Validate behavior against existing lifecycle docs and feature naming conventions

### Phase 4: Validation
- [x] Task 4.1: Unit tests for base docs checks and feature docs checks
- [x] Task 4.2: Unit tests for feature normalization and git/worktree validation logic
- [x] Task 4.3: Integration tests for CLI exit codes and terminal output
- [x] Task 4.4: Manual verification on repositories with and without required docs/worktrees

## Dependencies
**What needs to happen in what order?**

- Task dependencies and blockers
- Command registration and result model must be in place before integration tests.
- Feature-name normalization should be implemented before feature doc and git checks.
- Git check module should be stable before finalizing remediation messages.
- External dependencies (APIs, services, etc.)
- Local git executable availability for feature-level checks.
- Team/resource dependencies
- Maintainer review for lifecycle workflow compatibility and naming conventions.

## Timeline & Estimates
**When will things be done?**

- Estimated effort per task/phase
- Phase 1: 0.5-1 day
- Phase 2: 1-1.5 days
- Phase 3: 0.5 day
- Phase 4: 0.5-1 day
- Target dates for milestones
- Milestone 1: day 1
- Milestone 2: day 2-3
- Milestone 3: day 3-4
- Buffer for unknowns
- +20% for git/worktree edge-case handling and cross-platform output differences

## Risks & Mitigation
**What could go wrong?**

- Technical risks
- Git worktree detection may vary by repo state and user flow.
- Divergence between shell script and new TypeScript checks can cause inconsistent behavior.
- Resource risks
- Limited test coverage for unusual git/worktree layouts.
- Dependency risks
- Existing scripts or docs may still assume `check-docs.sh` behavior/output.
- Mitigation strategies
- Add fixture-based tests for multiple git states.
- Keep output mapping close to existing `check-docs.sh` semantics initially.
- Update docs and scripts in same change to avoid workflow drift.

## Resources Needed
**What do we need to succeed?**

- Team members and roles
- CLI implementer and reviewer
- Tools and services
- Existing TypeScript unit/integration test tooling
- Infrastructure
- Local git repo fixtures for worktree tests
- Documentation/knowledge
- Dev-lifecycle skill conventions and existing `check-docs.sh` behavior
Loading