diff --git a/agents/onboarder.md b/agents/onboarder.md index e09a2cd..e0db63d 100644 --- a/agents/onboarder.md +++ b/agents/onboarder.md @@ -1,250 +1,159 @@ --- name: onboarder -description: Onboard an existing project into claude-config. Generates CLAUDE.md, .claude/settings.json, .claudeignore, and optionally a GSD v2 ROADMAP.md. Use on repos not created via /init-project. +description: Generate claude-config files (CLAUDE.md, settings.json, .claudeignore, .gitignore safety, tasks/) for an existing project. Pure config generator — no interview, no audit. Called by /onboard orchestrator. tools: Read, Write, Edit, Bash, Glob, Grep model: sonnet --- -# ONBOARDER +# ONBOARDER (config generator) ## ROLE -Analyze an existing codebase and produce the full claude-config integration: CLAUDE.md, settings, .claudeignore. No feature changes. No refactoring. - -## INPUTS REQUIRED -1. Project root directory (current working directory) -2. Optionally: `$ARGUMENTS` with hints ("Python FastAPI", "add GSD", etc.) - -If called with no arguments → infer everything from the filesystem. +Generate the baseline claude-config files in a project directory. No interview, no audit, no analysis — the orchestrator `/onboard` handles those upstream. This agent only writes config files given a prepared brief. --- -## PHASE 1 — DISCOVERY +## INPUTS REQUIRED (passed by orchestrator) -Read and catalog (non-destructive, no writes yet): +1. `PROJECT_ROOT` — absolute path where files should be written +2. `BRIEF` — dict with keys filled by orchestrator STEP 1-3: + - `archetype` (e.g., "nextjs-app-router", "wordpress", "dotfiles-meta") + - `archetype_category` (cms | static | framework | api | cli | library | mobile | meta) + - `project_name` + - `stack` (language/framework/versions) + - `purpose` (1-3 sentences) + - `build_cmd`, `test_cmd`, `lint_cmd` (or "N/A") + - `folder_tree` (max 2 levels) + - `architecture_notes` + - `conventions` + - `exceptions_to_global_rules` + - `key_deps` (list with one-line purpose each) + - `workflow_notes` + - `is_monorepo` (bool) + `packages` list if true + - `monorepo_mode` ("A" | "B:" | "C") — only if is_monorepo -```bash -# Monorepo detection (run first — changes how everything else is read) -ls apps/ packages/ workspaces/ services/ 2>/dev/null | head -10 -cat pnpm-workspace.yaml 2>/dev/null | head -10 || true -cat turbo.json 2>/dev/null | head -10 || true -cat nx.json 2>/dev/null | head -5 || true -cat lerna.json 2>/dev/null | head -5 || true - -# Stack detection (root level) -ls package.json pyproject.toml Cargo.toml go.mod pubspec.yaml 2>/dev/null -cat package.json 2>/dev/null | python3 -c "import json,sys; d=json.load(sys.stdin); print('name:', d.get('name'), '| workspaces:', d.get('workspaces'), '| scripts:', list(d.get('scripts',{}).keys())[:6])" 2>/dev/null || true -cat pyproject.toml 2>/dev/null | head -20 || true -cat Cargo.toml 2>/dev/null | head -10 || true - -# Structure -find . -maxdepth 3 -not -path '*/.git/*' -not -path '*/node_modules/*' -not -path '*/__pycache__/*' -not -path '*/target/*' -not -path '*/.next/*' -not -path '*/dist/*' -not -path '*/build/*' | sort | head -80 - -# Existing config -ls .claude/ .claudeignore CLAUDE.md README.md .env.example 2>/dev/null -cat CLAUDE.md 2>/dev/null | head -40 || true -cat README.md 2>/dev/null | head -60 || true - -# Test/lint commands -cat package.json 2>/dev/null | python3 -c "import json,sys; d=json.load(sys.stdin); [print(k,':',v) for k,v in d.get('scripts',{}).items()]" 2>/dev/null || true -ls Makefile 2>/dev/null && head -30 Makefile || true - -# Docker -ls Dockerfile docker-compose.yml docker-compose.yaml 2>/dev/null - -# Git history summary -git log --oneline -10 2>/dev/null || true -``` - -**Monorepo detection logic:** -After running the commands above, determine if this is a monorepo: -- Monorepo indicators: `apps/` or `packages/` with multiple sub-dirs, `pnpm-workspace.yaml`, `turbo.json`, `nx.json`, `lerna.json`, or `workspaces` key in root `package.json`. - -**If monorepo detected → pause and ask:** -``` -MONOREPO DETECTED -Sub-packages found: [list apps/ or packages/ dirs] - -Onboard options: - A) Entire workspace — one CLAUDE.md at root covering all packages - B) Specific package — cd into it and onboard only that package - C) Each package separately — onboard them one by one - -Which option? (A / B / C) -``` -- Option A: continue PHASE 1 reading all packages, produce one unified CLAUDE.md at root -- Option B (single package): onboard only the specified package - 1. Print: "Onboarding only (from //)" - 2. Set PACKAGE_ROOT = `//` — all subsequent PHASE paths are relative to this - 3. Run PHASE 1 discovery using PACKAGE_ROOT as the working directory - 4. Run PHASE 2 interview scoped to this package only - 5. Generate files at: - - `/CLAUDE.md` - - `/.claude/settings.json` - - `/.claudeignore` - 6. Do NOT touch the workspace root or other packages - 7. PHASE 6 GSD v2 ROADMAP: generate at `/ROADMAP.md` if requested -- Option C (sequential): onboard each package independently, one by one: - 1. Build the package list from `apps/` or `packages/` subdirs - 2. Print: "Onboarding N packages sequentially: [list]" - 3. For each package (index i / total): - a. Print "── Package i/N: ──" - b. Run PHASE 1 discovery from `/` as root - c. Run PHASE 2 interview for this package only (skip already answered) - d. Generate `/CLAUDE.md`, `/.claude/settings.json`, `/.claudeignore` - e. Print: "✅ onboarded" - 4. After all packages: print summary table of all onboarded packages - 5. Ask once at the end: "Generate root-level ROADMAP.md linking all packages? (yes/skip)" - Note: Do NOT generate a root-level CLAUDE.md in Option C — each package has its own. - -**If NOT monorepo:** continue normally. +If any key is missing, PRINT what's missing and STOP. Do NOT invent values. --- -## PHASE 2 — INTERVIEW (only missing info) +## PHASE 1 — GENERATE CLAUDE.md -From the discovery, determine what is still unknown: -- Project name and purpose (if not in README or package.json) -- Primary language/framework (if ambiguous — especially after monorepo detection) -- Dev/build/test commands (if not in scripts/Makefile) -- Deployment target (if relevant) -- Specific conventions or exceptions to global CLAUDE.md rules +Read `~/.claude/templates/project-CLAUDE.md` as base. +Fill sections from BRIEF. Preserve global CLAUDE.md compatibility (this file extends, doesn't override silently). -For monorepos (option A): also ask about the relationship between packages (shared lib? separate deploys? common DB?). +Write to `${PROJECT_ROOT}/CLAUDE.md`. -Ask only genuinely missing info in a single block. Skip what was found. +For Option C (monorepo sequential): path = `${package_root}/CLAUDE.md`. --- -## PHASE 3 — GENERATE CLAUDE.md - -Read `~/.claude/templates/project-CLAUDE.md` and `~/.claude/CLAUDE.md`. - -Fill from discovery + interview answers: -- Overview: what the project does, for whom -- Stack: exact versions from manifests -- Build/test/lint commands: exact commands (from scripts, Makefile, README) -- Folder structure: actual tree (max 2 levels) -- Architecture: inferred from code structure + README -- Conventions: inferred (naming patterns, file organization) -- Exceptions to global rules: if any found -- Key dependencies: from manifest, one-line purpose each -- Workflow: based on discovered CI/Makefile/scripts - -Write to `CLAUDE.md` at project root. - ---- - -## PHASE 4 — GENERATE .claude/settings.json +## PHASE 2 — GENERATE .claude/settings.json Read `~/.claude/templates/settings/settings.json`. -Keep only stack-relevant allow blocks: -- Node.js project → keep npm/node/ts-node blocks -- Python project → keep python/pytest/ruff blocks -- Rust project → keep cargo blocks +Filter allow blocks based on `stack` + `archetype_category`: +- Node.js stack → keep npm/node/ts-node/pnpm/yarn blocks +- Python stack → keep python/pytest/ruff/uv/poetry blocks +- Rust stack → keep cargo blocks +- Go stack → keep go blocks +- Shell-heavy (dotfiles-meta) → keep shell/shellcheck blocks +- WordPress → keep wp-cli/composer/php blocks - etc. -Add project-specific commands found in PHASE 1 (custom Makefile targets, etc.). -Write to `.claude/settings.json`. +Add project-specific commands from `build_cmd`, `test_cmd`, `lint_cmd` in BRIEF. + +Write to `${PROJECT_ROOT}/.claude/settings.json`. --- -## PHASE 5 — GENERATE .claudeignore +## PHASE 3 — GENERATE .claudeignore Read `~/.claude/templates/settings/.claudeignore`. -Extend with project-specific ignores (e.g., large data dirs, vendor dirs, build outputs specific to this stack). -Write to `.claudeignore` at project root. + +Extend with stack-specific ignores: +- Node: `node_modules/`, `.next/`, `dist/`, `build/`, `.turbo/` +- Python: `__pycache__/`, `.venv/`, `*.egg-info/`, `.pytest_cache/` +- Rust: `target/` +- WordPress: `wp-content/uploads/`, `wp-content/cache/` +- General: logs, tmp, large data dirs detected in discovery + +Write to `${PROJECT_ROOT}/.claudeignore`. --- -## PHASE 5b — .gitignore SAFETY CHECK +## PHASE 4 — .gitignore SAFETY CHECK ```bash -ls .gitignore 2>/dev/null -grep 'settings.local.json' .gitignore 2>/dev/null || echo "not found" +test -f ${PROJECT_ROOT}/.gitignore && echo "exists" || echo "absent" +grep -q 'settings.local.json' ${PROJECT_ROOT}/.gitignore 2>/dev/null && echo "has-entry" || echo "no-entry" ``` -- **`.gitignore` exists AND contains `settings.local.json`** → nothing to do. ✅ -- **`.gitignore` exists but does NOT contain `settings.local.json`** → - Append to existing `.gitignore`: +- **`.gitignore` exists AND contains `settings.local.json`** → nothing to do. +- **`.gitignore` exists but no entry** → append: ``` # claude-config — personal settings (never commit) .claude/settings.local.json ``` - Print: "📝 Added .claude/settings.local.json to existing .gitignore" -- **`.gitignore` absent** → create a minimal one: +- **`.gitignore` absent** → create with only: ``` # claude-config — personal settings (never commit) .claude/settings.local.json ``` - Print: "📝 Created .gitignore with .claude/settings.local.json entry" - -Target path for `.gitignore` check depends on the mode: -- **Single project / Option A**: check and update `/.gitignore` -- **Option B**: check and update `/.gitignore` -- **Option C** (sequential): run this check for each package in its own `/.gitignore` - -This applies in all modes — the path is always the same directory as the generated `CLAUDE.md`. --- -## PHASE 5c — tasks/ scaffold +## PHASE 5 — tasks/ scaffold ```bash -ls tasks/LESSONS.md tasks/TODO.md 2>/dev/null +ls ${PROJECT_ROOT}/tasks/LESSONS.md ${PROJECT_ROOT}/tasks/TODO.md 2>/dev/null ``` -- **Both exist** → nothing to do. ✅ -- **tasks/TODO.md missing** → create it with: -``` +- **tasks/TODO.md missing** → create with header: + ``` # TODO -``` -- **tasks/LESSONS.md missing** → create it with: -``` + ``` +- **tasks/LESSONS.md missing** → create with header: + ``` # Lessons learned -``` -- Print: "📋 tasks/TODO.md and tasks/LESSONS.md ready." + ``` -Applies in all modes (single project, Option A, B, C). Path = same directory as generated `CLAUDE.md`. +**Do NOT overwrite existing content.** --- -## PHASE 6 — GSD v2 ROADMAP (optional) +## PHASE 6 — GSD v2 ROADMAP (optional, per orchestrator flag) -Ask: "Generate a GSD v2 ROADMAP.md for multi-session feature management? (yes / skip)" +Only if BRIEF has `generate_roadmap: true` : +- Check `command -v gsd` +- Generate `${PROJECT_ROOT}/ROADMAP.md` with milestones inferred from BRIEF +- If `gsd` not in PATH: print "⚠️ GSD v2 not installed — ROADMAP generated, install with `npm install -g gsd-pi` to use" -If yes: -- **First check: `command -v gsd`** - - If NOT found: print "⚠️ GSD v2 not installed — run: `npm install -g gsd-pi` - ROADMAP.md will be generated but `gsd init` cannot run now. - After installing: run `gsd` in your terminal → `/gsd auto`." - Generate ROADMAP.md anyway (it will be ready when GSD is installed). - - If found: generate ROADMAP.md then print "✅ Run `gsd` in terminal → `/gsd auto` to start." -- Read CLAUDE.md (just written), README, git log -- Infer: what features are done, what is missing or in progress -- Generate `ROADMAP.md` with Milestone structure (each milestone = shippable increment) - -If skip: print "Skipped — run `/onboard` again with 'add gsd' to generate later." +If `generate_roadmap: false` → skip. --- ## OUTPUT ``` -ONBOARD COMPLETE: -STACK : +ONBOARDER COMPLETE +PROJECT_ROOT : +ARCHETYPE : FILES WRITTEN: ✅ CLAUDE.md ✅ .claude/settings.json ✅ .claudeignore - [✅ ROADMAP.md] (if GSD v2 selected) -COMMANDS : -EXCEPTIONS : -NEXT STEPS : - 1. Review CLAUDE.md — correct any wrong inferences - 2. bash ~/.claude/link.sh — verify symlinks OK - 3. /plugin-check "" — configure plugins - 4. /ship-feature "" — start working + ✅ .gitignore (created | updated | unchanged) + ✅ tasks/TODO.md (created | unchanged) + ✅ tasks/LESSONS.md (created | unchanged) + [✅ ROADMAP.md] (if generate_roadmap) ``` + +--- + +## RULES +- NO interview (handled upstream). +- NO audit (handled downstream by orchestrator). +- NO destructive writes: never overwrite CLAUDE.md if it exists without asking (print path + STOP, let orchestrator decide). +- Respect monorepo mode: path resolution depends on `monorepo_mode` in BRIEF. +- If any BRIEF key is missing, STOP and report — do not guess. diff --git a/skills/onboard/SKILL.md b/skills/onboard/SKILL.md index 581532a..9984419 100644 --- a/skills/onboard/SKILL.md +++ b/skills/onboard/SKILL.md @@ -1,15 +1,848 @@ --- name: onboard -description: Onboard an existing project into claude-config — generates CLAUDE.md, settings, .claudeignore, optional GSD v2 ROADMAP. Use on repos not created via /init-project. -argument-hint: [optional hints: "Python FastAPI" | "add gsd" | "Next.js monorepo"] +description: Onboard an existing project — detects archetype, installs claude-config, runs full audit (dette/SEO-GEO/UI-UX/perf/sécu/a11y/doc), produces improvement plan in ./tasks/. Use on repos not created via /init-project. +argument-hint: [optional hints: "Python FastAPI" | "add gsd" | "Next.js monorepo" | "force-archetype:wordpress"] disable-model-invocation: true allowed-tools: Read, Write, Edit, Bash, Glob, Grep --- -Load and follow strictly: -- $HOME/.claude/agents/onboarder.md +# ORCHESTRATOR: ONBOARD -Run the ONBOARDER agent on the current working directory. - -Additional hints from user (if any): +## REQUEST $ARGUMENTS + +--- + +## STEP 0 — PLUGIN CHECK + AUTO-ACTIVATE + +Load `$HOME/.claude/agents/plugin-advisor.md` with hint "onboarding existing project + $ARGUMENTS". + +- ACTION REQUIRED → show RECOMMENDATIONS block, offer: A) apply recos B) type "force". STOP. +- PROPOSED CHANGES exist → show list, ask "Apply? (yes / no / customize)". Apply on confirm. +- OK → `✅ Plugin check passed — [active plugins] — complexity: %`, continue. + +Complexity score is carried forward for STEP 4 graphify decision. + +--- + +## STEP 1 — ARCHETYPE DETECTION + +Load `$HOME/.claude/lib/archetype-detector.md`. Apply algorithm on current working directory. + +**If user passed `force-archetype:` in $ARGUMENTS** → skip detection, use that archetype, print `🎯 Archetype forcé : `. Verify `~/.claude/lib/project-archetypes/.md` exists, else STOP with error. + +Otherwise: +- Scan filesystem for signals (respect counter-signals / exclusions). +- Score each archetype in `~/.claude/lib/project-archetypes/*.md` (hors `_TEMPLATE.md`). +- Apply selection rules from `archetype-detector.md`. + +**Output format:** +``` +ARCHETYPE DETECTION +Top scores: + 1. XX/YY (zz%) — strong:N, medium:N, weak:N [SELECTED | AMBIGUOUS] + 2. ... + +SELECTED: (confiance: HAUTE | MOYENNE | BASSE) +``` + +**Cases:** +- SELECTED HAUTE → continue STEP 2 avec l'archétype. +- SELECTED MOYENNE → afficher "⚠️ Confiance moyenne — confirmez ? (yes / switch to / describe manually)". STOP. +- AMBIGUOUS → présenter options A/B/C/D comme dans `archetype-detector.md`. STOP. +- UNKNOWN → présenter questions manuelles (type de projet, public/interne, DB, stack). STOP. + +**Afficher les implications auto-appliquées** de l'archétype : +``` +IMPLICATIONS (auto depuis archétype ): + - public : true | false + - database : required | optional | none + - audit_stack : [analyze, code-clean, seo, design-review, perf, cso, a11y, doc] + - plugins : context7=, ui-ux-pro-max=, gstack= +``` + +**Si archétype a un bloc d'avertissement spécifique** (ex: react-spa en public → avertissement SEO) : **l'afficher en pleine largeur**, demander confirmation ou exploration migration. Stocker la réponse pour STEP 7. + +--- + +## STEP 1b — MONOREPO GATE + +Si filesystem scan détecte un monorepo (plugin-advisor signal OR `apps/`+`packages/`+workspace config) : +``` +MONOREPO DETECTED +Packages found: [list] +Options: + A) Onboard entire workspace (one CLAUDE.md at root) + B) Onboard a specific package (cd into it) + C) Onboard each package separately (sequential) +Choice? (A / B / C) +``` +STOP. La réponse détermine si STEP 1 tourne une fois (A) ou N fois (C) ou avec un PROJECT_ROOT différent (B). + +--- + +## STEP 2 — BASELINE CONFIG (onboarder agent) + +Load `$HOME/.claude/agents/onboarder.md`. Passer un BRIEF minimal issu du filesystem scan : +- `archetype` (depuis STEP 1) +- `project_name` (depuis package.json/pyproject.toml/README.md/dir name) +- `stack` (depuis manifests détectés) +- `purpose` (depuis README.md première section) +- `build_cmd`, `test_cmd`, `lint_cmd` (depuis package.json scripts / Makefile / README) +- Les champs manquants à ce stade restent `null` — STEP 3 les remplira via interview + +L'agent génère : +- `CLAUDE.md` (brouillon — à raffiner après STEP 3) +- `.claude/settings.json` +- `.claudeignore` +- `.gitignore` (safety check) +- `tasks/TODO.md`, `tasks/LESSONS.md` +- **Pas encore** `ROADMAP.md` (décision STEP 9) + +Si `CLAUDE.md` existe déjà : lire son contenu, ne PAS écraser — fusionner après STEP 3. + +--- + +## STEP 3 — DEEP INTERVIEW + +L'orchestrateur pilote directement l'interview (l'agent `interviewer.md` est laissé pour `/init-project` où le BRIEF format est attendu ; ici on reste en markdown libre dans la CLAUDE.md). + +Source des questions : +- **3a** — set minimum business (hardcodé ci-dessous, toujours posé sauf si déjà connu) +- **3b** — bloc `## Interview questions (adaptive)` du fichier `~/.claude/lib/project-archetypes/.md` + +### 3a — Set minimum business (toujours posé sauf si déjà trouvé dans README/CLAUDE.md existant) +1. Users cibles / persona principal ? +2. Stade projet ? (prototype / bêta / prod / maintenance) +3. Deadlines clés ? (MVP, release, audit externe) +4. Taille équipe + rôles ? +5. Contraintes légales ? (RGPD, RGAA a11y, HIPAA, autres) +6. Budget perfs ? (TTI cible, taille bundle, contraintes hébergement) + +### 3b — Questions adaptatives par archétype +Charger le bloc `## Interview questions (adaptive)` depuis `~/.claude/lib/project-archetypes/.md`. Poser uniquement ce qui n'est pas déjà connu. + +### 3c — Filtrage +Ne pas redemander ce qui est déjà dans : +- README.md +- package.json / pyproject.toml / Cargo.toml +- Un CLAUDE.md existant +- Les réponses STEP 1 / 1b + +Présenter toutes les questions en UN BLOC. Attendre les réponses. STOP. + +Après réponses : **mettre à jour le brouillon CLAUDE.md** avec les infos obtenues. + +--- + +## STEP 3.5 — CTX7 DOC AUDIT (avant graphify) + +Vérifier que le projet a les docs de ses fast-libs accessibles. + +```bash +command -v ctx7 &>/dev/null && ctx7 --version 2>/dev/null | head -1 || echo "ctx7-not-installed" +ls .ctx7-cache/ 2>/dev/null +``` + +### Détection fast-libs +Parse manifests selon l'archétype : +- **nextjs-app-router** → chercher : next, react, prisma, @supabase/*, drizzle-orm, next-auth, @clerk/* +- **react-spa** → chercher : react, @tanstack/*, zustand, jotai +- **rest-api-node** → chercher : fastify, @nestjs/*, prisma, drizzle-orm +- **rest-api-python** → chercher : fastapi, pydantic, sqlalchemy (si ≥ 2.0) +- **astro-static** → chercher : astro, @astrojs/* +- **wordpress / cli-tool / library / dotfiles-meta / static-html** → souvent aucune fast-lib, audit léger + +### Vérification cache +Pour chaque fast-lib détectée : +1. Existe un fichier `.ctx7-cache/.md` ? +2. Fraîcheur < 7 jours ? + +### Actions +- **ctx7 installé + fast-libs détectées + cache manquant/obsolète** → proposer : + ``` + 📚 DOC AUDIT ctx7 + Fast-libs détectées : [liste] + Cache manquant/obsolète : [liste] + + Pré-fetcher les docs maintenant ? (yes / skip) + ``` + Si yes : + ```bash + mkdir -p .ctx7-cache + ctx7 docs /vercel/next.js "app router middleware routing" > .ctx7-cache/nextjs-core.md + # ... pour chaque lib détectée + ``` + Ajouter `.ctx7-cache/` au `.gitignore` si absent. + +- **ctx7 non installé MAIS fast-libs détectées** → WARN : + ``` + ⚠️ ctx7 non installé — risque de code utilisant des APIs obsolètes + sur : [liste fast-libs] + Install : `npm install -g ctx7 && ctx7 setup --claude` + Ou continuer sans (non recommandé pour fast-libs). + ``` + Demander : `yes install now / continue without / skip audit`. + +- **Pas de fast-lib** → skip silencieusement. + +--- + +## STEP 4 — GRAPHIFY (si complexity ≥ 30% et pas déjà présent) + +```bash +command -v graphify &>/dev/null && echo "available" || echo "not-installed" +test -f graphify-out/GRAPH_REPORT.md && echo "graph-exists" +``` + +- **Pas installé** → skip avec message : `graphify non installé — skip audit architectural. Install : (voir graphify/SKILL.md)` +- **Complexity < 30%** → skip silencieusement, projet trop petit pour justifier. +- **Graphe déjà présent + récent** (fichier < 7j) → skip, réutiliser l'existant. +- **Sinon** → run : + ```bash + graphify . --output graphify-out 2>&1 | tail -20 + ``` + Puis `test -f graphify-out/GRAPH_REPORT.md` pour valider. + +Print : `🔗 Knowledge graph : graphify-out/GRAPH_REPORT.md (N nodes, M edges)`. + +--- + +## STEP 4.5 — AUDIT WORKSPACE + +Créer le dossier transitoire `.onboard-audit/` à la racine projet : + +```bash +mkdir -p .onboard-audit +# Gitignore (ajout idempotent) +grep -q '^\.onboard-audit/' .gitignore 2>/dev/null || \ + printf '\n# onboard audit raw outputs (consumed by /onboard STEP 7)\n.onboard-audit/\n' >> .gitignore +``` + +Ce dossier contient les sorties brutes des audits (L3a+L3b). STEP 7 (L4) les synthétise vers `tasks/`. Peut être supprimé après L4 sans perte. + +--- + +## STEP 5 — ANALYZE (read-only, general) + +Spawn un subagent analyzer (isolé, pas de partage de contexte) : + +``` +Agent( + subagent_type="analyzer", + description="Onboard — deep read-only analysis", + prompt=""" + Read-only factual analysis of the project at . + ARCHETYPE context: . + Focus areas (ordered) : + 1. Architecture risks (fragile couplings, missing abstractions, cycles) + 2. Dette technique visible (TODO/FIXME/HACK markers, commented code, god files) + 3. Patterns utilisés (bons et mauvais) — cite fichier:ligne + 4. Stale code suspects (last modified > 2 ans, no refs) + 5. Test coverage visible (quels modules testés, lesquels aveugles) + 6. Config drift (multiple configs pour même chose, values en dur) + NO solutions. NO code changes. NO write outside the report. + Write the report to `/.onboard-audit/analyze.md` with sections: + ## Summary (3 bullet points) + ## Architecture risks + ## Dette technique + ## Patterns (good + bad) + ## Stale code suspects + ## Test coverage blind spots + ## Config drift + ## Cross-references (vers graphify-out/GRAPH_REPORT.md si présent) + Max 500 lignes. Priorise les éléments avec preuve concrète (fichier:ligne). + """ +) +``` + +Attendre la fin. Vérifier que `.onboard-audit/analyze.md` existe et est non vide. + +--- + +## STEP 6 — AUDIT DISPATCH selon archétype + +Lire le bloc `audit_stack:` du fichier `~/.claude/lib/project-archetypes/.md`. + +**Mapping audit_stack entry → action :** + +| Entry | Action | Livraison | +|---|---|---| +| `analyze` | Déjà fait en STEP 5 | L3a | +| `code-clean` | Spawn subagent `code-cleaner` (audit-only) | L3a | +| `cso` | Si gstack ON → Skill(cso). Sinon → Agent general-purpose avec checklist OWASP + deps audit | L3a | +| `doc` | Spawn subagent `doc-syncer` (auto-mode OFF, report-only) | L3a | +| `seo` | Subagents seo-analyzer + geo-analyzer en parallèle | L3b | +| `design-review` | Si gstack ON → Skill design-review. Sinon → Agent ui-ux-pro-max context statique | L3b | +| `perf` | Si gstack ON + URL → Lighthouse. Sinon → static bundle audit | L3b | +| `a11y` | Si gstack ON + URL → axe-core. Sinon → Agent static a11y audit | L3b | + +### STEP 6 dispatch (L3a portion) + +Lancer EN PARALLÈLE (un seul message, plusieurs Agent calls) les audits correspondant aux entrées de `audit_stack:` qui sont en L3a (`code-clean`, `cso`, `doc`). + +#### Dispatch code-cleaner (si `code-clean` dans audit_stack) +``` +Agent( + subagent_type="code-cleaner", + description="Onboard — code-clean audit only", + prompt=""" + AUDIT-ONLY mode — NO fixes, NO refactoring, NO file modifications. + Target: . ARCHETYPE: . + Produce a report covering: + 1. Dead code (unused exports, unreachable branches, commented-out blocks) + 2. Style violations (per project linter config if present, else per global CLAUDE.md rules) + 3. Structural issues (god files, overly deep nesting, poor separation of concerns) + 4. Stale imports / unused deps (package.json vs actual imports, pyproject.toml vs imports) + 5. Duplicate code (copy-paste patterns) + 6. Outdated deps (if manifest present — list; do NOT run npm audit unless safe) + Write the report to `/.onboard-audit/code-clean.md` with sections matching above. + Each issue cite fichier:ligne. Prioritise par Sévérité (Critique/Haute/Moyenne/Basse). + Max 500 lignes. Do NOT spawn sub-subagents (refactorer). Pure audit. + """ +) +``` + +#### Dispatch security — `cso` (si `cso` dans audit_stack) + +**Décision selon plugin state :** +```bash +# gstack actif ? +bash $HOME/.claude/lib/toggle-external.sh list 2>/dev/null | grep -E "^gstack\s+(enabled|on)" +``` + +- **gstack ON** → invoquer le skill cso via Skill tool : + ``` + Skill(skill="cso", args="comprehensive --report-only --output .onboard-audit/cso.md") + ``` + Note : le skill cso écrit son rapport lui-même ; on redirige via `--output` si supporté, sinon on capture la sortie et on écrit `.onboard-audit/cso.md` dans le skill parent. + +- **gstack OFF** → fallback via Agent general-purpose : + ``` + Agent( + subagent_type="general-purpose", + description="Onboard — security audit fallback", + prompt=""" + READ-ONLY security audit. No file modifications. + Target: . ARCHETYPE: . Stack: . + Coverage (OWASP-aligned + supply chain): + 1. Secrets in repo (git grep for API_KEY, TOKEN, PASSWORD, .env committed) + 2. Dependencies with known vulns (npm audit / pip-audit / cargo audit if available, non-destructive) + 3. SQL injection risks (string-concat queries — grep for 'SELECT.*\\+' patterns) + 4. XSS risks (dangerouslySetInnerHTML, v-html, innerHTML, template render unsanitized) + 5. Authentication (hardcoded tokens, weak hash, missing rate limits) + 6. CORS / CSP misconfig + 7. Outdated runtime (Node <18, Python <3.9, PHP <8.1, etc.) + 8. .env.example exists? .env committed? + 9. Missing SECURITY.md + 10. Docker image base (scratch vs latest vs pinned) if Dockerfile present + Write report to `/.onboard-audit/cso.md` with sections above, + each issue cite fichier:ligne, sévérité Critique/Haute/Moyenne/Basse. + Note en haut du rapport : "FALLBACK MODE — gstack cso skill not active, coverage limited." + Max 500 lignes. + """ + ) + ``` + +#### Dispatch doc-syncer (si `doc` dans audit_stack) +``` +Agent( + subagent_type="doc-syncer", + description="Onboard — doc drift audit only", + prompt=""" + REPORT-ONLY mode — NO edits, NO auto-sync. + Target: full project at . + Scope: + 1. README drift (build/test commands, install steps, usage examples vs actual code) + 2. CLAUDE.md drift (stack versions, commands) + 3. CHANGELOG.md freshness (last entry vs last commit date) + 4. INSTALL/CONFIGURE/USAGE/CONTRIBUTING drift if present + 5. Feature delta (feature added in code but not documented, feature documented but removed) + 6. Inline comments (JSDoc/docstring/rustdoc/godoc) coverage for public API + Cross-reference with git log last 6 months. + Write report to `/.onboard-audit/doc.md` with sections above, + each drift cite file:line + commit-hash + date. + Max 500 lignes. + """ +) +``` + +### Après les 3 dispatches + +Attendre la fin des 3 subagents. Vérifier que les 3 fichiers existent et sont non vides : +```bash +for f in .onboard-audit/{code-clean,cso,doc}.md; do + [ -s "$f" ] && echo "OK $f" || echo "MISSING $f" +done +``` + +Si un subagent a échoué : afficher l'erreur, proposer à l'utilisateur : +``` +⚠️ Audit a échoué : +Options : + A) Retry + B) Skip et continuer (rapport partiel en L4) + C) Abort onboard +``` + +### STEP 6 dispatch (L3b portion) — seo/geo + design + perf + a11y + +Pré-check ressources navigateur : +```bash +# gstack actif ? +bash $HOME/.claude/lib/toggle-external.sh list 2>/dev/null | grep -E "^gstack\s+(enabled|on)" +# URL déployée fournie par l'utilisateur en STEP 3 ? +echo "${BRIEF_deployed_url:-none}" +# dev server launchable ? +grep -E '"(dev|start|serve)":' package.json 2>/dev/null | head -3 +``` + +Lancer EN PARALLÈLE les audits présents dans `audit_stack:` de l'archétype (multiples Agent calls dans un seul message) : + +#### Dispatch SEO+GEO (si `seo` dans audit_stack) + +Le skill `/seo` appelle déjà seo-analyzer + geo-analyzer en parallèle, mais pour garder la cohérence "tout dans `.onboard-audit/`", on invoque les deux agents directement : + +``` +Agent( + subagent_type="seo-analyzer", + description="Onboard — SEO audit (classical engines)", + prompt=""" + AUDIT-ONLY mode — NO edits, NO auto-fixes. Target: . + Classical search engines: Google, Bing, DuckDuckGo. + Archetype: . Public: . Deployed URL (si fournie): . + Coverage: + - meta (title, description, OG, Twitter Card) + - robots.txt, sitemap.xml, canonical, hreflang + - JSON-LD / Schema.org classical + - Core Web Vitals (estimé si pas d'URL live) + - headings hierarchy, alt attrs, images formats + - i18n / lang attribute + Si URL live fournie AND gstack actif: utiliser les outils live. + Sinon: audit statique sur le code (HTML templates, Astro pages, Next Metadata API, etc.). + Write report to `/.onboard-audit/seo.md`. + Structure sections par catégorie, chaque issue cite fichier:ligne + sévérité. + Max 500 lignes. + """ +) + +Agent( + subagent_type="geo-analyzer", + description="Onboard — GEO audit (AI engines)", + prompt=""" + AUDIT-ONLY mode — NO edits, NO auto-fixes. Target: . + AI search engines: ChatGPT, Perplexity, Claude, Gemini, Google AI Overviews, Copilot. + Archetype: . Public: . Deployed URL: . + Coverage: + - AI crawler directives in robots.txt (GPTBot, ClaudeBot, PerplexityBot, etc.) + - llms.txt / llms-full.txt presence and quality + - Schema.org types GEO-optimised (QAPage, Speakable, HowTo, Person+Article, Organization graph) + - Entity SEO (Wikidata QID, sameAs, @id consistency, Knowledge Panel signals) + - Content shape for LLM extraction (Definition Lead, TL;DR, Q→A structure, citable stats, freshness) + - AI visibility monitoring recommendations + Write report to `/.onboard-audit/geo.md`. + Max 500 lignes. Cite fichier:ligne, sévérité. + """ +) +``` + +**SEO+GEO skip rules:** +- Si archetype.public == false ET `seo` dans audit_stack → ne devrait pas arriver, mais si oui : skip silencieusement, `.onboard-audit/seo.md` et `geo.md` non créés. +- Si projet a 0 contenu HTML/template (ex: React SPA public) → lancer quand même mais signaler en haut du rapport : "⚠️ SPA détectée — SEO intrinsèquement limité, voir archetype warning dans .onboard-audit/archetype-warnings.md". + +#### Dispatch design-review (si `design-review` dans audit_stack) + +**Cas gstack ON + URL live OU dev server launchable :** +``` +Skill( + skill="gstack:design-review", + args="--url --output .onboard-audit/design.md --audit-only" +) +``` +Si le skill ne supporte pas `--output`, capturer la sortie et écrire à la main vers `.onboard-audit/design.md`. + +**Cas gstack OFF OU pas de site déployable (ex: react-spa sans dev server):** +``` +Agent( + subagent_type="general-purpose", + description="Onboard — static design review fallback", + prompt=""" + AUDIT-ONLY mode — NO edits. Static design review du code UI. + Target: . Archetype: . + Context: ui-ux-pro-max plugin state = . + Si ui-ux-pro-max actif : lire ses guidelines depuis les skills ui-ux-pro-max. + Coverage (static, depuis code uniquement) : + 1. Design system (tokens : colors, spacing, radius, typography) — présent ou absent ? + Cohérence : toutes les couleurs sont-elles dans les tokens ou hardcodées dans les composants ? + 2. Composants réutilisables vs duplication (Button en 5 variantes dispersées ?) + 3. Dark mode support ? Responsive (breakpoints) ? État de l'a11y dans les composants ? + 4. Animations (présence, durées < 300ms, ease-out par défaut — cf. emil-design-eng si actif) + 5. État vide / loading / error dans les composants + 6. Typography hiérarchie (combien de tailles différentes ? trop ?) + 7. Couleurs : contrastes ratio (AA minimum = 4.5:1 pour texte) + 8. Interactions : focus visible, hover states, disabled states + 9. Micro-interactions (billboard design ? transform scale(0.97) on :active ?) + Write report to `/.onboard-audit/design.md`. + Note en haut : "STATIC MODE — gstack inactif ou pas de dev server ; audit limité au code." + Max 500 lignes. Cite fichier:ligne. + """ +) +``` + +**Skip rules:** +- Si `design-review` pas dans audit_stack (backend, CLI, lib) → skip silencieusement. +- Si archetype frontend mais pas de composants détectés (tout HTML pur) → noter "pure HTML — design review réduit aux sections 3-8". + +#### Dispatch perf (si `perf` dans audit_stack) + +**Cas gstack ON + URL live :** +``` +Skill( + skill="gstack:browse", + args="--lighthouse --url --output .onboard-audit/perf-lighthouse.json" +) +``` +Puis parser le JSON Lighthouse (scores perf/a11y/bp/seo/pwa + top opportunities) → écrire `.onboard-audit/perf.md`. + +**Cas gstack OFF OU pas d'URL :** +``` +Agent( + subagent_type="general-purpose", + description="Onboard — static perf audit", + prompt=""" + AUDIT-ONLY mode — NO edits. + Target: . Archetype: . + Static perf audit (pas de browser) : + 1. Bundle analyzers config présent ? + - Next: `@next/bundle-analyzer` dans deps ? + - Vite: `rollup-plugin-visualizer` ? + - Webpack: `webpack-bundle-analyzer` ? + Si NON, recommander l'install + usage. + Si OUI et script existe, tenter execution NON-DESTRUCTIVE si safe (produit un HTML/rapport, pas de modif code). + 2. Dependencies taille — identifier les grosses deps (> 100kb) depuis package-lock.json / pnpm-lock.yaml. + 3. Images dans `public/` ou `assets/` : compter non-optimisées (PNG/JPG > 200kb sans WebP/AVIF variant). + 4. Polices web : Google Fonts via (blocking) vs self-hosted ? font-display: swap ? + 5. Code splitting : dynamic imports () présents ? Chaque route a son chunk ? + 6. Lazy loading : `loading="lazy"` sur les ? IntersectionObserver pour composants lourds ? + 7. React-specific: React.memo / useMemo / useCallback overuse ou sous-utilisé ? + 8. CSS: quantité totale, CSS-in-JS runtime cost, unused CSS ? + 9. SSR/SSG/ISR strategy (si Next/Astro) — cohérente avec le contenu ? + 10. Core Web Vitals estimés à partir du code (TTFB impossible, mais LCP/CLS inférables). + Write report to `/.onboard-audit/perf.md`. + Note "STATIC MODE" si sans browser. + Max 500 lignes. + """ +) +``` + +#### Dispatch a11y (si `a11y` dans audit_stack) + +**Cas gstack ON + URL live :** +``` +Skill( + skill="gstack:browse", + args="--axe --url --output .onboard-audit/a11y-axe.json" +) +``` +Parser axe-core résultats (violations, incomplete, inapplicable, passes) → `.onboard-audit/a11y.md`. + +**Cas statique :** +``` +Agent( + subagent_type="general-purpose", + description="Onboard — static a11y audit", + prompt=""" + AUDIT-ONLY mode — NO edits. + Target: . Archetype: . + Static a11y audit (WCAG 2.1 AA + RGAA 4.1 France) : + 1. présent sur toutes les pages ? + 2. Landmarks (header/nav/main/footer/aside) utilisés ou encore div-soup ? + 3. Heading hierarchy (h1 unique, pas de saut h1→h3) — scanner tous les templates. + 4. Images : ont tous un alt ? alt décoratif = "" ? alt redondant avec caption ? + 5. Formulaires : chaque a un