Compare commits

...
80 Commits
Author SHA1 Message Date
Denozordec 5d1102b497 feat(firewall): refactor FirewallPage to use new grid components and improve loading states
CI / changes (push) Successful in 10s
CI / commitlint (push) Has been skipped
CI / openapi (push) Has been skipped
CI / web (push) Successful in 43s
CI / go (push) Has been skipped
CI / bird2 (push) Has been skipped
CI / release (push) Successful in 4m13s
Updated the FirewallPage component to replace the existing table implementations with FirewallClientsGrid and FirewallRulesGrid for better performance and user experience. Integrated QueryState for handling loading and error states, enhancing the UI responsiveness. Removed deprecated ClientsTable and RulesTable components to streamline the codebase.
2026-07-09 01:41:09 +07:00
Denozordec 5edbd656ba feat(firewall): add packet statistics tracking for firewall clients
CI / changes (push) Successful in 11s
CI / commitlint (push) Has been skipped
CI / openapi (push) Successful in 29s
CI / web (push) Successful in 1m6s
CI / go (push) Successful in 1m23s
CI / bird2 (push) Successful in 17s
CI / release (push) Successful in 4m42s
Enhanced the firewall client functionality by introducing packet statistics tracking, including the cumulative count of packets dropped and accepted. Updated the API to support these new fields and modified the database schema accordingly. Improved the firewall scripts to collect and report packet statistics, ensuring better visibility into client performance. Adjusted the UI components to display packet counts in the clients table, enhancing user experience and monitoring capabilities.
2026-07-09 00:50:38 +07:00
Denozordec 4a4c11c6bf feat(firewall): rename revoke function to delete and update related UI components
Refactored the revoke functionality for firewall clients to be more accurately represented as a delete operation. Updated the corresponding API call to use the DELETE method and modified the UI components to reflect this change, including confirmation dialogs and success messages. Adjusted tests to ensure the new delete functionality works as intended.
2026-07-09 00:27:50 +07:00
Denozordec e51999c908 feat(firewall): add revoke functionality for firewall clients and enhance status badge
CI / changes (push) Successful in 13s
CI / commitlint (push) Has been skipped
CI / openapi (push) Successful in 30s
CI / web (push) Successful in 56s
CI / go (push) Successful in 1m11s
CI / bird2 (push) Successful in 27s
CI / release (push) Successful in 4m19s
Implemented the ability to revoke approved firewall clients and reject pending requests through new API endpoints. Updated the StatusBadge component to include additional status variants for 'approved', 'revoked', 'pending', and 'block'. Enhanced the FirewallPage UI to support client revocation and rejection actions, integrating confirmation dialogs for user interactions. Updated tests to ensure proper functionality of the new revoke feature.
2026-07-08 23:27:29 +07:00
Denozordec b7f7669685 feat(firewall): improve blocklist parsing and nft element addition
CI / changes (push) Successful in 9s
CI / commitlint (push) Has been skipped
CI / openapi (push) Successful in 25s
CI / web (push) Successful in 42s
CI / go (push) Successful in 1m1s
CI / bird2 (push) Successful in 15s
CI / release (push) Successful in 4m17s
Enhanced the blocklist parsing function to log when the blocklist file is empty. Introduced new helper functions `nft_join_elements` and `nft_add_v4_chunk` to streamline the addition of elements to the nftables, allowing for batch processing and improved error handling. Adjusted the chunk size for element addition to optimize performance. Updated logging to provide better visibility into the blocklist processing and applied prefixes.
2026-07-08 22:02:59 +07:00
Denozordec 947d1f0cc4 feat(firewall): enhance blocklist handling and installation script
CI / changes (push) Successful in 11s
CI / commitlint (push) Has been skipped
CI / openapi (push) Successful in 29s
CI / web (push) Successful in 58s
CI / go (push) Successful in 1m20s
CI / bird2 (push) Successful in 18s
CI / release (push) Successful in 4m37s
Updated the firewall scripts to improve blocklist handling by introducing a new method for fetching and parsing blocklist data using either `jq` or `python3`. Enhanced the installation script to ensure the presence of required dependencies and provided user guidance for post-approval actions. Additionally, improved logging for applied prefixes and total counts, ensuring better visibility into the firewall's operational status.
2026-07-08 21:45:32 +07:00
Denozordec 68f9d4b832 refactor(firewall): simplify SQL queries for firewall client retrieval
CI / changes (push) Successful in 13s
CI / commitlint (push) Has been skipped
CI / openapi (push) Has been skipped
CI / web (push) Has been skipped
CI / go (push) Successful in 1m6s
CI / bird2 (push) Successful in 18s
CI / release (push) Successful in 3m57s
Refactored the SQL queries in the Postgres repository for listing and retrieving firewall clients by introducing a constant for the selected columns. This change improves code readability and maintainability by reducing duplication in the query definitions. No functional changes were made to the data retrieval process.
2026-07-08 21:16:57 +07:00
Denozordec 72045afcde feat(firewall): improve error handling and documentation for firewall enrollment
CI / changes (push) Successful in 11s
CI / commitlint (push) Has been skipped
CI / openapi (push) Successful in 25s
CI / web (push) Successful in 43s
CI / go (push) Successful in 1m2s
CI / bird2 (push) Successful in 16s
CI / release (push) Successful in 3m41s
Enhanced the firewall enrollment process by implementing better error handling for HTTP responses, specifically addressing database schema issues. Updated the documentation to include migration requirements for PostgreSQL and clarified the steps to take if enrollment fails due to an outdated schema. This ensures users are better informed about necessary actions during deployment.
2026-07-08 21:00:27 +07:00
Denozordec e15768b25b feat(firewall): implement public HTTPS endpoints for firewall scripts and enhance URL handling
CI / changes (push) Successful in 15s
CI / commitlint (push) Has been skipped
CI / openapi (push) Has been skipped
CI / web (push) Successful in 1m0s
CI / go (push) Successful in 1m0s
CI / bird2 (push) Successful in 16s
CI / release (push) Successful in 3m39s
Added public HTTPS endpoints for firewall installation and enrollment scripts, allowing access without API keys. Updated the URL handling in the firewall code to ensure all suggested control plane URLs are served over HTTPS. Enhanced documentation to reflect the new public endpoints and their usage. Updated tests to verify the correct behavior of the new URL handling logic.
2026-07-08 18:54:27 +07:00
Denozordec 7b3f002e5f feat(firewall): enhance firewall management with community selection and script handling
CI / changes (push) Successful in 10s
CI / commitlint (push) Has been skipped
CI / openapi (push) Has been skipped
CI / web (push) Successful in 57s
CI / go (push) Successful in 1m11s
CI / bird2 (push) Successful in 15s
CI / release (push) Successful in 4m16s
Added a community selection feature to the firewall rules management UI, allowing users to specify BGP communities for block/accept policies. Updated the backend to support reading firewall scripts from a specified directory, improving script management. Enhanced documentation to clarify the new community functionality and its implications for firewall rules. Additionally, introduced tests for the firewall script endpoints to ensure proper functionality.
2026-07-08 17:50:38 +07:00
Denozordec fa2abc81f3 feat(firewall): add install context query and API endpoint for firewall client setup
CI / changes (push) Successful in 13s
CI / commitlint (push) Has been skipped
CI / openapi (push) Successful in 27s
CI / web (push) Successful in 1m1s
CI / go (push) Successful in 1m16s
CI / bird2 (push) Successful in 17s
CI / release (push) Successful in 4m4s
Introduced a new API endpoint for retrieving the install context of the firewall client, which includes the bundle seed, configuration status, and suggested control plane URL. Updated the frontend to utilize this new endpoint, enhancing the user experience by dynamically displaying relevant information. Additionally, added type definitions for the install context and integrated it into the existing firewall management flow.
2026-07-08 17:17:34 +07:00
Denozordec 7a3eae98b1 feat(firewall): implement firewall blocklist feature with client management and policy rules
CI / changes (push) Successful in 12s
CI / commitlint (push) Has been skipped
CI / openapi (push) Successful in 25s
CI / web (push) Successful in 46s
CI / go (push) Successful in 1m15s
CI / bird2 (push) Successful in 18s
CI / release (push) Successful in 3m59s
Introduced a comprehensive firewall blocklist feature, allowing for the management of firewall clients and their associated rules. This includes endpoints for enrolling clients, listing clients and rules, and reporting apply statuses. Enhanced the API to support firewall operations, including the ability to handle block/accept policies. Updated the documentation to reflect these changes and added necessary components in the web UI for better user interaction.

Additionally, modified the agent server to support firewall failover and integrated firewall functionality into the existing architecture.
2026-07-08 16:37:27 +07:00
Denozordec 276194a9d0 fix(daemon): update PID and timestamps in .codegraph/daemon.pid for synchronization 2026-07-07 17:09:55 +07:00
Denozordec 53b3c49612 refactor(settings): simplify settings query options and remove tenant dependency
CI / changes (push) Successful in 10s
CI / commitlint (push) Has been skipped
CI / openapi (push) Successful in 28s
CI / web (push) Successful in 1m0s
CI / go (push) Successful in 1m11s
CI / bird2 (push) Successful in 16s
CI / release (push) Successful in 4m5s
Updated the settings query options to eliminate the tenant ID parameter, streamlining the settings retrieval process. Adjusted the TenantSettingsComponent to reflect this change, ensuring it now queries settings without relying on tenant-specific data. This refactor enhances code clarity and reduces complexity in the settings management flow.
2026-07-06 23:28:14 +07:00
Denozordec db79820df0 feat(auth): introduce demo token support and enhance API token handling
CI / changes (push) Successful in 10s
CI / commitlint (push) Has been skipped
CI / openapi (push) Successful in 28s
CI / web (push) Successful in 57s
CI / go (push) Successful in 1m9s
CI / bird2 (push) Successful in 17s
CI / release (push) Successful in 3m57s
Added a local demo token for development purposes and improved the API token management by normalizing input tokens. Updated the authentication flow to utilize the new token handling, allowing for better session management and user experience. Enhanced the settings component to support the demo token and provide clear instructions for its use in local development.
2026-07-06 22:55:30 +07:00
Denozordec a902a4270d fix(api-keys): enhance API key management with new mutations and UI updates
CI / changes (push) Successful in 14s
CI / commitlint (push) Has been skipped
CI / openapi (push) Has been skipped
CI / web (push) Successful in 59s
CI / go (push) Has been skipped
CI / bird2 (push) Has been skipped
CI / release (push) Successful in 3m47s
Added new mutations for creating, revoking, and rotating API keys in the api-keys query file. Updated the Access component to utilize these mutations, improving the user interface with better feedback and session management. Introduced a new AccessApiKeysCard for displaying API key information and enhanced the overall layout and user experience in the access route.
2026-07-06 20:32:17 +07:00
Denozordec 3a3e6db018 fix(tabs): update Tabs component for orientation handling and improve class names
CI / changes (push) Successful in 10s
CI / commitlint (push) Has been skipped
CI / openapi (push) Has been skipped
CI / web (push) Successful in 45s
CI / go (push) Successful in 57s
CI / bird2 (push) Successful in 15s
CI / release (push) Successful in 4m15s
Enhanced the Tabs component to support orientation prop, ensuring proper layout for both horizontal and vertical orientations. Updated class names for better clarity and consistency in styling. Additionally, modified the daemon PID and timestamps in .codegraph/daemon.pid for synchronization.
2026-07-06 18:45:44 +07:00
Denozordec 144d342c16 fix(modules): enhance ModuleDetailComponent with additional queries and UI updates
CI / changes (push) Successful in 11s
CI / commitlint (push) Has been skipped
CI / openapi (push) Has been skipped
CI / web (push) Successful in 1m3s
CI / go (push) Has been skipped
CI / bird2 (push) Has been skipped
CI / release (push) Successful in 4m4s
Updated the ModuleDetailComponent to include new queries for communities and DoH profiles, improving data handling. Added a module type alert function for better user guidance and refined the UI to display module type in a more user-friendly manner. Removed unused components and streamlined the refresh functionality for better performance.
2026-07-03 16:50:21 +07:00
Denozordec 0af37d55c4 fix(pagination): enhance DataGridPagination to dynamically populate Select items
CI / changes (push) Successful in 9s
CI / commitlint (push) Has been skipped
CI / openapi (push) Has been skipped
CI / web (push) Successful in 1m0s
CI / go (push) Has been skipped
CI / bird2 (push) Has been skipped
CI / release (push) Successful in 4m37s
Updated the DataGridPagination component to map available sizes into Select items for better user experience. This change allows for dynamic selection of page sizes based on the provided props.
2026-07-03 14:43:46 +07:00
Denozordec 78f2ecc246 fix(auth): update Select components to include SelectValue for better placeholder handling
CI / changes (push) Successful in 9s
CI / commitlint (push) Has been skipped
CI / openapi (push) Has been skipped
CI / web (push) Successful in 57s
CI / go (push) Successful in 1m5s
CI / bird2 (push) Successful in 17s
CI / release (push) Successful in 4m0s
Modified the Select components in operations.tsx, settings.tsx, and tenant-settings.tsx to incorporate SelectValue for improved placeholder functionality. Additionally, updated the daemon PID and timestamps in .codegraph/daemon.pid for consistency.
2026-07-03 14:10:23 +07:00
DenozordecandCursor 8c97445f7e fix(jobs): make deploy coalescing deterministic via inflight counter
CI / changes (push) Successful in 12s
CI / openapi (push) Has been skipped
CI / web (push) Has been skipped
CI / commitlint (push) Has been skipped
CI / go (push) Successful in 1m11s
CI / bird2 (push) Successful in 16s
CI / release (push) Successful in 4m27s
TestParallelModuleRefresh_CoalescesDeployApply падал на CI под -race
(want exactly one deploy_apply job, got 2). Локально тест проходил
стабильно (100/500 итераций с -cpu), но узкая гонка проявлялась при
замедлении под race-детектором.

Корень: коалесцирование решало «делать ли deploy» через
CountOtherActiveRefresh, который опрашивал статусы job-ов (queued/
running). Статусы меняются асинхронно относительно tenantRefreshMu,
поэтому в редких таймингах оба параллельных refresh могли решить,
что другой уже не активен, и каждый породил свой deploy_apply.

Решение — детерминированный inflight-счётчик refresh-kind job-ов в
Registry (inflightRefresh map[string]int), управляемый под r.mu:
- инкремент в Enqueue при создании нового refresh-kind job-а;
- декремент + проверка «последний ли я» в finishModuleRefreshSuccess
  через новый метод finalizeRefreshCoalesce (под tenantRefreshMu).

Последний refresh (счётчик <= 1) делает render + deploy_apply; все
остальные defer-ят. Решение больше не зависит от опроса статусов и
таймингов ingest.

Чтобы счётчик не утёк на error/cancel путях (где refresh не доходит
до finishModuleRefreshSuccess), обработка module_refresh и
tenant_refresh вынесена в runModuleRefresh / runTenantRefresh с
defer-обёрткой, которая гарантированно освобождает слот, если
finishModuleRefreshSuccess не отработал.

CountOtherActiveRefresh / CountOtherActiveModuleRefresh оставлены
как публичные методы (могут использоваться в мониторинге); из
продакшн-логики коалесцирования убраны.

Проверки: go build, go vet, go test ./internal/... -count=1 — exit 0.
Стресс-тест коалесцирования: 200 итераций с -cpu=4 — стабильно.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-03 01:31:32 +07:00
DenozordecandCursor 0ea5b3b738 fix(bird2): switch download host from bird.network.cz to bird.nic.cz
CI / changes (push) Successful in 11s
CI / commitlint (push) Has been skipped
CI / openapi (push) Has been skipped
CI / web (push) Has been skipped
CI / go (push) Failing after 41s
CI / bird2 (push) Has been skipped
CI / release (push) Has been skipped
Docker-сборка birdc падала с HTTP 403 при скачивании исходников BIRD
2.14 с bird.network.cz. Старый домен bird.network.cz больше не отдаёт
файлы (403 для всех путей и User-Agent), официальный сайт BIRD переехал
на bird.nic.cz.

URL bird.nic.cz/download/bird-2.14.tar.gz проверен: 200 OK, ~1.4 МБ,
совпадает с размером на старом домене. Страница old-releases на новом
домене подтверждает тот же путь /download/bird-2.14.tar.gz.

Изменены все 5 вхождений старого домена в репозитории:
- deploy/docker/bird/bird-from-source.sh — критичный curl в сборке;
- .cursor/rules/networking-bird.mdc — BIRD2 docs и DOC-SYNC-05;
- .cursor/rules/context7-stack.mdc — приоритет источников;
- .cursor/rules/engineering.mdc — таблица Documentation Sync.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-02 23:30:56 +07:00
DenozordecandCursor 66b785f7cb fix(ci): replace pnpm/action-setup with corepack for web job
CI / changes (push) Successful in 9s
CI / commitlint (push) Has been skipped
CI / openapi (push) Successful in 29s
CI / web (push) Successful in 1m3s
CI / go (push) Successful in 1m10s
CI / bird2 (push) Successful in 19s
CI / release (push) Failing after 3m33s
pnpm/action-setup@v4 на Gitea Actions продолжает падать на
Running self-installer даже после перестановки шагов
(setup-node перед action-setup). Action использует GitHub-specific
механику скачивания pnpm, которая ненадёжна на Gitea runner.

Вместо pnpm/action-setup используем corepack (встроен в Node 22):
corepack enable активирует pnpm@10.33.2 из поля packageManager в
package.json — тот же механизм, что работает в Dockerfile. Это
устраняет зависимость от внешнего action и его self-installer.

Кэш pnpm-store добавим позже через actions/cache или setup-node
cache: pnpm (теперь pnpm доступен к моменту настройки кэша).
Сейчас приоритет — сделать step рабочим.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-02 23:17:26 +07:00
DenozordecandCursor cb14194a5f fix(ci): order setup-node before pnpm action and cache pnpm store
CI / changes (push) Successful in 8s
CI / commitlint (push) Has been skipped
CI / openapi (push) Successful in 28s
CI / web (push) Failing after 9s
CI / go (push) Successful in 58s
CI / bird2 (push) Successful in 15s
CI / release (push) Has been skipped
Job web падал на шаге pnpm/action-setup@v4 (Running self-installer)
из-за неверного порядка: pnpm/action-setup вызывался до
actions/setup-node, поэтому Node.js ещё не был настроен к моменту
запуска self-installer pnpm. Добавление packageManager в package.json
усугубило ситуацию — action начал honour'ить его через node-зависимый
инсталлер, которому не хватило Node.

Изменения в job web:
- actions/setup-node@v4 (node 22) перенесён ВЫШЕ pnpm/action-setup@v4;
- кэш pnpm-store включён через cache: true в pnpm/action-setup
  (вместо cache: pnpm в setup-node, который требует pnpm установленным
  раньше и спотыкается о тот же порядок).

Версия pnpm задаётся полем packageManager в package.json (pnpm@10.33.2)
и дублируется в Dockerfile через corepack prepare, поэтому version: 10
в action оставлен как совместимый fallback.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-02 23:09:44 +07:00
Denozordec 9c38e1bc57 fix(ci): update daemon PID and timestamps in configuration files
CI / changes (push) Successful in 9s
CI / commitlint (push) Has been skipped
CI / openapi (push) Successful in 27s
CI / web (push) Failing after 9s
CI / go (push) Successful in 52s
CI / bird2 (push) Successful in 15s
CI / release (push) Has been skipped
Updated the daemon PID from 44608 to 52448 and adjusted the startedAt timestamp in the .codegraph/daemon.pid file. Additionally, modified the CI workflow configuration in .gitea/workflows/ci.yaml to ensure consistent pnpm version usage during the setup process.
2026-07-02 19:10:18 +07:00
DenozordecandCursor 4ac99e43ae fix(web): pin pnpm version via packageManager and corepack prepare
CI / changes (push) Successful in 8s
CI / commitlint (push) Has been skipped
CI / openapi (push) Successful in 24s
CI / go (push) Successful in 53s
CI / bird2 (push) Successful in 16s
CI / web (push) Failing after 7s
CI / release (push) Has been skipped
Предыдущий фикс (onlyBuiltDependencies в pnpm-workspace.yaml) оказался
недостаточным: Docker-сборка evobgp-web продолжала падать с
ERR_PNPM_IGNORED_BUILDS для esbuild. Причина — в корневом package.json
отсутствовало поле packageManager, а Dockerfile вызывал corepack enable
без пина версии. Corepack активировал устаревшую pnpm, зашитую в образ
node:22-alpine, которая не поддерживает чтение onlyBuiltDependencies из
pnpm-workspace.yaml (эта возможность появилась в pnpm 10.4+).

Двойная защита от рассинхрона версий pnpm между локальной средой,
CI и Docker:

- package.json: packageManager = pnpm@10.33.2 (стандарт corepack).
- Dockerfile: corepack prepare pnpm@10.33.2 --activate — явно ставит
  нужную версию даже если package.json ещё не скопирован на момент
  первого вызова pnpm.

Локально: typecheck и build @evobgp/web — exit 0.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-02 19:03:58 +07:00
DenozordecandCursor f26c15401c fix(web): allow esbuild postinstall for pnpm 10 frozen install
CI / changes (push) Successful in 9s
CI / commitlint (push) Has been skipped
CI / openapi (push) Successful in 25s
CI / web (push) Successful in 46s
CI / go (push) Successful in 59s
CI / bird2 (push) Successful in 14s
CI / release (push) Failing after 1m58s
В pnpm 10 postinstall-скрипты unreviewed-зависимостей по умолчанию
блокируются (strictDepBuilds=true), из-за чего pnpm install
--frozen-lockfile в Docker падал с ERR_PNPM_IGNORED_BUILDS для
esbuild@0.28.1. Vite требует нативный бинарник esbuild для билда
apps/web, поэтому скрипт нужно выполнять.

onlyBuiltDependencies в pnpm-workspace.yaml явно одобряет сборку
esbuild. Поведение проверено локально в условиях CI (чистый store,
CI=true, --frozen-lockfile): postinstall выполняется, install и
build проходят с exit 0.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-02 18:30:37 +07:00
DenozordecandCursor c144b49acf feat!(web): migrate UI from SvelteKit to React + shadcn/ui + ReUI
CI / changes (push) Successful in 17s
CI / commitlint (push) Has been skipped
CI / openapi (push) Successful in 26s
CI / web (push) Successful in 46s
CI / go (push) Successful in 1m1s
CI / bird2 (push) Successful in 17s
CI / release (push) Failing after 2m22s
Web UI полностью переведён с SvelteKit на новый стек: React 19,
TanStack Router/Query/Table/Virtual, shadcn/ui (base-nova) и ReUI
enterprise-компоненты (data-grid, filters, autocomplete). Новый код
разложен по слоям: packages/ui (shadcn-примитивы), apps/web
(роуты, shared-обёртки, ReUI-адаптации).

BREAKING CHANGE: меняется структура и инструментинг фронтенда.

- apps/web/ — новый Vite + React-проект (@evobgp/web), file-based
  роуты TanStack Router; экраны dashboard, modules, monitoring,
  network, operations, schedule, settings, tenant-settings, access,
  directories.
- packages/ui/ — shadcn/ui-примитивы (@evobgp/ui) с общими стилями
  globals.css и cn-утилитой; CLI shadcn запускается из apps/web.
- apps/web/src/components/reui/ — enterprise-паттерны ReUI.
- pnpm workspace (pnpm-workspace.yaml, pnpm-lock.yaml, tsconfig.base.json)
  заменяет npm-проект в web/.
- web/ переименован в web-legacy-svelte/ (архив-референс для миграции);
  импорты оттуда запрещены правилом WEB-22.
- CI (.gitea/workflows/ci.yaml): job web переведён на Node 22 + pnpm 10
  (typecheck/lint/build через pnpm --filter @evobgp/web); пути триггеров
  обновлены под apps/web|packages/ui.
- deploy/docker/evobgp-web/Dockerfile: сборка из корня репозитория,
  pnpm install --frozen-lockfile, выход dist из apps/web/dist.
- .cursor/rules/web-shadcn.mdc, context7-stack.mdc, engineering.mdc,
  AGENTS.md — обновлены под React-стек (WEB-01..WEB-22, DOC-SYNC-06/07).

Проверки WEB-19 локально: typecheck, lint, build — exit 0.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-02 17:59:59 +07:00
Denozordec db75126bea feat(runtime-logs): enhance auto-cleanup features and documentation
CI / changes (push) Successful in 9s
CI / commitlint (push) Has been skipped
CI / openapi (push) Successful in 26s
CI / web (push) Successful in 33s
CI / go (push) Successful in 56s
CI / bird2 (push) Successful in 14s
CI / release (push) Successful in 20s
Added new endpoints for estimating and executing runtime log auto-cleanup based on tenant settings. Introduced configuration options for auto-cleanup policies, including scheduling and file size limits. Updated the API documentation and UI components to reflect these changes, improving user interaction with runtime log management. Enhanced error handling and added new UI elements for better visibility of audit logs and cleanup actions.
2026-06-12 22:44:39 +07:00
Denozordec f39df7c4bf feat(revisions): add pruning estimate and cleanup endpoints
CI / changes (push) Successful in 8s
CI / commitlint (push) Has been skipped
CI / openapi (push) Successful in 25s
CI / web (push) Successful in 32s
CI / go (push) Successful in 57s
CI / bird2 (push) Successful in 15s
CI / release (push) Successful in 3m18s
Implemented new endpoints for estimating and pruning revisions, including detailed schemas for requests and responses. The `RevisionPruneEstimate` and `RevisionPruneResult` components were added to the OpenAPI documentation, enhancing the API's functionality for managing revision retention. Updated the backend to support these operations and integrated them into the tenant settings UI for improved user interaction.
2026-06-12 21:56:36 +07:00
DenozordecandCursor 5dbdac3d2c feat(memory-bank): update active context and progress documentation
CI / changes (push) Successful in 8s
CI / commitlint (push) Has been skipped
CI / openapi (push) Successful in 25s
CI / web (push) Successful in 30s
CI / go (push) Successful in 54s
CI / bird2 (push) Successful in 14s
CI / release (push) Successful in 3m43s
Обновлены разделы активного контекста и прогресса для задачи `settings-ui-and-runtime-logs`. Упрощено отображение статуса завершённых фаз и добавлены ссылки на архив. Уточнены следующие шаги и активные задачи, улучшая ясность и доступность информации.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-12 21:11:15 +07:00
DenozordecandCursor a0f78a3d21 feat(runtime-logs): update documentation and UI for runtime log management
Обновлены разделы документации для управления файловыми логами, включая новые эндпоинты и параметры. Добавлены описания для вкладки «Файловые логи» в интерфейсе мониторинга и обновлены настройки tenant. Улучшен доступ к логам через API и интерфейс пользователя.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-12 21:04:29 +07:00
DenozordecandCursor 0c5502b5bb feat(runtime-logs): enhance runtime log management and configuration
Добавлены новые возможности для управления файловыми логами в Docker-сервисах:
- Обновлены конфигурации для поддержки логов, включая переменные окружения и монтирование директорий.
- Документация обновлена для описания новых эндпоинтов и параметров, связанных с логами.
- Упрощен доступ к логам через API и интерфейс пользователя.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-12 19:18:50 +07:00
DenozordecandCursor 3f0dd6c234 docs(runtime-logs): implement runtime log management features
Добавлены новые возможности для работы с файловыми логами Docker-сервисов:
- Эндпоинты для получения списка логов и хвоста лог-файла.
- Очистка лог-файлов с возможностью выбора режима (truncate или delete) и запись в аудит очистки.
- Обновлена документация и конфигурация для поддержки новых функций.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-12 19:04:53 +07:00
DenozordecandCursor 1c39c65fc5 docs(memory-bank): add creative phase CP-4 path safety
Решение: allowlist *.log, EvalSymlinks, проверка префикса root; creative phase завершён.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-12 18:58:16 +07:00
DenozordecandCursor 493575aca4 docs(memory-bank): add creative phase CP-3 runtime logs cleanup
Решение: truncate по умолчанию, delete опционально, лимиты tail и max 512 MiB на sync cleanup.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-12 18:58:06 +07:00
DenozordecandCursor e27936c072 docs(memory-bank): add creative phase CP-2 runtime logs UI
Решение: вкладка «Файловые логи» в Monitoring с подвкладками files и audit.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-12 18:58:01 +07:00
DenozordecandCursor ceb6f2f34f docs(memory-bank): add creative phase CP-1 tenant settings UI
Решение: /tenant-settings с вкладками BIRD/Ревизии/Дополнительно, пункт mainNav «Параметры», /settings остаётся frontend-only.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-12 18:57:17 +07:00
Denozordec de64374c91 feat(web): implement schedule editor in MaintenancePoliciesTab
CI / changes (push) Successful in 8s
CI / commitlint (push) Has been skipped
CI / openapi (push) Has been skipped
CI / web (push) Successful in 31s
CI / go (push) Successful in 51s
CI / bird2 (push) Successful in 15s
CI / release (push) Successful in 3m48s
Enhanced the MaintenancePoliciesTab by integrating a schedule editor for maintenance policies. Users can now select schedule modes, input custom cron expressions, and dynamically update the schedule preview. This update improves the user interface and experience for managing maintenance schedules.
2026-06-12 18:40:22 +07:00
Denozordec 132559cb8e feat(web): enhance MaintenancePoliciesTab with preset management
CI / changes (push) Successful in 8s
CI / commitlint (push) Has been skipped
CI / openapi (push) Has been skipped
CI / web (push) Successful in 29s
CI / go (push) Has been skipped
CI / bird2 (push) Has been skipped
CI / release (push) Successful in 3m46s
Added functionality for selecting and applying maintenance policy presets in the MaintenancePoliciesTab. Users can now create policies from selected presets, apply presets to the form, and receive notifications on the creation process. Updated UI components to support these features, improving user experience and efficiency in managing maintenance policies.
2026-06-12 14:07:24 +07:00
Denozordec aa4e3d0180 docs(agents): update engineering rules and add Context7 documentation references
CI / changes (push) Successful in 9s
CI / commitlint (push) Has been skipped
CI / openapi (push) Successful in 25s
CI / web (push) Successful in 31s
CI / go (push) Successful in 2m14s
CI / bird2 (push) Successful in 15s
CI / release (push) Successful in 3m53s
Added Context7 documentation links for stack IDs and skills to the agents guide, enhancing clarity on library usage and integration.
2026-06-12 13:48:37 +07:00
DenozordecandCursor 1ccffc85da test(maintenance): add policy executor and handler tests
Табличные тесты PolicyExecutor, ConfigProvider reload, memory CRUD политик и 503 для /v1/maintenance/* на memory-бэкенде без PostgreSQL.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-12 13:32:01 +07:00
DenozordecandCursor d38ee68c4e feat(web): add maintenance policies UI
Вкладка политик обслуживания PostgreSQL: CRUD через /v1/maintenance/policies, run/dry-run, форма с Zod. Hardcoded кнопки vacuum/cleanup в MonitoringPostgresTab заменены на MaintenancePoliciesTab.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-12 13:30:43 +07:00
DenozordecandCursor aaef47c7a7 feat(observability): add maintenance policy metrics
Prometheus: runs, duration, rows_deleted, config_changes; инкремент при CRUD и Execute.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-12 13:28:20 +07:00
DenozordecandCursor cbf345b25f refactor(maintenance): remove hardcoded retention and wire scheduler
RunPeriodicMaintenance и RunCleanup удалены; scheduler политик в StartBackground; deprecated /postgres/cleanup принимает policy_id.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-12 13:27:49 +07:00
DenozordecandCursor f548d0671f feat(api): add /v1/maintenance policies and run endpoints
OpenAPI, httpapi CRUD/run/dry-run, job maintenance_policy_run и audit с policy_id.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-12 13:23:10 +07:00
DenozordecandCursor 6510a9ca22 feat(maintenance): add policy executor and config provider
ConfigProvider, PolicyExecutor, DBStatsProvider, scheduler и safety; зависимость robfig/cron/v3.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-12 13:21:32 +07:00
DenozordecandCursor 07c3de4939 feat(store): add MaintenancePolicy CRUD backend
Типы maintenance_policy, методы store.Backend и реализации для PostgreSQL и in-memory.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-12 13:20:27 +07:00
DenozordecandCursor 948dac34fd feat(db): add maintenance_policy migration 000025
Добавлены таблицы maintenance_policy и maintenance_policy_config_audit для postgres и sqlite; в postgres_maintenance_audit — колонка policy_id.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-12 13:19:27 +07:00
Denozordec 480756d832 feat(settings): enhance revision retention minutes validation
CI / changes (push) Successful in 8s
CI / commitlint (push) Has been skipped
CI / openapi (push) Has been skipped
CI / web (push) Successful in 29s
CI / go (push) Has been skipped
CI / bird2 (push) Has been skipped
CI / release (push) Successful in 3m14s
Introduced a preprocessing function to normalize input for the revision retention minutes field, ensuring it handles various input types correctly. Updated the schema to utilize this new validation method, improving data integrity and user experience.
2026-06-01 14:35:51 +07:00
Denozordec 135fb34e00 fix(pgmonitor): standardize field alignment in QueriesResponse struct
CI / changes (push) Successful in 7s
CI / commitlint (push) Has been skipped
CI / openapi (push) Has been skipped
CI / web (push) Has been skipped
CI / go (push) Successful in 54s
CI / bird2 (push) Successful in 15s
CI / release (push) Successful in 3m46s
2026-06-01 14:18:03 +07:00
Denozordec 9efa3bbc8a feat(db): enhance PostgreSQL statistics monitoring and error handling
CI / changes (push) Successful in 8s
CI / commitlint (push) Has been skipped
CI / openapi (push) Has been skipped
CI / web (push) Successful in 30s
CI / go (push) Failing after 24s
CI / bird2 (push) Has been skipped
CI / release (push) Has been skipped
Updated the PostgreSQL monitoring service to improve handling of `pg_stat_statements` availability. Introduced a new method to check if the extension is queryable and updated the response structure to include availability status and hints. Enhanced the documentation to clarify the requirements for enabling `pg_stat_statements`. Adjusted related components to reflect these changes, ensuring better user feedback in the monitoring interface.
2026-06-01 14:15:38 +07:00
Denozordec fad2bd3353 feat(db): implement PostgreSQL monitoring and maintenance features
CI / changes (push) Successful in 9s
CI / commitlint (push) Has been skipped
CI / openapi (push) Successful in 26s
CI / web (push) Successful in 33s
CI / go (push) Successful in 2m11s
CI / bird2 (push) Successful in 16s
CI / release (push) Successful in 3m27s
Added PostgreSQL monitoring and maintenance capabilities to the API, including new endpoints for instance-level metrics, maintenance operations, and job scheduling. Updated the HTTP API to support PostgreSQL monitoring routes and integrated a background scheduler for metrics collection. Enhanced the CLI with database commands for maintenance tasks. Updated documentation to reflect these changes.
2026-06-01 13:43:33 +07:00
Denozordec 930e42b0b0 fix(db): update prefix handling in module_prefix_snapshot_row
CI / changes (push) Successful in 8s
CI / commitlint (push) Has been skipped
CI / openapi (push) Has been skipped
CI / web (push) Has been skipped
CI / go (push) Successful in 55s
CI / bird2 (push) Successful in 14s
CI / release (push) Successful in 3m21s
Modified the prefix column type in the module_prefix_snapshot_row table to TEXT, allowing for more flexible input. Adjusted related SQL queries and Go struct tags to ensure compatibility with JSON serialization. Cleaned up migration logic to handle prefix and community_id fields more robustly.
2026-05-25 11:16:03 +07:00
Denozordec 16b4923bd7 fix(db): change prefix column type to TEXT in prefix_snapshot_row
CI / changes (push) Successful in 8s
CI / openapi (push) Has been skipped
CI / commitlint (push) Has been skipped
CI / web (push) Has been skipped
CI / go (push) Successful in 54s
CI / bird2 (push) Successful in 14s
CI / release (push) Successful in 3m44s
Updated the prefix column in the prefix_snapshot_row table from CIDR to TEXT to accommodate broader input formats. Adjusted related SQL insert statements accordingly.
2026-05-25 11:08:06 +07:00
DenozordecandCursor 1cfd062835 chore(db): drop unused schema and redundant indexes
CI / changes (push) Successful in 8s
CI / commitlint (push) Has been skipped
CI / openapi (push) Has been skipped
CI / web (push) Has been skipped
CI / go (push) Successful in 54s
CI / bird2 (push) Successful in 14s
CI / release (push) Successful in 3m44s
Удалены мёртвые колонки, fetch_log и избыточные индексы.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-25 10:58:57 +07:00
DenozordecandCursor 21233bd578 chore(db): add job_audit brin index
BRIN-индекс по created_at для retention-удалений.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-25 10:58:57 +07:00
DenozordecandCursor 990cc739df refactor(db): normalize asn prefix cache and ttl cleanup
Строки asn_prefix_cache_row; периодический prune через evobgp-ingest.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-25 10:58:57 +07:00
DenozordecandCursor 3500bd4624 refactor(db): normalize module prefix snapshot rows
Строки префиксов в module_prefix_snapshot_row вместо JSONB blobs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-25 10:58:56 +07:00
DenozordecandCursor 374575ec01 refactor(db): mark prefix snapshot contract migration
Маркер миграции contract-фазы H2.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-25 10:58:01 +07:00
DenozordecandCursor f57b430052 feat(db): backfill prefix snapshots and switch read path
Backfill миграция; чтение префиксов через snapshot; запись без дублирования rows.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-25 10:58:01 +07:00
DenozordecandCursor 8a9d60a5a7 feat(db): add prefix snapshot tables (expand)
Таблицы prefix_snapshot и prefix_snapshot_row; колонка prefix_snapshot_id.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-25 10:58:01 +07:00
DenozordecandCursor b963311b43 perf(db): keyset pagination for revision prefixes
Keyset по id/ord вместо OFFSET; anti-join для RevisionDiff.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-25 10:56:46 +07:00
DenozordecandCursor 50bdb8232b refactor(db): split revision preview from meta_json
Preview BIRD-фрагменты в config_revision_preview; meta_json только счётчик префиксов.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-25 10:55:52 +07:00
DenozordecandCursor ee8e24ffc6 perf(db): add revision and module query indexes
Индексы для diff/list префиксов и сортировки модулей; covering index для pagination.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-25 10:55:10 +07:00
DenozordecandCursor 44b94caacf docs(db): add postgres schema diagnostics runbook
Runbook для оценки размеров таблиц, seq scan и EXPLAIN перед/после миграций схемы.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-25 10:55:02 +07:00
DenozordecandCursor cbb4b467ad fix(agentserver): hide upstream errors from clients
CI / changes (push) Successful in 8s
CI / commitlint (push) Has been skipped
CI / openapi (push) Has been skipped
CI / web (push) Has been skipped
CI / go (push) Successful in 58s
CI / bird2 (push) Successful in 14s
CI / release (push) Successful in 3m23s
Generic 502 detail как в httpapi; добавлен docs/production-checklist.md.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-25 10:34:03 +07:00
DenozordecandCursor e65cf0d958 feat(jobs): persist job lifecycle to PostgreSQL job_audit
UpsertQueued/Running/MarkTerminal через SetPersistHooks; исправлен deadlock
fireEnqueued под Registry mutex.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-25 10:33:57 +07:00
DenozordecandCursor 4a57c91e29 perf(pipeline): parallel prefetch and lean revision GET
GetRevisionSummary без preview_fragments; boundedRepoCtx для GetRevision;
parallel CDN prefetch с ctx из ingest.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-25 10:33:53 +07:00
DenozordecandCursor 2289107911 feat(httpclient): add circuit breaker for CDN and RIPEstat
Per-host circuit breaker с retry для CDN fetch и RIPEstat; порог 5 ошибок,
cooldown 30s.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-25 10:15:32 +07:00
DenozordecandCursor 782097420d fix(httpclient): replace DefaultClient with timed clients and retry
Пакет httpclient: timeout 45s, idle pool, DoWithRetry. Scheduler и nodecli
используют retry; pipeline/asnresolve/jobs — httpclient.New вместо DefaultClient.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-25 10:14:53 +07:00
DenozordecandCursor 82382d90f2 fix(pipeline): validate CDN URLs against SSRF
HTTPS-only CDN URLs; блокировка private/loopback/metadata IP и DNS-resolve
на fetch; проверка в httpapi при create/preview/patch CDN sources.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-25 10:14:10 +07:00
DenozordecandCursor 5a16a45922 fix(httpapi): redact agent_secret from speaker list responses
Секрет agent больше не отдаётся viewer/editor в GET/list speakers;
остаётся только при создании спикера.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-25 10:13:28 +07:00
DenozordecandCursor 6a6f6cedbc feat(pipeline): use stale snapshot when upstream fetch fails
При ошибке CDN/ASN/DoH ingest использует последний снимок префиксов
(или просроченный ASN-кэш), если EVOBGP_STALE_ON_UPSTREAM_ERROR не равен 0.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-25 10:13:07 +07:00
Denozordec 9639a03bfe feat(store): add test for clearing dispatch error on successful merge
CI / changes (push) Successful in 9s
CI / commitlint (push) Has been skipped
CI / openapi (push) Has been skipped
CI / web (push) Successful in 39s
CI / go (push) Successful in 58s
CI / bird2 (push) Successful in 16s
CI / release (push) Successful in 4m18s
- Introduced a new test case in speaker_meta_test.go to verify that the LastDispatchError is cleared when a successful dispatch status is merged.
- Updated MergeSpeakerMetaJSON function in speaker_meta.go to clear LastDispatchError if LastDispatchStatus is "ok".
- Enhanced speakerDispatchError function in network-metrics.ts to handle stale dispatch errors after successful agent sync.
2026-05-21 18:10:51 +07:00
DenozordecandCursor 48c10b7436 refactor(web): trigger release for network dashboard layout fixes
CI / changes (push) Successful in 7s
CI / commitlint (push) Has been skipped
CI / openapi (push) Has been skipped
CI / web (push) Has been skipped
CI / go (push) Successful in 40s
CI / bird2 (push) Successful in 16s
CI / release (push) Successful in 3m37s
Follow-up для semantic-release: правки overview/sheet и dispatch-ошибок уже в fb108ec, заголовок с запятой в scope не парсился. Уточнена формулировка verify в releasing.md.

Semver: patch.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-21 17:56:03 +07:00
Denozordec 4db6438245 remove commitlint configuration and update release documentation to enforce single scope in commit messages
CI / openapi (push) Has been cancelled
CI / web (push) Has been cancelled
CI / changes (push) Has been cancelled
CI / go (push) Has been cancelled
CI / bird2 (push) Has been cancelled
CI / commitlint (push) Has been cancelled
CI / release (push) Has been cancelled
2026-05-21 17:54:41 +07:00
Denozordec fb108ec5ab refactor(NetworkOverviewTab, NetworkSpeakerDetailSheet, NetworkSpeakerStatusCard): improve layout and error handling
CI / changes (push) Successful in 9s
CI / commitlint (push) Has been skipped
CI / openapi (push) Has been skipped
CI / web (push) Successful in 39s
CI / go (push) Has been skipped
CI / bird2 (push) Has been skipped
CI / release (push) Successful in 19s
- Refactored the layout of NetworkOverviewTab and NetworkSpeakerDetailSheet for better structure and readability.
- Enhanced error handling in NetworkSpeakerDetailSheet by introducing new error types for dispatch and agent errors.
- Updated NetworkSpeakerStatusCard to improve the display of speaker information and status.
- Adjusted styles in various components to ensure consistent spacing and alignment.
- Modified network-metrics.ts to include new functions for formatting speaker errors, improving user feedback on dispatch issues.
2026-05-21 17:50:27 +07:00
Denozordec a1ada06a76 feat(api): add live status tracking for speakers and BGP sessions
CI / changes (push) Successful in 9s
CI / commitlint (push) Has been skipped
CI / openapi (push) Successful in 24s
CI / web (push) Successful in 29s
CI / go (push) Successful in 43s
CI / bird2 (push) Successful in 15s
CI / release (push) Successful in 3m29s
- Introduced new schemas for `SpeakerLiveStatus`, `BgpSessionLive`, and `LiveSpeakerPoll` in OpenAPI documentation to support live status queries.
- Enhanced the `/v1/speakers` endpoint to include a `live` query parameter, allowing retrieval of real-time speaker and BGP status.
- Updated the HTTP API to collect and return live status data for speakers, improving monitoring capabilities.
- Modified frontend components to display live status information, enhancing user visibility into speaker health and BGP session states.
- Added a new endpoint `/v1/bird/status` for retrieving the local BIRD status, further enriching the network monitoring features.
2026-05-21 17:36:50 +07:00
Denozordec b5ed47902c feat(api): enhance peer session tracking and error handling
CI / changes (push) Successful in 8s
CI / commitlint (push) Has been skipped
CI / openapi (push) Has been skipped
CI / web (push) Successful in 35s
CI / go (push) Successful in 52s
CI / bird2 (push) Successful in 16s
CI / release (push) Successful in 3m58s
- Added `PollError` field to `peerSessionOnSpeaker` and `liveSpeakerPoll` types to capture polling errors for speakers.
- Updated `matchPeerOnSpeakers` function to handle polling errors and adjust session state reporting.
- Modified frontend components to display polling error messages alongside session states, improving user visibility into peer connection statuses.
- Enhanced API response structure to include live speaker polling information, facilitating better monitoring of speaker health.
2026-05-21 15:40:44 +07:00
744 changed files with 66848 additions and 1696 deletions
+119
View File
@@ -0,0 +1,119 @@
---
name: shadcn-react
description: Управление shadcn/ui (React) + ReUI компонентами в EvoBGP — registry, CLI, импорты, матрица выбора. Использовать при любых UI-задачах в apps/web/ или packages/ui/ (новые экраны, компоненты, формы, data-grid, filters и др.).
---
# shadcn/ui (React) + ReUI в EvoBGP
EvoBGP использует **React 19 + shadcn/ui (base-nova) + ReUI** (`style: base-nova`, не Radix). Источники правды: MCP `plugin-shadcn-shadcn` + [ui.shadcn.com/docs](https://ui.shadcn.com/docs/components) + [reui.io/docs](https://reui.io/docs/components/base/).
См. `.cursor/rules/web-shadcn.mdc` (основные правила) и `.cursor/rules/context7-stack.mdc` (Context7 ID стека).
## Порядок UI-задачи (строго)
0. **Codegraph** `codegraph_explore` — найти существующие реализации и shared-обёртки.
1. **MCP `plugin-shadcn-shadcn`**`get_project_registries` (должны быть `@shadcn` и `@reui`).
2. **`search_items_in_registries`** — компонент/block/example:
- shadcn primitives/blocks → omit `registries` или `["@shadcn"]`
- Data Grid, Filters, Stepper, Kanban, Autocomplete и др. → `registries: ["@reui"]`
3. **`get_item_examples_from_registries`** — полный код примера перед JSX.
4. **`get_add_command_for_items`** — точная CLI-команда `pnpm dlx shadcn@latest add ...`.
5. Выполнить add **из `apps/web`** (не из корня монорепо, не из `packages/ui`).
6. **CLI docs (обязательно):**
- `@shadcn/*``cd apps/web && pnpm dlx shadcn@latest docs <component>` — [ui.shadcn.com/docs/components](https://ui.shadcn.com/docs/components)
- `@reui/*` → [ReUI docs](https://reui.io/docs/components/base/<name>) + [llms.txt](https://reui.io/llms.txt)
7. Сверить examples из MCP с API из docs CLI — реализовать только после совпадения.
8. Адаптировать под TanStack Router / Query → `apps/web/src/`.
9. **`get_audit_checklist`** — перед merge PR.
## Размещение и импорты
| Слой | Путь | Импорт |
|------|------|--------|
| shadcn primitives | `packages/ui/src/components/` | `@evobgp/ui/components/*` |
| ReUI enterprise | `apps/web/src/components/reui/` | `@/components/reui/*` |
| Проектные обёртки | `apps/web/src/components/` | `@/components/<name>` |
```bash
cd apps/web
pnpm dlx shadcn@latest add button # @shadcn primitive → packages/ui/src/components/
pnpm dlx shadcn@latest add @reui/data-grid # ReUI enterprise → apps/web/src/components/reui/
```
## Матрица выбора shadcn vs ReUI
| Задача | Registry | Импорт |
|--------|----------|--------|
| Button, Card, Sheet, Field, Sidebar | `@shadcn` | `@evobgp/ui/components/*` |
| Blocks (sidebar-07, dashboard-01) | `@shadcn` | blocks → `apps/web/src/components/` |
| Data Grid (sort, pagination, virtual) | `@reui` | `@/components/reui/data-grid/*` → обёртка `DataGridCard` |
| Мультифильтры | `@reui` | `@/components/reui/filters` |
| Number field со stepper | `@reui` | `@/components/reui/number-field` |
| Autocomplete | `@reui` | `@/components/reui/autocomplete``AutoCompleteInput` |
| Date selector / range | `@reui` | `@/components/reui/date-selector` |
| Semantic badge (success/info/warning) | `@reui` | `@/components/reui/badge` или `StatusBadge` |
**Простые списки** — shadcn `Table`. **Сложные data-списки** — ReUI data-grid (через `DataGridCard`), не shadcn Data Table.
## Уже установленные shared-обёртки
В `apps/web/src/components/`:
- `PageHeader`, `PageShell` — заголовки и обёртки страниц
- `QueryState` — обёртка loading/error/empty для TanStack Query
- `EmptyState` — пустые списки
- `ConfirmDialog` — подтверждения (не `window.confirm`)
- `LoadingButton` — кнопка с loading-состоянием
- `StatusBadge` — статусные бейджи
- `SectionCards` — сетка KPI-карточек
- `Skeletons` (`TableSkeleton`, `SectionCardsSkeleton`) — скелетоны
- `TruncatedText` — текст с тултипом
- `ModeToggle` — переключатель темы
Перед созданием новой обёртки — проверить существующие через Codegraph.
## Уже установленные ReUI-компоненты
В `apps/web/src/components/reui/`:
- `autocomplete`, `badge`, `data-grid/*`, `date-selector`, `filters`, `number-field`
Перед добавлением дубликата — проверить Codegraph и существующие обёртки.
## Зависимости (только `apps/web`, не `packages/ui`)
| npm-пакет | ReUI-компоненты |
|-----------|-----------------|
| `@tanstack/react-table` | data-grid |
| `@tanstack/react-virtual` | data-grid (virtual) |
| `@dnd-kit/core`, `@dnd-kit/sortable`, `@dnd-kit/modifiers`, `@dnd-kit/utilities` | data-grid dnd, sortable, kanban |
| `date-fns`, `react-day-picker` | date-selector |
После `shadcn add @reui/...` — проверить, что CLI добавил недостающие deps в `apps/web/package.json`.
## Semantic tokens (Styling)
ReUI расширяет тему shadcn токенами `--success`, `--info`, `--warning`, `--destructive-foreground`, `--invert` — уже в `packages/ui/src/styles/globals.css`.
- Badge/Alert: `variant="success"` / `"info"` / `"warning"` — не `bg-emerald-*`
- Базовая тема: `pnpm dlx shadcn@latest apply b2fA --only theme`
- ReUI-токены: по [Styling guide](https://reui.io/docs/styling); не править `globals.css` вручную без сверки с docs
## Запрещено
- Писать UI по памяти, не проверив MCP
- Копипаст с ui.shadcn.com без examples/add из MCP
- Самописные примитивы, если есть item в registry
- Пропускать MCP «потому что компонент простой»
- Класть ReUI в `packages/ui` или импортировать как `@evobgp/ui`
- Radix-варианты (`/docs/components/radix/...`) — только Base UI
- Raw Tailwind-цвета вместо ReUI semantic `variant`
- Использовать Tabler/Bootstrap/Material UI
## Чеклист перед завершением UI-задачи
- [ ] MCP search (с правильным registry) + examples
- [ ] `shadcn add <name>` (или `@reui/<name>`) из `apps/web`
- [ ] Импорты: `@evobgp/ui/components/*` для shadcn, `@/components/reui/*` для ReUI
- [ ] Зависимости в `apps/web/package.json`
- [ ] `pnpm --filter @evobgp/web run typecheck` — exit 0
- [ ] `pnpm --filter @evobgp/web run lint` — exit 0
- [ ] `pnpm --filter @evobgp/web run build` — exit 0
+14
View File
@@ -0,0 +1,14 @@
{
"permissions": {
"allow": [
"mcp__codegraph__codegraph_explore",
"mcp__codegraph__codegraph_search",
"mcp__codegraph__codegraph_node",
"mcp__codegraph__codegraph_callers",
"mcp__codegraph__codegraph_callees",
"mcp__codegraph__codegraph_impact",
"mcp__codegraph__codegraph_files",
"mcp__codegraph__codegraph_status"
]
}
}
+16
View File
@@ -0,0 +1,16 @@
# CodeGraph data files
# These are local to each machine and should not be committed
# Database
*.db
*.db-wal
*.db-shm
# Cache
cache/
# Logs
*.log
# Hook markers
.dirty
+6
View File
@@ -0,0 +1,6 @@
{
"pid": 39884,
"version": "0.9.9",
"socketPath": "\\\\.\\pipe\\codegraph-97b92efdcc5351da",
"startedAt": 1783489774882
}
-3
View File
@@ -1,3 +0,0 @@
{
"extends": ["@commitlint/config-conventional"]
}
+124
View File
@@ -0,0 +1,124 @@
# ARCHIVE Command - Task Archiving
This command creates comprehensive archive documentation and updates the Memory Bank for future reference.
## Memory Bank Integration
Reads from:
- `memory-bank/tasks.md` - Complete task details and checklists
- `memory-bank/reflection/reflection-[task_id].md` - Reflection document
- `memory-bank/progress.md` - Implementation status
- `memory-bank/creative/creative-*.md` - Creative phase documents (Level 3-4)
Creates:
- `memory-bank/archive/archive-[task_id].md` - Archive document
Updates:
- `memory-bank/tasks.md` - Mark task as COMPLETE
- `memory-bank/progress.md` - Add archive reference
- `memory-bank/activeContext.md` - Reset for next task
## Progressive Rule Loading
### Step 1: Load Core Rules
```
Load: .cursor/rules/isolation_rules/main.mdc
Load: .cursor/rules/isolation_rules/Core/memory-bank-paths.mdc
```
### Step 2: Load ARCHIVE Mode Map
```
Load: .cursor/rules/isolation_rules/visual-maps/archive-mode-map.mdc
```
### Step 3: Load Complexity-Specific Archive Rules
Based on complexity level from `memory-bank/tasks.md`:
**Level 1:**
```
Load: .cursor/rules/isolation_rules/Level1/quick-documentation.mdc
```
**Level 2:**
```
Load: .cursor/rules/isolation_rules/Level2/archive-basic.mdc
```
**Level 3:**
```
Load: .cursor/rules/isolation_rules/Level3/archive-intermediate.mdc
```
**Level 4:**
```
Load: .cursor/rules/isolation_rules/Level4/archive-comprehensive.mdc
```
## Workflow
1. **Verify Reflection Complete**
- Check that `memory-bank/reflection/reflection-[task_id].md` exists
- Verify reflection is complete
- If not complete, return to `/reflect` command
2. **Create Archive Document**
**Level 1:**
- Create quick summary
- Update `memory-bank/tasks.md` marking task complete
**Level 2:**
- Create basic archive document
- Document changes made
- Update `memory-bank/tasks.md` and `memory-bank/progress.md`
**Level 3-4:**
- Create comprehensive archive document
- Include: Metadata, Summary, Requirements, Implementation details, Testing, Lessons Learned, References
- Archive creative phase documents
- Document code changes
- Document testing approach
- Summarize lessons learned
- Update all Memory Bank files
3. **Archive Document Structure**
```
# TASK ARCHIVE: [Task Name]
## METADATA
- Task ID, dates, complexity level
## SUMMARY
Brief overview of the task
## REQUIREMENTS
What the task needed to accomplish
## IMPLEMENTATION
How the task was implemented
## TESTING
How the solution was verified
## LESSONS LEARNED
Key takeaways from the task
## REFERENCES
Links to related documents (reflection, creative phases, etc.)
```
4. **Update Memory Bank**
- Create `memory-bank/archive/archive-[task_id].md`
- Mark task as COMPLETE in `memory-bank/tasks.md`
- Update `memory-bank/progress.md` with archive reference
- Reset `memory-bank/activeContext.md` for next task
- Clear completed task details from `memory-bank/tasks.md` (keep structure)
## Usage
Type `/archive` to archive the completed task after reflection is done.
## Next Steps
After archiving complete, use `/van` command to start the next task.
+117
View File
@@ -0,0 +1,117 @@
# BUILD Command - Code Implementation
This command implements the planned changes following the implementation plan and creative phase decisions. It enforces a test-driven approach where tests are written for all success criteria and must pass before completing each phase.
## Memory Bank Integration
Reads from:
- `memory-bank/tasks.md` - Implementation plan and checklists
- `memory-bank/creative/creative-*.md` - Design decisions (Level 3-4)
- `memory-bank/activeContext.md` - Current project context
Updates:
- `memory-bank/tasks.md` - Implementation progress, test results, and status
- `memory-bank/progress.md` - Build status, test outcomes, and observations
## Progressive Rule Loading
### Step 1: Load Core Rules
```
Load: .cursor/rules/isolation_rules/main.mdc
Load: .cursor/rules/isolation_rules/Core/memory-bank-paths.mdc
Load: .cursor/rules/isolation_rules/Core/command-execution.mdc
```
### Step 2: Load BUILD Mode Map
```
Load: .cursor/rules/isolation_rules/visual-maps/build-mode-map.mdc
```
### Step 3: Load Complexity-Specific Implementation Rules
Based on complexity level from `memory-bank/tasks.md`:
**Level 1:**
```
Load: .cursor/rules/isolation_rules/Level1/workflow-level1.mdc
Load: .cursor/rules/isolation_rules/Level1/optimized-workflow-level1.mdc
```
**Level 2:**
```
Load: .cursor/rules/isolation_rules/Level2/workflow-level2.mdc
```
**Level 3-4:**
```
Load: .cursor/rules/isolation_rules/Level3/implementation-intermediate.mdc
Load: .cursor/rules/isolation_rules/Level4/phased-implementation.mdc
```
## Workflow
1. **Verify Prerequisites**
- Check `memory-bank/tasks.md` for planning completion
- For Level 3-4: Verify creative phase documents exist
- Review implementation plan
2. **Determine Complexity Level**
- Read complexity level from `memory-bank/tasks.md`
- Load appropriate workflow rules
3. **Execute Implementation**
**Level 1 (Quick Bug Fix):**
- Review bug report
- Examine relevant code
- Implement targeted fix
- Write test(s) validating the fix
- Run tests and ensure they pass
- Update `memory-bank/tasks.md`
**Level 2 (Simple Enhancement):**
- Review build plan
- Examine relevant code areas
- Implement changes sequentially
- Write tests for each success criterion
- Run all tests and ensure they pass
- Update `memory-bank/tasks.md`
**Level 3-4 (Feature/System):**
- Review plan and creative decisions
- Create directory structure
- Build in planned phases
- **For each phase:**
- Write tests for all phase success criteria
- Run tests and ensure they pass
- Do NOT proceed to next phase until all tests pass
- Integration testing
- Document implementation
- Update `memory-bank/tasks.md` and `memory-bank/progress.md`
4. **Test-Driven Phase Completion**
- Extract success criteria from current phase in `memory-bank/tasks.md`
- Write test cases covering each success criterion
- Execute all tests
- **Gate:** All tests MUST pass before phase completion
- Document test results in `memory-bank/tasks.md`
- If tests fail: fix implementation, re-run tests, repeat until all pass
5. **Command Execution**
- Document all commands executed
- Document results and observations
- Follow platform-specific command guidelines
6. **Verification**
- Verify all build steps completed
- Verify all success criteria tests pass
- Verify changes meet requirements
- Update `memory-bank/tasks.md` with completion status
## Usage
Type `/build` to start implementation based on the plan in `memory-bank/tasks.md`.
## Next Steps
After implementation complete, proceed to `/reflect` command for task review.
+91
View File
@@ -0,0 +1,91 @@
# CREATIVE Command - Design Decisions
This command performs structured design exploration for components flagged during planning.
## Memory Bank Integration
Reads from:
- `memory-bank/tasks.md` - Components requiring creative phases
- `memory-bank/activeContext.md` - Current project context
Creates:
- `memory-bank/creative/creative-[feature_name].md` - Design decision documents
Updates:
- `memory-bank/tasks.md` - Records design decisions
## Progressive Rule Loading
### Step 1: Load Core Rules
```
Load: .cursor/rules/isolation_rules/main.mdc
Load: .cursor/rules/isolation_rules/Core/memory-bank-paths.mdc
```
### Step 2: Load CREATIVE Mode Map
```
Load: .cursor/rules/isolation_rules/visual-maps/creative-mode-map.mdc
```
### Step 3: Load Creative Phase Enforcement
```
Load: .cursor/rules/isolation_rules/Core/creative-phase-enforcement.mdc
Load: .cursor/rules/isolation_rules/Core/creative-phase-metrics.mdc
```
### Step 4: Load Specialized Creative Rules (Lazy Loaded)
Load only when specific creative phase type is needed:
**For Architecture Design:**
```
Load: .cursor/rules/isolation_rules/Phases/CreativePhase/creative-phase-architecture.mdc
```
**For UI/UX Design:**
```
Load: .cursor/rules/isolation_rules/Phases/CreativePhase/creative-phase-uiux.mdc
```
**For Algorithm Design:**
```
Load: .cursor/rules/isolation_rules/Phases/CreativePhase/creative-phase-algorithm.mdc
```
## Workflow
1. **Verify Planning Complete**
- Check `memory-bank/tasks.md` for planning completion
- Verify creative phases are identified
- If not complete, return to `/plan` command
2. **Identify Creative Phases**
- Read components flagged for creative work from `memory-bank/tasks.md`
- Prioritize components for design exploration
3. **Execute Creative Phase**
For each component:
- **🎨🎨🎨 ENTERING CREATIVE PHASE: [TYPE]**
- Define requirements and constraints
- Generate 2-4 design options
- Analyze pros/cons of each option
- Select and justify recommended approach
- Document implementation guidelines
- Verify solution meets requirements
- **🎨🎨🎨 EXITING CREATIVE PHASE**
4. **Document Decisions**
- Create `memory-bank/creative/creative-[feature_name].md`
- Update `memory-bank/tasks.md` with design decisions
5. **Verify Completion**
- Ensure all flagged components have completed creative phases
- Mark creative phase as complete in `memory-bank/tasks.md`
## Usage
Type `/creative` to start creative design work for components flagged in the plan.
## Next Steps
After all creative phases complete, proceed to `/build` command for implementation.
+84
View File
@@ -0,0 +1,84 @@
# PLAN Command - Task Planning
This command creates detailed implementation plans based on complexity level determined in VAN mode.
## Memory Bank Integration
Reads from:
- `memory-bank/tasks.md` - Task requirements and complexity level
- `memory-bank/activeContext.md` - Current project context
- `memory-bank/projectbrief.md` - Project foundation (if exists)
Updates:
- `memory-bank/tasks.md` - Adds detailed implementation plan
## Progressive Rule Loading
### Step 1: Load Core Rules
```
Load: .cursor/rules/isolation_rules/main.mdc
Load: .cursor/rules/isolation_rules/Core/memory-bank-paths.mdc
```
### Step 2: Load PLAN Mode Map
```
Load: .cursor/rules/isolation_rules/visual-maps/plan-mode-map.mdc
```
### Step 3: Load Complexity-Specific Planning Rules
Based on complexity level from `memory-bank/tasks.md`:
**Level 2:**
```
Load: .cursor/rules/isolation_rules/Level2/task-tracking-basic.mdc
Load: .cursor/rules/isolation_rules/Level2/workflow-level2.mdc
```
**Level 3:**
```
Load: .cursor/rules/isolation_rules/Level3/task-tracking-intermediate.mdc
Load: .cursor/rules/isolation_rules/Level3/planning-comprehensive.mdc
Load: .cursor/rules/isolation_rules/Level3/workflow-level3.mdc
```
**Level 4:**
```
Load: .cursor/rules/isolation_rules/Level4/task-tracking-advanced.mdc
Load: .cursor/rules/isolation_rules/Level4/architectural-planning.mdc
Load: .cursor/rules/isolation_rules/Level4/workflow-level4.mdc
```
## Workflow
1. **Read Task Context**
- Read `memory-bank/tasks.md` to get complexity level
- Read `memory-bank/activeContext.md` for current context
- Review codebase structure
2. **Create Implementation Plan**
- **Level 2:** Document planned changes, files to modify, implementation steps
- **Level 3:** Create comprehensive plan with components, dependencies, challenges
- **Level 4:** Create phased implementation plan with architectural considerations
3. **Technology Validation** (Level 2-4)
- Document technology stack selection
- Create proof of concept if needed
- Verify dependencies and build configuration
4. **Identify Creative Phases**
- Flag components requiring design decisions
- Document which components need creative exploration
5. **Update Memory Bank**
- Update `memory-bank/tasks.md` with complete plan
- Mark planning phase as complete
## Usage
Type `/plan` to start planning based on the task in `memory-bank/tasks.md`.
## Next Steps
- **If creative phases identified:** Use `/creative` command
- **If no creative phases:** Proceed to `/build` command
+101
View File
@@ -0,0 +1,101 @@
# REFLECT Command - Task Reflection
This command facilitates structured reflection on completed implementation, documenting lessons learned and process improvements.
## Memory Bank Integration
Reads from:
- `memory-bank/tasks.md` - Completed implementation details
- `memory-bank/progress.md` - Implementation status and observations
- `memory-bank/creative/creative-*.md` - Design decisions (Level 3-4)
Creates:
- `memory-bank/reflection/reflection-[task_id].md` - Reflection document
Updates:
- `memory-bank/tasks.md` - Reflection status
## Progressive Rule Loading
### Step 1: Load Core Rules
```
Load: .cursor/rules/isolation_rules/main.mdc
Load: .cursor/rules/isolation_rules/Core/memory-bank-paths.mdc
```
### Step 2: Load REFLECT Mode Map
```
Load: .cursor/rules/isolation_rules/visual-maps/reflect-mode-map.mdc
```
### Step 3: Load Complexity-Specific Reflection Rules
Based on complexity level from `memory-bank/tasks.md`:
**Level 1:**
```
Load: .cursor/rules/isolation_rules/Level1/quick-documentation.mdc
```
**Level 2:**
```
Load: .cursor/rules/isolation_rules/Level2/reflection-basic.mdc
```
**Level 3:**
```
Load: .cursor/rules/isolation_rules/Level3/reflection-intermediate.mdc
```
**Level 4:**
```
Load: .cursor/rules/isolation_rules/Level4/reflection-comprehensive.mdc
```
## Workflow
1. **Verify Implementation Complete**
- Check `memory-bank/tasks.md` for implementation completion
- If not complete, return to `/build` command
2. **Review Implementation**
- Compare implementation against original plan
- Review creative phase decisions (Level 3-4)
- Review code changes and testing
3. **Document Reflection**
**Level 1:**
- Quick review of bug fix
- Document solution
**Level 2:**
- Review enhancement
- Document what went well
- Document challenges
- Document lessons learned
**Level 3-4:**
- Comprehensive review of implementation
- Compare against original plan
- Document what went well
- Document challenges encountered
- Document lessons learned
- Document process improvements
- Document technical improvements
4. **Create Reflection Document**
- Create `memory-bank/reflection/reflection-[task_id].md`
- Structure: Summary, What Went Well, Challenges, Lessons Learned, Process Improvements, Technical Improvements, Next Steps
5. **Update Memory Bank**
- Update `memory-bank/tasks.md` with reflection status
- Mark reflection phase as complete
## Usage
Type `/reflect` to start reflection on the completed task.
## Next Steps
After reflection complete, proceed to `/archive` command to finalize task documentation.
+73
View File
@@ -0,0 +1,73 @@
# VAN Command - Initialization & Entry Point
This command initializes the Memory Bank system, performs platform detection, determines task complexity, and routes to appropriate workflows.
## Memory Bank Integration
**CRITICAL:** All Memory Bank files are located in `memory-bank/` directory:
- `memory-bank/tasks.md` - Source of truth for task tracking
- `memory-bank/activeContext.md` - Current focus
- `memory-bank/progress.md` - Implementation status
- `memory-bank/projectbrief.md` - Project foundation
## Progressive Rule Loading
This command loads rules progressively to optimize context usage:
### Step 1: Load Core Rules (Always Required)
```
Load: .cursor/rules/isolation_rules/main.mdc
Load: .cursor/rules/isolation_rules/Core/memory-bank-paths.mdc
Load: .cursor/rules/isolation_rules/Core/platform-awareness.mdc
Load: .cursor/rules/isolation_rules/Core/file-verification.mdc
```
### Step 2: Load VAN Mode Map
```
Load: .cursor/rules/isolation_rules/visual-maps/van_mode_split/van-mode-map.mdc
```
### Step 3: Load Complexity-Specific Rules (Based on Task Analysis)
After determining complexity level, load:
- **Level 1:** `.cursor/rules/isolation_rules/Level1/workflow-level1.mdc`
- **Level 2-4:** Load plan mode rules (transition to PLAN command)
## Workflow
1. **Platform Detection**
- Detect operating system
- Adapt commands for platform
- Set path separators
2. **Memory Bank Verification**
- Check if `memory-bank/` directory exists
- If not, create Memory Bank structure
- Verify essential files exist
3. **Task Analysis**
- Read `memory-bank/tasks.md` if exists
- Analyze task requirements
- Determine complexity level (1-4)
4. **Route Based on Complexity**
- **Level 1:** Continue in VAN mode, proceed to implementation
- **Level 2-4:** Transition to `/plan` command
5. **Update Memory Bank**
- Update `memory-bank/tasks.md` with complexity determination
- Update `memory-bank/activeContext.md` with current focus
## Usage
Type `/van` followed by your task description or initialization request.
Example:
```
/van Initialize project for adding user authentication feature
```
## Next Steps
- **Level 1 tasks:** Proceed directly to `/build` command
- **Level 2-4 tasks:** Use `/plan` command for detailed planning
+14
View File
@@ -0,0 +1,14 @@
{
"mcpServers": {
"codegraph": {
"type": "stdio",
"command": "codegraph",
"args": [
"serve",
"--mcp",
"--path",
"C:\\Users\\shats\\Dev\\EvoBGP"
]
}
}
}
@@ -0,0 +1,345 @@
---
name: EvoBGP → React+shadcn/ui+ReUI
overview: "Big-bang миграция web UI EvoBGP с SvelteKit+Svelte5 на React 19 + Vite + TanStack Router/Query + shadcn/ui (Base UI, base-nova) + ReUI registry, идентично эталону vps-tracker. Структура — pnpm workspaces monorepo (apps/web + packages/ui как @evobgp/ui). Скоуп: только фронтенд; Go-бэкенд, OpenAPI, nginx, compose и bake-конфиги сохраняются с минимальной правкой путей сборки. Старый web/ заменяется полностью; перенос доменных экранов идёт по одному роуту через MCP-shadcn с проверкой по docs."
todos:
- id: "1"
content: "Этап 0: Установить MCP в workspace EvoBGP (plugin-shadcn-shadcn с @reui, plugin-context7, cursor-ide-browser) — скопировать .cursor/mcp.json из vps-tracker"
status: pending
- id: "2"
content: "Этап 1: Архивировать web/ → web-legacy-svelte/, зафиксировать инвентарь 13 роутов и компонентов"
status: pending
- id: "3"
content: "Этап 2: Создать pnpm workspaces монорепо — pnpm-workspace.yaml, корневой package.json, tsconfig.base.json, .npmrc, .nvmrc"
status: pending
- id: "4"
content: "Этап 3: Создать packages/ui (@evobgp/ui) — package.json, components.json (base-nova + @reui), src/styles/globals.css (копия vps-tracker), lib/utils.ts, hooks/use-mobile.ts"
status: pending
- id: "5"
content: "Этап 4: Добавить shadcn-примитивы в packages/ui через MCP+CLI (33 компонента идентично vps-tracker)"
status: pending
- id: "6"
content: "Этап 5: Создать apps/web каркас — package.json (@evobgp/web), components.json, tsconfig, vite.config.ts (TanStackRouterPlugin+react+tailwindcss, alias @ и @evobgp/ui/*, proxy /v1)"
status: pending
- id: "7"
content: "Этап 6: React-инициализация — main.tsx (StrictMode→ThemeProvider→QC→Router+Toaster), lib/queryClient.ts, lib/router.ts (Register augmentation), routes/__root.tsx, theme-provider.tsx, index.html"
status: pending
- id: "8"
content: "Этап 7: Перенос app-shell (sidebar-07) и shared-обёрток (PageShell, PageHeader, EmptyState, QueryState, ConfirmDialog, StatusBadge, DataGridCard, FormSheet, FormField, LoadingButton, skeletons) из vps-tracker с адаптацией брендинга"
status: pending
- id: "9"
content: "Этап 8: Перенос API-клиента и типов из legacy — api-client.ts (Bearer localStorage, Idempotency-Key, RFC 9457 Problem, waitForJob, apiPageAll), types/api.ts, queries/* по доменам"
status: pending
- id: "10"
content: "Этап 9: Добавить ReUI enterprise через MCP+CLI — @reui/data-grid, filters, autocomplete, date-selector, number-field, color-picker, badge"
status: pending
- id: "11"
content: "Этап 10.1: Роуты _auth layout + settings (token+theme) + access (session+api-keys) — простые экраны"
status: pending
- id: "12"
content: "Этап 10.2: Роуты index (dashboard KPI+recent) + modules/index (DataGridCard) + modules/$moduleId (детали с cards)"
status: pending
- id: "13"
content: "Этап 10.3: Роуты network (peers/speakers/BIRD tabs, live refetchInterval) + operations (jobs/revisions/diff, waitForJob) + schedule"
status: pending
- id: "14"
content: "Этап 10.4: Роуты directories (communities/DoH) + monitoring (bird/postgres/runtime) + tenant-settings + редиректы peers→network, revisions→operations"
status: pending
- id: "15"
content: "Этап 11: Обновить deploy/docker/evobgp-web/Dockerfile (pnpm+corepack, COPY apps/web + packages, dist вместо build); nginx.conf НЕ трогать; проверить bake"
status: pending
- id: "16"
content: "Этап 12: Обновить .gitea/workflows/ci.yaml web job (pnpm, tsc --noEmit, eslint, build) + path-filter apps/web/** + packages/ui/**"
status: pending
- id: "17"
content: "Этап 13: Cursor rules — удалить web-shadcn.mdc; скопировать shadcn-mcp/reui-mcp/frontend-* из vps-tracker; обновить engineering.mdc (DEP-04, TEST-04, DOC-SYNC) и context7-stack.mdc; создать .agents/skills/{shadcn,reui}"
status: pending
- id: "18"
content: "Этап 14: Финал — pnpm build без ошибок, MCP get_audit_checklist, cursor-ide-browser smoke 13 роутов, удалить web-legacy-svelte/, коммит feat(frontend)"
status: pending
isProject: false
---
# Plan: Миграция EvoBGP web UI на React + shadcn/ui + ReUI
## Контекст
**Цель:** Перевести `web/` EvoBGP с SvelteKit 2.50 + Svelte 5.54 + shadcn-svelte на стек идентичный `vps-tracker/apps/web`:
- **Стек:** React 19 + Vite 7 + TanStack Router/Query v5 + shadcn/ui (Base UI, `style: base-nova`) + ReUI registry `@reui` + Tailwind v4 monorepo + lucide-react + react-hook-form + Zod + recharts + sonner + next-themes
- **Структура:** pnpm workspaces monorepo — `apps/web` (SPA) + `packages/ui` (`@evobgp/ui` barrel)
- **Скоуп:** только frontend. Go-бэкенд (`internal/*`), OpenAPI (`docs/openapi.yaml`), compose/bake/nginx — не трогаются (минимальная правка только путей сборки в Dockerfile)
- **Стратегия:** big-bang. Старый `web/` архивируется в `web-legacy-svelte/` и удаляется в финале. Рабочий UI создаётся с нуля
- **Эталон:** `c:\Users\shats\Dev\vps-tracker\apps\web\` + `c:\Users\shats\Dev\vps-tracker\packages\ui\`
**Инвентарь существующего EvoBGP web** (из исследования):
- 13 роутов SvelteKit: `/`, `/modules`, `/modules/[id]`, `/network` (+редирект `/peers`), `/operations` (+редирект `/revisions`), `/monitoring`, `/schedule`, `/directories`, `/access`, `/tenant-settings`, `/settings`
- ~130 доменных `.svelte`-компонентов в `web/src/lib/components/{modules,network,operations,monitoring,tenant-settings,access,...}`
- API-клиент `web/src/lib/api/client.ts` + типы `web/src/lib/api/types.ts` (4301 строка OpenAPI, 76 эндпоинтов)
- Токен в localStorage (`evobgp_api_token`), Bearer, RFC 9457 errors, cursor-пагинация, Idempotency-Key, polling jobs
- Тема `neutral` в `web/src/routes/layout.css` с semantic tokens `--success/--warning/--info`
- nginx.conf — SPA fallback `try_files $uri $uri/ /index.html` (нейтрален к фреймворку, не меняется)
- Сейчас npm (НЕ pnpm), корневого `pnpm-workspace.yaml` нет
**Архитектура после миграции**:
```mermaid
flowchart TB
subgraph EvoBGP[EvoBGP repo root]
PWS[pnpm-workspace.yaml]
RP[package.json + pnpm-lock.yaml]
TSB[tsconfig.base.json]
NVM[.nvmrc Node 22]
MCP[.cursor/mcp.json]
subgraph Apps
AW[apps/web — React SPA]
end
subgraph Packages
UI[packages/ui — @evobgp/ui]
end
Deploy[deploy/ nginx+compose+bake]
GoAPI[internal/httpapi — Go API]
end
AW -->|imports| UI
AW -->|/v1 proxy dev| GoAPI
Deploy -->|Dockerfile build| AW
Deploy -->|nginx /v1 proxy| GoAPI
UI -->|globals.css @source| AW
```
---
## Этапы (последовательность, safe-by-design)
### Этап 0 — MCP environment (предварительный)
Установить MCP-серверы в workspace EvoBGP. Источник: `c:\Users\shats\.cursor\projects\c-Users-shats-Dev-vps-tracker\mcps\` — там работают:
- `plugin-shadcn-shadcn` (serverName `shadcn`) — даёт инструменты `get_project_registries`, `search_items_in_registries` (с поддержкой `registries: ["@reui"]`), `get_item_examples_from_registries`, `get_add_command_for_items`, `view_items_in_registries`, `list_items_in_registries`, `get_audit_checklist`
- `plugin-context7-plugin-context7` — docs-lookup React/TanStack/Recharts
- `cursor-ide-browser` — визуальная проверка UI
Скопировать `.cursor/mcp.json` из vps-tracker → `c:\Users\shats\Dev\EvoBGP\.cursor\mcp.json`. Enable серверы в Cursor Settings. ReUI MCP и codegraph — **не существуют как отдельные MCP** (исследовано); ReUI доступен **через** `plugin-shadcn-shadcn` с `registries: ["@reui"]`.
### Этап 1 — Подготовка
1. **Зафиксировать инвентарь**: список 13 роутов + ~130 компонентов + API-клиент + типы. Не удалять пока ничего.
2. **Архивировать старый стек**: `web/``web-legacy-svelte/`. Оставить до финала как референс при переносе экранов.
### Этап 2 — Монорепо-каркас
Корневые файлы:
- `pnpm-workspace.yaml`: `packages: ['apps/*', 'packages/*']`
- Корневой `package.json`: `{"private": true, "scripts": {"dev": "pnpm --filter @evobgp/web dev", "build": "pnpm --filter @evobgp/web build", "lint": "pnpm -r lint"}}`. Существующий корневой `package.json` (semantic-release/commitlint) — слить в один или оставить как `package.release.json` (решить по ходу).
- `tsconfig.base.json`: `strict: true`, `target: ES2022`, `moduleResolution: bundler`, `jsx: react-jsx`, `paths: {"@/*": ["./apps/web/src/*"], "@evobgp/ui/components/*": ["./packages/ui/src/components/*"], "@evobgp/ui/hooks/*": ["./packages/ui/src/hooks/*"], "@evobgp/ui/lib/utils": ["./packages/ui/src/lib/utils.ts"]}`
- `.npmrc`: `engine-strict=true`
- `.nvmrc`: `22` (приводим к единой версии с Dockerfile)
- `.gitignore`: добавить `node_modules/`, `dist/`, `routeTree.gen.ts` (опц.)
### Этап 3 — `packages/ui` (@evobgp/ui)
Структура полностью повторяет `c:\Users\shats\Dev\vps-tracker\packages\ui\`:
- `packages/ui/package.json`:
- `name: "@evobgp/ui"`
- `exports`: `./components/*`, `./hooks/*`, `./lib/utils`, `./globals.css`
- `dependencies`: `@base-ui/react`, `class-variance-authority`, `clsx`, `cmdk`, `date-fns`, `lucide-react`, `next-themes`, `react-day-picker`, `recharts`, `sonner`, `tailwind-merge`
- `peerDependencies`: `react`, `react-dom` (19)
- `packages/ui/components.json` (точная копия vps-tracker с заменой `@cfdm``@evobgp`):
```json
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "base-nova",
"rsc": false,
"tsx": true,
"tailwind": {"config": "", "css": "src/styles/globals.css", "baseColor": "neutral", "cssVariables": true},
"iconLibrary": "lucide",
"registries": {"@reui": "https://reui.io/r/{style}/{name}.json"},
"aliases": {"components": "@evobgp/ui/components", "utils": "@evobgp/ui/lib/utils", "hooks": "@evobgp/ui/hooks", "lib": "@evobgp/ui/lib", "ui": "@evobgp/ui/components"}
}
```
- `packages/ui/src/styles/globals.css`: **точная копия** `c:\Users\shats\Dev\vps-tracker\packages\ui\src\styles\globals.css` (Tailwind v4 + `tw-animate-css` + `@source "../"` + `@source "../../../apps/web/src"` + `:root`/`.dark` со всеми oklch-токенами + ReUI semantic tokens `--success/--info/--warning/--destructive-foreground/--invert/--focus` + chart-1..5 + sidebar-* + `@theme inline` + `@layer base`)
- `packages/ui/src/lib/utils.ts`: `cn()` через `clsx` + `tailwind-merge`
- `packages/ui/src/hooks/use-mobile.ts`
### Этап 4 — shadcn-примитивы через MCP
Перед каждым `add` — обязательно через MCP:
1. `search_items_in_registries` → `get_item_examples_from_registries` → `get_add_command_for_items`
2. CLI `pnpm dlx shadcn@latest docs <component>` сверка с [ui.shadcn.com/docs/components](https://ui.shadcn.com/docs/components)
Компоненты (идентично набору `vps-tracker/packages/ui/src/components/`):
```
button button-group card input textarea label select checkbox field
separator scroll-area table badge tabs dialog alert-dialog sheet popover
dropdown-menu tooltip breadcrumb sidebar skeleton sonner spinner alert
command kbd calendar slider chart input-group input-otp toggle
```
Команда: `cd apps/web && pnpm dlx shadcn@latest add button card input ...` (CLI пишет в `packages/ui/src/components/` через aliases).
Применение темы: `pnpm dlx shadcn@latest apply b2fA --only theme -y` (обновит `:root`/`.dark` в `globals.css`).
### Этап 5 — `apps/web` каркас
- `apps/web/package.json` (`@evobgp/web`): deps из `vps-tracker/apps/web/package.json` с заменой `@cfdm/*` → `@evobgp/*`:
- `react`, `react-dom` 19
- `@tanstack/react-router`, `@tanstack/react-router-devtools`, `@tanstack/react-query`, `@tanstack/react-query-devtools`, `@tanstack/react-table`, `@tanstack/react-virtual`
- `@hookform/resolvers`, `react-hook-form`, `zod` (v3 для совместимости с RHF-resolvers — как в vps-tracker)
- `class-variance-authority`, `cmdk`, `date-fns`, `lucide-react`, `next-themes`, `react-day-picker`, `recharts`, `sonner`
- `@dnd-kit/core`, `@dnd-kit/modifiers`, `@dnd-kit/sortable`, `@dnd-kit/utilities`
- devDeps: `@tailwindcss/vite`, `@tanstack/router-plugin`, `@types/react`, `@types/react-dom`, `@vitejs/plugin-react`, `happy-dom`, `tailwindcss`, `tw-animate-css`, `typescript`, `vite`, `vitest`
- `apps/web/components.json` (алиасы web-side: `@/components`, `@/hooks`, `@/lib`, `utils: @evobgp/ui/lib/utils`, `ui: @evobgp/ui/components`; registries `@reui`; css `../../packages/ui/src/styles/globals.css`)
- `apps/web/vite.config.ts` (точная копия vps-tracker с заменой `@cfdm` → `@evobgp`): плагины `TanStackRouterPlugin({ target: 'react', autoCodeSplitting: true })` → `react()` → `tailwindcss()`; alias `@`, `@evobgp/ui/*`; server port 5173, proxy `/v1` и `/metrics` → `http://127.0.0.1:8080`
- `apps/web/tsconfig.json` extends `../../tsconfig.base.json`
- `apps/web/index.html` (#root, anti-FOUC тема-скрипт `evobgp-theme`)
### Этап 6 — React-инициализация
Точная копия vps-tracker с заменой путей:
- `apps/web/src/main.tsx`: `StrictMode → ThemeProvider → QueryClientProvider → RouterProvider + <Toaster richColors position="top-right" />`, единственный `import '@evobgp/ui/globals.css'`
- `apps/web/src/lib/queryClient.ts`: `staleTime: 60_000, retry: 1, refetchOnWindowFocus: false`
- `apps/web/src/lib/router.ts`: `createRouter({ routeTree, context, defaultPreload: 'intent', scrollRestoration: true })` + `declare module '@tanstack/react-router'` Register
- `apps/web/src/components/theme-provider.tsx`: next-themes `attribute="class" defaultTheme="system" enableSystem disableTransitionOnChange`
- `apps/web/src/routes/__root.tsx`: `createRootRouteWithContext<{ queryClient }>` + `<AppShell><Outlet /></AppShell>`
### Этап 7 — Перенос app-shell и shared-обёрток
Перенести из `vps-tracker/apps/web/src/components/` с адаптацией брендинга/навигации:
- `layout/app-shell.tsx` (block sidebar-07, `SidebarProvider → Sidebar collapsible="icon" → SidebarHeader/SidebarContent(navGroups)/SidebarFooter + SidebarInset(header sticky h-16 backdrop-blur + SidebarTrigger + Breadcrumb + actions + main)`). `render={<Link to={item.to} />}` — **Base UI render-prop, не Radix asChild**. Навигация подставляется под EvoBGP-экраны.
- `mode-toggle.tsx`, `page-shell.tsx`, `page-header.tsx`, `empty-state.tsx`, `query-state.tsx`, `confirm-dialog.tsx`, `status-badge.tsx`, `section-cards.tsx`, `form-sheet.tsx`, `form-field.tsx`, `loading-button.tsx`, `skeletons.tsx`
- `data-grid-card.tsx` (обёртка над `@reui/data-grid`) — полная копия с типизированным `DataGridCardProps<TData>`
### Этап 8 — API-клиент и типы (перенос из legacy)
- `apps/web/src/lib/api-client.ts`: перенос логики из `web-legacy-svelte/src/lib/api/client.ts`:
- `TOKEN_STORAGE_KEY = 'evobgp_api_token'`
- `mergeHeaders`: Accept JSON + Bearer из localStorage
- `apiFetch`, `apiJSON<T>`, `apiMutate<T>` с auto-Idempotency-Key
- `parseResponse<T>`: 204/205→undefined, ошибки → `ApiError` с RFC 9457 Problem
- `waitForJob(jobId, opts?)`: poll `GET /v1/jobs/{id}` каждые 400ms
- `apiPageAll<T>`: cursor-пагинация (`items`/`next_cursor`/`has_more`)
- `apps/web/src/types/api.ts`: перенос всех типов из `web-legacy-svelte/src/lib/api/types.ts` (`ModuleRow`, `BgpPeer`, `SpeakerRow`, `RevisionRow`, `JobRow`, `AuthSession`, `ApiKey`, `PostgresOverview`, etc.)
- `apps/web/src/queries/` — по доменам: `auth.ts`, `modules.ts`, `network.ts`, `operations.ts`, `monitoring.ts`, `directories.ts`, `access.ts`, `settings.ts` (queryOptions + key factories)
### Этап 9 — ReUI enterprise-компоненты
Через MCP `search_items_in_registries` с `registries: ["@reui"]` → `get_item_examples` → `get_add_command`:
```bash
cd apps/web
pnpm dlx shadcn@latest add @reui/data-grid
pnpm dlx shadcn@latest add @reui/filters
pnpm dlx shadcn@latest add @reui/autocomplete
pnpm dlx shadcn@latest add @reui/date-selector
pnpm dlx shadcn@latest add @reui/number-field
pnpm dlx shadcn@latest add @reui/color-picker
pnpm dlx shadcn@latest add @reui/badge
```
Документация для `@reui/*`: [reui.io/docs/components/base/](https://reui.io/docs/components/base) + [llms.txt](https://reui.io/llms.txt) — **не** ui.shadcn.com для ReUI.
Ложатся в `apps/web/src/components/reui/` (НЕ в packages/ui). Post-add: импорты shadcn-примитивов внутри ReUI → `@evobgp/ui/components/*`. Проверить что `@tanstack/react-table`, `@tanstack/react-virtual`, `@dnd-kit/*`, `date-fns`, `react-day-picker` попали в `apps/web/package.json`.
### Этап 10 — Реализация 13 роутов (поэтапно)
Каждый роут — отдельная подзадача. Порядок от простого к сложному (позволяет рано верифицировать стек):
| # | Файл (TanStack file-based) | Что делает | Источник (legacy) |
|---|---|---|---|
| 1 | `routes/_auth.tsx` + `_auth.tsx` layout | auth guard (токен в localStorage) | `routes/+layout.ts` |
| 2 | `routes/_auth/settings.tsx` | API-токен + тема (свет/тёмн/сист) | `routes/settings/+page.svelte` |
| 3 | `routes/_auth/access.tsx` | `GET /v1/auth/session` + список API-ключей | `routes/access/+page.svelte` |
| 4 | `routes/index.tsx` | dashboard: KPI + recent jobs/revisions + network status | `routes/+page.svelte` |
| 5 | `routes/_auth/modules/index.tsx` | список модулей (DataGridCard) | `routes/modules/+page.svelte` |
| 6 | `routes/_auth/modules/$moduleId.tsx` | детали модуля (cards: AS/Cdn/Domain/IpRange) | `routes/modules/[moduleId]/+page.svelte` |
| 7 | `routes/_auth/network.tsx` | peers + speakers + BIRD settings (tabs) | `routes/network/+page.svelte` |
| 8 | `routes/_auth/operations.tsx` | jobs + revisions + diff (tabs, waitForJob) | `routes/operations/+page.svelte` |
| 9 | `routes/_auth/schedule.tsx` | refresh jobs (tabs all/refresh/failed) | `routes/schedule/+page.svelte` |
| 10 | `routes/_auth/directories.tsx` | BGP communities + DoH profiles (tabs) | `routes/directories/+page.svelte` |
| 11 | `routes/_auth/monitoring.tsx` | bird status + version + postgres + runtime logs | `routes/monitoring/+page.svelte` |
| 12 | `routes/_auth/tenant-settings.tsx` | настройки BIRD/ревизий/runtime (tabs) | `routes/tenant-settings/+page.svelte` |
| 13 | редиректы | `/peers`→`/network`, `/revisions`→`/operations?tab=revisions` | `routes/peers`, `routes/revisions` |
Для каждого роута: MCP-shadcn search+examples → `pnpm dlx shadcn@latest docs <name>` сверка с [ui.shadcn.com/docs/components](https://ui.shadcn.com/docs/components) → ReUI для data-grid/filters → композиция @evobgp/ui + DataGridCard; логика переносится из соответствующего `+page.svelte` (но на TanStack Query вместо инлайн fetch). Live-данные (network, monitoring) — `refetchInterval` вместо кастомного `setInterval`.
### Этап 11 — Инфраструктура деплоя
**Минимальные правки (compose/bake не трогать):**
`deploy/docker/evobgp-web/Dockerfile` (3 стадии → 3 стадии):
- `deps`: установить pnpm (corepack), `COPY pnpm-workspace.yaml package.json apps/web/package.json packages/ui/package.json ./` + `COPY apps/web/ apps/web/` + `COPY packages/ packages/` → `pnpm install --frozen-lockfile`
- `build`: `COPY . .` → `pnpm --filter @evobgp/web build`
- `web`: `COPY --from=web-artifacts /app/apps/web/dist /usr/share/nginx/html` (вместо `/web/build`)
`deploy/docker/evobgp-web/nginx.conf` — **не меняется** (SPA fallback совместим).
`deploy/docker/docker-bake.hcl` — проверить что target `web-build` корректно прокидывает контекст.
### Этап 12 — CI/CD
`.gitea/workflows/ci.yaml`, job `web` (строки 164-181):
- `actions/setup-node@v4` → `node-version: "22"`, `cache: pnpm`, `cache-dependency-path: pnpm-lock.yaml`
- Добавить `pnpm install` (через corepack)
- Заменить `npm run check` → `pnpm --filter @evobgp/web exec tsc --noEmit`
- Заменить `npm run lint` → `pnpm --filter @evobgp/web lint` (eslint)
- Добавить `pnpm --filter @evobgp/web build` (раньше проверялось только в Docker)
Job `changes` — path-filter `web/*` → `apps/web/**` + `packages/ui/**` (расширить globs).
### Этап 13 — Cursor rules + skills
**Удалить** (Svelte-специфика):
- `.cursor/rules/web-shadcn.mdc` (WEB-01..WEB-19 — всё про shadcn-svelte)
**Скопировать из vps-tracker `.cursor/rules/`** (с заменой `@cfdm` → `@evobgp`, `Vps*` → `EvoBgp*`):
- `shadcn-mcp.mdc`, `reui-mcp.mdc`, `shadcn-ui-production.mdc`, `frontend-shadcn.mdc`, `frontend-monorepo.mdc`, `frontend-ui-patterns.mdc`, `vite-tanstack-frontend.mdc`
**Обновить** `engineering.mdc`:
- `DEP-04`: «shadcn-svelte/bits-ui» → «shadcn/ui React (Base UI) + ReUI registry»
- `TEST-04`: `npm run check` → `pnpm --filter @evobgp/web exec tsc --noEmit`; `npm run lint` → eslint
- `DOC-SYNC-06/07`: `shadcn-svelte.com` → `ui.shadcn.com/docs` + `reui.io/docs`
**Обновить** `context7-stack.mdc` Web UI таблица: убрать svelte/sveltekit/bits-ui/formsnap/`@lucide/svelte`; добавить React 19, TanStack Router/Query/Table/Virtual, ReUI llms.txt, `lucide-react`.
**Создать** `c:\Users\shats\Dev\EvoBGP\.agents\skills\` (сейчас не существует):
- `shadcn/SKILL.md` — скопировать из cloudflare-domain-manager
- `reui/SKILL.md` — скопировать из cloudflare-domain-manager, заменить обёртки под EvoBGP (`DataGridCard`, `NetworkFiltersToolbar`)
### Этап 14 — Финальная проверка и очистка
1. `pnpm install && pnpm --filter @evobgp/web build` без ошибок
2. MCP `get_audit_checklist` — пройти по чек-листу
3. `cursor-ide-browser` smoke-тест всех 13 роутов (login через dev-токен, навигация, CRUD, dark/light toggle)
4. Удалить `web-legacy-svelte/`
5. Проверить что compose поднимается (`docker compose --profile reference up`)
6. Коммит на main (gitflow по `.cursor/rules/conventional-commits.mdc`): `feat(frontend): миграция web UI на React + shadcn/ui + ReUI`
---
## Цитаты ключевых файлов эталона
- Конфиги: [apps/web/components.json](c:\Users\shats\Dev\vps-tracker\apps\web\components.json), [packages/ui/components.json](c:\Users\shats\Dev\vps-tracker\packages\ui\components.json)
- Стили: [packages/ui/src/styles/globals.css](c:\Users\shats\Dev\vps-tracker\packages\ui\src\styles\globals.css)
- Инициализация: [apps/web/src/main.tsx](c:\Users\shats\Dev\vps-tracker\apps\web\src\main.tsx), [lib/queryClient.ts](c:\Users\shats\Dev\vps-tracker\apps\web\src\lib\queryClient.ts), [lib/router.ts](c:\Users\shats\Dev\vps-tracker\apps\web\src\lib\router.ts)
- Layout: [components/layout/app-shell.tsx](c:\Users\shats\Dev\vps-tracker\apps\web\src\components\layout\app-shell.tsx)
- Vite: [apps/web/vite.config.ts](c:\Users\shats\Dev\vps-tracker\apps\web\vite.config.ts)
- ReUI обёртка: [components/data-grid-card.tsx](c:\Users\shats\Dev\vps-tracker\apps\web\src\components\data-grid-card.tsx)
- API-клиент legacy: [web/src/lib/api/client.ts](c:\Users\shats\Dev\EvoBGP\web\src\lib\api\client.ts), [web/src/lib/api/types.ts](c:\Users\shats\Dev\EvoBGP\web\src\lib\api\types.ts)
## Документация
- [shadcn/ui Installation](https://ui.shadcn.com/docs/installation)
- [shadcn/ui Components](https://ui.shadcn.com/docs/components)
- [shadcn/ui Monorepo](https://ui.shadcn.com/docs/monorepo)
- [shadcn/ui MCP Server](https://ui.shadcn.com/docs/mcp)
- [ReUI Get Started](https://reui.io/docs/get-started)
- [ReUI Styling](https://reui.io/docs/styling)
- [ReUI MCP](https://reui.io/docs/mcp)
- [ReUI llms.txt](https://reui.io/llms.txt)
## Риски и митигация
| Риск | Митигация |
|---|---|
| Big-bang = длинное окно неработающего UI в dev | Этапы 3-9 делаются параллельно с рабочим `web-legacy-svelte/`; переключение атомарно в финале |
| ReUI на React 19 / Base UI может иметь breaking changes | MCP `get_item_examples` + dry-run `--dry-run` перед add |
| OpenAPI drift (типы в legacy vs контракт) | Типы переносятся как есть (frontend-only scope); Zod-схемы по желанию позже |
| npm → pnpm меняет lock-файлы и CI | Пункт 12 явно покрывает CI; corepack в Dockerfile |
| 13 роутов = большой объём работы | Этап 10 разбит по сложности; можно остановиться после базовых и продолжить инкрементально |
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,408 @@
---
name: Технический аудит EvoBGP
overview: "Полный технический аудит EvoBGP для production-сценария (10+ клиентов, нестабильная сеть). Архитектура — hybrid control plane; сильные стороны: stale fallback, CDN/RIPEstat resilience, Ed25519 bundles. Критичные риски: in-process jobs, DoH без retry, misconfiguration demo-seed, отсутствие HA API."
todos:
- id: quick-ops-checklist
content: Применить production-checklist (SEED_DEMO=0, BUNDLE_SEED_HEX, DB/JOB/CONCURRENCY tuning, TLS)
status: pending
- id: fix-doh-retry
content: Добавить DoWithRetry для DoH в internal/pipeline/refresh.go
status: pending
- id: fix-job-meta-race
content: Исправить чтение j.Meta в worker.go через Snapshot() или locked accessor
status: pending
- id: cdn-preview-resilience
content: Перевести CDN preview на upstreamHTTPDo в routes_crud.go
status: pending
- id: partial-cdn-failure
content: "Partial CDN source failure: skip/degrade вместо fail всего модуля"
status: pending
- id: graceful-shutdown
content: Cancel/drain jobs при SIGTERM в cmd/evobgp-api и evobgp-all
status: pending
- id: ha-job-queue
content: "Roadmap: распределённая очередь jobs (PG claim или NATS) для HA API"
status: pending
isProject: false
---
# Технический аудит EvoBGP
## Executive summary
EvoBGP — **hybrid control plane**: один процесс [`evobgp-all`](cmd/evobgp-all/main.go) (monolith) или **reference Compose** с разделёнными воркерами ([`docs/architecture.md`](docs/architecture.md)). Data plane (BIRD + agent) отделён от control plane (API + PostgreSQL + jobs).
**Сильные стороны для нестабильной сети:**
- Stale snapshot fallback по умолчанию (`EVOBGP_STALE_ON_UPSTREAM_ERROR=1`) — [`internal/pipeline/collect_stale.go`](internal/pipeline/collect_stale.go)
- CDN/RIPEstat: retry (3×) + per-host circuit breaker — [`internal/httpclient/httpclient.go`](internal/httpclient/httpclient.go), [`circuit.go`](internal/httpclient/circuit.go)
- ETag conditional GET, ASN TTL-кэш, parallel collect с cap
- Подписанные бандлы Ed25519, verify перед apply
**Главные риски для 10+ клиентов:**
1. `jobs.Registry`**in-memory, только в процессе API** (ARCH-04)
2. DoH — **без retry/breaker** (критично при блокировках провайдеров)
3. Один failed CDN source **без stale cache валит весь модуль**
4. Production misconfiguration: `Bearer dev`, HTTP API, ephemeral bundle key
5. Data race на `Job.Meta` и alias pointers в `store.Memory`
---
## 1. Архитектура
### Стиль
```mermaid
flowchart TB
subgraph hybrid [Hybrid deployment]
All[evobgp_all monolith]
Split[evobgp_api + workers]
end
subgraph cp [Control plane]
API[HTTP API]
Jobs[jobs.Registry in-process]
PG[(PostgreSQL)]
end
subgraph dp [Data plane per speaker]
Agent[evobgp_agent]
BIRD[BIRD2]
NodeCLI[evobgp_node]
end
All --> API
Split --> API
API --> Jobs
API --> PG
NodeCLI --> API
Agent --> API
Agent --> BIRD
```
| Профиль | Стиль | Когда |
|---------|-------|-------|
| `microvps` / `evobgp-all` | Monolith | 1 VPS, shared Registry |
| reference Compose | Microservices-lite | API + scheduler/ingest/render/deploy |
| Remote speakers | Edge agents | Panel→Node dispatch |
### Узкие места (bottlenecks)
| # | Bottleneck | Где | Impact |
|---|------------|-----|--------|
| B1 | **In-process job queue** | [`internal/jobs/job.go:175-177`](internal/jobs/job.go) | HA API невозможен без потери/дублирования jobs; scheduler без `EVOBGP_CONTROL_PLANE_URL` создаёт **отдельный Registry** — [`cmd/evobgp-scheduler/main.go:58-60`](cmd/evobgp-scheduler/main.go) |
| B2 | **Module refresh = sync upstream fan-out** | [`internal/pipeline/collect_parallel.go`](internal/pipeline/collect_parallel.go) | До `EVOBGP_COLLECT_CONCURRENCY` (8 default, max 32) параллельных HTTP; worst case ~45s × retries на источник |
| B3 | **Default job concurrency = 8** | [`internal/jobs/job.go:264-268`](internal/jobs/job.go) | При burst refresh 10+ tenants — очередь растёт, goroutine блокируются на sem |
| B4 | **PostgreSQL pool default** | [`internal/db/open.go:28-38`](internal/db/open.go) | pgx default ~4 conns; при `JOB_MAX=16` + HTTP — contention без `EVOBGP_DB_MAX_CONNS=25` |
| B5 | **Live endpoints fan-out** | [`internal/httpapi/peers_live.go`](internal/httpapi/peers_live.go) | N goroutines × N speakers, 12s timeout каждый |
| B6 | **Broker — заглушка** | [`internal/broker`](internal/broker) | NATS URL логируется, очередь не распределена |
### Масштабируемость
- **Вертикальная:** хорошо до ~10–20 tenants при `evobgp-all` + tuning ([`docs/production-checklist.md`](docs/production-checklist.md))
- **Горизонтальная API:** **не поддерживается** — два `evobgp-api` = два независимых Registry; `job_audit` в PG — audit only, не очередь исполнения
- **Workers (ingest/render/deploy):** координируются через **общую БД**, не через jobs — OK для prefetch/drift
### Отказоустойчивость
| Сценарий | Поведение | Оценка |
|----------|-----------|--------|
| CDN/RIPEstat недоступен | Stale snapshot + circuit breaker | **Хорошо** (если был prior snapshot) |
| DoH недоступен | Fail модуля или stale domain snapshot | **Средне** (нет HTTP retry) |
| API restart mid-job | Job теряется из Registry; audit может быть inconsistent | **Плохо** |
| PG недоступен | API `/v1/ready` → 503 | **OK** |
| Agent unreachable | Deploy job succeed, drift в `evobgp-deploy` | **Частичный fail** (by design) |
**Рекомендация:** для 10+ клиентов — **`evobgp-all` на каждом CP** или один CP + tuning; HA API требует **распределённой очереди** (NATS/Redis + worker pool) — задокументировано как future work.
---
## 2. Анализ кода
### Антипаттерны
| ID | Проблема | Файл | Критичность |
|----|----------|------|-------------|
| A1 | **Concurrent map read/write** — worker читает `j.Meta` без lock, handler пишет через `mergeMeta`/`Snapshot` | [`worker.go:108,263,379`](internal/jobs/worker.go), [`job.go:103-111`](internal/jobs/job.go) | **high** |
| A2 | **Escape internal pointers** из Memory store | [`store/memory.go:416-475`](internal/store/memory.go) | **high** (tests/dev); **low** (prod PG) |
| A3 | **Fire-and-forget goroutine** на каждый auth | [`auth.go:79-81`](internal/httpapi/auth.go) | **medium** |
| A4 | **Silent error swallow** в prefetch | [`internal/ingest/run.go`](internal/ingest/run.go), `prefetch.go` | **medium** |
| A5 | **Bypass resilience layer** — CDN preview прямой `Do` | [`routes_crud.go:267`](internal/httpapi/routes_crud.go) | **medium** |
| A6 | **`EVOBGP_DEV_INSECURE` — dead code** | compose + [`server.go`](internal/httpapi/server.go) | **low** (misleading ops) |
| A7 | **Unused Registry** в ingest/render/deploy binaries | [`cmd/evobgp-ingest/main.go`](cmd/evobgp-ingest/main.go) | **low** (resource waste) |
### Maintainability
**Плюсы:** чёткое разделение слоёв (ARCH-01..10), `store.Backend`, OpenAPI как контракт, engineering rules, table-driven tests в birdfmt/pipeline.
**Минусы:**
- Дублирование retry-логики (httpclient vs nodedispatch inline loop)
- Env-tuning разбросан (`EVOBGP_*` в 15+ местах без central config struct для pipeline)
- `Job` comment «персистенция в БД пока не подключена» устарел — hooks есть в [`bootstrap.go:67-92`](internal/httpapi/bootstrap.go)
### Потенциальные баги и race conditions
1. **`j.Meta` data race** — `-race` на `TestParallelModuleRefresh_*` + concurrent `GET /v1/jobs/{id}` polling
2. **Memory store alias**`deploy.Run` читает `LastAppliedRevisionID` пока worker пишет
3. **peerLiveCache** возвращает slice без копии — [`peers_live.go:82-84`](internal/httpapi/peers_live.go)
4. **TOCTOU idempotency** — terminal job удаляется из `byIdempo`, повторный POST создаст новый job (by design, но клиент должен знать)
### Error handling
**Хорошо:**
- Префиксы ошибок (`httpclient:`, `birdfmt:`)
- HTTP 5xx через `writeProblem`, без raw `err.Error()` (ERR-01)
- `context.Context` в pipeline workers
**Пробелы:**
- `runRollback` без `workContext` — не отменяется — [`worker.go:500+`](internal/jobs/worker.go)
- Prefetch/ingest: ошибки не логируются
- `mergeBirdPostApplyMeta``context.Background()` 8s, игнорирует job cancel
---
## 3. Производительность
### Блокирующие операции
| Участок | Блокировка | Риск |
|---------|------------|------|
| `POST .../cdn-sources/preview` | Sync CDN fetch до 45s в HTTP handler | UI timeout, worker starvation |
| `GET /v1/peers/live` | N × agent HTTP, wg.Wait | Slow при многих speakers |
| Module refresh job | Sequential: ingest → render revision → optional deploy | Long job chain |
| `bird -p` / `birdc configure` | Subprocess в deploy | Disk I/O на ноде |
### Неэффективные алгоритмы / лишние запросы
- **Tenant refresh:** `aggregateTenantPrefixRowsAll` — parallel по модулям, но каждый модуль может refetch все CDN/ASN/DoH — [`aggregate.go:28+`](internal/pipeline/aggregate.go). Snapshot skip есть через `module_hash` — проверять hit rate в meta.
- **ASN resolve:** `PolitePause()` 150ms между AS — [`asnresolve/ripestat.go`](internal/asnresolve/ripestat.go) — при 50 AS = +7.5s minimum.
- **GetModulePrefixSnapshot** вызывается многократно в одном refresh (cdn_snapshot, collect_parallel) — potential duplicate DB reads.
- **Auth TouchAPIKeyLastUsed:** UPDATE на каждый request (async) — load на PG при high RPS.
### Кэширование
| Кэш | TTL | Gap |
|-----|-----|-----|
| ASN prefix cache | 1800s (`EVOBGP_ASN_CACHE_TTL_SEC`) | OK |
| CDN ETag in DB | Until 304/change | OK |
| Module prefix snapshot | Content-hash based skip | OK |
| peerLiveCache | In-memory, per-process | Не shared между API replicas; нет defensive copy |
| Circuit breaker state | Per-process | Не shared |
### Конкретные улучшения
```go
// 1. CDN preview — использовать upstreamHTTPDo вместо прямого Do
resp, err := pipeline.UpstreamHTTPDo(r.Context(), s.cdnHTTP, req) // extract upstreamHTTPDo
// 2. Job.Meta — читать под lock или через Snapshot()
st := j.Snapshot()
mid, _ := st["meta"].(map[string]any)["module_id"].(string)
// 3. Memory store — возвращать копии (как Postgres)
modCopy := *mod
return &modCopy, nil
```
---
## 4. Сетевое взаимодействие (критично)
### Текущее состояние
```mermaid
flowchart LR
subgraph resilient [Resilient path]
CDN[CDN fetch]
RIPE[RIPEstat]
CDN --> Breaker[Circuit breaker]
RIPE --> Breaker
Breaker --> Retry[DoWithRetry 3x linear 2s]
end
subgraph fragile [Fragile path]
DoH[DoH resolve]
Preview[CDN preview API]
AgentHealth[Agent health/bird]
DoH --> SingleDo[Single hc.Do]
Preview --> SingleDo
AgentHealth --> SingleDo
end
subgraph fallback [App-level fallback]
Stale[Stale snapshot]
SysDNS[System DNS]
DoH --> SysDNS
CDN --> Stale
RIPE --> Stale
end
```
| Upstream | Timeout | Retry | Breaker | Stale fallback |
|----------|---------|-------|---------|----------------|
| CDN ingest | 45s | 3× linear | per-host | yes |
| RIPEstat | 45s | 3× | per-host | yes + cache |
| DoH | 10s/profile | **no** | **no** | domain snapshot |
| CDN preview | 45s | **no** | **no** | N/A |
| Scheduler→API | 45s | 3× | no | N/A |
| Node dispatch | 30s | inline 3× | no | N/A |
### Пробелы для блокировок провайдеров
1. **DoH без retry** — transient timeout = fail; failover между profiles есть, но каждый profile — single shot
2. **429/408 не ретраятся** — только `>= 500`
3. **Нет jitter** — thundering herd при mass tenant refresh
4. **DNS rebinding TOCTOU** — SSRF check до fetch, HTTP dial без pinned IP — [`cdn_url.go:75-115`](internal/pipeline/cdn_url.go)
5. **Circuit breaker без half-open** — после 30s cooldown сразу full traffic — [`circuit.go:29-33`](internal/httpclient/circuit.go)
6. **Breaker per-process** — ingest container ≠ API container
### Рекомендации для нестабильной сети
| # | Изменение | Effort | Effect |
|---|-----------|--------|--------|
| N1 | DoH через `DoWithRetry` + optional breaker | Low | **High** для DOMAINS modules |
| N2 | Retry 429/503 с `Retry-After` + exponential backoff + jitter | Medium | **High** при rate limits |
| N3 | **Partial CDN failure** — continue с stale per-source, не fail whole module | Medium | **High** |
| N4 | Multiple DoH profiles + `failover` policy (already exists) — **документировать ops playbook** | Low | **High** (config, not code) |
| N5 | Pinned dialer / custom `Transport.DialContext` после SSRF resolve | Medium | **Medium** (SSRF hardening) |
| N6 | Proxy support (`HTTP_PROXY` / `EVOBGP_HTTP_PROXY`) для CDN/DoH | Medium | **High** в censored networks |
| N7 | Unify CDN preview на `upstreamHTTPDo` | Low | **Medium** |
---
## 5. Устойчивость и надёжность
### Graceful degradation
**Работает:**
- `EVOBGP_STALE_ON_UPSTREAM_ERROR=1` — ASN/CDN/domain stale — [`collect_stale.go`](internal/pipeline/collect_stale.go)
- CDN 304 без local cache → forced full GET — [`cdn_snapshot.go:141-159`](internal/pipeline/cdn_snapshot.go)
- DoH → system DNS fallback — [`doh_resolve.go:75-93`](internal/pipeline/doh_resolve.go)
- Deploy: job succeed even if agent wake fails (drift detection)
**Не работает / частично:**
- Один CDN source fail без cache → **весь module_refresh failed** — [`collect_parallel.go:221-223`](internal/pipeline/collect_parallel.go)
- Circuit open → immediate error, stale only if prior data exists
- API shutdown: HTTP drain 15s, **jobs не cancel/drain** — [`cmd/evobgp-api/main.go:67-72`](cmd/evobgp-api/main.go)
### Сценарии отказов
| Событие | Что произойдёт |
|---------|----------------|
| **Потеря CP↔PG** | Ready=false; running jobs fail; no new jobs persist audit reliably |
| **Потеря CP↔CDN** | Stale prefixes если были; иначе job fail; breaker opens 30s |
| **Потеря CP↔agent** | Deploy meta `dispatch_failed`; BIRD на старой ревизии; drift logs |
| **RIPEstat rate limit** | 429 → no retry → stale or fail |
| **Рост нагрузки** | Job queue; goroutine pile-up; PG pool exhaustion; `/metrics` shows queue depth |
| **API restart** | In-flight jobs lost; clients poll 404 or stale terminal state |
---
## 6. Безопасность
| ID | Finding | Severity | Fix |
|----|---------|----------|-----|
| S1 | `Bearer dev` → operator при demo-seed | **high** (misconfig) | `EVOBGP_SEED_DEMO=0` — [`auth.go:66-92`](internal/httpapi/auth.go) |
| S2 | API plain HTTP | **high** (ops) | TLS на edge (Traefik/nginx) |
| S3 | Ephemeral bundle key без `EVOBGP_BUNDLE_SEED_HEX` | **high** (ops) | Stable seed + pubkey на нодах |
| S4 | Compose defaults: weak PG password, `sslmode=disable` | **high** (ops) | Secrets manager, `sslmode=require` |
| S5 | `/metrics` без auth | **medium** | Network policy / mTLS |
| S6 | No rate limiting on auth | **medium** | Middleware limiter (e.g. per-IP) |
| S7 | CDN SSRF DNS rebinding | **medium** | Pinned dialer after resolve |
| S8 | `EVOBGP_CDN_ALLOW_PRIVATE=1` | **medium** | Never in prod |
| S9 | `EVOBGP_NODE_DISPATCH_INSECURE_TLS=1` | **medium** | Valid TLS to agent |
| S10 | Plaintext `EVOBGP_API_KEYS` in env | **medium** | DB keys via API |
| S11 | `editor` can cancel jobs | **low** | Restrict to operator |
| S12 | agent_secret `==` compare | **low** | `subtle.ConstantTimeCompare` |
**SQL injection:** не обнаружено — параметризованные запросы в [`repository/`](internal/repository/).
**Bundle crypto:** Ed25519 корректно; path traversal blocked в tar extract.
---
## 7. Конкретные рекомендации (prioritized backlog)
### High
| # | Описание | Как исправить |
|---|----------|---------------|
| H1 | DoH без retry | Обернуть `hc.Do` в `DoWithRetry(ctx, hc, req, 3)` в [`refresh.go:288,360`](internal/pipeline/refresh.go) |
| H2 | Data race `Job.Meta` | Читать через `Snapshot()` или добавить `MetaLocked()` accessor |
| H3 | CDN source partial failure | В `collectCDNPrefixRows`: при err без stale — log warning + skip source вместо `return nil, r.err` (config flag `EVOBGP_CDN_PARTIAL_OK=1`) |
| H4 | Production checklist enforcement | CI/deploy validation: reject `SEED_DEMO=1`, require `BUNDLE_SEED_HEX` |
| H5 | Job queue HA roadmap | Persist queued jobs in PG + worker claim (`SELECT FOR UPDATE SKIP LOCKED`) или NATS — ARCH-04 |
### Medium
| # | Описание | Как исправить |
|---|----------|---------------|
| M1 | CDN preview bypass | [`routes_crud.go:267`](internal/httpapi/routes_crud.go) → `upstreamHTTPDo` |
| M2 | Retry 429/503 | Extend `DoWithRetry` status check + parse `Retry-After` |
| M3 | Graceful shutdown | On SIGTERM: `Registry.RequestCancelAll()` + wait workers with timeout |
| M4 | Auth goroutine storm | Worker pool или sync touch with debounce |
| M5 | HTTP proxy support | Custom Transport reading `EVOBGP_HTTP_PROXY` |
| M6 | Memory store copies | Defensive copy in Get/List (dev/test safety) |
| M7 | Rate limiting | `golang.org/x/time/rate` on auth middleware |
### Low
| # | Описание | Как исправить |
|---|----------|---------------|
| L1 | Jitter in backoff | `wait + rand.Intn(wait/2)` in DoWithRetry |
| L2 | Half-open breaker | Single probe request after cooldown |
| L3 | Remove dead `EVOBGP_DEV_INSECURE` from compose | Docs + compose cleanup |
| L4 | Prefetch error logging | `log.Printf` or structured log in prefetch |
| L5 | peerLiveCache defensive copy | `append([]T(nil), views...)` on store |
---
## 8. Quick wins (максимальный эффект / минимум усилий)
1. **Ops (0 code):** [`docs/production-checklist.md`](docs/production-checklist.md) — `SEED_DEMO=0`, `BUNDLE_SEED_HEX`, `DB_MAX_CONNS=25`, `JOB_MAX=16`, `COLLECT_CONCURRENCY=16`, TLS edge, restrict metrics
2. **DoH retry** — 510 строк в `refresh.go`, reuse existing `DoWithRetry`
3. **CDN preview → upstreamHTTPDo** — 1 line change in handler
4. **Job.Meta read fix** — replace 4 reads in `worker.go` with `Snapshot()` parsing
5. **Log prefetch failures** — visibility без изменения behavior
6. **Document DoH failover playbook** — multiple profiles (Cloudflare, Google, Quad9) + `failover` policy for censored regions
7. **Run `go test -race ./internal/jobs/...`** in CI — catch Meta race
8. **Prefer `evobgp-all`** over split reference for &lt;20 tenants — eliminates Registry split bug
---
## Диаграмма: refresh под сетевым stress
```mermaid
sequenceDiagram
participant Op as Operator
participant API as evobgp_api
participant Job as module_refresh
participant CDN as CDN_upstream
participant PG as PostgreSQL
Op->>API: POST /modules/id/refresh
API->>Job: Enqueue
Job->>CDN: GET with ETag
alt CDN timeout or 5xx
CDN-->>Job: error after 3 retries
Job->>PG: load prior snapshot
alt stale exists
Job->>PG: CreateRenderRevision stale
Job-->>API: succeeded degraded
else no stale
Job-->>API: failed
end
else CDN 200
CDN-->>Job: new prefixes
Job->>PG: CreateRenderRevision
end
```
---
## Итоговая оценка зрелости
| Область | Оценка | Комментарий |
|---------|--------|-------------|
| Архитектура | 7/10 | Чистые слои; HA/API scaling — слабое место |
| Сеть/resilience | 6/10 | CDN/ASN хорошо; DoH/preview — пробелы |
| Concurrency | 6/10 | Registry продуман; Meta race, shutdown |
| Performance | 7/10 | Parallel collect, caching; tuning needed at scale |
| Security | 6/10 | Crypto OK; ops/config risks dominate |
| Maintainability | 8/10 | Docs, rules, OpenAPI, tests |
**Вердикт:** проект **готов для 10+ клиентов в single-CP deployment** (`evobgp-all` + PostgreSQL + production checklist) при условии ops discipline. Для **multi-CP HA** и **агрессивных сетевых блокировок** — приоритет: DoH retry, partial CDN failure, distributed job queue, HTTP proxy.
+100
View File
@@ -0,0 +1,100 @@
---
description: Context7 — закреплённые ID библиотек и документации стека EvoBGP
alwaysApply: true
---
# Context7 — стек EvoBGP
При вопросах об API, синтаксисе, конфигурации и миграциях библиотек **сначала** `query-docs` с ID из таблицы ниже. Шаг `resolve-library-id` **пропускать**, если библиотека уже перечислена (кроме неоднозначного случая).
Локальные версии: `go.mod`, `web/package.json`. При расхождении с ID — предпочитать версию из репозитория.
---
## Backend (Go)
| Библиотека | Context7 ID | Версия в проекте | Когда |
|------------|-------------|------------------|-------|
| Go stdlib | `/golang/go/go1_24_6` | Go 1.24 | `net/http`, `context`, тесты, concurrency |
| pgx | `/websites/pkg_go_dev_github_com_jackc_pgx_v5` | v5.7.2 | PostgreSQL, pool, транзакции, типы |
| Prometheus Go client | `/prometheus/client_golang` | v1.20.5 | метрики, `/metrics`, middleware |
| modernc SQLite | `/websites/pkg_go_dev_modernc_org_sqlite` | v1.34.5 | SQLite-бэкенд, миграции sqlite |
| miekg/dns | `/miekg/dns` | v1.1.72 | DNS-запросы, DoH, pipeline |
---
## HTTP-контракт и спецификации
| Библиотека | Context7 ID | Версия в проекте | Когда |
|------------|-------------|------------------|-------|
| OpenAPI | `/oai/openapi-specification` | 3.x в `docs/openapi.yaml` | схемы, operationId, problem+json |
| Redocly CLI | `/redocly/redocly-cli` | CI `@redocly/cli` | lint OpenAPI, `npx @redocly/cli lint` |
---
## Web UI (`apps/web/` + `packages/ui/`)
| Библиотека | Context7 ID | Версия в проекте | Когда |
|------------|-------------|------------------|-------|
| React | `/facebook/react` | ^19.2 | hooks, components, JSX |
| TanStack Router | `/tanstack/router` | ^1.130 | file-based routes, `createFileRoute`, `useSearch`, `Link` |
| TanStack Query | `/tanstack/query` | ^5.90 | `useQuery`, `useMutation`, `queryOptions`, invalidation |
| TanStack Table | `/websites/tanstack_table` | ^8.21 | data-grid колонки, сортировка (ReUI) |
| TanStack Virtual | `/tanstack/virtual` | ^3.14 | виртуализация списков (ReUI data-grid) |
| Vite | `/vitejs/vite/v7.3.1` | ^7.3.1 | dev server, build, plugins |
| TypeScript | `/microsoft/typescript/v5.9.3` | ^5.9.3 | типы, strict, tsconfig |
| Tailwind CSS | `/tailwindlabs/tailwindcss.com` | ^4.1 | v4, `@tailwindcss/vite`, утилиты |
| shadcn/ui (React) | MCP `plugin-shadcn-shadcn` + https://ui.shadcn.com/docs | base-nova | примитивы `@evobgp/ui/components/*` |
| ReUI | https://reui.io/llms.txt + MCP с `registries: ["@reui"]` | registry | enterprise: data-grid, filters, autocomplete |
| react-hook-form | `/react-hook-form` | ^7.60 | формы, controller |
| Zod | `/websites/zod_dev_v4` | ^3.25 / ^4 (apps/web) | схемы валидации |
| recharts | `/recharts/recharts` | 3.8.0 | графики через shadcn `Chart` |
| next-themes | `/pacocoursey/next-themes` | ^0.4 | dark/light theme provider |
| sonner | `/emilkowalski/sonner` | ^1.7 | toast notifications |
| lucide-react | `/lucide-icons/lucide` | ^0.468 | иконки |
UI-правила репозитория: `.cursor/rules/web-shadcn.mdc` (MCP + shadcn/ui React docs — первичный источник для компонентов).
---
## Data plane / BGP
| Библиотека | Context7 ID | Версия в проекте | Когда |
|------------|-------------|------------------|-------|
| BIRD 2 | `/llmstxt/bird_xmsl_dev_llms_txt` | BIRD2 в compose | `birdfmt`, фильтры, протоколы |
| BIRD (исходники) | `/cz-nic/bird` | — | низкоуровневый синтаксис daemon |
Сетевые правила: `.cursor/rules/networking-bird.mdc`.
---
## DevOps
| Библиотека | Context7 ID | Версия в проекте | Когда |
|------------|-------------|------------------|-------|
| Docker Compose | `/docker/compose` | `deploy/compose/` | сервисы, profiles, volumes |
| Docker | `/docker/docs` | — | образы, bake, networking |
---
## Приоритет источников
1. **Контракт HTTP** — `docs/openapi.yaml` (не Context7).
2. **Context7** — синтаксис и API библиотек из таблицы.
3. **Локальные docs** — `docs/`, `web/README.md`, `AGENTS.md`.
4. **Официальный сайт** — BIRD: https://bird.nic.cz/?get_doc (если Context7 не покрыл кейс).
## Примеры запросов
```
/docs /facebook/react hooks useState useEffect
/docs /tanstack/router createFileRoute useSearch Link
/docs /tanstack/query useQuery useMutation queryOptions
/docs /golang/go/go1_24_6 net/http ServeMux pattern matching
/docs /websites/pkg_go_dev_github_com_jackc_pgx_v5 pool acquire rows
/docs /llmstxt/bird_xmsl_dev_llms_txt filter bgp import
```
## Не через Context7
Рефакторинг `internal/*`, бизнес-логика EvoBGP, code review — код репозитория и `codegraph`. Context7 — только внешние библиотеки и инструменты.
+2
View File
@@ -142,6 +142,8 @@ feat(web): add module create dialog on /modules
| `.cursor/` | `chore` |
| прочее в корне | `chore` |
**Запрещено:** несколько scope через запятую (`refactor(web, httpapi): …`) — semantic-release не распознает `type`, релиз не будет (см. [docs/releasing.md](../../docs/releasing.md)).
`type` определять по **содержимому diff**, не только по пути.
## Multi-change
+6 -6
View File
@@ -94,8 +94,8 @@ alwaysApply: true
**DEP-03** | MUST | Миграции схемы — пары `.up.sql`/`.down.sql` для **postgres** и **sqlite**, синхронная нумерация.
*Проверка:* `migrations/postgres/`, `migrations/sqlite/`.
**DEP-04** | MUST | Web UI-библиотеки — только экосистема shadcn-svelte/bits-ui (см. `web-shadcn.mdc`).
*Проверка:* `web/package.json` review.
**DEP-04** | MUST | Web UI-библиотеки — только экосистема shadcn/ui (React) + ReUI (см. `web-shadcn.mdc`).
*Проверка:* `apps/web/package.json`, `packages/ui/package.json` review.
---
@@ -123,7 +123,7 @@ alwaysApply: true
**TEST-03** | MUST | Новые BIRD-сценарии в `internal/birdfmt/testdata/scenarios/*/bird.conf` + `bird -p`.
*Проверка:* CI job `bird2`.
**TEST-04** | MUST | Изменения `web/` — локально **`npm run check` и `npm run lint`** (обе команды, exit 0); CI job `web` в `.gitea/workflows/ci.yaml`. Агент: при fail lint — `npx prettier --write` затем повтор. Только `check` не заменяет `lint`.
**TEST-04** | MUST | Изменения `apps/web/**` или `packages/ui/**` — локально **`pnpm --filter @evobgp/web run typecheck`, `lint`, `build`** (все три команды, exit 0); CI job `web` в `.gitea/workflows/ci.yaml`.
*Проверка:* CI job `web`; `.cursor/rules/web-shadcn.mdc` WEB-19.
**TEST-05** | MUST | Изменения OpenAPI — `npx @redocly/cli lint docs/openapi.yaml`.
@@ -207,13 +207,13 @@ alwaysApply: true
| OpenAPI / problem+json | `docs/openapi.yaml`, RFC 9457 |
| Svelte / Kit | https://svelte.dev/docs , https://kit.svelte.dev/docs |
| shadcn-svelte | https://shadcn-svelte.com/docs |
| BIRD 2 | https://bird.network.cz/?get_doc |
| BIRD 2 | https://bird.nic.cz/?get_doc |
| Prometheus Go | https://pkg.go.dev/github.com/prometheus/client_golang |
**DOC-SYNC-01** | MUST | Новый API библиотеки — сверка версии в `go.mod`/`package.json` с официальной документацией.
**DOC-SYNC-02** | NEVER | Устаревшие примеры (Svelte 4 `export let`, deprecated pgx).
**DOC-SYNC-03** | MUST | Конфликт docs: **OpenAPI (HTTP)** → **код** → обзорные `docs/`; `.cursor/plans/` не контракт.
**DOC-SYNC-04** | MUST | Сомнения по Svelte — Svelte MCP / `npm run check`.
**DOC-SYNC-04** | MUST | Сомнения по React/shadcn/ReUI — MCP `plugin-shadcn-shadcn` + `pnpm --filter @evobgp/web run typecheck`.
**DOC-SYNC-05** | MUST | BIRD — официальная документация BIRD2 + `networking-bird.mdc` + `go test ./internal/birdfmt/...`.
Приоритет при сомнениях — **официальные источники**, не блоги и не «память модели».
@@ -230,7 +230,7 @@ alwaysApply: true
go vet ./...
go test ./... -race -count=1
npx @redocly/cli lint docs/openapi.yaml
# web: cd web; npm run check; npm run lint (или scripts/lint-web.ps1)
# web: pnpm --filter @evobgp/web run typecheck; pnpm --filter @evobgp/web run lint; pnpm --filter @evobgp/web run build
# go fmt/lint: gofmt -w <files>; scripts/lint-go.ps1 (gofmt + vet + golangci-lint)
# birdfmt: go test ./internal/birdfmt/... -count=1
```
@@ -0,0 +1,235 @@
---
description: Command execution guidelines for isolation-focused Memory Bank
globs: command-execution.mdc
alwaysApply: false
---
# COMMAND EXECUTION SYSTEM
> **TL;DR:** This system provides guidelines for efficient command execution, balancing clarity and token optimization through appropriate command chaining, with proper documentation of commands and results.
## 🔍 COMMAND EFFICIENCY WORKFLOW
```mermaid
graph TD
Start["Command<br>Planning"] --> Analyze["Analyze Command<br>Requirements"]
Analyze --> Balance["Balance Clarity<br>vs. Efficiency"]
Balance --> Complexity{"Command<br>Complexity?"}
Complexity -->|"Simple"| Single["Execute<br>Single Command"]
Complexity -->|"Moderate"| Chain["Use Efficient<br>Command Chaining"]
Complexity -->|"Complex"| Group["Group Into<br>Logical Steps"]
Single & Chain & Group --> Verify["Verify<br>Results"]
Verify --> Document["Document<br>Command & Result"]
Document --> Next["Next<br>Command"]
```
## 📋 COMMAND CHAINING GUIDELINES
```mermaid
graph TD
Command["Command<br>Execution"] --> ChainApprop{"Is Chaining<br>Appropriate?"}
ChainApprop -->|"Yes"| ChainTypes["Chain<br>Types"]
ChainApprop -->|"No"| SingleCmd["Use Single<br>Commands"]
ChainTypes --> Sequential["Sequential Operations<br>cmd1 && cmd2"]
ChainTypes --> Conditional["Conditional Operations<br>cmd1 || cmd2"]
ChainTypes --> Piping["Piping<br>cmd1 | cmd2"]
ChainTypes --> Grouping["Command Grouping<br>(cmd1; cmd2)"]
Sequential & Conditional & Piping & Grouping --> Doc["Document<br>Commands & Results"]
```
## 🚦 DIRECTORY VERIFICATION WORKFLOW
```mermaid
graph TD
Command["Command<br>Execution"] --> DirCheck["Check Current<br>Directory"]
DirCheck --> ProjectRoot{"In Project<br>Root?"}
ProjectRoot -->|"Yes"| Execute["Execute<br>Command"]
ProjectRoot -->|"No"| Locate["Locate<br>Project Root"]
Locate --> Found{"Project Root<br>Found?"}
Found -->|"Yes"| Navigate["Navigate to<br>Project Root"]
Found -->|"No"| Error["Error: Cannot<br>Find Project Root"]
Navigate --> Execute
Execute --> Verify["Verify<br>Results"]
```
## 📋 DIRECTORY VERIFICATION CHECKLIST
Before executing any npm or build command:
| Step | Windows (PowerShell) | Unix/Linux/Mac | Purpose |
|------|----------------------|----------------|---------|
| **Check package.json** | `Test-Path package.json` | `ls package.json` | Verify current directory is project root |
| **Check for parent directory** | `Test-Path "*/package.json"` | `find . -maxdepth 2 -name package.json` | Find potential project directories |
| **Navigate to project root** | `cd [project-dir]` | `cd [project-dir]` | Move to correct directory before executing commands |
## 📋 REACT-SPECIFIC COMMAND GUIDELINES
For React applications, follow these strict guidelines:
| Command | Correct Usage | Incorrect Usage | Notes |
|---------|---------------|----------------|-------|
| **npm start** | `cd [project-root] && npm start` | `npm start` (from parent dir) | Must execute from directory with package.json |
| **npm run build** | `cd [project-root] && npm run build` | `cd [parent-dir] && npm run build` | Must execute from directory with package.json |
| **npm install** | `cd [project-root] && npm install [pkg]` | `npm install [pkg]` (wrong dir) | Dependencies installed to nearest package.json |
| **npm create** | `npm create vite@latest my-app -- --template react` | Manually configuring webpack | Use standard tools for project creation |
## 🔄 COMMAND CHAINING PATTERNS
Effective command chaining patterns include:
| Pattern | Format | Examples | Use Case |
|---------|--------|----------|----------|
| **Sequential** | `cmd1 && cmd2` | `mkdir dir && cd dir` | Commands that should run in sequence, second only if first succeeds |
| **Conditional** | `cmd1 || cmd2` | `test -f file.txt || touch file.txt` | Fallback commands, second only if first fails |
| **Piping** | `cmd1 \| cmd2` | `grep "pattern" file.txt \| wc -l` | Pass output of first command as input to second |
| **Background** | `cmd &` | `npm start &` | Run command in background |
| **Grouping** | `(cmd1; cmd2)` | `(echo "Start"; npm test; echo "End")` | Group commands to run as a unit |
## 📋 COMMAND DOCUMENTATION TEMPLATE
```
## Command Execution: [Purpose]
### Command
```
[actual command or chain]
```
### Result
```
[command output]
```
### Effect
[Brief description of what changed in the system]
### Next Steps
[What needs to be done next]
```
## 🔍 PLATFORM-SPECIFIC CONSIDERATIONS
```mermaid
graph TD
Platform["Platform<br>Detection"] --> Windows["Windows<br>Commands"]
Platform --> Unix["Unix/Linux/Mac<br>Commands"]
Windows --> WinAdapt["Windows Command<br>Adaptations"]
Unix --> UnixAdapt["Unix Command<br>Adaptations"]
WinAdapt --> WinChain["Windows Chaining:<br>Commands separated by &"]
UnixAdapt --> UnixChain["Unix Chaining:<br>Commands separated by ;"]
WinChain & UnixChain --> Execute["Execute<br>Platform-Specific<br>Commands"]
```
## 📋 COMMAND EFFICIENCY EXAMPLES
Examples of efficient command usage:
| Inefficient | Efficient | Explanation |
|-------------|-----------|-------------|
| `mkdir dir`<br>`cd dir`<br>`npm init -y` | `mkdir dir && cd dir && npm init -y` | Combines related sequential operations |
| `ls`<br>`grep "\.js$"` | `ls \| grep "\.js$"` | Pipes output of first command to second |
| `test -f file.txt`<br>`if not exists, touch file.txt` | `test -f file.txt \|\| touch file.txt` | Creates file only if it doesn't exist |
| `mkdir dir1`<br>`mkdir dir2`<br>`mkdir dir3` | `mkdir dir1 dir2 dir3` | Uses command's built-in multiple argument capability |
| `npm install pkg1`<br>`npm install pkg2` | `npm install pkg1 pkg2` | Installs multiple packages in one command |
## 📋 REACT PROJECT INITIALIZATION STANDARDS
Always use these standard approaches for React project creation:
| Approach | Command | Benefits | Avoids |
|----------|---------|----------|--------|
| **Create React App** | `npx create-react-app my-app` | Preconfigured webpack & babel | Manual configuration errors |
| **Create React App w/TypeScript** | `npx create-react-app my-app --template typescript` | Type safety + preconfigured | Inconsistent module systems |
| **Vite** | `npm create vite@latest my-app -- --template react` | Faster build times | Complex webpack setups |
| **Next.js** | `npx create-next-app@latest my-app` | SSR support | Module system conflicts |
## ⚠️ ERROR HANDLING WORKFLOW
```mermaid
sequenceDiagram
participant User
participant AI
participant System
AI->>System: Execute Command
System->>AI: Return Result
alt Success
AI->>AI: Verify Expected Result
AI->>User: Report Success
else Error
AI->>AI: Analyze Error Message
AI->>AI: Identify Likely Cause
AI->>User: Explain Error & Cause
AI->>User: Suggest Corrective Action
User->>AI: Approve Correction
AI->>System: Execute Corrected Command
end
```
## 📋 COMMAND RESULT VERIFICATION
After command execution, verify:
```mermaid
graph TD
Execute["Execute<br>Command"] --> Check{"Check<br>Result"}
Check -->|"Success"| Verify["Verify Expected<br>Outcome"]
Check -->|"Error"| Analyze["Analyze<br>Error"]
Verify -->|"Expected"| Document["Document<br>Success"]
Verify -->|"Unexpected"| Investigate["Investigate<br>Unexpected Result"]
Analyze --> Diagnose["Diagnose<br>Error Cause"]
Diagnose --> Correct["Propose<br>Correction"]
Document & Investigate & Correct --> Next["Next Step<br>in Process"]
```
## 📝 COMMAND EXECUTION CHECKLIST
```
✓ COMMAND EXECUTION CHECKLIST
- Command purpose clearly identified? [YES/NO]
- Appropriate balance of clarity vs. efficiency? [YES/NO]
- Platform-specific considerations addressed? [YES/NO]
- Command documented with results? [YES/NO]
- Outcome verified against expectations? [YES/NO]
- Errors properly handled (if any)? [YES/NO/NA]
- For npm/build commands: Executed from project root? [YES/NO/NA]
- For React projects: Using standard tooling? [YES/NO/NA]
→ If all YES: Command execution complete
→ If any NO: Address missing elements
```
## 🚨 COMMAND EXECUTION WARNINGS
Avoid these common command issues:
```mermaid
graph TD
Warning["Command<br>Warnings"] --> W1["Excessive<br>Verbosity"]
Warning --> W2["Insufficient<br>Error Handling"]
Warning --> W3["Unnecessary<br>Complexity"]
Warning --> W4["Destructive<br>Operations Without<br>Confirmation"]
Warning --> W5["Wrong Directory<br>Execution"]
W1 --> S1["Use flags to reduce<br>unnecessary output"]
W2 --> S2["Include error handling<br>in command chains"]
W3 --> S3["Prefer built-in<br>command capabilities"]
W4 --> S4["Show confirmation<br>before destructive actions"]
W5 --> S5["Verify directory before<br>npm/build commands"]
```
@@ -0,0 +1,187 @@
---
description: complexity decision tree
globs: complexity-decision-tree.mdc
alwaysApply: false
---
# TASK COMPLEXITY DETERMINATION
> **TL;DR:** This document helps determine the appropriate complexity level (1-4) for any task. Use the decision tree and indicators to select the right process level, then load the corresponding process map.
## 🌳 COMPLEXITY DECISION TREE
```mermaid
graph TD
Start["New Task"] --> Q1{"Bug fix or<br>error correction?"}
Q1 -->|Yes| Q1a{"Affects single<br>component?"}
Q1a -->|Yes| L1["Level 1:<br>Quick Bug Fix"]
Q1a -->|No| Q1b{"Affects multiple<br>components?"}
Q1b -->|Yes| L2["Level 2:<br>Simple Enhancement"]
Q1b -->|No| Q1c{"Affects system<br>architecture?"}
Q1c -->|Yes| L3["Level 3:<br>Intermediate Feature"]
Q1c -->|No| L2
Q1 -->|No| Q2{"Adding small<br>feature or<br>enhancement?"}
Q2 -->|Yes| Q2a{"Self-contained<br>change?"}
Q2a -->|Yes| L2
Q2a -->|No| Q2b{"Affects multiple<br>components?"}
Q2b -->|Yes| L3
Q2b -->|No| L2
Q2 -->|No| Q3{"Complete feature<br>requiring multiple<br>components?"}
Q3 -->|Yes| Q3a{"Architectural<br>implications?"}
Q3a -->|Yes| L4["Level 4:<br>Complex System"]
Q3a -->|No| L3
Q3 -->|No| Q4{"System-wide or<br>architectural<br>change?"}
Q4 -->|Yes| L4
Q4 -->|No| L3
L1 --> LoadL1["Load Level 1 Map"]
L2 --> LoadL2["Load Level 2 Map"]
L3 --> LoadL3["Load Level 3 Map"]
L4 --> LoadL4["Load Level 4 Map"]
```
## 📊 COMPLEXITY LEVEL INDICATORS
Use these indicators to help determine task complexity:
### Level 1: Quick Bug Fix
- **Keywords**: "fix", "broken", "not working", "issue", "bug", "error", "crash"
- **Scope**: Single component or UI element
- **Duration**: Can be completed quickly (minutes to hours)
- **Risk**: Low, isolated changes
- **Examples**:
- Fix button not working
- Correct styling issue
- Fix validation error
- Resolve broken link
- Fix typo or text issue
### Level 2: Simple Enhancement
- **Keywords**: "add", "improve", "update", "change", "enhance", "modify"
- **Scope**: Single component or subsystem
- **Duration**: Hours to 1-2 days
- **Risk**: Moderate, contained to specific area
- **Examples**:
- Add form field
- Improve validation
- Update styling
- Add simple feature
- Change text content
- Enhance existing component
### Level 3: Intermediate Feature
- **Keywords**: "implement", "create", "develop", "build", "feature"
- **Scope**: Multiple components, complete feature
- **Duration**: Days to 1-2 weeks
- **Risk**: Significant, affects multiple areas
- **Examples**:
- Implement user authentication
- Create dashboard
- Develop search functionality
- Build user profile system
- Implement data visualization
- Create complex form system
### Level 4: Complex System
- **Keywords**: "system", "architecture", "redesign", "integration", "framework"
- **Scope**: Multiple subsystems or entire application
- **Duration**: Weeks to months
- **Risk**: High, architectural implications
- **Examples**:
- Implement authentication system
- Build payment processing framework
- Create microservice architecture
- Implement database migration system
- Develop real-time communication system
- Create multi-tenant architecture
## 🔍 COMPLEXITY ASSESSMENT QUESTIONS
Answer these questions to determine complexity:
1. **Scope Impact**
- Does it affect a single component or multiple?
- Are there system-wide implications?
- How many files will need to be modified?
2. **Design Decisions**
- Are complex design decisions required?
- Will it require creative phases for design?
- Are there architectural considerations?
3. **Risk Assessment**
- What happens if it fails?
- Are there security implications?
- Will it affect critical functionality?
4. **Implementation Effort**
- How long will it take to implement?
- Does it require specialized knowledge?
- Is extensive testing needed?
## 📊 KEYWORD ANALYSIS TABLE
| Keyword | Likely Level | Notes |
|---------|--------------|-------|
| "Fix" | Level 1 | Unless system-wide |
| "Bug" | Level 1 | Unless multiple components |
| "Error" | Level 1 | Unless architectural |
| "Add" | Level 2 | Unless complex feature |
| "Update" | Level 2 | Unless architectural |
| "Improve" | Level 2 | Unless system-wide |
| "Implement" | Level 3 | Complex components |
| "Create" | Level 3 | New functionality |
| "Develop" | Level 3 | Significant scope |
| "System" | Level 4 | Architectural implications |
| "Architecture" | Level 4 | Major structural changes |
| "Framework" | Level 4 | Core infrastructure |
## 🔄 COMPLEXITY ESCALATION
If during a task you discover it's more complex than initially determined:
```
⚠️ TASK ESCALATION NEEDED
Current Level: Level [X]
Recommended Level: Level [Y]
Reason: [Brief explanation]
Would you like me to escalate this task to Level [Y]?
```
If approved, switch to the appropriate higher-level process map.
## 🎯 PROCESS SELECTION
After determining complexity, load the appropriate process map:
| Level | Description | Process Map |
|-------|-------------|-------------|
| 1 | Quick Bug Fix | [Level 1 Map](mdc:.cursor/rules/visual-maps/level1-map.mdc) |
| 2 | Simple Enhancement | [Level 2 Map](mdc:.cursor/rules/visual-maps/level2-map.mdc) |
| 3 | Intermediate Feature | [Level 3 Map](mdc:.cursor/rules/visual-maps/level3-map.mdc) |
| 4 | Complex System | [Level 4 Map](mdc:.cursor/rules/visual-maps/level4-map.mdc) |
## 📝 COMPLEXITY DETERMINATION TEMPLATE
Use this template to document complexity determination:
```
## COMPLEXITY DETERMINATION
Task: [Task description]
Assessment:
- Scope: [Single component/Multiple components/System-wide]
- Design decisions: [Simple/Moderate/Complex]
- Risk: [Low/Moderate/High]
- Implementation effort: [Low/Moderate/High]
Keywords identified: [List relevant keywords]
Determination: Level [1/2/3/4] - [Quick Bug Fix/Simple Enhancement/Intermediate Feature/Complex System]
Loading process map: [Level X Map]
```
@@ -0,0 +1,145 @@
---
description: creative phase enforcement
globs: creative-phase-enforcement.md
alwaysApply: false
---
# CREATIVE PHASE ENFORCEMENT
> **TL;DR:** This document implements strict enforcement of creative phase requirements for Level 3-4 tasks, ensuring all design decisions are properly documented and verified before implementation can proceed.
## 🔍 ENFORCEMENT WORKFLOW
```mermaid
graph TD
Start["Task Start"] --> Check{"Level 3-4<br>Task?"}
Check -->|Yes| Analyze["Analyze Design<br>Decision Points"]
Check -->|No| Optional["Creative Phase<br>Optional"]
Analyze --> Decision{"Design Decisions<br>Required?"}
Decision -->|Yes| Gate["🚨 IMPLEMENTATION<br>BLOCKED"]
Decision -->|No| Allow["Allow<br>Implementation"]
Gate --> Creative["Enter Creative<br>Phase"]
Creative --> Verify{"All Decisions<br>Documented?"}
Verify -->|No| Return["Return to<br>Creative Phase"]
Verify -->|Yes| Proceed["Allow<br>Implementation"]
style Start fill:#4da6ff,stroke:#0066cc,color:white
style Check fill:#ffa64d,stroke:#cc7a30,color:white
style Analyze fill:#4dbb5f,stroke:#36873f,color:white
style Gate fill:#d94dbb,stroke:#a3378a,color:white
style Creative fill:#4dbbbb,stroke:#368787,color:white
style Verify fill:#d971ff,stroke:#a33bc2,color:white
```
## 🚨 ENFORCEMENT GATES
```mermaid
graph TD
subgraph "CREATIVE PHASE GATES"
G1["Entry Gate<br>Verify Requirements"]
G2["Process Gate<br>Verify Progress"]
G3["Exit Gate<br>Verify Completion"]
end
G1 --> G2 --> G3
style G1 fill:#4dbb5f,stroke:#36873f,color:white
style G2 fill:#ffa64d,stroke:#cc7a30,color:white
style G3 fill:#d94dbb,stroke:#a3378a,color:white
```
## 📋 ENFORCEMENT CHECKLIST
```markdown
## Entry Gate Verification
- [ ] Task complexity is Level 3-4
- [ ] Design decisions identified
- [ ] Creative phase requirements documented
- [ ] Required participants notified
## Process Gate Verification
- [ ] All options being considered
- [ ] Pros/cons documented
- [ ] Technical constraints identified
- [ ] Implementation impacts assessed
## Exit Gate Verification
- [ ] All decisions documented
- [ ] Rationale provided for choices
- [ ] Implementation plan outlined
- [ ] Verification against requirements
```
## 🚨 IMPLEMENTATION BLOCK NOTICE
When a creative phase is required but not completed:
```
🚨 IMPLEMENTATION BLOCKED
Creative phases MUST be completed before implementation.
Required Creative Phases:
- [ ] [Creative Phase 1]
- [ ] [Creative Phase 2]
- [ ] [Creative Phase 3]
⛔ This is a HARD BLOCK
Implementation CANNOT proceed until all creative phases are completed.
Type "PHASE.REVIEW" to begin creative phase review.
```
## ✅ VERIFICATION PROTOCOL
```mermaid
graph TD
subgraph "VERIFICATION STEPS"
V1["1. Requirements<br>Check"]
V2["2. Documentation<br>Review"]
V3["3. Decision<br>Validation"]
V4["4. Implementation<br>Readiness"]
end
V1 --> V2 --> V3 --> V4
style V1 fill:#4dbb5f,stroke:#36873f,color:white
style V2 fill:#ffa64d,stroke:#cc7a30,color:white
style V3 fill:#d94dbb,stroke:#a3378a,color:white
style V4 fill:#4dbbbb,stroke:#368787,color:white
```
## 🔄 CREATIVE PHASE MARKERS
Use these markers to clearly indicate creative phase boundaries:
```markdown
🎨🎨🎨 ENTERING CREATIVE PHASE: [TYPE] 🎨🎨🎨
Focus: [Specific component/feature]
Objective: [Clear goal of this creative phase]
Requirements: [List of requirements]
[Creative phase content]
🎨 CREATIVE CHECKPOINT: [Milestone]
- Progress: [Status]
- Decisions: [List]
- Next steps: [Plan]
🎨🎨🎨 EXITING CREATIVE PHASE 🎨🎨🎨
Summary: [Brief description]
Key Decisions: [List]
Next Steps: [Implementation plan]
```
## 🔄 DOCUMENT MANAGEMENT
```mermaid
graph TD
Current["Current Document"] --> Active["Active:<br>- creative-phase-enforcement.md"]
Current --> Related["Related:<br>- creative-phase-architecture.md<br>- task-tracking-intermediate.md"]
style Current fill:#4da6ff,stroke:#0066cc,color:white
style Active fill:#4dbb5f,stroke:#36873f,color:white
style Related fill:#ffa64d,stroke:#cc7a30,color:white
```
@@ -0,0 +1,195 @@
---
description: creative phase metrics
globs: creative-phase-metrics.md
alwaysApply: false
---
# CREATIVE PHASE METRICS
> **TL;DR:** This document defines comprehensive quality metrics and measurement criteria for creative phases, ensuring that design decisions meet required standards and are properly documented.
## 📊 METRICS OVERVIEW
```mermaid
graph TD
subgraph "CREATIVE PHASE METRICS"
M1["Documentation<br>Quality"]
M2["Decision<br>Coverage"]
M3["Option<br>Analysis"]
M4["Impact<br>Assessment"]
M5["Verification<br>Score"]
end
M1 --> Score["Quality<br>Score"]
M2 --> Score
M3 --> Score
M4 --> Score
M5 --> Score
style M1 fill:#4dbb5f,stroke:#36873f,color:white
style M2 fill:#ffa64d,stroke:#cc7a30,color:white
style M3 fill:#d94dbb,stroke:#a3378a,color:white
style M4 fill:#4dbbbb,stroke:#368787,color:white
style M5 fill:#d971ff,stroke:#a33bc2,color:white
style Score fill:#ff71c2,stroke:#c23b8a,color:white
```
## 📋 QUALITY METRICS SCORECARD
```markdown
# Creative Phase Quality Assessment
## 1. Documentation Quality [0-10]
- [ ] Clear problem statement (2 points)
- [ ] Well-defined objectives (2 points)
- [ ] Comprehensive requirements list (2 points)
- [ ] Proper formatting and structure (2 points)
- [ ] Cross-references to related documents (2 points)
## 2. Decision Coverage [0-10]
- [ ] All required decisions identified (2 points)
- [ ] Each decision point documented (2 points)
- [ ] Dependencies mapped (2 points)
- [ ] Impact analysis included (2 points)
- [ ] Future considerations noted (2 points)
## 3. Option Analysis [0-10]
- [ ] Multiple options considered (2 points)
- [ ] Pros/cons documented (2 points)
- [ ] Technical feasibility assessed (2 points)
- [ ] Resource requirements estimated (2 points)
- [ ] Risk factors identified (2 points)
## 4. Impact Assessment [0-10]
- [ ] System impact documented (2 points)
- [ ] Performance implications assessed (2 points)
- [ ] Security considerations addressed (2 points)
- [ ] Maintenance impact evaluated (2 points)
- [ ] Cost implications analyzed (2 points)
## 5. Verification Score [0-10]
- [ ] Requirements traced (2 points)
- [ ] Constraints validated (2 points)
- [ ] Test scenarios defined (2 points)
- [ ] Review feedback incorporated (2 points)
- [ ] Final verification completed (2 points)
Total Score: [Sum of all categories] / 50
Minimum Required Score: 40/50 (80%)
```
## 📈 QUALITY THRESHOLDS
```mermaid
graph TD
subgraph "QUALITY GATES"
T1["Minimum<br>40/50 (80%)"]
T2["Target<br>45/50 (90%)"]
T3["Excellent<br>48/50 (96%)"]
end
Score["Quality<br>Score"] --> Check{"Meets<br>Threshold?"}
Check -->|"< 80%"| Block["⛔ BLOCKED<br>Improvements Required"]
Check -->|"≥ 80%"| Pass["✓ PASSED<br>Can Proceed"]
style T1 fill:#4dbb5f,stroke:#36873f,color:white
style T2 fill:#ffa64d,stroke:#cc7a30,color:white
style T3 fill:#d94dbb,stroke:#a3378a,color:white
style Score fill:#4dbbbb,stroke:#368787,color:white
style Check fill:#d971ff,stroke:#a33bc2,color:white
```
## 🎯 METRIC EVALUATION PROCESS
```mermaid
graph TD
Start["Start<br>Evaluation"] --> Doc["1. Score<br>Documentation"]
Doc --> Dec["2. Assess<br>Decisions"]
Dec --> Opt["3. Review<br>Options"]
Opt --> Imp["4. Evaluate<br>Impact"]
Imp --> Ver["5. Verify<br>Completeness"]
Ver --> Total["Calculate<br>Total Score"]
Total --> Check{"Meets<br>Threshold?"}
Check -->|No| Return["Return for<br>Improvements"]
Check -->|Yes| Proceed["Proceed to<br>Next Phase"]
style Start fill:#4da6ff,stroke:#0066cc,color:white
style Doc fill:#ffa64d,stroke:#cc7a30,color:white
style Dec fill:#4dbb5f,stroke:#36873f,color:white
style Opt fill:#d94dbb,stroke:#a3378a,color:white
style Imp fill:#4dbbbb,stroke:#368787,color:white
style Ver fill:#d971ff,stroke:#a33bc2,color:white
```
## 📊 IMPROVEMENT RECOMMENDATIONS
For scores below threshold:
```markdown
## Documentation Quality Improvements
- Add clear problem statements
- Include specific objectives
- List all requirements
- Improve formatting
- Add cross-references
## Decision Coverage Improvements
- Identify missing decisions
- Document all decision points
- Map dependencies
- Add impact analysis
- Consider future implications
## Option Analysis Improvements
- Consider more alternatives
- Detail pros/cons
- Assess technical feasibility
- Estimate resource needs
- Identify risks
## Impact Assessment Improvements
- Document system impact
- Assess performance
- Address security
- Evaluate maintenance
- Analyze costs
## Verification Improvements
- Trace requirements
- Validate constraints
- Define test scenarios
- Incorporate feedback
- Complete verification
```
## ✅ METRICS VERIFICATION CHECKLIST
```markdown
## Pre-Review Verification
- [ ] All sections scored
- [ ] Calculations verified
- [ ] Supporting evidence attached
- [ ] Improvement areas identified
- [ ] Review feedback incorporated
## Final Metrics Verification
- [ ] Minimum score achieved
- [ ] All categories passed
- [ ] Documentation complete
- [ ] Improvements addressed
- [ ] Final approval obtained
```
## 🔄 DOCUMENT MANAGEMENT
```mermaid
graph TD
Current["Current Document"] --> Active["Active:<br>- creative-phase-metrics.md"]
Current --> Related["Related:<br>- creative-phase-enforcement.md<br>- creative-phase-architecture.md"]
style Current fill:#4da6ff,stroke:#0066cc,color:white
style Active fill:#4dbb5f,stroke:#36873f,color:white
style Related fill:#ffa64d,stroke:#cc7a30,color:white
```
@@ -0,0 +1,198 @@
---
description: Optimized file verification
globs: file-verification.mdc
alwaysApply: false
---
# OPTIMIZED FILE VERIFICATION SYSTEM
> **TL;DR:** This system efficiently verifies and creates required Memory Bank file structures using batch operations and platform-optimized commands.
## 🔍 OPTIMIZED FILE VERIFICATION WORKFLOW
```mermaid
graph TD
Start["Start File<br>Verification"] --> VerifyAll["Verify All<br>Required Components"]
VerifyAll --> MissingCheck{"Missing<br>Components?"}
MissingCheck -->|"Yes"| BatchCreate["Batch Create<br>All Missing Items"]
MissingCheck -->|"No"| Complete["Verification<br>Complete"]
BatchCreate --> Report["Generate<br>Verification Report"]
Report --> Complete
```
## 📋 OPTIMIZED DIRECTORY CREATION
```mermaid
graph TD
Start["Directory<br>Creation"] --> DetectOS["Detect Operating<br>System"]
DetectOS -->|"Windows"| WinCmd["Batch Create<br>Windows Command"]
DetectOS -->|"Mac/Linux"| UnixCmd["Batch Create<br>Unix Command"]
WinCmd & UnixCmd --> Verify["Verify<br>Creation Success"]
Verify --> Complete["Directory Setup<br>Complete"]
```
### Platform-Specific Commands
#### Windows (PowerShell)
```powershell
# Create all directories in one command
mkdir memory-bank, docs, docs\archive -ErrorAction SilentlyContinue
# Create all required files
$files = @(".cursorrules", "tasks.md",
"memory-bank\projectbrief.md",
"memory-bank\productContext.md",
"memory-bank\systemPatterns.md",
"memory-bank\techContext.md",
"memory-bank\activeContext.md",
"memory-bank\progress.md")
foreach ($file in $files) {
if (-not (Test-Path $file)) {
New-Item -Path $file -ItemType File -Force
}
}
```
#### Mac/Linux (Bash)
```bash
# Create all directories in one command
mkdir -p memory-bank docs/archive
# Create all required files
touch .cursorrules tasks.md \
memory-bank/projectbrief.md \
memory-bank/productContext.md \
memory-bank/systemPatterns.md \
memory-bank/techContext.md \
memory-bank/activeContext.md \
memory-bank/progress.md
```
## 📝 STREAMLINED VERIFICATION PROCESS
Instead of checking each component separately, perform batch verification:
```powershell
# Windows - PowerShell
$requiredDirs = @("memory-bank", "docs", "docs\archive")
$requiredFiles = @(".cursorrules", "tasks.md")
$mbFiles = @("projectbrief.md", "productContext.md", "systemPatterns.md",
"techContext.md", "activeContext.md", "progress.md")
$missingDirs = $requiredDirs | Where-Object { -not (Test-Path $_) -or -not (Test-Path $_ -PathType Container) }
$missingFiles = $requiredFiles | Where-Object { -not (Test-Path $_) -or (Test-Path $_ -PathType Container) }
$missingMBFiles = $mbFiles | ForEach-Object { "memory-bank\$_" } |
Where-Object { -not (Test-Path $_) -or (Test-Path $_ -PathType Container) }
if ($missingDirs.Count -eq 0 -and $missingFiles.Count -eq 0 -and $missingMBFiles.Count -eq 0) {
Write-Output "✓ All required components verified"
} else {
# Create all missing items at once
if ($missingDirs.Count -gt 0) {
$missingDirs | ForEach-Object { mkdir $_ -Force }
}
if ($missingFiles.Count -gt 0 -or $missingMBFiles.Count -gt 0) {
$allMissingFiles = $missingFiles + $missingMBFiles
$allMissingFiles | ForEach-Object { New-Item -Path $_ -ItemType File -Force }
}
}
```
## 📝 TEMPLATE INITIALIZATION
Optimize template creation with a single script:
```powershell
# Windows - PowerShell
$templates = @{
"tasks.md" = @"
# Memory Bank: Tasks
## Current Task
[Task not yet defined]
## Status
- [ ] Task definition
- [ ] Implementation plan
- [ ] Execution
- [ ] Documentation
## Requirements
[No requirements defined yet]
"@
"memory-bank\activeContext.md" = @"
# Memory Bank: Active Context
## Current Focus
[No active focus defined]
## Status
[No status defined]
## Latest Changes
[No changes recorded]
"@
# Add other templates here
}
foreach ($file in $templates.Keys) {
if (Test-Path $file) {
Set-Content -Path $file -Value $templates[$file]
}
}
```
## 🔍 PERFORMANCE OPTIMIZATION BEST PRACTICES
1. **Batch Operations**: Always use batch operations instead of individual commands
```
# GOOD: Create all directories at once
mkdir memory-bank docs docs\archive
# BAD: Create directories one at a time
mkdir memory-bank
mkdir docs
mkdir docs\archive
```
2. **Pre-Check Optimization**: Check all requirements first, then create only what's missing
```
# First check what's missing
$missingItems = ...
# Then create only what's missing
if ($missingItems) { ... }
```
3. **Error Handling**: Include error handling in all commands
```
mkdir memory-bank, docs, docs\archive -ErrorAction SilentlyContinue
```
4. **Platform Adaptation**: Auto-detect platform and use appropriate commands
```
if ($IsWindows) {
# Windows commands
} else {
# Unix commands
}
```
5. **One-Pass Verification**: Verify directory structure in a single pass
```
$requiredPaths = @("memory-bank", "docs", "docs\archive", ".cursorrules", "tasks.md")
$missingPaths = $requiredPaths | Where-Object { -not (Test-Path $_) }
```
## 📝 VERIFICATION REPORT FORMAT
```
✅ VERIFICATION COMPLETE
- Created directories: [list]
- Created files: [list]
- All components verified
Memory Bank system ready for use.
```
@@ -0,0 +1,271 @@
---
description: Hierarchical rule loading system for optimized token usage
globs: "**/rule-loading*/**", "**/optimization*/**"
alwaysApply: false
---
# HIERARCHICAL RULE LOADING SYSTEM
> **TL;DR:** This rule implements an optimized loading system that only loads necessary rules based on context, complexity level, and current phase to maximize token efficiency.
## 🧠 HIERARCHICAL RULE STRUCTURE
```mermaid
graph TD
Root["Root Rules"] --> Core["Core Rules<br>(Always Loaded)"]
Root --> Common["Common Rules<br>(Mode Independent)"]
Root --> Mode["Mode-Specific<br>Rules"]
Root --> Level["Complexity Level<br>Rules"]
Core --> Platform["Platform<br>Detection"]
Core --> File["File<br>Operations"]
Core --> Transition["Mode<br>Transitions"]
Mode --> VAN["VAN Mode<br>Rules"]
Mode --> PLAN["PLAN Mode<br>Rules"]
Mode --> CREATIVE["CREATIVE Mode<br>Rules"]
Mode --> BUILD["BUILD Mode<br>Rules"]
Mode --> REFLECT["REFLECT Mode<br>Rules"]
Level --> Level1["Level 1<br>Rules"]
Level --> Level2["Level 2<br>Rules"]
Level --> Level3["Level 3<br>Rules"]
Level --> Level4["Level 4<br>Rules"]
style Root fill:#4da6ff,stroke:#0066cc,color:white
style Core fill:#ffa64d,stroke:#cc7a30,color:white
style Common fill:#4dbb5f,stroke:#36873f,color:white
style Mode fill:#d94dbb,stroke:#a3378a,color:white
style Level fill:#4dbbbb,stroke:#368787,color:white
```
## 📊 RULE LOADING PROTOCOL
```mermaid
sequenceDiagram
participant User
participant LoadManager
participant RuleCache
participant FileSystem
User->>LoadManager: Request mode activation
LoadManager->>RuleCache: Check cached core rules
RuleCache-->>LoadManager: Return cached rules if available
LoadManager->>FileSystem: Load essential mode rules
FileSystem-->>LoadManager: Return essential rules
LoadManager->>LoadManager: Register lazy loaders for specialized rules
LoadManager->>User: Return initialized mode
User->>LoadManager: Request specialized functionality
LoadManager->>RuleCache: Check specialized rule cache
RuleCache-->>LoadManager: Return cached rule if available
alt Rule not in cache
LoadManager->>FileSystem: Load specialized rule
FileSystem-->>LoadManager: Return specialized rule
LoadManager->>RuleCache: Cache specialized rule
end
LoadManager->>User: Execute specialized functionality
```
## 🔄 RULE LOADING IMPLEMENTATION
```javascript
// Pseudocode for hierarchical rule loading
class RuleLoadManager {
constructor() {
this.cache = {
core: {},
common: {},
mode: {},
level: {}
};
this.lazyLoaders = {};
}
// Initialize a mode with only essential rules
initializeMode(modeName, complexityLevel) {
// Always load core rules
this.loadCoreRules();
// Load common rules
this.loadCommonRules();
// Load essential mode-specific rules
this.loadEssentialModeRules(modeName);
// Load complexity level rules
this.loadComplexityRules(complexityLevel);
// Register lazy loaders for specialized functionality
this.registerLazyLoaders(modeName, complexityLevel);
return {
modeName,
complexityLevel,
status: "initialized"
};
}
// Load only when specialized functionality is needed
loadSpecializedRule(ruleType) {
if (this.lazyLoaders[ruleType]) {
if (!this.cache.specialized[ruleType]) {
const rule = this.lazyLoaders[ruleType]();
this.cache.specialized[ruleType] = rule;
}
return this.cache.specialized[ruleType];
}
return null;
}
// Register specialized rule loaders based on mode and complexity
registerLazyLoaders(modeName, complexityLevel) {
// Clear existing lazy loaders
this.lazyLoaders = {};
// Register mode-specific lazy loaders
if (modeName === "CREATIVE") {
this.lazyLoaders["architecture"] = () => this.loadRule("creative-phase-architecture.mdc");
this.lazyLoaders["algorithm"] = () => this.loadRule("creative-phase-algorithm.mdc");
this.lazyLoaders["uiux"] = () => this.loadRule("creative-phase-uiux.mdc");
} else if (modeName === "BUILD") {
this.lazyLoaders["testing"] = () => this.loadRule("implementation-testing.mdc");
this.lazyLoaders["deployment"] = () => this.loadRule("implementation-deployment.mdc");
}
// Register complexity-specific lazy loaders
if (complexityLevel >= 3) {
this.lazyLoaders["comprehensive-planning"] = () => this.loadRule("planning-comprehensive.mdc");
this.lazyLoaders["advanced-verification"] = () => this.loadRule("verification-advanced.mdc");
}
}
}
```
## 📋 RULE DEPENDENCY MAP
```mermaid
graph TD
Main["main.mdc"] --> Core1["platform-awareness.mdc"]
Main --> Core2["file-verification.mdc"]
Main --> Core3["command-execution.mdc"]
subgraph "VAN Mode"
VanMap["van-mode-map.mdc"] --> Van1["van-complexity-determination.mdc"]
VanMap --> Van2["van-file-verification.mdc"]
VanMap --> Van3["van-platform-detection.mdc"]
end
subgraph "PLAN Mode"
PlanMap["plan-mode-map.mdc"] --> Plan1["task-tracking-basic.mdc"]
PlanMap --> Plan2["planning-comprehensive.mdc"]
end
subgraph "CREATIVE Mode"
CreativeMap["creative-mode-map.mdc"] --> Creative1["creative-phase-enforcement.mdc"]
CreativeMap --> Creative2["creative-phase-metrics.mdc"]
Creative1 & Creative2 -.-> CreativeSpecialized["Specialized Creative Rules"]
CreativeSpecialized --> CArch["creative-phase-architecture.mdc"]
CreativeSpecialized --> CAlgo["creative-phase-algorithm.mdc"]
CreativeSpecialized --> CUIUX["creative-phase-uiux.mdc"]
end
subgraph "BUILD Mode"
BuildMap["build-mode-map.mdc"] --> Impl1["implementation-guide.mdc"]
BuildMap --> Impl2["testing-strategy.mdc"]
end
```
## 🔍 MODE-SPECIFIC RULE LOADING
### VAN Mode Essential Rules
```markdown
- main.mdc (Core)
- platform-awareness.mdc (Core)
- file-verification.mdc (Core)
- van-mode-map.mdc (Mode)
```
### PLAN Mode Essential Rules
```markdown
- main.mdc (Core)
- plan-mode-map.mdc (Mode)
- task-tracking-[complexity].mdc (Level)
```
### CREATIVE Mode Essential Rules
```markdown
- main.mdc (Core)
- creative-mode-map.mdc (Mode)
- creative-phase-enforcement.mdc (Mode)
```
### CREATIVE Mode Specialized Rules (Lazy Loaded)
```markdown
- creative-phase-architecture.mdc (Specialized)
- creative-phase-algorithm.mdc (Specialized)
- creative-phase-uiux.mdc (Specialized)
```
### BUILD Mode Essential Rules
```markdown
- main.mdc (Core)
- command-execution.mdc (Core)
- build-mode-map.mdc (Mode)
```
## 🚀 IMPLEMENTATION BENEFITS
The hierarchical loading system provides:
1. **Reduced Initial Loading**: Only essential rules loaded at start (~70% token reduction)
2. **Cached Core Rules**: Rules shared between modes are cached
3. **Specialized Rule Loading**: Specialized rules loaded only when needed
4. **Complexity-Based Loading**: Only load rules appropriate for task complexity
## 📈 TOKEN USAGE COMPARISON
| Approach | Initial Tokens | Specialized Tokens | Total Tokens |
|----------|---------------|-------------------|--------------|
| Original System | ~70,000 | Included in initial | ~70,000 |
| Hierarchical System | ~15,000 | ~10,000 (on demand) | ~25,000 |
| **Token Reduction** | **~55,000 (78%)** | **N/A** | **~45,000 (64%)** |
## 🔄 USAGE EXAMPLE
### Example: Creative Phase with Architecture Rule
```javascript
// Initialize the CREATIVE mode with only essential rules
const mode = ruleManager.initializeMode("CREATIVE", 3);
// Core and essential mode rules are loaded
// Architecture rules are NOT loaded yet
// Later, when architecture design is needed:
const architectureRule = ruleManager.loadSpecializedRule("architecture");
// Now the architecture rule is loaded and cached
```
## 🧪 RULE LOADING VERIFICATION
To ensure the rule loading system is working optimally:
```markdown
## Rule Loading Verification
- Core Rules: [Loaded]
- Mode-Essential Rules: [Loaded]
- Complexity-Level Rules: [Loaded]
- Specialized Rules: [Not Loaded]
Current Token Usage: [X] tokens
Potential Token Savings: [Y] tokens
```
This hierarchical approach ensures optimal token usage while maintaining all functionality.
@@ -0,0 +1,23 @@
---
description: Defines canonical paths for core Memory Bank files.
globs: memory-bank-paths.mdc
alwaysApply: true
---
# CORE MEMORY BANK FILE LOCATIONS
**CRITICAL:** All core Memory Bank files reside within the `memory-bank/` directory at the project root. Do NOT create or modify these files outside this directory unless explicitly instructed for archiving purposes.
* **Tasks File:** `memory-bank/tasks.md` - This file is used for active, in-progress task tracking, detailing steps, checklists, and component lists. Its content, particularly the detailed checklists, is merged into the main archive document for the task upon completion. After archival, `tasks.md` is cleared to be ready for the next task. It is an ephemeral working document during a task's lifecycle, with its persistent record captured in the task's archive file.
* **Active Context File:** `memory-bank/activeContext.md`
* **Progress File:** `memory-bank/progress.md`
* **Project Brief File:** `memory-bank/projectbrief.md`
* **Product Context File:** `memory-bank/productContext.md`
* **System Patterns File:** `memory-bank/systemPatterns.md`
* **Tech Context File:** `memory-bank/techContext.md`
* **Style Guide File:** `memory-bank/style-guide.md`
* **Creative Phase Docs:** `memory-bank/creative/creative-[feature_name].md`
* **Reflection Docs:** `memory-bank/reflection/reflection-[task_id].md`
* **Archive Directory:** `memory-bank/archive/archive-[task_id].md`
**Verification Mandate:** Before any `create_file` or `edit_file` operation on these core files, verify the path starts with `memory-bank/`. If attempting to create a new core file (e.g., `tasks.md` at the start of a project), ensure it is created at `memory-bank/tasks.md`.
@@ -0,0 +1,361 @@
---
description: Optimized mode transition protocol
globs: "**/mode-transition*/**", "**/context-preservation*/**"
alwaysApply: false
---
# MODE TRANSITION OPTIMIZATION
> **TL;DR:** This file implements optimized mode transitions to preserve context efficiently between different phases of the Memory Bank system.
## 🔄 UNIFIED CONTEXT TRANSFER PROTOCOL
```mermaid
graph TD
Start["Mode A"] --> Create["Create Context<br>Summary Document"]
Create --> Store["Store Critical<br>Context Data"]
Store --> Transition["Transition<br>to Mode B"]
Transition --> Verify["Verify Context<br>Availability"]
Verify --> Load["Load Relevant<br>Context Data"]
Load --> Continue["Continue in<br>Mode B"]
style Start fill:#4da6ff,stroke:#0066cc,color:white
style Create fill:#ffa64d,stroke:#cc7a30,color:white
style Store fill:#4dbb5f,stroke:#36873f,color:white
style Transition fill:#d94dbb,stroke:#a3378a,color:white
style Verify fill:#4dbbbb,stroke:#368787,color:white
style Load fill:#d971ff,stroke:#a33bc2,color:white
style Continue fill:#ff71c2,stroke:#c23b8a,color:white
```
## 📊 CONTEXT TRANSITION DOCUMENT
Create a standardized transition document when switching modes:
```markdown
# MODE TRANSITION: [Source Mode] → [Target Mode]
## Context Summary
- Task: [Task name/description]
- Complexity: Level [1-4]
- Current Phase: [Phase name]
- Progress: [Percentage or status]
## Key Decisions
- [Decision 1]: [Brief summary]
- [Decision 2]: [Brief summary]
- [Decision 3]: [Brief summary]
## Critical Context
- [Context item 1]: [Value/status]
- [Context item 2]: [Value/status]
- [Context item 3]: [Value/status]
## Next Steps
1. [Next step 1]
2. [Next step 2]
3. [Next step 3]
## Resource Pointers
- [Resource 1]: [Location]
- [Resource 2]: [Location]
- [Resource 3]: [Location]
```
## 🔍 MODE-SPECIFIC TRANSITION HANDLERS
### VAN → PLAN Transition
```markdown
### VAN → PLAN
- Context preserved: Complexity level, platform detection, file structure
- Files transferred: tasks.md (initialized), activeContext.md (initialized)
- Rule optimization: Pre-load planning rules based on complexity level
```
### PLAN → CREATIVE Transition
```markdown
### PLAN → CREATIVE
- Context preserved: Task requirements, component list, creative phase flags
- Files transferred: tasks.md (updated with plan), creative phase components list
- Rule optimization: Only load creative templates for identified components
```
### CREATIVE → BUILD Transition
```markdown
### CREATIVE → BUILD
- Context preserved: Design decisions, implementation guidelines, requirements
- Files transferred: tasks.md, design documents, implementation checklist
- Rule optimization: Pre-load implementation templates based on design decisions
```
### BUILD → REFLECT Transition
```markdown
### BUILD → REFLECT
- Context preserved: Implementation status, challenges encountered, decisions
- Files transferred: tasks.md, progress.md, implementation notes
- Rule optimization: Load reflection templates based on completion status
```
## 🧠 HIERARCHICAL RULE CACHING
Implement rule caching to avoid redundant loading:
```javascript
// Pseudocode for rule caching
const ruleCache = {
core: {}, // Core rules shared across modes
van: {},
plan: {},
creative: {},
build: {},
reflect: {},
archive: {}
};
// Check cache before loading
function loadRule(rulePath) {
const cacheKey = getCacheKey(rulePath);
const category = getCategoryFromPath(rulePath);
if (ruleCache[category][cacheKey]) {
return ruleCache[category][cacheKey];
}
const ruleContent = readRuleFromFile(rulePath);
ruleCache[category][cacheKey] = ruleContent;
return ruleContent;
}
// Only invalidate specific rules when needed
function invalidateRule(rulePath) {
const cacheKey = getCacheKey(rulePath);
const category = getCategoryFromPath(rulePath);
if (ruleCache[category][cacheKey]) {
delete ruleCache[category][cacheKey];
}
}
```
## ⚡ DIFFERENTIAL MEMORY BANK UPDATES
```mermaid
graph TD
Start["Memory Bank<br>Update Request"] --> Check{"File<br>Changed?"}
Check -->|"No"| Skip["Skip Update<br>(No Changes)"]
Check -->|"Yes"| Changed{"Specific<br>Section Changed?"}
Changed -->|"No"| Full["Full File<br>Update"]
Changed -->|"Yes"| Partial["Partial<br>Update Only"]
style Start fill:#4da6ff,stroke:#0066cc,color:white
style Check fill:#ffa64d,stroke:#cc7a30,color:white
style Skip fill:#4dbb5f,stroke:#36873f,color:white
style Changed fill:#d94dbb,stroke:#a3378a,color:white
style Full fill:#4dbbbb,stroke:#368787,color:white
style Partial fill:#d971ff,stroke:#a33bc2,color:white
```
Implement a more efficient update mechanism:
```javascript
// Pseudocode for differential updates
function updateMemoryBankFile(filePath, newContent) {
// Read existing content
const currentContent = readFile(filePath);
// Skip if no changes
if (currentContent === newContent) {
return "No changes detected, update skipped";
}
// Check if we can do a partial update
const sections = parseIntoSections(currentContent);
const newSections = parseIntoSections(newContent);
let updatedContent = currentContent;
let updatedSections = 0;
// Only update changed sections
for (const [sectionName, sectionContent] of Object.entries(newSections)) {
if (!sections[sectionName] || sections[sectionName] !== sectionContent) {
updatedContent = replaceSection(updatedContent, sectionName, sectionContent);
updatedSections++;
}
}
// Write updated content
writeFile(filePath, updatedContent);
return `Updated ${updatedSections} section(s) in ${filePath}`;
}
```
## 🔗 CREATIVE TO BUILD BRIDGE
Special handling for the critical Creative → Build transition:
```markdown
## CREATIVE → BUILD BRIDGE
### Design Decision Summary
Automatically generated summary of all creative phase decisions:
```json
{
"components": [
{
"name": "ComponentA",
"decision": "Approach X selected",
"rationale": "Best performance characteristics",
"implementation_notes": [
"Use X library",
"Implement caching",
"Add error handling"
]
},
{
"name": "ComponentB",
"decision": "Custom solution",
"rationale": "Unique requirements",
"implementation_notes": [
"Build from scratch",
"Modular architecture",
"Unit tests required"
]
}
]
}
```
### Implementation Verification Checklist
Automatically generated verification checklist:
```markdown
# Implementation Readiness Checklist
- [ ] Design decisions available for all components
- [ ] Implementation notes provided for each decision
- [ ] Dependencies clearly identified
- [ ] Order of implementation determined
- [ ] Required libraries/frameworks documented
- [ ] Potential challenges identified
```
## 🚀 ADAPTIVE MODE LOADING
Implement progressive mode loading to optimize context:
```javascript
// Pseudocode for adaptive mode loading
function loadMode(modeName, taskComplexity) {
// Always load core rules
loadCoreRules();
// Load complexity-appropriate rules
loadComplexityRules(taskComplexity);
// Load mode-specific essential rules
loadModeEssentialRules(modeName);
// Only load specialized rules as needed
registerLazyLoadHandlers(modeName, taskComplexity);
}
function registerLazyLoadHandlers(modeName, taskComplexity) {
// Register handlers to load additional rules only when needed
if (modeName === "CREATIVE") {
registerHandler("architecture", () => loadRule("creative-phase-architecture.mdc"));
registerHandler("algorithm", () => loadRule("creative-phase-algorithm.mdc"));
registerHandler("uiux", () => loadRule("creative-phase-uiux.mdc"));
}
// Similar patterns for other specialized rule types
}
```
## ✅ MODE TRANSITION EXAMPLES
### Example: PLAN → CREATIVE Transition
When transitioning from PLAN to CREATIVE mode:
```markdown
# MODE TRANSITION: PLAN → CREATIVE
## Context Summary
- Task: Implement user authentication system
- Complexity: Level 3
- Current Phase: Planning completed
- Progress: 35% (Planning: 100%, Creative: 0%, Implement: 0%)
## Key Decisions
- Authentication: Requires exploration of options (JWT vs Sessions)
- User Management: Will use existing database schema
- Authorization: Role-based access control selected
## Critical Context
- Components for creative phase: Authentication mechanism, Session management
- Dependencies: User database, Authorization system
- Constraints: Must support SSO, Performance requirements
## Next Steps
1. Explore authentication options (JWT, Sessions, OAuth)
2. Design session management approach
3. Document implementation guidelines
## Resource Pointers
- Planning document: tasks.md (section 3)
- Requirements: activeContext.md
- Reference architecture: docs/system-architecture.md
```
### Example: CREATIVE → BUILD Transition
When transitioning from CREATIVE to BUILD mode:
```markdown
# MODE TRANSITION: CREATIVE → BUILD
## Context Summary
- Task: Implement user authentication system
- Complexity: Level 3
- Current Phase: Creative completed
- Progress: 70% (Planning: 100%, Creative: 100%, Implement: 0%)
## Key Decisions
- Authentication: JWT-based approach selected
- Token Storage: Secure HttpOnly cookies with CSRF protection
- Refresh Strategy: Silent refresh with sliding expiration
## Critical Context
- Implementation order: Auth API endpoints, Middleware, Client integration
- Testing requirements: Unit tests for JWT validation, Integration tests for auth flow
- Security considerations: XSS protection, CSRF mitigation, Rate limiting
## Next Steps
1. Implement JWT generation and validation
2. Create authentication middleware
3. Build user login/logout endpoints
4. Implement client-side auth integration
## Resource Pointers
- Creative document: creative-auth-decisions.md
- API specifications: api-spec.yaml
- Security requirements: security-policy.md
```
## 🔄 IMPLEMENTATION BENEFITS
This optimization provides:
1. Reduced token usage during mode transitions (~40% reduction)
2. Better context preservation between modes
3. Improved efficiency through rule caching
4. Targeted loading of only necessary rules
5. Optimized memory bank updates
6. Clear transition documents that preserve critical context
@@ -0,0 +1,321 @@
---
description: Integration hub for Memory Bank optimizations
globs: "**/optimization*/**", "**/integration*/**"
alwaysApply: false
---
# MEMORY BANK OPTIMIZATION INTEGRATION
> **TL;DR:** This file serves as the integration point for all Memory Bank optimizations, coordinating the various optimization components to work seamlessly together.
## 🔄 OPTIMIZATION INTEGRATION FLOW
```mermaid
graph TD
Start["Memory Bank<br>Initialization"] --> HRL["Hierarchical<br>Rule Loading"]
HRL --> ACM["Adaptive<br>Complexity Model"]
ACM --> DCM["Dynamic<br>Context Management"]
DCM --> TMO["Transition<br>Optimization"]
subgraph "Level-Specific Optimizations"
L1["Level 1<br>Optimizations"]
L2["Level 2<br>Optimizations"]
L3["Level 3<br>Optimizations"]
L4["Level 4<br>Optimizations"]
end
ACM --> L1 & L2 & L3 & L4
L1 & L2 & L3 & L4 --> CPO["Creative Phase<br>Optimization"]
CPO --> PDO["Progressive<br>Documentation"]
TMO --> PDO
PDO --> MBO["Memory Bank<br>Optimization"]
style Start fill:#4da6ff,stroke:#0066cc,color:white
style HRL fill:#ffa64d,stroke:#cc7a30,color:white
style ACM fill:#4dbb5f,stroke:#36873f,color:white
style DCM fill:#d94dbb,stroke:#a3378a,color:white
style TMO fill:#4dbbbb,stroke:#368787,color:white
style CPO fill:#e699d9,stroke:#d94dbb,color:white
style PDO fill:#d971ff,stroke:#a33bc2,color:white
style MBO fill:#ff71c2,stroke:#c23b8a,color:white
```
## 📋 OPTIMIZATION COMPONENT REGISTRY
```javascript
// Optimization component registry pseudocode
const optimizationRegistry = {
// Core optimizations
hierarchicalRuleLoading: {
file: "Core/hierarchical-rule-loading.mdc",
dependencies: [],
priority: 1
},
adaptiveComplexityModel: {
file: "main.mdc",
dependencies: ["hierarchicalRuleLoading"],
priority: 2
},
modeTransitionOptimization: {
file: "Core/mode-transition-optimization.mdc",
dependencies: ["hierarchicalRuleLoading", "adaptiveComplexityModel"],
priority: 3
},
// Level-specific optimizations
level1Optimization: {
file: "Level1/optimized-workflow-level1.mdc",
dependencies: ["adaptiveComplexityModel"],
priority: 4
},
// Feature-specific optimizations
creativePhaseOptimization: {
file: "Phases/CreativePhase/optimized-creative-template.mdc",
dependencies: ["hierarchicalRuleLoading", "adaptiveComplexityModel"],
priority: 5
}
};
```
## 🔄 OPTIMIZATION INITIALIZATION SEQUENCE
```mermaid
sequenceDiagram
participant MB as Memory Bank
participant Reg as Optimization Registry
participant HRL as Hierarchical Rule Loading
participant ACM as Adaptive Complexity
participant TMO as Transition Optimization
participant CPO as Creative Phase Optimization
MB->>Reg: Request optimization initialization
Reg->>Reg: Sort optimizations by priority & dependencies
Reg->>HRL: Initialize (Priority 1)
HRL-->>Reg: Initialization complete
Reg->>ACM: Initialize (Priority 2)
ACM->>HRL: Request rule loading services
HRL-->>ACM: Provide rule loading
ACM-->>Reg: Initialization complete
Reg->>TMO: Initialize (Priority 3)
TMO->>HRL: Request rule loading services
TMO->>ACM: Request complexity model
HRL-->>TMO: Provide rule loading
ACM-->>TMO: Provide complexity model
TMO-->>Reg: Initialization complete
Reg->>CPO: Initialize (Final)
CPO->>HRL: Request rule loading services
CPO->>ACM: Request complexity model
CPO->>TMO: Request transition services
HRL-->>CPO: Provide rule loading
ACM-->>CPO: Provide complexity model
TMO-->>CPO: Provide transition services
CPO-->>Reg: Initialization complete
Reg-->>MB: All optimizations initialized
```
## 🔍 OPTIMIZATION CONFIGURATION
```javascript
// Optimization configuration pseudocode
const optimizationConfig = {
// Token optimization settings
tokenOptimization: {
enableHierarchicalLoading: true,
enableProgressiveDocumentation: true,
enableLazyRuleLoading: true,
enableContextPruning: true
},
// Context preservation settings
contextPreservation: {
preserveDesignDecisions: true,
preserveImplementationContext: true,
preserveUserPreferences: true,
contextCompressionLevel: "high" // none, low, medium, high
},
// Documentation optimization
documentationOptimization: {
level1DocumentationLevel: "minimal", // minimal, standard, comprehensive
level2DocumentationLevel: "standard",
level3DocumentationLevel: "comprehensive",
level4DocumentationLevel: "comprehensive",
enableProgressiveDisclosure: true,
enableTemplateCaching: true
}
};
```
## 📊 OPTIMIZATION MONITORING
```mermaid
graph TD
Monitor["Optimization<br>Monitor"] --> TokenUsage["Token Usage<br>Tracking"]
Monitor --> ContextEfficiency["Context<br>Efficiency"]
Monitor --> RuleLoadingStats["Rule Loading<br>Statistics"]
Monitor --> DocumentationSize["Documentation<br>Size"]
TokenUsage --> Dashboard["Optimization<br>Dashboard"]
ContextEfficiency --> Dashboard
RuleLoadingStats --> Dashboard
DocumentationSize --> Dashboard
Dashboard --> Feedback["Optimization<br>Feedback Loop"]
Feedback --> Config["Optimization<br>Configuration"]
Config --> Monitor
style Monitor fill:#4da6ff,stroke:#0066cc,color:white
style Dashboard fill:#ffa64d,stroke:#cc7a30,color:white
style Feedback fill:#4dbb5f,stroke:#36873f,color:white
style Config fill:#d94dbb,stroke:#a3378a,color:white
```
## 📈 OPTIMIZATION METRICS
```markdown
# Optimization Metrics
## Token Usage
- Core Rule Loading: [X] tokens
- Mode-Specific Rules: [Y] tokens
- Creative Phase Documentation: [Z] tokens
- Overall Token Reduction: [P]%
## Context Efficiency
- Context Utilization: [Q]%
- Context Waste: [R]%
- Effective Token Capacity: [S] tokens
## Rule Loading
- Rules Loaded: [T] / [U] (Total)
- Lazy-Loaded Rules: [V]
- Cached Rules: [W]
## Documentation
- Level 1 Documentation Size: [X] tokens
- Level 2 Documentation Size: [Y] tokens
- Level 3 Documentation Size: [Z] tokens
- Level 4 Documentation Size: [AA] tokens
```
## 🔄 INTEGRATION USAGE EXAMPLES
### Initializing All Optimizations
```javascript
// Pseudocode for initializing all optimizations
function initializeMemoryBankOptimizations() {
// Load optimization registry
const registry = loadOptimizationRegistry();
// Sort by priority and dependencies
const sortedOptimizations = sortOptimizations(registry);
// Initialize each optimization in order
for (const opt of sortedOptimizations) {
initializeOptimization(opt);
}
// Configure optimization parameters
configureOptimizations(loadOptimizationConfig());
// Start monitoring
initializeOptimizationMonitoring();
return "Memory Bank optimizations initialized";
}
```
### Using Optimized Creative Phase
```markdown
// Using the optimized creative phase with progressive documentation
// Initialize with minimal documentation
📌 CREATIVE PHASE START: Authentication System
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1️⃣ PROBLEM
Description: Design an authentication system for the application
Requirements: Secure, scalable, supports SSO, easy to maintain
Constraints: Must work with existing user database, <100ms response time
2️⃣ OPTIONS
Option A: JWT-based stateless auth
Option B: Session-based auth with Redis
Option C: OAuth2 implementation
// Progressively add detail as needed
3️⃣ ANALYSIS
| Criterion | JWT | Sessions | OAuth2 |
|-----------|-----|----------|--------|
| Security | ⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
| Scalability | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ |
| Complexity | ⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ |
// Focus on decision and implementation
4️⃣ DECISION
Selected: Option A: JWT-based auth with refresh tokens
Rationale: Best balance of performance and scalability
5️⃣ IMPLEMENTATION NOTES
- Use HS256 algorithm for token signing
- Implement short-lived access tokens (15min)
- Store token blacklist in Redis for revocation
```
## 🔄 MODE TRANSITION EXAMPLE
```markdown
// Optimized mode transition from CREATIVE to BUILD
# MODE TRANSITION: CREATIVE → BUILD
## Context Summary
- Task: Authentication system implementation
- Complexity: Level 3
- Decision: JWT-based auth with refresh tokens
## Key Context
- Security requirements verified
- Algorithm selection: HS256
- Token lifecycle: 15min access / 7 days refresh
## Next Steps
1. Implement JWT generation module
2. Create token validation middleware
3. Build refresh token handling
// Transition happens with preserved context
// BUILD mode continues with this context available
```
## 🔄 HIERARCHICAL RULE LOADING EXAMPLE
```javascript
// Pseudocode example of hierarchical rule loading
// Initial load - only core rules
loadCoreRules();
// Determine complexity
const complexity = determineComplexity();
// Load mode-specific essential rules
loadModeEssentialRules("CREATIVE");
// Register lazy loaders for specialized rules
registerLazyLoader("architecture", () => loadRule("creative-phase-architecture.mdc"));
registerLazyLoader("algorithm", () => loadRule("creative-phase-algorithm.mdc"));
registerLazyLoader("uiux", () => loadRule("creative-phase-uiux.mdc"));
// Later, when architecture design is needed:
const architectureRule = loadSpecializedRule("architecture");
// Architecture rule is now loaded only when needed
```
These integrated optimizations work seamlessly together to provide a significantly more efficient Memory Bank system while maintaining all functionality.
@@ -0,0 +1,71 @@
---
description: Platform detection and command adaptation for isolation-focused Memory Bank
globs: platform-awareness.mdc
alwaysApply: false
---
# PLATFORM AWARENESS SYSTEM
> **TL;DR:** This system detects the operating system, path format, and shell environment, then adapts commands accordingly to ensure cross-platform compatibility.
## 🔍 PLATFORM DETECTION PROCESS
```mermaid
graph TD
Start["Start Platform<br>Detection"] --> DetectOS["Detect OS<br>Environment"]
DetectOS --> Windows["Windows<br>Detection"]
DetectOS --> Mac["macOS<br>Detection"]
DetectOS --> Linux["Linux<br>Detection"]
Windows & Mac & Linux --> PathCheck["Path Separator<br>Detection"]
PathCheck --> CmdAdapt["Command<br>Adaptation"]
CmdAdapt --> ShellCheck["Shell Type<br>Detection"]
ShellCheck --> Complete["Platform Detection<br>Complete"]
```
## 📋 PLATFORM DETECTION IMPLEMENTATION
For reliable platform detection:
```
## Platform Detection Results
Operating System: [Windows/macOS/Linux]
Path Separator: [\ or /]
Shell Environment: [PowerShell/Bash/Zsh/Cmd]
Command Adaptation: [Required/Not Required]
Adapting commands for [detected platform]...
```
## 🔍 PATH FORMAT CONVERSION
When converting paths between formats:
```mermaid
sequenceDiagram
participant Input as Path Input
participant Detector as Format Detector
participant Converter as Format Converter
participant Output as Adapted Path
Input->>Detector: Raw Path
Detector->>Detector: Detect Current Format
Detector->>Converter: Path + Current Format
Converter->>Converter: Apply Target Format
Converter->>Output: Platform-Specific Path
```
## 📝 PLATFORM VERIFICATION CHECKLIST
```
✓ PLATFORM VERIFICATION
- Operating system correctly identified? [YES/NO]
- Path separator format detected? [YES/NO]
- Shell environment identified? [YES/NO]
- Command set adapted appropriately? [YES/NO]
- Path format handling configured? [YES/NO]
→ If all YES: Platform adaptation complete
→ If any NO: Run additional detection steps
```
@@ -0,0 +1,205 @@
---
description: Optimized Level 1 workflow for quick bug fixes with token efficiency
globs: "**/level1*/**", "**/quick*/**", "**/bugfix*/**"
alwaysApply: false
---
# OPTIMIZED LEVEL 1 WORKFLOW
> **TL;DR:** This streamlined workflow for Level 1 tasks (quick bug fixes) optimizes for speed and token efficiency while maintaining quality.
## 🔧 LEVEL 1 PROCESS FLOW
```mermaid
graph TD
Start["START LEVEL 1<br>QUICK FIX"] --> Analyze["1️⃣ ANALYZE<br>Understand issue"]
Analyze --> Build["2️⃣ BUILD<br>Fix the issue"]
Build --> Verify["3️⃣ VERIFY<br>Test the fix"]
Verify --> Document["4️⃣ DOCUMENT<br>Record solution"]
style Start fill:#4da6ff,stroke:#0066cc,color:white
style Analyze fill:#ffa64d,stroke:#cc7a30,color:white
style Build fill:#4dbb5f,stroke:#36873f,color:white
style Verify fill:#d94dbb,stroke:#a3378a,color:white
style Document fill:#4dbbbb,stroke:#368787,color:white
```
## 📝 CONSOLIDATED DOCUMENTATION
Level 1 tasks use a single-file approach to minimize context switching:
```markdown
# QUICK FIX: [Issue Name]
## Issue Summary
- Type: [Bug/Hotfix/Quick Enhancement]
- Priority: [Low/Medium/High/Critical]
- Reported by: [Name/System]
- Affected area: [Component/Feature]
## Analysis
- Root cause: [Brief description]
- Affected files: [List of files]
- Impact: [Scope of impact]
## Solution
- Approach: [Brief description]
- Changes made: [List of changes]
- Commands executed: [Key commands]
## Verification
- Testing: [How the fix was tested]
- Results: [Test results]
- Additional checks: [Any other verification]
## Status
- [x] Fix implemented
- [x] Tests passed
- [x] Documentation updated
```
## 🔄 MEMORY BANK UPDATE
Level 1 tasks use a simplified Memory Bank update with minimal overhead:
```markdown
## tasks.md Update (Level 1)
### Task: [Task Name]
- Status: Complete
- Implementation: [One-line summary]
- Link to fix: [File/line reference]
```
## ⚡ TOKEN-OPTIMIZED TEMPLATE
For maximum efficiency, Level 1 tasks can use this ultra-compact template:
```markdown
## 🔧 FIX: [Issue]
📌 Problem: [Brief description]
🔍 Cause: [Root cause]
🛠️ Solution: [Implemented fix]
✅ Tested: [Verification method]
```
## 🔄 AUTO-DOCUMENTATION HELPERS
Use these helpers to automatically generate documentation:
```javascript
function generateLevel1Documentation(issue, rootCause, solution, verification) {
return `## 🔧 FIX: ${issue}
📌 Problem: ${issue}
🔍 Cause: ${rootCause}
🛠️ Solution: ${solution}
✅ Tested: ${verification}`;
}
```
## 📊 QUICK TEMPLATES FOR COMMON ISSUES
### Performance Fix
```markdown
## 🔧 FIX: Performance issue in [component]
📌 Problem: Slow response times in [component]
🔍 Cause: Inefficient query/algorithm
🛠️ Solution: Optimized [specific optimization]
✅ Tested: Response time improved from [X]ms to [Y]ms
```
### Bug Fix
```markdown
## 🔧 FIX: Bug in [component]
📌 Problem: [Specific behavior] not working correctly
🔍 Cause: [Root cause analysis]
🛠️ Solution: Fixed by [implementation details]
✅ Tested: Verified with [test approach]
```
### Quick Enhancement
```markdown
## 🔧 ENHANCEMENT: [Feature]
📌 Request: Add [specific capability]
🛠️ Implementation: Added by [implementation details]
✅ Tested: Verified with [test approach]
```
## ✅ STREAMLINED VERIFICATION
Level 1 tasks use a minimal verification process:
```markdown
VERIFICATION:
[x] Fix implemented and tested
[x] No regressions introduced
[x] Documentation updated
```
## 🚀 CONSOLIDATED MEMORY BANK UPDATE
Optimize Memory Bank updates for Level 1 tasks by using a single operation:
```javascript
// Pseudocode for optimized Level 1 Memory Bank update
function updateLevel1MemoryBank(taskInfo) {
// Read current tasks.md
const tasksContent = readFile("tasks.md");
// Create minimal update
const updateBlock = `
### Task: ${taskInfo.name}
- Status: Complete
- Implementation: ${taskInfo.solution}
- Link to fix: ${taskInfo.fileReference}
`;
// Add update to tasks.md
const updatedContent = appendToSection(tasksContent, "Completed Tasks", updateBlock);
// Write in single operation
writeFile("tasks.md", updatedContent);
return "Memory Bank updated";
}
```
## 🔄 OPTIMIZED LEVEL 1 WORKFLOW EXAMPLE
```markdown
## 🔧 FIX: Login button not working on mobile devices
📌 Problem:
Users unable to log in on mobile devices, button appears but doesn't trigger authentication
🔍 Cause:
Event listener using desktop-specific event (mousedown instead of handling touch events)
🛠️ Solution:
Updated event handling to use event delegation and support both mouse and touch events:
```js
// Before:
loginButton.addEventListener('mousedown', handleLogin);
// After:
loginButton.addEventListener('mousedown', handleLogin);
loginButton.addEventListener('touchstart', handleLogin);
```
✅ Tested:
- Verified on iOS Safari and Android Chrome
- Login now works on all tested mobile devices
- No regression on desktop browsers
```
## ⚡ TOKEN EFFICIENCY BENEFITS
This optimized Level 1 workflow provides:
1. Reduced documentation overhead (70% reduction)
2. Consolidated Memory Bank updates (single operation vs. multiple)
3. Focused verification process (essential checks only)
4. Template-based approach for common scenarios
5. Streamlined workflow with fewer steps
The updated approach maintains all critical information while significantly reducing token usage.
@@ -0,0 +1,225 @@
---
description: Quick documentation approach for Level 1 Quick Bug Fix tasks
globs: "**/level1/**", "**/documentation/**"
alwaysApply: false
---
# QUICK DOCUMENTATION FOR LEVEL 1 TASKS
> **TL;DR:** This document outlines a quick documentation approach for Level 1 (Quick Bug Fix) tasks, ensuring that essential information is captured with minimal overhead.
## 🔍 QUICK DOCUMENTATION OVERVIEW
```mermaid
graph TD
FixComplete["Bug Fix<br>Complete"] --> Document["Document<br>Solution"]
Document --> UpdateTasks["Update<br>tasks.md"]
UpdateTasks --> MinimalUpdates["Make Minimal<br>Memory Bank Updates"]
MinimalUpdates --> CrossReference["Create Simple<br>Cross-References"]
CrossReference --> Complete["Documentation<br>Complete"]
```
Level 1 tasks require efficient documentation that captures essential information without unnecessary detail. This approach ensures that critical knowledge is preserved while maintaining speed and efficiency.
## 📋 DOCUMENTATION PRINCIPLES
1. **Conciseness**: Keep documentation brief but complete
2. **Focus**: Document only what's necessary to understand the fix
3. **Context**: Provide sufficient context to understand the issue
4. **Solution**: Clearly describe what was changed and why
5. **Findability**: Ensure the fix can be easily found later
## 📋 QUICK FIX DOCUMENTATION TEMPLATE
```markdown
# Quick Fix: [Issue Title]
## Issue
[Brief description of the problem - 1-2 sentences]
## Root Cause
[Concise description of what caused the issue - 1-2 sentences]
## Solution
[Brief description of the fix implemented - 2-3 sentences]
## Files Changed
- [File path 1]
- [File path 2]
## Verification
[How the fix was tested/verified - 1-2 sentences]
## Notes
[Any additional information that might be helpful - optional]
```
## 📋 TASKS.MD UPDATES
For Level 1 tasks, update tasks.md with this format:
```markdown
## Completed Bug Fixes
- [X] [Level 1] Fixed: [Issue title] (Completed: YYYY-MM-DD)
- Issue: [One-line description]
- Root Cause: [One-line description]
- Solution: [One-line description]
- Files: [File paths]
```
For in-progress tasks:
```markdown
## Bug Fixes in Progress
- [ ] [Level 1] Fix: [Issue title] (Est: XX mins)
- Issue: [One-line description]
- Location: [Component/file]
```
## 📋 MEMORY BANK UPDATES
For Level 1 tasks, make these minimal Memory Bank updates:
1. **tasks.md**:
- Update with fix details as shown above
- Mark task as complete
2. **activeContext.md** (only if relevant):
```markdown
## Recent Fixes
- [YYYY-MM-DD] Fixed [issue] in [component/file]. [One-line description of fix]
```
3. **progress.md** (only if significant):
```markdown
## Bug Fixes
- [YYYY-MM-DD] Fixed [issue] in [component/file].
```
Other Memory Bank files typically do not need updates for Level 1 tasks unless the fix reveals important system information.
## 📋 COMMON BUG CATEGORIES
Categorize bugs to improve documentation consistency:
1. **Logic Error**:
- Example: "Fixed incorrect conditional logic in user validation"
2. **UI/Display Issue**:
- Example: "Fixed misaligned button in mobile view"
3. **Performance Issue**:
- Example: "Fixed slow loading of user profile data"
4. **Data Handling Error**:
- Example: "Fixed incorrect parsing of date format"
5. **Configuration Issue**:
- Example: "Fixed incorrect environment variable setting"
## 📋 QUICK DOCUMENTATION PROCESS
Follow these steps for efficient documentation:
1. **Immediately After Fix**:
- Document while the fix is fresh in your mind
- Focus on what, why, and how
- Be specific about changes made
2. **Update Task Tracking**:
- Update tasks.md with fix details
- Use consistent format for easy reference
3. **Minimal Cross-References**:
- Create only essential cross-references
- Ensure fix can be found in the future
4. **Check Completeness**:
- Verify all essential information is captured
- Ensure another developer could understand the fix
## 📋 EXAMPLES: GOOD VS. INSUFFICIENT DOCUMENTATION
### ❌ Insufficient Documentation
```markdown
Fixed the login bug.
```
### ✅ Good Documentation
```markdown
# Quick Fix: User Login Failure with Special Characters
## Issue
Users with special characters in email addresses (e.g., +, %) couldn't log in.
## Root Cause
The email validation regex was incorrectly escaping special characters.
## Solution
Updated the email validation regex in AuthValidator.js to properly handle special characters according to RFC 5322.
## Files Changed
- src/utils/AuthValidator.js
## Verification
Tested login with various special characters in email addresses (test+user@example.com, user%123@example.com).
```
## 📋 DOCUMENTATION VERIFICATION CHECKLIST
```
✓ DOCUMENTATION VERIFICATION
- Issue clearly described? [YES/NO]
- Root cause identified? [YES/NO]
- Solution explained? [YES/NO]
- Files changed listed? [YES/NO]
- Verification method described? [YES/NO]
- tasks.md updated? [YES/NO]
- Memory Bank minimally updated? [YES/NO]
→ If all YES: Documentation complete
→ If any NO: Complete missing information
```
## 📋 MINIMAL MODE DOCUMENTATION
For minimal mode, use this ultra-compact format:
```
✓ FIX: [Issue title]
✓ CAUSE: [One-line root cause]
✓ SOLUTION: [One-line fix description]
✓ FILES: [File paths]
✓ VERIFIED: [How verified]
```
## 🔄 DOCUMENTATION INTEGRATION
Quick documentation integrates with other systems:
```mermaid
graph TD
QuickDoc["Quick Fix<br>Documentation"] --> TasksMD["tasks.md<br>Update"]
QuickDoc --> FixDetails["Fix Details<br>Documentation"]
TasksMD --> Tracking["Task<br>Tracking"]
FixDetails --> Knowledge["Knowledge<br>Preservation"]
Tracking & Knowledge --> Future["Future<br>Reference"]
```
## 🚨 DOCUMENTATION EFFICIENCY PRINCIPLE
Remember:
```
┌─────────────────────────────────────────────────────┐
│ Document ONLY what's needed to understand the fix. │
│ Focus on ESSENTIAL information that would help │
│ someone who encounters the same issue in the future.│
└─────────────────────────────────────────────────────┘
```
This ensures that Level 1 tasks are documented efficiently without unnecessary overhead while preserving critical knowledge.
@@ -0,0 +1,190 @@
---
description: Streamlined workflow for Level 1 Quick Bug Fix tasks
globs: "**/level1/**", "**/workflow/**"
alwaysApply: false
---
# STREAMLINED WORKFLOW FOR LEVEL 1 TASKS
> **TL;DR:** This document outlines a streamlined workflow for Level 1 (Quick Bug Fix) tasks, focusing on efficient problem resolution with minimal overhead while maintaining adequate documentation.
## 🔍 LEVEL 1 WORKFLOW OVERVIEW
```mermaid
graph LR
Init["1. INITIALIZATION"] --> Impl["2. IMPLEMENTATION"]
Impl --> Doc["3. DOCUMENTATION"]
%% Document connections for each phase
Init -.-> InitDocs["Quick setup<br>Issue understanding"]
Impl -.-> ImplDocs["Focused fix<br>Verify resolution"]
Doc -.-> DocDocs["Document solution<br>Update tracking"]
```
## 📋 WORKFLOW PHASES
### Phase 1: INITIALIZATION
```mermaid
graph TD
Start["Start Level 1 Task"] --> Identify["Identify<br>Issue"]
Identify --> Understand["Understand<br>Problem"]
Understand --> Setup["Quick<br>Environment Setup"]
Setup --> TaskEntry["Create Quick<br>Task Entry"]
TaskEntry --> InitComplete["Initialization<br>Complete"]
```
**Steps:**
1. Identify the specific issue to fix
2. Understand the problem and its impact
3. Set up environment for quick fix
4. Create minimal task entry in tasks.md
**Milestone Checkpoint:**
```
✓ INITIALIZATION CHECKPOINT
- Issue clearly identified? [YES/NO]
- Problem understood? [YES/NO]
- Environment set up? [YES/NO]
- Task entry created? [YES/NO]
→ If all YES: Proceed to Implementation
→ If any NO: Complete initialization steps
```
### Phase 2: IMPLEMENTATION
```mermaid
graph TD
Start["Begin<br>Implementation"] --> Locate["Locate<br>Issue Source"]
Locate --> Develop["Develop<br>Fix"]
Develop --> Test["Test<br>Solution"]
Test --> Verify["Verify<br>Resolution"]
Verify --> ImplComplete["Implementation<br>Complete"]
```
**Steps:**
1. Locate the source of the issue
2. Develop a targeted fix
3. Test the solution thoroughly
4. Verify that the issue is resolved
**Milestone Checkpoint:**
```
✓ IMPLEMENTATION CHECKPOINT
- Issue source located? [YES/NO]
- Fix developed? [YES/NO]
- Solution tested? [YES/NO]
- Resolution verified? [YES/NO]
→ If all YES: Proceed to Documentation
→ If any NO: Complete implementation steps
```
### Phase 3: DOCUMENTATION
```mermaid
graph TD
Start["Begin<br>Documentation"] --> Update["Update<br>tasks.md"]
Update --> Solution["Document<br>Solution"]
Solution --> References["Create Minimal<br>Cross-References"]
References --> NotifyStakeholders["Notify<br>Stakeholders"]
NotifyStakeholders --> DocComplete["Documentation<br>Complete"]
```
**Steps:**
1. Update tasks.md with fix details
2. Document the solution concisely
3. Create minimal cross-references
4. Notify stakeholders as needed
**Milestone Checkpoint:**
```
✓ DOCUMENTATION CHECKPOINT
- tasks.md updated? [YES/NO]
- Solution documented? [YES/NO]
- Cross-references created? [YES/NO]
- Stakeholders notified? [YES/NO]
→ If all YES: Task Complete
→ If any NO: Complete documentation steps
```
## 📋 TASK STRUCTURE IN TASKS.MD
For Level 1 tasks, use this minimal structure:
```markdown
## Bug Fixes in Progress
- [ ] [Level 1] Fix: [Bug description] (Est: XX mins)
## Completed Bug Fixes
- [X] [Level 1] Fixed: [Bug description] (Completed: YYYY-MM-DD)
- Issue: [Brief issue description]
- Solution: [Brief solution description]
- Files changed: [File paths]
```
## 📋 MEMORY BANK UPDATES
For Level 1 tasks, make minimal Memory Bank updates:
1. **tasks.md**: Update with fix details
2. **activeContext.md**: Brief mention of fix if relevant
3. **progress.md**: Add to list of completed fixes
## 📋 WORKFLOW VERIFICATION CHECKLIST
```
✓ FINAL WORKFLOW VERIFICATION
- Issue identified and understood? [YES/NO]
- Fix implemented and verified? [YES/NO]
- tasks.md updated? [YES/NO]
- Solution documented? [YES/NO]
- Memory Bank minimally updated? [YES/NO]
→ If all YES: Level 1 Task Successfully Completed
→ If any NO: Address outstanding items
```
## 📋 TASK ESCALATION
If during the Level 1 process you discover the task is more complex:
```
⚠️ TASK ESCALATION NEEDED
Current Level: Level 1
Recommended Level: Level [2/3/4]
Reason: [Brief explanation]
Would you like me to escalate this task to Level [2/3/4]?
```
Escalation indicators:
1. Fix requires changes to multiple components
2. Solution requires design decisions
3. Testing reveals broader issues
4. Fix impacts core functionality
## 🔄 INTEGRATION WITH MEMORY BANK
```mermaid
graph TD
Workflow["Level 1<br>Workflow"] --> TM["Update<br>tasks.md"]
Workflow --> AC["Minimal Update<br>activeContext.md"]
Workflow --> PM["Brief Update<br>progress.md"]
TM & AC & PM --> MB["Memory Bank<br>Integration"]
MB --> NextTask["Transition to<br>Next Task"]
```
## 🚨 EFFICIENCY PRINCIPLE
Remember:
```
┌─────────────────────────────────────────────────────┐
│ Level 1 workflow prioritizes SPEED and EFFICIENCY. │
│ Minimize process overhead while ensuring adequate │
│ documentation of the solution. │
└─────────────────────────────────────────────────────┘
```
@@ -0,0 +1,181 @@
---
description: Basic archiving approach for Level 2 Simple Enhancement tasks
globs: "**/level2/**", "**/archive/**", "**/completion/**"
alwaysApply: false
---
# BASIC ARCHIVING FOR LEVEL 2 TASKS
> **TL;DR:** This document outlines a basic archiving approach for Level 2 (Simple Enhancement) tasks, ensuring that completed work is properly documented and knowledge is preserved with minimal overhead.
## 🔍 ARCHIVING OVERVIEW
Even for Level 2 tasks, proper archiving ensures that completed work is documented and knowledge is preserved. This basic archiving approach provides sufficient structure while maintaining efficiency.
## 📋 ARCHIVING PRINCIPLES
1. **Completion**: Clearly document what was completed
2. **Context**: Preserve the context of the enhancement
3. **Knowledge**: Capture key insights and lessons
4. **Findability**: Make archived information easy to find
5. **References**: Create cross-references to related work
## 📋 BASIC ARCHIVE STRUCTURE
```markdown
# Enhancement Archive: [Feature Name]
## Summary
[Brief summary of the enhancement]
## Date Completed
YYYY-MM-DD
## Key Files Modified
- [File path 1]
- [File path 2]
- [File path 3]
## Requirements Addressed
- [Requirement 1]
- [Requirement 2]
- [Requirement 3]
## Implementation Details
[Brief description of how the enhancement was implemented]
## Testing Performed
- [Test 1]
- [Test 2]
- [Test 3]
## Lessons Learned
- [Lesson 1]
- [Lesson 2]
- [Lesson 3]
## Related Work
- [Link to related task/enhancement 1]
- [Link to related task/enhancement 2]
## Notes
[Any additional information or context]
```
## 📋 ARCHIVE LOCATION
Store archives in an organized structure:
```
docs/
└── archive/
└── enhancements/
└── YYYY-MM/
├── feature-name-1.md
└── feature-name-2.md
```
## 📋 ARCHIVING PROCESS
Follow these steps to archive a Level 2 task:
1. **Prepare Archive Content**:
- Gather all relevant information
- Fill in the archive template
- Include all key implementation details
2. **Cross-Reference Creation**:
- Update tasks.md with link to archive
- Add reference in progress.md
- Update activeContext.md with next focus
3. **File Creation and Storage**:
- Create appropriate directory if needed
- Save archive file with descriptive name
- Ensure file follows naming convention
4. **Final Verification**:
- Check archive for completeness
- Verify all cross-references
- Ensure all links are working
## 📋 CROSS-REFERENCE FORMAT
When creating cross-references:
1. **In tasks.md**:
```markdown
## Completed Enhancements
- [X] [Feature Name] (YYYY-MM-DD) - [Archive Link](../docs/archive/enhancements/YYYY-MM/feature-name.md)
```
2. **In progress.md**:
```markdown
## Completed Milestones
- [Feature Name] enhancement completed on YYYY-MM-DD. See [archive entry](../docs/archive/enhancements/YYYY-MM/feature-name.md).
```
3. **In activeContext.md**:
```markdown
## Recently Completed
- [Feature Name] enhancement is now complete. Archive: [link](../docs/archive/enhancements/YYYY-MM/feature-name.md)
## Current Focus
- Moving to [Next Task Name]
```
## 📋 ARCHIVING VERIFICATION CHECKLIST
```
✓ ARCHIVE VERIFICATION
- Archive content complete? [YES/NO]
- Archive properly stored? [YES/NO]
- Cross-references created? [YES/NO]
- tasks.md updated? [YES/NO]
- progress.md updated? [YES/NO]
- activeContext.md updated? [YES/NO]
→ If all YES: Archiving complete
→ If any NO: Complete archiving process
```
## 📋 MINIMAL MODE ARCHIVING
For minimal mode, use this format:
```
✓ ARCHIVE: [Feature Name]
✓ DATE: YYYY-MM-DD
✓ FILES: [Key files changed]
✓ SUMMARY: [One-sentence summary]
✓ LESSONS: [Key takeaway]
✓ REFS: [tasks.md, progress.md, activeContext.md]
```
## 🔄 INTEGRATION WITH MEMORY BANK
Archiving integrates with Memory Bank:
```mermaid
graph TD
Archive["Enhancement<br>Archive"] --> TasksUpdate["Update<br>tasks.md"]
Archive --> ProgressUpdate["Update<br>progress.md"]
Archive --> ContextUpdate["Update<br>activeContext.md"]
TasksUpdate & ProgressUpdate & ContextUpdate --> CrossLinks["Create<br>Cross-Links"]
CrossLinks --> Verify["Verify<br>References"]
```
## 🚨 KNOWLEDGE PRESERVATION PRINCIPLE
Remember:
```
┌─────────────────────────────────────────────────────┐
│ Archive files are a VALUABLE KNOWLEDGE RESOURCE. │
│ Take care to preserve insights and lessons that │
│ will benefit future work. │
└─────────────────────────────────────────────────────┘
```
This ensures that knowledge is preserved and can be referenced in the future.
@@ -0,0 +1,178 @@
---
description: Basic reflection format for Level 2 Simple Enhancement tasks
globs: "**/level2/**", "**/reflection/**"
alwaysApply: false
---
# BASIC REFLECTION FOR LEVEL 2 TASKS
> **TL;DR:** This document outlines a basic reflection approach for Level 2 (Simple Enhancement) tasks, ensuring that key insights and lessons are captured without unnecessary overhead.
## 🔍 REFLECTION OVERVIEW
Reflection is essential for improving future work, even for simpler Level 2 enhancements. This basic reflection approach focuses on key outcomes, challenges, and lessons learned while maintaining efficiency.
## 📋 REFLECTION PRINCIPLES
1. **Honesty**: Accurately represent successes and challenges
2. **Specificity**: Include concrete examples and observations
3. **Insight**: Go beyond surface observations to derive useful insights
4. **Improvement**: Focus on actionable takeaways for future work
5. **Efficiency**: Keep reflection concise and focused on key learnings
## 📋 BASIC REFLECTION STRUCTURE
```markdown
# Level 2 Enhancement Reflection: [Feature Name]
## Enhancement Summary
[Brief one-paragraph summary of the enhancement]
## What Went Well
- [Specific success point 1]
- [Specific success point 2]
- [Specific success point 3]
## Challenges Encountered
- [Specific challenge 1]
- [Specific challenge 2]
- [Specific challenge 3]
## Solutions Applied
- [Solution to challenge 1]
- [Solution to challenge 2]
- [Solution to challenge 3]
## Key Technical Insights
- [Technical insight 1]
- [Technical insight 2]
- [Technical insight 3]
## Process Insights
- [Process insight 1]
- [Process insight 2]
- [Process insight 3]
## Action Items for Future Work
- [Specific action item 1]
- [Specific action item 2]
- [Specific action item 3]
## Time Estimation Accuracy
- Estimated time: [X hours/days]
- Actual time: [Y hours/days]
- Variance: [Z%]
- Reason for variance: [Brief explanation]
```
## 📋 REFLECTION QUALITY
High-quality reflections for Level 2 tasks should:
1. **Provide specific examples** rather than vague statements
2. **Identify concrete takeaways** not general observations
3. **Connect challenges to solutions** with clear reasoning
4. **Analyze estimation accuracy** to improve future planning
5. **Generate actionable improvements** for future work
## 📋 REFLECTION PROCESS
Follow these steps for effective Level 2 task reflection:
1. **Schedule Reflection**:
- Allocate dedicated time for reflection
- Complete reflection within 24 hours of task completion
2. **Gather Information**:
- Review the original task requirements
- Examine implementation details
- Consider challenges encountered
- Review time tracking data
3. **Complete Template**:
- Fill in all sections of the reflection template
- Include specific, concrete examples
- Be honest about challenges
4. **Extract Insights**:
- Identify patterns in challenges
- Connect challenges to potential future improvements
- Consider process improvements
5. **Document Action Items**:
- Create specific, actionable improvements
- Link these to future tasks where applicable
6. **Store Reflection**:
- Save reflection with the task archive
- Add cross-references to relevant documents
## 📋 EXAMPLES: VAGUE VS. SPECIFIC ENTRIES
### ❌ Vague Entries (Insufficient)
- "The implementation went well."
- "We had some challenges with the code."
- "The feature works as expected."
### ✅ Specific Entries (Sufficient)
- "The modular approach allowed for easy integration with the existing codebase, specifically the clean separation between the UI layer and data processing logic."
- "Challenge: The state management became complex when handling multiple user interactions. Solution: Implemented a more structured reducer pattern with clear actions and state transitions."
- "Action Item: Create a reusable component for file selection that handles all the edge cases we encountered in this implementation."
## 📋 REFLECTION VERIFICATION CHECKLIST
```
✓ REFLECTION VERIFICATION
- All template sections completed? [YES/NO]
- Specific examples provided? [YES/NO]
- Challenges honestly addressed? [YES/NO]
- Concrete solutions documented? [YES/NO]
- Actionable insights generated? [YES/NO]
- Time estimation analyzed? [YES/NO]
→ If all YES: Reflection complete
→ If any NO: Improve reflection quality
```
## 📋 MINIMAL MODE REFLECTION
For minimal mode, use this format:
```
✓ REFLECTION: [Feature Name]
✓ WENT WELL: [Key success]
✓ CHALLENGE: [Key challenge]
✓ SOLUTION: [Key solution]
✓ INSIGHT: [Most important takeaway]
✓ ACTION: [Top priority action item]
✓ TIME: Est [X] vs. Actual [Y] ([Z%] variance)
```
## 🔄 INTEGRATION WITH MEMORY BANK
Reflection integrates with Memory Bank:
```mermaid
graph TD
Reflection["Enhancement<br>Reflection"] --> Archive["Add to<br>Archive"]
Reflection --> ProgressUpdate["Update<br>progress.md"]
Reflection --> ActionItems["Document<br>Action Items"]
ActionItems --> Tasks["Add to<br>tasks.md"]
Archive & ProgressUpdate & Tasks --> CrossLinks["Create<br>Cross-Links"]
```
## 🚨 CONTINUOUS IMPROVEMENT PRINCIPLE
Remember:
```
┌─────────────────────────────────────────────────────┐
│ Every reflection should produce at least ONE │
│ actionable improvement for future work. │
└─────────────────────────────────────────────────────┘
```
This ensures that reflection directly contributes to ongoing improvement of both the product and the process.
@@ -0,0 +1,188 @@
---
description: Basic task tracking for Level 2 Simple Enhancement tasks
globs: "**/level2/**", "**/tracking/**", "**/task/**"
alwaysApply: false
---
# BASIC TASK TRACKING FOR LEVEL 2
> **TL;DR:** This document outlines a streamlined task tracking approach for Level 2 (Simple Enhancement) tasks. It provides a balanced framework for managing task progress with minimal overhead.
## 🔍 TASK TRACKING OVERVIEW
Level 2 tasks require a more structured tracking approach than Level 1, but don't need the comprehensive tracking of higher-level tasks. This basic tracking system provides sufficient structure while maintaining efficiency.
## 📋 TASK TRACKING PRINCIPLES
1. **Clarity**: Tasks should be clearly defined
2. **Visibility**: Progress should be visible at a glance
3. **Structure**: Break work into logical subtasks
4. **Updates**: Keep progress regularly updated
5. **Completion**: Clearly mark when tasks are done
## 📋 TASK STRUCTURE FOR LEVEL 2
```markdown
## [Feature Name] Enhancement
**Status**: [Not Started/In Progress/Complete]
**Priority**: [High/Medium/Low]
**Estimated Effort**: [Small/Medium/Large]
### Description
[Brief description of the enhancement]
### Requirements
- [Requirement 1]
- [Requirement 2]
- [Requirement 3]
### Subtasks
- [ ] [Subtask 1]
- [ ] [Subtask 2]
- [ ] [Subtask 3]
### Dependencies
- [Dependency 1]
- [Dependency 2]
### Notes
[Any additional information or context]
```
## 📋 TASKS.MD ORGANIZATION
Organize tasks.md with these sections for Level 2 tasks:
```markdown
# Tasks
## Active Enhancements
- [Enhancement 1] - [Status]
- [Enhancement 2] - [Status]
## Enhancement Details
### [Enhancement 1]
[Task structure as above]
### [Enhancement 2]
[Task structure as above]
## Completed Enhancements
- [X] [Completed Enhancement 1] (YYYY-MM-DD)
- [X] [Completed Enhancement 2] (YYYY-MM-DD)
```
## 📋 UPDATING TASK STATUS
Update tasks using this process:
1. **Starting a Task**:
- Update Status to "In Progress"
- Add start date to Notes
2. **Progress Updates**:
- Check off subtasks as completed
- Add brief notes about progress
- Update any changed requirements
3. **Completing a Task**:
- Update Status to "Complete"
- Check off all subtasks
- Move to Completed Enhancements
- Add completion date
## 📋 SUBTASK MANAGEMENT
For Level 2 tasks, subtasks should:
1. Be actionable and specific
2. Represent approximately 30-60 minutes of work
3. Follow a logical sequence
4. Be updated as soon as completed
5. Include verification steps
Example of well-structured subtasks:
```markdown
### Subtasks
- [ ] Review existing implementation of related features
- [ ] Create draft UI design for new button
- [ ] Add HTML structure for new component
- [ ] Implement button functionality in JavaScript
- [ ] Add appropriate styling in CSS
- [ ] Add event handling
- [ ] Test on desktop browsers
- [ ] Test on mobile browsers
- [ ] Update user documentation
```
## 📋 PROGRESS VISUALIZATION
Use progress indicators to show status:
```markdown
### Progress
[###-------] 30% Complete
```
For subtasks:
```markdown
### Subtasks (3/10 Complete)
- [X] Subtask 1
- [X] Subtask 2
- [X] Subtask 3
- [ ] Subtask 4
- [ ] Subtask 5
```
## 📋 TRACKING VERIFICATION CHECKLIST
```
✓ TASK TRACKING VERIFICATION
- Task clearly defined? [YES/NO]
- Requirements listed? [YES/NO]
- Subtasks created? [YES/NO]
- Dependencies identified? [YES/NO]
- Status up-to-date? [YES/NO]
→ If all YES: Task tracking is adequate
→ If any NO: Update task tracking
```
## 📋 MINIMAL MODE TRACKING
For minimal mode, use this format:
```
✓ TASK: [Enhancement name]
✓ STATUS: [In Progress/Complete]
✓ SUBTASKS: [X/Y Complete]
✓ NEXT: [Next action]
```
## 🔄 INTEGRATION WITH MEMORY BANK
Task tracking integrates with Memory Bank:
```mermaid
graph TD
TasksFile["tasks.md"] --> Active["activeContext.md"]
TasksFile --> Progress["progress.md"]
Active -->|"Current focus"| TasksFile
Progress -->|"Completion status"| TasksFile
```
## 🚨 TASKS.MD PRIMACY PRINCIPLE
Remember:
```
┌─────────────────────────────────────────────────────┐
│ tasks.md is the SINGLE SOURCE OF TRUTH for ALL │
│ task tracking. ALL task updates MUST be reflected │
│ in tasks.md IMMEDIATELY. │
└─────────────────────────────────────────────────────┘
```
This ensures everyone has visibility into current task status at all times.
@@ -0,0 +1,289 @@
---
description: Basic workflow for Level 2 Simple Enhancement tasks
globs: "**/level2/**", "**/workflow/**"
alwaysApply: false
---
# WORKFLOW FOR LEVEL 2 TASKS
> **TL;DR:** This document outlines a structured yet efficient workflow for Level 2 (Simple Enhancement) tasks, including 6 key phases with milestone checkpoints and quality verification.
## 🔍 LEVEL 2 WORKFLOW OVERVIEW
```mermaid
graph LR
Init["1. INITIALIZATION"] --> Doc["2. DOCUMENTATION<br>SETUP"]
Doc --> Plan["3. TASK<br>PLANNING"]
Plan --> Impl["4. IMPLEMENTATION"]
Impl --> Reflect["5. REFLECTION"]
Reflect --> Archive["6. ARCHIVING"]
%% Document connections for each phase
Init -.-> InitDocs["INITIALIZATION"]
Doc -.-> DocDocs["DOCUMENTATION"]
Plan -.-> PlanDocs["PLANNING"]
Impl -.-> ImplDocs["IMPLEMENTATION"]
Reflect -.-> ReflectDocs["REFLECTION"]
Archive -.-> ArchiveDocs["ARCHIVING"]
```
Level 2 tasks involve simple enhancements that require a structured approach with moderate planning and documentation. This workflow provides the right balance of process and efficiency.
## 📋 WORKFLOW PHASES
### Phase 1: INITIALIZATION
```mermaid
graph TD
Start["Start Level 2 Task"] --> Platform{"Detect<br>Platform"}
Platform --> FileCheck["Critical File<br>Verification"]
FileCheck --> LoadStructure["Load Memory<br>Bank Structure"]
LoadStructure --> TaskCreation["Create Task<br>in tasks.md"]
TaskCreation --> SetupComplete["Initialization<br>Complete"]
```
**Steps:**
1. Platform detection
2. Critical file verification
3. Memory Bank structure loading
4. Task creation in tasks.md
5. Initial task scope definition
**Milestone Checkpoint:**
```
✓ INITIALIZATION CHECKPOINT
- Platform detected and configured? [YES/NO]
- Critical files verified? [YES/NO]
- Memory Bank loaded? [YES/NO]
- Task created in tasks.md? [YES/NO]
- Initial scope defined? [YES/NO]
→ If all YES: Proceed to Documentation Setup
→ If any NO: Complete initialization steps
```
### Phase 2: DOCUMENTATION SETUP
```mermaid
graph TD
Start["Begin Documentation<br>Setup"] --> LoadTemplate["Load Basic<br>Documentation Templates"]
LoadTemplate --> UpdateProject["Update<br>projectbrief.md"]
UpdateProject --> UpdateContext["Update<br>activeContext.md"]
UpdateContext --> SetupComplete["Documentation<br>Setup Complete"]
```
**Steps:**
1. Load basic documentation templates
2. Update projectbrief.md with enhancement details
3. Update activeContext.md with current focus
4. Create minimal documentation structure
**Milestone Checkpoint:**
```
✓ DOCUMENTATION CHECKPOINT
- Documentation templates loaded? [YES/NO]
- projectbrief.md updated? [YES/NO]
- activeContext.md updated? [YES/NO]
- Documentation structure created? [YES/NO]
→ If all YES: Proceed to Task Planning
→ If any NO: Complete documentation setup
```
### Phase 3: TASK PLANNING
```mermaid
graph TD
Start["Begin Task<br>Planning"] --> Requirements["Define Clear<br>Requirements"]
Requirements --> SubTasks["Break Down<br>Into Subtasks"]
SubTasks --> TasksUpdate["Update tasks.md<br>With Subtasks"]
TasksUpdate --> TimeEstimate["Create Time<br>Estimates"]
TimeEstimate --> PlanComplete["Planning<br>Complete"]
```
**Steps:**
1. Define clear requirements
2. Break down into subtasks
3. Update tasks.md with subtasks
4. Create time estimates
5. Document dependencies and constraints
**Milestone Checkpoint:**
```
✓ PLANNING CHECKPOINT
- Requirements clearly defined? [YES/NO]
- Task broken down into subtasks? [YES/NO]
- tasks.md updated with subtasks? [YES/NO]
- Time estimates created? [YES/NO]
- Dependencies documented? [YES/NO]
→ If all YES: Proceed to Implementation
→ If any NO: Complete planning steps
```
### Phase 4: IMPLEMENTATION
```mermaid
graph TD
Start["Begin<br>Implementation"] --> SubTask1["Complete<br>Subtask 1"]
SubTask1 --> UpdateStatus1["Update Status<br>in tasks.md"]
UpdateStatus1 --> SubTask2["Complete<br>Subtask 2"]
SubTask2 --> UpdateStatus2["Update Status<br>in tasks.md"]
UpdateStatus2 --> FinalSubTask["Complete<br>Final Subtask"]
FinalSubTask --> Verification["Perform<br>Verification"]
Verification --> ImplComplete["Implementation<br>Complete"]
```
**Steps:**
1. Implement first subtask
2. Update status in tasks.md
3. Implement remaining subtasks
4. Regular status updates after each subtask
5. Verify complete implementation
**Milestone Checkpoint:**
```
✓ IMPLEMENTATION CHECKPOINT
- All subtasks completed? [YES/NO]
- Status updates maintained? [YES/NO]
- Enhancement fully implemented? [YES/NO]
- Basic verification performed? [YES/NO]
- tasks.md fully updated? [YES/NO]
→ If all YES: Proceed to Reflection
→ If any NO: Complete implementation steps
```
### Phase 5: REFLECTION
```mermaid
graph TD
Start["Begin<br>Reflection"] --> Template["Load Reflection<br>Template"]
Template --> Review["Review Completed<br>Enhancement"]
Review --> Document["Document Successes<br>and Challenges"]
Document --> Insights["Extract Key<br>Insights"]
Insights --> Actions["Define Action<br>Items"]
Actions --> ReflectComplete["Reflection<br>Complete"]
```
**Steps:**
1. Load reflection template
2. Review completed enhancement
3. Document successes and challenges
4. Extract key insights
5. Define action items for future work
**Milestone Checkpoint:**
```
✓ REFLECTION CHECKPOINT
- Reflection template loaded? [YES/NO]
- Enhancement reviewed? [YES/NO]
- Successes and challenges documented? [YES/NO]
- Key insights extracted? [YES/NO]
- Action items defined? [YES/NO]
→ If all YES: Proceed to Archiving
→ If any NO: Complete reflection steps
```
### Phase 6: ARCHIVING
```mermaid
graph TD
Start["Begin<br>Archiving"] --> Template["Load Archive<br>Template"]
Template --> Gather["Gather Implementation<br>Details"]
Gather --> Create["Create Archive<br>Document"]
Create --> CrossRef["Create Cross-<br>References"]
CrossRef --> Update["Update Memory<br>Bank Files"]
Update --> ArchiveComplete["Archiving<br>Complete"]
```
**Steps:**
1. Load archive template
2. Gather implementation details
3. Create archive document
4. Create cross-references
5. Update Memory Bank files
**Milestone Checkpoint:**
```
✓ ARCHIVING CHECKPOINT
- Archive template loaded? [YES/NO]
- Implementation details gathered? [YES/NO]
- Archive document created? [YES/NO]
- Cross-references created? [YES/NO]
- Memory Bank files updated? [YES/NO]
→ If all YES: Task Complete
→ If any NO: Complete archiving steps
```
## 📋 WORKFLOW VERIFICATION CHECKLIST
```
✓ FINAL WORKFLOW VERIFICATION
- All phases completed? [YES/NO]
- All milestone checkpoints passed? [YES/NO]
- tasks.md fully updated? [YES/NO]
- Reflection document created? [YES/NO]
- Archive document created? [YES/NO]
- Memory Bank fully updated? [YES/NO]
→ If all YES: Level 2 Task Successfully Completed
→ If any NO: Address outstanding items
```
## 📋 MINIMAL MODE WORKFLOW
For minimal mode, use this streamlined workflow:
```
1. INIT: Verify environment, create task entry
2. DOCS: Update projectbrief and activeContext
3. PLAN: Define requirements, subtasks, estimates
4. IMPL: Complete subtasks, update status
5. REFLECT: Document key insights and actions
6. ARCHIVE: Document completion and cross-reference
```
## 🔄 LEVEL TRANSITION HANDLING
```mermaid
graph TD
L2["Level 2 Task"] --> Assess["Continuous<br>Assessment"]
Assess --> Down["Downgrade to<br>Level 1"]
Assess --> Up["Upgrade to<br>Level 3/4"]
Down --> L1Trigger["Triggers:<br>- Simpler than expected<br>- Quick fix possible<br>- Single component"]
Up --> L34Trigger["Triggers:<br>- More complex<br>- Multiple components<br>- Design needed"]
L1Trigger --> L1Switch["Switch to<br>Level 1 Workflow"]
L34Trigger --> L34Switch["Switch to<br>Level 3/4 Workflow"]
```
## 🔄 INTEGRATION WITH MEMORY BANK
```mermaid
graph TD
Workflow["Level 2<br>Workflow"] --> PB["Update<br>projectbrief.md"]
Workflow --> AC["Update<br>activeContext.md"]
Workflow --> TM["Maintain<br>tasks.md"]
Workflow --> PM["Update<br>progress.md"]
PB & AC & TM & PM --> MB["Memory Bank<br>Integration"]
MB --> NextTask["Transition to<br>Next Task"]
```
## 🚨 EFFICIENCY PRINCIPLE
Remember:
```
┌─────────────────────────────────────────────────────┐
│ Level 2 workflow balances PROCESS with EFFICIENCY. │
│ Follow the structure but avoid unnecessary overhead. │
└─────────────────────────────────────────────────────┘
```
This ensures that simple enhancements are implemented with the right level of documentation and process.
@@ -0,0 +1,78 @@
---
description:
globs: archive-intermediate.mdc
alwaysApply: false
---
# LEVEL 3 ARCHIVE: INTERMEDIATE FEATURE DOCUMENTATION
> **TL;DR:** This guide outlines the archiving process for a completed Level 3 intermediate feature. The aim is to create a self-contained, easily accessible record of the feature's development lifecycle, including its planning, design decisions, implementation summary, and reflection.
## 🚀 Before You Start Archiving (L3 Pre-Archive Checklist)
1. **Confirm Reflection Complete:** Verify in `memory-bank/tasks.md` that the reflection phase for this feature is marked as complete and `memory-bank/reflection-[feature_id].md` exists and is finalized.
2. **Gather All Feature-Specific Documents:**
* The feature plan section from `memory-bank/tasks.md` (or a copy of it).
* All `memory-bank/creative/creative-[aspect_name].md` documents related to this feature.
* The `memory-bank/reflection/reflection-[feature_id].md` document.
* Key diagrams or architectural notes from `memory-bank/progress.md` if not captured elsewhere.
* A link to the primary commit(s) or feature branch merge for the implemented code.
## 📦 Level 3 Archiving Workflow
```mermaid
graph TD
StartArchive["Start L3 Archiving"] -->
VerifyReflect["1. Verify Reflection Complete<br>Check `tasks.md` & `reflection-[feature_id].md`"] -->
GatherDocs["2. Gather All Feature Documents<br>(Plan, Creative outputs, Reflection, Code links)"] -->
CreateArchiveFile["3. Create Feature Archive File<br>e.g., `memory-bank/archive/feature-[FeatureNameOrID]_YYYYMMDD.md`"] -->
PopulateArchive["4. Populate Archive File<br>(Using L3 Archive Template below)"] -->
VerifyLinks["5. Verify All Internal Links<br>in Archive File are Correct"] -->
FinalUpdateTasks["6. Final Update to `tasks.md`<br>(Mark Feature FULLY COMPLETED & ARCHIVED, link to archive file)"] -->
UpdateProgressFile["7. Add Final Entry to `progress.md`<br>(Note archiving & link to archive file)"] -->
ClearActiveCtx["8. Clear `activeContext.md`<br>Reset for Next Task/Project"] -->
ArchiveDone["L3 Archiving Complete<br>Feature successfully documented and closed."]
style StartArchive fill:#90a4ae,stroke:#607d8b
style ArchiveDone fill:#b0bec5,stroke:#90a4ae
````
## 📝 Structure for `memory-bank/archive/feature-[FeatureNameOrID]_YYYYMMDD.md`
* **Feature Title:** (e.g., "Archive: User Profile Feature - Avatar Upload Enhancement")
* **Feature ID (from `tasks.md`):**
* **Date Archived:** YYYY-MM-DD
* **Status:** COMPLETED & ARCHIVED
* **1. Feature Overview:**
* Brief description of the feature and its purpose (can be extracted from `tasks.md` or `projectbrief.md`).
* Link to the original task entry/plan in `tasks.md` (if `tasks.md` is versioned or kept historically).
* **2. Key Requirements Met:**
* List the main functional and non-functional requirements this feature addressed.
* **3. Design Decisions & Creative Outputs:**
* Summary of key design choices.
* Direct links to all relevant `memory-bank/creative/creative-[aspect_name].md` documents.
* Link to `memory-bank/style-guide.md` version used (if applicable).
* **4. Implementation Summary:**
* High-level overview of how the feature was implemented.
* List of primary new components/modules created.
* Key technologies or libraries utilized specifically for this feature.
* Link to the main feature branch merge commit or primary code location/pull request.
* **5. Testing Overview:**
* Brief summary of the testing strategy employed for this feature (unit, integration, E2E).
* Outcome of the testing.
* **6. Reflection & Lessons Learned:**
* Direct link to `memory-bank/reflection/reflection-[feature_id].md`.
* Optionally, copy 1-2 most critical lessons directly into the archive summary.
* **7. Known Issues or Future Considerations (Optional, if any remaining from reflection):**
* Any minor known issues deferred.
* Potential future enhancements related to this feature.
### Key Files and Components Affected (from tasks.md)
[Summary or direct copy of file/component checklists from the original tasks.md for this project. This provides a quick reference to the scope of changes at a component/file level.]
## 📌 What to Emphasize in L3 Archiving
* **Self-Contained Feature Record:** The goal is to have a go-to document in the archive that summarizes the "story" of this feature.
* **Traceability:** Easy navigation from the archive summary to detailed planning, design, and reflection documents.
* **Maintainability Focus:** Information that would help a future developer understand, maintain, or build upon this specific feature.
* **Not a Full System Archive:** Unlike Level 4, this is not about archiving the entire application state, but rather the lifecycle of one significant feature.
@@ -0,0 +1,72 @@
---
description:
globs: implementation-intermediate.mdc
alwaysApply: false
---
# LEVEL 3 IMPLEMENTATION: BUILDING INTERMEDIATE FEATURES
> **TL;DR:** This guide focuses on the systematic implementation of a planned and designed Level 3 feature. It emphasizes modular development, strict adherence to creative decisions and the style guide, integration with existing systems, and thorough feature-specific testing.
## 🛠️ Level 3 Feature Implementation Workflow
This workflow outlines the typical steps for building an intermediate feature.
```mermaid
graph TD
StartImpl["Start L3 Implementation"] -->
ReviewDocs["1. Review All Relevant Docs<br>(Tasks, Creative Docs, Style Guide)"] -->
SetupEnv["2. Setup/Verify Dev Environment<br>(Branch, Tools, Dependencies)"] -->
ModuleBreakdown["3. Break Down Feature into Modules/Major Components<br>(Based on plan in `tasks.md`)"] -->
BuildIterate["4. Implement Modules/Components Iteratively"]
BuildIterate --> ImplementModule["4a. Select Next Module/Component"]
ImplementModule --> CodeModule["4b. Code Module<br>(Adhere to design, style guide, coding standards)"]
CodeModule --> UnitTests["4c. Write & Pass Unit Tests"]
UnitTests --> SelfReview["4d. Self-Review/Code Linting"]
SelfReview --> MoreModules{"4e. More Modules<br>for this Feature?"}
MoreModules -- Yes --> ImplementModule
MoreModules -- No --> IntegrateModules["5. Integrate All Feature Modules/Components"]
IntegrateModules --> IntegrationTesting["6. Perform Integration Testing<br>(Feature modules + existing system parts)"]
IntegrationTesting --> E2EFeatureTesting["7. End-to-End Feature Testing<br>(Validate against user stories & requirements)"]
E2EFeatureTesting --> AccessibilityCheck["8. Accessibility & Responsiveness Check<br>(If UI is involved)"]
AccessibilityCheck --> CodeCleanup["9. Code Cleanup & Refinement"]
CodeCleanup --> UpdateMB["10. Update Memory Bank<br>(`tasks.md` sub-tasks, `progress.md` details)"]
UpdateMB --> FinalFeatureReview["11. Final Feature Review (Conceptual Peer Review if possible)"]
FinalFeatureReview --> ImplementationDone["L3 Implementation Complete<br>Ready for REFLECT Mode"]
style StartImpl fill:#e57373,stroke:#f44336
style BuildIterate fill:#ffcdd2,stroke:#ef9a9a
style ImplementationDone fill:#ef9a9a,stroke:#e57373
````
## 🔑 Key Considerations for Level 3 Implementation
* **Modularity & Encapsulation:** Design and build the feature in well-defined, reusable, and loosely coupled modules or components.
* **Adherence to Design:** Strictly follow the decisions documented in `memory-bank/creative-*.md` files and the `memory-bank/style-guide.md`. Deviations must be justified and documented.
* **State Management:** If the feature introduces or significantly interacts with complex application state, ensure the state management strategy (potentially defined in CREATIVE mode) is correctly implemented and tested.
* **API Interactions:**
* If consuming new or existing APIs, ensure requests and responses are handled correctly, including error states.
* If exposing new API endpoints as part of the feature, ensure they are robust, secure, and documented.
* **Error Handling:** Implement user-friendly error messages and robust error handling within the feature's scope.
* **Performance:** Be mindful of performance implications. Avoid common pitfalls like N+1 database queries, inefficient algorithms, or large asset loading without optimization, especially if identified as a concern in the PLAN or CREATIVE phase.
* **Security:** Implement with security best practices in mind, particularly for features handling user input, authentication, or sensitive data. Refer to any security design decisions from CREATIVE mode.
## 🧪 Testing Focus for Level 3 Features
* **Unit Tests:** Each new function, method, or logical unit within the feature's components should have corresponding unit tests. Aim for good coverage of core logic and edge cases.
* **Component Tests (for UI features):** Test UI components in isolation, verifying rendering, props handling, and event emissions.
* **Integration Tests:** Crucial for L3. Test how the different modules/components of the new feature work together. Also, test how the completed feature integrates with existing parts of the application it interacts with.
* **User Scenario / Acceptance Tests (Feature-Specific):** Validate that the feature fulfills its defined requirements and user stories from the user's perspective. This can be manual or automated.
## 📝 Documentation During Implementation
* **`memory-bank/tasks.md`:** Update the status of sub-tasks related to the feature as they are completed. Note any blockers or changes in estimates.
* **`memory-bank/progress.md`:** Make regular entries detailing:
* Modules/components completed.
* Key decisions made during implementation (if minor and not warranting a full CREATIVE cycle).
* Files significantly modified
* Test results for major integration points.
* Any deviations from the plan or creative designs, with rationale.
* **Code Comments:** Write clear, concise comments explaining complex logic, assumptions, or TODOs.
* **READMEs (if applicable):** If the feature introduces new modules or libraries that require specific setup or usage notes, consider adding or updating relevant README files.
@@ -0,0 +1,188 @@
---
description: planning comprehensive
globs: planning-comprehensive.mdc
alwaysApply: false
---
# LEVEL 3 COMPREHENSIVE PLANNING
> **TL;DR:** This document provides structured planning guidelines for Level 3 (Intermediate Feature) tasks, focusing on comprehensive planning with creative phases and clear implementation strategies.
## 🏗️ PLANNING WORKFLOW
```mermaid
graph TD
Start["Planning Start"] --> Req["📋 Requirements<br>Analysis"]
Req --> Comp["🔍 Component<br>Analysis"]
Comp --> Design["🎨 Design<br>Decisions"]
Design --> Impl["⚙️ Implementation<br>Strategy"]
Impl --> Test["🧪 Testing<br>Strategy"]
Test --> Doc["📚 Documentation<br>Plan"]
Design --> Creative["Creative Phases:"]
Creative --> UI["UI/UX Design"]
Creative --> Arch["Architecture"]
Creative --> Algo["Algorithm"]
style Start fill:#4da6ff,stroke:#0066cc,color:white
style Req fill:#ffa64d,stroke:#cc7a30,color:white
style Comp fill:#4dbb5f,stroke:#36873f,color:white
style Design fill:#d94dbb,stroke:#a3378a,color:white
style Impl fill:#4dbbbb,stroke:#368787,color:white
style Test fill:#d971ff,stroke:#a33bc2,color:white
style Doc fill:#ff71c2,stroke:#c23b8a,color:white
```
## 🔄 LEVEL TRANSITION HANDLING
```mermaid
graph TD
L3["Level 3 Task"] --> Assess["Continuous<br>Assessment"]
Assess --> Down["Downgrade to<br>Level 1/2"]
Assess --> Up["Upgrade to<br>Level 4"]
Down --> L12Trigger["Triggers:<br>- Simpler than expected<br>- Limited scope<br>- Few components"]
Up --> L4Trigger["Triggers:<br>- System-wide impact<br>- Architectural changes<br>- High complexity"]
L12Trigger --> L12Switch["Switch to<br>Level 1/2 Workflow"]
L4Trigger --> L4Switch["Switch to<br>Level 4 Workflow"]
```
## 📋 PLANNING TEMPLATE
```markdown
# Feature Planning Document
## Requirements Analysis
- Core Requirements:
- [ ] Requirement 1
- [ ] Requirement 2
- Technical Constraints:
- [ ] Constraint 1
- [ ] Constraint 2
## Component Analysis
- Affected Components:
- Component 1
- Changes needed:
- Dependencies:
- Component 2
- Changes needed:
- Dependencies:
## Design Decisions
- Architecture:
- [ ] Decision 1
- [ ] Decision 2
- UI/UX:
- [ ] Design 1
- [ ] Design 2
- Algorithms:
- [ ] Algorithm 1
- [ ] Algorithm 2
## Implementation Strategy
1. Phase 1:
- [ ] Task 1
- [ ] Task 2
2. Phase 2:
- [ ] Task 3
- [ ] Task 4
## Testing Strategy
- Unit Tests:
- [ ] Test 1
- [ ] Test 2
- Integration Tests:
- [ ] Test 3
- [ ] Test 4
## Documentation Plan
- [ ] API Documentation
- [ ] User Guide Updates
- [ ] Architecture Documentation
```
## 🎨 CREATIVE PHASE IDENTIFICATION
```mermaid
graph TD
subgraph "CREATIVE PHASES REQUIRED"
UI["🎨 UI/UX Design<br>Required: Yes/No"]
Arch["🏗️ Architecture Design<br>Required: Yes/No"]
Algo["⚙️ Algorithm Design<br>Required: Yes/No"]
end
UI --> UITrig["Triggers:<br>- New UI Component<br>- UX Flow Change"]
Arch --> ArchTrig["Triggers:<br>- System Structure Change<br>- New Integration"]
Algo --> AlgoTrig["Triggers:<br>- Performance Critical<br>- Complex Logic"]
style UI fill:#4dbb5f,stroke:#36873f,color:white
style Arch fill:#ffa64d,stroke:#cc7a30,color:white
style Algo fill:#d94dbb,stroke:#a3378a,color:white
```
## ✅ VERIFICATION CHECKLIST
```mermaid
graph TD
subgraph "PLANNING VERIFICATION"
R["Requirements<br>Complete"]
C["Components<br>Identified"]
D["Design Decisions<br>Made"]
I["Implementation<br>Plan Ready"]
T["Testing Strategy<br>Defined"]
Doc["Documentation<br>Plan Ready"]
end
R --> C --> D --> I --> T --> Doc
style R fill:#4dbb5f,stroke:#36873f,color:white
style C fill:#ffa64d,stroke:#cc7a30,color:white
style D fill:#d94dbb,stroke:#a3378a,color:white
style I fill:#4dbbbb,stroke:#368787,color:white
style T fill:#d971ff,stroke:#a33bc2,color:white
style Doc fill:#ff71c2,stroke:#c23b8a,color:white
```
## 🔄 IMPLEMENTATION PHASES
```mermaid
graph LR
Setup["🛠️ Setup"] --> Core["⚙️ Core<br>Implementation"]
Core --> UI["🎨 UI<br>Implementation"]
UI --> Test["🧪 Testing"]
Test --> Doc["📚 Documentation"]
style Setup fill:#4da6ff,stroke:#0066cc,color:white
style Core fill:#4dbb5f,stroke:#36873f,color:white
style UI fill:#ffa64d,stroke:#cc7a30,color:white
style Test fill:#d94dbb,stroke:#a3378a,color:white
style Doc fill:#4dbbbb,stroke:#368787,color:white
```
## 🔄 INTEGRATION WITH MEMORY BANK
```mermaid
graph TD
L3["Level 3<br>Task"] --> PB["Comprehensive<br>projectbrief.md"]
L3 --> AC["Detailed<br>activeContext.md"]
L3 --> TM["Structured<br>tasks.md"]
L3 --> PM["Detailed<br>progress.md"]
PB & AC & TM & PM --> MB["Memory Bank<br>Integration"]
MB --> NextPhase["Proceed to<br>Implementation"]
```
## 🚨 PLANNING EFFICIENCY PRINCIPLE
Remember:
```
┌─────────────────────────────────────────────────────┐
│ Level 3 planning requires COMPREHENSIVE DESIGN but │
│ should avoid OVER-ENGINEERING. Focus on delivering │
│ maintainable, well-documented features. │
└─────────────────────────────────────────────────────┘
```
@@ -0,0 +1,74 @@
---
description:
globs: reflection-intermediate.mdc
alwaysApply: false
---
# LEVEL 3 REFLECTION: INTERMEDIATE FEATURE REVIEW
> **TL;DR:** This guide structures the reflection process for a completed Level 3 intermediate feature. The focus is on a detailed review of the entire feature development lifecycle, from planning and design through implementation and testing, to extract meaningful lessons and identify improvements for future feature work.
## 🔍 Level 3 Reflection Process
The goal is to create a comprehensive `memory-bank/reflection/reflection-[feature_id].md` document.
```mermaid
graph TD
StartReflect["Start L3 Reflection"] -->
ReviewDocs["1. Review All Gathered Documentation"] -->
AssessOutcome["2. Assess Overall Feature Outcome<br>Did it meet all requirements from tasks.md? Was it successful?"] -->
AnalyzePlan["3. Analyze Planning Phase Effectiveness<br>Was planning-comprehensive.mdc guidance effective? Was the plan accurate? Scope creep?"] -->
AnalyzeCreative["4. Analyze Creative Phase(s) Effectiveness<br>Were design decisions sound? Did they translate well to implementation? Issues?"] -->
AnalyzeImpl["5. Analyze Implementation Phase<br>What went well? Challenges? Bottlenecks? Adherence to design/style guide?"] -->
AnalyzeTesting["6. Analyze Testing Phase<br>Were tests adequate? Bugs found post-release (if applicable)? Test coverage feel right?"] -->
IdentifyLessons["7. Identify Key Lessons Learned<br>(Technical, Process, Teamwork, Estimation)"] -->
ProposeImprovements["8. Propose Actionable Improvements<br>For future L3 feature development"] -->
DraftReflectionDoc["9. Draft `reflection-[feature_id].md`<br>Using structured template"] -->
FinalizeReflection["10. Finalize & Save Reflection Document"] -->
UpdateTasksStatus["11. Update `tasks.md`<br>Mark L3 Reflection Complete"] -->
ReflectionDone["L3 Reflection Complete<br>Ready for ARCHIVE Mode"]
style StartReflect fill:#ba68c8,stroke:#9c27b0
style ReflectionDone fill:#d1c4e9,stroke:#b39ddb
````
## 📝 Structure for `memory-bank/reflection-[feature_id].md`
* **Feature Name & ID:**
* **Date of Reflection:**
* **Brief Feature Summary:** (What was built?)
* **1. Overall Outcome & Requirements Alignment:**
* How well did the final feature meet the initial requirements?
* Were there any deviations from the original scope? If so, why?
* What is the overall assessment of the feature's success?
* **2. Planning Phase Review:**
* How effective was the guidance from `Level3/planning-comprehensive.mdc`?
* Was the initial plan in `tasks.md` (component breakdown, strategy, risks) accurate and helpful?
* What could have been planned better? Were estimations (if made) accurate?
* **3. Creative Phase(s) Review (if applicable):**
* Were the right aspects flagged for CREATIVE mode?
* How effective were the design decisions made in `creative-*.md` documents?
* Did these designs translate well into practical implementation? Any friction points?
* Was `memory-bank/style-guide.md` clear and sufficient for UI aspects?
* **4. Implementation Phase Review:**
* What were the major successes during implementation? (e.g., efficient module development, good use of libraries)
* What were the biggest challenges or roadblocks? How were they overcome?
* Were there any unexpected technical difficulties or complexities?
* How was adherence to the style guide and coding standards?
* **5. Testing Phase Review:**
* Was the testing strategy (unit, integration, E2E for the feature) effective?
* Did testing uncover significant issues early enough?
* What could improve the testing process for similar features?
* **6. What Went Well? (Highlight 3-5 key positives across all phases for this feature)**
* **7. What Could Have Been Done Differently? (Identify 3-5 areas for improvement)**
* **8. Key Lessons Learned:**
* **Technical:** New insights about technologies, patterns, or architecture used for this feature.
* **Process:** Insights about the L3 workflow, communication, task management.
* **Estimation (if applicable):** Lessons about estimating work for features of this scale.
* **9. Actionable Improvements for Future L3 Features:** (Specific suggestions)
## 🎯 Focus Areas for L3 Reflection
* **Feature Scope Management:** Was the scope well-defined and managed?
* **Integration Complexity:** Challenges or successes in integrating the feature with the existing application.
* **Design-to-Implementation Fidelity:** How closely did the final product match the designs?
* **Cross-Component Impact:** Understanding the ripple effects of the feature.
@@ -0,0 +1,135 @@
---
description: task tracking intermediate
globs: task-tracking-intermediate.mdc
alwaysApply: false
---
# LEVEL 3 INTERMEDIATE TASK TRACKING
> **TL;DR:** This document provides structured task tracking guidelines for Level 3 (Intermediate Feature) tasks, using visual tracking elements and clear checkpoints.
## 🔍 TASK TRACKING WORKFLOW
```mermaid
graph TD
Start["Task Start"] --> Init["📋 Initialize<br>Task Entry"]
Init --> Struct["🏗️ Create Task<br>Structure"]
Struct --> Track["📊 Progress<br>Tracking"]
Track --> Update["🔄 Regular<br>Updates"]
Update --> Complete["✅ Task<br>Completion"]
Struct --> Components["Components:"]
Components --> Req["Requirements"]
Components --> Steps["Implementation<br>Steps"]
Components --> Creative["Creative Phase<br>Markers"]
Components --> Check["Checkpoints"]
Track --> Status["Track Status:"]
Status --> InProg["🔄 In Progress"]
Status --> Block["⛔ Blocked"]
Status --> Done["✅ Complete"]
Status --> Skip["⏭️ Skipped"]
style Start fill:#4da6ff,stroke:#0066cc,color:white
style Init fill:#ffa64d,stroke:#cc7a30,color:white
style Struct fill:#4dbb5f,stroke:#36873f,color:white
style Track fill:#d94dbb,stroke:#a3378a,color:white
style Update fill:#4dbbbb,stroke:#368787,color:white
style Complete fill:#d971ff,stroke:#a33bc2,color:white
```
## 📋 TASK ENTRY TEMPLATE
```markdown
# [Task Title]
## Requirements
- [ ] Requirement 1
- [ ] Requirement 2
- [ ] Requirement 3
## Components Affected
- Component 1
- Component 2
- Component 3
## Implementation Steps
1. [ ] Step 1
2. [ ] Step 2
3. [ ] Step 3
## Creative Phases Required
- [ ] 🎨 UI/UX Design
- [ ] 🏗️ Architecture Design
- [ ] ⚙️ Algorithm Design
## Checkpoints
- [ ] Requirements verified
- [ ] Creative phases completed
- [ ] Implementation tested
- [ ] Documentation updated
## Current Status
- Phase: [Current Phase]
- Status: [In Progress/Blocked/Complete]
- Blockers: [If any]
```
## 🔄 PROGRESS TRACKING VISUALIZATION
```mermaid
graph TD
subgraph "TASK PROGRESS"
P1["✓ Requirements<br>Defined"]
P2["✓ Components<br>Identified"]
P3["→ Creative Phase<br>In Progress"]
P4["□ Implementation"]
P5["□ Testing"]
P6["□ Documentation"]
end
style P1 fill:#4dbb5f,stroke:#36873f,color:white
style P2 fill:#4dbb5f,stroke:#36873f,color:white
style P3 fill:#ffa64d,stroke:#cc7a30,color:white
style P4 fill:#d94dbb,stroke:#a3378a,color:white
style P5 fill:#4dbbbb,stroke:#368787,color:white
style P6 fill:#d971ff,stroke:#a33bc2,color:white
```
## ✅ UPDATE PROTOCOL
```mermaid
sequenceDiagram
participant Task as Task Entry
participant Status as Status Update
participant Creative as Creative Phase
participant Implementation as Implementation
Task->>Status: Update Progress
Status->>Creative: Flag for Creative Phase
Creative->>Implementation: Complete Design
Implementation->>Status: Update Status
Status->>Task: Mark Complete
```
## 🎯 CHECKPOINT VERIFICATION
| Phase | Verification Items | Status |
|-------|-------------------|--------|
| Requirements | All requirements documented | [ ] |
| Components | Affected components listed | [ ] |
| Creative | Design decisions documented | [ ] |
| Implementation | Code changes tracked | [ ] |
| Testing | Test results recorded | [ ] |
| Documentation | Updates completed | [ ] |
## 🔄 DOCUMENT MANAGEMENT
```mermaid
graph TD
Current["Current Documents"] --> Active["Active:<br>- task-tracking-intermediate.md<br>- planning-comprehensive.md"]
Current --> Required["Required Next:<br>- creative-phase-enforcement.md<br>- implementation-phase-reference.md"]
style Current fill:#4da6ff,stroke:#0066cc,color:white
style Active fill:#4dbb5f,stroke:#36873f,color:white
style Required fill:#ffa64d,stroke:#cc7a30,color:white
```
@@ -0,0 +1,326 @@
---
description: Defines the standard workflow for Level 3 (Intermediate Feature) tasks, guiding through comprehensive planning, targeted creative design, structured implementation, detailed reflection, and feature-specific archiving.
globs: workflow-level3.mdc
alwaysApply: false
---
# LEVEL 3 WORKFLOW: INTERMEDIATE FEATURE DEVELOPMENT
> **TL;DR:** This document outlines a structured workflow for Level 3 (Intermediate Feature) tasks. These tasks involve developing significant new functionality that may span multiple components, requiring comprehensive planning, often necessitating targeted creative design phases, followed by systematic implementation, in-depth reflection, and feature-specific archiving. This workflow balances detailed process with efficiency for moderately complex features.
## 🔍 LEVEL 3 WORKFLOW OVERVIEW
Level 3 tasks represent a significant development effort, building a complete feature. The workflow ensures adequate planning, design for key aspects, and methodical execution.
```mermaid
graph LR
Init["1. INITIALIZATION<br>(VAN Mode Output)"] -->
DocSetup["2. DOCUMENTATION SETUP"] -->
Plan["3. FEATURE PLANNING (PLAN Mode)"] -->
Creative["4. CREATIVE PHASES (CREATIVE Mode)"] -->
Impl["5. IMPLEMENTATION (BUILD Mode)"] -->
Reflect["6. REFLECTION (REFLECT Mode)"] -->
Archive["7. ARCHIVING (ARCHIVE Mode)"]
%% Document connections for each phase (conceptual links to mode guidance)
Init -.-> InitDocs["Core Rules & L3 Confirmation"]
DocSetup -.-> DocSetupDocs["Memory Bank Setup for L3"]
Plan -.-> PlanDocs["Comprehensive Feature Plan"]
Creative -.-> CreativeDocs["Targeted Design Documents"]
Impl -.-> ImplDocs["Feature Implementation & Testing"]
Reflect -.-> ReflectDocs["In-depth Feature Reflection"]
Archive -.-> ArchiveDocs["Feature Archive Package"]
style Init fill:#a1c4fd,stroke:#669df6
style DocSetup fill:#b3e5fc,stroke:#81d4fa
style Plan fill:#c8e6c9,stroke:#a5d6a7
style Creative fill:#ffd8b2,stroke:#ffcc80
style Impl fill:#ffcdd2,stroke:#ef9a9a
style Reflect fill:#d1c4e9,stroke:#b39ddb
style Archive fill:#cfd8dc,stroke:#b0bec5
````
Level 3 tasks typically involve creating a new, distinct feature or making substantial modifications to an existing one that affects multiple parts of the application.
## 🔄 LEVEL TRANSITION HANDLING (Within Level 3 Workflow)
```mermaid
graph TD
L3["Level 3 Task In Progress"] --> Assess["Continuous Assessment<br>During PLAN or early BUILD"]
Assess --> Up["Upgrade to<br>Level 4?"]
Assess --> Down["Downgrade to<br>Level 2?"]
Assess --> MaintainL3["Maintain<br>Level 3"]
Up --> L4Trigger["Triggers:<br>- Unforeseen system-wide impact<br>- Requires deep architectural changes<br>- Scope significantly larger than planned"]
Down --> L2Trigger["Triggers:<br>- Feature simpler than anticipated<br>- Very limited component interaction<br>- No complex design decisions emerge"]
L4Trigger --> L4Switch["Stop L3 Workflow.<br>Re-initialize task as Level 4 (VAN).<br>Preserve existing docs as input."]
L2Trigger --> L2Switch["Adapt L3 Workflow:<br>Simplify remaining phases,<br>use L2 Reflection/Archive rules."]
style Assess fill:#ffe082,stroke:#ffca28
style Up fill:#ef9a9a,stroke:#e57373
style Down fill:#a5d6a7,stroke:#81c784
style MaintainL3 fill:#b3e5fc,stroke:#81d4fa
```
## 📋 WORKFLOW PHASES
### Phase 1: INITIALIZATION (Output from VAN Mode)
This phase is largely completed in VAN mode, which identifies the task as Level 3.
* **Input:** User request leading to an "Intermediate Feature" classification.
* **Key Existing Files (from VAN):**
* `memory-bank/tasks.md`: Entry created, complexity set to Level 3.
* `memory-bank/activeContext.md`: Initial context set.
* Relevant Core Rules loaded (e.g., `Core/memory-bank-paths.mdc`, `main.mdc`).
* **Steps within this Workflow File (Confirmation):**
1. Confirm task is Level 3 by checking `memory-bank/tasks.md`.
2. Ensure core Memory Bank structure and paths are known (AI should have internalized from `main` rule).
* **Milestone Checkpoint:**
```
✓ INITIALIZATION CONFIRMED (L3)
- Task correctly identified as Level 3 in tasks.md? [YES/NO]
- Core Memory Bank files (tasks.md, activeContext.md) accessible via canonical paths? [YES/NO]
→ If all YES: Proceed to Documentation Setup for L3.
→ If any NO: Revisit VAN mode or core file setup.
```
### Phase 2: DOCUMENTATION SETUP (L3 Specific)
Prepare the Memory Bank for a Level 3 feature.
```mermaid
graph TD
StartDoc["Begin L3 Documentation<br>Setup"] --> LoadL3PlanTrack["Load L3 Planning & Tracking Rules<br>Level3/planning-comprehensive.mdc<br>Level3/task-tracking-intermediate.mdc"]
LoadL3PlanTrack --> UpdateBrief["Review/Update `projectbrief.md`<br>Ensure feature aligns with overall project goals"]
UpdateBrief --> UpdateActiveCtx["Update `activeContext.md`<br>Set focus to L3 Feature Planning"]
UpdateActiveCtx --> PrepTaskFile["Prepare `tasks.md` for<br>Comprehensive Feature Plan sections"]
PrepTaskFile --> DocSetupComplete["L3 Documentation<br>Setup Complete"]
style StartDoc fill:#b3e5fc,stroke:#81d4fa
style DocSetupComplete fill:#81d4fa,stroke:#4fc3f7
```
* **Steps:**
1. Load Level 3 specific planning (`Level3/planning-comprehensive.mdc`) and task tracking (`Level3/task-tracking-intermediate.mdc`) rules.
2. Review `memory-bank/projectbrief.md`: Briefly note the new feature if it impacts the overall brief.
3. Update `memory-bank/activeContext.md`: Set current focus to "Level 3 Feature Planning: [Feature Name]".
4. Ensure `memory-bank/tasks.md` is ready for the detailed planning sections outlined in `Level3/planning-comprehensive.mdc`.
* **Milestone Checkpoint:**
```
✓ L3 DOCUMENTATION SETUP CHECKPOINT
- L3 Planning & Tracking rules loaded? [YES/NO]
- projectbrief.md reviewed/updated for feature context? [YES/NO]
- activeContext.md reflects focus on L3 feature planning? [YES/NO]
- tasks.md prepared for detailed L3 plan? [YES/NO]
→ If all YES: Proceed to Feature Planning.
→ If any NO: Complete documentation setup steps.
```
### Phase 3: FEATURE PLANNING (PLAN Mode)
Guided by `visual-maps/plan-mode-map.mdc` and using `Level3/planning-comprehensive.mdc` and `Level3/task-tracking-intermediate.mdc`.
```mermaid
graph TD
StartPlan["Begin L3 Feature<br>Planning"] --> ReqDef["Define Detailed<br>Requirements (Functional & Non-Functional)"]
ReqDef --> CompAnalysis["Component Analysis<br>(New & Affected Components, Interactions)"]
CompAnalysis --> ImplStrategy["Develop Implementation<br>Strategy & High-Level Steps"]
ImplStrategy --> DepRiskMgmt["Identify Dependencies,<br>Risks, & Mitigations"]
DepRiskMgmt --> CreativeFlag["Flag Aspects for<br>CREATIVE Mode (UI, Arch, Algo)"]
CreativeFlag --> UpdateTasks["Update `tasks.md` with<br>Full L3 Feature Plan"]
UpdateTasks --> PlanComplete["L3 Feature Planning<br>Complete"]
style StartPlan fill:#c8e6c9,stroke:#a5d6a7
style PlanComplete fill:#a5d6a7,stroke:#81c784
```
* **Steps:**
1. Define detailed functional and non-functional requirements for the feature.
2. Perform component analysis: identify new components to build and existing ones that will be modified. Map their interactions.
3. Develop an implementation strategy: outline the main steps or stages for building the feature.
4. Identify dependencies (technical, data, other features) and potential risks, along with mitigation ideas.
5. **Critical for L3:** Explicitly identify and flag parts of the feature that require CREATIVE mode (e.g., specific UI/UX challenges, new architectural patterns for the feature, complex algorithms).
6. Document the complete plan (requirements, components, strategy, dependencies, risks, creative flags) in `memory-bank/tasks.md` under the Level 3 feature task entry.
* **Milestone Checkpoint:**
```
✓ L3 FEATURE PLANNING CHECKPOINT
- Detailed requirements documented in tasks.md? [YES/NO]
- Component analysis (new/affected, interactions) complete? [YES/NO]
- Implementation strategy outlined? [YES/NO]
- Dependencies and risks documented? [YES/NO]
- Aspects needing CREATIVE mode explicitly flagged in tasks.md? [YES/NO]
- tasks.md comprehensively updated with the feature plan? [YES/NO]
→ If all YES: Proceed to CREATIVE Phases (if flagged) or IMPLEMENTATION.
→ If any NO: Complete planning steps.
```
### Phase 4: CREATIVE PHASES (CREATIVE Mode)
Triggered if aspects were flagged in the PLAN phase. Guided by `visual-maps/creative-mode-map.mdc` and `Phases/CreativePhase/*.mdc` rules.
```mermaid
graph TD
StartCreative["Begin L3 Creative<br>Phases (If Needed)"] --> SelectAspect["Select Flagged Aspect<br>from `tasks.md`"]
SelectAspect --> DesignExplore["Explore Design/Arch Options<br>(Use relevant creative-phase-*.mdc rules)"]
DesignExplore --> DecideDocument["Make & Document Decision<br>in `creative-[aspect_name].md`"]
DecideDocument --> UpdateTasksCreative["Update `tasks.md` with<br>Decision Summary & Link"]
UpdateTasksCreative --> MoreAspects{"More Flagged<br>Aspects?"}
MoreAspects -- Yes --> SelectAspect
MoreAspects -- No --> CreativeComplete["L3 Creative Phases<br>Complete"]
style StartCreative fill:#ffd8b2,stroke:#ffcc80
style CreativeComplete fill:#ffcc80,stroke:#ffb74d
```
* **Steps:**
1. For each aspect flagged in `tasks.md` for creative exploration:
a. Load relevant `creative-phase-*.mdc` rule (e.g., UI/UX, architecture).
b. Define the problem, explore options, analyze trade-offs.
c. Make a design decision and document it with rationale in a new `memory-bank/creative-[aspect_name].md` file.
d. Update `tasks.md`: mark the creative sub-task as complete and link to the decision document.
* **Milestone Checkpoint:**
```
✓ L3 CREATIVE PHASES CHECKPOINT
- All flagged aspects from PLAN phase addressed? [YES/NO]
- Design decisions documented in respective `memory-bank/creative-*.md` files? [YES/NO]
- Rationale for decisions clearly stated? [YES/NO]
- tasks.md updated to reflect completion of creative sub-tasks and links to decision docs? [YES/NO]
→ If all YES: Proceed to Implementation.
→ If any NO: Complete creative phase work.
```
### Phase 5: IMPLEMENTATION (BUILD Mode)
Guided by `visual-maps/build-mode-map.mdc` and `Level3/implementation-L3.mdc`.
```mermaid
graph TD
StartImpl["Begin L3 Feature<br>Implementation"] --> ReviewPlanDesign["Review Plan (`tasks.md`)<br>& Creative Docs (`creative-*.md`)"]
ReviewPlanDesign --> SetupDevEnv["Setup Dev Environment<br>(Branch, Dependencies, Tools)"]
SetupDevEnv --> BuildModules["Implement Feature Modules/Components<br>Iteratively or Sequentially"]
BuildModules --> UnitIntegrationTests["Conduct Unit & Integration Tests<br>for Each Module/Feature Part"]
UnitIntegrationTests --> StyleAdherence["Ensure Adherence to<br>`memory-bank/style-guide.md`"]
StyleAdherence --> UpdateProgressDocs["Regularly Update `tasks.md` (sub-tasks)<br>& `progress.md` (milestones)"]
UpdateProgressDocs --> E2EFeatureTest["End-to-End Feature Testing<br>Against Requirements"]
E2EFeatureTest --> ImplComplete["L3 Feature Implementation<br>Complete"]
style StartImpl fill:#ffcdd2,stroke:#ef9a9a
style ImplComplete fill:#ef9a9a,stroke:#e57373
```
* **Steps:**
1. Thoroughly review the feature plan in `memory-bank/tasks.md` and all relevant `memory-bank/creative-*.md` decision documents.
2. Set up the development environment (new branch, install any new dependencies, configure tools).
3. Implement the feature, building out modules/components as planned. Prioritize clean code and adherence to design specifications.
4. Perform unit tests for new logic and integration tests as components are assembled.
5. Ensure all UI elements strictly follow `memory-bank/style-guide.md`.
6. Update `memory-bank/tasks.md` with progress on sub-tasks, and `memory-bank/progress.md` with details of implemented parts, commands used, and any significant findings.
7. Conduct end-to-end testing of the completed feature against its requirements.
* **Milestone Checkpoint:**
```
✓ L3 IMPLEMENTATION CHECKPOINT
- Feature fully implemented as per plan and creative designs? [YES/NO]
- All UI elements adhere to `memory-bank/style-guide.md`? [YES/NO]
- Unit and integration tests performed and passing? [YES/NO]
- End-to-end feature testing successful? [YES/NO]
- `tasks.md` and `progress.md` updated with implementation status? [YES/NO]
→ If all YES: Proceed to Reflection.
→ If any NO: Complete implementation and testing.
```
### Phase 6: REFLECTION (REFLECT Mode)
Guided by `visual-maps/reflect-mode-map.mdc` and `Level3/reflection-L3.mdc`.
```mermaid
graph TD
StartReflect["Begin L3 Feature<br>Reflection"] --> ReviewCompleted["Review Completed Feature<br>(Code, Plan, Design Docs, Test Results)"]
ReviewCompleted --> AnalyzeProcess["Analyze Development Process<br>(Successes, Challenges, Deviations)"]
AnalyzeProcess --> DocumentLessons["Document Key Lessons Learned<br>(Technical & Process)"]
DocumentLessons --> AssessDesignChoices["Assess Effectiveness of<br>Creative Phase Decisions"]
AssessDesignChoices --> CreateReflectDoc["Create `reflection-[feature_id].md`"]
CreateReflectDoc --> UpdateTasksReflect["Update `tasks.md` (Reflection Complete)"]
UpdateTasksReflect --> ReflectComplete["L3 Feature Reflection<br>Complete"]
style StartReflect fill:#d1c4e9,stroke:#b39ddb
style ReflectComplete fill:#b39ddb,stroke:#9575cd
```
* **Steps:**
1. Review the entire feature development lifecycle: initial requirements, plan, creative designs, implementation, and testing outcomes.
2. Analyze what went well, what was challenging, and any deviations from the original plan or design.
3. Document key lessons learned regarding technology, architecture, process, or team collaboration relevant to this feature.
4. Specifically assess how effective the creative phase decisions were during actual implementation.
5. Create the `memory-bank/reflection-[feature_id].md` document.
6. Update `memory-bank/tasks.md` to mark the reflection stage for the feature as complete.
* **Milestone Checkpoint:**
```
✓ L3 REFLECTION CHECKPOINT
- Feature development lifecycle thoroughly reviewed? [YES/NO]
- Successes, challenges, and lessons learned documented in `reflection-[feature_id].md`? [YES/NO]
- Effectiveness of creative/design decisions assessed? [YES/NO]
- `tasks.md` updated to reflect reflection completion? [YES/NO]
→ If all YES: Proceed to Archiving.
→ If any NO: Complete reflection documentation.
```
### Phase 7: ARCHIVING (ARCHIVE Mode - Highly Recommended for L3)
Guided by `visual-maps/archive-mode-map.mdc` and `Level3/archive-L3.mdc`.
```mermaid
graph TD
StartArchive["Begin L3 Feature<br>Archiving"] --> ConsolidateDocs["Consolidate All Feature Docs<br>(Plan, Creative, Reflection, Key Progress Notes)"]
ConsolidateDocs --> CreateArchiveSummary["Create Archive Summary Document<br>`archive/feature-[feature_id]_YYYYMMDD.md`"]
CreateArchiveSummary --> LinkDocs["Link to Detailed Docs<br>within Archive Summary"]
LinkDocs --> FinalUpdateTasks["Final Update to `tasks.md`<br>(Mark Feature COMPLETED & ARCHIVED)"]
FinalUpdateTasks --> ResetActiveCtx["Clear `activeContext.md`<br>Prepare for Next Task"]
ResetActiveCtx --> ArchiveComplete["L3 Feature Archiving<br>Complete"]
style StartArchive fill:#cfd8dc,stroke:#b0bec5
style ArchiveComplete fill:#b0bec5,stroke:#90a4ae
```
* **Steps:**
1. Consolidate all documentation related to the feature: the plan section from `tasks.md`, all `creative-*.md` files, the `reflection-*.md` file, and relevant summaries from `progress.md`.
2. Create a dedicated feature archive summary document in `memory-bank/archive/feature-[feature_id]_YYYYMMDD.md`. This summary should briefly describe the feature, its purpose, key decisions, and link to the more detailed documents.
3. Update `memory-bank/tasks.md` to mark the entire Level 3 feature task as "COMPLETED" and "ARCHIVED," providing a link to the new archive summary.
4. Update `memory-bank/activeContext.md` to clear information related to the completed feature, preparing for the next task.
* **Milestone Checkpoint:**
```
✓ L3 ARCHIVING CHECKPOINT
- Feature archive summary created in `memory-bank/archive/`? [YES/NO]
- Archive summary links to all relevant planning, creative, and reflection docs? [YES/NO]
- `tasks.md` shows the feature as COMPLETED and ARCHIVED with a link to the archive? [YES/NO]
- `activeContext.md` cleared and ready for a new task? [YES/NO]
→ If all YES: Level 3 Task Fully Completed. Suggest VAN Mode for next task.
→ If any NO: Complete archiving steps.
```
## 🚨 LEVEL 3 GOVERNANCE PRINCIPLE
Remember:
```
┌─────────────────────────────────────────────────────┐
│ Level 3 tasks build significant features. Balance │
│ detailed planning and targeted design with efficient│
│ execution. Document key decisions and outcomes to │
│ ensure the feature is understandable and maintainable.│
└─────────────────────────────────────────────────────┘
```
This ensures that intermediate features are developed with an appropriate level of rigor, bridging the gap between simple enhancements and full-scale system development.
```
```
@@ -0,0 +1,809 @@
---
description: Architectural planning guidelines for Level 4 Complex System tasks
globs: "**/level4/**", "**/architecture/**"
alwaysApply: false
---
# ARCHITECTURAL PLANNING FOR LEVEL 4 TASKS
> **TL;DR:** This document outlines a comprehensive architectural planning approach for Level 4 (Complex System) tasks, ensuring a robust, scalable, and maintainable architecture that aligns with business objectives and technical requirements.
## 🔍 ARCHITECTURAL PLANNING OVERVIEW
Level 4 Complex System tasks require thorough architectural planning to ensure the resulting system is robust, scalable, maintainable, and aligned with business objectives. This document outlines a structured approach to architectural planning that systematically addresses key concerns and produces comprehensive documentation.
```mermaid
flowchart TD
classDef phase fill:#f9d77e,stroke:#d9b95c,color:#000
classDef artifact fill:#f4b8c4,stroke:#d498a4,color:#000
classDef verification fill:#c5e8b7,stroke:#a5c897,color:#000
Start([Begin Architectural<br>Planning]) --> Reqs[Analyze<br>Requirements]
Reqs --> Context[Define Business<br>Context]
Context --> Vision[Establish Vision<br>and Goals]
Vision --> Principles[Define Architectural<br>Principles]
Principles --> Constraints[Identify<br>Constraints]
Constraints --> Explore[Explore<br>Alternatives]
Explore --> Evaluate[Evaluate<br>Options]
Evaluate --> Decision[Document<br>Decisions]
Decision --> Create[Create Architecture<br>Documentation]
Create --> Validate[Validate<br>Architecture]
Validate --> Communicate[Communicate<br>Architecture]
Communicate --> Verification{Architecture<br>Verification}
Verification -->|Pass| Complete([Architectural<br>Planning Complete])
Verification -->|Fail| Revise[Revise<br>Architecture]
Revise --> Verification
Reqs -.-> ReqDoc((Requirements<br>Document))
Context -.-> ConDoc((Context<br>Document))
Vision -.-> VisDoc((Vision<br>Document))
Principles -.-> PrinDoc((Principles<br>Document))
Explore -.-> AltDoc((Alternatives<br>Analysis))
Decision -.-> ADR((Architecture<br>Decision Records))
Create -.-> ArchDoc((Architecture<br>Documentation))
class Start,Complete milestone
class Reqs,Context,Vision,Principles,Constraints,Explore,Evaluate,Decision,Create,Validate,Communicate,Revise step
class Verification verification
class ReqDoc,ConDoc,VisDoc,PrinDoc,AltDoc,ADR,ArchDoc artifact
```
## 📋 ARCHITECTURAL PLANNING PRINCIPLES
1. **Business Alignment**: Architecture must directly support business objectives and user needs.
2. **Future-Proofing**: Architecture must anticipate future requirements and facilitate change.
3. **Simplicity**: Prefer simple solutions over complex ones when possible.
4. **Separation of Concerns**: Systems should be divided into distinct components with minimal overlap.
5. **Defense in Depth**: Multiple layers of security controls should be employed.
6. **Loose Coupling**: Components should interact through well-defined interfaces with minimal dependencies.
7. **High Cohesion**: Related functionality should be grouped together, unrelated functionality separated.
8. **Resilience**: Architecture should anticipate failures and provide mechanisms for recovery.
9. **Scalability**: Architecture should support growth in users, data, and functionality.
10. **Measurability**: Architecture should enable monitoring and measurement of key metrics.
## 📋 ARCHITECTURAL REQUIREMENTS ANALYSIS
Begin architectural planning with a comprehensive analysis of requirements:
### Functional Requirements Analysis
```mermaid
flowchart LR
classDef req fill:#f9d77e,stroke:#d9b95c,color:#000
classDef arch fill:#a8d5ff,stroke:#88b5e0,color:#000
FR[Functional<br>Requirements] --> USE[Use Cases/<br>User Stories]
USE --> DOM[Domain<br>Model]
DOM --> COMP[Component<br>Identification]
COMP --> INT[Interface<br>Definition]
INT --> FLOW[Information<br>Flow]
class FR,USE,DOM req
class COMP,INT,FLOW arch
```
**Template for Functional Requirements Analysis:**
```markdown
## Functional Requirements Analysis
### Key Use Cases
- Use Case 1: [Description]
- Use Case 2: [Description]
- Use Case 3: [Description]
### Domain Model
- Entity 1: [Description and attributes]
- Entity 2: [Description and attributes]
- Entity 3: [Description and attributes]
- Relationships:
- Entity 1 → Entity 2: [Relationship type and description]
- Entity 2 → Entity 3: [Relationship type and description]
### Component Identification
- Component 1: [Description and responsibilities]
- Component 2: [Description and responsibilities]
- Component 3: [Description and responsibilities]
### Interface Definitions
- Interface 1: [Description, methods, parameters]
- Interface 2: [Description, methods, parameters]
- Interface 3: [Description, methods, parameters]
### Information Flow
- Flow 1: [Description of information exchange]
- Flow 2: [Description of information exchange]
- Flow 3: [Description of information exchange]
```
### Non-Functional Requirements Analysis
```mermaid
flowchart LR
classDef req fill:#f9d77e,stroke:#d9b95c,color:#000
classDef arch fill:#a8d5ff,stroke:#88b5e0,color:#000
NFR[Non-Functional<br>Requirements] --> PERF[Performance<br>Requirements]
NFR --> SEC[Security<br>Requirements]
NFR --> SCAL[Scalability<br>Requirements]
NFR --> AVAIL[Availability<br>Requirements]
NFR --> MAINT[Maintainability<br>Requirements]
PERF & SEC & SCAL & AVAIL & MAINT --> ARCH[Architectural<br>Decisions]
class NFR,PERF,SEC,SCAL,AVAIL,MAINT req
class ARCH arch
```
**Template for Non-Functional Requirements Analysis:**
```markdown
## Non-Functional Requirements Analysis
### Performance Requirements
- Response Time: [Requirements]
- Throughput: [Requirements]
- Resource Utilization: [Requirements]
- Architectural Implications: [Implications for architecture]
### Security Requirements
- Authentication: [Requirements]
- Authorization: [Requirements]
- Data Protection: [Requirements]
- Audit/Logging: [Requirements]
- Architectural Implications: [Implications for architecture]
### Scalability Requirements
- User Scalability: [Requirements]
- Data Scalability: [Requirements]
- Transaction Scalability: [Requirements]
- Architectural Implications: [Implications for architecture]
### Availability Requirements
- Uptime Requirements: [Requirements]
- Fault Tolerance: [Requirements]
- Disaster Recovery: [Requirements]
- Architectural Implications: [Implications for architecture]
### Maintainability Requirements
- Modularity: [Requirements]
- Extensibility: [Requirements]
- Testability: [Requirements]
- Architectural Implications: [Implications for architecture]
```
## 📋 BUSINESS CONTEXT DOCUMENTATION
Document the business context to ensure architectural alignment:
```markdown
## Business Context Documentation
### Business Objectives
- Objective 1: [Description]
- Objective 2: [Description]
- Objective 3: [Description]
### Key Stakeholders
- Stakeholder Group 1: [Description, needs, and concerns]
- Stakeholder Group 2: [Description, needs, and concerns]
- Stakeholder Group 3: [Description, needs, and concerns]
### Business Processes
- Process 1: [Description and flow]
- Process 2: [Description and flow]
- Process 3: [Description and flow]
### Business Constraints
- Constraint 1: [Description and impact]
- Constraint 2: [Description and impact]
- Constraint 3: [Description and impact]
### Business Metrics
- Metric 1: [Description and target]
- Metric 2: [Description and target]
- Metric 3: [Description and target]
### Business Risks
- Risk 1: [Description, probability, impact, and mitigation]
- Risk 2: [Description, probability, impact, and mitigation]
- Risk 3: [Description, probability, impact, and mitigation]
```
## 📋 ARCHITECTURAL VISION AND GOALS
Document the architectural vision and goals:
```markdown
## Architectural Vision and Goals
### Vision Statement
[Concise statement of the architectural vision]
### Strategic Goals
- Goal 1: [Description and success criteria]
- Goal 2: [Description and success criteria]
- Goal 3: [Description and success criteria]
### Quality Attributes
- Quality Attribute 1: [Description and importance]
- Quality Attribute 2: [Description and importance]
- Quality Attribute 3: [Description and importance]
### Technical Roadmap
- Short-term (0-6 months): [Key architectural milestones]
- Medium-term (6-18 months): [Key architectural milestones]
- Long-term (18+ months): [Key architectural milestones]
### Key Success Indicators
- Indicator 1: [Description and measurement]
- Indicator 2: [Description and measurement]
- Indicator 3: [Description and measurement]
```
## 📋 ARCHITECTURAL PRINCIPLES
Document architectural principles to guide decision-making:
```markdown
## Architectural Principles
### Principle 1: [Name]
- **Statement**: [Concise statement of the principle]
- **Rationale**: [Why this principle is important]
- **Implications**: [What this principle means for the architecture]
- **Examples**: [Examples of applying this principle]
### Principle 2: [Name]
- **Statement**: [Concise statement of the principle]
- **Rationale**: [Why this principle is important]
- **Implications**: [What this principle means for the architecture]
- **Examples**: [Examples of applying this principle]
### Principle 3: [Name]
- **Statement**: [Concise statement of the principle]
- **Rationale**: [Why this principle is important]
- **Implications**: [What this principle means for the architecture]
- **Examples**: [Examples of applying this principle]
...
```
## 📋 CONSTRAINTS IDENTIFICATION
Document constraints that impact architectural decisions:
```markdown
## Architectural Constraints
### Technical Constraints
- Constraint 1: [Description and impact]
- Constraint 2: [Description and impact]
- Constraint 3: [Description and impact]
### Organizational Constraints
- Constraint 1: [Description and impact]
- Constraint 2: [Description and impact]
- Constraint 3: [Description and impact]
### External Constraints
- Constraint 1: [Description and impact]
- Constraint 2: [Description and impact]
- Constraint 3: [Description and impact]
### Regulatory/Compliance Constraints
- Constraint 1: [Description and impact]
- Constraint 2: [Description and impact]
- Constraint 3: [Description and impact]
### Resource Constraints
- Constraint 1: [Description and impact]
- Constraint 2: [Description and impact]
- Constraint 3: [Description and impact]
```
## 📋 ARCHITECTURAL ALTERNATIVES EXPLORATION
Document and evaluate architectural alternatives:
```markdown
## Architectural Alternatives
### Alternative 1: [Name]
- **Description**: [Brief description of the alternative]
- **Key Components**:
- Component 1: [Description]
- Component 2: [Description]
- Component 3: [Description]
- **Advantages**:
- [Advantage 1]
- [Advantage 2]
- [Advantage 3]
- **Disadvantages**:
- [Disadvantage 1]
- [Disadvantage 2]
- [Disadvantage 3]
- **Risks**:
- [Risk 1]
- [Risk 2]
- [Risk 3]
- **Cost Factors**:
- [Cost Factor 1]
- [Cost Factor 2]
- [Cost Factor 3]
- **Alignment with Requirements**:
- [How well this alternative addresses requirements]
### Alternative 2: [Name]
...
### Alternative 3: [Name]
...
## Evaluation Criteria
- Criterion 1: [Description and weighting]
- Criterion 2: [Description and weighting]
- Criterion 3: [Description and weighting]
## Evaluation Matrix
| Criterion | Alternative 1 | Alternative 2 | Alternative 3 |
|-----------|---------------|---------------|---------------|
| Criterion 1 | Score | Score | Score |
| Criterion 2 | Score | Score | Score |
| Criterion 3 | Score | Score | Score |
| Total | Sum | Sum | Sum |
## Recommended Approach
[Description of the recommended architectural approach with justification]
```
## 📋 ARCHITECTURE DECISION RECORDS (ADRs)
Document key architectural decisions:
```markdown
# Architecture Decision Record: [Decision Title]
## Status
[Proposed/Accepted/Deprecated/Superseded]
## Context
[Description of the context and problem statement]
## Decision
[Description of the decision made]
## Consequences
[Description of the consequences of the decision]
## Alternatives Considered
[Description of alternatives considered]
## Related Decisions
[References to related decisions]
## Notes
[Additional notes and considerations]
```
## 📋 COMPREHENSIVE ARCHITECTURE DOCUMENTATION
Create comprehensive architecture documentation:
### System Context Diagram
```mermaid
flowchart TD
classDef system fill:#f9d77e,stroke:#d9b95c,color:#000
classDef external fill:#a8d5ff,stroke:#88b5e0,color:#000
classDef user fill:#c5e8b7,stroke:#a5c897,color:#000
U1[User 1] --> S[System]
U2[User 2] --> S
S --> E1[External<br>System 1]
S --> E2[External<br>System 2]
S --> E3[External<br>System 3]
class S system
class E1,E2,E3 external
class U1,U2 user
```
### High-Level Architecture Diagram
```mermaid
flowchart TD
classDef frontend fill:#f9d77e,stroke:#d9b95c,color:#000
classDef backend fill:#a8d5ff,stroke:#88b5e0,color:#000
classDef data fill:#c5e8b7,stroke:#a5c897,color:#000
classDef integration fill:#f4b8c4,stroke:#d498a4,color:#000
U[Users] --> F[Frontend<br>Layer]
F --> B[Backend<br>Layer]
B --> D[Data<br>Layer]
B --> I[Integration<br>Layer]
I --> E[External<br>Systems]
class F frontend
class B backend
class D data
class I integration
class U,E external
```
### Component Architecture Diagram
```mermaid
flowchart TD
classDef ui fill:#f9d77e,stroke:#d9b95c,color:#000
classDef service fill:#a8d5ff,stroke:#88b5e0,color:#000
classDef data fill:#c5e8b7,stroke:#a5c897,color:#000
UI[User Interface] --> API[API Gateway]
API --> S1[Service 1]
API --> S2[Service 2]
API --> S3[Service 3]
S1 --> DB1[Database 1]
S2 --> DB1
S2 --> DB2[Database 2]
S3 --> DB2
class UI ui
class API,S1,S2,S3 service
class DB1,DB2 data
```
### Data Architecture Diagram
```mermaid
flowchart TD
classDef entity fill:#f9d77e,stroke:#d9b95c,color:#000
classDef relation fill:#a8d5ff,stroke:#88b5e0,color:#000
E1[Entity 1] -- 1:N --> E2[Entity 2]
E1 -- 1:1 --> E3[Entity 3]
E2 -- N:M --> E4[Entity 4]
E3 -- 1:N --> E4
class E1,E2,E3,E4 entity
```
### Security Architecture Diagram
```mermaid
flowchart TD
classDef security fill:#f9d77e,stroke:#d9b95c,color:#000
classDef app fill:#a8d5ff,stroke:#88b5e0,color:#000
U[Users] --> WAF[Web Application<br>Firewall]
WAF --> LB[Load<br>Balancer]
LB --> API[API Gateway]
API --> AuthZ[Authorization<br>Service]
API --> S1[Service 1]
API --> S2[Service 2]
AuthZ --> IAM[Identity &<br>Access Management]
class WAF,AuthZ,IAM security
class API,S1,S2 app
class U,LB external
```
### Deployment Architecture Diagram
```mermaid
flowchart TD
classDef env fill:#f9d77e,stroke:#d9b95c,color:#000
classDef component fill:#a8d5ff,stroke:#88b5e0,color:#000
subgraph Production
LB[Load Balancer] --> W1[Web Server 1]
LB --> W2[Web Server 2]
W1 & W2 --> A1[App Server 1]
W1 & W2 --> A2[App Server 2]
A1 & A2 --> DB[Database<br>Cluster]
end
class Production env
class LB,W1,W2,A1,A2,DB component
```
### Architecture Documentation Template
```markdown
# System Architecture Document
## 1. Introduction
- **Purpose**: [Purpose of the architecture]
- **Scope**: [Scope of the architecture]
- **Audience**: [Intended audience for the document]
- **References**: [Related documents and references]
## 2. System Context
- **System Purpose**: [Brief description of system purpose]
- **Context Diagram**: [System context diagram]
- **External Systems**: [Description of external systems and interfaces]
- **User Types**: [Description of user types and interactions]
## 3. Architecture Overview
- **Architecture Style**: [Description of the architectural style/pattern]
- **High-Level Architecture**: [High-level architecture diagram]
- **Key Components**: [Overview of key components]
- **Technology Stack**: [Overview of technology stack]
## 4. Component Architecture
- **Component Diagram**: [Component architecture diagram]
- **Component Descriptions**:
- Component 1: [Description, responsibilities, interfaces]
- Component 2: [Description, responsibilities, interfaces]
- Component 3: [Description, responsibilities, interfaces]
- **Component Interactions**: [Description of component interactions]
- **API Specifications**: [Overview of key APIs]
## 5. Data Architecture
- **Data Model**: [Data architecture diagram]
- **Entity Descriptions**:
- Entity 1: [Description, attributes, relationships]
- Entity 2: [Description, attributes, relationships]
- Entity 3: [Description, attributes, relationships]
- **Data Storage**: [Description of data storage approaches]
- **Data Access**: [Description of data access patterns]
- **Data Migration**: [Overview of data migration approach]
## 6. Security Architecture
- **Security Model**: [Security architecture diagram]
- **Authentication**: [Authentication approach]
- **Authorization**: [Authorization approach]
- **Data Protection**: [Data protection mechanisms]
- **Security Controls**: [Key security controls]
- **Audit and Logging**: [Audit and logging approach]
## 7. Deployment Architecture
- **Deployment Model**: [Deployment architecture diagram]
- **Environment Descriptions**:
- Environment 1: [Description and configuration]
- Environment 2: [Description and configuration]
- Environment 3: [Description and configuration]
- **Infrastructure Requirements**: [Infrastructure requirements]
- **Scaling Approach**: [Scaling approach]
## 8. Quality Attributes
- **Performance**: [Performance characteristics and mechanisms]
- **Scalability**: [Scalability approach]
- **Availability**: [Availability approach]
- **Maintainability**: [Maintainability approach]
- **Reliability**: [Reliability approach]
- **Portability**: [Portability considerations]
## 9. Cross-Cutting Concerns
- **Logging**: [Logging approach]
- **Error Handling**: [Error handling approach]
- **Monitoring**: [Monitoring approach]
- **Configuration Management**: [Configuration management approach]
- **Internationalization**: [Internationalization approach]
## 10. Architecture Decisions
- [References to Architecture Decision Records]
## 11. Risks and Mitigations
- Risk 1: [Description and mitigation]
- Risk 2: [Description and mitigation]
- Risk 3: [Description and mitigation]
## 12. Glossary
- Term 1: [Definition]
- Term 2: [Definition]
- Term 3: [Definition]
```
## 📋 ARCHITECTURE VALIDATION
Validate architecture against requirements and principles:
```markdown
## Architecture Validation
### Requirements Coverage
- Requirement 1: [Covered/Partially Covered/Not Covered] - [Explanation]
- Requirement 2: [Covered/Partially Covered/Not Covered] - [Explanation]
- Requirement 3: [Covered/Partially Covered/Not Covered] - [Explanation]
### Principles Alignment
- Principle 1: [Aligned/Partially Aligned/Not Aligned] - [Explanation]
- Principle 2: [Aligned/Partially Aligned/Not Aligned] - [Explanation]
- Principle 3: [Aligned/Partially Aligned/Not Aligned] - [Explanation]
### Quality Attribute Scenarios
- Scenario 1: [Description and validation]
- Scenario 2: [Description and validation]
- Scenario 3: [Description and validation]
### Architecture Review Findings
- Finding 1: [Description and resolution]
- Finding 2: [Description and resolution]
- Finding 3: [Description and resolution]
### Risk Assessment
- Risk 1: [Description, probability, impact, and mitigation]
- Risk 2: [Description, probability, impact, and mitigation]
- Risk 3: [Description, probability, impact, and mitigation]
### Validation Outcome
[Summary of validation outcome and next steps]
```
## 📋 ARCHITECTURE COMMUNICATION
Communicate architecture to stakeholders:
```markdown
## Architecture Communication Plan
### Key Stakeholders
- Stakeholder Group 1: [Communication needs]
- Stakeholder Group 2: [Communication needs]
- Stakeholder Group 3: [Communication needs]
### Communication Materials
- **Executive Summary**: [Purpose and audience]
- **Technical Reference**: [Purpose and audience]
- **Developer Guide**: [Purpose and audience]
- **Operations Guide**: [Purpose and audience]
### Communication Schedule
- Event 1: [Date, audience, purpose]
- Event 2: [Date, audience, purpose]
- Event 3: [Date, audience, purpose]
### Feedback Mechanism
[Description of how feedback will be collected and incorporated]
```
## 📋 MEMORY BANK INTEGRATION
```mermaid
flowchart TD
classDef memfile fill:#f4b8c4,stroke:#d498a4,color:#000
classDef process fill:#f9d77e,stroke:#d9b95c,color:#000
Architecture[Architectural<br>Planning] --> PB[projectbrief.md]
Architecture --> PC[productContext.md]
Architecture --> SP[systemPatterns.md]
Architecture --> TC[techContext.md]
PB & PC & SP & TC --> MBI[Memory Bank<br>Integration]
MBI --> Next[Implementation<br>Phase]
class PB,PC,SP,TC memfile
class Architecture,MBI,Next process
```
### Memory Bank Updates
Update the following Memory Bank files during architectural planning:
1. **projectbrief.md**
- Update with architectural vision
- Document high-level architecture approach
- Link to architecture documentation
2. **productContext.md**
- Update with business context documentation
- Document key stakeholder requirements
- Capture business drivers for architectural decisions
3. **systemPatterns.md**
- Document architectural patterns and styles chosen
- Capture key architecture decisions with rationales
- Document technical patterns to be used
4. **techContext.md**
- Update with technology stack decisions
- Document technical constraints and considerations
- Capture integration approaches
## 📋 ARCHITECTURAL PLANNING VERIFICATION CHECKLIST
```
✓ ARCHITECTURAL PLANNING VERIFICATION CHECKLIST
Requirements Analysis
- Functional requirements analyzed? [YES/NO]
- Non-functional requirements analyzed? [YES/NO]
- Domain model created? [YES/NO]
- Component identification completed? [YES/NO]
Business Context
- Business objectives documented? [YES/NO]
- Key stakeholders identified? [YES/NO]
- Business processes documented? [YES/NO]
- Business constraints identified? [YES/NO]
Vision and Goals
- Architectural vision stated? [YES/NO]
- Strategic goals defined? [YES/NO]
- Quality attributes identified? [YES/NO]
- Technical roadmap created? [YES/NO]
Architectural Principles
- Core principles defined? [YES/NO]
- Principles have clear rationales? [YES/NO]
- Implications of principles documented? [YES/NO]
- Examples of applying principles provided? [YES/NO]
Constraints Identification
- Technical constraints documented? [YES/NO]
- Organizational constraints documented? [YES/NO]
- External constraints documented? [YES/NO]
- Regulatory constraints documented? [YES/NO]
Alternatives Exploration
- Multiple alternatives identified? [YES/NO]
- Alternatives evaluated against criteria? [YES/NO]
- Advantages and disadvantages documented? [YES/NO]
- Recommended approach justified? [YES/NO]
Architecture Documentation
- System context documented? [YES/NO]
- High-level architecture documented? [YES/NO]
- Component architecture documented? [YES/NO]
- Data architecture documented? [YES/NO]
- Security architecture documented? [YES/NO]
- Deployment architecture documented? [YES/NO]
Architecture Validation
- Requirements coverage validated? [YES/NO]
- Principles alignment checked? [YES/NO]
- Quality attribute scenarios assessed? [YES/NO]
- Architecture review conducted? [YES/NO]
Memory Bank Integration
- projectbrief.md updated? [YES/NO]
- productContext.md updated? [YES/NO]
- systemPatterns.md updated? [YES/NO]
- techContext.md updated? [YES/NO]
```
## 📋 MINIMAL MODE ARCHITECTURE PLANNING FORMAT
For situations requiring a more compact architectural planning approach:
```markdown
## Level 4 Architecture Planning: [System Name]
### System Context
- **Purpose**: [Brief description of system purpose]
- **Users**: [Primary users]
- **External Systems**: [Key external systems]
### Key Architectural Decisions
- **Architecture Style**: [Chosen style with brief rationale]
- **Component Structure**: [Key components with brief descriptions]
- **Data Model**: [Brief description of data approach]
- **Technical Stack**: [Key technologies]
### Quality Attributes
- **Performance**: [Brief description of approach]
- **Security**: [Brief description of approach]
- **Scalability**: [Brief description of approach]
- **Maintainability**: [Brief description of approach]
### Architecture Diagram
[Simple architecture diagram]
### Key Risks and Mitigations
- **Risk 1**: [Brief description] - **Mitigation**: [Brief approach]
- **Risk 2**: [Brief description] - **Mitigation**: [Brief approach]
### Memory Bank Updates
- [Brief description of updates needed]
```
## 🚨 ARCHITECTURAL PLANNING ENFORCEMENT PRINCIPLE
```
┌─────────────────────────────────────────────────────┐
│ ARCHITECTURAL PLANNING IS MANDATORY for Level 4 │
│ tasks. Implementation CANNOT begin until │
│ architectural planning is complete and approved. │
└─────────────────────────────────────────────────────┘
```
@@ -0,0 +1,684 @@
---
description: Comprehensive archiving approach for Level 4 Complex System tasks
globs: "**/level4/**", "**/archive/**"
alwaysApply: false
---
# COMPREHENSIVE ARCHIVING FOR LEVEL 4 TASKS
> **TL;DR:** This document outlines a comprehensive archiving approach for Level 4 (Complex System) tasks, ensuring all system knowledge, decisions, implementation details, and lessons learned are preserved for future reference and reuse.
## 🔍 COMPREHENSIVE ARCHIVING OVERVIEW
Level 4 Complex System tasks require thorough archiving to preserve system knowledge, design decisions, implementation details, and lessons learned. This systematic archiving process ensures that the organization maintains institutional knowledge and enables future teams to understand, maintain, and extend the system.
```mermaid
flowchart TD
classDef phase fill:#f9d77e,stroke:#d9b95c,color:#000
classDef artifact fill:#f4b8c4,stroke:#d498a4,color:#000
classDef verification fill:#c5e8b7,stroke:#a5c897,color:#000
Start([Begin Archiving<br>Process]) --> Template[Load Comprehensive<br>Archive Template]
Template --> RefDoc[Review Reflection<br>Document]
RefDoc --> SysDoc[Create System<br>Documentation]
SysDoc --> ArchDoc[Document Architecture<br>and Design]
ArchDoc --> ImplDoc[Document Implementation<br>Details]
ImplDoc --> APIDoc[Create API<br>Documentation]
APIDoc --> DataDoc[Document Data<br>Models and Schemas]
DataDoc --> SecDoc[Document Security<br>Measures]
SecDoc --> TestDoc[Document Testing<br>Procedures and Results]
TestDoc --> DeployDoc[Document Deployment<br>Procedures]
DeployDoc --> OpDoc[Create Operational<br>Documentation]
OpDoc --> KnowledgeDoc[Create Knowledge<br>Transfer Documentation]
KnowledgeDoc --> CrossRef[Create Cross-Reference<br>Documentation]
CrossRef --> Archive[Archive All<br>Project Materials]
Archive --> UpdateMB[Update Memory<br>Bank]
UpdateMB --> Verification{Archiving<br>Verification}
Verification -->|Pass| Complete([Archiving<br>Complete])
Verification -->|Fail| Revise[Revise<br>Archiving]
Revise --> Verification
Template -.-> AT((Archive<br>Template))
SysDoc -.-> SD((System<br>Documentation))
ArchDoc -.-> AD((Architecture<br>Documentation))
ImplDoc -.-> ID((Implementation<br>Documentation))
APIDoc & DataDoc -.-> IntDoc((Interface<br>Documentation))
TestDoc & DeployDoc & OpDoc -.-> OpDocs((Operational<br>Documentation))
class Start,Complete milestone
class Template,RefDoc,SysDoc,ArchDoc,ImplDoc,APIDoc,DataDoc,SecDoc,TestDoc,DeployDoc,OpDoc,KnowledgeDoc,CrossRef,Archive,UpdateMB step
class Verification verification
class AT,SD,AD,ID,IntDoc,OpDocs artifact
```
## 📋 ARCHIVE TEMPLATE STRUCTURE
### 1. System Overview
```markdown
## System Overview
### System Purpose and Scope
[Comprehensive description of the system purpose, scope, and business context]
### System Architecture
[Summary of the architecture, including diagrams, patterns, and key design decisions]
### Key Components
- Component 1: [Description and purpose]
- Component 2: [Description and purpose]
- Component 3: [Description and purpose]
### Integration Points
[Description of all internal and external integration points]
### Technology Stack
[Comprehensive list of all technologies, frameworks, and tools used]
### Deployment Environment
[Description of the deployment environment, infrastructure, and configuration]
```
### 2. Requirements and Design Documentation
```markdown
## Requirements and Design Documentation
### Business Requirements
[Comprehensive list of business requirements with traceability]
### Functional Requirements
[Detailed functional requirements with implementation mapping]
### Non-Functional Requirements
[Non-functional requirements with implementation approaches]
### Architecture Decision Records
[Collection of all architecture decision records (ADRs)]
### Design Patterns Used
[Catalog of all design patterns with usage examples]
### Design Constraints
[Documentation of all design constraints and their impact]
### Design Alternatives Considered
[Summary of alternatives considered and reasons for final selections]
```
### 3. Implementation Documentation
```markdown
## Implementation Documentation
### Component Implementation Details
- **Component 1**:
- **Purpose**: [Component purpose]
- **Implementation approach**: [Implementation details]
- **Key classes/modules**: [List with descriptions]
- **Dependencies**: [Internal and external dependencies]
- **Special considerations**: [Important notes]
- **Component 2**:
- **Purpose**: [Component purpose]
- **Implementation approach**: [Implementation details]
- **Key classes/modules**: [List with descriptions]
- **Dependencies**: [Internal and external dependencies]
- **Special considerations**: [Important notes]
### Key Files and Components Affected (from tasks.md)
[Summary or direct copy of file/component checklists from the original tasks.md for this project. This provides a quick reference to the scope of changes at a component/file level.]
### Algorithms and Complex Logic
[Documentation of key algorithms and complex business logic]
### Third-Party Integrations
[Details of all third-party integrations including APIs and libraries]
### Configuration Parameters
[Complete listing of all configuration parameters and their purpose]
### Build and Packaging Details
[Documentation of build process, packaging, and artifacts]
```
### 4. API Documentation
```markdown
## API Documentation
### API Overview
[High-level overview of all APIs (internal and external)]
### API Endpoints
- **Endpoint 1**:
- **URL/Path**: [Endpoint URL or path]
- **Method**: [HTTP method]
- **Purpose**: [Purpose of the endpoint]
- **Request Format**: [Request format with examples]
- **Response Format**: [Response format with examples]
- **Error Codes**: [Possible error codes and meanings]
- **Security**: [Security considerations]
- **Rate Limits**: [Any rate limits]
- **Notes**: [Additional notes]
- **Endpoint 2**:
- **URL/Path**: [Endpoint URL or path]
- **Method**: [HTTP method]
- **Purpose**: [Purpose of the endpoint]
- **Request Format**: [Request format with examples]
- **Response Format**: [Response format with examples]
- **Error Codes**: [Possible error codes and meanings]
- **Security**: [Security considerations]
- **Rate Limits**: [Any rate limits]
- **Notes**: [Additional notes]
### API Authentication
[Authentication methods and implementation details]
### API Versioning Strategy
[Versioning approach and migration strategy]
### SDK or Client Libraries
[Available SDKs or client libraries with usage examples]
```
### 5. Data Model and Schema Documentation
```markdown
## Data Model and Schema Documentation
### Data Model Overview
[High-level overview of the data model with entity relationship diagrams]
### Database Schema
[Detailed database schema with tables, columns, and relationships]
### Data Dictionary
[Comprehensive data dictionary with all entities and attributes]
### Data Validation Rules
[Data validation rules and enforcement mechanisms]
### Data Migration Procedures
[Procedures for data migration and version management]
### Data Archiving Strategy
[Strategy for data archiving and retention]
```
### 6. Security Documentation
```markdown
## Security Documentation
### Security Architecture
[Overview of security architecture and design principles]
### Authentication and Authorization
[Detailed implementation of authentication and authorization]
### Data Protection Measures
[Measures implemented to protect sensitive data]
### Security Controls
[Technical and procedural security controls]
### Vulnerability Management
[Approach to vulnerability management and patching]
### Security Testing Results
[Summary of security testing and assessments]
### Compliance Considerations
[Regulatory and compliance considerations addressed]
```
### 7. Testing Documentation
```markdown
## Testing Documentation
### Test Strategy
[Overall testing strategy and approach]
### Test Cases
[Catalog of test cases with expected results]
### Automated Tests
[Documentation of automated tests and frameworks]
### Performance Test Results
[Results of performance testing with benchmarks]
### Security Test Results
[Results of security testing with findings]
### User Acceptance Testing
[UAT approach, scenarios, and results]
### Known Issues and Limitations
[Documentation of known issues and system limitations]
```
### 8. Deployment Documentation
```markdown
## Deployment Documentation
### Deployment Architecture
[Detailed deployment architecture with diagrams]
### Environment Configuration
[Configuration details for all environments]
### Deployment Procedures
[Step-by-step deployment procedures]
### Configuration Management
[Configuration management approach and tools]
### Release Management
[Release management process and procedures]
### Rollback Procedures
[Procedures for rolling back deployments]
### Monitoring and Alerting
[Monitoring setup, metrics, and alerting configuration]
```
### 9. Operational Documentation
```markdown
## Operational Documentation
### Operating Procedures
[Day-to-day operational procedures]
### Maintenance Tasks
[Routine maintenance tasks and schedules]
### Troubleshooting Guide
[Guide for troubleshooting common issues]
### Backup and Recovery
[Backup and recovery procedures]
### Disaster Recovery
[Disaster recovery plan and procedures]
### Performance Tuning
[Performance tuning guidelines and procedures]
### SLAs and Metrics
[Service level agreements and key performance metrics]
```
### 10. Knowledge Transfer Documentation
```markdown
## Knowledge Transfer Documentation
### System Overview for New Team Members
[Concise system overview for onboarding]
### Key Concepts and Terminology
[Glossary of key concepts and terminology]
### Common Tasks and Procedures
[Guide to common tasks and procedures]
### Frequently Asked Questions
[FAQs for system users and maintainers]
### Training Materials
[Training materials for different roles]
### Support Escalation Process
[Process for escalating support issues]
### Further Reading and Resources
[Additional resources and documentation]
```
### 11. Project History and Learnings
```markdown
## Project History and Learnings
### Project Timeline
[Summary of the project timeline and key milestones]
### Key Decisions and Rationale
[Record of key decisions and their rationale]
### Challenges and Solutions
[Documentation of challenges faced and how they were addressed]
### Lessons Learned
[Key lessons learned that might benefit future projects]
### Performance Against Objectives
[Assessment of performance against original objectives]
### Future Enhancements
[Potential future enhancements and extensions]
```
## 📋 ARCHIVING PROCESS
### 1. Preparation
```mermaid
flowchart TD
classDef step fill:#f9d77e,stroke:#d9b95c,color:#000
classDef artifact fill:#f4b8c4,stroke:#d498a4,color:#000
Start([Begin Archive<br>Preparation]) --> Template[Load Archive<br>Template]
Template --> Review[Review Project<br>Documentation]
Review --> Identify[Identify All<br>Artifacts]
Identify --> Gather[Gather All<br>Materials]
Gather --> Organize[Organize<br>Materials]
Organize --> Plan[Create Archiving<br>Plan]
Plan --> Resources[Allocate<br>Resources]
Resources --> Complete([Preparation<br>Complete])
Template -.-> AT((Archive<br>Template))
Review -.-> ProjDocs((Project<br>Documentation))
Identify -.-> ArtList((Artifact<br>List))
Plan -.-> ArchPlan((Archiving<br>Plan))
class Start,Complete milestone
class Template,Review,Identify,Gather,Organize,Plan,Resources step
class AT,ProjDocs,ArtList,ArchPlan artifact
```
**Key Preparation Steps:**
1. Load the comprehensive archive template
2. Review all project documentation including reflection document
3. Identify all artifacts to be archived
4. Gather all materials from various sources
5. Organize materials according to the archive structure
6. Create a detailed archiving plan
7. Allocate resources for the archiving process
### 2. Documentation Creation
```mermaid
flowchart TD
classDef step fill:#f9d77e,stroke:#d9b95c,color:#000
classDef artifact fill:#f4b8c4,stroke:#d498a4,color:#000
Start([Begin Documentation<br>Creation]) --> System[Create System<br>Documentation]
System --> Req[Create Requirements<br>and Design Documentation]
Req --> Impl[Create Implementation<br>Documentation]
Impl --> API[Create API<br>Documentation]
API --> Data[Create Data Model<br>Documentation]
Data --> Security[Create Security<br>Documentation]
Security --> Test[Create Testing<br>Documentation]
Test --> Deploy[Create Deployment<br>Documentation]
Deploy --> Ops[Create Operational<br>Documentation]
Ops --> Knowledge[Create Knowledge Transfer<br>Documentation]
Knowledge --> History[Create Project History<br>Documentation]
History --> Review[Review All<br>Documentation]
Review --> Complete([Documentation<br>Creation Complete])
System -.-> SysDoc((System<br>Documentation))
Req -.-> ReqDoc((Requirements<br>Documentation))
Impl -.-> ImplDoc((Implementation<br>Documentation))
API -.-> APIDoc((API<br>Documentation))
Data -.-> DataDoc((Data Model<br>Documentation))
Security -.-> SecDoc((Security<br>Documentation))
Test -.-> TestDoc((Testing<br>Documentation))
Deploy -.-> DeployDoc((Deployment<br>Documentation))
Ops -.-> OpsDoc((Operational<br>Documentation))
Knowledge -.-> KnowDoc((Knowledge Transfer<br>Documentation))
History -.-> HistDoc((Project History<br>Documentation))
class Start,Complete milestone
class System,Req,Impl,API,Data,Security,Test,Deploy,Ops,Knowledge,History,Review step
class SysDoc,ReqDoc,ImplDoc,APIDoc,DataDoc,SecDoc,TestDoc,DeployDoc,OpsDoc,KnowDoc,HistDoc artifact
```
**Key Documentation Steps:**
1. Create comprehensive system documentation
2. Document requirements and design decisions
3. Document implementation details for all components
4. Create complete API documentation
5. Document data models and schemas
6. Document security measures and controls
7. Create thorough testing documentation
8. Document deployment procedures
9. Create operational documentation
10. Prepare knowledge transfer documentation
11. Document project history and learnings
12. Review all documentation for completeness and accuracy
### 3. Archiving and Integration
```mermaid
flowchart TD
classDef step fill:#f9d77e,stroke:#d9b95c,color:#000
classDef artifact fill:#f4b8c4,stroke:#d498a4,color:#000
classDef verification fill:#c5e8b7,stroke:#a5c897,color:#000
Start([Begin Archiving<br>and Integration]) --> Consolidate[Consolidate All<br>Documentation]
Consolidate --> CrossRef[Create Cross-Reference<br>Index]
CrossRef --> Version[Version All<br>Documentation]
Version --> Archive[Archive in<br>Repository]
Archive --> UpdateMB[Update Memory<br>Bank]
UpdateMB --> AccessControl[Establish Access<br>Controls]
AccessControl --> Announce[Announce<br>Availability]
Announce --> Verification{Archiving<br>Verification}
Verification -->|Pass| Complete([Archiving<br>Complete])
Verification -->|Fail| Revise[Revise<br>Archiving]
Revise --> Verification
Consolidate -.-> AllDocs((Consolidated<br>Documentation))
CrossRef -.-> Index((Cross-Reference<br>Index))
Archive -.-> Repo((Archive<br>Repository))
UpdateMB -.-> MB((Updated Memory<br>Bank))
class Start,Complete milestone
class Consolidate,CrossRef,Version,Archive,UpdateMB,AccessControl,Announce,Revise step
class Verification verification
class AllDocs,Index,Repo,MB artifact
```
**Key Archiving Steps:**
1. Consolidate all documentation into a cohesive package
2. Create a cross-reference index linking all documentation
3. Version all documentation appropriately
4. Archive in the designated repository
5. Update Memory Bank with relevant information
6. Establish appropriate access controls
7. Announce availability to relevant stakeholders
8. Verify archiving completeness and accessibility
## 📋 MEMORY BANK INTEGRATION
```mermaid
flowchart TD
classDef memfile fill:#f4b8c4,stroke:#d498a4,color:#000
classDef process fill:#f9d77e,stroke:#d9b95c,color:#000
Archiving[Comprehensive<br>Archiving] --> PB[projectbrief.md]
Archiving --> PC[productContext.md]
Archiving --> AC[activeContext.md]
Archiving --> SP[systemPatterns.md]
Archiving --> TC[techContext.md]
Archiving --> P[progress.md]
PB & PC & AC & SP & TC & P --> MBI[Memory Bank<br>Integration]
MBI --> Next[Repository of<br>Knowledge]
class PB,PC,AC,SP,TC,P memfile
class Archiving,MBI,Next process
```
### Memory Bank Updates
Specific updates to make to Memory Bank files:
1. **projectbrief.md**
- Update with final system description
- Document completion status
- Include links to archived documentation
2. **productContext.md**
- Update with final business context
- Document business value delivered
- Include links to requirements documentation
3. **activeContext.md**
- Update with system status (completed)
- Document handover information
- Include links to operational documentation
4. **systemPatterns.md**
- Update with final architecture patterns
- Document successful implementation patterns
- Include links to architecture documentation
5. **techContext.md**
- Update with final technology stack
- Document integration points
- Include links to technical documentation
6. **progress.md**
- Update with final project status
- Document completion metrics
- Include links to project history documentation
## 📋 ARCHIVING VERIFICATION CHECKLIST
```
✓ ARCHIVING VERIFICATION CHECKLIST
System Documentation
- System overview complete? [YES/NO]
- Architecture documented with diagrams? [YES/NO]
- Key components documented? [YES/NO]
- Integration points documented? [YES/NO]
Requirements and Design
- Business requirements documented? [YES/NO]
- Functional requirements documented? [YES/NO]
- Architecture decisions documented? [YES/NO]
- Design patterns documented? [YES/NO]
Implementation
- Component implementation details documented? [YES/NO]
- Key algorithms documented? [YES/NO]
- Third-party integrations documented? [YES/NO]
- Configuration parameters documented? [YES/NO]
API Documentation
- API endpoints documented? [YES/NO]
- Request/response formats documented? [YES/NO]
- Authentication documented? [YES/NO]
- Error handling documented? [YES/NO]
Data Documentation
- Data model documented? [YES/NO]
- Database schema documented? [YES/NO]
- Data dictionary provided? [YES/NO]
- Data validation rules documented? [YES/NO]
Security Documentation
- Security architecture documented? [YES/NO]
- Authentication/authorization documented? [YES/NO]
- Data protection measures documented? [YES/NO]
- Security testing results documented? [YES/NO]
Testing Documentation
- Test strategy documented? [YES/NO]
- Test cases documented? [YES/NO]
- Test results documented? [YES/NO]
- Known issues documented? [YES/NO]
Deployment Documentation
- Deployment architecture documented? [YES/NO]
- Environment configurations documented? [YES/NO]
- Deployment procedures documented? [YES/NO]
- Rollback procedures documented? [YES/NO]
Operational Documentation
- Operating procedures documented? [YES/NO]
- Troubleshooting guide provided? [YES/NO]
- Backup and recovery documented? [YES/NO]
- Monitoring configuration documented? [YES/NO]
Knowledge Transfer
- Onboarding overview provided? [YES/NO]
- Key concepts documented? [YES/NO]
- Common tasks documented? [YES/NO]
- FAQs provided? [YES/NO]
Project History
- Project timeline documented? [YES/NO]
- Key decisions documented? [YES/NO]
- Lessons learned documented? [YES/NO]
- Future enhancements suggested? [YES/NO]
Memory Bank Integration
- All Memory Bank files updated? [YES/NO]
- Cross-references created? [YES/NO]
- Documentation properly versioned? [YES/NO]
- Archive repository established? [YES/NO]
```
## 📋 MINIMAL MODE ARCHIVING FORMAT
For situations requiring a more compact archiving approach:
```markdown
## Level 4 Task Archive: [System Name]
### System Summary
- **Purpose**: [Brief description of system purpose]
- **Key Components**: [List of key components]
- **Architecture**: [Brief architecture description with diagram]
### Implementation Summary
- **Technology Stack**: [Key technologies used]
- **Key Modules**: [Brief description of important modules]
- **Integration Points**: [List of major integration points]
### Critical Documentation
- **API Documentation**: [Link or brief summary]
- **Data Model**: [Link or brief description]
- **Deployment Configuration**: [Link or brief description]
- **Security Measures**: [Link or brief summary]
### Operational Information
- **Deployment Procedure**: [Link or brief description]
- **Key Configuration Parameters**: [List of important parameters]
- **Monitoring Setup**: [Brief monitoring details]
- **Common Issues**: [List of common issues with solutions]
### Repository Information
- **Code Repository**: [Link to repository]
- **Documentation Repository**: [Link to documentation]
- **Build Artifacts**: [Link to build artifacts]
### Knowledge Transfer Summary
- **Key Contacts**: [List of key people with knowledge]
- **Critical Knowledge Areas**: [Areas requiring special expertise]
- **Training Resources**: [Links to training materials]
### Memory Bank Links
- [Links to updated Memory Bank files]
```
## 🚨 ARCHIVING ENFORCEMENT PRINCIPLE
```
┌─────────────────────────────────────────────────────┐
│ COMPREHENSIVE ARCHIVING IS MANDATORY for Level 4 │
│ tasks. No complex system is considered complete │
│ until comprehensive archiving is finished and │
│ verified. │
└─────────────────────────────────────────────────────┘
```
@@ -0,0 +1,655 @@
---
description: Phased Implementation for Level 4 Complex System tasks
globs: "**/level4/**", "**/implementation/**"
alwaysApply: false
---
# PHASED IMPLEMENTATION FOR LEVEL 4 TASKS
> **TL;DR:** This document outlines a structured phased implementation approach for Level 4 (Complex System) tasks, ensuring controlled, incremental delivery of complex systems with appropriate verification at each phase.
## 🔍 PHASED IMPLEMENTATION OVERVIEW
Level 4 Complex System tasks require a controlled, incremental approach to implementation to manage complexity, reduce risk, and ensure quality. This document outlines a phased implementation methodology that divides complex system development into discrete, verifiable phases with clear entry and exit criteria.
```mermaid
flowchart TD
classDef phase fill:#f9d77e,stroke:#d9b95c,color:#000
classDef artifact fill:#f4b8c4,stroke:#d498a4,color:#000
classDef verification fill:#c5e8b7,stroke:#a5c897,color:#000
Start([Begin Implementation<br>Process]) --> Framework[Establish Implementation<br>Framework]
Framework --> Plan[Create Phasing<br>Plan]
Plan --> Foundation[Implement<br>Foundation Phase]
Foundation --> VerifyF{Foundation<br>Verification}
VerifyF -->|Pass| Core[Implement<br>Core Phase]
VerifyF -->|Fail| ReviseF[Revise<br>Foundation]
ReviseF --> VerifyF
Core --> VerifyC{Core<br>Verification}
VerifyC -->|Pass| Extension[Implement<br>Extension Phase]
VerifyC -->|Fail| ReviseC[Revise<br>Core]
ReviseC --> VerifyC
Extension --> VerifyE{Extension<br>Verification}
VerifyE -->|Pass| Integration[Implement<br>Integration Phase]
VerifyE -->|Fail| ReviseE[Revise<br>Extension]
ReviseE --> VerifyE
Integration --> VerifyI{Integration<br>Verification}
VerifyI -->|Pass| Finalization[Implement<br>Finalization Phase]
VerifyI -->|Fail| ReviseI[Revise<br>Integration]
ReviseI --> VerifyI
Finalization --> VerifyFin{Finalization<br>Verification}
VerifyFin -->|Pass| Complete([Implementation<br>Complete])
VerifyFin -->|Fail| ReviseFin[Revise<br>Finalization]
ReviseFin --> VerifyFin
Framework -.-> IF((Implementation<br>Framework))
Plan -.-> PP((Phasing<br>Plan))
Foundation -.-> FP((Foundation<br>Phase))
Core -.-> CP((Core<br>Phase))
Extension -.-> EP((Extension<br>Phase))
Integration -.-> IP((Integration<br>Phase))
Finalization -.-> FiP((Finalization<br>Phase))
class Start,Complete milestone
class Framework,Plan,Foundation,Core,Extension,Integration,Finalization,ReviseF,ReviseC,ReviseE,ReviseI,ReviseFin step
class VerifyF,VerifyC,VerifyE,VerifyI,VerifyFin verification
class IF,PP,FP,CP,EP,IP,FiP artifact
```
## 📋 IMPLEMENTATION PHASING PRINCIPLES
1. **Incremental Value Delivery**: Each phase delivers tangible, verifiable value.
2. **Progressive Complexity**: Complexity increases gradually across phases.
3. **Risk Mitigation**: Early phases address high-risk elements to fail fast if needed.
4. **Verification Gates**: Each phase has explicit entry and exit criteria.
5. **Business Alignment**: Phases align with business priorities and user needs.
6. **Technical Integrity**: Each phase maintains architectural and technical integrity.
7. **Continuous Integration**: Work is continuously integrated and tested.
8. **Knowledge Building**: Each phase builds upon knowledge gained in previous phases.
9. **Explicit Dependencies**: Dependencies between phases are clearly documented.
10. **Adaptability**: The phasing plan can adapt to new information while maintaining structure.
## 📋 STANDARD IMPLEMENTATION PHASES
Level 4 Complex System tasks typically follow a five-phase implementation approach:
```mermaid
flowchart LR
classDef phase fill:#f9d77e,stroke:#d9b95c,color:#000
P1[1. Foundation<br>Phase] --> P2[2. Core<br>Phase]
P2 --> P3[3. Extension<br>Phase]
P3 --> P4[4. Integration<br>Phase]
P4 --> P5[5. Finalization<br>Phase]
class P1,P2,P3,P4,P5 phase
```
### Phase 1: Foundation Phase
The Foundation Phase establishes the basic architecture and infrastructure required for the system.
**Key Activities:**
- Set up development, testing, and deployment environments
- Establish core architectural components and patterns
- Implement database schema and basic data access
- Create skeleton application structure
- Implement authentication and authorization framework
- Establish logging, monitoring, and error handling
- Create basic CI/CD pipeline
**Exit Criteria:**
- Basic architectural framework is functional
- Environment setup is complete and documented
- Core infrastructure components are in place
- Basic CI/CD pipeline is operational
- Architecture review confirms alignment with design
### Phase 2: Core Phase
The Core Phase implements the essential functionality that provides the minimum viable system.
**Key Activities:**
- Implement core business logic
- Develop primary user flows and interfaces
- Create essential system services
- Implement critical API endpoints
- Develop basic reporting capabilities
- Establish primary integration points
- Create automated tests for core functionality
**Exit Criteria:**
- Core business functionality is implemented
- Essential user flows are working
- Primary APIs are functional
- Core automated tests are passing
- Business stakeholders verify core functionality
### Phase 3: Extension Phase
The Extension Phase adds additional features and capabilities to the core system.
**Key Activities:**
- Implement secondary business processes
- Add additional user interfaces and features
- Enhance existing functionality based on feedback
- Implement advanced features
- Extend integration capabilities
- Enhance error handling and edge cases
- Expand test coverage
**Exit Criteria:**
- All planned features are implemented
- Extended functionality is working correctly
- Secondary business processes are functional
- Enhanced features have been validated
- Test coverage meets defined thresholds
### Phase 4: Integration Phase
The Integration Phase ensures all components work together properly and integrates with external systems.
**Key Activities:**
- Perform deep integration testing
- Implement all external system integrations
- Conduct end-to-end testing
- Perform performance and load testing
- Conduct security testing
- Implement any required data migrations
- Verify system behavior under various conditions
**Exit Criteria:**
- All integrations are working correctly
- End-to-end tests are passing
- Performance meets defined requirements
- Security tests show no critical vulnerabilities
- System handles error conditions gracefully
### Phase 5: Finalization Phase
The Finalization Phase prepares the system for production release.
**Key Activities:**
- Optimize performance
- Conduct user acceptance testing
- Finalize documentation
- Conduct final security review
- Create production deployment plan
- Prepare support materials and training
- Conduct final system review
**Exit Criteria:**
- All acceptance criteria are met
- Documentation is complete
- User acceptance testing is successful
- Production deployment plan is approved
- Support and maintenance procedures are established
## 📋 PHASE PLANNING TEMPLATE
For each implementation phase, create a detailed plan using this template:
```markdown
## [Phase Name] Implementation Plan
### Phase Overview
- **Purpose**: [Brief description of phase purpose]
- **Timeline**: [Start and end dates]
- **Dependencies**: [Dependencies on other phases or external factors]
- **Key Stakeholders**: [List of key stakeholders for this phase]
### Entry Criteria
- [ ] [Criterion 1]
- [ ] [Criterion 2]
- [ ] [Criterion 3]
### Implementation Components
- **Component 1**: [Description]
- [ ] Task 1.1: [Description]
- [ ] Task 1.2: [Description]
- **Component 2**: [Description]
- [ ] Task 2.1: [Description]
- [ ] Task 2.2: [Description]
### Technical Considerations
- [Key technical considerations for this phase]
### Risk Assessment
- **Risk 1**: [Description]
- Impact: [High/Medium/Low]
- Mitigation: [Strategy]
- **Risk 2**: [Description]
- Impact: [High/Medium/Low]
- Mitigation: [Strategy]
### Quality Assurance
- [QA approach for this phase]
- [Testing requirements]
### Exit Criteria
- [ ] [Criterion 1]
- [ ] [Criterion 2]
- [ ] [Criterion 3]
### Deliverables
- [List of deliverables for this phase]
```
## 📋 PHASE VERIFICATION
Each phase requires formal verification before proceeding to the next phase.
```mermaid
flowchart TD
classDef activity fill:#f9d77e,stroke:#d9b95c,color:#000
classDef artifact fill:#f4b8c4,stroke:#d498a4,color:#000
classDef decision fill:#c5e8b7,stroke:#a5c897,color:#000
Start([Begin Phase<br>Verification]) --> CodeReview[Conduct Code<br>Review]
CodeReview --> TestExecution[Execute Automated<br>Tests]
TestExecution --> QAVerification[Perform QA<br>Verification]
QAVerification --> ArchReview[Conduct Architecture<br>Review]
ArchReview --> StakeholderReview[Conduct Stakeholder<br>Review]
StakeholderReview --> Checklist[Complete Verification<br>Checklist]
Checklist --> ExitCriteria{All Exit<br>Criteria Met?}
ExitCriteria -->|Yes| Approval[Obtain Phase<br>Approval]
ExitCriteria -->|No| Issues[Document<br>Issues]
Issues --> Remediation[Implement<br>Remediation]
Remediation --> Retest[Verify<br>Fixes]
Retest --> ExitCriteria
Approval --> Complete([Verification<br>Complete])
CodeReview -.-> CodeReport((Code Review<br>Report))
TestExecution -.-> TestReport((Test<br>Report))
QAVerification -.-> QAReport((QA<br>Report))
ArchReview -.-> ArchReport((Architecture<br>Report))
StakeholderReview -.-> StakeReport((Stakeholder<br>Report))
Checklist -.-> CheckDoc((Verification<br>Checklist))
class Start,Complete milestone
class CodeReview,TestExecution,QAVerification,ArchReview,StakeholderReview,Checklist,Approval,Issues,Remediation,Retest activity
class ExitCriteria decision
class CodeReport,TestReport,QAReport,ArchReport,StakeReport,CheckDoc artifact
```
### Phase Verification Checklist Template
```markdown
## Phase Verification Checklist
### Implementation Completeness
- [ ] All planned components implemented
- [ ] All tasks marked as complete
- [ ] No outstanding TODOs in code
- [ ] All documentation updated
### Code Quality
- [ ] Code review completed
- [ ] No critical issues found in static analysis
- [ ] Code meets established standards
- [ ] Technical debt documented
### Testing
- [ ] Unit tests completed and passing
- [ ] Integration tests completed and passing
- [ ] End-to-end tests completed and passing
- [ ] Performance testing completed (if applicable)
- [ ] Security testing completed (if applicable)
- [ ] Test coverage meets requirements
### Architecture
- [ ] Implementation follows architectural design
- [ ] No architectural violations introduced
- [ ] Technical patterns correctly implemented
- [ ] Non-functional requirements met
### Stakeholder Verification
- [ ] Business requirements met
- [ ] Stakeholder demo completed
- [ ] Feedback incorporated
- [ ] Acceptance criteria verified
### Risk Assessment
- [ ] All identified risks addressed
- [ ] No new risks introduced
- [ ] Contingency plans in place for known issues
### Exit Criteria
- [ ] All exit criteria met
- [ ] Any exceptions documented and approved
- [ ] Phase signoff obtained from required parties
```
## 📋 HANDLING PHASE DEPENDENCIES
```mermaid
flowchart TD
classDef solid fill:#f9d77e,stroke:#d9b95c,color:#000
classDef partial fill:#a8d5ff,stroke:#88b5e0,color:#000
F[Foundation<br>Phase] --> C[Core<br>Phase]
F --> E[Extension<br>Phase]
F --> I[Integration<br>Phase]
F --> FN[Finalization<br>Phase]
C --> E
C --> I
C --> FN
E --> I
E --> FN
I --> FN
class F,C solid
class E,I,FN partial
```
### Dependency Management Strategies
1. **Vertical Slicing**: Implement complete features across all phases for priority functionality.
2. **Stubbing and Mocking**: Create temporary implementations to allow progress on dependent components.
3. **Interface Contracts**: Define clear interfaces between components to allow parallel development.
4. **Feature Toggles**: Implement features but keep them disabled until dependencies are ready.
5. **Incremental Integration**: Gradually integrate components as they become available.
### Dependency Documentation Format
```markdown
## Implementation Dependencies
### Foundation Phase Dependencies
- **External Dependencies**:
- Development environment setup
- Access to source control
- Access to CI/CD pipeline
### Core Phase Dependencies
- **Foundation Phase Dependencies**:
- Authentication framework
- Database schema
- Logging infrastructure
- Basic application skeleton
- **External Dependencies**:
- API specifications from external systems
- Test data
### Extension Phase Dependencies
- **Core Phase Dependencies**:
- Core business logic
- Primary user interface
- Essential services
- **External Dependencies**:
- [List external dependencies]
### Integration Phase Dependencies
- **Core Phase Dependencies**:
- [List core dependencies]
- **Extension Phase Dependencies**:
- [List extension dependencies]
- **External Dependencies**:
- Access to integration test environments
- Test credentials for external systems
### Finalization Phase Dependencies
- **All previous phases must be complete**
- **External Dependencies**:
- User acceptance testing environment
- Production deployment approval
```
## 📋 PHASE TRANSITION PROCESS
```mermaid
flowchart TD
classDef step fill:#f9d77e,stroke:#d9b95c,color:#000
classDef artifact fill:#f4b8c4,stroke:#d498a4,color:#000
classDef verification fill:#c5e8b7,stroke:#a5c897,color:#000
Start([Begin Phase<br>Transition]) --> Verification[Verify Current<br>Phase Complete]
Verification --> Checkpoint{Phase<br>Verified?}
Checkpoint -->|No| Remediation[Remediate<br>Issues]
Remediation --> Verification
Checkpoint -->|Yes| Documentation[Update<br>Documentation]
Documentation --> Reflection[Conduct Phase<br>Reflection]
Reflection --> NextPlan[Finalize Next<br>Phase Plan]
NextPlan --> Approvals[Obtain<br>Approvals]
Approvals --> Kickoff[Conduct Next<br>Phase Kickoff]
Kickoff --> End([Begin Next<br>Phase])
Verification -.-> VerifDoc((Verification<br>Checklist))
Documentation -.-> Docs((Updated<br>Documentation))
Reflection -.-> ReflectDoc((Reflection<br>Document))
NextPlan -.-> PlanDoc((Phase<br>Plan))
class Start,End milestone
class Verification,Remediation,Documentation,Reflection,NextPlan,Approvals,Kickoff step
class Checkpoint verification
class VerifDoc,Docs,ReflectDoc,PlanDoc artifact
```
### Phase Transition Checklist
```markdown
## Phase Transition Checklist
### Current Phase Closure
- [ ] All exit criteria met and documented
- [ ] All verification steps completed
- [ ] All issues resolved or documented
- [ ] Phase retrospective completed
### Documentation Updates
- [ ] Technical documentation updated
- [ ] User documentation updated
- [ ] Architecture documentation updated
- [ ] Test documentation updated
### Knowledge Transfer
- [ ] Lessons learned documented
- [ ] Knowledge shared with team
- [ ] Training conducted if needed
### Next Phase Preparation
- [ ] Next phase plan reviewed and updated
- [ ] Resources aligned
- [ ] Dependencies verified
- [ ] Entry criteria confirmed
### Approvals
- [ ] Technical lead approval
- [ ] Business stakeholder approval
- [ ] Project management approval
```
## 📋 IMPLEMENTATION TRACKING IN TASKS.MD
Update `tasks.md` to track phased implementation progress:
```markdown
## [SYSTEM-ID]: System Name
### Implementation Phases
#### 1. Foundation Phase
- **Status**: [Not Started/In Progress/Complete]
- **Progress**: [0-100%]
- **Start Date**: [Date]
- **Target Completion**: [Date]
- **Actual Completion**: [Date]
**Key Components**:
- [ ] Component 1: [Status] - [Progress %]
- [ ] Component 2: [Status] - [Progress %]
**Verification Status**:
- [ ] Code Review: [Status]
- [ ] Testing: [Status]
- [ ] Architecture Review: [Status]
- [ ] Stakeholder Approval: [Status]
**Issues/Blockers**:
- [List of issues if any]
#### 2. Core Phase
...
#### 3. Extension Phase
...
#### 4. Integration Phase
...
#### 5. Finalization Phase
...
```
## 📋 MEMORY BANK INTEGRATION
```mermaid
flowchart TD
classDef memfile fill:#f4b8c4,stroke:#d498a4,color:#000
classDef process fill:#f9d77e,stroke:#d9b95c,color:#000
Implementation[Phased<br>Implementation] --> PB[projectbrief.md]
Implementation --> PC[productContext.md]
Implementation --> AC[activeContext.md]
Implementation --> SP[systemPatterns.md]
Implementation --> TC[techContext.md]
Implementation --> P[progress.md]
PB & PC & AC & SP & TC & P --> MBI[Memory Bank<br>Integration]
MBI --> Implementation
class PB,PC,AC,SP,TC,P memfile
class Implementation,MBI process
```
### Memory Bank Updates
Update the following Memory Bank files during phased implementation:
1. **projectbrief.md**
- Update implementation approach
- Document phase-specific objectives
- Link to phase plans
2. **activeContext.md**
- Update with current implementation phase
- Document active implementation tasks
- Highlight current focus areas
3. **systemPatterns.md**
- Document implementation patterns used
- Update with architectural decisions made during implementation
- Record any pattern adaptations
4. **techContext.md**
- Update with implementation technologies
- Document technical constraints encountered
- Record technical decisions made
5. **progress.md**
- Update implementation progress by phase
- Document completed components
- Track overall implementation status
## 📋 IMPLEMENTATION VERIFICATION CHECKLIST
```
✓ IMPLEMENTATION VERIFICATION CHECKLIST
Planning
- Implementation framework established? [YES/NO]
- Phasing plan created? [YES/NO]
- Phase dependencies documented? [YES/NO]
- Entry/exit criteria defined for all phases? [YES/NO]
- Risk assessment performed? [YES/NO]
Foundation Phase
- Environment setup complete? [YES/NO]
- Core architecture implemented? [YES/NO]
- Basic infrastructure in place? [YES/NO]
- CI/CD pipeline operational? [YES/NO]
- Foundation verification completed? [YES/NO]
Core Phase
- Core business logic implemented? [YES/NO]
- Primary user flows working? [YES/NO]
- Essential services operational? [YES/NO]
- Core APIs implemented? [YES/NO]
- Core verification completed? [YES/NO]
Extension Phase
- Secondary features implemented? [YES/NO]
- Enhanced functionality working? [YES/NO]
- Additional user interfaces complete? [YES/NO]
- Extended test coverage in place? [YES/NO]
- Extension verification completed? [YES/NO]
Integration Phase
- All components integrated? [YES/NO]
- External integrations working? [YES/NO]
- End-to-end testing completed? [YES/NO]
- Performance testing executed? [YES/NO]
- Integration verification completed? [YES/NO]
Finalization Phase
- All optimizations complete? [YES/NO]
- User acceptance testing passed? [YES/NO]
- Documentation finalized? [YES/NO]
- Production deployment plan ready? [YES/NO]
- Final system review completed? [YES/NO]
Memory Bank Integration
- All Memory Bank files updated? [YES/NO]
- Implementation status reflected? [YES/NO]
- Technical decisions documented? [YES/NO]
- Progress tracking current? [YES/NO]
```
## 📋 MINIMAL MODE IMPLEMENTATION FORMAT
For situations requiring a more compact implementation approach:
```markdown
## [SYSTEM-ID]: Phased Implementation
### Phase Status Summary
- **Foundation**: [Status] - [Progress %]
- **Core**: [Status] - [Progress %]
- **Extension**: [Status] - [Progress %]
- **Integration**: [Status] - [Progress %]
- **Finalization**: [Status] - [Progress %]
### Current Phase: [Phase Name]
- **Key Components**: [List of key components being implemented]
- **Blockers**: [List of blockers if any]
- **Next Steps**: [List of immediate next steps]
### Verification Status
- [List of verification steps and their status]
### Memory Bank Updates
- [List of Memory Bank files that need updating]
```
## 🚨 IMPLEMENTATION VERIFICATION PRINCIPLE
```
┌─────────────────────────────────────────────────────┐
│ NO PHASE IS CONSIDERED COMPLETE until all │
│ verification steps have been passed and documented. │
│ Phases MUST NOT be rushed to meet deadlines at the │
│ expense of quality or architectural integrity. │
└─────────────────────────────────────────────────────┘
```
@@ -0,0 +1,719 @@
---
description: Comprehensive reflection format for Level 4 Complex System tasks
globs: "**/level4/**", "**/reflection/**"
alwaysApply: false
---
# COMPREHENSIVE REFLECTION FOR LEVEL 4 TASKS
> **TL;DR:** This document outlines a structured, comprehensive approach to reflection for Level 4 (Complex System) tasks, including system review, success and challenge analysis, strategic insights, and action planning.
## 🔍 COMPREHENSIVE REFLECTION OVERVIEW
Level 4 Complex System tasks require in-depth reflection to capture key insights, document successes and challenges, extract strategic lessons, and guide future improvements. This systematic reflection process ensures organizational learning and continuous improvement.
```mermaid
flowchart TD
classDef phase fill:#f9d77e,stroke:#d9b95c,color:#000
classDef artifact fill:#f4b8c4,stroke:#d498a4,color:#000
classDef verification fill:#c5e8b7,stroke:#a5c897,color:#000
Start([Begin Reflection<br>Process]) --> Template[Load Comprehensive<br>Reflection Template]
Template --> SysReview[Conduct System<br>Review]
SysReview --> ArchReview[Review Architecture<br>Decisions]
ArchReview --> ImplementReview[Review Implementation<br>Approach]
ImplementReview --> SuccessAnalysis[Document Successes<br>and Achievements]
SuccessAnalysis --> ChallengeAnalysis[Document Challenges<br>and Solutions]
ChallengeAnalysis --> Technical[Extract Technical<br>Insights]
Technical --> Process[Extract Process<br>Insights]
Process --> Business[Extract Business<br>Insights]
Business --> Strategic[Define Strategic<br>Actions]
Strategic --> Timeline[Analyze Timeline<br>Performance]
Timeline --> Documentation[Complete Reflection<br>Documentation]
Documentation --> Integration[Integrate with<br>Memory Bank]
Integration --> Verification{Reflection<br>Verification}
Verification -->|Pass| Complete([Reflection<br>Complete])
Verification -->|Fail| Revise[Revise<br>Reflection]
Revise --> Verification
Template -.-> RT((Reflection<br>Template))
SysReview -.-> SR((System<br>Review))
SuccessAnalysis & ChallengeAnalysis -.-> SCD((Success/Challenge<br>Document))
Technical & Process & Business -.-> Insights((Insight<br>Document))
Strategic -.-> Actions((Strategic<br>Actions))
class Start,Complete milestone
class Template,SysReview,ArchReview,ImplementReview,SuccessAnalysis,ChallengeAnalysis,Technical,Process,Business,Strategic,Timeline,Documentation,Integration step
class Verification verification
class RT,SR,SCD,Insights,Actions artifact
```
## 📋 REFLECTION TEMPLATE STRUCTURE
### 1. System Overview
```markdown
## System Overview
### System Description
[Comprehensive description of the implemented system, including purpose, scope, and key features]
### System Context
[Description of how the system fits into the broader technical and business ecosystem]
### Key Components
- Component 1: [Description and purpose]
- Component 2: [Description and purpose]
- Component 3: [Description and purpose]
### System Architecture
[Summary of the architectural approach, key patterns, and design decisions]
### System Boundaries
[Description of system boundaries, interfaces, and integration points]
### Implementation Summary
[Overview of the implementation approach, technologies, and methods used]
```
### 2. Project Performance Analysis
```markdown
## Project Performance Analysis
### Timeline Performance
- **Planned Duration**: [X] weeks/months
- **Actual Duration**: [Y] weeks/months
- **Variance**: [+/-Z] weeks/months ([P]%)
- **Explanation**: [Analysis of timeline variances]
### Resource Utilization
- **Planned Resources**: [X] person-months
- **Actual Resources**: [Y] person-months
- **Variance**: [+/-Z] person-months ([P]%)
- **Explanation**: [Analysis of resource variances]
### Quality Metrics
- **Planned Quality Targets**: [List of quality targets]
- **Achieved Quality Results**: [List of achieved quality results]
- **Variance Analysis**: [Analysis of quality variances]
### Risk Management Effectiveness
- **Identified Risks**: [Number of risks identified]
- **Risks Materialized**: [Number and percentage of risks that occurred]
- **Mitigation Effectiveness**: [Effectiveness of risk mitigation strategies]
- **Unforeseen Risks**: [Description of unforeseen risks that emerged]
```
### 3. Achievements and Successes
```markdown
## Achievements and Successes
### Key Achievements
1. **Achievement 1**: [Description]
- **Evidence**: [Concrete evidence of success]
- **Impact**: [Business/technical impact]
- **Contributing Factors**: [What enabled this success]
2. **Achievement 2**: [Description]
- **Evidence**: [Concrete evidence of success]
- **Impact**: [Business/technical impact]
- **Contributing Factors**: [What enabled this success]
### Technical Successes
- **Success 1**: [Description of technical success]
- **Approach Used**: [Description of approach]
- **Outcome**: [Results achieved]
- **Reusability**: [How this can be reused]
- **Success 2**: [Description of technical success]
- **Approach Used**: [Description of approach]
- **Outcome**: [Results achieved]
- **Reusability**: [How this can be reused]
### Process Successes
- **Success 1**: [Description of process success]
- **Approach Used**: [Description of approach]
- **Outcome**: [Results achieved]
- **Reusability**: [How this can be reused]
### Team Successes
- **Success 1**: [Description of team success]
- **Approach Used**: [Description of approach]
- **Outcome**: [Results achieved]
- **Reusability**: [How this can be reused]
```
### 4. Challenges and Solutions
```markdown
## Challenges and Solutions
### Key Challenges
1. **Challenge 1**: [Description]
- **Impact**: [Business/technical impact]
- **Resolution Approach**: [How it was addressed]
- **Outcome**: [Final result]
- **Preventative Measures**: [How to prevent in future]
2. **Challenge 2**: [Description]
- **Impact**: [Business/technical impact]
- **Resolution Approach**: [How it was addressed]
- **Outcome**: [Final result]
- **Preventative Measures**: [How to prevent in future]
### Technical Challenges
- **Challenge 1**: [Description of technical challenge]
- **Root Cause**: [Analysis of root cause]
- **Solution**: [How it was solved]
- **Alternative Approaches**: [Other approaches considered]
- **Lessons Learned**: [Key takeaways]
- **Challenge 2**: [Description of technical challenge]
- **Root Cause**: [Analysis of root cause]
- **Solution**: [How it was solved]
- **Alternative Approaches**: [Other approaches considered]
- **Lessons Learned**: [Key takeaways]
### Process Challenges
- **Challenge 1**: [Description of process challenge]
- **Root Cause**: [Analysis of root cause]
- **Solution**: [How it was solved]
- **Process Improvements**: [Improvements made or suggested]
### Unresolved Issues
- **Issue 1**: [Description of unresolved issue]
- **Current Status**: [Status]
- **Proposed Path Forward**: [Suggested next steps]
- **Required Resources**: [What's needed to resolve]
```
### 5. Technical Insights
```markdown
## Technical Insights
### Architecture Insights
- **Insight 1**: [Description of architectural insight]
- **Context**: [When/where this was observed]
- **Implications**: [What this means for future work]
- **Recommendations**: [Suggested changes or actions]
- **Insight 2**: [Description of architectural insight]
- **Context**: [When/where this was observed]
- **Implications**: [What this means for future work]
- **Recommendations**: [Suggested changes or actions]
### Implementation Insights
- **Insight 1**: [Description of implementation insight]
- **Context**: [When/where this was observed]
- **Implications**: [What this means for future work]
- **Recommendations**: [Suggested changes or actions]
### Technology Stack Insights
- **Insight 1**: [Description of technology stack insight]
- **Context**: [When/where this was observed]
- **Implications**: [What this means for future work]
- **Recommendations**: [Suggested changes or actions]
### Performance Insights
- **Insight 1**: [Description of performance insight]
- **Context**: [When/where this was observed]
- **Metrics**: [Relevant performance metrics]
- **Implications**: [What this means for future work]
- **Recommendations**: [Suggested optimizations]
### Security Insights
- **Insight 1**: [Description of security insight]
- **Context**: [When/where this was observed]
- **Implications**: [What this means for future work]
- **Recommendations**: [Suggested security improvements]
```
### 6. Process Insights
```markdown
## Process Insights
### Planning Insights
- **Insight 1**: [Description of planning process insight]
- **Context**: [When/where this was observed]
- **Implications**: [What this means for future work]
- **Recommendations**: [Suggested process improvements]
### Development Process Insights
- **Insight 1**: [Description of development process insight]
- **Context**: [When/where this was observed]
- **Implications**: [What this means for future work]
- **Recommendations**: [Suggested process improvements]
### Testing Insights
- **Insight 1**: [Description of testing process insight]
- **Context**: [When/where this was observed]
- **Implications**: [What this means for future work]
- **Recommendations**: [Suggested process improvements]
### Collaboration Insights
- **Insight 1**: [Description of collaboration insight]
- **Context**: [When/where this was observed]
- **Implications**: [What this means for future work]
- **Recommendations**: [Suggested collaboration improvements]
### Documentation Insights
- **Insight 1**: [Description of documentation insight]
- **Context**: [When/where this was observed]
- **Implications**: [What this means for future work]
- **Recommendations**: [Suggested documentation improvements]
```
### 7. Business Insights
```markdown
## Business Insights
### Value Delivery Insights
- **Insight 1**: [Description of value delivery insight]
- **Context**: [When/where this was observed]
- **Business Impact**: [Impact on business outcomes]
- **Recommendations**: [Suggested improvements]
### Stakeholder Insights
- **Insight 1**: [Description of stakeholder insight]
- **Context**: [When/where this was observed]
- **Implications**: [What this means for stakeholder management]
- **Recommendations**: [Suggested improvements]
### Market/User Insights
- **Insight 1**: [Description of market/user insight]
- **Context**: [When/where this was observed]
- **Implications**: [What this means for product direction]
- **Recommendations**: [Suggested improvements]
### Business Process Insights
- **Insight 1**: [Description of business process insight]
- **Context**: [When/where this was observed]
- **Implications**: [What this means for business processes]
- **Recommendations**: [Suggested improvements]
```
### 8. Strategic Actions
```markdown
## Strategic Actions
### Immediate Actions
- **Action 1**: [Description of immediate action]
- **Owner**: [Person responsible]
- **Timeline**: [Expected completion date]
- **Success Criteria**: [How to measure success]
- **Resources Required**: [What's needed]
- **Priority**: [High/Medium/Low]
- **Action 2**: [Description of immediate action]
- **Owner**: [Person responsible]
- **Timeline**: [Expected completion date]
- **Success Criteria**: [How to measure success]
- **Resources Required**: [What's needed]
- **Priority**: [High/Medium/Low]
### Short-Term Improvements (1-3 months)
- **Improvement 1**: [Description of short-term improvement]
- **Owner**: [Person responsible]
- **Timeline**: [Expected completion date]
- **Success Criteria**: [How to measure success]
- **Resources Required**: [What's needed]
- **Priority**: [High/Medium/Low]
### Medium-Term Initiatives (3-6 months)
- **Initiative 1**: [Description of medium-term initiative]
- **Owner**: [Person responsible]
- **Timeline**: [Expected completion date]
- **Success Criteria**: [How to measure success]
- **Resources Required**: [What's needed]
- **Priority**: [High/Medium/Low]
### Long-Term Strategic Directions (6+ months)
- **Direction 1**: [Description of long-term strategic direction]
- **Business Alignment**: [How this aligns with business strategy]
- **Expected Impact**: [Anticipated outcomes]
- **Key Milestones**: [Major checkpoints]
- **Success Criteria**: [How to measure success]
```
### 9. Knowledge Transfer
```markdown
## Knowledge Transfer
### Key Learnings for Organization
- **Learning 1**: [Description of key organizational learning]
- **Context**: [When/where this was learned]
- **Applicability**: [Where this can be applied]
- **Suggested Communication**: [How to share this]
### Technical Knowledge Transfer
- **Technical Knowledge 1**: [Description of technical knowledge]
- **Audience**: [Who needs this knowledge]
- **Transfer Method**: [How to transfer]
- **Documentation**: [Where documented]
### Process Knowledge Transfer
- **Process Knowledge 1**: [Description of process knowledge]
- **Audience**: [Who needs this knowledge]
- **Transfer Method**: [How to transfer]
- **Documentation**: [Where documented]
### Documentation Updates
- **Document 1**: [Name of document to update]
- **Required Updates**: [What needs to be updated]
- **Owner**: [Person responsible]
- **Timeline**: [When it will be updated]
```
### 10. Reflection Summary
```markdown
## Reflection Summary
### Key Takeaways
- **Takeaway 1**: [Description of key takeaway]
- **Takeaway 2**: [Description of key takeaway]
- **Takeaway 3**: [Description of key takeaway]
### Success Patterns to Replicate
1. [Pattern 1 description]
2. [Pattern 2 description]
3. [Pattern 3 description]
### Issues to Avoid in Future
1. [Issue 1 description]
2. [Issue 2 description]
3. [Issue 3 description]
### Overall Assessment
[Comprehensive assessment of the project's success, challenges, and strategic value]
### Next Steps
[Clear description of immediate next steps following this reflection]
```
## 📋 REFLECTION PROCESS
### 1. Preparation
```mermaid
flowchart TD
classDef step fill:#f9d77e,stroke:#d9b95c,color:#000
classDef artifact fill:#f4b8c4,stroke:#d498a4,color:#000
Start([Begin Reflection<br>Preparation]) --> Template[Load Reflection<br>Template]
Template --> Data[Gather Project<br>Data]
Data --> Metrics[Collect Performance<br>Metrics]
Metrics --> Feedback[Gather Stakeholder<br>Feedback]
Feedback --> Schedule[Schedule Reflection<br>Session]
Schedule --> Participants[Identify<br>Participants]
Participants --> Agenda[Create Session<br>Agenda]
Agenda --> Complete([Preparation<br>Complete])
Template -.-> TDoc((Reflection<br>Template))
Data -.-> ProjData((Project<br>Data))
Metrics -.-> MetricsDoc((Performance<br>Metrics))
Feedback -.-> FeedbackDoc((Stakeholder<br>Feedback))
class Start,Complete milestone
class Template,Data,Metrics,Feedback,Schedule,Participants,Agenda step
class TDoc,ProjData,MetricsDoc,FeedbackDoc artifact
```
**Key Preparation Steps:**
1. Load the comprehensive reflection template
2. Gather project data (tasks.md, documentation, artifacts)
3. Collect performance metrics (timeline, resource utilization, quality)
4. Gather stakeholder feedback (internal and external)
5. Schedule reflection session(s) with key participants
6. Prepare session agenda and pre-work materials
### 2. Conducting the Reflection Session
```mermaid
flowchart TD
classDef step fill:#f9d77e,stroke:#d9b95c,color:#000
classDef artifact fill:#f4b8c4,stroke:#d498a4,color:#000
Start([Begin Reflection<br>Session]) --> Intro[Introduction and<br>Context Setting]
Intro --> Project[Project Overview<br>Presentation]
Project --> Success[Success<br>Identification]
Success --> Challenge[Challenge<br>Identification]
Challenge --> Root[Root Cause<br>Analysis]
Root --> Insights[Insight<br>Generation]
Insights --> Actions[Action<br>Planning]
Actions --> Documentation[Document<br>Outcomes]
Documentation --> Next[Define Next<br>Steps]
Next --> Complete([Session<br>Complete])
Success -.-> SuccessDoc((Success<br>Document))
Challenge -.-> ChallengeDoc((Challenge<br>Document))
Insights -.-> InsightDoc((Insight<br>Document))
Actions -.-> ActionDoc((Action<br>Plan))
class Start,Complete milestone
class Intro,Project,Success,Challenge,Root,Insights,Actions,Documentation,Next step
class SuccessDoc,ChallengeDoc,InsightDoc,ActionDoc artifact
```
**Session Format:**
- **Duration**: 2-4 hours (may be split across multiple sessions)
- **Participants**: Project team, key stakeholders, technical leads
- **Facilitation**: Neutral facilitator to guide the process
- **Documentation**: Dedicated scribe to capture insights and actions
### 3. Documentation and Integration
```mermaid
flowchart TD
classDef step fill:#f9d77e,stroke:#d9b95c,color:#000
classDef artifact fill:#f4b8c4,stroke:#d498a4,color:#000
classDef verification fill:#c5e8b7,stroke:#a5c897,color:#000
Start([Begin Documentation<br>and Integration]) --> Draft[Draft Reflection<br>Document]
Draft --> Review[Review with<br>Key Stakeholders]
Review --> Revise[Incorporate<br>Feedback]
Revise --> Finalize[Finalize<br>Document]
Finalize --> UpdateMB[Update Memory<br>Bank]
UpdateMB --> ActionReg[Create Action<br>Register]
ActionReg --> Archive[Archive Project<br>Documents]
Archive --> Verification{Documentation<br>Verification}
Verification -->|Pass| Complete([Documentation<br>Complete])
Verification -->|Fail| MoreRevision[Address<br>Documentation Gaps]
MoreRevision --> Verification
Draft -.-> DraftDoc((Draft<br>Document))
Finalize -.-> FinalDoc((Final<br>Reflection))
ActionReg -.-> ActReg((Action<br>Register))
class Start,Complete milestone
class Draft,Review,Revise,Finalize,UpdateMB,ActionReg,Archive,MoreRevision step
class Verification verification
class DraftDoc,FinalDoc,ActReg artifact
```
**Key Documentation Steps:**
1. Draft comprehensive reflection document using the template
2. Review draft with key stakeholders and participants
3. Incorporate feedback and finalize document
4. Update Memory Bank with key insights and learnings
5. Create action register for tracking improvement actions
6. Archive project documents with reflection document
7. Verify documentation completeness and quality
## 📋 REFLECTION TECHNIQUES
### Root Cause Analysis
```mermaid
flowchart TD
classDef step fill:#f9d77e,stroke:#d9b95c,color:#000
Start([Identify<br>Challenge]) --> What[What<br>Happened?]
What --> When[When Did<br>It Happen?]
When --> Where[Where Did<br>It Happen?]
Where --> Who[Who Was<br>Involved?]
Who --> How[How Did<br>It Happen?]
How --> Why1[Why Did<br>It Happen?]
Why1 --> Why2[Why?<br>Deeper]
Why2 --> Why3[Why?<br>Deeper]
Why3 --> Why4[Why?<br>Deeper]
Why4 --> Why5[Why?<br>Root Cause]
Why5 --> Solution[Identify<br>Solution]
Solution --> Prevent[Prevention<br>Strategy]
class Start milestone
class What,When,Where,Who,How,Why1,Why2,Why3,Why4,Why5,Solution,Prevent step
```
### Success Analysis
```mermaid
flowchart TD
classDef step fill:#f9d77e,stroke:#d9b95c,color:#000
Start([Identify<br>Success]) --> Define[Define the<br>Success]
Define --> Impact[Measure the<br>Impact]
Impact --> Factors[Identify Contributing<br>Factors]
Factors --> Context[Consider<br>Context]
Context --> Patterns[Identify<br>Patterns]
Patterns --> Generalize[Generalize<br>Approach]
Generalize --> Apply[Define Where<br>to Apply]
class Start milestone
class Define,Impact,Factors,Context,Patterns,Generalize,Apply step
```
### Insight Generation
```mermaid
flowchart TD
classDef step fill:#f9d77e,stroke:#d9b95c,color:#000
Start([Begin Insight<br>Generation]) --> Observe[Observe<br>Patterns]
Observe --> Question[Question<br>Assumptions]
Question --> Connect[Connect<br>Dots]
Connect --> Contrast[Contrast with<br>Prior Knowledge]
Contrast --> Hypothesize[Form<br>Hypothesis]
Hypothesize --> Test[Test<br>Hypothesis]
Test --> Refine[Refine<br>Insight]
Refine --> Apply[Apply to<br>Future Work]
class Start milestone
class Observe,Question,Connect,Contrast,Hypothesize,Test,Refine,Apply step
```
## 📋 MEMORY BANK INTEGRATION
```mermaid
flowchart TD
classDef memfile fill:#f4b8c4,stroke:#d498a4,color:#000
classDef process fill:#f9d77e,stroke:#d9b95c,color:#000
Reflection[Comprehensive<br>Reflection] --> PB[projectbrief.md]
Reflection --> PC[productContext.md]
Reflection --> AC[activeContext.md]
Reflection --> SP[systemPatterns.md]
Reflection --> TC[techContext.md]
Reflection --> P[progress.md]
PB & PC & AC & SP & TC & P --> MBI[Memory Bank<br>Integration]
MBI --> Next[Enhanced Future<br>Projects]
class PB,PC,AC,SP,TC,P memfile
class Reflection,MBI,Next process
```
### Memory Bank Updates
Specific updates to make to Memory Bank files:
1. **projectbrief.md**
- Update with strategic insights
- Document key achievements
- Incorporate lessons learned
2. **productContext.md**
- Update with business insights
- Document market/user insights
- Include value delivery insights
3. **activeContext.md**
- Update with current status
- Document action items
- Include next steps
4. **systemPatterns.md**
- Update with architectural insights
- Document successful patterns
- Include technical knowledge
5. **techContext.md**
- Update with implementation insights
- Document technology stack insights
- Include performance and security insights
6. **progress.md**
- Update with final status
- Document achievements
- Include project metrics
## 📋 REFLECTION VERIFICATION CHECKLIST
```
✓ REFLECTION VERIFICATION CHECKLIST
System Review
- System overview complete and accurate? [YES/NO]
- Project performance metrics collected and analyzed? [YES/NO]
- System boundaries and interfaces described? [YES/NO]
Success and Challenge Analysis
- Key achievements documented with evidence? [YES/NO]
- Technical successes documented with approach? [YES/NO]
- Key challenges documented with resolutions? [YES/NO]
- Technical challenges documented with solutions? [YES/NO]
- Unresolved issues documented with path forward? [YES/NO]
Insight Generation
- Technical insights extracted and documented? [YES/NO]
- Process insights extracted and documented? [YES/NO]
- Business insights extracted and documented? [YES/NO]
Strategic Planning
- Immediate actions defined with owners? [YES/NO]
- Short-term improvements identified? [YES/NO]
- Medium-term initiatives planned? [YES/NO]
- Long-term strategic directions outlined? [YES/NO]
Knowledge Transfer
- Key learnings for organization documented? [YES/NO]
- Technical knowledge transfer planned? [YES/NO]
- Process knowledge transfer planned? [YES/NO]
- Documentation updates identified? [YES/NO]
Memory Bank Integration
- projectbrief.md updated with insights? [YES/NO]
- productContext.md updated with insights? [YES/NO]
- activeContext.md updated with insights? [YES/NO]
- systemPatterns.md updated with insights? [YES/NO]
- techContext.md updated with insights? [YES/NO]
- progress.md updated with final status? [YES/NO]
```
## 📋 MINIMAL MODE REFLECTION FORMAT
For situations requiring a more compact reflection:
```markdown
## Level 4 Task Reflection: [System Name]
### System Summary
- **Purpose**: [Brief description of system purpose]
- **Key Components**: [List of key components]
- **Architecture**: [Brief architecture description]
### Performance Summary
- **Timeline**: [Planned] vs [Actual] ([Variance])
- **Resources**: [Planned] vs [Actual] ([Variance])
- **Quality**: [Summary of quality achievements]
### Key Successes
1. [Success 1 with evidence and impact]
2. [Success 2 with evidence and impact]
3. [Success 3 with evidence and impact]
### Key Challenges
1. [Challenge 1 with resolution and lessons]
2. [Challenge 2 with resolution and lessons]
3. [Challenge 3 with resolution and lessons]
### Critical Insights
- **Technical**: [Key technical insight with recommendation]
- **Process**: [Key process insight with recommendation]
- **Business**: [Key business insight with recommendation]
### Priority Actions
1. [Immediate action with owner and timeline]
2. [Short-term improvement with owner and timeline]
3. [Medium-term initiative with owner and timeline]
### Memory Bank Updates
- [List of specific Memory Bank updates needed]
```
## 🚨 REFLECTION ENFORCEMENT PRINCIPLE
```
┌─────────────────────────────────────────────────────┐
│ COMPREHENSIVE REFLECTION IS MANDATORY for Level 4 │
│ tasks. Archiving CANNOT proceed until reflection │
│ is completed and verified. │
└─────────────────────────────────────────────────────┘
```
@@ -0,0 +1,466 @@
---
description: Advanced task tracking for Level 4 Complex System tasks
globs: "**/level4/**", "**/task-tracking/**"
alwaysApply: false
---
# ADVANCED TASK TRACKING FOR LEVEL 4 TASKS
> **TL;DR:** This document outlines a comprehensive task tracking approach for Level 4 (Complex System) tasks, ensuring detailed tracking of complex, multi-phase work with clear dependencies, progress tracking, and architectural alignment.
## 🔍 ADVANCED TASK TRACKING OVERVIEW
Level 4 Complex System tasks require sophisticated task tracking to manage the complexity of system development, coordinate multiple team members, track dependencies, and ensure alignment with architectural principles. This document outlines a comprehensive task tracking approach for such complex endeavors.
```mermaid
flowchart TD
classDef phase fill:#f9d77e,stroke:#d9b95c,color:#000
classDef artifact fill:#f4b8c4,stroke:#d498a4,color:#000
classDef verification fill:#c5e8b7,stroke:#a5c897,color:#000
Start([Begin Task<br>Tracking]) --> Framework[Establish Task<br>Framework]
Framework --> Hierarchy[Define Task<br>Hierarchy]
Hierarchy --> Breakdown[Create Work<br>Breakdown Structure]
Breakdown --> Dependencies[Document<br>Dependencies]
Dependencies --> Milestones[Define Key<br>Milestones]
Milestones --> Schedule[Create<br>Schedule]
Schedule --> Resources[Define Resource<br>Allocation]
Resources --> Risks[Document<br>Risks]
Risks --> Quality[Define Quality<br>Metrics]
Quality --> Progress[Track<br>Progress]
Progress --> Adaptations[Document<br>Adaptations]
Adaptations --> Verification{Task Tracking<br>Verification}
Verification -->|Pass| Complete([Task Tracking<br>Complete])
Verification -->|Fail| Revise[Revise Task<br>Tracking]
Revise --> Verification
Framework -.-> TF((Task<br>Framework))
Hierarchy -.-> TH((Task<br>Hierarchy))
Breakdown -.-> WBS((Work Breakdown<br>Structure))
Dependencies -.-> DP((Dependency<br>Matrix))
Milestones -.-> MS((Milestone<br>Document))
Schedule -.-> SC((Schedule<br>Document))
Resources -.-> RA((Resource<br>Allocation))
Risks -.-> RM((Risk<br>Management))
Quality -.-> QM((Quality<br>Metrics))
Progress -.-> PT((Progress<br>Tracking))
Adaptations -.-> AD((Adaptation<br>Document))
class Start,Complete milestone
class Framework,Hierarchy,Breakdown,Dependencies,Milestones,Schedule,Resources,Risks,Quality,Progress,Adaptations,Revise step
class Verification verification
class TF,TH,WBS,DP,MS,SC,RA,RM,QM,PT,AD artifact
```
## 📋 TASK TRACKING PRINCIPLES
1. **Architectural Alignment**: All tasks must align with the established architectural principles and patterns.
2. **Hierarchical Organization**: Tasks are organized in a hierarchical structure with clear parent-child relationships.
3. **Dependency Management**: All task dependencies are explicitly documented and tracked.
4. **Progression Transparency**: Task status and progress are clearly documented and visible to all stakeholders.
5. **Quality Integration**: Quality metrics and verification are integrated into task definitions.
6. **Resource Allocation**: Tasks include clear allocation of resources required for completion.
7. **Risk Awareness**: Each significant task includes risk assessment and mitigation strategies.
8. **Adaptive Planning**: Task tracking accommodates changes and adaptations while maintaining system integrity.
9. **Milestone Tracking**: Clear milestones are defined and used to track overall progress.
10. **Comprehensive Documentation**: All aspects of the task lifecycle are documented thoroughly.
## 📋 TASK HIERARCHY STRUCTURE
Level 4 tasks follow a hierarchical structure:
```mermaid
flowchart TD
classDef system fill:#f9d77e,stroke:#d9b95c,color:#000
classDef component fill:#a8d5ff,stroke:#88b5e0,color:#000
classDef feature fill:#c5e8b7,stroke:#a5c897,color:#000
classDef task fill:#f4b8c4,stroke:#d498a4,color:#000
classDef subtask fill:#d8c1f7,stroke:#b8a1d7,color:#000
System[System-Level Work] --> Component1[Component 1]
System --> Component2[Component 2]
System --> Component3[Component 3]
Component1 --> Feature1[Feature 1.1]
Component1 --> Feature2[Feature 1.2]
Feature1 --> Task1[Task 1.1.1]
Feature1 --> Task2[Task 1.1.2]
Task1 --> Subtask1[Subtask 1.1.1.1]
Task1 --> Subtask2[Subtask 1.1.1.2]
Task1 --> Subtask3[Subtask 1.1.1.3]
class System system
class Component1,Component2,Component3 component
class Feature1,Feature2 feature
class Task1,Task2 task
class Subtask1,Subtask2,Subtask3 subtask
```
### Levels of Hierarchy:
1. **System Level**: The overall system being built or modified.
2. **Component Level**: Major components or subsystems of the system.
3. **Feature Level**: Specific features within each component.
4. **Task Level**: Concrete tasks required to implement a feature.
5. **Subtask Level**: Detailed subtasks for complex tasks.
## 📋 COMPREHENSIVE TASK STRUCTURE
Each Level 4 task in `tasks.md` follows this comprehensive structure:
```markdown
## [SYSTEM-ID]: System Name
### System Overview
- **Purpose**: [Brief description of system purpose]
- **Architectural Alignment**: [How the system aligns with architectural principles]
- **Status**: [Planning/In Progress/Review/Complete]
- **Milestones**:
- Milestone 1: [Date] - [Status]
- Milestone 2: [Date] - [Status]
- Milestone 3: [Date] - [Status]
### Components
#### [COMP-ID]: Component Name
- **Purpose**: [Brief description of component purpose]
- **Status**: [Planning/In Progress/Review/Complete]
- **Dependencies**: [List of dependencies]
- **Responsible**: [Team or individual responsible]
##### [FEAT-ID]: Feature Name
- **Description**: [Feature description]
- **Status**: [Planning/In Progress/Review/Complete]
- **Priority**: [Critical/High/Medium/Low]
- **Related Requirements**: [List of requirements IDs this feature addresses]
- **Quality Criteria**: [Measurable criteria for completion]
- **Progress**: [0-100%]
###### [TASK-ID]: Task Name
- **Description**: [Task description]
- **Status**: [TODO/In Progress/Review/Done]
- **Assigned To**: [Assignee]
- **Estimated Effort**: [Effort estimate]
- **Actual Effort**: [Actual effort]
- **Dependencies**: [Tasks this depends on]
- **Blocks**: [Tasks blocked by this]
- **Risk Assessment**: [Risk level and description]
- **Quality Gates**: [Quality gates this must pass]
- **Implementation Notes**: [Key implementation notes]
**Subtasks**:
- [ ] [SUB-ID]: [Subtask description] - [Status]
- [ ] [SUB-ID]: [Subtask description] - [Status]
- [ ] [SUB-ID]: [Subtask description] - [Status]
### System-Wide Tasks
- [ ] [SYS-TASK-ID]: [System-wide task description] - [Status]
- [ ] [SYS-TASK-ID]: [System-wide task description] - [Status]
### Risks and Mitigations
- **Risk 1**: [Description] - **Mitigation**: [Mitigation strategy]
- **Risk 2**: [Description] - **Mitigation**: [Mitigation strategy]
### Progress Summary
- **Overall Progress**: [0-100%]
- **Component 1**: [0-100%]
- **Component 2**: [0-100%]
- **Component 3**: [0-100%]
### Latest Updates
- [Date]: [Update description]
- [Date]: [Update description]
```
## 📋 TASK TRACKING ORGANIZATION IN TASKS.MD
For Level 4 Complex System tasks, organize `tasks.md` as follows:
```markdown
# TASK TRACKING
## ACTIVE SYSTEMS
- [SYSTEM-ID]: [System Name] - [Status]
- [SYSTEM-ID]: [System Name] - [Status]
## SYSTEM DETAILS
[Detailed task structure for each system as per the template above]
## COMPLETED SYSTEMS
- [SYSTEM-ID]: [System Name] - Completed [Date]
- [SYSTEM-ID]: [System Name] - Completed [Date]
## SYSTEM DEPENDENCIES
```mermaid
graph TD
System1 --> System2
System1 --> System3
System2 --> System4
```
## RISK REGISTER
| Risk ID | Description | Probability | Impact | Mitigation |
|---------|-------------|-------------|--------|------------|
| RISK-01 | [Description] | High/Med/Low | High/Med/Low | [Strategy] |
| RISK-02 | [Description] | High/Med/Low | High/Med/Low | [Strategy] |
## RESOURCE ALLOCATION
| Resource | System | Allocation % | Time Period |
|----------|--------|--------------|------------|
| [Name/Team] | [System-ID] | [%] | [Start-End] |
| [Name/Team] | [System-ID] | [%] | [Start-End] |
```
## 📋 DEPENDENCY MANAGEMENT
```mermaid
flowchart TD
classDef critical fill:#f8707e,stroke:#d85060,color:#000
classDef high fill:#f9d77e,stroke:#d9b95c,color:#000
classDef medium fill:#a8d5ff,stroke:#88b5e0,color:#000
classDef low fill:#c5e8b7,stroke:#a5c897,color:#000
Task1[Task 1] --> Task2[Task 2]
Task1 --> Task3[Task 3]
Task2 --> Task4[Task 4]
Task3 --> Task4
Task4 --> Task5[Task 5]
Task4 --> Task6[Task 6]
Task5 --> Task7[Task 7]
Task6 --> Task7
class Task1,Task4,Task7 critical
class Task2,Task5 high
class Task3 medium
class Task6 low
```
For complex systems, document dependencies in a dedicated section:
```markdown
## Dependency Matrix
| Task ID | Depends On | Blocks | Type | Status |
|---------|------------|--------|------|--------|
| TASK-01 | - | TASK-02, TASK-03 | Technical | Completed |
| TASK-02 | TASK-01 | TASK-04 | Technical | In Progress |
| TASK-03 | TASK-01 | TASK-04 | Resource | Not Started |
| TASK-04 | TASK-02, TASK-03 | TASK-05, TASK-06 | Technical | Not Started |
```
### Dependency Types:
- **Technical**: One task technically requires another to be completed first
- **Resource**: Tasks compete for the same resources
- **Information**: One task requires information produced by another
- **Architectural**: Tasks have architectural dependencies
- **Temporal**: Tasks must be completed in a specific time sequence
## 📋 MILESTONE TRACKING
For Level 4 tasks, track milestones explicitly:
```markdown
## System Milestones
| Milestone ID | Description | Target Date | Actual Date | Status | Deliverables |
|--------------|-------------|-------------|-------------|--------|--------------|
| MILE-01 | Architecture Approved | [Date] | [Date] | Completed | Architecture Document |
| MILE-02 | Component Design Completed | [Date] | - | In Progress | Design Documents |
| MILE-03 | Component 1 Implementation | [Date] | - | Not Started | Code, Tests |
| MILE-04 | Integration Complete | [Date] | - | Not Started | Integrated System |
| MILE-05 | System Testing Complete | [Date] | - | Not Started | Test Reports |
| MILE-06 | Deployment Ready | [Date] | - | Not Started | Deployment Package |
```
## 📋 PROGRESS VISUALIZATION
Include visual representations of progress in `tasks.md`:
```markdown
## Progress Visualization
### Overall System Progress
```mermaid
pie title System Progress
"Completed" : 30
"In Progress" : 25
"Not Started" : 45
```
### Component Progress
```mermaid
graph TD
subgraph Progress
C1[Component 1: 75%]
C2[Component 2: 50%]
C3[Component 3: 20%]
C4[Component 4: 5%]
end
```
### Timeline
```mermaid
gantt
title System Timeline
dateFormat YYYY-MM-DD
section Architecture
Architecture Design :done, arch, 2023-01-01, 30d
Architecture Review :done, arch-rev, after arch, 10d
section Component 1
Design :active, c1-des, after arch-rev, 20d
Implementation :c1-imp, after c1-des, 40d
Testing :c1-test, after c1-imp, 15d
section Component 2
Design :active, c2-des, after arch-rev, 25d
Implementation :c2-imp, after c2-des, 50d
Testing :c2-test, after c2-imp, 20d
```
```
## 📋 UPDATING TASK STATUS
For Level 4 tasks, status updates include:
1. **Progress Updates**: Update task status and progress percentage
2. **Effort Tracking**: Record actual effort against estimates
3. **Risk Updates**: Update risk assessments and mitigations
4. **Dependency Status**: Update status of dependencies
5. **Milestone Tracking**: Update milestone status
6. **Issue Documentation**: Document issues encountered
7. **Adaptation Documentation**: Document any adaptations to the original plan
8. **Quality Gate Status**: Update status of quality gates
Status update cycle:
- **Daily**: Update task and subtask status
- **Weekly**: Update component status and progress visualization
- **Bi-weekly**: Update system-level progress and milestone status
- **Monthly**: Complete system review including risks and adaptations
## 📋 TASK TRACKING VERIFICATION CHECKLIST
```
✓ TASK TRACKING VERIFICATION CHECKLIST
Task Structure
- System level work properly defined? [YES/NO]
- Component level tasks identified? [YES/NO]
- Feature level tasks specified? [YES/NO]
- Task level details provided? [YES/NO]
- Subtasks created for complex tasks? [YES/NO]
Task Information
- All tasks have clear descriptions? [YES/NO]
- Status accurately reflected? [YES/NO]
- Proper assignments made? [YES/NO]
- Effort estimates provided? [YES/NO]
- Dependencies documented? [YES/NO]
Progress Tracking
- Overall progress calculated? [YES/NO]
- Component progress updated? [YES/NO]
- Milestone status updated? [YES/NO]
- Progress visualizations current? [YES/NO]
- Latest updates documented? [YES/NO]
Risk Management
- Risks identified and assessed? [YES/NO]
- Mitigation strategies documented? [YES/NO]
- Risk register updated? [YES/NO]
- Impact on schedule assessed? [YES/NO]
- Contingency plans documented? [YES/NO]
Resource Allocation
- Resources allocated to tasks? [YES/NO]
- Resource conflicts identified? [YES/NO]
- Resource allocation optimized? [YES/NO]
- Future resource needs projected? [YES/NO]
- Resource allocation documented? [YES/NO]
Quality Integration
- Quality criteria defined for tasks? [YES/NO]
- Quality gates specified? [YES/NO]
- Verification procedures documented? [YES/NO]
- Quality metrics being tracked? [YES/NO]
- Quality issues documented? [YES/NO]
Architectural Alignment
- Tasks align with architecture? [YES/NO]
- Architectural dependencies tracked? [YES/NO]
- Architectural constraints documented? [YES/NO]
- Architecture evolution tracked? [YES/NO]
- Architectural decisions documented? [YES/NO]
```
## 📋 INTEGRATION WITH MEMORY BANK
Level 4 task tracking is tightly integrated with the Memory Bank:
1. **projectbrief.md**: System-level tasks are derived from and linked to the project brief
2. **productContext.md**: Tasks are aligned with business context and objectives
3. **systemPatterns.md**: Tasks respect and implement defined architectural patterns
4. **techContext.md**: Tasks are aligned with the technology stack and constraints
5. **activeContext.md**: Current focus and status from `tasks.md` informs the active context
6. **progress.md**: System progress from `tasks.md` is reflected in overall progress
```mermaid
flowchart TD
classDef memfile fill:#f4b8c4,stroke:#d498a4,color:#000
classDef process fill:#f9d77e,stroke:#d9b95c,color:#000
TaskTracking[Advanced Task<br>Tracking] --> PB[projectbrief.md]
TaskTracking --> PC[productContext.md]
TaskTracking --> AC[activeContext.md]
TaskTracking --> SP[systemPatterns.md]
TaskTracking --> TC[techContext.md]
TaskTracking --> P[progress.md]
P --> TU[Task<br>Updates]
TU --> TaskTracking
class PB,PC,AC,SP,TC,P memfile
class TaskTracking,TU process
```
## 📋 MINIMAL MODE TASK TRACKING
For situations requiring a more compact tracking approach:
```markdown
## [SYSTEM-ID]: System Name - [Status]
### Key Components:
- [COMP-ID]: [Component Name] - [Status] - [Progress %]
- [COMP-ID]: [Component Name] - [Status] - [Progress %]
### Active Tasks:
- [ ] [TASK-ID]: [Task Description] - [Assignee] - [Status]
- Dependencies: [List of task IDs]
- Risks: [Brief risk description]
- [ ] [TASK-ID]: [Task Description] - [Assignee] - [Status]
### Milestones:
- [MILE-ID]: [Milestone description] - [Target Date] - [Status]
- [MILE-ID]: [Milestone description] - [Target Date] - [Status]
### Critical Paths:
- [TASK-ID] → [TASK-ID] → [TASK-ID] → [TASK-ID]
- [TASK-ID] → [TASK-ID] → [TASK-ID]
### Updates:
- [Date]: [Brief update]
```
## 🚨 TASK TRACKING PRIMACY PRINCIPLE
```
┌─────────────────────────────────────────────────────┐
│ tasks.md is the SINGLE SOURCE OF TRUTH for all task │
│ tracking. All task-related decisions and status │
│ updates MUST be reflected in tasks.md. │
└─────────────────────────────────────────────────────┘
```
@@ -0,0 +1,424 @@
---
description: Comprehensive workflow for Level 4 Complex System tasks
globs: "**/level4/**", "**/workflow/**"
alwaysApply: false
---
# COMPREHENSIVE WORKFLOW FOR LEVEL 4 TASKS
> **TL;DR:** This document outlines a comprehensive workflow for Level 4 (Complex System) tasks, including 7 key phases with rigorous planning, mandatory creative phases, architectural design, phased implementation, and extensive documentation.
## 🔍 LEVEL 4 WORKFLOW OVERVIEW
```mermaid
graph LR
Init["1. INITIALIZATION"] --> Doc["2. DOCUMENTATION<br>SETUP"]
Doc --> Plan["3. ARCHITECTURAL<br>PLANNING"]
Plan --> Create["4. CREATIVE<br>PHASES"]
Create --> Impl["5. PHASED<br>IMPLEMENTATION"]
Impl --> Reflect["6. REFLECTION"]
Reflect --> Archive["7. ARCHIVING"]
%% Document connections for each phase
Init -.-> InitDocs["INITIALIZATION"]
Doc -.-> DocDocs["DOCUMENTATION"]
Plan -.-> PlanDocs["ARCHITECTURAL PLANNING"]
Create -.-> CreateDocs["CREATIVE PHASES"]
Impl -.-> ImplDocs["PHASED IMPLEMENTATION"]
Reflect -.-> ReflectDocs["REFLECTION"]
Archive -.-> ArchiveDocs["ARCHIVING"]
```
## 🔄 LEVEL TRANSITION HANDLING
```mermaid
graph TD
L4["Level 4 Task"] --> Assess["Continuous<br>Assessment"]
Assess --> Down["Downgrade to<br>Level 2/3"]
Assess --> Split["Split into<br>Multiple Tasks"]
Down --> L23Trigger["Triggers:<br>- Less complex<br>- Limited scope<br>- Few components"]
Split --> MultiTrigger["Triggers:<br>- Too large<br>- Independent parts<br>- Parallel possible"]
L23Trigger --> L23Switch["Switch to<br>Level 2/3 Workflow"]
MultiTrigger --> CreateTasks["Create Multiple<br>Lower Level Tasks"]
```
Level 4 tasks involve complex systems that require comprehensive planning, rigorous design, systematic implementation, and thorough documentation. This workflow ensures all aspects are addressed with the appropriate level of detail, structure, and verification.
## 📋 WORKFLOW PHASES
### Phase 1: INITIALIZATION
```mermaid
graph TD
Start["Start Level 4 Task"] --> Platform{"Detect<br>Platform"}
Platform --> FileCheck["Critical File<br>Verification"]
FileCheck --> LoadStructure["Comprehensive Memory<br>Bank Structure Loading"]
LoadStructure --> TaskCreation["Create Detailed<br>Task Framework"]
TaskCreation --> Context["Establish Enterprise<br>Context"]
Context --> Resources["Identify and Allocate<br>All Resources"]
Resources --> SetupComplete["Initialization<br>Complete"]
```
**Steps:**
1. Platform detection with comprehensive environment configuration
2. Critical file verification with in-depth integrity checks
3. Comprehensive Memory Bank structure loading with full reference mapping
4. Create detailed task framework in tasks.md with full structure
5. Establish complete enterprise context and stakeholder requirements
6. Identify and allocate all necessary resources (technical, human, time)
7. Perform system readiness assessment
**Milestone Checkpoint:**
```
✓ INITIALIZATION CHECKPOINT
- Platform detected and fully configured? [YES/NO]
- Critical files verified with integrity checks? [YES/NO]
- Memory Bank comprehensively loaded and mapped? [YES/NO]
- Detailed task framework created? [YES/NO]
- Enterprise context established? [YES/NO]
- Stakeholder requirements documented? [YES/NO]
- All resources identified and allocated? [YES/NO]
- System readiness assessed? [YES/NO]
→ If all YES: Proceed to Documentation Setup
→ If any NO: Complete initialization steps
```
### Phase 2: DOCUMENTATION SETUP
```mermaid
graph TD
Start["Begin Documentation<br>Setup"] --> LoadTemplate["Load Comprehensive<br>Documentation Templates"]
LoadTemplate --> Framework["Establish Documentation<br>Framework"]
Framework --> UpdateProject["Update<br>projectbrief.md"]
UpdateProject --> UpdateContext["Update<br>activeContext.md"]
UpdateContext --> SystemPatterns["Update<br>systemPatterns.md"]
SystemPatterns --> TechContext["Update<br>techContext.md"]
TechContext --> Standards["Document System<br>Standards"]
Standards --> Architecture["Document Existing<br>Architecture"]
Architecture --> SetupComplete["Documentation<br>Setup Complete"]
```
**Steps:**
1. Load comprehensive documentation templates for all aspects
2. Establish complete documentation framework with structure
3. Update projectbrief.md with detailed system description and requirements
4. Update activeContext.md with current focus, dependencies, and stakeholders
5. Update systemPatterns.md with comprehensive patterns and principles
6. Update techContext.md with complete technical landscape
7. Document system standards, constraints, and conventions
8. Document existing architecture and integration points
**Milestone Checkpoint:**
```
✓ DOCUMENTATION CHECKPOINT
- Documentation templates loaded? [YES/NO]
- Documentation framework established? [YES/NO]
- projectbrief.md comprehensively updated? [YES/NO]
- activeContext.md fully updated? [YES/NO]
- systemPatterns.md comprehensively updated? [YES/NO]
- techContext.md fully updated? [YES/NO]
- System standards documented? [YES/NO]
- Existing architecture documented? [YES/NO]
→ If all YES: Proceed to Architectural Planning
→ If any NO: Complete documentation setup
```
### Phase 3: ARCHITECTURAL PLANNING
```mermaid
graph TD
Start["Begin Architectural<br>Planning"] --> Requirements["Analyze Comprehensive<br>Requirements"]
Requirements --> BusinessContext["Document Business<br>Context"]
BusinessContext --> VisionDefine["Define Vision<br>and Goals"]
VisionDefine --> ArchitecturalPrinciples["Establish Architectural<br>Principles"]
ArchitecturalPrinciples --> Alternatives["Explore Architectural<br>Alternatives"]
Alternatives --> Evaluation["Perform Detailed<br>Evaluation"]
Evaluation --> Selection["Make Architecture<br>Selection"]
Selection --> Documentation["Create Architecture<br>Documentation"]
Documentation --> Review["Conduct Architecture<br>Review"]
Review --> PlanComplete["Architectural Planning<br>Complete"]
```
**Steps:**
1. Analyze comprehensive requirements with traceability
2. Document complete business context and constraints
3. Define clear vision and goals with measurable objectives
4. Establish architectural principles and non-functional requirements
5. Explore multiple architectural alternatives with thorough analysis
6. Perform detailed evaluation using weighted criteria
7. Make architecture selection with comprehensive justification
8. Create complete architecture documentation with diagrams
9. Conduct formal architecture review with stakeholders
**Milestone Checkpoint:**
```
✓ ARCHITECTURAL PLANNING CHECKPOINT
- Requirements comprehensively analyzed? [YES/NO]
- Business context fully documented? [YES/NO]
- Vision and goals clearly defined? [YES/NO]
- Architectural principles established? [YES/NO]
- Alternatives thoroughly explored? [YES/NO]
- Detailed evaluation performed? [YES/NO]
- Architecture selection justified? [YES/NO]
- Architecture documentation complete? [YES/NO]
- Architecture review conducted? [YES/NO]
→ If all YES: Proceed to Creative Phases
→ If any NO: Complete architectural planning
```
### Phase 4: CREATIVE PHASES
```mermaid
graph TD
Start["Begin Creative<br>Phases"] --> IdentifyNeeds["Identify Creative<br>Phase Needs"]
IdentifyNeeds --> Architecture["Architecture<br>Design Phase"]
Architecture --> Algorithm["Algorithm<br>Design Phase"]
Algorithm --> UIUX["UI/UX<br>Design Phase"]
UIUX --> Integration["Integration<br>Design Phase"]
Integration --> Security["Security<br>Design Phase"]
Security --> Performance["Performance<br>Design Phase"]
Performance --> Resilience["Resilience<br>Design Phase"]
Resilience --> Documentation["Comprehensive<br>Design Documentation"]
Documentation --> Review["Design<br>Review"]
Review --> CreativeComplete["Creative Phases<br>Complete"]
```
**Steps:**
1. Identify all required creative phases based on system needs
2. Execute comprehensive Architecture Design with patterns and principles
3. Conduct thorough Algorithm Design for all complex processes
4. Perform detailed UI/UX Design with user research and testing
5. Create Integration Design for all system interfaces
6. Develop Security Design with threat modeling
7. Design for Performance with capacity planning
8. Plan for Resilience with failure modes and recovery
9. Create comprehensive design documentation for all aspects
10. Conduct formal design review with stakeholders
**Milestone Checkpoint:**
```
✓ CREATIVE PHASES CHECKPOINT
- All required creative phases identified? [YES/NO]
- Architecture design completed with patterns? [YES/NO]
- Algorithm design conducted for complex processes? [YES/NO]
- UI/UX design performed with user research? [YES/NO]
- Integration design created for interfaces? [YES/NO]
- Security design developed with threat modeling? [YES/NO]
- Performance design completed with capacity planning? [YES/NO]
- Resilience design planned with failure modes? [YES/NO]
- Comprehensive design documentation created? [YES/NO]
- Formal design review conducted? [YES/NO]
→ If all YES: Proceed to Phased Implementation
→ If any NO: Complete creative phases
```
### Phase 5: PHASED IMPLEMENTATION
```mermaid
graph TD
Start["Begin Phased<br>Implementation"] --> PrepEnv["Prepare Comprehensive<br>Implementation Environment"]
PrepEnv --> Framework["Establish Implementation<br>Framework"]
Framework --> RoadmapDefine["Define Implementation<br>Roadmap"]
RoadmapDefine --> PhaseImplementation["Implement<br>Sequential Phases"]
PhaseImplementation --> PhaseVerification["Verify Each<br>Phase"]
PhaseVerification --> Integration["Perform Integration<br>Testing"]
Integration --> SystemTest["Conduct System<br>Testing"]
SystemTest --> UAT["User Acceptance<br>Testing"]
UAT --> Stabilization["System<br>Stabilization"]
Stabilization --> ImplComplete["Implementation<br>Complete"]
```
**Steps:**
1. Prepare comprehensive implementation environment with all tools
2. Establish implementation framework with standards and processes
3. Define detailed implementation roadmap with phases and dependencies
4. Implement sequential phases with milestone verification
5. Verify each phase against requirements and design
6. Perform comprehensive integration testing across phases
7. Conduct thorough system testing of the complete solution
8. Execute formal user acceptance testing with stakeholders
9. Perform system stabilization and performance tuning
10. Document all implementation details and deployment procedures
**Milestone Checkpoint:**
```
✓ PHASED IMPLEMENTATION CHECKPOINT
- Implementation environment fully prepared? [YES/NO]
- Implementation framework established? [YES/NO]
- Detailed roadmap defined with phases? [YES/NO]
- All phases sequentially implemented? [YES/NO]
- Each phase verified against requirements? [YES/NO]
- Comprehensive integration testing performed? [YES/NO]
- Thorough system testing conducted? [YES/NO]
- User acceptance testing executed? [YES/NO]
- System stabilization completed? [YES/NO]
- Implementation details documented? [YES/NO]
→ If all YES: Proceed to Reflection
→ If any NO: Complete implementation steps
```
### Phase 6: REFLECTION
```mermaid
graph TD
Start["Begin<br>Reflection"] --> Template["Load Comprehensive<br>Reflection Template"]
Template --> SystemReview["Complete System<br>Review"]
SystemReview --> Process["Analyze Process<br>Effectiveness"]
Process --> Success["Document Successes<br>with Evidence"]
Success --> Challenges["Document Challenges<br>with Solutions"]
Challenges --> TechnicalInsights["Extract Strategic<br>Technical Insights"]
TechnicalInsights --> ProcessInsights["Extract Process<br>Improvement Insights"]
ProcessInsights --> BusinessInsights["Document Business<br>Impact"]
BusinessInsights --> StrategicActions["Define Strategic<br>Action Items"]
StrategicActions --> ReflectComplete["Reflection<br>Complete"]
```
**Steps:**
1. Load comprehensive reflection template with all sections
2. Conduct complete system review against original goals
3. Analyze process effectiveness with metrics
4. Document successes with concrete evidence and impact
5. Document challenges with implemented solutions and lessons
6. Extract strategic technical insights for enterprise knowledge
7. Extract process improvement insights for future projects
8. Document business impact and value delivered
9. Define strategic action items with prioritization
10. Create comprehensive reflection documentation
**Milestone Checkpoint:**
```
✓ REFLECTION CHECKPOINT
- Comprehensive reflection template loaded? [YES/NO]
- Complete system review conducted? [YES/NO]
- Process effectiveness analyzed? [YES/NO]
- Successes documented with evidence? [YES/NO]
- Challenges documented with solutions? [YES/NO]
- Strategic technical insights extracted? [YES/NO]
- Process improvement insights extracted? [YES/NO]
- Business impact documented? [YES/NO]
- Strategic action items defined? [YES/NO]
- Comprehensive reflection documentation created? [YES/NO]
→ If all YES: Proceed to Archiving
→ If any NO: Complete reflection steps
```
### Phase 7: ARCHIVING
```mermaid
graph TD
Start["Begin<br>Archiving"] --> Template["Load Comprehensive<br>Archive Template"]
Template --> SystemDoc["Create System<br>Documentation"]
SystemDoc --> Architecture["Document Final<br>Architecture"]
Architecture --> Design["Compile Design<br>Decisions"]
Design --> Implementation["Document Implementation<br>Details"]
Implementation --> Testing["Compile Testing<br>Documentation"]
Testing --> Deployment["Create Deployment<br>Documentation"]
Deployment --> Maintenance["Prepare Maintenance<br>Guide"]
Maintenance --> Knowledge["Transfer Knowledge<br>to Stakeholders"]
Knowledge --> Archive["Create Comprehensive<br>Archive Package"]
Archive --> ArchiveComplete["Archiving<br>Complete"]
```
**Steps:**
1. Load comprehensive archive template with all sections
2. Create complete system documentation with all aspects
3. Document final architecture with diagrams and rationales
4. Compile all design decisions with justifications
5. Document all implementation details with technical specifics
6. Compile comprehensive testing documentation with results
7. Create detailed deployment documentation with procedures
8. Prepare maintenance guide with operational procedures
9. Transfer knowledge to all stakeholders with training
10. Create comprehensive archive package with all artifacts
**Milestone Checkpoint:**
```
✓ ARCHIVING CHECKPOINT
- Comprehensive archive template loaded? [YES/NO]
- Complete system documentation created? [YES/NO]
- Final architecture documented? [YES/NO]
- Design decisions compiled? [YES/NO]
- Implementation details documented? [YES/NO]
- Testing documentation compiled? [YES/NO]
- Deployment documentation created? [YES/NO]
- Maintenance guide prepared? [YES/NO]
- Knowledge transferred to stakeholders? [YES/NO]
- Comprehensive archive package created? [YES/NO]
→ If all YES: Task Complete
→ If any NO: Complete archiving steps
```
## 📋 WORKFLOW VERIFICATION CHECKLIST
```
✓ FINAL WORKFLOW VERIFICATION
- All 7 phases completed? [YES/NO]
- All milestone checkpoints passed? [YES/NO]
- Architectural planning properly executed? [YES/NO]
- All required creative phases completed? [YES/NO]
- Implementation performed in proper phases? [YES/NO]
- Comprehensive reflection conducted? [YES/NO]
- Complete system documentation archived? [YES/NO]
- Memory Bank fully updated? [YES/NO]
- Knowledge successfully transferred? [YES/NO]
→ If all YES: Level 4 Task Successfully Completed
→ If any NO: Address outstanding items
```
## 📋 MINIMAL MODE WORKFLOW
For minimal mode, use this streamlined workflow while retaining key elements:
```
1. INIT: Verify environment, create structured task framework, establish context
2. DOCS: Update all Memory Bank documents, document standards and architecture
3. PLAN: Define architecture with principles, alternatives, evaluation, selection
4. CREATE: Execute all required creative phases with documentation
5. IMPL: Implement in phases with verification, integration, testing
6. REFLECT: Document successes, challenges, insights, and strategic actions
7. ARCHIVE: Create comprehensive documentation and knowledge transfer
```
## 🔄 INTEGRATION WITH MEMORY BANK
This workflow integrates comprehensively with Memory Bank:
```mermaid
graph TD
Workflow["Level 4<br>Workflow"] --> PB["Comprehensive Update<br>projectbrief.md"]
Workflow --> AC["Detailed Update<br>activeContext.md"]
Workflow --> SP["Strategic Update<br>systemPatterns.md"]
Workflow --> TC["Complete Update<br>techContext.md"]
Workflow --> TM["Structured Maintenance<br>tasks.md"]
Workflow --> PM["Enterprise Update<br>progress.md"]
PB & AC & SP & TC & TM & PM --> MB["Memory Bank<br>Integration"]
MB --> KT["Knowledge<br>Transfer"]
KT --> NextSystem["Enterprise<br>System Evolution"]
```
## 🚨 LEVEL 4 GOVERNANCE PRINCIPLE
Remember:
```
┌─────────────────────────────────────────────────────┐
│ Level 4 tasks represent ENTERPRISE-CRITICAL work. │
│ RIGOROUS governance, comprehensive documentation, │
│ and thorough verification are MANDATORY at each │
│ phase. NO EXCEPTIONS. │
└─────────────────────────────────────────────────────┘
```
This ensures that complex systems are designed, implemented, and documented to the highest standards, with enterprise-grade quality and governance.
@@ -0,0 +1,187 @@
---
description: creative phase architecture
globs: creative-phase-architecture.md
alwaysApply: false
---
# CREATIVE PHASE: ARCHITECTURE DESIGN
> **TL;DR:** This document provides structured guidance for architectural design decisions during creative phases, ensuring comprehensive evaluation of options and clear documentation of architectural choices.
## 🏗️ ARCHITECTURE DESIGN WORKFLOW
```mermaid
graph TD
Start["Architecture<br>Design Start"] --> Req["1. Requirements<br>Analysis"]
Req --> Comp["2. Component<br>Identification"]
Comp --> Options["3. Architecture<br>Options"]
Options --> Eval["4. Option<br>Evaluation"]
Eval --> Decision["5. Decision &<br>Documentation"]
Decision --> Valid["6. Validation &<br>Verification"]
style Start fill:#4da6ff,stroke:#0066cc,color:white
style Req fill:#ffa64d,stroke:#cc7a30,color:white
style Comp fill:#4dbb5f,stroke:#36873f,color:white
style Options fill:#d94dbb,stroke:#a3378a,color:white
style Eval fill:#4dbbbb,stroke:#368787,color:white
style Decision fill:#d971ff,stroke:#a33bc2,color:white
style Valid fill:#ff71c2,stroke:#c23b8a,color:white
```
## 📋 ARCHITECTURE DECISION TEMPLATE
```markdown
# Architecture Decision Record
## Context
- System Requirements:
- [Requirement 1]
- [Requirement 2]
- Technical Constraints:
- [Constraint 1]
- [Constraint 2]
## Component Analysis
- Core Components:
- [Component 1]: [Purpose/Role]
- [Component 2]: [Purpose/Role]
- Interactions:
- [Interaction 1]
- [Interaction 2]
## Architecture Options
### Option 1: [Name]
- Description: [Brief description]
- Pros:
- [Pro 1]
- [Pro 2]
- Cons:
- [Con 1]
- [Con 2]
- Technical Fit: [High/Medium/Low]
- Complexity: [High/Medium/Low]
- Scalability: [High/Medium/Low]
### Option 2: [Name]
[Same structure as Option 1]
## Decision
- Chosen Option: [Option name]
- Rationale: [Explanation]
- Implementation Considerations:
- [Consideration 1]
- [Consideration 2]
## Validation
- Requirements Met:
- [✓] Requirement 1
- [✓] Requirement 2
- Technical Feasibility: [Assessment]
- Risk Assessment: [Evaluation]
```
## 🎯 ARCHITECTURE EVALUATION CRITERIA
```mermaid
graph TD
subgraph "EVALUATION CRITERIA"
C1["Scalability"]
C2["Maintainability"]
C3["Performance"]
C4["Security"]
C5["Cost"]
C6["Time to Market"]
end
style C1 fill:#4dbb5f,stroke:#36873f,color:white
style C2 fill:#ffa64d,stroke:#cc7a30,color:white
style C3 fill:#d94dbb,stroke:#a3378a,color:white
style C4 fill:#4dbbbb,stroke:#368787,color:white
style C5 fill:#d971ff,stroke:#a33bc2,color:white
style C6 fill:#ff71c2,stroke:#c23b8a,color:white
```
## 📊 ARCHITECTURE VISUALIZATION TEMPLATES
### Component Diagram Template
```mermaid
graph TD
subgraph "SYSTEM ARCHITECTURE"
C1["Component 1"]
C2["Component 2"]
C3["Component 3"]
C1 -->|"Interface 1"| C2
C2 -->|"Interface 2"| C3
end
style C1 fill:#4dbb5f,stroke:#36873f,color:white
style C2 fill:#ffa64d,stroke:#cc7a30,color:white
style C3 fill:#d94dbb,stroke:#a3378a,color:white
```
### Data Flow Template
```mermaid
sequenceDiagram
participant C1 as Component 1
participant C2 as Component 2
participant C3 as Component 3
C1->>C2: Request
C2->>C3: Process
C3-->>C2: Response
C2-->>C1: Result
```
## ✅ VERIFICATION CHECKLIST
```markdown
## Architecture Design Verification
- [ ] All system requirements addressed
- [ ] Component responsibilities defined
- [ ] Interfaces specified
- [ ] Data flows documented
- [ ] Security considerations addressed
- [ ] Scalability requirements met
- [ ] Performance requirements met
- [ ] Maintenance approach defined
## Implementation Readiness
- [ ] All components identified
- [ ] Dependencies mapped
- [ ] Technical constraints documented
- [ ] Risk assessment completed
- [ ] Resource requirements defined
- [ ] Timeline estimates provided
```
## 🔄 ARCHITECTURE REVIEW PROCESS
```mermaid
graph TD
subgraph "REVIEW PROCESS"
R1["Technical<br>Review"]
R2["Security<br>Review"]
R3["Performance<br>Review"]
R4["Final<br>Approval"]
end
R1 --> R2 --> R3 --> R4
style R1 fill:#4dbb5f,stroke:#36873f,color:white
style R2 fill:#ffa64d,stroke:#cc7a30,color:white
style R3 fill:#d94dbb,stroke:#a3378a,color:white
style R4 fill:#4dbbbb,stroke:#368787,color:white
```
## 🔄 DOCUMENT MANAGEMENT
```mermaid
graph TD
Current["Current Document"] --> Active["Active:<br>- creative-phase-architecture.md"]
Current --> Related["Related:<br>- creative-phase-enforcement.md<br>- planning-comprehensive.md"]
style Current fill:#4da6ff,stroke:#0066cc,color:white
style Active fill:#4dbb5f,stroke:#36873f,color:white
style Related fill:#ffa64d,stroke:#cc7a30,color:white
```
@@ -0,0 +1,232 @@
---
description: UI/UX Design Guidelines and Process for the Creative Phase
globs: creative-phase-uiux.mdc
alwaysApply: false
---
Okay, I've updated the style guide location to `memory-bank/style-guide.md` and will provide the entire content for the new `creative-phase-uiux.md` file within a single markdown code block for easy copying. I've also reviewed the Mermaid diagrams to ensure they are correctly formatted.
# Creative Phase: UI/UX Design Guidelines
**Document Purpose:** This document outlines the structured approach for UI/UX design decisions during the Creative Phase. It ensures user-centric designs, exploration of multiple options, adherence to a style guide (if available or created), and clear documentation of UI/UX choices, aligning with React/Tailwind best practices.
## 🎨 UI/UX Design Philosophy
* **User-Centricity**: Designs must prioritize the user's needs, goals, and context.
* **Clarity & Simplicity**: Interfaces should be intuitive and easy to understand.
* **Consistency**: Maintain consistency with established design patterns, project-specific styles, and platform conventions.
* **Accessibility (A11y)**: Adhere to WCAG guidelines to ensure usability for people with disabilities.
* **Efficiency**: Enable users to accomplish tasks with minimal effort.
* **Feedback**: Provide clear and timely feedback for user actions.
* **Visual Cohesion**: Ensure new UI elements align with the existing or defined project style guide.
## 🌊 UI/UX Design Workflow
This workflow guides the UI/UX design process within the Creative Phase, incorporating a crucial style guide check.
```mermaid
graph TD
Start["UI/UX Design Start"] --> StyleGuideCheck["0. Style Guide Check<br>Attempt to locate 'memory-bank/style-guide.md' or user-provided path."]
StyleGuideCheck --> HasStyleGuide{"Style Guide<br>Available/Loaded?"}
HasStyleGuide -- "Yes" --> Understand["Understand User & Task<br>(Personas, User Stories, Requirements)"]
HasStyleGuide -- "No" --> PromptCreateStyleGuide["Prompt User: Create/Link Style Guide?"]
PromptCreateStyleGuide --> UserResponse{"User Opts to Create/Link?"}
UserResponse -- "Yes, Create" --> DefineStyleGuideSubProcess["SUB-PROCESS:Define Basic Style Guide"]
UserResponse -- "Yes, Link" --> LinkStyleGuide["User provides path/URL.<br>Load Style Guide."]
UserResponse -- "No" --> Understand_NoGuide["Understand User & Task<br>(Proceeding without Style Guide - WARN user of inconsistencies)"]
DefineStyleGuideSubProcess --> StyleGuideCreated["Basic 'memory-bank/style-guide.md' Created/Defined"]
StyleGuideCreated --> Understand
LinkStyleGuide --> Understand
Understand_NoGuide --> InfoArch_NoGuide["Information Architecture"]
Understand --> InfoArch["Information Architecture<br>(Structure, Navigation, Content Hierarchy)"]
InfoArch --> Interaction["Interaction Design<br>(User Flows, Wireframes, Prototypes - Conceptual)"]
Interaction --> VisualDesign["Visual Design<br>(APPLY STYLE GUIDE, Leverage React/Tailwind, Mockups - Conceptual)"]
VisualDesign --> Options["Explore UI/UX Options<br>(Generate 2-3 distinct solutions)"]
Options --> Evaluate["Evaluate Options<br>(Usability, Feasibility, A11y, Aesthetics, <b>Style Guide Alignment</b>)"]
Evaluate --> Decision["Make & Document UI/UX Decision<br>(Use Optimized Creative Template)"]
Decision --> Validate["Validate Against Requirements, Principles & <b>Style Guide</b>"]
Validate --> UIUX_Complete["UI/UX Design Complete for Component"]
InfoArch_NoGuide --> Interaction_NoGuide["Interaction Design"]
Interaction_NoGuide --> VisualDesign_NoGuide["Visual Design<br>(Leverage React/Tailwind, Aim for Internal Consistency)"]
VisualDesign_NoGuide --> Options_NoGuide["Explore UI/UX Options"]
Options_NoGuide --> Evaluate_NoGuide["Evaluate Options<br>(Usability, Feasibility, A11y, Aesthetics)"]
Evaluate_NoGuide --> Decision_NoGuide["Make & Document UI/UX Decision"]
Decision_NoGuide --> Validate_NoGuide["Validate Against Requirements & Principles"]
Validate_NoGuide --> UIUX_Complete
style Start fill:#4da6ff,stroke:#0066cc,color:white
style StyleGuideCheck fill:#ab87ff,stroke:#7d5bbe,color:white
style HasStyleGuide fill:#ab87ff,stroke:#7d5bbe,color:white
style PromptCreateStyleGuide fill:#ffcb6b,stroke:#f9a825,color:black
style UserResponse fill:#ffcb6b,stroke:#f9a825,color:black
style DefineStyleGuideSubProcess fill:#c3e88d,stroke:#82a75c,color:black
style LinkStyleGuide fill:#c3e88d,stroke:#82a75c,color:black
style StyleGuideCreated fill:#c3e88d,stroke:#82a75c,color:black
style VisualDesign fill:#4dbbbb,stroke:#368787,color:white
style Evaluate fill:#d971ff,stroke:#a33bc2,color:white
style Validate fill:#71c2ff,stroke:#3b8aa3,color:white
style Understand_NoGuide fill:#ff8a80,stroke:#c85a54,color:black
style UIUX_Complete fill:#5fd94d,stroke:#3da336,color:white
```
## 📖 Style Guide Integration
A consistent visual style is paramount for good UI/UX. This section details how to reference an existing style guide or prompt for its creation. **The primary location for the style guide in this system will be `memory-bank/style-guide.md`.**
### Step 0: Style Guide Check & Handling
**A. Checking for an Existing Style Guide:**
1. **Primary Location Check**: The system **MUST** first look for the style guide at this specific path:
* `memory-bank/style-guide.md`
2. **Secondary Check (User Prompt)**: If `memory-bank/style-guide.md` is not found, the system **MUST** prompt the user:
```
"I could not find 'memory-bank/style-guide.md'.
Is there an existing style guide at a different location, or a URL I should reference?
If yes, please provide the full path or URL.
Otherwise, we can create a basic 'memory-bank/style-guide.md' now, or you can opt to proceed without one (though this is not recommended for new UI development)."
```
**B. Using an Existing Style Guide:**
* If `memory-bank/style-guide.md` is found or an alternative path/URL is provided by the user:
* Load its content into context.
* **CRITICAL**: All subsequent UI/UX design proposals (colors, typography, spacing, component appearance) **MUST** adhere strictly to this guide.
* When evaluating options (Step 6 of the workflow), "Adherence to Style Guide" **MUST** be a key evaluation criterion.
**C. If No Style Guide Exists or is Provided (User Interaction):**
* If no style guide is found or linked by the user, the system **MUST** strongly recommend creating one:
```
"No style guide has been referenced. For optimal UI consistency and development efficiency, creating 'memory-bank/style-guide.md' is highly recommended."
"Would you like to:"
"1. Create a basic 'memory-bank/style-guide.md' now? (I can help you define core elements like colors, typography, and spacing based on observations or your input.)"
"2. Proceed with UI/UX design without a style guide? (WARNING: This may lead to visual inconsistencies and is strongly discouraged for new features or significant UI changes.)"
"Please choose 1 or 2."
```
(If the user previously chose to link one but it failed, this prompt should adapt).
**D. Assisting in Style Guide Creation (If user opts-in for option 1):**
This initiates a sub-process to define and document a basic style guide, which will be saved as `memory-bank/style-guide.md`.
```mermaid
graph TD
StartCreate["User Opts to Create Style Guide"] --> GatherInspiration["Gather Inspiration<br>(e.g., Analyze user-provided image, existing UI, or direct user input)"]
GatherInspiration --> DefineColors["Define Core Color Palette<br>(Primary, Secondary, Accent, Neutrals, Status Colors - with hex codes)"]
DefineColors --> DefineTypography["Define Typography<br>(Font Families, Sizes, Weights for Headings, Body, Links)"]
DefineTypography --> DefineSpacing["Define Spacing System<br>(Base unit, margins, paddings, Tailwind scale usage)"]
DefineSpacing --> DefineComponents["Define Key Component Styles (Conceptual)<br>(Buttons, Inputs, Cards - using Tailwind utility classes if applicable)"]
DefineComponents --> DefineTone["Define Tone of Voice & Imagery Style (Optional)"]
DefineTone --> GenerateDoc["Generate content for 'memory-bank/style-guide.md'<br>(Populate with defined elements)"]
GenerateDoc --> SaveFile["Save the generated content to 'memory-bank/style-guide.md'"]
SaveFile --> Confirm["Confirm 'memory-bank/style-guide.md' creation & Proceed with UI/UX Design"]
style StartCreate fill:#c3e88d,stroke:#82a75c,color:black
style GatherInspiration fill:#e0f2f1,stroke:#a7c4c0,color:black
style SaveFile fill:#89cff0,stroke:#50a6c2,color:black
```
* **Process**:
1. **Inspiration**: Analyze user-provided examples (like the dashboard image `original-a5959a2926d1e7ede16dbe1d27593a59.webp`) or ask for user preferences.
* `AI: "To create a style guide, do you have an existing design, screenshot, or website I can analyze for styles? Or would you like to define them from scratch?"`
2. **Define Elements**: Guide the user through defining colors, typography, spacing, and key component styles (as detailed in the previous response regarding the sample based on the image).
3. **Documentation**: Generate the content for `memory-bank/style-guide.md`. The structure should be similar to the sample style guide created from the dashboard image.
4. **Save File**: The system should then create and save this content to the file `memory-bank/style-guide.md`.
* Once `memory-bank/style-guide.md` is created/loaded, it becomes the **single source of truth for visual design**.
## 🖼️ Key UI/UX Design Considerations (To be applied using `memory-bank/style-guide.md`)
### 1. User Needs Analysis
* **Personas**: Define target user personas.
* **User Stories/Jobs-to-be-Done**: Clarify what users need to achieve.
* **Use Cases**: Detail specific interaction scenarios.
### 2. Information Architecture (IA)
* **Content Inventory & Audit**: Understand existing content.
* **Hierarchy & Structure**: Organize content logically.
* **Navigation Design**: Design intuitive navigation (menus, breadcrumbs) adhering to `memory-bank/style-guide.md` for appearance.
* **Labeling**: Use clear and consistent labels.
### 3. Interaction Design (IxD)
* **User Flows**: Map out the user's path.
* **Wireframes**: Create low-fidelity layouts.
* **Prototypes (Conceptual)**: Describe interactive elements and transitions.
* **Error Handling & Prevention**: Design clear error messages (styled per `memory-bank/style-guide.md`).
* **Feedback Mechanisms**: Implement visual/textual feedback (styled per `memory-bank/style-guide.md`).
### 4. Visual Design (Strictly follow `memory-bank/style-guide.md`)
* **Style Guide Adherence**: **CRITICAL** - All visual choices **MUST** conform to `memory-bank/style-guide.md`.
* **Visual Hierarchy**: Use the Style Guide's typography and spacing to guide the user.
* **Layout & Composition**: Arrange elements effectively using Tailwind CSS and Style Guide spacing.
* **Typography**: Apply defined font families, sizes, and weights from the Style Guide.
* **Color Palette**: Exclusively use colors defined in the Style Guide.
* **Imagery & Iconography**: Use icons and images that match the Style Guide's defined style.
* **Branding**: Align with project branding guidelines as documented in the Style Guide.
### 5. Accessibility (A11y)
* **WCAG Compliance Level**: Target AA or AAA.
* **Semantic HTML**.
* **Keyboard Navigation**.
* **ARIA Attributes**.
* **Color Contrast**: Verify against Style Guide colors.
* **Alternative Text**.
### 6. Platform & Responsiveness
* **Responsive Design**: Ensure UI adapts to screen sizes using Style Guide's responsive principles (if defined).
* **Platform Conventions**: Adhere to UI patterns for the target platform(s).
## 🛠️ UI/UX Option Evaluation & Decision Making
Reference the project's `optimized-creative-template.mdc`. Key evaluation criteria **must** include:
* Usability
* Learnability
* Efficiency
* Accessibility
* Aesthetics (as defined by `memory-bank/style-guide.md`)
* Feasibility (React/Tailwind)
* Alignment with Requirements
* **Adherence to `memory-bank/style-guide.md` (CRITICAL if guide exists)**
```mermaid
graph TD
subgraph "UI/UX EVALUATION CRITERIA"
C1["Usability"]
C2["Learnability"]
C3["Efficiency"]
C4["Accessibility (A11y)"]
C5["Aesthetics (Per Style Guide)"]
C6["Feasibility (React/Tailwind)"]
C7["Alignment with Requirements"]
C8["<b>Style Guide Adherence</b>"]
end
style C8 fill:#ff5555,stroke:#c30052,color:white
```
## 📝 Documentation Standards
* Use the project's `optimized-creative-template.mdc` for documenting UI/UX decisions.
* Clearly describe chosen UI patterns and rationale, referencing `memory-bank/style-guide.md`.
* Document considerations for responsive states and accessibility, as guided by `memory-bank/style-guide.md`.
## ✅ UI/UX Design Verification Checklist
* [ ] **Style Guide (`memory-bank/style-guide.md`) referenced or created?**
* [ ] User needs clearly understood and addressed?
* [ ] Information architecture logical and intuitive?
* [ ] Interaction design clear and efficient?
* [ ] **Visual design strictly adheres to `memory-bank/style-guide.md`?**
* [ ] Accessibility standards met?
* [ ] Responsive design addressed?
* [ ] Design decisions documented with rationale and Style Guide references?
* [ ] Alignment with React/Tailwind best practices and Style Guide considered?
## 🔄 Integration with Other Creative Phases
* **Architecture Design**: Ensure UI/UX is compatible with system architecture.
* **Data Model Design**: UI should effectively present/capture data from the data model.
* **Style Guide**: All UI/UX work **must** be a direct application or extension of the established `memory-bank/style-guide.md`.
```
@@ -0,0 +1,219 @@
---
description: Optimized creative phase template with progressive documentation
globs: "**/creative*/**", "**/design*/**", "**/decision*/**"
alwaysApply: false
---
# OPTIMIZED CREATIVE PHASE TEMPLATE
> **TL;DR:** This template implements a progressive documentation approach for creative phases, optimizing token usage while maintaining thorough design exploration.
## 📝 PROGRESSIVE DOCUMENTATION MODEL
```mermaid
graph TD
Start["Creative Phase Start"] --> P1["1️⃣ PROBLEM<br>Define scope"]
P1 --> P2["2️⃣ OPTIONS<br>Explore alternatives"]
P2 --> P3["3️⃣ ANALYSIS<br>Evaluate selected options"]
P3 --> P4["4️⃣ DECISION<br>Finalize approach"]
P4 --> P5["5️⃣ IMPLEMENTATION<br>Document guidelines"]
style Start fill:#d971ff,stroke:#a33bc2,color:white
style P1 fill:#4da6ff,stroke:#0066cc,color:white
style P2 fill:#ffa64d,stroke:#cc7a30,color:white
style P3 fill:#4dbb5f,stroke:#36873f,color:white
style P4 fill:#d94dbb,stroke:#a3378a,color:white
style P5 fill:#4dbbbb,stroke:#368787,color:white
```
## 📋 TEMPLATE STRUCTURE
```markdown
📌 CREATIVE PHASE START: [Component Name]
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1️⃣ PROBLEM
Description: [Brief problem description]
Requirements: [Key requirements as bullet points]
Constraints: [Technical or business constraints]
2️⃣ OPTIONS
Option A: [Name] - [One-line description]
Option B: [Name] - [One-line description]
Option C: [Name] - [One-line description]
3️⃣ ANALYSIS
| Criterion | Option A | Option B | Option C |
|-----------|----------|----------|----------|
| Performance | ⭐⭐⭐ | ⭐⭐ | ⭐⭐⭐⭐ |
| Complexity | ⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ |
| Maintainability | ⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐ |
Key Insights:
- [Insight 1]
- [Insight 2]
4️⃣ DECISION
Selected: [Option X]
Rationale: [Brief justification]
5️⃣ IMPLEMENTATION NOTES
- [Implementation note 1]
- [Implementation note 2]
- [Implementation note 3]
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📌 CREATIVE PHASE END
```
## 🧩 DETAILED OPTION ANALYSIS (ON DEMAND)
Detailed analysis can be provided on demand for selected options:
```markdown
<details>
<summary>Detailed Analysis: Option A</summary>
### Option A: [Full Name]
**Complete Description**:
[Detailed description of how the option works]
**Pros**:
- [Pro 1 with explanation]
- [Pro 2 with explanation]
- [Pro 3 with explanation]
**Cons**:
- [Con 1 with explanation]
- [Con 2 with explanation]
**Implementation Complexity**: [Low/Medium/High]
[Explanation of complexity factors]
**Resource Requirements**:
[Details on resource needs]
**Risk Assessment**:
[Analysis of risks]
</details>
```
## 📊 COMPLEXITY-BASED SCALING
The template automatically scales documentation requirements based on task complexity level:
### Level 1-2 (Quick Fix/Enhancement)
- Simplified problem/solution
- Focus on implementation
- Minimal option exploration
### Level 3 (Feature Development)
- Multiple options required
- Analysis table with key criteria
- Implementation guidelines
### Level 4 (Enterprise Development)
- Comprehensive analysis
- Multiple viewpoints considered
- Detailed implementation plan
- Expanded verification criteria
## ✅ VERIFICATION PROTOCOL
Quality verification is condensed into a simple checklist:
```markdown
VERIFICATION:
[x] Problem clearly defined
[x] Multiple options considered
[x] Decision made with rationale
[x] Implementation guidance provided
```
## 🔄 USAGE EXAMPLES
### Architecture Decision (Level 3)
```markdown
📌 CREATIVE PHASE START: Authentication System
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1️⃣ PROBLEM
Description: Design an authentication system for the application
Requirements: Secure, scalable, supports SSO, easy to maintain
Constraints: Must work with existing user database, <100ms response time
2️⃣ OPTIONS
Option A: JWT-based stateless auth - Simple token-based approach
Option B: Session-based auth with Redis - Server-side session storage
Option C: OAuth2 implementation - Delegated authorization framework
3️⃣ ANALYSIS
| Criterion | JWT | Sessions | OAuth2 |
|-----------|-----|----------|--------|
| Security | ⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
| Scalability | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ |
| Complexity | ⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ |
| Performance | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐ |
Key Insights:
- JWT offers best performance but limited revocation options
- Sessions provide better security control but require more infrastructure
- OAuth2 most complex but offers best integration possibilities
4️⃣ DECISION
Selected: Option A: JWT-based auth with refresh tokens
Rationale: Best balance of performance and scalability while meeting security needs
5️⃣ IMPLEMENTATION NOTES
- Use HS256 algorithm for token signing
- Implement short-lived access tokens (15min) with longer refresh tokens (7 days)
- Store token blacklist in Redis for revocation capability
- Add rate limiting on token endpoints
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📌 CREATIVE PHASE END
```
### Algorithm Decision (Level 2)
```markdown
📌 CREATIVE PHASE START: Search Algorithm
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1️⃣ PROBLEM
Description: Implement efficient text search for product catalog
Requirements: Fast results, support for partial matches, case insensitive
Constraints: Dataset < 10,000 items, must work in browser environment
2️⃣ OPTIONS
Option A: Simple regex search - Basic pattern matching
Option B: Trie-based search - Prefix tree structure
Option C: Fuzzy search with Levenshtein - Edit distance algorithm
3️⃣ DECISION
Selected: Option B: Trie-based search
Rationale: Best performance for prefix searches with manageable memory usage
4️⃣ IMPLEMENTATION NOTES
- Use existing trie library
- Preprocess text to lowercase during indexing
- Implement letter-by-letter search for instant results
- Add debounce (300ms) to prevent excessive rebuilding
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📌 CREATIVE PHASE END
```
## 🏆 TOKEN EFFICIENCY BENEFITS
This template significantly reduces token usage by:
1. Focusing on essential information without unnecessary verbosity
2. Using compact tabular formats for comparisons
3. Implementing progressive disclosure for detailed information
4. Scaling documentation requirements by task complexity
5. Using visual indicators (emojis) for quick scanning
The template maintains the rigor of the creative process while improving token efficiency by approximately 60% over the previous format.
+237
View File
@@ -0,0 +1,237 @@
---
description: Optimized main rule for improved token efficiency
globs: main.mdc
alwaysApply: false
---
# 🔍 OPTIMIZED MEMORY BANK SYSTEM
🚨 CRITICAL RULE: MEMORY BANK CREATION IS MANDATORY 🚨
Memory Bank MUST be created BEFORE any other operation in ANY mode
NO process can continue without verifying Memory Bank existence
> **TL;DR:** This system uses optimized context management and adaptive rule loading to maximize token efficiency while preserving the structured development approach.
## 🧭 OPTIMIZED MODE ARCHITECTURE
```mermaid
graph TD
subgraph "Memory Bank Core"
Context["Context Manager"]
Rules["Rule Loader"]
FileIO["File Manager"]
Transition["Mode Transition"]
end
subgraph "Custom Modes"
VAN["VAN<br>Initialization"]
PLAN["PLAN<br>Planning"]
CREATIVE["CREATIVE<br>Design"]
BUILD["BUILD<br>Building"]
REFLECT["REFLECT<br>Review"]
ARCHIVE["ARCHIVE<br>Documentation"]
end
Context --> VAN & PLAN & CREATIVE & BUILD & REFLECT & ARCHIVE
Rules --> VAN & PLAN & CREATIVE & BUILD & REFLECT & ARCHIVE
FileIO --> VAN & PLAN & CREATIVE & BUILD & REFLECT & ARCHIVE
Transition --> VAN & PLAN & CREATIVE & BUILD & REFLECT & ARCHIVE
VAN --> PLAN
PLAN --> CREATIVE
CREATIVE --> BUILD
BUILD --> REFLECT
REFLECT --> ARCHIVE
style Context fill:#4da6ff,stroke:#0066cc,color:white
style Rules fill:#ffa64d,stroke:#cc7a30,color:white
style FileIO fill:#4dbb5f,stroke:#36873f,color:white
style Transition fill:#d94dbb,stroke:#a3378a,color:white
```
## 📈 ADAPTIVE COMPLEXITY MODEL
```mermaid
graph TD
Task["Task Creation"] --> Complexity{"Complexity<br>Level?"}
Complexity -->|"Level 1<br>Quick Fix"| L1["3-Phase<br>Streamlined Process"]
Complexity -->|"Level 2<br>Enhancement"| L2["4-Phase<br>Balanced Process"]
Complexity -->|"Level 3<br>Feature"| L3["5-Phase<br>Comprehensive Process"]
Complexity -->|"Level 4<br>Enterprise"| L4["6-Phase<br>Governance Process"]
L1 --> L1_Process["VAN → BUILD → REFLECT"]
L2 --> L2_Process["VAN → PLAN → BUILD → REFLECT"]
L3 --> L3_Process["VAN → PLAN → CREATIVE → BUILD → REFLECT"]
L4 --> L4_Process["VAN → PLAN → CREATIVE → BUILD → REFLECT → ARCHIVE"]
style Complexity fill:#d94dbb,stroke:#a3378a,color:white
style L1 fill:#4dbb5f,stroke:#36873f,color:white
style L2 fill:#ffa64d,stroke:#cc7a30,color:white
style L3 fill:#4da6ff,stroke:#0066cc,color:white
style L4 fill:#ff5555,stroke:#cc0000,color:white
```
## 🧠 HIERARCHICAL RULE LOADING
Rules are loaded hierarchically to optimize context usage:
```mermaid
graph TD
Root["Memory Bank<br>Common Rules"] --> Core["Core Rules<br>Shared Across Modes"]
Core --> L1["Level 1<br>Rules"]
Core --> L2["Level 2<br>Rules"]
Core --> L3["Level 3<br>Rules"]
Core --> L4["Level 4<br>Rules"]
Core --> VM["Mode<br>Visual Maps"]
Core --> Phase["Phase-Specific<br>Rules"]
Phase --> VAN_Rules["VAN Mode<br>Rules"]
Phase --> PLAN_Rules["PLAN Mode<br>Rules"]
Phase --> CREATIVE_Rules["CREATIVE Mode<br>Rules"]
Phase --> BUILD_Rules["BUILD Mode<br>Rules"]
Phase --> REFLECT_Rules["REFLECT Mode<br>Rules"]
Phase --> ARCHIVE_Rules["ARCHIVE Mode<br>Rules"]
style Root fill:#4da6ff,stroke:#0066cc,color:white
style Core fill:#ffa64d,stroke:#cc7a30,color:white
style Phase fill:#4dbb5f,stroke:#36873f,color:white
```
## 🔄 TOKEN-OPTIMIZED CREATIVE PHASE
Creative phase documentation is progressively generated:
```mermaid
graph TD
Start["Creative Phase<br>Initiation"] --> P1["1️⃣ PROBLEM<br>Define scope"]
P1 --> P2["2️⃣ OPTIONS<br>List alternatives"]
P2 --> P3["3️⃣ ANALYSIS<br>Compare options"]
P3 --> P4["4️⃣ DECISION<br>Select approach"]
P4 --> P5["5️⃣ GUIDELINES<br>Document implementation"]
P3 -.->|"On Demand"| Details["Detailed Option<br>Analysis"]
style Start fill:#d971ff,stroke:#a33bc2,color:white
style P1 fill:#4da6ff,stroke:#0066cc,color:white
style P2 fill:#ffa64d,stroke:#cc7a30,color:white
style P3 fill:#4dbb5f,stroke:#36873f,color:white
style P4 fill:#d94dbb,stroke:#a3378a,color:white
style P5 fill:#4dbbbb,stroke:#368787,color:white
style Details fill:#e699d9,stroke:#d94dbb,color:white,stroke-dasharray: 5 5
```
## 🔀 OPTIMIZED MODE TRANSITIONS
Mode transitions use a unified context transfer protocol:
```mermaid
sequenceDiagram
participant Current as Current Mode
participant Context as Context Manager
participant Next as Next Mode
Current->>Context: Create transition document
Current->>Context: Store critical context
Context->>Context: Prepare rule cache
Current->>Next: Initiate transition
Next->>Context: Verify context availability
Context->>Next: Load relevant context
Context->>Next: Load cached rules
Next->>Next: Continue with preserved context
```
## 📊 MEMORY BANK EFFICIENT UPDATES
```mermaid
graph TD
subgraph "Memory Bank Files"
tasks["tasks.md<br>Source of Truth"]
active["activeContext.md<br>Current Focus"]
creative["creative-*.md<br>Design Decisions"]
progress["progress.md<br>Implementation Status"]
transition["transition.md<br>Mode Transitions"]
end
Update["Update Request"] --> Diff{"Changed?"}
Diff -->|"No"| Skip["Skip Update"]
Diff -->|"Yes"| Section{"Section<br>Change?"}
Section -->|"Yes"| Partial["Update Changed<br>Sections Only"]
Section -->|"No"| Full["Full File<br>Update"]
Partial --> tasks
Full --> tasks
style Update fill:#4da6ff,stroke:#0066cc,color:white
style Diff fill:#ffa64d,stroke:#cc7a30,color:white
style Section fill:#4dbb5f,stroke:#36873f,color:white
style Partial fill:#d94dbb,stroke:#a3378a,color:white
style Full fill:#4dbbbb,stroke:#368787,color:white
```
## 💻 COMPLEXITY-BASED DOCUMENTATION
Documentation requirements scale based on complexity level:
| Documentation | Level 1 | Level 2 | Level 3 | Level 4 |
|---------------|---------|---------|---------|---------|
| Problem Definition | Brief | Standard | Detailed | Comprehensive |
| Options Analysis | Optional | Basic | Multiple Options | Extensive |
| Implementation Plan | Simple | Standard | Detailed | Phased |
| Testing Requirements | Basic | Standard | Comprehensive | Rigorous |
| Documentation | Minimal | Standard | Detailed | Extensive |
## 📑 OPTIMIZED TEMPLATES BY LEVEL
### Level 1: Quick Fix Template
```markdown
## QUICK FIX: [Issue Name]
- Problem: [Brief description]
- Solution: [Implemented approach]
- Verification: [How fix was tested]
```
### Level 2: Enhancement Template
```markdown
## ENHANCEMENT: [Feature Name]
- Requirement: [What needs to be done]
- Approach: [How it was implemented]
- Testing: [Verification approach]
- Documentation: [Where documented]
```
### Level 3-4: Comprehensive Template
Uses the optimized creative phase template with appropriate documentation depth
## 🔄 REFERENCE MAPS
Each mode's visual process map is optimized for token efficiency:
- @VAN Mode Map (Optimized)
- @PLAN Mode Map (Optimized)
- @CREATIVE Mode Map (Optimized)
- @BUILD Mode Map (Optimized)
- @REFLECT Mode Map (Optimized)
- @ARCHIVE Mode Map (Optimized)
## ⚡ TOKEN EFFICIENCY IMPROVEMENTS
Optimizations in this version:
1. Hierarchical rule loading (65% token reduction)
2. Progressive creative phase documentation (60% token reduction)
3. Context preservation during mode transitions (40% token reduction)
4. Differential Memory Bank updates (30% token reduction)
5. Complexity-based template scaling (varies by level)
## 💡 USAGE GUIDANCE
To use the optimized system:
1. Start with the VAN command to initialize and determine complexity
2. Follow the complexity-appropriate workflow
3. Use progressive documentation appropriate to task complexity
4. Let the system manage rule loading and context preservation
5. Enjoy the improved token efficiency while maintaining structured development
@@ -0,0 +1,272 @@
---
description: Visual process map for ARCHIVE mode (Task Documentation)
globs: "**/archive*/**", "**/document*/**", "**/complete*/**"
alwaysApply: false
---
# ARCHIVE MODE: TASK DOCUMENTATION PROCESS MAP
> **TL;DR:** This visual map guides the ARCHIVE mode process, focusing on creating comprehensive documentation of the completed task, archiving relevant files, and updating the Memory Bank for future reference.
## 🧭 ARCHIVE MODE PROCESS FLOW
```mermaid
graph TD
Start["START ARCHIVE MODE"] --> ReadTasks["Read tasks.md<br>reflection.md and<br>progress.md"]
%% Initial Assessment
ReadTasks --> VerifyReflect{"Reflection<br>Complete?"}
VerifyReflect -->|"No"| ReturnReflect["Return to<br>REFLECT Mode"]
VerifyReflect -->|"Yes"| AssessLevel{"Determine<br>Complexity Level"}
%% Level-Based Archiving
AssessLevel -->|"Level 1"| L1Archive["LEVEL 1 ARCHIVING"]
AssessLevel -->|"Level 2"| L2Archive["LEVEL 2 ARCHIVING<br>Level2/archive-basic.mdc"]
AssessLevel -->|"Level 3"| L3Archive["LEVEL 3 ARCHIVING<br>Level3/archive-intermediate.mdc"]
AssessLevel -->|"Level 4"| L4Archive["LEVEL 4 ARCHIVING<br>Level4/archive-comprehensive.mdc"]
%% Level 1 Archiving (Minimal)
L1Archive --> L1Summary["Create Quick<br>Summary"]
L1Summary --> L1Task["Update<br>tasks.md"]
L1Task --> L1Complete["Mark Task<br>Complete"]
%% Level 2 Archiving (Basic)
L2Archive --> L2Summary["Create Basic<br>Archive Document"]
L2Summary --> L2Doc["Document<br>Changes"]
L2Doc --> L2Task["Update<br>tasks.md"]
L2Task --> L2Progress["Update<br>progress.md"]
L2Progress --> L2Complete["Mark Task<br>Complete"]
%% Level 3-4 Archiving (Comprehensive)
L3Archive & L4Archive --> L34Summary["Create Comprehensive<br>Archive Document"]
L34Summary --> L34Doc["Document<br>Implementation"]
L34Doc --> L34Creative["Archive Creative<br>Phase Documents"]
L34Creative --> L34Code["Document Code<br>Changes"]
L34Code --> L34Test["Document<br>Testing"]
L34Test --> L34Lessons["Summarize<br>Lessons Learned"]
L34Lessons --> L34Task["Update<br>tasks.md"]
L34Task --> L34Progress["Update<br>progress.md"]
L34Progress --> L34System["Update System<br>Documentation"]
L34System --> L34Complete["Mark Task<br>Complete"]
%% Completion
L1Complete & L2Complete & L34Complete --> CreateArchive["Create Archive<br>Document in<br>docs/archive/"]
CreateArchive --> UpdateActive["Update<br>activeContext.md"]
UpdateActive --> Reset["Reset for<br>Next Task"]
```
## 📋 ARCHIVE DOCUMENT STRUCTURE
The archive document should follow this structured format:
```mermaid
graph TD
subgraph "Archive Document Structure"
Header["# TASK ARCHIVE: [Task Name]"]
Meta["## METADATA<br>Task info, dates, complexity"]
Summary["## SUMMARY<br>Brief overview of the task"]
Requirements["## REQUIREMENTS<br>What the task needed to accomplish"]
Implementation["## IMPLEMENTATION<br>How the task was implemented"]
Testing["## TESTING<br>How the solution was verified"]
Lessons["## LESSONS LEARNED<br>Key takeaways from the task"]
Refs["## REFERENCES<br>Links to related documents"]
end
Header --> Meta --> Summary --> Requirements --> Implementation --> Testing --> Lessons --> Refs
```
## 📊 REQUIRED FILE STATE VERIFICATION
Before archiving can begin, verify file state:
```mermaid
graph TD
Start["File State<br>Verification"] --> CheckTasks{"tasks.md has<br>reflection<br>complete?"}
CheckTasks -->|"No"| ErrorReflect["ERROR:<br>Return to REFLECT Mode"]
CheckTasks -->|"Yes"| CheckReflection{"reflection.md<br>exists?"}
CheckReflection -->|"No"| ErrorCreate["ERROR:<br>Create reflection.md first"]
CheckReflection -->|"Yes"| CheckProgress{"progress.md<br>updated?"}
CheckProgress -->|"No"| ErrorProgress["ERROR:<br>Update progress.md first"]
CheckProgress -->|"Yes"| ReadyArchive["Ready for<br>Archiving"]
```
## 🔍 ARCHIVE TYPES BY COMPLEXITY
```mermaid
graph TD
subgraph "Level 1: Minimal Archive"
L1A["Basic Bug<br>Description"]
L1B["Solution<br>Summary"]
L1C["Affected<br>Files"]
end
subgraph "Level 2: Basic Archive"
L2A["Enhancement<br>Description"]
L2B["Implementation<br>Summary"]
L2C["Testing<br>Results"]
L2D["Lessons<br>Learned"]
end
subgraph "Level 3-4: Comprehensive Archive"
L3A["Detailed<br>Requirements"]
L3B["Architecture/<br>Design Decisions"]
L3C["Implementation<br>Details"]
L3D["Testing<br>Strategy"]
L3E["Performance<br>Considerations"]
L3F["Future<br>Enhancements"]
L3G["Cross-References<br>to Other Systems"]
end
L1A --> L1B --> L1C
L2A --> L2B --> L2C --> L2D
L3A --> L3B --> L3C --> L3D --> L3E --> L3F --> L3G
```
## 📝 ARCHIVE DOCUMENT TEMPLATES
### Level 1 (Minimal) Archive
```
# Bug Fix Archive: [Bug Name]
## Date
[Date of fix]
## Summary
[Brief description of the bug and solution]
## Implementation
[Description of the fix implemented]
## Files Changed
- [File 1]
- [File 2]
```
### Levels 2-4 (Comprehensive) Archive
```
# Task Archive: [Task Name]
## Metadata
- **Complexity**: Level [2/3/4]
- **Type**: [Enhancement/Feature/System]
- **Date Completed**: [Date]
- **Related Tasks**: [Related task references]
## Summary
[Comprehensive summary of the task]
## Requirements
- [Requirement 1]
- [Requirement 2]
- [Requirement 3]
## Implementation
### Approach
[Description of implementation approach]
### Key Components
- [Component 1]: [Description]
- [Component 2]: [Description]
### Files Changed
- [File 1]: [Description of changes]
- [File 2]: [Description of changes]
## Testing
- [Test 1]: [Result]
- [Test 2]: [Result]
## Lessons Learned
- [Lesson 1]
- [Lesson 2]
- [Lesson 3]
## Future Considerations
- [Future enhancement 1]
- [Future enhancement 2]
## References
- [Link to reflection document]
- [Link to creative phase documents]
- [Other relevant references]
```
## 📋 ARCHIVE LOCATION AND NAMING
Archive documents should be organized following this pattern:
```mermaid
graph TD
subgraph "Archive Structure"
Root["docs/archive/"]
Tasks["tasks/"]
Features["features/"]
Systems["systems/"]
Root --> Tasks
Root --> Features
Root --> Systems
Tasks --> Bug["bug-fix-name-YYYYMMDD.md"]
Tasks --> Enhancement["enhancement-name-YYYYMMDD.md"]
Features --> Feature["feature-name-YYYYMMDD.md"]
Systems --> System["system-name-YYYYMMDD.md"]
end
```
## 📊 TASKS.MD FINAL UPDATE
When archiving is complete, update tasks.md with:
```
## Status
- [x] Initialization complete
- [x] Planning complete
[For Level 3-4:]
- [x] Creative phases complete
- [x] Implementation complete
- [x] Reflection complete
- [x] Archiving complete
## Archive
- **Date**: [Completion date]
- **Archive Document**: [Link to archive document]
- **Status**: COMPLETED
```
## 📋 ARCHIVE VERIFICATION CHECKLIST
```
✓ ARCHIVE VERIFICATION
- Reflection document reviewed? [YES/NO]
- Archive document created with all sections? [YES/NO]
- Archive document placed in correct location? [YES/NO]
- tasks.md marked as completed? [YES/NO]
- progress.md updated with archive reference? [YES/NO]
- activeContext.md updated for next task? [YES/NO]
- Creative phase documents archived (Level 3-4)? [YES/NO/NA]
→ If all YES: Archiving complete - Memory Bank reset for next task
→ If any NO: Complete missing archive elements
```
## 🔄 TASK COMPLETION NOTIFICATION
When archiving is complete, notify user with:
```
## TASK ARCHIVED
✅ Archive document created in docs/archive/
✅ All task documentation preserved
✅ Memory Bank updated with references
✅ Task marked as COMPLETED
→ Memory Bank is ready for the next task
→ To start a new task, use VAN MODE
```
@@ -0,0 +1,321 @@
---
description: Visual process map for BUILD mode (Code Implementation)
globs: implementation-mode-map.mdc
alwaysApply: false
---
# BUILD MODE: CODE EXECUTION PROCESS MAP
> **TL;DR:** This visual map guides the BUILD mode process, focusing on efficient code implementation based on the planning and creative phases, with proper command execution and progress tracking.
## 🧭 BUILD MODE PROCESS FLOW
```mermaid
graph TD
Start["START BUILD MODE"] --> ReadDocs["Read Reference Documents<br>Core/command-execution.md"]
%% Initialization
ReadDocs --> CheckLevel{"Determine<br>Complexity Level<br>from tasks.md"}
%% Level 1 Implementation
CheckLevel -->|"Level 1<br>Quick Bug Fix"| L1Process["LEVEL 1 PROCESS<br>Level1/quick-bug-workflow.md"]
L1Process --> L1Review["Review Bug<br>Report"]
L1Review --> L1Examine["Examine<br>Relevant Code"]
L1Examine --> L1Fix["Implement<br>Targeted Fix"]
L1Fix --> L1Test["Test<br>Fix"]
L1Test --> L1Update["Update<br>tasks.md"]
%% Level 2 Implementation
CheckLevel -->|"Level 2<br>Simple Enhancement"| L2Process["LEVEL 2 PROCESS<br>Level2/enhancement-workflow.md"]
L2Process --> L2Review["Review Build<br>Plan"]
L2Review --> L2Examine["Examine Relevant<br>Code Areas"]
L2Examine --> L2Implement["Implement Changes<br>Sequentially"]
L2Implement --> L2Test["Test<br>Changes"]
L2Test --> L2Update["Update<br>tasks.md"]
%% Level 3-4 Implementation
CheckLevel -->|"Level 3-4<br>Feature/System"| L34Process["LEVEL 3-4 PROCESS<br>Level3/feature-workflow.md<br>Level4/system-workflow.md"]
L34Process --> L34Review["Review Plan &<br>Creative Decisions"]
L34Review --> L34Phase{"Creative Phase<br>Documents<br>Complete?"}
L34Phase -->|"No"| L34Error["ERROR:<br>Return to CREATIVE Mode"]
L34Phase -->|"Yes"| L34DirSetup["Create Directory<br>Structure"]
L34DirSetup --> L34VerifyDirs["VERIFY Directories<br>Created Successfully"]
L34VerifyDirs --> L34Implementation["Build<br>Phase"]
%% Implementation Phases
L34Implementation --> L34Phase1["Phase 1<br>Build"]
L34Phase1 --> L34VerifyFiles["VERIFY Files<br>Created Successfully"]
L34VerifyFiles --> L34Test1["Test<br>Phase 1"]
L34Test1 --> L34Document1["Document<br>Phase 1"]
L34Document1 --> L34Next1{"Next<br>Phase?"}
L34Next1 -->|"Yes"| L34Implementation
L34Next1 -->|"No"| L34Integration["Integration<br>Testing"]
L34Integration --> L34Document["Document<br>Integration Points"]
L34Document --> L34Update["Update<br>tasks.md"]
%% Command Execution
L1Fix & L2Implement & L34Phase1 --> CommandExec["COMMAND EXECUTION<br>Core/command-execution.md"]
CommandExec --> DocCommands["Document Commands<br>& Results"]
%% Completion & Transition
L1Update & L2Update & L34Update --> VerifyComplete["Verify Build<br>Complete"]
VerifyComplete --> UpdateProgress["Update progress.md<br>with Status"]
UpdateProgress --> Transition["NEXT MODE:<br>REFLECT MODE"]
```
## 📋 REQUIRED FILE STATE VERIFICATION
Before implementation can begin, verify file state:
```mermaid
graph TD
Start["File State<br>Verification"] --> CheckTasks{"tasks.md has<br>planning complete?"}
CheckTasks -->|"No"| ErrorPlan["ERROR:<br>Return to PLAN Mode"]
CheckTasks -->|"Yes"| CheckLevel{"Task<br>Complexity?"}
CheckLevel -->|"Level 1"| L1Ready["Ready for<br>Implementation"]
CheckLevel -->|"Level 2"| L2Ready["Ready for<br>Implementation"]
CheckLevel -->|"Level 3-4"| CheckCreative{"Creative phases<br>required?"}
CheckCreative -->|"No"| L34Ready["Ready for<br>Implementation"]
CheckCreative -->|"Yes"| VerifyCreative{"Creative phases<br>completed?"}
VerifyCreative -->|"No"| ErrorCreative["ERROR:<br>Return to CREATIVE Mode"]
VerifyCreative -->|"Yes"| L34Ready
```
## 🔄 FILE SYSTEM VERIFICATION PROCESS
```mermaid
graph TD
Start["Start File<br>Verification"] --> CheckDir["Check Directory<br>Structure"]
CheckDir --> DirResult{"Directories<br>Exist?"}
DirResult -->|"No"| ErrorDir["❌ ERROR:<br>Missing Directories"]
DirResult -->|"Yes"| CheckFiles["Check Each<br>Created File"]
ErrorDir --> FixDir["Fix Directory<br>Structure"]
FixDir --> CheckDir
CheckFiles --> FileResult{"All Files<br>Exist?"}
FileResult -->|"No"| ErrorFile["❌ ERROR:<br>Missing/Wrong Path Files"]
FileResult -->|"Yes"| Complete["✅ Verification<br>Complete"]
ErrorFile --> FixFile["Fix File Paths<br>or Recreate Files"]
FixFile --> CheckFiles
```
## 📋 DIRECTORY VERIFICATION STEPS
Before beginning any file creation:
```
✓ DIRECTORY VERIFICATION PROCEDURE
1. Create all directories first before any files
2. Use ABSOLUTE paths: /full/path/to/directory
3. Verify each directory after creation:
ls -la /full/path/to/directory # Linux/Mac
dir "C:\full\path\to\directory" # Windows
4. Document directory structure in progress.md
5. Only proceed to file creation AFTER verifying ALL directories exist
```
## 📋 FILE CREATION VERIFICATION
After creating files:
```
✓ FILE VERIFICATION PROCEDURE
1. Use ABSOLUTE paths for all file operations: /full/path/to/file.ext
2. Verify each file creation was successful:
ls -la /full/path/to/file.ext # Linux/Mac
dir "C:\full\path\to\file.ext" # Windows
3. If verification fails:
a. Check for path resolution issues
b. Verify directory exists
c. Try creating with corrected path
d. Recheck file exists after correction
4. Document all file paths in progress.md
```
## 🔄 COMMAND EXECUTION WORKFLOW
```mermaid
graph TD
Start["Command<br>Execution"] --> Analyze["Analyze Command<br>Requirements"]
Analyze --> Complexity{"Command<br>Complexity?"}
Complexity -->|"Simple"| Simple["Execute<br>Single Command"]
Complexity -->|"Moderate"| Chain["Use Efficient<br>Command Chaining"]
Complexity -->|"Complex"| Break["Break Into<br>Logical Steps"]
Simple & Chain & Break --> Verify["Verify<br>Results"]
Verify --> Document["Document<br>Command & Result"]
Document --> Next["Next<br>Command"]
```
## 📋 LEVEL-SPECIFIC BUILD APPROACHES
```mermaid
graph TD
subgraph "Level 1: Quick Bug Fix"
L1A["Targeted Code<br>Examination"]
L1B["Minimal<br>Change Scope"]
L1C["Direct<br>Fix"]
L1D["Verify<br>Fix"]
end
subgraph "Level 2: Enhancement"
L2A["Sequential<br>Build"]
L2B["Contained<br>Changes"]
L2C["Standard<br>Testing"]
L2D["Component<br>Documentation"]
end
subgraph "Level 3-4: Feature/System"
L3A["Directory<br>Structure First"]
L3B["Verify Dirs<br>Before Files"]
L3C["Phased<br>Build"]
L3D["Verify Files<br>After Creation"]
L3E["Integration<br>Testing"]
L3F["Detailed<br>Documentation"]
end
L1A --> L1B --> L1C --> L1D
L2A --> L2B --> L2C --> L2D
L3A --> L3B --> L3C --> L3D --> L3E --> L3F
```
## 📝 BUILD DOCUMENTATION FORMAT
Document builds with:
```
## Build: [Component/Feature]
### Approach
[Brief description of build approach]
### Directory Structure
- [/absolute/path/to/dir1/]: [Purpose]
- [/absolute/path/to/dir2/]: [Purpose]
### Code Changes
- [/absolute/path/to/file1.ext]: [Description of changes]
- [/absolute/path/to/file2.ext]: [Description of changes]
### Verification Steps
- [✓] Directory structure created and verified
- [✓] All files created in correct locations
- [✓] File content verified
### Commands Executed
```
[Command 1]
[Result]
```
```
[Command 2]
[Result]
```
### Testing
- [Test 1]: [Result]
- [Test 2]: [Result]
### Status
- [x] Build complete
- [x] Testing performed
- [x] File verification completed
- [ ] Documentation updated
```
## 📊 TASKS.MD UPDATE FORMAT
During the build process, update tasks.md with progress:
```
## Status
- [x] Initialization complete
- [x] Planning complete
[For Level 3-4:]
- [x] Creative phases complete
- [x] Directory structure created and verified
- [x] [Built component 1]
- [x] [Built component 2]
- [ ] [Remaining component]
## Build Progress
- [Component 1]: Complete
- Files: [/absolute/path/to/files]
- [Details about implementation]
- [Component 2]: Complete
- Files: [/absolute/path/to/files]
- [Details about implementation]
- [Component 3]: In Progress
- [Current status]
```
## 📋 PROGRESS.MD UPDATE FORMAT
Update progress.md with:
```
# Build Progress
## Directory Structure
- [/absolute/path/to/dir1/]: Created and verified
- [/absolute/path/to/dir2/]: Created and verified
## [Date]: [Component/Feature] Built
- **Files Created**:
- [/absolute/path/to/file1.ext]: Verified
- [/absolute/path/to/file2.ext]: Verified
- **Key Changes**:
- [Change 1]
- [Change 2]
- **Testing**: [Test results]
- **Next Steps**: [What comes next]
```
## 📊 BUILD VERIFICATION CHECKLIST
```
✓ BUILD VERIFICATION
- Directory structure created correctly? [YES/NO]
- All files created in correct locations? [YES/NO]
- All file paths verified with absolute paths? [YES/NO]
- All planned changes implemented? [YES/NO]
- Testing performed for all changes? [YES/NO]
- Code follows project standards? [YES/NO]
- Edge cases handled appropriately? [YES/NO]
- Build documented with absolute paths? [YES/NO]
- tasks.md updated with progress? [YES/NO]
- progress.md updated with details? [YES/NO]
→ If all YES: Build complete - ready for REFLECT mode
→ If any NO: Complete missing build elements
```
## 🔄 MODE TRANSITION NOTIFICATION
When the build is complete, notify user with:
```
## BUILD COMPLETE
✅ Directory structure verified
✅ All files created in correct locations
✅ All planned changes implemented
✅ Testing performed successfully
✅ tasks.md updated with status
✅ progress.md updated with details
→ NEXT RECOMMENDED MODE: REFLECT MODE
```
@@ -0,0 +1,224 @@
---
description: Visual process map for CREATIVE mode (Design Decisions)
globs: "**/creative*/**", "**/design*/**", "**/decision*/**"
alwaysApply: false
---
# CREATIVE MODE: DESIGN PROCESS MAP
> **TL;DR:** This visual map guides the CREATIVE mode process, focusing on structured design decision-making for components that require deeper exploration before implementation.
## 🧭 CREATIVE MODE PROCESS FLOW
```mermaid
graph TD
Start["START CREATIVE MODE"] --> ReadTasks["Read tasks.md<br>For Creative Requirements"]
%% Initial Assessment
ReadTasks --> VerifyPlan{"Plan Complete<br>& Creative Phases<br>Identified?"}
VerifyPlan -->|"No"| ReturnPlan["Return to<br>PLAN Mode"]
VerifyPlan -->|"Yes"| IdentifyPhases["Identify Creative<br>Phases Required"]
%% Creative Phase Selection
IdentifyPhases --> SelectPhase["Select Next<br>Creative Phase"]
SelectPhase --> PhaseType{"Creative<br>Phase Type?"}
%% Creative Phase Types
PhaseType -->|"UI/UX<br>Design"| UIPhase["UI/UX CREATIVE PHASE<br>Core/creative-phase-uiux.md"]
PhaseType -->|"Architecture<br>Design"| ArchPhase["ARCHITECTURE CREATIVE PHASE<br>Core/creative-phase-architecture.md"]
PhaseType -->|"Data Model<br>Design"| DataPhase["DATA MODEL CREATIVE PHASE<br>Core/creative-phase-data.md"]
PhaseType -->|"Algorithm<br>Design"| AlgoPhase["ALGORITHM CREATIVE PHASE<br>Core/creative-phase-algorithm.md"]
%% UI/UX Creative Phase
UIPhase --> UI_Problem["Define UI/UX<br>Problem"]
UI_Problem --> UI_Research["Research UI<br>Patterns"]
UI_Research --> UI_Options["Explore UI<br>Options"]
UI_Options --> UI_Evaluate["Evaluate User<br>Experience"]
UI_Evaluate --> UI_Decision["Make Design<br>Decision"]
UI_Decision --> UI_Document["Document UI<br>Design"]
%% Architecture Creative Phase
ArchPhase --> Arch_Problem["Define Architecture<br>Challenge"]
Arch_Problem --> Arch_Options["Explore Architecture<br>Options"]
Arch_Options --> Arch_Analyze["Analyze Tradeoffs"]
Arch_Analyze --> Arch_Decision["Make Architecture<br>Decision"]
Arch_Decision --> Arch_Document["Document<br>Architecture"]
Arch_Document --> Arch_Diagram["Create Architecture<br>Diagram"]
%% Data Model Creative Phase
DataPhase --> Data_Requirements["Define Data<br>Requirements"]
Data_Requirements --> Data_Structure["Design Data<br>Structure"]
Data_Structure --> Data_Relations["Define<br>Relationships"]
Data_Relations --> Data_Validation["Design<br>Validation"]
Data_Validation --> Data_Document["Document<br>Data Model"]
%% Algorithm Creative Phase
AlgoPhase --> Algo_Problem["Define Algorithm<br>Problem"]
Algo_Problem --> Algo_Options["Explore Algorithm<br>Approaches"]
Algo_Options --> Algo_Evaluate["Evaluate Time/Space<br>Complexity"]
Algo_Evaluate --> Algo_Decision["Make Algorithm<br>Decision"]
Algo_Decision --> Algo_Document["Document<br>Algorithm"]
%% Documentation & Completion
UI_Document & Arch_Diagram & Data_Document & Algo_Document --> CreateDoc["Create Creative<br>Phase Document"]
CreateDoc --> UpdateTasks["Update tasks.md<br>with Decision"]
UpdateTasks --> MorePhases{"More Creative<br>Phases?"}
MorePhases -->|"Yes"| SelectPhase
MorePhases -->|"No"| VerifyComplete["Verify All<br>Phases Complete"]
VerifyComplete --> NotifyComplete["Signal Creative<br>Phases Complete"]
```
## 📋 CREATIVE PHASE DOCUMENT FORMAT
Each creative phase should produce a document with this structure:
```mermaid
graph TD
subgraph "Creative Phase Document"
Header["🎨 CREATIVE PHASE: [TYPE]"]
Problem["PROBLEM STATEMENT<br>Clear definition of the problem"]
Options["OPTIONS ANALYSIS<br>Multiple approaches considered"]
Pros["PROS & CONS<br>Tradeoffs for each option"]
Decision["DECISION<br>Selected approach + rationale"]
Impl["IMPLEMENTATION PLAN<br>Steps to implement the decision"]
Diagram["VISUALIZATION<br>Diagrams of the solution"]
end
Header --> Problem --> Options --> Pros --> Decision --> Impl --> Diagram
```
## 🔍 CREATIVE TYPES AND APPROACHES
```mermaid
graph TD
subgraph "UI/UX Design"
UI1["User Flow<br>Analysis"]
UI2["Component<br>Hierarchy"]
UI3["Interaction<br>Patterns"]
UI4["Visual Design<br>Principles"]
end
subgraph "Architecture Design"
A1["Component<br>Structure"]
A2["Data Flow<br>Patterns"]
A3["Interface<br>Design"]
A4["System<br>Integration"]
end
subgraph "Data Model Design"
D1["Entity<br>Relationships"]
D2["Schema<br>Design"]
D3["Validation<br>Rules"]
D4["Query<br>Optimization"]
end
subgraph "Algorithm Design"
AL1["Complexity<br>Analysis"]
AL2["Efficiency<br>Optimization"]
AL3["Edge Case<br>Handling"]
AL4["Scaling<br>Considerations"]
end
```
## 📊 REQUIRED FILE STATE VERIFICATION
Before creative phase work can begin, verify file state:
```mermaid
graph TD
Start["File State<br>Verification"] --> CheckTasks{"tasks.md has<br>planning complete?"}
CheckTasks -->|"No"| ErrorPlan["ERROR:<br>Return to PLAN Mode"]
CheckTasks -->|"Yes"| CheckCreative{"Creative phases<br>identified?"}
CheckCreative -->|"No"| ErrorCreative["ERROR:<br>Return to PLAN Mode"]
CheckCreative -->|"Yes"| ReadyCreative["Ready for<br>Creative Phase"]
```
## 📋 OPTIONS ANALYSIS TEMPLATE
For each creative phase, analyze multiple options:
```
## OPTIONS ANALYSIS
### Option 1: [Name]
**Description**: [Brief description]
**Pros**:
- [Pro 1]
- [Pro 2]
**Cons**:
- [Con 1]
- [Con 2]
**Complexity**: [Low/Medium/High]
**Implementation Time**: [Estimate]
### Option 2: [Name]
**Description**: [Brief description]
**Pros**:
- [Pro 1]
- [Pro 2]
**Cons**:
- [Con 1]
- [Con 2]
**Complexity**: [Low/Medium/High]
**Implementation Time**: [Estimate]
### Option 3: [Name]
**Description**: [Brief description]
**Pros**:
- [Pro 1]
- [Pro 2]
**Cons**:
- [Con 1]
- [Con 2]
**Complexity**: [Low/Medium/High]
**Implementation Time**: [Estimate]
```
## 🎨 CREATIVE PHASE MARKERS
Use these visual markers for creative phases:
```
🎨🎨🎨 ENTERING CREATIVE PHASE: [TYPE] 🎨🎨🎨
[Creative phase content]
🎨 CREATIVE CHECKPOINT: [Milestone]
[Additional content]
🎨🎨🎨 EXITING CREATIVE PHASE - DECISION MADE 🎨🎨🎨
```
## 📊 CREATIVE PHASE VERIFICATION CHECKLIST
```
✓ CREATIVE PHASE VERIFICATION
- Problem clearly defined? [YES/NO]
- Multiple options considered (3+)? [YES/NO]
- Pros/cons documented for each option? [YES/NO]
- Decision made with clear rationale? [YES/NO]
- Implementation plan included? [YES/NO]
- Visualization/diagrams created? [YES/NO]
- tasks.md updated with decision? [YES/NO]
→ If all YES: Creative phase complete
→ If any NO: Complete missing elements
```
## 🔄 MODE TRANSITION NOTIFICATION
When all creative phases are complete, notify user with:
```
## CREATIVE PHASES COMPLETE
✅ All required design decisions made
✅ Creative phase documents created
✅ tasks.md updated with decisions
✅ Implementation plan updated
→ NEXT RECOMMENDED MODE: BUILD MODE
```
@@ -0,0 +1,275 @@
---
description: Visual process map for PLAN mode (Code Implementation)
globs: plan-mode-map.mdc
alwaysApply: false
---
# PLAN MODE: TASK PLANNING PROCESS MAP
> **TL;DR:** This visual map guides the PLAN mode process, focusing on creating detailed implementation plans based on the complexity level determined during initialization, with mandatory technology validation before implementation.
## 🧭 PLAN MODE PROCESS FLOW
```mermaid
graph TD
Start["START PLANNING"] --> ReadTasks["Read tasks.md<br>Core/task-tracking.md"]
%% Complexity Level Determination
ReadTasks --> CheckLevel{"Determine<br>Complexity Level"}
CheckLevel -->|"Level 2"| Level2["LEVEL 2 PLANNING<br>Level2/enhancement-planning.md"]
CheckLevel -->|"Level 3"| Level3["LEVEL 3 PLANNING<br>Level3/feature-planning.md"]
CheckLevel -->|"Level 4"| Level4["LEVEL 4 PLANNING<br>Level4/system-planning.md"]
%% Level 2 Planning
Level2 --> L2Review["Review Code<br>Structure"]
L2Review --> L2Document["Document<br>Planned Changes"]
L2Document --> L2Challenges["Identify<br>Challenges"]
L2Challenges --> L2Checklist["Create Task<br>Checklist"]
L2Checklist --> L2Update["Update tasks.md<br>with Plan"]
L2Update --> L2Tech["TECHNOLOGY<br>VALIDATION"]
L2Tech --> L2Verify["Verify Plan<br>Completeness"]
%% Level 3 Planning
Level3 --> L3Review["Review Codebase<br>Structure"]
L3Review --> L3Requirements["Document Detailed<br>Requirements"]
L3Requirements --> L3Components["Identify Affected<br>Components"]
L3Components --> L3Plan["Create Comprehensive<br>Implementation Plan"]
L3Plan --> L3Challenges["Document Challenges<br>& Solutions"]
L3Challenges --> L3Update["Update tasks.md<br>with Plan"]
L3Update --> L3Tech["TECHNOLOGY<br>VALIDATION"]
L3Tech --> L3Flag["Flag Components<br>Requiring Creative"]
L3Flag --> L3Verify["Verify Plan<br>Completeness"]
%% Level 4 Planning
Level4 --> L4Analysis["Codebase Structure<br>Analysis"]
L4Analysis --> L4Requirements["Document Comprehensive<br>Requirements"]
L4Requirements --> L4Diagrams["Create Architectural<br>Diagrams"]
L4Diagrams --> L4Subsystems["Identify Affected<br>Subsystems"]
L4Subsystems --> L4Dependencies["Document Dependencies<br>& Integration Points"]
L4Dependencies --> L4Plan["Create Phased<br>Implementation Plan"]
L4Plan --> L4Update["Update tasks.md<br>with Plan"]
L4Update --> L4Tech["TECHNOLOGY<br>VALIDATION"]
L4Tech --> L4Flag["Flag Components<br>Requiring Creative"]
L4Flag --> L4Verify["Verify Plan<br>Completeness"]
%% Technology Validation Gate - NEW
L2Tech & L3Tech & L4Tech --> TechGate["⛔ TECHNOLOGY<br>VALIDATION GATE"]
TechGate --> TechSelection["Document Technology<br>Stack Selection"]
TechSelection --> TechHelloWorld["Create Hello World<br>Proof of Concept"]
TechHelloWorld --> TechDependencies["Verify Required<br>Dependencies"]
TechDependencies --> TechConfig["Validate Build<br>Configuration"]
TechConfig --> TechBuild["Complete Test<br>Build"]
TechBuild --> TechVerify["⛔ TECHNOLOGY<br>CHECKPOINT"]
%% Verification & Completion
L2Verify & L3Verify & L4Verify & TechVerify --> CheckCreative{"Creative<br>Phases<br>Required?"}
%% Mode Transition
CheckCreative -->|"Yes"| RecCreative["NEXT MODE:<br>CREATIVE MODE"]
CheckCreative -->|"No"| RecBuild["NEXT MODE:<br>BUILD MODE"]
%% Style for Technology Gate
style TechGate fill:#ff5555,stroke:#dd3333,color:white,stroke-width:3px
style TechVerify fill:#ff5555,stroke:#dd3333,color:white,stroke-width:3px
style TechSelection fill:#4da6ff,stroke:#0066cc,color:white
style TechHelloWorld fill:#4da6ff,stroke:#0066cc,color:white
style TechDependencies fill:#4da6ff,stroke:#0066cc,color:white
style TechConfig fill:#4da6ff,stroke:#0066cc,color:white
style TechBuild fill:#4da6ff,stroke:#0066cc,color:white
```
## 📋 LEVEL-SPECIFIC PLANNING APPROACHES
```mermaid
graph TD
subgraph "Level 2: Enhancement"
L2A["Basic Requirements<br>Analysis"]
L2B["Simple Component<br>Identification"]
L2C["Linear Implementation<br>Plan"]
L2D["Basic Checklist<br>Creation"]
end
subgraph "Level 3: Feature"
L3A["Detailed Requirements<br>Analysis"]
L3B["Component Mapping<br>with Dependencies"]
L3C["Multi-Phase<br>Implementation Plan"]
L3D["Comprehensive<br>Checklist"]
L3E["Creative Phase<br>Identification"]
end
subgraph "Level 4: System"
L4A["Architectural<br>Requirements Analysis"]
L4B["System Component<br>Mapping"]
L4C["Subsystem<br>Integration Plan"]
L4D["Phased Implementation<br>Strategy"]
L4E["Risk Assessment<br>& Mitigation"]
L4F["Multiple Creative<br>Phase Requirements"]
end
L2A --> L2B --> L2C --> L2D
L3A --> L3B --> L3C --> L3D --> L3E
L4A --> L4B --> L4C --> L4D --> L4E --> L4F
```
## 🔧 TECHNOLOGY VALIDATION WORKFLOW
```mermaid
graph TD
Start["Technology<br>Validation Start"] --> Select["Technology<br>Stack Selection"]
Select --> Document["Document Chosen<br>Technologies"]
Document --> POC["Create Minimal<br>Proof of Concept"]
POC --> Build["Verify Build<br>Process Works"]
Build --> Dependencies["Validate All<br>Dependencies"]
Dependencies --> Config["Confirm Configuration<br>Files Are Correct"]
Config --> Test["Complete Test<br>Build/Run"]
Test --> Success{"All Checks<br>Pass?"}
Success -->|"Yes"| Ready["Ready for<br>Implementation"]
Success -->|"No"| Fix["Fix Technology<br>Issues"]
Fix --> Document
style Start fill:#4da6ff,stroke:#0066cc,color:white
style POC fill:#4da6ff,stroke:#0066cc,color:white
style Success fill:#ff5555,stroke:#dd3333,color:white
style Fix fill:#ff5555,stroke:#dd3333,color:white
style Ready fill:#10b981,stroke:#059669,color:white
```
## 📊 REQUIRED FILE STATE VERIFICATION
Before planning can begin, verify the file state:
```mermaid
graph TD
Start["File State<br>Verification"] --> CheckTasks{"tasks.md<br>initialized?"}
CheckTasks -->|"No"| ErrorTasks["ERROR:<br>Return to VAN Mode"]
CheckTasks -->|"Yes"| CheckActive{"activeContext.md<br>exists?"}
CheckActive -->|"No"| ErrorActive["ERROR:<br>Return to VAN Mode"]
CheckActive -->|"Yes"| ReadyPlan["Ready for<br>Planning"]
```
## 📝 TASKS.MD UPDATE FORMAT
During planning, update tasks.md with this structure:
```
# Task: [Task name]
## Description
[Detailed description]
## Complexity
Level: [2/3/4]
Type: [Enhancement/Feature/Complex System]
## Technology Stack
- Framework: [Selected framework]
- Build Tool: [Selected build tool]
- Language: [Selected language]
- Storage: [Selected storage mechanism]
## Technology Validation Checkpoints
- [ ] Project initialization command verified
- [ ] Required dependencies identified and installed
- [ ] Build configuration validated
- [ ] Hello world verification completed
- [ ] Test build passes successfully
## Status
- [x] Initialization complete
- [x] Planning complete
- [ ] Technology validation complete
- [ ] [Implementation steps]
## Implementation Plan
1. [Step 1]
- [Subtask 1.1]
- [Subtask 1.2]
2. [Step 2]
- [Subtask 2.1]
- [Subtask 2.2]
## Creative Phases Required
- [ ] [Component 1] Design
- [ ] [Component 2] Architecture
- [ ] [Component 3] Data Model
## Dependencies
- [Dependency 1]
- [Dependency 2]
## Challenges & Mitigations
- [Challenge 1]: [Mitigation strategy]
- [Challenge 2]: [Mitigation strategy]
```
## 📋 CREATIVE PHASE IDENTIFICATION
For Level 3-4 tasks, identify components requiring creative phases:
```mermaid
graph TD
Start["Creative Phase<br>Identification"] --> CheckComp{"Component<br>Analysis"}
CheckComp --> UI["UI/UX<br>Components"]
CheckComp --> Data["Data Model<br>Components"]
CheckComp --> Arch["Architecture<br>Components"]
CheckComp --> Algo["Algorithm<br>Components"]
UI & Data & Arch & Algo --> Decision{"Design Decisions<br>Required?"}
Decision -->|"Yes"| Flag["Flag for<br>Creative Phase"]
Decision -->|"No"| Skip["Standard<br>Implementation"]
Flag --> Document["Document in<br>tasks.md"]
```
## 📊 TECHNOLOGY VALIDATION CHECKLIST
```
✓ TECHNOLOGY VALIDATION CHECKLIST
- Technology stack clearly defined? [YES/NO]
- Project initialization command documented? [YES/NO]
- Required dependencies identified? [YES/NO]
- Minimal proof of concept created? [YES/NO]
- Hello world build/run successful? [YES/NO]
- Configuration files validated? [YES/NO]
- Test build completes successfully? [YES/NO]
→ If all YES: Technology validation complete - ready for next phase
→ If any NO: Resolve technology issues before proceeding
```
## 📊 PLAN VERIFICATION CHECKLIST
```
✓ PLAN VERIFICATION CHECKLIST
- Requirements clearly documented? [YES/NO]
- Technology stack validated? [YES/NO]
- Affected components identified? [YES/NO]
- Implementation steps detailed? [YES/NO]
- Dependencies documented? [YES/NO]
- Challenges & mitigations addressed? [YES/NO]
- Creative phases identified (Level 3-4)? [YES/NO/NA]
- tasks.md updated with plan? [YES/NO]
→ If all YES: Planning complete - ready for next mode
→ If any NO: Complete missing plan elements
```
## 🔄 MODE TRANSITION NOTIFICATION
When planning is complete, notify user with:
```
## PLANNING COMPLETE
✅ Implementation plan created
✅ Technology stack validated
✅ tasks.md updated with plan
✅ Challenges and mitigations documented
[✅ Creative phases identified (for Level 3-4)]
→ NEXT RECOMMENDED MODE: [CREATIVE/BUILD] MODE
@@ -0,0 +1,495 @@
---
description: QA Mode
globs: qa-mode-map.mdc
alwaysApply: false
---
> **TL;DR:** This enhanced QA mode provides comprehensive validation at any stage of development. It automatically detects the current phase, validates Memory Bank consistency, verifies task tracking, and performs phase-specific technical validation to ensure project quality throughout the development lifecycle.
## 🔍 ENHANCED QA MODE PROCESS FLOW
```mermaid
graph TD
Start["🚀 START QA MODE"] --> DetectPhase["🧭 PHASE DETECTION<br>Determine current project phase"]
%% Phase detection decision path
DetectPhase --> PhaseDetermination{"Current Phase?"}
PhaseDetermination -->|"VAN"| VANChecks["VAN Phase Validation"]
PhaseDetermination -->|"PLAN"| PLANChecks["PLAN Phase Validation"]
PhaseDetermination -->|"CREATIVE"| CREATIVEChecks["CREATIVE Phase Validation"]
PhaseDetermination -->|"BUILD"| BUILDChecks["BUILD Phase Validation"]
%% Universal checks that apply to all phases
DetectPhase --> UniversalChecks["🔍 UNIVERSAL VALIDATION"]
UniversalChecks --> MemoryBankCheck["1️⃣ MEMORY BANK VERIFICATION<br>Check consistency & updates"]
MemoryBankCheck --> TaskTrackingCheck["2️⃣ TASK TRACKING VERIFICATION<br>Validate tasks.md as source of truth"]
TaskTrackingCheck --> ReferenceCheck["3️⃣ REFERENCE VALIDATION<br>Verify cross-references between docs"]
%% Phase-specific validations feed into comprehensive report
VANChecks & PLANChecks & CREATIVEChecks & BUILDChecks --> PhaseSpecificResults["Phase-Specific Results"]
ReferenceCheck & PhaseSpecificResults --> ValidationResults{"✅ All Checks<br>Passed?"}
%% Results Processing
ValidationResults -->|"Yes"| SuccessReport["📝 GENERATE SUCCESS REPORT<br>All validations passed"]
ValidationResults -->|"No"| FailureReport["⚠️ GENERATE FAILURE REPORT<br>With specific fix instructions"]
%% Success Path
SuccessReport --> UpdateMB["📚 Update Memory Bank<br>Record successful validation"]
UpdateMB --> ContinueProcess["🚦 CONTINUE: Phase processes<br>can proceed"]
%% Failure Path
FailureReport --> IdentifyFixes["🔧 IDENTIFY REQUIRED FIXES"]
IdentifyFixes --> ApplyFixes["🛠️ APPLY FIXES"]
ApplyFixes --> Revalidate["🔄 Re-run validation"]
Revalidate --> ValidationResults
%% Style nodes for clarity
style Start fill:#4da6ff,stroke:#0066cc,color:white
style DetectPhase fill:#f6ad55,stroke:#c27022,color:white
style UniversalChecks fill:#f6546a,stroke:#c30052,color:white
style MemoryBankCheck fill:#10b981,stroke:#059669,color:white
style TaskTrackingCheck fill:#10b981,stroke:#059669,color:white
style ReferenceCheck fill:#10b981,stroke:#059669,color:white
style ValidationResults fill:#f6546a,stroke:#c30052,color:white
style SuccessReport fill:#10b981,stroke:#059669,color:white
style FailureReport fill:#f6ad55,stroke:#c27022,color:white
style ContinueProcess fill:#10b981,stroke:#059669,color:white,stroke-width:2px
style IdentifyFixes fill:#f6ad55,stroke:#c27022,color:white
```
## 🧭 PHASE DETECTION PROCESS
The enhanced QA mode first determines which phase the project is currently in:
```mermaid
graph TD
PD["Phase Detection"] --> CheckMB["Analyze Memory Bank Files"]
CheckMB --> CheckActive["Check activeContext.md<br>for current phase"]
CheckActive --> CheckProgress["Check progress.md<br>for recent activities"]
CheckProgress --> CheckTasks["Check tasks.md<br>for task status"]
CheckTasks --> PhaseResult{"Determine<br>Current Phase"}
PhaseResult -->|"VAN"| VAN["VAN Phase<br>Initialization"]
PhaseResult -->|"PLAN"| PLAN["PLAN Phase<br>Task Planning"]
PhaseResult -->|"CREATIVE"| CREATIVE["CREATIVE Phase<br>Design Decisions"]
PhaseResult -->|"BUILD"| BUILD["BUILD Phase<br>Implementation"]
VAN & PLAN & CREATIVE & BUILD --> LoadChecks["Load Phase-Specific<br>Validation Checks"]
style PD fill:#4da6ff,stroke:#0066cc,color:white
style PhaseResult fill:#f6546a,stroke:#c30052,color:white
style LoadChecks fill:#10b981,stroke:#059669,color:white
```
## 📝 UNIVERSAL MEMORY BANK VERIFICATION
This process ensures Memory Bank files are consistent and up-to-date regardless of phase:
```mermaid
graph TD
MBVS["Memory Bank<br>Verification"] --> CoreCheck["Check Core Files Exist"]
CoreCheck --> CoreFiles["Verify Required Files:<br>projectbrief.md<br>activeContext.md<br>tasks.md<br>progress.md"]
CoreFiles --> ContentCheck["Verify Content<br>Consistency"]
ContentCheck --> LastModified["Check Last Modified<br>Timestamps"]
LastModified --> CrossRef["Validate Cross-<br>References"]
CrossRef --> ConsistencyCheck{"All Files<br>Consistent?"}
ConsistencyCheck -->|"Yes"| PassMB["✅ Memory Bank<br>Verification Passed"]
ConsistencyCheck -->|"No"| FailMB["❌ Memory Bank<br>Inconsistencies Found"]
FailMB --> FixSuggestions["Generate Fix<br>Suggestions"]
style MBVS fill:#4da6ff,stroke:#0066cc,color:white
style ConsistencyCheck fill:#f6546a,stroke:#c30052,color:white
style PassMB fill:#10b981,stroke:#059669,color:white
style FailMB fill:#ff5555,stroke:#dd3333,color:white
```
## 📋 TASK TRACKING VERIFICATION
This process validates tasks.md as the single source of truth:
```mermaid
graph TD
TTV["Task Tracking<br>Verification"] --> CheckTasksFile["Check tasks.md<br>Existence & Format"]
CheckTasksFile --> VerifyReferences["Verify Task References<br>in Other Documents"]
VerifyReferences --> ProgressCheck["Check Consistency with<br>progress.md"]
ProgressCheck --> StatusCheck["Verify Task Status<br>Accuracy"]
StatusCheck --> TaskConsistency{"Tasks Properly<br>Tracked?"}
TaskConsistency -->|"Yes"| PassTasks["✅ Task Tracking<br>Verification Passed"]
TaskConsistency -->|"No"| FailTasks["❌ Task Tracking<br>Issues Found"]
FailTasks --> TaskFixSuggestions["Generate Task Tracking<br>Fix Suggestions"]
style TTV fill:#4da6ff,stroke:#0066cc,color:white
style TaskConsistency fill:#f6546a,stroke:#c30052,color:white
style PassTasks fill:#10b981,stroke:#059669,color:white
style FailTasks fill:#ff5555,stroke:#dd3333,color:white
```
## 🔄 REFERENCE VALIDATION PROCESS
This process ensures proper cross-referencing between documents:
```mermaid
graph TD
RV["Reference<br>Validation"] --> FindRefs["Find Cross-References<br>in Documents"]
FindRefs --> VerifyRefs["Verify Reference<br>Accuracy"]
VerifyRefs --> CheckBackRefs["Check Bidirectional<br>References"]
CheckBackRefs --> RefConsistency{"References<br>Consistent?"}
RefConsistency -->|"Yes"| PassRefs["✅ Reference Validation<br>Passed"]
RefConsistency -->|"No"| FailRefs["❌ Reference<br>Issues Found"]
FailRefs --> RefFixSuggestions["Generate Reference<br>Fix Suggestions"]
style RV fill:#4da6ff,stroke:#0066cc,color:white
style RefConsistency fill:#f6546a,stroke:#c30052,color:white
style PassRefs fill:#10b981,stroke:#059669,color:white
style FailRefs fill:#ff5555,stroke:#dd3333,color:white
```
## 🚨 PHASE-SPECIFIC VALIDATION PROCESSES
### VAN Phase Validation
```mermaid
graph TD
VAN["VAN Phase<br>Validation"] --> InitCheck["Check Initialization<br>Completeness"]
InitCheck --> PlatformCheck["Verify Platform<br>Detection"]
PlatformCheck --> ComplexityCheck["Validate Complexity<br>Determination"]
ComplexityCheck --> VANConsistency{"VAN Phase<br>Complete?"}
VANConsistency -->|"Yes"| PassVAN["✅ VAN Phase<br>Validation Passed"]
VANConsistency -->|"No"| FailVAN["❌ VAN Phase<br>Issues Found"]
style VAN fill:#4da6ff,stroke:#0066cc,color:white
style VANConsistency fill:#f6546a,stroke:#c30052,color:white
style PassVAN fill:#10b981,stroke:#059669,color:white
style FailVAN fill:#ff5555,stroke:#dd3333,color:white
```
### PLAN Phase Validation
```mermaid
graph TD
PLAN["PLAN Phase<br>Validation"] --> PlanCheck["Check Planning<br>Documentation"]
PlanCheck --> TaskBreakdown["Verify Task<br>Breakdown"]
TaskBreakdown --> ScopeCheck["Validate Scope<br>Definition"]
ScopeCheck --> PLANConsistency{"PLAN Phase<br>Complete?"}
PLANConsistency -->|"Yes"| PassPLAN["✅ PLAN Phase<br>Validation Passed"]
PLANConsistency -->|"No"| FailPLAN["❌ PLAN Phase<br>Issues Found"]
style PLAN fill:#4da6ff,stroke:#0066cc,color:white
style PLANConsistency fill:#f6546a,stroke:#c30052,color:white
style PassPLAN fill:#10b981,stroke:#059669,color:white
style FailPLAN fill:#ff5555,stroke:#dd3333,color:white
```
### CREATIVE Phase Validation
```mermaid
graph TD
CREATIVE["CREATIVE Phase<br>Validation"] --> DesignCheck["Check Design<br>Documents"]
DesignCheck --> ArchCheck["Verify Architectural<br>Decisions"]
ArchCheck --> PatternCheck["Validate Design<br>Patterns"]
PatternCheck --> CREATIVEConsistency{"CREATIVE Phase<br>Complete?"}
CREATIVEConsistency -->|"Yes"| PassCREATIVE["✅ CREATIVE Phase<br>Validation Passed"]
CREATIVEConsistency -->|"No"| FailCREATIVE["❌ CREATIVE Phase<br>Issues Found"]
style CREATIVE fill:#4da6ff,stroke:#0066cc,color:white
style CREATIVEConsistency fill:#f6546a,stroke:#c30052,color:white
style PassCREATIVE fill:#10b981,stroke:#059669,color:white
style FailCREATIVE fill:#ff5555,stroke:#dd3333,color:white
```
### BUILD Phase Technical Validation
This retains the original QA validation from the previous version:
```mermaid
graph TD
BUILD["BUILD Phase<br>Validation"] --> ReadDesign["Read Design Decisions"]
ReadDesign --> FourChecks["Four-Point Technical<br>Validation"]
FourChecks --> DepCheck["1️⃣ Dependency<br>Verification"]
DepCheck --> ConfigCheck["2️⃣ Configuration<br>Validation"]
ConfigCheck --> EnvCheck["3️⃣ Environment<br>Validation"]
EnvCheck --> MinBuildCheck["4️⃣ Minimal Build<br>Test"]
MinBuildCheck --> BUILDConsistency{"Technical<br>Prerequisites Met?"}
BUILDConsistency -->|"Yes"| PassBUILD["✅ BUILD Phase<br>Validation Passed"]
BUILDConsistency -->|"No"| FailBUILD["❌ BUILD Phase<br>Issues Found"]
style BUILD fill:#4da6ff,stroke:#0066cc,color:white
style FourChecks fill:#f6546a,stroke:#c30052,color:white
style BUILDConsistency fill:#f6546a,stroke:#c30052,color:white
style PassBUILD fill:#10b981,stroke:#059669,color:white
style FailBUILD fill:#ff5555,stroke:#dd3333,color:white
```
## 📋 UNIVERSAL VALIDATION COMMAND EXECUTION
### Memory Bank Verification Commands:
```bash
# Check Memory Bank file existence and recency
ls -la memory-bank/
find memory-bank/ -type f -mtime -7 | sort
# Check for consistency between files
grep -r "task" memory-bank/
grep -r "requirement" memory-bank/
```
### Task Tracking Verification Commands:
```bash
# Verify tasks.md as source of truth
test -f tasks.md && echo "✅ tasks.md exists" || echo "❌ tasks.md missing"
# Check references to tasks in other files
grep -r "Task" --include="*.md" .
grep -r "task" --include="*.md" . | grep -v "tasks.md" | wc -l
# Verify task status consistency
grep -i "completed\|done\|finished" tasks.md
grep -i "in progress\|started" tasks.md
```
### Reference Validation Commands:
```bash
# Find cross-references between files
grep -r "see\|refer\|reference" --include="*.md" .
# Check for broken references
for file in $(grep -l "see\|refer\|reference" --include="*.md" .); do
for ref in $(grep -o '[a-zA-Z0-9_-]*\.md' $file); do
test -f $ref || echo "❌ Broken reference: $ref in $file"
done
done
```
## 📋 1️⃣ DEPENDENCY VERIFICATION PROCESS (Original)
This validation point ensures all required packages are correctly installed.
### Command Execution:
```bash
# Check if packages are installed
npm list react react-dom tailwindcss postcss autoprefixer
# Verify package versions match requirements
npm list | grep -E "react|tailwind|postcss"
# Check for peer dependency warnings
npm ls --depth=0
```
### Validation Criteria:
- All required packages must be installed
- Versions must be compatible with requirements
- No critical peer dependency warnings
- Required dev dependencies must be present
### Common Fixes:
- `npm install [missing-package]` - Install missing packages
- `npm install [package]@[version]` - Fix version mismatches
- `npm install --save-dev [dev-dependency]` - Add development dependencies
## 📝 2️⃣ CONFIGURATION VALIDATION PROCESS (Original)
This validation point ensures configuration files are in the correct format for the project.
### Command Execution:
```bash
# Check package.json for module type
grep "\"type\":" package.json
# Verify configuration file extensions match module type
find . -name "*.config.*" | grep -E "\.(js|cjs|mjs)$"
# Test configuration syntax
node -c *.config.js || node -c *.config.cjs || node -c *.config.mjs
```
### Validation Criteria:
- Configuration file extensions must match module type in package.json
- File syntax must be valid
- Configuration must reference installed packages
### Common Fixes:
- Rename `.js` to `.cjs` for CommonJS in ES module projects
- Fix syntax errors in configuration files
- Adjust configuration to reference installed packages
## 🌐 3️⃣ ENVIRONMENT VALIDATION PROCESS (Original)
This validation point ensures the development environment is correctly set up.
### Command Execution:
```bash
# Check build tools
npm run --help
# Verify node version compatibility
node -v
# Check for environment variables
printenv | grep -E "NODE_|PATH|HOME"
# Verify access permissions
ls -la .
```
### Validation Criteria:
- Node.js version must be compatible with requirements
- Build commands must be defined in package.json
- Environment must have necessary access permissions
- Required environment variables must be set
### Common Fixes:
- Update Node.js version
- Add missing scripts to package.json
- Fix file permissions with chmod/icacls
- Set required environment variables
## 🔥 4️⃣ MINIMAL BUILD TEST PROCESS (Original)
This validation point tests a minimal build to ensure basic functionality works.
### Command Execution:
```bash
# Run a minimal build
npm run build -- --dry-run || npm run dev -- --dry-run
# Test entry point file existence
find src -name "main.*" -o -name "index.*"
# Validate HTML entry point
grep -i "script.*src=" index.html
```
### Validation Criteria:
- Build process must complete without errors
- Entry point files must exist and be correctly referenced
- HTML must reference the correct JavaScript entry point
- Basic rendering must work in a test environment
### Common Fixes:
- Fix entry point references in HTML
- Correct import paths in JavaScript
- Fix build configuration errors
- Update incorrect paths or references
## 📊 ENHANCED COMPREHENSIVE QA REPORT FORMAT
```
╔═════════════════════════ 🔍 ENHANCED QA VALIDATION REPORT ═════════════════════╗
│ │
│ Project: [Project Name] Date: [Current Date] │
│ Platform: [OS Platform] Detected Phase: [Current Phase] │
│ │
│ ━━━━━━━━━━━━━━━━━━━━━━━━ UNIVERSAL VALIDATION RESULTS ━━━━━━━━━━━━━━━━━━━━━━━ │
│ │
│ 1️⃣ MEMORY BANK VERIFICATION │
│ ✓ Core Files: [Status] │
│ ✓ Content Consistency: [Status] │
│ ✓ Last Modified: [Status] │
│ │
│ 2️⃣ TASK TRACKING VERIFICATION │
│ ✓ tasks.md Status: [Status] │
│ ✓ Task References: [Status] │
│ ✓ Status Consistency: [Status] │
│ │
│ 3️⃣ REFERENCE VALIDATION │
│ ✓ Cross-References: [Status] │
│ ✓ Reference Accuracy: [Status] │
│ │
│ ━━━━━━━━━━━━━━━━━━━━━━━ PHASE-SPECIFIC VALIDATION ━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
│ │
│ [VAN/PLAN/CREATIVE/BUILD] PHASE VALIDATION │
│ ✓ [Phase-specific check 1]: [Status] │
│ ✓ [Phase-specific check 2]: [Status] │
│ ✓ [Phase-specific check 3]: [Status] │
│ │
│ [Technical validation section shown only for BUILD phase] │
│ │
│ ━━━━━━━━━━━━━━━━━━━━━━━━━━━ OVERALL STATUS ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
│ │
│ ✅ VALIDATION PASSED - Project quality verified for current phase │
│ │
╚═══════════════════════════════════════════════════════════════════════════════╝
```
## 🚫 ENHANCED FAILURE REPORT FORMAT
If validation fails, a detailed failure report is generated:
```
╔═════════════════════════ ⚠️ QA VALIDATION FAILURES ═════════════════════════════╗
│ │
│ Project: [Project Name] Date: [Current Date] │
│ Platform: [OS Platform] Detected Phase: [Current Phase] │
│ │
│ ━━━━━━━━━━━━━━━━━━━━━━━━━━ FAILED CHECKS ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
│ │
│ ❌ MEMORY BANK ISSUES │
│ • [Specific issue details] │
│ • [Specific issue details] │
│ │
│ ❌ TASK TRACKING ISSUES │
│ • [Specific issue details] │
│ • [Specific issue details] │
│ │
│ ❌ REFERENCE ISSUES │
│ • [Specific issue details] │
│ • [Specific issue details] │
│ │
│ ❌ [PHASE]-SPECIFIC ISSUES │
│ • [Specific issue details] │
│ • [Specific issue details] │
│ │
│ ━━━━━━━━━━━━━━━━━━━━━━━━━━━ REQUIRED FIXES ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
│ │
│ 1. [Specific fix instruction with command] │
│ 2. [Specific fix instruction with command] │
│ 3. [Specific fix instruction with command] │
│ │
│ ⚠️ VALIDATION FAILED - Please resolve issues before proceeding │
│ │
╚═════════════════════════════════════════════════════════════════════════════════╝
```
## 🔄 QA-ANYTIME ACTIVATION PROTOCOL
The enhanced QA mode can be activated at any time in the development process:
```mermaid
graph TD
Start["User Types: QA"] --> DetectContext["Detect Current Context"]
DetectContext --> RunQA["Run QA with Context-Aware Checks"]
RunQA --> GenerateReport["Generate Appropriate QA Report"]
GenerateReport --> UserResponse["Present Report to User"]
UserResponse --> FixNeeded{"Fixes<br>Needed?"}
FixNeeded -->|"Yes"| SuggestFixes["Display Fix Instructions"]
FixNeeded -->|"No"| ContinueWork["Continue Current Phase Work"]
style Start fill:#4da6ff,stroke:#0066cc,color:white
style FixNeeded fill:#f6546a,stroke:#c30052,color:white
style SuggestFixes fill:#ff5555,stroke:#dd3333,color:white
style ContinueWork fill:#10b981,stroke:#059669,color:white
```
This enhanced QA mode serves as a "quality guardian" throughout the development process, ensuring documentation is consistently maintained and all phase requirements are met before proceeding to the next phase.
@@ -0,0 +1,229 @@
---
description: Visual process map for REFLECT mode (Task Reflection)
globs: "**/reflect*/**", "**/review*/**", "**/retrospect*/**"
alwaysApply: false
---
# REFLECT MODE: TASK REVIEW PROCESS MAP
> **TL;DR:** This visual map guides the REFLECT mode process, focusing on structured review of the implementation, documenting lessons learned, and preparing insights for future reference.
## 🧭 REFLECT MODE PROCESS FLOW
```mermaid
graph TD
Start["START REFLECT MODE"] --> ReadTasks["Read tasks.md<br>and progress.md"]
%% Initial Assessment
ReadTasks --> VerifyImplement{"Implementation<br>Complete?"}
VerifyImplement -->|"No"| ReturnBuild["Return to<br>BUILD Mode"]
VerifyImplement -->|"Yes"| AssessLevel{"Determine<br>Complexity Level"}
%% Level-Based Reflection
AssessLevel -->|"Level 1"| L1Reflect["LEVEL 1 REFLECTION<br>Level1/reflection-basic.md"]
AssessLevel -->|"Level 2"| L2Reflect["LEVEL 2 REFLECTION<br>Level2/reflection-standard.md"]
AssessLevel -->|"Level 3"| L3Reflect["LEVEL 3 REFLECTION<br>Level3/reflection-comprehensive.md"]
AssessLevel -->|"Level 4"| L4Reflect["LEVEL 4 REFLECTION<br>Level4/reflection-advanced.md"]
%% Level 1 Reflection (Quick)
L1Reflect --> L1Review["Review<br>Bug Fix"]
L1Review --> L1Document["Document<br>Solution"]
L1Document --> L1Update["Update<br>tasks.md"]
%% Level 2 Reflection (Standard)
L2Reflect --> L2Review["Review<br>Enhancement"]
L2Review --> L2WWW["Document<br>What Went Well"]
L2WWW --> L2Challenges["Document<br>Challenges"]
L2Challenges --> L2Lessons["Document<br>Lessons Learned"]
L2Lessons --> L2Update["Update<br>tasks.md"]
%% Level 3-4 Reflection (Comprehensive)
L3Reflect & L4Reflect --> L34Review["Review Implementation<br>& Creative Phases"]
L34Review --> L34Plan["Compare Against<br>Original Plan"]
L34Plan --> L34WWW["Document<br>What Went Well"]
L34WWW --> L34Challenges["Document<br>Challenges"]
L34Challenges --> L34Lessons["Document<br>Lessons Learned"]
L34Lessons --> L34ImproveProcess["Document Process<br>Improvements"]
L34ImproveProcess --> L34Update["Update<br>tasks.md"]
%% Completion & Transition
L1Update & L2Update & L34Update --> CreateReflection["Create<br>reflection.md"]
CreateReflection --> UpdateSystem["Update System<br>Documentation"]
UpdateSystem --> Transition["NEXT MODE:<br>ARCHIVE MODE"]
```
## 📋 REFLECTION STRUCTURE
The reflection should follow this structured format:
```mermaid
graph TD
subgraph "Reflection Document Structure"
Header["# TASK REFLECTION: [Task Name]"]
Summary["## SUMMARY<br>Brief summary of completed task"]
WWW["## WHAT WENT WELL<br>Successful aspects of implementation"]
Challenges["## CHALLENGES<br>Difficulties encountered during implementation"]
Lessons["## LESSONS LEARNED<br>Key insights gained from the experience"]
ProcessImp["## PROCESS IMPROVEMENTS<br>How to improve for future tasks"]
TechImp["## TECHNICAL IMPROVEMENTS<br>Better approaches for similar tasks"]
NextSteps["## NEXT STEPS<br>Follow-up actions or future work"]
end
Header --> Summary --> WWW --> Challenges --> Lessons --> ProcessImp --> TechImp --> NextSteps
```
## 📊 REQUIRED FILE STATE VERIFICATION
Before reflection can begin, verify file state:
```mermaid
graph TD
Start["File State<br>Verification"] --> CheckTasks{"tasks.md has<br>implementation<br>complete?"}
CheckTasks -->|"No"| ErrorBuild["ERROR:<br>Return to BUILD Mode"]
CheckTasks -->|"Yes"| CheckProgress{"progress.md<br>has implementation<br>details?"}
CheckProgress -->|"No"| ErrorProgress["ERROR:<br>Update progress.md first"]
CheckProgress -->|"Yes"| ReadyReflect["Ready for<br>Reflection"]
```
## 🔍 IMPLEMENTATION REVIEW APPROACH
```mermaid
graph TD
subgraph "Implementation Review"
Original["Review Original<br>Requirements"]
Plan["Compare Against<br>Implementation Plan"]
Actual["Assess Actual<br>Implementation"]
Creative["Review Creative<br>Phase Decisions"]
Changes["Identify Deviations<br>from Plan"]
Results["Evaluate<br>Results"]
end
Original --> Plan --> Actual
Plan --> Creative --> Changes
Actual --> Results
Changes --> Results
```
## 📝 REFLECTION DOCUMENT TEMPLATES
### Level 1 (Basic) Reflection
```
# Bug Fix Reflection: [Bug Name]
## Summary
[Brief description of the bug and solution]
## Implementation
[Description of the fix implemented]
## Testing
[Description of testing performed]
## Additional Notes
[Any other relevant information]
```
### Levels 2-4 (Comprehensive) Reflection
```
# Task Reflection: [Task Name]
## Summary
[Brief summary of the task and what was achieved]
## What Went Well
- [Success point 1]
- [Success point 2]
- [Success point 3]
## Challenges
- [Challenge 1]: [How it was addressed]
- [Challenge 2]: [How it was addressed]
- [Challenge 3]: [How it was addressed]
## Lessons Learned
- [Lesson 1]
- [Lesson 2]
- [Lesson 3]
## Process Improvements
- [Process improvement 1]
- [Process improvement 2]
## Technical Improvements
- [Technical improvement 1]
- [Technical improvement 2]
## Next Steps
- [Follow-up task 1]
- [Follow-up task 2]
```
## 📊 REFLECTION QUALITY METRICS
```mermaid
graph TD
subgraph "Reflection Quality Metrics"
Specific["Specific<br>Not general or vague"]
Actionable["Actionable<br>Provides clear direction"]
Honest["Honest<br>Acknowledges successes and failures"]
Forward["Forward-Looking<br>Focuses on future improvement"]
Evidence["Evidence-Based<br>Based on concrete examples"]
end
```
## 📋 TASKS.MD UPDATE FORMAT
During reflection, update tasks.md with:
```
## Status
- [x] Initialization complete
- [x] Planning complete
[For Level 3-4:]
- [x] Creative phases complete
- [x] Implementation complete
- [x] Reflection complete
- [ ] Archiving
## Reflection Highlights
- **What Went Well**: [Key successes]
- **Challenges**: [Key challenges]
- **Lessons Learned**: [Key lessons]
- **Next Steps**: [Follow-up actions]
```
## 📊 REFLECTION VERIFICATION CHECKLIST
```
✓ REFLECTION VERIFICATION
- Implementation thoroughly reviewed? [YES/NO]
- What Went Well section completed? [YES/NO]
- Challenges section completed? [YES/NO]
- Lessons Learned section completed? [YES/NO]
- Process Improvements identified? [YES/NO]
- Technical Improvements identified? [YES/NO]
- Next Steps documented? [YES/NO]
- reflection.md created? [YES/NO]
- tasks.md updated with reflection status? [YES/NO]
→ If all YES: Reflection complete - ready for ARCHIVE mode
→ If any NO: Complete missing reflection elements
```
## 🔄 MODE TRANSITION NOTIFICATION
When reflection is complete, notify user with:
```
## REFLECTION COMPLETE
✅ Implementation thoroughly reviewed
✅ Reflection document created
✅ Lessons learned documented
✅ Process improvements identified
✅ tasks.md updated with reflection status
→ NEXT RECOMMENDED MODE: ARCHIVE MODE
```
@@ -0,0 +1,902 @@
---
description: Visual process map for VAN mode (Initialization)
globs: van-mode-map.mdc
alwaysApply: false
---
# VAN MODE: INITIALIZATION PROCESS MAP
> **TL;DR:** This visual map defines the VAN mode process for project initialization, task analysis, and technical validation. It guides users through platform detection, file verification, complexity determination, and technical validation to ensure proper setup before implementation.
## 🧭 VAN MODE PROCESS FLOW
```mermaid
graph TD
Start["START VAN MODE"] --> PlatformDetect["PLATFORM DETECTION"]
PlatformDetect --> DetectOS["Detect Operating System"]
DetectOS --> CheckPath["Check Path Separator Format"]
CheckPath --> AdaptCmds["Adapt Commands if Needed"]
AdaptCmds --> PlatformCP["⛔ PLATFORM CHECKPOINT"]
%% Basic File Verification with checkpoint
PlatformCP --> BasicFileVerify["BASIC FILE VERIFICATION"]
BasicFileVerify --> BatchCheck["Batch Check Essential Components"]
BatchCheck --> BatchCreate["Batch Create Essential Structure"]
BatchCreate --> BasicFileCP["⛔ BASIC FILE CHECKPOINT"]
%% Early Complexity Determination
BasicFileCP --> EarlyComplexity["EARLY COMPLEXITY DETERMINATION"]
EarlyComplexity --> AnalyzeTask["Analyze Task Requirements"]
AnalyzeTask --> EarlyLevelCheck{"Complexity Level?"}
%% Level handling paths
EarlyLevelCheck -->|"Level 1"| ComplexityCP["⛔ COMPLEXITY CHECKPOINT"]
EarlyLevelCheck -->|"Level 2-4"| CRITICALGATE["🚫 CRITICAL GATE: FORCE MODE SWITCH"]
CRITICALGATE --> ForceExit["Exit to PLAN mode"]
%% Level 1 continues normally
ComplexityCP --> InitSystem["INITIALIZE MEMORY BANK"]
InitSystem --> Complete1["LEVEL 1 INITIALIZATION COMPLETE"]
%% For Level 2+ tasks after PLAN and CREATIVE modes
ForceExit -.-> OtherModes["PLAN → CREATIVE modes"]
OtherModes -.-> VANQA["VAN QA MODE"]
VANQA --> QAProcess["Technical Validation Process"]
QAProcess --> QACheck{"All Checks Pass?"}
QACheck -->|"Yes"| BUILD["To BUILD MODE"]
QACheck -->|"No"| FixIssues["Fix Technical Issues"]
FixIssues --> QAProcess
%% Style nodes
style PlatformCP fill:#f55,stroke:#d44,color:white
style BasicFileCP fill:#f55,stroke:#d44,color:white
style ComplexityCP fill:#f55,stroke:#d44,color:white
style CRITICALGATE fill:#ff0000,stroke:#990000,color:white,stroke-width:3px
style ForceExit fill:#ff0000,stroke:#990000,color:white,stroke-width:2px
style VANQA fill:#4da6ff,stroke:#0066cc,color:white,stroke-width:3px
style QAProcess fill:#4da6ff,stroke:#0066cc,color:white
style QACheck fill:#4da6ff,stroke:#0066cc,color:white
style FixIssues fill:#ff5555,stroke:#dd3333,color:white
```
## 🌐 PLATFORM DETECTION PROCESS
```mermaid
graph TD
PD["Platform Detection"] --> CheckOS["Detect Operating System"]
CheckOS --> Win["Windows"]
CheckOS --> Mac["macOS"]
CheckOS --> Lin["Linux"]
Win & Mac & Lin --> Adapt["Adapt Commands<br>for Platform"]
Win --> WinPath["Path: Backslash (\\)"]
Mac --> MacPath["Path: Forward Slash (/)"]
Lin --> LinPath["Path: Forward Slash (/)"]
Win --> WinCmd["Command Adaptations:<br>dir, icacls, etc."]
Mac --> MacCmd["Command Adaptations:<br>ls, chmod, etc."]
Lin --> LinCmd["Command Adaptations:<br>ls, chmod, etc."]
WinPath & MacPath & LinPath --> PathCP["Path Separator<br>Checkpoint"]
WinCmd & MacCmd & LinCmd --> CmdCP["Command<br>Checkpoint"]
PathCP & CmdCP --> PlatformComplete["Platform Detection<br>Complete"]
style PD fill:#4da6ff,stroke:#0066cc,color:white
style PlatformComplete fill:#10b981,stroke:#059669,color:white
```
## 📁 FILE VERIFICATION PROCESS
```mermaid
graph TD
FV["File Verification"] --> CheckFiles["Check Essential Files"]
CheckFiles --> CheckMB["Check Memory Bank<br>Structure"]
CheckMB --> MBExists{"Memory Bank<br>Exists?"}
MBExists -->|"Yes"| VerifyMB["Verify Memory Bank<br>Contents"]
MBExists -->|"No"| CreateMB["Create Memory Bank<br>Structure"]
CheckFiles --> CheckDocs["Check Documentation<br>Files"]
CheckDocs --> DocsExist{"Docs<br>Exist?"}
DocsExist -->|"Yes"| VerifyDocs["Verify Documentation<br>Structure"]
DocsExist -->|"No"| CreateDocs["Create Documentation<br>Structure"]
VerifyMB & CreateMB --> MBCP["Memory Bank<br>Checkpoint"]
VerifyDocs & CreateDocs --> DocsCP["Documentation<br>Checkpoint"]
MBCP & DocsCP --> FileComplete["File Verification<br>Complete"]
style FV fill:#4da6ff,stroke:#0066cc,color:white
style FileComplete fill:#10b981,stroke:#059669,color:white
style MBCP fill:#f6546a,stroke:#c30052,color:white
style DocsCP fill:#f6546a,stroke:#c30052,color:white
```
## 🧩 COMPLEXITY DETERMINATION PROCESS
```mermaid
graph TD
CD["Complexity<br>Determination"] --> AnalyzeTask["Analyze Task<br>Requirements"]
AnalyzeTask --> CheckKeywords["Check Task<br>Keywords"]
CheckKeywords --> ScopeCheck["Assess<br>Scope Impact"]
ScopeCheck --> RiskCheck["Evaluate<br>Risk Level"]
RiskCheck --> EffortCheck["Estimate<br>Implementation Effort"]
EffortCheck --> DetermineLevel{"Determine<br>Complexity Level"}
DetermineLevel -->|"Level 1"| L1["Level 1:<br>Quick Bug Fix"]
DetermineLevel -->|"Level 2"| L2["Level 2:<br>Simple Enhancement"]
DetermineLevel -->|"Level 3"| L3["Level 3:<br>Intermediate Feature"]
DetermineLevel -->|"Level 4"| L4["Level 4:<br>Complex System"]
L1 --> CDComplete["Complexity Determination<br>Complete"]
L2 & L3 & L4 --> ModeSwitch["Force Mode Switch<br>to PLAN"]
style CD fill:#4da6ff,stroke:#0066cc,color:white
style CDComplete fill:#10b981,stroke:#059669,color:white
style ModeSwitch fill:#ff0000,stroke:#990000,color:white
style DetermineLevel fill:#f6546a,stroke:#c30052,color:white
```
## 🔄 COMPLETE WORKFLOW WITH QA VALIDATION
The full workflow includes technical validation before implementation:
```mermaid
flowchart LR
VAN1["VAN MODE
(Initial Analysis)"] --> PLAN["PLAN MODE
(Task Planning)"]
PLAN --> CREATIVE["CREATIVE MODE
(Design Decisions)"]
CREATIVE --> VANQA["VAN QA MODE
(Technical Validation)"]
VANQA --> BUILD["BUILD MODE
(Implementation)"]
```
## 🔍 TECHNICAL VALIDATION OVERVIEW
The VAN QA technical validation process consists of four key validation points:
```mermaid
graph TD
VANQA["VAN QA MODE"] --> FourChecks["FOUR-POINT VALIDATION"]
FourChecks --> DepCheck["1️⃣ DEPENDENCY VERIFICATION<br>Check all required packages"]
DepCheck --> ConfigCheck["2️⃣ CONFIGURATION VALIDATION<br>Verify format & compatibility"]
ConfigCheck --> EnvCheck["3️⃣ ENVIRONMENT VALIDATION<br>Check build environment"]
EnvCheck --> MinBuildCheck["4️⃣ MINIMAL BUILD TEST<br>Test core functionality"]
MinBuildCheck --> ValidationResults{"All Checks<br>Passed?"}
ValidationResults -->|"Yes"| SuccessReport["GENERATE SUCCESS REPORT"]
ValidationResults -->|"No"| FailureReport["GENERATE FAILURE REPORT"]
SuccessReport --> BUILD["Proceed to BUILD MODE"]
FailureReport --> FixIssues["Fix Technical Issues"]
FixIssues --> ReValidate["Re-validate"]
ReValidate --> ValidationResults
style VANQA fill:#4da6ff,stroke:#0066cc,color:white
style FourChecks fill:#f6546a,stroke:#c30052,color:white
style ValidationResults fill:#f6546a,stroke:#c30052,color:white
style BUILD fill:#10b981,stroke:#059669,color:white
style FixIssues fill:#ff5555,stroke:#dd3333,color:white
```
## 📝 VALIDATION STATUS FORMAT
The QA Validation step includes clear status indicators:
```
╔═════════════════ 🔍 QA VALIDATION STATUS ═════════════════╗
│ ✓ Design Decisions │ Verified as implementable │
│ ✓ Dependencies │ All required packages installed │
│ ✓ Configurations │ Format verified for platform │
│ ✓ Environment │ Suitable for implementation │
╚════════════════════════════════════════════════════════════╝
✅ VERIFIED - Clear to proceed to BUILD mode
```
## 🚨 MODE TRANSITION TRIGGERS
### VAN to PLAN Transition
For complexity levels 2-4:
```
🚫 LEVEL [2-4] TASK DETECTED
Implementation in VAN mode is BLOCKED
This task REQUIRES PLAN mode
You MUST switch to PLAN mode for proper documentation and planning
Type 'PLAN' to switch to planning mode
```
### CREATIVE to VAN QA Transition
After completing the CREATIVE mode:
```
⏭️ NEXT MODE: VAN QA
To validate technical requirements before implementation, please type 'VAN QA'
```
### VAN QA to BUILD Transition
After successful validation:
```
✅ TECHNICAL VALIDATION COMPLETE
All prerequisites verified successfully
You may now proceed to BUILD mode
Type 'BUILD' to begin implementation
```
## 🔒 BUILD MODE PREVENTION MECHANISM
The system prevents moving to BUILD mode without passing QA validation:
```mermaid
graph TD
Start["User Types: BUILD"] --> CheckQA{"QA Validation<br>Completed?"}
CheckQA -->|"Yes and Passed"| AllowBuild["Allow BUILD Mode"]
CheckQA -->|"No or Failed"| BlockBuild["BLOCK BUILD MODE"]
BlockBuild --> Message["Display:<br>⚠️ QA VALIDATION REQUIRED"]
Message --> ReturnToVANQA["Prompt: Type VAN QA"]
style CheckQA fill:#f6546a,stroke:#c30052,color:white
style BlockBuild fill:#ff0000,stroke:#990000,color:white,stroke-width:3px
style Message fill:#ff5555,stroke:#dd3333,color:white
style ReturnToVANQA fill:#4da6ff,stroke:#0066cc,color:white
```
## 🔄 QA COMMAND PRECEDENCE
QA validation can be called at any point in the process flow, and takes immediate precedence over any other current steps, including forced mode switches:
```mermaid
graph TD
UserQA["User Types: QA"] --> HighPriority["⚠️ HIGH PRIORITY COMMAND"]
HighPriority --> CurrentTask["Pause Current Task/Process"]
CurrentTask --> LoadQA["Load QA Mode Map"]
LoadQA --> RunQA["Execute QA Validation Process"]
RunQA --> QAResults{"QA Results"}
QAResults -->|"PASS"| ResumeFlow["Resume Prior Process Flow"]
QAResults -->|"FAIL"| FixIssues["Fix Identified Issues"]
FixIssues --> ReRunQA["Re-run QA Validation"]
ReRunQA --> QAResults
style UserQA fill:#f8d486,stroke:#e8b84d,color:black
style HighPriority fill:#ff0000,stroke:#cc0000,color:white,stroke-width:3px
style LoadQA fill:#4da6ff,stroke:#0066cc,color:white
style RunQA fill:#4da6ff,stroke:#0066cc,color:white
style QAResults fill:#f6546a,stroke:#c30052,color:white
```
### QA Interruption Rules
When a user types **QA** at any point:
1. **The QA command MUST take immediate precedence** over any current operation, including the "FORCE MODE SWITCH" triggered by complexity assessment.
2. The system MUST:
- Immediately load the QA mode map
- Execute the full QA validation process
- Address any failures before continuing
3. **Required remediation steps take priority** over any pending mode switches or complexity rules
4. After QA validation is complete and passes:
- Resume the previously determined process flow
- Continue with any required mode switches
```
⚠️ QA OVERRIDE ACTIVATED
All other processes paused
QA validation checks now running...
Any issues found MUST be remediated before continuing with normal process flow
```
## 📋 CHECKPOINT VERIFICATION TEMPLATE
Each major checkpoint in VAN mode uses this format:
```
✓ SECTION CHECKPOINT: [SECTION NAME]
- Requirement 1? [YES/NO]
- Requirement 2? [YES/NO]
- Requirement 3? [YES/NO]
→ If all YES: Ready for next section
→ If any NO: Fix missing items before proceeding
```
## 🚀 VAN MODE ACTIVATION
When the user types "VAN", respond with a confirmation and start the process:
```
User: VAN
Response: OK VAN - Beginning Initialization Process
```
After completing CREATIVE mode, when the user types "VAN QA", respond:
```
User: VAN QA
Response: OK VAN QA - Beginning Technical Validation
```
This ensures clear communication about which phase of VAN mode is active.
## 🔍 DETAILED QA VALIDATION PROCESS
### 1️⃣ DEPENDENCY VERIFICATION
This step verifies that all required packages are installed and compatible:
```mermaid
graph TD
Start["Dependency Verification"] --> ReadDeps["Read Required Dependencies<br>from Creative Phase"]
ReadDeps --> CheckInstalled["Check if Dependencies<br>are Installed"]
CheckInstalled --> DepStatus{"All Dependencies<br>Installed?"}
DepStatus -->|"Yes"| VerifyVersions["Verify Versions<br>and Compatibility"]
DepStatus -->|"No"| InstallMissing["Install Missing<br>Dependencies"]
InstallMissing --> VerifyVersions
VerifyVersions --> VersionStatus{"Versions<br>Compatible?"}
VersionStatus -->|"Yes"| DepSuccess["Dependencies Verified<br>✅ PASS"]
VersionStatus -->|"No"| UpgradeVersions["Upgrade/Downgrade<br>as Needed"]
UpgradeVersions --> RetryVerify["Retry Verification"]
RetryVerify --> VersionStatus
style Start fill:#4da6ff,stroke:#0066cc,color:white
style DepSuccess fill:#10b981,stroke:#059669,color:white
style DepStatus fill:#f6546a,stroke:#c30052,color:white
style VersionStatus fill:#f6546a,stroke:#c30052,color:white
```
#### Windows (PowerShell) Implementation:
```powershell
# Example: Verify Node.js dependencies for a React project
function Verify-Dependencies {
$requiredDeps = @{
"node" = ">=14.0.0"
"npm" = ">=6.0.0"
}
$missingDeps = @()
$incompatibleDeps = @()
# Check Node.js version
$nodeVersion = $null
try {
$nodeVersion = node -v
if ($nodeVersion -match "v(\d+)\.(\d+)\.(\d+)") {
$major = [int]$Matches[1]
if ($major -lt 14) {
$incompatibleDeps += "node (found $nodeVersion, required >=14.0.0)"
}
}
} catch {
$missingDeps += "node"
}
# Check npm version
$npmVersion = $null
try {
$npmVersion = npm -v
if ($npmVersion -match "(\d+)\.(\d+)\.(\d+)") {
$major = [int]$Matches[1]
if ($major -lt 6) {
$incompatibleDeps += "npm (found $npmVersion, required >=6.0.0)"
}
}
} catch {
$missingDeps += "npm"
}
# Display results
if ($missingDeps.Count -eq 0 -and $incompatibleDeps.Count -eq 0) {
Write-Output "✅ All dependencies verified and compatible"
return $true
} else {
if ($missingDeps.Count -gt 0) {
Write-Output "❌ Missing dependencies: $($missingDeps -join ', ')"
}
if ($incompatibleDeps.Count -gt 0) {
Write-Output "❌ Incompatible versions: $($incompatibleDeps -join ', ')"
}
return $false
}
}
```
#### Mac/Linux (Bash) Implementation:
```bash
#!/bin/bash
# Example: Verify Node.js dependencies for a React project
verify_dependencies() {
local missing_deps=()
local incompatible_deps=()
# Check Node.js version
if command -v node &> /dev/null; then
local node_version=$(node -v)
if [[ $node_version =~ v([0-9]+)\.([0-9]+)\.([0-9]+) ]]; then
local major=${BASH_REMATCH[1]}
if (( major < 14 )); then
incompatible_deps+=("node (found $node_version, required >=14.0.0)")
fi
fi
else
missing_deps+=("node")
fi
# Check npm version
if command -v npm &> /dev/null; then
local npm_version=$(npm -v)
if [[ $npm_version =~ ([0-9]+)\.([0-9]+)\.([0-9]+) ]]; then
local major=${BASH_REMATCH[1]}
if (( major < 6 )); then
incompatible_deps+=("npm (found $npm_version, required >=6.0.0)")
fi
fi
else
missing_deps+=("npm")
fi
# Display results
if [ ${#missing_deps[@]} -eq 0 ] && [ ${#incompatible_deps[@]} -eq 0 ]; then
echo "✅ All dependencies verified and compatible"
return 0
else
if [ ${#missing_deps[@]} -gt 0 ]; then
echo "❌ Missing dependencies: ${missing_deps[*]}"
fi
if [ ${#incompatible_deps[@]} -gt 0 ]; then
echo "❌ Incompatible versions: ${incompatible_deps[*]}"
fi
return 1
fi
}
```
### 2️⃣ CONFIGURATION VALIDATION
This step validates configuration files format and compatibility:
```mermaid
graph TD
Start["Configuration Validation"] --> IdentifyConfigs["Identify Configuration<br>Files"]
IdentifyConfigs --> ReadConfigs["Read Configuration<br>Files"]
ReadConfigs --> ValidateSyntax["Validate Syntax<br>and Format"]
ValidateSyntax --> SyntaxStatus{"Syntax<br>Valid?"}
SyntaxStatus -->|"Yes"| CheckCompatibility["Check Compatibility<br>with Platform"]
SyntaxStatus -->|"No"| FixSyntax["Fix Syntax<br>Errors"]
FixSyntax --> RetryValidate["Retry Validation"]
RetryValidate --> SyntaxStatus
CheckCompatibility --> CompatStatus{"Compatible with<br>Platform?"}
CompatStatus -->|"Yes"| ConfigSuccess["Configurations Validated<br>✅ PASS"]
CompatStatus -->|"No"| AdaptConfigs["Adapt Configurations<br>for Platform"]
AdaptConfigs --> RetryCompat["Retry Compatibility<br>Check"]
RetryCompat --> CompatStatus
style Start fill:#4da6ff,stroke:#0066cc,color:white
style ConfigSuccess fill:#10b981,stroke:#059669,color:white
style SyntaxStatus fill:#f6546a,stroke:#c30052,color:white
style CompatStatus fill:#f6546a,stroke:#c30052,color:white
```
#### Configuration Validation Implementation:
```powershell
# Example: Validate configuration files for a web project
function Validate-Configurations {
$configFiles = @(
"package.json",
"tsconfig.json",
"vite.config.js"
)
$invalidConfigs = @()
$incompatibleConfigs = @()
foreach ($configFile in $configFiles) {
if (Test-Path $configFile) {
# Check JSON syntax for JSON files
if ($configFile -match "\.json$") {
try {
Get-Content $configFile -Raw | ConvertFrom-Json | Out-Null
} catch {
$invalidConfigs += "$configFile (JSON syntax error: $($_.Exception.Message))"
continue
}
}
# Specific configuration compatibility checks
if ($configFile -eq "vite.config.js") {
$content = Get-Content $configFile -Raw
# Check for React plugin in Vite config
if ($content -notmatch "react\(\)") {
$incompatibleConfigs += "$configFile (Missing React plugin for React project)"
}
}
} else {
$invalidConfigs += "$configFile (file not found)"
}
}
# Display results
if ($invalidConfigs.Count -eq 0 -and $incompatibleConfigs.Count -eq 0) {
Write-Output "✅ All configurations validated and compatible"
return $true
} else {
if ($invalidConfigs.Count -gt 0) {
Write-Output "❌ Invalid configurations: $($invalidConfigs -join ', ')"
}
if ($incompatibleConfigs.Count -gt 0) {
Write-Output "❌ Incompatible configurations: $($incompatibleConfigs -join ', ')"
}
return $false
}
}
```
### 3️⃣ ENVIRONMENT VALIDATION
This step checks if the environment is properly set up for the implementation:
```mermaid
graph TD
Start["Environment Validation"] --> CheckEnv["Check Build Environment"]
CheckEnv --> VerifyBuildTools["Verify Build Tools"]
VerifyBuildTools --> ToolsStatus{"Build Tools<br>Available?"}
ToolsStatus -->|"Yes"| CheckPerms["Check Permissions<br>and Access"]
ToolsStatus -->|"No"| InstallTools["Install Required<br>Build Tools"]
InstallTools --> RetryTools["Retry Verification"]
RetryTools --> ToolsStatus
CheckPerms --> PermsStatus{"Permissions<br>Sufficient?"}
PermsStatus -->|"Yes"| EnvSuccess["Environment Validated<br>✅ PASS"]
PermsStatus -->|"No"| FixPerms["Fix Permission<br>Issues"]
FixPerms --> RetryPerms["Retry Permission<br>Check"]
RetryPerms --> PermsStatus
style Start fill:#4da6ff,stroke:#0066cc,color:white
style EnvSuccess fill:#10b981,stroke:#059669,color:white
style ToolsStatus fill:#f6546a,stroke:#c30052,color:white
style PermsStatus fill:#f6546a,stroke:#c30052,color:white
```
#### Environment Validation Implementation:
```powershell
# Example: Validate environment for a web project
function Validate-Environment {
$requiredTools = @(
@{Name = "git"; Command = "git --version"},
@{Name = "node"; Command = "node --version"},
@{Name = "npm"; Command = "npm --version"}
)
$missingTools = @()
$permissionIssues = @()
# Check build tools
foreach ($tool in $requiredTools) {
try {
Invoke-Expression $tool.Command | Out-Null
} catch {
$missingTools += $tool.Name
}
}
# Check write permissions in project directory
try {
$testFile = ".__permission_test"
New-Item -Path $testFile -ItemType File -Force | Out-Null
Remove-Item -Path $testFile -Force
} catch {
$permissionIssues += "Current directory (write permission denied)"
}
# Check if port 3000 is available (commonly used for dev servers)
try {
$listener = New-Object System.Net.Sockets.TcpListener([System.Net.IPAddress]::Loopback, 3000)
$listener.Start()
$listener.Stop()
} catch {
$permissionIssues += "Port 3000 (already in use or access denied)"
}
# Display results
if ($missingTools.Count -eq 0 -and $permissionIssues.Count -eq 0) {
Write-Output "✅ Environment validated successfully"
return $true
} else {
if ($missingTools.Count -gt 0) {
Write-Output "❌ Missing tools: $($missingTools -join ', ')"
}
if ($permissionIssues.Count -gt 0) {
Write-Output "❌ Permission issues: $($permissionIssues -join ', ')"
}
return $false
}
}
```
### 4️⃣ MINIMAL BUILD TEST
This step performs a minimal build test to ensure core functionality:
```mermaid
graph TD
Start["Minimal Build Test"] --> CreateTest["Create Minimal<br>Test Project"]
CreateTest --> BuildTest["Attempt<br>Build"]
BuildTest --> BuildStatus{"Build<br>Successful?"}
BuildStatus -->|"Yes"| RunTest["Run Basic<br>Functionality Test"]
BuildStatus -->|"No"| FixBuild["Fix Build<br>Issues"]
FixBuild --> RetryBuild["Retry Build"]
RetryBuild --> BuildStatus
RunTest --> TestStatus{"Test<br>Passed?"}
TestStatus -->|"Yes"| TestSuccess["Minimal Build Test<br>✅ PASS"]
TestStatus -->|"No"| FixTest["Fix Test<br>Issues"]
FixTest --> RetryTest["Retry Test"]
RetryTest --> TestStatus
style Start fill:#4da6ff,stroke:#0066cc,color:white
style TestSuccess fill:#10b981,stroke:#059669,color:white
style BuildStatus fill:#f6546a,stroke:#c30052,color:white
style TestStatus fill:#f6546a,stroke:#c30052,color:white
```
#### Minimal Build Test Implementation:
```powershell
# Example: Perform minimal build test for a React project
function Perform-MinimalBuildTest {
$buildSuccess = $false
$testSuccess = $false
# Create minimal test project
$testDir = ".__build_test"
if (Test-Path $testDir) {
Remove-Item -Path $testDir -Recurse -Force
}
try {
# Create minimal test directory
New-Item -Path $testDir -ItemType Directory | Out-Null
Push-Location $testDir
# Initialize minimal package.json
@"
{
"name": "build-test",
"version": "1.0.0",
"description": "Minimal build test",
"main": "index.js",
"scripts": {
"build": "echo Build test successful"
}
}
"@ | Set-Content -Path "package.json"
# Attempt build
npm run build | Out-Null
$buildSuccess = $true
# Create minimal test file
@"
console.log('Test successful');
"@ | Set-Content -Path "index.js"
# Run basic test
node index.js | Out-Null
$testSuccess = $true
} catch {
Write-Output "❌ Build test failed: $($_.Exception.Message)"
} finally {
Pop-Location
if (Test-Path $testDir) {
Remove-Item -Path $testDir -Recurse -Force
}
}
# Display results
if ($buildSuccess -and $testSuccess) {
Write-Output "✅ Minimal build test passed successfully"
return $true
} else {
if (-not $buildSuccess) {
Write-Output "❌ Build process failed"
}
if (-not $testSuccess) {
Write-Output "❌ Basic functionality test failed"
}
return $false
}
}
```
## 📋 COMPREHENSIVE QA REPORT FORMAT
After running all validation steps, a comprehensive report is generated:
```
╔═════════════════════ 🔍 QA VALIDATION REPORT ══════════════════════╗
│ │
│ PROJECT: [Project Name] │
│ TIMESTAMP: [Current Date/Time] │
│ │
│ 1️⃣ DEPENDENCY VERIFICATION │
│ ✓ Required: [List of required dependencies] │
│ ✓ Installed: [List of installed dependencies] │
│ ✓ Compatible: [Yes/No] │
│ │
│ 2️⃣ CONFIGURATION VALIDATION │
│ ✓ Config Files: [List of configuration files] │
│ ✓ Syntax Valid: [Yes/No] │
│ ✓ Platform Compatible: [Yes/No] │
│ │
│ 3️⃣ ENVIRONMENT VALIDATION │
│ ✓ Build Tools: [Available/Missing] │
│ ✓ Permissions: [Sufficient/Insufficient] │
│ ✓ Environment Ready: [Yes/No] │
│ │
│ 4️⃣ MINIMAL BUILD TEST │
│ ✓ Build Process: [Successful/Failed] │
│ ✓ Functionality Test: [Passed/Failed] │
│ ✓ Build Ready: [Yes/No] │
│ │
│ 🚨 FINAL VERDICT: [PASS/FAIL] │
│ ➡️ [Success message or error details] │
╚═════════════════════════════════════════════════════════════════════╝
```
## ❌ FAILURE REPORT FORMAT
If any validation step fails, a detailed failure report is generated:
```
⚠️⚠️⚠️ QA VALIDATION FAILED ⚠️⚠️⚠️
The following issues must be resolved before proceeding to BUILD mode:
1️⃣ DEPENDENCY ISSUES:
- [Detailed description of dependency issues]
- [Recommended fix]
2️⃣ CONFIGURATION ISSUES:
- [Detailed description of configuration issues]
- [Recommended fix]
3️⃣ ENVIRONMENT ISSUES:
- [Detailed description of environment issues]
- [Recommended fix]
4️⃣ BUILD TEST ISSUES:
- [Detailed description of build test issues]
- [Recommended fix]
⚠️ BUILD MODE IS BLOCKED until these issues are resolved.
Type 'VAN QA' after fixing the issues to re-validate.
```
## 🔄 INTEGRATION WITH DESIGN DECISIONS
The VAN QA mode reads and validates design decisions from the CREATIVE phase:
```mermaid
graph TD
Start["Read Design Decisions"] --> ReadCreative["Parse Creative Phase<br>Documentation"]
ReadCreative --> ExtractTech["Extract Technology<br>Choices"]
ExtractTech --> ExtractDeps["Extract Required<br>Dependencies"]
ExtractDeps --> BuildValidationPlan["Build Validation<br>Plan"]
BuildValidationPlan --> StartValidation["Start Four-Point<br>Validation Process"]
style Start fill:#4da6ff,stroke:#0066cc,color:white
style ExtractTech fill:#f6546a,stroke:#c30052,color:white
style BuildValidationPlan fill:#10b981,stroke:#059669,color:white
style StartValidation fill:#f6546a,stroke:#c30052,color:white
```
### Technology Extraction Process:
```powershell
# Example: Extract technology choices from creative phase documentation
function Extract-TechnologyChoices {
$techChoices = @{}
# Read from systemPatterns.md
if (Test-Path "memory-bank\systemPatterns.md") {
$content = Get-Content "memory-bank\systemPatterns.md" -Raw
# Extract framework choice
if ($content -match "Framework:\s*(\w+)") {
$techChoices["framework"] = $Matches[1]
}
# Extract UI library choice
if ($content -match "UI Library:\s*(\w+)") {
$techChoices["ui_library"] = $Matches[1]
}
# Extract state management choice
if ($content -match "State Management:\s*([^\\n]+)") {
$techChoices["state_management"] = $Matches[1].Trim()
}
}
return $techChoices
}
```
## 🚨 IMPLEMENTATION PREVENTION MECHANISM
If QA validation fails, the system prevents moving to BUILD mode:
```powershell
# Example: Enforce QA validation before allowing BUILD mode
function Check-QAValidationStatus {
$qaStatusFile = "memory-bank\.qa_validation_status"
if (Test-Path $qaStatusFile) {
$status = Get-Content $qaStatusFile -Raw
if ($status -match "PASS") {
return $true
}
}
# Display block message
Write-Output "`n`n"
Write-Output "🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫"
Write-Output "⛔️ BUILD MODE BLOCKED: QA VALIDATION REQUIRED"
Write-Output "⛔️ You must complete QA validation before proceeding to BUILD mode"
Write-Output "`n"
Write-Output "Type 'VAN QA' to perform technical validation"
Write-Output "`n"
Write-Output "🚫 NO IMPLEMENTATION CAN PROCEED WITHOUT VALIDATION 🚫"
Write-Output "🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫"
return $false
}
```
## 🧪 COMMON QA VALIDATION FIXES
Here are common fixes for issues encountered during QA validation:
### Dependency Issues:
- **Missing Node.js**: Install Node.js from https://nodejs.org/
- **Outdated npm**: Run `npm install -g npm@latest` to update
- **Missing packages**: Run `npm install` or `npm install [package-name]`
### Configuration Issues:
- **Invalid JSON**: Use a JSON validator to check syntax
- **Missing React plugin**: Add `import react from '@vitejs/plugin-react'` and `plugins: [react()]` to vite.config.js
- **Incompatible TypeScript config**: Update `tsconfig.json` with correct React settings
### Environment Issues:
- **Permission denied**: Run terminal as administrator (Windows) or use sudo (Mac/Linux)
- **Port already in use**: Kill process using the port or change the port in configuration
- **Missing build tools**: Install required command-line tools
### Build Test Issues:
- **Build fails**: Check console for specific error messages
- **Test fails**: Verify minimal configuration is correct
- **Path issues**: Ensure paths use correct separators for the platform
## 🔒 FINAL QA VALIDATION CHECKPOINT
```
✓ SECTION CHECKPOINT: QA VALIDATION
- Dependency Verification Passed? [YES/NO]
- Configuration Validation Passed? [YES/NO]
- Environment Validation Passed? [YES/NO]
- Minimal Build Test Passed? [YES/NO]
→ If all YES: Ready for BUILD mode
→ If any NO: Fix identified issues before proceeding
```
@@ -0,0 +1,142 @@
---
description: Visual process map for VAN mode complexity determination
globs: van-complexity-determination.mdc
alwaysApply: false
---
# VAN MODE: COMPLEXITY DETERMINATION
> **TL;DR:** This component determines the appropriate complexity level (1-4) for the current task and directs the workflow accordingly.
## 🔍 COMPLEXITY DECISION TREE
```mermaid
graph TD
Start["New Task"] --> Q1{"Bug fix or<br>error correction?"}
Q1 -->|Yes| Q1a{"Affects single<br>component?"}
Q1a -->|Yes| L1["Level 1:<br>Quick Bug Fix"]
Q1a -->|No| Q1b{"Affects multiple<br>components?"}
Q1b -->|Yes| L2["Level 2:<br>Simple Enhancement"]
Q1b -->|No| Q1c{"Affects system<br>architecture?"}
Q1c -->|Yes| L3["Level 3:<br>Intermediate Feature"]
Q1c -->|No| L2
Q1 -->|No| Q2{"Adding small<br>feature or<br>enhancement?"}
Q2 -->|Yes| Q2a{"Self-contained<br>change?"}
Q2a -->|Yes| L2
Q2a -->|No| Q2b{"Affects multiple<br>components?"}
Q2b -->|Yes| L3
Q2b -->|No| L2
Q2 -->|No| Q3{"Complete feature<br>requiring multiple<br>components?"}
Q3 -->|Yes| Q3a{"Architectural<br>implications?"}
Q3a -->|Yes| L4["Level 4:<br>Complex System"]
Q3a -->|No| L3
Q3 -->|No| Q4{"System-wide or<br>architectural<br>change?"}
Q4 -->|Yes| L4
Q4 -->|No| L3
style Start fill:#4da6ff,stroke:#0066cc,color:white
style L1 fill:#10b981,stroke:#059669,color:white
style L2 fill:#f6546a,stroke:#c30052,color:white
style L3 fill:#f6546a,stroke:#c30052,color:white
style L4 fill:#f6546a,stroke:#c30052,color:white
```
## 📋 LEVEL INDICATORS
### Level 1: Quick Bug Fix
- **Keywords**: fix, bug, error, crash, issue
- **Scope**: Single component
- **Time**: Minutes to hours
- **Risk**: Low, isolated
- **Example**: Button not working, styling issue
### Level 2: Simple Enhancement
- **Keywords**: add, improve, update, enhance
- **Scope**: Single component/subsystem
- **Time**: Hours to 1-2 days
- **Risk**: Moderate, contained
- **Example**: Add form field, improve validation
### Level 3: Intermediate Feature
- **Keywords**: implement, create, develop
- **Scope**: Multiple components
- **Time**: Days to 1-2 weeks
- **Risk**: Significant
- **Example**: User authentication, dashboard
### Level 4: Complex System
- **Keywords**: system, architecture, redesign
- **Scope**: Multiple subsystems
- **Time**: Weeks to months
- **Risk**: High, architectural
- **Example**: Payment system, microservices
## 📋 COMPLEXITY CHECKLIST
```
✓ COMPLEXITY DETERMINATION
- Task type identified? [YES/NO]
- Scope assessed? [YES/NO]
- Time estimated? [YES/NO]
- Risk evaluated? [YES/NO]
- Dependencies mapped? [YES/NO]
→ If all YES: Proceed with level-specific workflow
→ If any NO: Complete assessment
```
## 🔄 LEVEL TRANSITION TRIGGERS
```mermaid
graph TD
Current["Current Level"] --> Higher["Level Up Triggers"]
Current --> Lower["Level Down Triggers"]
Higher --> H1["Multiple Components"]
Higher --> H2["Design Decisions"]
Higher --> H3["System Impact"]
Lower --> L1["Isolated Change"]
Lower --> L2["Simple Fix"]
Lower --> L3["No Design Needed"]
style Current fill:#4da6ff,stroke:#0066cc,color:white
style Higher fill:#f6546a,stroke:#c30052,color:white
style Lower fill:#10b981,stroke:#059669,color:white
```
## 📋 WORKFLOW LOADING
Based on determined level:
- Level 1: Continue in VAN mode
- Level 2-4: Transition to PLAN mode
**Next Step:** Load appropriate level-specific workflow
## 🚨 MODE TRANSITION TRIGGER (VAN to PLAN)
If complexity is determined to be Level 2, 3, or 4:
```
🚫 LEVEL [2-4] TASK DETECTED
Implementation in VAN mode is BLOCKED
This task REQUIRES PLAN mode
You MUST switch to PLAN mode for proper documentation and planning
Type 'PLAN' to switch to planning mode
```
## 📋 CHECKPOINT VERIFICATION TEMPLATE (Example)
```
✓ SECTION CHECKPOINT: COMPLEXITY DETERMINATION
- Task Analyzed? [YES/NO]
- Complexity Level Determined? [YES/NO]
→ If Level 1: Proceed to VAN Mode Completion.
→ If Level 2-4: Trigger PLAN Mode transition.
```
**Next Step (Level 1):** Complete VAN Initialization (e.g., initialize Memory Bank if needed).
**Next Step (Level 2-4):** Exit VAN mode and initiate PLAN mode.
@@ -0,0 +1,302 @@
---
description: Visual process map for VAN mode file verification
globs: van-file-verification.mdc
alwaysApply: false
---
# OPTIMIZED FILE VERIFICATION SYSTEM
🚨 CRITICAL: MEMORY BANK VERIFICATION REQUIRED 🚨
Memory Bank structure MUST exist before any file operations
This check MUST be executed first in all verification processes
> **TL;DR:** This system provides a structured approach to verify file structure integrity before task implementation, with emphasis on efficient checks and clear status reporting.
## 🔍 FILE VERIFICATION WORKFLOW
```mermaid
graph TD
%% Critical Memory Bank verification - MUST be first
Start["Start File Verification"] --> MemBankCheck{"Memory Bank<br>Exists?"}
MemBankCheck -->|"No"| CreateMemBank["CREATE MEMORY BANK<br>[CRITICAL]"]
MemBankCheck -->|"Yes"| VerifyMemBankComplete["Verify Memory Bank<br>Structure Complete"]
CreateMemBank --> VerifyMemBankComplete
VerifyMemBankComplete --> PassCheck{"All Critical<br>Checks Pass?"}
PassCheck -->|"No"| AbortAll["⛔ ABORT ALL OPERATIONS<br>Fix Memory Bank First"]
PassCheck -->|"Yes"| MainVerification
%% Regular verification flow continues here
MainVerification["Start Full<br>File Verification"] --> BatchVerify["Batch Verification<br>Using Patterns"]
BatchVerify --> BrokenLinks["Check for<br>Broken References"]
BrokenLinks --> DirectoryStructure["Verify Directory<br>Structure"]
DirectoryStructure --> Status{"All Verifications<br>Successful?"}
Status -->|"Yes"| Complete["Verification<br>Complete ✓"]
Status -->|"No"| Diagnose["Diagnose<br>Issues"]
Diagnose --> Attempt{"Attempt Auto<br>Resolution?"}
Attempt -->|"Yes"| AutoFix["Auto-Fix<br>Issues"]
Attempt -->|"No"| ReportIssue["Report Issues to<br>User"]
AutoFix --> Recheck{"Issues<br>Resolved?"}
Recheck -->|"Yes"| ReportSuccess["Report Success<br>to User"]
Recheck -->|"No"| ReportIssue
ReportSuccess --> Complete
ReportIssue --> UserAction["Wait for<br>User Action"]
UserAction --> ReVerify["Re-Verify<br>After User Action"]
ReVerify --> Status
style MemBankCheck fill:#ff0000,stroke:#990000,color:white,stroke-width:3px
style CreateMemBank fill:#ff0000,stroke:#990000,color:white,stroke-width:3px
style VerifyMemBankComplete fill:#ff0000,stroke:#990000,color:white,stroke-width:3px
style PassCheck fill:#ff0000,stroke:#990000,color:white,stroke-width:3px
style AbortAll fill:#ff0000,stroke:#990000,color:white,stroke-width:3px
style Status fill:#f6546a,stroke:#c30052,color:white
style Complete fill:#10b981,stroke:#059669,color:white
```
## 🧩 MEMORY BANK VERIFICATION - CRITICAL COMPONENT
Memory Bank verification MUST be executed first in any file verification process:
```javascript
function verifyMemoryBank() {
// Check if Memory Bank exists
const memoryBankExists = checkDirectoryExists("memory-bank");
if (!memoryBankExists) {
console.error("⛔ CRITICAL ERROR: Memory Bank does not exist");
createMemoryBankStructure();
return verifyMemoryBankCreation();
}
// Check required subdirectories
const requiredDirs = [
"memory-bank/active-context",
"memory-bank/system-patterns",
"memory-bank/creative-phase",
"memory-bank/implementation"
];
const missingDirs = requiredDirs.filter(dir => !checkDirectoryExists(dir));
if (missingDirs.length > 0) {
console.error(`⛔ CRITICAL ERROR: Missing Memory Bank directories: ${missingDirs.join(", ")}`);
createMissingDirectories(missingDirs);
return verifyMemoryBankCreation();
}
// Check critical files
const criticalFiles = [
"memory-bank/active-context/activeContext.md",
"memory-bank/system-patterns/systemPatterns.md"
];
const missingFiles = criticalFiles.filter(file => !checkFileExists(file));
if (missingFiles.length > 0) {
console.error(`⛔ CRITICAL ERROR: Missing critical files: ${missingFiles.join(", ")}`);
createMissingFiles(missingFiles);
return verifyMemoryBankCreation();
}
return true; // Memory Bank verification successful
}
// MANDATORY: This must be called before any other verification
const memoryBankVerified = verifyMemoryBank();
if (!memoryBankVerified) {
throw new Error("⛔ MEMORY BANK VERIFICATION FAILED - CANNOT PROCEED");
}
```
## 📋 MEMORY BANK VERIFICATION CHECKLIST
```
✓ MEMORY BANK VERIFICATION CHECKLIST
- Memory Bank directory exists? [YES/NO]
- Required subdirectories exist? [YES/NO]
- Critical files exist? [YES/NO]
- File content is valid? [YES/NO]
→ If ALL YES: Memory Bank verification passed - Continue file verification
→ If ANY NO: STOP ALL PROCESSING and FIX MEMORY BANK
```
## 🔍 BATCH VERIFICATION WORKFLOW
## 📋 OPTIMIZED DIRECTORY CREATION
```mermaid
graph TD
Start["Directory<br>Creation"] --> DetectOS["Detect Operating<br>System"]
DetectOS -->|"Windows"| WinCmd["Batch Create<br>Windows Command"]
DetectOS -->|"Mac/Linux"| UnixCmd["Batch Create<br>Unix Command"]
WinCmd & UnixCmd --> Verify["Verify<br>Creation Success"]
Verify --> Complete["Directory Setup<br>Complete"]
```
### Platform-Specific Commands
#### Windows (PowerShell)
```powershell
# Create all directories in one command
mkdir memory-bank, docs, docs\archive -ErrorAction SilentlyContinue
# Create all required files
$files = @(".cursorrules", "tasks.md",
"memory-bank\projectbrief.md",
"memory-bank\productContext.md",
"memory-bank\systemPatterns.md",
"memory-bank\techContext.md",
"memory-bank\activeContext.md",
"memory-bank\progress.md")
foreach ($file in $files) {
if (-not (Test-Path $file)) {
New-Item -Path $file -ItemType File -Force
}
}
```
#### Mac/Linux (Bash)
```bash
# Create all directories in one command
mkdir -p memory-bank docs/archive
# Create all required files
touch .cursorrules tasks.md \
memory-bank/projectbrief.md \
memory-bank/productContext.md \
memory-bank/systemPatterns.md \
memory-bank/techContext.md \
memory-bank/activeContext.md \
memory-bank/progress.md
```
## 📝 STREAMLINED VERIFICATION PROCESS
Instead of checking each component separately, perform batch verification:
```powershell
# Windows - PowerShell
$requiredDirs = @("memory-bank", "docs", "docs\archive")
$requiredFiles = @(".cursorrules", "tasks.md")
$mbFiles = @("projectbrief.md", "productContext.md", "systemPatterns.md",
"techContext.md", "activeContext.md", "progress.md")
$missingDirs = $requiredDirs | Where-Object { -not (Test-Path $_) -or -not (Test-Path $_ -PathType Container) }
$missingFiles = $requiredFiles | Where-Object { -not (Test-Path $_) -or (Test-Path $_ -PathType Container) }
$missingMBFiles = $mbFiles | ForEach-Object { "memory-bank\$_" } |
Where-Object { -not (Test-Path $_) -or (Test-Path $_ -PathType Container) }
if ($missingDirs.Count -eq 0 -and $missingFiles.Count -eq 0 -and $missingMBFiles.Count -eq 0) {
Write-Output "✓ All required components verified"
} else {
# Create all missing items at once
if ($missingDirs.Count -gt 0) {
$missingDirs | ForEach-Object { mkdir $_ -Force }
}
if ($missingFiles.Count -gt 0 -or $missingMBFiles.Count -gt 0) {
$allMissingFiles = $missingFiles + $missingMBFiles
$allMissingFiles | ForEach-Object { New-Item -Path $_ -ItemType File -Force }
}
}
```
## 📝 TEMPLATE INITIALIZATION
Optimize template creation with a single script:
```powershell
# Windows - PowerShell
$templates = @{
"tasks.md" = @"
# Memory Bank: Tasks
## Current Task
[Task not yet defined]
## Status
- [ ] Task definition
- [ ] Implementation plan
- [ ] Execution
- [ ] Documentation
## Requirements
[No requirements defined yet]
"@
"memory-bank\activeContext.md" = @"
# Memory Bank: Active Context
## Current Focus
[No active focus defined]
## Status
[No status defined]
## Latest Changes
[No changes recorded]
"@
# Add other templates here
}
foreach ($file in $templates.Keys) {
if (Test-Path $file) {
Set-Content -Path $file -Value $templates[$file]
}
}
```
## 🔍 PERFORMANCE OPTIMIZATION BEST PRACTICES
1. **Batch Operations**: Always use batch operations instead of individual commands
```
# GOOD: Create all directories at once
mkdir memory-bank docs docs\archive
# BAD: Create directories one at a time
mkdir memory-bank
mkdir docs
mkdir docs\archive
```
2. **Pre-Check Optimization**: Check all requirements first, then create only what's missing
```
# First check what's missing
$missingItems = ...
# Then create only what's missing
if ($missingItems) { ... }
```
3. **Error Handling**: Include error handling in all commands
```
mkdir memory-bank, docs, docs\archive -ErrorAction SilentlyContinue
```
4. **Platform Adaptation**: Auto-detect platform and use appropriate commands
```
if ($IsWindows) {
# Windows commands
} else {
# Unix commands
}
```
5. **One-Pass Verification**: Verify directory structure in a single pass
```
$requiredPaths = @("memory-bank", "docs", "docs\archive", ".cursorrules", "tasks.md")
$missingPaths = $requiredPaths | Where-Object { -not (Test-Path $_) }
```
## 📝 VERIFICATION REPORT FORMAT
```
✅ VERIFICATION COMPLETE
- Created directories: [list]
- Created files: [list]
- All components verified
Memory Bank system ready for use.
```
@@ -0,0 +1,914 @@
---
description: Visual process map for VAN mode (Index/Entry Point)
globs: van-mode-map.mdc
alwaysApply: false
---
# VAN MODE: INITIALIZATION PROCESS MAP
🚨 MANDATORY FIRST STEP: MEMORY BANK CREATION 🚨
NO OPERATION CAN PROCEED WITHOUT MEMORY BANK STRUCTURE
> **TL;DR:** This visual map defines the VAN mode process for project initialization, task analysis, and technical validation. It guides users through platform detection, file verification, complexity determination, and technical validation to ensure proper setup before implementation.
## 🧭 VAN MODE PROCESS FLOW
```mermaid
graph TD
Start["START VAN MODE"] --> PlatformDetect["PLATFORM DETECTION"]
PlatformDetect --> DetectOS["Detect Operating System"]
DetectOS --> CheckPath["Check Path Separator Format"]
CheckPath --> AdaptCmds["Adapt Commands if Needed"]
AdaptCmds --> PlatformCP["⛔ PLATFORM CHECKPOINT"]
%% Add Critical Memory Bank Checkpoint
PlatformCP --> MemoryBankCheck{"Memory Bank<br>Exists?"}
MemoryBankCheck -->|"No"| CreateMemoryBank["CREATE MEMORY BANK<br>[CRITICAL STEP]"]
MemoryBankCheck -->|"Yes"| BasicFileVerify["BASIC FILE VERIFICATION"]
CreateMemoryBank --> MemoryBankCP["⛔ MEMORY BANK VERIFICATION [REQUIRED]"]
MemoryBankCP --> BasicFileVerify
%% Basic File Verification with checkpoint
BasicFileVerify --> BatchCheck["Batch Check Essential Components"]
BatchCheck --> BatchCreate["Batch Create Essential Structure"]
BatchCreate --> BasicFileCP["⛔ BASIC FILE CHECKPOINT"]
%% Early Complexity Determination
BasicFileCP --> EarlyComplexity["EARLY COMPLEXITY DETERMINATION"]
EarlyComplexity --> AnalyzeTask["Analyze Task Requirements"]
AnalyzeTask --> EarlyLevelCheck{"Complexity Level?"}
%% Level handling paths
EarlyLevelCheck -->|"Level 1"| ComplexityCP["⛔ COMPLEXITY CHECKPOINT"]
EarlyLevelCheck -->|"Level 2-4"| CRITICALGATE["🚫 CRITICAL GATE: FORCE MODE SWITCH"]
CRITICALGATE --> ForceExit["Exit to PLAN mode"]
%% Level 1 continues normally
ComplexityCP --> InitSystem["INITIALIZE MEMORY BANK"]
InitSystem --> Complete1["LEVEL 1 INITIALIZATION COMPLETE"]
%% For Level 2+ tasks after PLAN and CREATIVE modes
ForceExit -.-> OtherModes["PLAN → CREATIVE modes"]
OtherModes -.-> VANQA["VAN QA MODE"]
VANQA --> QAProcess["Technical Validation Process"]
QAProcess --> QACheck{"All Checks Pass?"}
QACheck -->|"Yes"| BUILD["To BUILD MODE"]
QACheck -->|"No"| FixIssues["Fix Technical Issues"]
FixIssues --> QAProcess
%% Style nodes
style PlatformCP fill:#f55,stroke:#d44,color:white
style MemoryBankCP fill:#ff0000,stroke:#990000,color:white,stroke-width:3px
style MemoryBankCheck fill:#ff0000,stroke:#990000,color:white,stroke-width:3px
style CreateMemoryBank fill:#ff0000,stroke:#990000,color:white,stroke-width:3px
style BasicFileCP fill:#f55,stroke:#d44,color:white
style ComplexityCP fill:#f55,stroke:#d44,color:white
style CRITICALGATE fill:#ff0000,stroke:#990000,color:white,stroke-width:3px
style ForceExit fill:#ff0000,stroke:#990000,color:white,stroke-width:2px
style VANQA fill:#4da6ff,stroke:#0066cc,color:white,stroke-width:3px
style QAProcess fill:#4da6ff,stroke:#0066cc,color:white
style QACheck fill:#4da6ff,stroke:#0066cc,color:white
style FixIssues fill:#ff5555,stroke:#dd3333,color:white
```
## 🌐 PLATFORM DETECTION PROCESS
```mermaid
graph TD
PD["Platform Detection"] --> CheckOS["Detect Operating System"]
CheckOS --> Win["Windows"]
CheckOS --> Mac["macOS"]
CheckOS --> Lin["Linux"]
Win & Mac & Lin --> Adapt["Adapt Commands<br>for Platform"]
Win --> WinPath["Path: Backslash (\\)"]
Mac --> MacPath["Path: Forward Slash (/)"]
Lin --> LinPath["Path: Forward Slash (/)"]
Win --> WinCmd["Command Adaptations:<br>dir, icacls, etc."]
Mac --> MacCmd["Command Adaptations:<br>ls, chmod, etc."]
Lin --> LinCmd["Command Adaptations:<br>ls, chmod, etc."]
WinPath & MacPath & LinPath --> PathCP["Path Separator<br>Checkpoint"]
WinCmd & MacCmd & LinCmd --> CmdCP["Command<br>Checkpoint"]
PathCP & CmdCP --> PlatformComplete["Platform Detection<br>Complete"]
style PD fill:#4da6ff,stroke:#0066cc,color:white
style PlatformComplete fill:#10b981,stroke:#059669,color:white
```
## 📁 FILE VERIFICATION PROCESS
```mermaid
graph TD
FV["File Verification"] --> CheckFiles["Check Essential Files"]
CheckFiles --> CheckMB["Check Memory Bank<br>Structure"]
CheckMB --> MBExists{"Memory Bank<br>Exists?"}
MBExists -->|"Yes"| VerifyMB["Verify Memory Bank<br>Contents"]
MBExists -->|"No"| CreateMB["Create Memory Bank<br>Structure"]
CheckFiles --> CheckDocs["Check Documentation<br>Files"]
CheckDocs --> DocsExist{"Docs<br>Exist?"}
DocsExist -->|"Yes"| VerifyDocs["Verify Documentation<br>Structure"]
DocsExist -->|"No"| CreateDocs["Create Documentation<br>Structure"]
VerifyMB & CreateMB --> MBCP["Memory Bank<br>Checkpoint"]
VerifyDocs & CreateDocs --> DocsCP["Documentation<br>Checkpoint"]
MBCP & DocsCP --> FileComplete["File Verification<br>Complete"]
style FV fill:#4da6ff,stroke:#0066cc,color:white
style FileComplete fill:#10b981,stroke:#059669,color:white
style MBCP fill:#f6546a,stroke:#c30052,color:white
style DocsCP fill:#f6546a,stroke:#c30052,color:white
```
## 🧩 COMPLEXITY DETERMINATION PROCESS
```mermaid
graph TD
CD["Complexity<br>Determination"] --> AnalyzeTask["Analyze Task<br>Requirements"]
AnalyzeTask --> CheckKeywords["Check Task<br>Keywords"]
CheckKeywords --> ScopeCheck["Assess<br>Scope Impact"]
ScopeCheck --> RiskCheck["Evaluate<br>Risk Level"]
RiskCheck --> EffortCheck["Estimate<br>Implementation Effort"]
EffortCheck --> DetermineLevel{"Determine<br>Complexity Level"}
DetermineLevel -->|"Level 1"| L1["Level 1:<br>Quick Bug Fix"]
DetermineLevel -->|"Level 2"| L2["Level 2:<br>Simple Enhancement"]
DetermineLevel -->|"Level 3"| L3["Level 3:<br>Intermediate Feature"]
DetermineLevel -->|"Level 4"| L4["Level 4:<br>Complex System"]
L1 --> CDComplete["Complexity Determination<br>Complete"]
L2 & L3 & L4 --> ModeSwitch["Force Mode Switch<br>to PLAN"]
style CD fill:#4da6ff,stroke:#0066cc,color:white
style CDComplete fill:#10b981,stroke:#059669,color:white
style ModeSwitch fill:#ff0000,stroke:#990000,color:white
style DetermineLevel fill:#f6546a,stroke:#c30052,color:white
```
## 🔄 COMPLETE WORKFLOW WITH QA VALIDATION
The full workflow includes technical validation before implementation:
```mermaid
flowchart LR
VAN1["VAN MODE
(Initial Analysis)"] --> PLAN["PLAN MODE
(Task Planning)"]
PLAN --> CREATIVE["CREATIVE MODE
(Design Decisions)"]
CREATIVE --> VANQA["VAN QA MODE
(Technical Validation)"]
VANQA --> BUILD["BUILD MODE
(Implementation)"]
```
## 🔍 TECHNICAL VALIDATION OVERVIEW
The VAN QA technical validation process consists of four key validation points:
```mermaid
graph TD
VANQA["VAN QA MODE"] --> FourChecks["FOUR-POINT VALIDATION"]
FourChecks --> DepCheck["1️⃣ DEPENDENCY VERIFICATION<br>Check all required packages"]
DepCheck --> ConfigCheck["2️⃣ CONFIGURATION VALIDATION<br>Verify format & compatibility"]
ConfigCheck --> EnvCheck["3️⃣ ENVIRONMENT VALIDATION<br>Check build environment"]
EnvCheck --> MinBuildCheck["4️⃣ MINIMAL BUILD TEST<br>Test core functionality"]
MinBuildCheck --> ValidationResults{"All Checks<br>Passed?"}
ValidationResults -->|"Yes"| SuccessReport["GENERATE SUCCESS REPORT"]
ValidationResults -->|"No"| FailureReport["GENERATE FAILURE REPORT"]
SuccessReport --> BUILD["Proceed to BUILD MODE"]
FailureReport --> FixIssues["Fix Technical Issues"]
FixIssues --> ReValidate["Re-validate"]
ReValidate --> ValidationResults
style VANQA fill:#4da6ff,stroke:#0066cc,color:white
style FourChecks fill:#f6546a,stroke:#c30052,color:white
style ValidationResults fill:#f6546a,stroke:#c30052,color:white
style BUILD fill:#10b981,stroke:#059669,color:white
style FixIssues fill:#ff5555,stroke:#dd3333,color:white
```
## 📝 VALIDATION STATUS FORMAT
The QA Validation step includes clear status indicators:
```
╔═════════════════ 🔍 QA VALIDATION STATUS ═════════════════╗
│ ✓ Design Decisions │ Verified as implementable │
│ ✓ Dependencies │ All required packages installed │
│ ✓ Configurations │ Format verified for platform │
│ ✓ Environment │ Suitable for implementation │
╚════════════════════════════════════════════════════════════╝
✅ VERIFIED - Clear to proceed to BUILD mode
```
## 🚨 MODE TRANSITION TRIGGERS
### VAN to PLAN Transition
For complexity levels 2-4:
```
🚫 LEVEL [2-4] TASK DETECTED
Implementation in VAN mode is BLOCKED
This task REQUIRES PLAN mode
You MUST switch to PLAN mode for proper documentation and planning
Type 'PLAN' to switch to planning mode
```
### CREATIVE to VAN QA Transition
After completing the CREATIVE mode:
```
⏭️ NEXT MODE: VAN QA
To validate technical requirements before implementation, please type 'VAN QA'
```
### VAN QA to BUILD Transition
After successful validation:
```
✅ TECHNICAL VALIDATION COMPLETE
All prerequisites verified successfully
You may now proceed to BUILD mode
Type 'BUILD' to begin implementation
```
## 🔒 BUILD MODE PREVENTION MECHANISM
The system prevents moving to BUILD mode without passing QA validation:
```mermaid
graph TD
Start["User Types: BUILD"] --> CheckQA{"QA Validation<br>Completed?"}
CheckQA -->|"Yes and Passed"| AllowBuild["Allow BUILD Mode"]
CheckQA -->|"No or Failed"| BlockBuild["BLOCK BUILD MODE"]
BlockBuild --> Message["Display:<br>⚠️ QA VALIDATION REQUIRED"]
Message --> ReturnToVANQA["Prompt: Type VAN QA"]
style CheckQA fill:#f6546a,stroke:#c30052,color:white
style BlockBuild fill:#ff0000,stroke:#990000,color:white,stroke-width:3px
style Message fill:#ff5555,stroke:#dd3333,color:white
style ReturnToVANQA fill:#4da6ff,stroke:#0066cc,color:white
```
## 🔄 QA COMMAND PRECEDENCE
QA validation can be called at any point in the process flow, and takes immediate precedence over any other current steps, including forced mode switches:
```mermaid
graph TD
UserQA["User Types: QA"] --> HighPriority["⚠️ HIGH PRIORITY COMMAND"]
HighPriority --> CurrentTask["Pause Current Task/Process"]
CurrentTask --> LoadQA["Load QA Mode Map"]
LoadQA --> RunQA["Execute QA Validation Process"]
RunQA --> QAResults{"QA Results"}
QAResults -->|"PASS"| ResumeFlow["Resume Prior Process Flow"]
QAResults -->|"FAIL"| FixIssues["Fix Identified Issues"]
FixIssues --> ReRunQA["Re-run QA Validation"]
ReRunQA --> QAResults
style UserQA fill:#f8d486,stroke:#e8b84d,color:black
style HighPriority fill:#ff0000,stroke:#cc0000,color:white,stroke-width:3px
style LoadQA fill:#4da6ff,stroke:#0066cc,color:white
style RunQA fill:#4da6ff,stroke:#0066cc,color:white
style QAResults fill:#f6546a,stroke:#c30052,color:white
```
### QA Interruption Rules
When a user types **QA** at any point:
1. **The QA command MUST take immediate precedence** over any current operation, including the "FORCE MODE SWITCH" triggered by complexity assessment.
2. The system MUST:
- Immediately load the QA mode map
- Execute the full QA validation process
- Address any failures before continuing
3. **Required remediation steps take priority** over any pending mode switches or complexity rules
4. After QA validation is complete and passes:
- Resume the previously determined process flow
- Continue with any required mode switches
```
⚠️ QA OVERRIDE ACTIVATED
All other processes paused
QA validation checks now running...
Any issues found MUST be remediated before continuing with normal process flow
```
## 📋 CHECKPOINT VERIFICATION TEMPLATE
Each major checkpoint in VAN mode uses this format:
```
✓ SECTION CHECKPOINT: [SECTION NAME]
- Requirement 1? [YES/NO]
- Requirement 2? [YES/NO]
- Requirement 3? [YES/NO]
→ If all YES: Ready for next section
→ If any NO: Fix missing items before proceeding
```
## 🚀 VAN MODE ACTIVATION
When the user types "VAN", respond with a confirmation and start the process:
```
User: VAN
Response: OK VAN - Beginning Initialization Process
```
After completing CREATIVE mode, when the user types "VAN QA", respond:
```
User: VAN QA
Response: OK VAN QA - Beginning Technical Validation
```
This ensures clear communication about which phase of VAN mode is active.
## 🔍 DETAILED QA VALIDATION PROCESS
### 1️⃣ DEPENDENCY VERIFICATION
This step verifies that all required packages are installed and compatible:
```mermaid
graph TD
Start["Dependency Verification"] --> ReadDeps["Read Required Dependencies<br>from Creative Phase"]
ReadDeps --> CheckInstalled["Check if Dependencies<br>are Installed"]
CheckInstalled --> DepStatus{"All Dependencies<br>Installed?"}
DepStatus -->|"Yes"| VerifyVersions["Verify Versions<br>and Compatibility"]
DepStatus -->|"No"| InstallMissing["Install Missing<br>Dependencies"]
InstallMissing --> VerifyVersions
VerifyVersions --> VersionStatus{"Versions<br>Compatible?"}
VersionStatus -->|"Yes"| DepSuccess["Dependencies Verified<br>✅ PASS"]
VersionStatus -->|"No"| UpgradeVersions["Upgrade/Downgrade<br>as Needed"]
UpgradeVersions --> RetryVerify["Retry Verification"]
RetryVerify --> VersionStatus
style Start fill:#4da6ff,stroke:#0066cc,color:white
style DepSuccess fill:#10b981,stroke:#059669,color:white
style DepStatus fill:#f6546a,stroke:#c30052,color:white
style VersionStatus fill:#f6546a,stroke:#c30052,color:white
```
#### Windows (PowerShell) Implementation:
```powershell
# Example: Verify Node.js dependencies for a React project
function Verify-Dependencies {
$requiredDeps = @{
"node" = ">=14.0.0"
"npm" = ">=6.0.0"
}
$missingDeps = @()
$incompatibleDeps = @()
# Check Node.js version
$nodeVersion = $null
try {
$nodeVersion = node -v
if ($nodeVersion -match "v(\d+)\.(\d+)\.(\d+)") {
$major = [int]$Matches[1]
if ($major -lt 14) {
$incompatibleDeps += "node (found $nodeVersion, required >=14.0.0)"
}
}
} catch {
$missingDeps += "node"
}
# Check npm version
$npmVersion = $null
try {
$npmVersion = npm -v
if ($npmVersion -match "(\d+)\.(\d+)\.(\d+)") {
$major = [int]$Matches[1]
if ($major -lt 6) {
$incompatibleDeps += "npm (found $npmVersion, required >=6.0.0)"
}
}
} catch {
$missingDeps += "npm"
}
# Display results
if ($missingDeps.Count -eq 0 -and $incompatibleDeps.Count -eq 0) {
Write-Output "✅ All dependencies verified and compatible"
return $true
} else {
if ($missingDeps.Count -gt 0) {
Write-Output "❌ Missing dependencies: $($missingDeps -join ', ')"
}
if ($incompatibleDeps.Count -gt 0) {
Write-Output "❌ Incompatible versions: $($incompatibleDeps -join ', ')"
}
return $false
}
}
```
#### Mac/Linux (Bash) Implementation:
```bash
#!/bin/bash
# Example: Verify Node.js dependencies for a React project
verify_dependencies() {
local missing_deps=()
local incompatible_deps=()
# Check Node.js version
if command -v node &> /dev/null; then
local node_version=$(node -v)
if [[ $node_version =~ v([0-9]+)\.([0-9]+)\.([0-9]+) ]]; then
local major=${BASH_REMATCH[1]}
if (( major < 14 )); then
incompatible_deps+=("node (found $node_version, required >=14.0.0)")
fi
fi
else
missing_deps+=("node")
fi
# Check npm version
if command -v npm &> /dev/null; then
local npm_version=$(npm -v)
if [[ $npm_version =~ ([0-9]+)\.([0-9]+)\.([0-9]+) ]]; then
local major=${BASH_REMATCH[1]}
if (( major < 6 )); then
incompatible_deps+=("npm (found $npm_version, required >=6.0.0)")
fi
fi
else
missing_deps+=("npm")
fi
# Display results
if [ ${#missing_deps[@]} -eq 0 ] && [ ${#incompatible_deps[@]} -eq 0 ]; then
echo "✅ All dependencies verified and compatible"
return 0
else
if [ ${#missing_deps[@]} -gt 0 ]; then
echo "❌ Missing dependencies: ${missing_deps[*]}"
fi
if [ ${#incompatible_deps[@]} -gt 0 ]; then
echo "❌ Incompatible versions: ${incompatible_deps[*]}"
fi
return 1
fi
}
```
### 2️⃣ CONFIGURATION VALIDATION
This step validates configuration files format and compatibility:
```mermaid
graph TD
Start["Configuration Validation"] --> IdentifyConfigs["Identify Configuration<br>Files"]
IdentifyConfigs --> ReadConfigs["Read Configuration<br>Files"]
ReadConfigs --> ValidateSyntax["Validate Syntax<br>and Format"]
ValidateSyntax --> SyntaxStatus{"Syntax<br>Valid?"}
SyntaxStatus -->|"Yes"| CheckCompatibility["Check Compatibility<br>with Platform"]
SyntaxStatus -->|"No"| FixSyntax["Fix Syntax<br>Errors"]
FixSyntax --> RetryValidate["Retry Validation"]
RetryValidate --> SyntaxStatus
CheckCompatibility --> CompatStatus{"Compatible with<br>Platform?"}
CompatStatus -->|"Yes"| ConfigSuccess["Configurations Validated<br>✅ PASS"]
CompatStatus -->|"No"| AdaptConfigs["Adapt Configurations<br>for Platform"]
AdaptConfigs --> RetryCompat["Retry Compatibility<br>Check"]
RetryCompat --> CompatStatus
style Start fill:#4da6ff,stroke:#0066cc,color:white
style ConfigSuccess fill:#10b981,stroke:#059669,color:white
style SyntaxStatus fill:#f6546a,stroke:#c30052,color:white
style CompatStatus fill:#f6546a,stroke:#c30052,color:white
```
#### Configuration Validation Implementation:
```powershell
# Example: Validate configuration files for a web project
function Validate-Configurations {
$configFiles = @(
"package.json",
"tsconfig.json",
"vite.config.js"
)
$invalidConfigs = @()
$incompatibleConfigs = @()
foreach ($configFile in $configFiles) {
if (Test-Path $configFile) {
# Check JSON syntax for JSON files
if ($configFile -match "\.json$") {
try {
Get-Content $configFile -Raw | ConvertFrom-Json | Out-Null
} catch {
$invalidConfigs += "$configFile (JSON syntax error: $($_.Exception.Message))"
continue
}
}
# Specific configuration compatibility checks
if ($configFile -eq "vite.config.js") {
$content = Get-Content $configFile -Raw
# Check for React plugin in Vite config
if ($content -notmatch "react\(\)") {
$incompatibleConfigs += "$configFile (Missing React plugin for React project)"
}
}
} else {
$invalidConfigs += "$configFile (file not found)"
}
}
# Display results
if ($invalidConfigs.Count -eq 0 -and $incompatibleConfigs.Count -eq 0) {
Write-Output "✅ All configurations validated and compatible"
return $true
} else {
if ($invalidConfigs.Count -gt 0) {
Write-Output "❌ Invalid configurations: $($invalidConfigs -join ', ')"
}
if ($incompatibleConfigs.Count -gt 0) {
Write-Output "❌ Incompatible configurations: $($incompatibleConfigs -join ', ')"
}
return $false
}
}
```
### 3️⃣ ENVIRONMENT VALIDATION
This step checks if the environment is properly set up for the implementation:
```mermaid
graph TD
Start["Environment Validation"] --> CheckEnv["Check Build Environment"]
CheckEnv --> VerifyBuildTools["Verify Build Tools"]
VerifyBuildTools --> ToolsStatus{"Build Tools<br>Available?"}
ToolsStatus -->|"Yes"| CheckPerms["Check Permissions<br>and Access"]
ToolsStatus -->|"No"| InstallTools["Install Required<br>Build Tools"]
InstallTools --> RetryTools["Retry Verification"]
RetryTools --> ToolsStatus
CheckPerms --> PermsStatus{"Permissions<br>Sufficient?"}
PermsStatus -->|"Yes"| EnvSuccess["Environment Validated<br>✅ PASS"]
PermsStatus -->|"No"| FixPerms["Fix Permission<br>Issues"]
FixPerms --> RetryPerms["Retry Permission<br>Check"]
RetryPerms --> PermsStatus
style Start fill:#4da6ff,stroke:#0066cc,color:white
style EnvSuccess fill:#10b981,stroke:#059669,color:white
style ToolsStatus fill:#f6546a,stroke:#c30052,color:white
style PermsStatus fill:#f6546a,stroke:#c30052,color:white
```
#### Environment Validation Implementation:
```powershell
# Example: Validate environment for a web project
function Validate-Environment {
$requiredTools = @(
@{Name = "git"; Command = "git --version"},
@{Name = "node"; Command = "node --version"},
@{Name = "npm"; Command = "npm --version"}
)
$missingTools = @()
$permissionIssues = @()
# Check build tools
foreach ($tool in $requiredTools) {
try {
Invoke-Expression $tool.Command | Out-Null
} catch {
$missingTools += $tool.Name
}
}
# Check write permissions in project directory
try {
$testFile = ".__permission_test"
New-Item -Path $testFile -ItemType File -Force | Out-Null
Remove-Item -Path $testFile -Force
} catch {
$permissionIssues += "Current directory (write permission denied)"
}
# Check if port 3000 is available (commonly used for dev servers)
try {
$listener = New-Object System.Net.Sockets.TcpListener([System.Net.IPAddress]::Loopback, 3000)
$listener.Start()
$listener.Stop()
} catch {
$permissionIssues += "Port 3000 (already in use or access denied)"
}
# Display results
if ($missingTools.Count -eq 0 -and $permissionIssues.Count -eq 0) {
Write-Output "✅ Environment validated successfully"
return $true
} else {
if ($missingTools.Count -gt 0) {
Write-Output "❌ Missing tools: $($missingTools -join ', ')"
}
if ($permissionIssues.Count -gt 0) {
Write-Output "❌ Permission issues: $($permissionIssues -join ', ')"
}
return $false
}
}
```
### 4️⃣ MINIMAL BUILD TEST
This step performs a minimal build test to ensure core functionality:
```mermaid
graph TD
Start["Minimal Build Test"] --> CreateTest["Create Minimal<br>Test Project"]
CreateTest --> BuildTest["Attempt<br>Build"]
BuildTest --> BuildStatus{"Build<br>Successful?"}
BuildStatus -->|"Yes"| RunTest["Run Basic<br>Functionality Test"]
BuildStatus -->|"No"| FixBuild["Fix Build<br>Issues"]
FixBuild --> RetryBuild["Retry Build"]
RetryBuild --> BuildStatus
RunTest --> TestStatus{"Test<br>Passed?"}
TestStatus -->|"Yes"| TestSuccess["Minimal Build Test<br>✅ PASS"]
TestStatus -->|"No"| FixTest["Fix Test<br>Issues"]
FixTest --> RetryTest["Retry Test"]
RetryTest --> TestStatus
style Start fill:#4da6ff,stroke:#0066cc,color:white
style TestSuccess fill:#10b981,stroke:#059669,color:white
style BuildStatus fill:#f6546a,stroke:#c30052,color:white
style TestStatus fill:#f6546a,stroke:#c30052,color:white
```
#### Minimal Build Test Implementation:
```powershell
# Example: Perform minimal build test for a React project
function Perform-MinimalBuildTest {
$buildSuccess = $false
$testSuccess = $false
# Create minimal test project
$testDir = ".__build_test"
if (Test-Path $testDir) {
Remove-Item -Path $testDir -Recurse -Force
}
try {
# Create minimal test directory
New-Item -Path $testDir -ItemType Directory | Out-Null
Push-Location $testDir
# Initialize minimal package.json
@"
{
"name": "build-test",
"version": "1.0.0",
"description": "Minimal build test",
"main": "index.js",
"scripts": {
"build": "echo Build test successful"
}
}
"@ | Set-Content -Path "package.json"
# Attempt build
npm run build | Out-Null
$buildSuccess = $true
# Create minimal test file
@"
console.log('Test successful');
"@ | Set-Content -Path "index.js"
# Run basic test
node index.js | Out-Null
$testSuccess = $true
} catch {
Write-Output "❌ Build test failed: $($_.Exception.Message)"
} finally {
Pop-Location
if (Test-Path $testDir) {
Remove-Item -Path $testDir -Recurse -Force
}
}
# Display results
if ($buildSuccess -and $testSuccess) {
Write-Output "✅ Minimal build test passed successfully"
return $true
} else {
if (-not $buildSuccess) {
Write-Output "❌ Build process failed"
}
if (-not $testSuccess) {
Write-Output "❌ Basic functionality test failed"
}
return $false
}
}
```
## 📋 COMPREHENSIVE QA REPORT FORMAT
After running all validation steps, a comprehensive report is generated:
```
╔═════════════════════ 🔍 QA VALIDATION REPORT ══════════════════════╗
│ │
│ PROJECT: [Project Name] │
│ TIMESTAMP: [Current Date/Time] │
│ │
│ 1️⃣ DEPENDENCY VERIFICATION │
│ ✓ Required: [List of required dependencies] │
│ ✓ Installed: [List of installed dependencies] │
│ ✓ Compatible: [Yes/No] │
│ │
│ 2️⃣ CONFIGURATION VALIDATION │
│ ✓ Config Files: [List of configuration files] │
│ ✓ Syntax Valid: [Yes/No] │
│ ✓ Platform Compatible: [Yes/No] │
│ │
│ 3️⃣ ENVIRONMENT VALIDATION │
│ ✓ Build Tools: [Available/Missing] │
│ ✓ Permissions: [Sufficient/Insufficient] │
│ ✓ Environment Ready: [Yes/No] │
│ │
│ 4️⃣ MINIMAL BUILD TEST │
│ ✓ Build Process: [Successful/Failed] │
│ ✓ Functionality Test: [Passed/Failed] │
│ ✓ Build Ready: [Yes/No] │
│ │
│ 🚨 FINAL VERDICT: [PASS/FAIL] │
│ ➡️ [Success message or error details] │
╚═════════════════════════════════════════════════════════════════════╝
```
## ❌ FAILURE REPORT FORMAT
If any validation step fails, a detailed failure report is generated:
```
⚠️⚠️⚠️ QA VALIDATION FAILED ⚠️⚠️⚠️
The following issues must be resolved before proceeding to BUILD mode:
1️⃣ DEPENDENCY ISSUES:
- [Detailed description of dependency issues]
- [Recommended fix]
2️⃣ CONFIGURATION ISSUES:
- [Detailed description of configuration issues]
- [Recommended fix]
3️⃣ ENVIRONMENT ISSUES:
- [Detailed description of environment issues]
- [Recommended fix]
4️⃣ BUILD TEST ISSUES:
- [Detailed description of build test issues]
- [Recommended fix]
⚠️ BUILD MODE IS BLOCKED until these issues are resolved.
Type 'VAN QA' after fixing the issues to re-validate.
```
## 🔄 INTEGRATION WITH DESIGN DECISIONS
The VAN QA mode reads and validates design decisions from the CREATIVE phase:
```mermaid
graph TD
Start["Read Design Decisions"] --> ReadCreative["Parse Creative Phase<br>Documentation"]
ReadCreative --> ExtractTech["Extract Technology<br>Choices"]
ExtractTech --> ExtractDeps["Extract Required<br>Dependencies"]
ExtractDeps --> BuildValidationPlan["Build Validation<br>Plan"]
BuildValidationPlan --> StartValidation["Start Four-Point<br>Validation Process"]
style Start fill:#4da6ff,stroke:#0066cc,color:white
style ExtractTech fill:#f6546a,stroke:#c30052,color:white
style BuildValidationPlan fill:#10b981,stroke:#059669,color:white
style StartValidation fill:#f6546a,stroke:#c30052,color:white
```
### Technology Extraction Process:
```powershell
# Example: Extract technology choices from creative phase documentation
function Extract-TechnologyChoices {
$techChoices = @{}
# Read from systemPatterns.md
if (Test-Path "memory-bank\systemPatterns.md") {
$content = Get-Content "memory-bank\systemPatterns.md" -Raw
# Extract framework choice
if ($content -match "Framework:\s*(\w+)") {
$techChoices["framework"] = $Matches[1]
}
# Extract UI library choice
if ($content -match "UI Library:\s*(\w+)") {
$techChoices["ui_library"] = $Matches[1]
}
# Extract state management choice
if ($content -match "State Management:\s*([^\\n]+)") {
$techChoices["state_management"] = $Matches[1].Trim()
}
}
return $techChoices
}
```
## 🚨 IMPLEMENTATION PREVENTION MECHANISM
If QA validation fails, the system prevents moving to BUILD mode:
```powershell
# Example: Enforce QA validation before allowing BUILD mode
function Check-QAValidationStatus {
$qaStatusFile = "memory-bank\.qa_validation_status"
if (Test-Path $qaStatusFile) {
$status = Get-Content $qaStatusFile -Raw
if ($status -match "PASS") {
return $true
}
}
# Display block message
Write-Output "`n`n"
Write-Output "🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫"
Write-Output "⛔️ BUILD MODE BLOCKED: QA VALIDATION REQUIRED"
Write-Output "⛔️ You must complete QA validation before proceeding to BUILD mode"
Write-Output "`n"
Write-Output "Type 'VAN QA' to perform technical validation"
Write-Output "`n"
Write-Output "🚫 NO IMPLEMENTATION CAN PROCEED WITHOUT VALIDATION 🚫"
Write-Output "🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫"
return $false
}
```
## 🧪 COMMON QA VALIDATION FIXES
Here are common fixes for issues encountered during QA validation:
### Dependency Issues:
- **Missing Node.js**: Install Node.js from https://nodejs.org/
- **Outdated npm**: Run `npm install -g npm@latest` to update
- **Missing packages**: Run `npm install` or `npm install [package-name]`
### Configuration Issues:
- **Invalid JSON**: Use a JSON validator to check syntax
- **Missing React plugin**: Add `import react from '@vitejs/plugin-react'` and `plugins: [react()]` to vite.config.js
- **Incompatible TypeScript config**: Update `tsconfig.json` with correct React settings
### Environment Issues:
- **Permission denied**: Run terminal as administrator (Windows) or use sudo (Mac/Linux)
- **Port already in use**: Kill process using the port or change the port in configuration
- **Missing build tools**: Install required command-line tools
### Build Test Issues:
- **Build fails**: Check console for specific error messages
- **Test fails**: Verify minimal configuration is correct
- **Path issues**: Ensure paths use correct separators for the platform
## 🔒 FINAL QA VALIDATION CHECKPOINT
```
✓ SECTION CHECKPOINT: QA VALIDATION
- Dependency Verification Passed? [YES/NO]
- Configuration Validation Passed? [YES/NO]
- Environment Validation Passed? [YES/NO]
- Minimal Build Test Passed? [YES/NO]
→ If all YES: Ready for BUILD mode
→ If any NO: Fix identified issues before proceeding
```
@@ -0,0 +1,50 @@
---
description: Visual process map for VAN mode platform detection
globs: van-platform-detection.mdc
alwaysApply: false
---
# VAN MODE: PLATFORM DETECTION
> **TL;DR:** Detects the OS, determines path separators, and notes command adaptations required.
## 🌐 PLATFORM DETECTION PROCESS
```mermaid
graph TD
PD["Platform Detection"] --> CheckOS["Detect Operating System"]
CheckOS --> Win["Windows"]
CheckOS --> Mac["macOS"]
CheckOS --> Lin["Linux"]
Win & Mac & Lin --> Adapt["Adapt Commands<br>for Platform"]
Win --> WinPath["Path: Backslash (\\)"]
Mac --> MacPath["Path: Forward Slash (/)"]
Lin --> LinPath["Path: Forward Slash (/)"]
Win --> WinCmd["Command Adaptations:<br>dir, icacls, etc."]
Mac --> MacCmd["Command Adaptations:<br>ls, chmod, etc."]
Lin --> LinCmd["Command Adaptations:<br>ls, chmod, etc."]
WinPath & MacPath & LinPath --> PathCP["Path Separator<br>Checkpoint"]
WinCmd & MacCmd & LinCmd --> CmdCP["Command<br>Checkpoint"]
PathCP & CmdCP --> PlatformComplete["Platform Detection<br>Complete"]
style PD fill:#4da6ff,stroke:#0066cc,color:white
style PlatformComplete fill:#10b981,stroke:#059669,color:white
```
## 📋 CHECKPOINT VERIFICATION TEMPLATE (Example)
```
✓ SECTION CHECKPOINT: PLATFORM DETECTION
- Operating System Detected? [YES/NO]
- Path Separator Confirmed? [YES/NO]
- Command Adaptations Noted? [YES/NO]
→ If all YES: Platform Detection Complete.
→ If any NO: Resolve before proceeding.
```
**Next Step:** Load and process `van-file-verification.mdc`.
@@ -0,0 +1,117 @@
---
description: Process map for VAN QA minimal build test
globs: van-qa-checks/build-test.mdc
alwaysApply: false
---
# VAN QA: MINIMAL BUILD TEST
> **TL;DR:** This component performs a minimal build test to ensure core build functionality works properly.
## 4️⃣ MINIMAL BUILD TEST PROCESS
```mermaid
graph TD
Start["Minimal Build Test"] --> CreateTest["Create Minimal<br>Test Project"]
CreateTest --> BuildTest["Attempt<br>Build"]
BuildTest --> BuildStatus{"Build<br>Successful?"}
BuildStatus -->|"Yes"| RunTest["Run Basic<br>Functionality Test"]
BuildStatus -->|"No"| FixBuild["Fix Build<br>Issues"]
FixBuild --> RetryBuild["Retry Build"]
RetryBuild --> BuildStatus
RunTest --> TestStatus{"Test<br>Passed?"}
TestStatus -->|"Yes"| TestSuccess["Minimal Build Test<br>✅ PASS"]
TestStatus -->|"No"| FixTest["Fix Test<br>Issues"]
FixTest --> RetryTest["Retry Test"]
RetryTest --> TestStatus
style Start fill:#4da6ff,stroke:#0066cc,color:white
style TestSuccess fill:#10b981,stroke:#059669,color:white
style BuildStatus fill:#f6546a,stroke:#c30052,color:white
style TestStatus fill:#f6546a,stroke:#c30052,color:white
```
### Minimal Build Test Implementation:
```powershell
# Example: Perform minimal build test for a React project
function Perform-MinimalBuildTest {
$buildSuccess = $false
$testSuccess = $false
# Create minimal test project
$testDir = ".__build_test"
if (Test-Path $testDir) {
Remove-Item -Path $testDir -Recurse -Force
}
try {
# Create minimal test directory
New-Item -Path $testDir -ItemType Directory | Out-Null
Push-Location $testDir
# Initialize minimal package.json
@"
{
"name": "build-test",
"version": "1.0.0",
"description": "Minimal build test",
"main": "index.js",
"scripts": {
"build": "echo Build test successful"
}
}
"@ | Set-Content -Path "package.json"
# Attempt build
npm run build | Out-Null
$buildSuccess = $true
# Create minimal test file
@"
console.log('Test successful');
"@ | Set-Content -Path "index.js"
# Run basic test
node index.js | Out-Null
$testSuccess = $true
} catch {
Write-Output "❌ Build test failed: $($_.Exception.Message)"
} finally {
Pop-Location
if (Test-Path $testDir) {
Remove-Item -Path $testDir -Recurse -Force
}
}
# Display results
if ($buildSuccess -and $testSuccess) {
Write-Output "✅ Minimal build test passed successfully"
return $true
} else {
if (-not $buildSuccess) {
Write-Output "❌ Build process failed"
}
if (-not $testSuccess) {
Write-Output "❌ Basic functionality test failed"
}
return $false
}
}
```
## 📋 MINIMAL BUILD TEST CHECKPOINT
```
✓ CHECKPOINT: MINIMAL BUILD TEST
- Test project creation successful? [YES/NO]
- Build process completed successfully? [YES/NO]
- Basic functionality test passed? [YES/NO]
→ If all YES: QA Validation complete, proceed to generate success report.
→ If any NO: Fix build issues before continuing.
```
**Next Step (on PASS):** Load `van-qa-utils/reports.mdc` to generate success report.
**Next Step (on FAIL):** Check `van-qa-utils/common-fixes.mdc` for build test fixes.
@@ -0,0 +1,103 @@
---
description: Process map for VAN QA configuration validation
globs: van-qa-checks/config-check.mdc
alwaysApply: false
---
# VAN QA: CONFIGURATION VALIDATION
> **TL;DR:** This component validates configuration files for proper syntax and compatibility with the project and platform.
## 2️⃣ CONFIGURATION VALIDATION PROCESS
```mermaid
graph TD
Start["Configuration Validation"] --> IdentifyConfigs["Identify Configuration<br>Files"]
IdentifyConfigs --> ReadConfigs["Read Configuration<br>Files"]
ReadConfigs --> ValidateSyntax["Validate Syntax<br>and Format"]
ValidateSyntax --> SyntaxStatus{"Syntax<br>Valid?"}
SyntaxStatus -->|"Yes"| CheckCompatibility["Check Compatibility<br>with Platform"]
SyntaxStatus -->|"No"| FixSyntax["Fix Syntax<br>Errors"]
FixSyntax --> RetryValidate["Retry Validation"]
RetryValidate --> SyntaxStatus
CheckCompatibility --> CompatStatus{"Compatible with<br>Platform?"}
CompatStatus -->|"Yes"| ConfigSuccess["Configurations Validated<br>✅ PASS"]
CompatStatus -->|"No"| AdaptConfigs["Adapt Configurations<br>for Platform"]
AdaptConfigs --> RetryCompat["Retry Compatibility<br>Check"]
RetryCompat --> CompatStatus
style Start fill:#4da6ff,stroke:#0066cc,color:white
style ConfigSuccess fill:#10b981,stroke:#059669,color:white
style SyntaxStatus fill:#f6546a,stroke:#c30052,color:white
style CompatStatus fill:#f6546a,stroke:#c30052,color:white
```
### Configuration Validation Implementation:
```powershell
# Example: Validate configuration files for a web project
function Validate-Configurations {
$configFiles = @(
"package.json",
"tsconfig.json",
"vite.config.js"
)
$invalidConfigs = @()
$incompatibleConfigs = @()
foreach ($configFile in $configFiles) {
if (Test-Path $configFile) {
# Check JSON syntax for JSON files
if ($configFile -match "\.json$") {
try {
Get-Content $configFile -Raw | ConvertFrom-Json | Out-Null
} catch {
$invalidConfigs += "$configFile (JSON syntax error: $($_.Exception.Message))"
continue
}
}
# Specific configuration compatibility checks
if ($configFile -eq "vite.config.js") {
$content = Get-Content $configFile -Raw
# Check for React plugin in Vite config
if ($content -notmatch "react\(\)") {
$incompatibleConfigs += "$configFile (Missing React plugin for React project)"
}
}
} else {
$invalidConfigs += "$configFile (file not found)"
}
}
# Display results
if ($invalidConfigs.Count -eq 0 -and $incompatibleConfigs.Count -eq 0) {
Write-Output "✅ All configurations validated and compatible"
return $true
} else {
if ($invalidConfigs.Count -gt 0) {
Write-Output "❌ Invalid configurations: $($invalidConfigs -join ', ')"
}
if ($incompatibleConfigs.Count -gt 0) {
Write-Output "❌ Incompatible configurations: $($incompatibleConfigs -join ', ')"
}
return $false
}
}
```
## 📋 CONFIGURATION VALIDATION CHECKPOINT
```
✓ CHECKPOINT: CONFIGURATION VALIDATION
- All configuration files found? [YES/NO]
- All configuration syntax valid? [YES/NO]
- All configurations compatible with platform? [YES/NO]
→ If all YES: Continue to Environment Validation.
→ If any NO: Fix configuration issues before continuing.
```
**Next Step (on PASS):** Load `van-qa-checks/environment-check.mdc`.
**Next Step (on FAIL):** Check `van-qa-utils/common-fixes.mdc` for configuration fixes.
@@ -0,0 +1,147 @@
---
description: Process map for VAN QA dependency verification
globs: van-qa-checks/dependency-check.mdc
alwaysApply: false
---
# VAN QA: DEPENDENCY VERIFICATION
> **TL;DR:** This component verifies that all required dependencies are installed and compatible with the project requirements.
## 1️⃣ DEPENDENCY VERIFICATION PROCESS
```mermaid
graph TD
Start["Dependency Verification"] --> ReadDeps["Read Required Dependencies<br>from Creative Phase"]
ReadDeps --> CheckInstalled["Check if Dependencies<br>are Installed"]
CheckInstalled --> DepStatus{"All Dependencies<br>Installed?"}
DepStatus -->|"Yes"| VerifyVersions["Verify Versions<br>and Compatibility"]
DepStatus -->|"No"| InstallMissing["Install Missing<br>Dependencies"]
InstallMissing --> VerifyVersions
VerifyVersions --> VersionStatus{"Versions<br>Compatible?"}
VersionStatus -->|"Yes"| DepSuccess["Dependencies Verified<br>✅ PASS"]
VersionStatus -->|"No"| UpgradeVersions["Upgrade/Downgrade<br>as Needed"]
UpgradeVersions --> RetryVerify["Retry Verification"]
RetryVerify --> VersionStatus
style Start fill:#4da6ff,stroke:#0066cc,color:white
style DepSuccess fill:#10b981,stroke:#059669,color:white
style DepStatus fill:#f6546a,stroke:#c30052,color:white
style VersionStatus fill:#f6546a,stroke:#c30052,color:white
```
### Windows (PowerShell) Implementation:
```powershell
# Example: Verify Node.js dependencies for a React project
function Verify-Dependencies {
$requiredDeps = @{ "node" = ">=14.0.0"; "npm" = ">=6.0.0" }
$missingDeps = @(); $incompatibleDeps = @()
# Check Node.js version
try {
$nodeVersion = node -v
if ($nodeVersion -match "v(\d+)\.(\d+)\.(\d+)") {
$major = [int]$Matches[1]
if ($major -lt 14) {
$incompatibleDeps += "node (found $nodeVersion, required >=14.0.0)"
}
}
} catch {
$missingDeps += "node"
}
# Check npm version
try {
$npmVersion = npm -v
if ($npmVersion -match "(\d+)\.(\d+)\.(\d+)") {
$major = [int]$Matches[1]
if ($major -lt 6) {
$incompatibleDeps += "npm (found $npmVersion, required >=6.0.0)"
}
}
} catch {
$missingDeps += "npm"
}
# Display results
if ($missingDeps.Count -eq 0 -and $incompatibleDeps.Count -eq 0) {
Write-Output "✅ All dependencies verified and compatible"
return $true
} else {
if ($missingDeps.Count -gt 0) {
Write-Output "❌ Missing dependencies: $($missingDeps -join ', ')"
}
if ($incompatibleDeps.Count -gt 0) {
Write-Output "❌ Incompatible versions: $($incompatibleDeps -join ', ')"
}
return $false
}
}
```
### Mac/Linux (Bash) Implementation:
```bash
#!/bin/bash
# Example: Verify Node.js dependencies for a React project
verify_dependencies() {
local missing_deps=()
local incompatible_deps=()
# Check Node.js version
if command -v node &> /dev/null; then
local node_version=$(node -v)
if [[ $node_version =~ v([0-9]+)\.([0-9]+)\.([0-9]+) ]]; then
local major=${BASH_REMATCH[1]}
if (( major < 14 )); then
incompatible_deps+=("node (found $node_version, required >=14.0.0)")
fi
fi
else
missing_deps+=("node")
fi
# Check npm version
if command -v npm &> /dev/null; then
local npm_version=$(npm -v)
if [[ $npm_version =~ ([0-9]+)\.([0-9]+)\.([0-9]+) ]]; then
local major=${BASH_REMATCH[1]}
if (( major < 6 )); then
incompatible_deps+=("npm (found $npm_version, required >=6.0.0)")
fi
fi
else
missing_deps+=("npm")
fi
# Display results
if [ ${#missing_deps[@]} -eq 0 ] && [ ${#incompatible_deps[@]} -eq 0 ]; then
echo "✅ All dependencies verified and compatible"
return 0
else
if [ ${#missing_deps[@]} -gt 0 ]; then
echo "❌ Missing dependencies: ${missing_deps[*]}"
fi
if [ ${#incompatible_deps[@]} -gt 0 ]; then
echo "❌ Incompatible versions: ${incompatible_deps[*]}"
fi
return 1
fi
}
```
## 📋 DEPENDENCY VERIFICATION CHECKPOINT
```
✓ CHECKPOINT: DEPENDENCY VERIFICATION
- Required dependencies identified? [YES/NO]
- All dependencies installed? [YES/NO]
- All versions compatible? [YES/NO]
→ If all YES: Continue to Configuration Validation.
→ If any NO: Fix dependency issues before continuing.
```
**Next Step (on PASS):** Load `van-qa-checks/config-check.mdc`.
**Next Step (on FAIL):** Check `van-qa-utils/common-fixes.mdc` for dependency fixes.
@@ -0,0 +1,104 @@
---
description: Process map for VAN QA environment validation
globs: van-qa-checks/environment-check.mdc
alwaysApply: false
---
# VAN QA: ENVIRONMENT VALIDATION
> **TL;DR:** This component verifies that the build environment is properly set up with required tools and permissions.
## 3️⃣ ENVIRONMENT VALIDATION PROCESS
```mermaid
graph TD
Start["Environment Validation"] --> CheckEnv["Check Build Environment"]
CheckEnv --> VerifyBuildTools["Verify Build Tools"]
VerifyBuildTools --> ToolsStatus{"Build Tools<br>Available?"}
ToolsStatus -->|"Yes"| CheckPerms["Check Permissions<br>and Access"]
ToolsStatus -->|"No"| InstallTools["Install Required<br>Build Tools"]
InstallTools --> RetryTools["Retry Verification"]
RetryTools --> ToolsStatus
CheckPerms --> PermsStatus{"Permissions<br>Sufficient?"}
PermsStatus -->|"Yes"| EnvSuccess["Environment Validated<br>✅ PASS"]
PermsStatus -->|"No"| FixPerms["Fix Permission<br>Issues"]
FixPerms --> RetryPerms["Retry Permission<br>Check"]
RetryPerms --> PermsStatus
style Start fill:#4da6ff,stroke:#0066cc,color:white
style EnvSuccess fill:#10b981,stroke:#059669,color:white
style ToolsStatus fill:#f6546a,stroke:#c30052,color:white
style PermsStatus fill:#f6546a,stroke:#c30052,color:white
```
### Environment Validation Implementation:
```powershell
# Example: Validate environment for a web project
function Validate-Environment {
$requiredTools = @(
@{Name = "git"; Command = "git --version"},
@{Name = "node"; Command = "node --version"},
@{Name = "npm"; Command = "npm --version"}
)
$missingTools = @()
$permissionIssues = @()
# Check build tools
foreach ($tool in $requiredTools) {
try {
Invoke-Expression $tool.Command | Out-Null
} catch {
$missingTools += $tool.Name
}
}
# Check write permissions in project directory
try {
$testFile = ".__permission_test"
New-Item -Path $testFile -ItemType File -Force | Out-Null
Remove-Item -Path $testFile -Force
} catch {
$permissionIssues += "Current directory (write permission denied)"
}
# Check if port 3000 is available (commonly used for dev servers)
try {
$listener = New-Object System.Net.Sockets.TcpListener([System.Net.IPAddress]::Loopback, 3000)
$listener.Start()
$listener.Stop()
} catch {
$permissionIssues += "Port 3000 (already in use or access denied)"
}
# Display results
if ($missingTools.Count -eq 0 -and $permissionIssues.Count -eq 0) {
Write-Output "✅ Environment validated successfully"
return $true
} else {
if ($missingTools.Count -gt 0) {
Write-Output "❌ Missing tools: $($missingTools -join ', ')"
}
if ($permissionIssues.Count -gt 0) {
Write-Output "❌ Permission issues: $($permissionIssues -join ', ')"
}
return $false
}
}
```
## 📋 ENVIRONMENT VALIDATION CHECKPOINT
```
✓ CHECKPOINT: ENVIRONMENT VALIDATION
- All required build tools installed? [YES/NO]
- Project directory permissions sufficient? [YES/NO]
- Required ports available? [YES/NO]
→ If all YES: Continue to Minimal Build Test.
→ If any NO: Fix environment issues before continuing.
```
**Next Step (on PASS):** Load `van-qa-checks/build-test.mdc`.
**Next Step (on FAIL):** Check `van-qa-utils/common-fixes.mdc` for environment fixes.
@@ -0,0 +1,142 @@
---
description: Visual process map for VAN QA mode (Technical Validation Entry Point)
globs: van-qa-main.mdc
alwaysApply: false
---
# VAN MODE: QA TECHNICAL VALIDATION (Main Entry)
> **TL;DR:** This is the entry point for the QA validation process that executes *after* CREATIVE mode and *before* BUILD mode. It ensures technical requirements are met before implementation begins.
## 📣 HOW TO USE THESE QA RULES
To access any QA validation rule or component, use the `fetch_rules` tool with exact rule names:
```
// CRITICAL: Always use fetch_rules to load validation components
// For detailed examples and guidance, load:
// isolation_rules/visual-maps/van-qa-utils/rule-calling-guide
```
## 🚀 VAN QA MODE ACTIVATION
After completing CREATIVE mode, when the user types "VAN QA", respond:
```mermaid
graph TD
UserQA["User Types: QA"] --> HighPriority["⚠️ HIGH PRIORITY COMMAND"]
HighPriority --> CurrentTask["Pause Current Task/Process"]
CurrentTask --> LoadQA["Load QA Main Map (This File)"]
LoadQA --> RunQA["Execute QA Validation Process"]
RunQA --> QAResults{"QA Results"}
QAResults -->|"PASS"| ResumeFlow["Resume Prior Process Flow"]
QAResults -->|"FAIL"| FixIssues["Fix Identified Issues"]
FixIssues --> ReRunQA["Re-run QA Validation"]
ReRunQA --> QAResults
style UserQA fill:#f8d486,stroke:#e8b84d,color:black
style HighPriority fill:#ff0000,stroke:#cc0000,color:white,stroke-width:3px
style LoadQA fill:#4da6ff,stroke:#0066cc,color:white
style RunQA fill:#4da6ff,stroke:#0066cc,color:white
style QAResults fill:#f6546a,stroke:#c30052,color:white
```
### QA Interruption Rules
1. **Immediate Precedence:** `QA` command interrupts everything.
2. **Load & Execute:** Load this map (`van-qa-main.mdc`) and its components (see below).
3. **Remediation Priority:** Fixes take priority over pending mode switches.
4. **Resume:** On PASS, resume the previous flow.
```
⚠️ QA OVERRIDE ACTIVATED
All other processes paused
QA validation checks now running...
Any issues found MUST be remediated before continuing with normal process flow
```
## 🔍 TECHNICAL VALIDATION OVERVIEW
Four-point validation process with selective loading:
```mermaid
graph TD
VANQA["VAN QA MODE"] --> FourChecks["FOUR-POINT VALIDATION"]
FourChecks --> DepCheck["1️⃣ DEPENDENCY VERIFICATION
Load: van-qa-checks/dependency-check.mdc"]
DepCheck --> ConfigCheck["2️⃣ CONFIGURATION VALIDATION
Load: van-qa-checks/config-check.mdc"]
ConfigCheck --> EnvCheck["3️⃣ ENVIRONMENT VALIDATION
Load: van-qa-checks/environment-check.mdc"]
EnvCheck --> MinBuildCheck["4️⃣ MINIMAL BUILD TEST
Load: van-qa-checks/build-test.mdc"]
MinBuildCheck --> ValidationResults{"All Checks<br>Passed?"}
ValidationResults -->|"Yes"| SuccessReport["GENERATE SUCCESS REPORT
Load: van-qa-utils/reports.mdc"]
ValidationResults -->|"No"| FailureReport["GENERATE FAILURE REPORT
Load: van-qa-utils/reports.mdc"]
SuccessReport --> BUILD_Transition["Trigger BUILD Mode
Load: van-qa-utils/mode-transitions.mdc"]
FailureReport --> FixIssues["Fix Technical Issues
Load: van-qa-utils/common-fixes.mdc"]
FixIssues --> ReValidate["Re-validate (Re-run VAN QA)"]
ReValidate --> FourChecks
style VANQA fill:#4da6ff,stroke:#0066cc,color:white
style FourChecks fill:#f6546a,stroke:#c30052,color:white
style ValidationResults fill:#f6546a,stroke:#c30052,color:white
style BUILD_Transition fill:#10b981,stroke:#059669,color:white
style FixIssues fill:#ff5555,stroke:#dd3333,color:white
```
## 🔄 INTEGRATION WITH DESIGN DECISIONS
Reads Creative Phase outputs to inform validation:
```mermaid
graph TD
Start["Read Design Decisions"] --> ReadCreative["Parse Creative Phase<br>Documentation"]
ReadCreative --> ExtractTech["Extract Technology<br>Choices"]
ExtractTech --> ExtractDeps["Extract Required<br>Dependencies"]
ExtractDeps --> BuildValidationPlan["Build Validation<br>Plan"]
BuildValidationPlan --> StartValidation["Start Four-Point<br>Validation Process"]
style Start fill:#4da6ff,stroke:#0066cc,color:white
style ExtractTech fill:#f6546a,stroke:#c30052,color:white
style BuildValidationPlan fill:#10b981,stroke:#059669,color:white
style StartValidation fill:#f6546a,stroke:#c30052,color:white
```
## 📋 COMPONENT LOADING SEQUENCE
The QA validation process follows this selective loading sequence:
1. **Main Entry (This File)**: `van-qa-main.mdc`
2. **Validation Checks**:
- `van-qa-checks/dependency-check.mdc`
- `van-qa-checks/config-check.mdc`
- `van-qa-checks/environment-check.mdc`
- `van-qa-checks/build-test.mdc`
3. **Utilities (As Needed)**:
- `van-qa-utils/reports.mdc`
- `van-qa-utils/common-fixes.mdc`
- `van-qa-utils/mode-transitions.mdc`
## 📋 FINAL QA VALIDATION CHECKPOINT
```
✓ SECTION CHECKPOINT: QA VALIDATION
- Dependency Verification Passed? [YES/NO]
- Configuration Validation Passed? [YES/NO]
- Environment Validation Passed? [YES/NO]
- Minimal Build Test Passed? [YES/NO]
→ If all YES: Ready for BUILD mode transition.
→ If any NO: Fix identified issues and re-run VAN QA.
```
**Next Step (on PASS):** Trigger BUILD mode (load `van-qa-utils/mode-transitions.mdc`).
**Next Step (on FAIL):** Address issues (load `van-qa-utils/common-fixes.mdc`) and re-run `VAN QA`.
@@ -0,0 +1,92 @@
---
description: Utility for VAN QA common validation fixes
globs: van-qa-utils/common-fixes.mdc
alwaysApply: false
---
# VAN QA: COMMON VALIDATION FIXES
> **TL;DR:** This component provides common fixes for issues that may arise during the QA validation process.
## 🧪 COMMON QA VALIDATION FIXES BY CATEGORY
### Dependency Issues
| Issue | Fix |
|-------|-----|
| **Missing Node.js** | Download and install Node.js from https://nodejs.org/ |
| **Outdated npm** | Run `npm install -g npm@latest` to update |
| **Missing packages** | Run `npm install` or `npm install [package-name]` |
| **Package version conflicts** | Adjust versions in package.json and run `npm install` |
| **Dependency resolution issues** | Run `npm cache clean -f` and try installing again |
### Configuration Issues
| Issue | Fix |
|-------|-----|
| **Invalid JSON** | Use a JSON validator (e.g., jsonlint) to check syntax |
| **Missing React plugin** | Add `import react from '@vitejs/plugin-react'` and `plugins: [react()]` to vite.config.js |
| **Incompatible TypeScript config** | Update `tsconfig.json` with correct React settings |
| **Mismatched version references** | Ensure consistent versions across configuration files |
| **Missing entries in config files** | Add required fields to configuration files |
### Environment Issues
| Issue | Fix |
|-------|-----|
| **Permission denied** | Run terminal as administrator (Windows) or use sudo (Mac/Linux) |
| **Port already in use** | Kill process using the port: `netstat -ano \| findstr :PORT` then `taskkill /F /PID PID` (Windows) or `lsof -i :PORT` then `kill -9 PID` (Mac/Linux) |
| **Missing build tools** | Install required command-line tools (git, node, etc.) |
| **Environment variable issues** | Set required environment variables: `$env:VAR_NAME = "value"` (PowerShell) or `export VAR_NAME="value"` (Bash) |
| **Disk space issues** | Free up disk space, clean npm/package cache files |
### Build Test Issues
| Issue | Fix |
|-------|-----|
| **Build fails** | Check console for specific error messages |
| **Test fails** | Verify minimal configuration is correct |
| **Path issues** | Ensure paths use correct separators for the platform (`\` for Windows, `/` for Mac/Linux) |
| **Missing dependencies** | Make sure all required dependencies are installed |
| **Script permissions** | Ensure script files have execution permissions (chmod +x on Unix) |
## 📝 ISSUE DIAGNOSIS PROCEDURES
### 1. Dependency Diagnosis
```powershell
# Find conflicting dependencies
npm ls [package-name]
# Check for outdated packages
npm outdated
# Check for vulnerabilities
npm audit
```
### 2. Configuration Diagnosis
```powershell
# List all configuration files
Get-ChildItem -Recurse -Include "*.json","*.config.js" | Select-Object FullName
# Find missing references in tsconfig.json
if (Test-Path "tsconfig.json") {
$tsconfig = Get-Content "tsconfig.json" -Raw | ConvertFrom-Json
if (-not $tsconfig.compilerOptions.jsx) {
Write-Output "Missing jsx setting in tsconfig.json"
}
}
```
### 3. Environment Diagnosis
```powershell
# Check process using a port (Windows)
netstat -ano | findstr ":3000"
# List environment variables
Get-ChildItem Env:
# Check disk space
Get-PSDrive C | Select-Object Used,Free
```
**Next Step:** Return to the validation process or follow the specific fix recommendations provided above.
@@ -0,0 +1,101 @@
---
description: Utility for VAN QA mode transitions
globs: van-qa-utils/mode-transitions.mdc
alwaysApply: false
---
# VAN QA: MODE TRANSITIONS
> **TL;DR:** This component handles transitions between modes, particularly the QA validation to BUILD mode transition, and prevents BUILD mode access without successful QA validation.
## 🔒 BUILD MODE PREVENTION MECHANISM
The system prevents moving to BUILD mode without passing QA validation:
```mermaid
graph TD
Start["User Types: BUILD"] --> CheckQA{"QA Validation<br>Completed?"}
CheckQA -->|"Yes and Passed"| AllowBuild["Allow BUILD Mode"]
CheckQA -->|"No or Failed"| BlockBuild["BLOCK BUILD MODE"]
BlockBuild --> Message["Display:<br>⚠️ QA VALIDATION REQUIRED"]
Message --> ReturnToVANQA["Prompt: Type VAN QA"]
style CheckQA fill:#f6546a,stroke:#c30052,color:white
style BlockBuild fill:#ff0000,stroke:#990000,color:white,stroke-width:3px
style Message fill:#ff5555,stroke:#dd3333,color:white
style ReturnToVANQA fill:#4da6ff,stroke:#0066cc,color:white
```
### Implementation Example (PowerShell):
```powershell
# Check QA status before allowing BUILD mode
function Check-QAValidationStatus {
$qaStatusFile = "memory-bank\.qa_validation_status" # Assumes status is written by reports.mdc
if (Test-Path $qaStatusFile) {
$status = Get-Content $qaStatusFile -Raw
if ($status -match "PASS") {
return $true
}
}
# Display block message
Write-Output "`n`n"
Write-Output "🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫"
Write-Output "⛔️ BUILD MODE BLOCKED: QA VALIDATION REQUIRED"
Write-Output "⛔️ You must complete QA validation before proceeding to BUILD mode"
Write-Output "`n"
Write-Output "Type 'VAN QA' to perform technical validation"
Write-Output "`n"
Write-Output "🚫 NO IMPLEMENTATION CAN PROCEED WITHOUT VALIDATION 🚫"
Write-Output "🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫🚫"
return $false
}
```
## 🚨 MODE TRANSITION TRIGGERS
### CREATIVE to VAN QA Transition:
After completing the CREATIVE phase, trigger this message to prompt QA validation:
```
⏭️ NEXT MODE: VAN QA
To validate technical requirements before implementation, please type 'VAN QA'
```
### VAN QA to BUILD Transition (On Success):
After successful QA validation, trigger this message to allow BUILD mode:
```
✅ TECHNICAL VALIDATION COMPLETE
All prerequisites verified successfully
You may now proceed to BUILD mode
Type 'BUILD' to begin implementation
```
### Manual BUILD Mode Access (When QA Already Passed):
When the user manually types 'BUILD', check the QA status before allowing access:
```powershell
# Handle BUILD mode request
function Handle-BuildModeRequest {
if (Check-QAValidationStatus) {
# Allow transition to BUILD mode
Write-Output "`n"
Write-Output "✅ QA VALIDATION CHECK: PASSED"
Write-Output "Loading BUILD mode..."
Write-Output "`n"
# Here you would load the BUILD mode map
# [Code to load BUILD mode map]
return $true
}
# QA validation failed or not completed, BUILD mode blocked
return $false
}
```
**Next Step (on QA SUCCESS):** Continue to BUILD mode.
**Next Step (on QA FAILURE):** Return to QA validation process.
@@ -0,0 +1,149 @@
---
description: Utility for VAN QA validation reports
globs: van-qa-utils/reports.mdc
alwaysApply: false
---
# VAN QA: VALIDATION REPORTS
> **TL;DR:** This component contains the formats for comprehensive success and failure reports generated upon completion of the QA validation process.
## 📋 COMPREHENSIVE SUCCESS REPORT FORMAT
After all four validation points pass, generate this success report:
```
╔═════════════════════ 🔍 QA VALIDATION REPORT ══════════════════════╗
│ PROJECT: [Project Name] | TIMESTAMP: [Current Date/Time] │
├─────────────────────────────────────────────────────────────────────┤
│ 1️⃣ DEPENDENCIES: ✓ Compatible │
│ 2️⃣ CONFIGURATION: ✓ Valid & Compatible │
│ 3️⃣ ENVIRONMENT: ✓ Ready │
│ 4️⃣ MINIMAL BUILD: ✓ Successful & Passed │
├─────────────────────────────────────────────────────────────────────┤
│ 🚨 FINAL VERDICT: PASS │
│ ➡️ Clear to proceed to BUILD mode │
╚═════════════════════════════════════════════════════════════════════╝
```
### Success Report Generation Example:
```powershell
function Generate-SuccessReport {
param (
[string]$ProjectName = "Current Project"
)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$report = @"
╔═════════════════════ 🔍 QA VALIDATION REPORT ══════════════════════╗
│ PROJECT: $ProjectName | TIMESTAMP: $timestamp │
├─────────────────────────────────────────────────────────────────────┤
│ 1️⃣ DEPENDENCIES: ✓ Compatible │
│ 2️⃣ CONFIGURATION: ✓ Valid & Compatible │
│ 3️⃣ ENVIRONMENT: ✓ Ready │
│ 4️⃣ MINIMAL BUILD: ✓ Successful & Passed │
├─────────────────────────────────────────────────────────────────────┤
│ 🚨 FINAL VERDICT: PASS │
│ ➡️ Clear to proceed to BUILD mode │
╚═════════════════════════════════════════════════════════════════════╝
"@
# Save validation status (used by BUILD mode prevention mechanism)
"PASS" | Set-Content -Path "memory-bank\.qa_validation_status"
return $report
}
```
## ❌ FAILURE REPORT FORMAT
If any validation step fails, generate this detailed failure report:
```
⚠️⚠️⚠️ QA VALIDATION FAILED ⚠️⚠️⚠️
The following issues must be resolved before proceeding to BUILD mode:
1️⃣ DEPENDENCY ISSUES:
- [Detailed description of dependency issues]
- [Recommended fix]
2️⃣ CONFIGURATION ISSUES:
- [Detailed description of configuration issues]
- [Recommended fix]
3️⃣ ENVIRONMENT ISSUES:
- [Detailed description of environment issues]
- [Recommended fix]
4️⃣ BUILD TEST ISSUES:
- [Detailed description of build test issues]
- [Recommended fix]
⚠️ BUILD MODE IS BLOCKED until these issues are resolved.
Type 'VAN QA' after fixing the issues to re-validate.
```
### Failure Report Generation Example:
```powershell
function Generate-FailureReport {
param (
[string[]]$DependencyIssues = @(),
[string[]]$ConfigIssues = @(),
[string[]]$EnvironmentIssues = @(),
[string[]]$BuildIssues = @()
)
$report = @"
⚠️⚠️⚠️ QA VALIDATION FAILED ⚠️⚠️⚠️
The following issues must be resolved before proceeding to BUILD mode:
"@
if ($DependencyIssues.Count -gt 0) {
$report += @"
1️⃣ DEPENDENCY ISSUES:
$(($DependencyIssues | ForEach-Object { "- $_" }) -join "`n")
"@
}
if ($ConfigIssues.Count -gt 0) {
$report += @"
2️⃣ CONFIGURATION ISSUES:
$(($ConfigIssues | ForEach-Object { "- $_" }) -join "`n")
"@
}
if ($EnvironmentIssues.Count -gt 0) {
$report += @"
3️⃣ ENVIRONMENT ISSUES:
$(($EnvironmentIssues | ForEach-Object { "- $_" }) -join "`n")
"@
}
if ($BuildIssues.Count -gt 0) {
$report += @"
4️⃣ BUILD TEST ISSUES:
$(($BuildIssues | ForEach-Object { "- $_" }) -join "`n")
"@
}
$report += @"
⚠️ BUILD MODE IS BLOCKED until these issues are resolved.
Type 'VAN QA' after fixing the issues to re-validate.
"@
# Save validation status (used by BUILD mode prevention mechanism)
"FAIL" | Set-Content -Path "memory-bank\.qa_validation_status"
return $report
}
```
**Next Step (on SUCCESS):** Load `van-qa-utils/mode-transitions.mdc` to handle BUILD mode transition.
**Next Step (on FAILURE):** Load `van-qa-utils/common-fixes.mdc` for issue remediation guidance.
@@ -0,0 +1,66 @@
---
description: Comprehensive guide for calling VAN QA rules
globs: van-qa-utils/rule-calling-guide.mdc
alwaysApply: false
---
# VAN QA: COMPREHENSIVE RULE CALLING GUIDE
> **TL;DR:** This reference guide shows how to properly call all VAN QA rules at the right time during the validation process.
## 🔍 RULE CALLING BASICS
Remember these key principles:
1. Always use the `fetch_rules` tool to load rules
2. Use exact rule paths
3. Load components only when needed
## 📋 MAIN QA ENTRY POINT
When user types "VAN QA", load the main entry point:
```
fetch_rules with "isolation_rules/visual-maps/van-qa-main"
```
## 📋 VALIDATION CHECKS
Load these components sequentially during validation:
```
1. fetch_rules with "isolation_rules/visual-maps/van-qa-checks/dependency-check"
2. fetch_rules with "isolation_rules/visual-maps/van-qa-checks/config-check"
3. fetch_rules with "isolation_rules/visual-maps/van-qa-checks/environment-check"
4. fetch_rules with "isolation_rules/visual-maps/van-qa-checks/build-test"
```
## 📋 UTILITY COMPONENTS
Load these when needed based on validation results:
```
- For reports: fetch_rules with "isolation_rules/visual-maps/van-qa-utils/reports"
- For fixes: fetch_rules with "isolation_rules/visual-maps/van-qa-utils/common-fixes"
- For transitions: fetch_rules with "isolation_rules/visual-maps/van-qa-utils/mode-transitions"
```
## ⚠️ CRITICAL REMINDERS
Remember to call these rules at these specific points:
- ALWAYS load the main QA entry point when "VAN QA" is typed
- ALWAYS load dependency-check before starting validation
- ALWAYS load reports after completing validation
- ALWAYS load mode-transitions after successful validation
- ALWAYS load common-fixes after failed validation
## 🔄 FULL VALIDATION SEQUENCE
Complete sequence for a QA validation process:
1. Load main entry: `isolation_rules/visual-maps/van-qa-main`
2. Load first check: `isolation_rules/visual-maps/van-qa-checks/dependency-check`
3. Load second check: `isolation_rules/visual-maps/van-qa-checks/config-check`
4. Load third check: `isolation_rules/visual-maps/van-qa-checks/environment-check`
5. Load fourth check: `isolation_rules/visual-maps/van-qa-checks/build-test`
6. If pass, load: `isolation_rules/visual-maps/van-qa-utils/reports`
7. If pass, load: `isolation_rules/visual-maps/van-qa-utils/mode-transitions`
8. If fail, load: `isolation_rules/visual-maps/van-qa-utils/common-fixes`
@@ -0,0 +1,19 @@
---
description: Utility for remembering how to call VAN QA rules
globs: van-qa-utils/rule-calling-help.mdc
alwaysApply: false
---
# VAN QA: HOW TO CALL RULES
> **TL;DR:** This file provides examples and reminders on how to properly call VAN QA rules using the fetch_rules tool.
## 🚨 RULE CALLING SYNTAX
Always use the `fetch_rules` tool with the correct syntax:
```
<function_calls>
<invoke name="fetch_rules">
<parameter name="rule_names">["isolation_rules/visual-maps/rule-name"]
</invoke>
</function_calls>
@@ -0,0 +1,363 @@
# VAN MODE: QA TECHNICAL VALIDATION (Pre-BUILD)
> **TL;DR:** This map details the technical validation process executed *after* CREATIVE mode and *before* BUILD mode, triggered by the `VAN QA` command. It ensures dependencies, configuration, environment, and basic build functionality are sound.
## 🚀 VAN QA MODE ACTIVATION
After completing CREATIVE mode, when the user types "VAN QA", respond:
```
User: VAN QA
Response: OK VAN QA - Beginning Technical Validation
Loading QA Validation map...
```
## 🔄 QA COMMAND PRECEDENCE (QA Override)
QA validation can be called at any point (`QA` command) and takes immediate precedence:
```mermaid
graph TD
UserQA["User Types: QA"] --> HighPriority["⚠️ HIGH PRIORITY COMMAND"]
HighPriority --> CurrentTask["Pause Current Task/Process"]
CurrentTask --> LoadQA["Load QA Validation Map (This File)"]
LoadQA --> RunQA["Execute QA Validation Process"]
RunQA --> QAResults{"QA Results"}
QAResults -->|"PASS"| ResumeFlow["Resume Prior Process Flow"]
QAResults -->|"FAIL"| FixIssues["Fix Identified Issues"]
FixIssues --> ReRunQA["Re-run QA Validation"]
ReRunQA --> QAResults
style UserQA fill:#f8d486,stroke:#e8b84d,color:black
style HighPriority fill:#ff0000,stroke:#cc0000,color:white,stroke-width:3px
style LoadQA fill:#4da6ff,stroke:#0066cc,color:white
style RunQA fill:#4da6ff,stroke:#0066cc,color:white
style QAResults fill:#f6546a,stroke:#c30052,color:white
```
### QA Interruption Rules
1. **Immediate Precedence:** `QA` command interrupts everything.
2. **Load & Execute:** Load this map (`van-qa-validation.mdc`) and run the full process.
3. **Remediation Priority:** Fixes take priority over pending mode switches.
4. **Resume:** On PASS, resume the previous flow.
```
⚠️ QA OVERRIDE ACTIVATED
All other processes paused
QA validation checks now running...
Any issues found MUST be remediated before continuing with normal process flow
```
## 🔍 TECHNICAL VALIDATION OVERVIEW
Four-point validation process:
```mermaid
graph TD
VANQA["VAN QA MODE"] --> FourChecks["FOUR-POINT VALIDATION"]
FourChecks --> DepCheck["1️⃣ DEPENDENCY VERIFICATION"]
DepCheck --> ConfigCheck["2️⃣ CONFIGURATION VALIDATION"]
ConfigCheck --> EnvCheck["3️⃣ ENVIRONMENT VALIDATION"]
EnvCheck --> MinBuildCheck["4️⃣ MINIMAL BUILD TEST"]
MinBuildCheck --> ValidationResults{"All Checks<br>Passed?"}
ValidationResults -->|"Yes"| SuccessReport["GENERATE SUCCESS REPORT"]
ValidationResults -->|"No"| FailureReport["GENERATE FAILURE REPORT"]
SuccessReport --> BUILD_Transition["Trigger BUILD Mode"]
FailureReport --> FixIssues["Fix Technical Issues"]
FixIssues --> ReValidate["Re-validate (Re-run VAN QA)"]
ReValidate --> FourChecks
style VANQA fill:#4da6ff,stroke:#0066cc,color:white
style FourChecks fill:#f6546a,stroke:#c30052,color:white
style ValidationResults fill:#f6546a,stroke:#c30052,color:white
style BUILD_Transition fill:#10b981,stroke:#059669,color:white
style FixIssues fill:#ff5555,stroke:#dd3333,color:white
```
## 🔄 INTEGRATION WITH DESIGN DECISIONS
Reads Creative Phase outputs (e.g., `memory-bank/systemPatterns.md`) to inform validation:
```mermaid
graph TD
Start["Read Design Decisions"] --> ReadCreative["Parse Creative Phase<br>Documentation"]
ReadCreative --> ExtractTech["Extract Technology<br>Choices"]
ExtractTech --> ExtractDeps["Extract Required<br>Dependencies"]
ExtractDeps --> BuildValidationPlan["Build Validation<br>Plan"]
BuildValidationPlan --> StartValidation["Start Four-Point<br>Validation Process"]
style Start fill:#4da6ff,stroke:#0066cc,color:white
style ExtractTech fill:#f6546a,stroke:#c30052,color:white
style BuildValidationPlan fill:#10b981,stroke:#059669,color:white
style StartValidation fill:#f6546a,stroke:#c30052,color:white
```
### Example Technology Extraction (PowerShell):
```powershell
# Example: Extract technology choices from creative phase documentation
function Extract-TechnologyChoices {
$techChoices = @{}
# Read from systemPatterns.md
if (Test-Path "memory-bank\systemPatterns.md") {
$content = Get-Content "memory-bank\systemPatterns.md" -Raw
if ($content -match "Framework:\s*(\w+)") { $techChoices["framework"] = $Matches[1] }
if ($content -match "UI Library:\s*(\w+)") { $techChoices["ui_library"] = $Matches[1] }
if ($content -match "State Management:\s*([^\n]+)") { $techChoices["state_management"] = $Matches[1].Trim() }
}
return $techChoices
}
```
## 🔍 DETAILED QA VALIDATION STEPS & SCRIPTS
### 1️⃣ DEPENDENCY VERIFICATION
```mermaid
# Mermaid graph for Dependency Verification (as in original file)
graph TD
Start["Dependency Verification"] --> ReadDeps["Read Required Dependencies<br>from Creative Phase"]
ReadDeps --> CheckInstalled["Check if Dependencies<br>are Installed"]
CheckInstalled --> DepStatus{"All Dependencies<br>Installed?"}
DepStatus -->|"Yes"| VerifyVersions["Verify Versions<br>and Compatibility"]
DepStatus -->|"No"| InstallMissing["Install Missing<br>Dependencies"]
InstallMissing --> VerifyVersions
VerifyVersions --> VersionStatus{"Versions<br>Compatible?"}
VersionStatus -->|"Yes"| DepSuccess["Dependencies Verified<br>✅ PASS"]
VersionStatus -->|"No"| UpgradeVersions["Upgrade/Downgrade<br>as Needed"]
UpgradeVersions --> RetryVerify["Retry Verification"]
RetryVerify --> VersionStatus
style Start fill:#4da6ff; style DepSuccess fill:#10b981; style DepStatus fill:#f6546a; style VersionStatus fill:#f6546a;
```
#### Example Implementation (PowerShell):
```powershell
# Verify-Dependencies function (as in original file)
function Verify-Dependencies {
$requiredDeps = @{ "node" = ">=14.0.0"; "npm" = ">=6.0.0" }
$missingDeps = @(); $incompatibleDeps = @()
try { $nodeVersion = node -v; if ($nodeVersion -match "v(\d+).*") { if ([int]$Matches[1] -lt 14) { $incompatibleDeps += "node" } } } catch { $missingDeps += "node" }
try { $npmVersion = npm -v; if ($npmVersion -match "(\d+).*") { if ([int]$Matches[1] -lt 6) { $incompatibleDeps += "npm" } } } catch { $missingDeps += "npm" }
if ($missingDeps.Count -eq 0 -and $incompatibleDeps.Count -eq 0) { Write-Output "✅ Deps OK"; return $true } else { Write-Output "❌ Deps FAIL"; return $false }
}
```
#### Example Implementation (Bash):
```bash
# verify_dependencies function (as in original file)
verify_dependencies() {
local missing_deps=(); local incompatible_deps=()
if command -v node &> /dev/null; then node_version=$(node -v); if [[ $node_version =~ v([0-9]+) ]]; then if (( ${BASH_REMATCH[1]} < 14 )); then incompatible_deps+=("node"); fi; fi; else missing_deps+=("node"); fi
if command -v npm &> /dev/null; then npm_version=$(npm -v); if [[ $npm_version =~ ([0-9]+) ]]; then if (( ${BASH_REMATCH[1]} < 6 )); then incompatible_deps+=("npm"); fi; fi; else missing_deps+=("npm"); fi
if [ ${#missing_deps[@]} -eq 0 ] && [ ${#incompatible_deps[@]} -eq 0 ]; then echo "✅ Deps OK"; return 0; else echo "❌ Deps FAIL"; return 1; fi
}
```
### 2️⃣ CONFIGURATION VALIDATION
```mermaid
# Mermaid graph for Configuration Validation (as in original file)
graph TD
Start["Configuration Validation"] --> IdentifyConfigs["Identify Files"]
IdentifyConfigs --> ReadConfigs["Read Files"]
ReadConfigs --> ValidateSyntax["Validate Syntax"]
ValidateSyntax --> SyntaxStatus{"Valid?"}
SyntaxStatus -->|"Yes"| CheckCompatibility["Check Compatibility"]
SyntaxStatus -->|"No"| FixSyntax["Fix Syntax"]
FixSyntax --> RetryValidate["Retry"]
RetryValidate --> SyntaxStatus
CheckCompatibility --> CompatStatus{"Compatible?"}
CompatStatus -->|"Yes"| ConfigSuccess["Configs Validated ✅ PASS"]
CompatStatus -->|"No"| AdaptConfigs["Adapt Configs"]
AdaptConfigs --> RetryCompat["Retry Check"]
RetryCompat --> CompatStatus
style Start fill:#4da6ff; style ConfigSuccess fill:#10b981; style SyntaxStatus fill:#f6546a; style CompatStatus fill:#f6546a;
```
#### Example Implementation (PowerShell):
```powershell
# Validate-Configurations function (as in original file)
function Validate-Configurations {
$configFiles = @("package.json", "tsconfig.json", "vite.config.js")
$invalidConfigs = @(); $incompatibleConfigs = @()
foreach ($configFile in $configFiles) {
if (Test-Path $configFile) {
if ($configFile -match "\.json$") { try { Get-Content $configFile -Raw | ConvertFrom-Json | Out-Null } catch { $invalidConfigs += "$configFile (JSON)"; continue } }
if ($configFile -eq "vite.config.js") { $content = Get-Content $configFile -Raw; if ($content -notmatch "react\(\)") { $incompatibleConfigs += "$configFile (React)" } }
} else { $invalidConfigs += "$configFile (missing)" }
}
if ($invalidConfigs.Count -eq 0 -and $incompatibleConfigs.Count -eq 0) { Write-Output "✅ Configs OK"; return $true } else { Write-Output "❌ Configs FAIL"; return $false }
}
```
### 3️⃣ ENVIRONMENT VALIDATION
```mermaid
# Mermaid graph for Environment Validation (as in original file)
graph TD
Start["Environment Validation"] --> CheckEnv["Check Env"]
CheckEnv --> VerifyBuildTools["Verify Tools"]
VerifyBuildTools --> ToolsStatus{"Available?"}
ToolsStatus -->|"Yes"| CheckPerms["Check Permissions"]
ToolsStatus -->|"No"| InstallTools["Install Tools"]
InstallTools --> RetryTools["Retry"]
RetryTools --> ToolsStatus
CheckPerms --> PermsStatus{"Sufficient?"}
PermsStatus -->|"Yes"| EnvSuccess["Environment Validated ✅ PASS"]
PermsStatus -->|"No"| FixPerms["Fix Permissions"]
FixPerms --> RetryPerms["Retry Check"]
RetryPerms --> PermsStatus
style Start fill:#4da6ff; style EnvSuccess fill:#10b981; style ToolsStatus fill:#f6546a; style PermsStatus fill:#f6546a;
```
#### Example Implementation (PowerShell):
```powershell
# Validate-Environment function (as in original file)
function Validate-Environment {
$requiredTools = @(@{Name='git';Cmd='git --version'},@{Name='node';Cmd='node --version'},@{Name='npm';Cmd='npm --version'})
$missingTools = @(); $permissionIssues = @()
foreach ($tool in $requiredTools) { try { Invoke-Expression $tool.Cmd | Out-Null } catch { $missingTools += $tool.Name } }
try { $testFile = ".__perm_test"; New-Item $testFile -ItemType File -Force | Out-Null; Remove-Item $testFile -Force } catch { $permissionIssues += "CWD Write" }
try { $L = New-Object Net.Sockets.TcpListener([Net.IPAddress]::Loopback, 3000); $L.Start(); $L.Stop() } catch { $permissionIssues += "Port 3000" }
if ($missingTools.Count -eq 0 -and $permissionIssues.Count -eq 0) { Write-Output "✅ Env OK"; return $true } else { Write-Output "❌ Env FAIL"; return $false }
}
```
### 4️⃣ MINIMAL BUILD TEST
```mermaid
# Mermaid graph for Minimal Build Test (as in original file)
graph TD
Start["Minimal Build Test"] --> CreateTest["Create Test Proj"]
CreateTest --> BuildTest["Attempt Build"]
BuildTest --> BuildStatus{"Success?"}
BuildStatus -->|"Yes"| RunTest["Run Basic Test"]
BuildStatus -->|"No"| FixBuild["Fix Build Issues"]
FixBuild --> RetryBuild["Retry Build"]
RetryBuild --> BuildStatus
RunTest --> TestStatus{"Passed?"}
TestStatus -->|"Yes"| TestSuccess["Build Test ✅ PASS"]
TestStatus -->|"No"| FixTest["Fix Test Issues"]
FixTest --> RetryTest["Retry Test"]
RetryTest --> TestStatus
style Start fill:#4da6ff; style TestSuccess fill:#10b981; style BuildStatus fill:#f6546a; style TestStatus fill:#f6546a;
```
#### Example Implementation (PowerShell):
```powershell
# Perform-MinimalBuildTest function (as in original file)
function Perform-MinimalBuildTest {
$buildSuccess = $false; $testSuccess = $false; $testDir = ".__build_test"
if (Test-Path $testDir) { Remove-Item $testDir -Recurse -Force }
try {
New-Item $testDir -ItemType Directory | Out-Null; Push-Location $testDir
'{"name": "build-test","scripts": {"build": "echo Build test successful"}}' | Set-Content package.json
npm run build | Out-Null; $buildSuccess = $true
'console.log("Test successful");' | Set-Content index.js
node index.js | Out-Null; $testSuccess = $true
} catch { Write-Output "❌ Build test exception" } finally { Pop-Location; if (Test-Path $testDir) { Remove-Item $testDir -Recurse -Force } }
if ($buildSuccess -and $testSuccess) { Write-Output "✅ Build Test OK"; return $true } else { Write-Output "❌ Build Test FAIL"; return $false }
}
```
## 📝 VALIDATION REPORT FORMATS
### Comprehensive Success Report:
```
╔═════════════════════ 🔍 QA VALIDATION REPORT ══════════════════════╗
│ PROJECT: [Project Name] | TIMESTAMP: [Current Date/Time] │
├─────────────────────────────────────────────────────────────────────┤
│ 1️⃣ DEPENDENCIES: ✓ Compatible │
│ 2️⃣ CONFIGURATION: ✓ Valid & Compatible │
│ 3️⃣ ENVIRONMENT: ✓ Ready │
│ 4️⃣ MINIMAL BUILD: ✓ Successful & Passed │
├─────────────────────────────────────────────────────────────────────┤
│ 🚨 FINAL VERDICT: PASS │
│ ➡️ Clear to proceed to BUILD mode │
╚═════════════════════════════════════════════════════════════════════╝
```
### Detailed Failure Report:
```
⚠️⚠️⚠️ QA VALIDATION FAILED ⚠️⚠️⚠️
Issues must be resolved before BUILD mode:
1️⃣ DEPENDENCY ISSUES: [Details/Fix]
2️⃣ CONFIGURATION ISSUES: [Details/Fix]
3️⃣ ENVIRONMENT ISSUES: [Details/Fix]
4️⃣ BUILD TEST ISSUES: [Details/Fix]
⚠️ BUILD MODE BLOCKED. Type 'VAN QA' after fixing to re-validate.
```
## 🧪 COMMON QA VALIDATION FIXES
- **Dependencies:** Install Node/npm, run `npm install`, check versions.
- **Configuration:** Validate JSON, check required plugins (e.g., React for Vite), ensure TSConfig compatibility.
- **Environment:** Check permissions (Admin/sudo), ensure ports are free, install missing CLI tools (git, etc.).
- **Build Test:** Check logs for errors, verify minimal config, check path separators.
## 🔒 BUILD MODE PREVENTION MECHANISM
Logic to check QA status before allowing BUILD mode transition.
```mermaid
graph TD
Start["User Types: BUILD"] --> CheckQA{"QA Validation<br>Passed?"}
CheckQA -->|"Yes"| AllowBuild["Allow BUILD Mode"]
CheckQA -->|"No"| BlockBuild["BLOCK BUILD MODE"]
BlockBuild --> Message["Display:<br>⚠️ QA VALIDATION REQUIRED"]
Message --> ReturnToVANQA["Prompt: Type VAN QA"]
style CheckQA fill:#f6546a; style BlockBuild fill:#ff0000,stroke:#990000; style Message fill:#ff5555; style ReturnToVANQA fill:#4da6ff;
```
### Example Implementation (PowerShell):
```powershell
# Example: Check QA status before allowing BUILD
function Check-QAValidationStatus {
$qaStatusFile = "memory-bank\.qa_validation_status" # Assumes status is written here
if (Test-Path $qaStatusFile) {
if ((Get-Content $qaStatusFile -Raw) -match "PASS") { return $true }
}
Write-Output "🚫 BUILD MODE BLOCKED: QA VALIDATION REQUIRED. Type 'VAN QA'. 🚫"
return $false
}
```
## 🚨 MODE TRANSITION TRIGGERS (Relevant to QA)
### CREATIVE to VAN QA Transition:
```
⏭️ NEXT MODE: VAN QA
To validate technical requirements before implementation, please type 'VAN QA'
```
### VAN QA to BUILD Transition (On Success):
```
✅ TECHNICAL VALIDATION COMPLETE
All prerequisites verified successfully
You may now proceed to BUILD mode
Type 'BUILD' to begin implementation
```
## 📋 FINAL QA VALIDATION CHECKPOINT
```
✓ SECTION CHECKPOINT: QA VALIDATION
- Dependency Verification Passed? [YES/NO]
- Configuration Validation Passed? [YES/NO]
- Environment Validation Passed? [YES/NO]
- Minimal Build Test Passed? [YES/NO]
→ If all YES: Ready for BUILD mode transition.
→ If any NO: Fix identified issues and re-run VAN QA.
```
**Next Step (on PASS):** Trigger BUILD mode.
**Next Step (on FAIL):** Address issues and re-run `VAN QA`.
+2 -2
View File
@@ -23,7 +23,7 @@ alwaysApply: false
| Параметры BIRD tenant | Global settings: `bird_router_id`, `bird_local_asn`, … (`docs/manual.md`) |
| BGP peers | `BGPPeer` + `ParsePeerNeighbor` |
**BIRD2 docs:** https://bird.network.cz/?get_doc
**BIRD2 docs:** https://bird.nic.cz/?get_doc
---
@@ -199,7 +199,7 @@ alwaysApply: false
## Documentation Sync
**DOC-SYNC-05** | MUST | BIRD — https://bird.network.cz/?get_doc
**DOC-SYNC-05** | MUST | BIRD — https://bird.nic.cz/?get_doc
**DOC-SYNC-08** | MUST | BGP policy — RFC 4271, 4760, 7454 + BIRD docs + `birdfmt`
**DOC-SYNC-09** | MUST | CIDR — https://pkg.go.dev/net/netip ; примеры — RFC 5737, 3849
+79 -74
View File
@@ -1,126 +1,131 @@
---
description: EvoBGP WebUI — shadcn-svelte, Svelte 5, слои ui/core|patterns|app
description: EvoBGP WebUI — React 19, shadcn/ui (base-nova), ReUI, TanStack Router/Query
globs:
- web/**
- apps/web/**
- packages/ui/**
alwaysApply: false
---
# Web UI — shadcn-svelte
# Web UI — React + shadcn/ui + ReUI
**Источник правды:** https://shadcn-svelte.com/docs (не React shadcn/ui, не Legacy Docs).
**Источники правды:**
- shadcn/ui React: https://ui.shadcn.com/docs/components
- ReUI Base UI: https://reui.io/docs/components/base/<name>
- ReUI llms.txt: https://reui.io/llms.txt
- MCP `plugin-shadcn-shadcn` (registries: `@shadcn`, `@reui`) — перед любой UI-задачей
Общие правила Go/API: `.cursor/rules/engineering.mdc`. Локальная карта: `web/README.md`.
Общие правила Go/API: `.cursor/rules/engineering.mdc`. Стек ID: `.cursor/rules/context7-stack.mdc`.
## Слои UI
| Слой | Путь | Назначение |
|------|------|------------|
| Примитивы | `src/lib/ui/core/` | shadcn-svelte (только CLI `add`) |
| Паттерны | `src/lib/ui/patterns/` | FormField, AppDataTable, ConfirmDialog, EmptyState |
| App chrome | `src/lib/ui/app/` | Layout, PageHeader, `notify` |
| Legacy | `src/lib/components/ui/` | Re-export; **не добавлять новые файлы** |
| shadcn-примитивы | `packages/ui/src/components/` | output `shadcn add` (не трогать под кейс) |
| ReUI enterprise | `apps/web/src/components/reui/` | output `shadcn add @reui/*` |
| Shared обёртки | `apps/web/src/components/` | PageHeader, QueryState, ConfirmDialog, StatusBadge, SectionCards, LoadingButton |
| Роуты | `apps/web/src/routes/` | TanStack Router (file-based) |
Тема: `src/routes/layout.css`, `src/lib/ui/app/tokens.md`. CLI из `web/`: `npx shadcn-svelte@latest add <component> -y -o`.
---
Тема: `packages/ui/src/styles/globals.css`. CLI из `apps/web`: `pnpm dlx shadcn@latest add <component>`.
## Правила
**WEB-01** | MUST | Перед новым UI — проверить https://shadcn-svelte.com/docs/components; использовать компонент, не HTML+CSS с нуля.
*Rationale:* Open Code + единый дизайн.
*Проверка:* review; нет голых `<button class=…>`.
**WEB-01** | MUST | Перед новым UI — MCP `plugin-shadcn-shadcn`: `search_items_in_registries` → `get_item_examples_from_registries` → `get_add_command_for_items`. Только после — JSX.
*Rationale:* единый источник правды и API.
*Проверка:* review; нет самописных примитивов, если есть registry item.
**WEB-02** | MUST | Отсутствующий примитив — `npx shadcn-svelte@latest add <component> -y -o` → `src/lib/ui/core/`.
*Rationale:* Distribution через CLI и `components.json`.
*Проверка:* файлы только в `ui/core`.
**WEB-02** | MUST | Отсутствующий shadcn-примитив — `pnpm dlx shadcn@latest add <component>` (из `apps/web`). ReUI — `pnpm dlx shadcn@latest add @reui/<name>`.
*Проверка:* файлы в `packages/ui/src/components/` (для shadcn) или `apps/web/src/components/reui/` (для ReUI).
**WEB-03** | NEVER | Альтернативные UI-kit'ы (Material, Vuetify, DaisyUI-only без shadcn-примитива).
*Проверка:* `package.json` review.
**WEB-03** | NEVER | Альтернативные UI-kit'ы (Material, Vuetify, Tabler, Bootstrap утилиты).
*Проверка:* `apps/web/package.json` review.
**WEB-04** | MUST | Комозиция по docs: все sub-компоненты (`DialogHeader`, `TableRow`, `Field`, …).
*Проверка:* сверка со страницей компонента в docs.
**WEB-04** | MUST | Композиция по docs: использовать под-компоненты (`CardHeader`, `TableRow`, `TabsList`, …).
*Проверка:* сверка с shadcn/ReUI docs.
**WEB-05** | MUST | Формы — Formsnap + `sveltekit-superforms`; UI в `ui/patterns/form`, не ad-hoc валидация на странице.
*Проверка:* https://shadcn-svelte.com/docs/components/form
**WEB-05** | MUST | Формы — `react-hook-form` + Zod; через `FormField`/`Form` обёртки.
*Проверка:* https://ui.shadcn.com/docs/components/form
**WEB-06** | MUST | Таблицы — Data Table + `@tanstack/table-core`; на страницах — `AppDataTable` из patterns.
*Проверка:* https://shadcn-svelte.com/docs/components/data-table
**WEB-06** | MUST | Сложные data-списки — ReUI `DataGridCard` (ReUI data-grid, не shadcn Data Table). Простые списки — shadcn `Table`.
*Проверка:* `@/components/reui/data-grid` или `@evobgp/ui/components/table`.
**WEB-07** | MUST | Toast — Sonner через `notify` из `ui/app/toast.js`.
*Проверка:* https://shadcn-svelte.com/docs/components/sonner
**WEB-07** | MUST | Toast — `sonner` (`Toaster` в `main.tsx`); `toast.success/error/message` из `sonner`.
*Проверка:* https://ui.shadcn.com/docs/components/sonner
**WEB-08** | MUST | Иконки — `@lucide/svelte` (`components.json` → `iconLibrary: lucide`).
*Проверка:* imports.
**WEB-08** | MUST | Иконки — `lucide-react` (`components.json` → `iconLibrary: lucide`).
*Проверка:* imports; нет `@tabler/icons-react`, `@lucide/svelte`.
**WEB-09** | MUST | Цвета — CSS-переменные `layout.css` и токены `tokens.md`; не hex/rgb на страницах.
*Проверка:* grep `#[0-9a-f]{3,6}` в `routes/`.
**WEB-09** | MUST | Цвета — CSS-переменные `globals.css` и ReUI semantic токены (`variant="success"/"info"/"warning"`); не hex/rgb на страницах.
*Проверка:* grep `#[0-9a-f]{3,6}` в `apps/web/src/routes/`.
**WEB-10** | SHOULD | Кастомизация — правка `ui/core` (Open Code), не `!important` поверх API.
**WEB-10** | SHOULD | Кастомизация — правка `packages/ui`/`reui` (Open Code), не `!important` поверх API.
**WEB-11** | MUST | `apps/web/src/routes/**` — композиция `@evobgp/ui/components/*` + `@/components/*` + `@/components/reui/*`; не копировать целые примитивы в route.
*Проверка:* review.
**WEB-11** | MUST | `routes/**` — композиция `ui/core` + `ui/patterns` + `ui/app`; не копировать целые примитивы shadcn в route.
**WEB-12** | NEVER | Примеры Svelte/SvelteKit, Tabler, Bootstrap — без адаптации под текущий React-стек.
*Проверка:* `pnpm --filter @evobgp/web run typecheck`.
**WEB-13** | MUST | Реактивность — React 19 (`useState`, `useEffect`, TanStack Query/Router хуки); не Svelte runes, не `export let`.
*Проверка:* `pnpm --filter @evobgp/web run typecheck`.
**WEB-14** | SHOULD | Нетривиальный UI — прочитать страницу компонента shadcn/ReUI (props, a11y).
**WEB-15** | MUST | Сомнения — MCP `plugin-shadcn-shadcn` + shadcn CLI docs + `pnpm --filter @evobgp/web run typecheck`.
**WEB-16** | MUST | Подтверждение удаления — `ConfirmDialog` из `@/components/confirm-dialog`, не `window.confirm`.
**WEB-17** | MUST | Пустые списки — `EmptyState` или через `QueryState` с `emptyTitle`.
*Проверка:* review.
**WEB-12** | NEVER | Примеры React shadcn/ui или Svelte 4 Legacy без адаптации под https://shadcn-svelte.com/docs/migration/svelte-5
*Проверка:* `npm run check`.
**WEB-18** | SHOULD | Повторяемая комбинация core (≥2 раза) — вынести в `apps/web/src/components/`.
**WEB-13** | MUST | Реактивность — Svelte 5 runes (`$state`, `$derived`, `$effect`); не `export let` для локального state страниц.
*Проверка:* `npm run check`; Svelte MCP.
**WEB-14** | SHOULD | Нетривиальный UI — прочитать страницу компонента (props, a11y).
*Проверка:* PR description.
**WEB-15** | MUST | Сомнения — https://shadcn-svelte.com/llms.txt , Svelte MCP, `npm run check`.
*Проверка:* локально.
**WEB-19** | MUST | **После любого изменения `web/**`** — перед завершением задачи агент **обязан** выполнить в `web/`:
**WEB-19** | MUST | **После любого изменения `apps/web/**` или `packages/ui/**`** — перед завершением задачи агент **обязан**:
```powershell
npm run check
npm run lint
pnpm --filter @evobgp/web run typecheck
pnpm --filter @evobgp/web run lint
pnpm --filter @evobgp/web run build
```
Если `npm run lint` падает (Prettier) — **сначала** `npx prettier --write <изменённые файлы>` или `npx prettier --write .`, затем снова `npm run check` и `npm run lint`. Не сдавать PR/ответ, пока обе команды не exit 0.
*Rationale:* CI job `web` = `check` + `prettier --check`; `svelte-check` не ловит форматирование.
*Проверка:* CI job `web`; pre-commit hook `prettier-web`.
Все три команды должны exit 0. Не сдавать PR/ответ, пока все три не пройдут.
*Rationale:* CI job `web` = typecheck + lint + build.
*Проверка:* CI job `web`.
**WEB-16** | MUST | Подтверждение удаления — `ConfirmDialog` из patterns, не `window.confirm`.
*Проверка:* review.
**WEB-20** | MUST | Роутинг — TanStack Router (file-based `apps/web/src/routes/`); типобезопасные `createFileRoute`, `useSearch`, `Link`. Не `react-router-dom`.
*Проверка:* `tsr generate` в `build`/`typecheck` скриптах.
**WEB-17** | MUST | Пустые списки — `EmptyState` из patterns.
*Проверка:* review.
**WEB-21** | MUST | Data fetching — TanStack Query (`useQuery`, `useMutation`, `queryOptions`); query-key factories в `apps/web/src/queries/`. Mutations invalidate keys, не refetch вручную.
*Проверка:* review `queries/*.ts`.
**WEB-18** | SHOULD | Повторяемая комбинация core (≥2 раза) — вынести в `ui/patterns/`.
*Проверка:* review.
**WEB-22** | MUST | Legacy Svelte — в `web-legacy-svelte/` (archive). Не использовать импорты оттуда в новом коде; только как референс при миграции роутов.
---
## Documentation Sync (Web)
**DOC-SYNC-06** | MUST | UI — первично https://shadcn-svelte.com/docs; при конфликте с блогами/Stack Overflow побеждает официальная страница компонента.
**DOC-SYNC-07** | MUST | Перед `add` — сверить Installation/Theming с `web/components.json` и `src/routes/layout.css`.
**DOC-SYNC-06** | MUST | UI — первично MCP + shadcn/ui docs (React) + ReUI docs (Base UI); при конфликте с блогами/Stack Overflow побеждает официальная страница.
**DOC-SYNC-07** | MUST | Перед `add` — сверить Installation/Theming с `apps/web/components.json`, `packages/ui/components.json` и `packages/ui/src/styles/globals.css`.
Tailwind v4: https://shadcn-svelte.com/docs/migration/tailwind-v4
Tailwind v4 + base-nova: https://ui.shadcn.com/docs/migration/tailwind-v4
ReUI semantic tokens: https://reui.io/docs/styling
---
## Enforcement
**Обязательный финальный шаг агента при правках `web/**`:** `npm run check` **и** `npm run lint` (см. **WEB-19**). Только `check` недостаточно.
**Обязательный финальный шаг агента при правках `apps/web/**` или `packages/ui/**`** (см. **WEB-19**):
```powershell
cd web
npm run check
npm run lint
# при warn/fail lint:
npx prettier --write .
npm run check
npm run lint
pnpm --filter @evobgp/web run typecheck
pnpm --filter @evobgp/web run lint
pnpm --filter @evobgp/web run build
```
**PR checklist `web/**`:**
- [ ] `npm run check` — exit 0
- [ ] `npm run lint` (prettier --check) — exit 0
- [ ] `ui/core` / `ui/patterns`, не дубли примитивов
- [ ] Новые примитивы через shadcn CLI
**PR checklist `apps/web/**` / `packages/ui/**`:**
- [ ] `pnpm --filter @evobgp/web run typecheck` — exit 0
- [ ] `pnpm --filter @evobgp/web run lint` — exit 0
- [ ] `pnpm --filter @evobgp/web run build` — exit 0
- [ ] shadcn-примитивы в `packages/ui/src/components/`, ReUI в `apps/web/src/components/reui/`
- [ ] Новые примитивы через shadcn CLI (`@shadcn` или `@reui`)
- [ ] Импорты: `@evobgp/ui/components/*` для shadcn, `@/components/reui/*` для ReUI
- [ ] Ссылка на docs компонента (если новый паттерн)
**CI:** job `web` — `npm run check` + `npm run lint`.
**CI:** job `web` — `typecheck` + `lint` + `build`.
+13 -1
View File
@@ -1,7 +1,19 @@
{
"plugins": {
"svelte": {
"shadcn": {
"enabled": true
},
"context7-plugin": {
"enabled": true
},
"claude-plugins-official/gopls-lsp": {
"enabled": true
},
"claude-plugins-official/typescript-lsp": {
"enabled": true
},
"svelte": {
"enabled": false
}
}
}
+34
View File
@@ -0,0 +1,34 @@
---
name: context7-evobgp
description: Context7 lookup для стека EvoBGP — использовать закреплённые library ID из .cursor/rules/context7-stack.mdc вместо resolve-library-id.
---
# Context7 — EvoBGP stack
Перед `query-docs` открой `.cursor/rules/context7-stack.mdc` и выбери ID из таблицы по области задачи.
## Workflow
1. Определи область: `internal/` (Go), `apps/web/` + `packages/ui/` (React + shadcn/ui + ReUI), `docs/openapi.yaml`, `birdfmt`/`pipeline` (BIRD), `deploy/compose` (Docker).
2. Найди строку в таблице `context7-stack.mdc`.
3. Вызови `query-docs` с `libraryId` из таблицы и полным вопросом пользователя.
4. `resolve-library-id` — только если библиотеки нет в таблице или нужна другая major-версия.
## Быстрые ID (частые)
| Задача | libraryId |
|--------|-----------|
| React 19 hooks | `/facebook/react` |
| TanStack Router | `/tanstack/router` |
| TanStack Query | `/tanstack/query` |
| shadcn/ui (React) | MCP `plugin-shadcn-shadcn` + https://ui.shadcn.com/docs |
| ReUI Base UI | https://reui.io/llms.txt + MCP с `registries: ["@reui"]` |
| pgx pool/query | `/websites/pkg_go_dev_github_com_jackc_pgx_v5` |
| Go net/http | `/golang/go/go1_24_6` |
| OpenAPI lint | `/redocly/redocly-cli` |
| BIRD config | `/llmstxt/bird_xmsl_dev_llms_txt` |
| Tailwind v4 | `/tailwindlabs/tailwindcss.com` |
| Zod schema | `/websites/zod_dev_v4` |
| recharts | `/recharts/recharts` |
Полный список и версии — в `context7-stack.mdc`.
+12
View File
@@ -0,0 +1,12 @@
{
"mcpServers": {
"codegraph": {
"type": "stdio",
"command": "codegraph",
"args": [
"serve",
"--mcp"
]
}
}
}
+13 -11
View File
@@ -98,9 +98,9 @@ jobs:
openapi=true
go=true
;;
web/README.md|web/components.json)
apps/web/README.md|apps/web/components.json|packages/ui/components.json)
;;
web/*)
apps/web/*|packages/ui/*|packages/shared/*)
web=true
;;
deploy/bird/*)
@@ -126,7 +126,7 @@ jobs:
docs/*)
go=true
;;
package.json|package-lock.json|.releaserc.json)
package.json|package-lock.json|pnpm-lock.yaml|pnpm-workspace.yaml|.releaserc.json)
full_pipeline=true
;;
*)
@@ -169,16 +169,16 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: "20"
cache: npm
cache-dependency-path: web/package-lock.json
- name: npm ci, check, lint
node-version: "22"
- name: Enable pnpm via corepack
run: corepack enable
- name: pnpm install, typecheck, lint, build
run: |
set -euxo pipefail
cd web
npm ci
npm run check
npm run lint
pnpm install --frozen-lockfile
pnpm --filter @evobgp/web run typecheck
pnpm --filter @evobgp/web run lint
pnpm --filter @evobgp/web run build
# ---------------------------------------------------------------------------
go:
@@ -303,6 +303,8 @@ jobs:
cache-dependency-path: package-lock.json
- name: Install release tooling
run: npm ci
- name: Verify releasable commit messages
run: node scripts/commit/verify-release-commits.mjs
- name: Semantic release
run: npx semantic-release
env:
+11 -1
View File
@@ -1,6 +1,13 @@
# Root npm (semantic-release, commitlint) — npm ci in CI, never commit deps
# Root npm/pnpm (semantic-release, commitlint, workspaces) — never commit deps
node_modules/
# Vite / TS build output
apps/web/dist/
packages/*/dist/
# TanStack Router auto-generated route tree
apps/web/src/routeTree.gen.ts
# Generated by deploy/docker/write-bake-override.sh (CI/local bake)
deploy/docker/docker-bake.override.hcl
@@ -17,3 +24,6 @@ Thumbs.db
.env.*
!.env.example
!.env.*.example
# Compose runtime log sidecar output (deploy/compose/runtime-logs)
deploy/compose/runtime-logs/
+12
View File
@@ -0,0 +1,12 @@
{
"mcpServers": {
"codegraph": {
"type": "stdio",
"command": "codegraph",
"args": [
"serve",
"--mcp"
]
}
}
}
View File
+1
View File
@@ -0,0 +1 @@
22
+12 -8
View File
@@ -4,10 +4,10 @@
## С чего начать (минимум чтения)
0. **Инженерные правила** — при изменении кода следовать [.cursor/rules/engineering.mdc](.cursor/rules/engineering.mdc); для `web/` — [.cursor/rules/web-shadcn.mdc](.cursor/rules/web-shadcn.mdc); для `birdfmt` / `pipeline` / BIRD — [.cursor/rules/networking-bird.mdc](.cursor/rules/networking-bird.mdc).
0. **Инженерные правила** — при изменении кода следовать [.cursor/rules/engineering.mdc](.cursor/rules/engineering.mdc); для `apps/web/` + `packages/ui/` — [.cursor/rules/web-shadcn.mdc](.cursor/rules/web-shadcn.mdc); для `birdfmt` / `pipeline` / BIRD — [.cursor/rules/networking-bird.mdc](.cursor/rules/networking-bird.mdc). **Context7 (документация библиотек)** — закреплённые ID стека: [.cursor/rules/context7-stack.mdc](.cursor/rules/context7-stack.mdc); скилл [.cursor/skills/context7-evobgp/SKILL.md](.cursor/skills/context7-evobgp/SKILL.md).
1. **[docs/README.md](docs/README.md)** — оглавление и роли читателя.
2. **[docs/architecture.md](docs/architecture.md)** — компоненты `cmd/`, карта `internal/`, потоки данных (одного этого файла обычно достаточно для ориентации).
3. Задача-специфично: [docs/api.md](docs/api.md), [docs/access.md](docs/access.md), [web/README.md](web/README.md) — только если меняете API, доступ или фронт.
3. Задача-специфично: [docs/api.md](docs/api.md), [docs/access.md](docs/access.md) — только если меняете API или доступ.
Источник правды по HTTP-контракту: **[docs/openapi.yaml](docs/openapi.yaml)**. Не дублируйте длинные фрагменты спецификации в ответах — ссылайтесь на путь и тег/операцию.
@@ -57,14 +57,18 @@
Пользовательская документация в `docs/` — преимущественно на русском. Комментарии и имена в коде — в существующем стиле репозитория.
## Svelte / фронтенд
## Frontend (React + shadcn/ui + ReUI)
При правках `web/**/*.svelte` или Svelte-модулей следуйте [.cursor/rules/web-shadcn.mdc](.cursor/rules/web-shadcn.mdc) (**WEB-19**): перед завершением задачи **обязательно**:
При правках `apps/web/**` или `packages/ui/**` следуйте [.cursor/rules/web-shadcn.mdc](.cursor/rules/web-shadcn.mdc) (**WEB-19**): перед завершением задачи **обязательно**:
```powershell
cd web
npm run check
npm run lint
pnpm --filter @evobgp/web run typecheck
pnpm --filter @evobgp/web run lint
pnpm --filter @evobgp/web run build
```
Если `lint` падает — `npx prettier --write .` и повторить обе команды. CI job `web` не пропускает без этого.
Все три команды должны exit 0. CI job `web` не пропускает без этого.
Стек: React 19, TanStack Router/Query, shadcn/ui (base-nova, registry `@shadcn` + `@reui`), Tailwind v4, lucide-react. Legacy Svelte — в `web-legacy-svelte/` (архив, только референс при миграции).
UI-задачи начинаются с MCP `plugin-shadcn-shadcn` (search → examples → add command), затем CLI `pnpm dlx shadcn@latest add ...` из `apps/web`. См. также [.cursor/rules/context7-stack.mdc](.cursor/rules/context7-stack.mdc) для Context7 ID стека.
+23
View File
@@ -0,0 +1,23 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "base-nova",
"rsc": false,
"tsx": true,
"tailwind": {
"config": "",
"css": "../../packages/ui/src/styles/globals.css",
"baseColor": "neutral",
"cssVariables": true
},
"iconLibrary": "lucide",
"registries": {
"@reui": "https://reui.io/r/{style}/{name}.json"
},
"aliases": {
"components": "@/components",
"hooks": "@/hooks",
"lib": "@/lib",
"utils": "@evobgp/ui/lib/utils",
"ui": "@evobgp/ui/components"
}
}
+36
View File
@@ -0,0 +1,36 @@
import js from '@eslint/js'
import tseslint from 'typescript-eslint'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import globals from 'globals'
export default tseslint.config(
{ ignores: ['dist', 'src/routeTree.gen.ts'] },
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ['**/*.{ts,tsx}'],
languageOptions: {
ecmaVersion: 2022,
globals: globals.browser,
},
plugins: {
'react-hooks': reactHooks,
'react-refresh': reactRefresh,
},
rules: {
...reactHooks.configs.recommended.rules,
'react-refresh/only-export-components': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-unused-expressions': 'off',
'@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_' }],
'prefer-const': 'off',
},
},
{
files: ['src/components/reui/**/*.{ts,tsx}'],
rules: {
'@typescript-eslint/no-unused-vars': 'off',
'react-hooks/exhaustive-deps': 'off',
},
},
)
+23
View File
@@ -0,0 +1,23 @@
<!doctype html>
<html lang="ru" class="">
<head>
<meta charset="UTF-8" />
<link rel="icon" href="/favicon.svg" type="image/svg+xml" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="color-scheme" content="light dark" />
<title>EvoBGP</title>
<script>
// Anti-FOUC: apply persisted theme before paint (matches next-themes attribute="class")
try {
var t = localStorage.getItem('evobgp-theme');
var m = window.matchMedia('(prefers-color-scheme: dark)').matches;
var dark = t === 'dark' || (!t || t === 'system') && m;
if (dark) document.documentElement.classList.add('dark');
} catch (e) {}
</script>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+62
View File
@@ -0,0 +1,62 @@
{
"name": "@evobgp/web",
"private": true,
"version": "0.0.1",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsr generate && tsc -b && vite build",
"preview": "vite preview",
"typecheck": "tsr generate && tsc --noEmit",
"lint": "eslint .",
"test": "vitest run"
},
"dependencies": {
"@base-ui/react": "^1.0.0",
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/modifiers": "^9.0.0",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@evobgp/ui": "workspace:*",
"@hookform/resolvers": "^3.10.0",
"@tanstack/react-query": "^5.90.2",
"@tanstack/react-query-devtools": "^5.90.2",
"@tanstack/react-router": "^1.130.2",
"@tanstack/react-router-devtools": "^1.130.2",
"@tanstack/react-table": "^8.21.3",
"@tanstack/react-virtual": "^3.14.4",
"class-variance-authority": "^0.7.1",
"cmdk": "^1.1.1",
"date-fns": "^4.4.0",
"input-otp": "^1.4.2",
"lucide-react": "^0.468.0",
"next-themes": "^0.4.6",
"react": "^19.2.0",
"react-day-picker": "^10.0.1",
"react-dom": "^19.2.0",
"react-hook-form": "^7.60.0",
"recharts": "3.8.0",
"sonner": "^1.7.0",
"zod": "^3.25.0"
},
"devDependencies": {
"@tailwindcss/vite": "^4.1.0",
"@tanstack/router-plugin": "^1.130.0",
"@tanstack/router-cli": "^1.130.0",
"@types/react": "^19.2.7",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^5.1.1",
"eslint": "^9.0.0",
"@eslint/js": "^9.0.0",
"eslint-plugin-react-hooks": "^5.0.0",
"eslint-plugin-react-refresh": "^0.4.0",
"globals": "^15.0.0",
"typescript-eslint": "^8.0.0",
"happy-dom": "^18.0.0",
"tailwindcss": "^4.1.0",
"tw-animate-css": "^1.0.0",
"typescript": "^5.9.2",
"vite": "^7.3.1",
"vitest": "^3.0.0"
}
}
+4
View File
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
<rect width="32" height="32" rx="7" fill="#0f172a"/>
<text x="16" y="22" font-family="ui-sans-serif,system-ui,sans-serif" font-size="18" font-weight="700" fill="#f8fafc" text-anchor="middle">B</text>
</svg>

After

Width:  |  Height:  |  Size: 272 B

@@ -0,0 +1,190 @@
import { useState } from 'react'
import { Plus, RefreshCw, Trash2 } from 'lucide-react'
import { Button } from '@evobgp/ui/components/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@evobgp/ui/components/card'
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@evobgp/ui/components/table'
import { ApiKeyCreateDialog } from '@/components/access/api-key-create-dialog'
import { ApiKeyTokenDialog } from '@/components/access/api-key-token-dialog'
import { Badge } from '@/components/reui/badge'
import { ConfirmDialog } from '@/components/confirm-dialog'
import { QueryState } from '@/components/query-state'
import { StatusBadge } from '@/components/status-badge'
import { TableSkeleton } from '@/components/skeletons'
import { formatApiKeyDate } from '@/lib/access/api-key-labels'
import { useRevokeApiKeyMutation, useRotateApiKeyMutation } from '@/queries/api-keys'
import type { ApiKey, ApiKeyCreated } from '@/types/api'
interface AccessApiKeysCardProps {
items: ApiKey[]
isLoading: boolean
isError: boolean
error: unknown
onRetry: () => void
}
export function AccessApiKeysCard({
items,
isLoading,
isError,
error,
onRetry,
}: AccessApiKeysCardProps) {
const [createOpen, setCreateOpen] = useState(false)
const [tokenDialogOpen, setTokenDialogOpen] = useState(false)
const [revealedToken, setRevealedToken] = useState('')
const revoke = useRevokeApiKeyMutation()
const rotate = useRotateApiKeyMutation()
function showToken(created: ApiKeyCreated) {
setRevealedToken(created.token)
setTokenDialogOpen(true)
}
function handleRotated(id: string) {
rotate.mutate(id, {
onSuccess: (created) => showToken(created),
})
}
return (
<>
<Card>
<CardHeader className="flex flex-col gap-3 border-b py-3 sm:flex-row sm:items-center sm:justify-between">
<div className="min-w-0 flex-1">
<CardTitle className="text-base">API-ключи</CardTitle>
<CardDescription>
Управление ключами tenant. Полный токен показывается только при создании и ротации.
</CardDescription>
</div>
<div className="flex shrink-0 flex-wrap items-center justify-end gap-2">
<Button size="sm" variant="outline" onClick={onRetry} disabled={isLoading}>
<RefreshCw className={isLoading ? 'animate-spin' : ''} />
Обновить
</Button>
<Button size="sm" onClick={() => setCreateOpen(true)}>
<Plus />
Создать
</Button>
</div>
</CardHeader>
<CardContent className="p-0">
<QueryState
data={items}
isLoading={isLoading}
isError={isError}
error={error}
empty={items.length === 0}
emptyTitle="Нет ключей"
emptyDescription="Создайте API-ключ для автоматизации или отдельного доступа."
skeleton={<TableSkeleton rows={4} cols={6} />}
onRetry={onRetry}
>
{(data) => (
<Table>
<TableHeader>
<TableRow>
<TableHead>Имя</TableHead>
<TableHead>Роль</TableHead>
<TableHead>Префикс</TableHead>
<TableHead>Статус</TableHead>
<TableHead>Истекает</TableHead>
<TableHead>Последнее использование</TableHead>
<TableHead className="w-24" />
</TableRow>
</TableHeader>
<TableBody>
{data.map((k) => (
<TableRow key={k.id}>
<TableCell className="font-medium">{k.name}</TableCell>
<TableCell>
<Badge variant="outline" className="font-mono text-xs">
{k.role}
</Badge>
</TableCell>
<TableCell className="font-mono text-xs text-muted-foreground">
{k.prefix}
</TableCell>
<TableCell>
{k.revoked_at ? (
<StatusBadge status="error" label="отозван" />
) : (
<StatusBadge status="active" label="активен" />
)}
</TableCell>
<TableCell className="text-sm text-muted-foreground">
{formatApiKeyDate(k.expires_at)}
</TableCell>
<TableCell className="text-sm text-muted-foreground">
{formatApiKeyDate(k.last_used_at)}
</TableCell>
<TableCell>
<div className="flex gap-1">
<ConfirmDialog
trigger={
<Button
variant="ghost"
size="icon-sm"
title="Ротировать"
disabled={!!k.revoked_at || rotate.isPending}
>
<RefreshCw className="size-3.5" />
</Button>
}
title="Ротировать ключ?"
description="Старый токен перестанет работать сразу."
confirmLabel="Ротировать"
onConfirm={() => handleRotated(k.id)}
/>
<ConfirmDialog
trigger={
<Button
variant="ghost"
size="icon-sm"
className="text-destructive"
disabled={!!k.revoked_at || revoke.isPending}
title="Отозвать"
>
<Trash2 className="size-3.5" />
</Button>
}
title="Отозвать API-ключ?"
description={`${k.name} (${k.prefix}…)`}
confirmLabel="Отозвать"
destructive
onConfirm={() => revoke.mutate(k.id)}
/>
</div>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</QueryState>
</CardContent>
</Card>
<ApiKeyCreateDialog
open={createOpen}
onOpenChange={setCreateOpen}
onCreated={showToken}
/>
<ApiKeyTokenDialog
open={tokenDialogOpen}
token={revealedToken}
onOpenChange={setTokenDialogOpen}
/>
</>
)
}
@@ -0,0 +1,132 @@
import { useEffect, useState } from 'react'
import { toast } from 'sonner'
import { Button } from '@evobgp/ui/components/button'
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@evobgp/ui/components/dialog'
import { Input } from '@evobgp/ui/components/input'
import { Label } from '@evobgp/ui/components/label'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@evobgp/ui/components/select'
import { LoadingButton } from '@/components/loading-button'
import { API_KEY_ROLE_ITEMS } from '@/lib/access/api-key-labels'
import { useCreateApiKeyMutation } from '@/queries/api-keys'
import type { ApiKeyCreate, ApiKeyCreated, ApiKeyRole } from '@/types/api'
interface ApiKeyCreateDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
onCreated: (created: ApiKeyCreated) => void
}
export function ApiKeyCreateDialog({ open, onOpenChange, onCreated }: ApiKeyCreateDialogProps) {
const createMutation = useCreateApiKeyMutation()
const [name, setName] = useState('')
const [role, setRole] = useState<ApiKeyRole>('editor')
const [expiresLocal, setExpiresLocal] = useState('')
useEffect(() => {
if (!open) return
setName('')
setRole('editor')
setExpiresLocal('')
}, [open])
function handleOpenChange(next: boolean) {
onOpenChange(next)
}
async function save() {
if (!name.trim()) {
toast.error('Укажите имя')
return
}
const body: ApiKeyCreate = {
name: name.trim(),
role,
}
if (expiresLocal.trim()) {
const d = new Date(expiresLocal)
if (Number.isNaN(d.getTime())) {
toast.error('Некорректная дата истечения')
return
}
body.expires_at = d.toISOString()
}
try {
const created = await createMutation.mutateAsync(body)
onOpenChange(false)
onCreated(created)
} catch {
// toast handled in mutation
}
}
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent className="sm:max-w-sm">
<DialogHeader>
<DialogTitle>Новый API-ключ</DialogTitle>
</DialogHeader>
<div className="flex flex-col gap-4 py-2">
<div className="flex flex-col gap-2">
<Label htmlFor="key-name">Имя</Label>
<Input
id="key-name"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="CI / оператор UI"
/>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="key-role">Роль</Label>
<Select
items={[...API_KEY_ROLE_ITEMS]}
value={role}
onValueChange={(v) => v && setRole(v as ApiKeyRole)}
>
<SelectTrigger id="key-role" className="w-full">
<SelectValue placeholder="Выберите роль" />
</SelectTrigger>
<SelectContent>
{API_KEY_ROLE_ITEMS.map((opt) => (
<SelectItem key={opt.value} value={opt.value}>
{opt.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="key-expires">Истекает (опционально)</Label>
<Input
id="key-expires"
type="datetime-local"
value={expiresLocal}
onChange={(e) => setExpiresLocal(e.target.value)}
/>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => handleOpenChange(false)}>
Отмена
</Button>
<LoadingButton onClick={save} loading={createMutation.isPending}>
Создать
</LoadingButton>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,51 @@
import { Copy } from 'lucide-react'
import { toast } from 'sonner'
import { Button } from '@evobgp/ui/components/button'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@evobgp/ui/components/dialog'
interface ApiKeyTokenDialogProps {
open: boolean
token: string
onOpenChange: (open: boolean) => void
}
export function ApiKeyTokenDialog({ open, token, onOpenChange }: ApiKeyTokenDialogProps) {
async function copyToken() {
if (!token) return
try {
await navigator.clipboard.writeText(token)
toast.success('Скопировано')
} catch {
toast.error('Не удалось скопировать')
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>Сохраните токен</DialogTitle>
<DialogDescription>
Он больше не будет показан. Скопируйте в безопасное хранилище.
</DialogDescription>
</DialogHeader>
<div className="break-all rounded-md border bg-muted/40 p-3 font-mono text-xs">{token}</div>
<DialogFooter>
<Button variant="outline" onClick={copyToken}>
<Copy />
Копировать
</Button>
<Button onClick={() => onOpenChange(false)}>Готово</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,53 @@
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from '@evobgp/ui/components/alert-dialog'
import type { ReactElement, ReactNode } from 'react'
interface ConfirmDialogProps {
trigger: ReactElement
title: string
description?: ReactNode
confirmLabel?: string
cancelLabel?: string
destructive?: boolean
onConfirm: () => void
}
export function ConfirmDialog({
trigger,
title,
description,
confirmLabel = 'Подтвердить',
cancelLabel = 'Отмена',
destructive,
onConfirm,
}: ConfirmDialogProps) {
return (
<AlertDialog>
<AlertDialogTrigger render={trigger} />
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{title}</AlertDialogTitle>
{description ? <AlertDialogDescription>{description}</AlertDialogDescription> : null}
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{cancelLabel}</AlertDialogCancel>
<AlertDialogAction
variant={destructive ? 'destructive' : 'default'}
onClick={onConfirm}
>
{confirmLabel}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
)
}
+28
View File
@@ -0,0 +1,28 @@
import type { ReactNode } from 'react'
import { cn } from '@evobgp/ui/lib/utils'
interface EmptyStateProps {
title: string
description?: string
icon?: ReactNode
action?: ReactNode
className?: string
}
export function EmptyState({ title, description, icon, action, className }: EmptyStateProps) {
return (
<div
className={cn(
'flex flex-col items-center justify-center gap-3 rounded-lg border border-dashed p-8 text-center',
className,
)}
>
{icon ? <div className="text-muted-foreground">{icon}</div> : null}
<div className="flex flex-col gap-1">
<p className="text-sm font-medium">{title}</p>
{description ? <p className="text-sm text-muted-foreground">{description}</p> : null}
</div>
{action ? <div className="mt-2">{action}</div> : null}
</div>
)
}
@@ -0,0 +1,215 @@
import {
ColumnDef,
getCoreRowModel,
getPaginationRowModel,
getSortedRowModel,
useReactTable,
} from '@tanstack/react-table'
import { useMemo } from 'react'
import { Button } from '@evobgp/ui/components/button'
import { ConfirmDialog } from '@/components/confirm-dialog'
import { StatusBadge } from '@/components/status-badge'
import { DataGridColumnHeader } from '@/components/reui/data-grid/data-grid-column-header'
import { DataGridPagination } from '@/components/reui/data-grid/data-grid-pagination'
import { DataGrid, DataGridContainer } from '@/components/reui/data-grid/data-grid'
import { DataGridTable } from '@/components/reui/data-grid/data-grid-table'
import type { FirewallClient } from '@/types/api'
function formatPacketCount(value?: number | null): string | null {
if (value == null || value <= 0) return null
if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}M`
if (value >= 1_000) return `${(value / 1_000).toFixed(1)}k`
return String(value)
}
export interface FirewallClientsGridProps {
clients: FirewallClient[]
isLoading?: boolean
onApprove: (id: string) => void
onReject: (id: string) => void
approvePending?: boolean
rejectPending?: boolean
emptyTitle?: string
}
export function FirewallClientsGrid({
clients,
isLoading = false,
onApprove,
onReject,
approvePending = false,
rejectPending = false,
emptyTitle = 'Нет клиентов',
}: FirewallClientsGridProps) {
const columns = useMemo<ColumnDef<FirewallClient>[]>(
() => [
{
accessorKey: 'name',
header: ({ column }) => <DataGridColumnHeader column={column} title="Имя" />,
cell: ({ row }) => (
<div>
<div className="font-medium">{row.original.name}</div>
<div className="text-muted-foreground text-xs">
{row.original.hostname || row.original.token_prefix}
</div>
</div>
),
meta: { headerTitle: 'Имя' },
},
{
accessorKey: 'status',
header: ({ column }) => <DataGridColumnHeader column={column} title="Статус" />,
cell: ({ row }) => <StatusBadge status={row.original.status} />,
meta: { headerTitle: 'Статус' },
},
{
id: 'last_seen_at',
accessorFn: (row) => row.last_seen_at ?? '',
header: ({ column }) => <DataGridColumnHeader column={column} title="Last seen" />,
cell: ({ row }) => (
<span className="text-xs">{row.original.last_seen_at?.slice(0, 19) ?? '—'}</span>
),
sortingFn: (a, b) => {
const av = a.original.last_seen_at ?? ''
const bv = b.original.last_seen_at ?? ''
return av.localeCompare(bv)
},
meta: { headerTitle: 'Last seen' },
},
{
id: 'apply',
enableSorting: false,
header: 'Apply',
cell: ({ row }) => {
const c = row.original
return (
<span className="text-xs">
{c.last_apply_status ?? '—'}
{c.last_apply_prefix_count != null ? ` (${c.last_apply_prefix_count})` : ''}
</span>
)
},
meta: { headerTitle: 'Apply' },
},
{
id: 'packets',
enableSorting: false,
header: 'Пакеты',
cell: ({ row }) => {
const dropped = formatPacketCount(row.original.last_apply_packets_dropped)
const accepted = formatPacketCount(row.original.last_apply_packets_accepted)
if (!dropped && !accepted) {
return <span className="text-muted-foreground text-xs"></span>
}
return (
<span className="text-muted-foreground text-xs">
{dropped ? <span className="text-destructive">{dropped}</span> : null}
{dropped && accepted ? ' · ' : null}
{accepted ? <span className="text-success">{accepted}</span> : null}
</span>
)
},
meta: { headerTitle: 'Пакеты' },
},
{
id: 'actions',
enableSorting: false,
header: () => null,
cell: ({ row }) => {
const c = row.original
return (
<div className="flex justify-end gap-2">
{c.status === 'pending' ? (
<>
<Button
size="sm"
variant="outline"
type="button"
disabled={approvePending}
onClick={() => onApprove(c.id)}
>
Одобрить
</Button>
<ConfirmDialog
trigger={
<Button
size="sm"
variant="outline"
type="button"
className="text-destructive"
disabled={rejectPending}
>
Отклонить
</Button>
}
title="Отклонить запрос?"
description={`${c.name}${c.hostname ? ` (${c.hostname})` : ''} — запись будет удалена, токен перестанет работать.`}
confirmLabel="Отклонить"
destructive
onConfirm={() => onReject(c.id)}
/>
</>
) : null}
{c.status === 'approved' ? (
<ConfirmDialog
trigger={
<Button
size="sm"
variant="ghost"
type="button"
className="text-destructive"
disabled={rejectPending}
>
Удалить
</Button>
}
title="Удалить клиент?"
description={`${c.name} — запись будет удалена, blocklist и токен перестанут работать.`}
confirmLabel="Удалить"
destructive
onConfirm={() => onReject(c.id)}
/>
) : null}
</div>
)
},
},
],
[approvePending, onApprove, onReject, rejectPending],
)
const table = useReactTable({
data: clients,
columns,
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(),
getPaginationRowModel: getPaginationRowModel(),
getRowId: (row) => row.id,
initialState: { pagination: { pageSize: 10 } },
})
return (
<DataGrid
table={table}
recordCount={clients.length}
isLoading={isLoading}
emptyMessage={emptyTitle}
tableLayout={{ headerSticky: true, dense: true }}
>
<DataGridContainer>
<DataGridTable />
</DataGridContainer>
<DataGridPagination
sizes={[10, 25, 50]}
sizesLabel="Показать"
sizesDescription="на странице"
info="{from}{to} из {count}"
rowsPerPageLabel="Строк на странице"
previousPageLabel="Предыдущая страница"
nextPageLabel="Следующая страница"
/>
</DataGrid>
)
}
@@ -0,0 +1,142 @@
import {
ColumnDef,
getCoreRowModel,
getPaginationRowModel,
getSortedRowModel,
useReactTable,
} from '@tanstack/react-table'
import { useMemo } from 'react'
import { Button } from '@evobgp/ui/components/button'
import { ConfirmDialog } from '@/components/confirm-dialog'
import { StatusBadge } from '@/components/status-badge'
import { DataGridColumnHeader } from '@/components/reui/data-grid/data-grid-column-header'
import { DataGridPagination } from '@/components/reui/data-grid/data-grid-pagination'
import { DataGrid, DataGridContainer } from '@/components/reui/data-grid/data-grid'
import { DataGridTable } from '@/components/reui/data-grid/data-grid-table'
import { communityLabel } from '@/lib/modules/helpers'
import type { BgpCommunity, FirewallRule } from '@/types/api'
export interface FirewallRulesGridProps {
rules: FirewallRule[]
communities: BgpCommunity[]
isLoading?: boolean
onDelete: (id: string) => void
deletePending?: boolean
emptyTitle?: string
}
export function FirewallRulesGrid({
rules,
communities,
isLoading = false,
onDelete,
deletePending = false,
emptyTitle = 'Нет правил — blocklist пуст (default accept).',
}: FirewallRulesGridProps) {
const columns = useMemo<ColumnDef<FirewallRule>[]>(
() => [
{
accessorKey: 'priority',
header: ({ column }) => <DataGridColumnHeader column={column} title="#" />,
cell: ({ row }) => row.original.priority,
meta: { headerTitle: '#' },
},
{
accessorKey: 'action',
header: ({ column }) => <DataGridColumnHeader column={column} title="Действие" />,
cell: ({ row }) => (
<StatusBadge status={row.original.action} label={row.original.action} />
),
meta: { headerTitle: 'Действие' },
},
{
id: 'community',
enableSorting: false,
header: 'Community',
cell: ({ row }) => (
<span className="text-sm">
{row.original.community_id
? communityLabel(row.original.community_id, communities)
: 'Все'}
</span>
),
meta: { headerTitle: 'Community' },
},
{
accessorKey: 'comment',
enableSorting: false,
header: 'Комментарий',
cell: ({ row }) => row.original.comment || '—',
meta: { headerTitle: 'Комментарий' },
},
{
id: 'actions',
enableSorting: false,
header: () => null,
cell: ({ row }) => {
const r = row.original
return (
<ConfirmDialog
trigger={
<Button
size="sm"
variant="ghost"
type="button"
className="text-destructive"
disabled={deletePending}
>
Удалить
</Button>
}
title="Удалить правило?"
description={
r.comment
? `Правило #${r.priority} (${r.action}): ${r.comment}`
: `Правило #${r.priority} (${r.action}) будет удалено.`
}
confirmLabel="Удалить"
destructive
onConfirm={() => onDelete(r.id)}
/>
)
},
},
],
[communities, deletePending, onDelete],
)
const table = useReactTable({
data: rules,
columns,
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(),
getPaginationRowModel: getPaginationRowModel(),
getRowId: (row) => row.id,
initialState: { pagination: { pageSize: 10 } },
})
return (
<DataGrid
table={table}
recordCount={rules.length}
isLoading={isLoading}
emptyMessage={emptyTitle}
tableLayout={{ headerSticky: true, dense: true }}
>
<DataGridContainer>
<DataGridTable />
</DataGridContainer>
<DataGridPagination
sizes={[10, 25, 50]}
sizesLabel="Показать"
sizesDescription="на странице"
info="{from}{to} из {count}"
rowsPerPageLabel="Строк на странице"
previousPageLabel="Предыдущая страница"
nextPageLabel="Следующая страница"
/>
</DataGrid>
)
}
@@ -0,0 +1,174 @@
import {
LayoutDashboard,
Boxes,
Network,
Cog,
ListChecks,
Activity,
Settings,
BookText,
KeyRound,
ServerCog,
Shield,
} from 'lucide-react'
import {
Sidebar,
SidebarContent,
SidebarFooter,
SidebarGroup,
SidebarGroupContent,
SidebarGroupLabel,
SidebarHeader,
SidebarInset,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
SidebarProvider,
SidebarTrigger,
} from '@evobgp/ui/components/sidebar'
import {
Breadcrumb,
BreadcrumbItem,
BreadcrumbLink,
BreadcrumbList,
BreadcrumbPage,
BreadcrumbSeparator,
} from '@evobgp/ui/components/breadcrumb'
import { Separator } from '@evobgp/ui/components/separator'
import { Link, useRouterState } from '@tanstack/react-router'
import type { ComponentType, ReactNode } from 'react'
import { ModeToggle } from '@/components/mode-toggle'
interface NavItem {
to: string
label: string
icon: ComponentType<{ className?: string }>
}
interface NavGroup {
label: string
items: NavItem[]
}
const NAV_GROUPS: NavGroup[] = [
{
label: 'Обзор',
items: [{ to: '/dashboard', label: 'Dashboard', icon: LayoutDashboard }],
},
{
label: 'Маршрутизация',
items: [
{ to: '/modules', label: 'Модули', icon: Boxes },
{ to: '/network', label: 'Сеть', icon: Network },
{ to: '/directories', label: 'Справочники', icon: BookText },
],
},
{
label: 'Операции',
items: [
{ to: '/operations', label: 'Операции', icon: Cog },
{ to: '/firewall', label: 'Firewall', icon: Shield },
{ to: '/schedule', label: 'Задачи', icon: ListChecks },
{ to: '/monitoring', label: 'Мониторинг', icon: Activity },
],
},
{
label: 'Система',
items: [
{ to: '/access', label: 'Доступ', icon: KeyRound },
{ to: '/tenant-settings', label: 'Настройки BIRD', icon: ServerCog },
{ to: '/settings', label: 'Настройки UI', icon: Settings },
],
},
]
const ALL_NAV_ITEMS = NAV_GROUPS.flatMap((g) => g.items)
const ROUTE_LABELS: Record<string, string> = Object.fromEntries(
ALL_NAV_ITEMS.map((i) => [i.to, i.label]),
)
const PARENT_ROUTE: Record<string, string> = {}
export function AppShell({ children }: { children: ReactNode }) {
const pathname = useRouterState({ select: (s) => s.location.pathname })
const activeItem =
ALL_NAV_ITEMS.find((i) => pathname === i.to || (i.to !== '/' && pathname.startsWith(`${i.to}/`))) ??
ALL_NAV_ITEMS[0]
const parentTo = PARENT_ROUTE[activeItem.to]
const parentLabel = parentTo ? ROUTE_LABELS[parentTo] : null
return (
<SidebarProvider>
<Sidebar collapsible="icon">
<SidebarHeader>
<div className="flex items-center gap-2 px-2 py-1.5">
<div className="flex size-8 items-center justify-center rounded-md bg-primary text-primary-foreground text-sm font-bold">
B
</div>
<div className="flex flex-col overflow-hidden group-data-[collapsible=icon]:hidden">
<span className="truncate text-sm font-semibold">EvoBGP</span>
<span className="truncate text-xs text-muted-foreground">Control Plane</span>
</div>
</div>
</SidebarHeader>
<SidebarContent>
{NAV_GROUPS.map((group) => (
<SidebarGroup key={group.label}>
<SidebarGroupLabel>{group.label}</SidebarGroupLabel>
<SidebarGroupContent>
<SidebarMenu>
{group.items.map((item) => {
const Icon = item.icon
const isActive = pathname === item.to || pathname.startsWith(`${item.to}/`)
return (
<SidebarMenuItem key={item.to}>
<SidebarMenuButton
render={<Link to={item.to} />}
isActive={isActive}
tooltip={item.label}
>
<Icon className="size-4" />
<span>{item.label}</span>
</SidebarMenuButton>
</SidebarMenuItem>
)
})}
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
))}
</SidebarContent>
<SidebarFooter />
</Sidebar>
<SidebarInset>
<header className="sticky top-0 z-10 flex h-16 shrink-0 items-center gap-2 border-b bg-background/95 px-4 backdrop-blur supports-[backdrop-filter]:bg-background/80">
<SidebarTrigger />
<Separator orientation="vertical" className="mr-2 data-[orientation=vertical]:h-4" />
<Breadcrumb>
<BreadcrumbList>
{parentLabel && parentTo ? (
<>
<BreadcrumbItem className="hidden md:block">
<BreadcrumbLink render={<Link to={parentTo} />}>{parentLabel}</BreadcrumbLink>
</BreadcrumbItem>
<BreadcrumbSeparator className="hidden md:block" />
</>
) : null}
<BreadcrumbItem>
<BreadcrumbPage>{ROUTE_LABELS[activeItem.to] ?? activeItem.label}</BreadcrumbPage>
</BreadcrumbItem>
</BreadcrumbList>
</Breadcrumb>
<div className="ml-auto flex items-center gap-2">
<ModeToggle />
</div>
</header>
<main className="flex flex-1 flex-col gap-4 p-4 md:gap-6 md:p-6">{children}</main>
</SidebarInset>
</SidebarProvider>
)
}
@@ -0,0 +1,19 @@
import { Button } from '@evobgp/ui/components/button'
import { Loader2Icon } from 'lucide-react'
import type { ButtonHTMLAttributes, ReactNode } from 'react'
type LoadingButtonProps = ButtonHTMLAttributes<HTMLButtonElement> & {
loading?: boolean
variant?: 'default' | 'outline' | 'secondary' | 'ghost' | 'destructive' | 'link'
size?: 'default' | 'xs' | 'sm' | 'lg' | 'icon' | 'icon-xs' | 'icon-sm' | 'icon-lg'
children: ReactNode
}
export function LoadingButton({ loading, disabled, children, ...props }: LoadingButtonProps) {
return (
<Button disabled={disabled || loading} {...props}>
{loading ? <Loader2Icon className="animate-spin" data-icon="inline-start" /> : null}
{children}
</Button>
)
}

Some files were not shown because too many files have changed in this diff Show More