---
name: app-init
description: First-time APP project architecture initialization. Guides downstream projects to define their tech stack, conventions, and domain-specific skills.
tasks:
  - app-init
---

# /app-init

> Triggered once per downstream project — when the brain is deployed but no project-level ADR exists yet.

## 0. Detection (Called from /bootstrap)

This workflow is triggered when `/bootstrap` Step 1 detects:
- `docs/adr/` contains NO project-specific ADR
- AND the task is NOT a `tiny-fix`

Bootstrap outputs: `"🏗️ New project detected — no architecture ADR found. Running /app-init to establish project conventions before proceeding."`

If the user declines, record in Work Log: `"App-init skipped by user"` and proceed with normal bootstrap. The detection will trigger again on next non-tiny-fix bootstrap until an ADR is created.

---

## 1. Tech Stack Discovery

Ask the user ONE batched question set (max 5 questions). Do NOT ask one at a time:

```
🏗️ Let's set up your project architecture. Please answer these:

1. **Project type**: Web app / Mobile app / Full-stack / API-only / Other?
2. **Frontend**: React / Vue / Next.js / Flutter / React Native / None / Other?
3. **Backend**: Node.js (Express/Fastify) / Python (FastAPI/Django) / Go / None / Other?
4. **Database**: PostgreSQL / MySQL / MongoDB / SQLite / Supabase / Firebase / Other?
5. **Auth strategy**: JWT / OAuth2 / Session-based / Third-party (Auth0/Clerk/Supabase Auth) / Other?
6. **Official doc URLs**: For your main frameworks/libraries, paste the official doc URLs you'd like the AI to reference (e.g., `https://nextjs.org/docs`). Or type "auto" and I'll use well-known defaults.

(Answer briefly — I'll generate the full ADR for your review.)
```

**Adaptation rules**:
- If user already described their stack in conversation, extract answers from context — do NOT re-ask.
- If user says "not sure yet", use `[TBD]` in ADR and mark for future decision.
- If user provides partial answers, fill what you can and ask ONLY about missing critical items (max 2 follow-up questions).

---

## 2. Generate Project ADR

Create `docs/adr/ADR-001-project-architecture.md` using the template at `.agentcortex/templates/adr-tech-stack.md`.

**Numbering**: If `ADR-001` already exists, increment to next available number.

Fill in all sections from user answers. For `[TBD]` items, include a `## Open Decisions` section listing them.

**SSoT Update (mandatory)**: After writing the ADR file, insert the new ADR into `current_state.md` under the `**ADR Index**` heading. Edit the file directly — find the `**ADR Index**` line and append the new entry immediately below it:

```
- docs/adr/ADR-00N-project-architecture.md: Project Architecture · applies_to: **
```

This is an `/app-init`-specific SSoT write exception (documented alongside the `/retro` exception). It is safe to write directly because `/app-init` runs at session start before any concurrent session is active on the branch.

**Do NOT use `guard_context_write.py` for this write** — that tool supports whole-file replace or end-of-file append only; it has no section-targeting capability. A direct text edit under the heading is the correct and only approach.

**Why mandatory**: `validate.sh` checks ADR disk presence vs. SSoT index. Without this update, every greenfield project fails validation immediately after `/app-init` with `[FAIL] SSoT ADR Index completeness` — before the user has had a chance to run `/ship`.

---

## 3. Generate Domain Skills (Scaffolds)

Based on the tech stack, generate project-specific skill files. These are **scaffolds with sensible defaults** — the user can customize later.

**Skill generation rules**:

| Tech Stack Signal | Skill to Generate | Target Path |
|---|---|---|
| Any backend framework | `api-design` | `.agents/skills/api-design/SKILL.md` |
| Any frontend framework | `frontend-patterns` | `.agents/skills/frontend-patterns/SKILL.md` |
| Any database | `database-design` | `.agents/skills/database-design/SKILL.md` |
| Any auth strategy | `auth-security` | `.agents/skills/auth-security/SKILL.md` |
| Any tech stack chosen (always) | `doc-lookup` | `.agents/skills/doc-lookup/SKILL.md` |

**How to generate**: Use the scaffold minimum structure defined in §5 below as the base. Customize the `## Conventions` section based on the user's specific framework choices from Step 1. Reference the corresponding full SKILL.md at `.agents/skills/<skill-name>/SKILL.md` — if it already contains generic scaffold content (marked with `<!-- This is a SCAFFOLD skill -->`), update its `## Conventions` section with the project-specific decisions. If the SKILL.md doesn't exist yet, create it following the §5 structure.

**`doc-lookup` special handling**:
- **Always generated** — as long as ANY tech stack choice is made (not all `[TBD]`).
- **Existing skill detection**: If `.agents/skills/doc-lookup/SKILL.md` already exists AND is NOT a scaffold (no `<!-- This is a SCAFFOLD skill -->` comment), ask user: `"📚 Existing doc-lookup skill detected. Keep current / Overwrite with framework defaults / Merge?"`. This respects downstream projects that may have already created their own doc-lookup skill.
- Customize `## Doc URL Registry` table: keep ONLY the technologies chosen in Step 1. If user answered "auto" for doc URLs, use the well-known defaults from the scaffold. If user provided custom URLs, use those.
- Add any additional libraries the user mentioned (ORMs, UI libraries, testing frameworks) to the registry.

**Important**: Each generated SKILL.md MUST include a header comment:
```markdown
<!-- Generated by /app-init. Customize for your project. -->
<!-- Framework: [user's choice] | Generated: [date] -->
```

Also create the short summary in `.agent/skills/<skill-name>` (one-line file matching existing pattern).

---

## 4a. Generate Domain Doc Skeletons (AC-7)

Based on the tech stack answers from Step 1, generate Domain Doc L1 skeleton files at `docs/architecture/`. Create `docs/architecture/` if it does not exist.

**Always generate**: `docs/architecture/system-overview.md` (one per project, always).

**Conditional generation** (one per major tech layer chosen):

| Tech Stack Signal | Domain Doc to Generate |
|---|---|
| Auth strategy chosen | `docs/architecture/auth-flow.md` |
| Database chosen | `docs/architecture/data-flow.md` |
| Frontend framework chosen | `docs/architecture/ui-patterns.md` |
| Backend framework chosen | `docs/architecture/api-design.md` |

**Skeleton format** for each generated file:
```markdown
---
status: living
domain: <domain-noun>
created: <YYYY-MM-DD>
last_updated: <YYYY-MM-DD>
---

# <Domain Name> — Layer 1 Synthesis

> This is the current effective design. Written by /app-init. Updated only by /govern-docs --restructure.
> Decision history is in docs/architecture/<domain>.log.md (L2 — append-only).

## Current Design

[TBD] — Populated by /govern-docs --restructure after first /ship consolidation.

## Key Principles

[TBD]

## Constraints

[TBD]
```

**Do NOT generate L2 files** (`.log.md`). L2 is created on first `/ship` knowledge consolidation.

**Downstream-owned after creation**: Framework MUST NOT overwrite these files on re-run. If a file already exists, skip generation and note it in the output summary.

## 4b. Generate Docs Routing Skeleton (AC-2)

Copy `.agentcortex/templates/docs-readme.md` to `docs/README.md`.

**Downstream-owned**: If `docs/README.md` already exists, DO NOT overwrite. Output: `"docs/README.md already exists — skipping file generation. Provide merge-safe retrofit guidance by mapping the existing sections to the standard docs taxonomy headings: Naming Axiom, Retrofit Note, and Document Types & Canonical Paths. Do not delete or regenerate unless the user explicitly asks to replace it."`

## 4c. Generate APP Feature Spec Template

Copy `.agentcortex/templates/spec-app-feature.md` to `.agentcortex/templates/spec-app-feature-<project>.md` (where `<project>` is derived from the repo name or user input).

Customize the template sections based on the tech stack:
- If REST API → include endpoint definition block
- If GraphQL → include query/mutation definition block
- If has frontend → include route + component block
- If has DB → include schema migration block
- **Primary domain**: Set `primary_domain:` to the most relevant domain noun from the generated Domain Doc skeletons.

---

## 5. Skill Scaffold Minimum Structure

Every generated SKILL.md MUST contain at minimum:

```markdown
# <Skill Name>

## When to Apply
[Classification triggers — which task types activate this skill]

## Conventions
[Project-specific conventions derived from ADR]

## Checklist
[Items to verify during /implement and /review]

## Anti-Patterns
[Common mistakes to avoid for this tech stack]

## References
[Link to ADR, external docs, or style guides]
```

---

## 6. Update Spec Intake Awareness

After generating skills, append to `docs/specs/_product-backlog.md` (if exists) or note in `current_state.md`:

```
## Project Skills
- api-design: [framework] conventions
- frontend-patterns: [framework] conventions
- database-design: [database] conventions
- auth-security: [strategy] conventions
- doc-lookup: official doc URLs for [tech list]
```

This allows `/spec-intake` to recommend relevant skills during feature decomposition.

---

## 7. Output & Handoff

**Write Project Name to SSoT (mandatory)**: Before outputting the summary, edit `current_state.md` directly to set the `**Project Name**` field to the project identifier derived in §4c (i.e., the same `<project>` value used in the spec template filename). Find the `- **Project Name**:` line and replace its value:

```
- **Project Name**: <project>
```

This is an `/app-init`-specific SSoT write exception (same scope as the ADR Index write in §2). It is safe to write directly because `/app-init` runs at session start before any concurrent session is active. Do NOT use `guard_context_write.py` — no section-targeting capability.

**Why mandatory**: `/spec-intake §3` reads this field to resolve the project-customized spec template filename (`spec-app-feature-<project>.md`) without a full glob. If this field is absent, every subsequent `/spec-intake` run must fall back to glob search and may silently use the wrong template.

Output a summary:

```
🏗️ App-Init Complete

## Generated Files
1. ADR: docs/adr/ADR-00N-project-architecture.md
2. Skills: [list of generated skill files]
3. Spec Template: .agentcortex/templates/spec-app-feature-<project>.md
4. Domain Docs: [list of docs/architecture/*.md files created or skipped]
5. Docs Routing Skeleton: docs/README.md (created or skipped)

## Tech Stack
- Frontend: [choice]
- Backend: [choice]
- Database: [choice]
- Auth: [choice]

## Doc Lookup
- Official doc URLs configured for: [tech list]
- Skill: .agents/skills/doc-lookup/SKILL.md

## Domain Docs
- Created: [list domain docs created with [TBD] sections]
- Skipped (already exist): [list]
- Note: L2 decision logs are created on first /ship consolidation.

## Open Decisions
- [any TBD items]

## Next Step
Ready to proceed with your original task. Returning to /bootstrap.
```

Then return control to `/bootstrap` §1 (Initialization & Required Reading) with the newly created context available.

---

## 8. Partial Mode (Mid-Development Architecture Decisions)

**Trigger**: `/app-init --partial` from bootstrap §0a, or user explicitly asks to add/update a tech layer mid-project.

**Common scenarios**:
- Project started frontend-only, now adding a backend
- Project had no auth, now needs login
- Database choice was `[TBD]` and now needs to be decided
- User says "我現在要加後端" or "help me set up the API layer"

**Flow**:

1. READ existing ADR (`ADR-00N-project-architecture.md`).
2. Identify which sections are `[TBD]` or missing.
3. If triggered by bootstrap §0a: ask ONLY about the `[TBD]` sections relevant to the current task.
4. If triggered by user intent: ask about the specific layer they mentioned.
5. **Update** the existing ADR (not create a new one) — fill in the `[TBD]` sections.
6. Generate any NEW skills that are now needed (e.g., if backend was added, generate `api-design` and `database-design` skills if they don't exist).
7. If skills already exist but need updating (e.g., database skill exists but DB choice was TBD), update the skill's Conventions section.

**Cost**: Partial mode reads only the existing ADR (~200-400 tokens) + asks 1-3 targeted questions. Much cheaper than full init.

**Output**: Same as §7 but with `[UPDATED]` tags on changed sections.

---

## 9. Re-Run and Manual Trigger Policy

- **Full re-run**: User says "重新設定架構" or "re-init app". AI reads existing ADR, asks what changed, generates a NEW ADR (next number) that supersedes the old one. Old ADR stays as history.
- **Partial update**: User says "加後端", "set up database", "define API conventions", etc. → Partial mode (§8).
- **Add single skill**: User says "新增 skill" or "add skill for X". AI generates just that skill without re-running full app-init.
- **Intent routing**: AGENTS.md Intent-Driven Routing recognizes these patterns:
  - "設定架構", "init app", "define tech stack" → full /app-init
  - "加 [layer]", "set up [layer]", "define [layer] conventions" → /app-init --partial
  - "新增 skill", "add [name] skill" → skill-only generation (§3 only)

---

## 10. Onboard Mode (Existing Repo, Read-Only)

**Trigger**:
- `/app-init --mode=onboard`
- Natural language: "onboard me to this repo", "幫我熟悉這個專案", "what's the state of this project"
- Auto-suggested by `/bootstrap` when a NEW session opens against a repo that already has `current_state.md` AND the user asks "where am I" / "what's going on" without a clear task.

**Hard guarantee**: This mode is **read-only**. It MUST NOT create, modify, or delete any file. Output goes to stdout only.

**Inputs read** (in order, abort early if any is missing):
1. `.agentcortex/context/current_state.md` — Project Intent, ADR Index, Spec Index, Active Backlog, last 3 Ship History entries, Active HIGH Global Lessons.
2. `git log --oneline -10` — recent commit cadence.
3. `.agentcortex/context/work/*.md` (filenames + Header `Current Phase` only — do NOT read full bodies) — open Work Logs.
4. `docs/specs/_product-backlog.md` if present — Pending count by Tier.

**Output template** (terse, ≤ 25 lines):

```
🧭 Repo Onboard — <repo-name>

## Intent
<1-line from current_state.md Project Intent>

## Active Work
- Open Work Logs: <count> (<list of branch names + Current Phase>)
- Most recent ship: <Ship History entry 1, 1-line>

## Backlog Snapshot
- Pending features: <N>  · quick-wins: <N>  · architecture-changes: <N>
- Top 3 by recency or priority: <names>

## Recent Commits (10)
<git log oneline>

## Live Lessons (HIGH severity, capped at 5)
<bullet list — read from current_state.md Global Lessons §HIGH>

## Where to Start
- For new contributor: read AGENTS.md (loaded every turn) → engineering_guardrails.md (when classification ≥ quick-win) → workflows under .agent/workflows/.
- For continuation: pick a Pending row from Backlog Snapshot, run `/spec-intake` (multi-feature) or `/bootstrap` (single).
- For a recap of an open session: `/recap` reads the active Work Log `## Phase Summary` (no extra cost).
```

**Token budget**: ≤ 1,500 tokens of input reads, ≤ 600 tokens of output. Strictly cheaper than re-running full `/bootstrap`.

**Composition with `/recap`**: when the user asks for an open-session recap rather than a repo overview, point them at `/recap` (or do an inline 3-line summary from the active Work Log `## Phase Summary` — no new file).

**No Doc Proliferation**: The summary MUST NOT be saved to `docs/guides/onboarding.md` or any other path. If the user wants a persisted onboarding artifact, escalate to `/govern-docs` — that workflow owns the permanence decision.

## Hard Rules

1. **Never write project code** during app-init. This is a configuration/governance workflow only.
2. **Never assume tech stack** without user input. Even "obvious" choices must be confirmed.
3. **Skills are scaffolds, not laws**. The generated SKILL.md files are starting points. Users own them.
4. **Respect existing ADRs**. If the user already has ADRs from manual creation, do NOT overwrite. Offer to integrate.
5. **Token budget**: App-init is a one-time cost. Aim for < 3 turns total (ask → generate → confirm).
