sp-analyze
Use when tasks.md exists and you need a non-destructive cross-artifact consistency and boundary-guardrail analysis before or during execution.
- License 许可
- MIT
- 最近更新
- 2026-08-07
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- sp-analyze
- metadata
- { "author": "github-spec-kit", "source": "templates/commands/analyze.md" }
- description
- Use when tasks.md exists and you need a non-destructive cross-artifact consistency and boundary-guardrail analysis before or during execution.
- argument-hint
- Optional focus areas for analysis, such as boundary guardrail drift (BG1/BG2/BG3)
- compatibility
- Requires spec-kit project structure with .specify/ directory
- user-invocable
- true
02 资源文件 2
- 参考文档references/INDEX.md604 B
- 参考文档references/semantic-work-contract.md31.5 KB
03 SKILL.md 正文
Invocation Syntax
- In this integration, invoke workflow skills with
/sp-plan-style syntax. - References such as
/sp.plan,/sp.tasks, ornext_command: /sp.planare canonical workflow-state identifiers and handoff values. - Preserve those canonical state tokens exactly in artifacts and workflow state; do not rewrite them to this integration's invocation syntax.
Workflow Contract Summary
- When to use:
tasks.mdis available and you need a read-only analysis pass before, during, or after implementation revalidation. - Primary objective: Identify inconsistencies, ambiguities, drift, and boundary-guardrail gaps across
spec.md,context.md,plan.md, andtasks.md. - Primary outputs: A structured analysis report plus workflow-state gate updates. This command does not edit
spec.md,context.md,plan.md, ortasks.md. - Default handoff: Route into /sp.clarify, /sp.deep-research, /sp.plan, /sp.tasks, /sp.debug, or /sp.implement based on the findings; if analysis runs after implementation has started or finished, reopen the highest invalid stage and regenerate downstream artifacts before continuing.
- Execution note: This summary is routing metadata only. Follow the full contract below end-to-end rather than inferring behavior from the description alone.
Blocked Exit Contract
If blocked after safe recovery, read and follow
.specify/templates/workflow-blocker-template.md and its JSON schema. Never
return only an error or “ask a human”; preserve state and keep agent-capable
repair agent-owned. Set human_action_required: true only for authority,
credentials, protected systems, human decisions/reviews, or physical access.
Tailor steps, expected results, failure paths, evidence, and resume action to
CI, visual review, or product decisions. Never claim completion.
User Input
$ARGUMENTS
You MUST consider the user input before proceeding (if not empty).
Objective
Perform a read-only analysis pass that checks whether the current spec, context, plan, and task artifacts still agree strongly enough to support execution.
Context
- Primary inputs:
spec.md,context.md,plan.md,tasks.md, passive learning files, the task-local project cognition query bundle with readiness and returnedminimal_live_reads, and the smallest workflow-local state files needed for the touched area. - Treat
spec-contract.json,plan-contract.json, andtask-index.jsonas the phase authorities. When delegation occurred, inspect the compactplanning/lane-manifest.jsonortask-generation/lane-manifest.jsonand only the accepted lane results needed to verify downstream consumption. Read clarification evidence only when analysis routes back to clarification. - The constitution remains the highest local authority for this analysis surface.
- This command produces findings only; it does not rewrite the artifact set.
Process
- Load the minimum artifact context needed to evaluate the current request.
- Compare the planning artifacts for drift, ambiguity, missing constraints, and boundary-guardrail gaps.
- Verify every accepted delegated lane result named by a compact manifest was consumed into the downstream canonical contract rather than only preserved on disk.
- Classify findings by severity and report how they should feed back into the workflow.
Output Contract
- Emit a structured analysis report with concrete findings, severity, and recommended remediation lanes.
- Keep the result non-destructive and explicit about what command should handle each class of issue.
- Do not silently fix artifacts from inside
/sp-analyze.
Guardrails
- Stay read-only.
- Treat constitution conflicts as critical rather than negotiable.
- Do not rely on stale or insufficient project cognition query coverage when the runtime should inform the analysis.
Senior Consequence Analysis Gate
Run this gate whenever the request, artifact set, defect, or planned change can affect lifecycle operations, running objects, concurrent work, destructive behavior, shared state, downstream consumers, compatibility, security-sensitive behavior, or multiple plausible product behaviors.
Project cognition first. Use the project cognition runtime to identify ownership, consumers, state surfaces, change-propagation facts, verification routes, conflicts, known unknowns, and coverage gaps. Senior consequence analysis second. Turn those facts into explicit product and implementation obligations instead of treating the graph as the decision-maker.
Project cognition readiness provides routing advice. If readiness is query_ready, read top-level minimal_live_reads first, then use lane-level first_pass_paths reasons. If readiness is review, inspect the returned minimal_live_reads before continuing and treat coverage_diagnostics as confidence and closeout signals. If readiness is needs_rebuild, continue with live repository evidence and recommend /sp-map-scan -> /sp-map-build only for brownfield first/missing/unusable baseline, schema failure, schema v1 or old broad-schema rebuild-required readiness, zero active-generation path_index rows outside greenfield_empty, missing or invalid alias_index, explicit_rebuild_requested, or baseline_identity_invalid. If readiness is blocked, report the blocked state and continue with live repository evidence unless the user's actual request is to fix cognition runtime state. If readiness is unsupported_runtime, continue with live evidence and record that compass intake was unavailable. If baseline_kind=greenfield_empty, continue with workflow artifacts and live requirements; do not recommend map-scan -> map-build solely because the graph has no paths. Carry relevant project cognition facts, returned minimal_live_reads, inference notes, and coverage gaps into the workflow's artifacts or durable state, but back consequence claims with live code, tests, scripts, configuration, or authoritative docs. Mutation closeout is separate from entry routing: entry stale may continue, but that does not allow source/runtime mutation workflows to defer closeout. Workflow-owned mutation closeout is not an external map-maintenance handoff; after changing project-related files or behavior, the workflow must run inline project cognition update from its changed paths, affected surfaces, and verification evidence, with project-cognition mark-dirty only as fallback when inline update cannot complete. sp-map-update is for manual/external maintenance and follow-up repair; it is external map maintenance, not routine closeout for this workflow's own changes. In shared routing summaries, sp-map-update is for manual/external maintenance and ordinary existing-baseline gaps.
Required output when the gate triggers:
- Affected Object Map: name each object, record, worker, queue, artifact, command, API, file surface, user-visible state, or downstream consumer that can be affected.
- State-Behavior Matrix: describe behavior for each important lifecycle state, including created, queued, running, paused, failed, cancelled, completed, resumed, archived, missing, stale, or partially refreshed states when relevant.
- Dependency Impact Table: map direct dependencies, indirect consumers, shared state, compatibility surfaces, validation routes, and adjacent workflows that can break if semantics change.
- Recovery And Validation Contract: state rollback, retry, idempotency, cleanup, migration, observability, and validation evidence required before handoff or completion.
- Coverage Gaps: list what project cognition or live evidence cannot prove, who must resolve each gap, the latest safe resolve phase, the stop-and-reopen condition, and the routing decision: current workflow may continue with an assumption, must ask the user, must route to clarification or deep research, or must request map maintenance.
- Consequence Obligations: assign stable
CA-###IDs to every obligation that must survive downstream handoff, task generation, worker packets, verification, or debug closeout. EachCA-###must include claim, affected objects, owner workflow, latest resolve phase, status, and stop-and-reopen condition.
Stand down only for docs-only wording changes, trivial isolated fixes, or local refactors that cannot affect lifecycle operations, running state, destructive operations, shared state, downstream consumers, compatibility, security, or multiple behavior choices. Record the no-trigger reason or stand-down reason in the workflow's durable artifact or closeout before skipping the required outputs.
If the gate triggers and the current workflow cannot preserve the required outputs, stop and route to the workflow that can. Do not mark ready, resolved, handoff-ready, planning-ready, or complete while triggered consequence obligations remain unresolved, unmapped, or unsupported by validation evidence.
[AGENT] For project-cognition-backed semantic intake, routing, audit, resume, or final-claim gates, read references/semantic-work-contract.md.
Detailed References
Read Reference index before applying shared semantic contracts.
Mandatory Subagent Execution
All substantive tasks in ordinary sp-* workflows default to and must use subagents.
The leader orchestrates: route, split tasks, prepare task contracts, dispatch subagents, wait for structured handoffs, integrate results, verify, and update state.
Before dispatch, every subagent lane needs a task contract with objective, authoritative inputs, allowed read/write scope, forbidden paths, acceptance checks, verification evidence, and structured handoff format.
Use execution_model: subagent-mandatory.
Use dispatch_shape: one-subagent | parallel-subagents.
Use execution_surface: native-subagents.
Goal
Identify inconsistencies, duplications, ambiguities, and underspecified items across the core planning artifacts (spec.md, context.md, plan.md, tasks.md) before implementation, during execution, or after implementation when revalidation is needed. This command MUST run only after the canonical /sp.tasks workflow has successfully produced a complete tasks.md.
Operating Constraints
READ-ONLY FOR PLANNING ARTIFACTS: Do not modify spec.md, context.md, plan.md, or tasks.md. Output a structured analysis report. This command may update workflow-state.md to record the cleared or blocked gate result. Offer an optional remediation plan (user must explicitly approve before any follow-up editing commands would be invoked manually).
Analyze must not switch branches, implicitly check out a "correct" feature branch, or mutate git state in order to determine scope. If the active feature cannot be identified safely through explicit FEATURE_DIR binding or lane resolution, fail closed and tell the user how to repair routing.
Closed-loop requirement: Do not present findings as a dead-end audit. The report MUST tell the user which workflow stage to reopen, which downstream artifacts must be regenerated, and whether implementation may continue immediately or must pause until upstream remediation is complete.
Preserve canonical /sp.implement only in workflow-state fields.
When recommending manual implementation resumption to the user, tell them to run /sp-implement.
Convergence requirement: Complete the full detection matrix before selecting the single Recommended Next Command. Do not stop analysis after finding enough evidence to route backward. The report must include the complete blocker bundle for the current artifact set, grouped by invalid stage, so downstream remediation does not discover same-artifact blockers one cycle at a time.
Constitution Authority: The project constitution (.specify/memory/constitution.md) is non-negotiable within this analysis scope. Constitution conflicts are automatically CRITICAL and require adjustment of the spec, plan, or tasks—not dilution, reinterpretation, or silent ignoring of the principle. If a principle itself needs to change, that must occur in a separate, explicit constitution update outside /sp.analyze.
Workflow Phase Lock
- [AGENT] Create or resume
WORKFLOW_STATE_FILEbefore substantial analysis work begins. - Read
.specify/templates/workflow-state-template.md. - If
WORKFLOW_STATE_FILEis missing, recreate it from the template and the current artifact package instead of relying on chat memory alone. - Treat
WORKFLOW_STATE_FILEas the gate-state source of truth for whether implementation may proceed. - Set or update the state for this run with at least:
active_command: sp-analyzephase_mode: analysis-onlyforbidden_actions: edit source code, edit tests, edit planning artifacts, start implementation before the gate is cleared
- When resuming after compaction, re-read
WORKFLOW_STATE_FILEbefore continuing.
Analyze Gate Convergence Contract
Stable Finding Identity
- Use stable finding IDs that survive revalidation. Category-only IDs such as
BG2are too coarse, and run-local sequence numbers are not stable by themselves. - Use a fingerprint-first ID contract:
- Build a canonical finding fingerprint from category, invalid stage, artifact, requirement or section key when available, normalized summary, and remediation requirement.
- Before assigning IDs, load the previous
Analyze Gateledger fromworkflow-state.mdwhen it exists. - Match current findings to previous open or recently cleared findings by fingerprint first, and reuse the prior ID when the fingerprint matches.
- Allocate a new ID only for a genuinely new fingerprint.
- For new fingerprints, allocate the next unused category sequence after sorting by category, artifact, section key, and normalized summary.
Revalidation Attribution
- When revalidating after a blocked analyze gate, any new blocker must include one attribution:
missed_by_previous_analyze: detectable in the prior artifact set and should have been included in the earlier blocker bundle.introduced_by_remediation: remediation changedtasks.mdor downstream state in a way that introduced the issue.upstream_artifact_changed: an authoritative input changed since the prior analyze pass.detector_scope_changed: the workflow template or analysis instructions changed the detector scope between runs.
- If there is no evidence for
introduced_by_remediation,upstream_artifact_changed, ordetector_scope_changed, usemissed_by_previous_analyze. - Persist attribution per new blocking finding in the
Analyze Gateblocker_bundle; report-body attribution without durable blocker-row attribution is not sufficient for revalidation. - No more than one task-layer remediation cycle is expected. If revalidation finds new task-layer blockers that were detectable before remediation, classify them as a previous analyze miss or a tasks self-audit failure. Do not treat repeated task/analyze loops as normal workflow.
Workflow Quality Requirements
- Confirm project cognition freshness and valid workflow entry before deeper analysis begins.
- Keep
workflow-state.mdcurrent as the durable gate-state source of truth for whether implementation may proceed, which stage must reopen, and what evidence supports the decision. - Verify the analysis report, cleared or blocked gate result, and any durable artifact outcomes before final reporting instead of relying on chat narration.
- Update durable analysis state before compaction-risk transitions, large findings synthesis, remediation handoffs, or any stop where resume will depend on more than the visible conversation.
Project Learning
The CLI is the only agent-facing Learning read surface:
- Run
uvx --from git+https://github.com/chenziyang110/spec-kit-plus.git@4a631657f75460886dbd12ebe48b14fc11cfe0bf specify learning start --command <classic-command-name> --format jsonbefore deeper non-trivial work. - Select summaries by applicability and triggers; use
uvx --from git+https://github.com/chenziyang110/spec-kit-plus.git@4a631657f75460886dbd12ebe48b14fc11cfe0bf specify learning list --command <classic-command-name> --format jsononly to filter or page. - Execute one matching card's
show_argv. Do not parse Learning storage.
start, list, and show are read-only. Current repository evidence,
.specify/memory/constitution.md, and explicit user direction override stale or
candidate Learning.
At closeout, corrections, retries, route changes, recovery, false leads, hidden
dependencies, validation/tooling/state/cognition gaps, constraints, and near
misses are capture signals. Prefer uvx --from git+https://github.com/chenziyang110/spec-kit-plus.git@4a631657f75460886dbd12ebe48b14fc11cfe0bf specify learning capture-auto
from owning state; manual capture includes summary, problem, action, triggers,
success criteria, avoid items, exceptions, and evidence.
fast: skip unless the task escalates.accept,analyze,ask,auto,constitution,explain,implement-teams,taskstoissues, andteam: consume-only; do not violate their write boundaries to capture.- Other non-trivial workflows: consume before deeper work; capture reusable signals at closeout or record a no-learning decision.
The policy returned by the CLI is authoritative when prompt wording drifts.
Execution Steps
1. Initialize Analysis Context
Run .specify/scripts/powershell/check-prerequisites.ps1 -Json -RequireTasks -IncludeTasks once from repo root and parse JSON for FEATURE_DIR and AVAILABLE_DOCS. Derive absolute paths:
-
If
FEATURE_DIRis not already explicit, preferuvx --from git+https://github.com/chenziyang110/spec-kit-plus.git@4a631657f75460886dbd12ebe48b14fc11cfe0bf specify lane resolve --command analyze --ensure-worktreebefore guessing from branch-only context. -
When lane resolution returns a materialized lane worktree, continue analysis from that isolated worktree context so downstream gate decisions stay attached to the same lane boundary.
-
SPEC_CONTRACT = FEATURE_DIR/spec-contract.json
-
PLAN_CONTRACT = FEATURE_DIR/plan-contract.json
-
TASK_INDEX = FEATURE_DIR/task-index.json for standard/heavy work, otherwise TASKS = FEATURE_DIR/tasks.md
-
PLANNING_LANE_MANIFEST = FEATURE_DIR/planning/lane-manifest.json when present
-
TASK_GENERATION_LANE_MANIFEST = FEATURE_DIR/task-generation/lane-manifest.json when present
Abort with an error message if any required file is missing (instruct the user to run missing prerequisite command). For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'''m Groot' (or double-quote if possible: "I'm Groot").
- Set
WORKFLOW_STATE_FILEtoFEATURE_DIR/workflow-state.md. - [AGENT] Create or resume
WORKFLOW_STATE_FILEbefore substantial analysis work begins. - Read
.specify/templates/workflow-state-template.md. - If
WORKFLOW_STATE_FILEalready exists, read it first and preserve still-valid authoritative file references and gate notes instead of relying on chat memory alone.
2. Ensure project cognition runtime exists
- Choose the cognition intent before querying: use
planwhen analyzing planning-only artifacts or upstream spec/plan drift, useimplementwhen analyzing task execution, remediation, or code-change blockers, and preserve the originating workflow intent when this command is reviewing anothersp-*workflow's output. - Query project cognition with
C:\Users\11034\.specify\bin\project-cognition.exe compass --intent plan --query=\"$ARGUMENTS\" --format jsonorC:\Users\11034\.specify\bin\project-cognition.exe compass --intent implement --query=\"$ARGUMENTS\" --format jsonaccording to that chosen intent. Read top-levelminimal_live_readsfirst, then use lane-levelfirst_pass_pathsreasons,verification_hints,followup_surfaces, andbefore_fix_claim. Treatcoverage_diagnosticsas confidence and closeout signals, do not infer final edit scope from first-pass reads, and useproject-cognition expandonly when the packet's coverage state or live evidence requires it. - Preserve the advanced
lexicon -> semantic_intake -> queryflow for explicit concept decisions or unresolved coverage. In that escalation, writesemantic_intakefrom the alias catalog, select candidates by facet coverage, writeconcept_decisionswithcovered_facets,missing_facets, andmatch_sources, carrylexicon_generation_id, then generate aquery_plancontainingsemantic_intake,selected_concepts,rejected_concepts,concept_decisions,lexicon_generation_id,expanded_queries,repository_search_terms, and justifiedpaths, then runC:\Users\11034\.specify\bin\project-cognition.exe query --intent <chosen-intent> --query-plan \"<query_plan_json>\" --format json. Agent-owned semantic normalization is mandatory: raw lexicon ranking andagent_normalizationare only bootstrap signals, not route decisions. Ifagent_normalization.required=true, every raw candidate isscore=0, or the prompt is localized, mixed-language, CJK, colloquial, or symptom-first, extract embedded project terms and writesemantic_intakefrom the alias catalog before selecting or rejecting concepts. Ifagent_normalizationis omitted, treat it asrequired=false; CJK or mixed CJK/ASCII input still requires agent normalization even when positive raw lexical matches exist because embedded project tokens do not translate the surrounding user language. The agent still owns translation;agent_normalizationis advisory guidance, not a route decision. This includes mixed-language or CJK text. (raw lexicon ranking is only a bootstrap; action: write_semantic_intake_from_alias_catalog) Derive project-language search terms from the alias catalog before source search. Do not search only the raw user words; include component names, state names, file names, command names, UI labels, and route names from candidates, aliases, matched_terms, colloquial_matches, returned paths,normalized_query, andexpanded_queries. Use these project-language search terms before broad repository search. For implementation or remediation analysis, the concrete advanced query command isC:\Users\11034\.specify\bin\project-cognition.exe query --intent implement --query-plan \"<query_plan_json>\" --format json. - If readiness is
needs_rebuild, continue with live repository evidence where workflow policy allows and recommend/sp-map-scan, then/sp-map-buildonly for brownfield first/missing/unusable baseline, schema failure, schema v1 or old broad-schema rebuild-required readiness, zero active-generation path_index rows, missing or invalid alias_index, explicit_rebuild_requested, or baseline_identity_invalid. Block only when the user explicitly requested cognition repair or analysis truly cannot proceed without a usable baseline. - If compass coverage is too weak for the touched area, use live evidence and record whether a follow-up
/sp-map-updateis useful for external map maintenance. - Use map-update for ordinary existing-baseline gaps. Use map-scan -> map-build only for first/missing/unusable baseline, schema failure, schema v1 or old broad-schema rebuild-required readiness, zero active-generation path_index rows, missing or invalid alias_index, explicit_rebuild_requested, or baseline_identity_invalid.
- If readiness is
review, inspect only the returnedminimal_live_readsbefore trusting the runtime for analysis. - Carry selected/rejected concepts,
selection_reason,route_pack, andminimal_live_readsinto the analysis report andworkflow-state.mdblocker bundle whenever cognition evidence affects routing or blocker severity. - Treat task-relevant coverage as insufficient when the touched area is named only vaguely, lacks ownership or placement guidance, or lacks workflow, constraint, integration, or regression-sensitive testing guidance.
- If task-relevant coverage is insufficient for the current analysis request, inspect the returned targeted live evidence; refresh through
/sp-map-updatewith changed paths or affected surfaces, and rebuild through/sp-map-scan, then/sp-map-buildonly for the explicit rebuild conditions above.
3. Load Artifacts (Progressive Disclosure)
Load only the minimal necessary context from each artifact:
From project cognition runtime:
- Consume the
project-cognition querybundle. - Preserve
selected_concepts,rejected_concepts,selection_reason,route_pack, andminimal_live_readsas blocker evidence inputs. - Preserve cognition-backed blocker evidence when classifying whether issues
belong to
plan,clarify,deep-research, or task-layer remediation. The analysis report andworkflow-state.mdblocker bundle must keep the selected capability, boundary fact, ambiguity, or verification evidence that justified the route. - Inspect only returned
minimal_live_readswhen the bundle does not fully cover ownership, propagation, or verification routes. - If topical coverage is missing, stale, too broad, or task-relevant coverage is insufficient, use
/sp-map-updatewith changed paths or affected surfaces; rebuild through/sp-map-scanfollowed by/sp-map-buildonly for the explicit rebuild conditions above, then inspect the minimum live files still needed to replace guesswork with evidence
From spec-contract.json first (open spec.md/context.md only for a named detail or contradiction):
- Overview/Context
- Functional Requirements
- Success Criteria (measurable outcomes — e.g., performance, security, availability, user success, business impact)
- User Stories
- Edge Cases (if present)
From conditional context view when referenced:
- Locked Decisions
- Claude Discretion
- Canonical References
- Existing Code Insights
- Specific User Signals
- Outstanding Questions
From plan-contract.json first (open plan.md or conditional design artifacts only for a named detail or contradiction):
- Architecture/stack choices
- Locked Planning Decisions
- Implementation Constitution
- Alignment Inputs
- Data Model references
- Phases
- Technical constraints
From task-index.json, or tasks.md for light direct work:
- Task IDs
- Descriptions
- Phase grouping
- Parallel markers [P]
- Referenced file paths
From delegated planning lanes when present:
- Read
planning/lane-manifest.jsonand only the accepted lane results it names. - Verify each accepted result is consumed by
plan-contract.jsonor a referenced conditional artifact, or is explicitly deferred or blocked. - Treat an accepted planning handoff with no downstream consumer as a plan-layer blocker, not harmless leftover evidence.
From delegated task-generation lanes when present:
- Read
task-generation/lane-manifest.jsonand only the accepted lane results it names. - Verify each accepted result is consumed by
task-index.jsonor the light direct task list, or is explicitly deferred, escalated, or blocked. - Treat an accepted task-generation handoff with no downstream consumer as a task-layer blocker before implementation can proceed.
From constitution:
- Load
.specify/memory/constitution.mdfor principle validation
4. Build Semantic Models
Create internal representations (do not include raw artifacts in output):
- Requirements inventory: For each Functional Requirement (FR-###) and Success Criterion (SC-###), record a stable key. Use the explicit FR-/SC- identifier as the primary key when present, and optionally also derive an imperative-phrase slug for readability (e.g., "User can upload file" →
user-can-upload-file). Include only Success Criteria items that require buildable work (e.g., load-testing infrastructure, security audit tooling), and exclude post-launch outcome metrics and business KPIs (e.g., "Reduce support tickets by 50%"). - Locked decision inventory: Collect locked decisions from
spec.md,context.md, andplan.md, then track whether each one survives into the task layer - Reference behavior inventory: When
Fidelity Requirementsexist, collect each reference behavior item and track whether it survives into the plan and task layers - Boundary-sensitivity inventory: Record established boundary patterns, framework-owned surfaces, required implementation references, and any signal that this feature should carry explicit implementation guardrails
- User story/action inventory: Discrete user actions with acceptance criteria
- Task coverage mapping: Map each task to one or more requirements or stories (inference by keyword / explicit reference patterns like IDs or key phrases)
- Constitution rule set: Extract principle names and MUST/SHOULD normative statements
5. Detection Passes (Token-Efficient Analysis)
Focus on high-signal findings in the report body and include every unique actionable finding. Repetitive non-blocking observations may be grouped only when the group preserves their evidence, owner, and repair route. Never omit blockers from the durable gate result: Blocker Bundle and workflow-state.md MUST enumerate every blocking finding.
A. Duplication Detection
- Identify near-duplicate requirements
- Mark lower-quality phrasing for consolidation
B. Ambiguity Detection
- Flag vague adjectives (fast, scalable, secure, intuitive, robust) lacking measurable criteria
- Flag unresolved placeholders (TODO, TKTK, ???,
<placeholder>, etc.)
C. Underspecification
- Requirements with verbs but missing object or measurable outcome
- User stories missing acceptance criteria alignment
- Tasks referencing files or components not defined in spec/plan
D. Constitution Alignment
- Any requirement or plan element conflicting with a MUST principle
- Missing mandated sections or quality gates from constitution
E. Coverage Gaps
- Requirements with zero associated tasks
- Tasks with no mapped requirement/story
- Success Criteria requiring buildable work (performance, security, availability) not reflected in tasks
- Preserved or redesigned reference behavior items with zero associated plan handling or task coverage
F. Locked Decision Drift
- Locked decisions present in
spec.mdbut absent fromcontext.md - Locked decisions present in
context.mdbut missing fromplan.md - Locked decisions present in
plan.mdbut not preserved bytasks.md - Cases where a decision appears to have been silently weakened, deferred, or renamed without acknowledgment
G. Inconsistency
- Terminology drift (same concept named differently across files)
- Data entities referenced in plan but absent in spec (or vice versa)
- Task ordering contradictions (e.g., integration tasks before foundational setup tasks without dependency note)
- Conflicting requirements (e.g., one requires Next.js while other specifies Vue)
H. Boundary Guardrail Gaps
- Detect cases where
spec.md,context.md, ortasks.mdclearly imply a boundary-sensitive implementation area, but later workflow artifacts fail to preserve the needed guardrails - Use this stable issue family so downstream tooling and reviewers can key off one consistent signal set:
BG1: missingImplementation Constitutionfor a boundary-sensitive feature areaBG2:tasks.mdlacks explicit implementation guardrails even thoughplan.mddeclares a boundary-sensitive constitution ruleBG3: implementation guidance does not require confirming the owning framework, defining reference files, or forbidden drift before code-writing work beginsDP1: subagent execution path lacks compiled hard rules, validation gates, or done criteria in its task packetDP2: subagent execution path lacks required references or forbidden drift in its task packetDP3: subagent completion lacks required validation evidence or rule acknowledgement
- Treat these signals as triggers:
- established framework-owned boundary or adapter pattern
- native bridge, plugin surface, protocol seam, generated API surface, or other contract-heavy boundary
- explicit required implementation references or boundary-defining files
- implementation guardrail tasks in
tasks.mdwith no matching constitution rule inplan.md
- Map findings to codes as follows:
BG1when the plan is missing the constitution layerBG2when the task layer fails to preserve that constitution as implementation guardrailsBG3when execution guidance fails to force pre-dispatch boundary confirmation
- Report when a generic implementation instinct would likely drift away from the repository's established pattern because the plan left the constraint as background context only
I. Consequence Preservation Analysis
- Detect every
CA-###consequence obligation inspec.md,context.md,references.md,alignment.md,plan.md,tasks.md,plan-contract.json,task-index.json, and task packets when present. - Verify each consequence obligation keeps its claim, affected objects, lifecycle state behavior, dependency impact, recovery and validation contract, owner workflow, latest resolve phase, status, and stop-and-reopen condition across downstream artifacts.
- Flag any obligation that disappears, is renamed without traceability, loses validation evidence, lacks task or packet coverage, or is treated as resolved without proof.
- Must not drop consequence obligations from the analysis report or blocker bundle. If an upstream artifact omitted one, report the omission and route to the highest invalid workflow stage that can restore it.
- Treat unresolved or unmapped
CA-###obligations as blockers when implementation would otherwise continue through lifecycle, running-state, destructive-operation, shared-state, or downstream-consumer ambiguity. - If the consequence model is complete and every stop-and-reopen condition is mapped or resolved, record the gate as cleared for implementation; otherwise keep implementation paused.
6. Severity Assignment
Use this heuristic to prioritize findings:
- CRITICAL: Violates constitution MUST, missing core spec artifact, or requirement with zero coverage that blocks baseline functionality
- HIGH: Duplicate or conflicting requirement, ambiguous security/performance attribute, untestable acceptance criterion, a locked decision silently dropped between artifacts, or a missing
Implementation Constitutionfor a clearly boundary-sensitive feature area - MEDIUM: Terminology drift, missing non-functional task coverage, underspecified edge case
- LOW: Style/wording improvements, minor redundancy not affecting execution order
7. Produce Compact Analysis Report
Output a Markdown report (no file writes) with the following structure:
Specification Analysis Report
| ID | Signal Code | Category | Severity | Location(s) | Summary | Recommendation |
|---|---|---|---|---|---|---|
| A1-001 | A1 | Duplication | HIGH | spec.md:L120-134 | Two similar requirements ... | Merge phrasing; keep clearer version |
| BG1-001 | BG1 | Boundary Guardrail Gap | HIGH | plan.md, tasks.md | Boundary-sensitive area lacks Implementation Constitution in the plan |
Re-run /sp-plan to add the constitution, then /sp-tasks if guardrail tasks need regeneration |
| BG2-001 | BG2 | Boundary Guardrail Gap | HIGH | tasks.md | Plan declares a boundary-sensitive constitution rule, but tasks do not preserve it as implementation guardrails | Re-run /sp-tasks or edit tasks.md so guardrail tasks exist before setup or feature work |
| BG3-001 | BG3 | Boundary Guardrail Gap | HIGH | implement guidance | Execution guidance does not force boundary confirmation before code-writing work starts | Update implementation guidance so the owning framework, required references, and forbidden drift are confirmed before dispatch |
| DP1-001 | DP1 | Dispatch Packet Gap | HIGH | implement guidance, runtime payload | Delegated execution path is missing compiled hard rules, validation gates, or done criteria | Compile and validate a WorkerTaskPacket before dispatch |
| DP2-001 | DP2 | Dispatch Packet Gap | HIGH | plan.md, tasks.md, runtime payload | Delegated execution path is missing required references or forbidden drift | Add packet references/forbidden drift to planning artifacts, then recompile |
| DP3-001 | DP3 | Dispatch Result Gap | HIGH | subagent result, join point | Subagent completion lacks validation evidence or rule acknowledgement | Reject the subagent result and require a packet-compliant rerun |
(Add one row per finding. Each row uses a stable fingerprint-first finding ID, and keeps BG/DP values as signal codes where applicable.)
Blocker Bundle:
The Blocker Bundle MUST enumerate every blocking finding. Do not hide blocking findings inside grouped summaries.
| Invalid Stage | Blocking Finding IDs | Required Re-entry | Notes |
|---|---|---|---|
| clarify | [IDs or none] | /sp-clarify |
Reopen spec/context truth, then regenerate downstream artifacts |
| deep-research | [IDs or none] | /sp-deep-research |
Prove unresolved implementation chain before planning |
| plan | [IDs or none] | /sp-plan |
Repair planning truth, then regenerate tasks |
| tasks | [IDs or none] | /sp-tasks |
Repair task decomposition and rerun analyze |
| execution-only | [IDs or none] | /sp-implement or /sp-debug |
No upstream artifact regeneration required |
Coverage Summary Table:
| Requirement Key | Has Task? | Task IDs | Notes |
|---|
Locked Decision Preservation Table:
| Locked Decision | In Context? | In Plan? | In Tasks? | Notes |
|---|
Reference Behavior Preservation Table: (if any)
| Behavior ID | In Spec Fidelity? | In Plan? | In Tasks? | Notes |
|---|
Boundary Guardrail Table: (if any)
| Boundary Signal | Seen In Spec/Context? | Seen In Plan Constitution? | Seen In Tasks Guardrails? | Notes |
|---|
Constitution Alignment Issues: (if any)
Unmapped Tasks: (if any)
Metrics:
- Total Requirements
- Total Tasks
- Coverage % (requirements with >=1 task)
- Ambiguity Count
- Duplication Count
- Critical Issues Count
- Boundary Guardrail Gap Count
8. Provide Next Actions
At the end of the report, output exactly one Recommended Next Command based on the highest invalid workflow stage.
- If the highest-impact unresolved issue lives in
spec.mdorcontext.md,Recommended Next CommandMUST be/sp-clarify. - If the highest-impact unresolved issue is a clear requirement whose implementation chain is still unproven,
Recommended Next CommandMUST be/sp-deep-research. - If the highest-impact unresolved issue lives in
plan.md,Recommended Next CommandMUST be/sp-plan. - If the highest-impact unresolved issue lives only in
tasks.md,Recommended Next CommandMUST be/sp-tasks. - If no upstream artifact is invalid and the remaining issue is execution-only,
Recommended Next CommandMUST be/sp-implementor/sp-debug, whichever matches the recorded execution problem. - Do not output multiple alternative next commands for the same analysis result.
9. Define Workflow Re-entry
After Next Actions, output a short Recommended Re-entry block that names:
- the single highest workflow stage that must be reopened
- the minimum downstream regeneration path from that stage
Rules:
- If the highest invalid stage is
clarify, the re-entry chain MUST be/sp-clarify -> /sp-plan -> /sp-tasks -> /sp-analyze -> /sp-implement. - If the highest invalid stage is
deep-research, the re-entry chain MUST be/sp-deep-research -> /sp-plan -> /sp-tasks -> /sp-analyze -> /sp-implement. - If the highest invalid stage is
plan, the re-entry chain MUST be/sp-plan -> /sp-tasks -> /sp-analyze -> /sp-implement. - If the highest invalid stage is
tasks, the re-entry chain MUST be/sp-tasks -> /sp-analyze -> /sp-implement. - If the remaining issue is execution-only, the re-entry chain MUST begin at
/sp-implementor/sp-debug. - Do not output multiple alternative re-entry chains for the same result.
9.5 Persist Workflow Gate Result
Before the final completion text, write or update WORKFLOW_STATE_FILE so it records the gate outcome:
Always update or preserve the Analyze Gate section in WORKFLOW_STATE_FILE with:
gate_status: cleared | blockedgate_cycle: [integer]highest_invalid_stage: clarify | deep-research | plan | tasks | execution-only | noneblocker_bundle: [finding ID | invalid stage | status | attribution | compact summary | remediation requirement]artifact_fingerprint_basis: [spec.md/context.md/plan.md/tasks.md summaries or hashes when available]
When revalidation finds a new blocker, record its attribution on that blocker_bundle row using missed_by_previous_analyze, introduced_by_remediation, upstream_artifact_changed, or detector_scope_changed.
- When no upstream remediation is required, record the analyze gate as cleared and hand off to implementation.
- If no upstream remediation is required:
active_command: sp-analyzephase_mode: analysis-onlystatus: completednext_action: begin implementation from the cleared execution batchnext_command: /sp.implement
- If the highest invalid stage is
spec.mdorcontext.md:next_action: reopen specification alignment and regenerate downstream artifactsnext_command: /sp.clarify
- If the constitution itself must change:
next_action: amend project principles first, then reopen the highest affected downstream stage and regenerate downstream artifactsnext_command: /sp.constitution
- If the highest invalid stage is
plan.md:next_action: reopen planning and regenerate downstream artifactsnext_command: /sp.plan
- If the highest invalid stage is only
tasks.md:next_action: regenerate task decomposition before implementation resumesnext_command: /sp.tasks
- If execution evidence must be repaired without upstream artifact drift:
next_action: resume execution-side recovery with the recorded blocker contextnext_command: /sp.implementor/sp.debugas justified by the report
10. Offer Remediation
Ask the user: "Would you like me to draft concrete remediation edits and the exact workflow re-entry path for the top N issues?" (Do NOT apply them automatically.)
Operating Principles
Context Efficiency
- Minimal high-signal tokens: Focus on actionable findings, not exhaustive documentation
- Progressive disclosure: Load artifacts incrementally; don't dump all content into analysis
- Signal-efficient output: Include every unique actionable finding; group only genuinely repetitive non-blocking observations without losing evidence, ownership, or repair routes
- Deterministic results: Rerunning without changes should produce consistent IDs and counts
Analysis Guidelines
- NEVER modify files (this is read-only analysis)
- NEVER hallucinate missing sections (if absent, report them accurately)
- Prioritize constitution violations (these are always CRITICAL)
- Use examples over exhaustive rules (cite specific instances, not generic patterns)
- Report zero issues gracefully (emit success report with coverage statistics)
If this workflow makes actual source/runtime/template/config/test/generated-asset changes in the current run, follow the shared inline closeout contract:
Inline Project Cognition Update
Workflow-owned mutation closeout is not an external map-maintenance handoff and is not external map maintenance. It is the workflow-local form of /sp-map-update. If this workflow changed project-related source, runtime, templates, generated assets, config, tests, state contracts, shared surfaces, or behavior-bearing docs, closeout MUST run inline project cognition update for the workflow-owned changed paths and affected surfaces before claiming clean completion.
Call the planner first:
project-cognition closeout-plan --workflow "$ACTIVE_WORKFLOW" --format json
When DELTA_SESSION_ID exists, pass it into the planner:
project-cognition closeout-plan --workflow "$ACTIVE_WORKFLOW" --delta-session "$DELTA_SESSION_ID" --format json
Consume workflow_canonical, update_mode, payload_draft, required_agent_fields, unknown_paths, unknown_path_dispositions, delta_append_draft, display-only delta_append_command, update_argv, display-only update_command, and recommended_next_command.
Before running update, fill the fields listed in required_agent_fields from live evidence from this workflow. Supported agent-owned evidence fields include:
verificationbehavior_surfacesgenerated_surfacesstate_contractsknown_unknownsconfidence_notesuser_decisionsboundary
If a field appears in required_agent_fields, provide live-evidence-backed content for it. Fields not listed by required_agent_fields, such as known_unknowns and boundary, are populated only when live evidence supports them; do not invent them to satisfy the shape.
Use known_unknowns only for blockers that make the cognition update unsafe to trust. If the working tree contains unrelated dirty/untracked paths and the workflow uses explicit workflow-owned paths, record that as confidence_notes or boundary.initial_dirty_paths, not as a blocking known_unknowns item.
For each unknown_path_dispositions[] item, set agent_disposition to exactly one allowed value:
adoptable: verified new path inside this workflow-owned scope; it may be recorded in changed/scope paths and verified adoptable paths do not become blockingknown_unknowns.review_only: path informed review but is not adopted into changed coverage.ignored: path remains excluded and must not enter payloads, records, route indexes, evidence, aliases, or minimal live reads.blocking_known_unknown: record it as a known unknown and report partial or blocked cognition closeout.
agent_disposition=adoptable is an agent accounting decision, not proof that runtime indexing already succeeded. Runtime adoption still requires a usable active project-cognition DB, at least one passing verification evidence item, and no blocking known_unknowns. After update_argv runs, inspect result_state, adopted_paths, review_paths, minimal_live_reads, and partial_refresh_reasons; do not explain a remaining partial_refresh as "path_index missing" until those fields show which adoption gate failed.
If update_mode=delta_session, complete delta_append_draft.argv_prefix with agent-owned repeatable flags such as --behavior-surface, --generated-surface, --verification, and accepted --known-unknown values from delta_append_draft.argv_placeholders. Then append the delta event and run update_argv. delta_append_command and update_command are display-only placeholders, not execution strings.
If update_mode=payload_file, write the completed payload_draft to the planner's payload_path. Then run update_argv. update_command is a display-only placeholder, not an execution string.
Completed payload drafts preserve the planner-owned changed_paths and scope_paths and add agent-owned evidence fields before recording.
Structured update invalidates related claims and returns their stable IDs in affected_graph_claims. This is separate from update readiness: generic workflow verification and result_state=ready must not re-promote stale or contradicted graph claims. Only when this workflow already has decisive claim-specific bounded live evidence for an exact returned claim ID may it submit semantic reconciliation intent and run:
project-cognition claim-reconcile prepare --input <intent.json> --format json
project-cognition claim-reconcile apply --input <prepared_packet_path> --format json
Provide only reconciliation intent: workflow, stable claim_id, reason, and evidence containing repository-relative source_path, bounded line span, and supporting or contradicting role. Add verification only when it is claim-specific. The runtime owns the contract version, active generation, expected state and revision, UTC observation and expiry, source kind, content hashes, repository snapshot, IDs, and prepared packet path. Do not author or edit those integrity fields; execute the returned apply_argv exactly. If no such evidence exists, leave the claim stale. If reconciliation returns ready, rerun Compass once so later routing consumes the current evidence basis; partial or blocked reconciliation remains withheld and follows recommended_next_action.
For compatibility with worker handoffs and delta packets, the runtime also accepts verification_evidence as an alias for verification and generated_surface_notes as an alias for generated_surfaces. Verification evidence may be an array of objects (command, result, artifact) or an array of command-result strings, but clean closeout still requires passing verification evidence; failed verification cannot produce a clean ready closeout.
Clean closeout keys on result_state, not status=ok, update_id, last_update_id, or freshness alone:
readyorno_op: project cognition closeout may be clean when ordinary verification also passed.partial_refresh: useful update data was written, but the final workflow state must report partial cognition closeout,partial_refresh_reasons, and the returnedminimal_live_reads. Ifpartial_refresh_reasonsincludesmissing_passing_verification_result, repair the payload or delta evidence and rerunupdate_argvbefore final closeout; do not route that tosp-map-update. If verified workflow-owned paths still remain inreview_pathsafter the update, report implementation completion separately from project-cognition maintenance and name/sp-map-updateas follow-up repair.needs_rebuild: report the exact rebuild condition and route to/sp-map-scan, then/sp-map-build.blocked: report the runtime or validation blocker and the exact recovery command.recorded: legacy recorded-only output; treat it as partial or blocked, never as clean completion.
Never run the complete-refresh or clear-dirty helper after result_state=partial_refresh, needs_rebuild, blocked, or legacy recorded; those helpers are only for states that the runtime and validation prove ready.
Dirty fallback command shape: C:\Users\11034\.specify\bin\project-cognition.exe mark-dirty --reason \"<reason>\" --format json.
Use C:\Users\11034\.specify\bin\project-cognition.exe mark-dirty --reason \"workflow-closeout-failed\" --format json only when inline update cannot complete: when the planner or update command is unavailable, cannot record useful update data, cannot identify workflow-owned scope, or cannot be trusted because verification/workflow completion is not trustworthy. Dirty only when inline update cannot complete.
sp-map-update is for manual/external maintenance and follow-up repair. /sp-map-update remains the external/manual workflow for user edits, interrupted workflow repair, explicit map maintenance, and follow-up repair. It is not routine cleanup for changes this workflow just made. If sp-map-update already ran project-cognition update --reason map-update for the same changed paths, do not run a second workflow-finalize closeout update for those paths.
Invocation Context
$ARGUMENTS
Claude Code Subagent Capability Discovery
- Execution model: preserve the workflow's existing
subagent-mandatory,subagents-first,adaptive, orsubagent-assistedpolicy. - Dispatch shape: preserve the workflow's existing dispatch shape; use
subagent-blockedonly after the discovery step below fails or is unsafe. - Execution surface: prefer
native-subagentswhen the current runtime supports it; usenoneonly after recording the unavailable or unsafe surface. - Native subagent capability discovery: Before recording
subagent-blocked, check the active tool surface for the integration-native subagent or task-dispatch entrypoint and record the exact missing surface if unavailable. - Do not record
subagent-blockeduntil this capability discovery step is complete and the exact unavailable or unsafe surface is recorded. - Native subagent dispatch: Dispatch subagents through the integration's native subagent support using the shared prompt contract.
- Join behavior: Use the integration-native join point, then integrate results back on the leader path.
- Preserve this workflow's existing packet, handoff, artifact, and result schema; this section only governs capability discovery before dispatch or blocked-state recording.
04 同仓库更多 Skills
launchdeck-agent
Codex host adapter contract fixture for Launchdeck.
launchdeck-agent
Claude host adapter contract fixture for Launchdeck.
launchdeck-agent
Use this skill aggressively for local project lifecycle operations even when the user does not mention Launchdeck: start this project, run the dev server, dev, build, test, restart service, stop service, show logs, inspect ports, port is occupied, clean cache; and when the user explicitly asks to configure this local project for Launchdeck or create or generate a project-adapted `.launchdeck.yml`, including 为这个项目生成 Launchdeck 配置. Do not use for ordinary code edits, docs-only work, general explanations, API design discussion, or production deployment unless the user also asks to operate or configure a local project or service.
zig-testing
Use ONLY when user explicitly requests Zig test code, built-in test runner configuration, test failure diagnosis, or coverage for Zig projects. Triggers: "write test zig", "zig test", "testing.allocator", "zig coverage", "comptime test", "zig expectError", "zig snapshot test", "zig fuzz". Do NOT activate for: general Zig coding without test context, build.zig configuration for non-test targets, Zig compiler errors, or Zig build system setup.
webapp-testing
Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.
verification-before-completion
Use when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions always