diff --git a/docs/project-changelog.md b/docs/project-changelog.md index 3ab04231..ea4a4688 100644 --- a/docs/project-changelog.md +++ b/docs/project-changelog.md @@ -5,6 +5,18 @@ All notable changes to CafeKit are documented here, following ## [Unreleased] +### Fixed +- Installer no longer resets `locale.responseLanguage` to `en` on non-interactive upgrade (saved-locale restore hoisted above the interactivity check + no-downgrade guard; live regression fixture). Statusline autocompact reserve is proportional to the real context window (1M models no longer treated as 200k). + +### Changed +- `spec.{scaffold_guard, completion_gate, tollgate}` documented in runtime.json; Claude reminder honors `tollgate` like OpenCode; dead `useGemini` key dropped; `usage.cjs` OAuth endpoint marked experimental; legacy `Task`-tool prose → `Agent`; `inspector`/`debugger` gain `memory: user`. + +### Removed +- Legacy `archive-command/` tree (1,680 dead lines) + vestigial references. + +### Added +- Self-test: settings-template ↔ migration-manifest hook consistency check (11 hooks). + ## [0.14.1] - 2026-07-17 ### Fixed diff --git a/packages/spec/CHANGELOG.md b/packages/spec/CHANGELOG.md index 64464eae..0d8cfa9a 100644 --- a/packages/spec/CHANGELOG.md +++ b/packages/spec/CHANGELOG.md @@ -7,6 +7,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fixed +- **Installer preserves configured locale on non-interactive upgrade**: `selectLanguage` returned before restoring the saved locale when run with `--yes`, so every upgrade reset `locale.responseLanguage` to `en` (reproduced on 0.14.0 and 0.14.1). Saved-locale restore now runs regardless of interactivity, plus a hardening guard in `patchRuntimeLocale` never downgrades a configured label when the run made no explicit language choice. Covered by a live installer regression fixture proven to fail on the unpatched code. +- **Statusline context bar on 1M-context models**: the autocompact reserve was a hard-coded 45000 tokens (22.5% of a 200k window); it is now proportional (`0.225 × context_window_size` from the payload), so 1M windows are no longer treated as 200k. 200k behavior unchanged. + +### Changed +- **`spec` toggles unified and documented**: `runtime.json` template now lists `spec.{scaffold_guard, completion_gate, tollgate}`; the Claude `spec-state.cjs` reminder honors `spec.tollgate: false` (same key the OpenCode plugin already used). Dead `skills.research.useGemini` key removed from the template and config defaults (the research skill uses native WebSearch). `paths.plans` documented. +- **`usage.cjs` marked experimental**: the OAuth usage endpoint is undocumented and may break without notice; header now states the degradation contract (`status:"unavailable"`, statusline hides the segment) and the disable switch. +- Legacy `Task`-tool prose modernized to the `Agent` tool in develop/test/hotfix skill text (deliberate backward-compat notes in `CLAUDE.md` and `subagent-patterns.md` kept). `inspector` and `debugger` agents now carry `memory: user` like `researcher`. + +### Removed +- **Legacy `archive-command/` tree** (1,680 lines, 12 files): the pre-skill command-based spec workflow, superseded since the skills migration and never installed by the manifest. Vestigial `sourceSubdir` reference and its self-test assertion cleaned. + +### Added +- **Self-test: settings/manifest hook consistency check** — every `hooks/*.cjs` registered in the settings template must exist in the payload and in `migration-manifest.json` `runtime.files`, and vice versa (schema-drift tripwire; 11 hooks verified). + ## [0.14.1] - 2026-07-17 ### Fixed diff --git a/packages/spec/bin/lib/context.js b/packages/spec/bin/lib/context.js index 8f8b0f13..0d13b6f3 100644 --- a/packages/spec/bin/lib/context.js +++ b/packages/spec/bin/lib/context.js @@ -93,7 +93,7 @@ const PLATFORMS = { skillsRef: '.opencode/skills', commandPrefix: '/', sourceDir: 'claude', - sourceSubdir: 'archive-command' + sourceSubdir: 'commands' // Dead config (manifest commands.core is []); kept for shape parity } // Add new platforms here: // cursor: { diff --git a/packages/spec/bin/phases/post-install.js b/packages/spec/bin/phases/post-install.js index 37fb8a01..1beff716 100644 --- a/packages/spec/bin/phases/post-install.js +++ b/packages/spec/bin/phases/post-install.js @@ -93,6 +93,10 @@ function patchRuntimeLocale(ctx) { // Use locale (freeform label) so custom languages propagate to the AI hook. const locale = ctx.locale || ctx.lang; if (data.locale.responseLanguage === locale) continue; + // Hardening: never downgrade an existing configured label to a bare default + // code when this run never made an explicit language choice (ctx.locale + // empty). Protects user config on any code path that skips selectLanguage. + if (!ctx.locale && data.locale.responseLanguage) continue; data.locale.responseLanguage = locale; fs.writeFileSync(rtPath, `${JSON.stringify(data, null, 2)}\n`, 'utf8'); if (ctx.trackers[key]) ctx.trackers[key].record(rtPath); diff --git a/packages/spec/bin/phases/select-platform.js b/packages/spec/bin/phases/select-platform.js index 47707249..5a130e3b 100644 --- a/packages/spec/bin/phases/select-platform.js +++ b/packages/spec/bin/phases/select-platform.js @@ -35,17 +35,22 @@ function getInstalledLocale() { /** First step: pick the installer/UI language (interactive only). */ async function selectLanguage(ctx) { - if (!ctx.interactive || ctx.options.lang) return ctx; - - // If already installed, restore saved locale and skip the prompt - const savedLocale = getInstalledLocale(); - if (savedLocale) { - const code = Object.keys(LANGUAGE_LABELS).find((k) => LANGUAGE_LABELS[k] === savedLocale) || 'en'; - ctx.setLang(code, savedLocale); // updates ctx.t to the saved language - ctx.ui.info(ctx.t('langKept', { lang: savedLocale })); - return ctx; + // Restore the saved locale BEFORE the interactivity check: a non-interactive + // upgrade (--yes) must not forget the configured language. Skipping this left + // ctx at the 'en' default, and patchRuntimeLocale then clobbered the user's + // responseLanguage on every upgrade. + if (!ctx.options.lang) { + const savedLocale = getInstalledLocale(); + if (savedLocale) { + const code = Object.keys(LANGUAGE_LABELS).find((k) => LANGUAGE_LABELS[k] === savedLocale) || 'en'; + ctx.setLang(code, savedLocale); // updates ctx.t to the saved language + if (ctx.interactive) ctx.ui.info(ctx.t('langKept', { lang: savedLocale })); + return ctx; + } } + if (!ctx.interactive || ctx.options.lang) return ctx; + const options = [ ...SUPPORTED.map((code) => ({ value: code, label: LANGUAGE_LABELS[code] })), { value: OTHER, label: OTHER_LABEL.en + ' / その他 / Ngôn ngữ khác' } diff --git a/packages/spec/scripts/run-skill-self-tests.mjs b/packages/spec/scripts/run-skill-self-tests.mjs index c2d7c894..5e02e617 100644 --- a/packages/spec/scripts/run-skill-self-tests.mjs +++ b/packages/spec/scripts/run-skill-self-tests.mjs @@ -290,14 +290,6 @@ async function runStaticSemanticTests() { assert: (content) => content.includes("Init is never a stop point"), }, - { - label: "legacy spec-init redirects to hapo specs resume", - file: "src/claude/archive-command/spec-init.md", - assert: (content) => - content.includes("templates/spec-state.json") && - content.includes("/hapo:specs resume ") && - !content.includes("Command block showing `/spec-requirements"), - }, { label: "hapo:specs task rules require runtime reachability proof", file: "src/claude/skills/specs/rules/tasks-generation.md", @@ -959,6 +951,104 @@ async function runInstallerMigrationFixtureTests() { } } +/** + * Schema-drift tripwire: every hook command in the settings template must map + * to a real payload file that the migration manifest ships, and vice versa — + * a hook listed in runtime.files but registered nowhere is dead weight, a hook + * registered in settings but not shipped breaks at runtime. + */ +async function runSettingsManifestConsistencyCheck() { + const settings = JSON.parse( + await readFile(join(packageRoot, "src/claude/settings/settings.json"), "utf8"), + ); + const manifest = JSON.parse( + await readFile(join(packageRoot, "src/claude/migration-manifest.json"), "utf8"), + ); + + const registered = new Set( + JSON.stringify(settings.hooks).match(/hooks\/[a-z-]+\.cjs/g) || [], + ); + const shipped = new Set( + (manifest.runtime?.files || []).filter((f) => /^hooks\/[a-z-]+\.cjs$/.test(f)), + ); + + const failures = []; + for (const hook of registered) { + if (!shipped.has(hook)) failures.push(`registered in settings but not in manifest runtime.files: ${hook}`); + if (!(await fileExists(join(packageRoot, "src/claude", hook)))) { + failures.push(`registered in settings but payload file missing: ${hook}`); + } + } + for (const hook of shipped) { + if (!registered.has(hook)) failures.push(`shipped in manifest but registered in no settings event: ${hook}`); + } + + if (failures.length > 0) { + console.error(failures.join("\n")); + console.error("[FAIL] settings/manifest hook consistency check failed"); + process.exit(1); + } + + console.log(`✔ settings template and manifest agree on ${registered.size} hooks`); + return 1; +} + +/** + * Regression: a non-interactive upgrade (--yes/--force-overwrite) must preserve + * the configured locale.responseLanguage. Bug (0.14.0/0.14.1 era): selectLanguage + * returned before restoring the saved locale when !interactive, so + * patchRuntimeLocale clobbered the label with the 'en' default on every upgrade. + */ +async function runLocalePreservationFixtureTest() { + const root = await mkdtemp(join(tmpdir(), "cafekit-installer-locale-")); + + try { + await mkdir(join(root, ".claude"), { recursive: true }); + + const install = (args = []) => + spawnSync(process.execPath, [join(packageRoot, "bin", "install.js"), ...args], { + cwd: root, + input: "n\n\n", + encoding: "utf8", + env: { ...process.env, PATH: "/usr/bin:/bin" }, + }); + + const first = install(); + if (first.status !== 0) { + console.error(first.stdout, first.stderr); + console.error("[FAIL] locale fixture: fresh install failed"); + process.exit(1); + } + + // Simulate a configured install: user language saved as a freeform label. + const rtPath = join(root, ".claude", "runtime.json"); + const rt = JSON.parse(await readFile(rtPath, "utf8")); + rt.locale = { ...(rt.locale || {}), responseLanguage: "Tiếng Việt" }; + await writeFile(rtPath, `${JSON.stringify(rt, null, 2)}\n`); + + // Non-interactive upgrade — the exact path that clobbered the locale. + const second = install(["--force-overwrite"]); + if (second.status !== 0) { + console.error(second.stdout, second.stderr); + console.error("[FAIL] locale fixture: upgrade run failed"); + process.exit(1); + } + + const after = JSON.parse(await readFile(rtPath, "utf8")); + if (after.locale?.responseLanguage !== "Tiếng Việt") { + console.error( + `[FAIL] locale fixture: responseLanguage became ${JSON.stringify(after.locale?.responseLanguage)} after upgrade (expected "Tiếng Việt")`, + ); + process.exit(1); + } + + console.log("✔ installer upgrade preserves configured locale.responseLanguage"); + return 1; + } finally { + await rm(root, { recursive: true, force: true }); + } +} + async function runOpenCodeInstallerFixtureTests() { const root = await mkdtemp(join(tmpdir(), "cafekit-opencode-installer-")); @@ -1520,7 +1610,9 @@ async function main() { console.log("\n[skill-test] skill catalog checks"); totalTests += runSkillCatalogTests(); console.log("\n[skill-test] installer migration fixtures"); + totalTests += await runSettingsManifestConsistencyCheck(); totalTests += await runInstallerMigrationFixtureTests(); + totalTests += await runLocalePreservationFixtureTest(); console.log("\n[skill-test] OpenCode installer fixtures"); totalTests += await runOpenCodeInstallerFixtureTests(); console.log("\n[skill-test] spec artifact validator fixtures"); diff --git a/packages/spec/src/claude/agents/debugger.md b/packages/spec/src/claude/agents/debugger.md index 321b74bc..1e266d90 100644 --- a/packages/spec/src/claude/agents/debugger.md +++ b/packages/spec/src/claude/agents/debugger.md @@ -2,6 +2,7 @@ name: debugger description: "Investigates bugs, incidents, CI/log/DB/performance/frontend failures, traces exact root causes with evidence, and hands off a verification-ready fix plan. Edits code only when explicitly requested by a fix workflow." model: sonnet +memory: user tools: Glob, Grep, Read, Bash, WebFetch, WebSearch --- diff --git a/packages/spec/src/claude/agents/inspector.md b/packages/spec/src/claude/agents/inspector.md index 4201b2ce..03f147ed 100644 --- a/packages/spec/src/claude/agents/inspector.md +++ b/packages/spec/src/claude/agents/inspector.md @@ -3,6 +3,7 @@ name: inspector tools: Glob, Grep, Read, Bash description: "Codebase structure scanner. Use this agent when you need to quickly scout/inspect the codebase architecture, files, and directories. Specializes in finding relevant files for a given work scope before implementation begins." model: haiku +memory: user --- # Inspect — Codebase Scout diff --git a/packages/spec/src/claude/archive-command/code.md b/packages/spec/src/claude/archive-command/code.md deleted file mode 100644 index 6e9934b1..00000000 --- a/packages/spec/src/claude/archive-command/code.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: code -description: Implement approved work from specification tasks and then hand off to test and review. -allowed-tools: Read, Glob, Grep, Edit, Write, Bash -argument-hint: ---- - -# /code - Implement from spec tasks - -Use this command after /spec-tasks. - -1. Read `.specs/$ARGUMENTS/tasks.md` and identify the next pending task. -2. Implement only that task following project standards. -3. Run `/test`. -4. Run `/review`. - -Preferred flow: /spec-init -> /spec-requirements -> /spec-design -> /spec-tasks -> /code -> /test -> /review diff --git a/packages/spec/src/claude/archive-command/code/SKILL.md b/packages/spec/src/claude/archive-command/code/SKILL.md deleted file mode 100644 index 0e3447e4..00000000 --- a/packages/spec/src/claude/archive-command/code/SKILL.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -name: hapo:code -description: Implement the next approved spec task and then hand off to hapo:test and hapo:review. -version: 1.0.0 -argument-hint: ---- - -# Code - -Implement the next pending task from an approved spec instead of coding from memory. - -## Usage - -```bash -/hapo:code -``` - -## Load First - -- `references/execution-loop.md` -- `.specs/$ARGUMENTS/tasks.md` -- `.specs/$ARGUMENTS/design.md` -- `.specs/$ARGUMENTS/requirements.md` - -## Execute - -1. Read `.specs/$ARGUMENTS/tasks.md` and identify the next pending task. -2. Read the related context from `design.md` and `requirements.md`. -3. Implement only that task. Keep scope tight. -4. Follow the project standards already present in the repo. -5. Update task status in the spec artifact if the workflow supports it. -6. Hand off immediately to: - - `/hapo:test` - - `/hapo:review` - -## Output - -Return: -- implemented task name -- touched files -- blockers or follow-up items -- explicit handoff to `/hapo:test` and `/hapo:review` - -## Rules - -- Do not implement multiple major tasks in one pass. -- Stop if `tasks.md` is missing. -- Prefer existing patterns over new abstractions. -- Keep the work aligned to the spec. - -## Related - -- Command: `/code` -- Previous skill: `/hapo:spec-tasks` -- Next skills: `/hapo:test`, `/hapo:review` diff --git a/packages/spec/src/claude/archive-command/code/references/execution-loop.md b/packages/spec/src/claude/archive-command/code/references/execution-loop.md deleted file mode 100644 index 781e9d79..00000000 --- a/packages/spec/src/claude/archive-command/code/references/execution-loop.md +++ /dev/null @@ -1,21 +0,0 @@ -# Execution Loop - -## Goal - -Implement one approved task at a time and immediately validate it. - -## Loop - -1. Read the next pending task in `tasks.md`. -2. Read the matching context in `design.md` and `requirements.md`. -3. Implement only that task. -4. Run `/hapo:test`. -5. Run `/hapo:review`. -6. Move to the next task only after the current pass is clear. - -## Guardrails - -- Keep scope tight. -- Prefer existing project patterns. -- Do not batch multiple major tasks into one pass. -- Stop and report blockers instead of guessing. diff --git a/packages/spec/src/claude/archive-command/docs.md b/packages/spec/src/claude/archive-command/docs.md deleted file mode 100644 index 938e776e..00000000 --- a/packages/spec/src/claude/archive-command/docs.md +++ /dev/null @@ -1,609 +0,0 @@ ---- -name: docs -description: Documentation management command. Use '/docs init' to create initial docs, '/docs update' to update existing docs. -allowed-tools: Read, Write, Glob, Grep, Bash -argument-hint: [--focus=dir1,dir2] ---- - -# /docs - Documentation Management - -$ARGUMENTS - ---- - -## Purpose - -Unified command for project documentation: -- `/docs init` - Initialize comprehensive documentation (replaces old /init) -- `/docs update` - Update docs after code changes - ---- - -## Parse Arguments - -**Extract subcommand:** -- If `$ARGUMENTS` starts with `init` → Run INIT workflow -- If `$ARGUMENTS` starts with `update` → Run UPDATE workflow -- Else → Show usage help - -**Extract flags:** -- `--focus=dir1,dir2` - Focus on specific directories -- `--dir=./path` - Target specific directory - ---- - -## INIT Workflow (`/docs init`) - -### Step 1: Check Prerequisites - -```bash -# Check if docs/ already exists -ls -la docs/ 2>/dev/null && echo "EXISTS" || echo "NOT_FOUND" - -# Check repomix -which repomix || npm list -g repomix 2>/dev/null || echo "REPOMIX_NOT_FOUND" -``` - -**If docs/ exists:** -- Ask: "docs/ already exists. Overwrite / Merge / Skip?" - -### Step 2: Install Repomix (if needed) - -```bash -# Check if repomix is installed -which repomix 2>/dev/null || npm list -g repomix 2>/dev/null -``` - -**If repomix not found:** -- Detect package manager: npm, pnpm, yarn, bun -- Install repomix globally: - -```bash -# Detect package manager -test -f pnpm-lock.yaml && PM="pnpm" -test -f yarn.lock && PM="yarn" -test -f bun.lockb && PM="bun" -PM="${PM:-npm}" - -# Install repomix globally -$PM install -g repomix - -# Verify installation -which repomix -``` - -**Report:** -``` -📦 Installing repomix... ✅ Done -``` - -### Step 3: Run Repomix - -```bash -# Generate codebase compaction -repomix - -# Verify output -ls -la ./repomix-output.xml -``` - -### Step 4: Auto-Detect Project Info - -```bash -# Package manager & config -test -f pnpm-lock.yaml && echo "PNPM" -test -f yarn.lock && echo "YARN" -test -f package-lock.json && echo "NPM" -test -f bun.lockb && echo "BUN" -test -f requirements.txt && echo "PIP" -test -f poetry.lock && echo "POETRY" -test -f go.mod && echo "GO" -test -f Cargo.toml && echo "CARGO" - -# Read configs -cat package.json 2>/dev/null -cat pyproject.toml 2>/dev/null -cat go.mod 2>/dev/null -``` - -**Extract:** -- Project name, version, description -- Tech stack with versions -- Scripts/commands -- Dependencies - -### Step 5: Detect Structure & Platform - -```bash -# Directory structure -find . -maxdepth 3 -type d ! -path './node_modules/*' ! -path './.git/*' ! -path './.*' 2>/dev/null | sort | head -40 - -# Deployment platform -test -f vercel.json && echo "Vercel" -test -f netlify.toml && echo "Netlify" -test -f Dockerfile && echo "Docker" -test -f docker-compose.yml && echo "Docker Compose" -test -f fly.toml && echo "Fly.io" -test -d .github/workflows && echo "GitHub Actions" - -# Database -test -f prisma/schema.prisma && echo "Prisma" -test -f drizzle.config.ts && echo "Drizzle" - -# API -test -d src/app/api && echo "NextJS_API" -test -d src/routes && echo "Express_Routes" - -# Testing -cat package.json | grep -E '"(vitest|jest|playwright|cypress)"' && echo "Testing" -``` - -### Step 6: Generate 7 Documentation Files - -Create `docs/` directory and generate: - -#### 1. codebase-summary.md -```markdown -# Codebase Summary - -> Auto-generated project overview - -## Project Info -| Property | Value | -|----------|-------| -| **Name** | {detected} | -| **Version** | {detected} | -| **Type** | {detected} | - -## Statistics -| Metric | Value | -|--------|-------| -| Files | {from repomix} | -| Tokens | {from repomix} | -| Generated | {timestamp} | - -## Tech Stack -| Layer | Technology | -|-------|------------| -| {detected} | {with versions} | - -## Structure -``` -{directory tree} -``` -``` - -#### 2. project-overview-pdr.md -```markdown -# Project Overview (PDR) - -## Identity -- **Name:** {name} -- **Type:** {type} -- **Status:** Active - -## Description -{from package.json or README} - -## Features -{extracted from codebase} - -## Roadmap -- [ ] Current sprint -- [ ] Next milestones -``` - -#### 3. code-standards.md -```markdown -# Code Standards - -## Stack -- Language: {detected} -- Framework: {detected} -- Linting: {detected} - -## Conventions -{inferred from codebase patterns} - -## Patterns -{common patterns detected} -``` - -#### 4. system-architecture.md -```markdown -# System Architecture - -## Overview -{architecture type} - -## Components -| Component | Tech | Purpose | -|-----------|------|---------| -| {detected} | {tech} | {purpose} | - -## Data Flow -{simple description} - -## API Structure -{if detected} - -## Database -{if detected} -``` - -#### 5. design-guidelines.md -```markdown -# Design Guidelines - -## System -- CSS: {Tailwind/Styled/etc} -- UI Library: {detected} - -## Patterns -{detected patterns} - -## Responsive -{breakpoints} -``` - -#### 6. deployment-guide.md -```markdown -# Deployment Guide - -## Platform -{detected platform} - -## Quick Deploy -```bash -{platform commands} -``` - -## Environment -{from .env.example if exists} - -## Commands -| Command | Purpose | -|---------|---------| -| {from package.json} | {description} | -``` - -#### 7. project-roadmap.md -```markdown -# Project Roadmap - -## Current -{detected state} - -## Short Term (30d) -- [ ] Tasks - -## Medium Term (90d) -- [ ] Enhancements - -## Long Term (6mo) -- [ ] Scale - -## Tech Debt -{detected issues} -``` - -### Step 7: Generate CLAUDE.md - -```bash -# Check if CLAUDE.md exists -test -f CLAUDE.md && echo "EXISTS" || echo "NOT_FOUND" -``` - -**Create or update CLAUDE.md:** - -```markdown -# {Project Name} - -> Project-specific context for Claude Code. See `.claude/ROUTING.md` for agent routing rules. - ---- - -## Project Overview - -{description from package.json or README} - ---- - -## Tech Stack - -| Layer | Technology | -|-------|------------| -| {detected from package.json} | {with versions} | - ---- - -## Project Structure - -``` -{key directories from analysis} -``` - ---- - -## Key Directories - -| Directory | Purpose | -|-----------|---------| -| {detected} | {description} | - ---- - -## Quick Commands - -| Task | Command | -|------|---------| -| {from package.json scripts} | `{pm} run {script}` | - ---- - -## Project Docs (On-demand) - -| Doc | Purpose | Load when | -|-----|---------|-----------| -| `docs/codebase-summary.md` | Project overview | "summary", "overview" | -| `docs/project-overview-pdr.md` | Product requirements | "requirements", "pdr" | -| `docs/code-standards.md` | Coding conventions | "standards", "conventions" | -| `docs/system-architecture.md` | Architecture | "architecture", "design" | -| `docs/deployment-guide.md` | Deployment | "deploy", "production" | - ---- - -## Framework Reference - -See `.claude/ROUTING.md` for agent routing and framework rules. - ---- - -**Last Updated:** {timestamp} -``` - -**Write to file:** -```bash -# Generate CLAUDE.md content -cat > CLAUDE.md << 'EOF' -# {Project Name} - -> Project-specific context for Claude Code. See `.claude/ROUTING.md` for agent routing rules. - ---- - -## Project Overview - -{description} - ---- - -## Tech Stack - -| Layer | Technology | -|-------|------------| -{tech_stack_rows} - ---- - -## Project Structure - -``` -{structure} -``` - ---- - -## Key Directories - -| Directory | Purpose | -|-----------|---------| -{directory_rows} - ---- - -## Quick Commands - -| Task | Command | -|------|---------| -{commands_rows} - ---- - -## Project Docs (On-demand) - -| Doc | Purpose | Load when | -|-----|---------|-----------| -| `docs/codebase-summary.md` | Project overview | "summary", "overview" | -| `docs/project-overview-pdr.md` | Product requirements | "requirements", "pdr" | -| `docs/code-standards.md` | Coding conventions | "standards", "conventions" | -| `docs/system-architecture.md` | Architecture | "architecture", "design" | -| `docs/design-guidelines.md` | UI/UX standards | "design", "ui", "ux" | -| `docs/deployment-guide.md` | Deployment | "deploy", "production" | -| `docs/project-roadmap.md` | Roadmap | "roadmap", "future" | - ---- - -## Framework Reference - -See `.claude/ROUTING.md` for agent routing and framework rules. - ---- - -**Last Updated:** {timestamp} -EOF -``` - -### Step 8: Report - -```markdown -✅ Documentation initialized! - -📊 Detected: - - Project: {name} - - Type: {type} - - Stack: {summary} - - Files: {count} | Tokens: {count} - -📁 Generated (docs/): - ✓ codebase-summary.md - ✓ project-overview-pdr.md - ✓ code-standards.md - ✓ system-architecture.md - ✓ design-guidelines.md - ✓ deployment-guide.md - ✓ project-roadmap.md - -📝 Also created: - ✓ repomix-output.xml (AI context) - ✓ CLAUDE.md (root) - -🚀 Next: Run `/docs update` after code changes -``` - ---- - -## UPDATE Workflow (`/docs update`) - -### Step 1: Verify - -```bash -# Check docs/ exists -ls docs/ 2>/dev/null || echo "ERROR: Run '/docs init' first" - -# Backup -cp -r docs docs.backup.$(date +%Y%m%d_%H%M%S) -``` - -### Step 2: Ensure Repomix Installed - -```bash -# Check if repomix is installed -which repomix 2>/dev/null || npm list -g repomix 2>/dev/null -``` - -**If repomix not found:** -- Detect package manager -- Install repomix globally - -```bash -# Detect package manager -test -f pnpm-lock.yaml && PM="pnpm" -test -f yarn.lock && PM="yarn" -test -f bun.lockb && PM="bun" -PM="${PM:-npm}" - -# Install repomix -$PM install -g repomix -``` - -### Step 3: Re-analyze - -```bash -# Fresh repomix -repomix - -# Detect changes -git diff --stat HEAD~5..HEAD 2>/dev/null -``` - -### Step 4: Update Files - -Read existing docs, merge with new analysis: - -1. **codebase-summary.md** - Refresh stats, structure -2. **project-overview-pdr.md** - Add new features -3. **code-standards.md** - Update patterns -4. **system-architecture.md** - Sync components -5. **design-guidelines.md** - Refresh UI patterns -6. **deployment-guide.md** - Update commands -7. **project-roadmap.md** - Mark progress - -### Step 5: Update CLAUDE.md - -Update `CLAUDE.md` with latest project info: - -```bash -# Read existing CLAUDE.md if exists -test -f CLAUDE.md && cat CLAUDE.md || echo "NOT_FOUND" - -# Update key sections: -# - Tech Stack (from package.json) -# - Project Structure (from repomix) -# - Quick Commands (from package.json scripts) -# - Last Updated timestamp -``` - -**Update content:** -- Refresh "Tech Stack" table with latest versions -- Update "Project Structure" if directories changed -- Sync "Quick Commands" with package.json scripts -- Update "Last Updated" timestamp - -**If CLAUDE.md doesn't exist:** -- Create new following INIT workflow template - -### Step 6: Report - -```markdown -🔄 Documentation updated! - -📊 Changes: - - Files: {old} → {new} - - Tokens: {old} → {new} - -📝 Updated: - ✓ codebase-summary.md - ✓ project-overview-pdr.md - ✓ code-standards.md - ✓ system-architecture.md - ✓ design-guidelines.md - ✓ deployment-guide.md - ✓ project-roadmap.md - ✓ CLAUDE.md (root) - -💡 Review docs/ for any manual adjustments needed -``` - ---- - -## HELP (no valid subcommand) - -```markdown -/docs - Documentation Management - -Usage: - /docs init - Create initial documentation - /docs update - Update docs after code changes - -Options: - --focus=dir1,dir2 - Focus on specific directories - --dir=./path - Target specific directory - -Examples: - /docs init - /docs init --focus=src,api - /docs update - /docs update --focus=ui -``` - ---- - -## Error Handling - -| Scenario | Action | -|----------|--------| -| repomix not found | Warn, continue with manual analysis | -| No package.json | Ask user for project type | -| docs/ exists (init) | Ask: Overwrite/Merge/Skip | -| docs/ not found (update) | Prompt to run `/docs init` | -| Permission denied | Report path, suggest fix | - ---- - -## Notes - -- Always use detected values, never placeholders -- Include versions: "Next.js 14.1.0" not "Next.js" -- repomix-output.xml helps AI understand full context -- 7 docs files = comprehensive coverage diff --git a/packages/spec/src/claude/archive-command/review/codebase/parallel.md b/packages/spec/src/claude/archive-command/review/codebase/parallel.md deleted file mode 100644 index d1e98c10..00000000 --- a/packages/spec/src/claude/archive-command/review/codebase/parallel.md +++ /dev/null @@ -1,76 +0,0 @@ -# Parallel Review Workflow - -**Ultrathink** to exhaustively list ALL potential edge cases, then dispatch parallel `code-reviewer` agents to verify: $ARGUMENTS - -**IMPORTANT:** Activate needed skills. Ensure token efficiency. Sacrifice grammar for concision. - -## Workflow - -### 1. Ultrathink Edge Cases - -Main agent deeply analyzes the scope to LIST all potential edge cases FIRST: -- Read `codebase-summary.md` for context -- Use `/ck:scout` to find relevant files -- **Think exhaustively** about what could go wrong: - - Null/undefined scenarios - - Boundary conditions (off-by-one, empty, max values) - - Error handling gaps - - Race conditions, async edge cases - - Input validation holes - - Security vulnerabilities - - Resource leaks - - Untested code paths - -**Output format:** -```markdown -## Edge Cases Identified - -### Category: [scope-area] -1. [edge case description] → files: [file1, file2] -``` - -### 2. Categorize & Assign - -Group edge cases by similar scope for parallel verification: -- Each category → one `code-reviewer` agent -- Max 6 categories (merge small ones) -- Each reviewer gets specific edge cases to VERIFY, not discover - -### 3. Parallel Verification - -Launch N `code-reviewer` subagents simultaneously: -- Pass: category name, list of edge cases, relevant files -- Task: **VERIFY** if each edge case is properly handled in code -- Report: which edge cases are handled vs unhandled - -### 4. Aggregate Results - -```markdown -## Edge Case Verification Report - -### Summary -- Total edge cases: X -- Handled: Y -- Unhandled: Z -- Partial: W - -### Unhandled Edge Cases (Need Fix) -| # | Edge Case | File | Status | -|---|-----------|------|--------| -``` - -### 5. Adversarial Review (Always-On) - -After aggregation, spawn adversarial reviewer (see `adversarial-review.md`) on the full scope: -- Adversarial reviewer receives aggregated findings + unhandled edge cases as context -- Actively tries to break the code beyond what edge case verification found -- Adjudicate findings: Accept / Reject / Defer - -### 6. Auto-Fix Pipeline - -**IF** unhandled/partial edge cases found: -- Ask: "Found N unhandled edge cases. Fix with /ck:fix --parallel? [Y/n]" - -### 7. Final Report -- Summary of verification -- Ask: "Commit? [Y/n]" → use `git-manager` diff --git a/packages/spec/src/claude/archive-command/spec-design.md b/packages/spec/src/claude/archive-command/spec-design.md deleted file mode 100644 index 0702437a..00000000 --- a/packages/spec/src/claude/archive-command/spec-design.md +++ /dev/null @@ -1,247 +0,0 @@ ---- -name: spec-design -description: Create comprehensive technical design for a specification -allowed-tools: Glob, Grep, Read, Write, Edit, WebSearch, WebFetch -argument-hint: [-y] ---- - -# Technical Design Generator - - -- **Mission**: Generate comprehensive technical design document that translates requirements (WHAT) into architectural design (HOW) -- **Success Criteria**: - - All requirements mapped to technical components with clear interfaces - - Appropriate architecture discovery and research completed - - Design aligns with steering context and existing patterns - - Visual diagrams included for complex architectures - - - -## Core Task -Generate technical design document for feature **$ARGUMENTS** based on approved requirements. - -## Execution Steps - -### Step 0: Validate Phase State (Plan-Style Gate) - -- Read `.specs/$ARGUMENTS/spec.json` first -- If feature directory or `spec.json` is missing: stop and instruct user to run `/spec-init ` and `/spec-requirements ` first -- If requirements have not been generated yet (phase before requirements): stop and instruct user to run `/spec-requirements $ARGUMENTS` -- If `phase` is `tasks-generated`: stop and explain design phase is already completed; only re-run for explicit regeneration/update intent - -### Step 1: Load Context - -**Read all necessary context**: -- `.specs/$ARGUMENTS/spec.json`, `requirements.md`, `design.md` (if exists) -- Resolve scope baseline from `spec.json.scope_lock`: - - `scope_lock.source` = canonical original intent - - `scope_lock.in_scope[]` = designable capability space - - `scope_lock.out_of_scope[]` = capabilities that must stay deferred - - `scope_lock.expansion_policy` = default `requires-user-approval` -- Backward-compatible fallback for older specs without `scope_lock`: - - Derive baseline scope from project description and existing requirements - - Continue without hard-fail, but keep strict no-expansion behavior -- Load `.specs/steering/` (if exists) as constraints and standards only -- `{{SKILLS_DIR}}/specs/templates/design.md` for document structure -- `{{SKILLS_DIR}}/specs/rules/design-principles.md` for design principles -- `{{SKILLS_DIR}}/specs/templates/research.md` for discovery log structure -- **Load project docs context (Plan-style quality gate)** when available: - - `docs/codebase-summary.md` - - `docs/code-standards.md` - - `docs/system-architecture.md` - - `docs/project-overview-pdr.md` -- If any docs file is missing, continue and mention missing context in execution output (do not block generation) - -**Validate requirements approval and scope eligibility**: -- If `-y` flag provided: Auto-approve requirements in spec.json -- Otherwise: Verify approval status (stop if unapproved, see Safety & Fallback) -- Build `in_scope_requirement_ids` by filtering requirements against scope_lock -- If no in-scope requirement IDs found, or requirements are ambiguous against scope_lock: stop and instruct user to re-run `/spec-requirements $ARGUMENTS` - -### Step 2: Discovery & Analysis - -**Critical: This phase ensures design is based on complete, accurate information.** - -### Step 2A: Discovery Mode Router (Plan-Style) - -Before discovery, select a deterministic mode and record the reason: -- **minimal**: UI/CRUD-only change, no new external dependency/API, no schema change, <=2 integration points -- **light**: extension of existing feature with known patterns and limited integration risk -- **full**: new subsystem, external integration, auth/security/performance impact, schema boundary changes, or explicit user request for deep exploration -- **Default rule**: when uncertain, choose **light** (scope-safe by default) -- **Escalation trigger**: switch to **full** only when a concrete trigger is present and documented -- **Research budget**: keep discovery scoped; use at most 2 major external investigations unless findings reveal a blocker - -Use the selected mode to drive Step 2 execution and persist it in spec metadata during Step 3 finalize. - -1. **Classify Feature Type**: - - **New Feature** (greenfield) → Start with light discovery; escalate to full only with explicit triggers - - **Extension** (existing system) → Integration-focused discovery - - **Simple Addition** (CRUD/UI) → Minimal or no discovery - - **Complex Integration** → Full discovery required - - **Note**: Full mode is triggered by concrete signals, not by default uncertainty - -2. **Execute Appropriate Discovery Process**: - - **For Full Mode**: - - Read and execute `{{SKILLS_DIR}}/specs/rules/design-discovery-full.md` - - Conduct focused research using WebSearch/WebFetch only for in-scope uncertainty: - - External dependency verification (APIs, libraries, versions, compatibility) - - Official documentation, migration guides, known issues - - Security/performance considerations tied to current scope - - **For Light Mode**: - - Read and execute `{{SKILLS_DIR}}/specs/rules/design-discovery-light.md` - - Focus on integration points, existing patterns, compatibility - - Use Grep to analyze existing codebase patterns - - **For Minimal Mode / Simple Additions**: - - Skip formal discovery, quick pattern check only - -3. **Retain Discovery Findings for Step 3**: - - External API contracts and constraints (only if in-scope) - - Technology decisions with rationale - - Existing patterns to follow or extend - - Integration points and dependencies - - Identified risks and mitigation strategies - - Potential architecture patterns and boundary options - - Explicitly note any out-of-scope discoveries as deferred (do not design them now) - -4. **Persist Findings to Research Log**: - - Create or update `.specs/$ARGUMENTS/research.md` using the shared template - - Summarize discovery scope and key findings (Summary section) - - Record investigations in Research Log topics with sources and implications - - Document architecture pattern evaluation, design decisions, and risks - - Use the language specified in spec.json - -### Step 2B: Scope-Lock Enforcement Before Writing Design - -- Validate each planned component/flow against `in_scope_requirement_ids` -- If a design element does not map to an in-scope requirement ID: - - Remove it from main design sections - - Optionally note it in `research.md` as deferred/out-of-scope -- Do not open new domains (e.g., API/mobile/new data platform) without explicit user approval under `scope_lock.expansion_policy` - -### Step 3: Generate Design Document - -1. **Load Design Template and Rules**: - - Read `{{SKILLS_DIR}}/specs/templates/design.md` for structure - - Read `{{SKILLS_DIR}}/specs/rules/design-principles.md` for principles - -2. **Generate Design Document**: - - **Follow template structure strictly** - - **Design only for in-scope requirement IDs** from Step 1 - - **Integrate only in-scope discovery findings** throughout component definitions - - If existing design.md found, use it as reference context (merge mode) - - Apply design rules: Type Safety, Visual Communication, Formal Tone - - Use language specified in spec.json - - Include Mermaid diagrams only when complexity warrants visualization - -3. **Required Sections & Detail Level** (Complexity-Aware): - - **Verbosity Guideline**: Match depth to feature complexity. Prefer concise, concrete decisions over exhaustive boilerplate. - **Type Detail Rule**: Define full TypeScript interfaces only for components/contracts that cross boundaries or carry non-trivial state. - - | Section | Requirement | Instructions | - |---------|-------------|--------------| - | **Overview** | ✅ Mandatory | Purpose, users, impact, goals, non-goals focused on current scope | - | **Architecture** | ✅ Mandatory | Pattern and boundaries for in-scope requirements only | - | **System Flows** | 🔶 Conditional | Add Mermaid sequence/flow only when interactions are non-trivial | - | **Requirements Traceability** | ✅ Mandatory | Map only valid in-scope numeric requirement IDs | - | **Components and Interfaces** | ✅ Mandatory | Define interfaces/contracts only for components that need explicit boundaries | - | **Data Models** | 🔶 Conditional | Include only if data/storage changes are in-scope | - | **Error Handling** | ✅ Mandatory | Include feature-relevant errors and recovery strategies | - | **Testing Strategy** | ✅ Mandatory | Right-size test scope to feature risk and complexity | - | **Security Considerations** | 🔶 Conditional | Required when feature touches auth, input trust boundaries, or sensitive data | - | **Performance & Scalability** | 🔶 Conditional | Required when feature has explicit performance/scalability constraints | - | **Supporting References** | 🔶 Optional | Include only when details would hurt readability in main sections | - -4. **Update Metadata** in spec.json: - - Set `phase: "design-generated"` - - Set `approvals.design.generated: true, approved: false` - - Set `approvals.requirements.approved: true` - - Set `design_context.discovery_mode: "minimal" | "light" | "full"` (based on Step 2A) - - Set `design_context.discovery_reason: ""` - - Set `design_context.validation_recommended: true` when discovery mode is `full` or risk level is medium/high - - Update `updated_at` timestamp - -## Critical Constraints -- **Type Safety**: - - Enforce strong typing aligned with the project's technology stack - - For TypeScript, never use `any`; prefer precise types and generics - - Document public interfaces and contracts clearly where relevant -- **Scope Lock**: Do not design capabilities outside `scope_lock`; out-of-scope discoveries must be marked deferred -- **Latest Information**: Use WebSearch/WebFetch only when external dependencies are in-scope and uncertain -- **Steering Alignment**: Respect existing architecture patterns from steering context -- **Template Adherence**: Follow template structure while allowing complexity-aware section optionality -- **Design Focus**: Architecture and interfaces ONLY, no implementation code -- **Requirements Traceability IDs**: Use numeric requirement IDs only (e.g. "1.1", "1.2") as defined in requirements.md - - -## Tool Guidance -- **Read first**: Load all context before taking action (specs, steering, templates, rules) -- **Research when uncertain**: Use WebSearch/WebFetch only for in-scope external dependencies and unresolved constraints -- **Analyze existing code**: Use Grep to find patterns and integration points in codebase -- **Write last**: Generate design.md only after all research and analysis complete - -## Output Description - -**Command execution output** (separate from design.md content): - -Provide brief summary in the language specified in spec.json: - -1. **Status**: Confirm design document generated at `.specs/$ARGUMENTS/design.md` -2. **Discovery Type**: Which discovery process was executed (full/light/minimal) -3. **Discovery Rationale**: One-line reason why this mode was selected -4. **Key Findings**: 2-3 critical in-scope insights from `research.md` that shaped the design -5. **Scope Guard**: Confirm no out-of-scope domains were added to design.md (or list deferred items) -6. **Next Action**: Approval workflow guidance (include whether `/spec-validate $ARGUMENTS` is recommended before `/spec-tasks`) -7. **Research Log**: Confirm `research.md` updated with latest decisions - -**Format**: Concise Markdown (under 200 words) - -## Safety & Fallback - -### Error Scenarios - -**Requirements Not Approved**: -- **Stop Execution**: Cannot proceed without approved requirements -- **User Message**: "Requirements not yet approved. Approval required before design generation." -- **Suggested Action**: "Run `/spec-design $ARGUMENTS -y` to auto-approve requirements and proceed" - -**Missing Requirements**: -- **Stop Execution**: Requirements document must exist -- **User Message**: "No requirements.md found at `.specs/$ARGUMENTS/requirements.md`" -- **Suggested Action**: "Run `/spec-requirements $ARGUMENTS` to generate requirements first" - -**Template Missing**: -- **User Message**: "Template file missing" -- **Suggested Action**: "Check repository setup or restore template file" -- **Fallback**: Use inline basic structure with warning - -**Steering Context Missing**: -- **Warning**: "Steering directory empty or missing - design may not align with project standards" -- **Proceed**: Continue with generation but keep scope strictly bound to scope_lock - -**Discovery Complexity Unclear**: -- **Default**: Use light discovery process -- **Escalate to Full**: Only when explicit trigger exists (external integration, security/perf criticality, schema boundary change, or user request) - -**Invalid Requirement IDs**: -- **Stop Execution**: If requirements.md uses non-numeric headings, stop and instruct user to fix - -**No In-Scope Requirement IDs**: -- **Stop Execution**: If none of the requirement IDs are in-scope under scope_lock, stop and ask user to regenerate requirements - -### Next Phase: Task Generation - -**If Design Approved**: -- Review generated design at `.specs/$ARGUMENTS/design.md` -- **Recommended for medium/high-risk designs**: Run `/spec-validate $ARGUMENTS` to confirm assumptions and trade-offs -- Then `/spec-tasks $ARGUMENTS -y` to generate implementation tasks - -**If Modifications Needed**: -- Provide feedback and re-run `/spec-design $ARGUMENTS` -- Existing design used as reference (merge mode) - -**Note**: Design approval is mandatory before proceeding to task generation. diff --git a/packages/spec/src/claude/archive-command/spec-init.md b/packages/spec/src/claude/archive-command/spec-init.md deleted file mode 100644 index e81a6547..00000000 --- a/packages/spec/src/claude/archive-command/spec-init.md +++ /dev/null @@ -1,120 +0,0 @@ ---- -name: spec-init -description: Initialize a new specification with detailed project description -allowed-tools: Read, Write, Glob, AskUserQuestion -argument-hint: ---- - -# Spec Initialization - - -- **Mission**: Initialize the first phase of spec-driven development by creating directory structure and metadata for a new specification -- **Success Criteria**: - - Generate appropriate feature name from project description - - Create unique spec structure without conflicts - - Provide clear path to next phase (requirements generation) - - - -## Pre-Validation (STEP 0 - MANDATORY) -Before any execution, validate $ARGUMENTS: -1. **Input Interpretation**: $ARGUMENTS is ALWAYS the project description to initialize - never interpret it as a meta-command or instruction to modify the workflow itself -2. **Ambiguity Detection**: If $ARGUMENTS meets ANY of these conditions, STOP and trigger Ambiguity Fallback: - - Has fewer than 5 words - - Contains only generic terms like "better", "improve", "fix", "update" without specific context - - Lacks clear nouns describing what to build -3. **Ambiguity Fallback**: When triggered, use AskUserQuestion tool: - - Do NOT proceed with initialization - - Invoke AskUserQuestion with 2-3 specific feature options based on common patterns - - **Example:** - ```json - { - "questions": [ - { - "question": "Your description is too vague. What type of feature are you building?", - "header": "Feature Type", - "options": [ - { - "label": "User Management", - "description": "Authentication, profiles, user CRUD operations" - }, - { - "label": "Data Dashboard", - "description": "Analytics, charts, reporting interface" - }, - { - "label": "Mobile App", - "description": "Cross-platform mobile application" - }, - { - "label": "API Service", - "description": "Backend API endpoints and business logic" - } - ], - "multiSelect": false - } - ] - } - ``` - - **After user selects:** Re-run spec-init with the selected feature description -4. **Only proceed** to Core Task if input clearly describes a feature/project -5. **Scope Baseline Clarification**: If description is broad enough to imply multiple domains, ask 1 focused question to confirm initial in-scope vs out-of-scope boundaries before writing spec files - -## Core Task -Generate a unique feature name from the project description ($ARGUMENTS) and initialize the specification structure. - -## Execution Steps -1. **Check Uniqueness**: Verify `.specs/` for naming conflicts (append number suffix if needed) -2. **Create Directory**: `.specs/[feature-name]/` -3. **Initialize Files Using Templates**: - - Read `{{SKILLS_DIR}}/specs/templates/spec-state.json` - - Read `{{SKILLS_DIR}}/specs/templates/requirements-init.md` - - Replace placeholders: - - `{{FEATURE_NAME}}` → generated feature name - - `{{TIMESTAMP}}` → current ISO 8601 timestamp - - `{{PROJECT_DESCRIPTION}}` → $ARGUMENTS - - Set `scope_lock` in `spec.json` as initialization contract: - - `scope_lock.source` = original project description - - `scope_lock.in_scope` = concise bullets derived from explicit user intent - - `scope_lock.out_of_scope` = nearby domains/capabilities explicitly excluded for this iteration - - `scope_lock.expansion_policy` = `requires-user-approval` - - Write `spec.json` and `requirements.md` to spec directory - -## Important Constraints -- DO NOT generate requirements/design/tasks at this stage -- Follow stage-by-stage development principles -- Maintain strict phase separation -- Only initialization is performed in this phase -- Scope lock is mandatory: initialize `scope_lock` and treat it as authoritative baseline for later phases - - -## Tool Guidance -- Use **Glob** to check existing spec directories for name uniqueness -- Use **Read** to fetch templates: `spec-state.json` and `requirements-init.md` -- Use **Write** to create spec.json and requirements.md after placeholder replacement -- Perform validation before any file write operation - -## Output Description -Provide output in the language specified in `spec.json` with the following structure: - -1. **Generated Feature Name**: `feature-name` format with 1-2 sentence rationale -2. **Project Summary**: Brief summary (1 sentence) -3. **Created Files**: Bullet list with full paths -4. **Next Step**: Command block showing `/hapo:specs resume ` -5. **Notes**: Explain this legacy init command only initialized files. Recommend using `/hapo:specs ` for the normal end-to-end CafeKit flow. - -**Command integrity:** CafeKit continuation uses `/hapo:specs resume `. - -**Format Requirements**: -- Use Markdown headings (##, ###) -- Wrap commands in code blocks -- Keep total output concise (under 250 words) -- Use clear, professional language per `spec.json.language` - -## Safety & Fallback -- **Ambiguous Feature Name**: If feature name generation is unclear, propose 2-3 options and ask user to select -- **Template Missing**: If template files don't exist in `{{SKILLS_DIR}}/specs/templates/`, report error with specific missing file path and suggest checking repository setup -- **Directory Conflict**: If feature name already exists, append numeric suffix (e.g., `feature-name-2`) and notify user of automatic conflict resolution -- **Write Failure**: Report error with specific path and suggest checking permissions or disk space diff --git a/packages/spec/src/claude/archive-command/spec-requirements.md b/packages/spec/src/claude/archive-command/spec-requirements.md deleted file mode 100644 index 8c39528b..00000000 --- a/packages/spec/src/claude/archive-command/spec-requirements.md +++ /dev/null @@ -1,138 +0,0 @@ ---- -name: spec-requirements -description: Generate comprehensive requirements for a specification -allowed-tools: Glob, Grep, Read, Write, Edit, WebSearch, WebFetch -argument-hint: ---- - -# Requirements Generation - - -- **Mission**: Generate comprehensive, testable requirements in EARS format based on the project description from spec initialization -- **Success Criteria**: - - Create complete requirements document aligned with steering context - - Follow the project's EARS patterns and constraints for all acceptance criteria - - Focus on core functionality without implementation details - - Update metadata to track generation status - - - -## Core Task -Generate complete requirements for feature **$ARGUMENTS** based on the project description in requirements.md. - -## Execution Steps - -0. **Validate Phase State (Plan-Style Gate)**: - - Read `.specs/$ARGUMENTS/spec.json` first - - If missing feature directory or spec.json: stop and ask user to run `/spec-init ` first - - If `phase` is `design-generated` or `tasks-generated`: stop and explain requirements phase already completed; ask user to edit/re-run only with explicit intent to regenerate requirements - -1. **Load Context**: - - Read `.specs/$ARGUMENTS/spec.json` for language and metadata - - Read `.specs/$ARGUMENTS/requirements.md` for project description - - Resolve scope baseline from `spec.json.scope_lock`: - - `scope_lock.source` = canonical original intent - - `scope_lock.in_scope[]` = capability list that requirements MUST stay within - - `scope_lock.out_of_scope[]` = nearby capabilities that MUST NOT be promoted into main requirements - - `scope_lock.expansion_policy` = default `requires-user-approval` - - Backward-compatible fallback for older specs without `scope_lock`: - - Derive initial scope from project description in requirements.md - - Initialize scope lock in memory for this run (do not hard-fail) - - Load steering context from `.specs/steering/` (if exists) as **constraints only**: - - Use steering to enforce standards, conventions, and constraints - - Do NOT add new product capabilities/domains beyond scope_lock - -2. **Read Guidelines**: - - Read `{{SKILLS_DIR}}/specs/rules/ears-format.md` for EARS syntax rules - - Read `{{SKILLS_DIR}}/specs/templates/requirements.md` for document structure - - **Load project docs context (Plan-style quality gate)** when available: - - `docs/codebase-summary.md` - - `docs/code-standards.md` - - `docs/system-architecture.md` - - `docs/project-overview-pdr.md` - - If any docs file is missing, continue and note the missing context in output (do not block generation) - -3. **Analyze Existing Codebase** (for Extension/Enhancement features): - - Search for related files: `**/*.{tsx,jsx,ts,js,vue,py}` - - Read existing components/modules related to the feature - - Identify what's already implemented vs what needs to be added - - If existing implementation found: - - Add Introduction section in requirements.md acknowledging existing code - - Focus requirements on enhancements/additions, not reimplementation - - Reference existing components (e.g., "The project already has X and Y") - - If greenfield (no existing code): Skip Introduction, proceed normally - -4. **Scope-Lock Filtering & Clarification**: - - Draft candidate requirement topics from description + codebase findings - - Keep only topics that fit `scope_lock.in_scope` and `scope_lock.source` - - For topics matching `scope_lock.out_of_scope` or introducing new domains: - - Mark as `Deferred / Out of Scope` in requirements.md notes section - - Do NOT include them in main requirement list - - If ambiguity could change scope boundaries, ask 1-2 focused clarification questions before finalizing requirements - -5. **Generate Requirements**: - - Create initial requirements based on project description - - Consider existing codebase findings (if any) - - Group related functionality into logical requirement areas - - Apply EARS format to all acceptance criteria: - - Event-Driven: `When [event], the [system] shall [response]` - - State-Driven: `While [precondition], the [system] shall [response]` - - Unwanted: `If [trigger], the [system] shall [response]` - - Optional: `Where [feature], the [system] shall [response]` - - Ubiquitous: `The [system] shall [response]` - - Use language specified in spec.json - -6. **Update Metadata**: - - Set `phase: "requirements-generated"` - - Set `approvals.requirements.generated: true` - - Update `updated_at` timestamp - -## Important Constraints -- Focus on WHAT, not HOW (no implementation details) -- Requirements must be testable and verifiable -- Choose appropriate subject for EARS statements (system/service name for software) -- Requirements generation is scope-locked by `spec.json.scope_lock` -- Out-of-scope ideas must be captured as deferred, not merged into primary requirements -- Requirement headings in requirements.md MUST include a leading numeric ID only (for example: "Requirement 1", "1.", "2 Feature ..."); do not use alphabetic IDs like "Requirement A". - - -## Tool Guidance -- **Read first**: Load all context (spec, scope lock, steering constraints, rules, templates) before generation -- **Write last**: Update requirements.md only after complete generation -- Use **WebSearch/WebFetch** only if external domain knowledge needed - -## Output Description -Provide output in the language specified in spec.json with: - -1. **Generated Requirements Summary**: Brief overview of major in-scope requirement areas (3-5 bullets) -2. **Scope Guard Summary**: List deferred/out-of-scope topics excluded from primary requirements -3. **Document Status**: Confirm requirements.md updated and spec.json metadata updated -4. **Next Steps**: Guide user on how to proceed (approve and continue, or modify) - -**Format Requirements**: -- Use Markdown headings for clarity -- Include file paths in code blocks -- Keep summary concise (under 300 words) - -## Safety & Fallback - -### Error Scenarios -- **Missing Project Description**: If requirements.md lacks project description, ask user for feature details -- **Ambiguous Requirements**: Propose initial version and iterate with user rather than asking many upfront questions -- **Template Missing**: If template files don't exist, use inline fallback structure with warning -- **Language Undefined**: Default to English (`en`) if spec.json doesn't specify language -- **Incomplete Requirements**: After generation, explicitly ask user if requirements cover all expected functionality -- **Steering Directory Empty**: Warn user that project standards context is missing and may affect quality constraints -- **Scope Drift Risk**: If candidate requirements introduce domains outside scope_lock, ask 1-2 clarifying questions; if unconfirmed, classify as deferred/out-of-scope -- **Non-numeric Requirement Headings**: If existing headings do not include a leading numeric ID, normalize them to numeric IDs - -### Next Phase: Design Generation - -**If Requirements Approved**: -- Review generated requirements at `.specs/$ARGUMENTS/requirements.md` -- Then `/spec-design $ARGUMENTS` to proceed to design phase - -**If Modifications Needed**: -- Provide feedback and re-run `/spec-requirements $ARGUMENTS` - -**Note**: Approval is mandatory before proceeding to design phase. diff --git a/packages/spec/src/claude/archive-command/spec-status.md b/packages/spec/src/claude/archive-command/spec-status.md deleted file mode 100644 index 91b699b4..00000000 --- a/packages/spec/src/claude/archive-command/spec-status.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -name: spec-status -description: Display current status of a specification. -allowed-tools: Read, Glob -argument-hint: [feature-name] ---- - -# /spec-status - View Specification Status - -$ARGUMENTS - ---- - -## Purpose - -Hiển thị trạng thái hiện tại của một spec hoặc liệt kê tất cả specs. - ---- - -## Task - -### Execution Steps - -**If `$ARGUMENTS` is provided:** - -1. Read `.specs/$ARGUMENTS/spec.json` -2. Display: - - Feature name - - Current phase - - Approval status - - Discovery mode (if available) - - Validation status and last validated time (if available) - - **Backward compatibility fallback (older specs):** - - If `design_context` is missing, show Discovery mode as `n/a` - - If `validation` is missing, show Validation as `not-run` and Last validated as `n/a` - - Created/Updated timestamps - - Summary of files - -**If no arguments:** - -1. Glob `.specs/*/spec.json` -2. List all specs with their status - ---- - -## Output Format - -### Single Spec Status - -```markdown -## 📊 Spec Status: `` - -| Property | Value | -|----------|-------| -| **Phase** | `` | -| **Discovery Mode** | `` | -| **Validation** | `` | -| **Last Validated** | `` | -| **Created** | `` | -| **Updated** | `` | - -### Approvals -- Requirements: ✅/❌ Generated | ✅/❌ Approved -- Design: ✅/❌ Generated | ✅/❌ Approved -- Tasks: ✅/❌ Generated | ✅/❌ Approved - -### Files -- `spec.json` ✅ -- `requirements.md` ✅/❌ -- `research.md` ✅/❌ -- `design.md` ✅/❌ -- `tasks.md` ✅/❌ - -### Next Action -- If phase = `requirements-generated`: Run `/spec-design ` -- If phase = `design-generated`: Run `/spec-tasks ` -- If phase = `tasks-generated`: Run `/code `, then `/test`, then `/review` -``` - -### All Specs List - -```markdown -## 📊 All Specs - -| Feature | Phase | Last Updated | -|---------|-------|--------------| -| `mobile-app` | tasks-generated | 2026-01-21 | -| `auth-module` | design-generated | 2026-01-20 | -``` - ---- - -## Usage Examples - -``` -/spec-status mobile-app -/spec-status -``` diff --git a/packages/spec/src/claude/archive-command/spec-tasks.md b/packages/spec/src/claude/archive-command/spec-tasks.md deleted file mode 100644 index a8801c63..00000000 --- a/packages/spec/src/claude/archive-command/spec-tasks.md +++ /dev/null @@ -1,173 +0,0 @@ ---- -name: spec-tasks -description: Generate implementation tasks for a specification -allowed-tools: Glob, Grep, Read, Write, Edit, WebSearch, WebFetch -argument-hint: [-y] [--sequential] ---- - -# Implementation Tasks Generator - - -- **Mission**: Generate detailed, actionable implementation tasks that translate technical design into executable work items -- **Success Criteria**: - - All requirements mapped to specific tasks - - Tasks properly sized (1-3 hours each) - - Clear task progression with proper hierarchy - - Natural language descriptions focused on capabilities - - - -## Core Task -Generate implementation tasks for feature **$ARGUMENTS** based on approved requirements and design. - -## Execution Steps - -### Step 0: Validate Phase State (Plan-Style Gate) - -- Read `.specs/$ARGUMENTS/spec.json` first -- If feature directory or `spec.json` is missing: stop and instruct user to run `/spec-init `, `/spec-requirements `, and `/spec-design ` first -- If design has not been generated yet (phase before design): stop and instruct user to run `/spec-design $ARGUMENTS` -- If `phase` is already `tasks-generated`: explain tasks phase already exists and only continue for explicit regeneration/merge intent - -### Step 1: Load Context - -**Read all necessary context**: -- `.specs/$ARGUMENTS/spec.json`, `requirements.md`, `design.md` -- `.specs/$ARGUMENTS/tasks.md` (if exists, for merge mode) -- `.specs/$ARGUMENTS/research.md` (if exists, includes validation log) -- Resolve scope baseline from `spec.json.scope_lock` (fallback to derived baseline when missing) -- **Entire `.specs/steering/` directory** for complete project memory (if exists) -- **Load project docs context (Plan-style quality gate)** when available: - - `docs/codebase-summary.md` - - `docs/code-standards.md` - - `docs/system-architecture.md` - - `docs/project-overview-pdr.md` -- If any docs file is missing, continue and mention missing context in execution output (do not block generation) - -**Validate approvals**: -- If `-y` flag provided: Auto-approve requirements and design in spec.json -- Otherwise: Verify both approved (stop if not, see Safety & Fallback) -- **Backward compatibility fallback (older specs):** - - If `validation` object is missing, treat validation status as `not-run` - - If `design_context` object is missing, treat `validation_recommended` as `false` -- If `spec.json.validation.status == "completed"`, treat validation as satisfied -- If validation is missing and `design_context.validation_recommended == true`, warn user to run `/spec-validate $ARGUMENTS` before continuing (do not hard-block) -- Determine sequential mode based on presence of `--sequential` - -### Step 2: Generate Implementation Tasks - -**Load generation rules and template**: -- Read `{{SKILLS_DIR}}/specs/rules/tasks-generation.md` for principles -- If `sequential` is **false**: Read `{{SKILLS_DIR}}/specs/rules/tasks-parallel-analysis.md` for parallel judgement criteria -- Read `{{SKILLS_DIR}}/specs/templates/tasks.md` for format (supports `(P)` markers) - -**Generate task list following all rules**: -- Use language specified in spec.json -- Map all requirements to tasks -- Only use valid in-scope requirement IDs from requirements.md -- Every task MUST reference at least one valid in-scope requirement ID -- Reject or defer task candidates that map only to out-of-scope capabilities -- When documenting requirement coverage, list numeric requirement IDs only (comma-separated) without descriptive suffixes, parentheses, translations, or free-form labels -- Ensure all in-scope design components included -- Verify task progression is logical and incremental -- Collapse single-subtask structures by promoting them to major tasks and avoid duplicating details on container-only major tasks (use template patterns accordingly) -- Apply `(P)` markers to tasks that satisfy parallel criteria (omit markers in sequential mode) -- Mark optional test coverage subtasks with `- [ ]*` only when they strictly cover acceptance criteria already satisfied by core implementation and can be deferred post-MVP -- If existing tasks.md found, merge with new content - -### Step 3: Finalize - -**Write and update**: -- Create/update `.specs/$ARGUMENTS/tasks.md` -- Update spec.json metadata: - - Set `phase: "tasks-generated"` - - Set `approvals.tasks.generated: true, approved: false` - - Set `approvals.requirements.approved: true` - - Set `approvals.design.approved: true` - - Update `updated_at` timestamp - -## Critical Constraints -- **Follow rules strictly**: All principles in tasks-generation.md are mandatory -- **Natural Language**: Describe what to do, not code structure details -- **Complete Coverage**: ALL in-scope requirements must map to tasks -- **Scope Lock**: Do not generate out-of-scope tasks; classify them as deferred when needed -- **Requirement Mapping Integrity**: Each task must map to valid numeric in-scope requirement IDs -- **Maximum 2 Levels**: Major tasks and sub-tasks only (no deeper nesting) -- **Sequential Numbering**: Major tasks increment (1, 2, 3...), never repeat -- **Task Integration**: Every task must connect to the system (no orphaned work) - - -## Tool Guidance -- **Read first**: Load all context, rules, and templates before generation -- **Write last**: Generate tasks.md only after complete analysis and verification - -## Output Description - -Provide brief summary in the language specified in spec.json: - -1. **Status**: Confirm tasks generated at `.specs/$ARGUMENTS/tasks.md` -2. **Task Summary**: - - Total: X major tasks, Y sub-tasks - - All Z requirements covered - - Average task size: 1-3 hours per sub-task -3. **Quality Validation**: - - ✅ All in-scope requirements mapped to tasks - - ✅ Task dependencies verified - - ✅ Testing tasks included -4. **Scope Guard**: - - ✅ Every task maps to valid in-scope requirement IDs - - ✅ Out-of-scope tasks deferred/blocked -5. **Next Action**: Review tasks and proceed when ready - -**Format**: Concise (under 200 words) - -## Safety & Fallback - -### Error Scenarios - -**Requirements or Design Not Approved**: -- **Stop Execution**: Cannot proceed without approved requirements and design -- **User Message**: "Requirements and design must be approved before task generation" -- **Suggested Action**: "Run `/spec-tasks $ARGUMENTS -y` to auto-approve both and proceed" - -**Missing Requirements or Design**: -- **Stop Execution**: Both documents must exist -- **User Message**: "Missing requirements.md or design.md at `.specs/$ARGUMENTS/`" -- **Suggested Action**: "Complete requirements and design phases first" - -**Incomplete Requirements Coverage**: -- **Warning**: "Not all in-scope requirements mapped to tasks. Review coverage." -- **User Action Required**: Confirm intentional gaps or regenerate tasks - -**Out-of-Scope Tasks Detected**: -- **Block/Defer**: Do not include out-of-scope tasks in primary task plan -- **User Guidance**: Request explicit scope expansion approval if user wants those tasks promoted - -**Template/Rules Missing**: -- **User Message**: "Template or rules files missing in `{{SKILLS_DIR}}/specs/`" -- **Fallback**: Use inline basic structure with warning -- **Suggested Action**: "Check repository setup or restore template files" - -**Missing Numeric Requirement IDs**: -- **Stop Execution**: All requirements in requirements.md MUST have numeric IDs. If any requirement lacks a numeric ID, stop and request that requirements.md be fixed before generating tasks. - -**Invalid Requirement Mapping in Tasks**: -- **Stop Execution**: If a generated task cannot map to valid in-scope numeric requirement IDs, remove/defer it and regenerate task mapping - -### Next Phase: Implementation - -**Before Starting Implementation**: -- **IMPORTANT**: Clear conversation history and free up context before running `/code` -- This applies when starting first task OR switching between tasks -- Fresh context ensures clean state and proper task focus - -**If Tasks Approved**: -- Execute coding pass from approved spec tasks: `/code $ARGUMENTS` -- After coding, run `/test` then `/review` -- Repeat in small passes and clear context between iterations when needed - -**If Modifications Needed**: -- Provide feedback and re-run `/spec-tasks $ARGUMENTS` -- Existing tasks used as reference (merge mode) - -**Note**: Continue with `/test` then `/review` after `/code` to complete the workflow. diff --git a/packages/spec/src/claude/archive-command/spec-validate.md b/packages/spec/src/claude/archive-command/spec-validate.md deleted file mode 100644 index 169a5f6d..00000000 --- a/packages/spec/src/claude/archive-command/spec-validate.md +++ /dev/null @@ -1,118 +0,0 @@ ---- -name: spec-validate -description: Validate design decisions with interview questions before task generation -allowed-tools: Read, Write, Edit, Glob, AskUserQuestion -argument-hint: ---- - -# Specification Validation Interview - - -- **Mission**: Validate critical design decisions, assumptions, and trade-offs before generating implementation tasks. -- **Success Criteria**: - - Ask targeted, concrete questions about high-impact decisions - - Record answers in spec artifacts for future traceability - - Update spec metadata to reflect validation status - - - -## Core Task -Run a structured interview for feature **$ARGUMENTS** and persist decisions. - -## Execution Steps - -### Step 0: Resolve & Validate State -- Require `$ARGUMENTS` as feature name -- Read `.specs/$ARGUMENTS/spec.json` -- Stop with guidance if spec does not exist -- Ensure `requirements.md` and `design.md` exist before validation - -### Step 1: Load Validation Context -Read: -- `.specs/$ARGUMENTS/spec.json` -- `.specs/$ARGUMENTS/requirements.md` -- `.specs/$ARGUMENTS/design.md` -- `.specs/$ARGUMENTS/research.md` (if exists) - -Resolve scope lock first: -- `scope_lock.source` -- `scope_lock.in_scope[]` -- `scope_lock.out_of_scope[]` -- `scope_lock.expansion_policy` - -Extract decision points around in-scope trade-offs only: -- architecture and boundaries -- assumptions and defaults -- integration risks -- scope and sequencing -- testing/security/performance trade-offs - -### Step 2: Determine Question Budget -Use injected session validation settings when available (`Validation: mode=X, questions=MIN-MAX`). -- If unavailable, use 3-6 questions -- Ask only meaningful questions that can change in-scope implementation -- Each question must have 2-4 concrete options -- Prefer in-scope confirmation questions first; scope-expansion questions are optional and only if needed - -### Step 3: Interview User -Use `AskUserQuestion` in batches (max 4 questions per call). -Rules: -- Include one recommended option when a safe default exists -- Keep options mutually exclusive -- Do not ask redundant questions -- Keep questions inside current scope by default -- Open-scope expansion questions are allowed only when scope pressure is detected and must require explicit user approval - -### Step 4: Persist Validation Log -Append to `.specs/$ARGUMENTS/research.md` under `## Validation Log`. -If section missing, create it. - -Session format: -```markdown -## Validation Log - -### Session N — YYYY-MM-DD -- Questions asked: X - -1. [Category] Question text - - Options: A | B | C - - Answer: ... - - Rationale: why this decision matters - -#### Confirmed Decisions -- ... - -#### Follow-up Actions -- [ ] ... -``` - -### Step 5: Update Metadata -Update `.specs/$ARGUMENTS/spec.json`: -- `approvals.requirements.approved: true` -- `approvals.design.approved: true` -- `validation.last_validated_at: ` -- `validation.questions_asked: ` -- `validation.status: "completed"` -- increment `validation.session_count` (initialize to 1 if absent) -- if explicit expansion approved by user, update `scope_lock.in_scope` / `scope_lock.out_of_scope` accordingly -- update `updated_at` - -## Constraints -- Keep input/output contract of existing `spec-*` commands unchanged -- Validation must be traceable and append-only (never overwrite old sessions) -- Ask fewer questions when artifact is simple; quality over quantity -- Do not introduce new capability domains during validation unless user explicitly approves scope expansion - - -## Output Description -Provide concise summary: -1. Validation status and files updated -2. Number of questions asked -3. Top confirmed decisions -4. Recommended next command: - - `/spec-tasks $ARGUMENTS` when ready - -## Safety & Fallback -- Missing spec/design artifacts: stop and instruct the exact preceding command -- Empty decision surface: ask only 1-2 high-value confirmation questions -- Write failure: report exact path and retry guidance diff --git a/packages/spec/src/claude/archive-command/test.md b/packages/spec/src/claude/archive-command/test.md deleted file mode 100644 index 8a8d65c0..00000000 --- a/packages/spec/src/claude/archive-command/test.md +++ /dev/null @@ -1,8 +0,0 @@ ---- -description: ⚡ Run tests locally and analyze the summary report. ---- - -Use the `test-runner` subagent to run tests locally and analyze the summary report. - -**IMPORTANT**: **Do not** start implementing. -**IMPORTANT:** Analyze the skills catalog and activate the skills that are needed for the task during the process. \ No newline at end of file diff --git a/packages/spec/src/claude/hooks/lib/config.cjs b/packages/spec/src/claude/hooks/lib/config.cjs index 892b1765..73f458fe 100644 --- a/packages/spec/src/claude/hooks/lib/config.cjs +++ b/packages/spec/src/claude/hooks/lib/config.cjs @@ -52,11 +52,6 @@ const DEFAULT_CONFIG = { packageManager: 'auto', framework: 'auto' }, - skills: { - research: { - useGemini: true // Toggle Gemini CLI usage in research skill - } - }, assertions: [], statusline: 'full', statuslineColors: true, diff --git a/packages/spec/src/claude/hooks/spec-state.cjs b/packages/spec/src/claude/hooks/spec-state.cjs index 8b06b6f0..fd6b1c76 100755 --- a/packages/spec/src/claude/hooks/spec-state.cjs +++ b/packages/spec/src/claude/hooks/spec-state.cjs @@ -30,6 +30,10 @@ try { if (fs.existsSync(p)) runtime = JSON.parse(fs.readFileSync(p, 'utf8')); } catch { /* ignore */ } + // Reminder toggle — same key the OpenCode spec-state plugin honors. + // (The Stop completion gate has its own toggle: spec.completion_gate.) + if (runtime.spec && runtime.spec.tollgate === false) process.exit(0); + const baseDir = process.env.PROJECT_ROOT || cwd; const specsPath = path.join(baseDir, runtime.paths?.specs || 'specs'); diff --git a/packages/spec/src/claude/hooks/usage.cjs b/packages/spec/src/claude/hooks/usage.cjs index 286ea810..b63d4ed8 100644 --- a/packages/spec/src/claude/hooks/usage.cjs +++ b/packages/spec/src/claude/hooks/usage.cjs @@ -8,6 +8,12 @@ * Fetches Claude Code usage limits from Anthropic OAuth API and writes to cache. * Cache is read by status.cjs for statusline display. * + * ⚠ EXPERIMENTAL / UNDOCUMENTED API: api.anthropic.com/api/oauth/usage with the + * "oauth-2025-04-20" beta header is not a public contract and may break or + * change shape without notice. Every failure path degrades to + * status:"unavailable" (statusline hides the segment) — never block on it. + * Disable entirely with "usage": { "enabled": false } if it misbehaves. + * * Features: * - Cross-platform credential retrieval (macOS Keychain, file-based) * - Throttled API calls: 1 min (prompt) / 5 min (tool use) diff --git a/packages/spec/src/claude/runtime.json b/packages/spec/src/claude/runtime.json index 51d34dd1..00d15f32 100644 --- a/packages/spec/src/claude/runtime.json +++ b/packages/spec/src/claude/runtime.json @@ -13,21 +13,18 @@ }, "paths": { "docs": "docs", - "specs": "specs" + "specs": "specs", + "plans": "plans" }, "spec": { "scaffold_guard": true, - "completion_gate": true + "completion_gate": true, + "tollgate": true }, "locale": { "thinkingLanguage": null, "responseLanguage": null }, - "skills": { - "research": { - "useGemini": true - } - }, "usage": { "enabled": true }, diff --git a/packages/spec/src/claude/skills/develop/SKILL.md b/packages/spec/src/claude/skills/develop/SKILL.md index 5afc519e..c5aa5726 100644 --- a/packages/spec/src/claude/skills/develop/SKILL.md +++ b/packages/spec/src/claude/skills/develop/SKILL.md @@ -95,7 +95,7 @@ You MUST implement all scoped behavior for the active task, MUST NOT add out-of- | Thought (Excuse) | Reality (Rule) | |-------------------|----------------| | "No need to scout first" | Coding without knowing the architecture is blind. ALWAYS call the `inspector` agent to scan files. | -| "Review process is too tedious, let me just finish it myself" | The system needs an audit trail through agents. ALWAYS delegate via `Task` tool. | +| "Review process is too tedious, let me just finish it myself" | The system needs an audit trail through agents. ALWAYS delegate via the `Agent` tool. | ## Absolute Workflow diff --git a/packages/spec/src/claude/skills/hotfix/references/parallel-patterns.md b/packages/spec/src/claude/skills/hotfix/references/parallel-patterns.md index 8a1aefe3..21017564 100644 --- a/packages/spec/src/claude/skills/hotfix/references/parallel-patterns.md +++ b/packages/spec/src/claude/skills/hotfix/references/parallel-patterns.md @@ -1,6 +1,6 @@ # Parallel Patterns & Task Coordination -How to effectively leverage multiple subagents and native Task tools during fix workflows. +How to effectively leverage multiple subagents (the `Agent` tool) and native task tracking (`TaskCreate`/`TaskUpdate`) during fix workflows. ## When to Go Parallel diff --git a/packages/spec/src/claude/skills/test/SKILL.md b/packages/spec/src/claude/skills/test/SKILL.md index 1cfe21e9..1925a3ab 100644 --- a/packages/spec/src/claude/skills/test/SKILL.md +++ b/packages/spec/src/claude/skills/test/SKILL.md @@ -177,7 +177,7 @@ It merges the JSON data into `.hapo/test-memory.json` per `references/test-memor | `hapo:develop` | orchestrates | Spawns hapo:test at Step 4 | | `inspector` agent | hapo:test → | Scout test file locations when structure is unfamiliar | | `god-developer` agent | hapo:test → | FAIL verdicts route back here for fixing | -| `test-runner` agent | hapo:test → | Primary executor, spawned via Task tool | +| `test-runner` agent | hapo:test → | Primary executor, spawned via the `Agent` tool | | chrome-devtools scripts | test-runner → | UI verification (navigate, screenshot, console, network, performance, aria-snapshot, inject-auth) | ## References diff --git a/packages/spec/src/claude/status.cjs b/packages/spec/src/claude/status.cjs index d705ae9b..b8a94493 100755 --- a/packages/spec/src/claude/status.cjs +++ b/packages/spec/src/claude/status.cjs @@ -21,8 +21,10 @@ const { countConfigs } = require('./hooks/lib/counter.cjs'); const { loadConfig } = require('./hooks/lib/config.cjs'); const { getGitInfo } = require('./hooks/lib/git.cjs'); -// Buffer constant matching /context output (22.5% of 200k) -const AUTOCOMPACT_BUFFER = 45000; +// Autocompact reserve as a fraction of the ACTUAL window size from the payload. +// Derived from /context on a 200k window (45000/200000 = 22.5%); expressed as a +// ratio so 1M-context models are not treated as if they were 200k. +const AUTOCOMPACT_BUFFER_RATIO = 0.225; /** * Expand home directory to ~ @@ -411,19 +413,20 @@ async function main() { } } catch {} - // Context window - use current_usage fields with AUTOCOMPACT_BUFFER + // Context window - use current_usage fields with a proportional reserve const usage = data.context_window?.current_usage || {}; const contextSize = data.context_window?.context_window_size || 0; let contextPercent = 0; let totalTokens = 0; - if (contextSize > 0 && contextSize > AUTOCOMPACT_BUFFER) { + if (contextSize > 0) { totalTokens = (usage.input_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0) + (usage.cache_read_input_tokens ?? 0); - // Add buffer to match /context calculation - contextPercent = Math.min(100, Math.round(((totalTokens + AUTOCOMPACT_BUFFER) / contextSize) * 100)); + // Add the reserve to match /context calculation on any window size + const buffer = Math.round(contextSize * AUTOCOMPACT_BUFFER_RATIO); + contextPercent = Math.min(100, Math.round(((totalTokens + buffer) / contextSize) * 100)); } // Write context data to temp file for hooks to read