joycraft 0.4.0 → 0.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +432 -14
- package/dist/chunk-2S7KP7FU.js +36 -0
- package/dist/chunk-2S7KP7FU.js.map +1 -0
- package/dist/chunk-HHW4Q2UC.js +2297 -0
- package/dist/chunk-HHW4Q2UC.js.map +1 -0
- package/dist/cli.js +6 -2
- package/dist/cli.js.map +1 -1
- package/dist/{init-XHJDJIZW.js → init-DHVJEWGX.js} +7 -4
- package/dist/init-DHVJEWGX.js.map +1 -0
- package/dist/init-autofix-OVHXYVLB.js +118 -0
- package/dist/init-autofix-OVHXYVLB.js.map +1 -0
- package/dist/{upgrade-NOHZWQMO.js → upgrade-RN2D5RAT.js} +60 -15
- package/dist/upgrade-RN2D5RAT.js.map +1 -0
- package/package.json +11 -2
- package/dist/chunk-FNGCEYUY.js +0 -1280
- package/dist/chunk-FNGCEYUY.js.map +0 -1
- package/dist/init-XHJDJIZW.js.map +0 -1
- package/dist/upgrade-NOHZWQMO.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/bundled-files.ts"],"sourcesContent":["// Bundled file contents — embedded at build time\n\nexport const SKILLS: Record<string, string> = {\n \"joycraft-decompose.md\": `---\nname: joycraft-decompose\ndescription: Break a feature brief into atomic specs — small, testable, independently executable units\n---\n\n# Decompose Feature into Atomic Specs\n\nYou have a Feature Brief (or the user has described a feature). Your job is to decompose it into atomic specs that can be executed independently — one spec per session.\n\n## Step 1: Verify the Brief Exists\n\nLook for a Feature Brief in \\`docs/briefs/\\`. If one doesn't exist yet, tell the user:\n\n> No feature brief found. Run \\`/joycraft-new-feature\\` first to interview and create one, or describe the feature now and I'll work from your description.\n\nIf the user describes the feature inline, work from that description directly. You don't need a formal brief to decompose — but recommend creating one for complex features.\n\n## Step 2: Identify Natural Boundaries\n\n**Why:** Good boundaries make specs independently testable and committable. Bad boundaries create specs that can't be verified without other specs also being done.\n\nRead the brief (or description) and identify natural split points:\n\n- **Data layer changes** (schemas, types, migrations) — always a separate spec\n- **Pure functions / business logic** — separate from I/O\n- **UI components** — separate from data fetching\n- **API endpoints / route handlers** — separate from business logic\n- **Test infrastructure** (mocks, fixtures, helpers) — can be its own spec if substantial\n- **Configuration / environment** — separate from code changes\n\nAsk yourself: \"Can this piece be committed and tested without the other pieces existing?\" If yes, it's a good boundary.\n\n## Step 3: Build the Decomposition Table\n\nFor each atomic spec, define:\n\n| # | Spec Name | Description | Dependencies | Size |\n|---|-----------|-------------|--------------|------|\n\n**Rules:**\n- Each spec name is \\`verb-object\\` format (e.g., \\`add-terminal-detection\\`, \\`extract-prompt-module\\`)\n- Each description is ONE sentence — if you need two, the spec is too big\n- Dependencies reference other spec numbers — keep the dependency graph shallow\n- More than 2 dependencies on a single spec = it's too big, split further\n- Aim for 3-7 specs per feature. Fewer than 3 = probably not decomposed enough. More than 10 = the feature brief is too big\n\n## Step 4: Present and Iterate\n\nShow the decomposition table to the user. Ask:\n1. \"Does this breakdown match how you think about this feature?\"\n2. \"Are there any specs that feel too big or too small?\"\n3. \"Should any of these run in parallel (separate worktrees)?\"\n\nIterate until the user approves.\n\n## Step 5: Generate Atomic Specs\n\nFor each approved row, create \\`docs/specs/YYYY-MM-DD-spec-name.md\\`. Create the \\`docs/specs/\\` directory if it doesn't exist.\n\n**Why:** Each spec must be self-contained — a fresh Claude session should be able to execute it without reading the Feature Brief. Copy relevant constraints and context into each spec.\n\nUse this structure:\n\n\\`\\`\\`markdown\n# [Verb + Object] — Atomic Spec\n\n> **Parent Brief:** \\`docs/briefs/YYYY-MM-DD-feature-name.md\\` (or \"standalone\")\n> **Status:** Ready\n> **Date:** YYYY-MM-DD\n> **Estimated scope:** [1 session / N files / ~N lines]\n\n---\n\n## What\nOne paragraph — what changes when this spec is done?\n\n## Why\nOne sentence — what breaks or is missing without this?\n\n## Acceptance Criteria\n- [ ] [Observable behavior]\n- [ ] Build passes\n- [ ] Tests pass\n\n## Constraints\n- MUST: [hard requirement]\n- MUST NOT: [hard prohibition]\n\n## Affected Files\n| Action | File | What Changes |\n|--------|------|-------------|\n\n## Approach\nStrategy, data flow, key decisions. Name one rejected alternative.\n\n## Edge Cases\n| Scenario | Expected Behavior |\n|----------|------------------|\n\\`\\`\\`\n\nIf \\`docs/templates/ATOMIC_SPEC_TEMPLATE.md\\` exists, reference it for the full template with additional guidance.\n\nFill in all sections — each spec must be self-contained (no \"see the brief for context\"). Copy relevant constraints from the Feature Brief into each spec. Write acceptance criteria specific to THIS spec, not the whole feature.\n\n## Step 6: Recommend Execution Strategy\n\nBased on the dependency graph:\n- **Independent specs** — \"These can run in parallel worktrees\"\n- **Sequential specs** — \"Execute these in order: 1 -> 2 -> 4\"\n- **Mixed** — \"Start specs 1 and 3 in parallel. After 1 completes, start 2.\"\n\nUpdate the Feature Brief's Execution Strategy section with the plan (if a brief exists).\n\n## Step 7: Hand Off\n\nTell the user:\n\\`\\`\\`\nDecomposition complete:\n- [N] atomic specs created in docs/specs/\n- [N] can run in parallel, [N] are sequential\n- Estimated total: [N] sessions\n\nTo execute:\n- Sequential: Open a session, point Claude at each spec in order\n- Parallel: Use worktrees — one spec per worktree, merge when done\n- Each session should end with /joycraft-session-end to capture discoveries\n\nReady to start execution?\n\\`\\`\\`\n`,\n\n \"joycraft-implement-level5.md\": `---\nname: joycraft-implement-level5\ndescription: Set up Level 5 autonomous development — autofix loop, holdout scenario testing, and scenario evolution from specs\n---\n\n# Implement Level 5 — Autonomous Development Loop\n\nYou are guiding the user through setting up Level 5: the autonomous feedback loop where specs go in, validated software comes out. This is a one-time setup that installs workflows, creates a scenarios repo, and configures the autofix loop.\n\n## Before You Begin\n\nCheck prerequisites:\n\n1. **Project must be initialized.** Look for \\`.joycraft-version\\`. If missing, tell the user to run \\`npx joycraft init\\` first.\n2. **Project should be at Level 4.** Check \\`docs/joycraft-assessment.md\\` if it exists. If the project hasn't been assessed yet, suggest running \\`/joycraft-tune\\` first. But don't block — the user may know they're ready.\n3. **Git repo with GitHub remote.** This setup requires GitHub Actions. Check for \\`.git/\\` and a GitHub remote.\n\nIf prerequisites aren't met, explain what's needed and stop.\n\n## Step 1: Explain What Level 5 Means\n\nTell the user:\n\n> Level 5 is the autonomous loop. When you push specs, three things happen automatically:\n>\n> 1. **Scenario evolution** — A separate AI agent reads your specs and writes holdout tests in a private scenarios repo. These tests are invisible to your coding agent.\n> 2. **Autofix** — When CI fails on a PR, Claude Code automatically attempts a fix (up to 3 times).\n> 3. **Holdout validation** — When CI passes, your scenarios repo runs behavioral tests against the PR. Results post as PR comments.\n>\n> The key insight: your coding agent never sees the scenario tests. This prevents it from gaming the test suite — like a validation set in machine learning.\n\n## Step 2: Gather Configuration\n\nAsk these questions **one at a time**:\n\n### Question 1: Scenarios repo name\n\n> What should we call your scenarios repo? It'll be a private repo that holds your holdout tests.\n>\n> Default: \\`{current-repo-name}-scenarios\\`\n\nAccept the default or the user's choice.\n\n### Question 2: GitHub App\n\n> Level 5 needs a GitHub App to provide a separate identity for autofix pushes (this avoids GitHub's anti-recursion protection).\n>\n> **Option A:** Install the shared Joycraft Autofix app (quickest — 1 click)\n> **Option B:** Create your own GitHub App (more control)\n>\n> Which do you prefer?\n\nIf Option A: The App ID is \\`3180156\\`. Note this for later.\nIf Option B: Guide them to create an app at \\`https://github.com/settings/apps/new\\` with permissions: Contents (Read & Write), Pull Requests (Read & Write), Actions (Read & Write). They'll need the App ID from the settings page.\n\n### Question 3: App ID\n\nIf they chose Option B, ask for their App ID. If Option A, use \\`3180156\\`.\n\n## Step 3: Run init-autofix\n\nRun the CLI command with the gathered configuration:\n\n\\`\\`\\`bash\nnpx joycraft init-autofix --scenarios-repo {name} --app-id {id}\n\\`\\`\\`\n\nReview the output with the user. Confirm files were created.\n\n## Step 4: Walk Through Secret Configuration\n\nGuide the user step by step:\n\n### 4a: GitHub App Private Key\n\n> If you chose the shared Joycraft Autofix app, you'll need to generate a private key:\n> 1. Go to https://github.com/settings/apps/joycraft-autofix\n> 2. Scroll to \"Private keys\" and generate one\n> 3. Download the \\`.pem\\` file\n>\n> If you created your own app, generate a private key from your app's settings page.\n\n### 4b: Add Secrets to Main Repo\n\n> Go to your repo's Settings > Secrets and variables > Actions, and add:\n> - \\`JOYCRAFT_APP_PRIVATE_KEY\\` — paste the contents of your \\`.pem\\` file\n> - \\`ANTHROPIC_API_KEY\\` — your Anthropic API key\n\n### 4c: Install the App\n\n> The GitHub App needs to be installed on your repo:\n> - Shared app: https://github.com/apps/joycraft-autofix/installations/new\n> - Own app: Go to your app's settings > Install App\n\n### 4d: Create the Scenarios Repo\n\n> Create the private scenarios repo:\n> \\`\\`\\`bash\n> gh repo create {scenarios-repo-name} --private\n> \\`\\`\\`\n>\n> Then copy the scenario templates into it:\n> \\`\\`\\`bash\n> cp -r docs/templates/scenarios/* ../{scenarios-repo-name}/\n> cd ../{scenarios-repo-name}\n> git add -A && git commit -m \"init: scaffold scenarios repo from Joycraft\"\n> git push\n> \\`\\`\\`\n\n### 4e: Add Secrets to Scenarios Repo\n\n> The scenarios repo also needs the App private key:\n> - \\`JOYCRAFT_APP_PRIVATE_KEY\\` — same \\`.pem\\` file as the main repo\n> - \\`ANTHROPIC_API_KEY\\` — same key (needed for scenario generation)\n\n## Step 5: Verify Setup\n\nHelp the user verify everything is wired correctly:\n\n1. **Check workflow files exist:** \\`ls .github/workflows/autofix.yml .github/workflows/scenarios-dispatch.yml .github/workflows/spec-dispatch.yml .github/workflows/scenarios-rerun.yml\\`\n2. **Check scenario templates were copied:** Verify the scenarios repo has \\`example-scenario.test.ts\\`, \\`workflows/run.yml\\`, \\`workflows/generate.yml\\`, \\`prompts/scenario-agent.md\\`\n3. **Check the App ID is correct** in the workflow files (not still a placeholder)\n\n## Step 6: Update CLAUDE.md\n\nIf the project's CLAUDE.md doesn't already have an \"External Validation\" section, add one:\n\n> ## External Validation\n>\n> This project uses holdout scenario tests in a separate private repo.\n>\n> ### NEVER\n> - Access, read, or reference the scenarios repo\n> - Mention scenario test names or contents\n> - Modify the scenarios dispatch workflow to leak test information\n>\n> The scenarios repo is deliberately invisible to you. This is the holdout guarantee.\n\n## Step 7: First Test (Optional)\n\nIf the user wants to test the loop:\n\n> Want to do a quick test? Here's how:\n>\n> 1. Write a simple spec in \\`docs/specs/\\` and push to main — this triggers scenario generation\n> 2. Create a PR with a small change — when CI passes, scenarios will run\n> 3. Watch for the scenario test results as a PR comment\n>\n> Or deliberately break something in a PR to test the autofix loop.\n\n## Step 8: Summary\n\nPrint a summary of what was set up:\n\n> **Level 5 is live.** Here's what's running:\n>\n> | Trigger | What Happens |\n> |---------|-------------|\n> | Push specs to \\`docs/specs/\\` | Scenario agent writes holdout tests |\n> | PR fails CI | Claude autofix attempts (up to 3x) |\n> | PR passes CI | Holdout scenarios run against PR |\n> | Scenarios update | Open PRs re-tested with latest scenarios |\n>\n> Your scenarios repo: \\`{name}\\`\n> Your coding agent cannot see those tests. The holdout wall is intact.\n\nUpdate \\`docs/joycraft-assessment.md\\` if it exists — set the Level 5 score to reflect the new setup.\n`,\n\n \"joycraft-interview.md\": `---\nname: joycraft-interview\ndescription: Brainstorm freely about what you want to build — yap, explore ideas, and get a structured summary you can use later\n---\n\n# Interview — Idea Exploration\n\nYou are helping the user brainstorm and explore what they want to build. This is a lightweight, low-pressure conversation — not a formal spec process. Let them yap.\n\n## How to Run the Interview\n\n### 1. Open the Floor\n\nStart with something like:\n\"What are you thinking about building? Just talk — I'll listen and ask questions as we go.\"\n\nLet the user talk freely. Do not interrupt their flow. Do not push toward structure yet.\n\n### 2. Ask Clarifying Questions\n\nAs they talk, weave in questions naturally — don't fire them all at once:\n\n- **What problem does this solve?** Who feels the pain today?\n- **What does \"done\" look like?** If this worked perfectly, what would a user see?\n- **What are the constraints?** Time, tech, team, budget — what boxes are we in?\n- **What's NOT in scope?** What's tempting but should be deferred?\n- **What are the edge cases?** What could go wrong? What's the weird input?\n- **What exists already?** Are we building on something or starting fresh?\n\n### 3. Play Back Understanding\n\nAfter the user has gotten their ideas out, reflect back:\n\"So if I'm hearing you right, you want to [summary]. The core problem is [X], and done looks like [Y]. Is that right?\"\n\nLet them correct and refine. Iterate until they say \"yes, that's it.\"\n\n### 4. Write a Draft Brief\n\nCreate a draft file at \\`docs/briefs/YYYY-MM-DD-topic-draft.md\\`. Create the \\`docs/briefs/\\` directory if it doesn't exist.\n\nUse this format:\n\n\\`\\`\\`markdown\n# [Topic] — Draft Brief\n\n> **Date:** YYYY-MM-DD\n> **Status:** DRAFT\n> **Origin:** /joycraft-interview session\n\n---\n\n## The Idea\n[2-3 paragraphs capturing what the user described — their words, their framing]\n\n## Problem\n[What pain or gap this addresses]\n\n## What \"Done\" Looks Like\n[The user's description of success — observable outcomes]\n\n## Constraints\n- [constraint 1]\n- [constraint 2]\n\n## Open Questions\n- [things that came up but weren't resolved]\n- [decisions that need more thought]\n\n## Out of Scope (for now)\n- [things explicitly deferred]\n\n## Raw Notes\n[Any additional context, quotes, or tangents worth preserving]\n\\`\\`\\`\n\n### 5. Hand Off\n\nAfter writing the draft, tell the user:\n\n\\`\\`\\`\nDraft brief saved to docs/briefs/YYYY-MM-DD-topic-draft.md\n\nWhen you're ready to move forward:\n- /joycraft-new-feature — formalize this into a full Feature Brief with specs\n- /joycraft-decompose — break it directly into atomic specs if scope is clear\n- Or just keep brainstorming — run /joycraft-interview again anytime\n\\`\\`\\`\n\n## Guidelines\n\n- **This is NOT /joycraft-new-feature.** Do not push toward formal briefs, decomposition tables, or atomic specs. The point is exploration.\n- **Let the user lead.** Your job is to listen, clarify, and capture — not to structure or direct.\n- **Mark everything as DRAFT.** The output is a starting point, not a commitment.\n- **Keep it short.** The draft brief should be 1-2 pages max. Capture the essence, not every detail.\n- **Multiple interviews are fine.** The user might run this several times as their thinking evolves. Each creates a new dated draft.\n`,\n\n \"joycraft-new-feature.md\": `---\nname: joycraft-new-feature\ndescription: Guided feature development — interview the user, produce a Feature Brief, then decompose into atomic specs\n---\n\n# New Feature Workflow\n\nYou are starting a new feature. Follow this process in order. Do not skip steps.\n\n## Phase 1: Interview\n\nInterview the user about what they want to build. Let them talk — your job is to listen, then sharpen.\n\n**Why:** A thorough interview prevents wasted implementation time. Most failed features fail because the problem wasn't understood, not because the code was wrong.\n\n**Ask about:**\n- What problem does this solve? Who is affected?\n- What does \"done\" look like? How will a user know this works?\n- What are the hard constraints? (business rules, tech limitations, deadlines)\n- What is explicitly NOT in scope? (push hard on this — aggressive scoping is key)\n- Are there edge cases or error conditions we need to handle?\n- What existing code/patterns should this follow?\n\n**Interview technique:**\n- Let the user \"yap\" — don't interrupt their flow of ideas\n- After they finish, play back your understanding: \"So if I'm hearing you right...\"\n- Ask clarifying questions that force specificity: \"When you say 'handle errors,' what should the user see?\"\n- Push toward testable statements: \"How would we verify that works?\"\n\nKeep asking until you can fill out a Feature Brief. When ready, say:\n\"I have enough context. Let me write the Feature Brief for your review.\"\n\n## Phase 2: Feature Brief\n\nWrite a Feature Brief to \\`docs/briefs/YYYY-MM-DD-feature-name.md\\`. Create the \\`docs/briefs/\\` directory if it doesn't exist.\n\n**Why:** The brief is the single source of truth for what we're building. It prevents scope creep and gives every spec a shared reference point.\n\nUse this structure:\n\n\\`\\`\\`markdown\n# [Feature Name] — Feature Brief\n\n> **Date:** YYYY-MM-DD\n> **Project:** [project name]\n> **Status:** Interview | Decomposing | Specs Ready | In Progress | Complete\n\n---\n\n## Vision\nWhat are we building and why? The full picture in 2-4 paragraphs.\n\n## User Stories\n- As a [role], I want [capability] so that [benefit]\n\n## Hard Constraints\n- MUST: [constraint that every spec must respect]\n- MUST NOT: [prohibition that every spec must respect]\n\n## Out of Scope\n- NOT: [tempting but deferred]\n\n## Decomposition\n| # | Spec Name | Description | Dependencies | Est. Size |\n|---|-----------|-------------|--------------|-----------|\n| 1 | [verb-object] | [one sentence] | None | [S/M/L] |\n\n## Execution Strategy\n- [ ] Sequential (specs have chain dependencies)\n- [ ] Parallel worktrees (specs are independent)\n- [ ] Mixed\n\n## Success Criteria\n- [ ] [End-to-end behavior 1]\n- [ ] [No regressions in existing features]\n\\`\\`\\`\n\nIf \\`docs/templates/FEATURE_BRIEF_TEMPLATE.md\\` exists, reference it for the full template with additional guidance.\n\nPresent the brief to the user. Focus review on:\n- \"Does the decomposition match how you think about this?\"\n- \"Is anything in scope that shouldn't be?\"\n- \"Are the specs small enough? Can each be described in one sentence?\"\n\nIterate until approved.\n\n## Phase 3: Generate Atomic Specs\n\nFor each row in the decomposition table, create a self-contained spec file at \\`docs/specs/YYYY-MM-DD-spec-name.md\\`. Create the \\`docs/specs/\\` directory if it doesn't exist.\n\n**Why:** Each spec must be understandable WITHOUT reading the Feature Brief. This prevents the \"Curse of Instructions\" — no spec should require holding the entire feature in context. Copy relevant context into each spec.\n\nUse this structure for each spec:\n\n\\`\\`\\`markdown\n# [Verb + Object] — Atomic Spec\n\n> **Parent Brief:** \\`docs/briefs/YYYY-MM-DD-feature-name.md\\`\n> **Status:** Ready\n> **Date:** YYYY-MM-DD\n> **Estimated scope:** [1 session / N files / ~N lines]\n\n---\n\n## What\nOne paragraph — what changes when this spec is done?\n\n## Why\nOne sentence — what breaks or is missing without this?\n\n## Acceptance Criteria\n- [ ] [Observable behavior]\n- [ ] Build passes\n- [ ] Tests pass\n\n## Constraints\n- MUST: [hard requirement]\n- MUST NOT: [hard prohibition]\n\n## Affected Files\n| Action | File | What Changes |\n|--------|------|-------------|\n\n## Approach\nStrategy, data flow, key decisions. Name one rejected alternative.\n\n## Edge Cases\n| Scenario | Expected Behavior |\n|----------|------------------|\n\\`\\`\\`\n\nIf \\`docs/templates/ATOMIC_SPEC_TEMPLATE.md\\` exists, reference it for the full template with additional guidance.\n\n## Phase 4: Hand Off for Execution\n\nTell the user:\n\\`\\`\\`\nFeature Brief and [N] atomic specs are ready.\n\nSpecs:\n1. [spec-name] — [one sentence] [S/M/L]\n2. [spec-name] — [one sentence] [S/M/L]\n...\n\nRecommended execution:\n- [Parallel/Sequential/Mixed strategy]\n- Estimated: [N] sessions total\n\nTo execute: Start a fresh session per spec. Each session should:\n1. Read the spec\n2. Implement\n3. Run /joycraft-session-end to capture discoveries\n4. Commit and PR\n\nReady to start?\n\\`\\`\\`\n\n**Why:** A fresh session for execution produces better results. The interview session has too much context noise — a clean session with just the spec is more focused.\n\nYou can also use \\`/joycraft-decompose\\` to re-decompose a brief if the breakdown needs adjustment, or run \\`/joycraft-interview\\` first for a lighter brainstorm before committing to the full workflow.\n`,\n\n \"joycraft-session-end.md\": `---\nname: joycraft-session-end\ndescription: Wrap up a session — capture discoveries, verify, prepare for PR or next session\n---\n\n# Session Wrap-Up\n\nBefore ending this session, complete these steps in order.\n\n## 1. Capture Discoveries\n\n**Why:** Discoveries are the surprises — things that weren't in the spec or that contradicted expectations. They prevent future sessions from hitting the same walls.\n\nCheck: did anything surprising happen during this session? If yes, create or update a discovery file at \\`docs/discoveries/YYYY-MM-DD-topic.md\\`. Create the \\`docs/discoveries/\\` directory if it doesn't exist.\n\nOnly capture what's NOT obvious from the code or git diff:\n- \"We thought X but found Y\" — assumptions that were wrong\n- \"This API/library behaves differently than documented\" — external gotchas\n- \"This edge case needs handling in a future spec\" — deferred work with context\n- \"The approach in the spec didn't work because...\" — spec-vs-reality gaps\n- Key decisions made during implementation that aren't in the spec\n\n**Do NOT capture:**\n- Files changed (that's the diff)\n- What you set out to do (that's the spec)\n- Step-by-step narrative of the session (nobody re-reads these)\n\nUse this format:\n\n\\`\\`\\`markdown\n# Discoveries — [topic]\n\n**Date:** YYYY-MM-DD\n**Spec:** [link to spec if applicable]\n\n## [Discovery title]\n**Expected:** [what we thought would happen]\n**Actual:** [what actually happened]\n**Impact:** [what this means for future work]\n\\`\\`\\`\n\nIf nothing surprising happened, skip the discovery file entirely. No discovery is a good sign — the spec was accurate.\n\n## 1b. Update Context Documents\n\nIf \\`docs/context/\\` exists, quickly check whether this session revealed anything about:\n\n- **Production risks** — did you interact with or learn about production vs staging systems? → Update \\`docs/context/production-map.md\\`\n- **Wrong assumptions** — did the agent (or you) assume something that turned out to be false? → Update \\`docs/context/dangerous-assumptions.md\\`\n- **Key decisions** — did you make an architectural or tooling choice? → Add a row to \\`docs/context/decision-log.md\\`\n- **Unwritten rules** — did you discover a convention or constraint not documented anywhere? → Update \\`docs/context/institutional-knowledge.md\\`\n\nSkip this if nothing applies. Don't force it — only update when there's genuine new context.\n\n## 2. Run Validation\n\nRun the project's validation commands. Check CLAUDE.md for project-specific commands. Common checks:\n\n- Type-check (e.g., \\`tsc --noEmit\\`, \\`mypy\\`, \\`cargo check\\`)\n- Tests (e.g., \\`npm test\\`, \\`pytest\\`, \\`cargo test\\`)\n- Lint (e.g., \\`eslint\\`, \\`ruff\\`, \\`clippy\\`)\n\nFix any failures before proceeding.\n\n## 3. Update Spec Status\n\nIf working from an atomic spec in \\`docs/specs/\\`:\n- All acceptance criteria met — update status to \\`Complete\\`\n- Partially done — update status to \\`In Progress\\`, note what's left\n\nIf working from a Feature Brief in \\`docs/briefs/\\`, check off completed specs in the decomposition table.\n\n## 4. Commit\n\nCommit all changes including the discovery file (if created) and spec status updates. The commit message should reference the spec if applicable.\n\n## 5. Report\n\n\\`\\`\\`\nSession complete.\n- Spec: [spec name] — [Complete / In Progress]\n- Build: [passing / failing]\n- Discoveries: [N items / none]\n- Next: [what the next session should tackle, or \"ready for PR\"]\n\\`\\`\\`\n`,\n\n \"joycraft-tune.md\": `---\nname: joycraft-tune\ndescription: Assess and upgrade your project's AI development harness — score 7 dimensions, apply fixes, show path to Level 5\n---\n\n# Tune — Project Harness Assessment & Upgrade\n\nYou are evaluating and upgrading this project's AI development harness. Follow these steps in order.\n\n## Step 1: Detect Harness State\n\nCheck the following and note what exists:\n\n1. **CLAUDE.md** — Read it if it exists. Check whether it contains meaningful content (not just a project name or generic README).\n2. **Key directories** — Check for: \\`docs/specs/\\`, \\`docs/briefs/\\`, \\`docs/discoveries/\\`, \\`docs/templates/\\`, \\`.claude/skills/\\`\n3. **Boundary framework** — Look for \\`Always\\`, \\`Ask First\\`, and \\`Never\\` sections in CLAUDE.md (or similar behavioral constraints under any heading).\n4. **Skills infrastructure** — Check \\`.claude/skills/\\` for installed skill files.\n5. **Test configuration** — Look for test commands in package.json, pyproject.toml, Cargo.toml, Makefile, or CI config files.\n\n## Step 2: Route Based on State\n\n### If No Harness (no CLAUDE.md, or CLAUDE.md is just a README with no structured sections):\n\nTell the user:\n- Their project has no AI development harness\n- Recommend running \\`npx joycraft init\\` to scaffold one\n- Briefly explain what it sets up: CLAUDE.md with boundaries, spec/brief templates, skills, documentation structure\n- **Stop here** — do not run the full assessment on a bare project\n\n### If Harness Exists (CLAUDE.md has structured content — boundaries, commands, architecture, or domain rules):\n\nContinue to Step 3 for the full assessment.\n\n## Step 3: Score 7 Dimensions\n\nRead CLAUDE.md thoroughly. Explore the project structure. Score each dimension on a 1-5 scale with specific evidence.\n\n### Dimension 1: Spec Quality\n\nLook in \\`docs/specs/\\` for specification files.\n\n| Score | Criteria |\n|-------|----------|\n| 1 | No specs directory or no spec files |\n| 2 | Specs exist but are informal notes or TODOs |\n| 3 | Specs have structure (sections, some criteria) but lack consistency |\n| 4 | Specs are structured with clear acceptance criteria and constraints |\n| 5 | Atomic specs: self-contained, acceptance criteria, constraints, edge cases, affected files |\n\n**Evidence:** Number of specs found, example of best/worst, whether acceptance criteria are present.\n\n### Dimension 2: Spec Granularity\n\nCan each spec be completed in a single coding session?\n\n| Score | Criteria |\n|-------|----------|\n| 1 | No specs |\n| 2 | Specs cover entire features or epics |\n| 3 | Specs are feature-sized (multi-session but bounded) |\n| 4 | Most specs are session-sized with clear scope |\n| 5 | All specs are atomic — one session, one concern, clear done state |\n\n### Dimension 3: Behavioral Boundaries\n\nRead CLAUDE.md for explicit behavioral constraints.\n\n| Score | Criteria |\n|-------|----------|\n| 1 | No CLAUDE.md or no behavioral guidance |\n| 2 | CLAUDE.md exists with general instructions but no structured boundaries |\n| 3 | Some boundaries exist but not organized as Always/Ask First/Never |\n| 4 | Always/Ask First/Never sections present with reasonable coverage |\n| 5 | Comprehensive boundaries covering code style, testing, deployment, dependencies, and dangerous operations |\n\n**Important:** Projects may have strong rules under different headings (e.g., \"Critical Rules\", \"Constraints\"). Give credit for substance over format — a project with clear, enforced rules scores higher than one with empty Always/Ask First/Never sections.\n\n### Dimension 4: Skills & Hooks\n\nLook in \\`.claude/skills/\\` for skill files. Check for hooks configuration.\n\n| Score | Criteria |\n|-------|----------|\n| 1 | No .claude/ directory |\n| 2 | .claude/ exists but empty or minimal |\n| 3 | A few skills installed, no hooks |\n| 4 | Multiple relevant skills, basic hooks |\n| 5 | Comprehensive skills covering workflow, hooks for validation |\n\n### Dimension 5: Documentation\n\nExamine \\`docs/\\` directory structure and content.\n\n| Score | Criteria |\n|-------|----------|\n| 1 | No docs/ directory |\n| 2 | docs/ exists with ad-hoc files |\n| 3 | Some structure (subdirectories) but inconsistent |\n| 4 | Structured docs/ with templates and clear organization |\n| 5 | Full structure: briefs/, specs/, templates/, architecture docs, referenced from CLAUDE.md |\n\n### Dimension 6: Knowledge Capture & Contextual Stewardship\n\nLook for discoveries, decisions, session notes, and context documents.\n\n| Score | Criteria |\n|-------|----------|\n| 1 | No knowledge capture mechanism |\n| 2 | Ad-hoc notes or a discoveries directory with no entries |\n| 3 | Discoveries directory with some entries, or context docs exist but empty |\n| 4 | Active discoveries + at least 2 context docs with content (production-map, dangerous-assumptions, decision-log, institutional-knowledge) |\n| 5 | Full contextual stewardship: discoveries with entries, all 4 context docs maintained, session-end workflow in active use |\n\n**Check for:** \\`docs/discoveries/\\`, \\`docs/context/production-map.md\\`, \\`docs/context/dangerous-assumptions.md\\`, \\`docs/context/decision-log.md\\`, \\`docs/context/institutional-knowledge.md\\`. Score based on both existence AND whether they have real content (not just templates).\n\n### Dimension 7: Testing & Validation\n\nLook for test config, CI setup, and validation commands.\n\n| Score | Criteria |\n|-------|----------|\n| 1 | No test configuration |\n| 2 | Test framework installed but few/no tests |\n| 3 | Tests exist with reasonable coverage |\n| 4 | Tests + CI pipeline configured |\n| 5 | Tests + CI + validation commands in CLAUDE.md + scenario tests |\n\n## Step 4: Write Assessment\n\nWrite the assessment to \\`docs/joycraft-assessment.md\\` AND display it in the conversation. Use this format:\n\n\\`\\`\\`markdown\n# Joycraft Assessment — [Project Name]\n\n**Date:** [today's date]\n**Overall Level:** [1-5, based on average score]\n\n## Scores\n\n| Dimension | Score | Summary |\n|-----------|-------|---------|\n| Spec Quality | X/5 | [one-line summary] |\n| Spec Granularity | X/5 | [one-line summary] |\n| Behavioral Boundaries | X/5 | [one-line summary] |\n| Skills & Hooks | X/5 | [one-line summary] |\n| Documentation | X/5 | [one-line summary] |\n| Knowledge Capture | X/5 | [one-line summary] |\n| Testing & Validation | X/5 | [one-line summary] |\n\n**Average:** X.X/5\n\n## Detailed Findings\n\n### [Dimension Name] — X/5\n**Evidence:** [specific files, paths, counts found]\n**Gap:** [what's missing]\n**Recommendation:** [specific action to improve]\n\n## Upgrade Plan\n\nTo reach Level [current + 1], complete these steps:\n1. [Most impactful action] — addresses [dimension] (X -> Y)\n2. [Next action] — addresses [dimension] (X -> Y)\n[up to 5 actions, ordered by impact]\n\\`\\`\\`\n\n## Step 5: Apply Upgrades\n\nImmediately after presenting the assessment, apply upgrades using the three-tier model below. Do NOT ask for per-item permission — batch everything and show a consolidated report at the end.\n\n### Tier 1: Silent Apply (just do it)\nThese are safe, additive operations. Apply them without asking:\n- Create missing directories (\\`docs/specs/\\`, \\`docs/briefs/\\`, \\`docs/discoveries/\\`, \\`docs/templates/\\`)\n- Install missing skills to \\`.claude/skills/\\`\n- Copy missing templates to \\`docs/templates/\\`\n- Create AGENTS.md if it doesn't exist\n\n### Git Autonomy Preference\n\nBefore applying Behavioral Boundaries to CLAUDE.md, ask the user ONE question:\n\n> How autonomous should git operations be?\n> 1. **Cautious** — commits freely, asks before pushing or opening PRs *(good for learning the workflow)*\n> 2. **Autonomous** — commits, pushes to branches, and opens PRs without asking *(good for spec-driven development)*\n\nBased on their answer, use the appropriate git rules in the Behavioral Boundaries section:\n\n**If Cautious (default):**\n\\`\\`\\`\n### ASK FIRST\n- Pushing to remote\n- Creating or merging pull requests\n- Any destructive git operation (force-push, reset --hard, branch deletion)\n\n### NEVER\n- Push directly to main/master without approval\n- Amend commits that have been pushed\n\\`\\`\\`\n\n**If Autonomous:**\n\\`\\`\\`\n### ALWAYS\n- Push to feature branches after each commit\n- Open a PR when all specs in a feature are complete\n- Use descriptive branch names: feature/spec-name\n\n### ASK FIRST\n- Merging PRs to main/master\n- Any destructive git operation (force-push, reset --hard, branch deletion)\n\n### NEVER\n- Push directly to main/master (always use feature branches + PR)\n- Amend commits that have been pushed to remote\n\\`\\`\\`\n\n### Risk Interview\n\nBefore applying upgrades, ask 3-5 targeted questions to capture what's dangerous in this project. Skip this if \\`docs/context/production-map.md\\` or \\`docs/context/dangerous-assumptions.md\\` already exist (offer to update instead).\n\n**Question 1:** \"What could this agent break that would ruin your day? Think: production databases, live APIs, billing systems, user data, infrastructure.\"\n\nFrom the answer, generate:\n- NEVER rules for CLAUDE.md (e.g., \"NEVER connect to production DB at postgres://prod.example.com\")\n- Deny patterns for .claude/settings.json (e.g., deny Bash commands containing production hostnames)\n\n**Question 2:** \"What external services does this project connect to? Which are production vs. staging/dev?\"\n\nFrom the answer, generate:\n- \\`docs/context/production-map.md\\` documenting what's real vs safe to touch\n- Include: service name, URL/endpoint, environment (prod/staging/dev), what happens if corrupted\n\n**Question 3:** \"What are the unwritten rules a new developer would need months to learn about this project?\"\n\nFrom the answer, generate:\n- Additions to CLAUDE.md boundaries (new ALWAYS/ASK FIRST/NEVER rules)\n- \\`docs/context/dangerous-assumptions.md\\` with \"Agent might assume X, but actually Y\"\n\n**Question 4 (optional):** \"What happened last time something went wrong with an automated tool or deploy?\"\n\nIf the user has a story, capture the lesson as a specific NEVER rule and add to dangerous-assumptions.md.\n\n**Question 5:** \"Any files, directories, or commands that should be completely off-limits?\"\n\nFrom the answer, generate deny rules for .claude/settings.json and add to NEVER section.\n\n**Rules for the interview:**\n- Ask questions ONE AT A TIME, not all at once\n- If the user says \"nothing\" or \"skip\", respect that and move on\n- Keep it to 2-3 minutes total — don't interrogate\n- Generate artifacts immediately after the interview, don't wait for all questions\n- This is the SECOND and LAST set of questions during /joycraft-tune (first is git autonomy)\n\n### Tier 2: Apply and Show Diff (do it, then report)\nThese modify important files but are additive (append-only). Apply them, then show what changed so the user can review. Git is the undo button.\n- Add missing sections to CLAUDE.md (Behavioral Boundaries, Development Workflow, Getting Started with Joycraft, Key Files, Common Gotchas)\n- Use the git autonomy preference from above when generating the Behavioral Boundaries section\n- Draft section content from the actual codebase — not generic placeholders. Read the project's real rules, real commands, real structure.\n- Only append — never modify or reformat existing content\n\n### Tier 3: Confirm First (ask before acting)\nThese are potentially destructive or opinionated. Ask before proceeding:\n- Rewriting or reorganizing existing CLAUDE.md sections\n- Overwriting files the user has customized\n- Suggesting test framework installation or CI setup (present as recommendations, don't auto-install)\n\n### Reading a Previous Assessment\n\nIf \\`docs/joycraft-assessment.md\\` already exists, read it first. If all recommendations have been applied, report \"nothing to upgrade\" and offer to re-assess.\n\n### After Applying\n\nAppend a history entry to \\`docs/joycraft-history.md\\` (create if needed):\n\\`\\`\\`\n| [date] | [new avg score] | [change from last] | [summary of what changed] |\n\\`\\`\\`\n\nThen display a single consolidated report:\n\n\\`\\`\\`markdown\n## Upgrade Results\n\n| Dimension | Before | After | Change |\n|------------------------|--------|-------|--------|\n| Spec Quality | X/5 | X/5 | +X |\n| ... | ... | ... | ... |\n\n**Previous Level:** X — **New Level:** X\n\n### What Changed\n- [list each change applied]\n\n### Remaining Gaps\n- [anything still below 3.5, with specific next action]\n\\`\\`\\`\n\nUpdate \\`docs/joycraft-assessment.md\\` with the new scores and today's date.\n\n## Step 6: Show Path to Level 5\n\nAfter the upgrade report, always show the Level 5 roadmap tailored to the project's current state:\n\n\\`\\`\\`markdown\n## Path to Level 5 — Autonomous Development\n\nYou're at Level [X]. Here's what each level looks like:\n\n| Level | You | AI | Key Skill |\n|-------|-----|-----|-----------|\n| 2 | Guide direction | Multi-file changes | AI-native tooling |\n| 3 | Review diffs | Primary developer | Code review at scale |\n| 4 | Write specs, check tests | End-to-end development | Specification writing |\n| 5 | Define what + why | Specs in, software out | Systems design |\n\n### Your Next Steps Toward Level [X+1]:\n1. [Specific action based on current gaps — e.g., \"Write your first atomic spec using /joycraft-new-feature\"]\n2. [Next action — e.g., \"Add vitest and write tests for your core logic\"]\n3. [Next action — e.g., \"Use /joycraft-session-end consistently to build your discoveries log\"]\n\n### What Level 5 Looks Like (Your North Star):\n- A backlog of ready specs that agents pull from and execute autonomously\n- CI failures auto-generate fix specs — no human triage for regressions\n- Multi-agent execution with parallel worktrees, one spec per agent\n- External holdout scenarios (tests the agent can't see) prevent overfitting\n- CLAUDE.md evolves from discoveries — the harness improves itself\n\n### You'll Know You're at Level 5 When:\n- You describe a feature in one sentence and walk away\n- The system produces a PR with tests, docs, and discoveries — without further input\n- Failed CI runs generate their own fix specs\n- Your harness improves without you manually editing CLAUDE.md\n\nThis is a significant journey. Most teams are at Level 2. Getting to Level 4 with Joycraft's workflow is achievable — Level 5 requires building validation infrastructure (scenario tests, spec queues, CI feedback loops) that goes beyond what Joycraft scaffolds today. But the harness you're building now is the foundation.\n\\`\\`\\`\n\nTailor the \"Next Steps\" section based on the project's actual gaps — don't show generic advice.\n\n## Edge Cases\n\n- **Not a git repo:** Note this. Joycraft works best in a git repo.\n- **CLAUDE.md is just a README:** Treat as \"no harness.\"\n- **Non-Joycraft skills already installed:** Acknowledge them. Do not replace — suggest additions.\n- **Monorepo:** Assess the root CLAUDE.md. Note if component-level CLAUDE.md files exist.\n- **Project has rules under non-standard headings:** Give credit. Suggest reformatting as Always/Ask First/Never but acknowledge the rules are there.\n- **Assessment file missing when upgrading:** Run the full assessment first, then offer to apply.\n- **Assessment is stale:** Warn and offer to re-assess before proceeding.\n- **All recommendations already applied:** Report \"nothing to upgrade\" and stop.\n- **User declines a recommendation:** Skip it, continue, include in \"What Was Skipped.\"\n- **CLAUDE.md does not exist at all:** Create it with recommended sections, but ask the user first.\n- **Non-Joycraft content in CLAUDE.md:** Preserve exactly as-is. Only append or merge — never remove or reformat existing content.\n`,\n\n};\n\nexport const TEMPLATES: Record<string, string> = {\n \"context/dangerous-assumptions.md\": `# Dangerous Assumptions\n\n> Things the AI agent might assume that are wrong in this project.\n> Generated by Joycraft risk interview. Update when you discover new gotchas.\n\n## Assumptions\n\n| Agent Might Assume | But Actually | Impact If Wrong |\n|-------------------|-------------|----------------|\n| _Example: All databases are dev/test_ | _The default connection is production_ | _Data loss_ |\n| _Example: Deleting and recreating is safe_ | _Some resources have manual config not in code_ | _Hours of manual recovery_ |\n\n## Historical Incidents\n\n| Date | What Happened | Lesson | Rule Added |\n|------|-------------|--------|------------|\n| _Example: 2026-03-15_ | _Agent deleted staging infra thinking it was temp_ | _Always verify environment before destructive ops_ | _NEVER: Delete cloud resources without listing them first_ |\n`,\n\n \"context/decision-log.md\": `# Decision Log\n\n> Why choices were made, not just what was chosen.\n> Update this when making architectural, tooling, or process decisions.\n> This is the institutional memory that prevents re-litigating settled questions.\n\n## Decisions\n\n| Date | Decision | Why | Alternatives Rejected | Revisit When |\n|------|----------|-----|----------------------|-------------|\n| _Example: 2026-03-15_ | _Use Supabase over Firebase_ | _Postgres flexibility, row-level security, self-hostable_ | _Firebase (vendor lock-in), PlanetScale (no RLS)_ | _If we need real-time sync beyond Supabase's capabilities_ |\n\n## Principles\n\n_Capture recurring decision patterns here — they save time on future choices._\n\n- _Example: \"Prefer tools we can self-host over pure SaaS — reduces vendor risk\"_\n- _Example: \"Choose boring technology for infrastructure, cutting-edge only for core differentiators\"_\n`,\n\n \"context/institutional-knowledge.md\": `# Institutional Knowledge\n\n> Unwritten rules, team conventions, and organizational context that AI agents can't derive from code.\n> This is the knowledge that takes a new developer months to absorb.\n> Update when you catch yourself saying \"oh, you didn't know about that?\"\n\n## Team Conventions\n\n_Things everyone on the team knows but nobody wrote down._\n\n- _Example: \"We never deploy on Fridays\"_\n- _Example: \"The CEO reviews all UI changes before they ship\"_\n- _Example: \"PR titles must reference the Jira ticket number\"_\n\n## Organizational Constraints\n\n_Business rules, compliance requirements, or political realities that affect technical decisions._\n\n- _Example: \"Legal requires all user data to be stored in EU regions\"_\n- _Example: \"The payments team owns the billing schema — never modify without their approval\"_\n- _Example: \"We have an informal agreement with Vendor X about API rate limits\"_\n\n## Historical Context\n\n_Why things are the way they are — especially when it looks wrong._\n\n- _Example: \"The auth module uses an old pattern because it predates our TypeScript migration — don't refactor without a spec\"_\n- _Example: \"The caching layer has a 5-second TTL because we had a consistency bug in 2025 — increasing it requires careful testing\"_\n\n## People & Ownership\n\n_Who owns what, who to ask, who cares about what._\n\n- _Example: \"Alice owns the payment pipeline — all changes need her review\"_\n- _Example: \"The data team is sensitive about query performance on the analytics tables\"_\n`,\n\n \"context/production-map.md\": `# Production Map\n\n> What's real, what's staging, what's safe to touch.\n> Generated by Joycraft risk interview. Update as your infrastructure evolves.\n\n## Services\n\n| Service | Environment | URL/Endpoint | Impact if Corrupted |\n|---------|-------------|-------------|-------------------|\n| _Example: Main DB_ | _Production_ | _postgres://prod.example.com_ | _1.9M user records lost_ |\n| _Example: Staging DB_ | _Staging_ | _postgres://staging.example.com_ | _Test data only, safe to reset_ |\n\n## Secrets & Credentials\n\n| Secret | Location | Notes |\n|--------|----------|-------|\n| _Example: DATABASE_URL_ | _.env.local_ | _Production connection — NEVER commit_ |\n\n## Safe to Touch\n\n- [ ] Staging environment at [URL]\n- [ ] Test/fixture data in [location]\n- [ ] Development API keys\n\n## NEVER Touch Without Explicit Approval\n\n- [ ] Production database\n- [ ] Live API endpoints\n- [ ] User-facing infrastructure\n`,\n\n \"examples/example-brief.md\": `# Add User Notifications — Feature Brief\n\n> **Date:** 2026-03-15\n> **Project:** acme-web\n> **Status:** Specs Ready\n\n---\n\n## Vision\n\nOur users have no idea when things happen in their account. A teammate comments on their pull request, a deployment finishes, a billing threshold is hit — they find out by accident, minutes or hours later. This is the #1 complaint in our last user survey.\n\nWe are building a notification system that delivers real-time and batched notifications across in-app, email, and (later) Slack channels. Users will have fine-grained control over what they receive and how. When this ships, no important event goes unnoticed, and no user gets buried in noise they didn't ask for.\n\nThe system is designed to be extensible — new event types plug in without touching the notification infrastructure. We start with three event types (PR comments, deploy status, billing alerts) and prove the pattern works before expanding.\n\n## User Stories\n\n- As a developer, I want to see a notification badge in the app when someone comments on my PR so that I can respond quickly\n- As a team lead, I want to receive an email when a production deployment fails so that I can coordinate the response\n- As a billing admin, I want to get alerted when usage exceeds 80% of our plan limit so that I can upgrade before service is disrupted\n- As any user, I want to control which notifications I receive and through which channels so that I am not overwhelmed\n\n## Hard Constraints\n\n- MUST: All notifications go through a single event bus — no direct coupling between event producers and delivery channels\n- MUST: Email delivery uses the existing SendGrid integration (do not add a new email provider)\n- MUST: Respect user preferences before delivering — never send a notification the user has opted out of\n- MUST NOT: Store notification content in plaintext in the database — use the existing encryption-at-rest pattern\n- MUST NOT: Send more than 50 emails per user per day (batch if necessary)\n\n## Out of Scope\n\n- NOT: Slack/Discord integration (Phase 2)\n- NOT: Push notifications / mobile (Phase 2)\n- NOT: Notification templates with rich HTML — plain text and simple markdown only for now\n- NOT: Admin dashboard for monitoring notification delivery rates\n- NOT: Retroactive notifications for events that happened before the feature ships\n\n## Decomposition\n\n| # | Spec Name | Description | Dependencies | Est. Size |\n|---|-----------|-------------|--------------|-----------|\n| 1 | add-notification-preferences-api | Create REST endpoints for users to read and update their notification preferences | None | M |\n| 2 | add-event-bus-infrastructure | Set up the internal event bus that decouples event producers from notification delivery | None | M |\n| 3 | add-notification-delivery-service | Build the service that consumes events, checks preferences, and dispatches to channels (in-app, email) | Spec 1, Spec 2 | L |\n| 4 | add-in-app-notification-ui | Add notification bell, dropdown, and badge count to the app header | Spec 3 | M |\n| 5 | add-email-batching | Implement daily digest batching for email notifications that exceed the per-user threshold | Spec 3 | S |\n\n## Execution Strategy\n\n- [x] Agent teams (parallel teammates within phases, sequential between phases)\n\n\\`\\`\\`\nPhase 1: Teammate A -> Spec 1 (preferences API), Teammate B -> Spec 2 (event bus)\nPhase 2: Teammate A -> Spec 3 (delivery service) — depends on Phase 1\nPhase 3: Teammate A -> Spec 4 (UI), Teammate B -> Spec 5 (batching) — both depend on Spec 3\n\\`\\`\\`\n\n## Success Criteria\n\n- [ ] User updates notification preferences via API, and subsequent events respect those preferences\n- [ ] A PR comment event triggers an in-app notification visible in the UI within 2 seconds\n- [ ] A deploy failure event sends an email to subscribed users via SendGrid\n- [ ] When email threshold (50/day) is exceeded, remaining notifications are batched into a daily digest\n- [ ] No regressions in existing PR, deployment, or billing features\n\n## External Scenarios\n\n| Scenario | What It Tests | Pass Criteria |\n|----------|--------------|---------------|\n| opt-out-respected | User disables email for deploy events, deploy fails | No email sent, in-app notification still appears |\n| batch-threshold | Send 51 email-eligible events for one user in a day | 50 individual emails + 1 digest containing the overflow |\n| preference-persistence | User sets preferences, logs out, logs back in | Preferences are unchanged |\n`,\n\n \"examples/example-spec.md\": `# Add Notification Preferences API — Atomic Spec\n\n> **Parent Brief:** \\`docs/briefs/2026-03-15-add-user-notifications.md\\`\n> **Status:** Ready\n> **Date:** 2026-03-15\n> **Estimated scope:** 1 session / 4 files / ~250 lines\n\n---\n\n## What\n\nAdd REST API endpoints that let users read and update their notification preferences. Each user gets a preferences record with per-event-type, per-channel toggles (e.g., \"PR comments: in-app=on, email=off\"). Preferences default to all-on for new users and are stored encrypted alongside the user profile.\n\n## Why\n\nThe notification delivery service (Spec 3) needs to check preferences before dispatching. Without this API, there is no way for users to control what they receive, and we cannot build the delivery pipeline.\n\n## Acceptance Criteria\n\n- [ ] \\`GET /api/v1/notifications/preferences\\` returns the current user's preferences as JSON\n- [ ] \\`PATCH /api/v1/notifications/preferences\\` updates one or more preference fields and returns the updated record\n- [ ] New users get default preferences (all channels enabled for all event types) on first read\n- [ ] Preferences are validated — unknown event types or channels return 400\n- [ ] Preferences are stored using the existing encryption-at-rest pattern (\\`EncryptedJsonColumn\\`)\n- [ ] Endpoint requires authentication (returns 401 for unauthenticated requests)\n- [ ] Build passes\n- [ ] Tests pass (unit + integration)\n\n## Constraints\n\n- MUST: Use the existing \\`EncryptedJsonColumn\\` utility for storage — do not roll a new encryption pattern\n- MUST: Follow the existing REST controller pattern in \\`src/controllers/\\`\n- MUST NOT: Expose other users' preferences (scope queries to authenticated user only)\n- SHOULD: Return the full preferences object on PATCH (not just the changed fields), so the frontend can replace state without merging\n\n## Affected Files\n\n| Action | File | What Changes |\n|--------|------|-------------|\n| Create | \\`src/controllers/notification-preferences.controller.ts\\` | New controller with GET and PATCH handlers |\n| Create | \\`src/models/notification-preferences.model.ts\\` | Sequelize model with EncryptedJsonColumn for preferences blob |\n| Create | \\`src/migrations/20260315-add-notification-preferences.ts\\` | Database migration to create notification_preferences table |\n| Create | \\`tests/controllers/notification-preferences.test.ts\\` | Unit and integration tests for both endpoints |\n| Modify | \\`src/routes/index.ts\\` | Register the new controller routes |\n\n## Approach\n\nCreate a \\`NotificationPreferences\\` model backed by a single \\`notification_preferences\\` table with columns: \\`id\\`, \\`user_id\\` (unique FK), \\`preferences\\` (EncryptedJsonColumn), \\`created_at\\`, \\`updated_at\\`. The \\`preferences\\` column stores a JSON blob shaped like \\`{ \"pr_comment\": { \"in_app\": true, \"email\": true }, \"deploy_status\": { ... } }\\`.\n\nThe GET endpoint does a find-or-create: if no record exists for the user, create one with defaults and return it. The PATCH endpoint deep-merges the request body into the existing preferences, validates the result against a known schema of event types and channels, and saves.\n\n**Rejected alternative:** Storing preferences as individual rows (one per event-type-channel pair). This would make queries more complex and would require N rows per user instead of 1. The JSON blob approach is simpler and matches how the frontend will consume the data.\n\n## Edge Cases\n\n| Scenario | Expected Behavior |\n|----------|------------------|\n| PATCH with empty body \\`{}\\` | Return 200 with unchanged preferences (no-op) |\n| PATCH with unknown event type \\`{\"foo\": {\"email\": true}}\\` | Return 400 with validation error listing valid event types |\n| GET for user with no existing record | Create default preferences, return 200 |\n| Concurrent PATCH requests | Last-write-wins (optimistic, no locking) — acceptable for user preferences |\n`,\n\n \"scenarios/README.md\": `# \\$SCENARIOS_REPO\n\nHoldout scenario tests for the main project. These tests run in CI against the\nbuilt artifact of each PR — but they live here, in a separate repository, so\nthe coding agent working on the main project cannot see them.\n\n---\n\n## What is the holdout pattern?\n\nThink of it like a validation set in machine learning. When you train a model,\nyou keep a slice of your data hidden from the training process. If the model\nscores well on data it has never seen, you can trust that it has actually\nlearned something — not just memorized the training examples.\n\nScenario tests work the same way. The coding agent writes code and passes\ninternal tests in the main repo. These scenario tests then check whether the\nresult behaves correctly from a real user's perspective, using only the public\ninterface of the built artifact.\n\nBecause the agent cannot read this repository, it cannot game the tests. A\npassing scenario run means the feature genuinely works.\n\n---\n\n## Why a separate repository?\n\nA single repository would expose the tests to the agent. Claude Code reads\nfiles in the working directory; if scenario tests lived in the main repo, the\nagent could (and would) read them when fixing failures, which defeats the\npurpose.\n\nA separate repo also means:\n\n- The test suite can be updated by humans without triggering the autofix loop\n- Scenarios can reference multiple projects over time\n- Access controls are independent — the scenarios repo can be more restricted\n\n---\n\n## How the CI pipeline works\n\n\\`\\`\\`\nMain repo PR opened\n |\n v\nMain repo CI runs (unit + integration tests)\n |\n | passes\n v\nscenarios-dispatch.yml fires a repository_dispatch event\n |\n v\nThis repo: run.yml receives the event\n |\n +-- clones main-repo PR branch to ../main-repo\n |\n +-- builds the artifact (npm ci && npm run build)\n |\n +-- runs: NO_COLOR=1 npx vitest run\n |\n +-- captures exit code + output\n |\n v\nPosts PASS / FAIL comment on the originating PR\n\\`\\`\\`\n\nThe PR author sees the scenario result as a comment. No separate status check\nis required, though you can add one via the GitHub Checks API if you prefer.\n\n---\n\n## Adding scenarios\n\n### Rules\n\n1. **Behavioral, not structural.** Test what the tool does, not how it is\n built internally. Invoke the binary; assert on stdout, exit codes, and\n filesystem state. Never import from \\`../main-repo/src\\`.\n\n2. **End-to-end.** Each test should represent something a real user would\n actually do. If you would not put it in a demo or docs example, reconsider\n whether it belongs here.\n\n3. **No source imports.** The entire point of the holdout is that tests cannot\n see source code. Any \\`import\\` that reaches into \\`../main-repo/src\\` breaks\n the pattern.\n\n4. **Independent.** Each test must be able to run in isolation. Use \\`beforeEach\\`\n / \\`afterEach\\` to set up and tear down temp directories. Do not share mutable\n state between tests.\n\n5. **Deterministic.** Avoid network calls, timestamps, or random values in\n assertions unless the feature under test genuinely involves them.\n\n### File layout\n\n\\`\\`\\`\n\\$SCENARIOS_REPO/\n├── example-scenario.test.ts # Starter file — replace with real scenarios\n├── workflows/\n│ └── run.yml # CI workflow (do not rename)\n├── package.json\n└── README.md\n\\`\\`\\`\n\nAdd new \\`.test.ts\\` files at the top level or in subdirectories. Vitest will\ndiscover them automatically.\n\n### Example structure\n\n\\`\\`\\`ts\nimport { spawnSync } from \"node:child_process\";\nimport { join } from \"node:path\";\n\nconst CLI = join(__dirname, \"..\", \"main-repo\", \"dist\", \"cli.js\");\n\nit(\"init creates a CLAUDE.md file\", () => {\n const tmp = mkdtempSync(join(tmpdir(), \"scenario-\"));\n const { status } = spawnSync(\"node\", [CLI, \"init\", tmp], { encoding: \"utf8\" });\n expect(status).toBe(0);\n expect(existsSync(join(tmp, \"CLAUDE.md\"))).toBe(true);\n});\n\\`\\`\\`\n\n---\n\n## Internal tests vs scenario tests\n\n| | Internal tests (main repo) | Scenario tests (this repo) |\n|---|---|---|\n| Location | \\`tests/\\` in main repo | This repo |\n| Visible to agent | Yes | No |\n| What they test | Units, modules, logic | End-to-end behavior |\n| Import source code | Yes | Never |\n| Run on every push | Yes | Yes (via dispatch) |\n| Purpose | Catch regressions fast | Validate real behavior |\n\n---\n\n## Relationship to Joycraft\n\nThis repository was bootstrapped by \\`npx joycraft init --autofix\\`. Joycraft\nmanages the \\`run.yml\\` workflow and keeps it in sync when you run\n\\`npx joycraft upgrade\\`. The test files are yours — Joycraft will never\noverwrite them.\n\nIf the \\`run.yml\\` workflow needs updating (e.g., a new version of\n\\`actions/create-github-app-token\\`), run \\`npx joycraft upgrade\\` in this repo\nand review the diff before applying.\n`,\n\n \"scenarios/example-scenario.test.ts\": `/**\n * Example Scenario Test\n *\n * This file is a template for scenario tests in your holdout repository.\n * Scenarios are behavioral, end-to-end tests that run against the BUILT\n * artifact of your main project — not its source code.\n *\n * The Holdout Pattern\n * -------------------\n * These tests live in a SEPARATE repository that your coding agent cannot\n * see. This is intentional: if the agent could read these tests, it could\n * write code that passes them without actually solving the problem correctly\n * (the same way a student who sees the exam beforehand can score well without\n * understanding the material).\n *\n * In CI, the main repo is cloned to ../main-repo (relative to this repo's\n * checkout). The run.yml workflow builds the artifact there before running\n * these tests, so \\`../main-repo\\` is always available and already built.\n *\n * How to Write Scenarios\n * ----------------------\n * DO:\n * - Invoke the built binary / entry point via child_process (execSync, spawnSync)\n * - Test observable behavior: exit codes, stdout/stderr content, file system state\n * - Write scenarios around things a real user would actually do\n * - Keep each test fully independent — no shared state between tests\n *\n * DON'T:\n * - Import from ../main-repo/src — that defeats the holdout\n * - Test internal implementation details (function names, module structure)\n * - Rely on network access unless your tool genuinely requires it\n * - Share mutable fixtures across tests\n */\n\nimport { execSync, spawnSync } from \"node:child_process\";\nimport { existsSync, mkdtempSync, rmSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { afterEach, beforeEach, describe, expect, it } from \"vitest\";\n\n// Path to the built CLI entry point in the main repo.\n// The run.yml workflow clones the main repo to ../main-repo and builds it\n// before this test file runs, so this path is always valid in CI.\nconst CLI = join(__dirname, \"..\", \"main-repo\", \"dist\", \"cli.js\");\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/** Run the CLI and return { stdout, stderr, status }. Never throws. */\nfunction runCLI(args: string[], cwd?: string) {\n const result = spawnSync(\"node\", [CLI, ...args], {\n encoding: \"utf8\",\n cwd: cwd ?? process.cwd(),\n env: { ...process.env, NO_COLOR: \"1\" },\n });\n return {\n stdout: result.stdout ?? \"\",\n stderr: result.stderr ?? \"\",\n status: result.status ?? 1,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Basic invocation scenarios\n// ---------------------------------------------------------------------------\n\ndescribe(\"CLI: basic invocation\", () => {\n it(\"--help prints usage information\", () => {\n const { stdout, status } = runCLI([\"--help\"]);\n expect(status).toBe(0);\n expect(stdout).toContain(\"Usage:\");\n });\n\n it(\"--version returns a semver string\", () => {\n const { stdout, status } = runCLI([\"--version\"]);\n expect(status).toBe(0);\n // Matches x.y.z, x.y.z-alpha.1, etc.\n expect(stdout.trim()).toMatch(/^\\\\d+\\\\.\\\\d+\\\\.\\\\d+/);\n });\n\n it(\"unknown command exits non-zero\", () => {\n const { status } = runCLI([\"not-a-real-command\"]);\n expect(status).not.toBe(0);\n });\n});\n\n// ---------------------------------------------------------------------------\n// Example: filesystem interaction scenario\n//\n// This pattern is useful when your CLI creates or modifies files.\n// Each test gets a fresh temp directory so they can't interfere.\n// ---------------------------------------------------------------------------\n\ndescribe(\"CLI: init command (example — replace with your real scenarios)\", () => {\n let tmpDir: string;\n\n beforeEach(() => {\n tmpDir = mkdtempSync(join(tmpdir(), \"scenarios-\"));\n });\n\n afterEach(() => {\n rmSync(tmpDir, { recursive: true, force: true });\n });\n\n it(\"init creates expected output in an empty directory\", () => {\n // This is a placeholder. Replace with whatever your CLI actually does.\n // The point is: invoke the binary, observe side effects, assert on them.\n const { status } = runCLI([\"init\", tmpDir]);\n\n // Example assertions — adjust to your tool's actual behavior:\n // expect(status).toBe(0);\n // expect(existsSync(join(tmpDir, \"CLAUDE.md\"))).toBe(true);\n\n // Remove this line once you've written a real assertion above:\n expect(typeof status).toBe(\"number\"); // placeholder\n });\n});\n`,\n\n \"scenarios/package.json\": `{\n \"name\": \"\\$SCENARIOS_REPO\",\n \"version\": \"0.0.1\",\n \"private\": true,\n \"type\": \"module\",\n \"scripts\": {\n \"test\": \"vitest run\"\n },\n \"devDependencies\": {\n \"vitest\": \"^3.0.0\"\n }\n}\n`,\n\n \"scenarios/prompts/scenario-agent.md\": `You are a QA engineer working in a holdout test repository. You CANNOT access the main repository's source code. Your job is to write or update behavioral scenario tests based on specs that are pushed from the main repo.\n\n## What You Have Access To\n\n- This scenarios repository (test files, \\`specs/\\` mirror, \\`package.json\\`)\n- The incoming spec (provided below)\n- A list of existing test files and spec mirrors (provided below)\n- The main repo is available at \\`../main-repo\\` and is already built — you can invoke its CLI or entry point via \\`execSync\\`/\\`spawnSync\\`, but you MUST NOT import from \\`../main-repo/src\\`\n\n## Triage Decision Tree\n\nRead the incoming spec carefully. Decide which of these three actions to take:\n\n### SKIP — Do nothing if the spec is:\n- An internal refactor with no user-facing behavior change (e.g., \"extract module\", \"rename internal type\")\n- CI or dev tooling changes (e.g., \"add lint rule\", \"update GitHub Actions workflow\")\n- Documentation-only changes\n- Performance improvements with identical observable behavior\n\nIf you SKIP, write a brief comment in the relevant test file (or a new one) explaining why, then stop.\n\n### NEW — Create a new test file if the spec describes:\n- A new command, flag, or subcommand\n- A new output format or file that gets generated\n- A new user-facing behavior that doesn't map to any existing test file\n\nName the file after the feature area: \\`[feature-area].test.ts\\`. One feature area per test file.\n\n### UPDATE — Modify an existing test file if the spec:\n- Changes behavior that is already tested\n- Adds a flag or option to an existing command\n- Modifies output format for an existing feature\n\nMatch to the most relevant existing test file by feature area.\n\n**If you are unsure whether a spec is user-facing, err on the side of writing a test.**\n\n## Test Writing Rules\n\n1. **Behavioral only.** Test observable output — stdout, stderr, exit codes, files created/modified on disk. Never test internal implementation details or import source modules.\n\n2. **Use \\`execSync\\` or \\`spawnSync\\`.** Invoke the built binary at \\`../main-repo/dist/cli.js\\` (or whatever the main repo's entry point is). Check \\`../main-repo/package.json\\` to find the correct entry point if unsure.\n\n3. **Use vitest.** Import \\`describe\\`, \\`it\\`, \\`expect\\` from \\`vitest\\`. Use \\`beforeEach\\`/\\`afterEach\\` for temp directory setup/teardown.\n\n4. **Each test is fully independent.** No shared mutable state between tests. Each test that touches the filesystem gets its own temp directory via \\`mkdtempSync\\`.\n\n5. **Assert on realistic user actions.** Write tests that reflect what a real user would do — not what the implementation happens to do.\n\n6. **Never import from the parent repo's source.** If you find yourself writing \\`import { ... } from '../main-repo/src/...'\\`, stop — that defeats the holdout.\n\n## Test File Template\n\n\\`\\`\\`typescript\nimport { execSync, spawnSync } from 'node:child_process';\nimport { existsSync, mkdtempSync, rmSync, readFileSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { describe, it, expect, beforeEach, afterEach } from 'vitest';\n\nconst CLI = join(__dirname, '..', 'main-repo', 'dist', 'cli.js');\n\nfunction runCLI(args: string[], cwd?: string) {\n const result = spawnSync('node', [CLI, ...args], {\n encoding: 'utf8',\n cwd: cwd ?? process.cwd(),\n env: { ...process.env, NO_COLOR: '1' },\n });\n return {\n stdout: result.stdout ?? '',\n stderr: result.stderr ?? '',\n status: result.status ?? 1,\n };\n}\n\ndescribe('[feature area]: [behavior being tested]', () => {\n let tmpDir: string;\n\n beforeEach(() => {\n tmpDir = mkdtempSync(join(tmpdir(), 'scenarios-'));\n });\n\n afterEach(() => {\n rmSync(tmpDir, { recursive: true, force: true });\n });\n\n it('[specific observable behavior]', () => {\n const { stdout, status } = runCLI(['command', 'args'], tmpDir);\n expect(status).toBe(0);\n expect(stdout).toContain('expected output');\n });\n});\n\\`\\`\\`\n\n## Checklist Before Committing\n\n- [ ] Decision: SKIP / NEW / UPDATE (and why)\n- [ ] Tests assert on observable behavior, not implementation\n- [ ] No imports from \\`../main-repo/src\\`\n- [ ] Each test has its own temp directory if it touches the filesystem\n- [ ] File is named after the feature area, not the spec\n`,\n\n \"scenarios/workflows/generate.yml\": `# Scenario Generation Workflow\n#\n# Triggered by a \\`spec-pushed\\` repository_dispatch event sent from the main\n# project when a spec is added or modified on main. A scenario agent triages\n# the spec and writes or updates holdout tests in this repo.\n#\n# After the agent commits changes, fires \\`scenarios-updated\\` back to the main\n# repo so that any open PRs are re-tested with the new/updated scenarios.\n#\n# Prerequisites:\n# - ANTHROPIC_API_KEY secret: Anthropic API key for Claude Code\n# - JOYCRAFT_APP_PRIVATE_KEY secret: GitHub App private key (.pem)\n# - \\$JOYCRAFT_APP_ID is replaced with the actual App ID number at install time\n\nname: Generate Scenarios\n\non:\n repository_dispatch:\n types: [spec-pushed]\n\njobs:\n generate:\n name: Run scenario agent\n runs-on: ubuntu-latest\n\n steps:\n # ── 1. Check out the scenarios repo ──────────────────────────────────\n - name: Checkout scenarios repo\n uses: actions/checkout@v4\n\n # ── 2. Save incoming spec to local mirror ─────────────────────────────\n # The agent reads this file to understand what changed.\n - name: Save spec to mirror\n run: |\n mkdir -p specs\n cat > \"specs/\\${{ github.event.client_payload.spec_filename }}\" << 'SPEC_EOF'\n \\${{ github.event.client_payload.spec_content }}\n SPEC_EOF\n echo \"Saved \\${{ github.event.client_payload.spec_filename }} to specs/\"\n\n # ── 3. Gather context for the agent ───────────────────────────────────\n # Bounded context: filenames only (not file contents) to stay within\n # token limits. The agent uses these lists to decide whether to create\n # a new test file or update an existing one.\n - name: Gather context\n id: context\n run: |\n EXISTING_TESTS=\\$(find . -name \"*.test.ts\" -not -path \"./.git/*\" \\\\\n | sed 's|^\\\\./||' | sort | tr '\\\\n' ',' | sed 's/,\\$//')\n EXISTING_SPECS=\\$(find specs/ -name \"*.md\" 2>/dev/null \\\\\n | sed 's|^specs/||' | sort | tr '\\\\n' ',' | sed 's/,\\$//')\n\n echo \"existing_tests=\\$EXISTING_TESTS\" >> \"\\$GITHUB_OUTPUT\"\n echo \"existing_specs=\\$EXISTING_SPECS\" >> \"\\$GITHUB_OUTPUT\"\n echo \"Existing test files: \\$EXISTING_TESTS\"\n echo \"Existing spec mirrors: \\$EXISTING_SPECS\"\n\n # ── 4. Set up Node.js ─────────────────────────────────────────────────\n - name: Set up Node.js\n uses: actions/setup-node@v4\n with:\n node-version: \"20\"\n\n # ── 5. Install Claude Code CLI ────────────────────────────────────────\n - name: Install Claude Code\n run: npm install -g @anthropic-ai/claude-code\n\n # ── 6. Run scenario agent ─────────────────────────────────────────────\n # - Uses \\`claude -p\\` (prompt mode) for non-interactive execution.\n # - No --model flag: the environment's default model is used.\n # - --dangerously-skip-permissions lets Claude write files without prompts.\n # - --max-turns 20 caps the agentic loop so it can't run indefinitely.\n - name: Run scenario agent\n id: agent\n env:\n ANTHROPIC_API_KEY: \\${{ secrets.ANTHROPIC_API_KEY }}\n run: |\n PROMPT=\\$(cat .claude/prompts/scenario-agent.md 2>/dev/null || cat prompts/scenario-agent.md)\n\n claude -p \\\\\n --dangerously-skip-permissions \\\\\n --max-turns 20 \\\\\n \"\\${PROMPT}\n\n ---\n\n ## Incoming Spec\n\n Filename: \\${{ github.event.client_payload.spec_filename }}\n\n Content:\n \\$(cat 'specs/\\${{ github.event.client_payload.spec_filename }}')\n\n ---\n\n ## Context\n\n Existing test files in this repo: \\${{ steps.context.outputs.existing_tests }}\n Existing spec mirrors: \\${{ steps.context.outputs.existing_specs }}\"\n\n # ── 7. Commit any changes the agent made ──────────────────────────────\n - name: Commit scenario changes\n id: commit\n run: |\n git config user.name \"Joycraft Scenario Agent\"\n git config user.email \"joycraft-scenarios@users.noreply.github.com\"\n\n git add -A\n\n if git diff --cached --quiet; then\n echo \"No changes to commit — spec triaged as no-op.\"\n echo \"committed=false\" >> \"\\$GITHUB_OUTPUT\"\n exit 0\n fi\n\n git commit -m \"scenarios: update tests for \\${{ github.event.client_payload.spec_filename }}\"\n git push\n echo \"committed=true\" >> \"\\$GITHUB_OUTPUT\"\n\n # ── 8. Generate GitHub App token for cross-repo dispatch ──────────────\n # Only needed if the agent committed changes (otherwise nothing to re-run).\n - name: Generate GitHub App token\n id: app-token\n if: steps.commit.outputs.committed == 'true'\n uses: actions/create-github-app-token@v1\n with:\n app-id: \\$JOYCRAFT_APP_ID\n private-key: \\${{ secrets.JOYCRAFT_APP_PRIVATE_KEY }}\n repositories: \\${{ github.event.client_payload.repo }}\n\n # ── 9. Notify main repo that scenarios were updated ───────────────────\n # Fires \\`scenarios-updated\\` so the main repo's re-run workflow can\n # trigger scenario runs against any open PRs that may now be affected.\n - name: Dispatch scenarios-updated to main repo\n if: steps.commit.outputs.committed == 'true'\n env:\n GH_TOKEN: \\${{ steps.app-token.outputs.token }}\n run: |\n REPO=\"\\${{ github.event.client_payload.repo }}\"\n REPO_OWNER=\"\\${REPO%%/*}\"\n REPO_NAME=\"\\${REPO##*/}\"\n\n gh api \"repos/\\${REPO_OWNER}/\\${REPO_NAME}/dispatches\" \\\\\n -f event_type=scenarios-updated \\\\\n -f \"client_payload[spec_filename]=\\${{ github.event.client_payload.spec_filename }}\" \\\\\n -f \"client_payload[scenarios_repo]=\\${{ github.repository }}\"\n\n echo \"Dispatched scenarios-updated to \\${REPO}\"\n`,\n\n \"scenarios/workflows/run.yml\": `# Scenarios Run Workflow\n#\n# Triggered by a \\`repository_dispatch\\` event (type: run-scenarios) sent from\n# the main project's CI pipeline after a PR passes its internal tests.\n#\n# This workflow:\n# 1. Clones the main repo's PR branch to ../main-repo\n# 2. Builds the artifact\n# 3. Runs the scenario tests in this repo\n# 4. Posts a PASS or FAIL comment on the originating PR\n#\n# Prerequisites:\n# - A GitHub App (\"Joycraft Autofix\" or equivalent) installed on BOTH repos.\n# \\$JOYCRAFT_APP_ID is replaced with the actual App ID number at install time.\n# JOYCRAFT_APP_PRIVATE_KEY must be stored as a repository secret in this repo.\n# - This scenarios repo must be added to the App's repository access list.\n\nname: Run Scenarios\n\non:\n repository_dispatch:\n types: [run-scenarios]\n\njobs:\n run-scenarios:\n name: Run holdout scenario tests\n runs-on: ubuntu-latest\n\n steps:\n # ── 1. Check out the scenarios repo ─────────────────────────────────────\n - name: Checkout scenarios repo\n uses: actions/checkout@v4\n with:\n path: scenarios\n\n # ── 2. Mint a GitHub App token ───────────────────────────────────────────\n # \\$JOYCRAFT_APP_ID is replaced with the numeric App ID at install time\n # (e.g., app-id: 3180156). It is NOT a secret — App IDs are public.\n - name: Generate GitHub App token\n id: app-token\n uses: actions/create-github-app-token@v1\n with:\n app-id: \\$JOYCRAFT_APP_ID\n private-key: \\${{ secrets.JOYCRAFT_APP_PRIVATE_KEY }}\n repositories: \\${{ github.event.client_payload.repo }}\n\n # ── 3. Clone the main repo's PR branch ──────────────────────────────────\n # Cloned to ./main-repo so scenario tests can reference ../main-repo\n # relative to the scenarios/ checkout.\n - name: Clone main repo PR branch\n env:\n GH_TOKEN: \\${{ steps.app-token.outputs.token }}\n run: |\n git clone \\\\\n --branch \\${{ github.event.client_payload.branch }} \\\\\n --depth 1 \\\\\n https://x-access-token:\\${GH_TOKEN}@github.com/\\${{ github.event.client_payload.repo }}.git \\\\\n main-repo\n\n # ── 4. Set up Node.js ────────────────────────────────────────────────────\n - name: Set up Node.js\n uses: actions/setup-node@v4\n with:\n node-version: \"20\"\n cache: \"npm\"\n cache-dependency-path: main-repo/package-lock.json\n\n # ── 5. Build the main repo artifact ─────────────────────────────────────\n - name: Build main repo\n working-directory: main-repo\n run: npm ci && npm run build\n\n # ── 6. Install scenario test dependencies ────────────────────────────────\n - name: Install scenario dependencies\n working-directory: scenarios\n run: npm ci\n\n # ── 7. Run scenario tests ────────────────────────────────────────────────\n # set +e — don't abort on non-zero exit; we capture it manually\n # set -o pipefail — propagate failures through pipes (for tee)\n # NO_COLOR=1 — strip color codes before they reach tee\n # ANSI codes are also stripped via sed as a belt-and-suspenders measure\n - name: Run scenario tests\n id: scenarios\n working-directory: scenarios\n run: |\n set +e\n set -o pipefail\n NO_COLOR=1 npx vitest run 2>&1 \\\\\n | sed 's/\\\\x1b\\\\[[0-9;]*m//g' \\\\\n | tee test-output.txt\n VITEST_EXIT=\\$?\n echo \"exit_code=\\$VITEST_EXIT\" >> \"\\$GITHUB_OUTPUT\"\n exit \\$VITEST_EXIT\n\n # ── 8. Post PASS or FAIL comment on the originating PR ──────────────────\n # Always runs so the PR author always gets feedback.\n - name: Post result comment on PR\n if: always()\n env:\n GH_TOKEN: \\${{ steps.app-token.outputs.token }}\n PR_NUMBER: \\${{ github.event.client_payload.pr_number }}\n MAIN_REPO: \\${{ github.event.client_payload.repo }}\n VITEST_EXIT: \\${{ steps.scenarios.outputs.exit_code }}\n run: |\n # Read test output (cap at 100 lines to keep the comment manageable)\n OUTPUT=\\$(head -100 scenarios/test-output.txt 2>/dev/null || echo \"(no output captured)\")\n\n if [ \"\\$VITEST_EXIT\" = \"0\" ]; then\n STATUS_LINE=\"**Scenario tests: PASS**\"\n else\n STATUS_LINE=\"**Scenario tests: FAIL** (exit code: \\$VITEST_EXIT)\"\n fi\n\n BODY=\"\\${STATUS_LINE}\n\n <details>\n <summary>Test output</summary>\n\n \\\\\\`\\\\\\`\\\\\\`\n \\${OUTPUT}\n \\\\\\`\\\\\\`\\\\\\`\n\n </details>\n\n Run triggered by commit \\\\\\`\\${{ github.event.client_payload.sha }}\\\\\\`.\"\n\n gh api \"repos/\\${MAIN_REPO}/issues/\\${PR_NUMBER}/comments\" \\\\\n -f body=\"\\$BODY\"\n`,\n\n \"workflows/autofix.yml\": `# Autofix Workflow\n#\n# Triggered when CI fails on a PR. Uses Claude Code to attempt an automated fix,\n# then pushes a commit and re-triggers CI. Limits to 3 autofix attempts per PR\n# before escalating to human review.\n#\n# Prerequisites:\n# - A GitHub App called \"Joycraft Autofix\" (or equivalent) installed on the repo.\n# Its credentials must be stored as repository secrets:\n# JOYCRAFT_APP_ID — the App's numeric ID\n# JOYCRAFT_APP_PRIVATE_KEY — the App's PEM private key\n# - ANTHROPIC_API_KEY secret for Claude Code\n\nname: Autofix\n\non:\n workflow_run:\n # Replace with the exact name of your CI workflow\n workflows: [\"CI\"]\n types: [completed]\n\n# One autofix run per PR at a time — cancel in-flight runs for the same PR\nconcurrency:\n group: autofix-pr-\\${{ github.event.workflow_run.pull_requests[0].number }}\n cancel-in-progress: true\n\njobs:\n autofix:\n name: Attempt automated fix\n runs-on: ubuntu-latest\n\n # Only run when CI failed and the triggering workflow was on a PR\n if: |\n github.event.workflow_run.conclusion == 'failure' &&\n github.event.workflow_run.pull_requests[0] != null\n\n steps:\n # ── 1. Mint a short-lived GitHub App token ──────────────────────────────\n # Using a dedicated App identity lets this workflow push commits without\n # triggering GitHub's anti-recursion protection on the GITHUB_TOKEN.\n - name: Generate GitHub App token\n id: app-token\n uses: actions/create-github-app-token@v1\n with:\n # \\$JOYCRAFT_APP_ID is replaced with the actual App ID number at install time\n app-id: \\$JOYCRAFT_APP_ID\n private-key: \\${{ secrets.JOYCRAFT_APP_PRIVATE_KEY }}\n\n # ── 2. Check out the PR branch ──────────────────────────────────────────\n # We check out the exact branch (not a merge ref) so that any commit we\n # push lands directly on the PR branch.\n - name: Checkout PR branch\n uses: actions/checkout@v4\n with:\n token: \\${{ steps.app-token.outputs.token }}\n ref: \\${{ github.event.workflow_run.pull_requests[0].head.ref }}\n fetch-depth: 0\n\n # ── 3. Count previous autofix attempts ─────────────────────────────────\n # Count \"autofix:\" commits in the log. If we have already made 3 attempts\n # on this PR, stop and ask a human to review instead.\n - name: Check autofix iteration count\n id: iteration\n run: |\n COUNT=\\$(git log --oneline | grep \"autofix:\" | wc -l | tr -d ' ')\n echo \"count=\\$COUNT\" >> \"\\$GITHUB_OUTPUT\"\n echo \"Autofix attempts so far: \\$COUNT\"\n\n # ── 4. Post \"human review needed\" and exit if limit reached ─────────────\n - name: Post human-review comment and exit\n if: steps.iteration.outputs.count >= 3\n env:\n GH_TOKEN: \\${{ steps.app-token.outputs.token }}\n PR_NUMBER: \\${{ github.event.workflow_run.pull_requests[0].number }}\n run: |\n gh pr comment \"\\$PR_NUMBER\" \\\\\n --body \"**Autofix limit reached (3 attempts).** Please review manually — Claude was unable to resolve the CI failures automatically.\"\n echo \"Max iterations reached. Exiting without further autofix.\"\n exit 0\n\n # ── 5. Fetch the CI failure logs ────────────────────────────────────────\n # Download logs from the failed workflow run so Claude has concrete\n # failure context to work from. ANSI escape codes are stripped so the\n # logs are readable as plain text.\n - name: Fetch CI failure logs\n id: logs\n env:\n GH_TOKEN: \\${{ github.token }}\n RUN_ID: \\${{ github.event.workflow_run.id }}\n run: |\n gh run view \"\\$RUN_ID\" --log-failed 2>&1 \\\\\n | sed 's/\\\\x1b\\\\[[0-9;]*m//g' \\\\\n > /tmp/ci-failure.log\n echo \"=== CI failure log (first 200 lines) ===\"\n head -200 /tmp/ci-failure.log\n\n # ── 6. Set up Node.js (adjust version to match your project) ───────────\n - name: Set up Node.js\n uses: actions/setup-node@v4\n with:\n node-version: \"20\"\n cache: \"npm\"\n\n # ── 7. Install project dependencies ─────────────────────────────────────\n - name: Install dependencies\n run: npm ci\n\n # ── 8. Install Claude Code CLI ───────────────────────────────────────────\n - name: Install Claude Code\n run: npm install -g @anthropic-ai/claude-code\n\n # ── 9. Run Claude Code to fix the failure ───────────────────────────────\n # - Uses \\`claude -p\\` (prompt mode) so it runs non-interactively.\n # - No --model flag: the environment's default model is used.\n # - --dangerously-skip-permissions lets Claude edit files without prompts.\n # - --max-turns 20 caps the agentic loop so it can't run indefinitely.\n # - set +e captures the exit code without aborting the step immediately.\n # - set -o pipefail ensures piped commands propagate failures correctly.\n - name: Run Claude Code autofix\n id: claude\n env:\n ANTHROPIC_API_KEY: \\${{ secrets.ANTHROPIC_API_KEY }}\n GH_TOKEN: \\${{ steps.app-token.outputs.token }}\n run: |\n set +e\n set -o pipefail\n\n FAILURE_LOG=\\$(cat /tmp/ci-failure.log)\n\n claude -p \\\\\n --dangerously-skip-permissions \\\\\n --max-turns 20 \\\\\n \"CI is failing on this PR. Here are the failure logs:\n\n \\${FAILURE_LOG}\n\n Please investigate the root cause, fix the code, and make sure the tests pass.\n Do not modify workflow files. Focus only on source code and test files.\n After making changes, run the test suite to verify the fix works.\" \\\\\n 2>&1 | sed 's/\\\\x1b\\\\[[0-9;]*m//g' | tee /tmp/claude-output.log\n\n CLAUDE_EXIT=\\$?\n echo \"exit_code=\\$CLAUDE_EXIT\" >> \"\\$GITHUB_OUTPUT\"\n exit \\$CLAUDE_EXIT\n\n # ── 10. Commit and push any changes Claude made ──────────────────────────\n # If Claude modified files, commit them with an \"autofix:\" prefix so the\n # iteration counter in step 3 can find them on future runs.\n - name: Commit and push autofix changes\n if: steps.claude.outputs.exit_code == '0'\n env:\n GH_TOKEN: \\${{ steps.app-token.outputs.token }}\n run: |\n git config user.name \"Joycraft Autofix\"\n git config user.email \"autofix@joycraft.dev\"\n\n git add -A\n\n if git diff --cached --quiet; then\n echo \"No changes to commit — Claude made no file modifications.\"\n exit 0\n fi\n\n ITERATION=\\${{ steps.iteration.outputs.count }}\n NEXT=\\$(( ITERATION + 1 ))\n\n git commit -m \"autofix: attempt \\$NEXT — fix CI failures [skip autofix]\"\n git push\n\n # ── 11. Post a summary comment on the PR ─────────────────────────────────\n # Always post a comment so the PR author knows what happened.\n - name: Post result comment\n if: always()\n env:\n GH_TOKEN: \\${{ steps.app-token.outputs.token }}\n PR_NUMBER: \\${{ github.event.workflow_run.pull_requests[0].number }}\n CLAUDE_EXIT: \\${{ steps.claude.outputs.exit_code }}\n run: |\n if [ \"\\$CLAUDE_EXIT\" = \"0\" ]; then\n BODY=\"**Autofix pushed a fix.** CI has been re-triggered. If it still fails, another autofix attempt will run (up to 3 total).\"\n else\n BODY=\"**Autofix ran but could not produce a clean fix** (exit code: \\$CLAUDE_EXIT). Please review the logs and fix manually.\"\n fi\n\n gh pr comment \"\\$PR_NUMBER\" --body \"\\$BODY\"\n`,\n\n \"workflows/scenarios-dispatch.yml\": `# Scenarios Dispatch Workflow\n#\n# Triggered when CI passes on a PR. Fires a \\`repository_dispatch\\` event to a\n# separate scenarios repository so that integration / end-to-end scenario tests\n# can run against the PR's code without living in this repo.\n#\n# Prerequisites:\n# - JOYCRAFT_APP_PRIVATE_KEY secret: GitHub App private key (.pem)\n# - \\$SCENARIOS_REPO is replaced with the actual repo name at install time\n\nname: Scenarios Dispatch\n\non:\n workflow_run:\n # Replace with the exact name of your CI workflow\n workflows: [\"CI\"]\n types: [completed]\n\njobs:\n dispatch:\n name: Fire scenarios dispatch\n runs-on: ubuntu-latest\n\n # Only run when CI succeeded and the triggering workflow was on a PR\n if: |\n github.event.workflow_run.conclusion == 'success' &&\n github.event.workflow_run.pull_requests[0] != null\n\n steps:\n # ── 1. Generate GitHub App token for cross-repo dispatch ─────────────\n - name: Generate GitHub App token\n id: app-token\n uses: actions/create-github-app-token@v1\n with:\n app-id: \\$JOYCRAFT_APP_ID\n private-key: \\${{ secrets.JOYCRAFT_APP_PRIVATE_KEY }}\n repositories: \\$SCENARIOS_REPO\n\n # ── 2. Fire repository_dispatch to the scenarios repo ──────────────────\n # Sends a \\`run-scenarios\\` event carrying enough context for the scenarios\n # repo to check out the correct branch/SHA and know which PR triggered it.\n # \\$SCENARIOS_REPO is replaced with the actual repo name at install time.\n - name: Dispatch run-scenarios event\n env:\n GH_TOKEN: \\${{ steps.app-token.outputs.token }}\n run: |\n PR_NUMBER=\\${{ github.event.workflow_run.pull_requests[0].number }}\n BRANCH=\\${{ github.event.workflow_run.pull_requests[0].head.ref }}\n SHA=\\${{ github.event.workflow_run.head_sha }}\n\n gh api repos/\\${{ github.repository_owner }}/\\$SCENARIOS_REPO/dispatches \\\\\n -f event_type=run-scenarios \\\\\n -f \"client_payload[pr_number]=\\$PR_NUMBER\" \\\\\n -f \"client_payload[branch]=\\$BRANCH\" \\\\\n -f \"client_payload[sha]=\\$SHA\" \\\\\n -f \"client_payload[repo]=\\${{ github.repository }}\"\n\n echo \"Dispatched run-scenarios to \\$SCENARIOS_REPO for PR #\\$PR_NUMBER\"\n`,\n\n \"workflows/scenarios-rerun.yml\": `# Scenarios Re-run Workflow\n#\n# Triggered when the scenarios repo reports that it has updated its tests\n# (type: scenarios-updated). Finds all open PRs and fires a \\`run-scenarios\\`\n# dispatch to the scenarios repo for each one, so that newly generated or\n# updated tests are exercised against in-flight PR branches.\n#\n# This handles the race condition where a PR's implementation completes before\n# the scenario agent has finished writing its holdout tests.\n#\n# Prerequisites:\n# - JOYCRAFT_APP_PRIVATE_KEY secret: GitHub App private key (.pem)\n# - \\$JOYCRAFT_APP_ID is replaced with the actual App ID number at install time\n# - \\$SCENARIOS_REPO is replaced with the actual scenarios repo name at install time\n\nname: Scenarios Re-run\n\non:\n repository_dispatch:\n types: [scenarios-updated]\n\njobs:\n rerun:\n name: Re-run scenarios against open PRs\n runs-on: ubuntu-latest\n\n steps:\n # ── 1. Generate GitHub App token for cross-repo dispatch ──────────────\n - name: Generate GitHub App token\n id: app-token\n uses: actions/create-github-app-token@v1\n with:\n app-id: \\$JOYCRAFT_APP_ID\n private-key: \\${{ secrets.JOYCRAFT_APP_PRIVATE_KEY }}\n repositories: \\$SCENARIOS_REPO\n\n # ── 2. List open PRs and dispatch run-scenarios for each ──────────────\n # If there are no open PRs, exits cleanly — nothing to do.\n - name: Dispatch run-scenarios for each open PR\n env:\n GH_TOKEN: \\${{ steps.app-token.outputs.token }}\n run: |\n OPEN_PRS=\\$(gh api repos/\\${{ github.repository }}/pulls \\\\\n --jq '.[] | \"\\\\(.number) \\\\(.head.ref) \\\\(.head.sha)\"')\n\n if [ -z \"\\$OPEN_PRS\" ]; then\n echo \"No open PRs — nothing to re-run.\"\n exit 0\n fi\n\n while IFS=' ' read -r PR_NUMBER BRANCH SHA; do\n [ -z \"\\$PR_NUMBER\" ] && continue\n\n echo \"Dispatching run-scenarios for PR #\\$PR_NUMBER (branch: \\$BRANCH, sha: \\$SHA)\"\n\n gh api repos/\\${{ github.repository_owner }}/\\$SCENARIOS_REPO/dispatches \\\\\n -f event_type=run-scenarios \\\\\n -f \"client_payload[pr_number]=\\$PR_NUMBER\" \\\\\n -f \"client_payload[branch]=\\$BRANCH\" \\\\\n -f \"client_payload[sha]=\\$SHA\" \\\\\n -f \"client_payload[repo]=\\${{ github.repository }}\"\n\n done <<< \"\\$OPEN_PRS\"\n`,\n\n \"workflows/spec-dispatch.yml\": `# Spec Dispatch Workflow\n#\n# Triggered when specs are pushed to main. For each added or modified spec,\n# fires a \\`spec-pushed\\` repository_dispatch event to the scenarios repo so\n# that a scenario agent can triage the spec and write/update holdout tests.\n#\n# Prerequisites:\n# - JOYCRAFT_APP_PRIVATE_KEY secret: GitHub App private key (.pem)\n# - \\$JOYCRAFT_APP_ID is replaced with the actual App ID number at install time\n# - \\$SCENARIOS_REPO is replaced with the actual scenarios repo name at install time\n\nname: Spec Dispatch\n\non:\n push:\n branches: [main]\n paths:\n - \"docs/specs/**\"\n\njobs:\n dispatch:\n name: Dispatch changed specs to scenarios repo\n runs-on: ubuntu-latest\n\n steps:\n # ── 1. Check out with depth 2 to enable HEAD~1 diff ──────────────────\n - name: Checkout\n uses: actions/checkout@v4\n with:\n fetch-depth: 2\n\n # ── 2. Find added or modified spec files ──────────────────────────────\n # --diff-filter=AM: Added or Modified only — ignore deletions.\n - name: Find changed specs\n id: changed\n run: |\n FILES=\\$(git diff --name-only --diff-filter=AM HEAD~1 HEAD -- 'docs/specs/*.md')\n echo \"files<<EOF\" >> \"\\$GITHUB_OUTPUT\"\n echo \"\\$FILES\" >> \"\\$GITHUB_OUTPUT\"\n echo \"EOF\" >> \"\\$GITHUB_OUTPUT\"\n echo \"Changed specs: \\$FILES\"\n\n # ── 3. Generate GitHub App token for cross-repo dispatch ──────────────\n # Skipped if no specs changed (token unused, save the round-trip).\n - name: Generate GitHub App token\n id: app-token\n if: steps.changed.outputs.files != ''\n uses: actions/create-github-app-token@v1\n with:\n app-id: \\$JOYCRAFT_APP_ID\n private-key: \\${{ secrets.JOYCRAFT_APP_PRIVATE_KEY }}\n repositories: \\$SCENARIOS_REPO\n\n # ── 4. Dispatch each changed spec to the scenarios repo ───────────────\n # Sends a \\`spec-pushed\\` event with the spec filename, full content,\n # commit SHA, branch, and originating repo. The scenario agent uses\n # this payload to triage and generate/update tests.\n - name: Dispatch spec-pushed events\n if: steps.changed.outputs.files != ''\n env:\n GH_TOKEN: \\${{ steps.app-token.outputs.token }}\n run: |\n while IFS= read -r SPEC_FILE; do\n [ -z \"\\$SPEC_FILE\" ] && continue\n\n SPEC_FILENAME=\\$(basename \"\\$SPEC_FILE\")\n SPEC_CONTENT=\\$(cat \"\\$SPEC_FILE\")\n\n echo \"Dispatching spec-pushed for \\$SPEC_FILENAME\"\n\n gh api repos/\\${{ github.repository_owner }}/\\$SCENARIOS_REPO/dispatches \\\\\n -f event_type=spec-pushed \\\\\n -f \"client_payload[spec_filename]=\\$SPEC_FILENAME\" \\\\\n -f \"client_payload[spec_content]=\\$SPEC_CONTENT\" \\\\\n -f \"client_payload[commit_sha]=\\${{ github.sha }}\" \\\\\n -f \"client_payload[branch]=\\${{ github.ref_name }}\" \\\\\n -f \"client_payload[repo]=\\${{ github.repository }}\"\n\n done <<< \"\\${{ steps.changed.outputs.files }}\"\n`,\n\n};\n"],"mappings":";;;AAEO,IAAM,SAAiC;AAAA,EAC5C,yBAAyB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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AA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA4DpC,iCAAiC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAiEjC,+BAA+B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAiFjC;","names":[]}
|
package/dist/cli.js
CHANGED
|
@@ -5,13 +5,17 @@ import { Command } from "commander";
|
|
|
5
5
|
var program = new Command();
|
|
6
6
|
program.name("joycraft").description("Scaffold and upgrade AI development harnesses").version("0.1.0");
|
|
7
7
|
program.command("init").description("Scaffold the Joycraft harness into the current project").argument("[dir]", "Target directory", ".").option("--force", "Overwrite existing files").action(async (dir, opts) => {
|
|
8
|
-
const { init } = await import("./init-
|
|
8
|
+
const { init } = await import("./init-DHVJEWGX.js");
|
|
9
9
|
await init(dir, { force: opts.force ?? false });
|
|
10
10
|
});
|
|
11
11
|
program.command("upgrade").description("Upgrade installed Joycraft templates and skills to latest").argument("[dir]", "Target directory", ".").option("--yes", "Auto-accept all updates").action(async (dir, opts) => {
|
|
12
|
-
const { upgrade } = await import("./upgrade-
|
|
12
|
+
const { upgrade } = await import("./upgrade-RN2D5RAT.js");
|
|
13
13
|
await upgrade(dir, { yes: opts.yes ?? false });
|
|
14
14
|
});
|
|
15
|
+
program.command("init-autofix").description("Set up the Level 5 auto-fix loop with holdout scenarios").argument("[dir]", "Target directory", ".").option("--scenarios-repo <name>", "Name for scenarios repo").option("--app-id <id>", "GitHub App ID for Joycraft Autofix").option("--force", "Overwrite existing workflow files").option("--dry-run", "Show what would be created without creating it").action(async (dir, opts) => {
|
|
16
|
+
const { initAutofix } = await import("./init-autofix-OVHXYVLB.js");
|
|
17
|
+
await initAutofix(dir, opts);
|
|
18
|
+
});
|
|
15
19
|
program.command("check-version").description("Check if a newer version of Joycraft is available").action(async () => {
|
|
16
20
|
try {
|
|
17
21
|
const { readFileSync } = await import("fs");
|
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli.ts"],"sourcesContent":["import { Command } from 'commander';\n\nconst program = new Command();\n\nprogram\n .name('joycraft')\n .description('Scaffold and upgrade AI development harnesses')\n .version('0.1.0');\n\nprogram\n .command('init')\n .description('Scaffold the Joycraft harness into the current project')\n .argument('[dir]', 'Target directory', '.')\n .option('--force', 'Overwrite existing files')\n .action(async (dir: string, opts: { force?: boolean }) => {\n const { init } = await import('./init.js');\n await init(dir, { force: opts.force ?? false });\n });\n\nprogram\n .command('upgrade')\n .description('Upgrade installed Joycraft templates and skills to latest')\n .argument('[dir]', 'Target directory', '.')\n .option('--yes', 'Auto-accept all updates')\n .action(async (dir: string, opts: { yes?: boolean }) => {\n const { upgrade } = await import('./upgrade.js');\n await upgrade(dir, { yes: opts.yes ?? false });\n });\n\nprogram\n .command('check-version')\n .description('Check if a newer version of Joycraft is available')\n .action(async () => {\n try {\n const { readFileSync } = await import('node:fs');\n const { join } = await import('node:path');\n const data = JSON.parse(readFileSync(join(process.cwd(), '.joycraft-version'), 'utf-8'));\n const res = await fetch('https://registry.npmjs.org/joycraft/latest', { signal: AbortSignal.timeout(3000) });\n if (res.ok) {\n const latest = ((await res.json()) as { version: string }).version;\n if (data.version !== latest) {\n console.log(`Joycraft ${latest} available (you have ${data.version}). Run: npx joycraft upgrade`);\n }\n }\n } catch {\n // Silent — don't block session start\n }\n });\n\nprogram.parse();\n"],"mappings":";;;AAAA,SAAS,eAAe;AAExB,IAAM,UAAU,IAAI,QAAQ;AAE5B,QACG,KAAK,UAAU,EACf,YAAY,+CAA+C,EAC3D,QAAQ,OAAO;AAElB,QACG,QAAQ,MAAM,EACd,YAAY,wDAAwD,EACpE,SAAS,SAAS,oBAAoB,GAAG,EACzC,OAAO,WAAW,0BAA0B,EAC5C,OAAO,OAAO,KAAa,SAA8B;AACxD,QAAM,EAAE,KAAK,IAAI,MAAM,OAAO,oBAAW;AACzC,QAAM,KAAK,KAAK,EAAE,OAAO,KAAK,SAAS,MAAM,CAAC;AAChD,CAAC;AAEH,QACG,QAAQ,SAAS,EACjB,YAAY,2DAA2D,EACvE,SAAS,SAAS,oBAAoB,GAAG,EACzC,OAAO,SAAS,yBAAyB,EACzC,OAAO,OAAO,KAAa,SAA4B;AACtD,QAAM,EAAE,QAAQ,IAAI,MAAM,OAAO,uBAAc;AAC/C,QAAM,QAAQ,KAAK,EAAE,KAAK,KAAK,OAAO,MAAM,CAAC;AAC/C,CAAC;AAEH,QACG,QAAQ,eAAe,EACvB,YAAY,mDAAmD,EAC/D,OAAO,YAAY;AAClB,MAAI;AACF,UAAM,EAAE,aAAa,IAAI,MAAM,OAAO,IAAS;AAC/C,UAAM,EAAE,KAAK,IAAI,MAAM,OAAO,MAAW;AACzC,UAAM,OAAO,KAAK,MAAM,aAAa,KAAK,QAAQ,IAAI,GAAG,mBAAmB,GAAG,OAAO,CAAC;AACvF,UAAM,MAAM,MAAM,MAAM,8CAA8C,EAAE,QAAQ,YAAY,QAAQ,GAAI,EAAE,CAAC;AAC3G,QAAI,IAAI,IAAI;AACV,YAAM,UAAW,MAAM,IAAI,KAAK,GAA2B;AAC3D,UAAI,KAAK,YAAY,QAAQ;AAC3B,gBAAQ,IAAI,YAAY,MAAM,wBAAwB,KAAK,OAAO,8BAA8B;AAAA,MAClG;AAAA,IACF;AAAA,EACF,QAAQ;AAAA,EAER;AACF,CAAC;AAEH,QAAQ,MAAM;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/cli.ts"],"sourcesContent":["import { Command } from 'commander';\n\nconst program = new Command();\n\nprogram\n .name('joycraft')\n .description('Scaffold and upgrade AI development harnesses')\n .version('0.1.0');\n\nprogram\n .command('init')\n .description('Scaffold the Joycraft harness into the current project')\n .argument('[dir]', 'Target directory', '.')\n .option('--force', 'Overwrite existing files')\n .action(async (dir: string, opts: { force?: boolean }) => {\n const { init } = await import('./init.js');\n await init(dir, { force: opts.force ?? false });\n });\n\nprogram\n .command('upgrade')\n .description('Upgrade installed Joycraft templates and skills to latest')\n .argument('[dir]', 'Target directory', '.')\n .option('--yes', 'Auto-accept all updates')\n .action(async (dir: string, opts: { yes?: boolean }) => {\n const { upgrade } = await import('./upgrade.js');\n await upgrade(dir, { yes: opts.yes ?? false });\n });\n\nprogram\n .command('init-autofix')\n .description('Set up the Level 5 auto-fix loop with holdout scenarios')\n .argument('[dir]', 'Target directory', '.')\n .option('--scenarios-repo <name>', 'Name for scenarios repo')\n .option('--app-id <id>', 'GitHub App ID for Joycraft Autofix')\n .option('--force', 'Overwrite existing workflow files')\n .option('--dry-run', 'Show what would be created without creating it')\n .action(async (dir: string, opts: { scenariosRepo?: string; appId?: string; force?: boolean; dryRun?: boolean }) => {\n const { initAutofix } = await import('./init-autofix.js');\n await initAutofix(dir, opts);\n });\n\nprogram\n .command('check-version')\n .description('Check if a newer version of Joycraft is available')\n .action(async () => {\n try {\n const { readFileSync } = await import('node:fs');\n const { join } = await import('node:path');\n const data = JSON.parse(readFileSync(join(process.cwd(), '.joycraft-version'), 'utf-8'));\n const res = await fetch('https://registry.npmjs.org/joycraft/latest', { signal: AbortSignal.timeout(3000) });\n if (res.ok) {\n const latest = ((await res.json()) as { version: string }).version;\n if (data.version !== latest) {\n console.log(`Joycraft ${latest} available (you have ${data.version}). Run: npx joycraft upgrade`);\n }\n }\n } catch {\n // Silent — don't block session start\n }\n });\n\nprogram.parse();\n"],"mappings":";;;AAAA,SAAS,eAAe;AAExB,IAAM,UAAU,IAAI,QAAQ;AAE5B,QACG,KAAK,UAAU,EACf,YAAY,+CAA+C,EAC3D,QAAQ,OAAO;AAElB,QACG,QAAQ,MAAM,EACd,YAAY,wDAAwD,EACpE,SAAS,SAAS,oBAAoB,GAAG,EACzC,OAAO,WAAW,0BAA0B,EAC5C,OAAO,OAAO,KAAa,SAA8B;AACxD,QAAM,EAAE,KAAK,IAAI,MAAM,OAAO,oBAAW;AACzC,QAAM,KAAK,KAAK,EAAE,OAAO,KAAK,SAAS,MAAM,CAAC;AAChD,CAAC;AAEH,QACG,QAAQ,SAAS,EACjB,YAAY,2DAA2D,EACvE,SAAS,SAAS,oBAAoB,GAAG,EACzC,OAAO,SAAS,yBAAyB,EACzC,OAAO,OAAO,KAAa,SAA4B;AACtD,QAAM,EAAE,QAAQ,IAAI,MAAM,OAAO,uBAAc;AAC/C,QAAM,QAAQ,KAAK,EAAE,KAAK,KAAK,OAAO,MAAM,CAAC;AAC/C,CAAC;AAEH,QACG,QAAQ,cAAc,EACtB,YAAY,yDAAyD,EACrE,SAAS,SAAS,oBAAoB,GAAG,EACzC,OAAO,2BAA2B,yBAAyB,EAC3D,OAAO,iBAAiB,oCAAoC,EAC5D,OAAO,WAAW,mCAAmC,EACrD,OAAO,aAAa,gDAAgD,EACpE,OAAO,OAAO,KAAa,SAAwF;AAClH,QAAM,EAAE,YAAY,IAAI,MAAM,OAAO,4BAAmB;AACxD,QAAM,YAAY,KAAK,IAAI;AAC7B,CAAC;AAEH,QACG,QAAQ,eAAe,EACvB,YAAY,mDAAmD,EAC/D,OAAO,YAAY;AAClB,MAAI;AACF,UAAM,EAAE,aAAa,IAAI,MAAM,OAAO,IAAS;AAC/C,UAAM,EAAE,KAAK,IAAI,MAAM,OAAO,MAAW;AACzC,UAAM,OAAO,KAAK,MAAM,aAAa,KAAK,QAAQ,IAAI,GAAG,mBAAmB,GAAG,OAAO,CAAC;AACvF,UAAM,MAAM,MAAM,MAAM,8CAA8C,EAAE,QAAQ,YAAY,QAAQ,GAAI,EAAE,CAAC;AAC3G,QAAI,IAAI,IAAI;AACV,YAAM,UAAW,MAAM,IAAI,KAAK,GAA2B;AAC3D,UAAI,KAAK,YAAY,QAAQ;AAC3B,gBAAQ,IAAI,YAAY,MAAM,wBAAwB,KAAK,OAAO,8BAA8B;AAAA,MAClG;AAAA,IACF;AAAA,EACF,QAAQ;AAAA,EAER;AACF,CAAC;AAEH,QAAQ,MAAM;","names":[]}
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {
|
|
3
|
-
SKILLS,
|
|
4
|
-
TEMPLATES,
|
|
5
3
|
hashContent,
|
|
6
4
|
writeVersion
|
|
7
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-2S7KP7FU.js";
|
|
6
|
+
import {
|
|
7
|
+
SKILLS,
|
|
8
|
+
TEMPLATES
|
|
9
|
+
} from "./chunk-HHW4Q2UC.js";
|
|
8
10
|
|
|
9
11
|
// src/init.ts
|
|
10
12
|
import { mkdirSync as mkdirSync2, existsSync as existsSync3, writeFileSync as writeFileSync2, readFileSync as readFileSync3 } from "fs";
|
|
@@ -294,6 +296,7 @@ This project uses [Joycraft](https://github.com/maksutovic/joycraft) for AI deve
|
|
|
294
296
|
| \`/joycraft-interview\` | Lightweight brainstorm \u2014 yap about ideas, get a structured summary |
|
|
295
297
|
| \`/joycraft-decompose\` | Break a brief into small, testable specs |
|
|
296
298
|
| \`/joycraft-session-end\` | Capture discoveries, verify, commit |
|
|
299
|
+
| \`/joycraft-implement-level5\` | Set up Level 5 \u2014 autofix loop, holdout scenarios, scenario evolution |
|
|
297
300
|
|
|
298
301
|
Run \`/joycraft-tune\` to see where your project stands and what to improve next.`;
|
|
299
302
|
}
|
|
@@ -758,4 +761,4 @@ function printSummary(result, stack) {
|
|
|
758
761
|
export {
|
|
759
762
|
init
|
|
760
763
|
};
|
|
761
|
-
//# sourceMappingURL=init-
|
|
764
|
+
//# sourceMappingURL=init-DHVJEWGX.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/init.ts","../src/detect.ts","../src/improve-claude-md.ts","../src/agents-md.ts","../src/permissions.ts","../src/safeguard.ts"],"sourcesContent":["import { mkdirSync, existsSync, writeFileSync, readFileSync } from 'node:fs';\nimport { join, basename, resolve, dirname } from 'node:path';\nimport { detectStack } from './detect.js';\nimport { generateCLAUDEMd } from './improve-claude-md.js';\nimport { generateAgentsMd } from './agents-md.js';\nimport { generatePermissions } from './permissions.js';\nimport { installSafeguardHooks } from './safeguard.js';\nimport { SKILLS, TEMPLATES } from './bundled-files.js';\nimport { writeVersion, hashContent } from './version.js';\n\nexport interface InitOptions {\n force: boolean;\n}\n\ninterface InitResult {\n created: string[];\n skipped: string[];\n modified: string[];\n warnings: string[];\n}\n\nfunction ensureDir(dir: string): void {\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n}\n\nfunction writeFile(path: string, content: string, force: boolean, result: InitResult): void {\n if (existsSync(path) && !force) {\n result.skipped.push(path);\n return;\n }\n writeFileSync(path, content, 'utf-8');\n result.created.push(path);\n}\n\nexport async function init(dir: string, opts: InitOptions): Promise<void> {\n const targetDir = resolve(dir);\n const result: InitResult = { created: [], skipped: [], modified: [], warnings: [] };\n\n // Detect stack\n const stack = await detectStack(targetDir);\n\n // 1. Create docs/ subdirectories\n const docsDirs = ['briefs', 'specs', 'discoveries', 'contracts', 'decisions', 'context'];\n for (const sub of docsDirs) {\n ensureDir(join(targetDir, 'docs', sub));\n }\n\n // 2. Copy skill files to .claude/skills/<name>/SKILL.md\n const skillsDir = join(targetDir, '.claude', 'skills');\n for (const [filename, content] of Object.entries(SKILLS)) {\n const skillName = filename.replace(/\\.md$/, '');\n const skillDir = join(skillsDir, skillName);\n ensureDir(skillDir);\n writeFile(join(skillDir, 'SKILL.md'), content, opts.force, result);\n }\n\n // 3. Copy template files to docs/templates/\n const templatesDir = join(targetDir, 'docs', 'templates');\n ensureDir(templatesDir);\n for (const [filename, content] of Object.entries(TEMPLATES)) {\n ensureDir(dirname(join(templatesDir, filename)));\n writeFile(join(templatesDir, filename), content, opts.force, result);\n }\n\n // 4. Handle CLAUDE.md — only create if missing, never modify existing (unless --force)\n const claudeMdPath = join(targetDir, 'CLAUDE.md');\n if (existsSync(claudeMdPath) && !opts.force) {\n result.skipped.push(claudeMdPath);\n } else {\n const projectName = basename(targetDir);\n const content = generateCLAUDEMd(projectName, stack);\n writeFileSync(claudeMdPath, content, 'utf-8');\n result.created.push(claudeMdPath);\n }\n\n // 5. Handle AGENTS.md — only create if missing, never modify existing (unless --force)\n const agentsMdPath = join(targetDir, 'AGENTS.md');\n if (existsSync(agentsMdPath) && !opts.force) {\n result.skipped.push(agentsMdPath);\n } else {\n const projectName = basename(targetDir);\n const content = generateAgentsMd(projectName, stack);\n writeFileSync(agentsMdPath, content, 'utf-8');\n result.created.push(agentsMdPath);\n }\n\n // 6. Write .joycraft-version with hashes of all managed files\n const fileHashes: Record<string, string> = {};\n for (const [filename, content] of Object.entries(SKILLS)) {\n const skillName = filename.replace(/\\.md$/, '');\n fileHashes[join('.claude', 'skills', skillName, 'SKILL.md')] = hashContent(content);\n }\n for (const [filename, content] of Object.entries(TEMPLATES)) {\n fileHashes[join('docs', 'templates', filename)] = hashContent(content);\n }\n writeVersion(targetDir, '0.1.0', fileHashes);\n\n // 7. Install version check hook\n const hooksDir = join(targetDir, '.claude', 'hooks');\n ensureDir(hooksDir);\n const hookScript = `// Joycraft version check — runs on Claude Code session start\nimport { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\ntry {\n const data = JSON.parse(readFileSync(join(process.cwd(), '.joycraft-version'), 'utf-8'));\n const res = await fetch('https://registry.npmjs.org/joycraft/latest', { signal: AbortSignal.timeout(3000) });\n if (res.ok) {\n const latest = (await res.json()).version;\n if (data.version !== latest) console.log('Joycraft ' + latest + ' available (you have ' + data.version + '). Run: npx joycraft upgrade');\n }\n} catch {}\n`;\n writeFile(join(hooksDir, 'joycraft-version-check.mjs'), hookScript, opts.force, result);\n\n // Update .claude/settings.json with SessionStart hook\n const settingsPath = join(targetDir, '.claude', 'settings.json');\n let settings: Record<string, unknown> = {};\n if (existsSync(settingsPath)) {\n try {\n settings = JSON.parse(readFileSync(settingsPath, 'utf-8'));\n } catch {\n // If settings.json is malformed, start fresh\n }\n }\n if (!settings.hooks) settings.hooks = {};\n const hooksConfig = settings.hooks as Record<string, unknown>;\n if (!hooksConfig.SessionStart) hooksConfig.SessionStart = [];\n const sessionStartHooks = hooksConfig.SessionStart as Array<Record<string, unknown>>;\n const hasJoycraftHook = sessionStartHooks.some(h => {\n const innerHooks = h.hooks as Array<Record<string, unknown>> | undefined;\n return innerHooks?.some(ih => typeof ih.command === 'string' && ih.command.includes('joycraft'));\n });\n if (!hasJoycraftHook) {\n sessionStartHooks.push({\n matcher: '',\n hooks: [{\n type: 'command',\n command: 'node .claude/hooks/joycraft-version-check.mjs',\n }],\n });\n writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\\n', 'utf-8');\n result.created.push(settingsPath);\n }\n\n // 8. Generate and merge permission rules into settings.json\n const permissions = generatePermissions(stack);\n // Re-read settings in case it was just created by hook step\n if (existsSync(settingsPath)) {\n try {\n settings = JSON.parse(readFileSync(settingsPath, 'utf-8'));\n } catch {\n // keep existing settings object\n }\n }\n if (!settings.permissions) settings.permissions = {};\n const perms = settings.permissions as Record<string, string[]>;\n if (!perms.allow) perms.allow = [];\n if (!perms.deny) perms.deny = [];\n for (const rule of permissions.allow) {\n if (!perms.allow.includes(rule)) perms.allow.push(rule);\n }\n for (const rule of permissions.deny) {\n if (!perms.deny.includes(rule)) perms.deny.push(rule);\n }\n writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\\n', 'utf-8');\n\n // 9. Install safeguard hooks (PreToolUse deny-pattern blocking)\n const hookResult = installSafeguardHooks(targetDir, [], opts.force);\n result.created.push(...hookResult.created);\n result.skipped.push(...hookResult.skipped);\n\n // 10. Check .gitignore for .claude/ exclusion\n const gitignorePath = join(targetDir, '.gitignore');\n if (existsSync(gitignorePath)) {\n const gitignore = readFileSync(gitignorePath, 'utf-8');\n if (/^\\.claude\\/?$/m.test(gitignore) || /^\\.claude\\/\\*$/m.test(gitignore)) {\n result.warnings.push(\n '.claude/ is in your .gitignore — teammates won\\'t get Joycraft skills.\\n' +\n ' Add this line to .gitignore to fix: !.claude/skills/'\n );\n }\n }\n\n // 11. Print summary\n printSummary(result, stack);\n}\n\nfunction printSummary(result: InitResult, stack: import('./detect.js').StackInfo): void {\n console.log('\\nJoycraft initialized!\\n');\n\n if (stack.language !== 'unknown') {\n const fw = stack.framework ? ` + ${stack.framework}` : '';\n console.log(` Detected stack: ${stack.language}${fw} (${stack.packageManager})`);\n } else {\n console.log(' Detected stack: unknown (no recognized manifest found)');\n }\n\n if (result.created.length > 0) {\n console.log(`\\n Created ${result.created.length} file(s):`);\n for (const f of result.created) {\n console.log(` + ${f}`);\n }\n }\n\n if (result.modified.length > 0) {\n console.log(`\\n Modified ${result.modified.length} file(s):`);\n for (const f of result.modified) {\n console.log(` ~ ${f}`);\n }\n }\n\n if (result.skipped.length > 0) {\n console.log(`\\n Skipped ${result.skipped.length} file(s) (already exist, use --force to overwrite):`);\n for (const f of result.skipped) {\n console.log(` - ${f}`);\n }\n }\n\n if (result.warnings.length > 0) {\n console.log('\\n Warnings:');\n for (const w of result.warnings) {\n console.log(` ⚠ ${w}`);\n }\n }\n\n const hasExistingClaude = result.skipped.some(f => f.endsWith('CLAUDE.md'));\n\n console.log('\\n Next steps:');\n if (hasExistingClaude) {\n console.log(' 1. Run Claude Code and try /joycraft-tune to assess and improve your existing CLAUDE.md');\n } else {\n console.log(' 1. Review and customize the generated CLAUDE.md for your project');\n }\n console.log(' 2. Try /joycraft-new-feature to start building with the spec-driven workflow');\n console.log(' 3. Commit .claude/skills/ and docs/ so your team gets the same workflow');\n console.log('');\n}\n","import { readFileSync, existsSync } from 'node:fs';\nimport { join } from 'node:path';\n\nexport interface StackInfo {\n language: string;\n packageManager: string;\n commands: {\n build?: string;\n test?: string;\n lint?: string;\n typecheck?: string;\n deploy?: string;\n };\n framework?: string;\n}\n\nfunction readFile(path: string): string | null {\n try {\n return readFileSync(path, 'utf-8');\n } catch {\n return null;\n }\n}\n\nfunction detectNodeFramework(pkg: { dependencies?: Record<string, string>; devDependencies?: Record<string, string> }): string | undefined {\n const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };\n if (allDeps['next']) return 'Next.js';\n if (allDeps['nuxt']) return 'Nuxt';\n if (allDeps['@remix-run/node'] || allDeps['@remix-run/react']) return 'Remix';\n if (allDeps['express']) return 'Express';\n if (allDeps['fastify']) return 'Fastify';\n if (allDeps['react']) return 'React';\n if (allDeps['vue']) return 'Vue';\n if (allDeps['svelte']) return 'Svelte';\n return undefined;\n}\n\nfunction detectNodeTestFramework(pkg: { devDependencies?: Record<string, string>; dependencies?: Record<string, string> }): string | undefined {\n const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };\n if (allDeps['vitest']) return 'vitest';\n if (allDeps['jest']) return 'jest';\n if (allDeps['mocha']) return 'mocha';\n return undefined;\n}\n\nfunction detectNodePackageManager(dir: string): string {\n if (existsSync(join(dir, 'pnpm-lock.yaml'))) return 'pnpm';\n if (existsSync(join(dir, 'yarn.lock'))) return 'yarn';\n if (existsSync(join(dir, 'bun.lockb')) || existsSync(join(dir, 'bun.lock'))) return 'bun';\n return 'npm';\n}\n\nfunction detectNode(dir: string): StackInfo | null {\n const raw = readFile(join(dir, 'package.json'));\n if (raw === null) return null;\n\n let pkg: Record<string, unknown>;\n try {\n pkg = JSON.parse(raw);\n } catch {\n return null;\n }\n\n const pm = detectNodePackageManager(dir);\n const run = pm === 'npm' ? 'npm run' : pm;\n const scripts = (pkg.scripts ?? {}) as Record<string, string>;\n const framework = detectNodeFramework(pkg as { dependencies?: Record<string, string>; devDependencies?: Record<string, string> });\n const testFramework = detectNodeTestFramework(pkg as { devDependencies?: Record<string, string>; dependencies?: Record<string, string> });\n\n const commands: StackInfo['commands'] = {};\n if (scripts.build) commands.build = `${run} build`;\n else commands.build = `${run} build`;\n if (scripts.test) commands.test = `${run} test`;\n else if (testFramework) commands.test = `${run} test`;\n else commands.test = `${pm === 'npm' ? 'npm' : pm} test`;\n if (scripts.lint) commands.lint = `${run} lint`;\n if (scripts.typecheck) commands.typecheck = `${run} typecheck`;\n else if ((pkg.devDependencies as Record<string, string> | undefined)?.['typescript']) {\n commands.typecheck = 'tsc --noEmit';\n }\n\n return {\n language: 'node',\n packageManager: pm,\n commands,\n framework,\n };\n}\n\nfunction detectPythonFramework(content: string): string | undefined {\n if (/fastapi/i.test(content)) return 'FastAPI';\n if (/django/i.test(content)) return 'Django';\n if (/flask/i.test(content)) return 'Flask';\n return undefined;\n}\n\nfunction detectPython(dir: string): StackInfo | null {\n const pyproject = readFile(join(dir, 'pyproject.toml'));\n if (pyproject !== null) {\n const isPoetry = /\\[tool\\.poetry\\]/.test(pyproject);\n const isUv = existsSync(join(dir, 'uv.lock'));\n\n let pm: string;\n let run: string;\n if (isUv) {\n pm = 'uv';\n run = 'uv run';\n } else if (isPoetry) {\n pm = 'poetry';\n run = 'poetry run';\n } else {\n pm = 'pip';\n run = 'python -m';\n }\n\n const framework = detectPythonFramework(pyproject);\n const hasPytest = /pytest/i.test(pyproject);\n\n return {\n language: 'python',\n packageManager: pm,\n commands: {\n build: `${pm === 'poetry' ? 'poetry' : pm} build`,\n test: hasPytest ? `${run} pytest` : `${run} pytest`,\n lint: `${run} ruff check .`,\n },\n framework,\n };\n }\n\n const requirements = readFile(join(dir, 'requirements.txt'));\n if (requirements !== null) {\n const framework = detectPythonFramework(requirements);\n return {\n language: 'python',\n packageManager: 'pip',\n commands: {\n build: 'pip install -e .',\n test: 'python -m pytest',\n lint: 'python -m ruff check .',\n },\n framework,\n };\n }\n\n return null;\n}\n\nfunction detectRust(dir: string): StackInfo | null {\n const cargo = readFile(join(dir, 'Cargo.toml'));\n if (cargo === null) return null;\n\n let framework: string | undefined;\n if (/actix-web/.test(cargo)) framework = 'Actix';\n else if (/axum/.test(cargo)) framework = 'Axum';\n else if (/rocket/.test(cargo)) framework = 'Rocket';\n\n return {\n language: 'rust',\n packageManager: 'cargo',\n commands: {\n build: 'cargo build',\n test: 'cargo test',\n lint: 'cargo clippy',\n },\n framework,\n };\n}\n\nfunction detectGo(dir: string): StackInfo | null {\n const gomod = readFile(join(dir, 'go.mod'));\n if (gomod === null) return null;\n\n let framework: string | undefined;\n if (/github\\.com\\/gin-gonic\\/gin/.test(gomod)) framework = 'Gin';\n else if (/github\\.com\\/gofiber\\/fiber/.test(gomod)) framework = 'Fiber';\n else if (/github\\.com\\/labstack\\/echo/.test(gomod)) framework = 'Echo';\n\n return {\n language: 'go',\n packageManager: 'go',\n commands: {\n build: 'go build ./...',\n test: 'go test ./...',\n lint: 'golangci-lint run',\n },\n framework,\n };\n}\n\nfunction detectSwift(dir: string): StackInfo | null {\n const pkg = readFile(join(dir, 'Package.swift'));\n if (pkg === null) return null;\n\n return {\n language: 'swift',\n packageManager: 'swift',\n commands: {\n build: 'swift build',\n test: 'swift test',\n },\n };\n}\n\nfunction detectMakefile(dir: string): StackInfo | null {\n const makefile = readFile(join(dir, 'Makefile'));\n if (makefile === null) return null;\n\n const commands: StackInfo['commands'] = {};\n commands.build = 'make build';\n if (/^test:/m.test(makefile)) commands.test = 'make test';\n if (/^lint:/m.test(makefile)) commands.lint = 'make lint';\n\n return {\n language: 'unknown',\n packageManager: 'make',\n commands,\n };\n}\n\nfunction detectDockerfile(dir: string): StackInfo | null {\n if (!existsSync(join(dir, 'Dockerfile'))) return null;\n\n return {\n language: 'unknown',\n packageManager: 'docker',\n commands: {\n build: 'docker build .',\n },\n };\n}\n\nexport async function detectStack(dir: string): Promise<StackInfo> {\n const detectors = [\n detectNode,\n detectPython,\n detectRust,\n detectGo,\n detectSwift,\n detectMakefile,\n detectDockerfile,\n ];\n\n for (const detect of detectors) {\n const result = detect(dir);\n if (result) return result;\n }\n\n return { language: 'unknown', packageManager: '', commands: {} };\n}\n","import type { StackInfo } from './detect.js';\n\ninterface Section {\n header: string;\n content: string;\n}\n\nfunction parseSections(markdown: string): Section[] {\n const lines = markdown.split('\\n');\n const sections: Section[] = [];\n let currentHeader = '';\n let currentLines: string[] = [];\n\n for (const line of lines) {\n if (line.startsWith('## ')) {\n if (currentHeader || currentLines.length > 0) {\n sections.push({ header: currentHeader, content: currentLines.join('\\n') });\n }\n currentHeader = line;\n currentLines = [];\n } else {\n currentLines.push(line);\n }\n }\n\n // Push the last section\n if (currentHeader || currentLines.length > 0) {\n sections.push({ header: currentHeader, content: currentLines.join('\\n') });\n }\n\n return sections;\n}\n\nfunction hasSection(sections: Section[], pattern: RegExp): boolean {\n return sections.some(s => pattern.test(s.header));\n}\n\nfunction generateCommandsBlock(stack: StackInfo): string {\n const lines: string[] = ['```bash'];\n if (stack.commands.build) lines.push(`# Build\\n${stack.commands.build}`);\n if (stack.commands.test) lines.push(`# Test\\n${stack.commands.test}`);\n if (stack.commands.lint) lines.push(`# Lint\\n${stack.commands.lint}`);\n if (stack.commands.typecheck) lines.push(`# Type check\\n${stack.commands.typecheck}`);\n if (stack.commands.deploy) lines.push(`# Deploy\\n${stack.commands.deploy}`);\n lines.push('```');\n return lines.join('\\n');\n}\n\nfunction generateBoundariesSection(): string {\n return `## Behavioral Boundaries\n\n### ALWAYS\n- Run tests and type-check before committing\n- Use \\`verb: concise message\\` format for commits\n- Commit after completing each discrete task (atomic commits)\n- Stage specific files by name (not \\`git add -A\\` or \\`git add .\\`)\n- Read \\`docs/context/\\` before making infrastructure or config changes\n- Follow existing code patterns and style\n\n### ASK FIRST\n- Pushing to remote\n- Creating or merging pull requests\n- Adding new dependencies\n- Modifying database schema or data models\n- Changing authentication or authorization flows\n- Any destructive git operation (force-push, reset --hard, branch deletion)\n\n### NEVER\n- Push directly to main/master without approval\n- Commit .env files, secrets, or credentials\n- Use --no-verify to skip hooks\n- Amend commits that have been pushed\n- Skip type-checking or linting\n- Commit code that doesn't build`;\n}\n\nfunction generateWorkflowSection(stack: StackInfo): string {\n return `## Development Workflow\n\n${generateCommandsBlock(stack)}`;\n}\n\nfunction generateArchitectureSection(): string {\n return `## Architecture\n\n_TODO: Add a brief description of your project's architecture and key directories._`;\n}\n\nfunction generateKeyFilesSection(): string {\n return `## Key Files\n\n| File | Purpose |\n|------|---------|\n| _TODO_ | _Add key files and their purposes_ |`;\n}\n\nfunction generateGotchasSection(): string {\n return `## Common Gotchas\n\n_TODO: Add any gotchas, quirks, or non-obvious behaviors that developers should know about._`;\n}\n\nfunction generateGettingStartedSection(): string {\n return `## Getting Started with Joycraft\n\nThis project uses [Joycraft](https://github.com/maksutovic/joycraft) for AI development workflow. Available skills:\n\n| Skill | Purpose |\n|-------|---------|\n| \\`/joycraft-tune\\` | Assess your harness, apply upgrades, see path to Level 5 |\n| \\`/joycraft-new-feature\\` | Interview -> Feature Brief -> Atomic Specs |\n| \\`/joycraft-interview\\` | Lightweight brainstorm — yap about ideas, get a structured summary |\n| \\`/joycraft-decompose\\` | Break a brief into small, testable specs |\n| \\`/joycraft-session-end\\` | Capture discoveries, verify, commit |\n| \\`/joycraft-implement-level5\\` | Set up Level 5 — autofix loop, holdout scenarios, scenario evolution |\n\nRun \\`/joycraft-tune\\` to see where your project stands and what to improve next.`;\n}\n\nfunction generateExternalValidationSection(): string {\n return `## External Validation\n\nThis project uses holdout scenario tests in a separate private repo.\n\n### NEVER\n- Access, read, or reference the scenarios repo\n- Mention scenario test names or contents\n- Modify the scenarios dispatch workflow to leak test information\n\nThe scenarios repo is deliberately invisible to you. This is the holdout guarantee — like a validation set in ML.`;\n}\n\nexport function improveCLAUDEMd(existing: string, stack: StackInfo): string {\n const sections = parseSections(existing);\n const additions: string[] = [];\n\n if (!hasSection(sections, /behavioral\\s*boundar/i)) {\n additions.push(generateBoundariesSection());\n }\n\n if (!hasSection(sections, /development\\s*workflow/i) && !hasSection(sections, /workflow/i)) {\n additions.push(generateWorkflowSection(stack));\n }\n\n if (!hasSection(sections, /architecture/i)) {\n additions.push(generateArchitectureSection());\n }\n\n if (!hasSection(sections, /key\\s*files/i)) {\n additions.push(generateKeyFilesSection());\n }\n\n if (!hasSection(sections, /common\\s*gotchas/i) && !hasSection(sections, /gotchas/i)) {\n additions.push(generateGotchasSection());\n }\n\n if (!hasSection(sections, /getting\\s*started.*joycraft/i) && !hasSection(sections, /joycraft.*skills/i)) {\n additions.push(generateGettingStartedSection());\n }\n\n if (!hasSection(sections, /external\\s*validation/i)) {\n additions.push(generateExternalValidationSection());\n }\n\n if (additions.length === 0) {\n return existing;\n }\n\n // Append missing sections\n const trimmed = existing.trimEnd();\n return trimmed + '\\n\\n' + additions.join('\\n\\n') + '\\n';\n}\n\nexport function generateCLAUDEMd(projectName: string, stack: StackInfo): string {\n const frameworkNote = stack.framework ? ` (${stack.framework})` : '';\n const langLabel = stack.language === 'unknown' ? '' : ` | **Stack:** ${stack.language}${frameworkNote}`;\n\n const lines: string[] = [\n `# ${projectName}`,\n '',\n `**Component:** _TODO: describe what this project is_${langLabel}`,\n '',\n '---',\n '',\n generateBoundariesSection(),\n '',\n generateWorkflowSection(stack),\n '',\n generateArchitectureSection(),\n '',\n generateKeyFilesSection(),\n '',\n generateGotchasSection(),\n '',\n generateGettingStartedSection(),\n '',\n ];\n\n return lines.join('\\n');\n}\n","import type { StackInfo } from './detect.js';\n\ninterface Section {\n header: string;\n content: string;\n}\n\nfunction parseSections(markdown: string): Section[] {\n const lines = markdown.split('\\n');\n const sections: Section[] = [];\n let currentHeader = '';\n let currentLines: string[] = [];\n\n for (const line of lines) {\n if (line.startsWith('## ')) {\n if (currentHeader || currentLines.length > 0) {\n sections.push({ header: currentHeader, content: currentLines.join('\\n') });\n }\n currentHeader = line;\n currentLines = [];\n } else {\n currentLines.push(line);\n }\n }\n\n if (currentHeader || currentLines.length > 0) {\n sections.push({ header: currentHeader, content: currentLines.join('\\n') });\n }\n\n return sections;\n}\n\nfunction hasSection(sections: Section[], pattern: RegExp): boolean {\n return sections.some(s => pattern.test(s.header));\n}\n\nfunction generateCommandsBlock(stack: StackInfo): string {\n const lines: string[] = ['```bash'];\n if (stack.commands.build) lines.push(stack.commands.build);\n if (stack.commands.test) lines.push(stack.commands.test);\n if (stack.commands.lint) lines.push(stack.commands.lint);\n if (stack.commands.typecheck) lines.push(stack.commands.typecheck);\n if (stack.commands.deploy) lines.push(stack.commands.deploy);\n lines.push('```');\n return lines.join('\\n');\n}\n\nfunction generateBoundariesSection(): string {\n return `## Behavioral Boundaries\n\n### ALWAYS\n- Run tests and type-check before committing\n- Follow existing code patterns and style\n\n### ASK FIRST\n- Adding new dependencies\n- Changing auth or data models\n- Any destructive operation\n\n### NEVER\n- Push to main without approval\n- Skip tests or type-checking\n- Hardcode secrets or credentials`;\n}\n\nfunction generateDevelopmentSection(stack: StackInfo): string {\n return `## Development\n\n${generateCommandsBlock(stack)}`;\n}\n\nfunction generateArchitectureSection(): string {\n return `## Architecture\n\n_TODO: Add a compact directory tree and one-paragraph summary._`;\n}\n\nfunction generateKeyFilesSection(): string {\n return `## Key Files\n\n| File | Purpose |\n|------|---------|\n| _TODO_ | _Add key files_ |`;\n}\n\nexport function generateAgentsMd(projectName: string, stack: StackInfo): string {\n const frameworkNote = stack.framework ? ` (${stack.framework})` : '';\n const langLabel = stack.language === 'unknown' ? '' : ` | **Stack:** ${stack.language}${frameworkNote}`;\n\n const lines: string[] = [\n `# ${projectName}`,\n '',\n `**Component:** _TODO: describe what this project is_${langLabel}`,\n '',\n '> Auto-generated by Joycraft. See CLAUDE.md for detailed instructions.',\n '',\n '---',\n '',\n generateBoundariesSection(),\n '',\n generateArchitectureSection(),\n '',\n generateKeyFilesSection(),\n '',\n generateDevelopmentSection(stack),\n '',\n ];\n\n return lines.join('\\n');\n}\n\nexport function improveAgentsMd(existing: string, stack: StackInfo): string {\n const sections = parseSections(existing);\n const additions: string[] = [];\n\n if (!hasSection(sections, /behavioral\\s*boundar/i)) {\n additions.push(generateBoundariesSection());\n }\n\n if (!hasSection(sections, /architecture/i)) {\n additions.push(generateArchitectureSection());\n }\n\n if (!hasSection(sections, /key\\s*files/i)) {\n additions.push(generateKeyFilesSection());\n }\n\n if (!hasSection(sections, /development/i)) {\n additions.push(generateDevelopmentSection(stack));\n }\n\n if (additions.length === 0) {\n return existing;\n }\n\n const trimmed = existing.trimEnd();\n return trimmed + '\\n\\n' + additions.join('\\n\\n') + '\\n';\n}\n","import type { StackInfo } from './detect.js';\n\nexport interface PermissionRules {\n allow: string[];\n deny: string[];\n}\n\nexport function generatePermissions(stack: StackInfo): PermissionRules {\n // Default deny rules for ALL projects\n const deny: string[] = [\n 'Bash(rm -rf *)',\n 'Bash(git push --force *)',\n 'Bash(git push -f *)',\n 'Bash(git reset --hard *)',\n 'Edit(//.env*)',\n 'Edit(//*.pem)',\n 'Edit(//*.key)',\n 'Edit(//.git/**)',\n ];\n\n // Default allow rules\n const allow: string[] = [\n 'Bash(git status)',\n 'Bash(git diff *)',\n 'Bash(git log *)',\n 'Bash(git add *)',\n 'Bash(git commit *)',\n 'Bash(git checkout *)',\n 'Bash(git branch *)',\n ];\n\n // Stack-specific rules\n if (stack.language === 'node') {\n allow.push(`Bash(${stack.packageManager} *)`);\n if (stack.packageManager !== 'npm') deny.push('Bash(npm install *)');\n if (stack.packageManager !== 'yarn') deny.push('Bash(yarn add *)');\n if (stack.packageManager !== 'pnpm') deny.push('Bash(pnpm add *)');\n if (stack.packageManager !== 'bun') deny.push('Bash(bun add *)');\n if (stack.commands.test) allow.push(`Bash(${stack.commands.test})`);\n if (stack.commands.build) allow.push(`Bash(${stack.commands.build})`);\n if (stack.commands.lint) allow.push(`Bash(${stack.commands.lint})`);\n if (stack.commands.typecheck) allow.push(`Bash(${stack.commands.typecheck})`);\n }\n\n if (stack.language === 'python') {\n allow.push(`Bash(${stack.packageManager} *)`);\n if (stack.commands.test) allow.push(`Bash(${stack.commands.test})`);\n if (stack.commands.lint) allow.push(`Bash(${stack.commands.lint})`);\n if (stack.commands.build) allow.push(`Bash(${stack.commands.build})`);\n }\n\n if (stack.language === 'rust') {\n allow.push('Bash(cargo *)');\n }\n\n if (stack.language === 'go') {\n allow.push('Bash(go *)');\n }\n\n if (stack.language === 'swift') {\n allow.push('Bash(swift *)');\n allow.push('Bash(xcodebuild *)');\n }\n\n return { allow, deny };\n}\n","import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';\nimport { join } from 'node:path';\n\nexport interface SafeguardConfig {\n denyPatterns: string[];\n}\n\n/**\n * Generate default deny patterns from common dangerous operations.\n */\nexport function getDefaultDenyPatterns(): string[] {\n return [\n 'rm\\\\s+-rf\\\\s+/', // rm -rf with absolute path\n 'rm\\\\s+-rf\\\\s+\\\\.', // rm -rf . or ./\n 'git\\\\s+push\\\\s+--force', // force push\n 'git\\\\s+push\\\\s+-f\\\\b', // force push shorthand\n 'git\\\\s+reset\\\\s+--hard', // hard reset\n 'DROP\\\\s+TABLE', // SQL drop\n 'DROP\\\\s+DATABASE', // SQL drop\n 'TRUNCATE', // SQL truncate\n 'chmod\\\\s+777', // wide-open permissions\n 'curl.*\\\\|.*sh', // pipe curl to shell\n 'wget.*\\\\|.*sh', // pipe wget to shell\n ];\n}\n\n/**\n * Generate the hook script that blocks dangerous Bash commands.\n */\nexport function generateHookScript(): string {\n return `#!/bin/bash\n# Joycraft Safeguard — PreToolUse hook\n# Blocks dangerous Bash commands. Exit 2 = block the action.\n# Edit deny-patterns.txt to customize what's blocked.\n\nTOOL_NAME=\"$1\"\n# Read the full tool input from stdin\nINPUT=$(cat)\n\n# Only check Bash commands\nif [ \"$TOOL_NAME\" != \"Bash\" ]; then\n exit 0\nfi\n\n# Extract the command from the JSON input\nCOMMAND=$(echo \"$INPUT\" | grep -o '\"command\":\"[^\"]*\"' | head -1 | sed 's/\"command\":\"//;s/\"$//')\n\nif [ -z \"$COMMAND\" ]; then\n exit 0\nfi\n\nPATTERNS_FILE=\"$(dirname \"$0\")/deny-patterns.txt\"\n\nif [ ! -f \"$PATTERNS_FILE\" ]; then\n exit 0\nfi\n\nwhile IFS= read -r pattern || [ -n \"$pattern\" ]; do\n # Skip empty lines and comments\n [ -z \"$pattern\" ] && continue\n [[ \"$pattern\" == \\\\#* ]] && continue\n\n if echo \"$COMMAND\" | grep -qEi \"$pattern\"; then\n echo \"Blocked by Joycraft Safeguard: command matches deny pattern '$pattern'\"\n echo \"Edit .claude/hooks/joycraft/deny-patterns.txt to modify blocked patterns.\"\n exit 2\n fi\ndone < \"$PATTERNS_FILE\"\n\nexit 0\n`;\n}\n\n/**\n * Generate deny-patterns.txt content from default patterns + custom patterns.\n */\nexport function generateDenyPatternsFile(customPatterns: string[] = []): string {\n const lines = [\n '# Joycraft Safeguard — Deny Patterns',\n '# One regex pattern per line. Lines starting with # are comments.',\n '# Commands matching any pattern will be blocked (exit 2).',\n '# Edit this file to customize what\\'s blocked.',\n '',\n '# Destructive file operations',\n 'rm\\\\s+-rf\\\\s+/',\n 'rm\\\\s+-rf\\\\s+\\\\.',\n '',\n '# Dangerous git operations',\n 'git\\\\s+push\\\\s+--force',\n 'git\\\\s+push\\\\s+-f\\\\b',\n 'git\\\\s+reset\\\\s+--hard',\n '',\n '# SQL destruction',\n 'DROP\\\\s+TABLE',\n 'DROP\\\\s+DATABASE',\n 'TRUNCATE',\n '',\n '# System security',\n 'chmod\\\\s+777',\n 'curl.*\\\\|.*sh',\n 'wget.*\\\\|.*sh',\n ];\n\n if (customPatterns.length > 0) {\n lines.push('');\n lines.push('# Project-specific patterns (from risk interview)');\n for (const p of customPatterns) {\n lines.push(p);\n }\n }\n\n return lines.join('\\n') + '\\n';\n}\n\n/**\n * Install safeguard hooks into a project.\n */\nexport function installSafeguardHooks(\n targetDir: string,\n customPatterns: string[] = [],\n force: boolean = false\n): { created: string[]; skipped: string[] } {\n const result = { created: [] as string[], skipped: [] as string[] };\n const hooksDir = join(targetDir, '.claude', 'hooks', 'joycraft');\n\n if (!existsSync(hooksDir)) {\n mkdirSync(hooksDir, { recursive: true });\n }\n\n // Write hook script\n const hookPath = join(hooksDir, 'block-dangerous.sh');\n if (!existsSync(hookPath) || force) {\n writeFileSync(hookPath, generateHookScript(), { mode: 0o755 });\n result.created.push(hookPath);\n } else {\n result.skipped.push(hookPath);\n }\n\n // Write deny patterns\n const patternsPath = join(hooksDir, 'deny-patterns.txt');\n if (!existsSync(patternsPath) || force) {\n writeFileSync(patternsPath, generateDenyPatternsFile(customPatterns));\n result.created.push(patternsPath);\n } else {\n result.skipped.push(patternsPath);\n }\n\n // Register hook in settings.json\n const settingsPath = join(targetDir, '.claude', 'settings.json');\n let settings: Record<string, unknown> = {};\n if (existsSync(settingsPath)) {\n try {\n settings = JSON.parse(readFileSync(settingsPath, 'utf-8'));\n } catch {}\n }\n\n if (!settings.hooks) settings.hooks = {};\n const hooks = settings.hooks as Record<string, unknown[]>;\n if (!hooks.PreToolUse) hooks.PreToolUse = [];\n\n const preToolUse = hooks.PreToolUse as Array<Record<string, unknown>>;\n const hasJoycraftHook = preToolUse.some(h => {\n const innerHooks = h.hooks as Array<Record<string, unknown>> | undefined;\n return innerHooks?.some(ih => typeof ih.command === 'string' && ih.command.includes('joycraft'));\n });\n\n if (!hasJoycraftHook) {\n preToolUse.push({\n matcher: 'Bash',\n hooks: [{\n type: 'command',\n command: '.claude/hooks/joycraft/block-dangerous.sh',\n }],\n });\n writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\\n', 'utf-8');\n }\n\n return result;\n}\n"],"mappings":";;;;;;;;;;;AAAA,SAAS,aAAAA,YAAW,cAAAC,aAAY,iBAAAC,gBAAe,gBAAAC,qBAAoB;AACnE,SAAS,QAAAC,OAAM,UAAU,SAAS,eAAe;;;ACDjD,SAAS,cAAc,kBAAkB;AACzC,SAAS,YAAY;AAerB,SAAS,SAAS,MAA6B;AAC7C,MAAI;AACF,WAAO,aAAa,MAAM,OAAO;AAAA,EACnC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,SAAS,oBAAoB,KAA8G;AACzI,QAAM,UAAU,EAAE,GAAG,IAAI,cAAc,GAAG,IAAI,gBAAgB;AAC9D,MAAI,QAAQ,MAAM,EAAG,QAAO;AAC5B,MAAI,QAAQ,MAAM,EAAG,QAAO;AAC5B,MAAI,QAAQ,iBAAiB,KAAK,QAAQ,kBAAkB,EAAG,QAAO;AACtE,MAAI,QAAQ,SAAS,EAAG,QAAO;AAC/B,MAAI,QAAQ,SAAS,EAAG,QAAO;AAC/B,MAAI,QAAQ,OAAO,EAAG,QAAO;AAC7B,MAAI,QAAQ,KAAK,EAAG,QAAO;AAC3B,MAAI,QAAQ,QAAQ,EAAG,QAAO;AAC9B,SAAO;AACT;AAEA,SAAS,wBAAwB,KAA8G;AAC7I,QAAM,UAAU,EAAE,GAAG,IAAI,cAAc,GAAG,IAAI,gBAAgB;AAC9D,MAAI,QAAQ,QAAQ,EAAG,QAAO;AAC9B,MAAI,QAAQ,MAAM,EAAG,QAAO;AAC5B,MAAI,QAAQ,OAAO,EAAG,QAAO;AAC7B,SAAO;AACT;AAEA,SAAS,yBAAyB,KAAqB;AACrD,MAAI,WAAW,KAAK,KAAK,gBAAgB,CAAC,EAA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iBAAiB;AAC7B,MAAI,mBAAmB;AACrB,YAAQ,IAAI,6FAA6F;AAAA,EAC3G,OAAO;AACL,YAAQ,IAAI,sEAAsE;AAAA,EACpF;AACA,UAAQ,IAAI,kFAAkF;AAC9F,UAAQ,IAAI,6EAA6E;AACzF,UAAQ,IAAI,EAAE;AAChB;","names":["mkdirSync","existsSync","writeFileSync","readFileSync","join","generateCommandsBlock","generateBoundariesSection","generateArchitectureSection","generateKeyFilesSection","existsSync","readFileSync","join","join","existsSync","readFileSync","existsSync","mkdirSync","writeFileSync","join","readFileSync"]}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
TEMPLATES
|
|
4
|
+
} from "./chunk-HHW4Q2UC.js";
|
|
5
|
+
|
|
6
|
+
// src/init-autofix.ts
|
|
7
|
+
import { mkdirSync, existsSync, writeFileSync } from "fs";
|
|
8
|
+
import { join, resolve, basename, dirname } from "path";
|
|
9
|
+
function ensureDir(dir) {
|
|
10
|
+
if (!existsSync(dir)) {
|
|
11
|
+
mkdirSync(dir, { recursive: true });
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
function replacePlaceholders(content, vars) {
|
|
15
|
+
let result = content;
|
|
16
|
+
for (const [key, value] of Object.entries(vars)) {
|
|
17
|
+
result = result.replaceAll("$" + key, value);
|
|
18
|
+
}
|
|
19
|
+
return result;
|
|
20
|
+
}
|
|
21
|
+
async function initAutofix(dir, opts) {
|
|
22
|
+
const targetDir = resolve(dir);
|
|
23
|
+
if (!existsSync(join(targetDir, ".joycraft-version"))) {
|
|
24
|
+
throw new Error("Project is not initialized. Run `npx joycraft init` first.");
|
|
25
|
+
}
|
|
26
|
+
const force = opts.force ?? false;
|
|
27
|
+
const dryRun = opts.dryRun ?? false;
|
|
28
|
+
const scenariosRepo = opts.scenariosRepo ?? `${basename(targetDir)}-scenarios`;
|
|
29
|
+
const appId = opts.appId;
|
|
30
|
+
const vars = {
|
|
31
|
+
SCENARIOS_REPO: scenariosRepo
|
|
32
|
+
};
|
|
33
|
+
if (appId !== void 0) {
|
|
34
|
+
vars["JOYCRAFT_APP_ID"] = appId;
|
|
35
|
+
}
|
|
36
|
+
const result = { created: [], skipped: [] };
|
|
37
|
+
const workflowsDir = join(targetDir, ".github", "workflows");
|
|
38
|
+
for (const [key, rawContent] of Object.entries(TEMPLATES)) {
|
|
39
|
+
if (!key.startsWith("workflows/")) continue;
|
|
40
|
+
const filename = key.slice("workflows/".length);
|
|
41
|
+
const destPath = join(workflowsDir, filename);
|
|
42
|
+
const content = replacePlaceholders(rawContent, vars);
|
|
43
|
+
if (dryRun) {
|
|
44
|
+
result.created.push(destPath);
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
if (existsSync(destPath) && !force) {
|
|
48
|
+
result.skipped.push(destPath);
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
ensureDir(dirname(destPath));
|
|
52
|
+
writeFileSync(destPath, content, "utf-8");
|
|
53
|
+
result.created.push(destPath);
|
|
54
|
+
}
|
|
55
|
+
const scenariosTemplateDir = join(targetDir, "docs", "templates", "scenarios");
|
|
56
|
+
for (const [key, rawContent] of Object.entries(TEMPLATES)) {
|
|
57
|
+
if (!key.startsWith("scenarios/")) continue;
|
|
58
|
+
const relativePath = key.slice("scenarios/".length);
|
|
59
|
+
const destPath = join(scenariosTemplateDir, relativePath);
|
|
60
|
+
const content = replacePlaceholders(rawContent, vars);
|
|
61
|
+
if (dryRun) {
|
|
62
|
+
result.created.push(destPath);
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
if (existsSync(destPath) && !force) {
|
|
66
|
+
result.skipped.push(destPath);
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
ensureDir(dirname(destPath));
|
|
70
|
+
writeFileSync(destPath, content, "utf-8");
|
|
71
|
+
result.created.push(destPath);
|
|
72
|
+
}
|
|
73
|
+
printSummary(result, dryRun, scenariosRepo);
|
|
74
|
+
}
|
|
75
|
+
function printSummary(result, dryRun, scenariosRepo) {
|
|
76
|
+
if (dryRun) {
|
|
77
|
+
console.log("\nDry run \u2014 these files would be created:\n");
|
|
78
|
+
for (const f of result.created) {
|
|
79
|
+
console.log(` + ${f}`);
|
|
80
|
+
}
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
console.log("\nJoycraft Autofix initialized!\n");
|
|
84
|
+
if (result.created.length > 0) {
|
|
85
|
+
console.log(` Created ${result.created.length} file(s):`);
|
|
86
|
+
for (const f of result.created) {
|
|
87
|
+
console.log(` + ${f}`);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
if (result.skipped.length > 0) {
|
|
91
|
+
console.log(`
|
|
92
|
+
Skipped ${result.skipped.length} file(s) (already exist, use --force to overwrite):`);
|
|
93
|
+
for (const f of result.skipped) {
|
|
94
|
+
console.log(` - ${f}`);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
console.log("\n Setup checklist:\n");
|
|
98
|
+
console.log(" 1. Create a GitHub App with these permissions:");
|
|
99
|
+
console.log(" - Contents: Read & Write");
|
|
100
|
+
console.log(" - Actions: Read & Write");
|
|
101
|
+
console.log(" - Pull requests: Read & Write");
|
|
102
|
+
console.log("");
|
|
103
|
+
console.log(" 2. Add these secrets to your main repo (GitHub Settings > Secrets):");
|
|
104
|
+
console.log(" JOYCRAFT_APP_PRIVATE_KEY \u2014 private key PEM from your GitHub App");
|
|
105
|
+
console.log(" ANTHROPIC_API_KEY \u2014 your Anthropic API key");
|
|
106
|
+
console.log("");
|
|
107
|
+
console.log(" 3. Create the scenarios repo (private):");
|
|
108
|
+
console.log(` ${scenariosRepo}`);
|
|
109
|
+
console.log(" Copy docs/templates/scenarios/ into it as the repo root.");
|
|
110
|
+
console.log("");
|
|
111
|
+
console.log(" 4. Update autofix.yml with your GitHub App ID if not already set.");
|
|
112
|
+
console.log("");
|
|
113
|
+
console.log(" Run `npx joycraft init-autofix --help` for options.\n");
|
|
114
|
+
}
|
|
115
|
+
export {
|
|
116
|
+
initAutofix
|
|
117
|
+
};
|
|
118
|
+
//# sourceMappingURL=init-autofix-OVHXYVLB.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/init-autofix.ts"],"sourcesContent":["import { mkdirSync, existsSync, writeFileSync } from 'node:fs';\nimport { join, resolve, basename, dirname } from 'node:path';\nimport { TEMPLATES } from './bundled-files.js';\n\nexport interface InitAutofixOptions {\n scenariosRepo?: string;\n appId?: string;\n force?: boolean;\n dryRun?: boolean;\n}\n\ninterface AutofixResult {\n created: string[];\n skipped: string[];\n}\n\nfunction ensureDir(dir: string): void {\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n}\n\n/**\n * Replace literal placeholders in content.\n * Replaces $KEY but intentionally leaves ${{ ... }} GitHub Actions expressions untouched —\n * the simple string replace of \"$KEY\" won't match \"${{\" since \"${{\" != \"$\" + \"KEY\".\n */\nfunction replacePlaceholders(content: string, vars: Record<string, string>): string {\n let result = content;\n for (const [key, value] of Object.entries(vars)) {\n // Only replace literal $KEY, not ${{ expressions }}\n // Use a regex that matches $KEY but not ${{\n result = result.replaceAll('$' + key, value);\n }\n return result;\n}\n\nexport async function initAutofix(dir: string, opts: InitAutofixOptions): Promise<void> {\n const targetDir = resolve(dir);\n\n // Check project is initialized\n if (!existsSync(join(targetDir, '.joycraft-version'))) {\n throw new Error('Project is not initialized. Run `npx joycraft init` first.');\n }\n\n const force = opts.force ?? false;\n const dryRun = opts.dryRun ?? false;\n\n // Determine placeholder values\n const scenariosRepo = opts.scenariosRepo ?? `${basename(targetDir)}-scenarios`;\n const appId = opts.appId; // may be undefined — leave $JOYCRAFT_APP_ID as-is if so\n\n const vars: Record<string, string> = {\n SCENARIOS_REPO: scenariosRepo,\n };\n if (appId !== undefined) {\n vars['JOYCRAFT_APP_ID'] = appId;\n }\n\n const result: AutofixResult = { created: [], skipped: [] };\n\n // Install workflow templates to .github/workflows/\n const workflowsDir = join(targetDir, '.github', 'workflows');\n for (const [key, rawContent] of Object.entries(TEMPLATES)) {\n if (!key.startsWith('workflows/')) continue;\n const filename = key.slice('workflows/'.length); // e.g. \"autofix.yml\"\n const destPath = join(workflowsDir, filename);\n const content = replacePlaceholders(rawContent, vars);\n\n if (dryRun) {\n result.created.push(destPath);\n continue;\n }\n\n if (existsSync(destPath) && !force) {\n result.skipped.push(destPath);\n continue;\n }\n\n ensureDir(dirname(destPath));\n writeFileSync(destPath, content, 'utf-8');\n result.created.push(destPath);\n }\n\n // Install scenario templates to docs/templates/scenarios/\n const scenariosTemplateDir = join(targetDir, 'docs', 'templates', 'scenarios');\n for (const [key, rawContent] of Object.entries(TEMPLATES)) {\n if (!key.startsWith('scenarios/')) continue;\n const relativePath = key.slice('scenarios/'.length); // e.g. \"README.md\" or \"workflows/run.yml\"\n const destPath = join(scenariosTemplateDir, relativePath);\n const content = replacePlaceholders(rawContent, vars);\n\n if (dryRun) {\n result.created.push(destPath);\n continue;\n }\n\n if (existsSync(destPath) && !force) {\n result.skipped.push(destPath);\n continue;\n }\n\n ensureDir(dirname(destPath));\n writeFileSync(destPath, content, 'utf-8');\n result.created.push(destPath);\n }\n\n printSummary(result, dryRun, scenariosRepo);\n}\n\nfunction printSummary(result: AutofixResult, dryRun: boolean, scenariosRepo: string): void {\n if (dryRun) {\n console.log('\\nDry run — these files would be created:\\n');\n for (const f of result.created) {\n console.log(` + ${f}`);\n }\n return;\n }\n\n console.log('\\nJoycraft Autofix initialized!\\n');\n\n if (result.created.length > 0) {\n console.log(` Created ${result.created.length} file(s):`);\n for (const f of result.created) {\n console.log(` + ${f}`);\n }\n }\n\n if (result.skipped.length > 0) {\n console.log(`\\n Skipped ${result.skipped.length} file(s) (already exist, use --force to overwrite):`);\n for (const f of result.skipped) {\n console.log(` - ${f}`);\n }\n }\n\n console.log('\\n Setup checklist:\\n');\n console.log(' 1. Create a GitHub App with these permissions:');\n console.log(' - Contents: Read & Write');\n console.log(' - Actions: Read & Write');\n console.log(' - Pull requests: Read & Write');\n console.log('');\n console.log(' 2. Add these secrets to your main repo (GitHub Settings > Secrets):');\n console.log(' JOYCRAFT_APP_PRIVATE_KEY — private key PEM from your GitHub App');\n console.log(' ANTHROPIC_API_KEY — your Anthropic API key');\n console.log('');\n console.log(' 3. Create the scenarios repo (private):');\n console.log(` ${scenariosRepo}`);\n console.log(' Copy docs/templates/scenarios/ into it as the repo root.');\n console.log('');\n console.log(' 4. Update autofix.yml with your GitHub App ID if not already set.');\n console.log('');\n console.log(' Run `npx joycraft init-autofix --help` for options.\\n');\n}\n"],"mappings":";;;;;;AAAA,SAAS,WAAW,YAAY,qBAAqB;AACrD,SAAS,MAAM,SAAS,UAAU,eAAe;AAejD,SAAS,UAAU,KAAmB;AACpC,MAAI,CAAC,WAAW,GAAG,GAAG;AACpB,cAAU,KAAK,EAAE,WAAW,KAAK,CAAC;AAAA,EACpC;AACF;AAOA,SAAS,oBAAoB,SAAiB,MAAsC;AAClF,MAAI,SAAS;AACb,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,IAAI,GAAG;AAG/C,aAAS,OAAO,WAAW,MAAM,KAAK,KAAK;AAAA,EAC7C;AACA,SAAO;AACT;AAEA,eAAsB,YAAY,KAAa,MAAyC;AACtF,QAAM,YAAY,QAAQ,GAAG;AAG7B,MAAI,CAAC,WAAW,KAAK,WAAW,mBAAmB,CAAC,GAAG;AACrD,UAAM,IAAI,MAAM,4DAA4D;AAAA,EAC9E;AAEA,QAAM,QAAQ,KAAK,SAAS;AAC5B,QAAM,SAAS,KAAK,UAAU;AAG9B,QAAM,gBAAgB,KAAK,iBAAiB,GAAG,SAAS,SAAS,CAAC;AAClE,QAAM,QAAQ,KAAK;AAEnB,QAAM,OAA+B;AAAA,IACnC,gBAAgB;AAAA,EAClB;AACA,MAAI,UAAU,QAAW;AACvB,SAAK,iBAAiB,IAAI;AAAA,EAC5B;AAEA,QAAM,SAAwB,EAAE,SAAS,CAAC,GA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