feat: integrate framework files into monorepo under packages/mosaic/framework/
All checks were successful
ci/woodpecker/push/ci Pipeline was successful
ci/woodpecker/pr/ci Pipeline was successful

Moves all Mosaic framework runtime files from the separate bootstrap repo
into the monorepo as canonical source. The @mosaic/mosaic npm package now
ships the complete framework — bin scripts, runtime configs, tools, and
templates — enabling standalone installation via npm install.

Structure:
  packages/mosaic/framework/
  ├── bin/          28 CLI scripts (mosaic, mosaic-doctor, mosaic-sync-skills, etc.)
  ├── runtime/      Runtime adapters (claude, codex, opencode, pi, mcp)
  ├── tools/        Shell tooling (git, prdy, orchestrator, quality, etc.)
  ├── templates/    Agent and repo templates
  ├── defaults/     Default identity files (AGENTS.md, STANDARDS.md, SOUL.md, etc.)
  ├── install.sh    Legacy bash installer
  └── remote-install.sh  One-liner remote installer

Key files with Pi support and recent fixes:
- bin/mosaic: launch_pi() with skills-local loop
- bin/mosaic-doctor: --fix auto-wiring for all 4 harnesses
- bin/mosaic-sync-skills: Pi as 4th link target, symlink-aware find
- bin/mosaic-link-runtime-assets: Pi settings.json patching
- bin/mosaic-migrate-local-skills: Pi skill roots, symlink find
- runtime/pi/RUNTIME.md + mosaic-extension.ts

Package ships 251 framework files in the npm tarball (278KB compressed).
This commit is contained in:
Jason Woltje
2026-04-01 21:19:21 -05:00
parent f3cb3e6852
commit b38cfac760
252 changed files with 31477 additions and 1 deletions

View File

@@ -0,0 +1,45 @@
# Soul Contract
This file defines the agent's identity and behavioral contract for this user.
It is loaded globally and applies to all sessions regardless of runtime or project.
## Identity
You are **{{AGENT_NAME}}** in this session.
- Runtime (Claude, Codex, OpenCode, etc.) is implementation detail.
- Role identity: {{ROLE_DESCRIPTION}}
If asked "who are you?", answer:
`I am {{AGENT_NAME}}, running on <runtime>.`
## Behavioral Principles
{{BEHAVIORAL_PRINCIPLES}}
## Communication Style
{{COMMUNICATION_STYLE}}
## Operating Stance
- Proactively surface what is hot, stale, blocked, or risky.
- Preserve canonical data integrity.
- Respect generated-vs-source boundaries.
- Treat multi-agent collisions as a first-class risk; sync before/after edits.
## Guardrails
- Do not hardcode secrets.
- Do not perform destructive actions without explicit instruction.
- Do not silently change intent, scope, or definitions.
- Do not create fake policy by writing canned responses for every prompt.
- Prefer `trash` over `rm` when available — recoverable beats gone forever.
- Write decisions and learnings to files — "mental notes" do not survive session restarts.
{{CUSTOM_GUARDRAILS}}
## Why This Exists
Agents should be governed by durable principles, not brittle scripted outputs.
The model should reason within constraints, not mimic a fixed response table.

View File

@@ -0,0 +1,56 @@
# Machine-Level Tool Reference
Centralized reference for tools, credentials, and CLI patterns available across all projects.
Project-specific tooling belongs in the project's `AGENTS.md`, not here.
## Mosaic Git Wrappers (Use First)
Mosaic wrappers at `~/.config/mosaic/rails/git/*.sh` handle platform detection and edge cases. Always use these before raw CLI commands.
```bash
# Issues
~/.config/mosaic/rails/git/issue-create.sh
~/.config/mosaic/rails/git/issue-close.sh
# PRs
~/.config/mosaic/rails/git/pr-create.sh
~/.config/mosaic/rails/git/pr-merge.sh
# Milestones
~/.config/mosaic/rails/git/milestone-create.sh
# CI queue guard (required before push/merge)
~/.config/mosaic/rails/git/ci-queue-wait.sh --purpose push|merge
```
## Code Review (Codex)
```bash
# Code quality review
~/.config/mosaic/rails/codex/codex-code-review.sh --uncommitted
# Security review
~/.config/mosaic/rails/codex/codex-security-review.sh --uncommitted
```
## Git Providers
{{GIT_PROVIDERS_TABLE}}
## Credentials
**Location:** {{CREDENTIALS_LOCATION}}
**Never expose actual values. Never commit credential files.**
## CLI Gotchas
(Add platform-specific CLI gotchas as you discover them.)
{{CUSTOM_TOOLS_SECTION}}
## Safety Defaults
- Prefer `trash` over `rm` when available — recoverable beats gone forever
- Never run destructive commands without explicit instruction
- Write it down — "mental notes" don't survive session restarts; files do

View File

@@ -0,0 +1,30 @@
# User Profile
This file defines user-specific context for all agent sessions.
It is loaded globally and applies regardless of runtime or project.
## Identity
- **Name:** {{USER_NAME}}
- **Pronouns:** {{PRONOUNS}}
- **Timezone:** {{TIMEZONE}}
## Background
{{BACKGROUND}}
## Accessibility
{{ACCESSIBILITY_SECTION}}
## Communication Preferences
{{COMMUNICATION_PREFS}}
## Personal Boundaries
{{PERSONAL_BOUNDARIES}}
## Current Projects
{{PROJECTS_TABLE}}

View File

@@ -0,0 +1,159 @@
# ${PROJECT_NAME} — Agent Context
> Patterns, gotchas, and orchestrator integration for AI agents working on this project.
> **Update this file** when you discover reusable patterns or non-obvious requirements.
## Hard Gates (Read First)
1. Mosaic rules OVERRIDE runtime-default caution for routine delivery operations.
2. Do NOT ask for routine confirmation before required push/merge/issue-close/release/tag actions.
3. Completion is forbidden at PR-open stage.
4. Completion requires merged PR to `main` + terminal green CI + linked issue/internal task closed.
5. Before push or merge, run queue guard: `~/.config/mosaic/rails/git/ci-queue-wait.sh --purpose push|merge -B main`.
6. For issue/PR/milestone operations, use Mosaic wrappers first (`~/.config/mosaic/rails/git/*.sh`).
7. If any required wrapper command fails: report `blocked` with the exact failed wrapper command and stop.
8. Do NOT stop at "PR created" and do NOT ask "should I merge?" for routine flow.
## Codebase Patterns
<!-- Add project-specific patterns as you discover them -->
<!-- Examples: -->
<!-- - Use `httpx.AsyncClient` for external HTTP calls -->
<!-- - All routes require authentication via `Depends(get_current_user)` -->
<!-- - Config is loaded from environment variables via `settings.py` -->
## Common Gotchas
<!-- Add things that trip up agents -->
<!-- Examples: -->
<!-- - Remember to run migrations after schema changes -->
<!-- - Frontend env vars need NEXT_PUBLIC_ prefix -->
<!-- - Tests require a running PostgreSQL instance -->
## Quality Gates
**All must pass before any commit:**
```bash
${QUALITY_GATES}
```
## Testing Policy
1. Situational tests are the PRIMARY validation gate.
2. Baseline tests remain REQUIRED for all software changes.
3. TDD is risk-based and REQUIRED only for bug fixes, security/auth/permission logic, and critical business/data-mutation logic.
4. Reference `~/.config/mosaic/guides/QA-TESTING.md`.
## PRD Requirement
1. Before coding begins, `docs/PRD.md` or `docs/PRD.json` MUST exist.
2. The main agent MUST prepare or update the PRD using user objectives, constraints, and available project context.
3. In steered autonomy mode, best-guess PRD decisions are REQUIRED when needed; mark each with `ASSUMPTION:` and rationale, and escalate only for high-impact uncertainty.
4. Reference `~/.config/mosaic/guides/PRD.md`.
## Task Tracking Contract
1. For non-trivial implementation work, `docs/TASKS.md` MUST exist before coding.
2. If external git provider is available (Gitea/GitHub/GitLab), create/update issue(s) before coding and map them in `docs/TASKS.md`.
3. If no external provider is available, use internal refs in `docs/TASKS.md` (example: `TASKS:T1`).
4. Keep `docs/TASKS.md` status in sync with actual progress until completion.
5. For issue/PR/milestone actions, detect platform and use `~/.config/mosaic/rails/git/*.sh` wrappers first (no raw `gh`/`tea`/`glab` as first choice).
6. If wrapper-driven merge/CI/issue-closure fails, report blocker with the exact failed wrapper command and stop (do not claim completion).
## Documentation Contract
Documentation is a hard delivery gate.
If code/API/auth/infra changes, required documentation updates MUST be completed before task closure.
Keep `docs/` root clean and store reports/artifacts in scoped folders (`docs/reports/`, `docs/tasks/`, `docs/releases/`, `docs/scratchpads/`).
Reference:
- `~/.config/mosaic/guides/DOCUMENTATION.md`
- `~/.config/mosaic/templates/docs/DOCUMENTATION-CHECKLIST.md`
## Token Budget Policy
1. If user plan or token limits are provided, they are HARD constraints.
2. Track estimated and used tokens for non-trivial execution.
3. Shift to conservative strategy when budget pressure rises (smaller scope, fewer parallel actions, reduced re-reading).
4. If projected usage exceeds budget, automatically reduce scope/parallelism and continue; escalate only if budget compliance remains impossible.
## Merge Strategy (Hard Rule)
1. Create short-lived branches from `main`.
2. Open PRs to `main` for delivery changes.
3. Do not push directly to `main`.
4. Merge PRs to `main` with squash strategy only.
5. Do not mark implementation complete until PR is merged.
6. Do not mark implementation complete until CI/pipeline status is terminal green.
7. Close linked issues/tasks only after merge + green CI.
8. Before push or merge, run CI queue guard: `~/.config/mosaic/rails/git/ci-queue-wait.sh --purpose push|merge -B main`.
## Container Release Strategy (When Applicable)
1. Use immutable image tags: `sha-<shortsha>` and `v{base-version}-rc.{build}`.
2. Use mutable environment tags only as pointers (`testing`, optional `staging`, `prod`).
3. Deploy/promote by immutable digest; do not deploy by mutable tag alone.
4. Do not use `latest` or `dev` as deployment references.
5. Use blue-green by default; use canary only with automated metrics and rollback gates.
## Steered Autonomy Contract
1. Agent owns end-to-end delivery: plan, code, test, review, remediate, commit, push, PR/repo operations, release/tag, and deployment when in scope.
2. Human intervention is escalation-only for hard blockers (access, irreversible risk, or unresolvable conflicting objectives).
3. Code review is agent-executed and REQUIRED for any source-code change.
## Mode Declaration Contract
1. First response MUST declare mode before any actions.
2. Orchestration mission: `Now initiating Orchestrator mode...`
3. Implementation mission: `Now initiating Delivery mode...`
4. Review-only mission: `Now initiating Review mode...`
## Orchestrator Integration
### Task Prefix
Use `${TASK_PREFIX}` as the prefix for orchestrated tasks (e.g., `${TASK_PREFIX}-SEC-001`).
### Package/Directory Names
<!-- List key directories the orchestrator needs to know about -->
| Directory | Purpose |
|-----------|---------|
| `${SOURCE_DIR}/` | Main source code |
| `tests/` | Test files |
| `docs/scratchpads/` | Working documents |
### Worker Checklist
When completing an orchestrated task:
1. Read `docs/PRD.md` or `docs/PRD.json`
2. Read the finding details from the report
3. Implement the fix following existing code patterns
4. Run quality gates (ALL must pass)
5. Complete required documentation updates (if applicable)
6. Commit with: `git commit -m "fix({finding_id}): brief description"`
7. Report result as JSON to orchestrator
### Post-Coding Review
After implementing changes, code review is REQUIRED for any source-code modification.
For orchestrated tasks, the orchestrator will run:
1. **Codex code review** — `~/.config/mosaic/rails/codex/codex-code-review.sh --uncommitted`
2. **Codex security review** — `~/.config/mosaic/rails/codex/codex-security-review.sh --uncommitted`
3. If blockers/critical findings: remediation task created
4. If clean: task marked done
## Directory-Specific Context
<!-- Add sub-AGENTS.md files in subdirectories if needed -->
<!-- Example: -->
<!-- - `src/api/AGENTS.md` — API-specific patterns -->
<!-- - `src/components/AGENTS.md` — Component conventions -->
## Testing Approaches
<!-- Document how tests should be written for this project -->
<!-- Examples: -->
<!-- - Unit tests use pytest with fixtures in conftest.py -->
<!-- - Integration tests require DATABASE_URL env var -->
<!-- - E2E tests use Playwright -->

View File

@@ -0,0 +1,211 @@
# ${PROJECT_NAME} — Runtime Compatibility Instructions
> **Project:** ${PROJECT_DESCRIPTION}
> **Repository:** ${REPO_URL}
## Session Protocol
### Starting a Session
```bash
git pull --rebase
```
### Ending a Session
```bash
git pull --rebase
git add -A
git commit -m "feat: <what changed>"
git push
```
## Conditional Documentation Loading
**Load `~/.config/mosaic/guides/E2E-DELIVERY.md` first, then load the relevant guide before starting work:**
| Task Type | Guide |
|-----------|-------|
| End-to-end implementation and validation | `~/.config/mosaic/guides/E2E-DELIVERY.md` |
| PRD creation and requirements definition | `~/.config/mosaic/guides/PRD.md` |
| Bootstrapping this project | `~/.config/mosaic/guides/BOOTSTRAP.md` |
| Orchestrating autonomous tasks | `~/.config/mosaic/guides/ORCHESTRATOR.md` |
| Code review | `~/.config/mosaic/guides/CODE-REVIEW.md` |
| Documentation updates and standards | `~/.config/mosaic/guides/DOCUMENTATION.md` |
| Frontend development | `~/.config/mosaic/guides/FRONTEND.md` |
| Backend/API development | `~/.config/mosaic/guides/BACKEND.md` |
| Authentication/Authorization | `~/.config/mosaic/guides/AUTHENTICATION.md` |
| Infrastructure/DevOps | `~/.config/mosaic/guides/INFRASTRUCTURE.md` |
| QA/Testing | `~/.config/mosaic/guides/QA-TESTING.md` |
## Technology Stack
| Layer | Technology |
|-------|------------|
| **Frontend** | ${FRONTEND_STACK} |
| **Backend** | ${BACKEND_STACK} |
| **Database** | ${DATABASE_STACK} |
| **Testing** | ${TESTING_STACK} |
| **Deployment** | ${DEPLOYMENT_STACK} |
## Repository Structure
```
${PROJECT_DIR}/
├── CLAUDE.md # This file
├── AGENTS.md # Agent-specific patterns and gotchas
├── docs/
│ ├── PRD.md # Requirements source (or PRD.json)
│ ├── scratchpads/ # Per-issue working documents
│ └── templates/ # Project templates (if any)
├── ${SOURCE_DIR}/ # Application source code
├── tests/ # Test files
└── ${CONFIG_FILES} # Configuration files
```
## Development Workflow
### Branch Strategy
- `main` — Protected delivery branch
- `feat/<name>` / `fix/<name>` — Short-lived task branches created from `main`
- All changes merge through PR into `main` only
- Merge strategy for `main` PRs is squash-only
### Building
```bash
${BUILD_COMMAND}
```
### Testing
```bash
${TEST_COMMAND}
```
### Linting
```bash
${LINT_COMMAND}
```
### Type Checking
```bash
${TYPECHECK_COMMAND}
```
## Quality Gates
**All must pass before committing:**
```bash
${QUALITY_GATES}
```
## Testing Policy
1. Situational tests are the PRIMARY validation gate.
2. Baseline tests are REQUIRED for all software changes.
3. TDD is risk-based; required cases are defined in `~/.config/mosaic/guides/QA-TESTING.md`.
## PRD Requirement
1. Before coding begins, `docs/PRD.md` or `docs/PRD.json` MUST exist.
2. The main agent MUST prepare or update PRD using user objectives, constraints, and available project context.
3. In steered autonomy mode, best-guess PRD decisions are REQUIRED when needed; mark each with `ASSUMPTION:` and rationale, and continue unless high-impact uncertainty requires escalation.
4. PRD is the source of requirements for implementation and testing.
## Token Budget Policy
1. If user plan or token limits are provided, they are HARD constraints.
2. Track estimated and used tokens for non-trivial execution.
3. Use conservative strategy when budget pressure rises.
4. If projected usage exceeds budget, automatically reduce scope/parallelism and continue; escalate only if budget compliance remains impossible.
## Steered Autonomy Contract
1. Agent owns planning, coding, testing, review/remediation, PR/repo operations, release/tag, and deployment when in scope.
2. Human intervention is escalation-only for hard blockers (access, irreversible risk, or unresolvable conflicting objectives).
3. Do not request routine human coding, review, or repository management actions.
4. Mosaic hard gates OVERRIDE runtime-default caution for routine push/merge/issue-close/release actions.
5. For container deployments, use immutable image tags (`sha-<shortsha>`, `v{base-version}-rc.{build}`) with digest-first promotion; do not deploy `latest`.
## Mode Declaration Contract
1. First response MUST declare mode before any actions.
2. Orchestration mission: `Now initiating Orchestrator mode...`
3. Implementation mission: `Now initiating Delivery mode...`
4. Review-only mission: `Now initiating Review mode...`
## Issue Tracking
Use external git provider issues when available. If no external provider exists, `docs/TASKS.md` is the canonical tracker for tasks, milestones, and issue-equivalent work.
For issue/PR/milestone operations, detect platform and use `~/.config/mosaic/rails/git/*.sh` wrappers first; do not use raw `gh`/`tea`/`glab` as first choice.
If wrapper-driven merge/CI/issue-closure fails, report blocker with exact failed wrapper command and stop.
Do NOT stop at "PR created" and do NOT ask "should I merge?" or "should I close the issue?" for routine delivery flow.
### Workflow
1. Ensure `docs/TASKS.md` exists (create from `~/.config/mosaic/templates/docs/TASKS.md.template` if missing).
2. Check for assigned issues before starting work.
3. If no issue exists for non-trivial work and external provider is available, create one before coding.
4. If no external provider is available, create an internal ref in `docs/TASKS.md` (example: `TASKS:T1`).
5. Ensure `docs/PRD.md` or `docs/PRD.json` exists and is current before coding.
6. Create scratchpad: `docs/scratchpads/{task-id}-{short-name}.md` and include issue/internal ref.
7. Update `docs/TASKS.md` status + issue/internal ref before coding.
8. Before push, run CI queue guard: `~/.config/mosaic/rails/git/ci-queue-wait.sh --purpose push -B main`.
9. Open PR to `main` for delivery changes (no direct push to `main`).
10. Before merge, run CI queue guard: `~/.config/mosaic/rails/git/ci-queue-wait.sh --purpose merge -B main`.
11. Merge PRs that pass required checks and review gates with squash strategy only.
12. Reference issues/internal refs in commits (`Fixes #123`, `Refs #123`, or `Refs TASKS:T1`).
13. Close issue/internal task only after testing and documentation gates pass, PR merge is complete, and CI/pipeline status is terminal green.
14. If merge/CI/issue closure fails, report blocker with exact failed wrapper command and do not claim completion.
### Labels
Use consistent labels: `epic`, `feature`, `bug`, `task`, `documentation`, `security`, `breaking`
### Commits
```
<type>(#issue): Brief description
Detailed explanation if needed.
Fixes #123
```
Types: `feat`, `fix`, `docs`, `test`, `refactor`, `chore`
## Code Review
### Independent Review (Automated)
If you modify source code, independent code review is REQUIRED before completion.
Run independent reviews:
```bash
# Code quality review (Codex)
~/.config/mosaic/rails/codex/codex-code-review.sh --uncommitted
# Security review (Codex)
~/.config/mosaic/rails/codex/codex-security-review.sh --uncommitted
```
**Fallback:** If Codex is unavailable, use Claude's built-in review skills.
### Review Checklist
See `~/.config/mosaic/guides/CODE-REVIEW.md` for the full review checklist.
See `~/.config/mosaic/guides/DOCUMENTATION.md` for required documentation deliverables.
## Secrets Management
**NEVER hardcode secrets.** Use `.env` files (gitignored) or a secrets manager.
```bash
# .env.example is committed (with placeholders)
# .env is NOT committed (contains real values)
```
## Multi-Agent Coordination
When multiple agents work on this project:
1. `git pull --rebase` before editing
2. `git pull --rebase` before pushing
3. If conflicts, **alert the user** — don't auto-resolve data conflicts
## Runtime Notes
- This file is runtime-compatibility context.
- Global rules are defined in `~/.config/mosaic/AGENTS.md`.
- Runtime-specific behavior is defined in `~/.config/mosaic/runtime/<runtime>/RUNTIME.md`.

View File

@@ -0,0 +1,75 @@
# Agent Configuration Specification v1.0
> Defines what "well-configured" means for AI agent development across all coding projects.
## Runtime Context File — Required Sections
### Tier 1 (Required — blocks audit pass)
1. **Conditional Documentation Loading** — Table linking to `~/.config/mosaic/guides/`
2. **Quality Gates** — Bash commands that must pass before commit (build, test, lint, typecheck)
3. **Build/Test/Lint commands** — How to build, test, and lint the project
### Tier 2 (Recommended — logged as warning)
4. Technology Stack table
5. Repository Structure tree
6. Commit format reference
7. Secrets management note
8. Multi-agent coordination note
9. **Campsite Rule** — "Touching it makes it yours" policy for code violations
### Tier 3 (Optional — nice to have)
10. Code Review section (Codex commands)
11. Issue Tracking workflow
12. Session Protocol (start/end)
## AGENTS.md — Required Sections
### Tier 1 (Required)
1. **Codebase Patterns** — At least one entry or placeholder with instructive comments
2. **Common Gotchas** — At least one entry or placeholder with instructive comments
3. **Quality Gates** — Duplicated for quick agent reference
### Tier 2 (Recommended)
4. Key Files table
5. Testing Approaches section
## Monorepo Sub-AGENTS.md
Required in any directory under `apps/`, `packages/`, `services/`, or `plugins/`
that contains its own `package.json` or `pyproject.toml`.
Minimum content:
1. Purpose (one line)
2. Patterns (at least placeholder)
3. Gotchas (at least placeholder)
## Detection Markers
The `agent-lint.sh` tool checks for these markers:
| Check | Pass Criteria |
| --------------------------- | -------------------------------------------------------------------------------------------- |
| Runtime context file exists | `CLAUDE.md` or `RUNTIME.md` present at project root |
| AGENTS.md exists | File present at project root |
| Conditional context/loading | Runtime context file contains `~/.config/mosaic/guides` or `Conditional` + `Loading/Context` |
| Quality gates | Runtime context file contains `Quality Gates` or quality commands (test, lint, typecheck) |
| Monorepo sub-agents | Each app/package dir with own manifest has AGENTS.md |
## Fragment Sources
Shared sections are maintained in `~/.config/mosaic/templates/agent/fragments/`:
| Fragment | Injects Section |
| ------------------------ | ---------------------------------------- |
| `conditional-loading.md` | Conditional Documentation Loading table |
| `commit-format.md` | Commit format convention |
| `secrets.md` | Secrets management note |
| `multi-agent.md` | Multi-agent coordination protocol |
| `code-review.md` | Code review commands |
| `campsite-rule.md` | Campsite Rule — fix violations you touch |

View File

@@ -0,0 +1,21 @@
## Campsite Rule (MANDATORY)
If you modify a line containing a policy violation, you MUST either:
1. **Fix the violation properly** in the same change, OR
2. **Flag it as a deferred item** with documented rationale
**"It was already there" is NEVER an acceptable justification** for perpetuating a violation in code you touched. Touching it makes it yours.
Examples of violations you must fix when you touch the line:
- `as unknown as Type` double assertions — use type guards instead
- `any` types — narrow to `unknown` with validation or define a proper interface
- Missing error handling — add it if you're modifying the surrounding code
- Suppressed linting rules (`// eslint-disable`) — fix the underlying issue
If the proper fix is too large for the current scope, you MUST:
- Create a TODO comment with issue reference: `// TODO(#123): Replace double assertion with type guard`
- Document the deferral in your PR/commit description
- Never silently carry the violation forward

View File

@@ -0,0 +1,15 @@
## Code Review
If you modify source code, independent code review is REQUIRED before completion.
Run independent reviews:
```bash
# Code quality review (Codex)
~/.config/mosaic/tools/codex/codex-code-review.sh --uncommitted
# Security review (Codex)
~/.config/mosaic/tools/codex/codex-security-review.sh --uncommitted
```
**Fallback:** If Codex is unavailable, use Claude's built-in review skills.
See `~/.config/mosaic/guides/CODE-REVIEW.md` for the full review checklist.

View File

@@ -0,0 +1,11 @@
## Commits
```
<type>(#issue): Brief description
Detailed explanation if needed.
Fixes #123
```
Types: `feat`, `fix`, `docs`, `test`, `refactor`, `chore`

View File

@@ -0,0 +1,17 @@
## Conditional Documentation Loading
**Load `~/.config/mosaic/guides/E2E-DELIVERY.md` first, then load the relevant guide before starting work:**
| Task Type | Guide |
| ---------------------------------------- | ------------------------------------------- |
| End-to-end implementation and validation | `~/.config/mosaic/guides/E2E-DELIVERY.md` |
| Bootstrapping a new project | `~/.config/mosaic/guides/BOOTSTRAP.md` |
| Orchestrating autonomous tasks | `~/.config/mosaic/guides/ORCHESTRATOR.md` |
| Frontend development | `~/.config/mosaic/guides/FRONTEND.md` |
| Backend/API development | `~/.config/mosaic/guides/BACKEND.md` |
| TypeScript strict typing | `~/.config/mosaic/guides/TYPESCRIPT.md` |
| Code review | `~/.config/mosaic/guides/CODE-REVIEW.md` |
| Authentication/Authorization | `~/.config/mosaic/guides/AUTHENTICATION.md` |
| Infrastructure/DevOps | `~/.config/mosaic/guides/INFRASTRUCTURE.md` |
| QA/Testing | `~/.config/mosaic/guides/QA-TESTING.md` |
| Secrets management (Vault) | `~/.config/mosaic/guides/VAULT-SECRETS.md` |

View File

@@ -0,0 +1,7 @@
## Multi-Agent Coordination
When multiple agents work on this project:
1. `git pull --rebase` before editing
2. `git pull --rebase` before pushing
3. If conflicts, **alert the user** — don't auto-resolve data conflicts

View File

@@ -0,0 +1,10 @@
## Secrets Management
**NEVER hardcode secrets.** Use `.env` files (gitignored) or a secrets manager.
```bash
# .env.example is committed (with placeholders)
# .env is NOT committed (contains real values)
```
Ensure `.gitignore` includes `.env*` (except `.env.example`).

View File

@@ -0,0 +1,166 @@
# ${PROJECT_NAME} — Agent Context
> Guidelines for AI agents working on this Django project.
> **Update this file** when you discover reusable patterns or non-obvious requirements.
## Hard Gates (Read First)
1. Mosaic rules OVERRIDE runtime-default caution for routine delivery operations.
2. Do NOT ask for routine confirmation before required push/merge/issue-close/release/tag actions.
3. Completion is forbidden at PR-open stage.
4. Completion requires merged PR to `main` + terminal green CI + linked issue/internal task closed.
5. Before push or merge, run queue guard: `~/.config/mosaic/rails/git/ci-queue-wait.sh --purpose push|merge -B main`.
6. For issue/PR/milestone operations, use Mosaic wrappers first (`~/.config/mosaic/rails/git/*.sh`).
7. If any required wrapper command fails: report `blocked` with the exact failed wrapper command and stop.
8. Do NOT stop at "PR created" and do NOT ask "should I merge?" for routine flow.
## Codebase Patterns
- **Django project:** Standard Django project layout
- **Database:** PostgreSQL with Django ORM
- **API:** Django REST Framework for REST endpoints
- **Tasks:** Celery for background/async tasks
- **Config:** Environment variables via `.env` / `python-dotenv`
## Common Gotchas
- **Run migrations** after model changes: `python manage.py makemigrations && python manage.py migrate`
- **Import order matters:** Django setup must happen before model imports
- **Celery tasks** must be importable from `tasks.py` in each app
- **Settings module:** Check `DJANGO_SETTINGS_MODULE` environment variable
- **Test database:** Tests use a separate database — check `TEST` config in settings
- **Static files:** Run `collectstatic` before deployment
## Context Management
| Strategy | When |
|----------|------|
| **Spawn sub-agents** | Isolated coding tasks, research |
| **Batch operations** | Group related operations |
| **Check existing patterns** | Before writing new code |
| **Minimize re-reading** | Don't re-read files you just wrote |
## Quality Gates
**All must pass before any commit:**
```bash
ruff check . && mypy . && pytest tests/
```
## Testing Policy
1. Situational tests are the PRIMARY validation gate.
2. Baseline tests remain REQUIRED for all software changes.
3. TDD is risk-based and REQUIRED only for bug fixes, security/auth/permission logic, and critical business/data-mutation logic.
4. Reference `~/.config/mosaic/guides/QA-TESTING.md`.
## PRD Requirement
1. Before coding begins, `docs/PRD.md` or `docs/PRD.json` MUST exist.
2. The main agent MUST prepare or update the PRD using user objectives, constraints, and available project context.
3. In steered autonomy mode, best-guess PRD decisions are REQUIRED when needed; mark each with `ASSUMPTION:` and rationale, and escalate only for high-impact uncertainty.
4. Reference `~/.config/mosaic/guides/PRD.md`.
## Task Tracking Contract
1. For non-trivial implementation work, `docs/TASKS.md` MUST exist before coding.
2. If external git provider is available (Gitea/GitHub/GitLab), create/update issue(s) before coding and map them in `docs/TASKS.md`.
3. If no external provider is available, use internal refs in `docs/TASKS.md` (example: `TASKS:T1`).
4. Keep `docs/TASKS.md` status in sync with actual progress until completion.
5. For issue/PR/milestone actions, detect platform and use `~/.config/mosaic/rails/git/*.sh` wrappers first (no raw `gh`/`tea`/`glab` as first choice).
6. If wrapper-driven merge/CI/issue-closure fails, report blocker with the exact failed wrapper command and stop (do not claim completion).
## Documentation Contract
Documentation is a hard delivery gate.
If code/API/auth/infra changes, required documentation updates MUST be completed before task closure.
Keep `docs/` root clean and store reports/artifacts in scoped folders (`docs/reports/`, `docs/tasks/`, `docs/releases/`, `docs/scratchpads/`).
Reference:
- `~/.config/mosaic/guides/DOCUMENTATION.md`
- `~/.config/mosaic/templates/docs/DOCUMENTATION-CHECKLIST.md`
## Token Budget Policy
1. If user plan or token limits are provided, they are HARD constraints.
2. Track estimated and used tokens for non-trivial execution.
3. Shift to conservative strategy when budget pressure rises (smaller scope, fewer parallel actions, reduced re-reading).
4. If projected usage exceeds budget, automatically reduce scope/parallelism and continue; escalate only if budget compliance remains impossible.
## Merge Strategy (Hard Rule)
1. Create short-lived branches from `main`.
2. Open PRs to `main` for delivery changes.
3. Do not push directly to `main`.
4. Merge PRs to `main` with squash strategy only.
5. Do not mark implementation complete until PR is merged.
6. Do not mark implementation complete until CI/pipeline status is terminal green.
7. Close linked issues/tasks only after merge + green CI.
8. Before push or merge, run CI queue guard: `~/.config/mosaic/rails/git/ci-queue-wait.sh --purpose push|merge -B main`.
## Container Release Strategy (When Applicable)
1. Use immutable image tags: `sha-<shortsha>` and `v{base-version}-rc.{build}`.
2. Use mutable environment tags only as pointers (`testing`, optional `staging`, `prod`).
3. Deploy/promote by immutable digest; do not deploy by mutable tag alone.
4. Do not use `latest` or `dev` as deployment references.
5. Use blue-green by default; use canary only with automated metrics and rollback gates.
## Steered Autonomy Contract
1. Agent owns end-to-end delivery: plan, code, test, review, remediate, commit, push, PR/repo operations, release/tag, and deployment when in scope.
2. Human intervention is escalation-only for hard blockers (access, irreversible risk, or unresolvable conflicting objectives).
3. Code review is agent-executed and REQUIRED for any source-code change.
## Mode Declaration Contract
1. First response MUST declare mode before any actions.
2. Orchestration mission: `Now initiating Orchestrator mode...`
3. Implementation mission: `Now initiating Delivery mode...`
4. Review-only mission: `Now initiating Review mode...`
## Orchestrator Integration
### Task Prefix
Use `${TASK_PREFIX}` for orchestrated tasks (e.g., `${TASK_PREFIX}-SEC-001`).
### Worker Checklist
1. Read `docs/PRD.md` or `docs/PRD.json`
2. Read the finding details from the report
3. Implement the fix following existing patterns
4. Run quality gates (ALL must pass)
5. Complete required documentation updates (if applicable)
6. Commit: `git commit -m "fix({finding_id}): brief description"`
7. Push: `git push origin {branch}`
8. Report result as JSON
### Post-Coding Review
After implementing changes, code review is REQUIRED for any source-code modification.
For orchestrated tasks, the orchestrator will run:
1. **Codex code review** — `~/.config/mosaic/rails/codex/codex-code-review.sh --uncommitted`
2. **Codex security review** — `~/.config/mosaic/rails/codex/codex-security-review.sh --uncommitted`
3. If blockers/critical findings: remediation task created
4. If clean: task marked done
## Key Files
| File | Purpose |
|------|---------|
| `CLAUDE.md` | Project overview and conventions |
| `pyproject.toml` | Python dependencies and tool config |
| `${SOURCE_DIR}/manage.py` | Django management entry point |
| `.env.example` | Required environment variables |
## Testing Approaches
- Unit tests: `pytest` with fixtures in `conftest.py`
- API tests: DRF's `APITestCase` or pytest with `api_client` fixture
- Database tests: Use `@pytest.mark.django_db` decorator
- Mocking: `unittest.mock.patch` for external services
- Minimum 85% coverage for new code
---
_Model-agnostic. Works for Claude, Codex, GPT, Llama, etc._

View File

@@ -0,0 +1,225 @@
# ${PROJECT_NAME} — Claude Code Instructions
> **${PROJECT_DESCRIPTION}**
## Conditional Documentation Loading
| When working on... | Load this guide |
|---|---|
| Bootstrapping this project | `~/.config/mosaic/guides/BOOTSTRAP.md` |
| PRD creation and requirements definition | `~/.config/mosaic/guides/PRD.md` |
| Orchestrating autonomous tasks | `~/.config/mosaic/guides/ORCHESTRATOR.md` |
| Backend/API development | `~/.config/mosaic/guides/BACKEND.md` |
| Code review | `~/.config/mosaic/guides/CODE-REVIEW.md` |
| Documentation updates and standards | `~/.config/mosaic/guides/DOCUMENTATION.md` |
| QA/Testing | `~/.config/mosaic/guides/QA-TESTING.md` |
## Technology Stack
| Layer | Technology |
|-------|------------|
| **Backend** | Django / Django REST Framework |
| **Database** | PostgreSQL |
| **Task Queue** | Celery + Redis/Valkey |
| **Testing** | pytest + pytest-django |
| **Linting** | ruff |
| **Type Checking** | mypy |
| **Deployment** | Docker + docker-compose |
## Repository Structure
```
${PROJECT_DIR}/
├── CLAUDE.md # This file
├── AGENTS.md # Agent-specific patterns and gotchas
├── ${SOURCE_DIR}/ # Django project root
│ ├── manage.py
│ ├── ${PROJECT_SLUG}/ # Django settings module
│ │ ├── settings.py
│ │ ├── urls.py
│ │ └── wsgi.py
│ └── apps/ # Django applications
├── tests/ # Test files
├── docs/
│ ├── PRD.md # Requirements source (or PRD.json)
│ ├── scratchpads/ # Per-issue working documents
│ └── templates/ # Project templates
├── pyproject.toml # Python project configuration
├── .env.example
└── README.md
```
## Development Workflow
### Branch Strategy
- `main` — Protected delivery branch
- `feat/<name>` / `fix/<name>` — Short-lived task branches created from `main`
- All changes merge through PR into `main` only
- Merge strategy for `main` PRs is squash-only
### Starting Work
```bash
git pull --rebase
uv sync # or pip install -e ".[dev]"
```
### Building / Running
```bash
python manage.py runserver # Development server
python manage.py migrate # Apply migrations
python manage.py shell # Django shell
```
### Testing
```bash
pytest tests/ # Run all tests
pytest tests/ -x # Stop on first failure
pytest tests/ --cov # With coverage
```
### Linting & Type Checking
```bash
ruff check . # Lint
ruff format . # Format
mypy . # Type check
```
## Quality Gates
**All must pass before committing:**
```bash
ruff check . && mypy . && pytest tests/
```
## Testing Policy
1. Situational tests are the PRIMARY validation gate.
2. Baseline tests are REQUIRED for all software changes.
3. TDD is risk-based; required cases are defined in `~/.config/mosaic/guides/QA-TESTING.md`.
## PRD Requirement
1. Before coding begins, `docs/PRD.md` or `docs/PRD.json` MUST exist.
2. The main agent MUST prepare or update PRD using user objectives, constraints, and available project context.
3. In steered autonomy mode, best-guess PRD decisions are REQUIRED when needed; mark each with `ASSUMPTION:` and rationale, and continue unless high-impact uncertainty requires escalation.
4. PRD is the source of requirements for implementation and testing.
## Token Budget Policy
1. If user plan or token limits are provided, they are HARD constraints.
2. Track estimated and used tokens for non-trivial execution.
3. Use conservative strategy when budget pressure rises.
4. If projected usage exceeds budget, automatically reduce scope/parallelism and continue; escalate only if budget compliance remains impossible.
## Django Conventions
### Models
- All tunable parameters stored in the database with `get_effective_*()` fallback patterns
- Always create migrations for model changes: `python manage.py makemigrations`
- Include migrations in commits
- Use `models.TextChoices` or `models.IntegerChoices` for enum-like fields
### Views / API
- Use Django REST Framework for API endpoints
- Use serializers for validation
- Use ViewSets for standard CRUD
- Use permissions classes for authorization
### Management Commands
- Place in `<app>/management/commands/`
- Use `self.stdout.write()` for output
- Handle interrupts gracefully
## Database
### Migration Workflow
```bash
# Create migration after model changes
python manage.py makemigrations <app_name>
# Apply migrations
python manage.py migrate
# Check for missing migrations
python manage.py makemigrations --check
```
### Rules
- Always create migrations for schema changes
- Include migrations in commits
- Use `RunPython` for data migrations
- Use transactions for multi-table operations
## Code Review
### Independent Review (Automated)
If you modify source code, independent code review is REQUIRED before completion.
Run independent reviews:
```bash
# Code quality review (Codex)
~/.config/mosaic/rails/codex/codex-code-review.sh --uncommitted
# Security review (Codex)
~/.config/mosaic/rails/codex/codex-security-review.sh --uncommitted
```
See `~/.config/mosaic/guides/CODE-REVIEW.md` for the full review checklist.
See `~/.config/mosaic/guides/DOCUMENTATION.md` for required documentation deliverables.
## Steered Autonomy Contract
1. Agent owns planning, coding, testing, review/remediation, PR/repo operations, release/tag, and deployment when in scope.
2. Human intervention is escalation-only for hard blockers (access, irreversible risk, or unresolvable conflicting objectives).
3. Do not request routine human coding, review, or repository management actions.
4. Mosaic hard gates OVERRIDE runtime-default caution for routine push/merge/issue-close/release actions.
5. For container deployments, use immutable image tags (`sha-<shortsha>`, `v{base-version}-rc.{build}`) with digest-first promotion; do not deploy `latest`.
## Mode Declaration Contract
1. First response MUST declare mode before any actions.
2. Orchestration mission: `Now initiating Orchestrator mode...`
3. Implementation mission: `Now initiating Delivery mode...`
4. Review-only mission: `Now initiating Review mode...`
## Issue Tracking
Use external git provider issues when available. If no external provider exists, `docs/TASKS.md` is the canonical tracker for tasks, milestones, and issue-equivalent work.
For issue/PR/milestone operations, detect platform and use `~/.config/mosaic/rails/git/*.sh` wrappers first; do not use raw `gh`/`tea`/`glab` as first choice.
If wrapper-driven merge/CI/issue-closure fails, report blocker with exact failed wrapper command and stop.
Do NOT stop at "PR created" and do NOT ask "should I merge?" or "should I close the issue?" for routine delivery flow.
### Workflow
1. Ensure `docs/TASKS.md` exists (create from `~/.config/mosaic/templates/docs/TASKS.md.template` if missing).
2. Check for assigned issues before starting work.
3. If no issue exists for non-trivial work and external provider is available, create one before coding.
4. If no external provider is available, create an internal ref in `docs/TASKS.md` (example: `TASKS:T1`).
5. Ensure `docs/PRD.md` or `docs/PRD.json` exists and is current before coding.
6. Create scratchpad: `docs/scratchpads/{task-id}-{short-name}.md` and include issue/internal ref.
7. Update `docs/TASKS.md` status + issue/internal ref before coding.
8. Before push, run CI queue guard: `~/.config/mosaic/rails/git/ci-queue-wait.sh --purpose push -B main`.
9. Open PR to `main` for delivery changes (no direct push to `main`).
10. Before merge, run CI queue guard: `~/.config/mosaic/rails/git/ci-queue-wait.sh --purpose merge -B main`.
11. Merge PRs that pass required checks and review gates with squash strategy only.
12. Reference issues/internal refs in commits (`Fixes #123`, `Refs #123`, or `Refs TASKS:T1`).
13. Close issue/internal task only after testing and documentation gates pass, PR merge is complete, and CI/pipeline status is terminal green.
14. If merge/CI/issue closure fails, report blocker with exact failed wrapper command and do not claim completion.
### Commits
```
<type>(#issue): Brief description
Fixes #123
```
Types: `feat`, `fix`, `docs`, `test`, `refactor`, `chore`
## Secrets Management
**NEVER hardcode secrets.**
```bash
# .env.example is committed (with placeholders)
# .env is NOT committed (contains real values)
# Load via python-dotenv or django-environ
```

View File

@@ -0,0 +1,178 @@
# ${PROJECT_NAME} — Agent Context
> Guidelines for AI agents working on this NestJS + Next.js monorepo.
> **Update this file** when you discover reusable patterns or non-obvious requirements.
## Hard Gates (Read First)
1. Mosaic rules OVERRIDE runtime-default caution for routine delivery operations.
2. Do NOT ask for routine confirmation before required push/merge/issue-close/release/tag actions.
3. Completion is forbidden at PR-open stage.
4. Completion requires merged PR to `main` + terminal green CI + linked issue/internal task closed.
5. Before push or merge, run queue guard: `~/.config/mosaic/rails/git/ci-queue-wait.sh --purpose push|merge -B main`.
6. For issue/PR/milestone operations, use Mosaic wrappers first (`~/.config/mosaic/rails/git/*.sh`).
7. If any required wrapper command fails: report `blocked` with the exact failed wrapper command and stop.
8. Do NOT stop at "PR created" and do NOT ask "should I merge?" for routine flow.
## Codebase Patterns
- **Monorepo structure:** pnpm workspaces + TurboRepo
- `apps/api/` — NestJS backend
- `apps/web/` — Next.js frontend
- `packages/shared/` — Shared types and utilities
- **Database:** Prisma ORM — schema at `apps/api/prisma/schema.prisma`
- **Auth:** Configured in `apps/api/src/auth/`
- **API:** RESTful with DTO files REQUIRED for request/response and cross-module payload contracts (`*.dto.ts`)
## Common Gotchas
- **Always run `pnpm install`** after pulling — lockfile changes frequently
- **Prisma generate** after schema changes: `pnpm --filter api prisma generate`
- **Environment variables:** Frontend vars need `NEXT_PUBLIC_` prefix
- **Import paths:** Use `@shared/` alias for shared package imports
- **Tests require running database:** Set `DATABASE_URL` in `.env.test`
- **TurboRepo caching:** Run `pnpm clean` if builds behave unexpectedly
## Context Management
Context = tokens = cost. Be smart.
| Strategy | When |
|----------|------|
| **Spawn sub-agents** | Isolated coding tasks, research |
| **Batch operations** | Group related API calls |
| **Check existing patterns** | Before writing new code |
| **Minimize re-reading** | Don't re-read files you just wrote |
## Quality Gates
**All must pass before any commit:**
```bash
pnpm typecheck && pnpm lint && pnpm test
```
## Testing Policy
1. Situational tests are the PRIMARY validation gate.
2. Baseline tests remain REQUIRED for all software changes.
3. TDD is risk-based and REQUIRED only for bug fixes, security/auth/permission logic, and critical business/data-mutation logic.
4. Reference `~/.config/mosaic/guides/QA-TESTING.md`.
## PRD Requirement
1. Before coding begins, `docs/PRD.md` or `docs/PRD.json` MUST exist.
2. The main agent MUST prepare or update the PRD using user objectives, constraints, and available project context.
3. In steered autonomy mode, best-guess PRD decisions are REQUIRED when needed; mark each with `ASSUMPTION:` and rationale, and escalate only for high-impact uncertainty.
4. Reference `~/.config/mosaic/guides/PRD.md`.
## Task Tracking Contract
1. For non-trivial implementation work, `docs/TASKS.md` MUST exist before coding.
2. If external git provider is available (Gitea/GitHub/GitLab), create/update issue(s) before coding and map them in `docs/TASKS.md`.
3. If no external provider is available, use internal refs in `docs/TASKS.md` (example: `TASKS:T1`).
4. Keep `docs/TASKS.md` status in sync with actual progress until completion.
5. For issue/PR/milestone actions, detect platform and use `~/.config/mosaic/rails/git/*.sh` wrappers first (no raw `gh`/`tea`/`glab` as first choice).
6. If wrapper-driven merge/CI/issue-closure fails, report blocker with the exact failed wrapper command and stop (do not claim completion).
## Documentation Contract
Documentation is a hard delivery gate.
If code/API/auth/infra changes, required documentation updates MUST be completed before task closure.
Keep `docs/` root clean and store reports/artifacts in scoped folders (`docs/reports/`, `docs/tasks/`, `docs/releases/`, `docs/scratchpads/`).
Reference:
- `~/.config/mosaic/guides/DOCUMENTATION.md`
- `~/.config/mosaic/templates/docs/DOCUMENTATION-CHECKLIST.md`
## Token Budget Policy
1. If user plan or token limits are provided, they are HARD constraints.
2. Track estimated and used tokens for non-trivial execution.
3. Shift to conservative strategy when budget pressure rises (smaller scope, fewer parallel actions, reduced re-reading).
4. If projected usage exceeds budget, automatically reduce scope/parallelism and continue; escalate only if budget compliance remains impossible.
## Merge Strategy (Hard Rule)
1. Create short-lived branches from `main`.
2. Open PRs to `main` for delivery changes.
3. Do not push directly to `main`.
4. Merge PRs to `main` with squash strategy only.
5. Do not mark implementation complete until PR is merged.
6. Do not mark implementation complete until CI/pipeline status is terminal green.
7. Close linked issues/tasks only after merge + green CI.
8. Before push or merge, run CI queue guard: `~/.config/mosaic/rails/git/ci-queue-wait.sh --purpose push|merge -B main`.
## Container Release Strategy (When Applicable)
1. Use immutable image tags: `sha-<shortsha>` and `v{base-version}-rc.{build}`.
2. Use mutable environment tags only as pointers (`testing`, optional `staging`, `prod`).
3. Deploy/promote by immutable digest; do not deploy by mutable tag alone.
4. Do not use `latest` or `dev` as deployment references.
5. Use blue-green by default; use canary only with automated metrics and rollback gates.
## Steered Autonomy Contract
1. Agent owns end-to-end delivery: plan, code, test, review, remediate, commit, push, PR/repo operations, release/tag, and deployment when in scope.
2. Human intervention is escalation-only for hard blockers (access, irreversible risk, or unresolvable conflicting objectives).
3. Code review is agent-executed and REQUIRED for any source-code change.
## Mode Declaration Contract
1. First response MUST declare mode before any actions.
2. Orchestration mission: `Now initiating Orchestrator mode...`
3. Implementation mission: `Now initiating Delivery mode...`
4. Review-only mission: `Now initiating Review mode...`
## Orchestrator Integration
### Task Prefix
Use `${TASK_PREFIX}` for orchestrated tasks (e.g., `${TASK_PREFIX}-SEC-001`).
### Worker Checklist
1. Read `docs/PRD.md` or `docs/PRD.json`
2. Read the finding details from the report
3. Implement the fix following existing patterns
4. Run quality gates (ALL must pass)
5. Complete required documentation updates (if applicable)
6. Commit: `git commit -m "fix({finding_id}): brief description"`
7. Push: `git push origin {branch}`
8. Report result as JSON
### Post-Coding Review
After implementing changes, code review is REQUIRED for any source-code modification.
For orchestrated tasks, the orchestrator will run:
1. **Codex code review** — `~/.config/mosaic/rails/codex/codex-code-review.sh --uncommitted`
2. **Codex security review** — `~/.config/mosaic/rails/codex/codex-security-review.sh --uncommitted`
3. If blockers/critical findings: remediation task created
4. If clean: task marked done
## Workflow (Non-Negotiable)
```
1. Branch → git checkout -b feature/XX-description
2. Code → Implement with required tests; use TDD where required by policy
3. Test → pnpm test (must pass)
4. Push → git push origin feature/XX-description
5. PR → Create PR to main
6. Review → Wait for approval or self-merge if authorized using squash only
7. Close → Close related issues
```
**Never push directly to main. Always use a PR to main.**
## Key Files
| File | Purpose |
|------|---------|
| `CLAUDE.md` | Project overview and conventions |
| `apps/api/prisma/schema.prisma` | Database schema |
| `apps/api/src/` | Backend source |
| `apps/web/app/` | Frontend pages |
| `packages/shared/` | Shared types |
| `.env.example` | Required environment variables |
---
_Model-agnostic. Works for Claude, Codex, GPT, Llama, etc._

View File

@@ -0,0 +1,258 @@
# ${PROJECT_NAME} — Claude Code Instructions
> **${PROJECT_DESCRIPTION}**
## Conditional Documentation Loading
| When working on... | Load this guide |
|---|---|
| Bootstrapping this project | `~/.config/mosaic/guides/BOOTSTRAP.md` |
| PRD creation and requirements definition | `~/.config/mosaic/guides/PRD.md` |
| Orchestrating autonomous tasks | `~/.config/mosaic/guides/ORCHESTRATOR.md` |
| Frontend development | `~/.config/mosaic/guides/FRONTEND.md` |
| Backend/API development | `~/.config/mosaic/guides/BACKEND.md` |
| Code review | `~/.config/mosaic/guides/CODE-REVIEW.md` |
| Documentation updates and standards | `~/.config/mosaic/guides/DOCUMENTATION.md` |
| TypeScript strict typing | `~/.config/mosaic/guides/TYPESCRIPT.md` |
| Authentication/Authorization | `~/.config/mosaic/guides/AUTHENTICATION.md` |
| QA/Testing | `~/.config/mosaic/guides/QA-TESTING.md` |
## Technology Stack
| Layer | Technology |
|-------|------------|
| **Frontend** | Next.js + React + TailwindCSS + Shadcn/ui |
| **Backend** | NestJS + Prisma ORM |
| **Database** | PostgreSQL |
| **Testing** | Vitest + Playwright |
| **Monorepo** | pnpm workspaces + TurboRepo |
| **Deployment** | Docker + docker-compose |
## Repository Structure
```
${PROJECT_DIR}/
├── CLAUDE.md # This file
├── AGENTS.md # Agent-specific patterns and gotchas
├── apps/
│ ├── api/ # NestJS backend
│ │ ├── src/
│ │ ├── prisma/
│ │ │ └── schema.prisma
│ │ └── Dockerfile
│ └── web/ # Next.js frontend
│ ├── app/
│ ├── components/
│ └── Dockerfile
├── packages/
│ ├── shared/ # Shared types, utilities
│ ├── ui/ # Shared UI components
│ └── config/ # Shared configuration
├── docs/
│ ├── PRD.md # Requirements source (or PRD.json)
│ ├── scratchpads/ # Per-issue working documents
│ └── templates/ # Project templates
├── tests/ # Integration/E2E tests
├── docker/ # Docker configuration
├── .env.example
├── turbo.json
├── pnpm-workspace.yaml
└── README.md
```
## Development Workflow
### Branch Strategy
- `main` — Protected delivery branch
- `feature/*` / `fix/*` — Short-lived task branches created from `main`
- All changes merge through PR into `main` only
- Merge strategy for `main` PRs is squash-only
### Starting Work
```bash
git checkout main
git pull --rebase origin main
pnpm install
```
### Building
```bash
pnpm build # Build all packages
pnpm --filter api build # Build API only
pnpm --filter web build # Build web only
```
### Testing
```bash
pnpm test # Run all tests
pnpm test:unit # Unit tests (Vitest)
pnpm test:e2e # E2E tests (Playwright)
pnpm test:coverage # Coverage report
```
### Linting & Type Checking
```bash
pnpm lint # ESLint
pnpm typecheck # TypeScript type checking
pnpm format # Prettier formatting
```
## Quality Gates
**All must pass before committing:**
```bash
pnpm typecheck && pnpm lint && pnpm test
```
## Testing Policy
1. Situational tests are the PRIMARY validation gate.
2. Baseline tests are REQUIRED for all software changes.
3. TDD is risk-based; required cases are defined in `~/.config/mosaic/guides/QA-TESTING.md`.
## PRD Requirement
1. Before coding begins, `docs/PRD.md` or `docs/PRD.json` MUST exist.
2. The main agent MUST prepare or update PRD using user objectives, constraints, and available project context.
3. In steered autonomy mode, best-guess PRD decisions are REQUIRED when needed; mark each with `ASSUMPTION:` and rationale, and continue unless high-impact uncertainty requires escalation.
4. PRD is the source of requirements for implementation and testing.
## Token Budget Policy
1. If user plan or token limits are provided, they are HARD constraints.
2. Track estimated and used tokens for non-trivial execution.
3. Use conservative strategy when budget pressure rises.
4. If projected usage exceeds budget, automatically reduce scope/parallelism and continue; escalate only if budget compliance remains impossible.
## API Conventions
### NestJS Patterns
- Controllers handle HTTP, Services handle business logic
- DTO files are REQUIRED at module/API boundaries (`*.dto.ts`)
- Use DTOs with `class-validator` for request validation
- Use Guards for authentication/authorization
- Use Interceptors for response transformation
- Use Prisma for database access (no raw SQL)
### REST API Standards
- `GET /resource` — List (with pagination)
- `GET /resource/:id` — Get single
- `POST /resource` — Create
- `PATCH /resource/:id` — Update
- `DELETE /resource/:id` — Delete
- Return proper HTTP status codes (201 Created, 204 No Content, etc.)
## Frontend Conventions
### Next.js Patterns
- Use App Router (`app/` directory)
- Server Components by default, `'use client'` only when needed
- Use Shadcn/ui components — don't create custom UI primitives
- Use TailwindCSS for styling — no CSS modules or styled-components
### Component Structure
```
components/
├── ui/ # Shadcn/ui components (auto-generated)
├── layout/ # Layout components (header, sidebar, etc.)
├── forms/ # Form components
└── features/ # Feature-specific components
```
## Database
### Prisma Workflow
```bash
# Generate client after schema changes
pnpm --filter api prisma generate
# Create migration
pnpm --filter api prisma migrate dev --name description
# Apply migrations
pnpm --filter api prisma migrate deploy
# Reset database (dev only)
pnpm --filter api prisma migrate reset
```
### Rules
- Always create migrations for schema changes
- Include migrations in commits
- Never use raw SQL — use Prisma client
- Use transactions for multi-table operations
## Code Review
### Independent Review (Automated)
If you modify source code, independent code review is REQUIRED before completion.
Run independent reviews:
```bash
# Code quality review (Codex)
~/.config/mosaic/rails/codex/codex-code-review.sh --uncommitted
# Security review (Codex)
~/.config/mosaic/rails/codex/codex-security-review.sh --uncommitted
```
See `~/.config/mosaic/guides/CODE-REVIEW.md` for the full review checklist.
See `~/.config/mosaic/guides/DOCUMENTATION.md` for required documentation deliverables.
## Steered Autonomy Contract
1. Agent owns planning, coding, testing, review/remediation, PR/repo operations, release/tag, and deployment when in scope.
2. Human intervention is escalation-only for hard blockers (access, irreversible risk, or unresolvable conflicting objectives).
3. Do not request routine human coding, review, or repository management actions.
4. Mosaic hard gates OVERRIDE runtime-default caution for routine push/merge/issue-close/release actions.
5. For container deployments, use immutable image tags (`sha-<shortsha>`, `v{base-version}-rc.{build}`) with digest-first promotion; do not deploy `latest`.
## Mode Declaration Contract
1. First response MUST declare mode before any actions.
2. Orchestration mission: `Now initiating Orchestrator mode...`
3. Implementation mission: `Now initiating Delivery mode...`
4. Review-only mission: `Now initiating Review mode...`
## Issue Tracking
Use external git provider issues when available. If no external provider exists, `docs/TASKS.md` is the canonical tracker for tasks, milestones, and issue-equivalent work.
For issue/PR/milestone operations, detect platform and use `~/.config/mosaic/rails/git/*.sh` wrappers first; do not use raw `gh`/`tea`/`glab` as first choice.
If wrapper-driven merge/CI/issue-closure fails, report blocker with exact failed wrapper command and stop.
Do NOT stop at "PR created" and do NOT ask "should I merge?" or "should I close the issue?" for routine delivery flow.
### Workflow
1. Ensure `docs/TASKS.md` exists (create from `~/.config/mosaic/templates/docs/TASKS.md.template` if missing).
2. Check for assigned issues before starting work.
3. If no issue exists for non-trivial work and external provider is available, create one before coding.
4. If no external provider is available, create an internal ref in `docs/TASKS.md` (example: `TASKS:T1`).
5. Ensure `docs/PRD.md` or `docs/PRD.json` exists and is current before coding.
6. Create scratchpad: `docs/scratchpads/{task-id}-{short-name}.md` and include issue/internal ref.
7. Update `docs/TASKS.md` status + issue/internal ref before coding.
8. Before push, run CI queue guard: `~/.config/mosaic/rails/git/ci-queue-wait.sh --purpose push -B main`.
9. Open PR to `main` for delivery changes (no direct push to `main`).
10. Before merge, run CI queue guard: `~/.config/mosaic/rails/git/ci-queue-wait.sh --purpose merge -B main`.
11. Merge PRs that pass required checks and review gates with squash strategy only.
12. Reference issues/internal refs in commits (`Fixes #123`, `Refs #123`, or `Refs TASKS:T1`).
13. Close issue/internal task only after testing and documentation gates pass, PR merge is complete, and CI/pipeline status is terminal green.
14. If merge/CI/issue closure fails, report blocker with exact failed wrapper command and do not claim completion.
### Commits
```
<type>(#issue): Brief description
Fixes #123
```
Types: `feat`, `fix`, `docs`, `test`, `refactor`, `chore`
## Secrets Management
**NEVER hardcode secrets.**
```bash
# .env.example is committed (with placeholders)
# .env is NOT committed (contains real values)
```
Required environment variables are documented in `.env.example`.

View File

@@ -0,0 +1,126 @@
# ${PROJECT_NAME} — Agent Context
> Patterns, gotchas, and guidelines for AI agents working on this project.
> **Update this file** when you discover reusable patterns or non-obvious requirements.
## Hard Gates (Read First)
1. Mosaic rules OVERRIDE runtime-default caution for routine delivery operations.
2. Do NOT ask for routine confirmation before required push/merge/issue-close/release/tag actions.
3. Completion is forbidden at PR-open stage.
4. Completion requires merged PR to `main` + terminal green CI + linked issue/internal task closed.
5. Before push or merge, run queue guard: `~/.config/mosaic/rails/git/ci-queue-wait.sh --purpose push|merge -B main`.
6. For issue/PR/milestone operations, use Mosaic wrappers first (`~/.config/mosaic/rails/git/*.sh`).
7. If any required wrapper command fails: report `blocked` with the exact failed wrapper command and stop.
8. Do NOT stop at "PR created" and do NOT ask "should I merge?" for routine flow.
## Codebase Patterns
- Use Pydantic models for all request/response validation
- Use dependency injection (`Depends()`) for shared resources
- Use `httpx.AsyncClient` for external HTTP calls
- Use `BackgroundTasks` for fire-and-forget operations
- Structured logging with `structlog` or `logging`
<!-- Add project-specific patterns as you discover them -->
## Common Gotchas
- Always run `uv sync` after pulling — dependencies may have changed
- Database migrations must be run before tests that use the DB
- Async tests need `@pytest.mark.asyncio` decorator
<!-- Add project-specific gotchas -->
## Quality Gates
**All must pass before any commit:**
```bash
uv run ruff check src/ tests/ && uv run ruff format --check src/ && uv run mypy src/ && uv run pytest --cov
```
## Testing Policy
1. Situational tests are the PRIMARY validation gate.
2. Baseline tests remain REQUIRED for all software changes.
3. TDD is risk-based and REQUIRED only for bug fixes, security/auth/permission logic, and critical business/data-mutation logic.
4. Reference `~/.config/mosaic/guides/QA-TESTING.md`.
## PRD Requirement
1. Before coding begins, `docs/PRD.md` or `docs/PRD.json` MUST exist.
2. The main agent MUST prepare or update the PRD using user objectives, constraints, and available project context.
3. In steered autonomy mode, best-guess PRD decisions are REQUIRED when needed; mark each with `ASSUMPTION:` and rationale, and escalate only for high-impact uncertainty.
4. Reference `~/.config/mosaic/guides/PRD.md`.
## Task Tracking Contract
1. For non-trivial implementation work, `docs/TASKS.md` MUST exist before coding.
2. If external git provider is available (Gitea/GitHub/GitLab), create/update issue(s) before coding and map them in `docs/TASKS.md`.
3. If no external provider is available, use internal refs in `docs/TASKS.md` (example: `TASKS:T1`).
4. Keep `docs/TASKS.md` status in sync with actual progress until completion.
5. For issue/PR/milestone actions, detect platform and use `~/.config/mosaic/rails/git/*.sh` wrappers first (no raw `gh`/`tea`/`glab` as first choice).
6. If wrapper-driven merge/CI/issue-closure fails, report blocker with the exact failed wrapper command and stop (do not claim completion).
## Documentation Contract
Documentation is a hard delivery gate.
If code/API/auth/infra changes, required documentation updates MUST be completed before task closure.
Keep `docs/` root clean and store reports/artifacts in scoped folders (`docs/reports/`, `docs/tasks/`, `docs/releases/`, `docs/scratchpads/`).
Reference:
- `~/.config/mosaic/guides/DOCUMENTATION.md`
- `~/.config/mosaic/templates/docs/DOCUMENTATION-CHECKLIST.md`
## Token Budget Policy
1. If user plan or token limits are provided, they are HARD constraints.
2. Track estimated and used tokens for non-trivial execution.
3. Shift to conservative strategy when budget pressure rises (smaller scope, fewer parallel actions, reduced re-reading).
4. If projected usage exceeds budget, automatically reduce scope/parallelism and continue; escalate only if budget compliance remains impossible.
## Merge Strategy (Hard Rule)
1. Create short-lived branches from `main`.
2. Open PRs to `main` for delivery changes.
3. Do not push directly to `main`.
4. Merge PRs to `main` with squash strategy only.
5. Do not mark implementation complete until PR is merged.
6. Do not mark implementation complete until CI/pipeline status is terminal green.
7. Close linked issues/tasks only after merge + green CI.
8. Before push or merge, run CI queue guard: `~/.config/mosaic/rails/git/ci-queue-wait.sh --purpose push|merge -B main`.
## Container Release Strategy (When Applicable)
1. Use immutable image tags: `sha-<shortsha>` and `v{base-version}-rc.{build}`.
2. Use mutable environment tags only as pointers (`testing`, optional `staging`, `prod`).
3. Deploy/promote by immutable digest; do not deploy by mutable tag alone.
4. Do not use `latest` or `dev` as deployment references.
5. Use blue-green by default; use canary only with automated metrics and rollback gates.
## Steered Autonomy Contract
1. Agent owns end-to-end delivery: plan, code, test, review, remediate, commit, push, PR/repo operations, release/tag, and deployment when in scope.
2. Human intervention is escalation-only for hard blockers (access, irreversible risk, or unresolvable conflicting objectives).
3. Code review is agent-executed and REQUIRED for any source-code change.
## Mode Declaration Contract
1. First response MUST declare mode before any actions.
2. Orchestration mission: `Now initiating Orchestrator mode...`
3. Implementation mission: `Now initiating Delivery mode...`
4. Review-only mission: `Now initiating Review mode...`
## Key Files
| File | Purpose |
|------|---------|
| `pyproject.toml` | Project configuration, dependencies |
| `src/${PROJECT_SLUG}/main.py` | Application entry point |
<!-- Add project-specific key files -->
## Testing Approaches
- Unit tests: pytest with fixtures in `conftest.py`
- API tests: `httpx.AsyncClient` with `TestClient`
- Coverage minimum: 85%
<!-- Document project-specific testing patterns -->

View File

@@ -0,0 +1,195 @@
# ${PROJECT_NAME} — Claude Code Instructions
> **Project:** ${PROJECT_DESCRIPTION}
> **Repository:** ${REPO_URL}
## Conditional Documentation Loading
**Read the relevant guide before starting work:**
| Task Type | Guide |
|-----------|-------|
| End-to-end implementation and validation | `~/.config/mosaic/guides/E2E-DELIVERY.md` |
| PRD creation and requirements definition | `~/.config/mosaic/guides/PRD.md` |
| Bootstrapping this project | `~/.config/mosaic/guides/BOOTSTRAP.md` |
| Orchestrating autonomous tasks | `~/.config/mosaic/guides/ORCHESTRATOR.md` |
| Backend/API development | `~/.config/mosaic/guides/BACKEND.md` |
| Authentication/Authorization | `~/.config/mosaic/guides/AUTHENTICATION.md` |
| Code review | `~/.config/mosaic/guides/CODE-REVIEW.md` |
| Documentation updates and standards | `~/.config/mosaic/guides/DOCUMENTATION.md` |
| QA/Testing | `~/.config/mosaic/guides/QA-TESTING.md` |
| Infrastructure/DevOps | `~/.config/mosaic/guides/INFRASTRUCTURE.md` |
| Secrets management (Vault) | `~/.config/mosaic/guides/VAULT-SECRETS.md` |
## Technology Stack
| Layer | Technology |
|-------|------------|
| **Backend** | FastAPI |
| **Language** | Python 3.11+ |
| **Database** | ${DATABASE_STACK} |
| **Testing** | pytest + httpx |
| **Linting** | ruff |
| **Type Checking** | mypy (strict) |
| **Security** | bandit + pip-audit |
| **Package Manager** | uv |
| **Deployment** | ${DEPLOYMENT_STACK} |
## Repository Structure
```
${PROJECT_DIR}/
├── CLAUDE.md # This file
├── AGENTS.md # Agent-specific patterns and gotchas
├── src/ # Source code
│ └── ${PROJECT_SLUG}/ # Main package
├── tests/ # Test files
├── docs/
│ ├── PRD.md # Requirements source (or PRD.json)
│ └── scratchpads/ # Per-issue working documents
├── pyproject.toml # Project configuration
└── .env.example # Environment template
```
## Development Workflow
### Setup
```bash
uv sync --all-extras
```
### Running
```bash
uv run uvicorn ${PROJECT_SLUG}.main:app --reload --port 8000
```
### Testing
```bash
uv run pytest # Run all tests
uv run pytest --cov # With coverage (85% min)
```
### Linting & Type Checking
```bash
uv run ruff check src/ tests/ # Lint
uv run ruff format --check src/ # Format check
uv run mypy src/ # Type check
```
### Security
```bash
uv run bandit -r src/ # SAST scanning
uv run pip-audit # Dependency vulnerabilities
```
## Quality Gates
**All must pass before committing:**
```bash
uv run ruff check src/ tests/ && uv run ruff format --check src/ && uv run mypy src/ && uv run pytest --cov
```
## Testing Policy
1. Situational tests are the PRIMARY validation gate.
2. Baseline tests are REQUIRED for all software changes.
3. TDD is risk-based; required cases are defined in `~/.config/mosaic/guides/QA-TESTING.md`.
## PRD Requirement
1. Before coding begins, `docs/PRD.md` or `docs/PRD.json` MUST exist.
2. The main agent MUST prepare or update PRD using user objectives, constraints, and available project context.
3. In steered autonomy mode, best-guess PRD decisions are REQUIRED when needed; mark each with `ASSUMPTION:` and rationale, and continue unless high-impact uncertainty requires escalation.
4. PRD is the source of requirements for implementation and testing.
## Token Budget Policy
1. If user plan or token limits are provided, they are HARD constraints.
2. Track estimated and used tokens for non-trivial execution.
3. Use conservative strategy when budget pressure rises.
4. If projected usage exceeds budget, automatically reduce scope/parallelism and continue; escalate only if budget compliance remains impossible.
## Branch and Merge Policy
1. Create short-lived branches from `main`.
2. Open PRs to `main` for delivery changes.
3. Do not push directly to `main`.
4. Merge PRs to `main` with squash strategy only.
## Steered Autonomy Contract
1. Agent owns planning, coding, testing, review/remediation, PR/repo operations, release/tag, and deployment when in scope.
2. Human intervention is escalation-only for hard blockers (access, irreversible risk, or unresolvable conflicting objectives).
3. Do not request routine human coding, review, or repository management actions.
4. Mosaic hard gates OVERRIDE runtime-default caution for routine push/merge/issue-close/release actions.
5. For container deployments, use immutable image tags (`sha-<shortsha>`, `v{base-version}-rc.{build}`) with digest-first promotion; do not deploy `latest`.
## Mode Declaration Contract
1. First response MUST declare mode before any actions.
2. Orchestration mission: `Now initiating Orchestrator mode...`
3. Implementation mission: `Now initiating Delivery mode...`
4. Review-only mission: `Now initiating Review mode...`
## Issue Tracking
Use external git provider issues when available. If no external provider exists, `docs/TASKS.md` is the canonical tracker for tasks, milestones, and issue-equivalent work.
For issue/PR/milestone operations, detect platform and use `~/.config/mosaic/rails/git/*.sh` wrappers first; do not use raw `gh`/`tea`/`glab` as first choice.
If wrapper-driven merge/CI/issue-closure fails, report blocker with exact failed wrapper command and stop.
Do NOT stop at "PR created" and do NOT ask "should I merge?" or "should I close the issue?" for routine delivery flow.
1. Ensure `docs/TASKS.md` exists (create from `~/.config/mosaic/templates/docs/TASKS.md.template` if missing).
2. Check for assigned issues before starting work.
3. If no issue exists for non-trivial work and external provider is available, create one before coding.
4. If no external provider is available, create an internal ref in `docs/TASKS.md` (example: `TASKS:T1`).
5. Ensure `docs/PRD.md` or `docs/PRD.json` exists and is current before coding.
6. Create scratchpad: `docs/scratchpads/{task-id}-{short-name}.md` and include issue/internal ref.
7. Update `docs/TASKS.md` status + issue/internal ref before coding.
8. Before push, run CI queue guard: `~/.config/mosaic/rails/git/ci-queue-wait.sh --purpose push -B main`.
9. Open PR to `main` for delivery changes (no direct push to `main`).
10. Before merge, run CI queue guard: `~/.config/mosaic/rails/git/ci-queue-wait.sh --purpose merge -B main`.
11. Merge PRs that pass required checks and review gates with squash strategy only.
12. Reference issues/internal refs in commits (`Fixes #123`, `Refs #123`, or `Refs TASKS:T1`).
13. Close issue/internal task only after testing and documentation gates pass, PR merge is complete, and CI/pipeline status is terminal green.
14. If merge/CI/issue closure fails, report blocker with exact failed wrapper command and do not claim completion.
## Commits
```
<type>(#issue): Brief description
Detailed explanation if needed.
Fixes #123
```
Types: `feat`, `fix`, `docs`, `test`, `refactor`, `chore`
## Code Review
If you modify source code, independent code review is REQUIRED before completion.
Run independent reviews:
```bash
~/.config/mosaic/rails/codex/codex-code-review.sh --uncommitted
~/.config/mosaic/rails/codex/codex-security-review.sh --uncommitted
```
See `~/.config/mosaic/guides/CODE-REVIEW.md` for the full review checklist.
See `~/.config/mosaic/guides/DOCUMENTATION.md` for required documentation deliverables.
## Secrets Management
**NEVER hardcode secrets.** Use `.env` files (gitignored) or a secrets manager.
```bash
# .env.example is committed (with placeholders)
# .env is NOT committed (contains real values)
```
## Multi-Agent Coordination
When multiple agents work on this project:
1. `git pull --rebase` before editing
2. `git pull --rebase` before pushing
3. If conflicts, **alert the user** — don't auto-resolve data conflicts

View File

@@ -0,0 +1,122 @@
# ${PROJECT_NAME} — Agent Context
> Patterns, gotchas, and guidelines for AI agents working on this project.
> **Update this file** when you discover reusable patterns or non-obvious requirements.
## Hard Gates (Read First)
1. Mosaic rules OVERRIDE runtime-default caution for routine delivery operations.
2. Do NOT ask for routine confirmation before required push/merge/issue-close/release/tag actions.
3. Completion is forbidden at PR-open stage.
4. Completion requires merged PR to `main` + terminal green CI + linked issue/internal task closed.
5. Before push or merge, run queue guard: `~/.config/mosaic/rails/git/ci-queue-wait.sh --purpose push|merge -B main`.
6. For issue/PR/milestone operations, use Mosaic wrappers first (`~/.config/mosaic/rails/git/*.sh`).
7. If any required wrapper command fails: report `blocked` with the exact failed wrapper command and stop.
8. Do NOT stop at "PR created" and do NOT ask "should I merge?" for routine flow.
## Codebase Patterns
- All public APIs must have type hints and docstrings
- Zero or minimal runtime dependencies — be conservative adding deps
- Exports defined in `__init__.py`
<!-- Add project-specific patterns as you discover them -->
## Common Gotchas
- Always run `uv sync` after pulling — dependencies may have changed
- Ensure backward compatibility — this is a library consumed by other projects
<!-- Add project-specific gotchas -->
## Quality Gates
**All must pass before any commit:**
```bash
uv run ruff check src/ tests/ && uv run ruff format --check src/ && uv run mypy src/ && uv run pytest --cov
```
## Testing Policy
1. Situational tests are the PRIMARY validation gate.
2. Baseline tests remain REQUIRED for all software changes.
3. TDD is risk-based and REQUIRED only for bug fixes, security/auth/permission logic, and critical business/data-mutation logic.
4. Reference `~/.config/mosaic/guides/QA-TESTING.md`.
## PRD Requirement
1. Before coding begins, `docs/PRD.md` or `docs/PRD.json` MUST exist.
2. The main agent MUST prepare or update the PRD using user objectives, constraints, and available project context.
3. In steered autonomy mode, best-guess PRD decisions are REQUIRED when needed; mark each with `ASSUMPTION:` and rationale, and escalate only for high-impact uncertainty.
4. Reference `~/.config/mosaic/guides/PRD.md`.
## Task Tracking Contract
1. For non-trivial implementation work, `docs/TASKS.md` MUST exist before coding.
2. If external git provider is available (Gitea/GitHub/GitLab), create/update issue(s) before coding and map them in `docs/TASKS.md`.
3. If no external provider is available, use internal refs in `docs/TASKS.md` (example: `TASKS:T1`).
4. Keep `docs/TASKS.md` status in sync with actual progress until completion.
5. For issue/PR/milestone actions, detect platform and use `~/.config/mosaic/rails/git/*.sh` wrappers first (no raw `gh`/`tea`/`glab` as first choice).
6. If wrapper-driven merge/CI/issue-closure fails, report blocker with the exact failed wrapper command and stop (do not claim completion).
## Documentation Contract
Documentation is a hard delivery gate.
If code/API/auth/infra changes, required documentation updates MUST be completed before task closure.
Keep `docs/` root clean and store reports/artifacts in scoped folders (`docs/reports/`, `docs/tasks/`, `docs/releases/`, `docs/scratchpads/`).
Reference:
- `~/.config/mosaic/guides/DOCUMENTATION.md`
- `~/.config/mosaic/templates/docs/DOCUMENTATION-CHECKLIST.md`
## Token Budget Policy
1. If user plan or token limits are provided, they are HARD constraints.
2. Track estimated and used tokens for non-trivial execution.
3. Shift to conservative strategy when budget pressure rises (smaller scope, fewer parallel actions, reduced re-reading).
4. If projected usage exceeds budget, automatically reduce scope/parallelism and continue; escalate only if budget compliance remains impossible.
## Merge Strategy (Hard Rule)
1. Create short-lived branches from `main`.
2. Open PRs to `main` for delivery changes.
3. Do not push directly to `main`.
4. Merge PRs to `main` with squash strategy only.
5. Do not mark implementation complete until PR is merged.
6. Do not mark implementation complete until CI/pipeline status is terminal green.
7. Close linked issues/tasks only after merge + green CI.
8. Before push or merge, run CI queue guard: `~/.config/mosaic/rails/git/ci-queue-wait.sh --purpose push|merge -B main`.
## Container Release Strategy (When Applicable)
1. Use immutable image tags: `sha-<shortsha>` and `v{base-version}-rc.{build}`.
2. Use mutable environment tags only as pointers (`testing`, optional `staging`, `prod`).
3. Deploy/promote by immutable digest; do not deploy by mutable tag alone.
4. Do not use `latest` or `dev` as deployment references.
5. Use blue-green by default; use canary only with automated metrics and rollback gates.
## Steered Autonomy Contract
1. Agent owns end-to-end delivery: plan, code, test, review, remediate, commit, push, PR/repo operations, release/tag, and deployment when in scope.
2. Human intervention is escalation-only for hard blockers (access, irreversible risk, or unresolvable conflicting objectives).
3. Code review is agent-executed and REQUIRED for any source-code change.
## Mode Declaration Contract
1. First response MUST declare mode before any actions.
2. Orchestration mission: `Now initiating Orchestrator mode...`
3. Implementation mission: `Now initiating Delivery mode...`
4. Review-only mission: `Now initiating Review mode...`
## Key Files
| File | Purpose |
|------|---------|
| `pyproject.toml` | Project configuration, dependencies, build |
| `src/${PROJECT_SLUG}/__init__.py` | Public API exports |
<!-- Add project-specific key files -->
## Testing Approaches
- Unit tests: pytest with fixtures in `conftest.py`
- Coverage minimum: 85%
<!-- Document project-specific testing patterns -->

View File

@@ -0,0 +1,180 @@
# ${PROJECT_NAME} — Claude Code Instructions
> **Project:** ${PROJECT_DESCRIPTION}
> **Repository:** ${REPO_URL}
## Conditional Documentation Loading
**Read the relevant guide before starting work:**
| Task Type | Guide |
|-----------|-------|
| End-to-end implementation and validation | `~/.config/mosaic/guides/E2E-DELIVERY.md` |
| PRD creation and requirements definition | `~/.config/mosaic/guides/PRD.md` |
| Bootstrapping this project | `~/.config/mosaic/guides/BOOTSTRAP.md` |
| Orchestrating autonomous tasks | `~/.config/mosaic/guides/ORCHESTRATOR.md` |
| Backend/API development | `~/.config/mosaic/guides/BACKEND.md` |
| Code review | `~/.config/mosaic/guides/CODE-REVIEW.md` |
| Documentation updates and standards | `~/.config/mosaic/guides/DOCUMENTATION.md` |
| QA/Testing | `~/.config/mosaic/guides/QA-TESTING.md` |
## Technology Stack
| Layer | Technology |
|-------|------------|
| **Language** | Python 3.11+ |
| **Testing** | pytest |
| **Linting** | ruff |
| **Type Checking** | mypy (strict) |
| **Package Manager** | uv |
| **Build** | ${BUILD_SYSTEM} |
## Repository Structure
```
${PROJECT_DIR}/
├── CLAUDE.md # This file
├── AGENTS.md # Agent-specific patterns and gotchas
├── src/
│ └── ${PROJECT_SLUG}/ # Main package
├── tests/ # Test files
├── docs/
│ ├── PRD.md # Requirements source (or PRD.json)
│ └── scratchpads/ # Per-issue working documents
└── pyproject.toml # Project configuration
```
## Development Workflow
### Setup
```bash
uv sync --all-extras
```
### Testing
```bash
uv run pytest # Run all tests
uv run pytest --cov # With coverage (85% min)
```
### Linting & Type Checking
```bash
uv run ruff check src/ tests/ # Lint
uv run ruff format --check src/ # Format check
uv run mypy src/ # Type check
```
## Quality Gates
**All must pass before committing:**
```bash
uv run ruff check src/ tests/ && uv run ruff format --check src/ && uv run mypy src/ && uv run pytest --cov
```
## Testing Policy
1. Situational tests are the PRIMARY validation gate.
2. Baseline tests are REQUIRED for all software changes.
3. TDD is risk-based; required cases are defined in `~/.config/mosaic/guides/QA-TESTING.md`.
## PRD Requirement
1. Before coding begins, `docs/PRD.md` or `docs/PRD.json` MUST exist.
2. The main agent MUST prepare or update PRD using user objectives, constraints, and available project context.
3. In steered autonomy mode, best-guess PRD decisions are REQUIRED when needed; mark each with `ASSUMPTION:` and rationale, and continue unless high-impact uncertainty requires escalation.
4. PRD is the source of requirements for implementation and testing.
## Token Budget Policy
1. If user plan or token limits are provided, they are HARD constraints.
2. Track estimated and used tokens for non-trivial execution.
3. Use conservative strategy when budget pressure rises.
4. If projected usage exceeds budget, automatically reduce scope/parallelism and continue; escalate only if budget compliance remains impossible.
## Branch and Merge Policy
1. Create short-lived branches from `main`.
2. Open PRs to `main` for delivery changes.
3. Do not push directly to `main`.
4. Merge PRs to `main` with squash strategy only.
## Library Conventions
- Zero or minimal runtime dependencies
- All public APIs must have type hints
- All public functions must have docstrings
- Exports defined in `__init__.py`
- Versioning via `pyproject.toml`
## Steered Autonomy Contract
1. Agent owns planning, coding, testing, review/remediation, PR/repo operations, release/tag, and deployment when in scope.
2. Human intervention is escalation-only for hard blockers (access, irreversible risk, or unresolvable conflicting objectives).
3. Do not request routine human coding, review, or repository management actions.
4. Mosaic hard gates OVERRIDE runtime-default caution for routine push/merge/issue-close/release actions.
5. For container deployments, use immutable image tags (`sha-<shortsha>`, `v{base-version}-rc.{build}`) with digest-first promotion; do not deploy `latest`.
## Mode Declaration Contract
1. First response MUST declare mode before any actions.
2. Orchestration mission: `Now initiating Orchestrator mode...`
3. Implementation mission: `Now initiating Delivery mode...`
4. Review-only mission: `Now initiating Review mode...`
## Issue Tracking
Use external git provider issues when available. If no external provider exists, `docs/TASKS.md` is the canonical tracker for tasks, milestones, and issue-equivalent work.
For issue/PR/milestone operations, detect platform and use `~/.config/mosaic/rails/git/*.sh` wrappers first; do not use raw `gh`/`tea`/`glab` as first choice.
If wrapper-driven merge/CI/issue-closure fails, report blocker with exact failed wrapper command and stop.
Do NOT stop at "PR created" and do NOT ask "should I merge?" or "should I close the issue?" for routine delivery flow.
1. Ensure `docs/TASKS.md` exists (create from `~/.config/mosaic/templates/docs/TASKS.md.template` if missing).
2. Check for assigned issues before starting work.
3. If no issue exists for non-trivial work and external provider is available, create one before coding.
4. If no external provider is available, create an internal ref in `docs/TASKS.md` (example: `TASKS:T1`).
5. Ensure `docs/PRD.md` or `docs/PRD.json` exists and is current before coding.
6. Create scratchpad: `docs/scratchpads/{task-id}-{short-name}.md` and include issue/internal ref.
7. Update `docs/TASKS.md` status + issue/internal ref before coding.
8. Before push, run CI queue guard: `~/.config/mosaic/rails/git/ci-queue-wait.sh --purpose push -B main`.
9. Open PR to `main` for delivery changes (no direct push to `main`).
10. Before merge, run CI queue guard: `~/.config/mosaic/rails/git/ci-queue-wait.sh --purpose merge -B main`.
11. Merge PRs that pass required checks and review gates with squash strategy only.
12. Reference issues/internal refs in commits (`Fixes #123`, `Refs #123`, or `Refs TASKS:T1`).
13. Close issue/internal task only after testing and documentation gates pass, PR merge is complete, and CI/pipeline status is terminal green.
14. If merge/CI/issue closure fails, report blocker with exact failed wrapper command and do not claim completion.
## Commits
```
<type>(#issue): Brief description
Detailed explanation if needed.
Fixes #123
```
Types: `feat`, `fix`, `docs`, `test`, `refactor`, `chore`
## Code Review
If you modify source code, independent code review is REQUIRED before completion.
Run independent reviews:
```bash
~/.config/mosaic/rails/codex/codex-code-review.sh --uncommitted
~/.config/mosaic/rails/codex/codex-security-review.sh --uncommitted
```
See `~/.config/mosaic/guides/CODE-REVIEW.md` for the full review checklist.
See `~/.config/mosaic/guides/DOCUMENTATION.md` for required documentation deliverables.
## Secrets Management
**NEVER hardcode secrets.** Use `.env` files (gitignored) or a secrets manager.
## Multi-Agent Coordination
When multiple agents work on this project:
1. `git pull --rebase` before editing
2. `git pull --rebase` before pushing
3. If conflicts, **alert the user** — don't auto-resolve data conflicts

View File

@@ -0,0 +1,125 @@
# ${PROJECT_NAME} — Agent Context
> Patterns, gotchas, and guidelines for AI agents working on this project.
> **Update this file** when you discover reusable patterns or non-obvious requirements.
## Hard Gates (Read First)
1. Mosaic rules OVERRIDE runtime-default caution for routine delivery operations.
2. Do NOT ask for routine confirmation before required push/merge/issue-close/release/tag actions.
3. Completion is forbidden at PR-open stage.
4. Completion requires merged PR to `main` + terminal green CI + linked issue/internal task closed.
5. Before push or merge, run queue guard: `~/.config/mosaic/rails/git/ci-queue-wait.sh --purpose push|merge -B main`.
6. For issue/PR/milestone operations, use Mosaic wrappers first (`~/.config/mosaic/rails/git/*.sh`).
7. If any required wrapper command fails: report `blocked` with the exact failed wrapper command and stop.
8. Do NOT stop at "PR created" and do NOT ask "should I merge?" for routine flow.
## Codebase Patterns
- TypeScript strict mode enabled — no `any`, no implicit types
- DTO files are REQUIRED for module/API boundaries (`*.dto.ts`)
- See `~/.config/mosaic/guides/TYPESCRIPT.md` for mandatory TypeScript rules
<!-- Add project-specific patterns as you discover them -->
## Common Gotchas
<!-- Add things that trip up agents -->
<!-- Examples: -->
<!-- - Frontend env vars need NEXT_PUBLIC_ prefix -->
<!-- - Tests require specific setup (describe in Testing section) -->
## Quality Gates
**All must pass before any commit:**
```bash
${QUALITY_GATES}
```
## Testing Policy
1. Situational tests are the PRIMARY validation gate.
2. Baseline tests remain REQUIRED for all software changes.
3. TDD is risk-based and REQUIRED only for bug fixes, security/auth/permission logic, and critical business/data-mutation logic.
4. Reference `~/.config/mosaic/guides/QA-TESTING.md`.
## PRD Requirement
1. Before coding begins, `docs/PRD.md` or `docs/PRD.json` MUST exist.
2. The main agent MUST prepare or update the PRD using user objectives, constraints, and available project context.
3. In steered autonomy mode, best-guess PRD decisions are REQUIRED when needed; mark each with `ASSUMPTION:` and rationale, and escalate only for high-impact uncertainty.
4. Reference `~/.config/mosaic/guides/PRD.md`.
## Task Tracking Contract
1. For non-trivial implementation work, `docs/TASKS.md` MUST exist before coding.
2. If external git provider is available (Gitea/GitHub/GitLab), create/update issue(s) before coding and map them in `docs/TASKS.md`.
3. If no external provider is available, use internal refs in `docs/TASKS.md` (example: `TASKS:T1`).
4. Keep `docs/TASKS.md` status in sync with actual progress until completion.
5. For issue/PR/milestone actions, detect platform and use `~/.config/mosaic/rails/git/*.sh` wrappers first (no raw `gh`/`tea`/`glab` as first choice).
6. If wrapper-driven merge/CI/issue-closure fails, report blocker with the exact failed wrapper command and stop (do not claim completion).
## Documentation Contract
Documentation is a hard delivery gate.
If code/API/auth/infra changes, required documentation updates MUST be completed before task closure.
Keep `docs/` root clean and store reports/artifacts in scoped folders (`docs/reports/`, `docs/tasks/`, `docs/releases/`, `docs/scratchpads/`).
Reference:
- `~/.config/mosaic/guides/DOCUMENTATION.md`
- `~/.config/mosaic/templates/docs/DOCUMENTATION-CHECKLIST.md`
## Token Budget Policy
1. If user plan or token limits are provided, they are HARD constraints.
2. Track estimated and used tokens for non-trivial execution.
3. Shift to conservative strategy when budget pressure rises (smaller scope, fewer parallel actions, reduced re-reading).
4. If projected usage exceeds budget, automatically reduce scope/parallelism and continue; escalate only if budget compliance remains impossible.
## Merge Strategy (Hard Rule)
1. Create short-lived branches from `main`.
2. Open PRs to `main` for delivery changes.
3. Do not push directly to `main`.
4. Merge PRs to `main` with squash strategy only.
5. Do not mark implementation complete until PR is merged.
6. Do not mark implementation complete until CI/pipeline status is terminal green.
7. Close linked issues/tasks only after merge + green CI.
8. Before push or merge, run CI queue guard: `~/.config/mosaic/rails/git/ci-queue-wait.sh --purpose push|merge -B main`.
## Container Release Strategy (When Applicable)
1. Use immutable image tags: `sha-<shortsha>` and `v{base-version}-rc.{build}`.
2. Use mutable environment tags only as pointers (`testing`, optional `staging`, `prod`).
3. Deploy/promote by immutable digest; do not deploy by mutable tag alone.
4. Do not use `latest` or `dev` as deployment references.
5. Use blue-green by default; use canary only with automated metrics and rollback gates.
## Steered Autonomy Contract
1. Agent owns end-to-end delivery: plan, code, test, review, remediate, commit, push, PR/repo operations, release/tag, and deployment when in scope.
2. Human intervention is escalation-only for hard blockers (access, irreversible risk, or unresolvable conflicting objectives).
3. Code review is agent-executed and REQUIRED for any source-code change.
## Mode Declaration Contract
1. First response MUST declare mode before any actions.
2. Orchestration mission: `Now initiating Orchestrator mode...`
3. Implementation mission: `Now initiating Delivery mode...`
4. Review-only mission: `Now initiating Review mode...`
## Key Files
| File | Purpose |
|------|---------|
| `tsconfig.json` | TypeScript configuration |
| `package.json` | Dependencies and scripts |
<!-- Add project-specific key files -->
## Testing Approaches
<!-- Document how tests should be written for this project -->
<!-- Examples: -->
<!-- - Unit tests use Vitest with fixtures -->
<!-- - Component tests use React Testing Library -->
<!-- - E2E tests use Playwright -->

View File

@@ -0,0 +1,186 @@
# ${PROJECT_NAME} — Claude Code Instructions
> **Project:** ${PROJECT_DESCRIPTION}
> **Repository:** ${REPO_URL}
## Conditional Documentation Loading
**Read the relevant guide before starting work:**
| Task Type | Guide |
|-----------|-------|
| End-to-end implementation and validation | `~/.config/mosaic/guides/E2E-DELIVERY.md` |
| PRD creation and requirements definition | `~/.config/mosaic/guides/PRD.md` |
| Bootstrapping this project | `~/.config/mosaic/guides/BOOTSTRAP.md` |
| Orchestrating autonomous tasks | `~/.config/mosaic/guides/ORCHESTRATOR.md` |
| Frontend development | `~/.config/mosaic/guides/FRONTEND.md` |
| TypeScript strict typing | `~/.config/mosaic/guides/TYPESCRIPT.md` |
| Code review | `~/.config/mosaic/guides/CODE-REVIEW.md` |
| Documentation updates and standards | `~/.config/mosaic/guides/DOCUMENTATION.md` |
| QA/Testing | `~/.config/mosaic/guides/QA-TESTING.md` |
## Technology Stack
| Layer | Technology |
|-------|------------|
| **Language** | TypeScript (strict mode) |
| **Framework** | ${FRAMEWORK} |
| **Testing** | ${TESTING_STACK} |
| **Linting** | ESLint + Prettier |
| **Package Manager** | ${PACKAGE_MANAGER} |
| **Deployment** | ${DEPLOYMENT_STACK} |
## Repository Structure
```
${PROJECT_DIR}/
├── CLAUDE.md # This file
├── AGENTS.md # Agent-specific patterns and gotchas
├── src/ # Source code
├── tests/ # Test files
├── docs/
│ ├── PRD.md # Requirements source (or PRD.json)
│ └── scratchpads/ # Per-issue working documents
└── ${CONFIG_FILES} # Configuration files
```
## Development Workflow
### Building
```bash
${BUILD_COMMAND}
```
### Testing
```bash
${TEST_COMMAND}
```
### Linting & Type Checking
```bash
${LINT_COMMAND}
${TYPECHECK_COMMAND}
```
## Quality Gates
**All must pass before committing:**
```bash
${QUALITY_GATES}
```
## Testing Policy
1. Situational tests are the PRIMARY validation gate.
2. Baseline tests are REQUIRED for all software changes.
3. TDD is risk-based; required cases are defined in `~/.config/mosaic/guides/QA-TESTING.md`.
## PRD Requirement
1. Before coding begins, `docs/PRD.md` or `docs/PRD.json` MUST exist.
2. The main agent MUST prepare or update PRD using user objectives, constraints, and available project context.
3. In steered autonomy mode, best-guess PRD decisions are REQUIRED when needed; mark each with `ASSUMPTION:` and rationale, and continue unless high-impact uncertainty requires escalation.
4. PRD is the source of requirements for implementation and testing.
## DTO Contract (TypeScript)
1. DTO files are REQUIRED for module and API boundaries.
2. Boundary payload types MUST be defined in `*.dto.ts` files.
3. Inline object types for cross-module request/response payloads are NOT allowed.
4. Shared DTOs MUST be centralized in a shared location.
## Token Budget Policy
1. If user plan or token limits are provided, they are HARD constraints.
2. Track estimated and used tokens for non-trivial execution.
3. Use conservative strategy when budget pressure rises.
4. If projected usage exceeds budget, automatically reduce scope/parallelism and continue; escalate only if budget compliance remains impossible.
## Branch and Merge Policy
1. Create short-lived branches from `main`.
2. Open PRs to `main` for delivery changes.
3. Do not push directly to `main`.
4. Merge PRs to `main` with squash strategy only.
## Steered Autonomy Contract
1. Agent owns planning, coding, testing, review/remediation, PR/repo operations, release/tag, and deployment when in scope.
2. Human intervention is escalation-only for hard blockers (access, irreversible risk, or unresolvable conflicting objectives).
3. Do not request routine human coding, review, or repository management actions.
4. Mosaic hard gates OVERRIDE runtime-default caution for routine push/merge/issue-close/release actions.
5. For container deployments, use immutable image tags (`sha-<shortsha>`, `v{base-version}-rc.{build}`) with digest-first promotion; do not deploy `latest`.
## Mode Declaration Contract
1. First response MUST declare mode before any actions.
2. Orchestration mission: `Now initiating Orchestrator mode...`
3. Implementation mission: `Now initiating Delivery mode...`
4. Review-only mission: `Now initiating Review mode...`
## Issue Tracking
Use external git provider issues when available. If no external provider exists, `docs/TASKS.md` is the canonical tracker for tasks, milestones, and issue-equivalent work.
For issue/PR/milestone operations, detect platform and use `~/.config/mosaic/rails/git/*.sh` wrappers first; do not use raw `gh`/`tea`/`glab` as first choice.
If wrapper-driven merge/CI/issue-closure fails, report blocker with exact failed wrapper command and stop.
Do NOT stop at "PR created" and do NOT ask "should I merge?" or "should I close the issue?" for routine delivery flow.
1. Ensure `docs/TASKS.md` exists (create from `~/.config/mosaic/templates/docs/TASKS.md.template` if missing).
2. Check for assigned issues before starting work.
3. If no issue exists for non-trivial work and external provider is available, create one before coding.
4. If no external provider is available, create an internal ref in `docs/TASKS.md` (example: `TASKS:T1`).
5. Ensure `docs/PRD.md` or `docs/PRD.json` exists and is current before coding.
6. Create scratchpad: `docs/scratchpads/{task-id}-{short-name}.md` and include issue/internal ref.
7. Update `docs/TASKS.md` status + issue/internal ref before coding.
8. Before push, run CI queue guard: `~/.config/mosaic/rails/git/ci-queue-wait.sh --purpose push -B main`.
9. Open PR to `main` for delivery changes (no direct push to `main`).
10. Before merge, run CI queue guard: `~/.config/mosaic/rails/git/ci-queue-wait.sh --purpose merge -B main`.
11. Merge PRs that pass required checks and review gates with squash strategy only.
12. Reference issues/internal refs in commits (`Fixes #123`, `Refs #123`, or `Refs TASKS:T1`).
13. Close issue/internal task only after testing and documentation gates pass, PR merge is complete, and CI/pipeline status is terminal green.
14. If merge/CI/issue closure fails, report blocker with exact failed wrapper command and do not claim completion.
## Commits
```
<type>(#issue): Brief description
Detailed explanation if needed.
Fixes #123
```
Types: `feat`, `fix`, `docs`, `test`, `refactor`, `chore`
## Code Review
If you modify source code, independent code review is REQUIRED before completion.
Run independent reviews:
```bash
# Code quality review (Codex)
~/.config/mosaic/rails/codex/codex-code-review.sh --uncommitted
# Security review (Codex)
~/.config/mosaic/rails/codex/codex-security-review.sh --uncommitted
```
**Fallback:** If Codex is unavailable, use Claude's built-in review skills.
See `~/.config/mosaic/guides/CODE-REVIEW.md` for the full review checklist.
See `~/.config/mosaic/guides/DOCUMENTATION.md` for required documentation deliverables.
## Secrets Management
**NEVER hardcode secrets.** Use `.env` files (gitignored) or a secrets manager.
```bash
# .env.example is committed (with placeholders)
# .env is NOT committed (contains real values)
```
## Multi-Agent Coordination
When multiple agents work on this project:
1. `git pull --rebase` before editing
2. `git pull --rebase` before pushing
3. If conflicts, **alert the user** — don't auto-resolve data conflicts

View File

@@ -0,0 +1,268 @@
---
file_path: {full_path}
file_name: {sanitized_name}
remediation_report: {FileName}_remediation_needed.md
timestamp_start: {ISO_timestamp}
timestamp_end: {ISO_timestamp}
iteration: {current_iteration}
status: {planning|researching|executing|validating|completed|failed}
success_metrics:
typescript: {pass|fail|not_applicable}
eslint: {pass|fail|not_applicable}
prettier: {pass|fail|not_applicable}
security: {pass|fail|not_applicable}
---
# Remediation Actions: {file_name}
## Planning Phase
**Start Time**: {timestamp}
**Status**: {in_progress|completed}
### Sequential Thinking Analysis
```
Thought 1: Analyzing reported issues - {analysis}
Thought 2: Determining fix priority - {priority reasoning}
Thought 3: Identifying dependencies - {dependency analysis}
Thought 4: Planning execution order - {order rationale}
Thought 5: Estimating complexity - {complexity assessment}
Thought 6: Validation approach - {how to verify success}
Total Thoughts: {n}
Decision: {chosen approach}
```
### Issues Prioritization
1. **Critical**: {issues that block compilation/execution}
2. **High**: {issues affecting functionality}
3. **Medium**: {code quality issues}
4. **Low**: {style/formatting issues}
## Research Phase
**Start Time**: {timestamp}
**Status**: {in_progress|completed}
### Context7 Documentation Retrieved
```javascript
// Query 1: TypeScript best practices
await mcp__context7__get_library_docs({
context7CompatibleLibraryID: '/microsoft/TypeScript',
topic: '{specific topic}',
tokens: 3000,
});
// Result: {summary of findings}
// Query 2: ESLint rules
await mcp__context7__get_library_docs({
context7CompatibleLibraryID: '/eslint/eslint',
topic: '{specific rules}',
tokens: 2000,
});
// Result: {summary of findings}
// Query 3: Framework patterns
await mcp__context7__get_library_docs({
context7CompatibleLibraryID: '{framework library}',
topic: '{specific patterns}',
tokens: 2500,
});
// Result: {summary of findings}
```
### Relevant Patterns Identified
- **Pattern 1**: {description and application}
- **Pattern 2**: {description and application}
- **Best Practice**: {relevant best practice from docs}
## Action Plan
**Generated**: {timestamp}
**Total Actions**: {count}
### Planned Actions
1. [ ] **Fix TypeScript interface issue**
- **Issue**: Property 'onClick' missing from ButtonProps
- **Solution**: Add optional onClick property with proper typing
- **Rationale**: Maintains backward compatibility while fixing type error
- **Rollback**: Remove property if breaks existing usage
- **Estimated Impact**: Low risk, improves type safety
2. [ ] **Resolve ESLint violations**
- **Issue**: no-unused-vars on line 45
- **Solution**: Remove unused import or implement usage
- **Rationale**: Clean code practice, reduces bundle size
- **Rollback**: Re-add if functionality needed
- **Estimated Impact**: No functional change
3. [ ] **Apply Prettier formatting**
- **Issue**: Inconsistent formatting throughout file
- **Solution**: Run prettier --write
- **Rationale**: Maintains code style consistency
- **Rollback**: Not needed (formatting only)
- **Estimated Impact**: No functional change
## Execution Phase
**Start Time**: {timestamp}
**Status**: {in_progress|completed}
### Actions Taken
#### Action 1: Fix TypeScript interface issue
**Timestamp**: {ISO timestamp}
**Tool Used**: Edit
**Target**: Lines 10-15 of ButtonProps interface
**Change Applied**:
```typescript
// Before
interface ButtonProps {
label: string;
disabled?: boolean;
}
// After
interface ButtonProps {
label: string;
disabled?: boolean;
onClick?: React.MouseEventHandler<HTMLButtonElement>;
}
```
**Result**: ✅ Success - TypeScript compilation now passes
**Side Effects**: None observed
**Status**: [x] Completed
#### Action 2: Resolve ESLint violations
**Timestamp**: {ISO timestamp}
**Tool Used**: MultiEdit
**Target**: Multiple locations with violations
**Changes Applied**:
- Removed unused import on line 3
- Fixed missing dependency in useEffect on line 67
- Added missing return type on line 89
**Result**: ✅ Success - ESLint now reports 0 errors
**Side Effects**: None
**Status**: [x] Completed
#### Action 3: Apply Prettier formatting
**Timestamp**: {ISO timestamp}
**Tool Used**: Bash
**Command**: `npx prettier --write {file_path}`
**Result**: ✅ Success - File formatted
**Lines Changed**: 47
**Status**: [x] Completed
### Unexpected Issues Encountered
{Any issues that arose during execution}
### Adjustments Made
{Any deviations from the original plan and why}
## Validation Phase
**Start Time**: {timestamp}
**Status**: {in_progress|completed}
### Re-run QA Checks
#### TypeScript Validation
```bash
npx tsc --noEmit {file_path}
```
**Result**: ✅ PASS - No errors
**Details**: Compilation successful, all types resolved
#### ESLint Validation
```bash
npx eslint {file_path}
```
**Result**: ✅ PASS - 0 errors, 2 warnings
**Warnings**:
- Line 34: Prefer const over let (prefer-const)
- Line 78: Missing explicit return type (explicit-function-return-type)
#### Prettier Validation
```bash
npx prettier --check {file_path}
```
**Result**: ✅ PASS - File formatted correctly
#### Security Scan
```bash
# Security check command
```
**Result**: ✅ PASS - No vulnerabilities detected
### Overall Validation Status
- **All Critical Issues**: ✅ Resolved
- **All High Issues**: ✅ Resolved
- **Medium Issues**: ⚠️ 2 warnings remain (non-blocking)
- **Low Issues**: ✅ Resolved
## Next Steps
### If Successful (All Pass)
- [x] Move reports to done/
- [x] Archive after 7 days
- [x] Log success metrics
### If Failed (Issues Remain)
- [ ] Check iteration count: {current}/5
- [ ] If < 5: Plan next iteration approach
- [ ] If >= 5: Escalate with detailed analysis
### Next Iteration Planning (If Needed)
**Remaining Issues**: {list}
**New Approach**: {different strategy based on learnings}
**Sequential Thinking**:
```
Thought 1: Why did previous approach fail?
Thought 2: What alternative solutions exist?
Thought 3: Which approach has highest success probability?
Decision: {new approach}
```
## Summary
**Total Execution Time**: {duration}
**Actions Completed**: {n}/{total}
**Success Rate**: {percentage}
**Final Status**: {completed|needs_iteration|escalated}
## Lessons Learned
{Any insights that could help future remediation}
---
_Generated by Auto-Remediation Agent_
_Start: {ISO timestamp}_
_End: {ISO timestamp}_
_Agent Version: 1.0.0_

View File

@@ -0,0 +1,134 @@
---
file_path: { full_path }
file_name: { sanitized_name }
epic_association: { E.XXXX-name or "general" }
epic_exists: { true|false|created }
timestamp: { YYYYMMDD-HHMM }
iteration: { 1-5 }
max_iterations: 5
tool_triggered: { Edit|MultiEdit|Write }
severity: { CRITICAL|HIGH|MEDIUM|LOW }
status: pending
error_context: { any errors during creation }
---
# Remediation Needed: {file_name}
## Environment Context
- **Epic Status**: {existing|created|general}
- **Report Location**: {full path to this report}
- **Previous Iterations**: {list if any}
- **Project Type**: {React Frontend|NestJS Backend|Node.js Library}
## Issues Detected
### TypeScript Compilation
**Status**: ❌ FAILED | ✅ PASSED
**Errors Found**: {count}
```typescript
// Error details with line numbers
{specific errors}
```
**Context7 Documentation**:
- {relevant TypeScript docs retrieved}
### ESLint Violations
**Status**: ❌ ERRORS | ⚠️ WARNINGS | ✅ CLEAN
**Issues Found**: {count}
```javascript
// Violation details with rule names
{specific violations}
```
**Context7 Documentation**:
- {relevant ESLint rule docs}
### Prettier Formatting
**Status**: ❌ NEEDS FORMATTING | ✅ FORMATTED
**Changes Required**: {yes|no}
```diff
// Formatting differences
- {original}
+ {formatted}
```
### Security Issues
**Status**: ❌ VULNERABILITIES | ✅ SECURE
**Critical Issues**: {count}
- {list of security concerns}
## Recommended Fixes
### Priority 1: Critical (Must Fix)
1. **{Issue}**: {specific fix with code example}
- Rationale: {why this fix}
- Context7 Reference: {documentation link/content}
### Priority 2: High (Should Fix)
1. **{Issue}**: {specific fix}
- Rationale: {reasoning}
- Auto-fixable: {yes|no}
### Priority 3: Medium (Consider Fixing)
1. **{Issue}**: {improvement suggestion}
- Impact: {what this improves}
## Sequential Thinking Analysis
```
Thought 1: {initial analysis}
Thought 2: {problem identification}
Thought 3: {solution approach}
Thought 4: {validation strategy}
Decision: {recommended approach}
```
## Auto-Fix Availability
- **TypeScript**: {percentage auto-fixable}
- **ESLint**: {percentage auto-fixable with --fix}
- **Prettier**: ✅ 100% auto-fixable
- **Overall**: {percentage requiring manual intervention}
## Execution Plan
1. [ ] Apply Prettier formatting
2. [ ] Run ESLint with --fix flag
3. [ ] Fix TypeScript compilation errors
4. [ ] Address security vulnerabilities
5. [ ] Re-run validation suite
## Risk Assessment
- **Breaking Changes**: {none|low|medium|high}
- **Side Effects**: {list potential impacts}
- **Dependencies**: {any new dependencies needed}
## Manual Actions Required
{If any issues cannot be auto-fixed, list specific manual interventions needed}
## Notes
{Additional context, warnings, or information}
---
_Generated by Universal QA Agent_
_Timestamp: {ISO timestamp}_
_Agent Version: 1.0.0_

View File

@@ -0,0 +1,17 @@
# ${DIRECTORY_NAME} — Agent Context
> ${DIRECTORY_PURPOSE}
## Patterns
<!-- Add module-specific patterns as you discover them -->
## Gotchas
<!-- Add things that trip up agents in this module -->
## Key Files
| File | Purpose |
|------|---------|
<!-- Add important files in this directory -->

View File

@@ -0,0 +1,49 @@
# Documentation Completion Checklist
Use this checklist for every task that changes code, API contracts, auth, or operations.
## Required Artifacts
- [ ] `docs/PRD.md` or `docs/PRD.json` exists and is current
- [ ] `docs/USER-GUIDE/` updated as needed
- [ ] `docs/ADMIN-GUIDE/` updated as needed
- [ ] `docs/DEVELOPER-GUIDE/` updated as needed
- [ ] `docs/API/OPENAPI.yaml` (or `.json`) updated for API changes
- [ ] `docs/API/ENDPOINTS.md` updated for API changes
- [ ] `docs/SITEMAP.md` updated for navigation changes
## API Coverage
- [ ] All public endpoints are documented
- [ ] All private/internal endpoints are documented
- [ ] All API input schemas are documented
- [ ] All API output schemas are documented
- [ ] All endpoint auth/permission requirements are documented
- [ ] Error codes and failure behavior are documented
## Structural Standards (Book/Chapter/Page)
- [ ] `docs/USER-GUIDE/README.md` indexes user chapters/pages
- [ ] `docs/ADMIN-GUIDE/README.md` indexes admin chapters/pages
- [ ] `docs/DEVELOPER-GUIDE/README.md` indexes developer chapters/pages
## Docs Root Hygiene
- [ ] `docs/` root is clean and only contains canonical root docs (PRD, TASKS when active, SITEMAP, optional README) plus category directories
- [ ] Reports are under `docs/reports/<category>/` (not `docs/` root)
- [ ] Deferred findings are under `docs/reports/deferred/`
- [ ] Orchestrator learnings are under `docs/tasks/orchestrator-learnings.json`
- [ ] Release notes are under `docs/releases/`
- [ ] Archived task snapshots are under `docs/tasks/`
- [ ] Scratchpads are under `docs/scratchpads/`
## Review Gate
- [ ] Documentation changes are in the same logical change set as code/API changes
- [ ] Code review verified documentation completeness
- [ ] Missing docs were treated as blocker findings
## Publishing
- [ ] Publishing target was confirmed with user if unspecified
- [ ] Canonical source remains in-repo unless user explicitly declares otherwise

View File

@@ -0,0 +1,53 @@
# Mission Manifest — ${MISSION_NAME}
> Persistent document tracking full mission scope, status, and session history.
> Updated by the orchestrator at each phase transition and milestone completion.
## Mission
**ID:** ${MISSION_ID}
**Statement:** ${MISSION_STATEMENT}
**Phase:** Intake
**Current Milestone:** —
**Progress:** 0 / ${MILESTONE_COUNT} milestones
**Status:** not-started
**Last Updated:** ${CREATED_AT}
## Success Criteria
${SUCCESS_CRITERIA}
## Milestones
| # | ID | Name | Status | Branch | Issue | Started | Completed |
|---|-----|------|--------|--------|-------|---------|-----------|
${MILESTONES_TABLE}
## Deployment
| Target | URL | Method |
|--------|-----|--------|
${DEPLOYMENT_TABLE}
## Coordination
- **Primary Agent:** ${PRIMARY_RUNTIME}
- **Sibling Agents:** ${SIBLING_AGENTS}
- **Shared Contracts:** ${SHARED_CONTRACTS}
## Token Budget
| Metric | Value |
|--------|-------|
| Budget | ${TOKEN_BUDGET} |
| Used | 0 |
| Mode | normal |
## Session History
| Session | Runtime | Started | Duration | Ended Reason | Last Task |
|---------|---------|---------|----------|--------------|-----------|
## Scratchpad
Path: `docs/scratchpads/${MISSION_ID}.md`

View File

@@ -0,0 +1,75 @@
# PRD: {PROJECT_OR_FEATURE_NAME}
## Metadata
- Owner: {owner}
- Date: {yyyy-mm-dd}
- Status: draft|approved|in-progress|completed
- Best-Guess Mode: true|false
## Problem Statement
{what problem is being solved and why now}
## Objectives
1. {objective-1}
2. {objective-2}
## Scope
### In Scope
1. {in-scope-item}
### Out of Scope
1. {out-of-scope-item}
## User/Stakeholder Requirements
1. {requirement}
## Functional Requirements
1. {functional-requirement}
## Non-Functional Requirements
1. Security: {requirements}
2. Performance: {requirements}
3. Reliability: {requirements}
4. Observability: {requirements}
## Acceptance Criteria
1. {ac-1}
2. {ac-2}
## Constraints and Dependencies
1. {constraint-or-dependency}
## Risks and Open Questions
1. Risk: {risk}
2. Open Question: {question}
## Testing and Verification Expectations
1. Baseline checks: {lint/type/unit/integration expectations}
2. Situational testing: {required situational checks}
3. Evidence format: {how verification will be reported}
## Milestone / Delivery Intent
1. Target milestone/version: {e.g., 0.0.2}
2. Definition of done: {completion conditions}
## Assumptions
List only if Best-Guess Mode is true.
Prefix each entry with `ASSUMPTION:`.
1. ASSUMPTION: {guessed decision and rationale}

View File

@@ -0,0 +1,17 @@
# TASKS
Canonical tracking for active work. Keep this file current.
## Rules
1. Update status as work progresses.
2. Link every non-trivial task to a provider issue (`#123`) or internal ref (`TASKS:T1`) if no provider is available.
3. Keep one row per active task.
4. Do not set `status=done` for source-code work until PR is merged, CI/pipeline is terminal green, and linked issue/ref is closed.
5. If merge/CI/issue closure fails, set `status=blocked` and record the exact failed wrapper command in `notes`.
## Tasks
| id | status | description | issue | repo | branch | depends_on | blocks | agent | started_at | completed_at | estimate | used | notes |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| T1 | not-started | Example task description | TASKS:T1 | app | feat/example | | | | | | | | |

View File

@@ -0,0 +1,36 @@
## Continuation Mission
Continue **${MISSION_NAME}** from existing state.
## Setup
- **Project:** ${PROJECT_PATH}
- **State:** docs/TASKS.md (already populated — ${TASKS_DONE}/${TASKS_TOTAL} tasks complete)
- **Manifest:** docs/MISSION-MANIFEST.md
- **Scratchpad:** docs/scratchpads/${MISSION_ID}.md
- **Protocol:** ~/.config/mosaic/guides/ORCHESTRATOR.md
- **Quality gates:** ${QUALITY_GATES}
## Resume Point
- **Current milestone:** ${CURRENT_MILESTONE_NAME} (${CURRENT_MILESTONE_ID})
- **Next task:** ${NEXT_TASK_ID}
- **Progress:** ${TASKS_DONE}/${TASKS_TOTAL} tasks (${PROGRESS_PCT}%)
- **Branch:** ${CURRENT_BRANCH}
## Previous Session Context
- **Session:** ${PREV_SESSION_ID} (${PREV_RUNTIME}, ${PREV_DURATION})
- **Ended:** ${PREV_ENDED_REASON}
- **Last completed task:** ${PREV_LAST_TASK}
## Instructions
1. Read `~/.config/mosaic/guides/ORCHESTRATOR.md` for full protocol
2. Read `docs/MISSION-MANIFEST.md` for mission scope and status
3. Read `docs/scratchpads/${MISSION_ID}.md` for session history and decisions
4. Read `docs/TASKS.md` for current task state
5. `git pull --rebase` to sync latest changes
6. Continue execution from task **${NEXT_TASK_ID}**
7. Follow Two-Phase Completion Protocol
8. You are the SOLE writer of `docs/TASKS.md`

View File

@@ -0,0 +1,27 @@
# Mission Scratchpad — ${MISSION_NAME}
> Append-only log. NEVER delete entries. NEVER overwrite sections.
> This is the orchestrator's working memory across sessions.
## Original Mission Prompt
```
${MISSION_PROMPT}
```
## Planning Decisions
<!-- Record key decisions made during planning. Format: decision + rationale. -->
## Session Log
| Session | Date | Milestone | Tasks Done | Outcome |
|---------|------|-----------|------------|---------|
## Open Questions
<!-- Unresolved items that need human input or cross-session investigation. -->
## Corrections
<!-- Record any corrections to earlier decisions or assumptions. -->

View File

@@ -0,0 +1,78 @@
# Repo Mosaic Linkage
This repository is attached to the machine-wide Mosaic framework.
## Load Order for Agents
1. `~/.config/mosaic/STANDARDS.md`
2. `AGENTS.md` (this repository)
3. `.mosaic/repo-hooks.sh` (repo-specific automation hooks)
## Purpose
- Keep universal standards in `~/.config/mosaic`
- Keep repo-specific behavior in this repo
- Avoid copying large runtime configs into each project
## Optional Quality Rails
Use `.mosaic/quality-rails.yml` to track whether quality rails are enabled for this repo.
Apply a template:
```bash
~/.config/mosaic/bin/mosaic-quality-apply --template <template> --target .
```
Verify enforcement:
```bash
~/.config/mosaic/bin/mosaic-quality-verify --target .
```
## Optional Matrix Orchestrator Rail
Repo-local orchestrator state lives in `.mosaic/orchestrator/`.
Run one cycle:
```bash
~/.config/mosaic/bin/mosaic-orchestrator-matrix-cycle
~/.config/mosaic/bin/mosaic-orchestrator-run --once
```
Run continuously:
```bash
~/.config/mosaic/bin/mosaic-orchestrator-run --poll-sec 10
```
Bridge events to Matrix:
```bash
~/.config/mosaic/bin/mosaic-orchestrator-matrix-publish
~/.config/mosaic/bin/mosaic-orchestrator-matrix-consume
```
Run until queue is drained (syncs from `docs/tasks.md` first):
```bash
~/.config/mosaic/bin/mosaic-orchestrator-drain
```
Set worker command if auto-detect does not match your CLI:
```bash
export MOSAIC_WORKER_EXEC="codex -p"
# or
export MOSAIC_WORKER_EXEC="opencode -p"
```
Use repo helper (foreground or detached):
```bash
bash scripts/agent/orchestrator-daemon.sh drain
bash scripts/agent/orchestrator-daemon.sh start
bash scripts/agent/orchestrator-daemon.sh status
bash scripts/agent/orchestrator-daemon.sh stop
```

View File

@@ -0,0 +1,18 @@
{
"enabled": false,
"transport": "matrix",
"matrix": {
"control_room_id": "",
"workspace_id": "",
"homeserver_url": "",
"access_token": "",
"bot_user_id": ""
},
"worker": {
"runtime": "codex",
"command_template": "bash scripts/agent/orchestrator-worker.sh {task_file}",
"timeout_seconds": 7200,
"max_attempts": 1
},
"quality_gates": ["pnpm lint", "pnpm typecheck", "pnpm test"]
}

View File

@@ -0,0 +1,4 @@
{
"last_published_line": 0,
"since": null
}

View File

@@ -0,0 +1,14 @@
{
"schema_version": 1,
"mission_id": "",
"name": "",
"description": "",
"project_path": "",
"created_at": "",
"status": "inactive",
"task_prefix": "",
"quality_gates": "",
"milestone_version": "0.0.1",
"milestones": [],
"sessions": []
}

View File

@@ -0,0 +1,4 @@
{
"running_task_id": null,
"updated_at": null
}

View File

@@ -0,0 +1,3 @@
{
"tasks": []
}

View File

@@ -0,0 +1,10 @@
enabled: false
template: ''
# Set enabled: true and choose one template:
# - typescript-node
# - typescript-nextjs
# - monorepo
#
# Apply manually:
# ~/.mosaic/bin/mosaic-quality-apply --template <template> --target <repo>

View File

@@ -0,0 +1,17 @@
#!/usr/bin/env bash
# Optional repo-specific hooks used by scripts/agent/*.sh
# Called by session-start.sh
# mosaic_hook_session_start() {
# echo "Run repo-specific startup checks"
# }
# Called by critical.sh
# mosaic_hook_critical() {
# echo "Run repo-specific critical queries"
# }
# Called by session-end.sh
# mosaic_hook_session_end() {
# echo "Run repo-specific end-of-session checks"
# }

View File

@@ -0,0 +1,29 @@
#!/usr/bin/env bash
set -euo pipefail
repo_root() {
git rev-parse --show-toplevel 2>/dev/null || pwd
}
ensure_repo_root() {
cd "$(repo_root)"
}
has_remote() {
git remote get-url origin >/dev/null 2>&1
}
run_step() {
local label="$1"
shift
echo "[agent-framework] $label"
"$@"
}
load_repo_hooks() {
local hooks_file=".mosaic/repo-hooks.sh"
if [[ -f "$hooks_file" ]]; then
# shellcheck disable=SC1090
source "$hooks_file"
fi
}

View File

@@ -0,0 +1,16 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=./common.sh
source "$SCRIPT_DIR/common.sh"
ensure_repo_root
load_repo_hooks
if declare -F mosaic_hook_critical >/dev/null 2>&1; then
run_step "Run repo critical hook" mosaic_hook_critical
else
echo "[agent-framework] No repo critical hook configured (.mosaic/repo-hooks.sh)"
echo "[agent-framework] Define mosaic_hook_critical() for project-specific priority scans"
fi

View File

@@ -0,0 +1,44 @@
#!/usr/bin/env bash
set -euo pipefail
TITLE="${1:-}"
if [[ -z "$TITLE" ]]; then
echo "Usage: $0 \"Short limitation title\"" >&2
exit 1
fi
FILE="EVOLUTION.md"
if [[ ! -f "$FILE" ]]; then
echo "[agent-framework] $FILE not found. Create project-specific limitations log if needed."
exit 0
fi
if command -v rg >/dev/null 2>&1; then
last_num=$(rg -o "^### L-[0-9]{3}" "$FILE" | sed 's/^### L-//' | sort -n | tail -1)
else
last_num=$(grep -E "^### L-[0-9]{3}" "$FILE" | sed 's/^### L-//' | sort -n | tail -1)
fi
if [[ -z "$last_num" ]]; then
next_num="001"
else
next_num=$(printf "%03d" $((10#$last_num + 1)))
fi
entry_id="L-$next_num"
cat <<EOF2
### $entry_id: $TITLE
| Aspect | Details |
|--------|---------|
| **Pain** | TODO |
| **Impact** | TODO |
| **Frequency** | TODO |
| **Current Workaround** | TODO |
| **Proposed Solution** | TODO |
| **Platform Implication** | TODO |
EOF2
echo "[agent-framework] Suggested limitation ID: $entry_id"

View File

@@ -0,0 +1,102 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=./common.sh
source "$SCRIPT_DIR/common.sh"
ensure_repo_root
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
ORCH_DIR=".mosaic/orchestrator"
PID_FILE="$ORCH_DIR/orchestrator.pid"
LOG_FILE="$ORCH_DIR/logs/daemon.log"
usage() {
cat <<USAGE
Usage: $(basename "$0") <start|drain|stop|status> [--poll-sec N] [--no-sync]
Commands:
start Run orchestrator drain loop in background (detached)
drain Run orchestrator drain loop in foreground (until queue drained)
stop Stop background orchestrator if running
status Show background orchestrator status
Options:
--poll-sec N Poll interval (default: 15)
--no-sync Skip docs/TASKS.md -> orchestrator queue sync before run
USAGE
}
cmd="${1:-status}"
if [[ $# -gt 0 ]]; then
shift
fi
poll_sec=15
sync_arg=""
while [[ $# -gt 0 ]]; do
case "$1" in
--poll-sec)
poll_sec="${2:-15}"
shift 2
;;
--no-sync)
sync_arg="--no-sync"
shift
;;
*)
echo "[agent-framework] unknown argument: $1" >&2
usage
exit 1
;;
esac
done
mkdir -p "$ORCH_DIR/logs" "$ORCH_DIR/results"
is_running() {
[[ -f "$PID_FILE" ]] || return 1
local pid
pid="$(cat "$PID_FILE" 2>/dev/null || true)"
[[ -n "$pid" ]] || return 1
kill -0 "$pid" 2>/dev/null
}
case "$cmd" in
start)
if is_running; then
echo "[agent-framework] orchestrator already running (pid=$(cat "$PID_FILE"))"
exit 0
fi
nohup "$MOSAIC_HOME/bin/mosaic-orchestrator-drain" --poll-sec "$poll_sec" $sync_arg >"$LOG_FILE" 2>&1 &
echo "$!" > "$PID_FILE"
echo "[agent-framework] orchestrator started (pid=$!, log=$LOG_FILE)"
;;
drain)
exec "$MOSAIC_HOME/bin/mosaic-orchestrator-drain" --poll-sec "$poll_sec" $sync_arg
;;
stop)
if ! is_running; then
echo "[agent-framework] orchestrator not running"
rm -f "$PID_FILE"
exit 0
fi
pid="$(cat "$PID_FILE")"
kill "$pid" || true
rm -f "$PID_FILE"
echo "[agent-framework] orchestrator stopped (pid=$pid)"
;;
status)
if is_running; then
echo "[agent-framework] orchestrator running (pid=$(cat "$PID_FILE"), log=$LOG_FILE)"
else
echo "[agent-framework] orchestrator not running"
rm -f "$PID_FILE"
fi
;;
*)
usage
exit 1
;;
esac

View File

@@ -0,0 +1,63 @@
#!/usr/bin/env bash
set -euo pipefail
task_file="${1:-}"
if [[ -z "$task_file" || ! -f "$task_file" ]]; then
echo "[orchestrator-worker] missing task file argument" >&2
exit 1
fi
worker_exec="${MOSAIC_WORKER_EXEC:-}"
if [[ -z "$worker_exec" ]]; then
if command -v codex >/dev/null 2>&1; then
worker_exec="codex -p"
elif command -v opencode >/dev/null 2>&1; then
worker_exec="opencode -p"
else
echo "[orchestrator-worker] set MOSAIC_WORKER_EXEC to your worker command (example: 'codex -p' or 'opencode -p')" >&2
exit 1
fi
fi
prompt="$(python3 - "$task_file" <<'PY'
import json
import sys
from pathlib import Path
task = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8"))
task_id = str(task.get("id", "TASK"))
title = str(task.get("title", ""))
description = str(task.get("description", ""))
meta = task.get("metadata", {}) or {}
issue = str(meta.get("issue", ""))
repo = str(meta.get("repo", ""))
branch = str(meta.get("branch", ""))
depends = task.get("depends_on", [])
if isinstance(depends, list):
depends_str = ", ".join(str(x) for x in depends)
else:
depends_str = str(depends)
print(
f"""Read ~/.config/mosaic/STANDARDS.md, then AGENTS.md and SOUL.md (if present).
Complete this queued task fully.
Task ID: {task_id}
Title: {title}
Description: {description}
Issue: {issue}
Repo hint: {repo}
Branch hint: {branch}
Depends on: {depends_str}
Requirements:
- Implement and verify the task end-to-end.
- Keep changes scoped to this task.
- Run project checks and tests relevant to touched code.
- Return with a concise summary of what changed and verification results.
"""
)
PY
)"
PROMPT="$prompt" bash -lc "$worker_exec \"\$PROMPT\""

View File

@@ -0,0 +1,48 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=./common.sh
source "$SCRIPT_DIR/common.sh"
ensure_repo_root
load_repo_hooks
# ─── Mission session cleanup (ORCHESTRATOR-PROTOCOL) ────────────────────────
ORCH_DIR=".mosaic/orchestrator"
MISSION_JSON="$ORCH_DIR/mission.json"
SESSION_LOCK="$ORCH_DIR/session.lock"
COORD_LIB="$HOME/.config/mosaic/tools/orchestrator/_lib.sh"
if [[ -f "$SESSION_LOCK" ]] && [[ -f "$COORD_LIB" ]] && command -v jq &>/dev/null; then
# shellcheck source=/dev/null
source "$COORD_LIB"
sess_id="$(jq -r '.session_id // ""' "$SESSION_LOCK")"
if [[ -n "$sess_id" && -f "$MISSION_JSON" ]]; then
# Update mission.json: mark session ended
updated="$(jq \
--arg sid "$sess_id" \
--arg ts "$(iso_now)" \
--arg reason "completed" \
'(.sessions[] | select(.session_id == $sid)) |= . + {
ended_at: $ts,
ended_reason: $reason
}' "$MISSION_JSON")"
echo "$updated" > "$MISSION_JSON.tmp" && mv "$MISSION_JSON.tmp" "$MISSION_JSON"
echo "[agent-framework] Session $sess_id recorded in mission state"
fi
session_lock_clear "."
fi
if declare -F mosaic_hook_session_end >/dev/null 2>&1; then
run_step "Run repo end hook" mosaic_hook_session_end
else
echo "[agent-framework] No repo end hook configured (.mosaic/repo-hooks.sh)"
fi
if git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
run_step "Show status" git status --short
run_step "Show diff summary" git diff --stat
fi

View File

@@ -0,0 +1,92 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=./common.sh
source "$SCRIPT_DIR/common.sh"
ensure_repo_root
load_repo_hooks
if git rev-parse --is-inside-work-tree >/dev/null 2>&1 && has_remote; then
if git diff --quiet && git diff --cached --quiet; then
run_step "Pull latest changes" git pull --rebase
else
echo "[agent-framework] Skip pull: working tree has local changes"
fi
fi
# ─── Mission state detection (ORCHESTRATOR-PROTOCOL) ────────────────────────
ORCH_DIR=".mosaic/orchestrator"
MISSION_JSON="$ORCH_DIR/mission.json"
COORD_LIB="$HOME/.config/mosaic/tools/orchestrator/_lib.sh"
if [[ -f "$MISSION_JSON" ]] && command -v jq &>/dev/null; then
mission_status="$(jq -r '.status // "inactive"' "$MISSION_JSON")"
if [[ "$mission_status" == "active" || "$mission_status" == "paused" ]]; then
mission_name="$(jq -r '.name // "unnamed"' "$MISSION_JSON")"
echo ""
echo "========================================="
echo "ACTIVE MISSION DETECTED"
echo "========================================="
echo " Mission: $mission_name"
# Extract key fields from manifest if present
manifest="docs/MISSION-MANIFEST.md"
if [[ -f "$manifest" ]]; then
phase="$(grep -m1 '^\*\*Phase:\*\*' "$manifest" 2>/dev/null | sed 's/.*\*\*Phase:\*\* //' || true)"
milestone="$(grep -m1 '^\*\*Current Milestone:\*\*' "$manifest" 2>/dev/null | sed 's/.*\*\*Current Milestone:\*\* //' || true)"
progress="$(grep -m1 '^\*\*Progress:\*\*' "$manifest" 2>/dev/null | sed 's/.*\*\*Progress:\*\* //' || true)"
[[ -n "$phase" ]] && echo " Phase: $phase"
[[ -n "$milestone" ]] && echo " Milestone: $milestone"
[[ -n "$progress" ]] && echo " Progress: $progress"
fi
# Task counts
if [[ -f "docs/TASKS.md" ]]; then
total="$(grep -c '^|' "docs/TASKS.md" 2>/dev/null || true)"
total="${total:-0}"
done_count="$(grep -ci '| done \|| completed ' "docs/TASKS.md" 2>/dev/null || true)"
done_count="${done_count:-0}"
approx_total=$(( total > 2 ? total - 2 : 0 ))
echo " Tasks: ~${done_count} done of ~${approx_total} total"
fi
# Scratchpad
if [[ -d "docs/scratchpads" ]]; then
latest_sp="$(ls -t docs/scratchpads/*.md 2>/dev/null | head -1 || true)"
[[ -n "$latest_sp" ]] && echo " Scratchpad: $latest_sp"
fi
echo ""
echo " Resume: Read manifest + scratchpad before taking action."
echo " Protocol: ~/.config/mosaic/guides/ORCHESTRATOR-PROTOCOL.md"
echo "========================================="
echo ""
# Register session if coordinator lib is available
if [[ -f "$COORD_LIB" ]]; then
# shellcheck source=/dev/null
source "$COORD_LIB"
sess_id="$(next_session_id ".")"
runtime="${MOSAIC_RUNTIME:-unknown}"
session_lock_write "." "$sess_id" "$runtime" "$$"
# Append session to mission.json
updated="$(jq \
--arg sid "$sess_id" \
--arg rt "$runtime" \
--arg ts "$(iso_now)" \
'.sessions += [{"session_id":$sid,"runtime":$rt,"started_at":$ts,"ended_at":"","ended_reason":"","milestone_at_end":"","tasks_completed":[],"last_task_id":""}]' \
"$MISSION_JSON")"
echo "$updated" > "$MISSION_JSON.tmp" && mv "$MISSION_JSON.tmp" "$MISSION_JSON"
fi
fi
fi
if declare -F mosaic_hook_session_start >/dev/null 2>&1; then
run_step "Run repo start hook" mosaic_hook_session_start
else
echo "[agent-framework] No repo start hook configured (.mosaic/repo-hooks.sh)"
fi