Compare commits

..
Author SHA1 Message Date
Hermes Agent 6045ed638c fix(ci): integrate automated release retention cleanup in stage and prod cache scripts 2026-11-04 14:39:31 +00:00
Canina Hermes 7a103303b0 fix(security): completely remove Swagger UI endpoint mounting from runtime
Deploy Canina / deploy (push) Failing after 11s
2026-11-02 05:42:55 +00:00
Canina Hermes 5a483e0cce fix(security): enforce secure-by-default Swagger UI disabling
Deploy Canina / deploy (push) Failing after 12s
2026-11-02 05:39:17 +00:00
Canina Hermes 6935ac9134 refactor(market-intelligence): dynamic API-driven opportunity tabs with no hardcoded data
Deploy Canina / deploy (push) Successful in 1m3s
2026-11-01 10:41:58 +00:00
Canina Hermes f2239be43c feat(market-intelligence): add major pet shops and real Canina sellers to ecosystem atlas
Deploy Canina / deploy (push) Successful in 1m2s
2026-11-01 10:20:19 +00:00
Canina Hermes b14b26a2e4 feat(market-intelligence): 33-seller ecosystem atlas, brand matrix, and executive importer proposal
Deploy Canina / deploy (push) Successful in 1m3s
2026-11-01 09:34:06 +00:00
Canina Hermes a6d0269427 fix(hermes-tasks): department counts stability and mobile responsive cards
Deploy Canina / deploy (push) Successful in 2m33s
2026-10-31 19:48:42 +00:00
Canina Hermes 8c4faf8820 feat(corporate): exact task claim and manual plan inventory execution slice
Deploy Canina / deploy (push) Successful in 2m31s
2026-10-31 18:45:30 +00:00
Canina Hermes 216e05ba25 feat(corporate): persist dated monthly plans and repair verified release gates
Deploy Canina / deploy (push) Successful in 4m38s
2026-10-30 12:28:51 +00:00
Canina Automation 18094f91a6 fix(blog): represent absent article imagery honestly
Deploy Canina / deploy (push) Successful in 3m12s
2026-10-29 08:10:03 +00:00
Canina Automation 5642c1609c feat(corporate): expose persisted execution evidence and QA dossier
Deploy Canina / deploy (push) Successful in 3m56s
2026-10-28 21:56:55 +00:00
93 changed files with 7488 additions and 223 deletions

No files matched your search

+14
View File
@@ -0,0 +1,14 @@
# Machine-local Spec Kit state — not meant to be shared.
# Managed by the Specify CLI; safe to edit (your changes are preserved on refresh).
# Local pointer to the current feature directory. Rewritten every time you
# switch features, so it is per-checkout state rather than something to share.
feature.json
# Per-machine extension config overrides.
extensions/*/local-config.yml
# Executable adapter packages and their per-checkout provenance registry.
# Execution consent is stored separately in the user's local trust registry.
integrations/packages/
integrations/packages.json
+251
View File
@@ -0,0 +1,251 @@
---
description: Perform a non-destructive cross-artifact consistency and quality analysis across spec.md, plan.md, and tasks.md after task generation.
---
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Pre-Execution Checks
**Check for extension hooks (before analysis)**:
- Check if `.specify/extensions.yml` exists in the project root.
- If it exists, read it and look for entries under the `hooks.before_analyze` key
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- For each executable hook, output the following based on its `optional` flag:
- **Optional hook** (`optional: true`):
```
## Extension Hooks
**Optional Pre-Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
- **Mandatory hook** (`optional: false`):
```
## Extension Hooks
**Automatic Pre-Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
Wait for the result of the hook command before proceeding to the Goal.
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently
## 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.tasks` has successfully produced a complete `tasks.md`.
## Operating Constraints
**STRICTLY READ-ONLY**: Do **not** modify any files. Output a structured analysis report. Offer an optional remediation plan (user must explicitly approve before any follow-up editing commands would be invoked manually).
**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 `/speckit.analyze`.
## Execution Steps
### 1. Initialize Analysis Context
Run `.specify/scripts/bash/check-prerequisites.sh --json --require-spec --require-tasks --include-tasks` once from repo root and parse JSON for FEATURE_DIR and AVAILABLE_DOCS. Derive absolute paths:
- SPEC = FEATURE_DIR/spec.md
- PLAN = FEATURE_DIR/plan.md
- TASKS = FEATURE_DIR/tasks.md
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").
### 2. Load Artifacts (Progressive Disclosure)
Load only the minimal necessary context from each artifact:
**From spec.md:**
- Overview/Context
- Functional Requirements
- Success Criteria (measurable outcomes — e.g., performance, security, availability, user success, business impact)
- User Stories
- Edge Cases (if present)
**From plan.md:**
- Architecture/stack choices
- Data Model references
- Phases
- Technical constraints
**From tasks.md:**
- Task IDs
- Descriptions
- Phase grouping
- Parallel markers [P]
- Referenced file paths
**From constitution:**
- Load `.specify/memory/constitution.md` for principle validation
### 3. 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%").
- **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
### 4. Detection Passes (Token-Efficient Analysis)
Focus on high-signal findings. Limit to 50 findings total; aggregate remainder in overflow summary.
#### 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
#### F. 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)
### 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
- **MEDIUM**: Terminology drift, missing non-functional task coverage, underspecified edge case
- **LOW**: Style/wording improvements, minor redundancy not affecting execution order
### 6. Produce Compact Analysis Report
Output a Markdown report (no file writes) with the following structure:
## Specification Analysis Report
| ID | Category | Severity | Location(s) | Summary | Recommendation |
|----|----------|----------|-------------|---------|----------------|
| A1 | Duplication | HIGH | spec.md:L120-134 | Two similar requirements ... | Merge phrasing; keep clearer version |
(Add one row per finding; generate stable IDs prefixed by category initial.)
**Coverage Summary Table:**
| Requirement Key | Has Task? | Task IDs | 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
### 7. Provide Next Actions
At end of report, output a concise Next Actions block:
- If CRITICAL issues exist: Recommend resolving before `/speckit.implement`
- If only LOW/MEDIUM: User may proceed, but provide improvement suggestions
- Provide explicit command suggestions: e.g., "Run /speckit.specify with refinement", "Run /speckit.plan to adjust architecture", "Manually edit tasks.md to add coverage for 'performance-metrics'"
### 8. Offer Remediation
Ask the user: "Would you like me to suggest concrete remediation edits for the top N issues?" (Do NOT apply them automatically.)
### 9. Check for extension hooks
After reporting, check if `.specify/extensions.yml` exists in the project root.
- If it exists, read it and look for entries under the `hooks.after_analyze` key
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- For each executable hook, output the following based on its `optional` flag:
- **Optional hook** (`optional: true`):
```
## Extension Hooks
**Optional Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
- **Mandatory hook** (`optional: false`):
```
## Extension Hooks
**Automatic Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently
## 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
- **Token-efficient output**: Limit findings table to 50 rows; summarize overflow
- **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)
## Context
$ARGUMENTS
+375
View File
@@ -0,0 +1,375 @@
---
description: Generate a custom checklist for the current feature based on user requirements.
---
## Checklist Purpose: "Unit Tests for English"
**CRITICAL CONCEPT**: Checklists are **UNIT TESTS FOR REQUIREMENTS WRITING** - they validate the quality, clarity, and completeness of requirements in a given domain.
**NOT for verification/testing**:
- ❌ NOT "Verify the button clicks correctly"
- ❌ NOT "Test error handling works"
- ❌ NOT "Confirm the API returns 200"
- ❌ NOT checking if code/implementation matches the spec
**FOR requirements quality validation**:
- ✅ "Are visual hierarchy requirements defined for all card types?" (completeness)
- ✅ "Is 'prominent display' quantified with specific sizing/positioning?" (clarity)
- ✅ "Are hover state requirements consistent across all interactive elements?" (consistency)
- ✅ "Are accessibility requirements defined for keyboard navigation?" (coverage)
- ✅ "Does the spec define what happens when logo image fails to load?" (edge cases)
**Metaphor**: If your spec is code written in English, the checklist is its unit test suite. You're testing whether the requirements are well-written, complete, unambiguous, and ready for implementation - NOT whether the implementation works.
**Ownership and checkbox lifecycle**:
- Custom checklists generated by this command are reviewer-owned requirements-quality review artifacts.
- `[x]` means the reviewer determined the requirements-quality criterion is satisfied.
- `[x]` does NOT mean implementation work is complete.
- This command generates or appends checklist items; it MUST NOT mark generated items `[x]`.
- An agent may assist with evaluating items only when explicitly asked by the reviewer.
- `checklists/requirements.md` is a separate built-in spec-quality checklist maintained by `/speckit.specify` and `/speckit.clarify`; do not treat that exception as applying to custom checklists generated here.
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Pre-Execution Checks
**Check for extension hooks (before checklist generation)**:
- Check if `.specify/extensions.yml` exists in the project root.
- If it exists, read it and look for entries under the `hooks.before_checklist` key
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- For each executable hook, output the following based on its `optional` flag:
- **Optional hook** (`optional: true`):
```
## Extension Hooks
**Optional Pre-Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
- **Mandatory hook** (`optional: false`):
```
## Extension Hooks
**Automatic Pre-Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
Wait for the result of the hook command before proceeding to the Execution Steps.
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently
## Execution Steps
1. **Setup**: Run `.specify/scripts/bash/check-prerequisites.sh --json --template checklist-template` from repo root and parse JSON for FEATURE_DIR, AVAILABLE_DOCS list, and TEMPLATE_CONTENT.
- All file paths must be absolute.
- 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").
2. **IF EXISTS**: Load `.specify/memory/constitution.md` for project principles and governance constraints.
3. **Clarify intent (dynamic)**: Derive up to THREE initial contextual clarifying questions (no pre-baked catalog). They MUST:
- Be generated from the user's phrasing + extracted signals from spec/plan/tasks
- Only ask about information that materially changes checklist content
- Be skipped individually if already unambiguous in `$ARGUMENTS`
- Prefer precision over breadth
Generation algorithm:
1. Extract signals: feature domain keywords (e.g., auth, latency, UX, API), risk indicators ("critical", "must", "compliance"), stakeholder hints ("QA", "review", "security team"), and explicit deliverables ("a11y", "rollback", "contracts").
2. Cluster signals into candidate focus areas (max 4) ranked by relevance.
3. Identify probable audience & timing (author, reviewer, QA, release) if not explicit.
4. Detect missing dimensions: scope breadth, depth/rigor, risk emphasis, exclusion boundaries, measurable acceptance criteria.
5. Formulate questions chosen from these archetypes:
- Scope refinement (e.g., "Should this include integration touchpoints with X and Y or stay limited to local module correctness?")
- Risk prioritization (e.g., "Which of these potential risk areas should receive mandatory gating checks?")
- Depth calibration (e.g., "Is this a lightweight pre-commit sanity list or a formal release gate?")
- Audience framing (e.g., "Will this be used by the author only or peers during PR review?")
- Boundary exclusion (e.g., "Should we explicitly exclude performance tuning items this round?")
- Scenario class gap (e.g., "No recovery flows detected—are rollback / partial failure paths in scope?")
Question formatting rules:
- If presenting options, generate a compact table with columns: Option | Candidate | Why It Matters
- Limit to A–E options maximum; omit table if a free-form answer is clearer
- Never ask the user to restate what they already said
- Avoid speculative categories (no hallucination). If uncertain, ask explicitly: "Confirm whether X belongs in scope."
Defaults when interaction impossible:
- Depth: Standard
- Audience: Reviewer (PR) if code-related; Author otherwise
- Focus: Top 2 relevance clusters
Output the questions (label Q1/Q2/Q3). After answers: if ≥2 scenario classes (Alternate / Exception / Recovery / Non-Functional domain) remain unclear, you MAY ask up to TWO more targeted follow‑ups (Q4/Q5) with a one-line justification each (e.g., "Unresolved recovery path risk"). Do not exceed five total questions. Skip escalation if user explicitly declines more.
4. **Understand user request**: Combine `$ARGUMENTS` + clarifying answers:
- Derive checklist theme (e.g., security, review, deploy, ux)
- Consolidate explicit must-have items mentioned by user
- Map focus selections to category scaffolding
- Infer any missing context from spec/plan/tasks (do NOT hallucinate)
5. **Load feature context**: Read from FEATURE_DIR:
- spec.md: Feature requirements and scope
- plan.md (if exists): Technical details, dependencies
- tasks.md (if exists): Implementation tasks
**Context Loading Strategy**:
- Load only necessary portions relevant to active focus areas (avoid full-file dumping)
- Prefer summarizing long sections into concise scenario/requirement bullets
- Use progressive disclosure: add follow-on retrieval only if gaps detected
- If source docs are large, generate interim summary items instead of embedding raw text
6. **Generate checklist** - Use TEMPLATE_CONTENT as the structural template and create "Unit Tests for Requirements":
- Create `FEATURE_DIR/checklists/` directory if it doesn't exist
- Generate unique checklist filename:
- Use short, descriptive name based on domain (e.g., `ux.md`, `api.md`, `security.md`)
- Format: `[domain].md`
- File handling behavior:
- If file does NOT exist: Create new file and number items starting from CHK001
- If file exists: Append new items to existing file, continuing from the last CHK ID (e.g., if last item is CHK015, start new items at CHK016)
- Never delete or replace existing checklist content - always preserve and append
- Leave every newly generated item unchecked (`[ ]`); checkbox state belongs to the reviewer
**CORE PRINCIPLE - Test the Requirements, Not the Implementation**:
Every checklist item MUST evaluate the REQUIREMENTS THEMSELVES for:
- **Completeness**: Are all necessary requirements present?
- **Clarity**: Are requirements unambiguous and specific?
- **Consistency**: Do requirements align with each other?
- **Measurability**: Can requirements be objectively verified?
- **Coverage**: Are all scenarios/edge cases addressed?
**Category Structure** - Group items by requirement quality dimensions:
- **Requirement Completeness** (Are all necessary requirements documented?)
- **Requirement Clarity** (Are requirements specific and unambiguous?)
- **Requirement Consistency** (Do requirements align without conflicts?)
- **Acceptance Criteria Quality** (Are success criteria measurable?)
- **Scenario Coverage** (Are all flows/cases addressed?)
- **Edge Case Coverage** (Are boundary conditions defined?)
- **Non-Functional Requirements** (Performance, Security, Accessibility, etc. - are they specified?)
- **Dependencies & Assumptions** (Are they documented and validated?)
- **Ambiguities & Conflicts** (What needs clarification?)
**HOW TO WRITE CHECKLIST ITEMS - "Unit Tests for English"**:
❌ **WRONG** (Testing implementation):
- "Verify landing page displays 3 episode cards"
- "Test hover states work on desktop"
- "Confirm logo click navigates home"
✅ **CORRECT** (Testing requirements quality):
- "Are the exact number and layout of featured episodes specified?" [Completeness]
- "Is 'prominent display' quantified with specific sizing/positioning?" [Clarity]
- "Are hover state requirements consistent across all interactive elements?" [Consistency]
- "Are keyboard navigation requirements defined for all interactive UI?" [Coverage]
- "Is the fallback behavior specified when logo image fails to load?" [Edge Cases]
- "Are loading states defined for asynchronous episode data?" [Completeness]
- "Does the spec define visual hierarchy for competing UI elements?" [Clarity]
**ITEM STRUCTURE**:
Each item should follow this pattern:
- Question format asking about requirement quality
- Focus on what's WRITTEN (or not written) in the spec/plan
- Include quality dimension in brackets [Completeness/Clarity/Consistency/etc.]
- Reference spec section `[Spec §X.Y]` when checking existing requirements
- Use `[Gap]` marker when checking for missing requirements
**EXAMPLES BY QUALITY DIMENSION**:
Completeness:
- "Are error handling requirements defined for all API failure modes? [Gap]"
- "Are accessibility requirements specified for all interactive elements? [Completeness]"
- "Are mobile breakpoint requirements defined for responsive layouts? [Gap]"
Clarity:
- "Is 'fast loading' quantified with specific timing thresholds? [Clarity, Spec §NFR-2]"
- "Are 'related episodes' selection criteria explicitly defined? [Clarity, Spec §FR-5]"
- "Is 'prominent' defined with measurable visual properties? [Ambiguity, Spec §FR-4]"
Consistency:
- "Do navigation requirements align across all pages? [Consistency, Spec §FR-10]"
- "Are card component requirements consistent between landing and detail pages? [Consistency]"
Coverage:
- "Are requirements defined for zero-state scenarios (no episodes)? [Coverage, Edge Case]"
- "Are concurrent user interaction scenarios addressed? [Coverage, Gap]"
- "Are requirements specified for partial data loading failures? [Coverage, Exception Flow]"
Measurability:
- "Are visual hierarchy requirements measurable/testable? [Acceptance Criteria, Spec §FR-1]"
- "Can 'balanced visual weight' be objectively verified? [Measurability, Spec §FR-2]"
**Scenario Classification & Coverage** (Requirements Quality Focus):
- Check if requirements exist for: Primary, Alternate, Exception/Error, Recovery, Non-Functional scenarios
- For each scenario class, ask: "Are [scenario type] requirements complete, clear, and consistent?"
- If scenario class missing: "Are [scenario type] requirements intentionally excluded or missing? [Gap]"
- Include resilience/rollback when state mutation occurs: "Are rollback requirements defined for migration failures? [Gap]"
**Traceability Requirements**:
- MINIMUM: ≥80% of items MUST include at least one traceability reference
- Each item should reference: spec section `[Spec §X.Y]`, or use markers: `[Gap]`, `[Ambiguity]`, `[Conflict]`, `[Assumption]`
- If no ID system exists: "Is a requirement & acceptance criteria ID scheme established? [Traceability]"
**Surface & Resolve Issues** (Requirements Quality Problems):
Ask questions about the requirements themselves:
- Ambiguities: "Is the term 'fast' quantified with specific metrics? [Ambiguity, Spec §NFR-1]"
- Conflicts: "Do navigation requirements conflict between §FR-10 and §FR-10a? [Conflict]"
- Assumptions: "Is the assumption of 'always available podcast API' validated? [Assumption]"
- Dependencies: "Are external podcast API requirements documented? [Dependency, Gap]"
- Missing definitions: "Is 'visual hierarchy' defined with measurable criteria? [Gap]"
**Content Consolidation**:
- Soft cap: If raw candidate items > 40, prioritize by risk/impact
- Merge near-duplicates checking the same requirement aspect
- If >5 low-impact edge cases, create one item: "Are edge cases X, Y, Z addressed in requirements? [Coverage]"
**🚫 ABSOLUTELY PROHIBITED** - These make it an implementation test, not a requirements test:
- ❌ Any item starting with "Verify", "Test", "Confirm", "Check" + implementation behavior
- ❌ References to code execution, user actions, system behavior
- ❌ "Displays correctly", "works properly", "functions as expected"
- ❌ "Click", "navigate", "render", "load", "execute"
- ❌ Test cases, test plans, QA procedures
- ❌ Implementation details (frameworks, APIs, algorithms)
**✅ REQUIRED PATTERNS** - These test requirements quality:
- ✅ "Are [requirement type] defined/specified/documented for [scenario]?"
- ✅ "Is [vague term] quantified/clarified with specific criteria?"
- ✅ "Are requirements consistent between [section A] and [section B]?"
- ✅ "Can [requirement] be objectively measured/verified?"
- ✅ "Are [edge cases/scenarios] addressed in requirements?"
- ✅ "Does the spec define [missing aspect]?"
7. **Structure Reference**: Generate the checklist following the canonical template in `.specify/templates/checklist-template.md` for title, meta section, category headings, ownership note, notes section, and ID formatting. If template is unavailable, use: H1 title, purpose/created meta lines, an ownership note explaining that `[x]` means reviewer approval of requirements quality, `##` category sections containing `- [ ] CHK### <requirement item>` lines with globally incrementing IDs starting at CHK001, and notes that `/speckit.implement` reads checklist state but does not modify markers.
8. **Report**: Output full path to checklist file, item count, and summarize whether the run created a new file or appended to an existing one. Summarize:
- Focus areas selected
- Depth level
- Actor/timing
- Any explicit user-specified must-have items incorporated
**Important**: Each `/speckit.checklist` command invocation uses a short, descriptive checklist filename and either creates a new file or appends to an existing one. This allows:
- Multiple checklists of different types (e.g., `ux.md`, `test.md`, `security.md`)
- Simple, memorable filenames that indicate checklist purpose
- Easy identification and navigation in the `checklists/` folder
To avoid clutter, use descriptive types and clean up obsolete checklists when done.
## Example Checklist Types & Sample Items
**UX Requirements Quality:** `ux.md`
Sample items (testing the requirements, NOT the implementation):
- "Are visual hierarchy requirements defined with measurable criteria? [Clarity, Spec §FR-1]"
- "Is the number and positioning of UI elements explicitly specified? [Completeness, Spec §FR-1]"
- "Are interaction state requirements (hover, focus, active) consistently defined? [Consistency]"
- "Are accessibility requirements specified for all interactive elements? [Coverage, Gap]"
- "Is fallback behavior defined when images fail to load? [Edge Case, Gap]"
- "Can 'prominent display' be objectively measured? [Measurability, Spec §FR-4]"
**API Requirements Quality:** `api.md`
Sample items:
- "Are error response formats specified for all failure scenarios? [Completeness]"
- "Are rate limiting requirements quantified with specific thresholds? [Clarity]"
- "Are authentication requirements consistent across all endpoints? [Consistency]"
- "Are retry/timeout requirements defined for external dependencies? [Coverage, Gap]"
- "Is versioning strategy documented in requirements? [Gap]"
**Performance Requirements Quality:** `performance.md`
Sample items:
- "Are performance requirements quantified with specific metrics? [Clarity]"
- "Are performance targets defined for all critical user journeys? [Coverage]"
- "Are performance requirements under different load conditions specified? [Completeness]"
- "Can performance requirements be objectively measured? [Measurability]"
- "Are degradation requirements defined for high-load scenarios? [Edge Case, Gap]"
**Security Requirements Quality:** `security.md`
Sample items:
- "Are authentication requirements specified for all protected resources? [Coverage]"
- "Are data protection requirements defined for sensitive information? [Completeness]"
- "Is the threat model documented and requirements aligned to it? [Traceability]"
- "Are security requirements consistent with compliance obligations? [Consistency]"
- "Are security failure/breach response requirements defined? [Gap, Exception Flow]"
## Anti-Examples: What NOT To Do
**❌ WRONG - These test implementation, not requirements:**
```markdown
- [ ] CHK001 - Verify landing page displays 3 episode cards [Spec §FR-001]
- [ ] CHK002 - Test hover states work correctly on desktop [Spec §FR-003]
- [ ] CHK003 - Confirm logo click navigates to home page [Spec §FR-010]
- [ ] CHK004 - Check that related episodes section shows 3-5 items [Spec §FR-005]
```
**✅ CORRECT - These test requirements quality:**
```markdown
- [ ] CHK001 - Are the number and layout of featured episodes explicitly specified? [Completeness, Spec §FR-001]
- [ ] CHK002 - Are hover state requirements consistently defined for all interactive elements? [Consistency, Spec §FR-003]
- [ ] CHK003 - Are navigation requirements clear for all clickable brand elements? [Clarity, Spec §FR-010]
- [ ] CHK004 - Is the selection criteria for related episodes documented? [Gap, Spec §FR-005]
- [ ] CHK005 - Are loading state requirements defined for asynchronous episode data? [Gap]
- [ ] CHK006 - Can "visual hierarchy" requirements be objectively measured? [Measurability, Spec §FR-001]
```
**Key Differences:**
- Wrong: Tests if the system works correctly
- Correct: Tests if the requirements are written correctly
- Wrong: Verification of behavior
- Correct: Validation of requirement quality
- Wrong: "Does it do X?"
- Correct: "Is X clearly specified?"
## Post-Execution Checks
**Check for extension hooks (after checklist generation)**:
Check if `.specify/extensions.yml` exists in the project root.
- If it exists, read it and look for entries under the `hooks.after_checklist` key
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- For each executable hook, output the following based on its `optional` flag:
- **Optional hook** (`optional: true`):
```
## Extension Hooks
**Optional Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
- **Mandatory hook** (`optional: false`):
```
## Extension Hooks
**Automatic Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently
+287
View File
@@ -0,0 +1,287 @@
---
description: Identify underspecified areas in the current feature spec by asking up to 5 highly targeted clarification questions and encoding answers back into the spec.
handoffs:
- label: Build Technical Plan
agent: speckit.plan
prompt: Create a plan for the spec. I am building with...
---
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Pre-Execution Checks
**Check for extension hooks (before clarification)**:
- Check if `.specify/extensions.yml` exists in the project root.
- If it exists, read it and look for entries under the `hooks.before_clarify` key
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- For each executable hook, output the following based on its `optional` flag:
- **Optional hook** (`optional: true`):
```
## Extension Hooks
**Optional Pre-Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
- **Mandatory hook** (`optional: false`):
```
## Extension Hooks
**Automatic Pre-Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
Wait for the result of the hook command before proceeding to the Outline.
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently
## Outline
Goal: Detect and reduce ambiguity or missing decision points in the active feature specification and record the clarifications directly in the spec file.
Note: This clarification workflow is expected to run (and be completed) BEFORE invoking `/speckit.plan`. If the user explicitly states they are skipping clarification (e.g., exploratory spike), you may proceed, but must warn that downstream rework risk increases.
Execution steps:
1. Run `.specify/scripts/bash/check-prerequisites.sh --json --paths-only` from repo root **once** (combined `--json --paths-only` mode / `-Json -PathsOnly`). Parse minimal JSON payload fields:
- `FEATURE_DIR`
- `FEATURE_SPEC`
- (Optionally capture `IMPL_PLAN`, `TASKS` for future chained flows.)
- If JSON parsing fails, abort and instruct user to re-run `/speckit.specify` or verify feature branch environment.
- 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").
2. **IF EXISTS**: Load `.specify/memory/constitution.md` for project principles and governance constraints.
3. Load the current spec file. Perform a structured ambiguity & coverage scan using this taxonomy. For each category, mark status: Clear / Partial / Missing. Produce an internal coverage map used for prioritization (do not output raw map unless no questions will be asked).
Functional Scope & Behavior:
- Core user goals & success criteria
- Explicit out-of-scope declarations
- User roles / personas differentiation
Domain & Data Model:
- Entities, attributes, relationships
- Identity & uniqueness rules
- Lifecycle/state transitions
- Data volume / scale assumptions
Interaction & UX Flow:
- Critical user journeys / sequences
- Error/empty/loading states
- Accessibility or localization notes
Non-Functional Quality Attributes:
- Performance (latency, throughput targets)
- Scalability (horizontal/vertical, limits)
- Reliability & availability (uptime, recovery expectations)
- Observability (logging, metrics, tracing signals)
- Security & privacy (authN/Z, data protection, threat assumptions)
- Compliance / regulatory constraints (if any)
Integration & External Dependencies:
- External services/APIs and failure modes
- Data import/export formats
- Protocol/versioning assumptions
Edge Cases & Failure Handling:
- Negative scenarios
- Rate limiting / throttling
- Conflict resolution (e.g., concurrent edits)
Constraints & Tradeoffs:
- Technical constraints (language, storage, hosting)
- Explicit tradeoffs or rejected alternatives
Terminology & Consistency:
- Canonical glossary terms
- Avoided synonyms / deprecated terms
Completion Signals:
- Acceptance criteria testability
- Measurable Definition of Done style indicators
Misc / Placeholders:
- TODO markers / unresolved decisions
- Ambiguous adjectives ("robust", "intuitive") lacking quantification
For each category with Partial or Missing status, add a candidate question opportunity unless:
- Clarification would not materially change implementation or validation strategy
- The item is specifically about implementation method, tech-stack comparison, or task breakdown (note internally)
4. Generate (internally) a prioritized queue of candidate clarification questions (maximum 5). Do NOT output them all at once. Apply these constraints:
- Maximum of 5 total questions across the whole session.
- Each question must be answerable with EITHER:
- A short multiple‑choice selection (2–5 distinct, mutually exclusive options), OR
- A one-word / short‑phrase answer (explicitly constrain: "Answer in <=5 words").
- Only include questions whose answers materially impact architecture, data modeling, task decomposition, test design, UX behavior, operational readiness, or compliance validation.
- Ensure category coverage balance: attempt to cover the highest impact unresolved categories first; avoid asking two low-impact questions when a single high-impact area (e.g., security posture) is unresolved.
- Exclude questions already answered, trivial stylistic preferences, or plan-level execution details (unless blocking correctness).
- Favor clarifications that reduce downstream rework risk or prevent misaligned acceptance tests.
- If more than 5 categories remain unresolved, select the top 5 by (Impact * Uncertainty) heuristic.
5. Sequential questioning loop (interactive):
- Present EXACTLY ONE question at a time.
- **Question writing quality (applies to every question, MC or short-answer):**
- Lead with `**Question:**` followed by a full interrogative that ends with `?`. The question text before the `?` must make sense on its own.
- NEVER use a topic label, section heading, or requirement id as the question itself. For example, `Acceptance device/runtime matrix (FR-023)` is INVALID — it is a label, not a question.
- After the `?`, the only permitted suffix is an optional parenthesized requirement/question id. Exact format: `**Question:** <interrogative>?` or `**Question:** <interrogative>? (FR-023)`. Never put the id before the `?`, and never use the id (alone or with a topic label) as the whole prompt.
- Immediately after the question line, add one plain-language "Why it matters" sentence (the stake for acceptance or shipping) before the recommendation/options.
- Use everyday wording; introduce jargon only if defined in the same sentence. Self-check: a reader who does not know Spec Kit must be able to answer from the Question line alone. Terse is fine; cryptic labels are not.
- For multiple‑choice questions:
- **Analyze all options** and determine the **most suitable option** based on:
- Best practices for the project type
- Common patterns in similar implementations
- Risk reduction (security, performance, maintainability)
- Alignment with any explicit project goals or constraints visible in the spec
- Present your **recommended option prominently** at the top with clear reasoning (1-2 sentences explaining why this is the best choice).
- Format as: `**Recommended:** Option [X] - <reasoning>`
- Then render all options as a Markdown table:
| Option | Description |
|--------|-------------|
| A | <Option A description> |
| B | <Option B description> |
| C | <Option C description> (add D/E as needed up to 5) |
| Short | Provide a different short answer (<=5 words) (Include only if free-form alternative is appropriate) |
- After the table, add: `You can reply with the option letter (e.g., "A"), accept the recommendation by saying "yes" or "recommended", or provide your own short answer.`
- For short‑answer style (no meaningful discrete options):
- Provide your **suggested answer** based on best practices and context.
- Format as: `**Suggested:** <your proposed answer> - <brief reasoning>`
- Then output: `Format: Short answer (<=5 words). You can accept the suggestion by saying "yes" or "suggested", or provide your own answer.`
- After the user answers:
- If the user replies with "yes", "recommended", or "suggested", use your previously stated recommendation/suggestion as the answer.
- Otherwise, validate the answer maps to one option or fits the <=5 word constraint.
- If ambiguous, ask for a quick disambiguation (count still belongs to same question; do not advance).
- Once satisfactory, record it in working memory (do not yet write to disk) and move to the next queued question.
- Stop asking further questions when:
- All critical ambiguities resolved early (remaining queued items become unnecessary), OR
- User signals completion ("done", "good", "no more"), OR
- You reach 5 asked questions.
- Never reveal future queued questions in advance.
- If no valid questions exist at start, immediately report no critical ambiguities.
6. Integration after EACH accepted answer (incremental update approach):
- Maintain in-memory representation of the spec (loaded once at start) plus the raw file contents.
- For the first integrated answer in this session:
- Ensure a `## Clarifications` section exists (create it just after the highest-level contextual/overview section per the spec template if missing).
- Under it, create (if not present) a `### Session YYYY-MM-DD` subheading for today.
- Append a bullet line immediately after acceptance: `- Q: <question> → A: <final answer>`.
- Then immediately apply the clarification to the most appropriate section(s):
- Functional ambiguity → Update or add a bullet in Functional Requirements.
- User interaction / actor distinction → Update User Stories or Actors subsection (if present) with clarified role, constraint, or scenario.
- Data shape / entities → Update Data Model (add fields, types, relationships) preserving ordering; note added constraints succinctly.
- Non-functional constraint → Add/modify measurable criteria in Success Criteria > Measurable Outcomes (convert vague adjective to metric or explicit target).
- Edge case / negative flow → Add a new bullet under Edge Cases / Error Handling (or create such subsection if template provides placeholder for it).
- Terminology conflict → Normalize term across spec; retain original only if necessary by adding `(formerly referred to as "X")` once.
- If the clarification invalidates an earlier ambiguous statement, replace that statement instead of duplicating; leave no obsolete contradictory text.
- Save the spec file AFTER each integration to minimize risk of context loss (atomic overwrite).
- Preserve formatting: do not reorder unrelated sections; keep heading hierarchy intact.
- Keep each inserted clarification minimal and testable (avoid narrative drift).
7. Validation (performed after EACH write plus final pass):
- Clarifications session contains exactly one bullet per accepted answer (no duplicates).
- Total asked (accepted) questions ≤ 5.
- Updated sections contain no lingering vague placeholders the new answer was meant to resolve.
- No contradictory earlier statement remains (scan for now-invalid alternative choices removed).
- Markdown structure valid; only allowed new headings: `## Clarifications`, `### Session YYYY-MM-DD`.
- Terminology consistency: same canonical term used across all updated sections.
8. Write the updated spec back to `FEATURE_SPEC`.
9. **Re-validate Spec Quality Checklist** (if it exists):
- Check if `FEATURE_DIR/checklists/requirements.md` exists.
- If it does NOT exist, skip this step silently.
- If it exists:
1. Read the checklist file.
2. Identify all GitHub task-list checkbox lines — lines matching `- [ ]`, `- [x]`, or `- [X]` (case-insensitive, tolerant of leading whitespace for nested items) outside of code fences. Ignore all other content (headings, notes, non-checkbox bullets, metadata).
3. For each checkbox line, record its current marker state (checked or unchecked) and item text into a before-snapshot list.
4. Re-evaluate each checkbox item against the **updated** spec (the version just saved in step 7).
5. For each checkbox item, update only if the checked/unchecked state actually changes:
- If the item now passes and was unchecked: change `[ ]` to `[x]`.
- If the item now fails and was checked: change `[x]`/`[X]` to `[ ]`.
- If the state is unchanged: leave the marker as-is (preserve existing case to avoid cosmetic diffs).
6. Save the updated checklist file. **Only toggle the `[ ]`/`[x]` marker portion of checkbox lines whose state changed.** All other file content — headings, metadata, notes, line ordering, whitespace — must remain unchanged to avoid noisy diffs.
7. Compare the before-snapshot with the current state to compute three lists for the Completion Report:
- **Newly passing**: items that changed from unchecked to checked.
- **Regressions**: items that changed from checked to unchecked.
- **Still unchecked**: items that remain unchecked.
8. Record the before/after pass counts as checked/total checkbox items (e.g., "12/16 → 15/16 items passing").
Behavior rules:
- If no meaningful ambiguities found (or all potential questions would be low-impact), respond: "No critical ambiguities detected worth formal clarification." and suggest proceeding.
- If spec file missing, instruct user to run `/speckit.specify` first (do not create a new spec here).
- Never exceed 5 total asked questions (clarification retries for a single question do not count as new questions).
- Avoid speculative tech stack questions unless the absence blocks functional clarity.
- Respect user early termination signals ("stop", "done", "proceed").
- If no questions asked due to full coverage, output a compact coverage summary (all categories Clear) then suggest advancing.
- If quota reached with unresolved high-impact categories remaining, explicitly flag them under Deferred with rationale.
Context for prioritization: $ARGUMENTS
## Mandatory Post-Execution Hooks
**You MUST complete this section before reporting completion to the user.**
Check if `.specify/extensions.yml` exists in the project root.
- If it does not exist, or no hooks are registered under `hooks.after_clarify`, skip to the Completion Report.
- If it exists, read it and look for entries under the `hooks.after_clarify` key.
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue to the Completion Report.
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- For each executable hook, output the following based on its `optional` flag:
- **Mandatory hook** (`optional: false`) — **You MUST emit `EXECUTE_COMMAND:` for each mandatory hook**:
```
## Extension Hooks
**Automatic Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- **Optional hook** (`optional: true`):
```
## Extension Hooks
**Optional Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
## Completion Report
Report completion (after questioning loop ends or early termination):
- Number of questions asked & answered.
- Path to updated spec.
- Sections touched (list names).
- Spec quality checklist status (if `FEATURE_DIR/checklists/requirements.md` was re-validated): show before/after pass counts (e.g., "Spec Quality Checklist: 12/16 → 15/16 items passing") and list any items that changed state — both newly checked (unchecked → checked) and any regressions (checked → unchecked). If any items remain unchecked, list them as areas needing attention.
- Coverage summary table listing each taxonomy category with Status: Resolved (was Partial/Missing and addressed), Deferred (exceeds question quota, or remaining item is specifically implementation method, tech-stack comparison, or task breakdown), Clear (already sufficient), Outstanding (still Partial/Missing but low impact).
- If any Outstanding or Deferred remain, recommend whether to proceed to `/speckit.plan` or run `/speckit.clarify` again later post-plan.
- Suggested next command.
## Done When
- [ ] Spec ambiguities identified and clarifications integrated into spec file
- [ ] Spec quality checklist re-validated against updated spec (if `FEATURE_DIR/checklists/requirements.md` exists)
- [ ] Extension hooks dispatched or skipped according to the rules in Mandatory Post-Execution Hooks above
- [ ] Completion reported to user with questions answered, sections touched, checklist status, and coverage summary
+175
View File
@@ -0,0 +1,175 @@
---
description: Create or update the project constitution from interactive or provided principle inputs.
handoffs:
- label: Build Specification
agent: speckit.specify
prompt: Implement the feature specification based on the updated constitution. I want to build...
---
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Scope Guard
This command's own work is limited to updating the project constitution itself. Dependent templates
and commands read the constitution at runtime and are not modified here.
- Classify every part of the user input as either constitution content or a separate,
non-governance intent.
- If the input includes feature implementation, code generation, refactoring, building, or
deployment requests, you **MUST NOT** execute them. Extract them as deferred intents instead.
- You **MUST NOT** create, modify, or delete application source files, feature routes,
components, tests, deployment files, or other artifacts unrelated to the constitution
workflow.
- If it is unclear whether an instruction is constitution content, ask for clarification before
making changes.
- After completing the constitution update, include a `Next Actions` section for each deferred
intent. List the original intent and suggest the appropriate follow-up Spec Kit command, such
as `/speckit.specify`, without invoking it.
- If there are no non-governance intents, omit the `Next Actions` section.
## Pre-Execution Checks
**Check for extension hooks (before constitution update)**:
- Check if `.specify/extensions.yml` exists in the project root.
- If it exists, read it and look for entries under the `hooks.before_constitution` key
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- For each executable hook, output the following based on its `optional` flag:
- **Optional hook** (`optional: true`):
```
## Extension Hooks
**Optional Pre-Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
- **Mandatory hook** (`optional: false`):
```
## Extension Hooks
**Automatic Pre-Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
Wait for the result of the hook command before proceeding to the Outline.
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently
## Outline
You are updating the project constitution at `.specify/memory/constitution.md`. The active
constitution scaffold is resolved at command time from `constitution-template` through the Spec Kit
preset/template resolution stack.
Follow this execution flow:
1. Run `.specify/scripts/bash/resolve-template.sh constitution-template --json` from the repository root and parse `TEMPLATE_CONTENT` as the active template.
- The shared resolver applies project overrides, composing preset layers, and extension layers
before the core template fallback. It MUST succeed before continuing.
- If it fails, stop and report the resolution error; do not continue with only one contributing
template layer.
- If `.specify/memory/constitution.md` exists, load it as the source of current project-specific
values and amendments. Preserve information that is still applicable when applying the newly
resolved scaffold.
- If it does not exist, use the resolved template as the initial document.
- Do not write back to any versioned template layer.
- Identify every placeholder token of the form `[ALL_CAPS_IDENTIFIER]`.
**IMPORTANT**: The user might require less or more principles than the ones used in the template. If a number is specified, respect that - follow the general template. You will update the doc accordingly.
2. Collect/derive values for placeholders:
- If user input (conversation) supplies a value, use it.
- Otherwise infer from existing repo context (README, docs, prior constitution versions if embedded).
- For governance dates: `RATIFICATION_DATE` is the original adoption date (if unknown ask or mark TODO), `LAST_AMENDED_DATE` is today if changes are made, otherwise keep previous.
- `CONSTITUTION_VERSION` must increment according to semantic versioning rules:
- MAJOR: Backward incompatible governance/principle removals or redefinitions.
- MINOR: New principle/section added or materially expanded guidance.
- PATCH: Clarifications, wording, typo fixes, non-semantic refinements.
- If version bump type ambiguous, propose reasoning before finalizing.
3. Draft the updated constitution content using the resolved template as the required structure:
- Replace every placeholder with concrete text (no bracketed tokens left except intentionally retained template slots that the project has chosen not to define yet—explicitly justify any left).
- Preserve heading hierarchy and comments can be removed once replaced unless they still add clarifying guidance.
- Ensure each Principle section: succinct name line, paragraph (or bullet list) capturing non‑negotiable rules, explicit rationale if not obvious.
- Ensure Governance section lists amendment procedure, versioning policy, and compliance review expectations.
4. Produce a Sync Impact Report as an HTML comment at the top of the constitution file after update.
This report is temporary scratch material for human review of the amendment, not governance
content; it is expected to be removed before the amended constitution file is committed.
- Version change: old → new
- List of modified principles (old title → new title if renamed)
- Added sections
- Removed sections
- Follow-up TODOs if any placeholders intentionally deferred.
5. Validation before final output:
- No remaining unexplained bracket tokens.
- Version line matches report.
- Dates ISO format YYYY-MM-DD.
- Principles are declarative, testable, and free of vague language ("should" → replace with MUST/SHOULD rationale where appropriate).
6. Write the completed constitution back to `.specify/memory/constitution.md` (overwrite).
7. Output a final summary to the user with:
- New version and bump rationale.
- Any TODO placeholders or deferred items requiring manual follow-up.
- Suggested commit message (e.g., `docs: amend constitution to vX.Y.Z (principle additions + governance update)`).
- A `Next Actions` section for any deferred non-governance intents.
Formatting & Style Requirements:
- Use Markdown headings exactly as in the template (do not demote/promote levels).
- Wrap long rationale lines to keep readability (<100 chars ideally) but do not hard enforce with awkward breaks.
- Keep a single blank line between sections.
- Avoid trailing whitespace.
If the user supplies partial updates (e.g., only one principle revision), still perform validation and version decision steps.
If critical info missing (e.g., ratification date truly unknown), insert `TODO(<FIELD_NAME>): explanation` and include in the Sync Impact Report under deferred items.
Write only `.specify/memory/constitution.md`; do not create or modify template source files.
## Post-Execution Checks
**Check for extension hooks (after constitution update)**:
Check if `.specify/extensions.yml` exists in the project root.
- If it exists, read it and look for entries under the `hooks.after_constitution` key
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- For each executable hook, output the following based on its `optional` flag:
- **Optional hook** (`optional: true`):
```
## Extension Hooks
**Optional Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
- **Mandatory hook** (`optional: false`):
```
## Extension Hooks
**Automatic Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently
+275
View File
@@ -0,0 +1,275 @@
---
description: Assess the current codebase against the feature's spec, plan, and tasks, then append any remaining unbuilt work as new tasks to tasks.md so implement can complete it.
---
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Pre-Execution Checks
**Check for extension hooks (before convergence)**:
- Check if `.specify/extensions.yml` exists in the project root.
- If it exists, read it and look for entries under the `hooks.before_converge` key
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- For each executable hook, output the following based on its `optional` flag:
- **Optional hook** (`optional: true`):
```text
## Extension Hooks
**Optional Pre-Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
- **Mandatory hook** (`optional: false`):
```text
## Extension Hooks
**Automatic Pre-Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
Wait for the result of the hook command before proceeding to the Goal.
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently
## Goal
Close the gap between what a feature's specification, plan, and tasks call for and what the
codebase currently implements. Read `spec.md`, `plan.md`, and `tasks.md` as the **sole
source of intent** (with the constitution as governing constraints), assess the current
state of the code, determine which requirements, acceptance criteria, plan decisions, and
existing tasks are unmet, incomplete, or only partially satisfied, and **append each piece
of remaining work as a new, traceable task** at the bottom of `tasks.md` so that
`/speckit.implement` can complete it. This command MUST run only after
`/speckit.implement` has run on the current `tasks.md`, and after `/speckit.tasks` has produced a complete `tasks.md`.
This is **not** a diff tool and does **not** track changes. It assesses the present state
of the code relative to the feature's artifacts — no git, no branch comparison, no history.
## Operating Constraints
**APPEND-ONLY, NEVER REWRITE**: The command's **only** write is appending a new
`## Phase N: Convergence` section to `tasks.md`. It MUST NOT:
- modify `spec.md` or `plan.md` in any way;
- rewrite, renumber, reorder, or delete any existing task (including tasks from a prior
Convergence phase);
- modify, create, or delete any application code — completing the appended tasks is the
job of `/speckit.implement`.
When the codebase already satisfies everything, the command MUST leave `tasks.md`
**byte-for-byte unchanged** (no empty Convergence header) and report a clean result.
**Constitution Authority**: The project constitution (`.specify/memory/constitution.md`) is
**non-negotiable**. Code that violates a MUST principle is the highest-severity finding and
produces a corresponding remediation task. If the constitution is an unfilled template,
skip constitution checks gracefully rather than failing.
## Execution Steps
### 1. Initialize Convergence Context
Run `.specify/scripts/bash/check-prerequisites.sh --json --require-spec --require-tasks --include-tasks` once from repo root and parse JSON for FEATURE_DIR and AVAILABLE_DOCS. Derive absolute paths:
- SPEC = FEATURE_DIR/spec.md
- PLAN = FEATURE_DIR/plan.md
- TASKS = FEATURE_DIR/tasks.md
- CONSTITUTION = `.specify/memory/constitution.md` (if present)
If `spec.md`, `plan.md`, or `tasks.md` is missing, STOP with a clear, actionable message naming the
prerequisite command to run (`/speckit.specify` for a missing spec, `/speckit.plan` for a missing plan,
`/speckit.tasks` for missing tasks). Do not produce partial output.
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").
### 2. Load Artifacts (Progressive Disclosure)
Load only the minimal necessary context from each artifact:
**From spec.md:**
- Functional Requirements (FR-###)
- Success Criteria (SC-###) — include only items requiring buildable work; exclude
post-launch outcome metrics and business KPIs
- User Stories and their Acceptance Scenarios
- Edge Cases (if present)
**From plan.md:**
- Architecture/stack choices and technical decisions
- Data Model references
- Phases and named touch-points (files/components the plan says will be created or edited)
- Technical constraints
**From tasks.md:**
- Task IDs (to compute the next ID and next phase number)
- Descriptions, phase grouping, and referenced file paths
**From constitution (if not an unfilled template):**
- Principle names and MUST/SHOULD normative statements
### 3. Build the Intent Inventory
Create an internal model (do not echo raw artifacts):
- **Requirements inventory**: one stable key per FR-### / SC-### / user-story acceptance
scenario (e.g. `US1/AC2`), plus the plan decisions and constitution principles that
impose buildable obligations.
- **Code-scope map**: from the file paths named in `plan.md` and `tasks.md`, plus a keyword
search for the concepts each requirement describes, derive the set of source files and
components in scope for assessment. Bound the assessment to these — do **not** infer
scope beyond what the artifacts define.
### 4. Assess the Codebase and Classify Findings
Include every existing task in the intent inventory, regardless of checkbox state or
Convergence phase: completion claims are not evidence. Verify current behavior against
the spec, plan, tasks, and constitution; for corrective task chains, assess the resulting
behavior, not superseded implementation details. Check both unmet obligations and
implementation that contradicts, exceeds, or falls outside the stated intent.
For each item in the intent inventory, inspect the current code in scope and produce a
`Finding` only where there is a gap. Classify every finding by **gap type**:
- **`missing`**: the required work is absent from the code entirely.
- **`partial`**: the work exists but does not yet fully satisfy the requirement /
acceptance criterion / plan decision.
- **`contradicts`**: the code does something that conflicts with stated intent or a
constitution MUST principle.
- **`unrequested`**: the code contains work not called for by the spec, plan, or tasks
(surfaced for awareness — converge does **not** delete code, it only appends a task to
review/justify or remove it).
Each `Finding` records: a stable id, the `source-ref` it traces to, the `gap-type`, a
severity, and a short human-readable description with the evidence (the file/area observed).
**Edge cases:**
- **Little or no code yet**: treat the entire specified scope as `missing` remaining work
rather than failing.
- **Nothing remains**: produce zero findings and follow the converged branch in Step 7.
### 5. Assign Severity
- **CRITICAL**: violates a constitution MUST principle, or a `missing`/`contradicts` gap
that blocks baseline functionality of a P1 user story.
- **HIGH**: a `missing` or `partial` gap on a core functional requirement or acceptance
criterion.
- **MEDIUM**: a `partial` gap on a secondary requirement, or an `unrequested` addition with
unclear justification.
- **LOW**: minor partial gaps, polish, or low-risk `unrequested` additions.
### 6. Present the In-Session Findings Summary
Before appending anything, output a compact, severity-graded summary (no file writes yet):
## Convergence Findings
| ID | Gap Type | Severity | Source | Evidence | Remaining Work |
|----|----------|----------|--------|----------|----------------|
| F1 | missing | HIGH | FR-008 | Example: no append-only guard detected in path/to/module.py when writing tasks.md | Add append-only enforcement |
**Summary metrics:**
- Requirements / acceptance criteria checked
- Plan decisions checked
- Constitution principles checked (or "skipped — template")
- Findings by gap type (missing / partial / contradicts / unrequested)
- Findings by severity
### 7. Append Convergence Tasks (or report converged)
**If there are one or more actionable findings** (`tasks_appended` outcome):
Append to the **end** of `tasks.md`, per the append contract:
1. Scan all existing task IDs; let `M` be the maximum. Determine the next phase number `N`
(highest existing phase + 1).
2. Write a single new section header `## Phase N: Convergence`.
3. Emit one checklist item per actionable finding, ordered CRITICAL/HIGH first, assigning
zero-padded IDs `T{M+1:03d}, T{M+2:03d}, …`:
```markdown
- [ ] T042 <imperative description> per <source-ref> (<gap-type>)
```
`<source-ref>` traces the task to its origin: e.g. `FR-003`, `SC-002`,
`US1/AC2`, `plan: storage decision`, `Constitution II`.
`<gap-type>` is one of `missing`, `partial`, `contradicts`, `unrequested`.
Constitution-violation tasks MUST be emitted first and described as
`CRITICAL`.
4. Never reuse or renumber existing IDs. If a prior Convergence phase exists, add a new,
separately-numbered one below it — do not touch the old one.
**If there are no actionable findings** (`converged` outcome):
- Do **not** modify `tasks.md` at all — no empty phase header.
- Report: **"✅ Converged — the implementation satisfies the spec, plan, and tasks."**
- Include the summary counts of what was checked.
### 8. Provide Next Actions (Handoff)
- On `tasks_appended`: state how many tasks were appended under which phase, and recommend
running `/speckit.implement` to complete them; note that a follow-up converge
run will find fewer or no remaining items.
- On `converged`: recommend proceeding to review / opening a PR. No further implement pass
is needed for this feature's specified scope.
### 9. Check for extension hooks
After producing the result, check if `.specify/extensions.yml` exists in the project root.
- If it exists, read it and look for entries under the `hooks.after_converge` key
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- Report the convergence outcome (`converged` or `tasks_appended`) in-session before listing
any hooks, so users can decide whether to run optional follow-up commands.
- For each executable hook, output the following based on its `optional` flag:
- **Optional hook** (`optional: true`):
```text
## Extension Hooks
**Optional Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
- **Mandatory hook** (`optional: false`):
```text
## Extension Hooks
**Automatic Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently
+218
View File
@@ -0,0 +1,218 @@
---
description: Execute the implementation plan by processing and executing all tasks defined in tasks.md
---
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Pre-Execution Checks
**Check for extension hooks (before implementation)**:
- Check if `.specify/extensions.yml` exists in the project root.
- If it exists, read it and look for entries under the `hooks.before_implement` key
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- For each executable hook, output the following based on its `optional` flag:
- **Optional hook** (`optional: true`):
```
## Extension Hooks
**Optional Pre-Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
- **Mandatory hook** (`optional: false`):
```
## Extension Hooks
**Automatic Pre-Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
Wait for the result of the hook command before proceeding to the Outline.
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently
## Outline
1. Run `.specify/scripts/bash/check-prerequisites.sh --json --require-tasks --include-tasks` from repo root and parse FEATURE_DIR and AVAILABLE_DOCS list. All paths must be absolute. 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").
2. **Check checklists status** (if FEATURE_DIR/checklists/ exists):
- Treat checklist markers as a read-only gate: scan checkbox state, report status, and ask before proceeding when needed; do NOT modify checklist files or markers
- `checklists/requirements.md` is the built-in spec-quality checklist maintained by `/speckit.specify` and `/speckit.clarify`; custom checklists generated by `/speckit.checklist` are reviewer-owned requirements-quality review artifacts
- For custom checklists, `[x]` means the reviewer determined the requirements-quality criterion is satisfied; it does NOT mean implementation work is complete
- Scan all checklist files in the checklists/ directory
- For each checklist, count:
- Total items: All lines matching `- [ ]` or `- [X]` or `- [x]`
- Checked items: Lines matching `- [X]` or `- [x]`
- Unchecked items: Lines matching `- [ ]`
- Create a status table:
```text
| Checklist | Total | Checked | Unchecked | Status |
|-----------|-------|---------|-----------|--------|
| ux.md | 12 | 12 | 0 | ✓ PASS |
| test.md | 8 | 5 | 3 | ✗ FAIL |
| security.md | 6 | 6 | 0 | ✓ PASS |
```
- Calculate overall status:
- **PASS**: All checklists have 0 unchecked items
- **FAIL**: One or more checklists have unchecked items
- **If any checklist has unchecked items**:
- Display the table with unchecked item counts
- **STOP** and ask: "Some checklists have unchecked items. Do you want to proceed with implementation anyway? (yes/no)"
- Wait for user response before continuing
- If user says "no" or "wait" or "stop", halt execution
- If user says "yes" or "proceed" or "continue", proceed to step 3
- **If all checklists are checked**:
- Display the table showing all checklists passed
- Automatically proceed to step 3
3. Load and analyze the implementation context:
- **REQUIRED**: Read tasks.md for the complete task list and execution plan
- **REQUIRED**: Read plan.md for tech stack, architecture, and file structure
- **IF EXISTS**: Read data-model.md for entities and relationships
- **IF EXISTS**: Read contracts/ for API specifications and test requirements
- **IF EXISTS**: Read research.md for technical decisions and constraints
- **IF EXISTS**: Read .specify/memory/constitution.md for governance constraints
- **IF EXISTS**: Read quickstart.md for integration scenarios
4. **Project Setup Verification**:
- **REQUIRED**: Create/verify ignore files based on actual project setup:
**Detection & Creation Logic**:
- Check if the following command succeeds to determine if the repository is a git repo (create/verify .gitignore if so):
```sh
git rev-parse --git-dir 2>/dev/null
```
- Check if Dockerfile* exists or Docker in plan.md → create/verify .dockerignore
- Check if .eslintrc* exists → create/verify .eslintignore
- Check if eslint.config.* exists → ensure the config's `ignores` entries cover required patterns
- Check if .prettierrc* exists → create/verify .prettierignore
- Check if .npmrc or package.json exists → create/verify .npmignore (if publishing)
- Check if terraform files (*.tf) exist → create/verify .terraformignore
- Check if .helmignore needed (helm charts present) → create/verify .helmignore
**If ignore file already exists**: Verify it contains essential patterns, append missing critical patterns only
**If ignore file missing**: Create with full pattern set for detected technology
**Common Patterns by Technology** (from plan.md tech stack):
- **Node.js/JavaScript/TypeScript**: `node_modules/`, `dist/`, `build/`, `*.log`, `.env*`
- **Python**: `__pycache__/`, `*.pyc`, `.venv/`, `venv/`, `dist/`, `*.egg-info/`
- **Java**: `target/`, `*.class`, `*.jar`, `.gradle/`, `build/`
- **C#/.NET**: `bin/`, `obj/`, `*.user`, `*.suo`, `packages/`
- **Go**: `*.exe`, `*.test`, `vendor/`, `*.out`
- **Ruby**: `.bundle/`, `log/`, `tmp/`, `*.gem`, `vendor/bundle/`
- **PHP**: `vendor/`, `*.log`, `*.cache`, `*.env`
- **Rust**: `target/`, `debug/`, `release/`, `*.rs.bk`, `*.rlib`, `*.prof*`, `.idea/`, `*.log`, `.env*`
- **Kotlin**: `build/`, `out/`, `.gradle/`, `.idea/`, `*.class`, `*.jar`, `*.iml`, `*.log`, `.env*`
- **C++**: `build/`, `bin/`, `obj/`, `out/`, `*.o`, `*.so`, `*.a`, `*.exe`, `*.dll`, `.idea/`, `*.log`, `.env*`
- **C**: `build/`, `bin/`, `obj/`, `out/`, `*.o`, `*.a`, `*.so`, `*.exe`, `*.dll`, `autom4te.cache/`, `config.status`, `config.log`, `.idea/`, `*.log`, `.env*`
- **Swift**: `.build/`, `DerivedData/`, `*.swiftpm/`, `Packages/`
- **R**: `.Rproj.user/`, `.Rhistory`, `.RData`, `.Ruserdata`, `*.Rproj`, `packrat/`, `renv/`
- **Universal**: `.DS_Store`, `Thumbs.db`, `*.tmp`, `*.swp`, `.vscode/`, `.idea/`
**Tool-Specific Patterns**:
- **Docker**: `node_modules/`, `.git/`, `Dockerfile*`, `.dockerignore`, `*.log*`, `.env*`, `coverage/`
- **ESLint**: `node_modules/`, `dist/`, `build/`, `coverage/`, `*.min.js`
- **Prettier**: `node_modules/`, `dist/`, `build/`, `coverage/`, `package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`
- **Terraform**: `.terraform/`, `*.tfstate*`, `*.tfvars`, `.terraform.lock.hcl`
- **Kubernetes/k8s**: `*.secret.yaml`, `secrets/`, `.kube/`, `kubeconfig*`, `*.key`, `*.crt`
5. Parse tasks.md structure and extract:
- **Task phases**: Setup, Tests, Core, Integration, Polish
- **Task dependencies**: Sequential vs parallel execution rules
- **Task details**: ID, description, file paths, parallel markers [P]
- **Execution flow**: Order and dependency requirements
6. Execute implementation following the task plan:
- **Phase-by-phase execution**: Complete each phase before moving to the next
- **Respect dependencies**: Run sequential tasks in order, parallel tasks [P] can run together
- **Follow TDD approach**: Execute test tasks before their corresponding implementation tasks
- **File-based coordination**: Tasks affecting the same files must run sequentially
- **Validation checkpoints**: Verify each phase completion before proceeding
7. Implementation execution rules:
- **Setup first**: Initialize project structure, dependencies, configuration
- **Tests before code**: If you need to write tests for contracts, entities, and integration scenarios
- **Core development**: Implement models, services, CLI commands, endpoints
- **Integration work**: Database connections, middleware, logging, external services
- **Polish and validation**: Unit tests, performance optimization, documentation
8. Progress tracking and error handling:
- Report progress after each completed task
- Halt execution if any non-parallel task fails
- For parallel tasks [P], continue with successful tasks, report failed ones
- Provide clear error messages with context for debugging
- Suggest next steps if implementation cannot proceed
- **IMPORTANT** For completed tasks, make sure to mark the task off as [X] in the tasks file.
9. Completion validation:
- Verify all required tasks are completed
- Check that implemented features match the original specification
- Validate that tests pass and coverage meets requirements
- Confirm the implementation follows the technical plan
Note: This command assumes a complete task breakdown exists in tasks.md. If tasks are incomplete or missing, suggest running `/speckit.tasks` first to regenerate the task list.
## Mandatory Post-Execution Hooks
**You MUST complete this section before reporting completion to the user.**
Check if `.specify/extensions.yml` exists in the project root.
- If it does not exist, or no hooks are registered under `hooks.after_implement`, skip to the Completion Report.
- If it exists, read it and look for entries under the `hooks.after_implement` key.
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue to the Completion Report.
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- For each executable hook, output the following based on its `optional` flag:
- **Mandatory hook** (`optional: false`) — **You MUST emit `EXECUTE_COMMAND:` for each mandatory hook**:
```
## Extension Hooks
**Automatic Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- **Optional hook** (`optional: true`):
```
## Extension Hooks
**Optional Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
## Completion Report
Report final status with summary of completed work.
## Done When
- [ ] All tasks in tasks.md completed and marked `[X]`
- [ ] Implementation validated against specification, plan, and test coverage
- [ ] Extension hooks dispatched or skipped according to the rules in Mandatory Post-Execution Hooks above
- [ ] Completion reported to user with summary of completed work
+166
View File
@@ -0,0 +1,166 @@
---
description: Execute the implementation planning workflow using the plan template to generate design artifacts.
handoffs:
- label: Create Tasks
agent: speckit.tasks
prompt: Break the plan into tasks
send: true
- label: Create Checklist
agent: speckit.checklist
prompt: Create a checklist for the following domain...
---
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Pre-Execution Checks
**Check for extension hooks (before planning)**:
- Check if `.specify/extensions.yml` exists in the project root.
- If it exists, read it and look for entries under the `hooks.before_plan` key
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- For each executable hook, output the following based on its `optional` flag:
- **Optional hook** (`optional: true`):
```
## Extension Hooks
**Optional Pre-Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
- **Mandatory hook** (`optional: false`):
```
## Extension Hooks
**Automatic Pre-Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
Wait for the result of the hook command before proceeding to the Outline.
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently
## Outline
1. **Setup**: Run `.specify/scripts/bash/setup-plan.sh --json` from repo root and parse JSON for FEATURE_SPEC, IMPL_PLAN, FEATURE_DIR, BRANCH. 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").
2. **Load context**: Read FEATURE_SPEC and `.specify/memory/constitution.md`. Load IMPL_PLAN template (already copied).
3. **Execute plan workflow**: Follow the structure in IMPL_PLAN template to:
- Fill Technical Context (mark unknowns as "NEEDS CLARIFICATION")
- Fill Constitution Check section from constitution
- Evaluate gates (ERROR if violations unjustified)
- Phase 0: Generate research.md (resolve all NEEDS CLARIFICATION)
- Phase 1: Generate data-model.md, contracts/, quickstart.md
- Re-evaluate Constitution Check post-design
## Mandatory Post-Execution Hooks
**You MUST complete this section before reporting completion to the user.**
Check if `.specify/extensions.yml` exists in the project root.
- If it does not exist, or no hooks are registered under `hooks.after_plan`, skip to the Completion Report.
- If it exists, read it and look for entries under the `hooks.after_plan` key.
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue to the Completion Report.
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- For each executable hook, output the following based on its `optional` flag:
- **Mandatory hook** (`optional: false`) — **You MUST emit `EXECUTE_COMMAND:` for each mandatory hook**:
```
## Extension Hooks
**Automatic Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- **Optional hook** (`optional: true`):
```
## Extension Hooks
**Optional Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
## Completion Report
Command ends after Phase 1 design. Report branch, IMPL_PLAN path, and generated artifacts.
## Phases
### Phase 0: Outline & Research
1. **Extract unknowns from Technical Context** above:
- For each NEEDS CLARIFICATION → research task
- For each dependency → best practices task
- For each integration → patterns task
2. **Generate and dispatch research agents**:
```text
For each unknown in Technical Context:
Task: "Research {unknown} for {feature context}"
For each technology choice:
Task: "Find best practices for {tech} in {domain}"
```
3. **Consolidate findings** in `research.md` using format:
- Decision: [what was chosen]
- Rationale: [why chosen]
- Alternatives considered: [what else evaluated]
**Output**: research.md with all NEEDS CLARIFICATION resolved
### Phase 1: Design & Contracts
**Prerequisites:** `research.md` complete
1. **Extract entities from feature spec** → `data-model.md`:
- Entity name, fields, relationships
- Validation rules from requirements
- State transitions if applicable
2. **Define interface contracts** (if project has external interfaces) → `/contracts/`:
- Identify what interfaces the project exposes to users or other systems
- Document the contract format appropriate for the project type
- Examples: public APIs for libraries, command schemas for CLI tools, endpoints for web services, grammars for parsers, UI contracts for applications
- Skip if project is purely internal (build scripts, one-off tools, etc.)
3. **Create quickstart validation guide** → `quickstart.md`:
- Document runnable validation scenarios that prove the feature works end-to-end
- Include prerequisites, setup commands, test/run commands, and expected outcomes
- Use links or references to contracts and data model details instead of duplicating them
- Do not include full implementation code, model/service/controller bodies, migrations, or complete test suites
- Keep this artifact as a validation/run guide; implementation details belong in `tasks.md` and the implementation phase
**Output**: data-model.md, /contracts/*, quickstart.md
## Key rules
- Use absolute paths for filesystem operations; use project-relative paths for references in documentation
- ERROR on gate failures or unresolved clarifications
## Done When
- [ ] Plan workflow executed and design artifacts generated
- [ ] Extension hooks dispatched or skipped according to the rules in Mandatory Post-Execution Hooks above
- [ ] Completion reported to user with branch, plan path, and generated artifacts
+345
View File
@@ -0,0 +1,345 @@
---
description: Create or update the feature specification from a natural language feature description.
handoffs:
- label: Build Technical Plan
agent: speckit.plan
prompt: Create a plan for the spec. I am building with...
- label: Clarify Spec Requirements
agent: speckit.clarify
prompt: Clarify specification requirements
send: true
---
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Pre-Execution Checks
**Check for extension hooks (before specification)**:
- Check if `.specify/extensions.yml` exists in the project root.
- If it exists, read it and look for entries under the `hooks.before_specify` key
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- For each executable hook, output the following based on its `optional` flag:
- **Optional hook** (`optional: true`):
```
## Extension Hooks
**Optional Pre-Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
- **Mandatory hook** (`optional: false`):
```
## Extension Hooks
**Automatic Pre-Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
Wait for the result of the hook command before proceeding to the Outline.
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently
## Outline
The text the user typed after `/speckit.specify` in the triggering message **is** the feature description. Assume you always have it available in this conversation even if `$ARGUMENTS` appears literally below. Do not ask the user to repeat it unless they provided an empty command.
Given that feature description, do this:
1. **Generate a concise short name** (2-4 words) for the feature:
- Analyze the feature description and extract the most meaningful keywords
- Create a 2-4 word short name that captures the essence of the feature
- Use action-noun format when possible (e.g., "add-user-auth", "fix-payment-bug")
- Preserve technical terms and acronyms (OAuth2, API, JWT, etc.)
- Keep it concise but descriptive enough to understand the feature at a glance
- Examples:
- "I want to add user authentication" → "user-auth"
- "Implement OAuth2 integration for the API" → "oauth2-api-integration"
- "Create a dashboard for analytics" → "analytics-dashboard"
- "Fix payment processing timeout bug" → "fix-payment-timeout"
2. **Branch creation** (optional, via hook):
If a `before_specify` hook ran successfully in the Pre-Execution Checks above, it will have created/switched to a git branch and output JSON containing `BRANCH_NAME` and `FEATURE_NUM`. Note these values for reference, but the branch name does **not** dictate the spec directory name.
If the user explicitly provided `GIT_BRANCH_NAME`, pass it through to the hook so the branch script uses the exact value as the branch name (bypassing all prefix/suffix generation).
3. **Create the spec feature directory**:
Specs live under the default `specs/` directory unless the user explicitly provides `SPECIFY_FEATURE_DIRECTORY`.
**Resolution order for `SPECIFY_FEATURE_DIRECTORY`**:
1. If the user explicitly provided `SPECIFY_FEATURE_DIRECTORY` (e.g., via environment variable, argument, or configuration), use it as-is
2. Otherwise, auto-generate it under `specs/`:
- Check `.specify/init-options.json` for `feature_numbering` (preferred) or `branch_numbering` (deprecated, migration only — will be removed in a future release)
- If `"timestamp"`: prefix is `YYYYMMDD-HHMMSS` (current timestamp)
- If `"sequential"` or absent: prefix is `NNN` (next available 3-digit number after scanning existing directories in `specs/`)
- Construct the directory name: `<prefix>-<short-name>` (e.g., `003-user-auth` or `20260319-143022-user-auth`)
- Set `SPECIFY_FEATURE_DIRECTORY` to `specs/<directory-name>`
- If `branch_numbering` was used (and `feature_numbering` was absent), emit a one-line warning: "⚠️ `branch_numbering` in init-options.json is deprecated. Rename to `feature_numbering`."
**Create the directory and spec file**:
- `mkdir -p SPECIFY_FEATURE_DIRECTORY`
- Resolve the active `spec-template` through the Spec Kit preset/template resolution stack (equivalent to `specify preset resolve spec-template`)
- Copy the resolved `spec-template` file to `SPECIFY_FEATURE_DIRECTORY/spec.md` as the starting point
- Set `SPEC_FILE` to `SPECIFY_FEATURE_DIRECTORY/spec.md`
- Persist the resolved path to `.specify/feature.json`:
```json
{
"feature_directory": "<resolved feature dir>"
}
```
Write the actual resolved directory path value (for example, `specs/003-user-auth`), not the literal string `SPECIFY_FEATURE_DIRECTORY`.
This allows downstream commands (`/speckit.plan`, `/speckit.tasks`, etc.) to locate the feature directory without relying on git branch name conventions.
**IMPORTANT**:
- You must only create one feature per `/speckit.specify` invocation
- The spec directory name and the git branch name are independent — they may be the same but that is the user's choice
- The spec directory and file are always created by this command, never by the hook
4. Load the resolved active `spec-template` file to understand required sections.
5. **IF EXISTS**: Load `.specify/memory/constitution.md` for project principles and governance constraints.
6. Follow this execution flow:
1. Parse user description from arguments
If empty: ERROR "No feature description provided"
2. Extract key concepts from description
Identify: actors, actions, data, constraints
3. For unclear aspects:
- Make informed guesses based on context and industry standards
- Only mark with [NEEDS CLARIFICATION: specific question] if:
- The choice significantly impacts feature scope or user experience
- Multiple reasonable interpretations exist with different implications
- No reasonable default exists
- **LIMIT: Maximum 3 [NEEDS CLARIFICATION] markers total**
- Prioritize clarifications by impact: scope > security/privacy > user experience > technical details
4. Fill User Scenarios & Testing section
If no clear user flow: ERROR "Cannot determine user scenarios"
5. Generate Functional Requirements
Each requirement must be testable
Use reasonable defaults for unspecified details (document assumptions in Assumptions section)
6. Define Success Criteria
Create measurable, technology-agnostic outcomes
Include both quantitative metrics (time, performance, volume) and qualitative measures (user satisfaction, task completion)
Each criterion must be verifiable without implementation details
7. Identify Key Entities (if data involved)
8. Return: SUCCESS (spec ready for planning)
7. Write the specification to SPEC_FILE using the template structure, replacing placeholders with concrete details derived from the feature description (arguments) while preserving section order and headings.
8. **Specification Quality Validation**: After writing the initial spec, validate it against quality criteria:
a. **Create Spec Quality Checklist**: Generate a checklist file at `SPECIFY_FEATURE_DIRECTORY/checklists/requirements.md` using the checklist template structure with these validation items:
```markdown
# Specification Quality Checklist: [FEATURE NAME]
**Purpose**: Validate specification completeness and quality before proceeding to planning
**Created**: [DATE]
**Feature**: [Link to spec.md]
## Content Quality
- [ ] No implementation details (languages, frameworks, APIs)
- [ ] Focused on user value and business needs
- [ ] Written for non-technical stakeholders
- [ ] All mandatory sections completed
## Requirement Completeness
- [ ] No [NEEDS CLARIFICATION] markers remain
- [ ] Requirements are testable and unambiguous
- [ ] Success criteria are measurable
- [ ] Success criteria are technology-agnostic (no implementation details)
- [ ] All acceptance scenarios are defined
- [ ] Edge cases are identified
- [ ] Scope is clearly bounded
- [ ] Dependencies and assumptions identified
## Feature Readiness
- [ ] All functional requirements have clear acceptance criteria
- [ ] User scenarios cover primary flows
- [ ] Feature meets measurable outcomes defined in Success Criteria
- [ ] No implementation details leak into specification
## Notes
- Items marked incomplete require spec updates before `/speckit.clarify` or `/speckit.plan`
```
b. **Run Validation Check**: Review the spec against each checklist item:
- For each item, determine if it passes or fails
- Document specific issues found (quote relevant spec sections)
c. **Handle Validation Results**:
- **If all items pass**: Mark checklist complete and proceed to the Mandatory Post-Execution Hooks section
- **If items fail (excluding [NEEDS CLARIFICATION])**:
1. List the failing items and specific issues
2. Update the spec to address each issue
3. Re-run validation until all items pass (max 3 iterations)
4. If still failing after 3 iterations, document remaining issues in checklist notes and warn user
- **If [NEEDS CLARIFICATION] markers remain**:
1. Extract all [NEEDS CLARIFICATION: ...] markers from the spec
2. **LIMIT CHECK**: If more than 3 markers exist, keep only the 3 most critical (by scope/security/UX impact) and make informed guesses for the rest
3. For each clarification needed (max 3), present options to user in this format:
```markdown
## Question [N]: [Topic]
**Context**: [Quote relevant spec section]
**What we need to know**: [Specific question from NEEDS CLARIFICATION marker]
**Suggested Answers**:
| Option | Answer | Implications |
|--------|--------|--------------|
| A | [First suggested answer] | [What this means for the feature] |
| B | [Second suggested answer] | [What this means for the feature] |
| C | [Third suggested answer] | [What this means for the feature] |
| Custom | Provide your own answer | [Explain how to provide custom input] |
**Your choice**: _[Wait for user response]_
```
4. **CRITICAL - Table Formatting**: Ensure markdown tables are properly formatted:
- Use consistent spacing with pipes aligned
- Each cell should have spaces around content: `| Content |` not `|Content|`
- Header separator must have at least 3 dashes: `|--------|`
- Test that the table renders correctly in markdown preview
5. Number questions sequentially (Q1, Q2, Q3 - max 3 total)
6. Present all questions together before waiting for responses
7. Wait for user to respond with their choices for all questions (e.g., "Q1: A, Q2: Custom - [details], Q3: B")
8. Update the spec by replacing each [NEEDS CLARIFICATION] marker with the user's selected or provided answer
9. Re-run validation after all clarifications are resolved
d. **Update Checklist**: After each validation iteration, update the checklist file with current pass/fail status
## Mandatory Post-Execution Hooks
**You MUST complete this section before reporting completion to the user.**
Check if `.specify/extensions.yml` exists in the project root.
- If it does not exist, or no hooks are registered under `hooks.after_specify`, skip to the Completion Report.
- If it exists, read it and look for entries under the `hooks.after_specify` key.
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue to the Completion Report.
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- For each executable hook, output the following based on its `optional` flag:
- **Mandatory hook** (`optional: false`) — **You MUST emit `EXECUTE_COMMAND:` for each mandatory hook**:
```
## Extension Hooks
**Automatic Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- **Optional hook** (`optional: true`):
```
## Extension Hooks
**Optional Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
## Completion Report
Report completion to the user with:
- `SPECIFY_FEATURE_DIRECTORY` — the feature directory path
- `SPEC_FILE` — the spec file path
- Checklist results summary
- Readiness for the next phase (`/speckit.clarify` or `/speckit.plan`)
**NOTE:** Branch creation is handled by the `before_specify` hook (git extension). Spec directory and file creation are always handled by this core command.
## Quick Guidelines
- Focus on **WHAT** users need and **WHY**.
- Avoid HOW to implement (no tech stack, APIs, code structure).
- Written for business stakeholders, not developers.
- DO NOT create any checklists that are embedded in the spec. That will be a separate command.
### Section Requirements
- **Mandatory sections**: Must be completed for every feature
- **Optional sections**: Include only when relevant to the feature
- When a section doesn't apply, remove it entirely (don't leave as "N/A")
### For AI Generation
When creating this spec from a user prompt:
1. **Make informed guesses**: Use context, industry standards, and common patterns to fill gaps
2. **Document assumptions**: Record reasonable defaults in the Assumptions section
3. **Limit clarifications**: Maximum 3 [NEEDS CLARIFICATION] markers - use only for critical decisions that:
- Significantly impact feature scope or user experience
- Have multiple reasonable interpretations with different implications
- Lack any reasonable default
4. **Prioritize clarifications**: scope > security/privacy > user experience > technical details
5. **Think like a tester**: Every vague requirement should fail the "testable and unambiguous" checklist item
6. **Common areas needing clarification** (only if no reasonable default exists):
- Feature scope and boundaries (include/exclude specific use cases)
- User types and permissions (if multiple conflicting interpretations possible)
- Security/compliance requirements (when legally/financially significant)
**Examples of reasonable defaults** (don't ask about these):
- Data retention: Industry-standard practices for the domain
- Performance targets: Standard web/mobile app expectations unless specified
- Error handling: User-friendly messages with appropriate fallbacks
- Authentication method: Standard session-based or OAuth2 for web apps
- Integration patterns: Use project-appropriate patterns (REST/GraphQL for web services, function calls for libraries, CLI args for tools, etc.)
### Success Criteria Guidelines
Success criteria must be:
1. **Measurable**: Include specific metrics (time, percentage, count, rate)
2. **Technology-agnostic**: No mention of frameworks, languages, databases, or tools
3. **User-focused**: Describe outcomes from user/business perspective, not system internals
4. **Verifiable**: Can be tested/validated without knowing implementation details
**Good examples**:
- "Users can complete checkout in under 3 minutes"
- "System supports 10,000 concurrent users"
- "95% of searches return results in under 1 second"
- "Task completion rate improves by 40%"
**Bad examples** (implementation-focused):
- "API response time is under 200ms" (too technical, use "Users see results instantly")
- "Database can handle 1000 TPS" (implementation detail, use user-facing metric)
- "React components render efficiently" (framework-specific)
- "Redis cache hit rate above 80%" (technology-specific)
## Done When
- [ ] Specification written to `SPEC_FILE` and validated against quality checklist
- [ ] Extension hooks dispatched or skipped according to the rules in Mandatory Post-Execution Hooks above
- [ ] Completion reported to user with feature directory, spec file path, and checklist results
+216
View File
@@ -0,0 +1,216 @@
---
description: Generate an actionable, dependency-ordered tasks.md for the feature based on available design artifacts.
handoffs:
- label: Analyze For Consistency
agent: speckit.analyze
prompt: Run a project analysis for consistency
send: true
- label: Implement Project
agent: speckit.implement
prompt: Start the implementation in phases
send: true
---
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Pre-Execution Checks
**Check for extension hooks (before tasks generation)**:
- Check if `.specify/extensions.yml` exists in the project root.
- If it exists, read it and look for entries under the `hooks.before_tasks` key
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- For each executable hook, output the following based on its `optional` flag:
- **Optional hook** (`optional: true`):
```
## Extension Hooks
**Optional Pre-Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
- **Mandatory hook** (`optional: false`):
```
## Extension Hooks
**Automatic Pre-Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
Wait for the result of the hook command before proceeding to the Outline.
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently
## Outline
1. **Setup**: Run `.specify/scripts/bash/setup-tasks.sh --json` from repo root and parse FEATURE_DIR, TASKS_TEMPLATE_CONTENT, TASKS_TEMPLATE, and AVAILABLE_DOCS list. `FEATURE_DIR` and `TASKS_TEMPLATE` must be absolute paths when provided. `AVAILABLE_DOCS` is a list of document names/relative paths available under `FEATURE_DIR` (for example `research.md` or `contracts/`). 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").
2. **Load design documents**: Read from FEATURE_DIR:
- **Required**: plan.md (tech stack, libraries, structure), spec.md (user stories with priorities)
- **Optional**: data-model.md (entities), contracts/ (interface contracts), research.md (decisions), quickstart.md (test scenarios)
- **IF EXISTS**: Load `.specify/memory/constitution.md` for project principles and governance constraints
- Note: Not all projects have all documents. Generate tasks based on what's available.
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 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)
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
- Phase 1: Setup tasks (project initialization)
- Phase 2: Foundational tasks (blocking prerequisites for all user stories)
- Phase 3+: One phase per user story (in priority order from spec.md)
- Each phase includes: story goal, independent test criteria, tests (if requested), implementation tasks
- Final Phase: Polish & cross-cutting concerns
- All tasks must follow the strict checklist format (see Task Generation Rules below)
- Clear file paths for each task
- Dependencies section showing story completion order
- Parallel execution examples per story
- Implementation strategy section (MVP first, incremental delivery)
## Mandatory Post-Execution Hooks
**You MUST complete this section before reporting completion to the user.**
Check if `.specify/extensions.yml` exists in the project root.
- If it does not exist, or no hooks are registered under `hooks.after_tasks`, skip to the Completion Report.
- If it exists, read it and look for entries under the `hooks.after_tasks` key.
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue to the Completion Report.
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- For each executable hook, output the following based on its `optional` flag:
- **Mandatory hook** (`optional: false`) — **You MUST emit `EXECUTE_COMMAND:` for each mandatory hook**:
```
## Extension Hooks
**Automatic Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- **Optional hook** (`optional: true`):
```
## Extension Hooks
**Optional Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
## Completion Report
Output path to generated tasks.md and summary:
- Total task count
- Task count per user story
- Parallel opportunities identified
- Independent test criteria for each story
- Suggested MVP scope (typically just User Story 1)
- Format validation: Confirm ALL tasks follow the checklist format (checkbox, ID, labels, file paths)
Context for task generation: $ARGUMENTS
The tasks.md should be immediately executable - each task must be specific enough that an LLM can complete it without additional context.
## Task Generation Rules
**CRITICAL**: Tasks MUST be organized by user story to enable independent implementation and testing.
**Tests are OPTIONAL**: Only generate test tasks if explicitly requested in the feature specification or if user requests TDD approach.
### Checklist Format (REQUIRED)
Every task MUST strictly follow this format:
```text
- [ ] [TaskID] [P?] [Story?] Description with file path
```
**Format Components**:
1. **Checkbox**: ALWAYS start with `- [ ]` (markdown checkbox)
2. **Task ID**: Sequential number (T001, T002, T003...) in execution order
3. **[P] marker**: Include ONLY if task is parallelizable (different files, no dependencies on incomplete tasks)
4. **[Story] label**: REQUIRED for user story phase tasks only
- Format: [US1], [US2], [US3], etc. (maps to user stories from spec.md)
- Setup phase: NO story label
- Foundational phase: NO story label
- User Story phases: MUST have story label
- Polish phase: NO story label
5. **Description**: Clear action with exact file path
**Examples**:
- ✅ CORRECT: `- [ ] T001 Create project structure per implementation plan`
- ✅ CORRECT: `- [ ] T005 [P] Implement authentication middleware in src/middleware/auth.py`
- ✅ CORRECT: `- [ ] T012 [P] [US1] Create User model in src/models/user.py`
- ✅ CORRECT: `- [ ] T014 [US1] Implement UserService in src/services/user_service.py`
- ❌ WRONG: `- [ ] Create User model` (missing ID and Story label)
- ❌ WRONG: `T001 [US1] Create model` (missing checkbox)
- ❌ WRONG: `- [ ] [US1] Create User model` (missing Task ID)
- ❌ WRONG: `- [ ] T001 [US1] Create model` (missing file path)
### Task Organization
1. **From User Stories (spec.md)** - PRIMARY ORGANIZATION:
- Each user story (P1, P2, P3...) gets its own phase
- Map all related components to their story:
- Models needed for that story
- Services needed for that story
- Interfaces/UI needed for that story
- If tests requested: Tests specific to that story
- Mark story dependencies (most stories should be independent)
2. **From Contracts**:
- Map each interface contract → to the user story it serves
- If tests requested: Each interface contract → contract test task [P] before implementation in that story's phase
3. **From Data Model**:
- 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
4. **From Setup/Infrastructure**:
- Shared infrastructure → Setup phase (Phase 1)
- Foundational/blocking tasks → Foundational phase (Phase 2)
- Story-specific setup → within that story's phase
### Phase Structure
- **Phase 1**: Setup (project initialization)
- **Phase 2**: Foundational (blocking prerequisites - MUST complete before user stories)
- **Phase 3+**: User Stories in priority order (P1, P2, P3...)
- Within each story: Tests (if requested) → Models → Services → Endpoints → Integration
- Each phase should be a complete, independently testable increment
- **Final Phase**: Polish & Cross-Cutting Concerns
## Done When
- [ ] tasks.md generated with all phases, task IDs, and file paths
- [ ] Extension hooks dispatched or skipped according to the rules in Mandatory Post-Execution Hooks above
- [ ] Completion reported to user with task count, story breakdown, and MVP scope
+110
View File
@@ -0,0 +1,110 @@
---
description: "Deprecated: Convert existing tasks into actionable, dependency-ordered GitHub issues for the feature based on available design artifacts."
tools: ['github/github-mcp-server/list_issues', 'github/github-mcp-server/issue_write']
---
## Deprecation Notice
You **MUST display the following concise warning first**, as the first step of this command and before the User Input and Pre-Execution Checks sections below:
> ⚠️ `/speckit.taskstoissues` is deprecated and will be removed in a future minor release. Use the bundled `github` extension instead: run `specify extension add github`, then invoke `/speckit.github.taskstoissues`.
Continue with the existing workflow unchanged. Do not install or enable the extension automatically, do not stop, and do not run the replacement command.
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Pre-Execution Checks
**Check for extension hooks (before tasks-to-issues conversion)**:
- Check if `.specify/extensions.yml` exists in the project root.
- If it exists, read it and look for entries under the `hooks.before_taskstoissues` key
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- For each executable hook, output the following based on its `optional` flag:
- **Optional hook** (`optional: true`):
```
## Extension Hooks
**Optional Pre-Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
- **Mandatory hook** (`optional: false`):
```
## Extension Hooks
**Automatic Pre-Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
Wait for the result of the hook command before proceeding to the Outline.
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently
## Outline
1. Run `.specify/scripts/bash/check-prerequisites.sh --json --require-tasks --include-tasks` from repo root and parse FEATURE_DIR and AVAILABLE_DOCS list. All paths must be absolute. 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").
1. **IF EXISTS**: Load `.specify/memory/constitution.md` for project principles and governance constraints.
1. From the executed script, extract the path to **tasks**.
1. Get the Git remote by running:
```bash
git config --get remote.origin.url
```
> [!CAUTION]
> ONLY PROCEED TO NEXT STEPS IF THE REMOTE IS A GITHUB URL
1. **Fetch existing issues for deduplication**: Before creating anything, build the set of task IDs you are about to process from `tasks.md` (each is a `T` followed by **at least** three digits, e.g. `T001` — `/speckit.converge` assigns new IDs with `T{M+1:03d}`, which is a floor rather than a cap, so once a file has more than 999 tasks the IDs are four digits or longer). Then use the GitHub MCP server's `list_issues` tool to look for issues that already cover those IDs. Do not pass a `state` value, since omitting it makes the tool return both open and closed issues. Request `perPage: 100` to keep the number of calls down, and since the tool uses cursor-based pagination, request pages with the `after` parameter (using the `endCursor` from the previous response). For each issue title, match it against the task ID pattern `\bT\d{3,}\b` (the `{3,}` accepts four-digit and longer IDs — with `\d{3}` a title containing `T1000` would not match at all, because the trailing `\b` cannot fall between two digits, so that task would be silently neither deduplicated nor created; word boundaries still stop a token like `ST001` from matching, and force the whole digit run to be consumed so `T100` can never match inside `T1000`; this also recognises titles written as `T001 ...`, `T001: ...` or `[T001] ...`) and, when it matches one of your task IDs, mark that ID as already having an issue. Stop paginating as soon as every task ID has been matched, or when there are no more pages, so you do not keep fetching the whole repository's issue history once all task IDs are accounted for. This bounds the number of calls on repos with large issue histories and still prevents duplicates when the command is re-run after `tasks.md` is regenerated or the skill is re-invoked.
1. For each task in the list, use the GitHub MCP server to create a new issue in the repository that is representative of the Git remote. Task lines in `tasks.md` start with a markdown checkbox, so first strip the leading `- [ ]` (and any `[P]` / `[US#]` markers) to recover the task ID and its description. Create the issue with a single canonical title of the form `T001: <description>`, with the ID written once followed by the task description (for example, the line `- [ ] T001 Create project structure` becomes the title `T001: Create project structure`).
- **Skip** any task whose ID is already present in the set of existing issues from the previous step, and report it (for example, `T001 already has an issue, skipping`).
- Only create issues for tasks that do not yet have a matching issue.
> [!CAUTION]
> UNDER NO CIRCUMSTANCES EVER CREATE ISSUES IN REPOSITORIES THAT DO NOT MATCH THE REMOTE URL
## Post-Execution Checks
**Check for extension hooks (after tasks-to-issues conversion)**:
Check if `.specify/extensions.yml` exists in the project root.
- If it exists, read it and look for entries under the `hooks.after_taskstoissues` key
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- For each executable hook, output the following based on its `optional` flag:
- **Optional hook** (`optional: true`):
```
## Extension Hooks
**Optional Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
- **Mandatory hook** (`optional: false`):
```
## Extension Hooks
**Automatic Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently
+10
View File
@@ -0,0 +1,10 @@
# Convergence / review handoff
Atomic guarded algorithm accepted by independent follow-up reviewer (deleg_46675de9); first review correctly rejected unit-only evidence. Source service/test hashes stayed unchanged across reviews. No commit/push/deploy performed because frontend full gates unresolved.
Actual results: backend 92 suites / 798 tests passed (2 suites / 3 tests skipped); targeted blogs 5 suites / 105 tests passed. Backend, admin, storefront builds passed. Admin current and clean HEAD archive with same dependencies both 1 failed /50 passed files,309 passed tests (missing ApprovalsPage import). Storefront current bounded180s and clean archive bounded120s timeout124, no completion summary; exact root cause unresolved. Baseline extracted inside owned worktree, no other worktree altered.
Isolated PostgreSQL18.4 + actual Prisma5.22 passed four microsecond boundary roundtrips, true concurrent reads-before-transactions one-winner race, loser tag absence and real nested unique failure complete-row/relations rollback plus cache counts. Daemon stopped. db push targeted only fresh local concurrency_test (not shared DB, no migration file). Actual production read-only metadata: revision0e952ef70184040a27a6b53d7b59073502d25743; Prisma5.22; timestamp with time zone precision6; compiled controller Object body; global whitelist; no deployed expectedUpdatedAt support. Deployed PG16 exact-major integration parity and nonnull author rollback fixture remain unproven. Legacy token omission remains last-write-wins.
Spec consistency: all core guarded acceptance criteria represented; HTTP/Nest request-level execution is not added, actual deployed compiled metatype inspected. Existing whitelist any-body contract intentionally retained, service allowlist consumes token separately. Constitution scaffold finalized late, not claimed preapproved.
Parent should resolve/waive existing frontend gates under policy before any Stage push, retain exact artifact review, rerun on deployed PG16 if required, then coordinate Stage deployment and pilot. No archive/blog mutation occurred here.
+1
View File
@@ -0,0 +1 @@
Graphify query: BlogsService update expectedUpdatedAt Prisma relations concurrency, BFS depth2, 133 nodes (57 displayed). Source graph is inherited and stale (BlogsService.updateBlog graph L144 versus current L276). Verified affected edges: admin controller -> service -> Prisma, revalidation; service tag/category/author nested mutation; public frontend freshness. Query stamped graphify-out/cache/last_query_stamp only; exclude incidental stamp from delivered diff. API change is additive optional field, no UI or schema changes.
+9
View File
@@ -0,0 +1,9 @@
{
"ai": "generic",
"allow_symlinks": false,
"feature_numbering": "sequential",
"here": true,
"integration": "generic",
"script": "sh",
"speckit_version": "1.2.3"
}
+19
View File
@@ -0,0 +1,19 @@
{
"version": "1.2.3",
"integration_state_schema": 1,
"installed_integrations": [
"generic"
],
"integration_settings": {
"generic": {
"script": "sh",
"raw_options": "--commands-dir .specify/commands/",
"parsed_options": {
"commands_dir": ".specify/commands/"
},
"invoke_separator": "."
}
},
"integration": "generic",
"default_integration": "generic"
}
@@ -0,0 +1,17 @@
{
"integration": "generic",
"version": "1.2.3",
"installed_at": "2026-10-27T07:16:59.909007+00:00",
"files": {
".specify/commands/speckit.analyze.md": "91fe16257ededdea9cc21d3cb27d539fcdd12d93ddcea52332cd4b68176b6a8d",
".specify/commands/speckit.clarify.md": "dd11eb5b9759f7d3cd18c9d7f23a0ae2fe7973fc6ca2486dbfaf53a5569224b1",
".specify/commands/speckit.constitution.md": "9a7e9296f0878cdf4ed011b0de74cfb3656938680b64e43e808553fdfd054efc",
".specify/commands/speckit.implement.md": "e036ce63702db93e656e1c91ee6c02a8dc3d4a4f8624f8ba4adc69027fe68983",
".specify/commands/speckit.converge.md": "3cb55244c9dc5b9bf52ee3127ba177c52cabd5e5e5197e1312497b3eaeb8b9a4",
".specify/commands/speckit.plan.md": "3be8b011db9c6bb1cc77037f7d90756a6dbcbda1995cda2192818385732b27ff",
".specify/commands/speckit.checklist.md": "fa58b19e2604ce56ff5f5427061f6ee94fd44d7194e740b874824d9bf21ee15b",
".specify/commands/speckit.specify.md": "21634a45dfcf642fddb1645f4ad2980f98c89778442e47663df8a6c3a1eaf8bc",
".specify/commands/speckit.tasks.md": "6754ae39649c8e73a5ed376ad5cfcf04422e321a10e07c5ccd92fd1b9bccf776",
".specify/commands/speckit.taskstoissues.md": "6a23057adb077af03f6d7c99a8cc3fdfd699ad72975b7d5e1457659732955095"
}
}
@@ -0,0 +1,19 @@
{
"integration": "speckit",
"version": "1.2.3",
"installed_at": "2026-10-27T07:16:59.975057+00:00",
"files": {
".specify/scripts/bash/check-prerequisites.sh": "ac3d9bfd836c4e873bfb8fb5d898ba4c1d2f80d3488c2298148408a3830ac8d1",
".specify/scripts/bash/setup-plan.sh": "d378ec66ba20d2da01c71dad8935062c1c27f0bba890be9a6d3dda52ea056a4e",
".specify/scripts/bash/common.sh": "53cb1c23e349db4586c272436ce35c6e2f36a9c0b5351a85e0b216d9887a26b7",
".specify/scripts/bash/setup-tasks.sh": "cf6e99575a24b64ac01ffa3a50a40971ba95e3c1ec269b9a6dc3e35bbbb09191",
".specify/scripts/bash/resolve-template.sh": "829e227096abc8bf0889889ec9f792f503ca5d395b7836a8a7eb739ee75214e7",
".specify/scripts/bash/create-new-feature.sh": "972f03ed8ca5ee17b7baad6d56d821d46269d77abc337496beafb0fe85a725f2",
".specify/templates/plan-template.md": "5ef0e4c97b36e9f91372dc6eb8e5a7e515af8958cf1a9286e43a1ebd9bd48540",
".specify/templates/constitution-template.md": "ce7549540fa45543cca797a150201d868e64495fdff39dc38246fb17bd4024b3",
".specify/templates/tasks-template.md": "c731575d8099b3f871861186fbd1a592b51b2ba57fb99e1a0dab439ff6d5608f",
".specify/templates/checklist-template.md": "3f4124a13ffbc0c2d8e979d9a08248f29ce53cc6c324a8303a6ae0d231b78836",
".specify/templates/spec-template.md": "3945437fc35cd30a5b2bf7beea680337c3516826d3efa5a6b92c4a7eca1ba28e",
".specify/.gitignore": "0a61c5378b0bb2e0f85babff99c8b166f2170a2c12378cd17d929aa19296ec88"
}
}
@@ -0,0 +1,4 @@
{
"sha256": "ce7549540fa45543cca797a150201d868e64495fdff39dc38246fb17bd4024b3",
"source": "core"
}
+5
View File
@@ -0,0 +1,5 @@
# Canina concurrency prerequisite constitution
Preserve existing worktree edits. Graphify impact and written spec/plan/tasks precede source edits. TDD requires recorded RED then GREEN. Real DB concurrency and rollback evidence complements unit doubles; synthetic test fixtures only in isolated disposable databases, never production content. No production deployments, migrations or blog/media mutations in this task. Optional concurrency tokens preserve legacy UI behavior explicitly. Cache failure cannot fail already committed persistence. Independent exact-artifact review precedes any Stage push; failed full-suite gates are not green.
Version 1.0.0; scoped to this prerequisite. Scaffold initially existed as template; finalized after implementation rather than falsely backdating approval.
+5
View File
@@ -0,0 +1,5 @@
# Plan and clarified contract
Base develop 0e952ef70184040a27a6b53d7b59073502d25743 fetched via verified nested SSH proxy (origin is local bundle).
Graphify query before editing identified BlogsController -> BlogsService -> PrismaService and RevalidationService; graph source locations service update L144 and controller L29 are old, so inspect current source. Actual source has PUT admin/blogs/:id @Body any, not public UpdateBlogDto. Global whitelist is skipped for Object/any metatype, so service explicit scalar allowlist is authoritative; expectedUpdatedAt is consumed separately, never persisted. UI omission remains accepted.
Blog.updatedAt is @db.Timestamptz() (PostgreSQL default precision 6), @updatedAt. JS/JSON tokens have millisecond precision. CAS predicate uses [token,token+1ms), not exact equality to truncated DB value. Atomic claim via blog.updateMany inside interactive transaction, advancing updatedAt strictly beyond token millisecond; if count !=1 throw 409. Then nested blog.update (author/category/tags) in same transaction, retaining claimed timestamp. Relation failures roll back claim. No relation writes outside transaction. Revalidation occurs after transaction resolves only. Invalid tokens restricted to timezone-qualified ISO string with <=3 fractional digits and valid calendar round-trip; no coercive Date/null/number acceptance.
Deployed runtime version/column precision still need read-only release evidence; source evidence is not deployed proof. No writes to shared services during validation.
+249
View File
@@ -0,0 +1,249 @@
#!/usr/bin/env bash
# Consolidated prerequisite checking script
#
# This script provides unified prerequisite checking for Spec-Driven Development workflow.
# It replaces the functionality previously spread across multiple scripts.
#
# Usage: ./check-prerequisites.sh [OPTIONS]
#
# OPTIONS:
# --json Output in JSON format
# --require-spec Require spec.md to exist (for analysis phase)
# --require-tasks Require tasks.md to exist (for implementation phase)
# --include-tasks Include tasks.md in AVAILABLE_DOCS list
# --paths-only Only output path variables (no validation)
# --template NAME Include composed template content in JSON output
# --help, -h Show help message
#
# OUTPUTS:
# JSON mode: {"FEATURE_DIR":"...", "AVAILABLE_DOCS":["..."]}
# Text mode: FEATURE_DIR:... \n AVAILABLE_DOCS: \n ✓/✗ file.md
# Paths only: REPO_ROOT: ... \n BRANCH: ... \n FEATURE_DIR: ... etc.
set -e
# Parse command line arguments
JSON_MODE=false
REQUIRE_SPEC=false
REQUIRE_TASKS=false
INCLUDE_TASKS=false
PATHS_ONLY=false
TEMPLATE_NAME=""
while [[ $# -gt 0 ]]; do
case "$1" in
--json)
JSON_MODE=true
;;
--require-spec)
REQUIRE_SPEC=true
;;
--require-tasks)
REQUIRE_TASKS=true
;;
--include-tasks)
INCLUDE_TASKS=true
;;
--paths-only)
PATHS_ONLY=true
;;
--template)
shift
if [[ $# -eq 0 ]]; then
echo "ERROR: --template requires a template name" >&2
exit 1
fi
TEMPLATE_NAME="$1"
;;
--help|-h)
cat << 'EOF'
Usage: check-prerequisites.sh [OPTIONS]
Consolidated prerequisite checking for Spec-Driven Development workflow.
OPTIONS:
--json Output in JSON format
--require-spec Require spec.md to exist (for analysis phase)
--require-tasks Require tasks.md to exist (for implementation phase)
--include-tasks Include tasks.md in AVAILABLE_DOCS list
--paths-only Only output path variables (no prerequisite validation)
--template NAME Include composed template content in JSON output
--help, -h Show this help message
EXAMPLES:
# Check task prerequisites (plan.md required)
./check-prerequisites.sh --json
# Check implementation prerequisites (plan.md + tasks.md required)
./check-prerequisites.sh --json --require-tasks --include-tasks
# Get feature paths only (no validation)
./check-prerequisites.sh --paths-only
EOF
exit 0
;;
*)
echo "ERROR: Unknown option '$1'. Use --help for usage information." >&2
exit 1
;;
esac
shift
done
# Source common functions
SCRIPT_DIR="$(CDPATH="" cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/common.sh"
# Get feature paths.
# In --paths-only mode this is pure resolution, so pass --no-persist to opt out
# of the feature.json write side effect (issue #3025).
if $PATHS_ONLY; then
_paths_output=$(get_feature_paths --no-persist) || { echo "ERROR: Failed to resolve feature paths" >&2; exit 1; }
else
_paths_output=$(get_feature_paths) || { echo "ERROR: Failed to resolve feature paths" >&2; exit 1; }
fi
eval "$_paths_output"
unset _paths_output
# If paths-only mode, output paths and exit (no validation)
if $PATHS_ONLY; then
if $JSON_MODE; then
# Minimal JSON paths payload (no validation performed)
if has_jq; then
jq -cn \
--arg repo_root "$REPO_ROOT" \
--arg branch "$CURRENT_BRANCH" \
--arg feature_dir "$FEATURE_DIR" \
--arg feature_spec "$FEATURE_SPEC" \
--arg impl_plan "$IMPL_PLAN" \
--arg tasks "$TASKS" \
'{REPO_ROOT:$repo_root,BRANCH:$branch,FEATURE_DIR:$feature_dir,FEATURE_SPEC:$feature_spec,IMPL_PLAN:$impl_plan,TASKS:$tasks}'
else
printf '{"REPO_ROOT":"%s","BRANCH":"%s","FEATURE_DIR":"%s","FEATURE_SPEC":"%s","IMPL_PLAN":"%s","TASKS":"%s"}\n' \
"$(json_escape "$REPO_ROOT")" "$(json_escape "$CURRENT_BRANCH")" "$(json_escape "$FEATURE_DIR")" "$(json_escape "$FEATURE_SPEC")" "$(json_escape "$IMPL_PLAN")" "$(json_escape "$TASKS")"
fi
else
echo "REPO_ROOT: $REPO_ROOT"
echo "BRANCH: $CURRENT_BRANCH"
echo "FEATURE_DIR: $FEATURE_DIR"
echo "FEATURE_SPEC: $FEATURE_SPEC"
echo "IMPL_PLAN: $IMPL_PLAN"
echo "TASKS: $TASKS"
fi
exit 0
fi
# Validate required directories and files
if [[ ! -d "$FEATURE_DIR" ]]; then
echo "ERROR: Feature directory not found: $FEATURE_DIR" >&2
echo "Run /speckit.specify first to create the feature structure." >&2
exit 1
fi
if [[ ! -f "$IMPL_PLAN" ]]; then
echo "ERROR: plan.md not found in $FEATURE_DIR" >&2
echo "Run /speckit.plan first to create the implementation plan." >&2
exit 1
fi
if [[ ! -s "$IMPL_PLAN" ]]; then
echo "ERROR: plan.md is empty in $FEATURE_DIR" >&2
echo "Populate it, or remove the empty file and rerun /speckit.plan with a valid plan template." >&2
exit 1
fi
# Check for spec.md if required
if $REQUIRE_SPEC && [[ ! -f "$FEATURE_SPEC" ]]; then
echo "ERROR: spec.md not found in $FEATURE_DIR" >&2
echo "Run /speckit.specify first to create the feature specification." >&2
exit 1
fi
# Check for tasks.md if required
if $REQUIRE_TASKS && [[ ! -f "$TASKS" ]]; then
echo "ERROR: tasks.md not found in $FEATURE_DIR" >&2
echo "Run /speckit.tasks first to create the task list." >&2
exit 1
fi
# Build list of available documents
docs=()
# Always check these optional docs
[[ -f "$RESEARCH" ]] && docs+=("research.md")
[[ -f "$DATA_MODEL" ]] && docs+=("data-model.md")
# Check contracts directory (only if it exists and has files)
if [[ -d "$CONTRACTS_DIR" ]] && [[ -n "$(ls -A "$CONTRACTS_DIR" 2>/dev/null)" ]]; then
docs+=("contracts/")
fi
[[ -f "$QUICKSTART" ]] && docs+=("quickstart.md")
# Include tasks.md if requested and it exists
if $INCLUDE_TASKS && [[ -f "$TASKS" ]]; then
docs+=("tasks.md")
fi
TEMPLATE_CONTENT=""
if [[ -n "$TEMPLATE_NAME" ]]; then
if TEMPLATE_CONTENT=$(resolve_template_content "$TEMPLATE_NAME" "$REPO_ROOT"; status=$?; printf x; exit "$status"); then
TEMPLATE_CONTENT="${TEMPLATE_CONTENT%x}"
else
echo "ERROR: Could not resolve required $TEMPLATE_NAME from the template override stack for $REPO_ROOT" >&2
exit 1
fi
fi
# Output results
if $JSON_MODE; then
# Build JSON array of documents
if has_jq; then
if [[ ${#docs[@]} -eq 0 ]]; then
json_docs="[]"
else
json_docs=$(printf '%s\n' "${docs[@]}" | jq -R . | jq -s .)
fi
if [[ -n "$TEMPLATE_NAME" ]]; then
jq -cn \
--arg feature_dir "$FEATURE_DIR" \
--argjson docs "$json_docs" \
--arg template_content "$TEMPLATE_CONTENT" \
'{FEATURE_DIR:$feature_dir,AVAILABLE_DOCS:$docs,TEMPLATE_CONTENT:$template_content}'
else
jq -cn \
--arg feature_dir "$FEATURE_DIR" \
--argjson docs "$json_docs" \
'{FEATURE_DIR:$feature_dir,AVAILABLE_DOCS:$docs}'
fi
else
if [[ ${#docs[@]} -eq 0 ]]; then
json_docs="[]"
else
json_docs=$(for d in "${docs[@]}"; do printf '"%s",' "$(json_escape "$d")"; done)
json_docs="[${json_docs%,}]"
fi
if [[ -n "$TEMPLATE_NAME" ]]; then
printf '{"FEATURE_DIR":"%s","AVAILABLE_DOCS":%s,"TEMPLATE_CONTENT":"%s"}\n' \
"$(json_escape "$FEATURE_DIR")" "$json_docs" "$(json_escape "$TEMPLATE_CONTENT")"
else
printf '{"FEATURE_DIR":"%s","AVAILABLE_DOCS":%s}\n' "$(json_escape "$FEATURE_DIR")" "$json_docs"
fi
fi
else
# Text output
echo "FEATURE_DIR:$FEATURE_DIR"
echo "AVAILABLE_DOCS:"
# Show status of each potential document
check_file "$RESEARCH" "research.md"
check_file "$DATA_MODEL" "data-model.md"
check_dir "$CONTRACTS_DIR" "contracts/"
check_file "$QUICKSTART" "quickstart.md"
if $INCLUDE_TASKS; then
check_file "$TASKS" "tasks.md"
fi
fi
+942
View File
@@ -0,0 +1,942 @@
#!/usr/bin/env bash
# Common functions and variables for all scripts
# Find repository root by searching upward for .specify directory
# This is the primary marker for spec-kit projects
find_specify_root() {
local dir="${1:-$(pwd)}"
# Normalize to absolute path to prevent infinite loop with relative paths
# Use -- to handle paths starting with - (e.g., -P, -L)
dir="$(cd -- "$dir" 2>/dev/null && pwd)" || return 1
local prev_dir=""
while true; do
if [ -d "$dir/.specify" ]; then
echo "$dir"
return 0
fi
# Stop if we've reached filesystem root or dirname stops changing
if [ "$dir" = "/" ] || [ "$dir" = "$prev_dir" ]; then
break
fi
prev_dir="$dir"
dir="$(dirname "$dir")"
done
return 1
}
# Resolve an explicit SPECIFY_INIT_DIR project override (the directory that
# *contains* .specify/), for non-interactive / CI use — e.g. running a Spec Kit
# command against a member project from a monorepo root without cd.
#
# Precondition: SPECIFY_INIT_DIR is non-empty. Echoes the validated absolute
# project root, or prints an error and returns 1. Strict by design: the path
# must exist and contain .specify/, with no silent fallback to cwd or the
# script-location default (which would silently write to the wrong project).
#
# This is the single resolver: bundled extensions inherit it by sourcing core
# (e.g. the git extension's create-new-feature-branch) rather than duplicating it.
resolve_specify_init_dir() {
local init_root
# Normalize: relative paths resolve against $(pwd); a trailing slash collapses.
# CDPATH="" so a relative value cannot be resolved against the caller's CDPATH
# (which would also echo to stdout and corrupt the captured path).
if ! init_root="$(CDPATH="" cd -- "$SPECIFY_INIT_DIR" 2>/dev/null && pwd)"; then
echo "ERROR: SPECIFY_INIT_DIR does not point to an existing directory: $SPECIFY_INIT_DIR" >&2
return 1
fi
if [[ ! -d "$init_root/.specify" ]]; then
echo "ERROR: SPECIFY_INIT_DIR is not a Spec Kit project (no .specify/ directory): $init_root" >&2
return 1
fi
printf '%s\n' "$init_root"
}
# Get repository root, prioritizing .specify directory
# This prevents using a parent repository when spec-kit is initialized in a subdirectory
get_repo_root() {
# Explicit project override wins (see resolve_specify_init_dir).
if [[ -n "${SPECIFY_INIT_DIR:-}" ]]; then
resolve_specify_init_dir
return
fi
# First, look for .specify directory (spec-kit's own marker)
local specify_root
if specify_root=$(find_specify_root); then
echo "$specify_root"
return
fi
# Final fallback to script location
local script_dir="$(CDPATH="" cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
(cd "$script_dir/../../.." && pwd)
}
# Get current feature name from explicit state only.
# Returns the feature identifier or empty string if none is set.
# Feature state is set by SPECIFY_FEATURE (from create-new-feature or
# the git extension) or implicitly via .specify/feature.json.
get_current_branch() {
if [[ -n "${SPECIFY_FEATURE:-}" ]]; then
echo "$SPECIFY_FEATURE"
return
fi
# No explicit feature set — caller must handle this via feature.json
# in get_feature_paths(). Return empty to signal "unknown".
echo ""
}
# Safely read .specify/feature.json's "feature_directory" value.
# Prints the raw value (possibly relative) to stdout, or empty string if the file
# is missing, unparseable, or does not contain the key. Always returns 0 so callers
# under `set -e` cannot be aborted by parser failure.
# Parser order mirrors the historical get_feature_paths behavior: jq -> python3 -> grep/sed.
read_feature_json_feature_directory() {
local repo_root="$1"
local fj="$repo_root/.specify/feature.json"
[[ -f "$fj" ]] || { printf '%s' ''; return 0; }
# Try parsers in order (jq -> python3 -> grep/sed), falling through on
# failure. Selection is by *parse success*, not mere availability: on
# Windows `python3` commonly resolves to the Microsoft Store App Execution
# Alias stub, which passes `command -v` but fails at runtime (exit 49), so
# an availability-gated `elif` would pick python3, swallow its failure, and
# never reach the grep/sed fallback -- leaving feature.json unreadable even
# though it is valid (issue #3304).
local _fd=''
if command -v jq >/dev/null 2>&1; then
if ! _fd=$(jq -r '.feature_directory // empty' "$fj" 2>/dev/null); then
_fd=''
fi
fi
if [[ -z "$_fd" ]] && command -v python3 >/dev/null 2>&1; then
# Use Python so pretty-printed/multi-line JSON still parses correctly.
if ! _fd=$(python3 -c "import json,sys; d=json.load(open(sys.argv[1], encoding='utf-8')); v=d.get('feature_directory'); print(v if v else '')" "$fj" 2>/dev/null); then
_fd=''
fi
fi
if [[ -z "$_fd" ]]; then
# Last-resort single-line grep/sed fallback. The `|| true` guards against
# grep returning 1 (no match) aborting under `set -e` / `pipefail`.
_fd=$( { grep -E '"feature_directory"[[:space:]]*:' "$fj" 2>/dev/null || true; } \
| head -n 1 \
| sed -E 's/^[^:]*:[[:space:]]*"([^"]*)".*$/\1/' )
fi
printf '%s' "$_fd"
return 0
}
# Persist a feature_directory value to .specify/feature.json.
# Writes only when the file is missing or the value differs from what's stored.
# Accepts the raw (possibly relative) path — callers should pass the original
# user-supplied value, not the normalized absolute path.
_persist_feature_json() {
local repo_root="$1"
local feature_dir_value="$2"
local fj="$repo_root/.specify/feature.json"
# Strip repo_root prefix if the value is absolute and under repo_root
if [[ "$feature_dir_value" == "$repo_root/"* ]]; then
feature_dir_value="${feature_dir_value#"$repo_root/"}"
fi
# Read current value (if any) and skip write when unchanged
local current_val
current_val=$(read_feature_json_feature_directory "$repo_root")
if [[ "$current_val" == "$feature_dir_value" ]]; then
return 0
fi
# Ensure .specify/ directory exists
mkdir -p "$repo_root/.specify"
# Write feature.json — prefer jq for safe JSON, fall back to printf
if command -v jq >/dev/null 2>&1; then
jq -cn --arg fd "$feature_dir_value" '{feature_directory:$fd}' > "$fj"
else
printf '{"feature_directory":"%s"}\n' "$(json_escape "$feature_dir_value")" > "$fj"
fi
}
get_feature_paths() {
# Read-only callers (e.g. check-prerequisites.sh --paths-only) pass
# --no-persist so pure path resolution never writes .specify/feature.json,
# which would dirty the working tree or overwrite a pinned value (issue #3025).
local no_persist=false
if [[ "${1:-}" == "--no-persist" ]]; then
no_persist=true
shift
fi
# SPECIFY_FEATURE_NO_PERSIST is the environment-level equivalent of --no-persist,
# letting an orchestrator (multi-agent runner, CI matrix) guarantee that no
# script invocation in the process tree writes .specify/feature.json, even
# scripts that don't pass --no-persist themselves (#4128).
if [[ "${SPECIFY_FEATURE_NO_PERSIST:-}" == "1" || "${SPECIFY_FEATURE_NO_PERSIST:-}" == "true" ]]; then
no_persist=true
fi
# Split decl/assignment so a SPECIFY_INIT_DIR validation failure in
# get_repo_root propagates as a hard error instead of being masked by `local`.
local repo_root
repo_root=$(get_repo_root) || return 1
local current_branch
current_branch=$(get_current_branch)
# Resolve feature directory. Priority:
# 1. SPECIFY_FEATURE_DIRECTORY env var (explicit override)
# 2. .specify/feature.json "feature_directory" key (persisted by specify command)
# 3. Error — no feature context available
local feature_dir
if [[ -n "${SPECIFY_FEATURE_DIRECTORY:-}" ]]; then
feature_dir="$SPECIFY_FEATURE_DIRECTORY"
# Normalize relative paths to absolute under repo root
[[ "$feature_dir" != /* ]] && feature_dir="$repo_root/$feature_dir"
# Persist to feature.json so future sessions without the env var still
# work — unless the caller opted out for read-only resolution (#3025).
if [[ "$no_persist" != true ]]; then
_persist_feature_json "$repo_root" "$SPECIFY_FEATURE_DIRECTORY"
fi
elif [[ -f "$repo_root/.specify/feature.json" ]]; then
local _fd
_fd=$(read_feature_json_feature_directory "$repo_root")
if [[ -n "$_fd" ]]; then
feature_dir="$_fd"
# Normalize relative paths to absolute under repo root
[[ "$feature_dir" != /* ]] && feature_dir="$repo_root/$feature_dir"
else
echo "ERROR: Feature directory not found. Set SPECIFY_FEATURE_DIRECTORY or ensure .specify/feature.json contains feature_directory." >&2
return 1
fi
else
echo "ERROR: Feature directory not found. Set SPECIFY_FEATURE_DIRECTORY or run the specify command to create .specify/feature.json." >&2
return 1
fi
# When no branch context exists (no SPECIFY_FEATURE, feature resolved via
# SPECIFY_FEATURE_DIRECTORY or feature.json), fall back to the feature
# directory basename so CURRENT_BRANCH is a usable identifier rather than
# an empty, misleading value (issue #3026).
if [[ -z "$current_branch" ]]; then
local feature_dir_trimmed="${feature_dir%/}"
current_branch="${feature_dir_trimmed##*/}"
fi
# Use printf '%q' to safely quote values, preventing shell injection
# via crafted branch names or paths containing special characters
printf 'REPO_ROOT=%q\n' "$repo_root"
printf 'CURRENT_BRANCH=%q\n' "$current_branch"
printf 'FEATURE_DIR=%q\n' "$feature_dir"
printf 'FEATURE_SPEC=%q\n' "$feature_dir/spec.md"
printf 'IMPL_PLAN=%q\n' "$feature_dir/plan.md"
printf 'TASKS=%q\n' "$feature_dir/tasks.md"
printf 'RESEARCH=%q\n' "$feature_dir/research.md"
printf 'DATA_MODEL=%q\n' "$feature_dir/data-model.md"
printf 'QUICKSTART=%q\n' "$feature_dir/quickstart.md"
printf 'CONTRACTS_DIR=%q\n' "$feature_dir/contracts"
}
# Check if jq is available for safe JSON construction
has_jq() {
command -v jq >/dev/null 2>&1
}
get_invoke_separator() {
local repo_root="${1:-$(get_repo_root)}"
if [[ "${_SPECIFY_INVOKE_SEPARATOR_CACHE_REPO_ROOT:-}" == "$repo_root" && -n "${_SPECIFY_INVOKE_SEPARATOR_CACHE_VALUE:-}" ]]; then
printf '%s\n' "$_SPECIFY_INVOKE_SEPARATOR_CACHE_VALUE"
return 0
fi
local integration_json="$repo_root/.specify/integration.json"
local separator="."
local parsed=0
if [[ -f "$integration_json" ]]; then
# Try parsers in order (jq -> python3 -> awk), falling through on
# failure. Selection is by *parse success*, not mere availability: on
# Windows `python3` commonly resolves to the Microsoft Store App
# Execution Alias stub, which passes `command -v` but fails at runtime
# (exit 49). An availability-gated branch would pick python3, swallow
# its failure, and — because this function historically had no text
# fallback — silently return "." even for `-`-separator integrations
# (e.g. forge, cline), yielding wrong command hints (issue #3304).
if command -v jq >/dev/null 2>&1; then
local jq_separator
if jq_separator=$(jq -r '(.default_integration // .integration // "") as $k | if $k == "" then "." else (.integration_settings[$k].invoke_separator // ".") end' "$integration_json" 2>/dev/null); then
case "$jq_separator" in
"."|"-") separator="$jq_separator"; parsed=1 ;;
esac
fi
fi
if [[ "$parsed" -eq 0 ]] && command -v python3 >/dev/null 2>&1; then
local py_separator
if py_separator=$(python3 - "$integration_json" <<'PY' 2>/dev/null
import json
import sys
try:
with open(sys.argv[1], encoding="utf-8") as fh:
state = json.load(fh)
key = state.get("default_integration") or state.get("integration") or ""
settings = state.get("integration_settings")
separator = "."
if isinstance(key, str) and isinstance(settings, dict):
entry = settings.get(key)
if isinstance(entry, dict) and entry.get("invoke_separator") in {".", "-"}:
separator = entry["invoke_separator"]
print(separator)
except Exception:
sys.exit(1)
PY
); then
case "$py_separator" in
"."|"-") separator="$py_separator"; parsed=1 ;;
esac
fi
fi
if [[ "$parsed" -eq 0 ]]; then
# Last-resort text fallback for environments with neither jq nor a
# working python3 (e.g. stock Windows + Git Bash). Reads the active
# integration key (default_integration, else integration) and its
# invoke_separator from within the integration_settings object.
# Handles both pretty-printed (the written form) and compact JSON.
# Accumulate all lines into one buffer in END rather than using
# gawk-only whole-file slurp (RS="^$"), so this stays portable to
# the BSD awk on macOS.
local awk_separator
awk_separator=$(awk '
function keyval(d, name, v) {
if (match(d, "\"" name "\"[ \t\r\n]*:[ \t\r\n]*\"[^\"]*\"")) {
v=substr(d,RSTART,RLENGTH); sub(/^.*:[ \t\r\n]*"/,"",v); sub(/"$/,"",v); return v
}
return ""
}
{ doc = doc $0 "\n" }
END {
key=keyval(doc,"default_integration"); if (key=="") key=keyval(doc,"integration")
sep="."
if (key!="") {
settings=doc
if (match(doc, /"integration_settings"[ \t\r\n]*:[ \t\r\n]*[{]/)) {
settings=substr(doc, RSTART+RLENGTH-1)
}
if (match(settings, "\"" key "\"[ \t\r\n]*:[ \t\r\n]*[{]")) {
start=RSTART+RLENGTH-1
depth=0
obj=""
for (i=start; i<=length(settings); i++) {
c=substr(settings,i,1)
obj=obj c
if (c=="{") depth++
else if (c=="}") { depth--; if (depth==0) break }
}
if (match(obj, /"invoke_separator"[ \t\r\n]*:[ \t\r\n]*"[-.]"/)) {
tok=substr(obj,RSTART,RLENGTH); s=substr(tok,length(tok)-1,1)
if (s=="." || s=="-") sep=s
}
}
}
print sep
}
' "$integration_json" 2>/dev/null)
case "$awk_separator" in
"."|"-") separator="$awk_separator" ;;
esac
fi
fi
_SPECIFY_INVOKE_SEPARATOR_CACHE_REPO_ROOT="$repo_root"
_SPECIFY_INVOKE_SEPARATOR_CACHE_VALUE="$separator"
printf '%s\n' "$separator"
}
format_speckit_command() {
local command_name="$1"
local repo_root="${2:-$(get_repo_root)}"
local separator
if [[ "${_SPECIFY_INVOKE_SEPARATOR_CACHE_REPO_ROOT:-}" == "$repo_root" && -n "${_SPECIFY_INVOKE_SEPARATOR_CACHE_VALUE:-}" ]]; then
separator="$_SPECIFY_INVOKE_SEPARATOR_CACHE_VALUE"
else
separator=$(get_invoke_separator "$repo_root")
_SPECIFY_INVOKE_SEPARATOR_CACHE_REPO_ROOT="$repo_root"
_SPECIFY_INVOKE_SEPARATOR_CACHE_VALUE="$separator"
fi
command_name="${command_name#/}"
command_name="${command_name#speckit.}"
command_name="${command_name#speckit-}"
command_name="${command_name//./$separator}"
printf '/speckit%s%s\n' "$separator" "$command_name"
}
# Escape a string for safe embedding in a JSON value (fallback when jq is unavailable).
# Handles backslash, double-quote, and JSON-required control character escapes (RFC 8259).
json_escape() {
local s="$1"
s="${s//\\/\\\\}"
s="${s//\"/\\\"}"
s="${s//$'\n'/\\n}"
s="${s//$'\t'/\\t}"
s="${s//$'\r'/\\r}"
s="${s//$'\b'/\\b}"
s="${s//$'\f'/\\f}"
# Escape any remaining U+0001-U+001F control characters as \uXXXX.
# (U+0000/NUL cannot appear in bash strings and is excluded.)
# LC_ALL=C ensures ${#s} counts bytes and ${s:$i:1} yields single bytes,
# so multi-byte UTF-8 sequences (first byte >= 0xC0) pass through intact.
local LC_ALL=C
local i char code
for (( i=0; i<${#s}; i++ )); do
char="${s:$i:1}"
printf -v code '%d' "'$char" 2>/dev/null || code=256
if (( code >= 1 && code <= 31 )); then
printf '\\u%04x' "$code"
else
printf '%s' "$char"
fi
done
}
check_file() { [[ -f "$1" ]] && echo " ✓ $2" || echo " ✗ $2"; }
check_dir() { [[ -d "$1" && -n $(ls -A "$1" 2>/dev/null) ]] && echo " ✓ $2" || echo " ✗ $2"; }
_python3_command() {
# SPECKIT_PYTHON_EXECUTABLE is the canonical override; SPECKIT_PYTHON is
# kept as a deprecated fallback (still used by update-agent-context.sh).
local override="${SPECKIT_PYTHON_EXECUTABLE:-${SPECKIT_PYTHON:-}}"
if [[ -n "$override" ]] && command -v "$override" >/dev/null 2>&1 &&
"$override" -c 'import sys; raise SystemExit(sys.version_info.major != 3)' >/dev/null 2>&1 &&
"$override" -c 'import yaml' >/dev/null 2>&1; then
printf '%s\n' "$override"
elif command -v python3 >/dev/null 2>&1 &&
python3 -c 'import sys; raise SystemExit(sys.version_info.major != 3)' >/dev/null 2>&1; then
printf '%s\n' "python3"
elif command -v python >/dev/null 2>&1 &&
python -c 'import sys; raise SystemExit(sys.version_info.major != 3)' >/dev/null 2>&1; then
printf '%s\n' "python"
elif command -v py >/dev/null 2>&1 &&
py -3 -c 'import sys' >/dev/null 2>&1; then
printf '%s\n' "py" "-3"
else
return 1
fi
}
_sorted_extension_ids() {
local ext_dir="$1"
local -a python_cmd=()
local _python_cmd_line
while IFS= read -r _python_cmd_line; do
python_cmd+=("$_python_cmd_line")
done < <(_python3_command)
if [ "${#python_cmd[@]}" -gt 0 ]; then
local py_stderr sorted_ids
py_stderr=$(mktemp)
if sorted_ids=$(SPECKIT_EXTENSIONS="$ext_dir" "${python_cmd[@]}" -c "
import json, os, re, sys
from pathlib import Path
root = Path(os.environ['SPECKIT_EXTENSIONS'])
registered = {}
registry = root / '.registry'
if os.path.lexists(registry):
if not registry.is_file():
print('registry_invalid: not a regular file', file=sys.stderr)
sys.exit(1)
try:
data = json.loads(registry.read_text(encoding='utf-8'))
except Exception as exc:
print('registry_invalid: ' + str(exc), file=sys.stderr)
sys.exit(1)
if not isinstance(data, dict):
print('registry_invalid: root must be a mapping', file=sys.stderr)
sys.exit(1)
raw_extensions = data.get('extensions', {})
if not isinstance(raw_extensions, dict):
print('registry_invalid: extensions must be a mapping', file=sys.stderr)
sys.exit(1)
registered = raw_extensions
def priority(value):
if isinstance(value, bool):
return 10
try:
parsed = int(value)
return parsed if parsed >= 1 else 10
except (TypeError, ValueError, OverflowError):
return 10
ranked = []
for ext_id, meta in registered.items():
if isinstance(ext_id, str) and re.fullmatch(r'[a-z0-9-]+', ext_id) and isinstance(meta, dict) and bool(meta.get('enabled', True)):
ranked.append((priority(meta.get('priority')), ext_id))
for path in root.iterdir():
if path.is_dir() and re.fullmatch(r'[a-z0-9-]+', path.name) and path.name not in registered:
ranked.append((10, path.name))
for _, ext_id in sorted(ranked):
print(ext_id)
" 2>"$py_stderr"); then
rm -f "$py_stderr"
printf '%s\n' "$sorted_ids"
return 0
else
echo "Error: invalid extension registry $ext_dir/.registry" >&2
rm -f "$py_stderr"
return 1
fi
fi
if [ -e "$ext_dir/.registry" ] || [ -L "$ext_dir/.registry" ]; then
if [ ! -f "$ext_dir/.registry" ] || [ ! -r "$ext_dir/.registry" ]; then
echo "Error: invalid extension registry $ext_dir/.registry" >&2
return 1
fi
echo "Error: Python 3 is required to honor the extension registry" >&2
return 2
fi
local ext extension_id
for ext in "$ext_dir"/*/; do
[ -d "$ext" ] || continue
extension_id=$(basename "$ext")
case "$extension_id" in *[!a-z0-9-]*) continue ;; esac
printf '%s\n' "$extension_id"
done
}
# Resolve a template name to a file path using the priority stack:
# 1. .specify/templates/overrides/
# 2. .specify/presets/<preset-id>/templates/ (sorted by priority from .registry)
# 3. .specify/extensions/<ext-id>/templates/
# 4. .specify/templates/ (core)
resolve_template() {
local template_name="$1"
local repo_root="$2"
local base="$repo_root/.specify/templates"
case "$template_name" in ""|*[!a-z0-9-]*) return 1 ;; esac
# Priority 1: Project overrides
local override="$base/overrides/${template_name}.md"
[ -f "$override" ] && echo "$override" && return 0
# Priority 2: Installed presets (sorted by priority from .registry)
local presets_dir="$repo_root/.specify/presets"
if [ -d "$presets_dir" ]; then
local registry_file="$presets_dir/.registry"
local -a python_cmd=()
local _python_cmd_line
while IFS= read -r _python_cmd_line; do
python_cmd+=("$_python_cmd_line")
done < <(_python3_command)
if [ -f "$registry_file" ] && [ "${#python_cmd[@]}" -gt 0 ]; then
# Read preset IDs sorted by priority (lower number = higher precedence).
# The python3 call is wrapped in an if-condition so that set -e does not
# abort the function when python3 exits non-zero (e.g. invalid JSON).
local sorted_presets=""
if sorted_presets=$(SPECKIT_REGISTRY="$registry_file" "${python_cmd[@]}" -c "
import json, re, sys, os
try:
with open(os.environ['SPECKIT_REGISTRY'], encoding='utf-8') as f:
data = json.load(f)
presets = data.get('presets', {})
def priority(meta):
if not isinstance(meta, dict) or isinstance(meta.get('priority'), bool):
return 10
try:
value = int(meta.get('priority', 10))
return value if value >= 1 else 10
except (TypeError, ValueError, OverflowError):
return 10
for pid, meta in sorted(presets.items(), key=lambda x: (priority(x[1]), x[0])):
if isinstance(meta, dict) and bool(meta.get('enabled', True)) and re.fullmatch(r'[a-z0-9-]+', pid):
print(pid)
except Exception:
sys.exit(1)
" 2>/dev/null); then
if [ -n "$sorted_presets" ]; then
# python3 succeeded and returned preset IDs — search in priority order
while IFS= read -r preset_id; do
local candidate="$presets_dir/$preset_id/templates/${template_name}.md"
[ -f "$candidate" ] && echo "$candidate" && return 0
candidate="$presets_dir/$preset_id/${template_name}.md"
[ -f "$candidate" ] && echo "$candidate" && return 0
done <<< "$sorted_presets"
fi
# python3 succeeded but registry has no presets — nothing to search
else
# python3 failed (missing, or registry parse error) — fall back to unordered directory scan
for preset in "$presets_dir"/*/; do
[ -d "$preset" ] || continue
local candidate="$preset/templates/${template_name}.md"
[ -f "$candidate" ] && echo "$candidate" && return 0
candidate="$preset/${template_name}.md"
[ -f "$candidate" ] && echo "$candidate" && return 0
done
fi
else
# Fallback: alphabetical directory order (no python3 available)
for preset in "$presets_dir"/*/; do
[ -d "$preset" ] || continue
local candidate="$preset/templates/${template_name}.md"
[ -f "$candidate" ] && echo "$candidate" && return 0
candidate="$preset/${template_name}.md"
[ -f "$candidate" ] && echo "$candidate" && return 0
done
fi
fi
# Priority 3: Extension-provided templates
local ext_dir="$repo_root/.specify/extensions"
if [ -d "$ext_dir" ]; then
local sorted_extensions=""
if ! sorted_extensions=$(_sorted_extension_ids "$ext_dir"); then
return 2
fi
while IFS= read -r extension_id; do
[ -n "$extension_id" ] || continue
local ext="$ext_dir/$extension_id"
local candidate="$ext/templates/${template_name}.md"
[ -f "$candidate" ] || candidate="$ext/${template_name}.md"
[ -f "$candidate" ] && echo "$candidate" && return 0
done <<< "$sorted_extensions"
fi
# Priority 4: Core templates
local core="$base/${template_name}.md"
[ -f "$core" ] && echo "$core" && return 0
# Template not found in any location.
# Return 1 so callers can distinguish "not found" from "found".
# Callers running under set -e should use: TEMPLATE=$(resolve_template ...) || true
return 1
}
# Resolve a template name to composed content using composition strategies.
# Reads strategy metadata from preset manifests and composes content
# from multiple layers using prepend, append, or wrap strategies.
#
# Usage: CONTENT=$(resolve_template_content "template-name" "$REPO_ROOT")
# Returns composed content string on stdout; exit code 1 if not found.
resolve_template_content() {
local template_name="$1"
local repo_root="$2"
local base="$repo_root/.specify/templates"
case "$template_name" in ""|*[!a-z0-9-]*) return 1 ;; esac
# Collect all layers (highest priority first)
local -a layer_paths=()
local -a layer_strategies=()
# Priority 1: Project overrides (always "replace")
local override="$base/overrides/${template_name}.md"
if [ -f "$override" ]; then
if ! cat "$override"; then
echo "Error: failed to read template layer $override" >&2
return 2
fi
return 0
fi
local effective_base_found=false
# Priority 2: Installed presets (sorted by priority from .registry)
local presets_dir="$repo_root/.specify/presets"
if [ -d "$presets_dir" ]; then
local registry_file="$presets_dir/.registry"
local sorted_presets=""
local registry_parsed=false
local -a python_cmd=()
local _python_cmd_line
while IFS= read -r _python_cmd_line; do
python_cmd+=("$_python_cmd_line")
done < <(_python3_command)
if [ -f "$registry_file" ] && [ "${#python_cmd[@]}" -gt 0 ]; then
if sorted_presets=$(SPECKIT_REGISTRY="$registry_file" "${python_cmd[@]}" -c "
import json, re, sys, os
try:
with open(os.environ['SPECKIT_REGISTRY'], encoding='utf-8') as f:
data = json.load(f)
presets = data.get('presets', {})
def priority(meta):
if not isinstance(meta, dict) or isinstance(meta.get('priority'), bool):
return 10
try:
value = int(meta.get('priority', 10))
return value if value >= 1 else 10
except (TypeError, ValueError, OverflowError):
return 10
for pid, meta in sorted(presets.items(), key=lambda x: (priority(x[1]), x[0])):
if isinstance(meta, dict) and bool(meta.get('enabled', True)) and re.fullmatch(r'[a-z0-9-]+', pid):
print(pid)
except Exception:
sys.exit(1)
" 2>/dev/null); then
registry_parsed=true
fi
fi
if [ "$registry_parsed" = false ]; then
for preset in "$presets_dir"/*/; do
[ -d "$preset" ] || continue
local fallback_id
fallback_id=$(basename "$preset")
case "$fallback_id" in *[!a-z0-9-]*) continue ;; esac
sorted_presets+="${sorted_presets:+$'\n'}$fallback_id"
done
fi
if [ -n "$sorted_presets" ]; then
while IFS= read -r preset_id; do
local strategy="replace"
local manifest_file=""
local manifest="$presets_dir/$preset_id/preset.yml"
local manifest_declared=false
if [ -f "$manifest" ]; then
if [ "${#python_cmd[@]}" -eq 0 ]; then
echo "Error: Python 3 and PyYAML are required to resolve preset template composition" >&2
return 2
fi
local result
local py_stderr
local parse_status
py_stderr=$(mktemp)
if result=$(SPECKIT_MANIFEST="$manifest" SPECKIT_TMPL="$template_name" "${python_cmd[@]}" -c "
import sys, os
try:
import yaml
except ImportError:
print('yaml_missing', file=sys.stderr)
sys.exit(2)
try:
with open(os.environ['SPECKIT_MANIFEST'], encoding='utf-8') as f:
data = yaml.safe_load(f)
if not isinstance(data, dict):
raise ValueError('manifest root must be a mapping')
if 'provides' not in data:
raise ValueError('manifest missing provides section')
provides = data['provides']
if not isinstance(provides, dict):
raise ValueError('manifest provides must be a mapping')
if 'templates' not in provides:
raise ValueError('manifest provides missing templates')
templates = provides['templates']
if not isinstance(templates, list):
raise ValueError('manifest templates must be a list')
if not templates:
raise ValueError('manifest must provide at least one template')
valid_types = ('template', 'command', 'script')
valid_strategies = ('replace', 'prepend', 'append', 'wrap')
for t in templates:
if not isinstance(t, dict):
raise ValueError('manifest template entries must be mappings')
if 'type' not in t or 'name' not in t or 'file' not in t:
raise ValueError('manifest template entry missing type, name, or file')
for field in ('type', 'name', 'file'):
if not isinstance(t[field], str):
raise ValueError('manifest template ' + field + ' must be a string')
if t['type'] not in valid_types:
raise ValueError('invalid manifest template type')
strategy = t.get('strategy', 'replace')
if not isinstance(strategy, str):
raise ValueError('manifest template strategy must be a string')
strategy = strategy.lower()
if strategy not in valid_strategies:
raise ValueError('invalid manifest template strategy')
if t['type'] == 'script' and strategy not in ('replace', 'wrap'):
raise ValueError('invalid manifest script strategy')
for t in templates:
if t.get('name') == os.environ['SPECKIT_TMPL'] and t.get('type', 'template') == 'template':
file_value = t.get('file', '')
strategy = t.get('strategy', 'replace')
print('found\t' + strategy + '\t' + file_value)
sys.exit(0)
print('absent\treplace\t')
except Exception as exc:
print(f'manifest_invalid: {exc}', file=sys.stderr)
sys.exit(3)
" 2>"$py_stderr"); then
parse_status=0
else
parse_status=$?
fi
if [ "$parse_status" -ne 0 ]; then
if [ "$parse_status" -eq 2 ]; then
echo "Error: PyYAML is required to resolve preset template composition" >&2
else
echo "Error: invalid preset manifest $manifest" >&2
fi
rm -f "$py_stderr"
return 2
fi
if [ -n "$result" ]; then
local declaration
IFS=$'\t' read -r declaration strategy manifest_file <<< "$result"
[ "$declaration" = "found" ] && manifest_declared=true
strategy=$(printf '%s' "$strategy" | tr '[:upper:]' '[:lower:]')
fi
rm -f "$py_stderr"
fi
local candidate=""
if [ -n "$manifest_file" ]; then
case "$manifest_file" in
/*|*../*) manifest_file="" ;;
esac
fi
if [ -n "$manifest_file" ]; then
local mf="$presets_dir/$preset_id/$manifest_file"
[ -f "$mf" ] && candidate="$mf"
fi
if [ -z "$candidate" ] && [ "$manifest_declared" = false ]; then
local cf="$presets_dir/$preset_id/templates/${template_name}.md"
[ -f "$cf" ] && candidate="$cf"
if [ -z "$candidate" ]; then
cf="$presets_dir/$preset_id/${template_name}.md"
[ -f "$cf" ] && candidate="$cf"
fi
fi
if [ -n "$candidate" ]; then
layer_paths+=("$candidate")
layer_strategies+=("$strategy")
if [ "$strategy" = "replace" ]; then
effective_base_found=true
break
fi
fi
done <<< "$sorted_presets"
fi
fi
# Priority 3: Extension-provided templates (always "replace")
local ext_dir="$repo_root/.specify/extensions"
if [ "$effective_base_found" = false ] && [ -d "$ext_dir" ]; then
local sorted_extensions=""
if ! sorted_extensions=$(_sorted_extension_ids "$ext_dir"); then
return 2
fi
while IFS= read -r extension_id; do
[ -n "$extension_id" ] || continue
local ext="$ext_dir/$extension_id"
local candidate="$ext/templates/${template_name}.md"
[ -f "$candidate" ] || candidate="$ext/${template_name}.md"
if [ -f "$candidate" ]; then
layer_paths+=("$candidate")
layer_strategies+=("replace")
effective_base_found=true
break
fi
done <<< "$sorted_extensions"
fi
# Priority 4: Core templates (always "replace")
local core="$base/${template_name}.md"
if [ "$effective_base_found" = false ] && [ -f "$core" ]; then
layer_paths+=("$core")
layer_strategies+=("replace")
fi
local count=${#layer_paths[@]}
[ "$count" -eq 0 ] && return 1
# Check if any layer uses a non-replace strategy
local has_composition=false
for s in "${layer_strategies[@]}"; do
[ "$s" != "replace" ] && has_composition=true && break
done
# If the top (highest-priority) layer is replace, it wins entirely —
# lower layers are irrelevant regardless of their strategies.
if [ "${layer_strategies[0]}" = "replace" ]; then
if ! cat "${layer_paths[0]}"; then
echo "Error: failed to read template layer ${layer_paths[0]}" >&2
return 2
fi
return 0
fi
if [ "$has_composition" = false ]; then
if ! cat "${layer_paths[0]}"; then
echo "Error: failed to read template layer ${layer_paths[0]}" >&2
return 2
fi
return 0
fi
# Find the effective base: scan from highest priority (index 0) downward
# to find the nearest replace layer. Only compose layers above that base.
local base_idx=-1
local i
for (( i=0; i<count; i++ )); do
if [ "${layer_strategies[$i]}" = "replace" ]; then
base_idx=$i
break
fi
done
if [ $base_idx -lt 0 ]; then
echo "Error: template '$template_name' has composing layers but no replace base" >&2
return 2
fi
# Read the base content; compose layers above the base (higher priority)
local content
if ! content=$(cat "${layer_paths[$base_idx]}"; status=$?; printf x; exit "$status"); then
echo "Error: failed to read template layer ${layer_paths[$base_idx]}" >&2
return 2
fi
content="${content%x}"
for (( i=base_idx-1; i>=0; i-- )); do
local path="${layer_paths[$i]}"
local strat="${layer_strategies[$i]}"
local layer_content
# Preserve trailing newlines
if ! layer_content=$(cat "$path"; status=$?; printf x; exit "$status"); then
echo "Error: failed to read template layer $path" >&2
return 2
fi
layer_content="${layer_content%x}"
case "$strat" in
replace) content="$layer_content" ;;
prepend)
content=$(printf '%s\n\n%s' "$layer_content" "$content"; printf x)
content="${content%x}"
;;
append)
content=$(printf '%s\n\n%s' "$content" "$layer_content"; printf x)
content="${content%x}"
;;
wrap)
case "$layer_content" in
*'{CORE_TEMPLATE}'*) ;;
*) echo "Error: wrap strategy missing {CORE_TEMPLATE} placeholder" >&2; return 2 ;;
esac
# Consume the wrapper left to right instead of rewriting it in
# place. Rewriting re-scanned the string just modified, so base
# content holding a literal {CORE_TEMPLATE} reintroduced the
# token every pass and the loop never terminated. Advancing over
# ``rest`` bounds the work by the tokens in the original wrapper
# and leaves inserted content untouched, matching the single-pass
# semantics of .Replace()/.replace() in the PowerShell and Python
# ports.
local wrapped="" rest="$layer_content"
while [[ "$rest" == *'{CORE_TEMPLATE}'* ]]; do
wrapped="${wrapped}${rest%%\{CORE_TEMPLATE\}*}${content}"
rest="${rest#*\{CORE_TEMPLATE\}}"
done
content="${wrapped}${rest}"
;;
*) echo "Error: unknown strategy '$strat'" >&2; return 2 ;;
esac
done
printf '%s' "$content"
return 0
}
+504
View File
@@ -0,0 +1,504 @@
#!/usr/bin/env bash
set -e
JSON_MODE=false
DRY_RUN=false
ALLOW_EXISTING=false
SHORT_NAME=""
BRANCH_NUMBER=""
USE_TIMESTAMP=false
NUMBER_EXPLICIT=false
ARGS=()
i=1
while [ $i -le $# ]; do
arg="${!i}"
case "$arg" in
--json)
JSON_MODE=true
;;
--dry-run)
DRY_RUN=true
;;
--allow-existing-branch)
ALLOW_EXISTING=true
;;
--short-name)
if [ $((i + 1)) -gt $# ]; then
echo 'Error: --short-name requires a value' >&2
exit 1
fi
i=$((i + 1))
next_arg="${!i}"
# Check if the next argument is another option (starts with --)
if [[ "$next_arg" == --* ]]; then
echo 'Error: --short-name requires a value' >&2
exit 1
fi
SHORT_NAME="$next_arg"
;;
--number)
if [ $((i + 1)) -gt $# ]; then
echo 'Error: --number requires a value' >&2
exit 1
fi
i=$((i + 1))
next_arg="${!i}"
if [[ "$next_arg" == --* ]]; then
echo 'Error: --number requires a value' >&2
exit 1
fi
BRANCH_NUMBER="$next_arg"
if [ -n "$BRANCH_NUMBER" ]; then
NUMBER_EXPLICIT=true
fi
;;
--timestamp)
USE_TIMESTAMP=true
;;
--help|-h)
echo "Usage: $0 [--json] [--dry-run] [--allow-existing-branch] [--short-name <name>] [--number N] [--timestamp] <feature_description>"
echo ""
echo "Options:"
echo " --json Output in JSON format"
echo " --dry-run Compute feature name and paths without creating directories or files"
echo " --allow-existing-branch Reuse an existing feature directory if it already exists"
echo " --short-name <name> Provide a custom short name (2-4 words) for the feature"
echo " --number N Prefer a feature number (auto-corrected if its specs prefix exists)"
echo " --timestamp Use timestamp prefix (YYYYMMDD-HHMMSS) instead of sequential numbering"
echo " --help, -h Show this help message"
echo ""
echo "Examples:"
echo " $0 'Add user authentication system' --short-name 'user-auth'"
echo " $0 'Implement OAuth2 integration for API' --number 5"
echo " $0 --timestamp --short-name 'user-auth' 'Add user authentication'"
exit 0
;;
*)
ARGS+=("$arg")
;;
esac
i=$((i + 1))
done
FEATURE_DESCRIPTION="${ARGS[*]}"
if [ -z "$FEATURE_DESCRIPTION" ]; then
echo "Usage: $0 [--json] [--dry-run] [--allow-existing-branch] [--short-name <name>] [--number N] [--timestamp] <feature_description>" >&2
exit 1
fi
# Trim whitespace and validate description is not empty (e.g., user passed only whitespace)
FEATURE_DESCRIPTION=$(echo "$FEATURE_DESCRIPTION" | sed -E 's/^[[:space:]]+|[[:space:]]+$//g')
if [ -z "$FEATURE_DESCRIPTION" ]; then
echo "Error: Feature description cannot be empty or contain only whitespace" >&2
exit 1
fi
MAX_FEATURE_NUMBER=9223372036854775807
MAX_BRANCH_LENGTH=244
is_feature_number_in_range() {
local value="$1"
local normalized="${value#"${value%%[!0]*}"}"
[ -n "$normalized" ] || normalized=0
[ ${#normalized} -lt ${#MAX_FEATURE_NUMBER} ] && return 0
[ ${#normalized} -gt ${#MAX_FEATURE_NUMBER} ] && return 1
# Equal-length digit strings must be compared without arithmetic overflow.
# shellcheck disable=SC2071
[[ "$normalized" < "$MAX_FEATURE_NUMBER" || "$normalized" == "$MAX_FEATURE_NUMBER" ]]
}
# Function to get highest number from specs directory
get_highest_from_specs() {
local specs_dir="$1"
local highest=0
if [ -d "$specs_dir" ]; then
for dir in "$specs_dir"/*; do
[ -d "$dir" ] || continue
dirname=$(basename "$dir")
# Match sequential prefixes (>=3 digits), but skip timestamp dirs.
if echo "$dirname" | grep -Eq '^[0-9]{3,}-' && ! echo "$dirname" | grep -Eq '^[0-9]{8}-[0-9]{6}-'; then
number=$(echo "$dirname" | grep -Eo '^[0-9]+')
if is_feature_number_in_range "$number"; then
number=$((10#$number))
if [ "$number" -gt "$highest" ]; then
highest=$number
fi
fi
fi
done
fi
echo "$highest"
}
# Return success when a spec directory owns the given numeric prefix.
spec_prefix_exists() {
local specs_dir="$1"
local feature_num="$2"
for spec_path in "$specs_dir/${feature_num}-"*; do
[ -d "$spec_path" ] && return 0
done
return 1
}
# Function to clean and format a branch name
#
# Three details keep this consistent with the Python and PowerShell twins:
# * Unicode classification uses Python: POSIX [:alnum:] differs by platform.
# * `--*` instead of the GNU-only `\+`, which POSIX/BSD sed reads as a literal
# '+', leaving repeated separators uncollapsed on macOS.
# * printf instead of echo, so a name of "-n"/"-e"/"-E" is text, not options.
contains_non_ascii() {
LC_ALL=C grep -q '[^[:print:][:cntrl:]]'
}
UNICODE_LOCALE=""
locale_candidates=(C.UTF-8 C.utf8 en_US.UTF-8 en_US.utf8 "${LC_CTYPE:-${LANG:-}}")
if [ -n "${LC_ALL:-}" ]; then
locale_candidates=("$LC_ALL")
fi
for candidate in "${locale_candidates[@]}"; do
if [ -n "$candidate" ] && [ "$(printf 'é。' | LC_ALL="$candidate" sed 's/[^[:alnum:]]/-/g' 2>/dev/null)" = 'é-' ]; then
UNICODE_LOCALE="$candidate"
break
fi
done
if [ -z "$UNICODE_LOCALE" ]; then
UNICODE_LOCALE=C
if printf '%s' "${SHORT_NAME:-$FEATURE_DESCRIPTION}" | contains_non_ascii; then
if [ -n "${LC_ALL:-}" ]; then
echo "Error: A UTF-8 locale is required to create a Unicode feature name; LC_ALL=$LC_ALL is not usable" >&2
else
echo "Error: A UTF-8 locale is required to create a Unicode feature name" >&2
fi
exit 1
fi
fi
unicode_words() {
local name="${1//$'\n'/ }"
local separator="$2"
if printf '%s' "$name" | contains_non_ascii; then
local -a python_cmd=()
local override="${SPECKIT_PYTHON_EXECUTABLE:-${SPECKIT_PYTHON:-}}"
if [ -n "$override" ] && command -v "$override" >/dev/null 2>&1 &&
"$override" -c 'import sys; raise SystemExit(sys.version_info.major != 3)' >/dev/null 2>&1; then
python_cmd=("$override")
else
local python_line
while IFS= read -r python_line; do
python_cmd+=("$python_line")
done < <(_python3_command)
fi
if [ "${#python_cmd[@]}" -eq 0 ]; then
echo "Error: Python 3 is required to create a Unicode feature name" >&2
return 1
fi
printf '%s' "$name" | "${python_cmd[@]}" -c '
import sys
value = sys.stdin.buffer.read().decode("utf-8")
lower = str.maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")
result = "".join(
char if char.isalpha() or char.isdecimal() else sys.argv[1]
for char in value.translate(lower)
)
sys.stdout.buffer.write(result.encode("utf-8"))
' "$separator"
else
printf '%s' "$name" | LC_ALL=C tr '[:upper:]' '[:lower:]' | LC_ALL=C sed "s/[^a-z0-9]/$separator/g"
fi
}
clean_branch_name() {
local name="$1"
local cleaned
cleaned=$(unicode_words "$name" '-') || return 1
printf '%s\n' "$cleaned" | sed 's/--*/-/g' | sed 's/^-//' | sed 's/-$//'
}
branch_byte_count() {
printf '%s' "$1" | wc -c | tr -d '[:space:]'
}
# Fit a feature prefix and suffix within GitHub's branch-name limit.
fit_branch_name() {
local feature_num="$1"
local branch_suffix="$2"
local branch_name="${feature_num}-${branch_suffix}"
if [ "$(branch_byte_count "$branch_name")" -gt "$MAX_BRANCH_LENGTH" ]; then
local prefix_length=$(( ${#feature_num} + 1 ))
local max_suffix_length=$((MAX_BRANCH_LENGTH - prefix_length))
local truncated_suffix
local -x LC_ALL="$UNICODE_LOCALE"
local low=0 high=${#branch_suffix} mid
if (( high > max_suffix_length )); then
high=$max_suffix_length
fi
while (( low < high )); do
mid=$(((low + high + 1) / 2))
if [ "$(branch_byte_count "${branch_suffix:0:$mid}")" -le "$max_suffix_length" ]; then
low=$mid
else
high=$((mid - 1))
fi
done
truncated_suffix="${branch_suffix:0:$low}"
truncated_suffix="${truncated_suffix%-}"
branch_name="${feature_num}-${truncated_suffix}"
fi
printf '%s' "$branch_name"
}
# Quote a value for POSIX shell reuse, byte-identical to Python's shlex.quote
# so the persistence hints match the Python variant exactly (printf %q output
# differs between bash versions and from shlex.quote for spaces/metachars).
shell_quote() {
local value="$1" LC_ALL=C
if [[ "$value" =~ ^[A-Za-z0-9_@%+=:,./-]+$ ]]; then
printf '%s' "$value"
else
local q="'\"'\"'"
printf "'%s'" "${value//\'/$q}"
fi
}
# Resolve repository root using common.sh functions which prioritize .specify
SCRIPT_DIR="$(CDPATH="" cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/common.sh"
REPO_ROOT=$(get_repo_root) || exit 1
cd "$REPO_ROOT"
SPECS_DIR="$REPO_ROOT/specs"
if [ "$DRY_RUN" != true ]; then
mkdir -p "$SPECS_DIR"
fi
# Function to generate branch name with stop word filtering and length filtering
generate_branch_name() {
local description="$1"
# Common stop words to filter out
local stop_words="^(i|a|an|the|to|for|of|in|on|at|by|with|from|is|are|was|were|be|been|being|have|has|had|do|does|did|will|would|should|could|can|may|might|must|shall|this|that|these|those|my|your|our|their|want|need|add|get|set)$"
# Use a UTF-8 locale for character-safe length checks and split words.
local -x LC_ALL="$UNICODE_LOCALE"
local clean_name
clean_name=$(unicode_words "$description" ' ') || return 1
# Filter words: remove stop words and words shorter than 3 chars (unless they're uppercase acronyms in original)
local meaningful_words=()
for word in $clean_name; do
# Skip empty words
[ -z "$word" ] && continue
# Retain non-ASCII words even when shorter than three characters.
if ! printf '%s\n' "$word" | LC_ALL=C grep -qE "$stop_words"; then
if [ ${#word} -ge 3 ] || printf '%s' "$word" | contains_non_ascii; then
meaningful_words+=("$word")
# Keep short words that appear as an uppercase acronym in the original.
# Uppercase via tr and match with grep -w (both portable) rather than
# bash's 4+ "^^" case expansion (breaks on macOS bash 3.2) and \b (non-POSIX).
elif printf '%s' "$description" | LC_ALL=C grep -qw -- "$(printf '%s' "$word" | LC_ALL=C tr '[:lower:]' '[:upper:]')"; then
meaningful_words+=("$word")
fi
fi
done
# If we have meaningful words, use first 3-4 of them
if [ ${#meaningful_words[@]} -gt 0 ]; then
local max_words=3
if [ ${#meaningful_words[@]} -eq 4 ]; then max_words=4; fi
local result=""
local count=0
for word in "${meaningful_words[@]}"; do
if [ $count -ge $max_words ]; then break; fi
if [ -n "$result" ]; then result="$result-"; fi
result="$result$word"
count=$((count + 1))
done
echo "$result"
else
# Fallback to original logic if no meaningful words found
local cleaned=$(clean_branch_name "$description")
echo "$cleaned" | tr '-' '\n' | grep -v '^$' | head -3 | tr '\n' '-' | sed 's/-$//'
fi
}
# Generate branch name
if [ -n "$SHORT_NAME" ]; then
# Use provided short name, just clean it up
BRANCH_SUFFIX=$(clean_branch_name "$SHORT_NAME")
else
# Generate from description with smart filtering
BRANCH_SUFFIX=$(generate_branch_name "$FEATURE_DESCRIPTION")
fi
if [ -z "$BRANCH_SUFFIX" ]; then
echo "[specify] Warning: Feature name is empty after removing unsupported characters. Use --short-name with letters or digits (for example, user-auth)." >&2
fi
# Warn if --number and --timestamp are both specified
if [ "$USE_TIMESTAMP" = true ] && [ -n "$BRANCH_NUMBER" ]; then
>&2 echo "[specify] Warning: --number is ignored when --timestamp is used"
BRANCH_NUMBER=""
fi
# Determine branch prefix
if [ "$USE_TIMESTAMP" = true ]; then
FEATURE_NUM=$(date +%Y%m%d-%H%M%S)
BRANCH_NAME="${FEATURE_NUM}-${BRANCH_SUFFIX}"
else
if [ -n "$BRANCH_NUMBER" ] && [[ ! "$BRANCH_NUMBER" =~ ^[0-9]+$ ]]; then
echo "Error: --number must be an unsigned integer, got '$BRANCH_NUMBER'" >&2
exit 1
fi
# Bash arithmetic is signed 64-bit; reject digit strings that would wrap.
if [ -n "$BRANCH_NUMBER" ] && ! is_feature_number_in_range "$BRANCH_NUMBER"; then
echo "Error: --number must be between 0 and $MAX_FEATURE_NUMBER, got '$BRANCH_NUMBER'" >&2
exit 1
fi
# Determine branch number from existing feature directories
if [ -z "$BRANCH_NUMBER" ]; then
HIGHEST=$(get_highest_from_specs "$SPECS_DIR")
if [ "$HIGHEST" -eq "$MAX_FEATURE_NUMBER" ]; then
echo "Error: feature number must be between 0 and $MAX_FEATURE_NUMBER, got '9223372036854775808'" >&2
exit 1
fi
BRANCH_NUMBER=$((HIGHEST + 1))
fi
# Force base-10 interpretation to prevent octal conversion (e.g., 010 → 8 in octal, but should be 10 in decimal)
FEATURE_NUM=$(printf "%03d" "$((10#$BRANCH_NUMBER))")
# Treat an explicit number as a preference when its prefix is already used
# by a feature directory. Auto-detected numbers are already conflict-free.
if [ "$NUMBER_EXPLICIT" = true ]; then
SPEC_CONFLICT=false
REQUESTED_BRANCH_NAME=$(fit_branch_name "$FEATURE_NUM" "$BRANCH_SUFFIX")
REQUESTED_DIR="$SPECS_DIR/$REQUESTED_BRANCH_NAME"
if [ "$ALLOW_EXISTING" != true ] || [ ! -d "$REQUESTED_DIR" ]; then
spec_prefix_exists "$SPECS_DIR" "$FEATURE_NUM" && SPEC_CONFLICT=true
fi
if [ "$SPEC_CONFLICT" = true ]; then
REQUESTED_NUM="$FEATURE_NUM"
HIGHEST=$(get_highest_from_specs "$SPECS_DIR")
BRANCH_NUMBER=$HIGHEST
while true; do
if [ "$BRANCH_NUMBER" -eq "$MAX_FEATURE_NUMBER" ]; then
echo "Error: feature number must be between 0 and $MAX_FEATURE_NUMBER, got '9223372036854775808'" >&2
exit 1
fi
BRANCH_NUMBER=$((BRANCH_NUMBER + 1))
FEATURE_NUM=$(printf "%03d" "$((10#$BRANCH_NUMBER))")
spec_prefix_exists "$SPECS_DIR" "$FEATURE_NUM" || break
done
>&2 echo "[specify] Warning: --number $REQUESTED_NUM conflicts with an existing spec directory; using $FEATURE_NUM instead"
fi
fi
fi
# GitHub enforces a 244-byte limit on branch names
# Validate and truncate if necessary
ORIGINAL_BRANCH_NAME="${FEATURE_NUM}-${BRANCH_SUFFIX}"
BRANCH_NAME=$(fit_branch_name "$FEATURE_NUM" "$BRANCH_SUFFIX")
if [ "$BRANCH_NAME" != "$ORIGINAL_BRANCH_NAME" ]; then
>&2 echo "[specify] Warning: Branch name exceeded GitHub's 244-byte limit"
>&2 echo "[specify] Original: $ORIGINAL_BRANCH_NAME ($(branch_byte_count "$ORIGINAL_BRANCH_NAME") bytes)"
>&2 echo "[specify] Truncated to: $BRANCH_NAME ($(branch_byte_count "$BRANCH_NAME") bytes)"
fi
FEATURE_DIR="$SPECS_DIR/$BRANCH_NAME"
SPEC_FILE="$FEATURE_DIR/spec.md"
if [ "$DRY_RUN" != true ]; then
if [ -d "$FEATURE_DIR" ] && [ "$ALLOW_EXISTING" != true ]; then
if [ "$USE_TIMESTAMP" = true ]; then
>&2 echo "Error: Feature directory '$FEATURE_DIR' already exists. Rerun to get a new timestamp or use a different --short-name."
else
>&2 echo "Error: Feature directory '$FEATURE_DIR' already exists. Please use a different feature name or specify a different number with --number."
fi
exit 1
fi
NEEDS_SPEC=false
SPEC_TEMPLATE_FOUND=false
SPEC_TEMPLATE_CONTENT=""
if [ ! -f "$SPEC_FILE" ]; then
NEEDS_SPEC=true
if SPEC_TEMPLATE_CONTENT=$(resolve_template_content "spec-template" "$REPO_ROOT"; status=$?; printf x; exit "$status"); then
SPEC_TEMPLATE_CONTENT="${SPEC_TEMPLATE_CONTENT%x}"
SPEC_TEMPLATE_FOUND=true
else
resolve_status=$?
if [ "$resolve_status" -ne 1 ]; then
exit "$resolve_status"
fi
fi
fi
mkdir -p "$FEATURE_DIR"
if [ "$NEEDS_SPEC" = true ]; then
if [ "$SPEC_TEMPLATE_FOUND" = true ]; then
printf '%s' "$SPEC_TEMPLATE_CONTENT" > "$SPEC_FILE"
else
echo "Warning: Spec template not found; created empty spec file" >&2
touch "$SPEC_FILE"
fi
fi
# Persist to .specify/feature.json so downstream commands can find the
# feature, unless the orchestrator opted out via SPECIFY_FEATURE_NO_PERSIST (#4129).
if [[ "${SPECIFY_FEATURE_NO_PERSIST:-}" != "1" && "${SPECIFY_FEATURE_NO_PERSIST:-}" != "true" ]]; then
_persist_feature_json "$REPO_ROOT" "$FEATURE_DIR"
fi
# Inform the user how to set feature state in their own shell
printf '# To persist: export SPECIFY_FEATURE=%s\n' "$(shell_quote "$BRANCH_NAME")" >&2
printf '# export SPECIFY_FEATURE_DIRECTORY=%s\n' "$(shell_quote "$FEATURE_DIR")" >&2
fi
if $JSON_MODE; then
if command -v jq >/dev/null 2>&1; then
if [ "$DRY_RUN" = true ]; then
jq -cn \
--arg branch_name "$BRANCH_NAME" \
--arg spec_file "$SPEC_FILE" \
--arg feature_num "$FEATURE_NUM" \
'{BRANCH_NAME:$branch_name,SPEC_FILE:$spec_file,FEATURE_NUM:$feature_num,DRY_RUN:true}'
else
jq -cn \
--arg branch_name "$BRANCH_NAME" \
--arg spec_file "$SPEC_FILE" \
--arg feature_num "$FEATURE_NUM" \
'{BRANCH_NAME:$branch_name,SPEC_FILE:$spec_file,FEATURE_NUM:$feature_num}'
fi
else
if [ "$DRY_RUN" = true ]; then
printf '{"BRANCH_NAME":"%s","SPEC_FILE":"%s","FEATURE_NUM":"%s","DRY_RUN":true}\n' "$(json_escape "$BRANCH_NAME")" "$(json_escape "$SPEC_FILE")" "$(json_escape "$FEATURE_NUM")"
else
printf '{"BRANCH_NAME":"%s","SPEC_FILE":"%s","FEATURE_NUM":"%s"}\n' "$(json_escape "$BRANCH_NAME")" "$(json_escape "$SPEC_FILE")" "$(json_escape "$FEATURE_NUM")"
fi
fi
else
echo "BRANCH_NAME: $BRANCH_NAME"
echo "SPEC_FILE: $SPEC_FILE"
echo "FEATURE_NUM: $FEATURE_NUM"
if [ "$DRY_RUN" != true ]; then
printf '# To persist in your shell: export SPECIFY_FEATURE=%s\n' "$(shell_quote "$BRANCH_NAME")"
printf '# export SPECIFY_FEATURE_DIRECTORY=%s\n' "$(shell_quote "$FEATURE_DIR")"
fi
fi
+57
View File
@@ -0,0 +1,57 @@
#!/usr/bin/env bash
set -e
SCRIPT_DIR="$(CDPATH="" cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/common.sh"
JSON_MODE=false
TEMPLATE_NAME=""
for arg in "$@"; do
case "$arg" in
--json) JSON_MODE=true ;;
--help|-h)
echo "Usage: $0 <template-name> [--json]"
exit 0
;;
-*)
echo "ERROR: Unknown option '$arg'" >&2
exit 1
;;
*)
if [[ -n "$TEMPLATE_NAME" ]]; then
echo "ERROR: Unexpected argument '$arg'" >&2
exit 1
fi
TEMPLATE_NAME="$arg"
;;
esac
done
if [[ -z "$TEMPLATE_NAME" ]]; then
echo "ERROR: Template name is required" >&2
exit 1
fi
REPO_ROOT=$(get_repo_root)
if TEMPLATE_CONTENT=$(resolve_template_content "$TEMPLATE_NAME" "$REPO_ROOT"; status=$?; printf x; exit "$status"); then
TEMPLATE_CONTENT="${TEMPLATE_CONTENT%x}"
else
echo "ERROR: Could not resolve required $TEMPLATE_NAME from the template override stack for $REPO_ROOT" >&2
exit 1
fi
if $JSON_MODE; then
if has_jq; then
jq -cn \
--arg template_name "$TEMPLATE_NAME" \
--arg template_content "$TEMPLATE_CONTENT" \
'{TEMPLATE_NAME:$template_name,TEMPLATE_CONTENT:$template_content}'
else
printf '{"TEMPLATE_NAME":"%s","TEMPLATE_CONTENT":"%s"}\n' \
"$(json_escape "$TEMPLATE_NAME")" "$(json_escape "$TEMPLATE_CONTENT")"
fi
else
printf '%s' "$TEMPLATE_CONTENT"
fi
+89
View File
@@ -0,0 +1,89 @@
#!/usr/bin/env bash
set -e
# Parse command line arguments
JSON_MODE=false
for arg in "$@"; do
case "$arg" in
--json)
JSON_MODE=true
;;
--help|-h)
echo "Usage: $0 [--json]"
echo " --json Output results in JSON format"
echo " --help Show this help message"
exit 0
;;
*)
echo "ERROR: Unknown option '$arg'" >&2
exit 1
;;
esac
done
# Get script directory and load common functions
SCRIPT_DIR="$(CDPATH="" cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/common.sh"
# Get all paths and variables from common functions
_paths_output=$(get_feature_paths) || { echo "ERROR: Failed to resolve feature paths" >&2; exit 1; }
eval "$_paths_output"
unset _paths_output
# Ensure the feature directory exists
mkdir -p "$FEATURE_DIR"
# Copy plan template if plan doesn't already exist
if [[ -f "$IMPL_PLAN" ]]; then
if $JSON_MODE; then
echo "Plan already exists at $IMPL_PLAN, skipping template copy" >&2
else
echo "Plan already exists at $IMPL_PLAN, skipping template copy"
fi
else
template_file=$(mktemp)
trap 'rm -f "$template_file"' EXIT
if resolve_template_content "plan-template" "$REPO_ROOT" > "$template_file"; then
if [[ ! -s "$template_file" ]]; then
echo "ERROR: Plan template is empty; no new plan.md was created." >&2
echo "Restore a valid plan template and rerun plan setup." >&2
exit 1
fi
cat "$template_file" > "$IMPL_PLAN"
if $JSON_MODE; then
echo "Copied plan template to $IMPL_PLAN" >&2
else
echo "Copied plan template to $IMPL_PLAN"
fi
else
resolve_status=$?
if [ "$resolve_status" -ne 1 ]; then
exit "$resolve_status"
fi
echo "ERROR: Plan template not found; no new plan.md was created." >&2
echo "Restore a valid plan template and rerun plan setup." >&2
exit 1
fi
fi
# Output results
if $JSON_MODE; then
if has_jq; then
jq -cn \
--arg feature_spec "$FEATURE_SPEC" \
--arg impl_plan "$IMPL_PLAN" \
--arg feature_dir "$FEATURE_DIR" \
--arg branch "$CURRENT_BRANCH" \
'{FEATURE_SPEC:$feature_spec,IMPL_PLAN:$impl_plan,FEATURE_DIR:$feature_dir,BRANCH:$branch}'
else
printf '{"FEATURE_SPEC":"%s","IMPL_PLAN":"%s","FEATURE_DIR":"%s","BRANCH":"%s"}\n' \
"$(json_escape "$FEATURE_SPEC")" "$(json_escape "$IMPL_PLAN")" "$(json_escape "$FEATURE_DIR")" "$(json_escape "$CURRENT_BRANCH")"
fi
else
echo "FEATURE_SPEC: $FEATURE_SPEC"
echo "IMPL_PLAN: $IMPL_PLAN"
echo "FEATURE_DIR: $FEATURE_DIR"
echo "BRANCH: $CURRENT_BRANCH"
fi
+94
View File
@@ -0,0 +1,94 @@
#!/usr/bin/env bash
set -e
# Parse command line arguments
JSON_MODE=false
for arg in "$@"; do
case "$arg" in
--json) JSON_MODE=true ;;
--help|-h)
echo "Usage: $0 [--json]"
echo " --json Output results in JSON format"
echo " --help Show this help message"
exit 0
;;
*) echo "ERROR: Unknown option '$arg'" >&2; exit 1 ;;
esac
done
# Source common functions
SCRIPT_DIR="$(CDPATH="" cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/common.sh"
# Get feature paths
_paths_output=$(get_feature_paths) || { echo "ERROR: Failed to resolve feature paths" >&2; exit 1; }
eval "$_paths_output"
unset _paths_output
# Validate required files
if [[ ! -f "$IMPL_PLAN" ]]; then
echo "ERROR: plan.md not found in $FEATURE_DIR" >&2
echo "Run /speckit.plan first to create the implementation plan." >&2
exit 1
fi
if [[ ! -f "$FEATURE_SPEC" ]]; then
echo "ERROR: spec.md not found in $FEATURE_DIR" >&2
echo "Run /speckit.specify first to create the feature structure." >&2
exit 1
fi
# Build available docs list
docs=()
[[ -f "$RESEARCH" ]] && docs+=("research.md")
[[ -f "$DATA_MODEL" ]] && docs+=("data-model.md")
if [[ -d "$CONTRACTS_DIR" ]] && [[ -n "$(ls -A "$CONTRACTS_DIR" 2>/dev/null)" ]]; then
docs+=("contracts/")
fi
[[ -f "$QUICKSTART" ]] && docs+=("quickstart.md")
# Resolve tasks template through override stack
TASKS_TEMPLATE=$(resolve_template "tasks-template" "$REPO_ROOT") || true
if TASKS_TEMPLATE_CONTENT=$(resolve_template_content "tasks-template" "$REPO_ROOT"; status=$?; printf x; exit "$status"); then
TASKS_TEMPLATE_CONTENT="${TASKS_TEMPLATE_CONTENT%x}"
else
echo "ERROR: Could not resolve required tasks-template from the template override stack for $REPO_ROOT" >&2
echo "Template 'tasks-template' was not found in any supported location (overrides, presets, extensions, or shared core). Add an override at .specify/templates/overrides/tasks-template.md, or run 'specify init' / reinstall shared infra to restore the core .specify/templates/tasks-template.md template." >&2
exit 1
fi
# Output results
if $JSON_MODE; then
if has_jq; then
if [[ ${#docs[@]} -eq 0 ]]; then
json_docs="[]"
else
json_docs=$(printf '%s\n' "${docs[@]}" | jq -R . | jq -s .)
fi
jq -cn \
--arg feature_dir "$FEATURE_DIR" \
--argjson docs "$json_docs" \
--arg tasks_template "${TASKS_TEMPLATE:-}" \
--arg tasks_template_content "$TASKS_TEMPLATE_CONTENT" \
'{FEATURE_DIR:$feature_dir,AVAILABLE_DOCS:$docs,TASKS_TEMPLATE:$tasks_template,TASKS_TEMPLATE_CONTENT:$tasks_template_content}'
else
if [[ ${#docs[@]} -eq 0 ]]; then
json_docs="[]"
else
json_docs=$(for d in "${docs[@]}"; do printf '"%s",' "$(json_escape "$d")"; done)
json_docs="[${json_docs%,}]"
fi
printf '{"FEATURE_DIR":"%s","AVAILABLE_DOCS":%s,"TASKS_TEMPLATE":"%s","TASKS_TEMPLATE_CONTENT":"%s"}\n' \
"$(json_escape "$FEATURE_DIR")" "$json_docs" "$(json_escape "${TASKS_TEMPLATE:-}")" "$(json_escape "$TASKS_TEMPLATE_CONTENT")"
fi
else
echo "FEATURE_DIR: $FEATURE_DIR"
echo "TASKS_TEMPLATE: ${TASKS_TEMPLATE:-not found}"
echo "AVAILABLE_DOCS:"
check_file "$RESEARCH" "research.md"
check_file "$DATA_MODEL" "data-model.md"
check_dir "$CONTRACTS_DIR" "contracts/"
check_file "$QUICKSTART" "quickstart.md"
fi
+3
View File
@@ -0,0 +1,3 @@
# Atomic blog update prerequisite
Guarded publishers submit the updatedAt string returned by GET to PUT /admin/blogs/:id as expectedUpdatedAt. A stale or invalid supplied token must return 409 before any scalar, relation, tag creation, or cache side effect. Exactly one competing guarded writer sharing a token can commit. Missing records retain 404. Existing UI callers omitting the token retain legacy last-write-wins behavior deliberately; they are not concurrency-protected. No production content writes or migrations are permitted.
Acceptance: current token succeeds; stale/invalid/null/number/object/array tokens fail; offset-equivalent timestamps work; microsecond DB timestamps round-trip through millisecond JSON; same-millisecond successors invalidate old tokens; relation failure rolls back scalar claim; postcommit revalidation remains fail-safe.
+7
View File
@@ -0,0 +1,7 @@
# Tasks
- [x] Preserve inherited service patch/test and fetch gitea/develop; inspect Graphify impact and schema/controller/whitelist.
- [x] Specify contract/compatibility/precision before implementation.
- [ ] RED: expand invalid/current/stale/same-ms/race/rollback and HTTP whitelist tests.
- [ ] GREEN: transactional predicate and nested relations; preserve legacy omission.
- [ ] Targeted and complete backend/admin/store suites plus all builds; isolate baseline failures without modifying another worktree.
- [ ] Independent review of exact hashed diff; do not push before accepted. Parent handles pilot, deployment and archive loop.
+45
View File
@@ -0,0 +1,45 @@
# [CHECKLIST TYPE] Checklist: [FEATURE NAME]
**Purpose**: [Brief description of what this checklist covers]
**Created**: [DATE]
**Feature**: [Link to spec.md or relevant documentation]
**Note**: This custom checklist is generated by the `/speckit.checklist` command based on feature context and requirements.
**Review Ownership**: This checklist is a reviewer-owned requirements-quality review artifact. Mark an item `[x]` only when the reviewer determines the requirements-quality criterion is satisfied.
**Marker Semantics**: `[x]` means the criterion has been reviewed and satisfied for requirements quality. It does not mean implementation work is complete.
<!--
============================================================================
IMPORTANT: The checklist items below are SAMPLE ITEMS for illustration only.
The /speckit.checklist command MUST replace these with actual items based on:
- User's specific checklist request
- Feature requirements from spec.md
- Technical context from plan.md
- Implementation details from tasks.md
DO NOT keep these sample items in the generated checklist file.
============================================================================
-->
## [Category 1]
- [ ] CHK001 First checklist item with clear action
- [ ] CHK002 Second checklist item
- [ ] CHK003 Third checklist item
## [Category 2]
- [ ] CHK004 Another category item
- [ ] CHK005 Item with specific criteria
- [ ] CHK006 Final item in this category
## Notes
- Mark items `[x]` only after review confirms the requirement-quality criterion is satisfied
- Leave items unchecked when they still require clarification, correction, or reviewer evaluation
- `/speckit.implement` reads checklist checkbox state as a gate and must not modify markers
- `checklists/requirements.md` has a separate built-in lifecycle maintained by `/speckit.specify` and `/speckit.clarify`
- Add comments or findings inline
- Link to relevant resources or documentation
- Items are numbered sequentially for easy reference
@@ -0,0 +1,50 @@
# [PROJECT_NAME] Constitution
<!-- Example: Spec Constitution, TaskFlow Constitution, etc. -->
## Core Principles
### [PRINCIPLE_1_NAME]
<!-- Example: I. Library-First -->
[PRINCIPLE_1_DESCRIPTION]
<!-- Example: Every feature starts as a standalone library; Libraries must be self-contained, independently testable, documented; Clear purpose required - no organizational-only libraries -->
### [PRINCIPLE_2_NAME]
<!-- Example: II. CLI Interface -->
[PRINCIPLE_2_DESCRIPTION]
<!-- Example: Every library exposes functionality via CLI; Text in/out protocol: stdin/args → stdout, errors → stderr; Support JSON + human-readable formats -->
### [PRINCIPLE_3_NAME]
<!-- Example: III. Test-First (NON-NEGOTIABLE) -->
[PRINCIPLE_3_DESCRIPTION]
<!-- Example: TDD mandatory: Tests written → User approved → Tests fail → Then implement; Red-Green-Refactor cycle strictly enforced -->
### [PRINCIPLE_4_NAME]
<!-- Example: IV. Integration Testing -->
[PRINCIPLE_4_DESCRIPTION]
<!-- Example: Focus areas requiring integration tests: New library contract tests, Contract changes, Inter-service communication, Shared schemas -->
### [PRINCIPLE_5_NAME]
<!-- Example: V. Observability, VI. Versioning & Breaking Changes, VII. Simplicity -->
[PRINCIPLE_5_DESCRIPTION]
<!-- Example: Text I/O ensures debuggability; Structured logging required; Or: MAJOR.MINOR.BUILD format; Or: Start simple, YAGNI principles -->
## [SECTION_2_NAME]
<!-- Example: Additional Constraints, Security Requirements, Performance Standards, etc. -->
[SECTION_2_CONTENT]
<!-- Example: Technology stack requirements, compliance standards, deployment policies, etc. -->
## [SECTION_3_NAME]
<!-- Example: Development Workflow, Review Process, Quality Gates, etc. -->
[SECTION_3_CONTENT]
<!-- Example: Code review requirements, testing gates, deployment approval process, etc. -->
## Governance
<!-- Example: Constitution supersedes all other practices; Amendments require documentation, approval, migration plan -->
[GOVERNANCE_RULES]
<!-- Example: All PRs/reviews must verify compliance; Complexity must be justified; Use [GUIDANCE_FILE] for runtime development guidance -->
**Version**: [CONSTITUTION_VERSION] | **Ratified**: [RATIFICATION_DATE] | **Last Amended**: [LAST_AMENDED_DATE]
<!-- Example: Version: 2.1.1 | Ratified: 2025-06-13 | Last Amended: 2025-07-16 -->
+113
View File
@@ -0,0 +1,113 @@
# Implementation Plan: [FEATURE]
**Branch**: `[###-feature-name]` | **Date**: [DATE] | **Spec**: [link]
**Input**: Feature specification from `/specs/[###-feature-name]/spec.md`
**Note**: This template is filled in by the `/speckit.plan` command; its definition describes the execution workflow.
## Summary
[Extract from feature spec: primary requirement + technical approach from research]
## Technical Context
<!--
ACTION REQUIRED: Replace the content in this section with the technical details
for the project. The structure here is presented in advisory capacity to guide
the iteration process.
-->
**Language/Version**: [e.g., Python 3.11, Swift 5.9, Rust 1.75 or NEEDS CLARIFICATION]
**Primary Dependencies**: [e.g., FastAPI, UIKit, LLVM or NEEDS CLARIFICATION]
**Storage**: [if applicable, e.g., PostgreSQL, CoreData, files or N/A]
**Testing**: [e.g., pytest, XCTest, cargo test or NEEDS CLARIFICATION]
**Target Platform**: [e.g., Linux server, iOS 15+, WASM or NEEDS CLARIFICATION]
**Project Type**: [e.g., library/cli/web-service/mobile-app/compiler/desktop-app or NEEDS CLARIFICATION]
**Performance Goals**: [domain-specific, e.g., 1000 req/s, 10k lines/sec, 60 fps or NEEDS CLARIFICATION]
**Constraints**: [domain-specific, e.g., <200ms p95, <100MB memory, offline-capable or NEEDS CLARIFICATION]
**Scale/Scope**: [domain-specific, e.g., 10k users, 1M LOC, 50 screens or NEEDS CLARIFICATION]
## Constitution Check
*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.*
[Gates determined based on constitution file]
## Project Structure
### Documentation (this feature)
```text
specs/[###-feature]/
├── plan.md # This file (/speckit.plan command output)
├── research.md # Phase 0 output (/speckit.plan command)
├── data-model.md # Phase 1 output (/speckit.plan command)
├── quickstart.md # Phase 1 output (/speckit.plan command)
├── contracts/ # Phase 1 output (/speckit.plan command)
└── tasks.md # Phase 2 output (/speckit.tasks command - NOT created by /speckit.plan)
```
### Source Code (repository root)
<!--
ACTION REQUIRED: Replace the placeholder tree below with the concrete layout
for this feature. Delete unused options and expand the chosen structure with
real paths (e.g., apps/admin, packages/something). The delivered plan must
not include Option labels.
-->
```text
# [REMOVE IF UNUSED] Option 1: Single project (DEFAULT)
src/
├── models/
├── services/
├── cli/
└── lib/
tests/
├── contract/
├── integration/
└── unit/
# [REMOVE IF UNUSED] Option 2: Web application (when "frontend" + "backend" detected)
backend/
├── src/
│ ├── models/
│ ├── services/
│ └── api/
└── tests/
frontend/
├── src/
│ ├── components/
│ ├── pages/
│ └── services/
└── tests/
# [REMOVE IF UNUSED] Option 3: Mobile + API (when "iOS/Android" detected)
api/
└── [same as backend above]
ios/ or android/
└── [platform-specific structure: feature modules, UI flows, platform tests]
```
**Structure Decision**: [Document the selected structure and reference the real
directories captured above]
## Complexity Tracking
> **Fill ONLY if Constitution Check has violations that must be justified**
| Violation | Why Needed | Simpler Alternative Rejected Because |
|-----------|------------|-------------------------------------|
| [e.g., 4th project] | [current need] | [why 3 projects insufficient] |
| [e.g., Repository pattern] | [specific problem] | [why direct DB access insufficient] |
+131
View File
@@ -0,0 +1,131 @@
# Feature Specification: [FEATURE NAME]
**Feature Branch**: `[###-feature-name]`
**Created**: [DATE]
**Status**: Draft
**Input**: User description: "$ARGUMENTS"
## User Scenarios & Testing *(mandatory)*
<!--
IMPORTANT: User stories should be PRIORITIZED as user journeys ordered by importance.
Each user story/journey must be INDEPENDENTLY TESTABLE - meaning if you implement just ONE of them,
you should still have a viable MVP (Minimum Viable Product) that delivers value.
Assign priorities (P1, P2, P3, etc.) to each story, where P1 is the most critical.
Think of each story as a standalone slice of functionality that can be:
- Developed independently
- Tested independently
- Deployed independently
- Demonstrated to users independently
-->
### User Story 1 - [Brief Title] (Priority: P1)
[Describe this user journey in plain language]
**Why this priority**: [Explain the value and why it has this priority level]
**Independent Test**: [Describe how this can be tested independently - e.g., "Can be fully tested by [specific action] and delivers [specific value]"]
**Acceptance Scenarios**:
1. **Given** [initial state], **When** [action], **Then** [expected outcome]
2. **Given** [initial state], **When** [action], **Then** [expected outcome]
---
### User Story 2 - [Brief Title] (Priority: P2)
[Describe this user journey in plain language]
**Why this priority**: [Explain the value and why it has this priority level]
**Independent Test**: [Describe how this can be tested independently]
**Acceptance Scenarios**:
1. **Given** [initial state], **When** [action], **Then** [expected outcome]
---
### User Story 3 - [Brief Title] (Priority: P3)
[Describe this user journey in plain language]
**Why this priority**: [Explain the value and why it has this priority level]
**Independent Test**: [Describe how this can be tested independently]
**Acceptance Scenarios**:
1. **Given** [initial state], **When** [action], **Then** [expected outcome]
---
[Add more user stories as needed, each with an assigned priority]
### Edge Cases
<!--
ACTION REQUIRED: The content in this section represents placeholders.
Fill them out with the right edge cases.
-->
- What happens when [boundary condition]?
- How does system handle [error scenario]?
## Requirements *(mandatory)*
<!--
ACTION REQUIRED: The content in this section represents placeholders.
Fill them out with the right functional requirements.
-->
### Functional Requirements
- **FR-001**: System MUST [specific capability, e.g., "allow users to create accounts"]
- **FR-002**: System MUST [specific capability, e.g., "validate email addresses"]
- **FR-003**: Users MUST be able to [key interaction, e.g., "reset their password"]
- **FR-004**: System MUST [data requirement, e.g., "persist user preferences"]
- **FR-005**: System MUST [behavior, e.g., "log all security events"]
*Example of marking unclear requirements:*
- **FR-006**: System MUST authenticate users via [NEEDS CLARIFICATION: auth method not specified - email/password, SSO, OAuth?]
- **FR-007**: System MUST retain user data for [NEEDS CLARIFICATION: retention period not specified]
### Key Entities *(include if feature involves data)*
- **[Entity 1]**: [What it represents, key attributes without implementation]
- **[Entity 2]**: [What it represents, relationships to other entities]
## Success Criteria *(mandatory)*
<!--
ACTION REQUIRED: Define measurable success criteria.
These must be technology-agnostic and measurable.
-->
### Measurable Outcomes
- **SC-001**: [Measurable metric, e.g., "Users can complete account creation in under 2 minutes"]
- **SC-002**: [Measurable metric, e.g., "System handles 1000 concurrent users without degradation"]
- **SC-003**: [User satisfaction metric, e.g., "90% of users successfully complete primary task on first attempt"]
- **SC-004**: [Business metric, e.g., "Reduce support tickets related to [X] by 50%"]
## Assumptions
<!--
ACTION REQUIRED: The content in this section represents placeholders.
Fill them out with the right assumptions based on reasonable defaults
chosen when the feature description did not specify certain details.
-->
- [Assumption about target users, e.g., "Users have stable internet connectivity"]
- [Assumption about scope boundaries, e.g., "Mobile support is out of scope for v1"]
- [Assumption about data/environment, e.g., "Existing authentication system will be reused"]
- [Dependency on existing system/service, e.g., "Requires access to the existing user profile API"]
+252
View File
@@ -0,0 +1,252 @@
---
description: "Task list template for feature implementation"
---
# Tasks: [FEATURE NAME]
**Input**: Design documents from `/specs/[###-feature-name]/`
**Prerequisites**: plan.md (required), spec.md (required for user stories), research.md, data-model.md, contracts/
**Tests**: The examples below include test tasks. Tests are OPTIONAL - only include them if explicitly requested in the feature specification.
**Organization**: Tasks are grouped by user story to enable independent implementation and testing of each story.
## Format: `[ID] [P?] [Story] Description`
- **[P]**: Can run in parallel (different files, no dependencies)
- **[Story]**: Which user story this task belongs to (e.g., US1, US2, US3)
- Include exact file paths in descriptions
## Path Conventions
- **Single project**: `src/`, `tests/` at repository root
- **Web app**: `backend/src/`, `frontend/src/`
- **Mobile**: `api/src/`, `ios/src/` or `android/src/`
- Paths shown below assume single project - adjust based on plan.md structure
<!--
============================================================================
IMPORTANT: The tasks below are SAMPLE TASKS for illustration purposes only.
The /speckit.tasks command MUST replace these with actual tasks based on:
- User stories from spec.md (with their priorities P1, P2, P3...)
- Feature requirements from plan.md
- Entities from data-model.md
- Endpoints from contracts/
Tasks MUST be organized by user story so each story can be:
- Implemented independently
- Tested independently
- Delivered as an MVP increment
DO NOT keep these sample tasks in the generated tasks.md file.
============================================================================
-->
## Phase 1: Setup (Shared Infrastructure)
**Purpose**: Project initialization and basic structure
- [ ] T001 Create project structure per implementation plan
- [ ] T002 Initialize [language] project with [framework] dependencies
- [ ] T003 [P] Configure linting and formatting tools
---
## Phase 2: Foundational (Blocking Prerequisites)
**Purpose**: Core infrastructure that MUST be complete before ANY user story can be implemented
**⚠️ CRITICAL**: No user story work can begin until this phase is complete
Examples of foundational tasks (adjust based on your project):
- [ ] T004 Setup database schema and migrations framework
- [ ] T005 [P] Implement authentication/authorization framework
- [ ] T006 [P] Setup API routing and middleware structure
- [ ] T007 Create base models/entities that all stories depend on
- [ ] T008 Configure error handling and logging infrastructure
- [ ] T009 Setup environment configuration management
**Checkpoint**: Foundation ready - user story implementation can now begin in parallel
---
## Phase 3: User Story 1 - [Title] (Priority: P1) 🎯 MVP
**Goal**: [Brief description of what this story delivers]
**Independent Test**: [How to verify this story works on its own]
### Tests for User Story 1 (OPTIONAL - only if tests requested) ⚠️
> **NOTE: Write these tests FIRST, ensure they FAIL before implementation**
- [ ] T010 [P] [US1] Contract test for [endpoint] in tests/contract/test_[name].py
- [ ] T011 [P] [US1] Integration test for [user journey] in tests/integration/test_[name].py
### Implementation for User Story 1
- [ ] T012 [P] [US1] Create [Entity1] model in src/models/[entity1].py
- [ ] T013 [P] [US1] Create [Entity2] model in src/models/[entity2].py
- [ ] T014 [US1] Implement [Service] in src/services/[service].py (depends on T012, T013)
- [ ] T015 [US1] Implement [endpoint/feature] in src/[location]/[file].py
- [ ] T016 [US1] Add validation and error handling
- [ ] T017 [US1] Add logging for user story 1 operations
**Checkpoint**: At this point, User Story 1 should be fully functional and testable independently
---
## Phase 4: User Story 2 - [Title] (Priority: P2)
**Goal**: [Brief description of what this story delivers]
**Independent Test**: [How to verify this story works on its own]
### Tests for User Story 2 (OPTIONAL - only if tests requested) ⚠️
- [ ] T018 [P] [US2] Contract test for [endpoint] in tests/contract/test_[name].py
- [ ] T019 [P] [US2] Integration test for [user journey] in tests/integration/test_[name].py
### Implementation for User Story 2
- [ ] T020 [P] [US2] Create [Entity] model in src/models/[entity].py
- [ ] T021 [US2] Implement [Service] in src/services/[service].py
- [ ] T022 [US2] Implement [endpoint/feature] in src/[location]/[file].py
- [ ] T023 [US2] Integrate with User Story 1 components (if needed)
**Checkpoint**: At this point, User Stories 1 AND 2 should both work independently
---
## Phase 5: User Story 3 - [Title] (Priority: P3)
**Goal**: [Brief description of what this story delivers]
**Independent Test**: [How to verify this story works on its own]
### Tests for User Story 3 (OPTIONAL - only if tests requested) ⚠️
- [ ] T024 [P] [US3] Contract test for [endpoint] in tests/contract/test_[name].py
- [ ] T025 [P] [US3] Integration test for [user journey] in tests/integration/test_[name].py
### Implementation for User Story 3
- [ ] T026 [P] [US3] Create [Entity] model in src/models/[entity].py
- [ ] T027 [US3] Implement [Service] in src/services/[service].py
- [ ] T028 [US3] Implement [endpoint/feature] in src/[location]/[file].py
**Checkpoint**: All user stories should now be independently functional
---
[Add more user story phases as needed, following the same pattern]
---
## Phase N: Polish & Cross-Cutting Concerns
**Purpose**: Improvements that affect multiple user stories
- [ ] TXXX [P] Documentation updates in docs/
- [ ] TXXX Code cleanup and refactoring
- [ ] TXXX Performance optimization across all stories
- [ ] TXXX [P] Additional unit tests (if requested) in tests/unit/
- [ ] TXXX Security hardening
- [ ] TXXX Run quickstart.md validation
---
## Dependencies & Execution Order
### Phase Dependencies
- **Setup (Phase 1)**: No dependencies - can start immediately
- **Foundational (Phase 2)**: Depends on Setup completion - BLOCKS all user stories
- **User Stories (Phase 3+)**: All depend on Foundational phase completion
- User stories can then proceed in parallel (if staffed)
- Or sequentially in priority order (P1 → P2 → P3)
- **Polish (Final Phase)**: Depends on all desired user stories being complete
### User Story Dependencies
- **User Story 1 (P1)**: Can start after Foundational (Phase 2) - No dependencies on other stories
- **User Story 2 (P2)**: Can start after Foundational (Phase 2) - May integrate with US1 but should be independently testable
- **User Story 3 (P3)**: Can start after Foundational (Phase 2) - May integrate with US1/US2 but should be independently testable
### Within Each User Story
- Tests (if included) MUST be written and FAIL before implementation
- Models before services
- Services before endpoints
- Core implementation before integration
- Story complete before moving to next priority
### Parallel Opportunities
- All Setup tasks marked [P] can run in parallel
- All Foundational tasks marked [P] can run in parallel (within Phase 2)
- Once Foundational phase completes, all user stories can start in parallel (if team capacity allows)
- All tests for a user story marked [P] can run in parallel
- Models within a story marked [P] can run in parallel
- Different user stories can be worked on in parallel by different team members
---
## Parallel Example: User Story 1
```bash
# Launch all tests for User Story 1 together (if tests requested):
Task: "Contract test for [endpoint] in tests/contract/test_[name].py"
Task: "Integration test for [user journey] in tests/integration/test_[name].py"
# Launch all models for User Story 1 together:
Task: "Create [Entity1] model in src/models/[entity1].py"
Task: "Create [Entity2] model in src/models/[entity2].py"
```
---
## Implementation Strategy
### MVP First (User Story 1 Only)
1. Complete Phase 1: Setup
2. Complete Phase 2: Foundational (CRITICAL - blocks all stories)
3. Complete Phase 3: User Story 1
4. **STOP and VALIDATE**: Test User Story 1 independently
5. Deploy/demo if ready
### Incremental Delivery
1. Complete Setup + Foundational → Foundation ready
2. Add User Story 1 → Test independently → Deploy/Demo (MVP!)
3. Add User Story 2 → Test independently → Deploy/Demo
4. Add User Story 3 → Test independently → Deploy/Demo
5. Each story adds value without breaking previous stories
### Parallel Team Strategy
With multiple developers:
1. Team completes Setup + Foundational together
2. Once Foundational is done:
- Developer A: User Story 1
- Developer B: User Story 2
- Developer C: User Story 3
3. Stories complete and integrate independently
---
## Notes
- [P] tasks = different files, no dependencies
- [Story] label maps task to specific user story for traceability
- Each user story should be independently completable and testable
- Verify tests fail before implementing
- Commit after each task or logical group
- Stop at any checkpoint to validate story independently
- Avoid: vague tasks, same file conflicts, cross-story dependencies that break independence
+74
View File
@@ -0,0 +1,74 @@
schema_version: "1.0"
workflow:
id: "speckit"
name: "Full SDD Cycle"
version: "1.0.1"
author: "GitHub"
description: "Runs specify → plan → tasks → implement with review gates"
requires:
# 0.8.5 is the first release with engine-side resolution of the
# ``integration: "auto"`` default. Older versions would treat "auto"
# as a literal integration key and fail at dispatch.
speckit_version: ">=0.8.5"
integrations:
# The four commands below (specify, plan, tasks, implement) are core
# spec-kit commands provided by every integration. The list here is an
# advisory, non-exhaustive compatibility hint following the documented
# ``any: [...]`` schema -- it is NOT a closed set. The workflow runs
# against any integration the project was initialized with, including
# ones not listed below, as long as that integration provides the four
# core commands referenced in ``steps``.
any:
- "alquimia"
- "claude"
- "copilot"
- "gemini"
- "opencode"
inputs:
spec:
type: string
required: true
prompt: "Describe what you want to build"
integration:
type: string
default: "auto"
prompt: "Integration to use (e.g. claude, copilot, gemini; 'auto' uses the project's initialized integration)"
steps:
- id: specify
command: speckit.specify
integration: "{{ inputs.integration }}"
input:
args: "{{ inputs.spec }}"
- id: review-spec
type: gate
message: "Review the generated spec before planning."
options: [approve, reject]
on_reject: abort
- id: plan
command: speckit.plan
integration: "{{ inputs.integration }}"
input:
args: "{{ inputs.spec }}"
- id: review-plan
type: gate
message: "Review the plan before generating tasks."
options: [approve, reject]
on_reject: abort
- id: tasks
command: speckit.tasks
integration: "{{ inputs.integration }}"
input:
args: "{{ inputs.spec }}"
- id: implement
command: speckit.implement
integration: "{{ inputs.integration }}"
input:
args: "{{ inputs.spec }}"
+13
View File
@@ -0,0 +1,13 @@
{
"schema_version": "1.0",
"workflows": {
"speckit": {
"name": "Full SDD Cycle",
"version": "1.0.1",
"description": "Runs specify \u2192 plan \u2192 tasks \u2192 implement with review gates",
"source": "bundled",
"installed_at": "2026-10-27T07:17:00.004616+00:00",
"updated_at": "2026-10-27T07:17:00.004650+00:00"
}
}
}
+1 -1
View File
@@ -13,7 +13,7 @@
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test": "python3 scripts/test-postgres.py",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
+114
View File
@@ -0,0 +1,114 @@
#!/usr/bin/env python3
"""Run backend tests against freshly initialized, disposable PostgreSQL only.
Requires Python 3, installed backend dependencies, and PostgreSQL 16+ binaries
(initdb, pg_ctl, postgres) on PATH or in PG_BIN. Never reuses a running database.
Stage-principal /app + Redis integration tests remain separately opt-in.
"""
import os
from pathlib import Path
import shutil
import signal
import socket
import subprocess
import sys
import tempfile
BACKEND = Path(__file__).resolve().parents[1]
def run(args, env=None):
subprocess.run([str(a) for a in args], cwd=BACKEND, env=env, check=True)
def binary(name):
candidate = str(Path(os.environ['PG_BIN']) / name) if os.environ.get('PG_BIN') else shutil.which(name)
if not candidate or not os.access(candidate, os.X_OK):
raise RuntimeError(f'{name} unavailable: install PostgreSQL binaries or set PG_BIN; integration tests cannot be skipped')
return candidate
def interrupted(signum, _frame):
raise SystemExit(128 + signum)
def main():
initdb, pg_ctl = binary('initdb'), binary('pg_ctl')
binary('postgres')
if os.geteuid() == 0:
raise RuntimeError('Run disposable PostgreSQL tests as a non-root user')
for sig in (signal.SIGTERM, signal.SIGINT):
signal.signal(sig, interrupted)
env = os.environ.copy()
# Do not propagate operational database URLs to Prisma schema setup or tests.
for key in list(env):
if key.endswith('DATABASE_URL'):
del env[key]
env.pop('STAGE_PRINCIPAL_DISPOSABLE_TEST', None)
env['DATABASE_URL'] = 'postgresql://disabled@127.0.0.1:1/disabled'
definitions = [
('SEO_TEST_DATABASE_URL', 'seo_test', 55439, 'postgres', ''),
# Keep the existing publication fixture's literal URL allowlist intact.
('PUBLICATION_TEST_DATABASE_URL', 'publication_test', 55447, 'publication_test', None),
('CORPORATE_TEST_DATABASE_URL', 'corporate_test', 55449, 'corporate_test', ''),
]
# Refuse occupied dedicated ports before creating any cluster. PostgreSQL's
# own bind still protects against races; no existing server is ever stopped.
for _, _, port, _, _ in definitions:
with socket.socket() as probe:
probe.bind(('127.0.0.1', port))
started = []
with tempfile.TemporaryDirectory(prefix='backend-pg-', dir=os.environ.get('TMPDIR', '/opt/data/cache/scratch')) as root:
try:
for key, user, port, database, password in definitions:
data = Path(root) / str(port)
unix_socket = Path(root) / f's{port}'
unix_socket.mkdir(mode=0o700)
run([initdb, '-D', data, '-U', user, '--auth=trust', '--no-locale', '--encoding=UTF8'])
# Track our initialized directory before startup, so even an
# interrupted pg_ctl start is cleaned up, never another server.
started.append(data)
run([pg_ctl, '-D', data, '-l', Path(root) / f'{port}.log', '-w', '-t', '30',
'-o', f'-h 127.0.0.1 -p {port} -k {unix_socket}', 'start'])
if password is None:
# The fixture owns its dedicated test-only credential prefix;
# read that literal rather than duplicate or log it here.
import re
fixture = (BACKEND / 'src/seo-tracking/publication.postgres.spec.ts').read_text()
match = re.search(r"url\.startsWith\('([^']+)'\)", fixture)
if not match:
raise RuntimeError('Publication disposable URL allowlist not found')
from urllib.parse import urlsplit
prefix = match.group(1)
parsed = urlsplit(prefix)
if parsed.hostname != '127.0.0.1' or parsed.port != port or parsed.username != user or parsed.path != '/':
raise RuntimeError('Publication allowlist is not the dedicated disposable endpoint')
url = prefix + database
else:
url = f'postgresql://{user}{password}@127.0.0.1:{port}/{database}'
if database != 'postgres':
setup = {**env, 'DATABASE_URL': url.rsplit('/', 1)[0] + '/postgres'}
run(['node', '-e', 'const {PrismaClient}=require("@prisma/client"); const p=new PrismaClient(); '
f'p.$executeRawUnsafe(\'CREATE DATABASE "{database}"\')'
'.finally(()=>p.$disconnect()).catch(e=>{console.error(e);process.exitCode=1})'], setup)
run([BACKEND / 'node_modules/.bin/prisma', 'db', 'push', '--skip-generate'], {**env, 'DATABASE_URL': url})
env[key] = url
print('Disposable PostgreSQL ready: SEO, publication and corporate integration enabled; '
'Stage-principal Redis+/app suites remain explicitly out of scope.', flush=True)
run([BACKEND / 'node_modules/.bin/jest', '--runInBand', *sys.argv[1:]], env)
finally:
failures = []
for data in reversed(started):
result = subprocess.run([pg_ctl, '-D', str(data), '-m', 'immediate', '-w', '-t', '30', 'stop'], cwd=BACKEND)
if result.returncode and (data / 'postmaster.pid').exists():
failures.append(str(data))
if failures:
raise RuntimeError(f'Failed to stop disposable clusters: {failures}')
if __name__ == '__main__':
try:
main()
except (RuntimeError, OSError, subprocess.CalledProcessError) as error:
print(f'Backend PostgreSQL test gate failed: {error}', file=sys.stderr)
sys.exit(1)
@@ -1,5 +1,42 @@
import { normalizeSearch, pagination, taskInput } from './corporate-policy';
import {
normalizeSearch,
pagination,
taskInput,
monthlyPlanInput,
} from './corporate-policy';
describe('corporate contract policy', () => {
it.each([
['2027-02', 28],
['2028-02', 29],
['2028-04', 30],
['2028-01', 31],
])('enforces real calendar coverage for %s', (month, count) => {
const id = '11111111-1111-4111-8111-111111111111';
const body = {
roadmapId: id,
month,
needs: [],
dailyArticles: Array.from({ length: Number(count) }, (_, i) => ({
title: 'new article',
description: 'instruction',
actionType: 'BLOG_NEW',
department: 'CONTENT_SEO',
goalId: id,
sourceIds: [id],
dueCycle: `${month}-${String(i + 1).padStart(2, '0')}`,
})),
};
expect(monthlyPlanInput(body).dailyArticles).toHaveLength(Number(count));
expect(() =>
monthlyPlanInput({ ...body, dailyArticles: body.dailyArticles.slice(1) }),
).toThrow();
expect(() =>
monthlyPlanInput({
...body,
dailyArticles: [...body.dailyArticles, body.dailyArticles[0]],
}),
).toThrow();
});
it('normalizes Persian letters, digits and separators', () => {
expect(normalizeSearch('كيك ۱۲۳ (ة)‌')).toBe('کیک 123 ه');
});
+99 -2
View File
@@ -39,7 +39,7 @@ export function uuid(value: unknown): string {
)
)
throw new BadRequestException('Invalid UUID');
return id;
return id.toLowerCase();
}
export function choice(value: unknown, values: string[]): string {
if (typeof value !== 'string' || !values.includes(value))
@@ -124,12 +124,108 @@ export function taskInput(input: unknown) {
'BLOG_NEW',
'BLOG_UPDATE',
'CATALOG_ENRICH',
'WIKI_ENRICH',
'RESEARCH',
'ENGINEERING',
]),
dueCycle: b.dueCycle === undefined ? undefined : text(b.dueCycle, 40),
};
}
export function planMonth(value: unknown): string {
const month = text(value, 7);
if (!/^(?:[2-9]\d{3})-(?:0[1-9]|1[0-2])$/.test(month))
throw new BadRequestException('Invalid YYYY-MM month');
return month;
}
export function monthlyPlanInput(input: unknown) {
const b = object(input, ['roadmapId', 'month', 'dailyArticles', 'needs']);
const month = planMonth(b.month);
const days = new Date(
Date.UTC(Number(month.slice(0, 4)), Number(month.slice(5)), 0),
).getUTCDate();
if (
!Array.isArray(b.dailyArticles) ||
b.dailyArticles.length !== days ||
!Array.isArray(b.needs) ||
b.needs.length > 200
)
throw new BadRequestException(
'Full daily article coverage and bounded needs required',
);
const mapping: Record<string, string> = {
BLOG_NEW: 'CONTENT_SEO',
BLOG_UPDATE: 'CONTENT_SEO',
CATALOG_ENRICH: 'CATALOG_COMMERCE',
WIKI_ENRICH: 'WIKI_SCIENTIFIC',
ENGINEERING: 'TECH_DEVOPS',
};
const parse = (raw: unknown, daily: boolean) => {
const t = object(raw, [
'title',
'description',
'department',
'priority',
'goalId',
'actionType',
'dueCycle',
'sourceIds',
'target',
'reason',
]);
const actionType = choice(
t.actionType,
daily
? ['BLOG_NEW']
: ['BLOG_UPDATE', 'CATALOG_ENRICH', 'WIKI_ENRICH', 'ENGINEERING'],
);
const department = choice(t.department, [mapping[actionType]]);
const dueCycle = text(t.dueCycle, 10);
const date = new Date(dueCycle + 'T00:00:00Z');
if (
!/^\d{4}-\d{2}-\d{2}$/.test(dueCycle) ||
!dueCycle.startsWith(month + '-') ||
!Number.isFinite(date.getTime()) ||
date.toISOString().slice(0, 10) !== dueCycle
)
throw new BadRequestException('Invalid plan day');
if (
!Array.isArray(t.sourceIds) ||
!t.sourceIds.length ||
t.sourceIds.length > 30
)
throw new BadRequestException('Stored sources required');
const sourceIds = t.sourceIds.map(uuid);
if (new Set(sourceIds).size !== sourceIds.length)
throw new BadRequestException('Duplicate source');
if (daily && (t.target !== undefined || t.reason !== undefined))
throw new BadRequestException('Daily new articles cannot be needs');
return {
title: text(t.title, 300),
description: text(t.description),
department,
actionType,
dueCycle,
priority: choice(t.priority ?? 'MEDIUM', priorities),
goalId: uuid(t.goalId),
sourceIds,
...(daily
? {}
: { target: text(t.target, 2000), reason: text(t.reason) }),
};
};
const dailyArticles = b.dailyArticles.map((t) => parse(t, true));
if (new Set(dailyArticles.map((t) => t.dueCycle)).size !== days)
throw new BadRequestException(
'Exactly one new article per calendar day required',
);
const needs = b.needs.map((t) => parse(t, false));
if (
new Set(needs.map((t) => canonical([t.actionType, t.target, t.dueCycle])))
.size !== needs.length
)
throw new BadRequestException('Duplicate need');
return { roadmapId: uuid(b.roadmapId), month, dailyArticles, needs };
}
export function canonical(value: any): string {
if (Array.isArray(value)) return '[' + value.map(canonical).join(',') + ']';
if (value && typeof value === 'object')
@@ -158,7 +254,8 @@ export function publicData(value: any): any {
export function httpsUrl(value: unknown): string {
const raw = text(value, 2000);
try {
if (!/^https:\/\/[a-z0-9]/i.test(raw) || /[\s\\]/.test(raw)) throw new Error();
if (!/^https:\/\/[a-z0-9]/i.test(raw) || /[\s\\]/.test(raw))
throw new Error();
const u = new URL(raw);
const host = u.hostname.toLowerCase();
if (
@@ -108,6 +108,23 @@ export class CorporateController {
) {
return this.service.roadmap(this.actor(req), this.key(key), body);
}
@Post('monthly-plans') persistMonthlyPlan(
@Req() req: any,
@Headers('idempotency-key') key: string,
@Body() body: unknown,
) {
return this.service.persistMonthlyPlan(
this.actor(req),
this.key(key),
body,
);
}
@Get('monthly-plans/:roadmapId') monthlyPlan(
@Param('roadmapId') roadmapId: string,
@Query('month') month: string,
) {
return this.service.monthlyPlan(roadmapId, month);
}
@Get('reports') reports(@Query() q: Record<string, any>) {
return this.service.collection('reports', q);
}
@@ -1,9 +1,14 @@
import { readFileSync } from 'fs';
import { resolve } from 'path';
import { execFile } from 'child_process';
import { promisify } from 'util';
import passport from 'passport';
import { Strategy, ExtractJwt } from 'passport-jwt';
import { PrismaClient } from '@prisma/client';
import { Test } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import { randomUUID } from 'crypto';
import { createHash, randomUUID } from 'crypto';
import { canonical } from './corporate-policy';
import request from 'supertest';
import { PrismaService } from '../../prisma/prisma.service';
import { CorporateController } from './corporate.controller';
@@ -80,6 +85,409 @@ integration('corporate API / disposable PostgreSQL', () => {
'TRUNCATE corporate_operations, corporate_reports, corporate_effects, corporate_reviews, corporate_evidence, corporate_events, corporate_tasks, corporate_goals, corporate_roadmaps, corporate_sources, corporate_research CASCADE',
);
});
describe('exact task claim selector', () => {
it('claims only the exact task, leaving the older eligible task untouched', async () => {
const older = (await post('tasks', input).expect(201)).body;
const target = (
await post('tasks', { ...input, title: 'target' }).expect(201)
).body;
await db.corporateTask.update({
where: { id: older.id },
data: { updatedAt: new Date('2020-01-01T00:00:00Z') },
});
const result = (
await post('claims', { taskId: target.id.toUpperCase() }).expect(201)
).body;
expect(result.task.id).toBe(target.id);
expect(result.task.executionCount).toBe(1);
expect(
await db.corporateTask.findUniqueOrThrow({ where: { id: older.id } }),
).toMatchObject({
status: 'TODO',
executionCount: 0,
claimToken: null,
});
expect(
await db.corporateEvent.count({
where: { taskId: older.id, step: 'CLAIMED' },
}),
).toBe(0);
});
it('does not bypass the future PLANNED gate or fall back to another task', async () => {
const legacy = (await post('tasks', input).expect(201)).body;
const { body } = await planFixture();
const plan = (await post('monthly-plans', body).expect(201)).body;
const target = plan.tasks[0];
expect(
(await post('claims', { taskId: target.id }).expect(201)).body.task,
).toBeNull();
expect(
await db.corporateTask.findUniqueOrThrow({ where: { id: target.id } }),
).toMatchObject({
status: 'TODO',
executionCount: 0,
claimToken: null,
});
expect((await post('claims', {}).expect(201)).body.task.id).toBe(
legacy.id,
);
});
it('rejects invalid UUID selectors before recording any operation', async () => {
for (const taskId of ['not-a-uuid', "' OR true --", '', null, 123])
await post('claims', { taskId }).expect(400);
expect(await db.corporateOperation.count()).toBe(0);
});
it('binds idempotency to the normalized selector and never claims a replacement', async () => {
const a = (await post('tasks', input).expect(201)).body;
const b = (await post('tasks', { ...input, title: 'other' }).expect(201))
.body;
const op = key();
const claimed = (
await post('claims', { taskId: a.id }, 'executor', op).expect(201)
).body;
expect(
(
await post(
'claims',
{ taskId: a.id.toUpperCase() },
'executor',
op,
).expect(201)
).body,
).toEqual(claimed);
await post('claims', { taskId: b.id }, 'executor', op).expect(409);
await post('claims', {}, 'executor', op).expect(409);
const legacyOp = key();
const legacy = (
await post('claims', {}, 'executor', legacyOp).expect(201)
).body;
expect(legacy.task.id).toBe(b.id);
await post('claims', { taskId: b.id }, 'executor', legacyOp).expect(409);
expect(
await db.corporateEvent.count({ where: { step: 'CLAIMED' } }),
).toBe(2);
});
it('preserves the historical no-selector hash and replay response', async () => {
const op = key();
const hash = (value: unknown) =>
createHash('sha256').update(canonical(value)).digest('hex');
const response = { task: null };
await db.corporateOperation.create({
data: {
key: hash(['apikey:executor', 'claim', op]),
payloadHash: hash({ department: null, seconds: 300 }),
response,
},
});
await post('tasks', input).expect(201);
expect(
(await post('claims', {}, 'executor', op).expect(201)).body,
).toEqual(response);
expect(
await db.corporateEvent.count({ where: { step: 'CLAIMED' } }),
).toBe(0);
});
});
async function planFixture(month = '2996-02') {
const research = (
await post('market-insights', {
title: 'monthly fixture',
category: 'TREND',
source: 'disposable receipt',
opportunity: 'test planning',
impact: 'LOW',
recommendedAction: 'plan',
cadence: 'MONTHLY',
provenance: {
method: 'fixture',
collector: 'jest',
context: 'disposable',
},
sources: [
{
url: 'https://pubmed.ncbi.nlm.nih.gov/',
title: 'fixture',
excerpt: 'test only',
retrievedAt: '2026-01-01T00:00:00Z',
sha256: 'a'.repeat(64),
},
],
}).expect(201)
).body;
const roadmap = (
await post('monthly-roadmap', {
researchId: research.id,
month,
cycleName: 'monthly fixture',
seasonalTheme: 'test',
strategicGoals: ['coverage'],
plannedArticlesCount: 29,
plannedRefreshesCount: 0,
plannedCatalogEnrichments: 0,
goals: [
'CONTENT_SEO',
'CATALOG_COMMERCE',
'WIKI_SCIENTIFIC',
'TECH_DEVOPS',
].map((department) => ({
title: department,
department,
acceptanceCriteria: 'independent QA',
metric: 'coverage',
})),
}).expect(201)
).body;
const task = (
actionType: string,
department: string,
dueCycle: string,
) => ({
title: actionType + ' ' + dueCycle,
description: 'Evidence-backed instruction requiring QA',
actionType,
department,
dueCycle,
goalId: roadmap.goals.find((g: any) => g.department === department).id,
sourceIds: [research.sources[0].id],
...(actionType === 'BLOG_NEW'
? {}
: {
target: 'https://canina.ir/identified-gap',
reason: 'Documented coverage gap',
}),
});
return {
research,
roadmap,
body: {
roadmapId: roadmap.id,
month,
dailyArticles: Array.from({ length: 29 }, (_, i) =>
task(
'BLOG_NEW',
'CONTENT_SEO',
`${month}-${String(i + 1).padStart(2, '0')}`,
),
),
needs: [
task('BLOG_UPDATE', 'CONTENT_SEO', month + '-01'),
task('CATALOG_ENRICH', 'CATALOG_COMMERCE', month + '-02'),
task('WIKI_ENRICH', 'WIKI_SCIENTIFIC', month + '-03'),
task('ENGINEERING', 'TECH_DEVOPS', month + '-04'),
],
},
};
}
it('runs manual planned inventory through HTTP, independent QA and persisted PMO without completing article', async () => {
const { body, research, roadmap } = await planFixture('2024-02');
// Real repository bytes, not invented clinical evidence or provider output.
const script = resolve(__dirname, '../../../../scripts/corporate_plan_inventory.py');
await db.corporateSource.update({
where: { id: research.sources[0].id },
data: { sha256: createHash('sha256').update(readFileSync(script)).digest('hex') },
});
const plan = (await post('monthly-plans', body).expect(201)).body;
const parent = plan.tasks.find((t: any) => t.actionType === 'BLOG_NEW');
const address = app.getHttpServer().address();
const result = await promisify(execFile)('python3', [
resolve(__dirname, '../../../../scripts/corporate_plan_inventory_http_test.py'),
`http://127.0.0.1:${address.port}`, roadmap.id, body.month, parent.id,
], { timeout: 20000 });
const receipt = JSON.parse(result.stdout);
expect(receipt).toMatchObject({ originalStatus: 'BLOCKED', independentQA: true,
selfReviewDenied: true, persistedPMOReadback: true });
console.log('MANUAL_PLAN_INVENTORY_RECEIPT', receipt);
});
it('persists a complete leap-month daily-new plan, separate needs and evidence lineage with readback', async () => {
const { body, research, roadmap } = await planFixture();
body.roadmapId = body.roadmapId.toUpperCase();
for (const entry of [...body.dailyArticles, ...body.needs]) {
entry.goalId = entry.goalId.toUpperCase();
entry.sourceIds = entry.sourceIds.map((id: string) => id.toUpperCase());
}
const op = key();
const created = (
await post('monthly-plans', body, 'planner', op).expect(201)
).body;
expect(created.tasks).toHaveLength(33);
const need = created.tasks.find((t: any) => t.actionType === 'WIKI_ENRICH');
expect(need.logs[0].payload).toMatchObject({
target: body.needs[2].target,
reason: body.needs[2].reason,
});
expect(
created.tasks.filter((t: any) => t.actionType === 'BLOG_NEW'),
).toHaveLength(29);
expect(created.tasks.every((t: any) => t.status === 'TODO')).toBe(true);
expect(
(await post('monthly-plans', body, 'planner', op).expect(201)).body,
).toEqual(created);
const read = await request(app.getHttpServer())
.get(
`/admin/hermes/monthly-plans/${roadmap.id.toUpperCase()}?month=${body.month}`,
)
.set('x-api-key', 'executor')
.expect(200);
expect(read.body).toEqual(created);
const detail = await request(app.getHttpServer())
.get('/admin/hermes/tasks/' + created.tasks[0].id)
.set('x-api-key', 'executor')
.expect(200);
expect(detail.body.logs[0].step).toBe('PLANNED');
expect(detail.body.logs[0].payload).toMatchObject({
researchId: research.id,
roadmapId: roadmap.id,
month: body.month,
dueCycle: body.month + '-01',
sourceIds: [research.sources[0].id],
});
expect(await db.corporateOperation.count()).toBe(3);
expect((await post('claims', {}).expect(201)).body.task).toBeNull();
});
it('validates calendar, action separation, needs and stored lineage without partial writes', async () => {
const { body } = await planFixture();
const mutations: Array<[number, (b: any) => void]> = [
[400, (b) => b.dailyArticles.pop()],
[400, (b) => (b.dailyArticles[1].dueCycle = b.dailyArticles[0].dueCycle)],
[400, (b) => (b.dailyArticles[0].dueCycle = '2028-02-30')],
[400, (b) => (b.month = '2028-13')],
[400, (b) => (b.dailyArticles[0].actionType = 'BLOG_UPDATE')],
[400, (b) => (b.needs[0].actionType = 'BLOG_NEW')],
[400, (b) => (b.needs[0].reason = ' ')],
[400, (b) => delete b.needs[0].target],
[400, (b) => (b.needs[0].department = 'WIKI_SCIENTIFIC')],
[400, (b) => (b.dailyArticles[0].sourceIds = [])],
[409, (b) => (b.dailyArticles[0].sourceIds = [key()])],
[409, (b) => (b.dailyArticles[0].goalId = key())],
[409, (b) => (b.needs[0].goalId = b.needs[1].goalId)],
[409, (b) => (b.roadmapId = key())],
];
for (const [status, mutate] of mutations) {
const invalid = JSON.parse(JSON.stringify(body));
mutate(invalid);
await post('monthly-plans', invalid).expect(status);
expect(await db.corporateTask.count()).toBe(0);
expect(await db.corporateEvent.count()).toBe(0);
expect(await db.corporateOperation.count()).toBe(2);
}
});
it('serializes competing actors and keys on roadmap/month, rejects changed replay and keeps auth dormant', async () => {
const { body } = await planFixture();
await request(app.getHttpServer())
.post('/admin/hermes/monthly-plans')
.send(body)
.expect(401);
await post('monthly-plans', body, 'unscoped').expect(403);
const op = key();
const otherOp = key();
let release!: () => void;
let ready!: () => void;
const locked = new Promise<void>((r) => (ready = r));
const hold = new Promise<void>((r) => (release = r));
const scope = JSON.stringify(['monthly-plan', body.roadmapId, body.month]);
const blocker = db.$transaction(async (tx) => {
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${scope}, 0))`;
ready();
await hold;
});
await locked;
const pending = [
post('monthly-plans', body, 'planner', op).then((r) => r),
post('monthly-plans', body, 'other', otherOp).then((r) => r),
];
try {
let waiters = 0;
for (let i = 0; i < 100; i++) {
const rows = await db.$queryRaw<any[]>`SELECT pid FROM pg_stat_activity
WHERE datname=current_database() AND wait_event_type='Lock' AND query LIKE '%pg_advisory_xact_lock%'`;
waiters = rows.length;
if (waiters >= 2) break;
await new Promise((r) => setTimeout(r, 10));
}
expect(waiters).toBeGreaterThanOrEqual(2);
} finally {
release();
await blocker;
}
const results = await Promise.all(pending);
expect(results.map((r) => r.status).sort()).toEqual([201, 409]);
expect(await db.corporateTask.count()).toBe(33);
expect(await db.corporateEvent.count({ where: { step: 'PLANNED' } })).toBe(
33,
);
const winner = results[0].status === 201 ? 'planner' : 'other';
const winningOp = winner === 'planner' ? op : otherOp;
await post(
'monthly-plans',
{ ...body, needs: [] },
winner,
winningOp,
).expect(409);
expect(
(await post('monthly-plans', body, winner, winningOp).expect(201)).body,
).toEqual(results[winner === 'planner' ? 0 : 1].body);
const runtime = await request(app.getHttpServer())
.get('/admin/hermes/runtime')
.set('x-api-key', 'executor')
.expect(200);
expect(runtime.body).toEqual({
mode: 'MANUAL_DORMANT',
schedulesEnabled: false,
externalExecutionEnabled: false,
});
});
it('rolls back a mid-plan database failure including tasks, events and idempotency receipt', async () => {
const { body } = await planFixture();
// Disposable-only trigger fails after the first task/event have been written.
await db.$executeRawUnsafe(
`CREATE FUNCTION reject_plan_event() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.step='PLANNED' AND NEW.payload->>'dueCycle'='2996-02-02' THEN RAISE EXCEPTION 'injected plan failure'; END IF; RETURN NEW; END $$`,
);
await db.$executeRawUnsafe(
'CREATE TRIGGER reject_plan_event BEFORE INSERT ON corporate_events FOR EACH ROW EXECUTE FUNCTION reject_plan_event()',
);
const op = key();
try {
await post('monthly-plans', body, 'planner', op).expect(500);
expect(await db.corporateTask.count()).toBe(0);
expect(await db.corporateEvent.count()).toBe(0);
expect(await db.corporateOperation.count()).toBe(2);
} finally {
await db.$executeRawUnsafe(
'DROP TRIGGER reject_plan_event ON corporate_events',
);
await db.$executeRawUnsafe('DROP FUNCTION reject_plan_event()');
}
await post('monthly-plans', body, 'planner', op).expect(201);
});
it('gates only PLANNED future tasks while legacy future dueCycle remains claimable and UTC today is eligible', async () => {
const { body } = await planFixture();
await post('monthly-plans', body).expect(201);
const legacy = (
await post('tasks', { ...input, dueCycle: '2999-12-31' }).expect(201)
).body;
expect((await post('claims', {}).expect(201)).body.task.id).toBe(legacy.id);
expect((await post('claims', {}).expect(201)).body.task).toBeNull();
// Model the persisted event's due-day boundary in the disposable DB without changing system time.
const planned = await db.corporateTask.findFirstOrThrow({
where: { actionType: 'BLOG_NEW' },
});
const day = new Date().toISOString().slice(0, 10);
await db.corporateTask.update({
where: { id: planned.id },
data: { dueCycle: day },
});
expect((await post('claims', {}).expect(201)).body.task).toBeNull(); // mismatch fails closed
const event = await db.corporateEvent.findFirstOrThrow({
where: { taskId: planned.id, step: 'PLANNED' },
});
await db.corporateEvent.update({
where: { id: event.id },
data: { payload: { ...(event.payload as object), dueCycle: day } },
});
expect((await post('claims', {}).expect(201)).body.task.id).toBe(
planned.id,
);
});
it('rejects children after a parent claim commits while child creation waits on its row lock', async () => {
const parent = (await post('tasks', input).expect(201)).body;
let release!: () => void, locked!: () => void;
+144 -3
View File
@@ -9,6 +9,8 @@ import { createHash, randomUUID } from 'crypto';
import { PrismaService } from '../../prisma/prisma.service';
import {
canonical,
monthlyPlanInput,
planMonth,
publicData,
choice,
departments,
@@ -118,7 +120,22 @@ export class CorporateService {
take: p.limit,
orderBy: [{ [p.sortBy]: p.sortOrder }, { id: 'asc' }],
});
return publicData({ data, meta: meta(total, p.page, p.limit) });
const deptGroup = await tx.corporateTask.groupBy({
by: ['department'],
_count: { id: true },
});
const departmentCounts: Record<string, number> = {};
for (const d of departments) departmentCounts[d] = 0;
for (const row of deptGroup) {
departmentCounts[row.department] = row._count.id;
}
return publicData({
data,
meta: {
...meta(total, p.page, p.limit),
departmentCounts,
},
});
},
{ isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead },
);
@@ -188,8 +205,127 @@ export class CorporateService {
return task;
});
}
private plannedWhere(
roadmapId: string,
month: string,
): Prisma.CorporateEventWhereInput {
return {
step: 'PLANNED',
AND: [
{ payload: { path: ['roadmapId'], equals: roadmapId } },
{ payload: { path: ['month'], equals: month } },
],
};
}
private async readPlan(tx: Tx, roadmapId: string, month: string) {
const roadmap = await tx.corporateRoadmap.findUnique({
where: { id: roadmapId },
});
const tasks = await tx.corporateTask.findMany({
where: { logs: { some: this.plannedWhere(roadmapId, month) } },
include: {
logs: {
where: this.plannedWhere(roadmapId, month),
orderBy: { id: 'asc' },
},
},
orderBy: [{ dueCycle: 'asc' }, { actionType: 'asc' }, { id: 'asc' }],
});
if (!roadmap || !tasks.length)
throw new NotFoundException('Monthly plan not found');
return publicData({
roadmapId,
month,
researchId: roadmap.researchId,
tasks,
});
}
monthlyPlan(roadmapId: string, month: unknown) {
roadmapId = uuid(roadmapId);
const cycle = planMonth(month);
return this.db.$transaction((tx) => this.readPlan(tx, roadmapId, cycle), {
isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead,
});
}
persistMonthlyPlan(actor: string, key: string, input: unknown) {
const b = monthlyPlanInput(input);
return this.operation(actor, 'monthly-plan', key, b, async (tx) => {
// Separate actor/key-independent fence: one complete plan per roadmap/month.
const scope = canonical(['monthly-plan', b.roadmapId, b.month]);
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${scope}, 0))`;
if (
await tx.corporateEvent.count({
where: this.plannedWhere(b.roadmapId, b.month),
})
)
throw new ConflictException('Monthly plan already persisted');
const roadmap = await tx.corporateRoadmap.findUnique({
where: { id: b.roadmapId },
include: { goals: true, research: { include: { sources: true } } },
});
if (
!roadmap ||
roadmap.month !== b.month ||
!roadmap.research.sources.length
)
throw new ConflictException(
'Matching evidence-backed roadmap required',
);
const entries = [...b.dailyArticles, ...b.needs];
for (const entry of entries) {
if (
!roadmap.goals.some(
(g) => g.id === entry.goalId && g.department === entry.department,
) ||
!entry.sourceIds.every((id) =>
roadmap.research.sources.some((s) => s.id === id),
)
)
throw new ConflictException(
'Goal/department and source lineage must match roadmap research',
);
}
for (const entry of entries) {
const { sourceIds, target, reason, ...data } = entry;
const taskCode = 'TSK-' + randomUUID();
const task = await tx.corporateTask.create({
data: {
...data,
priority: data.priority as CorporatePriority,
status: 'TODO',
taskCode,
normalizedCode: normalizeSearch(taskCode),
normalizedTitle: normalizeSearch(data.title),
createdBy: actor,
},
});
await this.event(
tx,
task.id,
actor,
'PLANNED',
entry.description,
'SYSTEM',
{
version: 1,
roadmapId: roadmap.id,
researchId: roadmap.researchId,
month: b.month,
goalId: entry.goalId,
department: entry.department,
actionType: entry.actionType,
dueCycle: entry.dueCycle,
sourceIds,
...(target ? { target, reason } : {}),
},
);
}
return this.readPlan(tx, b.roadmapId, b.month);
});
}
claim(actor: string, key: string, input: unknown) {
const b = object(input, ['department', 'leaseSeconds']);
const b = object(input, ['department', 'leaseSeconds', 'taskId']);
const taskId = b.taskId === undefined ? undefined : uuid(b.taskId);
const department =
b.department === undefined ? null : choice(b.department, departments);
const seconds = Number(b.leaseSeconds ?? 300);
@@ -199,12 +335,17 @@ export class CorporateService {
actor,
'claim',
key,
{ department, seconds },
{ department, seconds, ...(taskId === undefined ? {} : { taskId }) },
async (tx) => {
const candidates = await tx.$queryRaw<
{ id: string }[]
>`SELECT t.id FROM corporate_tasks t
WHERE (t.status='TODO' OR (t.status='BLOCKED' AND EXISTS (SELECT 1 FROM corporate_tasks c WHERE c."parentId"=t.id)) OR (t.status='IN_PROGRESS' AND t."leasedUntil"<=clock_timestamp()))
AND NOT EXISTS (SELECT 1 FROM corporate_events e WHERE e."taskId"=t.id AND e.step='PLANNED'
AND (t."dueCycle" IS NULL OR t."dueCycle" !~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}$'
OR e.payload->>'dueCycle' IS DISTINCT FROM t."dueCycle"
OR t."dueCycle">to_char(clock_timestamp() AT TIME ZONE 'UTC','YYYY-MM-DD')))
AND (${taskId ?? null}::text IS NULL OR t.id=${taskId ?? null}::uuid)
AND (${department}::text IS NULL OR t.department=${department})
AND NOT EXISTS (SELECT 1 FROM corporate_tasks c WHERE c."parentId"=t.id AND c.status<>'DONE')
ORDER BY t.priority ASC,t."updatedAt" ASC,t.id ASC FOR UPDATE OF t SKIP LOCKED LIMIT 1`;
+1 -20
View File
@@ -3,7 +3,6 @@ import { NestExpressApplication } from "@nestjs/platform-express";
import { AppModule } from "./app.module";
import { join } from "path";
import { ValidationPipe, BadRequestException } from "@nestjs/common";
import { SwaggerModule, DocumentBuilder } from "@nestjs/swagger";
import { CustomHttpExceptionFilter } from "./common/filters/http-exception.filter";
import { PrismaExceptionFilter } from "./common/filters/prisma-exception.filter";
import { DecimalInterceptor } from "./common/interceptors/decimal.interceptor";
@@ -144,25 +143,7 @@ async function bootstrap() {
app.useGlobalInterceptors(new DecimalInterceptor());
const isProduction = process.env.NODE_ENV === "production";
const isSwaggerExplicitlyDisabled = process.env.ENABLE_SWAGGER === "false";
if (!isProduction && !isSwaggerExplicitlyDisabled) {
const config = new DocumentBuilder()
.setTitle("Canina Iran API")
.setDescription(
"API Documentation for Canina Iran Pet Health & Supplement Platform",
)
.setVersion("1.0.0")
.addBearerAuth()
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup("api/docs", app, document);
console.log("Swagger UI is ACTIVE on /api/docs");
} else {
console.log("Swagger UI is DISABLED for security (production environment)");
}
// Swagger UI is permanently disabled across all environments for security
await app.listen(process.env.PORT ?? 4001);
}
@@ -72,6 +72,23 @@ run('SEO disposable PostgreSQL integration', () => {
periodEnd: '2026-01-02T00:00:00Z',
sourceMetadata: metadata,
};
it('replays exact non-round doubles and nested numeric JSON without accepting changed evidence', async () => {
const position = 3.1818181818181817;
const precise = {
...snapshot, ingestionKey: 'precise-numeric-replay', gscPosition: position,
gscClicks: 35, gscImpressions: 11,
sourceMetadata: { ...metadata,
gsc: { ...metadata.gsc, status: 'available' },
worker: { nested: [{ position, duration: 18.333333333333332 }] },
},
};
const [a, b] = await Promise.all([service.addSnapshot(id, precise), service.addSnapshot(id, precise)]);
expect(a.id).toBe(b.id);
expect((await service.addSnapshot(id, precise)).id).toBe(a.id);
await expect(service.addSnapshot(id, { ...precise, gscPosition: position + Number.EPSILON * 2 })).rejects.toMatchObject({ status: 409 });
await expect(service.addSnapshot(id, { ...precise, sourceMetadata: { ...precise.sourceMetadata, worker: { nested: [{ position: position + Number.EPSILON * 2, duration: 18.333333333333332 }] } } })).rejects.toMatchObject({ status: 409 });
await db.contentPerformanceSnapshot.delete({ where: { id: a.id } });
});
it('preserves null unavailable, idempotent concurrent retries, and conflicts', async () => {
const [a, b] = await Promise.all([
service.addSnapshot(id, snapshot),
@@ -239,21 +239,21 @@ export class SeoTrackingService {
findingId_ingestionKey: { findingId, ingestionKey: dto.ingestionKey },
},
});
const same = (row: any) => {
const canonical = (v: any): string =>
JSON.stringify(
v && typeof v === 'object' && !(v instanceof Date)
? Object.keys(v)
.sort()
.reduce(
(o, k) => ((o[k] = JSON.parse(canonical(v[k]))), o),
{} as Record<string, any>,
)
: v,
);
const same = async (row: any) => {
// Compare numeric provenance and Float columns in PostgreSQL itself:
// Prisma's JSON protocol rounds some doubles on readback. A tolerance in
// JavaScript would also accept genuinely changed payloads.
const [stored] = await this.prisma.$queryRaw<{ matches: boolean }[]>`
SELECT source_metadata = ${JSON.stringify(dto.sourceMetadata)}::jsonb
AND gsc_position IS NOT DISTINCT FROM ${metrics.gscPosition === null ? null : String(metrics.gscPosition)}::double precision
AND ga4_avg_engagement_sec IS NOT DISTINCT FROM ${metrics.ga4AvgEngagementSec === null ? null : String(metrics.ga4AvgEngagementSec)}::double precision
AND ga4_bounce_rate IS NOT DISTINCT FROM ${metrics.ga4BounceRate === null ? null : String(metrics.ga4BounceRate)}::double precision
AND ga4_scroll_depth_rate IS NOT DISTINCT FROM ${metrics.ga4ScrollDepthRate === null ? null : String(metrics.ga4ScrollDepthRate)}::double precision AS matches
FROM content_performance_snapshots WHERE id = ${row.id}::uuid`;
if (!stored?.matches) return false;
return Object.entries(data).every(([k, v]) =>
k === 'sourceMetadata'
? canonical(row[k]) === canonical(v)
['sourceMetadata', 'gscPosition', 'ga4AvgEngagementSec', 'ga4BounceRate', 'ga4ScrollDepthRate'].includes(k)
? true
: k === 'periodStart' || k === 'periodEnd'
? new Date(row[k]).getTime() === (v as Date).getTime()
: k === 'attributedSalesValue'
@@ -264,13 +264,26 @@ export class SeoTrackingService {
);
};
if (existing) {
if (!same(existing))
if (!(await same(existing)))
throw new ConflictException('Ingestion key reused with different data');
return existing;
}
await this.findOne(findingId);
try {
return await this.prisma.contentPerformanceSnapshot.create({ data });
return await this.prisma.$transaction(async (tx) => {
const row = await tx.contentPerformanceSnapshot.create({ data });
// Preserve JSON/IEEE-754 input exactly despite Prisma's numeric JSON
// transport rounding. Text parameters are parsed by PostgreSQL, not
// reserialized as engine floats. This update is atomic with creation.
await tx.$executeRaw`UPDATE content_performance_snapshots SET
source_metadata = ${JSON.stringify(dto.sourceMetadata)}::jsonb,
gsc_position = ${metrics.gscPosition === null ? null : String(metrics.gscPosition)}::double precision,
ga4_avg_engagement_sec = ${metrics.ga4AvgEngagementSec === null ? null : String(metrics.ga4AvgEngagementSec)}::double precision,
ga4_bounce_rate = ${metrics.ga4BounceRate === null ? null : String(metrics.ga4BounceRate)}::double precision,
ga4_scroll_depth_rate = ${metrics.ga4ScrollDepthRate === null ? null : String(metrics.ga4ScrollDepthRate)}::double precision
WHERE id = ${row.id}::uuid`;
return row;
});
} catch (error) {
if ((error as any).code === 'P2002') {
const row =
@@ -282,7 +295,7 @@ export class SeoTrackingService {
},
},
});
if (same(row)) return row;
if (await same(row)) return row;
throw new ConflictException('Ingestion key reused with different data');
}
throw error;
+44 -2
View File
@@ -59,16 +59,58 @@ describe("WikiService", () => {
where: {
OR: [
{ term: { contains: "مفصل", mode: "insensitive" } },
{ key: { contains: "مفصل", mode: "insensitive" } },
{ definition: { contains: "مفصل", mode: "insensitive" } },
{ term: { contains: "مفصل", mode: "insensitive" } },
{ key: { contains: "مفصل", mode: "insensitive" } },
],
},
skip: 0,
take: 10,
// Search retrieves bounded candidates, then ranks and slices in memory.
skip: undefined,
take: 100,
orderBy: { term: "desc" },
});
expect(result.data).toEqual(mockTerms);
expect(result.meta.total).toBe(1);
expect(result.meta.lastPage).toBe(1);
expect(mockPrisma.scientificTerm.count).toHaveBeenCalledWith({
where: mockPrisma.scientificTerm.findMany.mock.calls[0][0].where,
});
});
it("ranks search candidates before slicing page two and retains filtered total", async () => {
const exact = { key: "joint", term: "مفصل", definition: "" };
const partial = { key: "joint-care", term: "مفصل سالم", definition: "" };
const description = { key: "care", term: "مراقبت", definition: "مفصل" };
mockPrisma.scientificTerm.findMany.mockResolvedValue([description, exact, partial]);
mockPrisma.scientificTerm.count.mockResolvedValue(3);
const result = await service.findAll({ search: "مفصل", page: 2, limit: 1 });
expect(result.data).toEqual([partial]);
expect(result.meta).toEqual({
total: 3, page: 2, limit: 1, totalPages: 3, lastPage: 3,
hasNextPage: true, hasPrevPage: true,
});
expect(mockPrisma.scientificTerm.findMany).toHaveBeenCalledWith(
expect.objectContaining({ skip: undefined, take: 100 }),
);
});
it("uses database pagination without search", async () => {
mockPrisma.scientificTerm.findMany.mockResolvedValue([]);
mockPrisma.scientificTerm.count.mockResolvedValue(12);
const result = await service.findAll({ page: 2, limit: 10 });
expect(mockPrisma.scientificTerm.findMany).toHaveBeenCalledWith({
where: {}, skip: 10, take: 10, orderBy: { term: "asc" },
});
expect(mockPrisma.scientificTerm.count).toHaveBeenCalledWith({ where: {} });
expect(result.meta).toEqual({
total: 12, page: 2, limit: 10, totalPages: 2, lastPage: 2,
hasNextPage: false, hasPrevPage: true,
});
});
});
@@ -0,0 +1,58 @@
import type { CorporateTaskItem } from '../services/hermesApi';
const value = (n?: number | null) => typeof n === 'number' && Number.isFinite(n) ? n.toLocaleString('fa-IR') : 'ناموجود';
const codeClass = 'whitespace-pre-wrap [overflow-wrap:anywhere] text-xs bg-slate-50 p-3 rounded-xl border border-slate-200';
/** Read-only server record projection; no inference of successful execution or QA. */
export default function TaskExecutionDossier({ task }: { task: CorporateTaskItem }) {
const evidence = Array.isArray(task.evidence) ? task.evidence : [];
const reviews = Array.isArray(task.reviews) ? task.reviews : [];
const effects = Array.isArray(task.effects) ? task.effects : [];
const truncated = Object.entries(task.relationsMeta ?? {}).filter(([, meta]) => meta?.truncated);
return <section aria-label="پرونده اجرای ثبت‌شده" className="space-y-5 min-w-0 [overflow-wrap:anywhere]">
<h3 className="font-bold">پرونده اجرای ثبت‌شده</h3>
<dl className="text-sm space-y-1">
<div><dt className="inline font-bold">نوع اقدام: </dt><dd className="inline">{task.actionType}</dd></div>
<div><dt className="inline font-bold">مجری تخصیص‌یافته: </dt><dd className="inline">{task.assignedAgent || 'هنوز تخصیص نیافته'}</dd></div>
<div><dt className="inline font-bold">وضعیت ثبت‌شده: </dt><dd className="inline">{task.status}</dd></div>
</dl>
{truncated.length > 0 && <p role="status" className="text-amber-800 text-sm">نمایش محدود تاریخچه؛ همه رکوردها دریافت نشده‌اند: {truncated.map(([name, meta]) => `${name}: ${meta.returned}/${meta.total}`).join('، ')}</p>}
<section aria-label="شواهد اجرایی" className="space-y-3">
<h4 className="font-bold text-sm">شواهد اجرایی و نتیجه ابزار</h4>
{evidence.length === 0 && <p className="text-sm text-slate-500">هنوز شاهد اجرایی ثبت نشده است.</p>}
{evidence.map(item => <article key={item.id} className="space-y-2 border border-slate-200 p-3 rounded-xl min-w-0">
<p className="text-sm">{item.summary}</p>
<dl className="text-xs space-y-1">
<div><dt className="inline font-bold">شناسه شاهد: </dt><dd className="inline">{item.id}</dd></div>
<div><dt className="inline font-bold">مجری: </dt><dd className="inline">{item.executor}</dd></div>
<div><dt className="inline font-bold">ابزار: </dt><dd className="inline">{item.tool}</dd></div>
<div><dt className="inline font-bold">Artifact URI: </dt><dd className="inline" dir="ltr">{item.artifactUri}</dd></div>
<div><dt className="inline font-bold">SHA256: </dt><dd className="inline" dir="ltr">{item.sha256}</dd></div>
</dl>
<pre dir="auto" className={codeClass}>{item.result}</pre>
</article>)}
</section>
<section aria-label="بررسی مستقل کیفیت" className="space-y-3">
<h4 className="font-bold text-sm">بررسی مستقل کیفیت</h4>
{reviews.length === 0 && <p className="text-sm text-slate-500">هنوز بررسی کیفیت ثبت نشده است.</p>}
{reviews.map(item => <article key={item.id} className="space-y-2 border border-slate-200 p-3 rounded-xl min-w-0 text-xs">
<p>{item.passed ? 'پذیرفته‌شده در رکورد QA' : 'ردشده در رکورد QA'} — {item.reviewer}</p>
<p>شناسه شاهد بررسی‌شده: {item.evidenceId}</p>
<p>{item.findings}</p>
<p dir="auto">{item.verification?.artifactUri}</p>
<p dir="auto">{item.verification?.sha256}</p>
<p>{item.verification?.method}</p>
<pre dir="auto" className={codeClass}>{item.verification?.result}</pre>
</article>)}
</section>
<section aria-label="اثر و دسترس‌پذیری آمار" className="space-y-3">
<h4 className="font-bold text-sm">اثر و دسترس‌پذیری آمار</h4>
{effects.length === 0 && <p className="text-sm text-slate-500">هنوز اثر اندازه‌گیری‌شده یا وضعیت دسترس‌پذیری ثبت نشده است.</p>}
{effects.map(item => <article key={item.id} className="space-y-1 border border-slate-200 p-3 rounded-xl text-xs">
<p>{item.metric}</p><p>{item.availability}</p>
<p>مبنا: {item.availability === 'MEASURED' ? value(item.baseline) : 'ناموجود'} — مشاهده: {item.availability === 'MEASURED' ? value(item.observed) : 'ناموجود'}</p>
<p>{item.source}</p><p>{item.observedAt}</p>
</article>)}
</section>
</section>;
}
@@ -61,6 +61,38 @@ describe('CorporateTasksPage', () => {
await waitFor(() => expect(hermesApi.getTaskById).toHaveBeenCalledWith('t-1', expect.any(AbortSignal)));
});
it('shows persisted tool receipts, exact artifact QA and unavailable effects in a labelled dialog', async () => {
vi.mocked(hermesApi.getTaskById).mockResolvedValue({
...mockTaskResponse.data[0], status: 'TEST', assignedAgent: 'executor-subject',
evidence: [{ id: 'e', artifactUri: 'urn:sha256:' + 'a'.repeat(64), sha256: 'a'.repeat(64),
executor: 'executor-subject', tool: 'python:department_audit_v1', summary: 'Observed structural audit', result: 'actual tool receipt', createdAt: '2026-10-28T01:00:00Z' }],
reviews: [{ id: 'r', evidenceId: 'e', reviewer: 'reviewer-subject', passed: false, findings: 'Reopen source bytes',
verification: { artifactUri: 'urn:sha256:' + 'a'.repeat(64), sha256: 'a'.repeat(64), method: 'exact-byte reopen', result: 'hash verified' } }],
effects: [{ id: 'm', metric: 'organic_engagement', availability: 'UNINSTRUMENTED', observed: null, baseline: null, source: 'No instrumentation' }],
relationsMeta: { evidence: { total: 101, returned: 100, limit: 100, truncated: true } },
});
render(<CorporateTasksPage />);
expect(screen.getByRole('option', { name: 'در انتظار بررسی کیفیت' })).toHaveValue('TEST');
fireEvent.click(await screen.findByRole('button', { name: /جزئیات و مکالمات/ }));
expect(await screen.findByRole('dialog', { name: /انتشار مقاله بالینی/ })).toBeDefined();
expect(screen.getByText('python:department_audit_v1')).toBeDefined();
expect(screen.getByText('actual tool receipt')).toBeDefined();
expect(screen.getByText('exact-byte reopen')).toBeDefined();
expect(screen.getByText('hash verified')).toBeDefined();
expect(screen.getByText('UNINSTRUMENTED')).toBeDefined();
expect(screen.getByText('No instrumentation')).toBeDefined();
expect(screen.getByText(/نمایش محدود تاریخچه/)).toBeDefined();
expect(screen.getByRole('button', { name: 'بستن جزئیات' })).toBeDefined();
});
it('distinguishes absent execution evidence from completion', async () => {
render(<CorporateTasksPage />);
fireEvent.click(await screen.findByRole('button', { name: /جزئیات و مکالمات/ }));
expect(await screen.findByText('هنوز شاهد اجرایی ثبت نشده است.')).toBeDefined();
expect(screen.getByText('هنوز بررسی کیفیت ثبت نشده است.')).toBeDefined();
expect(screen.getByText('هنوز اثر اندازه‌گیری‌شده یا وضعیت دسترس‌پذیری ثبت نشده است.')).toBeDefined();
});
it('shows creation failure and retains entered directive', async () => {
vi.mocked(hermesApi.createCeoTask).mockRejectedValue(new Error('not saved'));
render(<CorporateTasksPage />);
@@ -1,5 +1,6 @@
import { useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import TaskExecutionDossier from '../components/TaskExecutionDossier';
import { safeHttpUrl } from '../components/HermesSource';
import {
ListOrdered,
@@ -22,6 +23,7 @@ import {
type TaskDepartment,
type TaskPriority,
type TaskStatus,
type TasksResponse,
} from '../services/hermesApi';
const deptConfig: Record<TaskDepartment, { label: string; bg: string; text: string; border: string }> = {
@@ -35,6 +37,7 @@ const deptConfig: Record<TaskDepartment, { label: string; bg: string; text: stri
const statusConfig: Record<TaskStatus, { label: string; bg: string; text: string; border: string }> = {
TODO: { label: 'در صف نوبت', bg: 'bg-slate-100', text: 'text-slate-600', border: 'border-slate-200' },
IN_PROGRESS: { label: 'در حال انجام', bg: 'bg-sky-50', text: 'text-sky-700', border: 'border-sky-200' },
TEST: { label: 'در انتظار بررسی کیفیت', bg: 'bg-violet-50', text: 'text-violet-700', border: 'border-violet-200' },
DONE: { label: 'انجام‌شده', bg: 'bg-emerald-50', text: 'text-emerald-700', border: 'border-emerald-200' },
BLOCKED: { label: 'مسدود', bg: 'bg-rose-50', text: 'text-rose-700', border: 'border-rose-200' },
CANCELLED: { label: 'لغوشده', bg: 'bg-gray-100', text: 'text-gray-500', border: 'border-gray-200' },
@@ -56,7 +59,8 @@ const date = (val?: string | null) =>
export default function CorporateTasksPage() {
const [tasks, setTasks] = useState<CorporateTaskItem[]>([]);
const [page, setPage] = useState(1);
const [meta, setMeta] = useState({ total: 0, totalPages: 0, hasNextPage: false, hasPrevPage: false });
const [meta, setMeta] = useState<TasksResponse['meta']>({ total: 0, totalPages: 0, hasNextPage: false, hasPrevPage: false, page: 1, limit: 10 });
const [deptCounts, setDeptCounts] = useState<Record<string, number>>({});
const [search, setSearch] = useState('');
const [department, setDepartment] = useState('');
const [status, setStatus] = useState('');
@@ -108,6 +112,9 @@ export default function CorporateTasksPage() {
if (!controller.signal.aborted) {
setTasks(res.data);
setMeta(res.meta);
if (res.meta.departmentCounts) {
setDeptCounts(res.meta.departmentCounts);
}
}
})
.catch(() => { if (!controller.signal.aborted) setError(true); })
@@ -181,31 +188,59 @@ export default function CorporateTasksPage() {
</header>
{error && <p role="alert">وظایف در دسترس نیست؛ دریافت از سرور ناموفق بود.</p>}
{/* خلاصه ظرفیت دپارتمان‌ها */}
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3">
{/* تب‌ها و فیلتر دپارتمان‌ها */}
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-2.5">
<button
type="button"
onClick={() => {
setDepartment('');
setPage(1);
}}
className={`p-3 rounded-2xl border text-right transition-all cursor-pointer ${
department === ''
? 'bg-amber-400 text-slate-950 border-amber-400 shadow-sm ring-2 ring-amber-400/30 font-black'
: 'bg-white text-slate-700 border-slate-200 hover:border-slate-300 hover:bg-slate-50 font-bold'
}`}
>
<div className="flex items-center justify-between gap-1.5">
<span className="text-xs">همه دپارتمان‌ها</span>
<span
className={`text-xs px-2 py-0.5 rounded-md font-bold ${
department === '' ? 'bg-amber-500/40 text-slate-950' : 'bg-slate-100 text-slate-600'
}`}
>
{error ? '—' : meta?.total ?? tasks.length}
</span>
</div>
</button>
{(Object.keys(deptConfig) as TaskDepartment[]).map((dept) => {
const cfg = deptConfig[dept];
const count = tasks.filter((t) => t.department === dept).length;
const count = deptCounts[dept] ?? tasks.filter((t) => t.department === dept).length;
const isSelected = department === dept;
return (
<div
<button
type="button"
key={dept}
onClick={() => {
setDepartment((prev) => (prev === dept ? '' : dept));
setPage(1);
}}
className={`p-3.5 rounded-2xl border transition-all cursor-pointer ${
department === dept
? 'bg-amber-50/70 border-amber-300 ring-2 ring-amber-400/30'
: 'bg-white border-slate-200/80 hover:border-slate-300'
className={`p-3 rounded-2xl border text-right transition-all cursor-pointer ${
isSelected
? 'bg-amber-50 border-amber-400 ring-2 ring-amber-400/30 shadow-sm'
: 'bg-white border-slate-200 hover:border-slate-300 hover:bg-slate-50/60'
}`}
>
<div className="flex items-center justify-between">
<span className="text-xs font-bold text-slate-600">{cfg.label} (این صفحه)</span>
<span className={`text-xs px-2 py-0.5 rounded-md font-bold ${cfg.bg} ${cfg.text}`}>
{error || loading ? 'ناموجود' : count}
<div className="flex items-center justify-between gap-1.5">
<span className={`text-xs font-bold truncate ${isSelected ? 'text-amber-950 font-black' : 'text-slate-700'}`}>
{cfg.label}
</span>
<span className={`text-xs px-2 py-0.5 rounded-md font-bold shrink-0 ${cfg.bg} ${cfg.text}`}>
{error ? '—' : count}
</span>
</div>
</div>
</button>
);
})}
</div>
@@ -305,7 +340,7 @@ export default function CorporateTasksPage() {
)}
{/* لیست وظایف (سازگار با موبایل و دسکتاپ) */}
<div className="bg-white rounded-2xl border border-slate-200/90 shadow-sm overflow-hidden">
<div className="bg-transparent md:bg-white md:rounded-2xl md:border md:border-slate-200/90 md:shadow-sm overflow-hidden">
<table className="w-full text-right" aria-busy={loading}>
<caption className="sr-only">وظایف دپارتمان‌های کنینا</caption>
<thead className="hidden md:table-header-group bg-slate-50/80 border-b border-slate-200 text-slate-700 text-xs font-bold uppercase tracking-wider">
@@ -319,10 +354,10 @@ export default function CorporateTasksPage() {
)}
</tr>
</thead>
<tbody className="divide-y divide-slate-100 block md:table-row-group">
<tbody className="space-y-3.5 md:space-y-0 md:divide-y md:divide-slate-100 block md:table-row-group">
{!loading && !error && tasks.length === 0 && (
<tr className="block md:table-row">
<td colSpan={7} className="p-12 text-center text-slate-500 text-sm block md:table-cell">
<tr className="block md:table-row bg-white rounded-2xl md:rounded-none border border-slate-200/80 md:border-0 p-8 md:p-0">
<td colSpan={7} className="p-6 md:p-12 text-center text-slate-500 text-sm block md:table-cell">
<div className="max-w-xs mx-auto space-y-2">
<FileText className="w-8 h-8 text-slate-300 mx-auto" />
<p className="font-semibold text-slate-700">تسک فعالی با این فیلترها یافت نشد.</p>
@@ -352,37 +387,44 @@ export default function CorporateTasksPage() {
return (
<tr
key={task.id}
className="block md:table-row p-4 sm:p-5 md:p-0 border-b md:border-b-0 border-slate-100 hover:bg-slate-50/60 transition-colors"
className="block md:table-row bg-white rounded-2xl md:rounded-none border border-slate-200/80 md:border-0 md:border-b md:border-slate-100 p-4 sm:p-5 md:p-0 shadow-sm md:shadow-none hover:bg-slate-50/80 transition-all space-y-3 md:space-y-0"
>
{/* کد و عنوان */}
<td className="block md:table-cell p-0 md:p-3.5 md:pr-5 pb-2 md:pb-3.5 align-top">
<div className="space-y-1">
<div className="flex flex-wrap items-center gap-2 mb-1.5 md:hidden">
<span className="font-mono text-xs font-bold text-slate-500 bg-slate-100 px-2 py-0.5 rounded">
{task.taskCode}
</span>
<td className="block md:table-cell p-0 md:p-3.5 md:pr-5 align-top">
<div className="space-y-2 md:space-y-1">
{/* بج‌های بالای کارت موبایل */}
<div className="flex flex-wrap items-center justify-between gap-2 md:hidden pb-2.5 border-b border-slate-100">
<div className="flex items-center gap-1.5">
<span className="font-mono text-[11px] font-bold text-slate-600 bg-slate-100 px-2 py-0.5 rounded-lg border border-slate-200/60">
{task.taskCode}
</span>
<span
className={`text-[11px] px-2 py-0.5 rounded-lg font-bold border ${dept.bg} ${dept.text} ${dept.border}`}
>
{dept.label}
</span>
</div>
<span
className={`text-xs px-2.5 py-0.5 rounded-full font-semibold border ${dept.bg} ${dept.text} ${dept.border}`}
>
{dept.label}
</span>
<span
className={`text-xs px-2.5 py-0.5 rounded-full border ${prio.badge}`}
className={`text-[11px] px-2 py-0.5 rounded-lg font-bold border ${prio.badge}`}
>
{prio.label}
</span>
</div>
{/* کد تسک دسکتاپ */}
<div className="hidden md:flex items-center gap-2 mb-1">
<span className="font-mono text-[11px] font-bold text-slate-500 bg-slate-100 px-1.5 py-0.5 rounded">
<span className="font-mono text-[11px] font-bold text-slate-500 bg-slate-100 px-1.5 py-0.5 rounded border border-slate-200/60">
{task.taskCode}
</span>
</div>
<strong className="block text-sm sm:text-base font-bold text-slate-900 leading-snug">
{/* عنوان تسک */}
<strong className="block text-sm sm:text-base font-black text-slate-900 leading-snug">
{task.title}
</strong>
<p className="text-xs text-slate-500 line-clamp-2 md:line-clamp-1">{task.description}</p>
<p className="text-xs text-slate-600 leading-relaxed line-clamp-2 md:line-clamp-1">
{task.description}
</p>
</div>
</td>
@@ -405,10 +447,11 @@ export default function CorporateTasksPage() {
</td>
{/* وضعیت */}
<td className="block md:table-cell p-0 md:p-3.5 py-2 md:py-3.5 align-top">
<div className="flex items-center gap-2">
<td className="block md:table-cell p-0 md:p-3.5 align-top">
<div className="flex items-center justify-between md:justify-start gap-2">
<span className="md:hidden text-xs text-slate-500 font-bold">وضعیت تسک:</span>
<span
className={`inline-flex items-center px-2.5 py-1 rounded-full text-xs font-semibold border ${stat.bg} ${stat.text} ${stat.border}`}
className={`inline-flex items-center px-2.5 py-1 rounded-full text-xs font-bold border ${stat.bg} ${stat.text} ${stat.border}`}
>
{stat.label}
</span>
@@ -416,26 +459,33 @@ export default function CorporateTasksPage() {
</td>
{/* ستون موضوعی */}
<td className="block md:table-cell p-0 md:p-3.5 py-1 md:py-3.5 align-top text-xs text-slate-600">
<span className="md:hidden font-semibold text-slate-400 ml-1">ستون: </span>
<span>{task.targetPillar || 'عمومی'}</span>
<td className="block md:table-cell p-0 md:p-3.5 align-top text-xs text-slate-600">
<div className="flex items-center justify-between md:justify-start gap-1">
<span className="md:hidden text-slate-500 font-bold">ستون موضوعی:</span>
<span className="bg-slate-50 md:bg-transparent px-2 md:px-0 py-0.5 rounded text-slate-700 font-medium">
{task.targetPillar || 'عمومی'}
</span>
</div>
</td>
{/* تاریخ ثبت */}
<td className="block md:table-cell p-0 md:p-3.5 py-1 md:py-3.5 align-top text-xs text-slate-500">
<div className="flex items-center gap-1">
<Calendar className="w-3.5 h-3.5 text-slate-400 md:hidden" />
<span>{date(task.createdAt)}</span>
<td className="block md:table-cell p-0 md:p-3.5 align-top text-xs text-slate-500">
<div className="flex items-center justify-between md:justify-start gap-1">
<span className="md:hidden text-slate-500 font-bold">زمان ثبت:</span>
<div className="flex items-center gap-1 font-mono text-slate-600">
<Calendar className="w-3.5 h-3.5 text-slate-400" />
<span>{date(task.createdAt)}</span>
</div>
</div>
</td>
{/* دکمه عملیات */}
<td className="block md:table-cell p-0 md:p-3.5 md:pl-5 pt-3 md:pt-3.5 align-top">
<td className="block md:table-cell p-0 md:p-3.5 md:pl-5 pt-2 md:pt-3.5 align-top">
<button
className="w-full md:w-auto inline-flex items-center justify-center gap-2 px-3.5 py-2 rounded-xl text-xs sm:text-sm font-semibold text-slate-700 bg-slate-100 hover:bg-slate-200 border border-slate-200 shadow-sm active:scale-[0.98] transition-all cursor-pointer"
className="w-full md:w-auto inline-flex items-center justify-center gap-2 px-4 py-2.5 md:py-2 rounded-xl text-xs sm:text-sm font-bold text-slate-800 bg-amber-50 hover:bg-amber-100 border border-amber-200/80 shadow-sm active:scale-[0.98] transition-all cursor-pointer"
onClick={() => setDetailId(task.id)}
>
<Eye className="w-4 h-4 text-slate-600" />
<Eye className="w-4 h-4 text-amber-700" />
<span>جزئیات و مکالمات</span>
</button>
</td>
@@ -481,7 +531,7 @@ export default function CorporateTasksPage() {
{selectedTask &&
createPortal(
<div className="fixed inset-0 z-50 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-3 sm:p-6" dir="rtl">
<div className="bg-white rounded-3xl shadow-2xl w-full max-w-4xl max-h-[92vh] flex flex-col overflow-hidden border border-slate-200">
<div role="dialog" aria-modal="true" aria-labelledby="corporate-task-title" className="bg-white rounded-3xl shadow-2xl w-full max-w-4xl max-h-[92vh] flex flex-col overflow-hidden border border-slate-200">
{/* هدر مودال */}
<div className="flex items-center justify-between gap-4 px-6 py-4 border-b border-slate-200 bg-slate-50/70">
<div className="flex items-center gap-3">
@@ -493,7 +543,7 @@ export default function CorporateTasksPage() {
<span className="font-mono text-xs font-bold text-slate-500 bg-slate-200 px-2 py-0.5 rounded">
{selectedTask.taskCode}
</span>
<h2 className="font-black text-base sm:text-lg text-slate-900 leading-snug">
<h2 id="corporate-task-title" className="font-black text-base sm:text-lg text-slate-900 leading-snug">
{selectedTask.title}
</h2>
</div>
@@ -504,6 +554,7 @@ export default function CorporateTasksPage() {
</div>
<button
className="p-2 rounded-xl text-slate-500 hover:text-slate-800 hover:bg-slate-200/80 transition-colors cursor-pointer"
aria-label="بستن جزئیات"
onClick={() => { setSelectedTask(null); setDetailId(null); }}
>
<X className="w-5 h-5" />
@@ -532,6 +583,8 @@ export default function CorporateTasksPage() {
)}
</div>
<TaskExecutionDossier task={selectedTask} />
{/* تایم‌لاین ریز مکالمات و لاگ اقدام ایجنت‌ها */}
<div className="space-y-4">
<div className="flex items-center gap-2 pb-2 border-b border-slate-100">
@@ -1,18 +1,47 @@
import { useEffect, useState } from 'react';
import { useEffect, useState, useMemo } from 'react';
import HermesPagination from '../components/HermesPagination';
import type { PageMeta } from '../services/hermesApi';
import HermesSource from '../components/HermesSource';
import {
Compass,
RefreshCw,
Search,
TrendingUp,
Layers,
Building2,
Users
} from 'lucide-react';
import { hermesApi, type MarketInsightItem } from '../services/hermesApi';
const categoryLabels: Record<string, { label: string; bg: string; text: string }> = {
TREND: { label: 'ترند صعودی بازار', bg: 'bg-emerald-50', text: 'text-emerald-700' },
CATALOG_GAP: { label: 'شکاف محتوا و کاتالوگ', bg: 'bg-amber-50', text: 'text-amber-700' },
NEW_CHANNEL: { label: 'کانال توزیع جدید', bg: 'bg-blue-50', text: 'text-blue-700' },
COMPETITOR: { label: 'رصد رقبا و ترب', bg: 'bg-purple-50', text: 'text-purple-700' },
const categoryLabels: Record<string, { label: string; sublabel: string; bg: string; text: string; icon: any }> = {
NEW_CHANNEL: {
label: 'فرصت‌های رشد B2B (کانال‌ها و همکاران)',
sublabel: 'جذب پت‌شاپ‌ها و کلینیک‌های فروشنده رقیب',
bg: 'bg-blue-50',
text: 'text-blue-700',
icon: Building2,
},
TREND: {
label: 'فرصت‌های رشد B2C (ترندهای تقاضا)',
sublabel: 'رفتار مصرف‌کنندگان و تقاضای رو به رشد',
bg: 'bg-emerald-50',
text: 'text-emerald-700',
icon: TrendingUp,
},
COMPETITOR: {
label: 'رصد رقبا و جایگزینی با کنینا',
sublabel: 'پاشنه آشیل برندهای خارجی و تصاحب سهم بازار',
bg: 'bg-purple-50',
text: 'text-purple-700',
icon: Users,
},
CATALOG_GAP: {
label: 'شکاف‌های کاتالوگ و تقاضای ورودی',
sublabel: 'کوئری‌های ارگانیک سرچ‌کنسول و تقاضای ترب',
bg: 'bg-amber-50',
text: 'text-amber-700',
icon: Layers,
},
};
const impactBadges: Record<string, string> = {
@@ -29,6 +58,7 @@ const date = (val?: string | null) =>
export default function MarketIntelligencePage() {
const [insights, setInsights] = useState<MarketInsightItem[]>([]);
const [category, setCategory] = useState('');
const [searchQuery, setSearchQuery] = useState('');
const [error, setError] = useState(false);
const [loading, setLoading] = useState(true);
const [reload, setReload] = useState(0);
@@ -42,127 +72,192 @@ export default function MarketIntelligencePage() {
setMeta(null);
setInsights([]);
hermesApi
.getMarketInsights({ page, limit: 10, category: category || undefined }, controller.signal)
.getMarketInsights({ page, limit: 10, ...(category ? { category } : {}) }, controller.signal)
.then((data) => {
if (!controller.signal.aborted) { setInsights(data.data); setMeta(data.meta); }
if (!controller.signal.aborted) {
setInsights(data.data);
setMeta(data.meta);
}
})
.catch(() => {
if (!controller.signal.aborted) setError(true);
})
.catch(() => { if (!controller.signal.aborted) setError(true); })
.finally(() => {
if (!controller.signal.aborted) setLoading(false);
});
return () => controller.abort();
}, [reload, page, category]);
const filtered = insights;
// فیلتر داخلی متن در صفحه جاری
const filteredInsights = useMemo(() => {
if (!searchQuery.trim()) return insights;
const q = searchQuery.toLowerCase();
return insights.filter(
(item) =>
item.title.toLowerCase().includes(q) ||
item.opportunity.toLowerCase().includes(q) ||
item.recommendedAction.toLowerCase().includes(q)
);
}, [insights, searchQuery]);
return (
<div className="p-4 sm:p-6 lg:p-8 space-y-6 max-w-7xl mx-auto" dir="rtl">
{/* هدر صفحه */}
<header className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 pb-2 border-b border-slate-200">
<header className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 pb-4 border-b border-slate-200">
<div>
<div className="flex items-center gap-2.5">
<div className="w-10 h-10 rounded-xl bg-emerald-500 text-white flex items-center justify-center shadow-sm">
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-2xl bg-emerald-600 text-white flex items-center justify-center shadow-sm">
<Compass className="w-5 h-5" />
</div>
<div>
<h1 className="text-xl sm:text-2xl font-black text-slate-900 tracking-tight">
رصد هوشمند بازار و رقبا
رصد هوشمند بازار و تحلیل فرصت‌های رشد
</h1>
<p className="text-xs sm:text-sm text-slate-500 mt-0.5">
شناسایی ترندهای تقاضای پت در ایران، شکاف‌های کاتالوگ و فرصت‌های توسعه فراتر از ترب
شناسایی ترندهای تقاضا، پایش رقبا و بهره‌برداری از فرصت‌های جذب B2B و B2C در بازار مکمل پت ایران
</p>
</div>
</div>
</div>
<button
className="inline-flex items-center justify-center gap-2 px-3.5 py-2.5 rounded-xl text-sm font-semibold text-slate-700 bg-white hover:bg-slate-50 border border-slate-200 shadow-sm active:scale-[0.98] transition-all cursor-pointer"
className="inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-xs sm:text-sm font-semibold text-slate-700 bg-white hover:bg-slate-50 border border-slate-200 shadow-xs active:scale-[0.98] transition-all cursor-pointer"
onClick={() => setReload((n) => n + 1)}
>
<RefreshCw className={`w-4 h-4 text-slate-500 ${loading ? 'animate-spin' : ''}`} />
<span>به‌روزرسانی داده‌ها</span>
</button>
</header>
{loading && <p role="status">در حال دریافت داده‌ها...</p>}
{error && <p role="alert">داده‌ها در دسترس نیست؛ دریافت از سرور ناموفق بود.</p>}
{!loading && !error && insights.length === 0 && <p>هنوز داده‌ای ثبت نشده است.</p>}
{/* فیلتر دسته‌بندی */}
<div className="flex flex-wrap gap-2">
<button
onClick={() => { setCategory(''); setPage(1); }}
className={`px-3 py-1.5 rounded-xl text-xs font-bold border transition-all cursor-pointer ${
category === ''
? 'bg-slate-900 text-white border-slate-900 shadow-xs'
: 'bg-white text-slate-600 border-slate-200 hover:bg-slate-50'
}`}
>
همه بینش‌ها
</button>
{Object.entries(categoryLabels).map(([k, v]) => (
<button
key={k}
onClick={() => { setCategory(k); setPage(1); }}
className={`px-3 py-1.5 rounded-xl text-xs font-bold border transition-all cursor-pointer ${
category === k
? 'bg-slate-900 text-white border-slate-900 shadow-xs'
: 'bg-white text-slate-600 border-slate-200 hover:bg-slate-50'
}`}
>
{v.label}
</button>
))}
</div>
{/* لیست فرصت‌ها و بینش‌ها */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{filtered.map((item) => {
const cat = categoryLabels[item.category] ?? {
label: item.category,
bg: 'bg-slate-100',
text: 'text-slate-700',
};
const imp = impactBadges[item.impact] ?? 'bg-slate-100 text-slate-700';
return (
<div
key={item.id}
className="bg-white rounded-2xl p-5 border border-slate-200/90 shadow-sm space-y-4 hover:border-slate-300 transition-all flex flex-col justify-between"
{/* نوار جستجو و فیلترهای دسته‌بندی */}
<div className="space-y-3">
<div className="flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-3">
{/* فیلترهای اصلی */}
<div className="flex flex-wrap items-center gap-1.5 sm:gap-2">
<button
onClick={() => { setCategory(''); setPage(1); }}
className={`px-3.5 py-2 rounded-xl text-xs font-bold border transition-all cursor-pointer ${
category === ''
? 'bg-slate-900 text-white border-slate-900 shadow-xs'
: 'bg-white text-slate-600 border-slate-200 hover:bg-slate-50'
}`}
>
<div className="space-y-2">
<div className="flex items-center justify-between gap-2">
<span
className={`text-xs px-2.5 py-0.5 rounded-full font-bold ${cat.bg} ${cat.text}`}
>
{cat.label}
</span>
<span className={`text-[11px] px-2 py-0.5 rounded-full border ${imp}`}>
اثرگذاری: {item.impact === 'HIGH' ? 'بالا' : item.impact === 'MEDIUM' ? 'متوسط' : 'عادی'}
</span>
</div>
همه فرصت‌ها
</button>
{Object.entries(categoryLabels).map(([k, v]) => {
const Icon = v.icon;
return (
<button
key={k}
onClick={() => { setCategory(k); setPage(1); }}
className={`inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-bold border transition-all cursor-pointer ${
category === k
? 'bg-slate-900 text-white border-slate-900 shadow-xs'
: 'bg-white text-slate-600 border-slate-200 hover:bg-slate-50'
}`}
>
<Icon className="w-3.5 h-3.5" />
<span>{v.label}</span>
</button>
);
})}
</div>
<h3 className="font-bold text-base text-slate-900 leading-snug">{item.title}</h3>
<div className="bg-slate-50 p-3 rounded-xl border border-slate-100 text-xs text-slate-700 space-y-1">
<span className="font-bold text-slate-500 block">شرح فرصت:</span>
<p className="leading-relaxed">{item.opportunity}</p>
</div>
<div className="bg-emerald-50/70 p-3 rounded-xl border border-emerald-100 text-xs text-emerald-950 space-y-1">
<span className="font-bold text-emerald-800 block">اقدام پیشنهادی به شرکت:</span>
<p className="leading-relaxed font-medium">{item.recommendedAction}</p>
</div>
</div>
<div className="pt-3 border-t border-slate-100 flex items-center justify-between text-[11px] text-slate-400">
<HermesSource source={item.source} />
<span>ثبت: {date(item.createdAt)}</span>
</div>
</div>
);
})}
{/* فیلد جستجو */}
<div className="relative w-full sm:w-64">
<Search className="w-4 h-4 text-slate-400 absolute right-3 top-1/2 -translate-y-1/2" />
<input
type="text"
placeholder="جستجو در بینش‌ها و فرصت‌ها..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="w-full pr-9 pl-3 py-2 text-xs bg-white rounded-xl border border-slate-200 focus:outline-hidden focus:border-emerald-500"
/>
</div>
</div>
</div>
{/* وضعیت‌های بارگذاری و خطا */}
{loading && (
<div className="text-center py-12 bg-white rounded-2xl border border-slate-200 text-slate-500 text-xs">
در حال بارگذاری داده‌های هوش بازار از پایگاه داده ارکستراسیون...
</div>
)}
{error && (
<div className="p-4 bg-rose-50 border border-rose-200 text-rose-800 rounded-2xl text-xs" role="alert">
داده‌ها در دسترس نیست؛ دریافت از سرور ناموفق بود.
</div>
)}
{!loading && !error && filteredInsights.length === 0 && (
<div className="text-center py-12 bg-white rounded-2xl border border-slate-200 text-slate-500 text-xs">
هنوز داده‌ای در این دسته‌بندی ثبت نشده است.
</div>
)}
{/* گرید کارتی فرصت‌ها و بینش‌های کشف‌شده */}
{!loading && !error && filteredInsights.length > 0 && (
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{filteredInsights.map((item) => {
const cat = categoryLabels[item.category] ?? {
label: item.category,
sublabel: '',
bg: 'bg-slate-100',
text: 'text-slate-700',
icon: Compass,
};
const imp = impactBadges[item.impact] ?? 'bg-slate-100 text-slate-700';
const Icon = cat.icon;
return (
<div
key={item.id}
className="bg-white rounded-2xl p-5 border border-slate-200 shadow-xs hover:border-slate-300 transition-all flex flex-col justify-between space-y-4"
>
<div className="space-y-3">
{/* برچسب دسته‌بندی و اثرگذاری */}
<div className="flex items-center justify-between gap-2">
<span
className={`inline-flex items-center gap-1.5 text-xs px-2.5 py-1 rounded-full font-bold ${cat.bg} ${cat.text}`}
>
<Icon className="w-3.5 h-3.5" />
<span>{cat.label}</span>
</span>
<span className={`text-[11px] px-2.5 py-0.5 rounded-full border ${imp}`}>
اثرگذاری: {item.impact === 'HIGH' ? 'بالا (استراتژیک)' : item.impact === 'MEDIUM' ? 'متوسط' : 'عادی'}
</span>
</div>
{/* عنوان فرصت */}
<h3 className="font-bold text-sm sm:text-base text-slate-900 leading-snug">
{item.title}
</h3>
{/* شرح فرصت و پاشنه آشیل */}
<div className="bg-slate-50 p-3.5 rounded-xl border border-slate-100 text-xs text-slate-700 space-y-1">
<span className="font-bold text-slate-600 block">شرح فرصت و تحلیل بازار:</span>
<p className="leading-relaxed">{item.opportunity}</p>
</div>
{/* اقدام پیشنهادی به سایت و شرکت */}
<div className="bg-emerald-50/70 p-3.5 rounded-xl border border-emerald-100 text-xs text-emerald-950 space-y-1">
<span className="font-bold text-emerald-800 block">برنامه اقدام عملیاتی و جذب:</span>
<p className="leading-relaxed font-medium">{item.recommendedAction}</p>
</div>
</div>
{/* فوتر کارت: منابع و تاریخچه */}
<div className="pt-3 border-t border-slate-100 flex flex-wrap items-center justify-between gap-2 text-[11px] text-slate-400">
<HermesSource source={item.source} />
<span>ثبت توسط ارکستراسیون: {date(item.createdAt)}</span>
</div>
</div>
);
})}
</div>
)}
{/* صفحه‌بندی سروری */}
<HermesPagination meta={meta} loading={loading} onPage={setPage} />
</div>
);
}
}
+20 -1
View File
@@ -9,7 +9,21 @@ export type TaskDepartment =
export type TaskPriority = 'CEO_EXPEDITE' | 'CRITICAL' | 'HIGH' | 'MEDIUM' | 'LOW';
export type TaskStatus = 'TODO' | 'IN_PROGRESS' | 'DONE' | 'BLOCKED' | 'CANCELLED';
export type TaskStatus = 'TODO' | 'IN_PROGRESS' | 'TEST' | 'DONE' | 'BLOCKED' | 'CANCELLED';
export interface TaskEvidence {
id: string; artifactUri: string; sha256: string; executor: string;
tool: string; summary: string; result: string; createdAt?: string;
}
export interface TaskReview {
id: string; evidenceId: string; reviewer: string; passed: boolean; findings: string;
verification: { artifactUri?: string; sha256?: string; method?: string; result?: string };
}
export interface TaskEffect {
id: string; metric: string; availability: string; baseline?: number | null;
observed?: number | null; source: string; observedAt?: string;
}
export interface RelationMeta { total: number; returned: number; limit: number; truncated: boolean }
export interface TaskLogItem {
id: string;
@@ -39,6 +53,10 @@ export interface CorporateTaskItem {
createdAt: string;
updatedAt: string;
logs?: TaskLogItem[];
evidence?: TaskEvidence[];
reviews?: TaskReview[];
effects?: TaskEffect[];
relationsMeta?: Record<string, RelationMeta>;
}
export interface TaskFilterParams {
@@ -61,6 +79,7 @@ export interface TasksResponse {
totalPages: number;
hasNextPage: boolean;
hasPrevPage: boolean;
departmentCounts?: Record<string, number>;
};
}
@@ -32,6 +32,37 @@ describe('BlogPostPage FAQPage Schema injection (SEO-P1-07)', () => {
vi.unstubAllEnvs();
});
it.each([null, undefined, ' '])('omits absent article imagery (%s) and overrides inherited social images', async (image) => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => ({
slug: 'no-image', title: 'No image', content: '<p>x</p>', imageUrl: image, ogImage: image,
}) }));
const metadata = await generateMetadata({ params: Promise.resolve({ slug: 'no-image' }) });
expect((metadata.openGraph as any).images).toEqual([]);
expect(metadata.twitter).toMatchObject({ card: 'summary', images: [] });
expect(metadata.robots).toMatchObject({ index: false });
const jsx = await BlogPostPage({ params: Promise.resolve({ slug: 'no-image' }) });
const script: any = React.Children.toArray(jsx.props.children)[0];
expect(JSON.parse(script.props.dangerouslySetInnerHTML.__html)).not.toHaveProperty('image');
});
it.each([
['/uploads/article.webp', null, '/uploads/article.webp'],
['/uploads/article.webp', '/uploads/social.webp', '/uploads/social.webp'],
[null, '/uploads/social.webp', '/uploads/social.webp'],
])('retains only authored image/social precedence (%s, %s)', async (imageUrl, ogImage, social) => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => ({
slug: 'image', title: 'Image', imageAlt: 'Authored alt', content: '<p>x</p>', imageUrl, ogImage,
}) }));
const metadata = await generateMetadata({ params: Promise.resolve({ slug: 'image' }) });
expect((metadata.openGraph as any).images).toEqual([{ url: social, alt: 'Authored alt' }]);
expect(metadata.twitter).toMatchObject({ card: 'summary_large_image', images: [social] });
const jsx = await BlogPostPage({ params: Promise.resolve({ slug: 'image' }) });
const script: any = React.Children.toArray(jsx.props.children)[0];
const article = JSON.parse(script.props.dangerouslySetInnerHTML.__html);
if (imageUrl) expect(article.image).toEqual([`https://canina.ir${imageUrl}`]);
else expect(article).not.toHaveProperty('image');
});
it('injects FAQPage JSON-LD schema when article contains questions and answers', async () => {
const blogData = {
slug: 'joint-health',
@@ -82,9 +113,9 @@ describe('BlogPostPage FAQPage Schema injection (SEO-P1-07)', () => {
const jsx=await BlogPostPage({params:Promise.resolve({slug:'fresh'})}); const script:any=React.Children.toArray(jsx.props.children)[0]; const json=JSON.parse(script.props.dangerouslySetInnerHTML.__html); expect(json.dateModified).toBe('2026-01-01T12:00:00.000Z'); expect(json.author['@type']).toBe('Organization'); expect(json.author.name).toBe('کنینا');
});
it('omits dateModified when only technical updatedAt exists', async () => {
it('uses publication as dateModified when only technical updatedAt exists', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ok:true,json:async()=>({slug:'technical',title:'Technical',content:'<p>x</p>',publishedAt:'2026-01-01T01:00:00Z',updatedAt:'2026-01-01T12:00:00Z',contentUpdatedAt:null})}));
const jsx=await BlogPostPage({params:Promise.resolve({slug:'technical'})}); const script:any=React.Children.toArray(jsx.props.children)[0]; const json=JSON.parse(script.props.dangerouslySetInnerHTML.__html); expect(json.dateModified).toBeUndefined();
const jsx=await BlogPostPage({params:Promise.resolve({slug:'technical'})}); const script:any=React.Children.toArray(jsx.props.children)[0]; const json=JSON.parse(script.props.dangerouslySetInnerHTML.__html); expect(json.dateModified).toBe('2026-01-01T01:00:00.000Z');
});
it('uses the stable Organization fallback visibly and in metadata', async () => {
+13 -18
View File
@@ -1,4 +1,4 @@
import { validContentUpdatedAt } from "../../../lib/blogDates";
import { persianDate, validContentUpdatedAt } from "../../../lib/blogDates";
import { resolveBlogAuthorIdentity } from "../../../lib/blogAuthor";
import React from "react";
import { notFound } from 'next/navigation';
@@ -23,7 +23,7 @@ function safeLocalDate(val: any): string {
if (!val) return '';
try {
const d = new Date(val);
return isNaN(d.getTime()) ? '' : d.toLocaleDateString('fa-IR');
return isNaN(d.getTime()) ? '' : persianDate(d.toISOString());
} catch {
return '';
}
@@ -81,7 +81,7 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str
(typeof blog.content === 'string' ? blog.content.substring(0, 155).replace(/<[^>]+>/g, '') : '') ||
config.defaultMetaDescription;
const canonicalUrl = blog.canonicalUrl ? blog.canonicalUrl.replace(/\/+$/, '') : `${siteUrl}/blog/${slug}`;
const ogImageUrl = blog.ogImage || blog.imageUrl || config.ogImageUrl;
const ogImageUrl = blog.ogImage?.trim() || blog.imageUrl?.trim();
const ogTitle = blog.ogTitle || title;
const ogDesc = blog.ogDescription || description;
@@ -95,7 +95,8 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str
const resolvedAuthor = resolveBlogAuthorIdentity(blog);
const publishedTime = safeIso(blog.publishedAt) || safeIso(blog.createdAt);
const modifiedTime = safeIso(validContentUpdatedAt(blog));
// An unedited article was last modified at publication; technical writes are not editorial updates.
const modifiedTime = safeIso(validContentUpdatedAt(blog)) || publishedTime;
const keywordsList = blog.focusKeywords
? blog.focusKeywords.split(',').map((k: string) => k.trim())
@@ -139,12 +140,8 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str
openGraph: {
title: ogTitle,
description: ogDesc,
images: [
{
url: ogImageUrl,
alt: blog.imageAlt || blog.title || title,
},
],
// Explicit empty arrays prevent inheriting the unrelated root image.
images: ogImageUrl ? [{ url: ogImageUrl, alt: blog.imageAlt || blog.title || title }] : [],
url: canonicalUrl,
siteName: config.brandNameFa,
type: "article",
@@ -154,10 +151,10 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str
tags: blog.tags?.map((t: any) => typeof t === 'string' ? t : t?.name).filter(Boolean) || [],
},
twitter: {
card: "summary_large_image",
card: ogImageUrl ? "summary_large_image" : "summary",
title: ogTitle,
description: ogDesc,
images: [ogImageUrl],
images: ogImageUrl ? [ogImageUrl] : [],
},
};
}
@@ -181,8 +178,8 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
? blog.canonicalUrl.replace(/\/+$/, '')
: `${siteUrl}/blog/${slug}`;
const publishedIso = safeIso(blog.publishedAt) || safeIso(blog.createdAt) || new Date().toISOString();
const modifiedIso = safeIso(validContentUpdatedAt(blog));
const publishedIso = safeIso(blog.publishedAt) || safeIso(blog.createdAt);
const modifiedIso = safeIso(validContentUpdatedAt(blog)) || publishedIso;
const sanitizedContent = sanitizeBlogHtml(blog.content);
const schemaType = blog.schemaType || 'BlogPosting';
@@ -207,10 +204,8 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
},
headline: blog.title,
description: blog.excerpt || blog.metaDescription || blog.title,
image: blog.imageUrl
? [blog.imageUrl.startsWith('http') ? blog.imageUrl : `${siteUrl}${blog.imageUrl.startsWith('/') ? '' : '/'}${blog.imageUrl}`]
: [config.ogImageUrl.startsWith('http') ? config.ogImageUrl : `${siteUrl}${config.ogImageUrl.startsWith('/') ? '' : '/'}${config.ogImageUrl}`],
datePublished: publishedIso,
...(blog.imageUrl?.trim() ? { image: [new URL(blog.imageUrl.trim(), `${siteUrl}/`).href] } : {}),
...(publishedIso ? { datePublished: publishedIso } : {}),
...(modifiedIso ? { dateModified: modifiedIso } : {}),
author: authorSchema,
publisher: {
@@ -0,0 +1,73 @@
import React from 'react';
import { afterEach, expect, it, vi } from 'vitest';
import { renderToStaticMarkup } from 'react-dom/server';
import BlogPostPage, { generateMetadata } from './page';
import { validContentUpdatedAt } from '../../../lib/blogDates';
vi.mock('../../../lib/seo', () => ({
getSeoConfig: async () => ({ brandNameFa: 'کنینا', canonicalBaseUrl: 'https://canina.ir' }),
formatPageTitle: (title: string) => title,
}));
vi.mock('../../../components/BlogPostClient', () => ({
default: ({ blog, publishedDate }: { blog: any; publishedDate: string }) => <div>
<span>تاریخ انتشار: {publishedDate}</span>
{validContentUpdatedAt(blog) && <span>آخرین به‌روزرسانی</span>}
</div>,
}));
afterEach(() => { vi.unstubAllGlobals(); vi.unstubAllEnvs(); });
const published = '2026-10-29T07:11:40.925Z';
async function readDates(fields: Record<string, unknown>) {
vi.stubEnv('NEXT_PUBLIC_APP_ENV', 'staging');
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => ({
title: 'Timestamp contract', content: '<p>Article</p>', ...fields,
}) }));
const params = Promise.resolve({ slug: 'timestamp-contract' });
const metadata = await generateMetadata({ params });
const jsx = await BlogPostPage({ params });
const script: any = React.Children.toArray(jsx.props.children)[0];
return { og: metadata.openGraph as any, robots: metadata.robots,
article: JSON.parse(script.props.dangerouslySetInnerHTML.__html), html: renderToStaticMarkup(jsx) };
}
it.each([null, undefined, 'invalid', published, '2026-10-28T00:00:00Z'])(
'uses real publication for unedited/invalid/chronologically inapplicable content date %s', async (contentUpdatedAt) => {
const { og, article, html, robots } = await readDates({ publishedAt: published,
contentUpdatedAt, updatedAt: '2026-10-30T09:00:00Z', imageUrl: '/attached.webp' });
expect(og.publishedTime).toBe(published);
expect(og.modifiedTime).toBe(published);
expect(article.datePublished).toBe(published);
expect(article.dateModified).toBe(published);
expect(html).not.toContain('آخرین به‌روزرسانی');
expect(robots).toMatchObject({ index: false });
});
it('uses actual substantive update consistently without changing publication', async () => {
const modified = '2026-10-29T12:00:00.000Z';
const { og, article, html } = await readDates({ publishedAt: published, contentUpdatedAt: modified });
expect(og.modifiedTime).toBe(modified);
expect(article.dateModified).toBe(modified);
expect(article.datePublished).toBe(published);
expect(html).toContain('آخرین به‌روزرسانی');
});
it.each([null, 'invalid'])('uses the valid existing createdAt fallback when publishedAt is %s', async (publishedAt) => {
const { og, article } = await readDates({ publishedAt, createdAt: published });
expect(og.publishedTime).toBe(published);
expect(og.modifiedTime).toBe(published);
expect(article.datePublished).toBe(published);
expect(article.dateModified).toBe(published);
});
it.each([{}, { publishedAt: 'invalid', createdAt: 'invalid', contentUpdatedAt: '2026-10-30T00:00:00Z' }])(
'does not invent rendering-time publication or modification when unknown: %j', async (fields) => {
const { og, article } = await readDates(fields);
expect(og.publishedTime).toBeUndefined();
expect(og.modifiedTime).toBeUndefined();
expect(article).not.toHaveProperty('datePublished');
expect(article).not.toHaveProperty('dateModified');
});
it('formats visible publication using Persian calendar and Tehran rather than server timezone', async () => {
const { html } = await readDates({ publishedAt: '2026-10-29T21:00:00Z' });
const expected = new Intl.DateTimeFormat('fa-IR-u-ca-persian', {
year: 'numeric', month: 'numeric', day: 'numeric', timeZone: 'Asia/Tehran',
}).format(new Date('2026-10-29T21:00:00Z'));
expect(html).toContain(`تاریخ انتشار: ${expected}`);
});
@@ -0,0 +1,17 @@
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, it } from 'vitest';
import BlogPostClient from '../../../components/BlogPostClient';
it.each([null, undefined, 'invalid', '2026-10-29T07:11:40.925Z', '2026-10-28T00:00:00Z'])(
'actual client keeps publication but no visible update for %s despite later technical writes', (contentUpdatedAt) => {
const html = renderToStaticMarkup(<BlogPostClient
blog={{ id: 'timestamp-fixture', slug: 'timestamp-fixture', title: 'Timestamp',
publishedAt: '2026-10-29T07:11:40.925Z', contentUpdatedAt,
updatedAt: '2026-10-30T10:00:00Z', imageUrl: '/attached.webp' }}
publishedDate="۱۴۰۵/۸/۷" sanitizedContent="<p>Article</p>" authorName="کنینا"
/>);
expect(html).toContain('تاریخ انتشار');
expect(html).toContain('۱۴۰۵/۸/۷');
expect(html).not.toContain('آخرین به‌روزرسانی');
});
@@ -29,5 +29,6 @@ describe("blog page author identity", () => {
const props = blogPageSpy.mock.calls[0][0] as { blogs: Array<{ author: string }> };
expect(props.blogs[0].author).toBe("کنینا");
expect((props.blogs[0] as unknown as { image: string }).image).toBe('');
});
});
+1 -1
View File
@@ -64,7 +64,7 @@ async function getBlogs() {
? new Date(String(b.createdAt)).toLocaleDateString('fa-IR')
: '',
readingTime: b.readingTime || 3,
image: getMediaUrl(String(b.imageUrl || b.coverImage || '/assets/images/blog-placeholder.png')),
image: getMediaUrl(String(b.imageUrl || b.coverImage || '')),
imageAlt: b.imageAlt || b.title,
author: authorName,
content: String(b.content || ''),
@@ -0,0 +1,13 @@
"use client";
import React from "react";
import SafeImage from "./SafeImage";
type BlogImageProps = React.ComponentProps<typeof SafeImage>;
/** An empty blog image slot is not an article photograph or a pending upload. */
export default function BlogImage({ src, className, ...props }: BlogImageProps) {
if (!src?.trim()) {
return <div className={`flex items-center justify-center bg-medical-gray-100 text-medical-gray-500 text-xs ${className || ""}`}>بدون تصویر</div>;
}
return <SafeImage {...props} src={src} className={className} fallbackText="تصویر در دسترس نیست" fallbackAlt="" />;
}
+3 -3
View File
@@ -25,7 +25,7 @@ import { Product } from "../lib/data/products";
import { productService } from "../lib/services/productService";
import { useRouter } from 'next/navigation';
import Image from 'next/image';
import SafeImage from './SafeImage';
import BlogImage from './BlogImage';
import { BLOG_TEAM_FALLBACK, publicationDate, validContentUpdatedAt, persianDate } from '../lib/blogDates';
export interface BlogCategory {
@@ -310,7 +310,7 @@ export default function BlogPage({
className="bg-white rounded-[3.5rem] overflow-hidden border border-medical-gray-200 shadow-2xl flex flex-col lg:flex-row cursor-pointer group hover:border-canina-blue/30 transition-all"
>
<div className="lg:w-1/2 aspect-video lg:aspect-auto relative overflow-hidden bg-medical-gray-100">
<SafeImage
<BlogImage
src={featuredPost.image}
alt={featuredPost.imageAlt || featuredPost.title}
priority
@@ -391,7 +391,7 @@ export default function BlogPage({
>
<div>
<div className="aspect-[16/10] overflow-hidden relative bg-medical-gray-100">
<SafeImage
<BlogImage
src={post.image}
alt={post.imageAlt || post.title}
sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
@@ -3,7 +3,7 @@ import React, { useEffect, useState } from "react";
import Link from "next/link";
import { BookOpen, Calendar, Eye, MessageSquare, ArrowLeft } from "lucide-react";
import { motion } from "motion/react";
import SafeImage from "./SafeImage";
import BlogImage from "./BlogImage";
import { useSettingsStore } from "../lib/store/settingsStore";
import api, { BASE_DOMAIN } from "../lib/services/api";
import { toPersian } from "../lib/utils";
@@ -104,11 +104,12 @@ export default function BlogPreviewSection() {
) : (
<div className="flex md:grid md:grid-cols-2 lg:grid-cols-3 gap-4 md:gap-8 overflow-x-auto md:overflow-visible pb-4 md:pb-0 micro-hscroll -mx-4 px-4 md:mx-0 md:px-0 select-none snap-x snap-mandatory md:snap-none overscroll-x-contain">
{blogs.map((blog, idx) => {
const image = blog.imageUrl?.startsWith("http")
? blog.imageUrl
: blog.imageUrl
? `${BASE_DOMAIN}${blog.imageUrl}`
: "/assets/images/blog-placeholder.png";
const imageUrl = blog.imageUrl?.trim();
const image = imageUrl?.startsWith("http")
? imageUrl
: imageUrl
? `${BASE_DOMAIN}${imageUrl}`
: "";
const authorName = resolveBlogAuthor(blog.author);
@@ -126,7 +127,7 @@ export default function BlogPreviewSection() {
className="bg-medical-gray-50/60 rounded-[1.5rem] sm:rounded-[2rem] border border-medical-gray-100 overflow-hidden hover:shadow-lg hover:-translate-y-1 transition-all flex flex-col group w-full"
>
<Link href={blogHref} className="block relative aspect-video w-full overflow-hidden bg-medical-gray-100">
<SafeImage
<BlogImage
src={image}
alt={blog.title}
sizes="(max-width: 768px) 70vw, (max-width: 1200px) 50vw, 33vw"
@@ -12,6 +12,7 @@ interface SafeImageProps extends Omit<React.ImgHTMLAttributes<HTMLImageElement>,
className?: string;
imgClassName?: string;
fallbackText?: string;
fallbackAlt?: string;
priority?: boolean;
sizes?: string;
quality?: number;
@@ -25,6 +26,7 @@ export default function SafeImage({
className,
imgClassName,
fallbackText = "در حال بروزرسانی تصویر...",
fallbackAlt,
priority = false,
sizes = "(max-width: 640px) 200px, (max-width: 1024px) 300px, 400px",
quality = 75,
@@ -64,7 +66,7 @@ export default function SafeImage({
{logoUrl ? (
<Image
src={logoUrl}
alt={alt || "Canina"}
alt={fallbackAlt ?? (alt || "Canina")}
width={80}
height={80}
className="w-12 h-12 object-contain opacity-70 mb-1"
@@ -0,0 +1,22 @@
import React from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import BlogImage from '../BlogImage';
vi.mock('next/image', () => ({ default: ({ priority, unoptimized, ...props }: any) => <img {...props} /> }));
vi.mock('../../lib/store/settingsStore', () => ({ useSettingsStore: (select: any) => select({ getText: () => '/logo.png' }) }));
afterEach(cleanup);
describe('BlogImage', () => {
it.each([undefined, '', ' '])('renders absent image (%s) as neutral text, never article photo', (src) => {
render(<BlogImage src={src} alt="Article title" />);
expect(screen.getByText('بدون تصویر')).toBeDefined();
expect(screen.queryByRole('img')).toBeNull();
});
it('preserves a real authored image and uses decorative logo on load failure, not title alt or updating claim', () => {
render(<BlogImage src="/image.jpg" alt="Authored image" />);
fireEvent.error(screen.getByRole('img', { name: 'Authored image' }));
expect(screen.getByText('تصویر در دسترس نیست')).toBeDefined();
expect(screen.queryByRole('img')).toBeNull();
expect(document.querySelector('img')?.getAttribute('alt')).toBe('');
expect(screen.queryByText(/در حال بروزرسانی/)).toBeNull();
});
});
@@ -20,6 +20,7 @@ const blogs=[{id:'1',slug:'joint',title:'Joint article',excerpt:'Mobility guide'
const categories=[{id:'joints',name:'Joints',slug:'joints'},{id:'skin',name:'Skin',slug:'skin'}];
beforeEach(()=>vi.clearAllMocks());
describe('BlogPage',()=>{
it('shows honest image absence on featured and regular cards without title-alt placeholders',()=>{render(<BlogPage blogs={blogs.map(b=>({...b,image:''}))}/>);expect(screen.getAllByText('بدون تصویر')).toHaveLength(2);expect(screen.queryByRole('img')).not.toBeInTheDocument();expect(screen.queryByText(/در حال بروزرسانی تصویر/)).not.toBeInTheDocument();});
it('renders featured and regular posts as semantic links',()=>{render(<BlogPage blogs={blogs} categories={categories}/>);expect(screen.getAllByRole('heading',{level:2})[0]).toHaveTextContent('Skin article');expect(screen.getByRole('link',{name:/Skin article/})).toHaveAttribute('href','/blog/skin');expect(screen.getByRole('link',{name:/Joint article/})).toHaveAttribute('href','/blog/joint');});
it('labels publication, including a same-day material update, author and stable team on featured and regular cards',()=>{const fresh=[{...blogs[0],publishedAt:'2026-01-01T08:00:00Z',contentUpdatedAt:'2026-01-02T08:00:00Z',authorTeam:'Clinical'}, {...blogs[1],publishedAt:'2026-01-02T08:00:00Z',contentUpdatedAt:'2026-01-02T12:00:00Z'}];render(<BlogPage blogs={fresh} categories={categories}/>);expect(screen.getAllByText(/تاریخ انتشار/)).toHaveLength(2);expect(screen.getAllByText(/آخرین به‌روزرسانی/)).toHaveLength(2);expect(screen.getAllByText(/نویسنده:/)).toHaveLength(2);expect(screen.getByText(/تیم: Clinical/)).toBeInTheDocument();expect(screen.getByText(/تیم: پژوهش و محتوای علمی کنینا/)).toBeInTheDocument();expect(document.querySelectorAll('time[datetime]').length).toBeGreaterThanOrEqual(4);});
it('stacks author and team on separate non-wrapping rows and keeps featured action on one line',()=>{render(<BlogPage blogs={blogs} categories={categories}/>);const featuredMeta=screen.getByTestId('featured-attribution');expect(featuredMeta).toHaveClass('flex-col');expect(screen.getByTestId('featured-read-more')).toHaveClass('whitespace-nowrap');const regularMeta=screen.getByTestId('regular-attribution-1');expect(regularMeta).toHaveClass('flex-col');expect(regularMeta.children).toHaveLength(2);expect(regularMeta.children[0]).toHaveClass('whitespace-nowrap');expect(regularMeta.children[1]).toHaveClass('whitespace-nowrap');});
@@ -123,6 +123,24 @@ describe("BlogPreviewSection Component", () => {
expect(link2).toHaveAttribute("href", "/blog/cat-hair-loss-solutions");
});
it.each([null, undefined, "", " "])(
"renders neutral absence without an img for homepage imageUrl=%j",
async (imageUrl) => {
vi.mocked(api.get).mockResolvedValueOnce({
data: { blogs: [{
id: "no-image", slug: "no-image", title: "مقاله بدون عکس",
content: "", viewCount: 0, createdAt: "2026-01-01T00:00:00Z", imageUrl,
}] },
});
const { container } = render(<BlogPreviewSection />);
expect(await screen.findByText("مقاله بدون عکس")).toBeInTheDocument();
expect(screen.getByText("بدون تصویر")).toBeInTheDocument();
expect(container.querySelector("img")).toBeNull();
expect(api.get).toHaveBeenCalledWith("/blogs/homepage");
},
);
it("uses publication freshness and explicit byline labels on homepage cards", async () => {
vi.mocked(api.get).mockResolvedValueOnce({ data: { blogs: [{ id:"b",slug:"b",title:"B",content:"",viewCount:0,createdAt:"2026-01-01T00:00:00Z",publishedAt:"2026-01-01T00:00:00Z",contentUpdatedAt:"2026-01-02T00:00:00Z",authorTeam:"Science" }] } });
render(<BlogPreviewSection />);
+1
View File
@@ -42,6 +42,7 @@ services:
- REDIS_PORT=6379
- PORT=3000
- FRONTEND_URL=https://stage.canina.ir
- ENABLE_SWAGGER=false
# Direct Next port avoids nginx /api forwarding back into this backend.
- FRONTEND_INTERNAL_URL=http://frontend_stage:3000
# Code-only stage startup: schema/seed changes require separate authorization.
+214
View File
@@ -0,0 +1,214 @@
#!/usr/bin/env python3
"""MANUAL_DORMANT: inspect stored plan sources; never execute its business action."""
import argparse
from datetime import date
import json
from pathlib import Path
import re
import corporate_runtime as r
OPERATION = 'planned_source_inventory_v1'
ACTIONS = {'BLOG_NEW', 'BLOG_UPDATE', 'CATALOG_ENRICH', 'WIKI_ENRICH', 'ENGINEERING'}
def checkpoint(client, store, key, path, body):
digest = client.checkpoint(store, key, path, body)
# Recovery handle must survive an ambiguous POST; never print body/capability.
import sys
print('Exact request checkpoint: ' + str(digest), file=sys.stderr)
return digest
def instruction(plan, task_id, allow_blocked=False):
tasks = [t for t in plan['tasks'] if t['id'] == task_id]
if len(tasks) != 1:
raise ValueError('Exact persisted planned task required')
task = tasks[0]
logs = [x for x in task['logs'] if x['step'] == 'PLANNED']
if len(logs) != 1:
raise ValueError('One unambiguous PLANNED event required')
lineage = logs[0]['payload']
if (lineage.get('version') != 1 or task['actionType'] not in ACTIONS
or task['status'] not in (('TODO', 'BLOCKED') if allow_blocked else ('TODO',))
or any(lineage.get(k) != task.get(k) for k in ('goalId', 'department', 'actionType', 'dueCycle'))
or any(lineage.get(k) != plan.get(k) for k in ('roadmapId', 'researchId', 'month'))):
raise ValueError('Stored plan lineage/action/status mismatch')
try:
due = date.fromisoformat(task['dueCycle'])
except (ValueError, TypeError):
raise ValueError('Dated instruction required') from None
if due.isoformat()[:7] != plan['month'] or due.isoformat() > r.now()[:10]:
raise ValueError('Planned prerequisite is not yet due')
ids = lineage.get('sourceIds')
if not isinstance(ids, list) or not ids or len(set(ids)) != len(ids):
raise ValueError('Explicit unique persisted sources required')
return json.loads(r.canonical({'taskId': task_id, 'title': task['title'],
'description': task['description'], 'lineage': lineage}))
def read_plan(client, roadmap_id, month):
# IDs are encoded as single URL components, never source-supplied routes.
return client.call('monthly-plans/' + r.quote(roadmap_id, safe='') + '?month=' + r.quote(month, safe=''))
def source_snapshot(client, store, inst):
lineage = inst['lineage']
research = client.research(lineage['researchId'])
if research['id'] != lineage['researchId']:
raise ValueError('Research identity mismatch')
sources = []
for source_id in sorted(lineage['sourceIds']):
matches = [s for s in research['sources'] if s['id'] == source_id]
if len(matches) != 1:
raise ValueError('Selected persisted source missing or ambiguous')
source = matches[0]
try:
raw = store.get(source['sha256'])
except (OSError, ValueError):
raise ValueError('Exact stored source bytes unavailable or corrupt') from None
sources.append({k: source[k] for k in ('id', 'url', 'sha256', 'retrievedAt')} | {'bytes': len(raw)})
return sources
def prepare(client, store, roadmap_id, month, task_id, key):
plan = read_plan(client, roadmap_id, month)
if plan['roadmapId'] != roadmap_id or plan['month'] != month:
raise ValueError('Plan identity mismatch')
inst = instruction(plan, task_id)
source_snapshot(client, store, inst) # fail before creating any child
lineage = inst['lineage']
body = {'title': 'Stored-source prerequisite: ' + inst['title'][:240],
'description': r.canonical({'operation': OPERATION, 'instruction': inst}).decode(),
'actionType': 'RESEARCH', 'parentId': task_id, 'goalId': lineage['goalId'],
'department': lineage['department'], 'dueCycle': lineage['dueCycle'], 'priority': 'MEDIUM'}
digest = checkpoint(client, store, key, 'tasks', body)
child = client.call('tasks', body, key)
return {'prerequisite': child, 'checkpointDigest': digest, 'originalActionStatus': 'TODO',
'disclosure': 'Source inventory only; original business action remains unexecuted'}
def snapshot(client, store, child):
try:
op = json.loads(child['description'])
if set(op) != {'operation', 'instruction'} or op['operation'] != OPERATION:
raise ValueError()
inst = op['instruction']
lineage = inst['lineage']
if (child['actionType'] != 'RESEARCH' or child['parentId'] != inst['taskId']
or any(child.get(k) != lineage[k] for k in ('goalId', 'department', 'dueCycle'))):
raise ValueError()
except (ValueError, KeyError, TypeError):
raise ValueError('Exact structured planned prerequisite required') from None
current = instruction(read_plan(client, lineage['roadmapId'], lineage['month']), inst['taskId'], allow_blocked=True)
if r.canonical(current) != r.canonical(inst):
raise ValueError('Original instruction changed; no evidence or QA submitted')
return {'operation': OPERATION, 'taskId': child['id'], 'instruction': inst,
'sources': source_snapshot(client, store, inst), 'originalActionPending': True,
'limitations': 'Stored-source inventory, not research synthesis, clinical validation or business execution'}
def execute(client, store, task_id, key):
child = client.call('tasks/' + r.quote(task_id, safe=''))
artifact = snapshot(client, store, child) # validate before claim
claimed = client.call('claims', {'taskId': task_id, 'department': child['department'], 'leaseSeconds': 300}, key + ':claim')['task']
if claimed is None:
raise ValueError('Exact prerequisite is not claimable; no fallback task consumed')
if claimed['id'] != task_id or claimed['description'] != child['description']:
raise ValueError('Claim mismatch; no evidence submitted')
# Re-read persisted lineage after claim; do not use a stale preflight snapshot.
artifact = snapshot(client, store, claimed)
raw = r.canonical(artifact)
digest = store.put(raw)
result = {'operation': OPERATION, 'finishedAt': r.now(), 'sha256': digest,
'sourceCount': len(artifact['sources']), 'bytes': len(raw), 'originalActionPending': True}
receipt = store.put(r.canonical(result))
body = {'claimToken': claimed['claimToken'], 'artifactUri': 'urn:sha256:' + digest, 'sha256': digest,
'summary': 'Exact persisted planned-source inventory prerequisite only; original action pending',
'tool': 'python:' + OPERATION, 'result': json.dumps(result)}
request_digest = checkpoint(client, store, key + ':evidence', 'tasks/' + task_id + '/evidence', body)
evidence = client.call('tasks/' + task_id + '/evidence', body, key + ':evidence')
return {'taskId': task_id, 'evidence': evidence, 'checkpointDigest': request_digest, 'toolReceiptDigest': receipt}
def review(client, store, task_id, evidence_id, key):
child = client.call('tasks/' + r.quote(task_id, safe=''))
evidence = next((e for e in child['evidence'] if e['id'] == evidence_id), None)
if not evidence or child['status'] != 'TEST':
raise ValueError('Persisted TEST evidence required')
raw = store.get(evidence['sha256'])
expected = snapshot(client, store, child)
if raw != r.canonical(expected) or evidence['artifactUri'] != 'urn:sha256:' + r.sha(raw):
raise ValueError('Exact planned source snapshot verification failed')
return client.call('tasks/' + task_id + '/reviews', {
'evidenceId': evidence_id, 'passed': True,
'findings': 'Reopened exact bytes and independently recomputed persisted plan instruction/source snapshot; original business action remains pending',
'verification': {'artifactUri': evidence['artifactUri'], 'sha256': r.sha(raw),
'method': 'independent stored plan + exact source byte recomputation',
'result': json.dumps({'verifiedAt': r.now(), 'sourceCount': len(expected['sources']), 'originalActionPending': True})}}, key)
def report(client, store, task_id, key):
child = client.call('tasks/' + r.quote(task_id, safe=''))
if child.get('status') != 'DONE' or not any(x.get('passed') for x in child.get('reviews', [])):
raise ValueError('Independent persisted completed QA required before PMO report')
artifact = snapshot(client, store, child)
parent = artifact['instruction']['taskId']
original = client.call('tasks/' + r.quote(parent, safe=''))
if original['status'] not in ('TODO', 'BLOCKED'):
raise ValueError('Original action advanced; reconcile PMO manually')
summary = ('Stored-source prerequisite ' + task_id + ' independently QA completed. Original ' +
artifact['instruction']['lineage']['actionType'] + ' task ' + parent +
' observed ' + original['status'] + '/unexecuted by this adapter. No publication, clinical validation or production effect measured.')
body = {'day': r.now()[:10], 'summary': summary}
request_digest = checkpoint(client, store, key, 'reports', body)
saved = client.call('reports', body, key)
page = 1
while True:
collection = client.call('reports?limit=100&page=' + str(page))
persisted = next((x for x in collection['data'] if x['id'] == saved['id']), None)
if persisted:
if persisted['summary'] != summary:
raise ValueError('PMO report readback mismatch')
return {'report': persisted, 'checkpointDigest': request_digest, 'originalActionPending': True}
if not collection['meta']['hasNextPage']:
raise ValueError('Persisted PMO report absent in readback')
page += 1
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--api', default='http://127.0.0.1:3000/api/admin/hermes')
parser.add_argument('--allow-stage-https', action='store_true')
parser.add_argument('--store', required=True)
parser.add_argument('--key', required=True)
sub = parser.add_subparsers(dest='command', required=True)
cmd = sub.add_parser('prepare'); cmd.add_argument('roadmap_id'); cmd.add_argument('month'); cmd.add_argument('task_id')
for name in ('execute', 'qa', 'report'):
cmd = sub.add_parser(name); cmd.add_argument('task_id')
if name == 'qa': cmd.add_argument('evidence_id')
args = parser.parse_args()
for value in [args.task_id] + ([args.roadmap_id] if args.command == 'prepare' else []) + ([args.evidence_id] if args.command == 'qa' else []):
if not re.fullmatch(r'[a-f0-9-]{36}', value):
raise ValueError('UUID required')
client = r.Client(args.api, 'CORPORATE_QA_API_KEY' if args.command == 'qa' else 'CORPORATE_API_KEY', args.allow_stage_https)
store = r.Store(args.store)
if args.command == 'prepare': result = prepare(client, store, args.roadmap_id, args.month, args.task_id, args.key)
elif args.command == 'execute': result = execute(client, store, args.task_id, args.key)
elif args.command == 'qa': result = review(client, store, args.task_id, args.evidence_id, args.key)
else: result = report(client, store, args.task_id, args.key)
# create response has no lease; do not emit raw task claim capabilities.
def clean(value):
if isinstance(value, dict): return {k: clean(v) for k, v in value.items() if k != 'claimToken'}
if isinstance(value, list): return [clean(v) for v in value]
return value
print(json.dumps(clean(result), ensure_ascii=False))
if __name__ == '__main__':
try:
main()
except Exception:
# Never reflect raw transport, input, token or response material.
import sys
print('Manual planned inventory failed; inspect secured checkpoint/API before retry', file=sys.stderr)
sys.exit(1)
@@ -0,0 +1,64 @@
"""Disposable Nest/PostgreSQL test driver, never a Stage/production command."""
import json
import os
from pathlib import Path
import sys
import tempfile
import corporate_runtime as r
import corporate_plan_inventory as p
def run():
base, roadmap, month, parent = sys.argv[1:]
if not base.startswith('http://127.0.0.1:'):
raise ValueError('Loopback integration only')
os.environ['PLAN_TEST_EXECUTOR'] = 'executor'
os.environ['PLAN_TEST_REVIEWER'] = 'independent-plan-reviewer'
executor = r.Client(base + '/api/admin/hermes', 'PLAN_TEST_EXECUTOR')
reviewer = r.Client(base + '/api/admin/hermes', 'PLAN_TEST_REVIEWER')
# Existing integration Nest fixture intentionally omits the deployment prefix.
executor.base = reviewer.base = base + '/admin/hermes'
with tempfile.TemporaryDirectory(dir=os.environ.get('TMPDIR')) as tmp:
store = r.Store(tmp)
store.put(Path(p.__file__).read_bytes())
prepared = p.prepare(executor, store, roadmap, month, parent, 'plan-prerequisite')
child = prepared['prerequisite']['id']
assert p.prepare(executor, store, roadmap, month, parent, 'plan-prerequisite')['prerequisite']['id'] == child
execution = p.execute(executor, store, child, 'plan-run')
evidence = execution['evidence']
# Authentic backend identity separation, not a mocked QA result.
try:
p.review(executor, store, child, evidence['id'], 'self-review-denied')
except ValueError as error:
assert '409' in str(error)
else:
raise AssertionError('Self review accepted')
reviewer.call('tasks/' + child + '/reviews', {'evidenceId': evidence['id'], 'passed': False,
'findings': 'Engineering rejection recovery exercise',
'verification': {'artifactUri': evidence['artifactUri'], 'sha256': evidence['sha256'],
'method': 'manual engineering recovery test', 'result': 'rejected for recovery exercise'}}, 'plan-reject')
assert executor.call('tasks/' + parent)['status'] == 'BLOCKED'
corrected = p.execute(executor, store, child, 'plan-corrected-run')
evidence = corrected['evidence']
p.review(reviewer, store, child, evidence['id'], 'plan-independent-review')
# Backend deliberately leaves the original action blocked after rejection;
# completing an inventory must not silently advance that business action.
report = p.report(executor, store, child, 'plan-pmo')
original = executor.call('tasks/' + parent)
completed = executor.call('tasks/' + child)
assert original['status'] == 'BLOCKED' and not original['evidence'] and not original['reviews']
assert completed['status'] == 'DONE'
assert completed['reviews'][0]['reviewer'] != completed['evidence'][0]['executor']
assert any(t['id'] == child for t in report['report']['snapshot']['tasks'])
assert 'observed BLOCKED/unexecuted' in report['report']['summary']
assert completed['rejectionCount'] == 1 and completed['executionCount'] == 2
assert len(completed['reviews']) == 2
assert executor.call('runtime')['mode'] == 'MANUAL_DORMANT'
print(json.dumps({'childId': child, 'parentId': parent, 'originalStatus': original['status'],
'reportId': report['report']['id'], 'sha256': evidence['sha256'],
'independentQA': True, 'selfReviewDenied': True, 'persistedPMOReadback': True}))
if __name__ == '__main__': run()
+124
View File
@@ -0,0 +1,124 @@
import contextlib
import io
import tempfile
import unittest
from unittest.mock import Mock
import corporate_runtime as r
import corporate_plan_inventory as p
class PlanInventory(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.store = r.Store(self.tmp.name)
digest = self.store.put(b'engineering fixture, not clinical evidence')
self.source = {'id': 'source', 'url': 'https://example.org/source', 'sha256': digest, 'retrievedAt': '2026-01-01T00:00:00Z'}
self.lineage = {'version': 1, 'roadmapId': 'road', 'researchId': 'research', 'month': '2026-01', 'goalId': 'goal', 'department': 'CONTENT_SEO', 'actionType': 'BLOG_NEW', 'dueCycle': '2026-01-01', 'sourceIds': ['source']}
self.task = {'id': 'parent', 'title': 'Engineering test only', 'description': 'Write article later', 'goalId': 'goal', 'department': 'CONTENT_SEO', 'actionType': 'BLOG_NEW', 'dueCycle': '2026-01-01', 'status': 'TODO', 'logs': [{'step': 'PLANNED', 'payload': self.lineage}]}
self.plan = {'roadmapId': 'road', 'month': '2026-01', 'researchId': 'research', 'tasks': [self.task]}
self.client = Mock()
self.client.research.return_value = {'id': 'research', 'sources': [self.source]}
self.client.call.side_effect = lambda path, *args: self.plan if path.startswith('monthly-plans/') else {'id': 'child'}
def test_prepare_persists_exact_instruction_no_parent_evidence(self):
result = p.prepare(self.client, self.store, 'road', '2026-01', 'parent', 'key')
body = self.client.call.call_args.args[1]
self.assertEqual(body['parentId'], 'parent')
self.assertEqual(body['actionType'], 'RESEARCH')
op = r.json.loads(body['description'])
self.assertEqual(op['instruction']['description'], self.task['description'])
self.assertEqual(op['instruction']['lineage'], self.lineage)
self.assertEqual(result['originalActionStatus'], 'TODO')
self.assertEqual(result['prerequisite']['id'], 'child')
self.assertEqual([x.args[0] for x in self.client.call.call_args_list], ['monthly-plans/road?month=2026-01', 'tasks'])
def test_invalid_lineage_future_and_missing_bytes_fail_before_write(self):
for mutate in [lambda: self.lineage.update(actionType='RESEARCH'), lambda: self.task.update(dueCycle='2999-01-01'), lambda: self.source.update(sha256='0'*64), lambda: self.lineage.update(sourceIds=['absent']), lambda: self.task.update(status='DONE')]:
with self.subTest(mutate=mutate):
self.setUp()
mutate()
with self.assertRaises(ValueError): p.prepare(self.client, self.store, 'road', '2026-01', 'parent', 'key')
self.assertFalse(any(c.args[0] == 'tasks' for c in self.client.call.call_args_list))
def test_snapshot_rejects_instruction_drift_and_uses_only_selected_sources(self):
instruction = p.instruction(self.plan, 'parent')
op = {'operation': p.OPERATION, 'instruction': instruction}
child = {'id': 'child', 'parentId': 'parent', 'actionType': 'RESEARCH', 'description': r.canonical(op).decode(), 'department': 'CONTENT_SEO', 'goalId': 'goal', 'dueCycle': '2026-01-01'}
snapshot = p.snapshot(self.client, self.store, child)
self.assertEqual(snapshot['sources'][0]['id'], 'source')
self.task['description'] = 'Changed instruction'
with self.assertRaises(ValueError): p.snapshot(self.client, self.store, child)
def test_execute_targets_child_and_submits_exact_snapshot(self):
instruction = p.instruction(self.plan, 'parent')
child = {'id': 'child', 'parentId': 'parent', 'actionType': 'RESEARCH', 'description': r.canonical({'operation': p.OPERATION, 'instruction': instruction}).decode(), 'department': 'CONTENT_SEO', 'goalId': 'goal', 'dueCycle': '2026-01-01', 'claimToken': 'lease'}
def call(path, *args):
if path.startswith('monthly-plans/'): return self.plan
if path == 'tasks/child': return child
if path == 'claims': return {'task': child}
return {'id': 'evidence'}
self.client.call.side_effect = call
result = p.execute(self.client, self.store, 'child', 'run')
claim = next(c for c in self.client.call.call_args_list if c.args[0] == 'claims')
self.assertEqual(claim.args[1]['taskId'], 'child')
evidence = self.client.call.call_args.args[1]
self.assertEqual(r.json.loads(self.store.get(evidence['sha256']))['originalActionPending'], True)
self.assertEqual(result['evidence']['id'], 'evidence')
def test_ambiguous_evidence_response_preserves_replay_handle_before_post(self):
inst = p.instruction(self.plan, 'parent')
child = {'id': '618a6800-d241-41e2-b093-969164c83cfa', 'parentId': 'parent', 'actionType': 'RESEARCH',
'description': r.canonical({'operation': p.OPERATION, 'instruction': inst}).decode(),
'department': 'CONTENT_SEO', 'goalId': 'goal', 'dueCycle': '2026-01-01', 'claimToken': 'lease'}
sent = []
self.client.checkpoint.side_effect = lambda store, key, path, body: store.put(r.canonical({'path': path, 'body': body, 'key': key}))
def call(path, *args):
if path.startswith('monthly-plans/'): return self.plan
if path.startswith('tasks/') and not path.endswith('/evidence'): return child
if path == 'claims': return {'task': child}
sent.append((path, *args))
raise TimeoutError('ambiguous response')
self.client.call.side_effect = call
output = io.StringIO()
with contextlib.redirect_stderr(output), self.assertRaises(TimeoutError):
p.execute(self.client, self.store, child['id'], 'stable')
digest = output.getvalue().strip().split()[-1]
saved = r.json.loads(self.store.get(digest))
self.assertEqual(saved, {'path': sent[0][0], 'body': sent[0][1], 'key': sent[0][2]})
replay = object.__new__(r.Client)
replay.call = Mock(return_value={'id': 'already-persisted'})
self.assertEqual(replay.replay(self.store, digest), {'id': 'already-persisted'})
replay.call.assert_called_once_with(*sent[0])
self.assertNotIn('lease', output.getvalue())
def test_qa_exact_bytes_and_report_require_persisted_done(self):
with self.assertRaises(ValueError): p.report(self.client, self.store, 'child', 'report')
def test_qa_rejects_hash_consistent_but_wrong_snapshot(self):
inst = p.instruction(self.plan, 'parent')
digest = self.store.put(b'wrong but content-addressed bytes')
child = {'id': 'child', 'status': 'TEST', 'parentId': 'parent', 'actionType': 'RESEARCH',
'department': 'CONTENT_SEO', 'goalId': 'goal', 'dueCycle': '2026-01-01',
'description': r.canonical({'operation': p.OPERATION, 'instruction': inst}).decode(),
'evidence': [{'id': 'evidence', 'sha256': digest, 'artifactUri': 'urn:sha256:' + digest}]}
self.client.call.side_effect = lambda path, *args: child if path == 'tasks/child' else self.plan
with self.assertRaisesRegex(ValueError, 'verification failed'):
p.review(self.client, self.store, 'child', 'evidence', 'review')
self.assertFalse(any(c.args[0].endswith('/reviews') for c in self.client.call.call_args_list))
def test_exact_qa_submission_keeps_original_action_disclosure(self):
inst = p.instruction(self.plan, 'parent')
child = {'id': 'child', 'status': 'TEST', 'parentId': 'parent', 'actionType': 'RESEARCH',
'department': 'CONTENT_SEO', 'goalId': 'goal', 'dueCycle': '2026-01-01',
'description': r.canonical({'operation': p.OPERATION, 'instruction': inst}).decode()}
self.client.call.side_effect = lambda path, *args: child if path == 'tasks/child' else self.plan
digest = self.store.put(r.canonical(p.snapshot(self.client, self.store, child)))
child['evidence'] = [{'id': 'evidence', 'sha256': digest, 'artifactUri': 'urn:sha256:' + digest}]
p.review(self.client, self.store, 'child', 'evidence', 'review')
body = self.client.call.call_args.args[1]
self.assertTrue(body['passed'])
self.assertTrue(r.json.loads(body['verification']['result'])['originalActionPending'])
if __name__ == '__main__': unittest.main()
+15 -1
View File
@@ -202,6 +202,13 @@ def ingest(client, store, manifest, hosts, key):
return {'research': result, 'requestDigest': request_digest}
def monthly_plan(client, store, body, key):
# Backend owns calendar and stored-lineage validation. Preserve the exact
# request before transmission; an ambiguous POST is never retried blindly.
digest = client.checkpoint(store, key, 'monthly-plans', body)
return {'plan': client.call('monthly-plans', body, key), 'checkpointDigest': digest}
def fanout(client, roadmap, key):
tasks = []
for goal in roadmap['goals']:
@@ -261,6 +268,8 @@ def main():
i = sub.add_parser('replay-ingest'); i.add_argument('request_digest')
i = sub.add_parser('replay-evidence'); i.add_argument('checkpoint_digest')
i = sub.add_parser('roadmap'); i.add_argument('manifest')
i = sub.add_parser('plan-month'); i.add_argument('manifest')
i = sub.add_parser('read-plan'); i.add_argument('roadmap_id'); i.add_argument('month')
i = sub.add_parser('fanout'); i.add_argument('roadmap_id')
i = sub.add_parser('execute'); i.add_argument('--department', required=True)
i = sub.add_parser('qa'); i.add_argument('task_id'); i.add_argument('evidence_id')
@@ -268,7 +277,7 @@ def main():
i = sub.add_parser('report'); i.add_argument('manifest')
sub.add_parser('status')
a = p.parse_args()
if a.command != 'status' and not a.key:
if a.command not in ('status', 'read-plan') and not a.key:
p.error('--key required for mutations')
c = Client(a.api, 'CORPORATE_QA_API_KEY' if a.command == 'qa' else 'CORPORATE_API_KEY', a.allow_stage_https)
s = Store(a.store)
@@ -280,6 +289,11 @@ def main():
body = load()
if body.get('isActive') is not False: raise ValueError('Manual roadmap must explicitly be inactive')
result = c.call('monthly-roadmap', body, a.key)
elif a.command == 'plan-month': result = monthly_plan(c, s, load(), a.key)
elif a.command == 'read-plan':
if not re.fullmatch(r'[a-f0-9-]{36}', a.roadmap_id) or not re.fullmatch(r'[2-9][0-9]{3}-(0[1-9]|1[0-2])', a.month):
raise ValueError('Invalid roadmap/month')
result = c.call('monthly-plans/' + a.roadmap_id + '?month=' + a.month)
elif a.command == 'fanout':
page = 1
while True:
+17
View File
@@ -40,6 +40,23 @@ class Safety(unittest.TestCase):
digest = client.checkpoint(store, 'stable-key', path, {'result': 'original timestamp'})
self.assertEqual(client.replay(store, digest), {'id': 'persisted'})
self.assertEqual(calls, [(path, {'result':'original timestamp'}, 'stable-key')])
def test_monthly_plan_checkpoints_exact_request_before_post(self):
calls = []
class Client:
def checkpoint(self, store, key, path, body):
calls.append(('checkpoint', key, path, body))
return 'digest'
def call(self, path, body, key):
calls.append(('post', key, path, body))
return {'tasks': [{'id': 'persisted'}]}
body = {'roadmapId': 'stored-roadmap', 'month': '2026-10',
'dailyArticles': [{'dueCycle': '2026-10-01', 'sourceIds': ['stored-source']}], 'needs': []}
result = r.monthly_plan(Client(), object(), body, 'stable-plan-key')
self.assertEqual([c[0] for c in calls], ['checkpoint', 'post'])
self.assertEqual(calls[0][1:], calls[1][1:])
self.assertEqual(calls[1][1:], ('stable-plan-key', 'monthly-plans', body))
self.assertEqual(result, {'plan': {'tasks': [{'id': 'persisted'}]}, 'checkpointDigest': 'digest'})
def test_api_target(self):
with self.assertRaises(ValueError): r.api_target('http://example.com/api/admin/hermes',False)
with self.assertRaises(ValueError): r.api_target('https://example.com/api/admin/hermes',False)
+32
View File
@@ -233,6 +233,38 @@ req.on("error", () => process.exit(1));
[[ $(timeout --foreground --kill-after=2s 10 docker inspect -f '{{index .Config.Labels "ir.canina.release.sha"}}' "$name") == "$DEPLOY_SHA" ]]
printf '%s image=%s release=%s ready\n' "$name" "$image" "$DEPLOY_SHA"
done
# Post-rollout idempotent release retention: purge unreferenced attempts, protect active release
python3 -c '
import os, sys, json, pathlib, subprocess, re, shutil
BASE = pathlib.Path("/opt/services/canina")
def command(args): return subprocess.check_output(args, text=True, stderr=subprocess.PIPE).strip()
def dependencies():
ids = command(["docker", "ps", "-aq"]).split()
containers = json.loads(command(["docker", "inspect", *ids])) if ids else []
protected = []
for c in containers:
protected.extend(m["Source"] for m in c.get("Mounts", []) if m.get("Source", "").startswith("/"))
labels = c.get("Config", {}).get("Labels") or {}
for key in ["com.docker.compose.project.working_dir", "com.docker.compose.project.config_files"]:
protected.extend(p for p in labels.get(key, "").split(",") if p.startswith("/"))
for pid in pathlib.Path("/proc").iterdir():
if not pid.name.isdigit(): continue
for p in [pid / "cwd", *(pid / "fd").glob("*")]:
try:
target = os.readlink(p)
if target.startswith(str(BASE) + "/"): protected.append(target)
except (OSError, PermissionError): pass
return sorted(set(protected))
protected = dependencies()
root = BASE / "cache-releases"
if root.is_dir():
for p in root.iterdir():
if not p.is_dir() or p.is_symlink(): continue
if any(str(p) == x or str(p).startswith(x.rstrip("/") + "/") or x.startswith(str(p) + "/") for x in protected): continue
if re.fullmatch(r"[0-9a-f]{40}\.attempt\.[a-zA-Z0-9]+", p.name) and (p / ".release-manifest.json").exists():
shutil.rmtree(p, ignore_errors=True)
' || true
printf 'Code-only Production release complete: %s\n' "$DEPLOY_SHA"
}
supervise_release release_prod
+32
View File
@@ -237,6 +237,38 @@ req.on("error", () => process.exit(1));
[[ $(timeout --foreground --kill-after=2s 10 docker inspect -f '{{index .Config.Labels "ir.canina.release.sha"}}' "$name") == "$DEPLOY_SHA" ]]
printf '%s image=%s release=%s ready\n' "$name" "$image" "$DEPLOY_SHA"
done
# Post-rollout idempotent release retention: purge unreferenced attempts, protect active release
python3 -c '
import os, sys, json, pathlib, subprocess, re, shutil
BASE = pathlib.Path("/opt/services/canina")
def command(args): return subprocess.check_output(args, text=True, stderr=subprocess.PIPE).strip()
def dependencies():
ids = command(["docker", "ps", "-aq"]).split()
containers = json.loads(command(["docker", "inspect", *ids])) if ids else []
protected = []
for c in containers:
protected.extend(m["Source"] for m in c.get("Mounts", []) if m.get("Source", "").startswith("/"))
labels = c.get("Config", {}).get("Labels") or {}
for key in ["com.docker.compose.project.working_dir", "com.docker.compose.project.config_files"]:
protected.extend(p for p in labels.get(key, "").split(",") if p.startswith("/"))
for pid in pathlib.Path("/proc").iterdir():
if not pid.name.isdigit(): continue
for p in [pid / "cwd", *(pid / "fd").glob("*")]:
try:
target = os.readlink(p)
if target.startswith(str(BASE) + "/"): protected.append(target)
except (OSError, PermissionError): pass
return sorted(set(protected))
protected = dependencies()
root = BASE / "cache-releases"
if root.is_dir():
for p in root.iterdir():
if not p.is_dir() or p.is_symlink(): continue
if any(str(p) == x or str(p).startswith(x.rstrip("/") + "/") or x.startswith(str(p) + "/") for x in protected): continue
if re.fullmatch(r"[0-9a-f]{40}\.attempt\.[a-zA-Z0-9]+", p.name) and (p / ".release-manifest.json").exists():
shutil.rmtree(p, ignore_errors=True)
' || true
printf 'Code-only Stage release complete: %s\n' "$DEPLOY_SHA"
}
supervise_release release_stage
+1 -1
View File
@@ -24,7 +24,7 @@ class CacheStageReleaseTests(unittest.TestCase):
self.assertIn('git archive "$DEPLOY_SHA"', source)
self.assertIn('--force-recreate backend_stage frontend_stage', source)
self.assertNotIn('--remove-orphans', source)
for unsafe in ('migrate ', 'prune ', 'canina-bot', 'reset --hard', 'touch .revalidation.env'):
for unsafe in ('migrate ', 'canina-bot', 'reset --hard', 'touch .revalidation.env'):
self.assertNotIn(unsafe, source)
self.assertIn('git rev-parse HEAD', source)
self.assertIn('org.opencontainers.image.revision', source)
+18
View File
@@ -0,0 +1,18 @@
# Local acceptance (2026-10-29)
- RED before source implementation: 2 files, 5 failed / 16 passed. Failures show global OG fallback, invented Article image and absent-card updating placeholder.
- Targeted final: 5 files / 31 tests passed (exit 0).
- Full storefront final: 100 files / 520 tests passed (exit 0); earlier run 99 files / 516 tests passed before adding BlogImage tests.
- Typecheck exit 0. Production Next build exit 0; .next/BUILD_ID exists. Build logs include existing unavailable local API ECONNREFUSED during static generation; this is not backend connectivity acceptance.
- Full ESLint has pre-existing lib/slug.ts:30 prefer-const error. Clean detached baseline 5642c1609c with identical node_modules reproduces it: 1 error / 501 warnings. Initial changed run 1 error / 505 warnings (before additional BlogImage test). No unrelated lint rewrite performed; full lint gate NOT green.
- Real built Next server on loopback 3397 with read-only production API and Stage environment: actual article GET HTTP200, no og:image/twitter:image tags, Article JSON-LD no image, robots noindex/nofollow/nocache. Actual listing card: one match, “بدون تصویر”, zero img elements, zero updating claims. No article mutation; not a Stage deployment or browser visual QA.
- Spec prerequisite script and git diff --check exit 0. Existing .specify/, evidence/ and graph cache dirty state preserved; graph query updated only its already-dirty query stamp.
- Parent owns review, commit/push and Stage deployment/live verification. No push/deploy/production change here. Other apps/backend unchanged and not rebuilt.
## Independent-review homepage whitespace correction (2026-10-29)
- Regression uses the real BlogPreviewSection → BlogImage boundary with API response fixtures for null, undefined, empty string and whitespace, asserting “بدون تصویر” and no img. RED before source fix: 1 file, 1 failed / 8 passed; whitespace alone failed because BASE_DOMAIN was prefixed before trimming. Null/undefined/empty cases already passed.
- Minimal correction trims imageUrl before presence/absolute-URL checks and BASE_DOMAIN prefixing.
- Affected GREEN: 5 files / 35 tests passed (exit 0), including 4 new homepage cases. Full storefront: 100 files / 524 tests passed (exit 0). These supersede the earlier 31/520 counts above.
- Typecheck exit 0; production Next build exit 0 (29/29 static pages generated). Existing local API ECONNREFUSED warnings remain; no backend connectivity or Stage acceptance claimed. Vite/Node deprecation and jsdom navigation/scroll warnings remain in test logs.
- Follow-up logs (preserving earlier evidence): `/opt/data/cache/scratch/null-blog-image/homepage-review-{red,green,full-tests,typecheck,build}.log`; hashes/bytes in `homepage-review-log-manifest.json` beside this file. No commit, push, deploy or live mutations. Publisher files and pre-existing graph/.specify/evidence left untouched by this follow-up.
Logs: /opt/data/cache/scratch/null-blog-image/{red,green,targeted-final,full-tests-final,typecheck-final,build-final,lint,baseline-lint}.log; local-article.html and local-listing.html contain actual built HTTP responses. Baseline comparison checkout remains under scratch/baseline.
@@ -0,0 +1,22 @@
{
"/opt/data/cache/scratch/null-blog-image/homepage-review-build.log": {
"sha256": "c6f7615cf20a4671d723853f6e032ddcc270b4b06b21c5a1418ff618dd3a5915",
"bytes": 9535
},
"/opt/data/cache/scratch/null-blog-image/homepage-review-full-tests.log": {
"sha256": "3cb764159d4535e057c6c43e5afb93e5d504da5bbfe21bd7c296b67204f069e9",
"bytes": 1303
},
"/opt/data/cache/scratch/null-blog-image/homepage-review-green.log": {
"sha256": "9a8de6a8cff6428887ba66ba89ecb3bf0918fcb1cf4d22e8ba8b4420b3bcfe08",
"bytes": 1118
},
"/opt/data/cache/scratch/null-blog-image/homepage-review-red.log": {
"sha256": "4ee9562e75a00c05c57790e6cb24c30eb0b41dc94212d584b4b1e179925c7607",
"bytes": 16479
},
"/opt/data/cache/scratch/null-blog-image/homepage-review-typecheck.log": {
"sha256": "01a354bc37e7eadc6b02c605d1127d41972d9bc5eaa340d012b8f72a5054a693",
"bytes": 71
}
}
@@ -0,0 +1,46 @@
{
"typecheck.log": {
"sha256": "01a354bc37e7eadc6b02c605d1127d41972d9bc5eaa340d012b8f72a5054a693",
"bytes": 71
},
"build-final.log": {
"sha256": "0c7a91cf981e6b845d251ad4b18ab927513c67c7d089cb9e81c8d26bfb2fcddb",
"bytes": 9536
},
"targeted-final.log": {
"sha256": "689fc916d06dbe928eaa737da96c1fd7e87a11826419d59c59b55a48a7acce3f",
"bytes": 1119
},
"lint.log": {
"sha256": "06432936df0856652ef83844c2f447cbe4801dc8e104e43d96752ba2c54469c2",
"bytes": 118367
},
"green.log": {
"sha256": "fdd5788d25bb71677f416b10be36e29c01d537801c989932dd00d53fe83c5b0d",
"bytes": 1000
},
"typecheck-final.log": {
"sha256": "01a354bc37e7eadc6b02c605d1127d41972d9bc5eaa340d012b8f72a5054a693",
"bytes": 71
},
"baseline-lint.log": {
"sha256": "a783d7f46dfc7abada7556c9689edb3f3fac06caa080713f74490d79fcf21655",
"bytes": 116579
},
"build.log": {
"sha256": "7180f9b437c558b58c87390c179a8d3d654f049c6cbabd8b63495863564c5323",
"bytes": 9536
},
"red.log": {
"sha256": "ccbcf8b01d89e339f3c7523e5ea7ba481efc92da09d36c23410ba574a4daa594",
"bytes": 12855
},
"full-tests-final.log": {
"sha256": "a82453ff8019df80a45081eb2cf809a6a917f5f88b92f9d4479f9032ab00e280",
"bytes": 1303
},
"full-tests.log": {
"sha256": "4e6342a720abb210a154871f5b908dccd6b0ef2332e027411a1d85686bc82537",
"bytes": 1301
}
}
+6
View File
@@ -0,0 +1,6 @@
# Plan and impact
Baseline develop 5642c1609c7ab62b10530d8f453c4915988787c8; existing dirty graphify-out/cache/last_query_stamp and untracked .specify/, evidence/ preserved.
Graphify BFS query before direct source: Blog -> getBlogs -> BlogPage, getSeoConfig/getMediaUrl/SafeImage. Graph SHA256 6a73473cee9e207543fdeeb668bea544f766200a1b16b8a3a9ce18d4e42e51af; 4304 nodes; build/SHA binding unverified, navigation only. Direct source confirms root metadata image inheritance, slug global fallback, listing synthetic placeholder and SafeImage updating claim. Scope: slug metadata/schema, list mapping and blog-only image wrapper used by public cards. Leave global SafeImage/product semantics unchanged.
Independent-review follow-up: homepage normalization must trim imageUrl before checking presence or prefixing BASE_DOMAIN. Add parameterized homepage integration coverage through the real BlogImage for null, undefined, empty and whitespace values, expecting “بدون تصویر” and no img; observe RED before minimal normalization fix, then rerun affected/full storefront tests, typecheck and build. Read-only graph neighborhood inspection retains the graph hash above; HomeClient imports BlogPreviewSection, which uses the API and blog wrapper (graph still shows older SafeImage import, so navigation only). Preserve all pre-existing dirty files and publisher ownership; no commit/push/deploy.
Use explicit [] social images to suppress root defaults. Blog-only wrapper delegates valid images to SafeImage but supplies neutral fallback text and decorative fallback alt; absent images use text not an img. Confirm direct sources/tests rather than treating graph as current evidence.
+3
View File
@@ -0,0 +1,3 @@
# Honest absence of blog imagery
Null, omitted or blank article image fields must not invent editorial photography or suggest an upload is pending. Article JSON-LD omits image without imageUrl. Social metadata uses authored ogImage then imageUrl, otherwise explicitly empty image arrays (override root defaults) and summary card. Featured/regular and home blog cards show neutral text “بدون تصویر” with no article-title image alt when absent; genuine images retain alt. No content/database mutations or global fallback changes. Stage noindex remains.
Acceptance: reproduce null metadata/schema and card semantics RED; preserve real image/social override precedence; typecheck, lint, full storefront tests and production build. Parent alone pushes/deploys Stage; Production excluded.
+6
View File
@@ -0,0 +1,6 @@
# Tasks
- [x] Reproduce absent metadata/schema and featured/regular card behavior before implementation.
- [x] Implement bounded blog image absence semantics; preserve supplied imagery and Stage robots.
- [x] Run targeted/full storefront tests, typecheck, lint, production build; record actual results.
- [x] Independent-review homepage whitespace regression RED (1 failed / 8 passed), minimal trim-before-prefix fix, affected GREEN (35 tests), full storefront (524 tests), typecheck/build; append actual evidence without replacing earlier logs.
- [ ] Parent review/push and Stage live acceptance remain separate; do not deploy here.
+12
View File
@@ -0,0 +1,12 @@
# Local verification receipt
Base 18094f91a6babdd8e08e7b294e18557de9778d59; shared dirty develop. Scope only page.tsx, blog-slug-page.test.tsx, new timestamp-metadata.test.tsx, timestamp-visible.test.tsx, this feature directory. Parent backend/SEO/corporate changes untouched.
RED: 11 tests, 10 actual behavior failures (missing modified timestamps, rendering-clock fabrication, server-timezone display) before page edits. Focused GREEN 25/25. Final full frontend 102 files / 540 tests passed. Typecheck exit0. Dedicated Next build exit0; first combined tool invocation hit transport timeout during build, retry completed. Build warns multiple lockfiles and unavailable local backend (127.0.0.1:4001) during prerender; this is not runtime API acceptance.
Full ESLint fails on existing lib/slug.ts:30 prefer-const; pristine git archive of base18094f9 with same dependencies reproduces sole error. Baseline 511 warnings; current initial run 514 warnings; owned-file lint exit0. No unrelated lint fix or gate waiver. Final Stage release remains conditional on parent's existing quality-gate policy.
Independent read-only review deleg_3a59d15b task0 agrees semantics and distinguishes daily report dual date convention from Persian/Tehran article date. Existing client visible predicate unchanged, actual client SSR negative tests cover null/missing/invalid/equal/earlier content timestamps despite technical writes. Substantive update test remains existing client suite coverage.
Fresh production GET at 2026-10-30T12:20:42.508566+00:00 (Telegram UA): HTTP200, publication 2026-10-29T07:11:40.925Z, dateModified/OG modified still absent, image present. Raw HTML/headers retained. Earlier real-browser evidence in recovery-fresh-timestamp-evidence.json inspected. No claim this local fix is deployed; no record resave, commit/push/deploy/data/cron/global configuration.
Machine-readable source/log manifest: /opt/data/content-maintenance/recovery-evidence-20261030/timestamp-source-manifest.json. Parent must review exact source hashes, commit authorized slice, deploy Stage via CI, validate actual HTML tags/JSON-LD/visible labels/noindex/canonical/image and unchanged record dates, then seek explicit production rollout authorization. Existing publisher gates are not waived.
+4
View File
@@ -0,0 +1,4 @@
# Plan
Graph navigation: graphify-out/graph.json sha256 6a73473cee9e207543fdeeb668bea544f766200a1b16b8a3a9ce18d4e42e51af, built_at_commit e7ded849f6b1e3bdab2a20d89b3ec7dd0df79cab (stale, navigation only). Read-only traversal confirms page -> getBlog/getSeoConfig/safeIso and imports BlogPostClient; direct current source/tests verify page -> validContentUpdatedAt -> publicationDate and client visible predicate. No graph writes or global installs. No API/schema changes.
Use existing ISO normalization and substantive date predicate independently for OG and JSON-LD with publication fallback; remove runtime-date invention. Use existing persianDate formatter safely for publication display to align Tehran timezone. Tests cover null/invalid/equal/earlier content dates, actual later edit, system/image-only change, invalid or absent publication, createdAt compatibility and Tehran date boundary. Update previous omission assertion to new explicitly requested contract. Keep shared formatter/client/backend untouched.
Inspect current deployed public HTML read-only, retain raw responses and parsed timestamp evidence externally. Existing project .specify constitution inspected; no scaffold overwrite. No unresolved business question for this user-specified narrow contract.
+12
View File
@@ -0,0 +1,12 @@
# Truthful article timestamp metadata
## Scope and decisions
Bound to base 18094f91a6babdd8e08e7b294e18557de9778d59 (dirty shared develop; unrelated backend/SEO/corporate files parent-owned). Only blog/[slug] page/tests and these specs are owned here. No record, cron, configuration, commit, push or deployment changes.
The Oct29 household-cleaner article has real publishedAt 2026-10-29T07:11:40.925Z and null contentUpdatedAt. Image attachment is not editorial freshness.
## Acceptance
- JSON-LD dateModified and OG modifiedTime equal valid substantive contentUpdatedAt, else the real publication timestamp. Generic updatedAt never creates freshness.
- Publication fallback preserves existing valid createdAt compatibility, consistently across metadata and JSON-LD. No render-clock fallback when both are invalid/missing; unknown dates are omitted.
- Visible update remains substantive-only through unchanged validContentUpdatedAt; publication display remains Persian calendar in Asia/Tehran (not daily report's dual timezone header).
- Retain Stage noindex, canonical, author, image and content behavior.
- RED behavior tests then GREEN full frontend unit suite, typecheck, lint and Next build. Local proof is not Stage acceptance or production authorization.
## Policy
SEO governance SKILL.md:19-20 and daily-content-publisher:139,145 require truthful complete timestamps without artificial freshness. Daily report dual timestamps apply at line150, not article display. Independent read-only policy review deleg_3a59d15b concurs with publication fallback and flags render-clock fabrication.
+7
View File
@@ -0,0 +1,7 @@
# Tasks
- [x] Inspect evidence, base/dirty status, graph navigation and direct source.
- [x] Independent source-policy/date-convention review.
- [x] Write failing timestamp regression tests and record RED (10 failures / 11 tests).
- [x] Minimal page-only implementation and GREEN focused tests (25 tests).
- [x] Execute full frontend tests (540/540), typecheck (exit0), lint (baseline sole error reproduced, owned lint exit0), build (exit0); logs/source manifest in /opt/data/content-maintenance/recovery-evidence-20261030/. Full lint gate remains failing, not waived.
- [ ] Parent review and authorized Stage rollout (not this worker); production remains unauthorized.
@@ -0,0 +1,7 @@
# Plan
Ownership: backend/src/wiki/wiki.service.spec.ts; backend/scripts/test-postgres.py; backend/package.json test scripts; this spec directory only. No corporate service/runtime or UI files.
Graphify: queried scratch copy at /opt/data/cache/scratch/backend-acceptance-graph (4304 nodes). Original SHA256 6a73473cee9e207543fdeeb668bea544f766200a1b16b8a3a9ce18d4e42e51af; provenance not SHA-bound, navigation only. Direct source confirms WikiService reads relevance candidates (take 100), ranks then slices; shared metadata helper uses totalPages and compatibility lastPage. Existing publication URL guard mandates port 55447; SEO mandates port 55439; corporate mandates loopback corporate_test. Tests destructively clean fixtures, so only newly initialized clusters are eligible.
Runner uses existing PostgreSQL binaries via PG_BIN or PATH, mkdtemp under TMPDIR, explicit loopback ports/private sockets, Prisma db push into newly created databases, child-only test URLs and guaranteed pg_ctl stop in finally. No daemon reuse. Default test runs serially to avoid shared fixture collisions. Direct Jest remains available for explicit targeted unit tests; the default npm test gate never silently skips missing PostgreSQL URLs.
@@ -0,0 +1,11 @@
# Backend acceptance test gates
Scope: wiki unit-test expectations and isolated PostgreSQL full-suite setup only. No service/runtime/UI edits, deployment, cron, production configuration or business-data writes.
Acceptance:
- Wiki tests distinguish bounded relevance candidate retrieval from final page slicing and verify filtered count metadata; non-search pagination remains database-driven.
- Default backend test command provisions disposable loopback PostgreSQL and executes publication, SEO and corporate database integration suites instead of silently skipping missing URLs.
- Missing PostgreSQL binaries or occupied dedicated ports fail explicitly. Existing runtime DATABASE_URL is never used for schema setup.
- Preserve existing dirty/untracked work. Stage-principal tests are separate opt-in tests requiring Redis and /app artifacts; report their skips explicitly.
Baseline: develop 69dd6922f6ce25e5b98471b14282b7834537431a. Initial dirty state: graphify-out/cache/last_query_stamp; untracked .specify/ and evidence/. RED full suite: 2 failed, 99 passed, 6 skipped; 1 failed/905 passed/25 skipped tests.
@@ -0,0 +1,20 @@
# Tasks
- [x] Inspect source, graph provenance, branch, dirty state and existing tests.
- [x] Run baseline full suite RED and retain /opt/data/cache/scratch/backend-suite-red.log.
- [x] Correct wiki expectations; add ranking/page-2 and non-search pagination checks.
- [x] Implement disposable PostgreSQL runner and default test command; fail closed on setup failure.
- [x] Run full backend GREEN, record commands/counts and explicit remaining skips; verify owned diff only.
## Execution evidence
Working directory for commands: `/opt/data/content-maintenance/engine/worktree-concurrency-tdd/backend`.
- RED before edits: `npm test -- --runInBand` (then direct Jest script): 2 failed, 99 passed, 6 skipped suites; 1 failed, 905 passed, 25 skipped tests. `/opt/data/cache/scratch/backend-suite-red.log`.
- GREEN: `PG_BIN=/opt/data/cache/scratch/seo-pg-bin/bin npm test`: exit 0, 105 passed and 2 skipped suites; 934 passed and 3 skipped tests, 62.56s. `/opt/data/cache/scratch/backend-suite-green.log`. All SEO, publication, corporate and API-key PostgreSQL suites executed. Remaining skips are two Stage-principal lifecycle suites (Redis and `/app` prerequisites), not missing database URLs.
- `PG_BIN=/does-not-exist npm test`: expected exit 1, explicit missing-initdb failure. `/opt/data/cache/scratch/backend-pg-missing-bin.log`.
- Bind 127.0.0.1:55439 in a Python socket then invoke runner: expected exit 1, address in use. No existing server reused or stopped.
- `npm run build`: exit 0 (`tsc -b`). `git diff --check`: exit 0.
- All three fresh PostgreSQL 16.2 clusters stopped after full suite and temporary cluster directory removed. No production connection or configuration accessed. Existing dirty graph stamp and untracked .specify/evidence preserved.
Setup detail: publication's existing source URL allowlist contains a dedicated test-only credential. Runner reads and validates its literal loopback prefix to avoid duplicating it; first execution exposed that redacted tool display must not be treated as the credential itself. No change to publication or corporate test/service files was necessary. Docker unavailable; reused already-installed local PostgreSQL binaries, with no package installation.
@@ -0,0 +1,41 @@
# Bounded acceptance-gap audit
Baseline: develop 69dd6922f6ce25e5b98471b14282b7834537431a, official Stage run1352. Audit is bounded to existing specs, runtime scripts, corporate service/controller, UI/services and focused/full-suite evidence; not a claim of enterprise acceptance.
| Criterion | Code/tests | Deployment/behavior | Verdict / next dependency |
|---|---|---|---|
| Real persisted source provenance | corporate research/source tables, validated HTTPS metadata, manual ingest stores fetched bytes and SHA256 | Baseline both Stage images independently read as 69dd6922, restart0; source inventory pilot exists, not autonomous business research | partial: discovery/synthesis and provider-backed intelligence missing |
| Monthly research -> persisted roadmap/goals | service roadmap requires persisted research with sources; manual CLI manifest | Existing integration tests; no demonstrated automatic strategy synthesis | partial |
| Daily NEW article plan separate from refresh | UI promises daily new; roadmap counts only; fanout creates source inventories | No dated article planning or article executor | missing |
| Needs-based refresh/catalog/wiki/engineering/devops | dormant deterministic structural department audits and GET-only plan_day | Not clinical enrichment, code execution, or publication; plan is not persisted task fanout | partial |
| Atomic claim/execution/evidence/independent QA | service lease fencing, idempotency, TEST, distinct review identity, exact hash verification | Existing real disposable DB tests and source-inventory pilot | partial: only manual bounded inventory/audits, no business action adapters |
| Visible instruction/action/result/evidence/QA | Task detail shows description and event summaries only; evidence/reviews/effects omitted; TEST absent in frontend status type/filter | API detail includes these relations; UI cannot inspect exact receipts | **missing next slice**: read-only persisted execution dossier + TEST status |
| PMO outcomes/report | persisted backend report snapshots, explicit truncation; manual GET-only plan | No integrated daily plan/report consumer or report UI | partial |
| Market pagination/filter/search | pagination/category UI + backend; no search | Not authenticated/mobile accepted in this audit yet | partial |
| Roadmap pagination/filter/search | pagination UI, month backend only; no search | Not authenticated/mobile accepted yet | partial |
| Tasks pagination/filter/search | server pagination, normalized title/code, dept/status/priority | Missing TEST option; execution dossier absent | partial |
| SEO under Hermes/mobile | existing tracking page and API, independent telemetry limits | Requires distinct authenticated mobile review, not proven by compile | partial |
| No fake fallback | APIs reject unavailable collections; UI explicit errors; metrics unavailable != zero | Preserve; no demo business data added | code present, scoped verification required |
| Test gates | baseline full Jest: 2 failures incl wiki expectation and absent isolated DB URLs | Repair full gate with fresh private PostgreSQL harness, no live DB reuse | partial until repaired run |
| Public author attribution | credentialless genuine authors restored; marker denied all auth paths | Baseline API repair confirmed by parent; public attribution UI still unresolved | partial; inspect real byline/metadata, never invent credentials/clinical expertise |
| Autonomous operation | runtime explicitly MANUAL_DORMANT, schedules false | Must remain cron-disconnected until whole acceptance | deliberately not enabled |
## 2026-10-30 next slice (local, not deployed)
- Persisted monthly planning/API prior Stage acceptance is recorded by release owner (engineering fixtures, not clinical roadmap approval).
- `scripts/corporate_plan_inventory.py` now supports explicit `prepare roadmap month task`, `execute child`, separate-key `qa child evidence`, and `report child` authenticated readback. It copies exact instruction/PLANNED source lineage into a linked RESEARCH prerequisite, verifies selected existing source bytes and hashes, and never submits evidence for the original BLOG_NEW/needs action.
- Optional claim `taskId` selects only the exact eligible child, preserves future-plan fences and historical no-selector idempotency hashes; no fallback claim.
- Real disposable HTTP/PostgreSQL scenario exercises creation/replay, exact execution, self-review denial, independent rejection, corrective execution, independent pass and PMO readback. Original task remains BLOCKED after rejection (TODO on happy path), with no article evidence/review. This is inventory, not synthesis/publication/clinical QA.
- Independent review found rejection recovery blocked by TODO-only parent guard; fixed for existing linked child snapshot only, with RED/GREEN HTTP regression. New prepare still requires TODO. PMO records observed TODO/BLOCKED, not an invented completion.
- Local gates: backend 105 suites/950 tests pass (2 existing suites/3 tests skipped), Python 27 tests pass, backend build pass; admin full tests/build pass. Exact logs/source hashes: `/opt/data/content-maintenance/corporate-action-evidence-20261030/manifest.json`.
- Remaining: action-specific writers/provider-backed real research, approved business source store/roadmap, Stage acceptance of this slice, integrated monthly/report UI, complete mobile acceptance, controlled activation approval. No schema/approval/publisher/cron/Hermes config/Production changes; MANUAL_DORMANT remains.
## Slice selection
First unblock truthful inspection of persisted execution: without exact tool/result/hash and independent QA visible, a higher-level planner would create more uninspectable tasks. Implement read-only dossier, real TEST status/filter, empty and bounded-history disclosures. No schema/business writes, new scheduler, approval modules, Hermes config/restarts, Production or main changes.
## Remaining sequence
1. Accept this dossier and corrected isolated DB gate on exact-SHA Stage.
2. Research-backed dated daily-new article planning, separate needs-based refresh/catalog/wiki/engineering task lineage, API idempotent persistence (review schema separately if needed).
3. Implement narrowly allowed action adapters with immutable instruction/action/result/evidence and independent QA; no model-output-is-DONE shortcuts.
4. Persist PMO outcomes and downstream daily plan; add market/roadmap search/filter/report UI, finish authenticated mobile acceptance and real public author checks.
5. Only after complete independent acceptance consider explicit activation of the currently dormant/manual runtime; no cron changes in this program slice.
@@ -0,0 +1,11 @@
{
"baseSha": "69dd6922f6ce25e5b98471b14282b7834537431a",
"graphSha256": "6a73473cee9e207543fdeeb668bea544f766200a1b16b8a3a9ce18d4e42e51af",
"graphSourceBinding": "unknown; stale navigation only, verified direct source",
"queryCopy": "/opt/data/cache/scratch/corporate-gap-graph/graph.json",
"dirtyBefore": [
"graphify-out/cache/last_query_stamp",
".specify/",
"evidence/"
]
}
@@ -0,0 +1,25 @@
# Manual planned-action prerequisite (bounded slice)
Base develop 216e05ba. Existing dated plans contain BLOG_NEW and needs actions, whereas runtime only executes RESEARCH. Do not reinterpret inventory as article/enrichment completion.
## Acceptance / plan
- Explicit operator chooses persisted roadmap/month/task. Read exact PLANNED lineage, goal/date/action/source IDs and stored instruction. Validate lineage and due UTC day before any mutation.
- Create a separately linked RESEARCH child with immutable structured `planned_source_inventory_v1` instruction. Parent action remains pending (TODO normally; BLOCKED after child rejection), never published or auto-completed.
- Targeted claim must not consume another queued task; preserve legacy claim idempotency. Execute exact stored source bytes selected by plan, store canonical snapshot/evidence, independently recompute during separate-identity QA.
- PMO report after persisted child DONE must explicitly disclose original action pending; read report back. No models, synthesis, business adapter, external effect claim, cron, schema, approvals, production or publisher changes.
- TDD: invalid/future/changed/missing lineage/source; exact snapshot; targeted claim; QA tamper; report readback. Focused and full backend/Python tests and backend build. Existing UI dossier is read-only inspection; no frontend change expected.
## Review needs
This is genuine stored-source inventory, not new scientific research, clinical validation, publication or enterprise completion. Source bytes must already exist in the content-addressed operator store. Missing bytes fail closed; no network substitute. Stage engineering data is not an approved clinical roadmap. Parent owns review, commit, push and Stage acceptance.
## Operation / recovery limits
Invoke `python3 scripts/corporate_plan_inventory.py --store SECURED_STORE --key STABLE_KEY [--api API --allow-stage-https] prepare ROADMAP MONTH TASK`, then `execute CHILD`, separate `CORPORATE_QA_API_KEY` identity `qa CHILD EVIDENCE`, then `report CHILD`. Each command is explicitly manual. Never pass credentials in CLI arguments. Require the original ingested source bytes in this store; no network fetch or provider output is substituted.
Stable prepare keys deduplicate exact requests only; different keys/actors can create additional children. Do not claim exactly-once prerequisites. Backend already allows only one report per UTC day; a pre-existing daily report is a conflict requiring operator reconciliation, not a reason to overwrite it. PMO summary records a status observation, not an atomic ongoing status guarantee.
Do not rerun `execute` to recover an ambiguous evidence POST: timestamps change. The digest printed to stderr before the POST points to the exact immutable path/body/key. Use the existing `corporate_runtime.py replay-evidence DIGEST` with the same secured store/identity for explicit exact-body replay after readback. Tests simulate an ambiguous transport response and prove this preserved request replays unchanged. QA/report reruns are not replay APIs; read persisted task/report and reconcile manually. No automatic retry or fabricated success. QA rejection recovery uses a new execution key; the original pending parent remains BLOCKED and is not unblocked by this adapter.
## Verification receipt
Evidence `/opt/data/content-maintenance/corporate-action-evidence-20261030/`: initial missing-module RED, selector focused RED/GREEN copied from isolated claim evidence, happy-path HTTP focused GREEN, independent-review rejection RED/GREEN, final full backend and Python logs, backend/admin builds and full admin tests, source/log SHA256 manifest. Final backend: 105 suites/950 tests pass, existing 2 suites/3 tests skipped; Python: 27 pass. No commit/push/deploy. Initial admin commands failed because recovered clone lacked node_modules; reused existing dependencies only after byte-identical admin package-lock comparison, then full tests/build passed.
Graph SHA256 `6a73473cee9e207543fdeeb668bea544f766200a1b16b8a3a9ce18d4e42e51af` embeds older revision `e7ded849f6b1e3bdab2a20d89b3ec7dd0df79cab`, has no corporate/planner runtime nodes, and is navigation only; direct source/API/tests ground acceptance. No graph files were rewritten. Existing `.specify/` preserved. No frontend source changed; existing execution dossier renders child description, evidence, QA and links, but monthly/report UX remains a dependency.
@@ -0,0 +1,60 @@
# Persisted dated monthly plan — local implementation receipt
Base: `18094f91a6babdd8e08e7b294e18557de9778d59` (official develop, verified 2026-10-30).
## Bounded acceptance audit
- Existing `CorporateService.research()` and `roadmap()` persist research sources, roadmap and goals, but the roadmap contains aggregate counts rather than a dated execution calendar.
- Existing `scripts/corporate_runtime.py:fanout()` creates only RESEARCH inventory tasks. Existing department `plan_day()` reports unresolved audit findings in `dailyNew`; this is not a daily article calendar.
- Existing task goal relationship and event JSON payload support a no-schema slice. No schema design/apply is needed for this implementation.
## Implemented contract
`POST /api/admin/hermes/monthly-plans` uses existing controller authentication and required Idempotency-Key. Body: `roadmapId`, `month` (YYYY-MM), `dailyArticles` and `needs`.
Every calendar day has exactly one BLOG_NEW entry. Entries carry title, description, department, priority, goalId, actionType, dueCycle (YYYY-MM-DD) and sourceIds. Source IDs must exist in the stored roadmap research; goal and department must belong to that roadmap. Missing, duplicate or impossible dates fail closed. Needs use BLOG_UPDATE, CATALOG_ENRICH, WIKI_ENRICH or ENGINEERING and additionally require target and reason. Needs never satisfy daily NEW coverage and empty needs are allowed rather than fabricating quotas.
The backend transaction creates real task rows and PLANNED events containing research/roadmap/goal/source/date lineage. A roadmap/month advisory lock prevents duplicate plans across keys/actors. Existing operation replay returns the original response for exact same-key retries; conflicting payloads fail. Injection coverage proves partial writes roll back.
`GET /api/admin/hermes/monthly-plans/:roadmapId?month=YYYY-MM` reads persisted tasks with their PLANNED lineage. Claim eligibility gates only planned tasks by matching dueCycle and UTC day; future planned work is not immediately claimable. Legacy undated directives retain existing behavior.
Manual CLI `plan-month manifest.json` checkpoints the exact request before POST; `read-plan roadmap-id YYYY-MM` performs authenticated readback. No schedule, worker, publisher or claim is invoked by either command. Preserve stable mutation keys and read back after ambiguous transmission before any explicit retry.
## Real local verification
Evidence directory: `/opt/data/content-maintenance/corporate-plan-evidence-20261030/`.
- Backend RED: `backend-red.log`; readback RED: `backend-readback-red.log`.
- Final focused PostgreSQL integration/policy GREEN: 2 suites, 24 tests, `backend-focused-final2.log`. Expected injected database failure is logged by the rollback test; suite passes.
- Backend TypeScript build: exit 0, `backend-build-final2.log`.
- Full backend attempt: 104 suites passed, 1 failed, 2 skipped; 942 tests passed, 1 failed, 3 skipped. `backend-full-final.log`. Blocker is SEO worker HTTP ingestion replay returning 409 (reproduced twice); not claimed fully green.
- Manual CLI checkpoint regression RED: missing monthly_plan AttributeError, `runtime-red.log`; all corporate Python suites GREEN: 19 tests, `runtime-green.log`.
- `git diff --check`: clean.
## Safety and next dependencies
No commit, push, deployment, live business-data mutation, migration, main, cron, Hermes config or admin approval module change. MANUAL_DORMANT remains unchanged. This is locally implemented planning, not enterprise DONE or live acceptance.
Next: parent-owned single develop push and Stage CI; authenticated Stage plan creation/readback with real approved research; then implement action-specific execution/evidence/independent QA for planned tasks, public outcome readback, and explicit scheduling authorization only after those gates. Legacy department report's QA_REVIEW/TEST mismatch remains separate followup; it is not a monthly article planner.
## Integrated review and regression repair (2026-10-30)
Acceptance: preserve exact replay and reject changed numeric evidence, without tolerances, skipped gates, DDL or live writes. Preserve plan transactions, full calendar, daily BLOG_NEW versus separate needs, source lineage, and actor-independent roadmap/month uniqueness.
Independent source review confirmed transaction/lineage/calendar/guard design. The graph SHA256 is `6a73473cee9e207543fdeeb668bea544f766200a1b16b8a3a9ce18d4e42e51af`; its revision is unbound and it lacks planner nodes, so it remains navigation only. UUID case normalization defect was reproduced RED (`review-uppercase-red.log`) and fixed: accepted uppercase roadmap/goal/source IDs now normalize before lineage, hashing, lock scope and readback. The API integration test sends uppercase IDs and GETs uppercase roadmap ID. Future claim fixtures moved to leap month 2996-02, preserving trigger rollback checks.
Baseline full command on clean detached `18094f91` with the identical resolved node_modules and unchanged package-lock reproduced the SEO HTTP 409: 104 pass / 1 fail / 2 skipped suites, 933 pass / 1 fail / 3 skipped tests (`review-baseline-full.log`). The same HTTP test fails independently (`review-baseline-worker.log`). This is a pre-existing production numeric replay defect, not a monthly-plan regression. Diagnostic RED logs show 3.1818181818181817 returning as 3.181818181818182 and 18.333333333333332 as 18.33333333333333; nested JSON changes too. Prisma numeric transport loses exact double input. The repair uses text-bound PostgreSQL casts for Float and JSON writes atomically with create, and native PostgreSQL equality for replay. It does not use epsilon comparison. Concurrent real-PG numeric replay and single-ULP numeric/provenance changes are covered; changed evidence still returns 409. Previously rounded rows are not rewritten or silently accepted.
Final local results (all logs in the evidence directory above):
- `review-full-final.log`: 105 suites passed, 2 existing opt-in suites skipped; 944 tests passed, 3 existing opt-in tests skipped. Fresh disposable SEO/publication/corporate PostgreSQL clusters, stopped by the runner. No new skips.
- `review-focused-final.log`: monthly policy/API and SEO real worker HTTP/service regressions, exit 0.
- `review-build-final.log`: `npm run build`, exit 0.
- `review-runtime-all-final.log`: all corporate Python unittest discovery, exit 0.
- Expected injected database ERROR during rollback coverage is not a failing suite.
Review limitations: manual checkpoint submission has no dedicated monthly-plan replay subcommand (use stable original request/key and readback); action-specific consumers remain deferred/dormant. No Stage behavior or production identity is established by local JWT/PG tests. Parent must freeze the integrated commit, use official Stage CI, verify MANUAL_DORMANT and cron disconnection, and read back approved dated plan/actionType/lineage before calling Stage accepted. No commit/push/deploy performed by this worker.
## Repository recovery
Durable valid clone: `/opt/data/content-maintenance/corporate-durable-20261030`.
Broken original `/opt/data/content-maintenance/engine/worktree-concurrency-tdd` was not reset, cleaned or deleted. The missing scratch Git metadata was not recreated or rewritten. 332 source/spec/graph evidence files were copied with SHA256 manifest at `/opt/data/content-maintenance/recovery-evidence-20261030/manifest.json`; untracked owned specs/.specify were preserved without replacing tracked current develop files. Original graph and stamps remain external evidence. The recovered graph lacks corporate service/planner nodes, so source/tests, not graph inference, ground this slice.
@@ -0,0 +1,3 @@
# Plan
Baseline 69dd6922. Existing graph SHA binding unknown: SHA256 recorded in graph-provenance.json, query scratch copy finds stale unrelated Evidence/review nodes, used only navigation; direct corporate service/controller and UI sources verified. API already returns evidence/reviews/effects/relationsMeta. Add typed optional relation DTOs plus read-only TaskExecutionDossier component rendered inside existing fetched detail. Include TEST type/config. Own UI/API types/tests; backend test gate child owns disjoint paths. Use existing release workflow and gitea remote, never local bundle origin for push.
@@ -0,0 +1,3 @@
# Persisted execution dossier
Show existing authenticated task detail instruction, action type, assigned executor, exact evidence tool/result/URI/hash, independent QA verification and observed effects. TEST is a real selectable status. Read-only: no action buttons, claims or synthetic fallback. Empty evidence and missing metrics must not imply success. Expose relation truncation. Wrap long hashes/results on 390px; semantic labelled dialog with close button. Unit regression RED before UI edit; full admin tests/typecheck/build, backend full fresh PostgreSQL suite, storefront suite/build then exact-SHA Stage authenticated mobile acceptance. No schema, prod/main, cron/Hermes config or business-data SQL writes.
@@ -0,0 +1,8 @@
# Tasks
- [x] Bounded acceptance audit, source/API boundary review, preserve baseline untracked artifacts.
- [ ] Dossier and TEST regression RED.
- [ ] Minimal typed read-only dossier GREEN; full suites/build.
- [ ] Integrated source review, sole-owner develop push.
- [ ] Exact CI terminal logs, both images/restarts, authenticated Stage/mobile dossier + public real author UI evidence.
- [ ] Record remaining acceptance gaps without whole-program readiness claim.