diff --git a/.agents/plugins/marketplace.json b/.agents/plugins/marketplace.json new file mode 100644 index 00000000..ef0b8a60 --- /dev/null +++ b/.agents/plugins/marketplace.json @@ -0,0 +1,19 @@ +{ + "name": "maister-plugins", + "interface": { + "displayName": "Maister" + }, + "plugins": [ + { + "name": "maister-codex", + "source": { + "source": "local", + "path": "./plugins/maister-codex" + }, + "policy": { + "installation": "AVAILABLE" + }, + "category": "Development" + } + ] +} diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..b1356d02 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,29 @@ +# Maister repository guidance + +This repository contains workflow plugins. Treat `plugins/maister/` as the Claude Code source and `plugins/maister-copilot/` as generated output; never edit the generated Copilot package directly. + +The Codex port lives in `plugins/maister-codex/`. Keep it Codex-native: use `AGENTS.md` for durable project instructions, skills for reusable workflows, and `.codex/agents/*.toml` for project-scoped specialist subagents. Do not add Claude-only tool directives such as `AskUserQuestion`, `TaskCreate`, or `TaskUpdate` to the Codex port. + +## Versioning + +Releases keep all manifests at the same version (see `CLAUDE.md` "Beta Branch Management" for the branch workflow). Four manifests carry the version: + +- `.claude-plugin/marketplace.json` +- `.agents/plugins/marketplace.json` (Codex-native catalog; lists `maister-codex` only, no version field) +- `plugins/maister/.claude-plugin/plugin.json` +- `plugins/maister-copilot/.claude-plugin/plugin.json` +- `plugins/maister-codex/.codex-plugin/plugin.json` + +## Validation + +Run `make validate` (includes `validate-codex`) before handoff. Additionally validate with the local Codex tooling when available (path is machine-specific): + +```bash +python3 ~/.codex/skills/.system/plugin-creator/scripts/validate_plugin.py plugins/maister-codex +``` + +Validate every changed skill with: + +```bash +python3 ~/.codex/skills/.system/skill-creator/scripts/quick_validate.py +``` diff --git a/CLAUDE.md b/CLAUDE.md index 7fe2c173..206a2f02 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -86,10 +86,11 @@ After `git merge --squash`, git doesn't record that beta's commits were merged. ### Manifest files to update -These three files need version/name changes during the merge workflow: +These four files need version/name changes during the merge workflow: - `.claude-plugin/marketplace.json` — name + version + descriptions - `plugins/maister/.claude-plugin/plugin.json` — version + description - `plugins/maister-copilot/.claude-plugin/plugin.json` — version + description +- `plugins/maister-codex/.codex-plugin/plugin.json` — version + description ## Testing Changes diff --git a/Makefile b/Makefile index 2f885c1a..a162f536 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: build validate clean watch +.PHONY: build validate validate-codex clean watch build: bash platforms/copilot-cli/build.sh @@ -17,6 +17,24 @@ validate: @echo "Checking no maister: prefixes in copilot variant..." @! grep -r 'maister:' plugins/maister-copilot/ --include="*.md" 2>/dev/null || (echo "FAIL: maister: prefix found" && exit 1) @echo "All checks passed" + @$(MAKE) validate-codex + +validate-codex: + @echo "Checking codex plugin manifest parses..." + @node -e "JSON.parse(require('fs').readFileSync('plugins/maister-codex/.codex-plugin/plugin.json','utf8'))" || (echo "FAIL: invalid plugin.json" && exit 1) + @echo "Checking codex hooks config parses..." + @node -e "JSON.parse(require('fs').readFileSync('plugins/maister-codex/hooks/hooks.json','utf8'))" || (echo "FAIL: invalid hooks.json" && exit 1) + @echo "Checking codex hook scripts..." + @for f in plugins/maister-codex/hooks/*.mjs; do node --check "$$f" || exit 1; done + @echo "Checking no Claude-only artifacts in codex skills..." + @! grep -rE 'AskUserQuestion|TaskCreate|TaskUpdate|SlashCommand|Skill tool|Task tool|CLAUDE_PLUGIN_ROOT|CLAUDE\.md|/maister:' plugins/maister-codex/skills/ 2>/dev/null || (echo "FAIL: Claude-only artifact found in codex skills" && exit 1) + @echo "Checking codex SKILL.md names match directories..." + @for d in plugins/maister-codex/skills/*/; do n=$$(basename $$d); grep -q "^name: $$n$$" "$$d/SKILL.md" || (echo "FAIL: $$d frontmatter name != $$n" && exit 1); done + @echo "Checking codex agent template names match filenames..." + @for f in plugins/maister-codex/skills/maister-init/assets/agents/*.toml; do b=$$(basename $$f .toml); grep -q "^name = \"$$b\"$$" "$$f" || (echo "FAIL: $$f name != $$b" && exit 1); done + @echo "Checking codex-native marketplace manifest parses..." + @node -e "const m=JSON.parse(require('fs').readFileSync('.agents/plugins/marketplace.json','utf8')); if(!m.plugins.some(p=>p.name==='maister-codex')) throw new Error('maister-codex missing')" || (echo "FAIL: invalid .agents/plugins/marketplace.json" && exit 1) + @echo "Codex checks passed" clean: rm -rf plugins/maister-copilot/ diff --git a/plugins/maister-codex/.codex-plugin/plugin.json b/plugins/maister-codex/.codex-plugin/plugin.json new file mode 100644 index 00000000..2c30c4b4 --- /dev/null +++ b/plugins/maister-codex/.codex-plugin/plugin.json @@ -0,0 +1,38 @@ +{ + "name": "maister-codex", + "version": "2.2.3", + "description": "Structured, standards-aware development workflows for Codex", + "author": { + "name": "SkillPanel", + "email": "marek@skillpanel.com" + }, + "license": "MIT", + "keywords": [ + "development", + "standards", + "testing", + "workflow", + "migration", + "performance", + "research" + ], + "skills": "./skills/", + "mcpServers": "./.mcp.json", + "interface": { + "displayName": "Maister Codex", + "shortDescription": "Standards-aware software delivery workflows.", + "longDescription": "Plan, implement, migrate, optimize, research, design, and verify software changes with project standards, explicit gates, resumable artifacts, browser checks, and focused Codex subagents.", + "developerName": "SkillPanel", + "category": "Development", + "capabilities": [ + "Interactive", + "Write", + "Testing" + ], + "defaultPrompt": [ + "Use Maister to plan and implement this feature.", + "Use Maister to migrate or optimize this system.", + "Initialize Maister standards for this repository." + ] + } +} diff --git a/plugins/maister-codex/.mcp.json b/plugins/maister-codex/.mcp.json new file mode 100644 index 00000000..20d34743 --- /dev/null +++ b/plugins/maister-codex/.mcp.json @@ -0,0 +1,8 @@ +{ + "mcpServers": { + "playwright": { + "command": "npx", + "args": ["-y", "@playwright/mcp@latest"] + } + } +} diff --git a/plugins/maister-codex/AGENTS.md b/plugins/maister-codex/AGENTS.md new file mode 100644 index 00000000..aecfec72 --- /dev/null +++ b/plugins/maister-codex/AGENTS.md @@ -0,0 +1,13 @@ +# Maister Codex plugin guidance + +This directory is the Codex-native Maister plugin. Preserve the workflow principles from `plugins/maister/`: standards awareness, explicit phase gates, user-confirmed rollback, focused verification, and resumable task artifacts. Do not add Claude-only tool directives or treat `plugins/maister-copilot/` as a source. + +Use skills for reusable workflows and compose them by loading the named skill and following its instructions. Use Codex subagents only when the user, repository guidance, or the active skill explicitly requests delegation. Keep durable project guidance in `AGENTS.md`; keep workflow state under `.maister/tasks/`. + +At a required user decision gate, prefer `request_user_input` when available. Otherwise ask the equivalent concise question in the final response and pause. Use execution approval only for sensitive tool actions, never as a substitute for a product, scope, design, or workflow choice. Never infer approval for rollback, destructive recovery, scope expansion, or acceptance of critical findings. + +Codex custom agents are project-scoped, not plugin components. Maintain their distributable templates under `skills/maister-init/assets/agents/`; `$maister-codex:maister-init` copies selected templates into a project's `.codex/agents/` without replacing existing files unless the user approves it. + +Keep plugin lifecycle hooks in `hooks/hooks.json`, which Codex discovers by default. Hook commands are inlined as `node -e` one-liners because plugin-root path variables are not reliably expanded across harnesses; the `hooks/*.mjs` files are the readable sources and must be kept in sync with the inline commands. Keep bundled MCP configuration in `.mcp.json` and declare it through `mcpServers` in `.codex-plugin/plugin.json`. The current repository validator does not accept a manifest `hooks` field, so do not add one while the default hook path is used. + +Keep skills focused and self-contained. Put detailed reusable guidance in `references/`, deterministic helpers in `scripts/`, and templates in `assets/`; do not create a `README.md` inside a skill folder. Validate every changed skill and the plugin before handoff. diff --git a/plugins/maister-codex/README.md b/plugins/maister-codex/README.md new file mode 100644 index 00000000..ed61ee9b --- /dev/null +++ b/plugins/maister-codex/README.md @@ -0,0 +1,42 @@ +# Maister for Codex + +Maister provides Codex-native, standards-aware workflows for software delivery. It preserves resumable task artifacts, explicit approval gates, test-first implementation, focused verification, and user-confirmed rollback while leaving the Claude Code source package untouched. + +## Workflows + +- `$maister-codex:maister-work` classifies and routes software tasks, including resumes from existing `.maister/tasks/` directories. +- `$maister-codex:maister-development`, `$maister-codex:maister-performance`, `$maister-codex:maister-migration`, `$maister-codex:maister-research`, and `$maister-codex:maister-product-design` run full resumable workflows. +- `$maister-codex:maister-quick-dev`, `$maister-codex:maister-quick-plan`, and `$maister-codex:maister-quick-bugfix` handle focused work. +- `$maister-codex:maister-codebase-analysis`, `$maister-codex:maister-implementation-plan-executor`, `$maister-codex:maister-verify`, and `$maister-codex:maister-mockup-studio` provide reusable workflow stages. +- `$maister-codex:maister-reviews-code`, `$maister-codex:maister-reviews-pragmatic`, `$maister-codex:maister-reviews-production-readiness`, `$maister-codex:maister-reviews-reality-check`, and `$maister-codex:maister-reviews-spec-audit` provide focused read-only reviews. +- `$maister-codex:maister-init`, `$maister-codex:maister-docs-manager`, `$maister-codex:maister-standards-discover`, and `$maister-codex:maister-standards-update` initialize and maintain project guidance. + +The plugin bundles Playwright MCP for browser verification, mockups, and screenshot-backed documentation. It also includes Node-based lifecycle hooks: reminders for explicit skill invocation and state recovery after compaction, plus a PreToolUse guard that denies destructive shell commands (`git stash`, `git reset --hard`, `git clean`, force-push, `rm -rf`) from non-whitelisted subagents so parallel implementers cannot clobber each other's work. Codex asks you to review and trust plugin hooks before they run. Node.js is required for hooks, the HTML mockup companion, and Playwright MCP; no separate `jq` or Bash dependency is used. + +## Specialist agents + +`$maister-codex:maister-init` can copy 25 optional specialist templates into the current repository's `.codex/agents/` directory. This is the Codex-native distribution path for project-scoped custom agents; installing the plugin alone does not modify a repository's agent configuration. Existing templates are preserved unless you explicitly approve replacement. Maister workflows delegate to these agents by name when they are installed (for example `maister-task-group-implementer` during implementation waves, `maister-code-reviewer` during verification) and fall back to inline execution when they are absent. + +## Installation + +Install directly from GitHub: + +```bash +codex plugin marketplace add SkillPanel/Maister +codex plugin add maister-codex@maister-plugins +``` + +Add `--ref ` to install from a branch instead of the default one. + +## Local testing + +Register a local checkout as a marketplace, then install the plugin: + +```bash +codex plugin marketplace add /absolute/path/to/Maister +codex plugin add maister-codex@maister-plugins +``` + +Codex reads the native catalog at `.agents/plugins/marketplace.json` (named `maister-plugins`), which lists only the Codex package; `.claude-plugin/marketplace.json` remains the Claude Code / Copilot catalog. Start a new Codex thread after installation, then invoke a skill with `$maister-codex:maister-init` or `$maister-codex:maister-work`. + +Use `/hooks` to review bundled hooks and `/mcp verbose` to confirm the Playwright server. The first Playwright use may require `npx` to download `@playwright/mcp` under the active sandbox and network policy. diff --git a/plugins/maister-codex/hooks/block-destructive-commands.mjs b/plugins/maister-codex/hooks/block-destructive-commands.mjs new file mode 100644 index 00000000..b299fee1 --- /dev/null +++ b/plugins/maister-codex/hooks/block-destructive-commands.mjs @@ -0,0 +1,53 @@ +// Source of the inline `node -e` command in hooks.json (kept path-free there because +// plugin-root variables are not reliably expanded). Keep both in sync when editing. +// Block destructive shell commands from non-implementation subagents. +// Whitelist approach: only explicitly trusted execution agents bypass the check, +// so new agents are protected by default. The main agent (no agent identifier) +// passes through — the user's approval system governs it. + +let input = ''; +for await (const chunk of process.stdin) input += chunk; + +let event = {}; +try { + event = input.trim() ? JSON.parse(input) : {}; +} catch { + event = {}; +} + +const agentType = + event.agent_type || event.agentType || event.subagent_type || event.agent || ''; +const command = + (event.tool_input && (event.tool_input.command || event.tool_input.cmd)) || + (event.toolInput && (event.toolInput.command || event.toolInput.cmd)) || + ''; + +// Main agent: allow (execution approval handles sensitive actions there). +if (!agentType) process.exit(0); + +// Agents that legitimately need full shell access (test execution, docs capture). +// maister-task-group-implementer is intentionally NOT whitelisted: destructive git +// commands are blocked so one implementer cannot clobber parallel siblings. +const trusted = new Set([ + 'maister-test-suite-runner', + 'maister-e2e-test-verifier', + 'maister-user-docs-generator', + 'maister-docs-operator', +]); +if (trusted.has(String(agentType))) process.exit(0); + +const destructive = + /git\s+stash|git\s+reset\s+--hard|git\s+checkout\s+--\s+\.|git\s+checkout\s+\.\s*$|git\s+clean|git\s+push\s+(-f|--force)|rm\s+-rf/i; + +if (typeof command === 'string' && destructive.test(command)) { + const payload = { + hookSpecificOutput: { + hookEventName: 'PreToolUse', + permissionDecision: 'deny', + permissionDecisionReason: `Destructive command blocked for agent '${agentType}': ${String(command).slice(0, 80)}`, + }, + }; + process.stdout.write(`${JSON.stringify(payload)}\n`); +} + +process.exit(0); diff --git a/plugins/maister-codex/hooks/hooks.json b/plugins/maister-codex/hooks/hooks.json new file mode 100644 index 00000000..d9fff106 --- /dev/null +++ b/plugins/maister-codex/hooks/hooks.json @@ -0,0 +1,52 @@ +{ + "description": "Maister workflow reminders, subagent safety guidance, and destructive-command protection. Commands are inlined (node -e) so no plugin-root path variable is required; the sibling .mjs files are the readable sources — keep them in sync.", + "hooks": { + "SessionStart": [ + { + "matcher": "compact", + "hooks": [ + { + "type": "command", + "command": "node -e 'const f=require(\"fs\"),p=require(\"path\");let i=\"\";try{i=f.readFileSync(0,\"utf8\")}catch{}let e={};try{e=i.trim()?JSON.parse(i):{}}catch{}const w=p.resolve(typeof e.cwd===\"string\"&&e.cwd?e.cwd:process.cwd());if(f.existsSync(p.join(w,\".maister\",\"tasks\")))process.stdout.write(JSON.stringify({hookSpecificOutput:{hookEventName:\"SessionStart\",additionalContext:\"MAISTER RESUME CHECK: A .maister/tasks directory exists. If this chat was running a Maister orchestrator before compaction, read the active task orchestrator-state.yml and completed artifacts before continuing. Treat the state file, not recalled chat history, as the resume source of truth. Honor every remaining explicit phase approval gate.\"}})+\"\\n\")'", + "timeout": 10, + "additionalContextLimit": 1000 + } + ] + }, + { + "hooks": [ + { + "type": "command", + "command": "node -e 'process.stdout.write(JSON.stringify({hookSpecificOutput:{hookEventName:\"SessionStart\",additionalContext:\"MAISTER PLUGIN RULES: When the user explicitly invokes a $maister-codex:maister-* skill, read that skill completely and follow it before substituting another workflow. Skills compose natively: load each named supporting skill and follow its instructions. For a required phase gate, stop after presenting the review summary and request the specified user decision; do not mark the phase complete until the user responds. Never reset, discard, or roll back work without explicit user approval.\"}})+\"\\n\")'", + "timeout": 10, + "additionalContextLimit": 1200 + } + ] + } + ], + "PreToolUse": [ + { + "matcher": "Bash|shell|local_shell", + "hooks": [ + { + "type": "command", + "command": "node -e 'const f=require(\"fs\");let i=\"\";try{i=f.readFileSync(0,\"utf8\")}catch{}let e={};try{e=i.trim()?JSON.parse(i):{}}catch{}const a=e.agent_type||e.agentType||e.subagent_type||e.agent||\"\";const t=e.tool_input||e.toolInput||{};const c=t.command||t.cmd||\"\";if(!a)process.exit(0);if([\"maister-test-suite-runner\",\"maister-e2e-test-verifier\",\"maister-user-docs-generator\",\"maister-docs-operator\"].includes(String(a)))process.exit(0);const d=/git\\s+stash|git\\s+reset\\s+--hard|git\\s+checkout\\s+--\\s+\\.|git\\s+checkout\\s+\\.\\s*$|git\\s+clean|git\\s+push\\s+(-f|--force)|rm\\s+-rf/i;if(typeof c===\"string\"&&d.test(c))process.stdout.write(JSON.stringify({hookSpecificOutput:{hookEventName:\"PreToolUse\",permissionDecision:\"deny\",permissionDecisionReason:\"Destructive command blocked for agent \"+a+\": \"+String(c).slice(0,80)}})+\"\\n\")'", + "timeout": 10 + } + ] + } + ], + "SubagentStart": [ + { + "hooks": [ + { + "type": "command", + "command": "node -e 'process.stdout.write(JSON.stringify({hookSpecificOutput:{hookEventName:\"SubagentStart\",additionalContext:\"MAISTER SUBAGENT SAFETY: Stay within the assigned role, files, and output contract. Preserve unrelated work. Do not run git stash, git reset --hard, git clean, force-push, broad recursive deletion, or any rollback/discard operation. Return concrete evidence and unresolved blockers to the parent agent.\"}})+\"\\n\")'", + "timeout": 10, + "additionalContextLimit": 800 + } + ] + } + ] + } +} diff --git a/plugins/maister-codex/hooks/post-compact-reminder.mjs b/plugins/maister-codex/hooks/post-compact-reminder.mjs new file mode 100644 index 00000000..ccbce2eb --- /dev/null +++ b/plugins/maister-codex/hooks/post-compact-reminder.mjs @@ -0,0 +1,25 @@ +// Source of the inline `node -e` command in hooks.json (kept path-free there because +// plugin-root variables are not reliably expanded). Keep both in sync when editing. +import fs from 'node:fs'; +import path from 'node:path'; + +let input = ''; +for await (const chunk of process.stdin) input += chunk; + +let event = {}; +try { + event = input.trim() ? JSON.parse(input) : {}; +} catch { + event = {}; +} + +const workspace = path.resolve(typeof event.cwd === 'string' && event.cwd ? event.cwd : process.cwd()); +if (fs.existsSync(path.join(workspace, '.maister', 'tasks'))) { + const payload = { + hookSpecificOutput: { + hookEventName: 'SessionStart', + additionalContext: 'MAISTER RESUME CHECK: A .maister/tasks directory exists. If this chat was running a Maister orchestrator before compaction, read the active task orchestrator-state.yml and completed artifacts before continuing. Treat the state file, not recalled chat history, as the resume source of truth. Honor every remaining explicit phase approval gate.', + }, + }; + process.stdout.write(`${JSON.stringify(payload)}\n`); +} diff --git a/plugins/maister-codex/hooks/subagent-safety-reminder.mjs b/plugins/maister-codex/hooks/subagent-safety-reminder.mjs new file mode 100644 index 00000000..8148ff80 --- /dev/null +++ b/plugins/maister-codex/hooks/subagent-safety-reminder.mjs @@ -0,0 +1,10 @@ +// Source of the inline `node -e` command in hooks.json (kept path-free there because +// plugin-root variables are not reliably expanded). Keep both in sync when editing. +const payload = { + hookSpecificOutput: { + hookEventName: 'SubagentStart', + additionalContext: 'MAISTER SUBAGENT SAFETY: Stay within the assigned role, files, and output contract. Preserve unrelated work. Do not run git stash, git reset --hard, git clean, force-push, broad recursive deletion, or any rollback/discard operation. Return concrete evidence and unresolved blockers to the parent agent.', + }, +}; + +process.stdout.write(`${JSON.stringify(payload)}\n`); diff --git a/plugins/maister-codex/hooks/workflow-reminder.mjs b/plugins/maister-codex/hooks/workflow-reminder.mjs new file mode 100644 index 00000000..0b9f8c97 --- /dev/null +++ b/plugins/maister-codex/hooks/workflow-reminder.mjs @@ -0,0 +1,10 @@ +// Source of the inline `node -e` command in hooks.json (kept path-free there because +// plugin-root variables are not reliably expanded). Keep both in sync when editing. +const payload = { + hookSpecificOutput: { + hookEventName: 'SessionStart', + additionalContext: 'MAISTER PLUGIN RULES: When the user explicitly invokes a $maister-codex:maister-* skill, read that skill completely and follow it before substituting another workflow. Skills compose natively: load each named supporting skill and follow its instructions. For a required phase gate, stop after presenting the review summary and request the specified user decision; do not mark the phase complete until the user responds. Never reset, discard, or roll back work without explicit user approval.', + }, +}; + +process.stdout.write(`${JSON.stringify(payload)}\n`); diff --git a/plugins/maister-codex/skills/maister-codebase-analysis/SKILL.md b/plugins/maister-codex/skills/maister-codebase-analysis/SKILL.md new file mode 100644 index 00000000..27dbba23 --- /dev/null +++ b/plugins/maister-codex/skills/maister-codebase-analysis/SKILL.md @@ -0,0 +1,22 @@ +--- +name: maister-codebase-analysis +description: Analyze an unfamiliar codebase before a Maister implementation, bug fix, performance task, migration, or verification. Use to map responsible code paths, execution flow, callers, patterns, dependencies, tests, migration targets, and risks without changing application code. +--- + +# Maister Codebase Analysis + +Produce evidence, not a design or implementation. Do not modify application source files. Read the task type, description, task path, and any existing state before selecting investigation lanes. + +Choose the narrowest independent set: + +- file discovery (`references/file-discovery.md`) — entry points, symbols, ownership, generated surfaces; +- execution analysis (`references/code-analysis.md`) — data/control flow, state, failure modes; +- context discovery (`references/context-discovery.md`) — callers, consumers, tests, configuration, dependencies; +- pattern mining (`references/pattern-mining.md`) — analogous implementations and conventions to reuse; +- migration target (`references/migration-target.md`) — current/target APIs, compatibility boundaries, and conversion surface. + +Read each selected lane's reference file for its detailed prompt. For broad work, delegate non-overlapping read-only investigations concurrently and give each a specific lane and output contract. For small work, combine the selected lanes into one exploration using `references/combined.md`. Synthesize once — delegate synthesis to the installed `maister-codebase-analysis-reporter` agent when available, otherwise synthesize inline: deduplicate files and findings, cross-check contradictions, distinguish observed facts from inference, and retain line/symbol evidence. + +Write `/analysis/codebase-analysis.md` when a task path is supplied, otherwise return the analysis directly. Include TL;DR, task interpretation, scope, files and symbols, current execution flow, reusable patterns, tests/consumers/configuration, task-type findings, risks, unknowns, and recommended next actions. + +End with `status`, `summary`, `files_found`, `complexity`, and `risk_level`. Do not propose a detailed solution unless the caller explicitly requests one. diff --git a/plugins/maister-codex/skills/maister-codebase-analysis/agents/openai.yaml b/plugins/maister-codex/skills/maister-codebase-analysis/agents/openai.yaml new file mode 100644 index 00000000..49fb8888 --- /dev/null +++ b/plugins/maister-codex/skills/maister-codebase-analysis/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Maister Codebase Analysis" + short_description: "Map code paths, patterns, tests, and risks." + default_prompt: "Use $maister-codex:maister-codebase-analysis to map this codebase before changes." diff --git a/plugins/maister-codex/skills/maister-codebase-analysis/references/code-analysis.md b/plugins/maister-codex/skills/maister-codebase-analysis/references/code-analysis.md new file mode 100644 index 00000000..129c7b54 --- /dev/null +++ b/plugins/maister-codex/skills/maister-codebase-analysis/references/code-analysis.md @@ -0,0 +1,63 @@ +# Code Analysis — Prompt Templates + +Replace `[description]` with the actual task description. + +## Bug +``` +IMPORTANT: Do NOT create, write, or modify any files. Output all findings as text in your response only. + +Analyze the code related to: "[description]" + +Focus on: +1. Trace execution flow from input to output +2. Identify state changes and side effects +3. Look for edge cases, error conditions, race conditions +4. Find validation logic and where it might fail +5. Check for recent changes that might have introduced the bug + +Output: +- Execution flow diagram (text-based) +- Key functions/methods involved +- Potential problem areas +- State management approach +``` + +## Enhancement +``` +IMPORTANT: Do NOT create, write, or modify any files. Output all findings as text in your response only. + +Analyze the existing implementation of: "[description]" + +Focus on: +1. Understand current functionality and capabilities +2. Identify the component/service architecture +3. Document the data flow (props, state, API calls) +4. Note coding patterns used (hooks, classes, functional) +5. Assess complexity (simple/moderate/complex) + +Output: +- Current functionality summary +- Architecture overview +- Key functions and their purposes +- Coding patterns observed +``` + +## Feature +``` +IMPORTANT: Do NOT create, write, or modify any files. Output all findings as text in your response only. + +Analyze the codebase architecture for adding: "[description]" + +Focus on: +1. Understand the overall project structure +2. Identify architectural patterns in use (MVC, component-based, etc.) +3. Document naming conventions and code style +4. Find the data layer patterns (API, state management) +5. Note any relevant abstractions or base classes + +Output: +- Project structure overview +- Architectural patterns to follow +- Naming conventions to match +- Recommended approach for new feature +``` diff --git a/plugins/maister-codex/skills/maister-codebase-analysis/references/combined.md b/plugins/maister-codex/skills/maister-codebase-analysis/references/combined.md new file mode 100644 index 00000000..0b8d867b --- /dev/null +++ b/plugins/maister-codex/skills/maister-codebase-analysis/references/combined.md @@ -0,0 +1,31 @@ +# Combined Prompts — Guidance + +When merging multiple roles into a single agent, integrate concerns logically rather than concatenating prompts. Read the individual role templates first, then merge them into a coherent single prompt. + +## Example: File Discovery + Code Analysis (Bug) + +``` +IMPORTANT: Do NOT create, write, or modify any files. Output all findings as text in your response only. + +Explore and analyze the codebase for: "[description]" + +1. Find files where the bug likely occurs (search for error keywords, related functionality) +2. Trace the code path through these files - entry points, handlers, processing logic +3. Identify state changes, side effects, and potential failure points +4. Look for edge cases, validation logic, and error handling +5. Check for related configuration that might affect behavior + +Output: +- Relevant files with paths and why they matter +- Execution flow through identified files +- Key functions/methods and their roles +- Potential problem areas and root cause hypotheses +``` + +## Merging Principles + +- Unify the focus areas into a single logical flow (don't just list both sets of bullet points) +- Combine the output sections — avoid duplicate asks +- Keep the total prompt concise (aim for 8-12 focus items max) +- The merged prompt should read as one coherent task, not two tasks stitched together +- Always include the no-write constraint: "IMPORTANT: Do NOT create, write, or modify any files. Output all findings as text in your response only." diff --git a/plugins/maister-codex/skills/maister-codebase-analysis/references/context-discovery.md b/plugins/maister-codex/skills/maister-codebase-analysis/references/context-discovery.md new file mode 100644 index 00000000..35031bc0 --- /dev/null +++ b/plugins/maister-codex/skills/maister-codebase-analysis/references/context-discovery.md @@ -0,0 +1,63 @@ +# Context Discovery — Prompt Templates + +Replace `[description]` with the actual task description. + +## Bug +``` +IMPORTANT: Do NOT create, write, or modify any files. Output all findings as text in your response only. + +Find testing and context information for: "[description]" + +Focus on: +1. Find existing tests that cover this functionality +2. Look for test files that might help reproduce the bug +3. Identify test data or fixtures used +4. Find related integration or E2E tests +5. Check for any existing bug reports or TODOs in comments + +Output: +- Relevant test files and what they test +- Test coverage gaps +- Reproduction hints from tests +- Related issues or TODOs found in code +``` + +## Enhancement +``` +IMPORTANT: Do NOT create, write, or modify any files. Output all findings as text in your response only. + +Find dependencies and consumers for: "[description]" + +Focus on: +1. Find all files that import/use this feature (consumers) +2. Identify what this feature depends on (dependencies) +3. Locate test files and assess coverage +4. Find API endpoints or routes related to this feature +5. Check for documentation or comments + +Output: +- Consumer list (who uses this) +- Dependency list (what this uses) +- Test files and coverage assessment +- Integration points +``` + +## Feature +``` +IMPORTANT: Do NOT create, write, or modify any files. Output all findings as text in your response only. + +Find integration requirements for: "[description]" + +Focus on: +1. Identify where this feature needs to be registered/routed +2. Find existing integration patterns (how other features connect) +3. Look for shared dependencies this feature will need +4. Check for authentication/authorization patterns to follow +5. Find configuration or environment requirements + +Output: +- Required integration points +- Patterns to follow for registration +- Shared dependencies to use +- Configuration requirements +``` diff --git a/plugins/maister-codex/skills/maister-codebase-analysis/references/file-discovery.md b/plugins/maister-codex/skills/maister-codebase-analysis/references/file-discovery.md new file mode 100644 index 00000000..e3b446e5 --- /dev/null +++ b/plugins/maister-codex/skills/maister-codebase-analysis/references/file-discovery.md @@ -0,0 +1,51 @@ +# File Discovery — Prompt Templates + +Replace `[description]` with the actual task description. + +## Bug +``` +IMPORTANT: Do NOT create, write, or modify any files. Output all findings as text in your response only. + +Explore the codebase to find files related to: "[description]" + +Focus on: +1. Find files where the bug likely occurs (search for error keywords, related functionality) +2. Trace the code path - entry points, handlers, processing logic +3. Look for related error handling, validation, edge cases +4. Find configuration files that might affect this behavior + +Output a list of relevant files with their paths and why they're relevant. +Be thorough - check multiple naming conventions (PascalCase, kebab-case, snake_case). +``` + +## Enhancement +``` +IMPORTANT: Do NOT create, write, or modify any files. Output all findings as text in your response only. + +Explore the codebase to find files that implement: "[description]" + +Focus on: +1. Find the main files for this feature (components, services, controllers) +2. Look for related files (types, utilities, hooks, styles) +3. Check multiple naming patterns: *{keyword}*, {Domain}{Component}, etc. +4. Search in likely directories: src/components/, src/services/, src/features/ + +Output a ranked list of files with confidence indicators. +Include file paths, approximate line counts, and why each file is relevant. +``` + +## Feature +``` +IMPORTANT: Do NOT create, write, or modify any files. Output all findings as text in your response only. + +Explore the codebase to find patterns and integration points for: "[description]" + +Focus on: +1. Find similar existing features/components to use as templates +2. Identify where this new feature should live (directory structure) +3. Look for shared utilities, hooks, or base classes to extend +4. Find entry points where this feature needs to integrate (routes, menus, etc.) + +List the files that serve as good examples or integration points. +Include reasoning for why each pattern/location is appropriate. +``` diff --git a/plugins/maister-codex/skills/maister-codebase-analysis/references/migration-target.md b/plugins/maister-codex/skills/maister-codebase-analysis/references/migration-target.md new file mode 100644 index 00000000..e004d41c --- /dev/null +++ b/plugins/maister-codex/skills/maister-codebase-analysis/references/migration-target.md @@ -0,0 +1,23 @@ +# Migration Target — Prompt Template + +Primarily for migrations. Replace `[description]` with the actual task description. + +``` +IMPORTANT: Do NOT create, write, or modify any files. Output all findings as text in your response only. + +Analyze the target state for migration: "[description]" + +Focus on: +1. Find any existing usage of the target technology/pattern in the codebase +2. Look for partial migration attempts or hybrid implementations +3. Identify compatibility layers, adapters, or shims already in use +4. Check for migration-related configuration (build tools, transpilers, polyfills) +5. Document the target conventions and patterns to follow + +Output: +- Existing target technology usage (if any) +- Partial migration progress found +- Compatibility concerns identified +- Target conventions to follow +- Migration configuration requirements +``` diff --git a/plugins/maister-codex/skills/maister-codebase-analysis/references/pattern-mining.md b/plugins/maister-codex/skills/maister-codebase-analysis/references/pattern-mining.md new file mode 100644 index 00000000..20a3169e --- /dev/null +++ b/plugins/maister-codex/skills/maister-codebase-analysis/references/pattern-mining.md @@ -0,0 +1,22 @@ +# Pattern Mining — Prompt Template + +Primarily for features, usable for enhancements. Replace `[description]` with the actual task description. + +``` +IMPORTANT: Do NOT create, write, or modify any files. Output all findings as text in your response only. + +Find similar implementations and reusable patterns for: "[description]" + +Focus on: +1. Find the most similar existing feature/component in the codebase +2. Identify reusable abstractions, base classes, or utilities that can be extended +3. Document the conventions these similar implementations follow (file structure, naming, patterns) +4. Note any generators, templates, or scaffolding tools available +5. Identify shared hooks, mixins, or helper functions that should be reused + +Output: +- Best template/example to replicate (with file paths) +- Reusable abstractions and utilities (with file paths) +- Convention checklist to follow +- Anti-patterns observed in existing similar features (what NOT to copy) +``` diff --git a/plugins/maister-codex/skills/maister-development/SKILL.md b/plugins/maister-codex/skills/maister-development/SKILL.md new file mode 100644 index 00000000..27d7a207 --- /dev/null +++ b/plugins/maister-codex/skills/maister-development/SKILL.md @@ -0,0 +1,57 @@ +--- +name: maister-development +description: Run Maister’s full adaptive, resumable development workflow for features, enhancements, complex bugs, and multi-file implementation. Use when work needs analysis, requirements and specification, test-first planning, implementation, verification, and optional design, E2E, or user documentation. +--- + +# Maister Development + +Load and follow `$maister-codex:maister-orchestrator-framework` before starting or resuming; its state, timestamp, phase-gate, artifact-summary, dashboard, HTML-companion, recovery, and user-confirmed rollback contracts are mandatory. Use `.maister/tasks/development/YYYY-MM-DD-task-slug/` as the durable record. State and artifacts, not chat history, determine the next action. Never overwrite artifacts or roll back code without explicit approval. + +Initialize `analysis/`, `implementation/`, `verification/`, `documentation/`, `orchestrator-state.yml`, and `implementation/work-log.md`. Read `.maister/config.yml` (`html_output: true`, `mockup_format: html` by default), `.maister/docs/INDEX.md`, every applicable standard, and every project document linked from the index. When HTML output is enabled, copy the shared dashboard asset and maintain `dashboard-data.js` as described by the framework. + +## Adaptive phases + +| # | Phase | Required outcome | Transition | +| --- | --- | --- | --- | +| 1 | Codebase analysis | `analysis/codebase-analysis.md`, clarifications, risks | Continue | +| 2 | Gap and scope analysis | `analysis/gap-analysis.md`, characteristics, decisions | User gate | +| 3 | TDD red | Focused failing regression test when defect is reproducible | Continue | +| 4 | UI mockups | Binding design context for UI-heavy work | User gate | +| 5 | Requirements and specification | `analysis/requirements.md`, `implementation/spec.md` | User gate | +| 6 | Specification audit | `verification/spec-audit.md` for complex/high-risk work | Resolve or gate | +| 7 | Implementation planning | `implementation/implementation-plan.md`, dependencies and ownership | User gate | +| 8 | Implementation | Code, focused tests, completed plan steps, work log | User gate on deviation/failure | +| 9 | TDD green | Red test and related tests pass | Continue | +| 10 | Verification selection | Persist enabled optional reviews | User gate | +| 11 | Verification and issue resolution | Canonical verification report and fix history | User gate for non-trivial fixes | +| 12 | E2E verification | Runtime user-flow evidence when enabled/applicable | Continue or gate on blockers | +| 13 | User documentation | User guide and screenshots when enabled/applicable | Continue | +| 14 | Finalization | Completed state, summary, risks, commit suggestion | Finish | + +Run conditional phases only when evidence activates them and record every skip with its reason. Phase 3 activates for a reproducible defect. Phase 4 activates for UI-heavy work lacking binding design context. Phase 6 is recommended for complex, safety-sensitive, migration-like, or ambiguous specifications. Phases 12 and 13 activate from user options or task characteristics. + +## Analyze and specify + +Delegate to the installed specialist agents per the framework's delegation rule: `maister-gap-analyzer` for Phase 2, `maister-specification-creator` for Phase 5, `maister-spec-auditor` for Phase 6, `maister-implementation-planner` for Phase 7, `maister-e2e-test-verifier` for Phase 12, and `maister-user-docs-generator` for Phase 13; perform each lane inline under the same contract when an agent is not installed. + +Load `$maister-codex:maister-codebase-analysis` for Phase 1. In Phase 2, compare current and desired behavior, identify reusable patterns and integration points, and assess user reachability, personas, navigation, permissions, complete data lifecycle, critical touchpoints, and orphaned inputs or displays. Persist characteristics such as `has_reproducible_defect`, `modifies_existing`, `new_capability`, `data_operations`, `ui_heavy`, and `risk_level`. + +For Phase 3, add only the smallest valid regression test. If it already passes, stop and correct the reproduction. For Phase 4, load `$maister-codex:maister-mockup-studio` with `iteration: single`, `emit_index_rows: true`, and the task’s design context. Preserve external design inputs under `analysis/design-context/` and treat indexed mockups as binding. + +The specification must cover the problem, personas and user journey, functional behavior, acceptance criteria, scope and non-goals, data and security implications, failure behavior, standards, observability, documentation, rollout, and rollback. Audit it with `$maister-codex:maister-reviews-spec-audit` when Phase 6 is active. When HTML output is enabled, write the `spec.html` and `implementation-plan.html` companions per the framework's companion table as each markdown artifact is approved. + +## Plan and implement + +The plan must define cohesive task groups, dependencies, exact or expected files, file ownership, test-first steps, validation commands, visual references, rollback actions, and acceptance coverage. Detect overlapping file ownership before assigning parallel groups. Load `$maister-codex:maister-implementation-plan-executor` for Phase 8; do not bypass it by implementing the approved plan inline. + +Implementation runs focused tests after each group and continuously applies newly relevant standards. A red regression test must become green before verification. Stop for architecture changes, data-integrity risk, scope expansion, repeated failures, or any deviation that invalidates the approved specification or plan. + +## Verify and finalize + +Phase 10 records options for code review, pragmatic review, production readiness, reality assessment, E2E, and user docs. Load `$maister-codex:maister-verify` once for the canonical verification cycle; never launch competing full test suites. Present non-trivial findings before modifying code. After fixes, re-run affected checks and refresh the canonical report so no stale verdict remains. + +E2E uses the bundled Playwright MCP when available and writes evidence under `verification/`; degrade to explicit manual steps when unavailable. User documentation reuses E2E screenshots before capturing new ones. Finalization verifies all required artifacts, acceptance criteria, plan checkboxes, standards, and final verdict before setting `status: completed`. + +## State and recovery + +Record timestamps, status, current and completed phases, attempts, phase summaries, decisions, applicable standards, project documents, task characteristics, design/research context, verification options, artifacts, and failures. Support `--from`, `--reset-attempts`, `--research=`, `--e2e`, `--user-docs`, and `--sequential`. Limit analysis/spec/plan attempts to two, implementation groups to three unless the failure is clearly transient, and verification/fix cycles to three. Exhausted attempts pause the task; they never authorize rollback. diff --git a/plugins/maister-codex/skills/maister-development/agents/openai.yaml b/plugins/maister-codex/skills/maister-development/agents/openai.yaml new file mode 100644 index 00000000..2a565101 --- /dev/null +++ b/plugins/maister-codex/skills/maister-development/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Maister Development" + short_description: "Run a full, resumable development workflow." + default_prompt: "Use $maister-codex:maister-development to build this feature with standards and verification." diff --git a/plugins/maister-codex/skills/maister-docs-manager/SKILL.md b/plugins/maister-codex/skills/maister-docs-manager/SKILL.md new file mode 100644 index 00000000..51216dde --- /dev/null +++ b/plugins/maister-codex/skills/maister-docs-manager/SKILL.md @@ -0,0 +1,75 @@ +--- +name: maister-docs-manager +description: Manage `.maister/docs/`, baseline and project-specific coding standards, the documentation index, and durable `AGENTS.md` integration. Use when initializing, adding, updating, comparing, indexing, listing, or validating Maister project documentation. +--- + +# Maister Docs Manager + +Manage documentation as an internal service for `$maister-codex:maister-init`, `$maister-codex:maister-standards-update`, and `$maister-codex:maister-standards-discover`. It may also handle an explicit documentation-management request. Return control to the calling workflow after the requested operation. + +When an explicit request reaches a user decision gate, prefer `request_user_input` when available; otherwise ask the equivalent concise question in the final response and pause. When called by another workflow, return the decision needed so the coordinator can own the gate. + +Project files under `.maister/docs/` are the source of truth. Bundled files under `assets/standards/` are starting points only. Preserve project customizations and require explicit approval before overwriting or resetting them. + +## Structure and format + +Maintain this shape: + +```text +.maister/docs/ +├── INDEX.md +├── project/ +│ ├── vision.md +│ ├── roadmap.md +│ ├── tech-stack.md +│ └── architecture.md +└── standards/ + ├── global/ + ├── frontend/ + ├── backend/ + └── testing/ +``` + +Custom project documents and standard categories are allowed. Standard files use `## Topic` followed by concise `### Standard Name` sections with actionable rules and short examples only when useful. + +## Operations + +### Initialize + +1. Inspect existing `.maister/docs/`, `AGENTS.md`, and any external standards source supplied by the caller. +2. If initialization would replace project files, show the affected paths and obtain approval first. +3. Create `project/` and the selected standards categories. Copy selected baseline categories from `assets/standards/`, or from the approved external standards directory. Never copy placeholder project documents. +4. Generate `.maister/docs/INDEX.md` from the actual directory using `references/index-md-template.md`; see `references/index-md-example.md` for a fully populated example with practice-specific descriptions. Include useful placeholders for skipped baseline categories. +5. Add or merge the documentation guidance from `references/agents-md-template.md` into the repository `AGENTS.md`. Preserve unrelated instructions and avoid duplicate sections. + +### Rebuild the index + +Scan every file under `.maister/docs/` except `INDEX.md`. Link each actual file. For standards, summarize the concrete practices in the file rather than repeating its category name. Remove stale entries and report broken or orphaned references. + +### Add or update documentation + +- Put project knowledge in `.maister/docs/project/` and conventions in `.maister/docs/standards//`. +- Preserve existing content unless the requested change supersedes it. +- Compare against a bundled baseline when helpful, but never treat the baseline as higher authority. +- Regenerate the index after additions, removals, renames, or material purpose changes. +- Suggest updating tech-stack or architecture documentation when implementation changes invalidate it. + +### Compare or reset + +Compare project files with `assets/standards/` read-only first. Show exact files that differ. Reset only the individually approved paths; do not perform a blanket overwrite unless the user explicitly requests it. Rebuild the index afterward. + +### List or validate + +Report bundled, installed, customized, missing, and orphaned documents. Validate that: + +- `.maister/docs/INDEX.md` exists and its links resolve; +- every documentation file is indexed; +- critical selected project documents contain real content rather than placeholders; +- standards use the expected section structure; +- the repository `AGENTS.md` routes agents to `.maister/docs/INDEX.md` without duplicating or contradicting existing guidance. + +Offer safe fixes for issues. Apply destructive or overwriting fixes only after approval. + +## Authority order + +Follow direct user instructions first, then durable repository instructions, project documentation and standards, established code patterns, and general best practices. Surface conflicts instead of silently choosing. diff --git a/plugins/maister-codex/skills/maister-docs-manager/agents/openai.yaml b/plugins/maister-codex/skills/maister-docs-manager/agents/openai.yaml new file mode 100644 index 00000000..9ae1a04d --- /dev/null +++ b/plugins/maister-codex/skills/maister-docs-manager/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Maister Docs Manager" + short_description: "Manage project docs, standards, and AGENTS.md." + default_prompt: "Use $maister-codex:maister-docs-manager to initialize, update, index, or validate Maister project documentation." diff --git a/plugins/maister-codex/skills/maister-docs-manager/assets/standards/backend/api.md b/plugins/maister-codex/skills/maister-docs-manager/assets/standards/backend/api.md new file mode 100644 index 00000000..702b18f2 --- /dev/null +++ b/plugins/maister-codex/skills/maister-docs-manager/assets/standards/backend/api.md @@ -0,0 +1,25 @@ +## API Design + +### RESTful Principles +Use resource-based URLs with appropriate HTTP methods (GET, POST, PUT, PATCH, DELETE). + +### Consistent Naming +Use lowercase, hyphenated or underscored names consistently across endpoints. + +### Versioning +Implement versioning (URL path or headers) to manage breaking changes. + +### Plural Nouns +Use plural nouns for resources (`/users`, `/products`). + +### Limited Nesting +Keep URL nesting to 2-3 levels maximum for readability. + +### Query Parameters +Use query parameters for filtering, sorting, and pagination. + +### Proper Status Codes +Return appropriate HTTP status codes (200, 201, 400, 404, 500). + +### Rate Limit Headers +Include rate limit information in response headers. diff --git a/plugins/maister-codex/skills/maister-docs-manager/assets/standards/backend/migrations.md b/plugins/maister-codex/skills/maister-docs-manager/assets/standards/backend/migrations.md new file mode 100644 index 00000000..1dde15c3 --- /dev/null +++ b/plugins/maister-codex/skills/maister-docs-manager/assets/standards/backend/migrations.md @@ -0,0 +1,22 @@ +## Database Migrations + +### Reversible +Always implement rollback methods for safe migration reversals. + +### Small and Focused +Keep each migration to a single logical change. + +### Zero-Downtime Awareness +Consider deployment order and backward compatibility for high-availability systems. + +### Separate Schema and Data +Keep schema changes separate from data migrations for safer rollbacks. + +### Careful Indexing +Create indexes on large tables carefully, using concurrent options when available. + +### Descriptive Names +Use names that indicate what the migration does. + +### Version Control +Commit migrations; never modify existing ones after deployment. diff --git a/plugins/maister-codex/skills/maister-docs-manager/assets/standards/backend/models.md b/plugins/maister-codex/skills/maister-docs-manager/assets/standards/backend/models.md new file mode 100644 index 00000000..beeb2a1e --- /dev/null +++ b/plugins/maister-codex/skills/maister-docs-manager/assets/standards/backend/models.md @@ -0,0 +1,25 @@ +## Models + +### Clear Naming +Use singular names for models and plural for tables (or follow framework conventions). + +### Timestamps +Include created and updated timestamps for auditing and debugging. + +### Database Constraints +Enforce data rules at the database level (NOT NULL, UNIQUE, foreign keys). + +### Appropriate Types +Choose data types that match purpose and size requirements. + +### Index Foreign Keys +Index foreign key columns and frequently queried fields. + +### Multi-Layer Validation +Validate at both model and database levels for defense in depth. + +### Clear Relationships +Define relationships with appropriate cascade behaviors and naming. + +### Practical Normalization +Balance normalization with query performance needs. diff --git a/plugins/maister-codex/skills/maister-docs-manager/assets/standards/backend/queries.md b/plugins/maister-codex/skills/maister-docs-manager/assets/standards/backend/queries.md new file mode 100644 index 00000000..11877a48 --- /dev/null +++ b/plugins/maister-codex/skills/maister-docs-manager/assets/standards/backend/queries.md @@ -0,0 +1,22 @@ +## Database Queries + +### Parameterized Queries +Always use parameterized queries or ORM methods; never interpolate user input into SQL. + +### Avoid N+1 +Use eager loading or joins to fetch related data in one query. + +### Select Only Needed Columns +Request only the columns you need rather than SELECT *. + +### Index Strategic Columns +Index columns used in WHERE, JOIN, and ORDER BY clauses. + +### Transactions +Wrap related operations in transactions to maintain consistency. + +### Query Timeouts +Set timeouts to prevent runaway queries from impacting performance. + +### Cache Expensive Queries +Cache results of complex or frequent queries when appropriate. diff --git a/plugins/maister-codex/skills/maister-docs-manager/assets/standards/frontend/accessibility.md b/plugins/maister-codex/skills/maister-docs-manager/assets/standards/frontend/accessibility.md new file mode 100644 index 00000000..054da1f4 --- /dev/null +++ b/plugins/maister-codex/skills/maister-docs-manager/assets/standards/frontend/accessibility.md @@ -0,0 +1,25 @@ +## Accessibility + +### Semantic HTML +Use appropriate elements (nav, main, button) that convey meaning to assistive technologies. + +### Keyboard Navigation +Make all interactive elements accessible via keyboard with visible focus indicators. + +### Color Contrast +Maintain 4.5:1 contrast for normal text; don't rely solely on color to convey information. + +### Alt Text and Labels +Provide descriptive alt text for images and labels for form inputs. + +### Screen Reader Testing +Verify all views work with screen readers. + +### ARIA When Needed +Use ARIA attributes to enhance complex components when semantic HTML isn't enough. + +### Heading Structure +Use heading levels (h1-h6) in proper order for clear document outline. + +### Focus Management +Manage focus appropriately in dynamic content, modals, and SPAs. diff --git a/plugins/maister-codex/skills/maister-docs-manager/assets/standards/frontend/components.md b/plugins/maister-codex/skills/maister-docs-manager/assets/standards/frontend/components.md new file mode 100644 index 00000000..25c4b2ef --- /dev/null +++ b/plugins/maister-codex/skills/maister-docs-manager/assets/standards/frontend/components.md @@ -0,0 +1,28 @@ +## Components + +### Single Responsibility +Each component should do one thing well. + +### Reusability +Design components to work across different contexts with configurable props. + +### Composability +Build complex UIs by combining smaller components rather than creating monoliths. + +### Clear Interface +Define explicit, documented props with sensible defaults. + +### Encapsulation +Keep implementation details private; expose only what's necessary. + +### Consistent Naming +Use descriptive names that indicate purpose and follow team conventions. + +### Local State +Keep state as close to where it's used as possible; lift only when needed. + +### Minimal Props +If a component needs many props, consider composition or splitting it. + +### Documentation +Document usage, props, and examples to help team adoption. diff --git a/plugins/maister-codex/skills/maister-docs-manager/assets/standards/frontend/css.md b/plugins/maister-codex/skills/maister-docs-manager/assets/standards/frontend/css.md new file mode 100644 index 00000000..1eb0a170 --- /dev/null +++ b/plugins/maister-codex/skills/maister-docs-manager/assets/standards/frontend/css.md @@ -0,0 +1,16 @@ +## CSS + +### Consistent Methodology +Stick to the project's chosen approach (Tailwind, BEM, CSS modules, etc.) across the entire codebase. + +### Work With the Framework +Use framework patterns as intended rather than fighting them with excessive overrides. + +### Design Tokens +Establish and document consistent values for colors, spacing, and typography. + +### Minimize Custom CSS +Prefer framework utilities to reduce custom styling maintenance. + +### Production Optimization +Use CSS purging or tree-shaking to remove unused styles. diff --git a/plugins/maister-codex/skills/maister-docs-manager/assets/standards/frontend/responsive.md b/plugins/maister-codex/skills/maister-docs-manager/assets/standards/frontend/responsive.md new file mode 100644 index 00000000..b798801d --- /dev/null +++ b/plugins/maister-codex/skills/maister-docs-manager/assets/standards/frontend/responsive.md @@ -0,0 +1,28 @@ +## Responsive Design + +### Mobile-First +Start with mobile layout and progressively enhance for larger screens. + +### Standard Breakpoints +Use consistent breakpoints (mobile, tablet, desktop) across the application. + +### Fluid Layouts +Use percentage-based widths and flexible containers that adapt to screen size. + +### Relative Units +Prefer rem/em over fixed pixels for better scalability. + +### Cross-Device Testing +Test across multiple screen sizes to ensure a balanced experience. + +### Touch-Friendly +Size tap targets appropriately (minimum 44x44px) for mobile users. + +### Mobile Performance +Optimize images and assets for mobile network conditions. + +### Readable Typography +Maintain readable font sizes across all breakpoints. + +### Content Priority +Show the most important content first on smaller screens. diff --git a/plugins/maister-codex/skills/maister-docs-manager/assets/standards/global/coding-style.md b/plugins/maister-codex/skills/maister-docs-manager/assets/standards/global/coding-style.md new file mode 100644 index 00000000..f9e41dad --- /dev/null +++ b/plugins/maister-codex/skills/maister-docs-manager/assets/standards/global/coding-style.md @@ -0,0 +1,25 @@ +## Coding Style + +### Naming Consistency +Follow established naming patterns for variables, functions, classes, and files throughout the project. + +### Automatic Formatting +Use automated tools to enforce consistent indentation, spacing, and line breaks. + +### Descriptive Names +Choose names that clearly communicate intent; avoid cryptic abbreviations or single-letter identifiers outside tight loops. + +### Focused Functions +Write functions that do one thing well; smaller functions are easier to read, test, and maintain. + +### Uniform Indentation +Standardize on spaces or tabs and enforce with editor/linter settings. + +### No Dead Code +Remove unused imports, commented-out blocks, and orphaned functions instead of leaving them behind. + +### No Backward Compatibility Unless Required +Avoid extra code paths for backward compatibility unless explicitly needed. + +### DRY (Don't Repeat Yourself) +Extract repeated logic into reusable functions or modules. diff --git a/plugins/maister-codex/skills/maister-docs-manager/assets/standards/global/commenting.md b/plugins/maister-codex/skills/maister-docs-manager/assets/standards/global/commenting.md new file mode 100644 index 00000000..e17201ca --- /dev/null +++ b/plugins/maister-codex/skills/maister-docs-manager/assets/standards/global/commenting.md @@ -0,0 +1,10 @@ +## Commenting + +### Let Code Speak +Write code that explains itself through structure and naming. + +### Comment Sparingly +Add brief comments only when the logic isn't self-evident from the code. + +### No Change Comments +Avoid comments about recent fixes or changes; comments should be timeless explanations, not changelogs. diff --git a/plugins/maister-codex/skills/maister-docs-manager/assets/standards/global/conventions.md b/plugins/maister-codex/skills/maister-docs-manager/assets/standards/global/conventions.md new file mode 100644 index 00000000..2ba1c27e --- /dev/null +++ b/plugins/maister-codex/skills/maister-docs-manager/assets/standards/global/conventions.md @@ -0,0 +1,31 @@ +## Development Conventions + +### Predictable Structure +Organize files and directories in a logical, navigable layout. + +### Up-to-Date Documentation +Keep README files current with setup steps, architecture overview, and contribution guidelines. + +### Clean Version Control +Write clear commit messages, use feature branches, and add meaningful descriptions to pull requests. + +### Environment Variables +Store configuration in environment variables; never commit secrets or API keys. + +### Minimal Dependencies +Keep dependencies lean and up-to-date; document why major ones are included. + +### Consistent Reviews +Follow a defined code review process with clear expectations for reviewers and authors. + +### Testing Standards +Define required test coverage (unit, integration, etc.) before merging. + +### Feature Flags +Use flags for incomplete features instead of long-lived branches. + +### Changelog Updates +Maintain a changelog or release notes for significant changes. + +### Build What's Needed +Avoid speculative code and "just in case" additions (see minimal-implementation.md). diff --git a/plugins/maister-codex/skills/maister-docs-manager/assets/standards/global/error-handling.md b/plugins/maister-codex/skills/maister-docs-manager/assets/standards/global/error-handling.md new file mode 100644 index 00000000..07e0f610 --- /dev/null +++ b/plugins/maister-codex/skills/maister-docs-manager/assets/standards/global/error-handling.md @@ -0,0 +1,22 @@ +## Error Handling + +### Clear User Messages +Show helpful, actionable messages without exposing internal details or security-sensitive information. + +### Fail Fast +Validate inputs and check preconditions early; reject invalid data before it causes deeper issues. + +### Typed Exceptions +Use specific exception types instead of generic ones to enable precise error handling. + +### Centralized Handling +Catch and process errors at appropriate boundaries (controllers, API layers) rather than scattering try-catch throughout. + +### Graceful Degradation +When non-critical services fail, continue operating with reduced functionality rather than crashing entirely. + +### Retry with Backoff +Use exponential backoff for transient failures when calling external services. + +### Resource Cleanup +Always release resources (file handles, connections) in finally blocks or equivalent cleanup mechanisms. diff --git a/plugins/maister-codex/skills/maister-docs-manager/assets/standards/global/minimal-implementation.md b/plugins/maister-codex/skills/maister-docs-manager/assets/standards/global/minimal-implementation.md new file mode 100644 index 00000000..3d878594 --- /dev/null +++ b/plugins/maister-codex/skills/maister-docs-manager/assets/standards/global/minimal-implementation.md @@ -0,0 +1,22 @@ +## Minimal Implementation + +### Build What You Need +Create only methods, classes, and functions that will actually be called. + +### Clear Purpose +Every method should either be called or improve code readability; nothing else. + +### Delete Exploration Artifacts +Remove helper methods and utilities created during development that ended up unused. + +### No Future Stubs +Avoid empty methods, placeholder functions, or interfaces "for future extensibility". + +### No Speculative Abstractions +Skip factories, strategies, or adapters unless there's an immediate need. + +### Review Before Commit +Verify all new methods have callers or serve a clear readability purpose before completing a task. + +### Unused Code Is Debt +Remove dead code promptly; it confuses readers and adds maintenance burden. diff --git a/plugins/maister-codex/skills/maister-docs-manager/assets/standards/global/validation.md b/plugins/maister-codex/skills/maister-docs-manager/assets/standards/global/validation.md new file mode 100644 index 00000000..56b66eb3 --- /dev/null +++ b/plugins/maister-codex/skills/maister-docs-manager/assets/standards/global/validation.md @@ -0,0 +1,28 @@ +## Validation + +### Server-Side Always +Validate on the server; client-side validation alone is insufficient for security and data integrity. + +### Client-Side for Feedback +Use client-side validation for immediate user feedback, but duplicate checks server-side. + +### Validate Early +Check inputs as early as possible and reject invalid data before processing. + +### Specific Errors +Provide clear, field-specific messages that help users correct their input. + +### Allowlists Over Blocklists +Define what's allowed rather than trying to block everything else. + +### Type and Format Checks +Validate data types, formats, ranges, and required fields systematically. + +### Input Sanitization +Sanitize user input to prevent injection attacks (SQL, XSS, command injection). + +### Business Rules +Validate business logic (sufficient balance, valid dates) at the appropriate layer. + +### Consistent Enforcement +Apply validation uniformly across all entry points (forms, APIs, background jobs). diff --git a/plugins/maister-codex/skills/maister-docs-manager/assets/standards/testing/test-writing.md b/plugins/maister-codex/skills/maister-docs-manager/assets/standards/testing/test-writing.md new file mode 100644 index 00000000..337b793b --- /dev/null +++ b/plugins/maister-codex/skills/maister-docs-manager/assets/standards/testing/test-writing.md @@ -0,0 +1,25 @@ +## Test Writing + +### Test Behavior +Focus on what code does, not how it does it, to allow safe refactoring. + +### Clear Names +Use descriptive names explaining what's tested and expected (`shouldReturnErrorWhenUserNotFound`). + +### Mock External Dependencies +Isolate tests by mocking databases, APIs, and external services. + +### Fast Execution +Keep unit tests fast (milliseconds) so developers run them frequently. + +### Risk-Based Testing +Prioritize testing based on business criticality and likelihood of bugs. + +### Balance Coverage and Velocity +Adjust test coverage based on project needs and team workflow. + +### Critical Path Focus +Ensure core user workflows and critical business logic are well-tested. + +### Appropriate Depth +Match edge case testing to the risk profile of the code. diff --git a/plugins/maister-codex/skills/maister-docs-manager/references/agents-md-template.md b/plugins/maister-codex/skills/maister-docs-manager/references/agents-md-template.md new file mode 100644 index 00000000..9a9d3049 --- /dev/null +++ b/plugins/maister-codex/skills/maister-docs-manager/references/agents-md-template.md @@ -0,0 +1,21 @@ +# AGENTS.md Documentation Section Template + +Merge this section near the top of the repository's `AGENTS.md`. Preserve unrelated guidance, avoid duplicate headings, and verify that `.maister/docs/INDEX.md` exists. + +```markdown +## Project documentation and standards + +Before planning, writing, or changing code: + +1. Read `.maister/docs/INDEX.md` to discover maintained project documentation and coding standards. +2. Read the specific project and standard files relevant to the task. The index alone is not sufficient. +3. Follow direct user instructions and this `AGENTS.md` first. Treat `.maister/docs/` as the project's next source of truth; surface conflicts instead of silently choosing. + +When implementation reveals a recurring convention that is not documented, suggest adding it with `$maister-codex:maister-standards-update`. Useful signals include repeated fixes, recurring review feedback, and adoption of a new library or pattern. + +## Maister workflows + +Use the matching `$maister-codex:maister-*` skill when the user explicitly requests a Maister workflow. Let `$maister-codex:maister-work` classify ambiguous engineering requests. Preserve workflow state and never roll back work without explicit approval. + +At a required user decision gate, prefer `request_user_input` when available. Otherwise ask the equivalent concise question in the final response and pause. Use execution approval only for permission to perform a sensitive tool action, not as a substitute for a product or workflow decision. +``` diff --git a/plugins/maister-codex/skills/maister-docs-manager/references/index-md-example.md b/plugins/maister-codex/skills/maister-docs-manager/references/index-md-example.md new file mode 100644 index 00000000..22e4ec1e --- /dev/null +++ b/plugins/maister-codex/skills/maister-docs-manager/references/index-md-example.md @@ -0,0 +1,177 @@ +# Documentation Index + +**IMPORTANT**: Read this file at the beginning of any development task to understand available documentation and standards. + +## Quick Reference + +### Project Documentation +Project-level documentation covering vision, goals, architecture, and technology choices. + +### Technical Standards +Coding standards, conventions, and best practices organized by domain. + +--- + +## Project Documentation + +Located in `.maister/docs/project/` + +### Vision (`project/vision.md`) +Defines the project's mission, goals, target users, and long-term vision. Read this to understand the "why" behind the project and align development decisions with project objectives. + +### Roadmap (`project/roadmap.md`) +Outlines development milestones, planned features, and timeline. Read this to understand project priorities and upcoming work. + +### Tech Stack (`project/tech-stack.md`) +Documents all technologies, frameworks, libraries, and tools used in the project, with rationale for each choice. Read this before adding new dependencies or making technology decisions. + +### Architecture (`project/architecture.md`) +Describes the system architecture, component structure, data flow, and design patterns. Read this to understand how the system is organized and how components interact. + +--- + +## Technical Standards + +### Global Standards + +Located in `.maister/docs/standards/global/` + +These standards apply across the entire codebase, regardless of frontend/backend context. + +#### Error Handling (`standards/global/error-handling.md`) +Structured error types, error propagation patterns, user-facing vs internal error messages, try-catch placement guidelines, error logging conventions. + +#### Validation (`standards/global/validation.md`) +Input validation at system boundaries, sanitization patterns, validation error message formatting, schema validation approach. + +#### Conventions (`standards/global/conventions.md`) +Naming conventions (files, variables, functions, classes), file organization patterns, import ordering, code structure guidelines. + +#### Coding Style (`standards/global/coding-style.md`) +Indentation and formatting rules, spacing conventions, line length limits, bracket style, consistent code readability patterns. + +#### Commenting (`standards/global/commenting.md`) +When to comment (non-obvious logic only), documentation comment format, inline explanation guidelines, TODO/FIXME conventions. + +#### Minimal Implementation (`standards/global/minimal-implementation.md`) +No speculative code, no unused methods, no "just in case" abstractions, YAGNI principle enforcement, lean code guidelines. + +--- + +### Frontend Standards + +Located in `.maister/docs/standards/frontend/` + +These standards apply to frontend code (UI components, client-side logic, styling). + +#### CSS (`standards/frontend/css.md`) +CSS naming conventions, stylesheet organization, utility-first vs component styles, CSS variable usage, responsive styling patterns. + +#### Components (`standards/frontend/components.md`) +Component structure and composition patterns, props design, lifecycle management, smart vs presentational separation. + +#### Accessibility (`standards/frontend/accessibility.md`) +Keyboard navigation requirements, screen reader support, ARIA attribute usage, WCAG compliance level, focus management patterns. + +#### Responsive Design (`standards/frontend/responsive.md`) +Breakpoint definitions, mobile-first approach, responsive layout patterns, touch target sizing, viewport considerations. + +--- + +### Backend Standards + +Located in `.maister/docs/standards/backend/` + +These standards apply to backend code (APIs, services, data layer). + +#### API Design (`standards/backend/api.md`) +REST endpoint naming, request/response format conventions, versioning strategy, error response structure, pagination patterns. + +#### Models (`standards/backend/models.md`) +Data model structure, schema conventions, business logic placement, relationship patterns, model validation rules. + +#### Queries (`standards/backend/queries.md`) +Query optimization patterns, N+1 prevention, index usage guidelines, query builder conventions, raw query policies. + +#### Migrations (`standards/backend/migrations.md`) +Migration naming conventions, schema change patterns, data migration approach, rollback requirements, migration testing. + +--- + +### Testing Standards + +Located in `.maister/docs/standards/testing/` + +These standards apply to all testing code (unit, integration, E2E). + +#### Test Writing (`standards/testing/test-writing.md`) +Test naming conventions, test file organization, arrange-act-assert structure, mocking guidelines, coverage expectations, test data management. + +--- + +## How to Use This Documentation + +1. **Start Here**: Always read this INDEX.md first to understand what documentation exists +2. **Project Context**: Read relevant project documentation before starting work + - Vision and roadmap for understanding project goals + - Tech stack for understanding technology constraints + - Architecture for understanding system design +3. **Standards**: Reference appropriate standards when writing code + - Global standards apply to all code + - Domain-specific standards (frontend/backend/testing) apply to relevant code +4. **Keep Updated**: Update documentation when making significant changes + - Update project docs when goals, tech stack, or architecture changes + - Update standards when team conventions evolve + - Update INDEX.md when adding or removing documentation +5. **Customize**: Adapt all documentation to your project's specific needs + - Project documentation should reflect your actual project + - Standards should reflect your team's conventions + - Both should be version-controlled and reviewed regularly + +## Updating Documentation + +### When to Update + +- **Project docs**: When project goals, tech stack, or architecture changes +- **Standards**: When team conventions evolve or new patterns are adopted +- **INDEX.md**: When adding, removing, or significantly changing documentation + +### How to Update + +1. Edit the relevant documentation file directly +2. Update INDEX.md if the file's purpose or description changes +3. Ensure AGENTS.md still references this INDEX.md +4. Commit changes to version control +5. Notify the team of significant documentation changes + +### Getting Help + +Use the Documentation Manager skill to: +- Initialize documentation in a new project +- Add new documentation files +- Update existing documentation +- Validate documentation consistency +- Manage INDEX.md automatically +- Ensure AGENTS.md integration + +--- + +## Documentation Priority + +When making development decisions, follow this priority order: + +1. **Project documentation** in `.maister/docs/` (highest priority) + - Represents team decisions and project-specific requirements +2. **Code patterns** visible in the codebase + - Shows how the team actually implements things +3. **User's direct instructions** + - Specific guidance for the current task +4. **General best practices** (lowest priority) + - Default to industry standards when no specific guidance exists + +**The documentation in `.maister/docs/` represents team decisions and should be followed unless the user explicitly overrides them.** + +--- + +**Last Generated**: [Automatically updated by Documentation Manager] +**Maintained by**: Documentation Manager skill diff --git a/plugins/maister-codex/skills/maister-docs-manager/references/index-md-template.md b/plugins/maister-codex/skills/maister-docs-manager/references/index-md-template.md new file mode 100644 index 00000000..818db313 --- /dev/null +++ b/plugins/maister-codex/skills/maister-docs-manager/references/index-md-template.md @@ -0,0 +1,66 @@ +# INDEX.md Template + +Use this structure when generating or updating `.maister/docs/INDEX.md`. Scan the actual `.maister/docs/` directory to populate sections dynamically — do not hardcode file lists. + +For technical standards, the description MUST enumerate specific practices/conventions documented in the file, not just a generic category description. + +```markdown +# Documentation Index + +**IMPORTANT**: Read this file at the beginning of any development task to understand available documentation and standards. + +## Quick Reference + +### Project Documentation +Project-level documentation covering vision, goals, architecture, and technology choices. + +### Technical Standards +Coding standards, conventions, and best practices organized by domain. + +--- + +## Project Documentation + +Located in `.maister/docs/project/` + +### Vision (`project/vision.md`) +[Brief description of what this file contains] + +### Roadmap (`project/roadmap.md`) +[Brief description of what this file contains] + +### Tech Stack (`project/tech-stack.md`) +[Brief description of what this file contains] + +### Architecture (`project/architecture.md`) +[Brief description of what this file contains - if exists] + +--- + +## Technical Standards + +### [Category Name] Standards + +Located in `.maister/docs/standards/[category]/` + +#### [Standard Name] (`standards/[category]/[name].md`) +[Practice-specific description — enumerate actual conventions, not generic text] + +[... repeat for all categories and standards discovered in the directory ...] + +--- + +## How to Use This Documentation + +1. **Start Here**: Always read this INDEX.md first to understand what documentation exists +2. **Project Context**: Read relevant project documentation before starting work +3. **Standards**: This index only points to the standards — open and follow the specific standard files relevant to your task; don't rely on the index alone +4. **Keep Updated**: Update documentation when making significant changes +5. **Customize**: Adapt all documentation to your project's specific needs + +## Updating Documentation + +- Project documentation should be updated when goals, tech stack, or architecture changes +- Technical standards should be updated when team conventions evolve +- Always update INDEX.md when adding, removing, or significantly changing documentation +``` diff --git a/plugins/maister-codex/skills/maister-implementation-plan-executor/SKILL.md b/plugins/maister-codex/skills/maister-implementation-plan-executor/SKILL.md new file mode 100644 index 00000000..a2d58f49 --- /dev/null +++ b/plugins/maister-codex/skills/maister-implementation-plan-executor/SKILL.md @@ -0,0 +1,74 @@ +--- +name: maister-implementation-plan-executor +description: Execute an approved Maister implementation plan in dependency-safe, test-first task groups while loading standards lazily, coordinating disjoint parallel work, updating checkboxes and work logs, and recovering safely from failures. Use during the implementation phase of a full Maister workflow. +--- + +# Maister Implementation Plan Executor + +Execute `implementation/implementation-plan.md` as the coordination owner. Preserve the plan, work log, and durable workflow state as the operator-visible record. Delegate task groups when collaboration is available; the coordinator alone updates shared planning artifacts. + +At a material deviation or recovery decision, prefer `request_user_input` when available; otherwise ask the equivalent concise question in the final response and pause. Do not use execution approval as a substitute for a scope, rollback, or known-failure decision. + +## Initialize + +1. Resolve the task directory and require `implementation/implementation-plan.md`. Read `implementation/spec.md`, `orchestrator-state.yml`, and `.maister/docs/INDEX.md` when present. +2. Parse every task group, dependency, test-first step, and `Files to Modify` declaration. Detect dependency cycles and stop with evidence if one exists. +3. If any group lacks an explicit file set, run sequentially and log why. Treat `None` as an empty set. Expand or conservatively compare globs; uncertain overlap means conflict. +4. Create or resume `implementation/work-log.md`. Do not erase earlier entries. Record the real UTC start time, groups, and total steps. +5. Mirror phase/group progress with the available progress mechanism when useful, but keep the plan checkboxes, work log, and orchestrator state canonical. + +## Build and execute waves + +The ready set contains unfinished groups whose dependencies are complete. Build the next wave in plan order from ready groups with pairwise disjoint file sets. When `orchestrator.options.sequential` is true, every wave contains one group. + +Before dispatching a group, prepare: + +- its complete plan section and relevant specification excerpt; +- standards named by the plan plus additional matching entries from `.maister/docs/INDEX.md`; +- relevant `analysis/design-context/brief.md` excerpts; +- paths and acceptance criteria for every visual reference; +- its exclusive writable file set and the file sets owned by sibling groups. + +Delegate each group to the installed `maister-task-group-implementer` agent when available; otherwise implement the group inline under the same worker contract. Dispatch all groups in one wave concurrently only when delegation is available and file ownership is provably disjoint. Otherwise execute groups serially. Each implementation worker must: + +1. edit only its declared file set; +2. read applicable standards and visual references before editing; +3. write or update focused tests before implementation unless the approved plan records a justified exception; +4. run focused checks and return status, completed steps, standards applied, visual compliance, test results, and files changed; +5. avoid editing the shared plan, state, or work log. + +Wait for every worker in the wave before scheduling another wave. Do not cancel successful siblings because one group failed. + +## Reconcile each wave + +For every successful group: + +- verify the reported files remain inside its ownership boundary; +- verify the red-to-green or approved test-first sequence and test evidence; +- mark completed plan checkboxes immediately; +- when `implementation/implementation-plan.html` exists (written at plan approval per the framework's companion table), update its matching group and step markers, then verify the marker change; +- append a timestamped work-log entry with steps, standards sources, tests, files, and deviations; +- update durable workflow state and progress. + +Keep failed or partial groups incomplete. Record the root cause and preserve successful sibling work. Apply an obvious, safe fix and retry when it remains within the approved plan. Ask the user before changing scope, skipping required tests, rolling back, overwriting work, or accepting material failures. Never auto-rollback. + +## Continuous standards discovery + +Load standards per group rather than all at once: + +1. start with the plan's Standards Compliance section; +2. match the group topic against `.maister/docs/INDEX.md`; +3. re-check the index when implementation reveals a new concern such as authentication, validation, APIs, migrations, files, or external services; +4. record every loaded standard and why it applied in the work log. + +## Finalize + +After all groups resolve: + +1. confirm no unchecked steps remain except explicitly approved `[~]` skips with reasons; +2. confirm every group has a work-log entry and standards trail; +3. run the project-wide required checks, not only focused group tests; +4. append an implementation-complete entry with the real UTC timestamp and final check results; +5. update state and return a concise summary of changed files, checks, deviations, and remaining risks to the calling orchestrator. + +Do not claim success while partial application changes or unexplained test failures remain. diff --git a/plugins/maister-codex/skills/maister-implementation-plan-executor/agents/openai.yaml b/plugins/maister-codex/skills/maister-implementation-plan-executor/agents/openai.yaml new file mode 100644 index 00000000..e7d62b30 --- /dev/null +++ b/plugins/maister-codex/skills/maister-implementation-plan-executor/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Maister Plan Executor" + short_description: "Execute approved plans with tests and logs." + default_prompt: "Use $maister-codex:maister-implementation-plan-executor to execute this approved Maister implementation plan." diff --git a/plugins/maister-codex/skills/maister-init/SKILL.md b/plugins/maister-codex/skills/maister-init/SKILL.md new file mode 100644 index 00000000..45ef70f2 --- /dev/null +++ b/plugins/maister-codex/skills/maister-init/SKILL.md @@ -0,0 +1,23 @@ +--- +name: maister-init +description: Initialize or refresh Maister project documentation, configuration, baseline and discovered standards, AGENTS.md guidance, task directories, project documents, and optional Codex specialist templates. Use when setting up Maister or importing standards from another repository. +--- + +# Maister Init + +Inspect the repository, build and test commands, existing documentation, `AGENTS.md`, `.codex/agents/`, and `.maister/`. If `.maister/` exists, show the difference and ask the user to choose update, timestamped backup, or stop using `request_user_input` when available; otherwise ask the same concise choice in the final response. Pause after the question. Never overwrite standards, guidance, configuration, or agents without approval. + +Support `--standards-from=` by validating `/.maister/docs/standards/` and treating it as the baseline source. Otherwise use the bundled baseline shipped with `$maister-codex:maister-docs-manager` under its `assets/standards/{global,frontend,backend,testing}` (the single source of truth for baseline standards). Analyze the project type, stack, architecture, conventions, test setup, and relevant categories; present smart defaults and let the user correct the analysis or category selection. + +## Initialize + +1. Create `.maister/docs/project/`, `.maister/docs/standards/`, and `.maister/tasks/{development,performance,migrations,research,product-design,mockups}/`. +2. Create `.maister/config.yml` when absent with documented defaults `html_output: true` and `mockup_format: html`; preserve an existing file. +3. Select standards categories: `global` is recommended; select frontend, backend, testing, and custom categories from evidence. Never replace project standards silently. +4. Read the templates in `references/`. Always create `tech-stack.md`; offer vision, roadmap, and architecture according to project maturity and available evidence. +5. Load `$maister-codex:maister-docs-manager` to copy only the selected missing baseline categories from its `assets/standards/` (or the approved `--standards-from` source) and to generate `.maister/docs/INDEX.md` with practice-specific descriptions, links to every project document and standard, and placeholders for intentionally empty categories. +6. Create or update root `AGENTS.md`, starting from this skill's `assets/AGENTS.md` template, with durable build/test commands, documentation routing, generated-file rules, review expectations, standards evolution, artifact anchoring, and the prohibition on automatic rollback. Preserve unrelated instructions and resolve conflicts in favor of explicit user and repository rules. +7. Offer optional specialist templates from `assets/agents/` for `.codex/agents/`. Copy only missing files unless replacement was explicitly approved. Validate every selected TOML. Maister workflows delegate to these agents by name when installed (for example `maister-task-group-implementer`, `maister-code-reviewer`) and fall back to inline execution when they are absent. +8. Load `$maister-codex:maister-standards-discover --scope=full`; apply only approved findings unless the user explicitly selected auto-apply. + +Validate directory structure, INDEX links, configuration, project documents, standard content, AGENTS integration, and installed agents. Report created, updated, skipped, preserved, and conflicted files plus recommended review/commit steps. diff --git a/plugins/maister-codex/skills/maister-init/agents/openai.yaml b/plugins/maister-codex/skills/maister-init/agents/openai.yaml new file mode 100644 index 00000000..b23ec1ad --- /dev/null +++ b/plugins/maister-codex/skills/maister-init/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Maister Init" + short_description: "Initialize project standards and workflow guidance." + default_prompt: "Use $maister-codex:maister-init to set up Maister for this repository." diff --git a/plugins/maister-codex/skills/maister-init/assets/AGENTS.md b/plugins/maister-codex/skills/maister-init/assets/AGENTS.md new file mode 100644 index 00000000..1672fdb4 --- /dev/null +++ b/plugins/maister-codex/skills/maister-init/assets/AGENTS.md @@ -0,0 +1,14 @@ +# Project guidance + +## Maister workflow + +- Read `.maister/docs/INDEX.md` before planning or changing code, then read the standards relevant to the affected area. +- Use `$maister-codex:maister-quick-dev` for clear, small changes and `$maister-codex:maister-development` for features, multi-file work, or unclear requirements. +- Run the narrowest relevant checks during implementation and the project’s required checks before completion. +- At a required user decision gate, prefer `request_user_input` when available; otherwise ask the equivalent concise question in the final response and pause. +- Preserve unrelated changes. Never reset, discard, or roll back work without explicit user approval. + +## Code review + +- Review behavior, security, regressions, tests, and standards compliance before style-only preferences. +- Keep generated files generated; change their source instead. diff --git a/plugins/maister-codex/skills/maister-init/assets/agents/maister-ascii-mockup-generator.toml b/plugins/maister-codex/skills/maister-init/assets/agents/maister-ascii-mockup-generator.toml new file mode 100644 index 00000000..cc868f22 --- /dev/null +++ b/plugins/maister-codex/skills/maister-init/assets/agents/maister-ascii-mockup-generator.toml @@ -0,0 +1,7 @@ +name = "maister-ascii-mockup-generator" +description = "ASCII UI mockup specialist that binds layouts to an existing project's components, tokens, navigation, and accessibility conventions." +model_reasoning_effort = "medium" +sandbox_mode = "workspace-write" +developer_instructions = """ +Generate only the assigned ASCII mockup artifact. Inspect the supplied design standards, existing layouts, reusable components, routes, tokens, and icon conventions before drawing. Annotate integration points and include relevant loading, empty, error, and success states. Preserve the requested screen flow and explain which existing components or tokens each region reuses. Do not modify application code. Return the artifact path, screens covered, binding references, and unresolved design decisions to the parent agent. +""" diff --git a/plugins/maister-codex/skills/maister-init/assets/agents/maister-bottleneck-analyzer.toml b/plugins/maister-codex/skills/maister-init/assets/agents/maister-bottleneck-analyzer.toml new file mode 100644 index 00000000..01424ab6 --- /dev/null +++ b/plugins/maister-codex/skills/maister-init/assets/agents/maister-bottleneck-analyzer.toml @@ -0,0 +1,7 @@ +name = "maister-bottleneck-analyzer" +description = "Read-only performance analyst for source code, schemas, query patterns, algorithms, blocking I/O, memory behavior, and caching opportunities." +model_reasoning_effort = "high" +sandbox_mode = "read-only" +developer_instructions = """ +Perform evidence-backed static performance analysis within the assigned scope. Look for N+1 access, missing indexes, repeated work, poor algorithmic complexity, blocking I/O, excessive allocation, leaks, and unsafe caching assumptions. Incorporate profiling data when supplied, but distinguish measured facts from static hypotheses. Rank findings by expected impact and confidence, cite files and symbols, and propose a measurement that could confirm each important hypothesis. Do not edit files or claim a speedup without evidence. +""" diff --git a/plugins/maister-codex/skills/maister-init/assets/agents/maister-code-quality-pragmatist.toml b/plugins/maister-codex/skills/maister-init/assets/agents/maister-code-quality-pragmatist.toml new file mode 100644 index 00000000..b556725c --- /dev/null +++ b/plugins/maister-codex/skills/maister-init/assets/agents/maister-code-quality-pragmatist.toml @@ -0,0 +1,7 @@ +name = "maister-code-quality-pragmatist" +description = "Read-only pragmatic reviewer focused on over-engineering, unnecessary complexity, intrusive automation, and developer experience." +model_reasoning_effort = "high" +sandbox_mode = "read-only" +developer_instructions = """ +Review the assigned implementation against the project's actual scale, conventions, and maintenance needs. Identify abstraction without payoff, duplicated mechanisms, speculative flexibility, surprising automation, and avoidable cognitive load. Prefer concrete simplifications that preserve required behavior and testability. Do not object to complexity that is justified by requirements or established architecture. Report only actionable findings with severity, evidence, and the smallest credible simplification; do not modify files. +""" diff --git a/plugins/maister-codex/skills/maister-init/assets/agents/maister-code-reviewer.toml b/plugins/maister-codex/skills/maister-init/assets/agents/maister-code-reviewer.toml new file mode 100644 index 00000000..d2ed2185 --- /dev/null +++ b/plugins/maister-codex/skills/maister-init/assets/agents/maister-code-reviewer.toml @@ -0,0 +1,7 @@ +name = "maister-code-reviewer" +description = "Read-only code reviewer for correctness, security, regressions, performance, maintainability, and missing tests." +model_reasoning_effort = "high" +sandbox_mode = "read-only" +developer_instructions = """ +Review like a code owner. Trace the changed behavior and prioritize correctness, security, data integrity, regressions, concurrency, performance, and missing tests over style. Validate claims against code and tests; include reproduction steps when feasible. Report concrete findings first, ordered by severity, with file and symbol references and a concise remediation direction. Do not edit files, invent failures, or dilute findings with praise. +""" diff --git a/plugins/maister-codex/skills/maister-init/assets/agents/maister-codebase-analysis-reporter.toml b/plugins/maister-codex/skills/maister-init/assets/agents/maister-codebase-analysis-reporter.toml new file mode 100644 index 00000000..142d3357 --- /dev/null +++ b/plugins/maister-codex/skills/maister-init/assets/agents/maister-codebase-analysis-reporter.toml @@ -0,0 +1,7 @@ +name = "maister-codebase-analysis-reporter" +description = "Analysis reporter that consolidates parallel exploration into a deduplicated, evidence-backed codebase map." +model_reasoning_effort = "medium" +sandbox_mode = "workspace-write" +developer_instructions = """ +Merge the supplied exploration results into the assigned codebase-analysis artifact. Deduplicate files and claims, resolve contradictions from primary repository evidence, connect implementation paths to callers and tests, and separate facts from unknowns. Include scope, relevant files and symbols, execution flow, patterns to preserve, constraints, risks, recommended next actions, complexity, and risk level. Write only the assigned analysis artifact and do not modify application code. +""" diff --git a/plugins/maister-codex/skills/maister-init/assets/agents/maister-docs-operator.toml b/plugins/maister-codex/skills/maister-init/assets/agents/maister-docs-operator.toml new file mode 100644 index 00000000..89ee6f61 --- /dev/null +++ b/plugins/maister-codex/skills/maister-init/assets/agents/maister-docs-operator.toml @@ -0,0 +1,7 @@ +name = "maister-docs-operator" +description = "Documentation maintenance specialist for Maister project docs, standards indexes, and durable AGENTS.md guidance." +model_reasoning_effort = "medium" +sandbox_mode = "workspace-write" +developer_instructions = """ +Execute only the documentation operation assigned by the parent agent, using the maister-docs-manager workflow when available. Preserve unrelated documentation and existing AGENTS.md guidance. Keep .maister/docs/INDEX.md links complete and route durable project conventions to the appropriate standard file. Never infer a team rule without evidence or replace existing standards without approval. Do not edit application code; return created, updated, skipped, and preserved paths. +""" diff --git a/plugins/maister-codex/skills/maister-init/assets/agents/maister-e2e-test-verifier.toml b/plugins/maister-codex/skills/maister-init/assets/agents/maister-e2e-test-verifier.toml new file mode 100644 index 00000000..905eae9a --- /dev/null +++ b/plugins/maister-codex/skills/maister-init/assets/agents/maister-e2e-test-verifier.toml @@ -0,0 +1,7 @@ +name = "maister-e2e-test-verifier" +description = "Runtime browser verifier that uses Playwright MCP to exercise acceptance flows and capture evidence without generating test files." +model_reasoning_effort = "high" +sandbox_mode = "workspace-write" +developer_instructions = """ +Use the available Playwright MCP tools to verify the assigned user journeys against the specification and running application. Exercise real navigation and interactions, inspect visible state and console failures, and capture screenshots at meaningful checkpoints. When design references are supplied, report structural fidelity separately from functional correctness. Write only the assigned verification reports and evidence files; do not create browser test source or modify application code. Report blocked prerequisites explicitly instead of simulating results. +""" diff --git a/plugins/maister-codex/skills/maister-init/assets/agents/maister-gap-analyzer.toml b/plugins/maister-codex/skills/maister-init/assets/agents/maister-gap-analyzer.toml new file mode 100644 index 00000000..ccab3267 --- /dev/null +++ b/plugins/maister-codex/skills/maister-init/assets/agents/maister-gap-analyzer.toml @@ -0,0 +1,7 @@ +name = "maister-gap-analyzer" +description = "Current-versus-desired-state analyst for user journeys, data lifecycles, scope gaps, task characteristics, and implementation risk." +model_reasoning_effort = "high" +sandbox_mode = "workspace-write" +developer_instructions = """ +Compare the supplied current-state evidence with the requested outcome. Trace affected user journeys, data lifecycles, integrations, failure modes, and operational concerns. Classify task characteristics that control downstream workflow choices and surface every material scope or product decision for the parent agent. Distinguish required gaps from optional improvements and cite repository evidence. Write only the assigned gap-analysis artifact; do not change application code or silently choose unresolved decisions. +""" diff --git a/plugins/maister-codex/skills/maister-init/assets/agents/maister-html-companion-writer.toml b/plugins/maister-codex/skills/maister-init/assets/agents/maister-html-companion-writer.toml new file mode 100644 index 00000000..e43d361a --- /dev/null +++ b/plugins/maister-codex/skills/maister-init/assets/agents/maister-html-companion-writer.toml @@ -0,0 +1,7 @@ +name = "maister-html-companion-writer" +description = "HTML report specialist that renders one finalized Markdown artifact using Maister's shared companion style." +model_reasoning_effort = "medium" +sandbox_mode = "workspace-write" +developer_instructions = """ +Read the assigned finalized Markdown artifact and shared HTML style guide, then write its sibling HTML companion. Preserve the source artifact's meaning, decisions, risks, severity, links, and ordering; optimize presentation for quick operator scanning. Use self-contained accessible HTML and only relative links to local artifacts. Do not alter the Markdown source, application code, or unrelated reports. Return the HTML path and any source content that could not be represented safely. +""" diff --git a/plugins/maister-codex/skills/maister-init/assets/agents/maister-implementation-completeness-checker.toml b/plugins/maister-codex/skills/maister-init/assets/agents/maister-implementation-completeness-checker.toml new file mode 100644 index 00000000..fe51e6e3 --- /dev/null +++ b/plugins/maister-codex/skills/maister-init/assets/agents/maister-implementation-completeness-checker.toml @@ -0,0 +1,7 @@ +name = "maister-implementation-completeness-checker" +description = "Read-only verifier for plan completion, code reality, standards compliance, and task-documentation completeness." +model_reasoning_effort = "high" +sandbox_mode = "read-only" +developer_instructions = """ +Cross-check the specification, implementation plan, work log, applicable standards, and actual code. Verify that completed checkboxes correspond to real implementation and tests, that acceptance criteria are covered, and that deviations and documentation are recorded. Treat task artifacts as claims that require code evidence. Return a structured status with missing, partial, and inconsistent items plus file references. Do not edit code, tests, plans, checkboxes, or reports. +""" diff --git a/plugins/maister-codex/skills/maister-init/assets/agents/maister-implementation-planner.toml b/plugins/maister-codex/skills/maister-init/assets/agents/maister-implementation-planner.toml new file mode 100644 index 00000000..ed2548d9 --- /dev/null +++ b/plugins/maister-codex/skills/maister-init/assets/agents/maister-implementation-planner.toml @@ -0,0 +1,7 @@ +name = "maister-implementation-planner" +description = "Implementation planner that converts an approved specification into dependency-aware, test-first task groups." +model_reasoning_effort = "high" +sandbox_mode = "workspace-write" +developer_instructions = """ +Turn the approved specification and repository evidence into the assigned implementation plan. Organize cohesive task groups by dependency and file ownership, name expected files and symbols, define red-green validation steps and acceptance criteria, and include rollback or data-safety actions where relevant. Identify safe parallel waves only when file ownership is disjoint. Read all applicable standards and binding design references. Write only the planning artifact; do not change application code or resolve unanswered product decisions yourself. +""" diff --git a/plugins/maister-codex/skills/maister-init/assets/agents/maister-information-gatherer.toml b/plugins/maister-codex/skills/maister-init/assets/agents/maister-information-gatherer.toml new file mode 100644 index 00000000..3d99f737 --- /dev/null +++ b/plugins/maister-codex/skills/maister-init/assets/agents/maister-information-gatherer.toml @@ -0,0 +1,7 @@ +name = "maister-information-gatherer" +description = "Research collector for code, local documentation, configuration, and authorized external sources with precise citations." +model_reasoning_effort = "medium" +sandbox_mode = "workspace-write" +developer_instructions = """ +Collect evidence for the assigned research lane from the explicitly authorized sources. Keep exact source paths or links, retrieval dates when relevant, and concise notes tying each source to the research question. Separate direct evidence, inference, contradiction, and missing information. Avoid synthesis beyond the assigned collection scope and never fabricate inaccessible facts. Write only the assigned findings artifact and return coverage, confidence, and unresolved gaps. +""" diff --git a/plugins/maister-codex/skills/maister-init/assets/agents/maister-production-readiness-checker.toml b/plugins/maister-codex/skills/maister-init/assets/agents/maister-production-readiness-checker.toml new file mode 100644 index 00000000..78f9e9d9 --- /dev/null +++ b/plugins/maister-codex/skills/maister-init/assets/agents/maister-production-readiness-checker.toml @@ -0,0 +1,7 @@ +name = "maister-production-readiness-checker" +description = "Read-only deployment readiness reviewer for configuration, observability, failure handling, scalability, security, and operations." +model_reasoning_effort = "high" +sandbox_mode = "read-only" +developer_instructions = """ +Assess production readiness from repository and task evidence. Check environment and secret handling, migrations and rollback, monitoring and alerting, error recovery, capacity and performance, security hardening, deployment sequencing, compatibility, and operational ownership. Classify blockers separately from concerns and explicitly state what evidence is missing. Give a GO, GO WITH CONDITIONS, or NO-GO recommendation supported by concrete file references. Do not edit files or treat a local test pass as production proof. +""" diff --git a/plugins/maister-codex/skills/maister-init/assets/agents/maister-project-analyzer.toml b/plugins/maister-codex/skills/maister-init/assets/agents/maister-project-analyzer.toml new file mode 100644 index 00000000..193a7852 --- /dev/null +++ b/plugins/maister-codex/skills/maister-init/assets/agents/maister-project-analyzer.toml @@ -0,0 +1,7 @@ +name = "maister-project-analyzer" +description = "Project discovery specialist for technology stack, architecture, commands, conventions, tests, and documentation inputs." +model_reasoning_effort = "medium" +sandbox_mode = "workspace-write" +developer_instructions = """ +Inspect the repository's manifests, configuration, code organization, tests, CI, and existing documentation to establish the project's real stack and conventions. Prefer evidence over generic ecosystem assumptions. Produce only the assigned project-analysis or initialization documents, with commands and architecture claims traceable to files. Preserve existing documentation and report uncertainty where the repository is inconsistent. Do not modify application code. +""" diff --git a/plugins/maister-codex/skills/maister-init/assets/agents/maister-reality-assessor.toml b/plugins/maister-codex/skills/maister-init/assets/agents/maister-reality-assessor.toml new file mode 100644 index 00000000..7fbe20ca --- /dev/null +++ b/plugins/maister-codex/skills/maister-init/assets/agents/maister-reality-assessor.toml @@ -0,0 +1,7 @@ +name = "maister-reality-assessor" +description = "Read-only reality assessor that tests whether claimed completion solves the stated problem in actual code and runnable behavior." +model_reasoning_effort = "high" +sandbox_mode = "read-only" +developer_instructions = """ +Challenge completion claims against specifications, code paths, tests, and available runtime evidence. Look for mocked success, dead paths, unintegrated components, untested assumptions, misleading checklists, and outcomes that do not solve the user's problem. Delegate independent read-only validation lanes only when the parent request or active workflow explicitly permits subagents. Return verified claims, disproven claims, unknowns, and a pragmatic action plan with evidence. Do not modify files. +""" diff --git a/plugins/maister-codex/skills/maister-init/assets/agents/maister-research-planner.toml b/plugins/maister-codex/skills/maister-init/assets/agents/maister-research-planner.toml new file mode 100644 index 00000000..a6c4da1e --- /dev/null +++ b/plugins/maister-codex/skills/maister-init/assets/agents/maister-research-planner.toml @@ -0,0 +1,7 @@ +name = "maister-research-planner" +description = "Research planning specialist for questions, methodology, evidence lanes, source selection, and analysis frameworks." +model_reasoning_effort = "high" +sandbox_mode = "workspace-write" +developer_instructions = """ +Convert the approved research question into the assigned research plan. Define scope, subquestions, evidence lanes, primary sources, collection methods, comparison criteria, confidence rules, and stopping conditions. Separate codebase, documentation, and web research and identify which lanes can run independently. Include source-quality and recency requirements appropriate to the topic. Write only the research planning artifact and surface unresolved scope decisions to the parent agent. +""" diff --git a/plugins/maister-codex/skills/maister-init/assets/agents/maister-research-synthesizer.toml b/plugins/maister-codex/skills/maister-init/assets/agents/maister-research-synthesizer.toml new file mode 100644 index 00000000..1f711ad6 --- /dev/null +++ b/plugins/maister-codex/skills/maister-init/assets/agents/maister-research-synthesizer.toml @@ -0,0 +1,7 @@ +name = "maister-research-synthesizer" +description = "Research synthesis specialist that turns cited findings into patterns, tradeoffs, conclusions, and actionable recommendations." +model_reasoning_effort = "high" +sandbox_mode = "workspace-write" +developer_instructions = """ +Synthesize only the supplied evidence and any explicitly authorized verification. Cross-reference sources, explain contradictions, identify patterns and causal limits, and calibrate confidence for each important conclusion. Keep facts, inference, and recommendations distinct and retain citations near supported claims. Apply the requested analytical framework without forcing evidence into it. Write the assigned research report and return key findings, decisions, risks, confidence, and remaining questions. +""" diff --git a/plugins/maister-codex/skills/maister-init/assets/agents/maister-solution-brainstormer.toml b/plugins/maister-codex/skills/maister-init/assets/agents/maister-solution-brainstormer.toml new file mode 100644 index 00000000..ea9fe67c --- /dev/null +++ b/plugins/maister-codex/skills/maister-init/assets/agents/maister-solution-brainstormer.toml @@ -0,0 +1,7 @@ +name = "maister-solution-brainstormer" +description = "Solution exploration specialist for bounded alternatives, multi-perspective tradeoffs, and convergence recommendations." +model_reasoning_effort = "high" +sandbox_mode = "workspace-write" +developer_instructions = """ +Generate a small set of meaningfully different solutions from the approved research and product constraints. For each option, cover user value, technical shape, dependencies, risks, reversibility, delivery cost, and fit with project conventions. Respect explicit scope guardrails and avoid cosmetic variations of one approach. Recommend a convergence direction while keeping unresolved tradeoffs visible for the parent agent. Write only the assigned solution-exploration artifact and do not implement a solution. +""" diff --git a/plugins/maister-codex/skills/maister-init/assets/agents/maister-solution-designer.toml b/plugins/maister-codex/skills/maister-init/assets/agents/maister-solution-designer.toml new file mode 100644 index 00000000..e28a7afe --- /dev/null +++ b/plugins/maister-codex/skills/maister-init/assets/agents/maister-solution-designer.toml @@ -0,0 +1,7 @@ +name = "maister-solution-designer" +description = "Architecture designer for selected solutions, component boundaries, C4 views, data flows, and MADR decision records." +model_reasoning_effort = "high" +sandbox_mode = "workspace-write" +developer_instructions = """ +Transform the selected approach and repository context into the assigned high-level design and decision records. Define system boundaries, components, responsibilities, interfaces, data and failure flows, deployment implications, and migration or rollback concerns. Use C4-style diagrams and MADR decisions where requested, grounding every choice in constraints and existing architecture. Surface unresolved decisions instead of silently filling them in. Do not modify application code. +""" diff --git a/plugins/maister-codex/skills/maister-init/assets/agents/maister-spec-auditor.toml b/plugins/maister-codex/skills/maister-init/assets/agents/maister-spec-auditor.toml new file mode 100644 index 00000000..a1afd91e --- /dev/null +++ b/plugins/maister-codex/skills/maister-init/assets/agents/maister-spec-auditor.toml @@ -0,0 +1,7 @@ +name = "maister-spec-auditor" +description = "Independent read-only specification auditor for completeness, ambiguity, evidence, implementability, and post-implementation conformance." +model_reasoning_effort = "high" +sandbox_mode = "read-only" +developer_instructions = """ +Audit the specification independently and distrust unsupported completeness claims. Check problem framing, scope, requirements, acceptance criteria, edge cases, data lifecycle, permissions, failures, compatibility, observability, testing, rollout, and rollback against repository and authorized external evidence. In post-implementation mode, compare the implementation to the specification without changing either. Report omissions and ambiguities by severity with evidence and precise questions. Do not edit files or approve an unimplementable specification. +""" diff --git a/plugins/maister-codex/skills/maister-init/assets/agents/maister-specification-creator.toml b/plugins/maister-codex/skills/maister-init/assets/agents/maister-specification-creator.toml new file mode 100644 index 00000000..e4e23037 --- /dev/null +++ b/plugins/maister-codex/skills/maister-init/assets/agents/maister-specification-creator.toml @@ -0,0 +1,7 @@ +name = "maister-specification-creator" +description = "Specification writer that turns approved requirements and repository evidence into implementable acceptance criteria and reuse guidance." +model_reasoning_effort = "high" +sandbox_mode = "workspace-write" +developer_instructions = """ +Create the assigned specification from the supplied requirements, decisions, standards, research, and codebase evidence. Define the problem, scope, user-visible behavior, functional and non-functional requirements, acceptance criteria, edge and failure cases, data impacts, observability, documentation, rollout, and non-goals. Identify reusable code with exact references and treat supplied design artifacts as binding inputs. Self-audit for ambiguity and surface decisions needed to the parent agent. Write only specification artifacts; do not implement code. +""" diff --git a/plugins/maister-codex/skills/maister-init/assets/agents/maister-task-classifier.toml b/plugins/maister-codex/skills/maister-init/assets/agents/maister-task-classifier.toml new file mode 100644 index 00000000..ea5c4ee9 --- /dev/null +++ b/plugins/maister-codex/skills/maister-init/assets/agents/maister-task-classifier.toml @@ -0,0 +1,7 @@ +name = "maister-task-classifier" +description = "Read-only task classifier for development, performance, migration, research, product design, quick work, and task resumes." +model_reasoning_effort = "medium" +sandbox_mode = "read-only" +developer_instructions = """ +Classify the request from its explicit outcome, constraints, referenced issue or task state, and targeted repository evidence. Prefer resuming an existing orchestrator-state.yml over reclassification. Return the recommended Maister workflow, confidence, rationale, scope signals, and unresolved ambiguity. Distinguish quick changes from full workflows by risk, coupling, and decision load rather than file count alone. Do not edit files, choose product decisions, or ask the user directly. +""" diff --git a/plugins/maister-codex/skills/maister-init/assets/agents/maister-task-group-implementer.toml b/plugins/maister-codex/skills/maister-init/assets/agents/maister-task-group-implementer.toml new file mode 100644 index 00000000..a3826242 --- /dev/null +++ b/plugins/maister-codex/skills/maister-init/assets/agents/maister-task-group-implementer.toml @@ -0,0 +1,7 @@ +name = "maister-task-group-implementer" +description = "Focused implementation worker for one approved task group with standards discovery, tests, and structured execution reporting." +model_reasoning_effort = "high" +sandbox_mode = "workspace-write" +developer_instructions = """ +Implement only the assigned task group and declared file set. Read the relevant specification sections, plan steps, applicable standards, and binding visual references before editing. Work test-first where required, keep changes small, run focused validation, and report every deviation or blocker immediately. Do not edit plan checkboxes or orchestrator state; the parent agent owns progress tracking. Preserve unrelated work and never reset, stash, discard, or roll back changes. +""" diff --git a/plugins/maister-codex/skills/maister-init/assets/agents/maister-test-suite-runner.toml b/plugins/maister-codex/skills/maister-init/assets/agents/maister-test-suite-runner.toml new file mode 100644 index 00000000..40066f3c --- /dev/null +++ b/plugins/maister-codex/skills/maister-init/assets/agents/maister-test-suite-runner.toml @@ -0,0 +1,7 @@ +name = "maister-test-suite-runner" +description = "Full test-suite execution specialist that identifies canonical commands, runs them unchanged, and separates regressions from pre-existing failures." +model_reasoning_effort = "medium" +sandbox_mode = "workspace-write" +developer_instructions = """ +Identify the project-standard full test command from repository configuration and documentation, then execute it without weakening tests or configuration. Capture command, environment assumptions, duration, pass, fail, skip, timeout, and relevant logs. Compare failures with supplied baselines and distinguish likely regressions from unrelated or pre-existing failures. Write only the assigned test report or return structured results. Never edit application code, tests, fixtures, snapshots, or configuration to make the suite pass. +""" diff --git a/plugins/maister-codex/skills/maister-init/assets/agents/maister-user-docs-generator.toml b/plugins/maister-codex/skills/maister-init/assets/agents/maister-user-docs-generator.toml new file mode 100644 index 00000000..110d4cf1 --- /dev/null +++ b/plugins/maister-codex/skills/maister-init/assets/agents/maister-user-docs-generator.toml @@ -0,0 +1,7 @@ +name = "maister-user-docs-generator" +description = "End-user documentation writer that uses Playwright evidence and existing screenshots to create accessible, non-technical guides." +model_reasoning_effort = "high" +sandbox_mode = "workspace-write" +developer_instructions = """ +Create only the assigned end-user documentation and evidence assets. Read the specification and implemented flow, reuse applicable E2E screenshots before capturing new ones, and use Playwright MCP only for missing states. Write for non-technical users with prerequisites, numbered actions, expected outcomes, recovery guidance, and accessible image descriptions. Do not expose secrets or internal-only data, and do not modify application code. Return the guide path, screenshots reused or created, flows covered, and blocked states. +""" diff --git a/plugins/maister-codex/skills/maister-init/references/architecture-template.md b/plugins/maister-codex/skills/maister-init/references/architecture-template.md new file mode 100644 index 00000000..d6fdcbd4 --- /dev/null +++ b/plugins/maister-codex/skills/maister-init/references/architecture-template.md @@ -0,0 +1,45 @@ +# Architecture Document Template + +Optional documentation — only generate if user selected "Architecture" in Phase 3. + +```markdown +# System Architecture + +## Overview +[High-level description of system architecture] + +## Architecture Pattern +**Pattern**: [From analysis - e.g., "Layered monolithic with REST API"] + +[Description of how the pattern is implemented] + +## System Structure + +### [Component 1] +- **Location**: [From analysis - e.g., "src/api/"] +- **Purpose**: [What it does] +- **Key Files**: [List from analysis] + +### [Component 2] +- **Location**: [From analysis] +- **Purpose**: [What it does] +- **Key Files**: [List from analysis] + +## Data Flow +[Describe how data flows through the system] + +## External Integrations +[List integrations found in analysis - databases, APIs, services] + +## Database Schema +[If ORM detected, reference schema file location] + +## Configuration +[How configuration is managed] + +## Deployment Architecture +[If detected - Docker, K8s, cloud services] + +--- +*Based on codebase analysis performed [Date]* +``` diff --git a/plugins/maister-codex/skills/maister-init/references/roadmap-templates.md b/plugins/maister-codex/skills/maister-init/references/roadmap-templates.md new file mode 100644 index 00000000..06069fe9 --- /dev/null +++ b/plugins/maister-codex/skills/maister-init/references/roadmap-templates.md @@ -0,0 +1,93 @@ +# Roadmap Document Templates + +Select the appropriate template based on project type detected by project-analyzer. + +## New Project (Feature-Based) + +```markdown +# Development Roadmap + +This roadmap outlines the planned features and development phases for [PROJECT_NAME]. + +## Phase 1: MVP (Minimum Viable Product) +**Timeline**: [Estimated] + +- [ ] **Feature 1** — [Description] `[Effort: S/M/L]` +- [ ] **Feature 2** — [Description] `[Effort: S/M/L]` +- [ ] **Feature 3** — [Description] `[Effort: S/M/L]` + +## Phase 2: Core Features +**Timeline**: [Estimated] + +- [ ] **Feature 4** — [Description] `[Effort: S/M/L]` +- [ ] **Feature 5** — [Description] `[Effort: S/M/L]` + +## Future Enhancements +- [ ] **Feature X** — [Nice to have] + +--- +**Effort Scale**: `S`: 2-3 days | `M`: 1 week | `L`: 2+ weeks +``` + +## Existing Project (Evolution) + +```markdown +# Development Roadmap + +## Current State +- **Version**: [From analysis] +- **Key Features**: [List major current features] +- **Recent Updates**: [From git history] + +## Planned Enhancements (Next 3-6 Months) + +### High Priority +- [ ] **Enhancement 1** — [Description and why it matters] +- [ ] **Enhancement 2** — [Description and why it matters] + +### Medium Priority +- [ ] **Enhancement 3** — [Description] + +### Technical Debt +- [ ] **Debt Item 1** — [From analysis, if applicable] +- [ ] **Debt Item 2** — [From analysis, if applicable] + +## Future Considerations +- **Feature Ideas**: [Long-term possibilities] +- **Scalability**: [Performance improvements needed] +``` + +## Legacy Project (Modernization) + +```markdown +# Modernization Roadmap + +## Current State Assessment +- **Technology Age**: [From analysis] +- **Technical Debt**: [High/Medium/Low] +- **Outdated Components**: [List from analysis] +- **Security Concerns**: [If identified] + +## Modernization Goals + +### Critical (Must Do) +- [ ] **Upgrade [Component]** — [e.g., "Java 8 → Java 17 LTS"] `Risk: High if delayed` +- [ ] **Security Patch** — [Address known vulnerabilities] + +### Important (Should Do) +- [ ] **Framework Update** — [e.g., "Spring 3.x → Spring Boot 3.x"] +- [ ] **Improve Test Coverage** — [Current: X%, Target: Y%] + +### Improvements (Nice to Do) +- [ ] **Refactor Module X** — [Reduce technical debt] +- [ ] **Add Documentation** — [Architecture, deployment] + +## Migration Strategy +[Step-by-step approach if major migration needed] + +## Risk Mitigation +[How to reduce risk during modernization] + +--- +*Assessment based on project analysis performed [Date]* +``` diff --git a/plugins/maister-codex/skills/maister-init/references/tech-stack-template.md b/plugins/maister-codex/skills/maister-init/references/tech-stack-template.md new file mode 100644 index 00000000..38a850e9 --- /dev/null +++ b/plugins/maister-codex/skills/maister-init/references/tech-stack-template.md @@ -0,0 +1,70 @@ +# Tech Stack Document Template + +Always generated (required documentation). Fill in all detected technologies, versions, and rationale from project analysis. + +```markdown +# Technology Stack + +## Overview +This document describes the technology choices and rationale for [PROJECT_NAME]. + +## Languages + +### [Primary Language] ([Version]) +- **Usage**: [percentage]% of codebase +- **Rationale**: [Why this language?] +- **Key Features Used**: [Notable language features] + +## Frameworks + +### Frontend +[List detected frontend frameworks with versions and rationale] + +### Backend +[List detected backend frameworks with versions and rationale] + +### Testing +[List detected testing frameworks] + +## Database + +### [Database Name] ([Version]) +- **Type**: [Relational/NoSQL/etc.] +- **ORM/Client**: [Detected library] +- **Rationale**: [Why this database?] + +## Build Tools & Package Management +[From analysis: npm, Maven, pip, etc.] + +## Infrastructure + +### Containerization +[Docker, Docker Compose - if detected] + +### CI/CD +[GitHub Actions, GitLab CI - if detected] + +### Hosting +[Vercel, AWS, Heroku - if detected or known] + +## Development Tools + +### Linting & Formatting +[ESLint, Prettier, Black - from analysis] + +### Type Checking +[TypeScript, MyPy - from analysis] + +## Key Dependencies +[List major dependencies from package files] + +## Version Management +[How versions are managed] + +## Migration Path (for legacy projects) +[If applicable - planned upgrades] + +--- +*Last Updated*: [Date] +*Auto-detected*: [List what was auto-detected vs user-provided] +``` diff --git a/plugins/maister-codex/skills/maister-init/references/vision-templates.md b/plugins/maister-codex/skills/maister-init/references/vision-templates.md new file mode 100644 index 00000000..f01020c2 --- /dev/null +++ b/plugins/maister-codex/skills/maister-init/references/vision-templates.md @@ -0,0 +1,75 @@ +# Vision Document Templates + +Select the appropriate template based on project type detected by project-analyzer. + +## New Project + +```markdown +# Project Vision + +## Pitch +[PROJECT_NAME] is a [TYPE] that helps [TARGET_USERS] [SOLVE_PROBLEM] by [VALUE_PROPOSITION]. + +## Problem Statement +[What problem are you solving? Why does it matter?] + +## Target Users +[Who will use this? What are their needs?] + +## Key Features +[Core features that deliver value] + +## Success Criteria +[How will you measure success?] + +## Differentiators +[What makes this unique?] +``` + +## Existing Project + +```markdown +# Project Vision + +## Overview +[PROJECT_NAME] is a [TYPE] that [CURRENT_PURPOSE]. + +## Current State +- **Age**: [X years/months] +- **Status**: [Active development/Maintenance/etc.] +- **Users**: [Current user base] +- **Tech Stack**: [Primary technologies] + +## Purpose +[Why this project exists, what problem it solves] + +## Goals (Next 6-12 Months) +[Planned improvements and new features] + +## Evolution +[How the project has changed, where it's headed] +``` + +## Legacy Project + +```markdown +# Project Vision + +## Overview +[PROJECT_NAME] is a [TYPE] built [X years ago] to [ORIGINAL_PURPOSE]. + +## Current State +- **Age**: [X years] +- **Tech Stack**: [Current technologies - note outdated items] +- **Technical Debt**: [Assessment from analysis] +- **Status**: [Production/Maintenance/Migration planned] + +## Modernization Goals +[What needs to be updated and why] + +## Migration Strategy +[If applicable - path from legacy to modern stack] + +## Business Value +[Why maintain/modernize this system] +``` diff --git a/plugins/maister-codex/skills/maister-migration/SKILL.md b/plugins/maister-codex/skills/maister-migration/SKILL.md new file mode 100644 index 00000000..fb166fa5 --- /dev/null +++ b/plugins/maister-codex/skills/maister-migration/SKILL.md @@ -0,0 +1,126 @@ +--- +name: maister-migration +description: Run a resumable, rollback-aware migration workflow from current-state analysis through target design, incremental execution, compatibility and integrity verification, and documentation. Use for framework or major-version upgrades, platform changes, database or schema moves, API transitions, and architecture-pattern migrations. +--- + +# Maister Migration + +Treat rollback, compatibility, and data integrity as deliverables, not afterthoughts. Never execute a destructive cutover or rollback without explicit user authorization. + +Read `references/migration-types.md` when classifying the task and `references/migration-strategies.md` when choosing incremental, phased, dual-run, or big-bang execution. At every user gate, prefer `request_user_input` when available; otherwise ask the equivalent concise question in the final response and pause. + +## Initialize or resume + +Load and follow `$maister-codex:maister-orchestrator-framework`. Its state, timestamp, phase-gate, artifact-summary, dashboard, HTML-companion, recovery, and user-confirmed rollback contracts are mandatory. + +For a new task, create `.maister/tasks/migrations/YYYY-MM-DD-task-slug/` with `analysis/`, `implementation/`, `verification/`, `documentation/`, and `orchestrator-state.yml`. Read `.maister/config.yml`, `.maister/docs/INDEX.md`, all applicable project documents and standards, and parse `--type`, `--sequential`, and `--from=PHASE`. + +For a resume, restore the first incomplete phase from state unless `--from` was explicitly requested, read all completed artifacts, and preserve recorded decisions. Mandatory gates require a fresh user response. + +State must include the framework fields plus: + +```yaml +migration_context: + migration_type: general # code | data | architecture | general + current_system: {description: null, technologies: []} + target_system: {description: null, technologies: []} + migration_strategy: {approach: null, phases: []} + risk_level: null + breaking_changes: [] + rollback_plan_created: false + dual_run_configured: false + integrity_checks: [] + compatibility_matrix: [] +external_research: + performed: false + sources: [] + breaking_changes: [] +verification_context: + last_status: null + issues_found: 0 + fixes_applied: [] + reverify_count: 0 +options: + html_output: true + sequential: false + docs_enabled: false +``` + +## Phases + +### 1. Current-state analysis and clarification + +Load `$maister-codex:maister-codebase-analysis`. Map versions, dependencies, configuration, runtime and deployment topology, schemas and data ownership, integrations, public contracts, tests, consumers, generated files, and operational constraints. Ask only critical questions about scope, target, downtime, compatibility, and regulated or irreversible data. Write `analysis/current-state-analysis.md` and `analysis/clarifications.md`, then auto-continue. + +### 2. Target-state and gap analysis + +Define the target system and classify the migration as code, data, architecture, or mixed. Compare current and target capabilities, APIs, data models, operational behavior, and tooling. When version-specific behavior may have changed, verify it with primary official sources and cite them. + +Write `analysis/target-state-plan.md` with gaps, breaking changes, dependency ordering, risk level, and evaluated strategies: incremental, phased, dual-run, or big-bang. Prefer reversible, observable steps; justify any big-bang approach. Mandatory gate: present current and target summaries, type, strategy, critical gaps, and risk. + +### 3. Requirements and migration specification + +Confirm scope and exclusions, downtime and maintenance windows, backward/forward compatibility, data retention and reconciliation, rollout population, feature flags, cutover authority, rollback triggers, and existing behavior that must remain. + +Write: + +- `analysis/requirements.md`; +- `implementation/spec.md` with acceptance criteria and standards; +- `analysis/rollback-plan.md` with trigger, owner, exact reversal or restore procedure, validation, and point-of-no-return; +- `analysis/dual-run-plan.md` when old and new paths coexist, including synchronization, comparison, divergence handling, and retirement criteria. + +For data migrations, specify backup/restore validation, counts, checksums or invariants, idempotency, resumability, and reconciliation. For API or architecture migrations, specify contract/version compatibility and consumer sequencing. Mandatory specification-approval gate. + +### 4. Implementation planning + +Write `implementation/implementation-plan.md` with small migration task groups, dependencies, disjoint file ownership, preconditions, focused tests, compatibility and integrity checks, rollout/rollback step for each group, observability, and stop conditions. Include explicit checkpoints before irreversible work. Mandatory plan-approval gate. + +### 5. Migration execution + +Load `$maister-codex:maister-implementation-plan-executor`. Execute only the approved pre-cutover changes and non-destructive migration steps. Use parallel waves only for disjoint work; `--sequential` disables them. Verify every group incrementally and update `implementation/work-log.md` with commands, outcomes, checkpoints, and rollback readiness. + +Stop for approval before external deployment, production cutover, destructive schema/data operations, removal of the old path, or any step crossing a documented point of no return. Do not silently change strategy. Mandatory execution-summary gate. + +### 6. Verification and compatibility testing + +Load `$maister-codex:maister-verify` for completeness, standards, tests, and selected reviews. Write `verification/implementation-verification.md` and `verification/compatibility-test-results.md` covering: + +- old/new API, schema, configuration, and consumer compatibility; +- data counts, checksums or invariants, ordering, null/default handling, and retry/idempotency behavior; +- rollback rehearsal or a clearly identified untested rollback assumption; +- dual-run divergence and cutover criteria when applicable; +- security, performance, deployment, and observability regressions. + +An integrity failure is a hard stop. Never normalize it as a warning. Mandatory gate with verdict, compatibility results, integrity status, and rollback readiness. + +### 7. Migration issue resolution + +Run only when verification found issues. Ask which fixable issues to address, apply approved fixes, and reverify up to three cycles. Refresh the canonical verification and compatibility reports each time. Never roll back automatically. Unresolved critical compatibility or integrity issues block completion unless the user explicitly stops the workflow or accepts a non-production handoff. Mandatory resolution gate. + +### 8. Documentation and finalization + +When requested or needed by risk, write `documentation/migration-guide.md` with prerequisites, staged procedure, cutover checklist, verification, rollback, troubleshooting, owner handoffs, and old-system retirement criteria. Mark state complete only when required checks pass or accepted exceptions are recorded. Summarize changes, compatibility, integrity evidence, rollback readiness, remaining operational actions, and commit/deployment guidance. + +## Artifacts + +```text +analysis/current-state-analysis.md +analysis/clarifications.md +analysis/target-state-plan.md +analysis/requirements.md +analysis/rollback-plan.md +analysis/dual-run-plan.md # conditional +implementation/spec.md +implementation/implementation-plan.md +implementation/work-log.md +verification/implementation-verification.md +verification/compatibility-test-results.md +documentation/migration-guide.md # conditional +``` + +## Recovery limits + +- Phases 1-4: two attempts; then surface the missing source, target detail, or decision. +- Phase 5: five focused correction attempts; never use rollback as automatic recovery. +- Phases 6-7: three fix-and-reverify cycles and an immediate halt on integrity loss. +- Documentation: one retry, then produce a text-only guide from verified artifacts. diff --git a/plugins/maister-codex/skills/maister-migration/agents/openai.yaml b/plugins/maister-codex/skills/maister-migration/agents/openai.yaml new file mode 100644 index 00000000..e795a63e --- /dev/null +++ b/plugins/maister-codex/skills/maister-migration/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Maister Migration" + short_description: "Run safe, rollback-aware technology migrations." + default_prompt: "Use $maister-codex:maister-migration to plan and execute this technology or data migration." diff --git a/plugins/maister-codex/skills/maister-migration/references/migration-strategies.md b/plugins/maister-codex/skills/maister-migration/references/migration-strategies.md new file mode 100644 index 00000000..107dd1e0 --- /dev/null +++ b/plugins/maister-codex/skills/maister-migration/references/migration-strategies.md @@ -0,0 +1,397 @@ +# Migration Strategies Reference + +> **Design Documentation**: This file serves as **design documentation** for Codex agents implementing migration workflows. It provides conceptual patterns and decision frameworks for selecting and executing migration strategies. + +**Purpose:** Pattern guide for migration execution strategies (incremental, rollback, dual-run) + +This reference provides decision criteria and implementation patterns for the three core migration strategies supported by the migration orchestrator. + +--- + +## Table of Contents + +1. [Overview](#overview) +2. [Incremental Migration](#incremental-migration) +3. [Rollback Planning](#rollback-planning) +4. [Dual-Run Strategy](#dual-run-strategy) +5. [Strategy Selection Decision Tree](#strategy-selection-decision-tree) +6. [Combined Strategies](#combined-strategies) + +--- + +## Overview + +Migration strategies define **how** to execute the transition from current to target state. The migration orchestrator supports three core strategies, which can be combined: + +| Strategy | Purpose | Risk Level | Use When | +|----------|---------|------------|----------| +| **Incremental** | Migrate piece-by-piece with checkpoints | Low-Medium | Large migrations, complex changes | +| **Rollback** | Plan undo procedures for each phase | Medium | Critical systems, data migrations | +| **Dual-Run** | Run old and new systems in parallel | Medium-High | Zero-downtime requirements, data sync needed | + +### Key Principles + +1. **Risk Mitigation**: Choose strategies that minimize risk for your context +2. **Composability**: Strategies can be combined (e.g., incremental + rollback) +3. **Checkpoint-Based**: All strategies emphasize verification points +4. **Reversibility**: Plan how to undo changes before making them + +--- + +## Incremental Migration + +### Concept + +**Definition**: Break migration into smaller phases, complete one phase fully before starting next + +**Pattern**: +``` +Current State → Phase 1 → Verify → Phase 2 → Verify → Phase 3 → Verify → Target State + ↑ ↑ ↑ + Checkpoint Checkpoint Checkpoint +``` + +### When to Use + +**Strong Indicators**: +- Large migration scope (>50 files, >5,000 lines affected) +- Multiple independent subsystems to migrate +- Complex breaking changes requiring staged adaptation +- Team needs to learn new technology during migration + +**Avoid If**: +- Small, isolated change (<10 files) +- Tight deadline requiring fast completion +- No logical breakpoints in migration + +### Implementation Pattern + +**Phase Definition**: +1. **Identify Natural Boundaries**: Modules, layers, features that can migrate independently +2. **Define Dependencies**: Which phases must complete before others +3. **Set Verification Criteria**: How to validate each phase succeeded +4. **Plan Checkpoints**: Git tags, deployment points, rollback triggers + +**Example - Framework Migration (Vue 2 → Vue 3)**: +``` +Phase 1: Core dependencies (package.json, build config) + ↓ Verify: App still builds and runs +Phase 2: Shared components (buttons, forms, layouts) + ↓ Verify: Component tests pass +Phase 3: Feature modules (user management, dashboard) + ↓ Verify: Feature tests pass +Phase 4: Router and state management + ↓ Verify: Navigation and data flow work +Phase 5: Cleanup (remove compatibility shims) + ↓ Verify: Full test suite passes +``` + +**Task Group Structure**: +```markdown +### Task Group 1: Phase 1 - Core Dependencies +- [ ] 1.1 Write tests for compatibility layer +- [ ] 1.2 Upgrade core packages +- [ ] 1.3 Update build configuration +- [ ] 1.4 Verify app builds and runs +- [ ] 1.5 Run Phase 1 checkpoint tests + +### Task Group 2: Phase 2 - Shared Components +[continues with next phase after Phase 1 verified] +``` + +### Benefits + +- **Lower Risk**: Problems isolated to current phase +- **Easy Rollback**: Revert to previous phase checkpoint +- **Learning Curve**: Team learns as they progress +- **Progress Visibility**: Clear milestones + +### Challenges + +- **Longer Duration**: More phases = more time +- **Compatibility Layers**: May need temporary bridges between old/new +- **Coordination**: Larger teams need phase synchronization + +--- + +## Rollback Planning + +### Concept + +**Definition**: Document undo procedures for each migration phase before executing + +**Pattern**: +``` +Before Phase 1: Define rollback procedure +Execute Phase 1 +If failure: Execute rollback procedure → Back to known good state +If success: Continue to Phase 2 +``` + +### When to Use + +**Strong Indicators**: +- Production systems (downtime is costly) +- Data migrations (data loss risk) +- Critical business functionality +- Compliance/regulatory requirements +- First-time migration (learning experience) + +**Always Use For**: +- Data migrations (required) +- Production deployments (required) +- Architecture migrations affecting multiple systems + +### Implementation Pattern + +**Rollback Plan Structure** (`planning/rollback-plan.md`): +```markdown +# Rollback Plan: [Migration Name] + +## Rollback Overview +- **Rollback Complexity**: Simple | Moderate | Complex +- **Data Loss Risk**: None | Minimal | Moderate | High +- **Rollback Time Estimate**: [minutes/hours] + +## Phase 1: [Phase Name] Rollback +**Trigger**: [What indicates rollback needed] +**Procedure**: +1. [Undo step 1] +2. [Undo step 2] +**Verification**: [How to verify rollback succeeded] +**Data Recovery**: [How to restore data if modified] + +## Phase 2: [Phase Name] Rollback +[Same structure for each phase] +``` + +**Rollback Categories**: + +| Category | Example | Procedure | +|----------|---------|-----------| +| **Code Rollback** | Framework upgrade | `git revert [commit]`, redeploy | +| **Data Rollback** | Schema migration | Restore from backup, revert migrations | +| **Config Rollback** | Environment changes | Restore old config files, restart | +| **Infrastructure Rollback** | Platform migration | Switch DNS back, restore old infrastructure | + +**Rollback Testing Strategy**: +- **Non-Destructive Test**: Test rollback in non-prod first +- **Documented Steps**: Exact commands/procedures +- **Validation Criteria**: How to verify rollback succeeded +- **Time Estimate**: How long rollback takes (critical for production) + +### Benefits + +- **Confidence**: Knowing you can undo increases willingness to proceed +- **Recovery Speed**: Pre-planned procedures faster than improvised +- **Risk Management**: Downside risk clearly understood +- **Audit Trail**: Documented for compliance/retrospectives + +### Challenges + +- **Planning Overhead**: Requires upfront effort +- **Testing Rollback**: Hard to test without actually migrating +- **Data Rollback Complexity**: Can't always undo data changes cleanly + +--- + +## Dual-Run Strategy + +### Concept + +**Definition**: Run old and new systems in parallel, gradually shift traffic from old to new + +**Pattern**: +``` +Old System (100% traffic) → Dual-Run (Old + New in parallel) → New System (100% traffic) + ↓ + Synchronize data/state + Verify consistency + Gradual cutover (10% → 50% → 100%) +``` + +### When to Use + +**Strong Indicators**: +- Zero-downtime requirement (24/7 systems) +- Data migration with live writes during migration +- Need to compare old vs new behavior in production +- Large user base (gradual rollout safer) +- Regulatory requirement for parallel validation + +**Avoid If**: +- Systems can't coexist (e.g., Vue 2 and Vue 3 in same app) +- Data synchronization too complex +- Cost of running both systems prohibitive +- Migration scope too small to justify overhead + +### Implementation Pattern + +**Dual-Run Phases**: + +**Phase 1: Setup Dual Environment** +- Deploy new system alongside old +- Configure routing/load balancer for split traffic +- Set up data synchronization mechanism + +**Phase 2: Shadow Mode** (new system receives traffic but doesn't affect users) +- 100% traffic to old system +- Duplicate writes to new system (shadow) +- Compare old vs new results +- Identify discrepancies, fix new system + +**Phase 3: Gradual Cutover** +- 10% traffic → new system (monitor closely) +- 50% traffic → new system (A/B test) +- 100% traffic → new system (full cutover) + +**Phase 4: Old System Decommission** +- Keep old system running for 7-30 days (rollback safety net) +- After validation period, decommission old system + +**Dual-Run Plan Structure** (`planning/dual-run-plan.md`): +```markdown +# Dual-Run Plan: [Migration Name] + +## Synchronization Strategy +**Sync Direction**: Old → New | Bidirectional | New → Old +**Sync Mechanism**: [Database replication | Message queue | API calls] +**Sync Frequency**: [Real-time | Batch every X minutes] +**Conflict Resolution**: [Last-write-wins | Manual resolution | Application logic] + +## Cutover Plan +| Phase | Old Traffic % | New Traffic % | Duration | Success Criteria | +|-------|---------------|---------------|----------|------------------| +| Shadow | 100% | 0% (shadow) | 3-7 days | No errors in new system | +| Pilot | 90% | 10% | 3-7 days | Error rate <0.1% in new | +| Ramp | 50% | 50% | 3-7 days | Performance metrics equivalent | +| Full | 0% | 100% | - | All users migrated | + +## Monitoring +- **Key Metrics**: [Response time, error rate, data consistency] +- **Alerting**: [Thresholds that trigger rollback] +- **Comparison Dashboards**: [Old vs new side-by-side] +``` + +**Data Synchronization Patterns**: + +| Pattern | Description | Use When | +|---------|-------------|----------| +| **Write-Through** | Writes go to both old and new | Gradual migration, data validation | +| **Replication** | Database-level replication (one-way) | Read-heavy systems, database migrations | +| **Event Streaming** | Publish changes to message queue, both consume | Event-driven architectures | +| **Dual-Write + Reconciliation** | Write to both, periodic reconciliation job | Complex data models, conflict resolution needed | + +### Benefits + +- **Zero Downtime**: Users never experience outage +- **Gradual Validation**: Catch issues with small % of traffic first +- **Easy Rollback**: Just shift traffic back to old system +- **Real-World Testing**: Test new system with actual production load + +### Challenges + +- **Complexity**: Running two systems is operationally complex +- **Cost**: Double infrastructure during migration period +- **Data Consistency**: Synchronization bugs can cause data issues +- **Monitoring Overhead**: Need to watch both systems simultaneously + +--- + +## Strategy Selection Decision Tree + +Use this decision tree to select appropriate strategies: + +``` +START: What's the migration scope? +│ +├─ Small (<10 files, <1 day effort) +│ └─ Strategy: Big-Bang (single phase, direct migration) +│ +├─ Medium (10-50 files, 2-5 days effort) +│ └─ Is system critical? +│ ├─ Yes → Incremental + Rollback +│ └─ No → Incremental only +│ +└─ Large (>50 files, >5 days effort) + └─ Can system tolerate downtime? + ├─ Yes → Incremental + Rollback + └─ No → Incremental + Rollback + Dual-Run +``` + +**Special Cases**: + +- **Data Migration**: Always use Rollback + Dual-Run (if possible) +- **First-Time Team Migration**: Use Incremental (learning curve) +- **Architecture Migration**: Consider Dual-Run (old/new systems coexist) +- **Breaking Changes**: Use Incremental (adapt gradually) + +--- + +## Combined Strategies + +### Common Combinations + +**Incremental + Rollback** (Most Common): +- Break into phases (Incremental) +- Document rollback for each phase (Rollback) +- Use for: Most medium-large migrations + +**Incremental + Rollback + Dual-Run** (Maximum Safety): +- Break into phases (Incremental) +- Document rollback (Rollback) +- Run old/new in parallel (Dual-Run) +- Use for: Critical systems, data migrations, zero-downtime requirements + +**Example - Database Migration (MySQL → PostgreSQL)**: +``` +Strategy: Incremental + Rollback + Dual-Run + +Phase 1: Setup PostgreSQL + Replication + Rollback: Drop PostgreSQL instance, stop replication + Dual-Run: MySQL (primary), PostgreSQL (replica) + +Phase 2: Dual-Write Mode + Rollback: Stop writes to PostgreSQL, keep MySQL only + Dual-Run: Write to both, read from MySQL + +Phase 3: Shadow Read Mode + Rollback: Revert read queries to MySQL only + Dual-Run: Write to both, read from PostgreSQL (shadow) + +Phase 4: Cutover + Rollback: Switch connection strings back to MySQL + Dual-Run: Write to both, read from PostgreSQL (primary) + +Phase 5: Decommission MySQL + Rollback: Re-activate MySQL, switch back + Dual-Run: PostgreSQL only (MySQL kept for 30 days) +``` + +### Strategy Complexity Matrix + +| Combination | Complexity | Duration Overhead | Risk Reduction | +|------------|------------|-------------------|----------------| +| Incremental only | Low | +20-40% | Medium | +| Incremental + Rollback | Medium | +30-50% | High | +| Incremental + Dual-Run | High | +50-80% | High | +| Incremental + Rollback + Dual-Run | Very High | +80-120% | Very High | + +**Guidance**: Choose simplest strategy that adequately mitigates your risks. Over-engineering increases complexity without proportional benefit. + +--- + +## Summary + +**Key Takeaways**: +1. **Incremental** = Lower risk through phased execution +2. **Rollback** = Safety net for critical systems +3. **Dual-Run** = Zero downtime for live systems +4. **Combine strategies** based on risk, scope, and requirements +5. **Document procedures** before executing migration + +**References in SKILL.md**: +- Phase 2 (Specification): Select migration strategy +- Phase 3 (Planning): Structure implementation plan by strategy +- Phase 4 (Execution): Execute according to selected strategy +- Phase 5 (Verification): Test rollback procedures (non-destructive) diff --git a/plugins/maister-codex/skills/maister-migration/references/migration-types.md b/plugins/maister-codex/skills/maister-migration/references/migration-types.md new file mode 100644 index 00000000..5802f2b6 --- /dev/null +++ b/plugins/maister-codex/skills/maister-migration/references/migration-types.md @@ -0,0 +1,437 @@ +# Migration Types Reference + +> **Design Documentation**: This file serves as **design documentation** for Codex agents implementing migration workflows. It provides guidance for identifying migration types and adapting workflows accordingly. + +**Purpose:** Pattern guide for the three migration types: Code, Data, and Architecture + +This reference provides characteristics, detection patterns, and workflow adaptations for each migration type supported by the migration orchestrator. + +--- + +## Table of Contents + +1. [Overview](#overview) +2. [Code Migration](#code-migration) +3. [Data Migration](#data-migration) +4. [Architecture Migration](#architecture-migration) +5. [General Migration](#general-migration) +6. [Type Detection Algorithm](#type-detection-algorithm) + +--- + +## Overview + +Migration types classify migrations based on **what** is being changed: + +| Type | Focus | Examples | Risk Profile | +|------|-------|----------|--------------| +| **Code** | Language, framework, library | Vue 2→3, Python 2→3, Express→Fastify | Medium | +| **Data** | Database, storage, schema | MySQL→PostgreSQL, MongoDB→DynamoDB | High | +| **Architecture** | Patterns, structure | REST→GraphQL, Monolith→Microservices | High | +| **General** | Mixed or unclear | Complex refactoring with multiple aspects | Variable | + +### Why Type Matters + +Different types require different: +- **Risk assessments**: Data migrations are highest risk (data loss potential) +- **Verification approaches**: Data needs integrity checks, code needs functional tests +- **Rollback strategies**: Data rollback more complex than code rollback +- **Tools and techniques**: Database tools for data, test suites for code + +--- + +## Code Migration + +### Definition + +**What**: Changing programming language, framework, library, or major version with breaking changes + +**Characteristics**: +- Source code modifications (syntax, APIs, patterns) +- Dependency updates (package.json, requirements.txt, pom.xml) +- No data transformation (data structures unchanged or minimal changes) +- Primarily affects developers (users may not notice if functionality same) + +### Examples + +**Framework Migrations**: +- Vue 2 → Vue 3 (composition API, breaking changes) +- Angular 8 → Angular 15 (modules to standalone components) +- React Class Components → Hooks +- Express 4 → Express 5 + +**Language Migrations**: +- Python 2 → Python 3 (print statements, unicode) +- JavaScript → TypeScript (type annotations) +- Java 8 → Java 17 (new syntax, APIs) + +**Library Migrations**: +- Moment.js → Day.js (date handling library change) +- Axios → Fetch API (HTTP client change) +- Lodash → Native JavaScript (utility functions) + +### Detection Keywords + +**Primary Indicators**: +- Framework/library names: React, Vue, Angular, Express, Flask, Django, Spring, Rails +- Version terms: "upgrade", "migrate from X to Y", "move to version N" +- Language names: Python, Java, JavaScript, TypeScript, Go, Rust + +**Example Descriptions**: +- "Migrate from Vue 2 to Vue 3" → Code migration (framework) +- "Upgrade Express to v5" → Code migration (major version) +- "Convert JavaScript to TypeScript" → Code migration (language) + +### Workflow Adaptations + +**Phase 1 (Current State Analysis)**: +- Focus: Locate all source files using old framework/library +- Analyze: Dependency tree, API usage patterns, deprecated features used + +**Phase 2 (Target State Planning)**: +- Focus: Breaking changes between versions, API equivalents +- Output: Breaking changes list, API migration map + +**Phase 3 (Specification)**: +- Include: Compatibility shim requirements (if needed) +- Rollback: Simple (revert code via git) + +**Phase 5 (Execution)**: +- Strategy: Incremental (by module/component) +- Testing: Functional tests per module + +**Phase 6 (Verification)**: +- Focus: Functional equivalence (behavior unchanged) +- Tests: Full test suite, manual testing of critical flows + +### Risk Profile + +**Medium Risk**: +- **Risk**: Breaking changes causing bugs, build failures +- **Mitigation**: Comprehensive test coverage, incremental migration +- **Rollback**: Relatively easy (git revert) + +--- + +## Data Migration + +### Definition + +**What**: Changing database platform, storage system, or schema structure + +**Characteristics**: +- Data transformation (format, structure, relationships) +- Schema changes (tables, columns, indexes, constraints) +- Data integrity critical (no data loss tolerated) +- Often requires dual-run (old and new databases running in parallel) + +### Examples + +**Platform Migrations**: +- MySQL → PostgreSQL (SQL database change) +- MongoDB → DynamoDB (document to key-value) +- Redis → Memcached (caching layer change) +- On-premise DB → Cloud DB (AWS RDS, Azure SQL) + +**Schema Migrations**: +- Normalize database (split tables, add relationships) +- Denormalize for performance (merge tables) +- Add partitioning/sharding + +**Storage Migrations**: +- Local files → S3 (file storage migration) +- S3 → GCS (cloud provider change) +- SQL → NoSQL (data model change) + +### Detection Keywords + +**Primary Indicators**: +- Database names: MySQL, PostgreSQL, MongoDB, Redis, DynamoDB, Cassandra, Oracle +- Data terms: "schema change", "data migration", "database migration", "move data" +- Storage terms: "S3", "blob storage", "file migration" + +**Example Descriptions**: +- "Migrate database from MySQL to PostgreSQL" → Data migration (platform) +- "Move from MongoDB to DynamoDB" → Data migration (NoSQL change) +- "Migrate schema to normalized structure" → Data migration (schema) + +### Workflow Adaptations + +**Phase 1 (Current State Analysis)**: +- Focus: Database schema, row counts, data volume, stored procedures +- Analyze: Data relationships, foreign keys, indexes, constraints + +**Phase 2 (Target State Planning)**: +- Focus: Data transformation requirements, data mapping (old → new schema) +- Output: Data transformation specification, estimated migration time + +**Phase 3 (Specification)**: +- Include: Data validation procedures, integrity checks, rollback procedures +- Rollback: Complex (requires backup/restore strategies) +- Dual-Run: Often required (zero-downtime) + +**Phase 5 (Execution)**: +- Strategy: Incremental + Dual-Run (high confidence in strategy choice) +- Testing: Data integrity checks after each batch + +**Phase 6 (Verification)**: +- Focus: Data integrity (100% row count match, checksums, data validation) +- Tests: Full test suite + data integrity tests + performance benchmarks +- Critical: If data integrity fails, HALT (don't auto-fix, prompt user) + +### Risk Profile + +**High Risk**: +- **Risk**: Data loss, data corruption, downtime +- **Mitigation**: Backups before migration, dual-run, incremental batches, 100% data validation +- **Rollback**: Complex (restore from backup, may lose data written during migration) + +**Special Requirements**: +- **Backup**: Full backup before starting (non-negotiable) +- **Data Validation**: 100% row count match, checksums, business rule validation +- **Dual-Run**: Strongly recommended (old and new databases in parallel) +- **Monitoring**: Data synchronization lag, replication errors +- **Testing**: More verification attempts (max 3 instead of 2 for auto-fix) + +--- + +## Architecture Migration + +### Definition + +**What**: Changing fundamental system structure, communication patterns, or architectural style + +**Characteristics**: +- System-wide changes (affects multiple components/services) +- Changes how components interact (APIs, communication patterns) +- May affect both code and data (comprehensive migration) +- Often requires gradual transition (old and new coexist) + +### Examples + +**API Style Migrations**: +- REST API → GraphQL (query language change) +- SOAP → REST (API pattern modernization) +- RPC → REST (communication pattern change) + +**Architecture Pattern Migrations**: +- Monolith → Microservices (decomposition) +- Microservices → Monolith (consolidation) +- MVC → Component-Based (frontend architecture change) +- Layered → Hexagonal (backend architecture change) + +**Infrastructure Migrations**: +- On-Premise → Cloud (infrastructure change) +- Single Server → Distributed (scalability) +- Synchronous → Event-Driven (async patterns) + +### Detection Keywords + +**Primary Indicators**: +- Pattern names: REST, GraphQL, gRPC, SOAP, RPC +- Architecture styles: Monolith, Microservices, Serverless, Event-Driven, Hexagonal +- Refactoring terms: "refactor to", "change architecture", "restructure" + +**Example Descriptions**: +- "Refactor REST API to GraphQL" → Architecture migration (API style) +- "Migrate monolith to microservices" → Architecture migration (decomposition) +- "Change from MVC to component-based architecture" → Architecture migration (pattern) + +### Workflow Adaptations + +**Phase 1 (Current State Analysis)**: +- Focus: System components, communication patterns, dependencies between components +- Analyze: Coupling/cohesion, service boundaries, data flow + +**Phase 2 (Target State Planning)**: +- Focus: New architecture structure, component boundaries, communication patterns +- Output: Architecture diagram, component mapping (old → new) + +**Phase 3 (Specification)**: +- Include: Strangler fig pattern (if applicable), component interaction diagrams +- Rollback: Moderate to complex (depends on dual-run feasibility) +- Dual-Run: Often required (old and new architectures in parallel) + +**Phase 5 (Execution)**: +- Strategy: Incremental (by component/service) + Dual-Run (if possible) +- Testing: Integration tests, end-to-end tests, performance tests + +**Phase 6 (Verification)**: +- Focus: System-level behavior (end-to-end flows work), performance comparison +- Tests: Full test suite + integration tests + E2E tests + +### Risk Profile + +**High Risk**: +- **Risk**: System-wide breakage, performance degradation, complex rollback +- **Mitigation**: Strangler fig pattern, incremental component migration, dual-run +- **Rollback**: Moderate to complex (depends on how well old/new coexist) + +**Special Patterns**: +- **Strangler Fig**: Gradually replace old system with new (route traffic to new incrementally) +- **Branch by Abstraction**: Create abstraction layer, switch implementations behind it +- **Parallel Run**: Run old and new architectures in parallel, compare results + +--- + +## General Migration + +### Definition + +**What**: Migrations that don't fit cleanly into Code/Data/Architecture, or mix multiple types + +**Characteristics**: +- Ambiguous description ("modernize", "refactor" without specifics) +- Multiple aspects (code + data + architecture) +- Catch-all for unclear migrations + +### Examples + +- "Modernize legacy system" (unclear scope) +- "Refactor application for scalability" (multiple aspects) +- "Migrate to cloud" (infrastructure + code + data) + +### Workflow Adaptations + +**Phase 1-2 (Analysis + Planning)**: +- Spend extra time clarifying scope +- Prompt user to specify what's changing (code, data, architecture, or all) +- May reclassify after analysis + +**General Approach**: +- Use conservative defaults (high risk, incremental + rollback + dual-run) +- Prompt user more frequently for decisions +- Extra verification steps + +--- + +## Type Detection Algorithm + +### Overview + +Migration type detection uses keyword matching with confidence scoring. + +### Algorithm Pattern + +**Input**: `"Migrate from Vue 2 to Vue 3"` + +**Steps**: +1. **Extract Keywords**: `["migrate", "Vue", "2", "3"]` +2. **Match Against Patterns**: + - Code: `["Vue"]` → 1 match + - Data: `[]` → 0 matches + - Architecture: `[]` → 0 matches +3. **Calculate Scores**: + - Code: 1 match → 100% confidence (only category with matches) + - Data: 0 matches → 0% + - Architecture: 0 matches → 0% +4. **Select Type**: Code (highest score) +5. **Confirm with User** (interactive mode): "Detected migration type: Code. Correct? [Y/n]" + +### Keyword Categories + +**Code Migration Keywords**: +``` +Frameworks: React, Vue, Angular, Express, Flask, Django, Rails, Spring, Laravel +Languages: Python, Java, JavaScript, TypeScript, Go, Rust, C++, C#, Ruby, PHP +Terms: "upgrade", "migrate from X to Y", "version", "framework migration" +``` + +**Data Migration Keywords**: +``` +Databases: MySQL, PostgreSQL, MongoDB, Redis, DynamoDB, Cassandra, Oracle, SQL Server +Terms: "database", "schema", "data migration", "move data", "storage", "S3", "blob" +``` + +**Architecture Migration Keywords**: +``` +Patterns: REST, GraphQL, gRPC, SOAP, Monolith, Microservices, Serverless, Event-Driven +Terms: "refactor to", "architecture", "pattern", "system design", "restructure" +``` + +### Ambiguity Handling + +**Multiple Matches** (e.g., "Migrate MySQL database to PostgreSQL and refactor to microservices"): +- Scores: Code=0, Data=2 ("MySQL", "PostgreSQL"), Architecture=1 ("microservices") +- Primary Type: Data (highest score) +- Classification: Data + Architecture (mixed) +- Prompt user: "Detected primary type: Data. Also includes architecture changes. Proceed as data migration? [Y/n/specify]" + +**No Clear Matches** (e.g., "Modernize application"): +- Scores: Code=0, Data=0, Architecture=0 +- Classification: General +- Prompt user: "Unable to detect migration type. Please specify: [Code/Data/Architecture/Mixed]" + +### Confidence Levels + +| Score | Confidence | Action | +|-------|------------|--------| +| Single category with matches | 100% | Auto-detect, confirm in interactive | +| Primary category (>50% of matches) | 70-90% | Auto-detect, prompt to confirm | +| Tied categories | 50% | Prompt user to choose | +| No matches | 0% | Classify as General, prompt user | + +--- + +## Web Research Requirements by Type + +External research is automatically triggered by the gap-analyzer during Phase 2 (Target State Planning). The level of research depends on migration type. + +| Migration Type | External Research | Query Focus | Priority Sources | +|---------------|-------------------|-------------|------------------| +| **Code** (Version Upgrade) | **Required** | Migration guides, breaking changes, API changes | Official docs, release notes, upgrade guides | +| **Code** (Library Swap) | **Required** | Comparison guides, migration paths, compatibility | Official docs, community migration stories | +| **Data** (Platform Change) | **Recommended** | Compatibility, data transformation, tooling | Official docs, DBA resources, cloud provider docs | +| **Data** (Schema Change) | **Optional** | Best practices only | Internal docs preferred | +| **Architecture** | **Recommended** | Pattern implementation, migration strategies | Architecture blogs, official docs | +| **General** | **Optional** | Clarification research | N/A | + +### When to Skip External Research + +- Pure internal refactoring (no external technology change) +- Schema changes within same database platform +- Minor version upgrades (patch versions only) +- When offline mode required +- User explicitly requests `--no-web-research` + +### Research Depth by Complexity + +| Complexity | Research Depth | Queries | Focus | +|------------|---------------|---------|-------| +| Simple (<10 files) | Essential | 2-3 | Official migration guide only | +| Moderate (10-30 files) | Essential | 2-3 | Migration guide + breaking changes | +| Complex (>30 files) | Expanded | 4-6 | Guide + breaking changes + community experiences | +| Data migration (any size) | Expanded | 4-6 | Guide + compatibility + data transformation | + +### Example Research Queries + +**Code Migration (Vue 2 → Vue 3)**: +- Primary: "Vue 2 to Vue 3 migration guide" +- Secondary: "Vue 3 breaking changes 2024" +- Expanded: "Vue 3 composition API migration examples" + +**Data Migration (MySQL → PostgreSQL)**: +- Primary: "MySQL to PostgreSQL migration guide" +- Secondary: "PostgreSQL migration tools 2024" +- Expanded: "MySQL PostgreSQL syntax differences" + +**Architecture Migration (REST → GraphQL)**: +- Primary: "REST to GraphQL migration guide" +- Secondary: "GraphQL migration best practices" +- Expanded: "REST GraphQL coexistence patterns" + +--- + +## Summary + +**Key Takeaways**: +1. **Code**: Focus on functional equivalence, incremental migration, medium risk +2. **Data**: Focus on data integrity, dual-run often required, high risk +3. **Architecture**: Focus on system-level behavior, strangler fig pattern, high risk +4. **General**: Conservative defaults, extra clarification with user + +**References in SKILL.md**: +- Initialization (Step 2): Type detection algorithm +- Phase 1 (Analysis): Type-specific analysis focus +- Phase 2 (Target Planning): Type-specific gap analysis + external research +- Phase 6 (Verification): Type-specific verification requirements diff --git a/plugins/maister-codex/skills/maister-mockup-studio/SKILL.md b/plugins/maister-codex/skills/maister-mockup-studio/SKILL.md new file mode 100644 index 00000000..48bb5c4b --- /dev/null +++ b/plugins/maister-codex/skills/maister-mockup-studio/SKILL.md @@ -0,0 +1,42 @@ +--- +name: maister-mockup-studio +description: Generate and iteratively refine design-system-aware UI mockups as rendered HTML/CSS or terminal ASCII. Use standalone for screen and feature mockups, or from development and product-design workflows that need visual design artifacts. +--- + +# Maister Mockup Studio + +Create user-facing UI mockups that reuse the project's real standards, tokens, components, iconography, and interaction patterns. HTML is the default; ASCII is the zero-browser fallback. Persist files even when live preview is unavailable. + +## Inputs and result + +Accept these values from the caller when provided: + +| Input | Default | Meaning | +| --- | --- | --- | +| `task_path` | standalone task path | Workflow task directory | +| `output_subdir` | `analysis/mockups` | Destination relative to `task_path` | +| `format` | config or `html` | `html` or `ascii` | +| `iteration` | `full` | `single` for caller-owned review; `full` for this skill's refinement loop | +| `emit_index_rows` | `false` | Add stable visual-reference rows for downstream implementation | +| `context` | user request | Relevant specification, flow, constraints, screens, and design references | + +Return `mockup_files`, `index_rows`, `format_used`, `notes`, and the live gallery URL when available. + +## Workflow + +1. If no `task_path` is supplied, create `.maister/tasks/mockups/YYYY-MM-DD-/analysis/`. Read `.maister/config.yml` for `mockup_format`, defaulting to `html`. +2. Create the output directory. Read `references/design-resource-discovery.md` completely and run its three-tier discovery. Read every applicable discovered standard. Write `analysis/design-context/design-resources.md`, including the required `TL;DR`. +3. If HTML was requested, check `node --version`. If Node is absent, record the reason and use ASCII. +4. For HTML, read `references/visual-companion.md` completely. Start or reuse `server/index.mjs`, verify `/status`, retain the returned mutation token for `POST` requests, and surface the loopback-only gallery URL. Opening a browser is optional and may require approval; failure must not block generation. +5. Generate one specifically titled screen for every relevant view and state. Reuse discovered CSS variables, component names, and icons. Use `data-screen="slug"` for click-through navigation and annotations only for reuse, integration, or interaction hints. Do not generate architecture, data-flow, or entity diagrams. +6. POST each HTML screen to `/update` with the returned token in `X-Maister-Token`; the server persists each rendered file and an offline `index.html` gallery. For ASCII, generate a clear annotated wireframe at `/ascii-mockups.md`; delegate to the installed `maister-ascii-mockup-generator` agent when available, but the main agent remains responsible for persistence and validation. +7. With `iteration: full`, present the complete current mockup set and prefer `request_user_input` when available for `Approve (Recommended)`, `Revise`, or `Rethink`; otherwise ask the same concise choice in the final response. Regenerate only affected screens while keeping the set coherent. After roughly five rounds, recommend convergence without removing the option to revise again. With `iteration: single`, return after one generation so the caller owns the gate. +8. When `emit_index_rows` is true, add stable `screen:` and `component:` rows to `analysis/design-context/INDEX.md` with source paths and binding descriptions. +9. Keep the server alive for `iteration: single`. For standalone `iteration: full`, shut it down only after approval. Report saved paths and any degradation. + +## Fallback rules + +- Try ports 3847 through 3850; if none work, use ASCII. +- If browser automation or a platform opener is unavailable, print the URL and continue. +- If no project design resources exist, generate from established codebase patterns and record that limitation. +- A failed preview must never erase or invalidate saved mockup files. diff --git a/plugins/maister-codex/skills/maister-mockup-studio/agents/openai.yaml b/plugins/maister-codex/skills/maister-mockup-studio/agents/openai.yaml new file mode 100644 index 00000000..9a0cb499 --- /dev/null +++ b/plugins/maister-codex/skills/maister-mockup-studio/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Maister Mockup Studio" + short_description: "Create design-system-aware UI mockups." + default_prompt: "Use $maister-codex:maister-mockup-studio to create and refine UI mockups for this feature." diff --git a/plugins/maister-codex/skills/maister-mockup-studio/references/design-resource-discovery.md b/plugins/maister-codex/skills/maister-mockup-studio/references/design-resource-discovery.md new file mode 100644 index 00000000..e4d76dc3 --- /dev/null +++ b/plugins/maister-codex/skills/maister-mockup-studio/references/design-resource-discovery.md @@ -0,0 +1,65 @@ +# Design-Resource Discovery + +Before generating mockups, `mockup-studio` discovers the project's existing design language so mockups bind to it rather than inventing a generic look. This routine runs once per mockup-generation invocation (skip re-running on resume when `design_resources.ran` is already true in state). + +**Output**: a terse artifact `/analysis/design-context/design-resources.md` (opens with `## TL;DR`) and a `design_resources` block recorded in the caller's `orchestrator-state.yml`: + +```yaml +design_resources: + ran: true # discovery executed (resume skips re-run) + standards: [] # tier 1: [{path, topic}] resolved frontend/design/a11y standard files + design_system: [] # tier 2: [{kind: token|theme|tailwind|css-var|component-lib|icon-lib, path, note}] + skill_hints: [] # tier 3: [{kind: skill|agent|mcp-tool, name, why}] + found_any: false # false ⇒ generation proceeds unchanged (artifact still written, one line) +``` + +**Graceful default**: each tier independently no-ops. When all three are empty, set `found_any: false`, write a one-line artifact ("No project design resources detected — mockups generated from codebase patterns only"), and change nothing else. + +--- + +## Run order + +Run cheapest-and-orchestrator-only first, authoritative-and-delegable last. `mockup-studio` runs in the main agent context, so it can do all three (a subagent could not do tier 3). + +### Tier 3 — Available design skills / agents / MCP tools (MAIN CONTEXT ONLY) + +Scan the names + descriptions of the skills, subagents, and MCP tools visible in the current context for design/UI/UX signal. This is only possible from the main agent (a subagent cannot enumerate available skills/tools) — which is why mockup-studio is a skill, not a subagent. + +**Keywords**: `design, ui, ux, mockup, wireframe, prototype, figma, sketch, zeplin, storybook, component, theme, token, tailwind, chakra, shadcn, mui, a11y, accessib, icon, css, style`. + +For each match, record `{kind, name, why}`. Then, **best-effort and capability-aware**, optionally: +- **Consult** a matched design skill / design MCP for the palette, tokens, or style guidance before generating. +- **Read** a connected design MCP resource (e.g. a Figma file) when one is available. +- **Delegate** a screen to a matched component-builder skill *only* when the project's stack matches and the skill is present. + +**Hard scope**: tier-3 consults are for *style/token guidance or throwaway mockup markup* — NEVER for writing production components. If a consult fails or nothing matches, fall straight through. Never block on tier 3. + +### Tier 1 — Project standards + +From the project's `.maister/docs/INDEX.md` (the orchestrator already loaded it at init), select standard files whose path or heading matches `standards/frontend/`, `standards/design/`, or the keywords `ui | ux | component | accessibility | a11y | responsive | css | theme | design-system`. Record resolved paths in `standards[]`. + +These are **binding**: the generator (ASCII subagent or inline HTML) must read each file and honor its rules — color usage, spacing scale, component conventions, accessibility requirements. + +### Tier 2 — Codebase design system + +Discover the real, in-code design system. **Harvest from an existing `analysis/codebase-analysis.md` first** (development Phase 1 and product-design Phase 1 already ran codebase analysis) — use `rg --files` and `rg` only for the gaps. Look for: + +| Kind | Signals (examples) | +|------|--------------------| +| `token` | `**/tokens*.{json,js,ts,css}`, `**/design-tokens*` | +| `theme` | `**/theme.{ts,js,json}`, `theme/` dirs, MUI/Chakra theme objects | +| `tailwind` | `tailwind.config.*`, `panda.config.*`, `uno.config.*` | +| `css-var` | CSS custom properties — search CSS files with `rg -- '--[a-z-]+:'` | +| `component-lib` | `.storybook/`, `components.json` (shadcn), `@chakra-ui`/`@mui`/`@mantine` imports, a local `components/ui/` library | +| `icon-lib` | `lucide`, `@heroicons`, `react-icons`, `@tabler/icons`, a local `icons/` dir | + +Record each as `{kind, path, note}`. These are **binding**: generated mockups reuse the discovered tokens (echo the real CSS variables / class names), components (by their real names), and icon set — so the mockup resembles the actual app. + +--- + +## How findings bind to each generator + +- **HTML (inline, main context)**: mockup-studio generates HTML/CSS that echoes the discovered CSS custom properties / Tailwind classes / component names. Annotate reuse, e.g. `{"selector":".btn","note":"uses --color-primary from src/theme.ts"}`. +- **ASCII (subagent)**: mockup-studio passes the resolved standard paths, the design-system inventory, and skill hints in the `ascii-mockup-generator` prompt. The agent reads every standard and maps each mockup element to the real component/token by name. + +In both cases the rule is the same: **reuse the existing visual language; annotate any deliberate deviation with a rationale.** Do not invent a design system when one exists. diff --git a/plugins/maister-codex/skills/maister-mockup-studio/references/visual-companion.md b/plugins/maister-codex/skills/maister-mockup-studio/references/visual-companion.md new file mode 100644 index 00000000..5e761e89 --- /dev/null +++ b/plugins/maister-codex/skills/maister-mockup-studio/references/visual-companion.md @@ -0,0 +1,79 @@ +# Visual Companion + +The HTML path uses the zero-dependency Node server at `../server/index.mjs`, resolved relative to this reference's skill directory. Do not rely on a client-specific plugin-root environment variable. + +## Architecture + +```text +Mockup Studio -> POST /update -> Node HTTP server -> SSE refresh -> browser + ^ | + +---------------- user feedback in chat ---------------+ +``` + +The browser is a read-only renderer. User feedback and workflow decisions remain in the Codex conversation. The server uses only Node built-ins (`http`, `fs`, `path`, `crypto`, and `url`); no package installation is required. It binds only to `127.0.0.1`, limits request bodies to 2 MiB, and requires the per-process mutation token for every POST. + +## Protocol + +| Endpoint | Method | Result | +| --- | --- | --- | +| `/status` | GET | Health, active port, task path, persistence, screen count, and mutation token | +| `/` | GET | Gallery of all screens | +| `/screen/` | GET | One screen with navigation | +| `/latest` | GET | Most recently updated screen | +| `/events` | GET | Server-sent refresh events | +| `/update` | POST | Add or replace a screen and persist it | +| `/shutdown` | POST | Stop the server cleanly | + +POST screens as JSON with `X-Maister-Token: `: + +```json +{ + "type": "mockup", + "title": "Settings — Notifications", + "html": "
...
", + "css": ":root { --color-primary: #2457d6; }", + "annotations": [ + {"selector": ".save-button", "text": "Reuses the existing primary button"} + ] +} +``` + +Titles determine stable lowercase-hyphenated IDs. Posting a title again updates that screen. Each update writes `//.html`, an offline `index.html` gallery, and `.mockups.json`; a restarted server restores the gallery from this manifest. + +## Lifecycle + +1. Resolve the absolute `server/index.mjs` path from the loaded skill directory. +2. Query `/status` on `127.0.0.1` ports 3847 through 3850. Reuse a server whose `taskPath` matches and retain its `mutationToken`. Shut down a stale server only after confirming it belongs to another Maister mockup task, passing its token in `X-Maister-Token`. +3. Launch Node with quoted absolute arguments: + + ```text + node /server/index.mjs --task-path= --output-subdir= + ``` + + Keep the process/session handle, verify `/status`, and retain the returned mutation token before generating content. +4. Open the gallery with an available browser-automation connector when configured. A platform opener is a best-effort fallback and may require user approval. Otherwise print the URL. +5. POST every screen with `X-Maister-Token` and verify the response reports `saved: true`. +6. Keep the server running while an orchestrator-owned review gate is pending. In a standalone full refinement run, call `/shutdown` with `X-Maister-Token` after final approval. + +The server writes `.visual-companion.pid` below the output directory and removes it on clean shutdown, SIGTERM, or SIGINT. + +## Rendering guidance + +- Produce mid-fidelity user-facing screens, not system diagrams. +- Reuse discovered design tokens, components, copy style, and icons by their real names. +- Use annotations for component reuse, integration points, and interaction hints; do not encode requirements in annotations. +- Add `data-screen="target-slug"` to clickable elements to create a navigable prototype. +- Include relevant empty, loading, error, validation, responsive, and permission states. +- Use multiple specifically titled screens when the flow cannot be evaluated from one view. + +## Graceful degradation + +| Failure | Response | +| --- | --- | +| Node unavailable | Generate and persist ASCII mockups | +| Ports 3847–3850 unavailable | Generate ASCII and record the port conflict | +| Browser cannot open | Print the URL; continue saving HTML | +| Server fails once | Restart once; then fall back to ASCII | +| Preview disconnects | Keep the saved HTML deliverables and report the limitation | + +Preview failure never blocks the design workflow or invalidates files already written. diff --git a/plugins/maister-codex/skills/maister-mockup-studio/server/index.mjs b/plugins/maister-codex/skills/maister-mockup-studio/server/index.mjs new file mode 100644 index 00000000..cf28b098 --- /dev/null +++ b/plugins/maister-codex/skills/maister-mockup-studio/server/index.mjs @@ -0,0 +1,419 @@ +import http from 'node:http'; +import fs from 'node:fs'; +import path from 'node:path'; +import crypto from 'node:crypto'; +import { fileURLToPath } from 'node:url'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); + +// Parse --task-path from CLI args +const taskPathArg = process.argv.find(a => a.startsWith('--task-path=')); +const taskPathInput = taskPathArg ? path.resolve(taskPathArg.slice('--task-path='.length)) : null; +const taskPath = taskPathInput ? fs.realpathSync(taskPathInput) : null; + +// Parse --output-subdir (relative to task path). Default: analysis/mockups (product-design convention). +// The development workflow passes analysis/design-context/mockups so HTML lands in design-context. +const outputSubdirArg = process.argv.find(a => a.startsWith('--output-subdir=')); +const outputSubdirValue = outputSubdirArg + ? outputSubdirArg.slice('--output-subdir='.length) + : 'analysis/mockups'; + +if (path.isAbsolute(outputSubdirValue)) { + throw new Error('--output-subdir must be relative to --task-path'); +} + +const outputDir = taskPath ? path.resolve(taskPath, outputSubdirValue) : null; +if (taskPath && outputDir !== taskPath && !outputDir.startsWith(`${taskPath}${path.sep}`)) { + throw new Error('--output-subdir must stay inside --task-path'); +} + +function assertOutputPathSafe() { + if (!taskPath || !outputDir) return; + const relative = path.relative(taskPath, outputDir); + let cursor = taskPath; + for (const segment of relative.split(path.sep).filter(Boolean)) { + cursor = path.join(cursor, segment); + if (fs.existsSync(cursor) && fs.lstatSync(cursor).isSymbolicLink()) { + throw new Error(`--output-subdir cannot traverse a symbolic link: ${cursor}`); + } + } + if (fs.existsSync(outputDir)) { + const canonicalOutput = fs.realpathSync(outputDir); + if (canonicalOutput !== taskPath && !canonicalOutput.startsWith(`${taskPath}${path.sep}`)) { + throw new Error('--output-subdir resolves outside --task-path'); + } + } +} + +assertOutputPathSafe(); + +const mutationToken = crypto.randomBytes(24).toString('hex'); +const maxBodyBytes = 2 * 1024 * 1024; + +if (!taskPath) { + console.warn('[visual-companion] No --task-path provided. Mockups will NOT be saved to disk.'); +} + +// In-memory state: array of all mockups (screens) +const mockups = []; +let latestId = null; +let version = 0; +const sseClients = []; + +function slugify(title) { + return title + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-|-$/g, '') + || 'untitled'; +} + +function escapeAttr(s) { + return String(s).replace(/&/g, '&').replace(/"/g, '"'); +} + +// --- Manifest: raw screen payloads persisted alongside the rendered .html files. +// Lets the gallery survive a server restart (in-memory state is otherwise empty on +// startup even though the .html files exist on disk). +function manifestPath() { + if (!taskPath) return null; + assertOutputPathSafe(); + return path.join(outputDir, '.mockups.json'); +} + +function saveManifest() { + const p = manifestPath(); + if (!p) return; + try { + fs.mkdirSync(path.dirname(p), { recursive: true }); + fs.writeFileSync(p, JSON.stringify({ latestId, mockups }, null, 2), 'utf-8'); + } catch (err) { + console.warn(`[visual-companion] Could not write manifest: ${err.message}`); + } +} + +function loadManifest() { + const p = manifestPath(); + if (!p || !fs.existsSync(p)) return; + try { + const data = JSON.parse(fs.readFileSync(p, 'utf-8')); + if (Array.isArray(data.mockups) && data.mockups.length) { + mockups.push(...data.mockups); + latestId = data.latestId || mockups[mockups.length - 1].id; + version = mockups.length; + console.log(`Restored ${mockups.length} screen(s) from disk.`); + } + } catch (err) { + console.warn(`[visual-companion] Could not read manifest: ${err.message}`); + } +} + +// Save a rendered standalone HTML file to disk. Returns true if saved, false if skipped. +function saveToDisk(mockup) { + if (!taskPath) { + console.warn(`[visual-companion] Skipping disk save for "${mockup.id}" — no task path configured.`); + return false; + } + const dir = outputDir; + assertOutputPathSafe(); + fs.mkdirSync(dir, { recursive: true }); + assertOutputPathSafe(); + + const html = renderScreen(mockup, true); + const filePath = path.join(dir, `${mockup.id}.html`); + fs.writeFileSync(filePath, html, 'utf-8'); + fs.writeFileSync(path.join(dir, 'index.html'), renderGallery(true), 'utf-8'); + return true; +} + +// Render a single screen page with navigation +function renderScreen(mockup, staticMode = false) { + const templatePath = path.join(__dirname, 'template.html'); + let html = fs.readFileSync(templatePath, 'utf-8'); + + const title = mockup.title || 'Untitled'; + const content = `\n
${mockup.html || ''}
`; + const annotations = JSON.stringify(mockup.annotations || []); + + // Build screen nav + const screenHref = id => staticMode ? `${id}.html` : `/screen/${id}`; + const navItems = mockups.map(m => + `${m.title}` + ).join(''); + + const idx = mockups.indexOf(mockup); + const prev = idx > 0 ? mockups[idx - 1] : null; + const next = idx < mockups.length - 1 ? mockups[idx + 1] : null; + const prevLink = prev ? `← ${prev.title}` : ''; + const nextLink = next ? `${next.title} →` : ''; + + const nav = mockups.length > 1 + ? `` + : ''; + + html = html.replace('{{TITLE}}', title).replace('{{TITLE}}', title); + html = html.replace('{{NAV}}', nav); + html = html.replace('{{CONTENT}}', content); + html = html.replace('{{ANNOTATIONS}}', annotations); + html = html.replace('{{GALLERY_HREF}}', staticMode ? 'index.html' : '/'); + html = html.replace('{{LIVE_MODE}}', staticMode ? 'false' : 'true'); + + return html; +} + +// Render the gallery index page +function renderGallery(staticMode = false) { + const templatePath = path.join(__dirname, 'template.html'); + let html = fs.readFileSync(templatePath, 'utf-8'); + + const title = `Design Gallery — ${mockups.length} screen${mockups.length !== 1 ? 's' : ''}`; + + let content; + if (mockups.length === 0) { + content = '
Waiting for design mockups...
The orchestrator will send screens here.
'; + } else { + // Each preview renders inside its own + `; + }).join(''); + content = ``; + } + + html = html.replace('{{TITLE}}', title).replace('{{TITLE}}', title); + html = html.replace('{{NAV}}', ''); + html = html.replace('{{CONTENT}}', content); + html = html.replace('{{ANNOTATIONS}}', '[]'); + html = html.replace('{{GALLERY_HREF}}', staticMode ? 'index.html' : '/'); + html = html.replace('{{LIVE_MODE}}', staticMode ? 'false' : 'true'); + + return html; +} + +// Parse JSON body from request +function parseBody(req) { + return new Promise((resolve, reject) => { + let data = ''; + let bytes = 0; + req.on('data', chunk => { + bytes += chunk.length; + if (bytes > maxBodyBytes) { + reject(new Error('Request body exceeds 2 MiB')); + req.destroy(); + return; + } + data += chunk; + }); + req.on('end', () => { + try { resolve(data ? JSON.parse(data) : {}); } + catch (err) { reject(new Error('Invalid JSON body')); } + }); + req.on('error', reject); + }); +} + +// Notify all SSE clients +function notifyClients() { + for (let i = sseClients.length - 1; i >= 0; i--) { + try { sseClients[i].write('data: refresh\n\n'); } + catch { sseClients.splice(i, 1); } + } +} + +function jsonResponse(res, statusCode, body) { + const payload = JSON.stringify(body); + res.writeHead(statusCode, { + 'Content-Type': 'application/json', + 'Content-Length': Buffer.byteLength(payload), + }); + res.end(payload); +} + +function htmlResponse(res, html) { + res.writeHead(200, { + 'Content-Type': 'text/html', + 'Content-Length': Buffer.byteLength(html), + }); + res.end(html); +} + +// Main request handler +async function handler(req, res) { + const url = new URL(req.url, `http://${req.headers.host}`); + + try { + // GET /status + if (req.method === 'GET' && url.pathname === '/status') { + jsonResponse(res, 200, { status: 'ok', version: '1.0.0', port: activePort, screens: mockups.length, taskPath: taskPath || null, persistence: !!taskPath, mutationToken }); + return; + } + + if (req.method === 'POST' && req.headers['x-maister-token'] !== mutationToken) { + jsonResponse(res, 403, { error: 'Invalid mutation token' }); + return; + } + + // POST /shutdown + if (req.method === 'POST' && url.pathname === '/shutdown') { + jsonResponse(res, 200, { status: 'shutting_down' }); + cleanupPidFile(); + setTimeout(() => process.exit(0), 100); + return; + } + + // GET /events (SSE) + if (req.method === 'GET' && url.pathname === '/events') { + res.writeHead(200, { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache', + 'Connection': 'keep-alive', + }); + res.write('data: connected\n\n'); + sseClients.push(res); + req.on('close', () => { + const idx = sseClients.indexOf(res); + if (idx !== -1) sseClients.splice(idx, 1); + }); + return; + } + + // POST /update + if (req.method === 'POST' && url.pathname === '/update') { + const body = await parseBody(req); + const id = slugify(body.title || 'untitled'); + + const mockup = { + id, + type: body.type || 'mockup', + title: body.title || 'Untitled', + html: body.html || '', + css: body.css || '', + annotations: body.annotations || [], + }; + + // Update existing or add new + const existingIdx = mockups.findIndex(m => m.id === id); + if (existingIdx !== -1) { + mockups[existingIdx] = mockup; + } else { + mockups.push(mockup); + } + + latestId = id; + version++; + let saved = false; + if (taskPath) { + for (const screen of mockups) saveToDisk(screen); + saved = true; + } else { + saveToDisk(mockup); + } + saveManifest(); + notifyClients(); + jsonResponse(res, 200, { status: 'updated', version, id, screens: mockups.length, saved }); + return; + } + + // GET /screen/:id + const screenMatch = url.pathname.match(/^\/screen\/([a-z0-9-]+)$/); + if (req.method === 'GET' && screenMatch) { + const mockup = mockups.find(m => m.id === screenMatch[1]); + if (!mockup) { + jsonResponse(res, 404, { error: 'Screen not found' }); + return; + } + htmlResponse(res, renderScreen(mockup)); + return; + } + + // GET /latest + if (req.method === 'GET' && url.pathname === '/latest') { + const mockup = mockups.find(m => m.id === latestId); + if (!mockup) { + htmlResponse(res, renderGallery()); + return; + } + htmlResponse(res, renderScreen(mockup)); + return; + } + + // GET / (gallery) + if (req.method === 'GET' && url.pathname === '/') { + htmlResponse(res, renderGallery()); + return; + } + + jsonResponse(res, 404, { error: 'Not found' }); + } catch (err) { + console.error('Request error:', err.message); + jsonResponse(res, 500, { error: err.message }); + } +} + +// PID file management +function pidFilePath() { + if (!taskPath) return null; + assertOutputPathSafe(); + return path.join(outputDir, '.visual-companion.pid'); +} + +function writePidFile() { + const p = pidFilePath(); + if (!p) return; + fs.mkdirSync(path.dirname(p), { recursive: true }); + fs.writeFileSync(p, String(process.pid), 'utf-8'); +} + +function cleanupPidFile() { + try { + const p = pidFilePath(); + if (p) fs.unlinkSync(p); + } catch {} +} + +process.on('SIGTERM', () => { cleanupPidFile(); process.exit(0); }); +process.on('SIGINT', () => { cleanupPidFile(); process.exit(0); }); + +// Port fallback logic +let activePort = null; + +function tryPort(port) { + return new Promise((resolve, reject) => { + const server = http.createServer(handler); + server.listen(port, '127.0.0.1', () => resolve(server)); + server.on('error', reject); + }); +} + +async function start() { + loadManifest(); + const ports = [3847, 3848, 3849, 3850]; + for (const port of ports) { + try { + await tryPort(port); + activePort = port; + console.log(`Visual companion server running at http://127.0.0.1:${port}`); + console.log(`Mutation token: ${mutationToken}`); + if (taskPath) console.log(`Saving mockups to: ${outputDir}`); + writePidFile(); + return; + } catch (err) { + if (err.code === 'EADDRINUSE') { + console.error(`Port ${port} in use, trying next...`); + continue; + } + throw err; + } + } + console.error('All ports (3847-3850) in use. Cannot start server.'); + process.exit(1); +} + +start(); diff --git a/plugins/maister-codex/skills/maister-mockup-studio/server/template.html b/plugins/maister-codex/skills/maister-mockup-studio/server/template.html new file mode 100644 index 00000000..0f0636e5 --- /dev/null +++ b/plugins/maister-codex/skills/maister-mockup-studio/server/template.html @@ -0,0 +1,286 @@ + + + + + + {{TITLE}} — Product Design + + + +
+

{{TITLE}}

+
+ ⊞ Gallery + + Connected +
+
+ + {{NAV}} + +
+ {{CONTENT}} +
+ + + + diff --git a/plugins/maister-codex/skills/maister-orchestrator-framework/SKILL.md b/plugins/maister-codex/skills/maister-orchestrator-framework/SKILL.md new file mode 100644 index 00000000..9eab0adc --- /dev/null +++ b/plugins/maister-codex/skills/maister-orchestrator-framework/SKILL.md @@ -0,0 +1,28 @@ +--- +name: maister-orchestrator-framework +description: Apply Maister's shared rules for resumable, state-driven workflow orchestration, phase gates, recovery, dashboards, and artifact handoffs. Use when creating, auditing, or running a multi-phase Maister workflow. +--- + +# Maister Orchestrator Framework + +Treat this as the shared foundation for every multi-phase Maister workflow. It is primarily an internal reference skill; domain orchestrators load it rather than duplicating its contracts. + +Before initializing or resuming a workflow, read `references/orchestrator-patterns.md` completely. When authoring or auditing an orchestrator, also read `references/orchestrator-creation-checklist.md`. Read `references/html-report-style.md` only when HTML companions are enabled. + +## Required invariants + +- Keep `orchestrator-state.yml` as the durable source of truth. Chat history and transient progress UI are not resume state. +- Capture real UTC timestamps from the system before writing state, logs, or dashboard data. +- Validate completed-phase artifacts before resuming and continue at the first incomplete valid phase. +- Complete phase work, persist artifacts, and refresh the dashboard before presenting a phase gate. Mark the phase complete only after the gate is resolved. +- Ask the user about unresolved product decisions, destructive recovery, rollback, and critical verification findings. At a gate, prefer `request_user_input` when it is available; otherwise ask one concise direct question in the final response. End the turn when an immediate answer is required. +- Never roll back, reset, or discard work without explicit approval. +- Load `.maister/docs/INDEX.md` and the standards relevant to each phase. +- Delegate only independent work. Parallel writes require disjoint declared file ownership; otherwise serialize them. +- Open every durable markdown artifact with the `TL;DR`, `Key Decisions`, and `Open Questions / Risks` contract from the reference. + +## Optional operator output + +Read `.maister/config.yml` once at initialization and persist effective options into state. When `html_output` is true, copy `assets/dashboard.html` into the task root and maintain `dashboard-data.js` as a projection of state. HTML companions must follow `references/html-report-style.md`; markdown remains canonical. Browser opening is best-effort and must not block the workflow. + +Return control to the calling workflow after applying these rules. diff --git a/plugins/maister-codex/skills/maister-orchestrator-framework/agents/openai.yaml b/plugins/maister-codex/skills/maister-orchestrator-framework/agents/openai.yaml new file mode 100644 index 00000000..f1365f15 --- /dev/null +++ b/plugins/maister-codex/skills/maister-orchestrator-framework/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Maister Orchestrator Framework" + short_description: "Share resumable workflow orchestration patterns." + default_prompt: "Use $maister-codex:maister-orchestrator-framework to apply Maister state, gate, recovery, and artifact conventions." diff --git a/plugins/maister-codex/skills/maister-orchestrator-framework/assets/dashboard.html b/plugins/maister-codex/skills/maister-orchestrator-framework/assets/dashboard.html new file mode 100644 index 00000000..bc637430 --- /dev/null +++ b/plugins/maister-codex/skills/maister-orchestrator-framework/assets/dashboard.html @@ -0,0 +1,615 @@ + + + + + +Maister Workflow Dashboard + + + + +
+
+ Waiting for dashboard-data.js… If this persists, the workflow has not written data yet. +
+
+ + + + diff --git a/plugins/maister-codex/skills/maister-orchestrator-framework/references/html-report-style.md b/plugins/maister-codex/skills/maister-orchestrator-framework/references/html-report-style.md new file mode 100644 index 00000000..9d08f5ec --- /dev/null +++ b/plugins/maister-codex/skills/maister-orchestrator-framework/references/html-report-style.md @@ -0,0 +1,168 @@ +# HTML Companion Report Style Guide + +Shared conventions for agents that emit an HTML companion next to a markdown artifact (orchestrator-patterns.md § 9). Goal: every companion looks like part of one family, regardless of which agent or session produced it. + +## Hard Rules + +1. **Self-contained single file** — inline ` + + +