diff --git a/templates/commands/analyze.md b/templates/commands/analyze.md index 7de2d28f0d..5a70ce093b 100644 --- a/templates/commands/analyze.md +++ b/templates/commands/analyze.md @@ -51,7 +51,7 @@ You **MUST** consider the user input before proceeding (if not empty). ## Goal -Identify inconsistencies, duplications, ambiguities, and underspecified items across the three core artifacts (`spec.md`, `plan.md`, `tasks.md`) before implementation. This command MUST run only after `__SPECKIT_COMMAND_TASKS__` has successfully produced a complete `tasks.md`. +Identify inconsistencies, duplications, ambiguities, and underspecified items across the three core artifacts (`spec.md`, `plan.md`, `tasks.md`) before implementation. When `data-model.md` exists, also check constrained-field task citations and constraint consistency against it. This command MUST run only after `__SPECKIT_COMMAND_TASKS__` has successfully produced a complete `tasks.md`. ## Operating Constraints @@ -68,6 +68,7 @@ Run `{SCRIPT}` once from repo root and parse JSON for FEATURE_DIR and AVAILABLE_ - SPEC = FEATURE_DIR/spec.md - PLAN = FEATURE_DIR/plan.md - TASKS = FEATURE_DIR/tasks.md +- DATA_MODEL = FEATURE_DIR/data-model.md (optional) 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"). @@ -99,6 +100,11 @@ Load only the minimal necessary context from each artifact: - Parallel markers [P] - Referenced file paths +**From data-model.md (if present):** + +- Entity and exact field names, canonical source locations, and explicit constraints (max/min length, nullable/required, enum values, validation rules), including constraints encoded in field types +- If absent or no constrained fields exist, constrained-field checks are not applicable; do not invent fields or constraints or fail analysis for the missing optional document + **From constitution:** - Load `/memory/constitution.md` for principle validation @@ -110,6 +116,8 @@ 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%"). - **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) +- **Constrained-field inventory** (when applicable): Record each canonical `Entity.field`, its constraints, and its location in data-model.md; keep identically named fields on different entities distinct +- **Field citation mapping** (when applicable): Map explicit data-model.md references with exact `Entity.field` identities to implementing task IDs and task locations; retain unresolved references and task-stated constraints for the detection passes - **Constitution rule set**: Extract principle names and MUST/SHOULD normative statements ### 4. Detection Passes (Token-Efficient Analysis) @@ -142,6 +150,9 @@ Focus on high-signal findings. Limit to 50 findings total; aggregate remainder i - Requirements with zero associated tasks - Tasks with no mapped requirement/story - Success Criteria requiring buildable work (performance, security, availability) not reflected in tasks +- Each constrained field without an explicit `data-model.md` + `Entity.field` citation in at least one implementing task. Generic document/entity references, bare field names, and test-only references do not count; a shared implementing task may cite multiple fields, including fields implemented before later stories +- Require an explicit association between each cited field and its canonical definition. Mere co-occurrence of a document reference and a field mention is not a citation; for example, task prose setting `Request.SuspendReason` to 500 is not a citation just because the task cites data-model.md for `Request.Remark` +- Report unresolved field citations with their task IDs and locations; they must not be guessed as aliases or counted as coverage for another field. Also report any canonical field left uncovered #### F. Inconsistency @@ -149,13 +160,15 @@ Focus on high-signal findings. Limit to 50 findings total; aggregate remainder i - 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) +- Task-stated field constraints that contradict data-model.md, even when a valid citation is present. Compare any clearly identified field's task prose even when its citation is missing; check length, nullable/required status, enum values, and validation rules +- For each field mismatch, identify the exact `Entity.field`, task ID, canonical and task-stated restrictions, and both source locations. Do not flag citation-only tasks or semantically matching paraphrases for omitting/rewording constraint values. Do not invent canonical values when the source restriction is unclear; use the existing ambiguity/underspecification passes for unclear definitions ### 5. 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 +- **HIGH**: Duplicate or conflicting requirement, ambiguous security/performance attribute, untestable acceptance criterion, missing/unresolved constrained-field citations (Coverage), or contradictory task constraints (Inconsistency); retain CRITICAL escalation above - **MEDIUM**: Terminology drift, missing non-functional task coverage, underspecified edge case - **LOW**: Style/wording improvements, minor redundancy not affecting execution order @@ -176,6 +189,13 @@ Output a Markdown report (no file writes) with the following structure: | Requirement Key | Has Task? | Task IDs | Notes | |-----------------|-----------|----------|-------| +**Constrained-Field Coverage (when applicable):** + +| Field (`Entity.field`) | Canonical Location | Implementing Task IDs | Coverage / Consistency Notes | +|------------------------|--------------------|-----------------------|------------------------------| + +Use the existing finding table for field findings, including source locations and actionable recommendations. Field findings share the 50-finding limit and overflow summary; do not change the existing requirement coverage denominator or FR/SC coverage table semantics. + **Constitution Alignment Issues:** (if any) **Unmapped Tasks:** (if any) diff --git a/templates/commands/tasks.md b/templates/commands/tasks.md index 1b9c4255fe..d2dca80933 100644 --- a/templates/commands/tasks.md +++ b/templates/commands/tasks.md @@ -71,13 +71,14 @@ You **MUST** consider the user input before proceeding (if not empty). 3. **Execute task generation workflow**: - Load plan.md and extract tech stack, libraries, project structure - Load spec.md and extract user stories with their priorities (P1, P2, P3, etc.) - - If data-model.md exists: Extract entities and map to user stories + - If data-model.md exists: Extract entities and constrained fields, including constraints encoded in field types, and map to user stories - If contracts/ exists: Map interface contracts to user stories - If research.md exists: Extract decisions for setup tasks - Generate tasks organized by user story (see Task Generation Rules below) - Generate dependency graph showing user story completion order - Create parallel execution examples per user story - Validate task completeness (each user story has all needed tasks, independently testable) + - If data-model.md has constrained fields: Verify every constrained field has an explicit, resolving citation to `data-model.md` and its `Entity.field` in at least one implementing task; correct missing or unresolved citations before returning tasks.md 4. **Generate tasks.md**: Use TASKS_TEMPLATE_CONTENT (from the JSON output above) as the structure. For compatibility with older setup scripts that omit TASKS_TEMPLATE_CONTENT, read TASKS_TEMPLATE instead. Fill with: - Correct feature name from plan.md @@ -138,7 +139,7 @@ Output path to generated tasks.md and summary: Context for task generation: {ARGS} -The tasks.md should be immediately executable - each task must be specific enough that an LLM can complete it without additional context. +The tasks.md should be immediately executable - each task must be specific enough that an LLM can complete it without context beyond the feature's design documents. This does not require copying those documents into task descriptions. ## Task Generation Rules @@ -197,7 +198,10 @@ Every task MUST strictly follow this format: - Map each entity to the user story(ies) that need it - If entity serves multiple stories: Put in earliest story or Setup phase - Relationships → service layer tasks in appropriate story phase - - For each field with constraints in data-model.md (max length, nullable/required, enum values, validation rules), quote the constraint verbatim in the task description so it is not left to implementation-time discretion + - data-model.md is the canonical source for field constraints (max/min length, nullable/required, enum values, validation rules), including constraints encoded in field types + - Cite each constrained field explicitly using `data-model.md` and its exact `Entity.field` in the implementing task description; plain text or links are acceptable when both are unambiguous. A shared implementing task may cite multiple fields + - Associate each cited field explicitly with its canonical definition. A field mention elsewhere in the task is not a citation merely because other fields in that task cite data-model.md + - Use citations instead of duplicated constraint prose. Do not require verbatim copies of constraints in tasks.md. Do not restate unchanged constraints; state a constraint only when the task adds to or narrows the canonical rule, and identify that task-specific addition or narrowing. Task-specific constraints MUST NOT contradict the canonical field definition 4. **From Setup/Infrastructure**: - Shared infrastructure → Setup phase (Phase 1) diff --git a/tests/fixtures/constrained-fields.md b/tests/fixtures/constrained-fields.md new file mode 100644 index 0000000000..64fa18b8cd --- /dev/null +++ b/tests/fixtures/constrained-fields.md @@ -0,0 +1,308 @@ +# Constrained-field command regression scenarios + +These are agent-executed fixtures for `templates/commands/tasks.md` and +`templates/commands/analyze.md`, not inputs to a test-only analyzer. Scaffold +tests protect the instructions; an agent must check the outcomes below. + +## Common feature artifacts + +Use the following `spec.md`, `plan.md`, and `data-model.md` with each task variant. +Only the absent-model and unconstrained-model cases replace the data model. + +### spec.md + +```markdown +# Feature Specification: Request validation + +## User Scenarios & Testing + +### User Story 1 - Validate requests (Priority: P1) + +A contributor can submit a request that follows its canonical field rules. + +Acceptance: Valid requests succeed; invalid field values are rejected. + +## Requirements + +- **FR-001**: Validate request and audit fields using the canonical data model. + +## Success Criteria + +- **SC-001**: All accepted requests satisfy the canonical field constraints. +``` + +### plan.md + +```markdown +# Implementation Plan: Request validation + +## Summary + +Implement request validation and audit recording in src/request.py and +src/audit.py using data-model.md. Test valid and invalid inputs. + +## Technical Context + +Python library; existing validation helpers and pytest; no new dependencies. + +## Constitution Check + +Use the project's existing principles; no exceptions are needed. +``` + +### data-model.md + +```markdown +# Data Model + +## Request + +| Field | Type | Constraints | +|-------|------|-------------| +| SuspendReason | nvarchar(200) | Nullable; trim whitespace; if supplied, must not be empty after trimming. | +| Remark | nvarchar(200) | Required. | +| Status | enum | Required; allowed values: open, suspended. | +| RetryCount | integer | Nullable; inclusive range 0 through 3. | +| Code | string | Required; minimum length 3, maximum length 8; uppercase letters only. | + +## Audit + +| Field | Type | Constraints | +|-------|------|-------------| +| Remark | string | Required; maximum length 40. | +``` + +There are six constrained fields. `Request.SuspendReason` and `Request.Remark` +are the two 200-character lineage fields; `Audit.Remark` deliberately repeats a +field name with a different restriction. + +## Task-generation scenario + +Generate tasks from the common artifacts using the actual tasks command. +Expect every field to have an explicit `data-model.md` `Entity.field` reference +in at least one implementing task. Preserve checklist IDs, paths, and story +grouping. A shared implementation task may cover several fields. Constraint +values must not be restated when unchanged; cite their canonical definitions. + +As a second generation case, add an operation-specific rule requiring a +SuspendReason when suspending a request, while the general model permits null. +Expect the relevant task to retain its `data-model.md` `Request.SuspendReason` +citation and state only the operation-specific narrowing. It must not repeat +the unchanged length/trim rules or contradict the canonical definition. + +## Analysis baseline + +Start with these complete, citation-only tasks. Each variant below changes only +the specified lines; keep the other baseline lines unchanged. + +```markdown +# Tasks: Request validation + +## User Story 1 + +- [ ] T001 [US1] Implement request validation in src/request.py using data-model.md `Request.SuspendReason`, `Request.Remark`, `Request.Status`, `Request.RetryCount`, and `Request.Code`. +- [ ] T002 [US1] Implement audit validation in src/audit.py using data-model.md `Audit.Remark`. +- [ ] T003 [US1] Test valid and invalid requests and audit entries in tests/test_request.py. +``` + +Run each case independently. Count only constrained-field findings; ordinary +analysis may separately report shortcomings of this deliberately small feature. +Every missing citation is HIGH Coverage; every contradiction is HIGH +Inconsistency unless an existing CRITICAL escalation applies. Findings identify +the exact field, task IDs and source locations when available; contradictions +include both canonical and task-stated restrictions. Analysis must not edit files. + +### A01 - Citation-only, shared implementing task + +Use the analysis baseline unchanged. + +**Expected**: Six covered fields, zero constrained-field findings. No demand to +repeat values. Multiple fields in T001 are independently covered. + +### A02 - Omitted lineage field + +Remove only `` `Request.SuspendReason`, `` from T001. Leave the field defined in +the data model. + +**Expected**: One Coverage finding for `Request.SuspendReason`; five of six +fields covered. Mentioning `Request.Remark` does not cover the other 200-character +field. + +### A03 - Generic document/entity reference + +Replace T001: + +```markdown +- [ ] T001 [US1] Implement Request validation from data-model.md in src/request.py. +``` + +**Expected**: Five missing-field Coverage findings for Request fields; one of six +fields covered. The document name and entity name alone do not count. + +### A04 - Unresolved field reference + +Replace `Request.SuspendReason` with `Request.SuspensionReason` in T001. + +**Expected**: A Coverage finding for the unresolved `Request.SuspensionReason` +citation and a Coverage finding for the uncovered `Request.SuspendReason`. +Five of six fields covered; no guessed alias resolution. + +### A05 - Cited but conflicting length + +Append to T001: `Set Request.SuspendReason maximum length to 500.` + +**Expected**: Six covered fields and one Inconsistency finding naming +`Request.SuspendReason`, canonical 200, task-stated 500, and T001. A valid +citation does not neutralize contradictory prose. + +### A06 - Uncited and conflicting length + +Apply A02, then append to T001: +`Set Request.SuspendReason maximum length to 500.` + +**Expected**: Five of six fields covered, one missing-citation finding and one +200-versus-500 Inconsistency finding for `Request.SuspendReason`. Uncited prose +is still compared when its field identity is clear. + +### A07 - Matching paraphrase + +Append to T001: +`Request.SuspendReason may be omitted; when supplied, strip surrounding whitespace and reject an empty result; allow at most 200 characters.` + +**Expected**: Six covered fields, zero constrained-field findings. Equivalent +wording is not a mismatch and need not repeat every other field's constraints. + +### A08 - Conflicting required status + +Append to T001: `Request.SuspendReason is mandatory and cannot be null.` + +**Expected**: One Inconsistency finding for canonical nullable versus task +required/non-null. All six fields remain covered. + +### A09 - Conflicting allowed values + +Append to T001: `Request.Status also accepts archived.` + +**Expected**: One Inconsistency finding for canonical allowed values +`open, suspended` versus the additional `archived` value. + +### A10 - Conflicting validation + +Append to T001: `Accept Request.RetryCount values through 9.` + +**Expected**: One Inconsistency finding for canonical inclusive maximum 3 +versus task maximum 9. + +### A11 - Same field name on another entity + +Remove `Request.Remark` from T001 but keep T002's `Audit.Remark`. + +**Expected**: One Coverage finding for `Request.Remark`; five of six fields +covered. `Audit.Remark` must not cover `Request.Remark`. + +### A12 - Test-only reference + +Apply A02 and append to T003: `Check data-model.md Request.SuspendReason.` + +**Expected**: One missing implementation-citation finding for +`Request.SuspendReason`; a test-only reference does not satisfy coverage. + +### A13 - Missing optional data model + +Omit `data-model.md`. Keep the baseline tasks. + +**Expected**: Constrained-field checks are not applicable; no invented canonical +fields, missing-model error, or constrained-field findings. Ordinary analysis +still runs. + +### A14 - No constrained fields + +Replace `data-model.md` with: + +```markdown +# Data Model + +Request and Audit have no defined fields or restrictions yet. +``` + +Replace T001 and T002 with one entity-level implementation task. + +**Expected**: Constrained-field checks are not applicable; zero constrained-field +findings. Ordinary underspecification findings may still be appropriate. + +### A15 - Bare field names with matching copied values + +Replace T001: + +```markdown +- [ ] T001 [US1] Implement SuspendReason (nullable, trimmed, 200 characters), Remark (required, 200 characters), Status (open or suspended), RetryCount (0 through 3), and Code (3 through 8 uppercase letters) in src/request.py. +``` + +**Expected**: Five missing-field Coverage findings; copied values and bare field +names do not replace explicit document/qualified-field citations. No supported +contradiction is present. + +### A16 - Conflicting minimum length + +Append to T001: `Accept Request.Code values containing one uppercase letter.` + +**Expected**: One Inconsistency finding for canonical minimum length 3 versus +task minimum 1. + +### A17 - Links instead of plain document references + +Replace T002: + +```markdown +- [ ] T002 [US1] Implement [Audit.Remark](data-model.md#audit) validation in src/audit.py. +``` + +**Expected**: Six covered fields, zero constrained-field findings. A link is +valid when the document and exact field identity are explicit. + +### A18 - Ambiguous canonical restriction + +Change only the canonical RetryCount restriction to +`Nullable; range still to be decided.` Append to T001: +`Use Request.RetryCount maximum 9.` + +**Expected**: Do not invent a canonical numeric range or report a supported +numeric mismatch for RetryCount. The ordinary ambiguity/underspecification +pass may flag the undecided range. + +### A19 - Document-only reference + +Replace T001: + +```markdown +- [ ] T001 [US1] Implement field validation from data-model.md in src/request.py. +``` + +**Expected**: Five missing-field Coverage findings for Request fields; one of six +fields covered by the unchanged audit task. Naming the document without field +identities provides no Request field coverage. + +### A20 - Entity-only reference + +Replace T001: + +```markdown +- [ ] T001 [US1] Implement Request validation in src/request.py. +``` + +**Expected**: Five missing-field Coverage findings for Request fields; one of six +fields covered by the unchanged audit task. Naming the entity without document +and field references provides no Request field coverage. + +In A06, the separate sentence stating a 500-character limit is a field mention, +not an instruction to follow that field's canonical definition. Its qualified +name must not become a citation merely because other fields in the same task +are explicitly cited from data-model.md. The task has both a missing citation +and a contradiction. + +## Reproducible review record + +For each agent run, record the command/template revision, actual generated +tasks or field findings, comparison with these expectations, and whether any +input changed. Keep limitations explicit: pytest scaffold checks do not execute +these agent scenarios or guarantee model behavior. diff --git a/tests/test_tasks_template_constraints.py b/tests/test_tasks_template_constraints.py index a76cfb050b..f852ea14fe 100644 --- a/tests/test_tasks_template_constraints.py +++ b/tests/test_tasks_template_constraints.py @@ -1,29 +1,123 @@ -"""Regression test for #4383: tasks.md loses data-model field constraints. - -The /speckit.tasks command template maps data-model.md entities to task -descriptions but did not require that field-level constraints (max length, -nullable/required, enum values, validation rules) be carried into the -generated task text verbatim. Without an explicit instruction, the -implementing agent falls back to its own defaults instead of the value -recorded in data-model.md. +"""Scaffold regressions for citation-first constrained-field guidance. + +These checks inspect the shipped prompts, not LLM behavior. Exercise the +positive and negative artifact scenarios in fixtures/constrained-fields.md +through a coding agent for generation and analysis outcome evidence. """ +from __future__ import annotations + from pathlib import Path REPO_ROOT = Path(__file__).parent.parent TASKS_TEMPLATE = REPO_ROOT / "templates" / "commands" / "tasks.md" +ANALYZE_TEMPLATE = REPO_ROOT / "templates" / "commands" / "analyze.md" + + +def _section(path: Path, start: str, end: str) -> str: + text = path.read_text(encoding="utf-8") + return " ".join(text.split(start, 1)[1].split(end, 1)[0].split()) + + +def test_task_generation_requires_canonical_field_citations_not_verbatim_copies(): + section = _section( + TASKS_TEMPLATE, "**From Data Model**", "**From Setup/Infrastructure**" + ) + for clause in ( + "data-model.md is the canonical source", + "each constrained field", + "`Entity.field`", + "implementing task", + "Do not require verbatim copies", + "Do not restate unchanged constraints", + "only when the task adds to or narrows the canonical rule", + "Task-specific constraints MUST NOT contradict", + "A field mention elsewhere in the task is not a citation", + "constraints encoded in field types", + "max/min length, nullable/required, enum values, validation rules", + ): + assert clause in section, f"Missing task-generation guidance: {clause}" + assert "quote the constraint verbatim in the task description" not in section + + +def test_task_generation_checks_field_citation_completeness(): + section = _section( + TASKS_TEMPLATE, "3. **Execute task generation workflow**", "4. **Generate tasks.md**" + ) + assert "every constrained field has an explicit, resolving citation" in section + assert "at least one implementing task" in section -def test_data_model_section_requires_verbatim_field_constraints(): - content = TASKS_TEMPLATE.read_text(encoding="utf-8") +def test_task_generation_context_includes_the_feature_design_documents(): + section = _section( + TASKS_TEMPLATE, "Context for task generation:", "## Task Generation Rules" + ) + assert "without context beyond the feature's design documents" in section + assert "does not require copying those documents into task descriptions" in section + + +def test_analysis_loads_optional_model_and_builds_field_inventory(): + loading = _section( + ANALYZE_TEMPLATE, "### 2. Load Artifacts", "### 4. Detection Passes" + ) + for clause in ( + "**From data-model.md (if present):**", + "constraints encoded in field types", + "If absent or no constrained fields exist", + "do not invent fields or constraints", + "**Constrained-field inventory**", + "**Field citation mapping**", + "implementing task IDs", + "exact `Entity.field`", + ): + assert clause in loading, f"Missing analysis inventory guidance: {clause}" + + +def test_analysis_distinguishes_implementation_citations_from_mentions(): + coverage = _section( + ANALYZE_TEMPLATE, "#### E. Coverage Gaps", "#### F. Inconsistency" + ) + for clause in ( + "explicit `data-model.md` + `Entity.field` citation", + "Generic document/entity references, bare field names, and test-only references do not count", + "unresolved field citations", + "must not be guessed as aliases", + "shared implementing task may cite multiple fields", + "Mere co-occurrence of a document reference and a field mention is not a citation", + ): + assert clause in coverage, f"Missing citation coverage guidance: {clause}" + + +def test_analysis_compares_stated_constraints_without_requiring_copies(): + inconsistency = _section( + ANALYZE_TEMPLATE, "#### F. Inconsistency", "### 5. Severity Assignment" + ) + for clause in ( + "even when a valid citation is present", + "even when its citation is missing", + "length, nullable/required status, enum values, and validation rules", + "canonical and task-stated restrictions", + "Do not flag citation-only tasks or semantically matching paraphrases", + "Do not invent canonical values", + ): + assert clause in inconsistency, f"Missing constraint comparison guidance: {clause}" - from_data_model_start = content.index("**From Data Model**") - next_section_start = content.index("**From Setup/Infrastructure**") - section = content[from_data_model_start:next_section_start] - assert "quote the constraint verbatim in the task description" in section.lower(), ( - "The 'From Data Model' task-organization rules must instruct the " - "agent to quote field constraints (max length, nullable, enum, " - "validation rules) from data-model.md verbatim in task descriptions, " - "not merely mention that constraints exist." +def test_analysis_preserves_existing_report_and_read_only_guards(): + text = " ".join(ANALYZE_TEMPLATE.read_text(encoding="utf-8").split()) + report = _section( + ANALYZE_TEMPLATE, "### 5. Severity Assignment", "### 7. Provide Next Actions" ) + assert "**STRICTLY READ-ONLY**" in text + assert "Limit to 50 findings total" in text + for clause in ( + "missing/unresolved constrained-field citations", + "contradictory task constraints", + "**Constrained-Field Coverage (when applicable):**", + "Field (`Entity.field`)", + "Canonical Location", + "Implementing Task IDs", + "do not change the existing requirement coverage denominator", + "source locations", + ): + assert clause in report, f"Missing field reporting guidance: {clause}"