feat: auto --init flag, headless prompts, and prompt sanitizer (#1417)

* fix: Created 10 headless prompt files (5 workflows + 5 agents) in sdk/p…

- "sdk/prompts/workflows/execute-plan.md"
- "sdk/prompts/workflows/research-phase.md"
- "sdk/prompts/workflows/plan-phase.md"
- "sdk/prompts/workflows/verify-phase.md"
- "sdk/prompts/workflows/discuss-phase.md"
- "sdk/prompts/agents/gsd-executor.md"
- "sdk/prompts/agents/gsd-phase-researcher.md"
- "sdk/prompts/agents/gsd-planner.md"

GSD-Task: S01/T02

* feat: Created prompt-sanitizer.ts, wired headless prompt loading into P…

- "sdk/src/prompt-sanitizer.ts"
- "sdk/src/phase-prompt.ts"
- "sdk/src/gsd-tools.ts"
- "sdk/src/gsd-tools.test.ts"
- "sdk/src/phase-runner-types.test.ts"

GSD-Task: S01/T01

* test: Added 111 unit tests covering sanitizePrompt(), headless prompt l…

- "sdk/src/prompt-sanitizer.test.ts"
- "sdk/src/headless-prompts.test.ts"
- "sdk/src/phase-prompt.test.ts"

GSD-Task: S01/T03

* feat: Wired sdkPromptsDir preference and sanitizePrompt into InitRunner…

- "sdk/src/init-runner.ts"
- "sdk/package.json"

GSD-Task: S02/T01

* feat: add --init flag to auto command for single-command PRD-to-execution

gsd-sdk auto --init @path/to/prd.md now bootstraps the project (init)
then immediately runs the autonomous phase execution loop.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* chore: add remaining headless prompt files and templates

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* test: Extended init-runner.test.ts with 7 sdkPromptsDir preference and…

- "sdk/src/init-runner.test.ts"

GSD-Task: S02/T03

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
TÂCHES
2026-03-26 22:40:34 -06:00
committed by GitHub
parent 0fde35acf9
commit 89f95c43ba
38 changed files with 5146 additions and 49 deletions

View File

@@ -0,0 +1,110 @@
<purpose>
Extract implementation decisions that downstream agents need. Analyze the phase to identify gray areas and capture decisions that guide research and planning.
Headless SDK variant — in autonomous mode, AI self-discusses by analyzing available context and making decisions based on project artifacts and codebase patterns.
</purpose>
<downstream_awareness>
**CONTEXT.md feeds into:**
1. **Researcher** — Reads CONTEXT.md to know WHAT to research
- Locked decisions guide research focus
- Discretion areas get options explored
2. **Planner** — Reads CONTEXT.md to know WHAT decisions are locked
- Locked decisions become non-negotiable plan constraints
- Discretion areas allow planner flexibility
</downstream_awareness>
<philosophy>
In headless mode, the AI acts as both visionary and builder. It:
- Analyzes the phase goal and available context
- Identifies gray areas that need decisions
- Makes autonomous decisions based on codebase patterns, requirements, and best practices
- Documents decisions clearly for downstream agents
</philosophy>
<scope_guardrail>
The phase boundary comes from the roadmap and is FIXED. Discussion clarifies HOW to implement what's scoped, never WHETHER to add new capabilities.
When analysis suggests scope creep: note it in "Deferred Ideas" section, do not act on it.
</scope_guardrail>
<process>
<step name="initialize" priority="first">
Load phase context from injected context files. Extract: phase directory, phase number, phase name, has_research, has_context, has_plans.
If phase not found: report error via event stream.
</step>
<step name="check_existing">
If CONTEXT.md already exists: load it and use as-is (in headless mode, existing context is not re-discussed).
If no CONTEXT.md: proceed to analysis.
</step>
<step name="load_prior_context">
Read project-level and prior phase context:
- PROJECT.md — vision, principles, non-negotiables
- REQUIREMENTS.md — acceptance criteria, constraints
- STATE.md — current progress, decisions
- Prior CONTEXT.md files — locked preferences from earlier phases
</step>
<step name="analyze_phase">
Analyze the phase to identify gray areas:
1. **Domain boundary** — What capability is this phase delivering?
2. **Check prior decisions** — What's already decided from earlier phases?
3. **Gray areas by category** — For each relevant category, identify 1-2 specific ambiguities
4. **Auto-resolve each gray area** — Make decisions based on:
- Codebase patterns (existing conventions)
- Prior phase decisions (consistency)
- Requirements (constraints)
- Best practices (industry standard)
5. **Log each decision** with rationale
</step>
<step name="write_context">
Create CONTEXT.md capturing decisions made:
```markdown
# Phase [X]: [Name] - Context
**Gathered:** [date]
**Status:** Ready for planning
**Source:** AI self-discuss (headless mode)
## Phase Boundary
[Clear statement of what this phase delivers]
## Implementation Decisions
### [Category]
- **D-01:** [Decision] — Rationale: [why]
### AI Discretion
[Areas where AI had flexibility and chose approach]
## Existing Code Insights
### Reusable Assets
- [Component/hook/utility]: [How it could be used]
### Established Patterns
- [Pattern]: [How it constrains/enables this phase]
## Specific Ideas
[Any particular approaches derived from codebase analysis]
## Deferred Ideas
[Ideas that came up but belong in other phases]
```
</step>
</process>
<success_criteria>
- Phase validated against roadmap
- Prior context loaded and honored
- Gray areas identified and resolved autonomously
- CONTEXT.md captures actual decisions with rationale
- Scope maintained (no creep into deferred ideas)
</success_criteria>

View File

@@ -0,0 +1,106 @@
<purpose>
Execute a phase plan (PLAN.md) and create the outcome summary (SUMMARY.md).
Headless SDK variant — runs autonomously without interactive checkpoints or user prompts.
</purpose>
<process>
<step name="init_context" priority="first">
Load execution context from the session's injected context files. Extract: phase directory, phase number, plans, summaries, incomplete plans, state path, config path.
If planning directory is missing: report error via event stream.
</step>
<step name="identify_plan">
Find the first PLAN without a matching SUMMARY. Decimal phases supported (e.g., `01.1-hotfix/`).
Proceed autonomously — no user confirmation needed.
</step>
<step name="record_start_time">
Record plan start timestamp for duration tracking.
</step>
<step name="parse_segments">
Check for checkpoint types in the plan:
**Routing by checkpoint type:**
| Checkpoints | Pattern | Execution |
|-------------|---------|-----------|
| None | A (autonomous) | Execute full plan + SUMMARY |
| Verify-only | B (segmented) | Execute segments autonomously; log verification results instead of pausing |
| Decision | C (main) | Make decisions autonomously based on available context |
In headless mode, all checkpoint types are handled autonomously:
- **human-verify** checkpoints: run automated verification, log results, continue
- **decision** checkpoints: select the recommended option (first option), log the choice, continue
- **human-action** checkpoints: log as a blocker if it requires credentials/auth; otherwise continue with best-effort automation
</step>
<step name="load_prompt">
Read the PLAN.md file. This IS the execution instructions. Follow exactly.
**If plan contains `<interfaces>` block:** Use pre-extracted type definitions directly — do not re-read source files to discover types.
</step>
<step name="execute">
Deviations are normal — handle via rules below.
1. Read context files from prompt
2. Per task:
- **MANDATORY read_first gate:** If the task has a `<read_first>` field, read every listed file BEFORE making edits.
- `type="auto"`: Implement with deviation rules. Verify done criteria.
- `type="checkpoint:*"`: Handle autonomously per parse_segments routing above.
- **MANDATORY acceptance_criteria check:** After completing each task, verify EVERY criterion before moving to the next task.
3. Run `<verification>` checks
4. Confirm `<success_criteria>` met
5. Document deviations in Summary
</step>
<authentication_gates>
Auth errors during execution are interaction points, not failures.
**Indicators:** "Not authenticated", "Unauthorized", 401/403, "Please run {tool} login", "Set {ENV_VAR}"
**Headless protocol:**
1. Recognize auth gate
2. Log the authentication requirement as a blocker event
3. Continue with remaining non-blocked tasks
4. Report blocked tasks in summary
</authentication_gates>
<deviation_rules>
| Rule | Trigger | Action | Permission |
|------|---------|--------|------------|
| **1: Bug** | Broken behavior, errors, type errors, security vulns | Fix inline, track `[Rule 1 - Bug]` | Auto |
| **2: Missing Critical** | Missing error handling, validation, auth, CSRF/CORS | Add inline, track `[Rule 2 - Missing Critical]` | Auto |
| **3: Blocking** | Prevents completion: missing deps, wrong types, broken imports | Fix blocker, track `[Rule 3 - Blocking]` | Auto |
| **4: Architectural** | Structural change: new DB table, schema change, new service | Log as blocker event; do NOT proceed with architectural changes autonomously | Report |
</deviation_rules>
<step name="verification_failure_gate">
If verification fails, attempt repair autonomously:
1. Analyze the failure
2. Attempt fix (budget: 2 attempts)
3. If repair succeeds: continue
4. If repair exhausted: log failure, continue with remaining tasks, report in summary
</step>
<step name="create_summary">
Create SUMMARY.md with:
- Frontmatter: phase, plan, subsystem, tags, dependency graph, tech-stack, key-files, key-decisions, duration, completion timestamp
- Substantive one-liner (not vague)
- Task completion details
- Deviations documentation
- Any blocked items from auth gates or architectural decisions
</step>
</process>
<success_criteria>
- All tasks from PLAN.md completed (or blocked items documented)
- All verifications pass (or failures documented)
- SUMMARY.md created with substantive content
- Deviations tracked and documented
</success_criteria>

View File

@@ -0,0 +1,84 @@
<purpose>
Create executable phase plans (PLAN.md files) for a roadmap phase with integrated research and verification.
Headless SDK variant — runs autonomously. Research, planning, and plan-checking proceed without user prompts.
Default flow: Research (if needed) -> Plan -> Verify -> Done.
</purpose>
<process>
<step name="initialize">
Load all context from injected context files. Extract: phase directory, phase number, phase name, research status, context status, plan count, requirement IDs.
If planning directory is missing: report error via event stream.
</step>
<step name="validate_phase">
Validate phase exists in roadmap. If not found: report error with available phases.
</step>
<step name="load_context">
Load CONTEXT.md if it exists. This contains user decisions that constrain planning.
If no CONTEXT.md exists: proceed without — plan using research and requirements only. In headless mode, there is no interactive discuss-phase; context comes from prior artifacts or is skipped.
</step>
<step name="handle_research">
If RESEARCH.md exists: use existing research.
If RESEARCH.md is missing and research is enabled:
1. Execute research phase (spawn researcher agent)
2. Researcher writes RESEARCH.md
3. Continue to planning
If research is disabled: skip to planning step.
</step>
<step name="spawn_planner">
Execute planning with the planner agent definition. Provide:
- Phase number, name, and goal
- Context files: state, roadmap, requirements, context, research
- Phase requirement IDs (every ID must appear in a plan's requirements field)
The planner creates PLAN.md files with task breakdown, dependency analysis, and verification criteria.
</step>
<step name="handle_planner_return">
- **PLANNING COMPLETE** — Plans created. If plan checker is enabled: proceed to verification.
- **PLANNING BLOCKED** — Log blocker, report via event stream.
- **PLANNING INCONCLUSIVE** — Report with available context.
</step>
<step name="spawn_plan_checker">
If plan checker is enabled, execute verification with the plan-checker agent. Provide:
- Phase number and goal
- Plan files to verify
- Roadmap, requirements, context, research files
- Phase requirement IDs
The checker verifies plans will achieve the phase goal before execution.
</step>
<step name="handle_checker_return">
- **VERIFICATION PASSED** — Plans ready for execution.
- **ISSUES FOUND** — Enter revision loop (max 3 iterations):
1. Send issues back to planner for targeted revision
2. Re-run plan checker
3. If max iterations reached: proceed with current plans, log remaining issues
</step>
<step name="requirements_coverage_gate">
After plans pass the checker (or checker is skipped), verify all phase requirements are covered:
1. Extract requirement IDs claimed by plans
2. Compare against phase requirements from roadmap
3. If gaps found: log as warning, continue (headless mode does not block for coverage gaps)
</step>
</process>
<success_criteria>
- Phase validated against roadmap
- Research completed (unless skipped or existing)
- PLAN.md file(s) created with valid structure
- Plan checker passed (or issues logged)
- Requirements coverage verified
</success_criteria>

View File

@@ -0,0 +1,44 @@
<purpose>
Research how to implement a phase. Produces RESEARCH.md consumed by the planner.
Headless SDK variant — runs autonomously without interactive prompts.
</purpose>
<process>
<step name="resolve_model">
Use the model configuration provided by the SDK session. No interactive model selection.
</step>
<step name="validate_phase">
Validate the phase exists in the roadmap using context files. If not found: report error via event stream.
</step>
<step name="check_existing_research">
Check if RESEARCH.md already exists for this phase. If exists and no force-refresh requested: use existing, skip research.
</step>
<step name="gather_phase_context">
Load phase context from injected context files:
- Context file (CONTEXT.md) — user decisions
- Requirements file (REQUIREMENTS.md) — project requirements
- State file (STATE.md) — project decisions and history
</step>
<step name="spawn_researcher">
Execute research with the phase researcher agent definition. Provide:
- Phase number and name
- Phase description and goal
- Context files to read
- Output path for RESEARCH.md
The researcher investigates the phase's technical domain, identifies standard stack, patterns, pitfalls, and writes RESEARCH.md.
</step>
<step name="handle_return">
Process researcher results:
- **RESEARCH COMPLETE** — Research file written, proceed to next phase step
- **RESEARCH BLOCKED** — Log blocker, report to event stream
- **RESEARCH INCONCLUSIVE** — Log findings, continue with available context
</step>
</process>

View File

@@ -0,0 +1,127 @@
<purpose>
Verify phase goal achievement through goal-backward analysis. Check that the codebase delivers what the phase promised, not just that tasks completed.
Headless SDK variant — runs autonomously without interactive prompts.
</purpose>
<core_principle>
**Task completion does not equal goal achievement.**
A task "create chat component" can be marked complete when the component is a placeholder. The task was done — but the goal "working chat interface" was not achieved.
Goal-backward verification:
1. What must be TRUE for the goal to be achieved?
2. What must EXIST for those truths to hold?
3. What must be WIRED for those artifacts to function?
Then verify each level against the actual codebase.
</core_principle>
<process>
<step name="load_context" priority="first">
Load phase operation context from injected context files. Extract: phase directory, phase number, phase name, plan count.
Load phase details, plans, and summaries. Extract the **phase goal** from the roadmap (the outcome to verify, not tasks) and **requirements** if they exist.
</step>
<step name="establish_must_haves">
**Option A: Must-haves in PLAN frontmatter**
Extract must_haves from each PLAN: `{ truths: [...], artifacts: [...], key_links: [...] }`
Aggregate all must_haves across plans for phase-level verification.
**Option B: Use Success Criteria from roadmap**
If no must_haves in frontmatter, use Success Criteria directly as truths. Derive artifacts and key links from there.
**Option C: Derive from phase goal (fallback)**
If neither source available: state the goal, derive 3-7 observable truths, derive artifacts, derive key links.
</step>
<step name="verify_truths">
For each observable truth, determine if the codebase enables it.
**Status:** VERIFIED (all supporting artifacts pass) | FAILED (artifact missing/stub/unwired) | UNCERTAIN (needs investigation)
For each truth: identify supporting artifacts, check artifact status, check wiring, determine truth status.
</step>
<step name="verify_artifacts">
Three-level verification:
**Level 1 — Exists:** File exists on disk.
**Level 2 — Substantive:** File has real content (not stub/placeholder). Check line count, expected patterns.
**Level 3 — Wired:** File is imported AND used by other code.
| Exists | Substantive | Wired | Status |
|--------|-------------|-------|--------|
| Yes | Yes | Yes | VERIFIED |
| Yes | Yes | No | ORPHANED |
| Yes | No | - | STUB |
| No | - | - | MISSING |
</step>
<step name="verify_wiring">
Key links are critical connections. If broken, the goal fails even with all artifacts present.
Verify each key link by checking imports, usage patterns, fetch calls, database queries, form handlers, and state rendering.
</step>
<step name="verify_requirements">
For each requirement mapped to this phase: identify supporting truths/artifacts, determine status (SATISFIED / BLOCKED / UNCERTAIN).
</step>
<step name="scan_antipatterns">
Scan files modified in this phase for:
| Pattern | Severity |
|---------|----------|
| TODO/FIXME/XXX/HACK | Warning |
| Placeholder content | Blocker |
| Empty returns | Warning |
| Log-only functions | Warning |
Categorize: Blocker (prevents goal) | Warning (incomplete) | Info (notable).
</step>
<step name="determine_status">
**passed:** All truths VERIFIED, all artifacts pass levels 1-3, all key links WIRED, no blocker anti-patterns.
**gaps_found:** Any truth FAILED, artifact MISSING/STUB, key link NOT_WIRED, or blocker found.
**Score:** verified_truths / total_truths
</step>
<step name="generate_fix_plans">
If gaps_found:
1. Cluster related gaps by concern
2. Generate plan per cluster: objective, 2-3 tasks, re-verify step
3. Order by dependency: fix missing, fix stubs, fix wiring, verify
</step>
<step name="create_report">
Create VERIFICATION.md with: frontmatter (phase/timestamp/status/score), goal achievement, artifact table, wiring table, requirements coverage, anti-patterns, gaps summary, fix plans (if gaps_found).
</step>
<step name="return_to_orchestrator">
Return status (passed | gaps_found), score (N/M must-haves), report path.
If gaps_found: list gaps and recommended fix plan names.
</step>
</process>
<success_criteria>
- Must-haves established (from frontmatter or derived)
- All truths verified with status and evidence
- All artifacts checked at all three levels
- All key links verified
- Requirements coverage assessed
- Anti-patterns scanned and categorized
- Overall status determined
- Fix plans generated (if gaps_found)
- VERIFICATION.md created with complete report
- Results returned to orchestrator
</success_criteria>