Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d6db634a35 | ||
|
|
01f56c6db7 |
No files matched your search
@@ -12,7 +12,3 @@ uploads
|
||||
**/uploads
|
||||
*.pdf
|
||||
graphify-out
|
||||
**/.revalidation.env*
|
||||
**/.support*.env*
|
||||
**/*runtime.env
|
||||
**/release.override.json
|
||||
@@ -14,8 +14,9 @@ jobs:
|
||||
env:
|
||||
BRANCH: ${{ github.ref_name }}
|
||||
DEPLOY_SHA: ${{ github.sha }}
|
||||
GITHUB_ACTIONS: 'true'
|
||||
SUPPORT_CHAT_KEY: ${{ secrets.SUPPORT_CHAT_KEY }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# 1. رفع مشکل DNS و غیرفعال کردن پروکسی برای دامنه محلی
|
||||
echo "87.248.133.138 git.parsaaghayi.ir" >> /etc/hosts
|
||||
export http_proxy=""
|
||||
@@ -27,9 +28,7 @@ jobs:
|
||||
# 2. دانلود و اجرای اسکریپت deploy.sh بر اساس برنچ جاری
|
||||
mkdir -p scripts
|
||||
wget --no-proxy -qO scripts/deploy.sh https://git.parsaaghayi.ir/parsa/canina/raw/commit/${DEPLOY_SHA}/scripts/deploy.sh
|
||||
wget --no-proxy -qO scripts/release-cache-stage.sh https://git.parsaaghayi.ir/parsa/canina/raw/commit/${DEPLOY_SHA}/scripts/release-cache-stage.sh
|
||||
|
||||
wget --no-proxy -qO scripts/release-cache-prod.sh https://git.parsaaghayi.ir/parsa/canina/raw/commit/${DEPLOY_SHA}/scripts/release-cache-prod.sh
|
||||
chmod +x scripts/deploy.sh
|
||||
cd scripts
|
||||
./deploy.sh "${BRANCH}"
|
||||
./deploy.sh "${BRANCH}"
|
||||
@@ -0,0 +1,24 @@
|
||||
name: Hermes runtime contract review (NO DEPLOY)
|
||||
on:
|
||||
workflow_dispatch:
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
contract-review:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: npm
|
||||
cache-dependency-path: backend/package-lock.json
|
||||
- run: npm ci --ignore-scripts --no-audit
|
||||
working-directory: backend
|
||||
- run: npm test -- --runInBand hermes-management
|
||||
working-directory: backend
|
||||
- run: npx tsc -p src/hermes-management/tsconfig.contract.json --noEmit
|
||||
working-directory: backend
|
||||
- run: npx tsc -p src/hermes-management/tsconfig.contract.json
|
||||
working-directory: backend
|
||||
# No SSH, Docker socket, secrets, deployments, dispatch or runtime mutation.
|
||||
@@ -1,42 +0,0 @@
|
||||
name: Stage author bootstrap (dedicated repair)
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- ops/author-bootstrap-stage-rehearse
|
||||
- ops/author-bootstrap-stage-apply
|
||||
jobs:
|
||||
bootstrap:
|
||||
runs-on: canina
|
||||
steps:
|
||||
- name: Exact SHA build then isolated rehearsal and authorized repair
|
||||
env:
|
||||
GITHUB_SHA: ${{ github.sha }}
|
||||
GITHUB_REF: ${{ github.ref }}
|
||||
GITHUB_ACTIONS: 'true'
|
||||
STAGE_AUTHOR_BOOTSTRAP_REVIEWED_SHA: ${{ secrets.STAGE_AUTHOR_BOOTSTRAP_REVIEWED_SHA }}
|
||||
# Path only, NOT a token value. Parent supplies an existing private file
|
||||
# visible to the runner; absent file blocks repair AFTER image build.
|
||||
AUTHOR_BOOTSTRAP_TOKEN_FILE: ${{ secrets.STAGE_AUTHOR_BOOTSTRAP_TOKEN_FILE }}
|
||||
run: |
|
||||
set -eu
|
||||
set +x
|
||||
umask 077
|
||||
case "$GITHUB_REF" in
|
||||
refs/heads/ops/author-bootstrap-stage-rehearse|refs/heads/ops/author-bootstrap-stage-apply) ;;
|
||||
*) exit 2 ;;
|
||||
esac
|
||||
test "$STAGE_AUTHOR_BOOTSTRAP_REVIEWED_SHA" = "$GITHUB_SHA"
|
||||
export no_proxy="git.parsaaghayi.ir,localhost,127.0.0.1,87.248.133.138"
|
||||
echo "87.248.133.138 git.parsaaghayi.ir" >> /etc/hosts
|
||||
unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY
|
||||
root=$(mktemp -d)
|
||||
chmod 700 "$root"
|
||||
git init "$root/source"
|
||||
git -C "$root/source" fetch --depth=1 https://git.parsaaghayi.ir/parsa/canina.git "$GITHUB_SHA"
|
||||
git -C "$root/source" checkout --detach FETCH_HEAD
|
||||
test "$(git -C "$root/source" rev-parse HEAD)" = "$GITHUB_SHA"
|
||||
export AUTHOR_BOOTSTRAP_EVIDENCE="$root/evidence"
|
||||
printf 'Private Stage evidence directory (retained on failure): %s\n' "$root/evidence"
|
||||
python3 "$root/source/scripts/stage-author-bootstrap/ci.py"
|
||||
# Retain private dumps locally; never upload archive or credential files.
|
||||
printf 'Private Stage evidence directory: %s\n' "$root/evidence"
|
||||
@@ -1,35 +0,0 @@
|
||||
name: Stage SEO schema operation
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- ops/seo-schema-stage-rehearse
|
||||
- ops/seo-schema-stage-apply
|
||||
jobs:
|
||||
schema:
|
||||
runs-on: canina
|
||||
steps:
|
||||
- name: Exact immutable Stage operation
|
||||
env:
|
||||
GITHUB_SHA: ${{ github.sha }}
|
||||
GITHUB_REF: ${{ github.ref }}
|
||||
GITHUB_ACTIONS: 'true'
|
||||
STAGE_SCHEMA_REVIEWED_SHA: ${{ secrets.STAGE_SCHEMA_REVIEWED_SHA }}
|
||||
run: |
|
||||
set -eu
|
||||
case "$GITHUB_REF" in
|
||||
refs/heads/ops/seo-schema-stage-rehearse) mode=rehearse ;;
|
||||
refs/heads/ops/seo-schema-stage-apply) mode=apply ;;
|
||||
*) exit 2 ;;
|
||||
esac
|
||||
export no_proxy="git.parsaaghayi.ir,localhost,127.0.0.1,87.248.133.138"
|
||||
echo "87.248.133.138 git.parsaaghayi.ir" >> /etc/hosts
|
||||
unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY
|
||||
root=$(mktemp -d)
|
||||
chmod 700 "$root"
|
||||
git init "$root/source"
|
||||
git -C "$root/source" fetch --depth=1 https://git.parsaaghayi.ir/parsa/canina.git "$GITHUB_SHA"
|
||||
git -C "$root/source" checkout --detach FETCH_HEAD
|
||||
test "$(git -C "$root/source" rev-parse HEAD)" = "$GITHUB_SHA"
|
||||
python3 "$root/source/scripts/stage-schema/operation.py" "$mode" --sha "$GITHUB_SHA" --evidence "$root/evidence"
|
||||
# Private backups remain in this restricted runner directory; never upload dumps.
|
||||
printf 'Private Stage evidence directory: %s\n' "$root/evidence"
|
||||
@@ -16,7 +16,3 @@ playwright-report/
|
||||
playwright/.auth/
|
||||
blob-report/
|
||||
|
||||
|
||||
# Python CI helpers must not dirty immutable release checkouts.
|
||||
__pycache__/
|
||||
*.pyc
|
||||
@@ -1,14 +0,0 @@
|
||||
# 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
|
||||
@@ -1,251 +0,0 @@
|
||||
---
|
||||
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
|
||||
@@ -1,375 +0,0 @@
|
||||
---
|
||||
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
|
||||
@@ -1,287 +0,0 @@
|
||||
---
|
||||
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
|
||||
@@ -1,175 +0,0 @@
|
||||
---
|
||||
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
|
||||
@@ -1,275 +0,0 @@
|
||||
---
|
||||
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
|
||||
@@ -1,218 +0,0 @@
|
||||
---
|
||||
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
|
||||
@@ -1,166 +0,0 @@
|
||||
---
|
||||
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
|
||||
@@ -1,345 +0,0 @@
|
||||
---
|
||||
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
|
||||
@@ -1,216 +0,0 @@
|
||||
---
|
||||
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
|
||||
@@ -1,110 +0,0 @@
|
||||
---
|
||||
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
|
||||
@@ -1,10 +0,0 @@
|
||||
# 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 +0,0 @@
|
||||
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.
|
||||
@@ -1,9 +0,0 @@
|
||||
{
|
||||
"ai": "generic",
|
||||
"allow_symlinks": false,
|
||||
"feature_numbering": "sequential",
|
||||
"here": true,
|
||||
"integration": "generic",
|
||||
"script": "sh",
|
||||
"speckit_version": "1.2.3"
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"sha256": "ce7549540fa45543cca797a150201d868e64495fdff39dc38246fb17bd4024b3",
|
||||
"source": "core"
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,5 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,249 +0,0 @@
|
||||
#!/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
|
||||
@@ -1,942 +0,0 @@
|
||||
#!/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
|
||||
}
|
||||
@@ -1,504 +0,0 @@
|
||||
#!/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
|
||||
@@ -1,57 +0,0 @@
|
||||
#!/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
|
||||
@@ -1,89 +0,0 @@
|
||||
#!/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
|
||||
@@ -1,94 +0,0 @@
|
||||
#!/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
|
||||
@@ -1,3 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,7 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,45 +0,0 @@
|
||||
# [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
|
||||
@@ -1,50 +0,0 @@
|
||||
# [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 -->
|
||||
@@ -1,113 +0,0 @@
|
||||
# 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] |
|
||||
@@ -1,131 +0,0 @@
|
||||
# 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"]
|
||||
@@ -1,252 +0,0 @@
|
||||
---
|
||||
|
||||
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
|
||||
@@ -1,74 +0,0 @@
|
||||
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 }}"
|
||||
@@ -1,13 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
}
|
||||
}
|
||||
+9
-9
@@ -1,4 +1,4 @@
|
||||
FROM node:22-alpine AS app-builder
|
||||
FROM node:20-alpine AS app-builder
|
||||
USER root
|
||||
WORKDIR /app
|
||||
ENV NEXT_TELEMETRY_DISABLED=1
|
||||
@@ -7,17 +7,18 @@ ENV NEXT_PUBLIC_API_URL=https://api.canina.ir/api
|
||||
# Optional: Use Nexus as npm registry
|
||||
ARG NPM_REGISTRY=
|
||||
RUN if [ -n "$NPM_REGISTRY" ]; then \
|
||||
npm config set registry "$NPM_REGISTRY"; \
|
||||
npm config set registry "$NPM_REGISTRY" && \
|
||||
npm config set strict-ssl false; \
|
||||
fi
|
||||
|
||||
COPY frontend/application/package*.json ./
|
||||
RUN npm ci --include=dev --prefer-offline --no-audit && test -x node_modules/.bin/next
|
||||
RUN npm ci --include=dev --prefer-offline --no-audit
|
||||
COPY frontend/application ./
|
||||
ARG NEXT_PUBLIC_API_URL
|
||||
ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL
|
||||
RUN npm run build
|
||||
|
||||
FROM node:22-alpine AS admin-builder
|
||||
FROM node:20-alpine AS admin-builder
|
||||
USER root
|
||||
WORKDIR /app
|
||||
ENV VITE_API_URL=https://api.canina.ir/api
|
||||
@@ -25,17 +26,18 @@ ENV VITE_API_URL=https://api.canina.ir/api
|
||||
# Optional: Use Nexus as npm registry (inherits build-arg)
|
||||
ARG NPM_REGISTRY=
|
||||
RUN if [ -n "$NPM_REGISTRY" ]; then \
|
||||
npm config set registry "$NPM_REGISTRY"; \
|
||||
npm config set registry "$NPM_REGISTRY" && \
|
||||
npm config set strict-ssl false; \
|
||||
fi
|
||||
|
||||
COPY frontend/admin-panel/package*.json ./
|
||||
RUN npm ci --include=dev --prefer-offline --no-audit && test -x node_modules/.bin/vite
|
||||
RUN npm ci --include=dev --prefer-offline --no-audit
|
||||
COPY frontend/admin-panel ./
|
||||
ARG VITE_API_URL
|
||||
ENV VITE_API_URL=$VITE_API_URL
|
||||
RUN npm run build
|
||||
|
||||
FROM node:22-alpine
|
||||
FROM node:20-alpine
|
||||
USER root
|
||||
RUN addgroup -S nginx 2>/dev/null || true && adduser -S nginx -G nginx 2>/dev/null || true
|
||||
RUN mkdir -p /var/log/nginx /var/cache/nginx /run/nginx /etc/nginx/conf.d /etc/nginx/http.d
|
||||
@@ -47,8 +49,6 @@ RUN chown -R nginx:nginx /var/log/nginx /var/cache/nginx /run/nginx 2>/dev/null
|
||||
WORKDIR /app
|
||||
COPY --from=app-builder /app .
|
||||
COPY --from=admin-builder /app/dist ./admin_static
|
||||
# Build-context umask must not make public assets unreadable by nginx workers.
|
||||
RUN chmod -R a+rX /app/admin_static
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
COPY nginx.conf /etc/nginx/http.d/default.conf
|
||||
|
||||
|
||||
+2
-3
@@ -12,6 +12,7 @@ ENV npm_config_cache=/tmp/npm-cache
|
||||
ARG NPM_REGISTRY=
|
||||
RUN if [ -n "$NPM_REGISTRY" ]; then \
|
||||
npm config set registry "$NPM_REGISTRY" && \
|
||||
npm config set strict-ssl false && \
|
||||
echo "Using npm registry: $NPM_REGISTRY"; \
|
||||
fi
|
||||
|
||||
@@ -31,10 +32,8 @@ RUN http_proxy=http://172.17.0.1:8888 https_proxy=http://172.17.0.1:8888 \
|
||||
FROM node:20-alpine
|
||||
USER root
|
||||
RUN http_proxy=http://172.17.0.1:8888 https_proxy=http://172.17.0.1:8888 apk add --no-cache openssl || apk add --no-cache openssl || true
|
||||
RUN mkdir -p /app/uploads /app/private-stage-test && chmod 700 /app/private-stage-test && chown node:node /app/uploads /app/private-stage-test
|
||||
RUN mkdir -p /app/uploads && chown node:node /app/uploads
|
||||
WORKDIR /app
|
||||
ARG STAGE_TEST_ARTIFACT_SHA=disabled
|
||||
RUN printf "%s" "$STAGE_TEST_ARTIFACT_SHA" > /app/STAGE_TEST_ARTIFACT_SHA
|
||||
ENV PRISMA_HIDE_UPDATE_MESSAGE=true
|
||||
COPY --chown=node:node --from=builder /app/package*.json ./
|
||||
COPY --chown=node:node --from=builder /app/tsconfig.json ./tsconfig.json
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
"start:debug": "nest start --debug --watch",
|
||||
"start:prod": "node dist/main",
|
||||
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
||||
"test": "python3 scripts/test-postgres.py",
|
||||
"test": "jest",
|
||||
"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",
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
CREATE TABLE prepare_workflow_outbox (
|
||||
id uuid PRIMARY KEY, task_id uuid NOT NULL UNIQUE REFERENCES orchestration_tasks(id) ON DELETE RESTRICT,
|
||||
status varchar(20) NOT NULL DEFAULT 'PENDING' CHECK (status IN ('PENDING','DONE')),
|
||||
attempts integer NOT NULL DEFAULT 0 CHECK (attempts BETWEEN 0 AND 3),
|
||||
lease_owner varchar(100), lease_token uuid, lease_until timestamptz, heartbeat_at timestamptz,
|
||||
run_id uuid REFERENCES orchestration_runs(id) ON DELETE RESTRICT,
|
||||
reservation_id uuid REFERENCES orchestration_budget_ledger(id) ON DELETE RESTRICT,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX prepare_workflow_outbox_status_lease_until_idx ON prepare_workflow_outbox(status,lease_until);
|
||||
@@ -1,3 +0,0 @@
|
||||
-- Scheduling is distinct from immutable approval validity. Existing queues run immediately.
|
||||
ALTER TABLE "prepare_workflow_outbox" ADD COLUMN "not_before" TIMESTAMPTZ;
|
||||
CREATE INDEX "prepare_workflow_outbox_due_idx" ON "prepare_workflow_outbox" ("status", "not_before", "created_at");
|
||||
@@ -1 +0,0 @@
|
||||
ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "auth_expires_at" TIMESTAMPTZ, ADD COLUMN IF NOT EXISTS "stage_test_session" VARCHAR(64), ADD COLUMN IF NOT EXISTS "stage_test_generation" UUID;
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
-- Drop legacy governance and orchestration tables
|
||||
DROP TABLE IF EXISTS "prepare_workflow_outbox" CASCADE;
|
||||
DROP TABLE IF EXISTS "orchestration_kill_switches" CASCADE;
|
||||
DROP TABLE IF EXISTS "orchestration_budget_ledger" CASCADE;
|
||||
DROP TABLE IF EXISTS "orchestration_events" CASCADE;
|
||||
DROP TABLE IF EXISTS "orchestration_approval_decisions" CASCADE;
|
||||
DROP TABLE IF EXISTS "orchestration_dependencies" CASCADE;
|
||||
DROP TABLE IF EXISTS "orchestration_attestations" CASCADE;
|
||||
DROP TABLE IF EXISTS "orchestration_artifacts" CASCADE;
|
||||
DROP TABLE IF EXISTS "orchestration_runs" CASCADE;
|
||||
DROP TABLE IF EXISTS "orchestration_tasks" CASCADE;
|
||||
DROP TABLE IF EXISTS "department_tasks" CASCADE;
|
||||
DROP TABLE IF EXISTS "audit_logs" CASCADE;
|
||||
DROP TABLE IF EXISTS "approval_requests" CASCADE;
|
||||
@@ -1,89 +0,0 @@
|
||||
-- SEO models existed in schema.prisma without a tracked CREATE migration.
|
||||
-- Create only missing SEO objects, then additively upgrade existing SEO tables.
|
||||
-- This does not reconcile the repository's broader incomplete baseline: blogs
|
||||
-- must already exist (see prisma/MIGRATION_BASELINE.md). No live SQL is run here.
|
||||
DO $$ BEGIN
|
||||
CREATE TYPE "ResearchFindingStatus" AS ENUM ('RESEARCHED', 'ACTIONED', 'EVALUATING', 'SCALED', 'PRUNED');
|
||||
EXCEPTION
|
||||
WHEN duplicate_object THEN NULL;
|
||||
END $$;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "content_research_findings" (
|
||||
"id" UUID NOT NULL,
|
||||
"title" VARCHAR(255) NOT NULL,
|
||||
"hypothesis" TEXT NOT NULL,
|
||||
"target_keywords" TEXT[],
|
||||
"primary_keyword" VARCHAR(128) NOT NULL,
|
||||
"expected_outcome" TEXT NOT NULL,
|
||||
"status" "ResearchFindingStatus" NOT NULL DEFAULT 'RESEARCHED',
|
||||
"blog_id" UUID,
|
||||
"ceo_feedback" TEXT,
|
||||
"feedback_submitted_at" TIMESTAMPTZ,
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMPTZ NOT NULL,
|
||||
CONSTRAINT "content_research_findings_pkey" PRIMARY KEY ("id"),
|
||||
CONSTRAINT "content_research_findings_blog_id_fkey" FOREIGN KEY ("blog_id") REFERENCES "blogs"("id") ON DELETE SET NULL ON UPDATE CASCADE
|
||||
);
|
||||
|
||||
ALTER TABLE "content_research_findings"
|
||||
ADD COLUMN IF NOT EXISTS "version" INTEGER NOT NULL DEFAULT 0,
|
||||
ADD COLUMN IF NOT EXISTS "feedback_version" INTEGER NOT NULL DEFAULT 0,
|
||||
ADD COLUMN IF NOT EXISTS "search_text" TEXT NOT NULL DEFAULT '',
|
||||
ADD COLUMN IF NOT EXISTS "goal_metric" TEXT,
|
||||
ADD COLUMN IF NOT EXISTS "goal_target" DOUBLE PRECISION,
|
||||
ADD COLUMN IF NOT EXISTS "action_id" TEXT;
|
||||
-- action_id is a plain external reference, deliberately without a foreign key.
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "content_research_findings_blog_id_key" ON "content_research_findings"("blog_id");
|
||||
CREATE INDEX IF NOT EXISTS "content_research_findings_status_idx" ON "content_research_findings"("status");
|
||||
CREATE INDEX IF NOT EXISTS "content_research_findings_primary_keyword_idx" ON "content_research_findings"("primary_keyword");
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "content_performance_snapshots" (
|
||||
"id" UUID NOT NULL,
|
||||
"finding_id" UUID NOT NULL,
|
||||
"snapshot_date" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"gsc_impressions" INTEGER,
|
||||
"gsc_clicks" INTEGER,
|
||||
"gsc_position" DOUBLE PRECISION,
|
||||
"ga4_active_users" INTEGER,
|
||||
"ga4_avg_engagement_sec" DOUBLE PRECISION,
|
||||
"ga4_bounce_rate" DOUBLE PRECISION,
|
||||
"ga4_scroll_depth_rate" DOUBLE PRECISION,
|
||||
"attributed_orders_count" INTEGER,
|
||||
"attributed_sales_value" DECIMAL(15,2),
|
||||
"action_recommendation" VARCHAR(64),
|
||||
"analysis_notes" TEXT,
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "content_performance_snapshots_pkey" PRIMARY KEY ("id"),
|
||||
CONSTRAINT "content_performance_snapshots_finding_id_fkey" FOREIGN KEY ("finding_id") REFERENCES "content_research_findings"("id") ON DELETE CASCADE ON UPDATE CASCADE
|
||||
);
|
||||
|
||||
ALTER TABLE "content_performance_snapshots"
|
||||
ADD COLUMN IF NOT EXISTS "period_start" TIMESTAMPTZ,
|
||||
ADD COLUMN IF NOT EXISTS "period_end" TIMESTAMPTZ,
|
||||
ADD COLUMN IF NOT EXISTS "source_metadata" JSONB,
|
||||
ADD COLUMN IF NOT EXISTS "ingestion_key" TEXT,
|
||||
ALTER COLUMN "gsc_impressions" DROP NOT NULL,
|
||||
ALTER COLUMN "gsc_impressions" DROP DEFAULT,
|
||||
ALTER COLUMN "gsc_clicks" DROP NOT NULL,
|
||||
ALTER COLUMN "gsc_clicks" DROP DEFAULT,
|
||||
ALTER COLUMN "gsc_position" DROP NOT NULL,
|
||||
ALTER COLUMN "gsc_position" DROP DEFAULT,
|
||||
ALTER COLUMN "ga4_active_users" DROP NOT NULL,
|
||||
ALTER COLUMN "ga4_active_users" DROP DEFAULT,
|
||||
ALTER COLUMN "ga4_avg_engagement_sec" DROP NOT NULL,
|
||||
ALTER COLUMN "ga4_avg_engagement_sec" DROP DEFAULT,
|
||||
ALTER COLUMN "ga4_bounce_rate" DROP NOT NULL,
|
||||
ALTER COLUMN "ga4_bounce_rate" DROP DEFAULT,
|
||||
ALTER COLUMN "ga4_scroll_depth_rate" DROP NOT NULL,
|
||||
ALTER COLUMN "ga4_scroll_depth_rate" DROP DEFAULT,
|
||||
ALTER COLUMN "attributed_orders_count" DROP NOT NULL,
|
||||
ALTER COLUMN "attributed_orders_count" DROP DEFAULT,
|
||||
ALTER COLUMN "attributed_sales_value" DROP NOT NULL,
|
||||
ALTER COLUMN "attributed_sales_value" DROP DEFAULT;
|
||||
|
||||
-- Do not rewrite historical metrics: old zeros remain zeros, not proven measures.
|
||||
-- Newly added metadata/period/key columns remain SQL NULL for legacy snapshots;
|
||||
-- no provenance, observation period, or idempotency key can be inferred safely.
|
||||
CREATE INDEX IF NOT EXISTS "content_performance_snapshots_finding_id_snapshot_date_idx" ON "content_performance_snapshots"("finding_id", "snapshot_date");
|
||||
-- PostgreSQL permits multiple NULL keys, preserving all historical snapshots.
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "content_performance_snapshots_finding_id_ingestion_key_key" ON "content_performance_snapshots"("finding_id", "ingestion_key");
|
||||
@@ -1,244 +0,0 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "CorporateTaskStatus" AS ENUM ('TODO', 'IN_PROGRESS', 'TEST', 'DONE', 'BLOCKED', 'REJECTED', 'CANCELLED');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "CorporatePriority" AS ENUM ('CEO_EXPEDITE', 'CRITICAL', 'HIGH', 'MEDIUM', 'LOW');
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "corporate_tasks" (
|
||||
"id" UUID NOT NULL,
|
||||
"taskCode" TEXT NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"normalizedTitle" TEXT NOT NULL,
|
||||
"normalizedCode" TEXT NOT NULL,
|
||||
"description" TEXT NOT NULL,
|
||||
"department" TEXT NOT NULL,
|
||||
"priority" "CorporatePriority" NOT NULL DEFAULT 'CEO_EXPEDITE',
|
||||
"status" "CorporateTaskStatus" NOT NULL DEFAULT 'TODO',
|
||||
"actionType" TEXT NOT NULL DEFAULT 'CEO_DIRECTIVE',
|
||||
"dueCycle" TEXT,
|
||||
"parentId" UUID,
|
||||
"goalId" UUID,
|
||||
"assignedAgent" TEXT,
|
||||
"claimToken" UUID,
|
||||
"leasedUntil" TIMESTAMPTZ,
|
||||
"executionCount" INTEGER NOT NULL DEFAULT 0,
|
||||
"qaCount" INTEGER NOT NULL DEFAULT 0,
|
||||
"rejectionCount" INTEGER NOT NULL DEFAULT 0,
|
||||
"createdBy" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMPTZ NOT NULL,
|
||||
|
||||
CONSTRAINT "corporate_tasks_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "corporate_events" (
|
||||
"id" UUID NOT NULL,
|
||||
"taskId" UUID NOT NULL,
|
||||
"speaker" TEXT NOT NULL,
|
||||
"speakerName" TEXT NOT NULL,
|
||||
"step" TEXT NOT NULL,
|
||||
"content" TEXT NOT NULL,
|
||||
"payload" JSONB,
|
||||
"timestamp" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "corporate_events_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "corporate_evidence" (
|
||||
"id" UUID NOT NULL,
|
||||
"taskId" UUID NOT NULL,
|
||||
"claimToken" UUID NOT NULL,
|
||||
"executor" TEXT NOT NULL,
|
||||
"artifactUri" TEXT NOT NULL,
|
||||
"sha256" TEXT NOT NULL,
|
||||
"summary" TEXT NOT NULL,
|
||||
"tool" TEXT NOT NULL,
|
||||
"result" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "corporate_evidence_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "corporate_reviews" (
|
||||
"id" UUID NOT NULL,
|
||||
"taskId" UUID NOT NULL,
|
||||
"evidenceId" UUID NOT NULL,
|
||||
"reviewer" TEXT NOT NULL,
|
||||
"passed" BOOLEAN NOT NULL,
|
||||
"findings" TEXT NOT NULL,
|
||||
"verification" JSONB NOT NULL,
|
||||
"createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "corporate_reviews_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "corporate_research" (
|
||||
"id" UUID NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"category" TEXT NOT NULL,
|
||||
"source" TEXT NOT NULL,
|
||||
"opportunity" TEXT NOT NULL,
|
||||
"impact" TEXT NOT NULL,
|
||||
"recommendedAction" TEXT NOT NULL,
|
||||
"status" TEXT NOT NULL DEFAULT 'DISCOVERED',
|
||||
"cadence" TEXT NOT NULL,
|
||||
"provenance" JSONB NOT NULL,
|
||||
"createdBy" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "corporate_research_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "corporate_sources" (
|
||||
"id" UUID NOT NULL,
|
||||
"researchId" UUID NOT NULL,
|
||||
"url" TEXT NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"excerpt" TEXT NOT NULL,
|
||||
"retrievedAt" TIMESTAMPTZ NOT NULL,
|
||||
"sha256" TEXT NOT NULL,
|
||||
|
||||
CONSTRAINT "corporate_sources_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "corporate_roadmaps" (
|
||||
"id" UUID NOT NULL,
|
||||
"researchId" UUID NOT NULL,
|
||||
"cycleName" TEXT NOT NULL,
|
||||
"month" TEXT NOT NULL,
|
||||
"seasonalTheme" TEXT NOT NULL,
|
||||
"strategicGoals" TEXT[],
|
||||
"plannedArticlesCount" INTEGER NOT NULL,
|
||||
"plannedRefreshesCount" INTEGER NOT NULL,
|
||||
"plannedCatalogEnrichments" INTEGER NOT NULL,
|
||||
"isActive" BOOLEAN NOT NULL DEFAULT false,
|
||||
"createdBy" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "corporate_roadmaps_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "corporate_goals" (
|
||||
"id" UUID NOT NULL,
|
||||
"roadmapId" UUID NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"department" TEXT NOT NULL,
|
||||
"acceptanceCriteria" TEXT NOT NULL,
|
||||
"metric" TEXT NOT NULL,
|
||||
"target" DOUBLE PRECISION,
|
||||
"createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "corporate_goals_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "corporate_effects" (
|
||||
"id" UUID NOT NULL,
|
||||
"taskId" UUID NOT NULL,
|
||||
"metric" TEXT NOT NULL,
|
||||
"availability" TEXT NOT NULL,
|
||||
"baseline" DOUBLE PRECISION,
|
||||
"observed" DOUBLE PRECISION,
|
||||
"source" TEXT NOT NULL,
|
||||
"observedAt" TIMESTAMPTZ NOT NULL,
|
||||
"recordedBy" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "corporate_effects_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "corporate_reports" (
|
||||
"id" UUID NOT NULL,
|
||||
"day" TEXT NOT NULL,
|
||||
"summary" TEXT NOT NULL,
|
||||
"snapshot" JSONB NOT NULL,
|
||||
"createdBy" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "corporate_reports_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "corporate_operations" (
|
||||
"key" TEXT NOT NULL,
|
||||
"payloadHash" TEXT NOT NULL,
|
||||
"response" JSONB NOT NULL,
|
||||
"createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "corporate_operations_pkey" PRIMARY KEY ("key")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "corporate_tasks_taskCode_key" ON "corporate_tasks"("taskCode");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "corporate_tasks_status_priority_updatedAt_idx" ON "corporate_tasks"("status", "priority", "updatedAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "corporate_tasks_parentId_idx" ON "corporate_tasks"("parentId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "corporate_tasks_goalId_idx" ON "corporate_tasks"("goalId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "corporate_events_taskId_timestamp_idx" ON "corporate_events"("taskId", "timestamp");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "corporate_evidence_taskId_idx" ON "corporate_evidence"("taskId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "corporate_reviews_taskId_idx" ON "corporate_reviews"("taskId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "corporate_sources_researchId_idx" ON "corporate_sources"("researchId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "corporate_roadmaps_month_idx" ON "corporate_roadmaps"("month");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "corporate_goals_roadmapId_idx" ON "corporate_goals"("roadmapId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "corporate_effects_taskId_idx" ON "corporate_effects"("taskId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "corporate_reports_day_key" ON "corporate_reports"("day");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "corporate_tasks" ADD CONSTRAINT "corporate_tasks_parentId_fkey" FOREIGN KEY ("parentId") REFERENCES "corporate_tasks"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "corporate_tasks" ADD CONSTRAINT "corporate_tasks_goalId_fkey" FOREIGN KEY ("goalId") REFERENCES "corporate_goals"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "corporate_events" ADD CONSTRAINT "corporate_events_taskId_fkey" FOREIGN KEY ("taskId") REFERENCES "corporate_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "corporate_evidence" ADD CONSTRAINT "corporate_evidence_taskId_fkey" FOREIGN KEY ("taskId") REFERENCES "corporate_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "corporate_reviews" ADD CONSTRAINT "corporate_reviews_taskId_fkey" FOREIGN KEY ("taskId") REFERENCES "corporate_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "corporate_reviews" ADD CONSTRAINT "corporate_reviews_evidenceId_fkey" FOREIGN KEY ("evidenceId") REFERENCES "corporate_evidence"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "corporate_sources" ADD CONSTRAINT "corporate_sources_researchId_fkey" FOREIGN KEY ("researchId") REFERENCES "corporate_research"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "corporate_roadmaps" ADD CONSTRAINT "corporate_roadmaps_researchId_fkey" FOREIGN KEY ("researchId") REFERENCES "corporate_research"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "corporate_goals" ADD CONSTRAINT "corporate_goals_roadmapId_fkey" FOREIGN KEY ("roadmapId") REFERENCES "corporate_roadmaps"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "corporate_effects" ADD CONSTRAINT "corporate_effects_taskId_fkey" FOREIGN KEY ("taskId") REFERENCES "corporate_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
@@ -1,22 +0,0 @@
|
||||
-- Reviewed attribution-only storage; no business data or historical ledger writes.
|
||||
DO $$ BEGIN
|
||||
IF current_database() NOT IN ('caninodb_stage', 'rehearsal') THEN
|
||||
RAISE EXCEPTION 'public author bootstrap is Stage-only';
|
||||
END IF;
|
||||
END $$;
|
||||
ALTER TABLE public.users ADD COLUMN IF NOT EXISTS is_public_author BOOLEAN NOT NULL DEFAULT false;
|
||||
ALTER TABLE public.users ALTER COLUMN is_public_author SET NOT NULL;
|
||||
ALTER TABLE public.users ALTER COLUMN is_public_author SET DEFAULT false;
|
||||
ALTER TABLE public.users ALTER COLUMN mobile DROP NOT NULL;
|
||||
-- Repeated application is transactional and revalidates every existing row.
|
||||
ALTER TABLE public.users DROP CONSTRAINT IF EXISTS users_public_author_identity_check;
|
||||
ALTER TABLE public.users ADD CONSTRAINT users_public_author_identity_check CHECK (
|
||||
(is_public_author = false AND mobile IS NOT NULL)
|
||||
OR
|
||||
(is_public_author = true
|
||||
AND mobile IS NULL AND email IS NULL AND password IS NULL
|
||||
AND role = 'User_PetOwner'
|
||||
AND auth_expires_at IS NULL
|
||||
AND stage_test_generation IS NULL AND stage_test_session IS NULL
|
||||
AND wallet_balance = 0 AND charity_donation_total = 0)
|
||||
);
|
||||
+206
-272
@@ -1,202 +1,3 @@
|
||||
enum CorporateTaskStatus {
|
||||
TODO
|
||||
IN_PROGRESS
|
||||
TEST
|
||||
DONE
|
||||
BLOCKED
|
||||
REJECTED
|
||||
CANCELLED
|
||||
}
|
||||
|
||||
enum CorporatePriority {
|
||||
CEO_EXPEDITE
|
||||
CRITICAL
|
||||
HIGH
|
||||
MEDIUM
|
||||
LOW
|
||||
}
|
||||
|
||||
model CorporateTask {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
taskCode String @unique
|
||||
title String
|
||||
normalizedTitle String
|
||||
normalizedCode String
|
||||
description String
|
||||
department String
|
||||
priority CorporatePriority @default(CEO_EXPEDITE)
|
||||
status CorporateTaskStatus @default(TODO)
|
||||
actionType String @default("CEO_DIRECTIVE")
|
||||
dueCycle String?
|
||||
parentId String? @db.Uuid
|
||||
parent CorporateTask? @relation("TaskChildren", fields: [parentId], references: [id])
|
||||
children CorporateTask[] @relation("TaskChildren")
|
||||
goalId String? @db.Uuid
|
||||
goal CorporateGoal? @relation(fields: [goalId], references: [id])
|
||||
assignedAgent String?
|
||||
claimToken String? @db.Uuid
|
||||
leasedUntil DateTime? @db.Timestamptz()
|
||||
executionCount Int @default(0)
|
||||
qaCount Int @default(0)
|
||||
rejectionCount Int @default(0)
|
||||
createdBy String
|
||||
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||
updatedAt DateTime @updatedAt @db.Timestamptz()
|
||||
logs CorporateEvent[]
|
||||
evidence CorporateEvidence[]
|
||||
reviews CorporateReview[]
|
||||
effects CorporateEffect[]
|
||||
@@index([status, priority, updatedAt])
|
||||
@@index([parentId])
|
||||
@@index([goalId])
|
||||
@@map("corporate_tasks")
|
||||
}
|
||||
|
||||
model CorporateEvent {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
taskId String @db.Uuid
|
||||
task CorporateTask @relation(fields: [taskId], references: [id])
|
||||
speaker String
|
||||
speakerName String
|
||||
step String
|
||||
content String
|
||||
payload Json?
|
||||
timestamp DateTime @default(now()) @db.Timestamptz()
|
||||
@@index([taskId, timestamp])
|
||||
@@map("corporate_events")
|
||||
}
|
||||
|
||||
model CorporateEvidence {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
taskId String @db.Uuid
|
||||
task CorporateTask @relation(fields: [taskId], references: [id])
|
||||
claimToken String @db.Uuid
|
||||
executor String
|
||||
artifactUri String
|
||||
sha256 String
|
||||
summary String
|
||||
tool String
|
||||
result String
|
||||
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||
reviews CorporateReview[]
|
||||
@@index([taskId])
|
||||
@@map("corporate_evidence")
|
||||
}
|
||||
|
||||
model CorporateReview {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
taskId String @db.Uuid
|
||||
task CorporateTask @relation(fields: [taskId], references: [id])
|
||||
evidenceId String @db.Uuid
|
||||
evidence CorporateEvidence @relation(fields: [evidenceId], references: [id])
|
||||
reviewer String
|
||||
passed Boolean
|
||||
findings String
|
||||
verification Json
|
||||
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||
@@index([taskId])
|
||||
@@map("corporate_reviews")
|
||||
}
|
||||
|
||||
model CorporateResearch {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
title String
|
||||
category String
|
||||
source String
|
||||
opportunity String
|
||||
impact String
|
||||
recommendedAction String
|
||||
status String @default("DISCOVERED")
|
||||
cadence String
|
||||
provenance Json
|
||||
createdBy String
|
||||
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||
sources CorporateSource[]
|
||||
roadmaps CorporateRoadmap[]
|
||||
@@map("corporate_research")
|
||||
}
|
||||
|
||||
model CorporateSource {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
researchId String @db.Uuid
|
||||
research CorporateResearch @relation(fields: [researchId], references: [id])
|
||||
url String
|
||||
title String
|
||||
excerpt String
|
||||
retrievedAt DateTime @db.Timestamptz()
|
||||
sha256 String
|
||||
@@index([researchId])
|
||||
@@map("corporate_sources")
|
||||
}
|
||||
|
||||
model CorporateRoadmap {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
researchId String @db.Uuid
|
||||
research CorporateResearch @relation(fields: [researchId], references: [id])
|
||||
cycleName String
|
||||
month String
|
||||
seasonalTheme String
|
||||
strategicGoals String[]
|
||||
plannedArticlesCount Int
|
||||
plannedRefreshesCount Int
|
||||
plannedCatalogEnrichments Int
|
||||
isActive Boolean @default(false)
|
||||
createdBy String
|
||||
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||
goals CorporateGoal[]
|
||||
@@index([month])
|
||||
@@map("corporate_roadmaps")
|
||||
}
|
||||
|
||||
model CorporateGoal {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
roadmapId String @db.Uuid
|
||||
roadmap CorporateRoadmap @relation(fields: [roadmapId], references: [id])
|
||||
title String
|
||||
department String
|
||||
acceptanceCriteria String
|
||||
metric String
|
||||
target Float?
|
||||
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||
tasks CorporateTask[]
|
||||
@@index([roadmapId])
|
||||
@@map("corporate_goals")
|
||||
}
|
||||
|
||||
model CorporateEffect {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
taskId String @db.Uuid
|
||||
task CorporateTask @relation(fields: [taskId], references: [id])
|
||||
metric String
|
||||
availability String
|
||||
baseline Float?
|
||||
observed Float?
|
||||
source String
|
||||
observedAt DateTime @db.Timestamptz()
|
||||
recordedBy String
|
||||
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||
@@index([taskId])
|
||||
@@map("corporate_effects")
|
||||
}
|
||||
|
||||
model CorporateReport {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
day String @unique
|
||||
summary String
|
||||
snapshot Json
|
||||
createdBy String
|
||||
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||
@@map("corporate_reports")
|
||||
}
|
||||
|
||||
model CorporateOperation {
|
||||
key String @id
|
||||
payloadHash String
|
||||
response Json
|
||||
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||
@@map("corporate_operations")
|
||||
}
|
||||
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
binaryTargets = ["native", "linux-musl-openssl-3.0.x"]
|
||||
@@ -212,13 +13,9 @@ model User {
|
||||
firstName String @map("first_name") @db.VarChar(100)
|
||||
lastName String @map("last_name") @db.VarChar(100)
|
||||
email String? @unique @db.VarChar(150)
|
||||
mobile String? @unique @db.VarChar(15)
|
||||
isPublicAuthor Boolean @default(false) @map("is_public_author")
|
||||
mobile String @unique @db.VarChar(15)
|
||||
password String? @db.VarChar(255)
|
||||
role String @default("User_PetOwner") @db.VarChar(30)
|
||||
authExpiresAt DateTime? @map("auth_expires_at") @db.Timestamptz()
|
||||
stageTestGeneration String? @map("stage_test_generation") @db.Uuid
|
||||
stageTestSession String? @map("stage_test_session") @db.VarChar(64)
|
||||
walletBalance Decimal @default(0.00) @map("wallet_balance") @db.Decimal(15, 2)
|
||||
charityDonationTotal Decimal @default(0.00) @map("charity_donation_total") @db.Decimal(15, 2)
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
@@ -419,7 +216,6 @@ model Blog {
|
||||
category BlogCategory? @relation(fields: [categoryId], references: [id], onDelete: SetNull)
|
||||
tags BlogTag[]
|
||||
comments BlogComment[]
|
||||
researchFinding ContentResearchFinding?
|
||||
|
||||
@@index([categoryId])
|
||||
@@index([status])
|
||||
@@ -1222,79 +1018,217 @@ model SmsCampaign {
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// 5. SEO & Performance Tracking Models
|
||||
// 5. ApprovalRequest (CEO Governance & Decision Gate)
|
||||
// ------------------------------------------------------------------------------
|
||||
enum ResearchFindingStatus {
|
||||
RESEARCHED
|
||||
ACTIONED
|
||||
EVALUATING
|
||||
SCALED
|
||||
PRUNED
|
||||
}
|
||||
|
||||
model ContentResearchFinding {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
title String @db.VarChar(255)
|
||||
hypothesis String @db.Text
|
||||
targetKeywords String[] @map("target_keywords")
|
||||
primaryKeyword String @map("primary_keyword") @db.VarChar(128)
|
||||
expectedOutcome String @map("expected_outcome") @db.Text
|
||||
status ResearchFindingStatus @default(RESEARCHED)
|
||||
version Int @default(0)
|
||||
feedbackVersion Int @default(0) @map("feedback_version")
|
||||
searchText String @default("") @map("search_text") @db.Text
|
||||
goalMetric String? @map("goal_metric")
|
||||
goalTarget Float? @map("goal_target")
|
||||
// External action reference only; no orchestration relation or foreign key.
|
||||
actionId String? @map("action_id")
|
||||
|
||||
blogId String? @unique @map("blog_id") @db.Uuid
|
||||
blog Blog? @relation(fields: [blogId], references: [id], onDelete: SetNull)
|
||||
|
||||
ceoFeedback String? @map("ceo_feedback") @db.Text
|
||||
feedbackSubmittedAt DateTime? @map("feedback_submitted_at") @db.Timestamptz()
|
||||
|
||||
snapshots ContentPerformanceSnapshot[]
|
||||
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz()
|
||||
model ApprovalRequest {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
department String @db.VarChar(50)
|
||||
category String @db.VarChar(50)
|
||||
title String @db.VarChar(255)
|
||||
payload Json @db.JsonB
|
||||
testContext Json? @map("test_context") @db.JsonB
|
||||
status String @default("PENDING") @db.VarChar(30)
|
||||
ceoNotes String? @map("ceo_notes") @db.Text
|
||||
executedAt DateTime? @map("executed_at") @db.Timestamptz()
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
|
||||
|
||||
@@index([department])
|
||||
@@index([category])
|
||||
@@index([status])
|
||||
@@index([primaryKeyword])
|
||||
@@map("content_research_findings")
|
||||
@@index([createdAt])
|
||||
@@map("approval_requests")
|
||||
}
|
||||
|
||||
model ContentPerformanceSnapshot {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
findingId String @map("finding_id") @db.Uuid
|
||||
finding ContentResearchFinding @relation(fields: [findingId], references: [id], onDelete: Cascade)
|
||||
|
||||
snapshotDate DateTime @default(now()) @map("snapshot_date") @db.Timestamptz()
|
||||
// ------------------------------------------------------------------------------
|
||||
// 6. AuditLog (System & Database Changes History)
|
||||
// ------------------------------------------------------------------------------
|
||||
model AuditLog {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
entity String @db.VarChar(50) // e.g. product, blog, order, approval, settings
|
||||
entityId String? @map("entity_id") @db.VarChar(100)
|
||||
action String @db.VarChar(50) // CREATE, UPDATE, DELETE, EXECUTE, APPROVE, REJECT
|
||||
department String? @db.VarChar(50) // devops, seo, content, vet, commerce, pmo
|
||||
actor String @default("SYSTEM") @db.VarChar(100)
|
||||
summary String @db.VarChar(255)
|
||||
oldValues Json? @map("old_values") @db.JsonB
|
||||
newValues Json? @map("new_values") @db.JsonB
|
||||
metadata Json? @db.JsonB
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
|
||||
periodStart DateTime? @map("period_start") @db.Timestamptz()
|
||||
periodEnd DateTime? @map("period_end") @db.Timestamptz()
|
||||
sourceMetadata Json? @map("source_metadata")
|
||||
ingestionKey String? @map("ingestion_key")
|
||||
|
||||
gscImpressions Int? @map("gsc_impressions")
|
||||
gscClicks Int? @map("gsc_clicks")
|
||||
gscPosition Float? @map("gsc_position")
|
||||
|
||||
ga4ActiveUsers Int? @map("ga4_active_users")
|
||||
ga4AvgEngagementSec Float? @map("ga4_avg_engagement_sec")
|
||||
ga4BounceRate Float? @map("ga4_bounce_rate")
|
||||
ga4ScrollDepthRate Float? @map("ga4_scroll_depth_rate")
|
||||
|
||||
attributedOrdersCount Int? @map("attributed_orders_count")
|
||||
attributedSalesValue Decimal? @map("attributed_sales_value") @db.Decimal(15, 2)
|
||||
|
||||
actionRecommendation String? @map("action_recommendation") @db.VarChar(64)
|
||||
analysisNotes String? @map("analysis_notes") @db.Text
|
||||
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
|
||||
@@index([findingId, snapshotDate])
|
||||
@@unique([findingId, ingestionKey])
|
||||
@@map("content_performance_snapshots")
|
||||
@@index([entity])
|
||||
@@index([action])
|
||||
@@index([department])
|
||||
@@index([createdAt])
|
||||
@@map("audit_logs")
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// 7. DepartmentTask (Autonomous Corporate Task & Kanban Manager)
|
||||
// ------------------------------------------------------------------------------
|
||||
model DepartmentTask {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
code String @unique @db.VarChar(50)
|
||||
department String @db.VarChar(50) // devops, seo, content, vet, commerce, pmo
|
||||
title String @db.VarChar(255)
|
||||
description String? @db.Text
|
||||
status String @default("BACKLOG") @db.VarChar(30) // BACKLOG, IN_PROGRESS, IN_REVIEW, APPROVED, DEPLOYING, DONE
|
||||
priority String @default("MEDIUM") @db.VarChar(20) // LOW, MEDIUM, HIGH, CRITICAL
|
||||
assignee String? @db.VarChar(100)
|
||||
acceptanceCriteria Json? @map("acceptance_criteria") @db.JsonB
|
||||
executionLogs Json? @map("execution_logs") @db.JsonB
|
||||
deliverableUrl String? @map("deliverable_url") @db.VarChar(255)
|
||||
approvalId String? @map("approval_id") @db.Uuid
|
||||
startedAt DateTime? @map("started_at") @db.Timestamptz()
|
||||
completedAt DateTime? @map("completed_at") @db.Timestamptz()
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
|
||||
|
||||
@@index([department])
|
||||
@@index([status])
|
||||
@@index([priority])
|
||||
@@index([createdAt])
|
||||
@@map("department_tasks")
|
||||
}
|
||||
|
||||
// Orchestration v4 additive models. Legacy governance tables remain untouched.
|
||||
model OrchestrationTask {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
key String @unique @db.VarChar(120)
|
||||
title String @db.VarChar(255)
|
||||
department String @db.VarChar(50)
|
||||
state String @default("DRAFT") @db.VarChar(40)
|
||||
operationMode String @map("operation_mode") @db.VarChar(30)
|
||||
modelTier String? @map("model_tier") @db.VarChar(2)
|
||||
budgetLimitCents Int @map("budget_limit_cents")
|
||||
version Int @default(1)
|
||||
metadata Json @default("{}") @db.JsonB
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz()
|
||||
runs OrchestrationRun[]
|
||||
dependencies OrchestrationDependency[] @relation("task_dependencies")
|
||||
dependedOnBy OrchestrationDependency[] @relation("task_dependents")
|
||||
decisions OrchestrationApprovalDecision[]
|
||||
events OrchestrationEvent[]
|
||||
budgetLedger OrchestrationBudgetLedger[]
|
||||
@@index([state, createdAt])
|
||||
@@index([department, state])
|
||||
@@map("orchestration_tasks")
|
||||
}
|
||||
model OrchestrationRun {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
taskId String @map("task_id") @db.Uuid
|
||||
attempt Int @default(1)
|
||||
status String @default("PENDING") @db.VarChar(30)
|
||||
commitSha String @map("commit_sha") @db.VarChar(64)
|
||||
environment String @db.VarChar(50)
|
||||
retryClass String? @map("retry_class") @db.VarChar(30)
|
||||
idempotencyKey String @unique @map("idempotency_key") @db.VarChar(150)
|
||||
startedAt DateTime? @map("started_at") @db.Timestamptz()
|
||||
finishedAt DateTime? @map("finished_at") @db.Timestamptz()
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
task OrchestrationTask @relation(fields:[taskId],references:[id],onDelete:Restrict)
|
||||
artifacts OrchestrationArtifact[]
|
||||
attestations OrchestrationAttestation[]
|
||||
approvals OrchestrationApprovalDecision[]
|
||||
@@unique([taskId, attempt])
|
||||
@@index([taskId, status])
|
||||
@@map("orchestration_runs")
|
||||
}
|
||||
model OrchestrationArtifact {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
runId String @map("run_id") @db.Uuid
|
||||
kind String @db.VarChar(50)
|
||||
uri String @db.Text
|
||||
sha256 String @db.Char(64)
|
||||
sizeBytes BigInt? @map("size_bytes")
|
||||
metadata Json @default("{}") @db.JsonB
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
run OrchestrationRun @relation(fields:[runId],references:[id],onDelete:Restrict)
|
||||
@@unique([runId, sha256])
|
||||
@@map("orchestration_artifacts")
|
||||
}
|
||||
model OrchestrationAttestation {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
runId String @map("run_id") @db.Uuid
|
||||
kind String @db.VarChar(50)
|
||||
subjectHash String @map("subject_hash") @db.Char(64)
|
||||
predicate Json @db.JsonB
|
||||
signer String @db.VarChar(150)
|
||||
signature String? @db.Text
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
run OrchestrationRun @relation(fields:[runId],references:[id],onDelete:Restrict)
|
||||
@@unique([runId, kind, subjectHash, signer])
|
||||
@@map("orchestration_attestations")
|
||||
}
|
||||
model OrchestrationDependency {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
taskId String @map("task_id") @db.Uuid
|
||||
dependsOnTaskId String @map("depends_on_task_id") @db.Uuid
|
||||
kind String @default("BLOCKS") @db.VarChar(30)
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
task OrchestrationTask @relation("task_dependencies",fields:[taskId],references:[id],onDelete:Restrict)
|
||||
dependsOnTask OrchestrationTask @relation("task_dependents",fields:[dependsOnTaskId],references:[id],onDelete:Restrict)
|
||||
@@unique([taskId, dependsOnTaskId])
|
||||
@@map("orchestration_dependencies")
|
||||
}
|
||||
model OrchestrationApprovalDecision {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
taskId String @map("task_id") @db.Uuid
|
||||
gate Int
|
||||
decision String @db.VarChar(20)
|
||||
actorId String @map("actor_id") @db.VarChar(100)
|
||||
notes String? @db.Text
|
||||
expiresAt DateTime @map("expires_at") @db.Timestamptz()
|
||||
idempotencyKey String @unique @map("idempotency_key") @db.VarChar(150)
|
||||
runId String? @map("run_id") @db.Uuid
|
||||
artifactHash String? @map("artifact_hash") @db.Char(64)
|
||||
commitSha String? @map("commit_sha") @db.VarChar(64)
|
||||
environment String? @db.VarChar(50)
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
task OrchestrationTask @relation(fields:[taskId],references:[id],onDelete:Restrict)
|
||||
run OrchestrationRun? @relation(fields:[runId],references:[id],onDelete:Restrict)
|
||||
@@index([taskId, gate, createdAt])
|
||||
@@map("orchestration_approval_decisions")
|
||||
}
|
||||
model OrchestrationEvent {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
taskId String? @map("task_id") @db.Uuid
|
||||
eventType String @map("event_type") @db.VarChar(60)
|
||||
fromState String? @map("from_state") @db.VarChar(40)
|
||||
toState String? @map("to_state") @db.VarChar(40)
|
||||
sequence Int
|
||||
actorId String @map("actor_id") @db.VarChar(100)
|
||||
idempotencyKey String? @unique @map("idempotency_key") @db.VarChar(150)
|
||||
payload Json @default("{}") @db.JsonB
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
task OrchestrationTask? @relation(fields:[taskId],references:[id],onDelete:Restrict)
|
||||
@@unique([taskId, sequence])
|
||||
@@index([eventType, createdAt])
|
||||
@@map("orchestration_events")
|
||||
}
|
||||
model OrchestrationBudgetLedger {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
taskId String @map("task_id") @db.Uuid
|
||||
amountCents Int @map("amount_cents")
|
||||
kind String @db.VarChar(40)
|
||||
idempotencyKey String @unique @map("idempotency_key") @db.VarChar(150)
|
||||
actorId String @map("actor_id") @db.VarChar(100)
|
||||
metadata Json @default("{}") @db.JsonB
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
task OrchestrationTask @relation(fields:[taskId],references:[id],onDelete:Restrict)
|
||||
@@index([taskId, createdAt])
|
||||
@@map("orchestration_budget_ledger")
|
||||
}
|
||||
model OrchestrationKillSwitch {
|
||||
scope String @id @db.VarChar(80)
|
||||
level String @db.VarChar(30)
|
||||
active Boolean @default(true)
|
||||
reason String @db.Text
|
||||
actorId String @map("actor_id") @db.VarChar(100)
|
||||
version Int @default(1)
|
||||
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz()
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
@@map("orchestration_kill_switches")
|
||||
}
|
||||
@@ -1,114 +0,0 @@
|
||||
#!/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,7 +0,0 @@
|
||||
npm notice run backend@0.0.1 test
|
||||
npm notice run jest --runInBand api-keys.integration.spec
|
||||
Test Suites: 1 passed, 1 total
|
||||
Tests: 5 passed, 5 total
|
||||
Snapshots: 0 total
|
||||
Time: 4.044 s
|
||||
Ran all test suites matching api-keys.integration.spec.
|
||||
@@ -1,104 +0,0 @@
|
||||
npm notice run backend@0.0.1 test
|
||||
npm notice run jest --runInBand api-keys.integration.spec
|
||||
FAIL src/admin/api-keys.integration.spec.ts
|
||||
● human-only key administration / real key authentication and PostgreSQL › denies get to authenticated admin API key without mutating keys
|
||||
|
||||
expected 403 "Forbidden", got 200 "OK"
|
||||
|
||||
34 | const before = await db.apiKey.count();
|
||||
35 | const path = '/admin/api-keys' + (method === 'patch' ? `/${target}/toggle` : method === 'delete' ? `/${target}` : '');
|
||||
> 36 | await request(app.getHttpServer())[method](path).set('x-api-key', rawKey).send(method === 'post' ? { name: 'security-fixture-forged-reviewer', scopes: ['admin'] } : {}).expect(403);
|
||||
| ^
|
||||
37 | expect(await db.apiKey.count()).toBe(before);
|
||||
38 | expect((await db.apiKey.findUniqueOrThrow({ where: { id: target } })).status).toBe('ACTIVE');
|
||||
39 | });
|
||||
|
||||
at admin/api-keys.integration.spec.ts:36:174
|
||||
----
|
||||
at Test._assertStatus (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:309:14)
|
||||
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:365:13
|
||||
at Test._assertFunction (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:342:13)
|
||||
at Test.assert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:195:23)
|
||||
at localAssert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:138:14)
|
||||
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:156:7
|
||||
at Test.fn [as callback] (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:892:12)
|
||||
at callback (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:1183:18)
|
||||
at IncomingMessage.fn (../../../corporate-backend/backend/node_modules/superagent/src/node/parsers/json.js:19:7)
|
||||
|
||||
● human-only key administration / real key authentication and PostgreSQL › denies post to authenticated admin API key without mutating keys
|
||||
|
||||
expected 403 "Forbidden", got 201 "Created"
|
||||
|
||||
34 | const before = await db.apiKey.count();
|
||||
35 | const path = '/admin/api-keys' + (method === 'patch' ? `/${target}/toggle` : method === 'delete' ? `/${target}` : '');
|
||||
> 36 | await request(app.getHttpServer())[method](path).set('x-api-key', rawKey).send(method === 'post' ? { name: 'security-fixture-forged-reviewer', scopes: ['admin'] } : {}).expect(403);
|
||||
| ^
|
||||
37 | expect(await db.apiKey.count()).toBe(before);
|
||||
38 | expect((await db.apiKey.findUniqueOrThrow({ where: { id: target } })).status).toBe('ACTIVE');
|
||||
39 | });
|
||||
|
||||
at admin/api-keys.integration.spec.ts:36:174
|
||||
----
|
||||
at Test._assertStatus (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:309:14)
|
||||
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:365:13
|
||||
at Test._assertFunction (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:342:13)
|
||||
at Test.assert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:195:23)
|
||||
at localAssert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:138:14)
|
||||
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:156:7
|
||||
at Test.fn [as callback] (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:892:12)
|
||||
at callback (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:1183:18)
|
||||
at IncomingMessage.fn (../../../corporate-backend/backend/node_modules/superagent/src/node/parsers/json.js:19:7)
|
||||
|
||||
● human-only key administration / real key authentication and PostgreSQL › denies patch to authenticated admin API key without mutating keys
|
||||
|
||||
expected 403 "Forbidden", got 200 "OK"
|
||||
|
||||
34 | const before = await db.apiKey.count();
|
||||
35 | const path = '/admin/api-keys' + (method === 'patch' ? `/${target}/toggle` : method === 'delete' ? `/${target}` : '');
|
||||
> 36 | await request(app.getHttpServer())[method](path).set('x-api-key', rawKey).send(method === 'post' ? { name: 'security-fixture-forged-reviewer', scopes: ['admin'] } : {}).expect(403);
|
||||
| ^
|
||||
37 | expect(await db.apiKey.count()).toBe(before);
|
||||
38 | expect((await db.apiKey.findUniqueOrThrow({ where: { id: target } })).status).toBe('ACTIVE');
|
||||
39 | });
|
||||
|
||||
at admin/api-keys.integration.spec.ts:36:174
|
||||
----
|
||||
at Test._assertStatus (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:309:14)
|
||||
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:365:13
|
||||
at Test._assertFunction (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:342:13)
|
||||
at Test.assert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:195:23)
|
||||
at localAssert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:138:14)
|
||||
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:156:7
|
||||
at Test.fn [as callback] (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:892:12)
|
||||
at callback (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:1183:18)
|
||||
at IncomingMessage.fn (../../../corporate-backend/backend/node_modules/superagent/src/node/parsers/json.js:19:7)
|
||||
|
||||
● human-only key administration / real key authentication and PostgreSQL › denies delete to authenticated admin API key without mutating keys
|
||||
|
||||
expected 403 "Forbidden", got 200 "OK"
|
||||
|
||||
34 | const before = await db.apiKey.count();
|
||||
35 | const path = '/admin/api-keys' + (method === 'patch' ? `/${target}/toggle` : method === 'delete' ? `/${target}` : '');
|
||||
> 36 | await request(app.getHttpServer())[method](path).set('x-api-key', rawKey).send(method === 'post' ? { name: 'security-fixture-forged-reviewer', scopes: ['admin'] } : {}).expect(403);
|
||||
| ^
|
||||
37 | expect(await db.apiKey.count()).toBe(before);
|
||||
38 | expect((await db.apiKey.findUniqueOrThrow({ where: { id: target } })).status).toBe('ACTIVE');
|
||||
39 | });
|
||||
|
||||
at admin/api-keys.integration.spec.ts:36:174
|
||||
----
|
||||
at Test._assertStatus (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:309:14)
|
||||
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:365:13
|
||||
at Test._assertFunction (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:342:13)
|
||||
at Test.assert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:195:23)
|
||||
at localAssert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:138:14)
|
||||
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:156:7
|
||||
at Test.fn [as callback] (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:892:12)
|
||||
at callback (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:1183:18)
|
||||
at IncomingMessage.fn (../../../corporate-backend/backend/node_modules/superagent/src/node/parsers/json.js:19:7)
|
||||
|
||||
Test Suites: 1 failed, 1 total
|
||||
Tests: 4 failed, 1 passed, 5 total
|
||||
Snapshots: 0 total
|
||||
Time: 3.608 s
|
||||
Ran all test suites matching api-keys.integration.spec.
|
||||
@@ -1,207 +0,0 @@
|
||||
npm notice run backend@0.0.1 test
|
||||
npm notice run jest --runInBand
|
||||
[31m[Nest] 3987292 - [39m10/28/2026, 12:44:07 PM [31m ERROR[39m [38;5;3m[ZibalEBankService] [39m[31m[Zibal EBank API] Error requesting /ebank/v1/account/list/: transport failed[39m
|
||||
[31m[Nest] 3987292 - [39m10/28/2026, 12:44:07 PM [31m ERROR[39m [38;5;3m[ZibalEBankService] [39m[31m[Zibal EBank API] Error requesting /ebank/v1/account/list/: transport failed[39m
|
||||
[31m[Nest] 3987292 - [39m10/28/2026, 12:44:22 PM [31m ERROR[39m [38;5;3m[ZibalEBankService] [39m[31m[Zibal EBank API] Error requesting /ebank/v1/account/list/: aborted[39m
|
||||
[31m[Nest] 3987292 - [39m10/28/2026, 12:44:07 PM [31m ERROR[39m [38;5;3m[ZibalEBankService] [39m[31m[Zibal EBank API] Error requesting /ebank/v1/account/list/: Zibal EBank HTTP 503[39m
|
||||
[31m[Nest] 3987292 - [39m10/28/2026, 12:44:08 PM [31m ERROR[39m [38;5;3m[SslService] [39m[31mFailed to parse SSL certificate[39m
|
||||
[31m[Nest] 3987292 - [39m10/28/2026, 12:44:08 PM [31m ERROR[39m [38;5;3m[SslService] [39mError: error:0480006C:PEM routines::no start line
|
||||
[90m at new X509Certificate (node:internal/crypto/x509:121:21)[39m
|
||||
at SslService.getStatus [90m(/opt/data/cache/scratch/corporate-hardening-base/backend/[39msrc/admin/ssl.service.ts:104:20[90m)[39m
|
||||
at Object.<anonymous> [90m(/opt/data/cache/scratch/corporate-hardening-base/backend/[39msrc/admin/ssl.service.spec.ts:179:30[90m)[39m
|
||||
at Promise.finally.completed (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:1561:28)
|
||||
at new Promise (<anonymous>)
|
||||
at callAsyncCircusFn (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:1501:10)
|
||||
at _callCircusTest (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:1011:40)
|
||||
at _runTest (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:951:3)
|
||||
at /opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:853:7
|
||||
at _runTestsForDescribeBlock (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:866:11)
|
||||
at _runTestsForDescribeBlock (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:861:11)
|
||||
at _runTestsForDescribeBlock (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:861:11)
|
||||
at run (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:765:3)
|
||||
at runAndTransformResultsToJestFormat (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:1993:21)
|
||||
at jestAdapter (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/runner.js:111:19)
|
||||
at runTestInternal (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-runner[24m/build/index.js:276:16)
|
||||
at runTest (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-runner[24m/build/index.js:344:7) {
|
||||
library: [32m'PEM routines'[39m,
|
||||
reason: [32m'no start line'[39m,
|
||||
code: [32m'ERR_OSSL_PEM_NO_START_LINE'[39m
|
||||
}
|
||||
[31m[Nest] 3987292 - [39m10/28/2026, 12:44:12 PM [31m ERROR[39m [38;5;3m[PaymentService] [39m[31mSecurity Alert: Amount mismatch on trackId=tr-1! Zibal reported 1000000 Rials, but expected 5000000 Rials in DB.[39m
|
||||
FAIL src/seo-tracking/publication.postgres.spec.ts
|
||||
● Test suite failed to run
|
||||
|
||||
PrismaClientConstructorValidationError: Invalid value undefined for datasource "db" provided to PrismaClient constructor.
|
||||
It should have this form: { url: "CONNECTION_STRING" }
|
||||
Read more at https://pris.ly/d/client-constructor
|
||||
|
||||
20 | const deferred = () => { let resolve!: () => void; const promise = new Promise<void>(r => resolve = r); return { promise, resolve }; };
|
||||
21 | (url ? describe : describe.skip)('atomic publication: real PostgreSQL row ordering', () => {
|
||||
> 22 | const db = new PrismaClient({ datasources: { db: { url } } });
|
||||
| ^
|
||||
23 | let user: any;
|
||||
24 | const cache = { revalidateBlog: jest.fn(async () => false) };
|
||||
25 | const service = new SeoTrackingService(db as any, cache as any);
|
||||
|
||||
at Object.datasources (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:124:86)
|
||||
at Gl (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:126:2527)
|
||||
at new t (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:130:748)
|
||||
at seo-tracking/publication.postgres.spec.ts:22:14
|
||||
at Object.<anonymous> (seo-tracking/publication.postgres.spec.ts:21:33)
|
||||
|
||||
[33m[Nest] 3987292 - [39m10/28/2026, 12:44:18 PM [33m WARN[39m [38;5;3m[BlogsService] [39m[33mCache revalidation failed for updated blog [post]: cache down[39m
|
||||
FAIL src/wiki/wiki.service.spec.ts
|
||||
● WikiService › findAll › should paginate and filter terms with fallback to default sortBy
|
||||
|
||||
expect(jest.fn()).toHaveBeenCalledWith(...expected)
|
||||
|
||||
- Expected
|
||||
+ Received
|
||||
|
||||
@@ -1,21 +1,39 @@
|
||||
Object {
|
||||
"orderBy": Object {
|
||||
"term": "desc",
|
||||
},
|
||||
- "skip": 0,
|
||||
- "take": 10,
|
||||
+ "skip": undefined,
|
||||
+ "take": 100,
|
||||
"where": Object {
|
||||
"OR": Array [
|
||||
Object {
|
||||
"term": Object {
|
||||
"contains": "مفصل",
|
||||
"mode": "insensitive",
|
||||
},
|
||||
},
|
||||
Object {
|
||||
+ "key": Object {
|
||||
+ "contains": "مفصل",
|
||||
+ "mode": "insensitive",
|
||||
+ },
|
||||
+ },
|
||||
+ Object {
|
||||
"definition": Object {
|
||||
+ "contains": "مفصل",
|
||||
+ "mode": "insensitive",
|
||||
+ },
|
||||
+ },
|
||||
+ Object {
|
||||
+ "term": Object {
|
||||
+ "contains": "مفصل",
|
||||
+ "mode": "insensitive",
|
||||
+ },
|
||||
+ },
|
||||
+ Object {
|
||||
+ "key": Object {
|
||||
"contains": "مفصل",
|
||||
"mode": "insensitive",
|
||||
},
|
||||
},
|
||||
],,
|
||||
|
||||
Number of calls: 1
|
||||
|
||||
56 | });
|
||||
57 |
|
||||
> 58 | expect(mockPrisma.scientificTerm.findMany).toHaveBeenCalledWith({
|
||||
| ^
|
||||
59 | where: {
|
||||
60 | OR: [
|
||||
61 | { term: { contains: "مفصل", mode: "insensitive" } },
|
||||
|
||||
at Object.<anonymous> (wiki/wiki.service.spec.ts:58:50)
|
||||
|
||||
|
||||
Summary of all failing tests
|
||||
FAIL seo-tracking/publication.postgres.spec.ts
|
||||
● Test suite failed to run
|
||||
|
||||
PrismaClientConstructorValidationError: Invalid value undefined for datasource "db" provided to PrismaClient constructor.
|
||||
It should have this form: { url: "CONNECTION_STRING" }
|
||||
Read more at https://pris.ly/d/client-constructor
|
||||
|
||||
20 | const deferred = () => { let resolve!: () => void; const promise = new Promise<void>(r => resolve = r); return { promise, resolve }; };
|
||||
21 | (url ? describe : describe.skip)('atomic publication: real PostgreSQL row ordering', () => {
|
||||
> 22 | const db = new PrismaClient({ datasources: { db: { url } } });
|
||||
| ^
|
||||
23 | let user: any;
|
||||
24 | const cache = { revalidateBlog: jest.fn(async () => false) };
|
||||
25 | const service = new SeoTrackingService(db as any, cache as any);
|
||||
|
||||
at Object.datasources (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:124:86)
|
||||
at Gl (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:126:2527)
|
||||
at new t (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:130:748)
|
||||
at seo-tracking/publication.postgres.spec.ts:22:14
|
||||
at Object.<anonymous> (seo-tracking/publication.postgres.spec.ts:21:33)
|
||||
|
||||
FAIL wiki/wiki.service.spec.ts
|
||||
● WikiService › findAll › should paginate and filter terms with fallback to default sortBy
|
||||
|
||||
expect(jest.fn()).toHaveBeenCalledWith(...expected)
|
||||
|
||||
- Expected
|
||||
+ Received
|
||||
|
||||
@@ -1,21 +1,39 @@
|
||||
Object {
|
||||
"orderBy": Object {
|
||||
"term": "desc",
|
||||
},
|
||||
- "skip": 0,
|
||||
- "take": 10,
|
||||
+ "skip": undefined,
|
||||
+ "take": 100,
|
||||
"where": Object {
|
||||
"OR": Array [
|
||||
Object {
|
||||
"term": Object {
|
||||
"contains": "مفصل",
|
||||
"mode": "insensitive",
|
||||
},
|
||||
},
|
||||
Object {
|
||||
+ "key": Object {
|
||||
+ "contains": "مفصل",
|
||||
+ "mode": "insensitive",
|
||||
+ },
|
||||
+ },
|
||||
+ Object {
|
||||
"definition": Object {
|
||||
+ "contains": "مفصل",
|
||||
+ "mode": "insensitive",
|
||||
+ },
|
||||
+ },
|
||||
+ Object {
|
||||
+ "term": Object {
|
||||
+ "contains": "مفصل",
|
||||
+ "mode": "insensitive",
|
||||
+ },
|
||||
+ },
|
||||
+ Object {
|
||||
+ "key": Object {
|
||||
"contains": "مفصل",
|
||||
"mode": "insensitive",
|
||||
},
|
||||
},
|
||||
],,
|
||||
|
||||
Number of calls: 1
|
||||
|
||||
56 | });
|
||||
57 |
|
||||
> 58 | expect(mockPrisma.scientificTerm.findMany).toHaveBeenCalledWith({
|
||||
| ^
|
||||
59 | where: {
|
||||
60 | OR: [
|
||||
61 | { term: { contains: "مفصل", mode: "insensitive" } },
|
||||
|
||||
at Object.<anonymous> (wiki/wiki.service.spec.ts:58:50)
|
||||
|
||||
|
||||
Test Suites: 2 failed, 5 skipped, 95 passed, 97 of 102 total
|
||||
Tests: 1 failed, 13 skipped, 818 passed, 832 total
|
||||
Snapshots: 0 total
|
||||
Time: 55.893 s
|
||||
Ran all test suites.
|
||||
@@ -1,44 +0,0 @@
|
||||
npm notice run backend@0.0.1 test
|
||||
npm notice run jest --runInBand corporate.integration.spec -t bounds detail|oversized
|
||||
FAIL src/admin/hermes/corporate.integration.spec.ts
|
||||
● corporate API / disposable PostgreSQL › bounds detail relations and report snapshots with explicit truncation and immutable replay
|
||||
|
||||
expect(received).toHaveLength(expected)
|
||||
|
||||
Expected length: 100
|
||||
Received length: 106
|
||||
Received array: [[Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], …]
|
||||
|
||||
153 | await db.corporateEvent.createMany({ data: Array.from({ length: 105 }, () => ({ taskId: task.id, speaker: 'SYSTEM', speakerName: 'fixture', step: 'FIXTURE', content: 'x'.repeat(10000), payload: { nested: ['x'.repeat(10000)] } })) });
|
||||
154 | const detail = await request(app.getHttpServer()).get('/admin/hermes/tasks/' + task.id).set('x-api-key', 'executor').expect(200);
|
||||
> 155 | expect(detail.body.logs).toHaveLength(100);
|
||||
| ^
|
||||
156 | expect(detail.body.relationsMeta.logs).toEqual({ total: 106, returned: 100, limit: 100, truncated: true });
|
||||
157 | const op = key(), body = { day: new Date().toISOString().slice(0, 10), summary: 'bounded' };
|
||||
158 | const report = (await post('reports', body, 'executor', op).expect(201)).body;
|
||||
|
||||
at Object.<anonymous> (admin/hermes/corporate.integration.spec.ts:155:30)
|
||||
|
||||
● corporate API / disposable PostgreSQL › rolls back oversized mutation responses instead of persisting huge idempotency values
|
||||
|
||||
expect(received).rejects.toThrow()
|
||||
|
||||
Received promise resolved instead of rejected
|
||||
Resolved to value: {"value": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
||||
|
||||
168 | const service = app.get(CorporateService) as any;
|
||||
169 | const before = await db.corporateTask.count();
|
||||
> 170 | await expect(service.operation('fixture', 'oversize', key(), {}, async (tx: any) => {
|
||||
| ^
|
||||
171 | await tx.corporateTask.create({ data: { title: 'rollback', description: 'fixture', taskCode: key(), normalizedTitle: 'rollback', normalizedCode: key(), department: 'CONTENT_SEO', createdBy: 'fixture' } });
|
||||
172 | return { value: 'x'.repeat(1100000) };
|
||||
173 | })).rejects.toThrow('Operation response exceeds limit');
|
||||
|
||||
at expect (../../../corporate-backend/backend/node_modules/expect/build/index.js:2116:15)
|
||||
at Object.<anonymous> (admin/hermes/corporate.integration.spec.ts:170:11)
|
||||
|
||||
Test Suites: 1 failed, 1 total
|
||||
Tests: 2 failed, 10 skipped, 12 total
|
||||
Snapshots: 0 total
|
||||
Time: 4.583 s
|
||||
Ran all test suites matching corporate.integration.spec with tests matching "bounds detail|oversized".
|
||||
@@ -1,2 +0,0 @@
|
||||
npm notice run backend@0.0.1 build
|
||||
npm notice run tsc -b
|
||||
@@ -1,8 +0,0 @@
|
||||
npm notice run backend@0.0.1 test
|
||||
npm notice run jest --runInBand corporate.integration.spec corporate-policy.spec api-keys.integration.spec
|
||||
|
||||
Test Suites: 3 passed, 3 total
|
||||
Tests: 20 passed, 20 total
|
||||
Snapshots: 0 total
|
||||
Time: 9.263 s
|
||||
Ran all test suites matching corporate.integration.spec|corporate-policy.spec|api-keys.integration.spec.
|
||||
@@ -1,207 +0,0 @@
|
||||
npm notice run backend@0.0.1 test
|
||||
npm notice run jest --runInBand
|
||||
[31m[Nest] 3985069 - [39m10/28/2026, 12:42:14 PM [31m ERROR[39m [38;5;3m[ZibalEBankService] [39m[31m[Zibal EBank API] Error requesting /ebank/v1/account/list/: transport failed[39m
|
||||
[31m[Nest] 3985069 - [39m10/28/2026, 12:42:14 PM [31m ERROR[39m [38;5;3m[ZibalEBankService] [39m[31m[Zibal EBank API] Error requesting /ebank/v1/account/list/: transport failed[39m
|
||||
[31m[Nest] 3985069 - [39m10/28/2026, 12:42:29 PM [31m ERROR[39m [38;5;3m[ZibalEBankService] [39m[31m[Zibal EBank API] Error requesting /ebank/v1/account/list/: aborted[39m
|
||||
[31m[Nest] 3985069 - [39m10/28/2026, 12:42:14 PM [31m ERROR[39m [38;5;3m[ZibalEBankService] [39m[31m[Zibal EBank API] Error requesting /ebank/v1/account/list/: Zibal EBank HTTP 503[39m
|
||||
[31m[Nest] 3985069 - [39m10/28/2026, 12:42:15 PM [31m ERROR[39m [38;5;3m[SslService] [39m[31mFailed to parse SSL certificate[39m
|
||||
[31m[Nest] 3985069 - [39m10/28/2026, 12:42:15 PM [31m ERROR[39m [38;5;3m[SslService] [39mError: error:0480006C:PEM routines::no start line
|
||||
[90m at new X509Certificate (node:internal/crypto/x509:121:21)[39m
|
||||
at SslService.getStatus [90m(/opt/data/cache/scratch/corporate-hardening/backend/[39msrc/admin/ssl.service.ts:104:20[90m)[39m
|
||||
at Object.<anonymous> [90m(/opt/data/cache/scratch/corporate-hardening/backend/[39msrc/admin/ssl.service.spec.ts:179:30[90m)[39m
|
||||
at Promise.finally.completed (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:1561:28)
|
||||
at new Promise (<anonymous>)
|
||||
at callAsyncCircusFn (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:1501:10)
|
||||
at _callCircusTest (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:1011:40)
|
||||
at _runTest (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:951:3)
|
||||
at /opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:853:7
|
||||
at _runTestsForDescribeBlock (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:866:11)
|
||||
at _runTestsForDescribeBlock (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:861:11)
|
||||
at _runTestsForDescribeBlock (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:861:11)
|
||||
at run (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:765:3)
|
||||
at runAndTransformResultsToJestFormat (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:1993:21)
|
||||
at jestAdapter (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/runner.js:111:19)
|
||||
at runTestInternal (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-runner[24m/build/index.js:276:16)
|
||||
at runTest (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-runner[24m/build/index.js:344:7) {
|
||||
library: [32m'PEM routines'[39m,
|
||||
reason: [32m'no start line'[39m,
|
||||
code: [32m'ERR_OSSL_PEM_NO_START_LINE'[39m
|
||||
}
|
||||
[31m[Nest] 3985069 - [39m10/28/2026, 12:42:19 PM [31m ERROR[39m [38;5;3m[PaymentService] [39m[31mSecurity Alert: Amount mismatch on trackId=tr-1! Zibal reported 1000000 Rials, but expected 5000000 Rials in DB.[39m
|
||||
FAIL src/seo-tracking/publication.postgres.spec.ts
|
||||
● Test suite failed to run
|
||||
|
||||
PrismaClientConstructorValidationError: Invalid value undefined for datasource "db" provided to PrismaClient constructor.
|
||||
It should have this form: { url: "CONNECTION_STRING" }
|
||||
Read more at https://pris.ly/d/client-constructor
|
||||
|
||||
20 | const deferred = () => { let resolve!: () => void; const promise = new Promise<void>(r => resolve = r); return { promise, resolve }; };
|
||||
21 | (url ? describe : describe.skip)('atomic publication: real PostgreSQL row ordering', () => {
|
||||
> 22 | const db = new PrismaClient({ datasources: { db: { url } } });
|
||||
| ^
|
||||
23 | let user: any;
|
||||
24 | const cache = { revalidateBlog: jest.fn(async () => false) };
|
||||
25 | const service = new SeoTrackingService(db as any, cache as any);
|
||||
|
||||
at Object.datasources (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:124:86)
|
||||
at Gl (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:126:2527)
|
||||
at new t (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:130:748)
|
||||
at seo-tracking/publication.postgres.spec.ts:22:14
|
||||
at Object.<anonymous> (seo-tracking/publication.postgres.spec.ts:21:33)
|
||||
|
||||
[33m[Nest] 3985069 - [39m10/28/2026, 12:42:26 PM [33m WARN[39m [38;5;3m[BlogsService] [39m[33mCache revalidation failed for updated blog [post]: cache down[39m
|
||||
FAIL src/wiki/wiki.service.spec.ts
|
||||
● WikiService › findAll › should paginate and filter terms with fallback to default sortBy
|
||||
|
||||
expect(jest.fn()).toHaveBeenCalledWith(...expected)
|
||||
|
||||
- Expected
|
||||
+ Received
|
||||
|
||||
@@ -1,21 +1,39 @@
|
||||
Object {
|
||||
"orderBy": Object {
|
||||
"term": "desc",
|
||||
},
|
||||
- "skip": 0,
|
||||
- "take": 10,
|
||||
+ "skip": undefined,
|
||||
+ "take": 100,
|
||||
"where": Object {
|
||||
"OR": Array [
|
||||
Object {
|
||||
"term": Object {
|
||||
"contains": "مفصل",
|
||||
"mode": "insensitive",
|
||||
},
|
||||
},
|
||||
Object {
|
||||
+ "key": Object {
|
||||
+ "contains": "مفصل",
|
||||
+ "mode": "insensitive",
|
||||
+ },
|
||||
+ },
|
||||
+ Object {
|
||||
"definition": Object {
|
||||
+ "contains": "مفصل",
|
||||
+ "mode": "insensitive",
|
||||
+ },
|
||||
+ },
|
||||
+ Object {
|
||||
+ "term": Object {
|
||||
+ "contains": "مفصل",
|
||||
+ "mode": "insensitive",
|
||||
+ },
|
||||
+ },
|
||||
+ Object {
|
||||
+ "key": Object {
|
||||
"contains": "مفصل",
|
||||
"mode": "insensitive",
|
||||
},
|
||||
},
|
||||
],,
|
||||
|
||||
Number of calls: 1
|
||||
|
||||
56 | });
|
||||
57 |
|
||||
> 58 | expect(mockPrisma.scientificTerm.findMany).toHaveBeenCalledWith({
|
||||
| ^
|
||||
59 | where: {
|
||||
60 | OR: [
|
||||
61 | { term: { contains: "مفصل", mode: "insensitive" } },
|
||||
|
||||
at Object.<anonymous> (wiki/wiki.service.spec.ts:58:50)
|
||||
|
||||
|
||||
Summary of all failing tests
|
||||
FAIL seo-tracking/publication.postgres.spec.ts
|
||||
● Test suite failed to run
|
||||
|
||||
PrismaClientConstructorValidationError: Invalid value undefined for datasource "db" provided to PrismaClient constructor.
|
||||
It should have this form: { url: "CONNECTION_STRING" }
|
||||
Read more at https://pris.ly/d/client-constructor
|
||||
|
||||
20 | const deferred = () => { let resolve!: () => void; const promise = new Promise<void>(r => resolve = r); return { promise, resolve }; };
|
||||
21 | (url ? describe : describe.skip)('atomic publication: real PostgreSQL row ordering', () => {
|
||||
> 22 | const db = new PrismaClient({ datasources: { db: { url } } });
|
||||
| ^
|
||||
23 | let user: any;
|
||||
24 | const cache = { revalidateBlog: jest.fn(async () => false) };
|
||||
25 | const service = new SeoTrackingService(db as any, cache as any);
|
||||
|
||||
at Object.datasources (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:124:86)
|
||||
at Gl (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:126:2527)
|
||||
at new t (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:130:748)
|
||||
at seo-tracking/publication.postgres.spec.ts:22:14
|
||||
at Object.<anonymous> (seo-tracking/publication.postgres.spec.ts:21:33)
|
||||
|
||||
FAIL wiki/wiki.service.spec.ts
|
||||
● WikiService › findAll › should paginate and filter terms with fallback to default sortBy
|
||||
|
||||
expect(jest.fn()).toHaveBeenCalledWith(...expected)
|
||||
|
||||
- Expected
|
||||
+ Received
|
||||
|
||||
@@ -1,21 +1,39 @@
|
||||
Object {
|
||||
"orderBy": Object {
|
||||
"term": "desc",
|
||||
},
|
||||
- "skip": 0,
|
||||
- "take": 10,
|
||||
+ "skip": undefined,
|
||||
+ "take": 100,
|
||||
"where": Object {
|
||||
"OR": Array [
|
||||
Object {
|
||||
"term": Object {
|
||||
"contains": "مفصل",
|
||||
"mode": "insensitive",
|
||||
},
|
||||
},
|
||||
Object {
|
||||
+ "key": Object {
|
||||
+ "contains": "مفصل",
|
||||
+ "mode": "insensitive",
|
||||
+ },
|
||||
+ },
|
||||
+ Object {
|
||||
"definition": Object {
|
||||
+ "contains": "مفصل",
|
||||
+ "mode": "insensitive",
|
||||
+ },
|
||||
+ },
|
||||
+ Object {
|
||||
+ "term": Object {
|
||||
+ "contains": "مفصل",
|
||||
+ "mode": "insensitive",
|
||||
+ },
|
||||
+ },
|
||||
+ Object {
|
||||
+ "key": Object {
|
||||
"contains": "مفصل",
|
||||
"mode": "insensitive",
|
||||
},
|
||||
},
|
||||
],,
|
||||
|
||||
Number of calls: 1
|
||||
|
||||
56 | });
|
||||
57 |
|
||||
> 58 | expect(mockPrisma.scientificTerm.findMany).toHaveBeenCalledWith({
|
||||
| ^
|
||||
59 | where: {
|
||||
60 | OR: [
|
||||
61 | { term: { contains: "مفصل", mode: "insensitive" } },
|
||||
|
||||
at Object.<anonymous> (wiki/wiki.service.spec.ts:58:50)
|
||||
|
||||
|
||||
Test Suites: 2 failed, 6 skipped, 95 passed, 97 of 103 total
|
||||
Tests: 1 failed, 25 skipped, 818 passed, 844 total
|
||||
Snapshots: 0 total
|
||||
Time: 56.587 s
|
||||
Ran all test suites.
|
||||
@@ -1,7 +0,0 @@
|
||||
npm notice run backend@0.0.1 test
|
||||
npm notice run jest --runInBand corporate.integration.spec
|
||||
Test Suites: 1 passed, 1 total
|
||||
Tests: 7 passed, 7 total
|
||||
Snapshots: 0 total
|
||||
Time: 6.041 s
|
||||
Ran all test suites matching corporate.integration.spec.
|
||||
@@ -1,25 +0,0 @@
|
||||
npm notice run backend@0.0.1 test
|
||||
npm notice run jest --runInBand corporate.integration.spec -t rejects children
|
||||
FAIL src/admin/hermes/corporate.integration.spec.ts
|
||||
● corporate API / disposable PostgreSQL › rejects children after a parent claim commits while child creation waits on its row lock
|
||||
|
||||
expect(received).toBe(expected) // Object.is equality
|
||||
|
||||
Expected: 409
|
||||
Received: 201
|
||||
|
||||
103 | expect(waiting).toBe(true);
|
||||
104 | } finally { release(); await claiming; }
|
||||
> 105 | expect((await pending).status).toBe(409);
|
||||
| ^
|
||||
106 | expect(await db.corporateTask.count({ where: { parentId: parent.id } })).toBe(0);
|
||||
107 | });
|
||||
108 | it('accepts children on TODO and BLOCKED, which prevents parent claiming', async () => {
|
||||
|
||||
at Object.<anonymous> (admin/hermes/corporate.integration.spec.ts:105:36)
|
||||
|
||||
Test Suites: 1 failed, 1 total
|
||||
Tests: 1 failed, 6 skipped, 7 total
|
||||
Snapshots: 0 total
|
||||
Time: 4.263 s
|
||||
Ran all test suites matching corporate.integration.spec with tests matching "rejects children".
|
||||
@@ -1,7 +0,0 @@
|
||||
npm notice run backend@0.0.1 test
|
||||
npm notice run jest --runInBand corporate.integration.spec -t public reads
|
||||
Test Suites: 1 passed, 1 total
|
||||
Tests: 9 skipped, 1 passed, 10 total
|
||||
Snapshots: 0 total
|
||||
Time: 4.131 s
|
||||
Ran all test suites matching corporate.integration.spec with tests matching "public reads".
|
||||
@@ -1,25 +0,0 @@
|
||||
npm notice run backend@0.0.1 test
|
||||
npm notice run jest --runInBand corporate.integration.spec -t public reads
|
||||
FAIL src/admin/hermes/corporate.integration.spec.ts
|
||||
● corporate API / disposable PostgreSQL › public reads strip claim tokens recursively while claim and replay retain ownership token
|
||||
|
||||
expect(received).not.toContain(expected) // indexOf
|
||||
|
||||
Expected substring: not "claimToken"
|
||||
Received string: "{\"data\":[{\"id\":\"df2e8641-026a-4ed0-80ca-36fc10db3b3c\",\"taskCode\":\"TSK-257421eb-e384-403f-837c-f09345000cf2\",\"title\":\"كيك ۱۲۳\",\"normalizedTitle\":\"کیک 123\",\"normalizedCode\":\"tsk-257421eb-e384-403f-837c-f09345000cf2\",\"description\":\"integration fixture\",\"department\":\"CONTENT_SEO\",\"priority\":\"CEO_EXPEDITE\",\"status\":\"TEST\",\"actionType\":\"CEO_DIRECTIVE\",\"dueCycle\":null,\"parentId\":\"cb3407eb-35f4-4a02-9c5e-993e2b5924f1\",\"goalId\":null,\"assignedAgent\":\"apikey:executor\",\"claimToken\":\"b57fc669-e7c8-41c3-8904-f3bc60d2dc51\",\"leasedUntil\":null,\"executionCount\":1,\"qaCount\":0,\"rejectionCount\":0,\"createdBy\":\"apikey:executor\",\"createdAt\":\"2026-10-28T12:37:42.198Z\",\"updatedAt\":\"2026-10-28T12:37:42.296Z\"},{\"id\":\"cb3407eb-35f4-4a02-9c5e-993e2b5924f1\",\"taskCode\":\"TSK-40ee89e7-7127-4e85-aac2-dad7ea156be6\",\"title\":\"كيك ۱۲۳\",\"normalizedTitle\":\"کیک 123\",\"normalizedCode\":\"tsk-40ee89e7-7127-4
|
||||
|
||||
145 | for (const path of ['tasks', 'tasks/' + child.id, 'tasks/' + parent.id]) {
|
||||
146 | const r = await request(app.getHttpServer()).get('/admin/hermes/' + path).set('x-api-key', 'competitor').expect(200);
|
||||
> 147 | expect(JSON.stringify(r.body)).not.toContain('claimToken');
|
||||
| ^
|
||||
148 | expect(JSON.stringify(r.body)).not.toContain(claim.claimToken);
|
||||
149 | }
|
||||
150 | });
|
||||
|
||||
at Object.<anonymous> (admin/hermes/corporate.integration.spec.ts:147:42)
|
||||
|
||||
Test Suites: 1 failed, 1 total
|
||||
Tests: 1 failed, 9 skipped, 10 total
|
||||
Snapshots: 0 total
|
||||
Time: 3.842 s, estimated 6 s
|
||||
Ran all test suites matching corporate.integration.spec with tests matching "public reads".
|
||||
@@ -1,32 +0,0 @@
|
||||
npm notice run backend@0.0.1 test
|
||||
npm notice run jest --runInBand corporate.integration.spec -t malformed
|
||||
FAIL src/admin/hermes/corporate.integration.spec.ts
|
||||
● corporate API / disposable PostgreSQL › rejects malformed artifact locators and mismatched digest URNs before persistence
|
||||
|
||||
expected 400 "Bad Request", got 201 "Created"
|
||||
|
||||
166 | 'urn:sha256:' + 'b'.repeat(64),
|
||||
167 | ]) {
|
||||
> 168 | await post(`tasks/${task.id}/evidence`, { ...body, artifactUri }).expect(
|
||||
| ^
|
||||
169 | 400,
|
||||
170 | );
|
||||
171 | }
|
||||
|
||||
at Object.<anonymous> (admin/hermes/corporate.integration.spec.ts:168:73)
|
||||
----
|
||||
at Test._assertStatus (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:309:14)
|
||||
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:365:13
|
||||
at Test._assertFunction (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:342:13)
|
||||
at Test.assert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:195:23)
|
||||
at localAssert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:138:14)
|
||||
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:156:7
|
||||
at Test.fn [as callback] (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:892:12)
|
||||
at callback (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:1183:18)
|
||||
at IncomingMessage.fn (../../../corporate-backend/backend/node_modules/superagent/src/node/parsers/json.js:19:7)
|
||||
|
||||
Test Suites: 1 failed, 1 total
|
||||
Tests: 1 failed, 11 skipped, 12 total
|
||||
Snapshots: 0 total
|
||||
Time: 3.923 s, estimated 8 s
|
||||
Ran all test suites matching corporate.integration.spec with tests matching "malformed".
|
||||
@@ -1,8 +0,0 @@
|
||||
npm notice run backend@0.0.1 test
|
||||
npm notice run jest --runInBand corporate.integration.spec corporate-policy.spec
|
||||
|
||||
Test Suites: 2 passed, 2 total
|
||||
Tests: 12 passed, 12 total
|
||||
Snapshots: 0 total
|
||||
Time: 6.595 s
|
||||
Ran all test suites matching corporate.integration.spec|corporate-policy.spec.
|
||||
@@ -1,50 +0,0 @@
|
||||
npm notice run backend@0.0.1 test
|
||||
npm notice run jest --runInBand corporate.integration.spec -t malformed|coercions
|
||||
FAIL src/admin/hermes/corporate.integration.spec.ts
|
||||
● corporate API / disposable PostgreSQL › rejects malformed artifact locators and mismatched digest URNs before persistence
|
||||
|
||||
expected 400 "Bad Request", got 201 "Created"
|
||||
|
||||
119 | const body = { claimToken: claim.claimToken, artifactUri: '', sha256: 'a'.repeat(64), summary: 'receipt', tool: 'jest', result: 'passed' };
|
||||
120 | for (const artifactUri of ['https://', 'https://?x', 'https://bad host/x', 'https://user:pass@host.org/a', 'https://localhost/a', 'https://127.1/a', 'https://[::1]/a', 'urn:sha256:', 'urn:sha256:' + 'b'.repeat(64)]) {
|
||||
> 121 | await post(`tasks/${task.id}/evidence`, { ...body, artifactUri }).expect(400);
|
||||
| ^
|
||||
122 | }
|
||||
123 | expect(await db.corporateEvidence.count()).toBe(0);
|
||||
124 | await post(`tasks/${task.id}/evidence`, { ...body, artifactUri: 'https://pubmed.ncbi.nlm.nih.gov/123/' }).expect(201);
|
||||
|
||||
at Object.<anonymous> (admin/hermes/corporate.integration.spec.ts:121:73)
|
||||
----
|
||||
at Test._assertStatus (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:309:14)
|
||||
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:365:13
|
||||
at Test._assertFunction (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:342:13)
|
||||
at Test.assert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:195:23)
|
||||
at localAssert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:138:14)
|
||||
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:156:7
|
||||
at Test.fn [as callback] (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:892:12)
|
||||
at callback (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:1183:18)
|
||||
at IncomingMessage.fn (../../../corporate-backend/backend/node_modules/superagent/src/node/parsers/json.js:19:7)
|
||||
|
||||
● corporate API / disposable PostgreSQL › rejects implicit timestamp coercions in source and effect inputs
|
||||
|
||||
expect(received).rejects.toThrow()
|
||||
|
||||
Received promise resolved instead of rejected
|
||||
Resolved to value: {"cadence": "MONTHLY", "category": "TREND", "createdAt": "2026-10-28T12:34:28.558Z", "createdBy": "fixture", "id": "8c847ae0-ff80-4ba2-9986-26a2abdd167a", "impact": "LOW", "opportunity": "investigate", "provenance": {"collector": "fixture", "context": "isolated", "method": "test"}, "recommendedAction": "measure", "source": "receipt", "sources": [{"excerpt": "receipt", "id": "108f61d9-0e90-4d53-804e-0330d129a299", "researchId": "8c847ae0-ff80-4ba2-9986-26a2abdd167a", "retrievedAt": "1970-01-01T00:00:00.000Z", "sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "title": "source", "url": "https://pubmed.ncbi.nlm.nih.gov/"}], "status": "DISCOVERED", "title": "research"}
|
||||
|
||||
128 | const research = { title: 'research', category: 'TREND', source: 'receipt', opportunity: 'investigate', impact: 'LOW', recommendedAction: 'measure', cadence: 'MONTHLY', provenance: { method: 'test', collector: 'fixture', context: 'isolated' }, sources: [{ url: 'https://pubmed.ncbi.nlm.nih.gov/', title: 'source', excerpt: 'receipt', retrievedAt: '', sha256: 'a'.repeat(64) }] };
|
||||
129 | for (const time of [null, 0, false, [], '2026-01-01', '2026-02-30T00:00:00Z']) {
|
||||
> 130 | await expect(service.research('fixture', key(), { ...research, sources: [{ ...research.sources[0], retrievedAt: time }] })).rejects.toThrow();
|
||||
| ^
|
||||
131 | await expect(service.effect('fixture', key(), key(), { metric: 'views', availability: 'UNAVAILABLE', source: 'none', observedAt: time })).rejects.toThrow('Invalid observation time');
|
||||
132 | }
|
||||
133 | for (const url of ['https://', 'https://?bad', 'https://bad host'])
|
||||
|
||||
at expect (../../../corporate-backend/backend/node_modules/expect/build/index.js:2116:15)
|
||||
at Object.<anonymous> (admin/hermes/corporate.integration.spec.ts:130:13)
|
||||
|
||||
Test Suites: 1 failed, 1 total
|
||||
Tests: 2 failed, 7 skipped, 9 total
|
||||
Snapshots: 0 total
|
||||
Time: 3.997 s, estimated 6 s
|
||||
Ran all test suites matching corporate.integration.spec with tests matching "malformed|coercions".
|
||||
@@ -1,3 +0,0 @@
|
||||
# Plan
|
||||
Dedicated human-principal guard after authentication and role guard. Keep scope rules unchanged. Reuse parent row lock. Centralize locator/time validation and public projection. Bound detail/report queries with deterministic ordering, counts and metadata; cap serialized operation responses.
|
||||
Graph navigation: graphify-out/graph.json sha256 6a73473cee9e207543fdeeb668bea544f766200a1b16b8a3a9ce18d4e42e51af, 4304 nodes, build provenance unverified (navigation only). ApiKeysController -> JwtAuthGuard -> ApiKeysService verified directly at cc365bc; CorporateController -> CorporateService -> Prisma verified directly (corporate absent from stale map).
|
||||
@@ -1,2 +0,0 @@
|
||||
# Corporate hardening
|
||||
Base cc365bc. Backend only, no push/deploy. Humans retain admin key management; API keys cannot manage keys. Children attach only to TODO/BLOCKED under parent lock. Validate HTTPS locators/digest URNs and explicit ISO timestamp strings. Public reads omit claimToken recursively; claim retains it. Detail relations and report snapshots bounded with truncation metadata and idempotency response size guard. Acceptance: real disposable PG HTTP tests, ordering tests, backend build.
|
||||
@@ -1,7 +0,0 @@
|
||||
# Tasks
|
||||
- [x] RED/GREEN human key-admin gate with real key authentication
|
||||
- [x] RED/GREEN parent ordering on PostgreSQL
|
||||
- [x] RED/GREEN locator/time validation
|
||||
- [x] RED/GREEN public token projection
|
||||
- [x] RED/GREEN bounded reads/report/replay
|
||||
- [x] regression suite, backend build, commit (no push)
|
||||
@@ -1,14 +0,0 @@
|
||||
# Verification
|
||||
Base cc365bc; backend isolated branch hardening/corporate-security. No push/deploy/runtime changes.
|
||||
|
||||
Real PostgreSQL 16.2 started locally on 127.0.0.1:55439, corporate_test. Prisma db push applied only to disposable fixture (existing fixture lacked api_keys); tests use explicit opt-in, never runtime DATABASE_URL. Dependencies symlinked from corporate-backend/backend/node_modules, unchanged lockfile.
|
||||
|
||||
- RED auth: four key-management verbs returned 200/201 instead of 403 with real ApiKeysService validation against PG. GREEN 5 tests. Human path uses signed test-only Passport strategy (does not claim production JWT user lookup).
|
||||
- RED parent: child HTTP request observed waiting on PostgreSQL parent row lock; after IN_PROGRESS commit returned 201 instead of 409. GREEN includes TODO/BLOCKED child-first gating, existing SKIP LOCKED coverage.
|
||||
- RED validation: malformed HTTPS accepted, null timestamp persisted as epoch. GREEN malformed hosts, userinfo, loopback, malformed/mismatched digest URN, numeric/null/boolean/array/date-only/invalid calendar timestamp rejected.
|
||||
- RED projection: public reads exposed claimToken. GREEN list/detail/evidence/children omit it; claim and immutable claim replay retain ownership token.
|
||||
- RED bounds: detail returned 106 logs and oversized response persisted. GREEN limits 100 for each detail relation/report section, counts/truncation metadata, report 1000-character fields and omitted payloads; immutable report replay after source deletion; oversized operation rolls back task and operation.
|
||||
- Final targeted: 3 suites / 20 tests passed with real PG enabled. Backend tsc -b passed.
|
||||
- Full suite without opt-in: 95 passed suites, 2 failed, 6 skipped; 818 passed tests, 1 failed, 25 skipped. Exact clean cc365bc same dependencies: 95 passed suites, same 2 failed (publication.postgres undefined datasource in skipped describe; wiki stale pagination/search expectation), 5 skipped; 818 passed, same 1 failed, 13 skipped. Extra skips are new/expanded opt-in security tests, not regressions.
|
||||
|
||||
Report snapshot is intentionally partial, not a complete daily export. Relation metadata supports explicit partial display; no frontend changes owned here. Public detail relation count is capped, not arbitrary legacy JSON field bytes. All newly created idempotency responses capped at 1,000,000 UTF-8 bytes before durable save; rejection rolls back transaction. Existing legacy idempotency records are unchanged.
|
||||
@@ -1,53 +0,0 @@
|
||||
import { Test, TestingModule } from "@nestjs/testing";
|
||||
import { AdminController } from "./admin.controller";
|
||||
import { AdminService } from "./admin.service";
|
||||
import { SettingsService } from "../settings/settings.service";
|
||||
import { StageAuthorRestorationService } from "./stage-author-restoration.service";
|
||||
|
||||
describe("AdminController - Stage Author Restoration endpoint", () => {
|
||||
let controller: AdminController;
|
||||
let mockStageAuthorRestorationService: any;
|
||||
|
||||
beforeEach(async () => {
|
||||
mockStageAuthorRestorationService = {
|
||||
restoreStageAuthors: jest.fn().mockResolvedValue({
|
||||
success: true,
|
||||
totalConfigured: 5,
|
||||
restoredCount: 5,
|
||||
existingCount: 0,
|
||||
authors: [],
|
||||
}),
|
||||
};
|
||||
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [AdminController],
|
||||
providers: [
|
||||
{ provide: AdminService, useValue: {} },
|
||||
{ provide: SettingsService, useValue: {} },
|
||||
{
|
||||
provide: StageAuthorRestorationService,
|
||||
useValue: mockStageAuthorRestorationService,
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<AdminController>(AdminController);
|
||||
});
|
||||
|
||||
it.each([undefined, "10.0.0.2", "127.0.0.1.evil", "::ffff:10.0.0.2"])("denies non-loopback socket %s despite forwarded headers", async (remoteAddress) => {
|
||||
await expect(controller.restoreStageAuthors({ socket: { remoteAddress }, headers: { "x-forwarded-for": "127.0.0.1" }, ip: "127.0.0.1" } as any)).rejects.toThrow();
|
||||
expect(mockStageAuthorRestorationService.restoreStageAuthors).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["::1", "::ffff:127.0.0.1"])("accepts loopback socket %s", async remoteAddress => {
|
||||
await controller.restoreStageAuthors({ socket: { remoteAddress } } as any);
|
||||
expect(mockStageAuthorRestorationService.restoreStageAuthors).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("delegates restoreStageAuthors to StageAuthorRestorationService", async () => {
|
||||
const result = await controller.restoreStageAuthors({ socket: { remoteAddress: "127.0.0.1" } } as any);
|
||||
expect(mockStageAuthorRestorationService.restoreStageAuthors).toHaveBeenCalledTimes(1);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.restoredCount).toBe(5);
|
||||
});
|
||||
});
|
||||
@@ -1,73 +0,0 @@
|
||||
import { ForbiddenException } from "@nestjs/common";
|
||||
import { AdminService } from "./admin.service";
|
||||
import { AdminController } from "./admin.controller";
|
||||
|
||||
// All identities and credentials here are disposable test fixtures.
|
||||
describe("admin user privilege boundary", () => {
|
||||
let service: any;
|
||||
let prisma: any;
|
||||
const owner = { id: "owner-fixture", role: "SUPER_ADMIN" };
|
||||
const admin = { id: "admin-fixture", role: "ADMIN" };
|
||||
beforeEach(() => {
|
||||
prisma = {
|
||||
user: {
|
||||
findUnique: jest.fn().mockResolvedValue({ id: "target-fixture", role: "SUPER_ADMIN" }),
|
||||
update: jest.fn().mockImplementation(async ({ data }) => ({ role: "SUPER_ADMIN", ...data })),
|
||||
create: jest.fn(),
|
||||
},
|
||||
walletTransaction: { create: jest.fn() },
|
||||
$transaction: jest.fn(),
|
||||
};
|
||||
service = new AdminService(prisma, {} as never, {} as never);
|
||||
});
|
||||
it("allows an authenticated superadmin password-only edit without changing the exact role", async () => {
|
||||
const result = await service.updateUser("target-fixture", { password: "Fixture-only-123" }, owner);
|
||||
expect(result.role).toBe("SUPER_ADMIN");
|
||||
expect(prisma.user.update.mock.calls[0][0].data).not.toHaveProperty("role");
|
||||
});
|
||||
it.each(["ADMIN", "Admin", "User_PetOwner"])("denies %s assigning superadmin on create", async role => {
|
||||
prisma.user.findUnique.mockResolvedValue(null);
|
||||
await expect(service.createUser({ firstName: "Test", lastName: "Fixture", mobile: "09120000001", role: "SUPER_ADMIN" }, { id: "actor", role })).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(prisma.user.create).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each(["SUPER_ADMIN", "super-admin", "AdminSuper"])("denies ordinary admin escalation to %s", async role => {
|
||||
prisma.user.findUnique.mockResolvedValue({ id: admin.id, role: "Admin" });
|
||||
await expect(service.updateUser(admin.id, { role }, admin)).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(prisma.user.update).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each([{ password: "Fixture-only-123" }, { email: "fixture@example.test" }, { mobile: "09120000001" }, { role: "Admin" }, { walletBalance: 1 }, { firstName: "Changed" }])("denies ordinary admin editing superadmin", async dto => {
|
||||
await expect(service.updateUser("target-fixture", dto, admin)).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(prisma.user.update).not.toHaveBeenCalled();
|
||||
});
|
||||
it("denies alternate role endpoint revocation", async () => {
|
||||
await expect(service.updateUserRole("target-fixture", "Admin", admin)).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(prisma.user.update).not.toHaveBeenCalled();
|
||||
});
|
||||
it("denies deleting superadmin", async () => {
|
||||
await expect(service.deleteUser("target-fixture", admin)).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(prisma.$transaction).not.toHaveBeenCalled();
|
||||
});
|
||||
it("denies changing superadmin wallet", async () => {
|
||||
await expect(service.adjustUserWallet("target-fixture", 1, "deposit", "fixture", admin)).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(prisma.walletTransaction.create).not.toHaveBeenCalled();
|
||||
});
|
||||
it("accepts ADMIN alias for ordinary CRUD and authorized promotion/revocation", async () => {
|
||||
prisma.user.findUnique.mockResolvedValue({ id: "target-fixture", role: "User_PetOwner" });
|
||||
await service.updateUser("target-fixture", { role: "ADMIN" }, admin);
|
||||
await service.updateUser("target-fixture", { role: "SUPER_ADMIN" }, owner);
|
||||
prisma.user.findUnique.mockResolvedValue({ id: "target-fixture", role: "SUPER_ADMIN" });
|
||||
await service.updateUserRole("target-fixture", "Admin", owner);
|
||||
expect(prisma.user.update).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
it("fails closed without authenticated actor or with API key superadmin", async () => {
|
||||
await expect(service.updateUser("target-fixture", { role: "Admin" })).rejects.toBeInstanceOf(ForbiddenException);
|
||||
await expect(service.updateUser("target-fixture", { role: "Admin" }, { ...owner, isApiKey: true })).rejects.toBeInstanceOf(ForbiddenException);
|
||||
});
|
||||
it("controller forwards authenticated request identity, not DTO identity", async () => {
|
||||
const svc = { updateUser: jest.fn().mockResolvedValue({}) };
|
||||
const controller: any = new AdminController(svc as never, {} as never);
|
||||
const dto = { firstName: "Test" };
|
||||
await controller.updateUser("target-fixture", dto, { user: admin });
|
||||
expect(svc.updateUser).toHaveBeenCalledWith("target-fixture", dto, admin);
|
||||
});
|
||||
});
|
||||
@@ -1,72 +0,0 @@
|
||||
import { Test } from "@nestjs/testing";
|
||||
import { ExecutionContext } from "@nestjs/common";
|
||||
import { firstValueFrom, of } from "rxjs";
|
||||
import { AdminService } from "./admin.service";
|
||||
import { AdminController } from "./admin.controller";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
import { RedisService } from "../redis/redis.service";
|
||||
import { RevalidationService } from "../common/revalidation/revalidation.service";
|
||||
import { DecimalInterceptor } from "../common/interceptors/decimal.interceptor";
|
||||
import { Prisma } from "@prisma/client";
|
||||
|
||||
describe("admin users list contract", () => {
|
||||
const prisma = { user: { findMany: jest.fn(), count: jest.fn() } };
|
||||
let service: AdminService;
|
||||
|
||||
beforeEach(async () => {
|
||||
jest.clearAllMocks();
|
||||
const module = await Test.createTestingModule({
|
||||
providers: [
|
||||
AdminService,
|
||||
{ provide: PrismaService, useValue: prisma },
|
||||
{ provide: RedisService, useValue: {} },
|
||||
{ provide: RevalidationService, useValue: {} },
|
||||
],
|
||||
}).compile();
|
||||
service = module.get(AdminService);
|
||||
});
|
||||
|
||||
it("returns only allowlisted list fields with aggregates through the controller and decimal interceptor", async () => {
|
||||
// Deliberately return extra fields even if the query selects safely.
|
||||
prisma.user.findMany.mockResolvedValue([{
|
||||
id: "fixture-user", firstName: "Fixture", lastName: "User",
|
||||
mobile: "fixture-mobile", email: null, role: "ADMIN",
|
||||
walletBalance: new Prisma.Decimal(0), charityDonationTotal: new Prisma.Decimal(12),
|
||||
createdAt: new Date("2026-01-01T00:00:00Z"),
|
||||
password: "test-only-password-hash", passwordHash: "test-only-hash",
|
||||
refreshToken: "test-only-token", futureSecret: "must-not-leak",
|
||||
walletTransactions: [{ transactionReference: "private-reference" }],
|
||||
addresses: [], orders: [{ totalAmount: new Prisma.Decimal(100) }, { totalAmount: 25 }],
|
||||
_count: { orders: 3, reviews: 2, blogComments: 1, pets: 4 },
|
||||
}]);
|
||||
prisma.user.count.mockResolvedValue(11);
|
||||
const controller = new AdminController(service, {} as never);
|
||||
const result = await controller.getUsers({ page: 2, limit: 10 });
|
||||
const body = await firstValueFrom(new DecimalInterceptor().intercept({} as ExecutionContext, { handle: () => of(result) }));
|
||||
expect(body).toEqual({
|
||||
data: [{
|
||||
id: "fixture-user", firstName: "Fixture", lastName: "User", mobile: "fixture-mobile",
|
||||
email: null, role: "ADMIN", walletBalance: "0", charityDonationTotal: "12",
|
||||
createdAt: new Date("2026-01-01T00:00:00Z"), addresses: [],
|
||||
totalSpent: 125, ordersCount: 3, reviewsCount: 3, petsCount: 4,
|
||||
}],
|
||||
meta: { total: 11, page: 2, limit: 10, lastPage: 2 },
|
||||
});
|
||||
const query = prisma.user.findMany.mock.calls[0][0];
|
||||
expect(query.select).toBeDefined();
|
||||
expect(query.select.password).toBeUndefined();
|
||||
expect(query.include).toBeUndefined();
|
||||
expect(query.skip).toBe(10);
|
||||
});
|
||||
|
||||
it("preserves the empty paginated list contract and filters", async () => {
|
||||
prisma.user.findMany.mockResolvedValue([]);
|
||||
prisma.user.count.mockResolvedValue(0);
|
||||
expect(await service.getUsers({ search: "fixture", role: "ADMIN" })).toEqual({
|
||||
data: [], meta: { total: 0, page: 1, limit: 10, lastPage: 1 },
|
||||
});
|
||||
expect(prisma.user.findMany).toHaveBeenCalledWith(expect.objectContaining({
|
||||
where: expect.objectContaining({ role: "ADMIN", OR: expect.any(Array) }),
|
||||
}));
|
||||
});
|
||||
});
|
||||
@@ -2,7 +2,6 @@ import { Test, TestingModule } from "@nestjs/testing";
|
||||
import { AdminController } from "./admin.controller";
|
||||
import { AdminService } from "./admin.service";
|
||||
import { SettingsService } from "../settings/settings.service";
|
||||
import { StageAuthorRestorationService } from "./stage-author-restoration.service";
|
||||
|
||||
describe("AdminController", () => {
|
||||
let controller: AdminController;
|
||||
@@ -13,7 +12,6 @@ describe("AdminController", () => {
|
||||
providers: [
|
||||
{ provide: AdminService, useValue: {} },
|
||||
{ provide: SettingsService, useValue: {} },
|
||||
{ provide: StageAuthorRestorationService, useValue: {} },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
|
||||
@@ -7,10 +7,8 @@ import {
|
||||
Body,
|
||||
Param,
|
||||
Query,
|
||||
Req,
|
||||
UseGuards,
|
||||
BadRequestException,
|
||||
ForbiddenException,
|
||||
} from "@nestjs/common";
|
||||
import { AdminService, CouponInput } from "./admin.service";
|
||||
import { ProductDto } from "./dto/product.dto";
|
||||
@@ -29,9 +27,7 @@ import {
|
||||
} from "@nestjs/swagger";
|
||||
|
||||
import { CreateUserDto, UpdateUserDto } from "./dto/user.dto";
|
||||
import type { UserAdminActor } from "./user-role-policy";
|
||||
import { SettingsService } from "../settings/settings.service";
|
||||
import { StageAuthorRestorationService } from "./stage-author-restoration.service";
|
||||
|
||||
import { RolesGuard } from "../common/guards/roles.guard";
|
||||
import { Roles } from "../common/decorators/roles.decorator";
|
||||
@@ -45,7 +41,6 @@ export class AdminController {
|
||||
constructor(
|
||||
private readonly adminService: AdminService,
|
||||
private readonly settingsService: SettingsService,
|
||||
private readonly stageAuthorRestorationService?: StageAuthorRestorationService,
|
||||
) {}
|
||||
|
||||
@Get("dashboard/stats")
|
||||
@@ -67,8 +62,8 @@ export class AdminController {
|
||||
|
||||
@Post("users")
|
||||
@ApiOperation({ summary: "ایجاد کاربر جدید توسط ادمین" })
|
||||
async createUser(@Body() dto: CreateUserDto, @Req() req?: { user?: UserAdminActor }) {
|
||||
const user = await this.adminService.createUser(dto, req?.user);
|
||||
async createUser(@Body() dto: CreateUserDto) {
|
||||
const user = await this.adminService.createUser(dto);
|
||||
return {
|
||||
success: true,
|
||||
message: "کاربر جدید با موفقیت ایجاد شد",
|
||||
@@ -76,22 +71,6 @@ export class AdminController {
|
||||
};
|
||||
}
|
||||
|
||||
@Post("users/stage-author-restoration")
|
||||
@ApiOperation({
|
||||
summary:
|
||||
"بازیابی شناسه و مشخصات عمومی پنج نویسنده اورجینال مقالات در محیط استیج",
|
||||
})
|
||||
async restoreStageAuthors(@Req() req: { socket?: { remoteAddress?: string } }) {
|
||||
const peer = req?.socket?.remoteAddress;
|
||||
if (!peer || !["127.0.0.1", "::1", "::ffff:127.0.0.1"].includes(peer)) {
|
||||
throw new ForbiddenException("Stage author restoration requires a loopback socket");
|
||||
}
|
||||
if (!this.stageAuthorRestorationService) {
|
||||
throw new Error("StageAuthorRestorationService not initialized");
|
||||
}
|
||||
return this.stageAuthorRestorationService.restoreStageAuthors();
|
||||
}
|
||||
|
||||
@Get("users/:id")
|
||||
@ApiOperation({ summary: "جزئیات کاربر" })
|
||||
async getUserDetails(@Param("id") id: string) {
|
||||
@@ -101,8 +80,8 @@ export class AdminController {
|
||||
|
||||
@Put("users/:id")
|
||||
@ApiOperation({ summary: "ویرایش مشخصات کامل کاربر" })
|
||||
async updateUser(@Param("id") id: string, @Body() dto: UpdateUserDto, @Req() req?: { user?: UserAdminActor }) {
|
||||
const user = await this.adminService.updateUser(id, dto, req?.user);
|
||||
async updateUser(@Param("id") id: string, @Body() dto: UpdateUserDto) {
|
||||
const user = await this.adminService.updateUser(id, dto);
|
||||
return {
|
||||
success: true,
|
||||
message: "اطلاعات کاربر با موفقیت ویرایش شد",
|
||||
@@ -112,8 +91,8 @@ export class AdminController {
|
||||
|
||||
@Delete("users/:id")
|
||||
@ApiOperation({ summary: "حذف کاربر و دادههای مرتبط" })
|
||||
async deleteUser(@Param("id") id: string, @Req() req?: { user?: UserAdminActor }) {
|
||||
await this.adminService.deleteUser(id, req?.user);
|
||||
async deleteUser(@Param("id") id: string) {
|
||||
await this.adminService.deleteUser(id);
|
||||
return {
|
||||
success: true,
|
||||
message: "کاربر با موفقیت از سیستم حذف شد",
|
||||
@@ -122,8 +101,8 @@ export class AdminController {
|
||||
|
||||
@Put("users/:id/role")
|
||||
@ApiOperation({ summary: "تغییر نقش کاربر" })
|
||||
async updateUserRole(@Param("id") id: string, @Body("role") role: string, @Req() req?: { user?: UserAdminActor }) {
|
||||
const user = await this.adminService.updateUserRole(id, role, req?.user);
|
||||
async updateUserRole(@Param("id") id: string, @Body("role") role: string) {
|
||||
const user = await this.adminService.updateUserRole(id, role);
|
||||
return { success: true, data: user };
|
||||
}
|
||||
|
||||
@@ -134,7 +113,6 @@ export class AdminController {
|
||||
@Body("amount") amount: number,
|
||||
@Body("type") type: "deposit" | "withdrawal" | "refund",
|
||||
@Body("description") description?: string,
|
||||
@Req() req?: { user?: UserAdminActor },
|
||||
) {
|
||||
const numAmount = Number(amount);
|
||||
if (!numAmount || isNaN(numAmount) || numAmount <= 0) {
|
||||
@@ -152,7 +130,6 @@ export class AdminController {
|
||||
numAmount,
|
||||
type,
|
||||
description,
|
||||
req?.user,
|
||||
);
|
||||
return {
|
||||
success: true,
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import { CorporateController } from "./hermes/corporate.controller";
|
||||
import { CorporateService } from "./hermes/corporate.service";
|
||||
import { Module } from "@nestjs/common";
|
||||
import { AdminController } from "./admin.controller";
|
||||
import { AdminService } from "./admin.service";
|
||||
@@ -23,17 +21,18 @@ import { CompetitorPricingController } from "./competitor-pricing.controller";
|
||||
import { B2BLeadsController } from "./b2b-leads.controller";
|
||||
import { PricingSuggestionsController } from "./pricing-suggestions.controller";
|
||||
import { SmsCampaignsController } from "./sms-campaigns.controller";
|
||||
import { ApprovalsController } from "./approvals.controller";
|
||||
import { AuditLogsController } from "./audit-logs.controller";
|
||||
import { DepartmentTasksController } from "./department-tasks.controller";
|
||||
import { PrismaModule } from "../prisma/prisma.module";
|
||||
import { RedisModule } from "../redis/redis.module";
|
||||
import { SettingsModule } from "../settings/settings.module";
|
||||
import { SupportChatAnalyticsController } from "./support-chat-analytics.controller";
|
||||
import { SupportChatAnalyticsService } from "./support-chat-analytics.service";
|
||||
import { StageAuthorRestorationService } from "./stage-author-restoration.service";
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule, RedisModule, SettingsModule],
|
||||
controllers: [
|
||||
CorporateController,
|
||||
AdminController,
|
||||
ReportsController,
|
||||
MediaController,
|
||||
@@ -47,10 +46,12 @@ import { StageAuthorRestorationService } from "./stage-author-restoration.servic
|
||||
B2BLeadsController,
|
||||
PricingSuggestionsController,
|
||||
SmsCampaignsController,
|
||||
ApprovalsController,
|
||||
AuditLogsController,
|
||||
DepartmentTasksController,
|
||||
SupportChatAnalyticsController,
|
||||
],
|
||||
providers: [
|
||||
CorporateService,
|
||||
AdminService,
|
||||
ReportsService,
|
||||
MediaService,
|
||||
@@ -61,7 +62,6 @@ import { StageAuthorRestorationService } from "./stage-author-restoration.servic
|
||||
SslService,
|
||||
ApiKeysService,
|
||||
SupportChatAnalyticsService,
|
||||
StageAuthorRestorationService,
|
||||
],
|
||||
exports: [ApiKeysService, MediaService],
|
||||
})
|
||||
|
||||
@@ -61,10 +61,15 @@ export class CouponInput {
|
||||
targets?: CouponTargetInput[];
|
||||
}
|
||||
|
||||
import { ALLOWED_USER_ROLES, assertUserMutationAllowed } from "./user-role-policy";
|
||||
import type { UserAdminActor } from "./user-role-policy";
|
||||
import { randomUUID } from "crypto";
|
||||
import { authorizeStageSession, STAGE_TEST_ID, STAGE_TEST_EMAIL, STAGE_TEST_MOBILE } from "../auth/stage-test-principal";
|
||||
const ALLOWED_USER_ROLES = [
|
||||
"User_PetOwner",
|
||||
"User_Vet",
|
||||
"User_Clinic",
|
||||
"User_PetShop",
|
||||
"Customer",
|
||||
"Admin",
|
||||
"SUPER_ADMIN",
|
||||
];
|
||||
|
||||
@Injectable()
|
||||
export class AdminService {
|
||||
@@ -163,17 +168,12 @@ export class AdminService {
|
||||
skip,
|
||||
take: limit,
|
||||
orderBy: { [sortField]: sortDirection },
|
||||
select: {
|
||||
id: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
mobile: true,
|
||||
email: true,
|
||||
role: true,
|
||||
walletBalance: true,
|
||||
charityDonationTotal: true,
|
||||
createdAt: true,
|
||||
include: {
|
||||
addresses: true,
|
||||
walletTransactions: {
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 20,
|
||||
},
|
||||
orders: {
|
||||
where: { status: { not: "CANCELLED" } },
|
||||
select: { totalAmount: true },
|
||||
@@ -197,19 +197,9 @@ export class AdminService {
|
||||
(acc, curr) => acc + (Number(curr.totalAmount) || 0),
|
||||
0,
|
||||
) || 0;
|
||||
// Explicit response allowlist: never expose authentication fields or
|
||||
// new model columns implicitly through this administrative list.
|
||||
const { orders: _orders, ...rest } = u;
|
||||
return {
|
||||
id: u.id,
|
||||
firstName: u.firstName,
|
||||
lastName: u.lastName,
|
||||
mobile: u.mobile,
|
||||
email: u.email,
|
||||
role: u.role,
|
||||
walletBalance: u.walletBalance,
|
||||
charityDonationTotal: u.charityDonationTotal,
|
||||
createdAt: u.createdAt,
|
||||
addresses: u.addresses,
|
||||
...rest,
|
||||
totalSpent,
|
||||
ordersCount: u._count?.orders || 0,
|
||||
reviewsCount: (u._count?.reviews || 0) + (u._count?.blogComments || 0),
|
||||
@@ -237,12 +227,7 @@ export class AdminService {
|
||||
return user;
|
||||
}
|
||||
|
||||
async createUser(dto: CreateUserDto, actor?: UserAdminActor) {
|
||||
assertUserMutationAllowed(actor, undefined, dto.role);
|
||||
return this.persistUser(dto);
|
||||
}
|
||||
|
||||
private async persistUser(dto: CreateUserDto, stage?: { session: string; expiresAt: Date; generation?: string }) {
|
||||
async createUser(dto: CreateUserDto) {
|
||||
const mobile = normalizeMobile(dto.mobile);
|
||||
const existingMobile = await this.prisma.user.findUnique({
|
||||
where: { mobile },
|
||||
@@ -275,7 +260,6 @@ export class AdminService {
|
||||
|
||||
return this.prisma.user.create({
|
||||
data: {
|
||||
...(stage ? { id: STAGE_TEST_ID, stageTestGeneration:stage.generation || randomUUID(), stageTestSession: stage.session, authExpiresAt: stage.expiresAt } : {}),
|
||||
firstName: dto.firstName.trim(),
|
||||
lastName: dto.lastName.trim(),
|
||||
mobile,
|
||||
@@ -290,30 +274,7 @@ export class AdminService {
|
||||
});
|
||||
}
|
||||
|
||||
// Explicit CI seed authority, NOT a fabricated SUPER_ADMIN actor. Not controller-exposed.
|
||||
async provisionStageTestPrincipal(env: NodeJS.ProcessEnv, sha: string, password: string) {
|
||||
const grant = authorizeStageSession(env, sha);
|
||||
const existing = await this.prisma.user.findFirst({where:{OR:[{id:STAGE_TEST_ID},{email:STAGE_TEST_EMAIL},{mobile:STAGE_TEST_MOBILE}]}});
|
||||
if (existing) {
|
||||
if (existing.id !== STAGE_TEST_ID || existing.email !== STAGE_TEST_EMAIL || existing.mobile !== STAGE_TEST_MOBILE || existing.stageTestSession !== grant.session || (env.STAGE_TEST_GENERATION && existing.stageTestGeneration !== env.STAGE_TEST_GENERATION) || existing.role !== 'SUPER_ADMIN' || !existing.authExpiresAt || existing.authExpiresAt.getTime() <= Date.now() || !await bcrypt.compare(password, existing.password || '')) throw new Error('Refusing existing or unowned principal');
|
||||
return existing; // Never renew TTL on retry.
|
||||
}
|
||||
if (password.length < 32) throw new Error('Server generated secret required');
|
||||
return this.persistUser({firstName:'Stage',lastName:'CI independent reviewer',email:STAGE_TEST_EMAIL,mobile:STAGE_TEST_MOBILE,role:'SUPER_ADMIN',password}, {session:grant.session,expiresAt:new Date(Date.now()+grant.ttl*1000),generation:env.STAGE_TEST_GENERATION});
|
||||
}
|
||||
|
||||
async cleanupStageTestPrincipal(env: NodeJS.ProcessEnv, sha: string, onRevoked: () => void = () => undefined) {
|
||||
const grant = authorizeStageSession(env, sha);
|
||||
const existing = await this.prisma.user.findUnique({where:{id:STAGE_TEST_ID}});
|
||||
if (!existing) { onRevoked(); return; }
|
||||
if (existing.email !== STAGE_TEST_EMAIL || existing.mobile !== STAGE_TEST_MOBILE || existing.stageTestSession !== grant.session || !existing.authExpiresAt || (env.STAGE_TEST_GENERATION && existing.stageTestGeneration !== env.STAGE_TEST_GENERATION)) throw new Error('Refusing unowned principal cleanup');
|
||||
// Revoke before relational cleanup; failed cleanup cannot leave valid tokens.
|
||||
await this.prisma.user.update({where:{id:STAGE_TEST_ID,stageTestSession:grant.session,stageTestGeneration:existing.stageTestGeneration},data:{authExpiresAt:new Date(0),password:''}});
|
||||
onRevoked();
|
||||
return this.deleteUserRecords(STAGE_TEST_ID, {session:grant.session,generation:existing.stageTestGeneration});
|
||||
}
|
||||
|
||||
async updateUser(id: string, dto: UpdateUserDto, actor?: UserAdminActor) {
|
||||
async updateUser(id: string, dto: UpdateUserDto) {
|
||||
if (id === "12345678-1234-1234-1234-123456789012") {
|
||||
throw new BadRequestException(
|
||||
"امکان ویرایش حساب ادمین پیشفرض وجود ندارد",
|
||||
@@ -325,8 +286,6 @@ export class AdminService {
|
||||
throw new NotFoundException(`کاربری با شناسه ${id} یافت نشد`);
|
||||
}
|
||||
|
||||
assertUserMutationAllowed(actor, user.role, dto.role);
|
||||
|
||||
const normalizedMobile = dto.mobile
|
||||
? normalizeMobile(dto.mobile)
|
||||
: undefined;
|
||||
@@ -381,11 +340,17 @@ export class AdminService {
|
||||
});
|
||||
}
|
||||
|
||||
async updateUserRole(id: string, role: string, actor?: UserAdminActor) {
|
||||
return this.updateUser(id, { role }, actor);
|
||||
async updateUserRole(id: string, role: string) {
|
||||
if (!ALLOWED_USER_ROLES.includes(role)) {
|
||||
throw new BadRequestException("نقش کاربری مشخص شده نامعتبر است");
|
||||
}
|
||||
return this.prisma.user.update({
|
||||
where: { id },
|
||||
data: { role },
|
||||
});
|
||||
}
|
||||
|
||||
async deleteUser(id: string, actor?: UserAdminActor) {
|
||||
async deleteUser(id: string) {
|
||||
if (id === "12345678-1234-1234-1234-123456789012") {
|
||||
throw new BadRequestException("امکان حذف حساب ادمین پیشفرض وجود ندارد");
|
||||
}
|
||||
@@ -395,17 +360,7 @@ export class AdminService {
|
||||
throw new NotFoundException(`کاربری با شناسه ${id} یافت نشد`);
|
||||
}
|
||||
|
||||
assertUserMutationAllowed(actor, user.role);
|
||||
|
||||
return this.deleteUserRecords(id);
|
||||
}
|
||||
|
||||
private async deleteUserRecords(id: string, stage?: {session:string; generation:string|null}) {
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
if (stage) {
|
||||
// Acquire the row lock with an exact fence before deleting any related rows.
|
||||
await tx.user.update({where:{id,stageTestSession:stage.session,stageTestGeneration:stage.generation},data:{authExpiresAt:new Date(0),password:''}});
|
||||
}
|
||||
await tx.userAddress.deleteMany({ where: { userId: id } });
|
||||
await tx.walletTransaction.deleteMany({ where: { userId: id } });
|
||||
await tx.pet.deleteMany({ where: { userId: id } });
|
||||
@@ -1442,15 +1397,12 @@ export class AdminService {
|
||||
amount: number,
|
||||
type: "deposit" | "withdrawal" | "refund",
|
||||
description?: string,
|
||||
actor?: UserAdminActor,
|
||||
) {
|
||||
const user = await this.prisma.user.findUnique({ where: { id: userId } });
|
||||
if (!user) {
|
||||
throw new NotFoundException(`کاربری با شناسه ${userId} یافت نشد.`);
|
||||
}
|
||||
|
||||
assertUserMutationAllowed(actor, user.role);
|
||||
|
||||
const transaction = await this.prisma.walletTransaction.create({
|
||||
data: {
|
||||
userId,
|
||||
|
||||
@@ -8,34 +8,33 @@ import {
|
||||
Param,
|
||||
UseGuards,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
import { ApiKeysService } from './api-keys.service';
|
||||
import { CreateApiKeyDto } from './dto/api-key.dto';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
} from "@nestjs/common";
|
||||
import { ApiKeysService } from "./api-keys.service";
|
||||
import { CreateApiKeyDto } from "./dto/api-key.dto";
|
||||
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
|
||||
import {
|
||||
ApiTags,
|
||||
ApiBearerAuth,
|
||||
ApiOperation,
|
||||
ApiResponse,
|
||||
} from '@nestjs/swagger';
|
||||
} from "@nestjs/swagger";
|
||||
|
||||
import { RolesGuard } from '../common/guards/roles.guard';
|
||||
import { HumanAdminGuard } from '../common/guards/human-admin.guard';
|
||||
import { Roles } from '../common/decorators/roles.decorator';
|
||||
import { RolesGuard } from "../common/guards/roles.guard";
|
||||
import { Roles } from "../common/decorators/roles.decorator";
|
||||
|
||||
@ApiTags('Admin - مدیریت کلیدهای دسترسی (API Keys)')
|
||||
@ApiTags("Admin - مدیریت کلیدهای دسترسی (API Keys)")
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, RolesGuard, HumanAdminGuard)
|
||||
@Roles('Admin', 'SUPER_ADMIN')
|
||||
@Controller('admin/api-keys')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles("Admin", "SUPER_ADMIN")
|
||||
@Controller("admin/api-keys")
|
||||
export class ApiKeysController {
|
||||
constructor(private readonly apiKeysService: ApiKeysService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: 'دریافت لیست کلیدهای دسترسی API' })
|
||||
@ApiOperation({ summary: "دریافت لیست کلیدهای دسترسی API" })
|
||||
@ApiResponse({
|
||||
status: HttpStatus.OK,
|
||||
description: 'لیست کلیدها با موفقیت دریافت شد',
|
||||
description: "لیست کلیدها با موفقیت دریافت شد",
|
||||
})
|
||||
async findAll() {
|
||||
const keys = await this.apiKeysService.findAll();
|
||||
@@ -46,39 +45,39 @@ export class ApiKeysController {
|
||||
}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: 'ایجاد یک API Key جدید' })
|
||||
@ApiOperation({ summary: "ایجاد یک API Key جدید" })
|
||||
@ApiResponse({
|
||||
status: HttpStatus.CREATED,
|
||||
description: 'کلید جدید با موفقیت ایجاد شد',
|
||||
description: "کلید جدید با موفقیت ایجاد شد",
|
||||
})
|
||||
async create(@Body() dto: CreateApiKeyDto) {
|
||||
const result = await this.apiKeysService.create(dto);
|
||||
return {
|
||||
success: true,
|
||||
message:
|
||||
'کلید دسترسی با موفقیت ایجاد شد. لطفاً آن را در جای امن ذخیره نمایید.',
|
||||
"کلید دسترسی با موفقیت ایجاد شد. لطفاً آن را در جای امن ذخیره نمایید.",
|
||||
data: result,
|
||||
};
|
||||
}
|
||||
|
||||
@Patch(':id/toggle')
|
||||
@ApiOperation({ summary: 'تغییر وضعیت فعال/غیرفعال کلید' })
|
||||
async toggleStatus(@Param('id') id: string) {
|
||||
@Patch(":id/toggle")
|
||||
@ApiOperation({ summary: "تغییر وضعیت فعال/غیرفعال کلید" })
|
||||
async toggleStatus(@Param("id") id: string) {
|
||||
const updated = await this.apiKeysService.toggleStatus(id);
|
||||
return {
|
||||
success: true,
|
||||
message: 'وضعیت کلید با موفقیت بهروزرسانی شد',
|
||||
message: "وضعیت کلید با موفقیت بهروزرسانی شد",
|
||||
data: updated,
|
||||
};
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@ApiOperation({ summary: 'حذف کلید دسترسی' })
|
||||
async delete(@Param('id') id: string) {
|
||||
@Delete(":id")
|
||||
@ApiOperation({ summary: "حذف کلید دسترسی" })
|
||||
async delete(@Param("id") id: string) {
|
||||
await this.apiKeysService.delete(id);
|
||||
return {
|
||||
success: true,
|
||||
message: 'کلید دسترسی با موفقیت حذف شد',
|
||||
message: "کلید دسترسی با موفقیت حذف شد",
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,127 +0,0 @@
|
||||
import passport from 'passport';
|
||||
import { Strategy, ExtractJwt } from 'passport-jwt';
|
||||
import { sign } from 'jsonwebtoken';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import request from 'supertest';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { ApiKeysController } from './api-keys.controller';
|
||||
import { ApiKeysService } from './api-keys.service';
|
||||
|
||||
const integration = process.env.CORPORATE_TEST_DATABASE_URL
|
||||
? describe
|
||||
: describe.skip;
|
||||
integration(
|
||||
'human-only key administration / real key authentication and PostgreSQL',
|
||||
() => {
|
||||
let app: INestApplication, db: PrismaService, service: ApiKeysService;
|
||||
let rawKey: string, target: string;
|
||||
const secret = 'isolated-test-jwt';
|
||||
beforeAll(async () => {
|
||||
const url = new URL(process.env.CORPORATE_TEST_DATABASE_URL!);
|
||||
if (url.hostname !== '127.0.0.1' || url.pathname !== '/corporate_test')
|
||||
throw new Error('Disposable DB required');
|
||||
db = new PrismaClient({
|
||||
datasources: { db: { url: url.toString() } },
|
||||
}) as PrismaService;
|
||||
passport.use(
|
||||
'jwt',
|
||||
new Strategy(
|
||||
{
|
||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
secretOrKey: secret,
|
||||
},
|
||||
(p, done) => done(null, { id: p.sub, role: p.role }),
|
||||
),
|
||||
);
|
||||
const module = await Test.createTestingModule({
|
||||
controllers: [ApiKeysController],
|
||||
providers: [ApiKeysService, { provide: PrismaService, useValue: db }],
|
||||
}).compile();
|
||||
service = module.get(ApiKeysService);
|
||||
app = module.createNestApplication();
|
||||
await app.listen(0, '127.0.0.1');
|
||||
rawKey = (
|
||||
await service.create({
|
||||
name: 'security-fixture-admin',
|
||||
scopes: ['admin'],
|
||||
})
|
||||
).rawKey;
|
||||
target = (
|
||||
await service.create({
|
||||
name: 'security-fixture-target',
|
||||
scopes: ['read'],
|
||||
})
|
||||
).apiKey.id;
|
||||
});
|
||||
afterAll(async () => {
|
||||
await db?.apiKey.deleteMany({
|
||||
where: { name: { startsWith: 'security-fixture' } },
|
||||
});
|
||||
await app?.close();
|
||||
await db?.$disconnect();
|
||||
passport.unuse('jwt');
|
||||
});
|
||||
it.each(['get', 'post', 'patch', 'delete'] as const)(
|
||||
'denies %s to authenticated admin API key without mutating keys',
|
||||
async (method) => {
|
||||
const before = await db.apiKey.count();
|
||||
const path =
|
||||
'/admin/api-keys' +
|
||||
(method === 'patch'
|
||||
? `/${target}/toggle`
|
||||
: method === 'delete'
|
||||
? `/${target}`
|
||||
: '');
|
||||
await request(app.getHttpServer())
|
||||
[method](path)
|
||||
.set('x-api-key', rawKey)
|
||||
.send(
|
||||
method === 'post'
|
||||
? { name: 'security-fixture-forged-reviewer', scopes: ['admin'] }
|
||||
: {},
|
||||
)
|
||||
.expect(403);
|
||||
expect(await db.apiKey.count()).toBe(before);
|
||||
expect(
|
||||
(await db.apiKey.findUniqueOrThrow({ where: { id: target } })).status,
|
||||
).toBe('ACTIVE');
|
||||
},
|
||||
);
|
||||
it('retains human admin CRUD and rejects nonadmin humans and wildcard keys', async () => {
|
||||
const auth =
|
||||
'Bearer ' + sign({ sub: 'fixture-human', role: 'Admin' }, secret);
|
||||
const created = await request(app.getHttpServer())
|
||||
.post('/admin/api-keys')
|
||||
.set('Authorization', auth)
|
||||
.send({ name: 'security-fixture-human', scopes: ['read'] })
|
||||
.expect(201);
|
||||
const id = created.body.data.apiKey.id;
|
||||
await request(app.getHttpServer())
|
||||
.get('/admin/api-keys')
|
||||
.set('Authorization', auth)
|
||||
.expect(200);
|
||||
await request(app.getHttpServer())
|
||||
.patch(`/admin/api-keys/${id}/toggle`)
|
||||
.set('Authorization', auth)
|
||||
.expect(200);
|
||||
await request(app.getHttpServer())
|
||||
.delete(`/admin/api-keys/${id}`)
|
||||
.set('Authorization', auth)
|
||||
.expect(200);
|
||||
await request(app.getHttpServer())
|
||||
.get('/admin/api-keys')
|
||||
.set(
|
||||
'Authorization',
|
||||
'Bearer ' + sign({ sub: 'fixture-user', role: 'USER' }, secret),
|
||||
)
|
||||
.expect(403);
|
||||
const wildcard = await service.create({
|
||||
name: 'security-fixture-wildcard',
|
||||
scopes: ['*'],
|
||||
});
|
||||
expect((await service.validateKey(wildcard.rawKey)).role).toBe('USER');
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,25 @@
|
||||
import { GoneException } from '@nestjs/common';
|
||||
import { ApprovalsController } from './approvals.controller';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
describe('ApprovalsController retired mutation boundary',()=>{
|
||||
const access=jest.fn();
|
||||
const prisma=new Proxy({},{get:(_target,key)=>{access(key);throw new Error('Database access forbidden');}});
|
||||
const controller=new ApprovalsController(prisma as PrismaService);
|
||||
beforeEach(()=>access.mockClear());
|
||||
it('create {department:SEO,category:SEO,title:Legacy,payload:{}} returns 410 without reading or writing persistence',async()=>{
|
||||
await expect(controller.create({department:'SEO',category:'SEO',title:'Legacy',payload:{}})).rejects.toBeInstanceOf(GoneException);
|
||||
await expect(controller.create({department:'SEO',category:'SEO',title:'Legacy',payload:{}})).rejects.toMatchObject({status:410});
|
||||
expect(access).not.toHaveBeenCalled();
|
||||
});
|
||||
it('decide missing, {decision:APPROVED} returns 410 without reading or writing persistence',async()=>{
|
||||
await expect(controller.decide('missing', {decision:'APPROVED'})).rejects.toBeInstanceOf(GoneException);
|
||||
await expect(controller.decide('missing', {decision:'APPROVED'})).rejects.toMatchObject({status:410});
|
||||
expect(access).not.toHaveBeenCalled();
|
||||
});
|
||||
it('decide missing, {decision:REJECTED} returns 410 without reading or writing persistence',async()=>{
|
||||
await expect(controller.decide('missing', {decision:'REJECTED'})).rejects.toBeInstanceOf(GoneException);
|
||||
await expect(controller.decide('missing', {decision:'REJECTED'})).rejects.toMatchObject({status:410});
|
||||
expect(access).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,134 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Put,
|
||||
Body,
|
||||
Param,
|
||||
Query,
|
||||
UseGuards,
|
||||
NotFoundException,
|
||||
GoneException,
|
||||
} from "@nestjs/common";
|
||||
import { ApiTags, ApiBearerAuth, ApiOperation } from "@nestjs/swagger";
|
||||
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
|
||||
import { RolesGuard } from "../common/guards/roles.guard";
|
||||
import { Roles } from "../common/decorators/roles.decorator";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
import {
|
||||
CreateApprovalRequestDto,
|
||||
DecideApprovalDto,
|
||||
QueryApprovalDto,
|
||||
} from "./dto/approval-request.dto";
|
||||
|
||||
@ApiTags("Admin - CEO Approvals & Governance")
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles("Admin", "SUPER_ADMIN")
|
||||
@Controller("admin/approvals")
|
||||
export class ApprovalsController {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: "لیست موارد کارتابل تاییدات مدیریت" })
|
||||
async findAll(@Query() query: QueryApprovalDto) {
|
||||
const page = Number(query.page) || 1;
|
||||
const limit = Number(query.limit) || 100;
|
||||
const skip = (page - 1) * limit;
|
||||
|
||||
const where: any = {};
|
||||
if (query.department) where.department = query.department;
|
||||
if (query.category) where.category = query.category;
|
||||
if (query.status) where.status = query.status;
|
||||
|
||||
const [total, items, pendingCount] = await Promise.all([
|
||||
(this.prisma as any).approvalRequest.count({ where }),
|
||||
(this.prisma as any).approvalRequest.findMany({
|
||||
where,
|
||||
skip,
|
||||
take: limit,
|
||||
orderBy: { createdAt: "desc" },
|
||||
}),
|
||||
(this.prisma as any).approvalRequest.count({
|
||||
where: { status: "PENDING" },
|
||||
}),
|
||||
]);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: items,
|
||||
meta: {
|
||||
total,
|
||||
page,
|
||||
limit,
|
||||
totalPages: Math.ceil(total / limit),
|
||||
pendingCount,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@Get(":id")
|
||||
@ApiOperation({ summary: "دریافت جزییات یک آیتم کارتابل" })
|
||||
async findOne(@Param("id") id: string) {
|
||||
const item = await (this.prisma as any).approvalRequest.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
if (!item) {
|
||||
throw new NotFoundException(`Approval request ${id} not found`);
|
||||
}
|
||||
return { success: true, data: item };
|
||||
}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: "ثبت آیتم جدید جهت تایید مدیریت (از طرف سیستم یا دپارتمانها)" })
|
||||
async create(@Body() dto: CreateApprovalRequestDto) {
|
||||
throw new GoneException("Legacy orchestration mutations are retired. Orchestration v4 remains read-only; no replacement mutation is enabled.");
|
||||
}
|
||||
|
||||
@Post(":id/test")
|
||||
@ApiOperation({ summary: "اجرای شبیهسازی تست زنده برای آیتم کارتابل" })
|
||||
async runTestSimulation(@Param("id") id: string) {
|
||||
const item = await (this.prisma as any).approvalRequest.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
if (!item) {
|
||||
throw new NotFoundException(`Approval request ${id} not found`);
|
||||
}
|
||||
|
||||
let testResult: any = { status: "SIMULATION_SUCCESS" };
|
||||
if (item.category === "PRICING") {
|
||||
const payload = item.payload as any;
|
||||
testResult = {
|
||||
impact: "Price change simulation",
|
||||
currentPrice: payload.currentPrice,
|
||||
newPrice: payload.newPrice,
|
||||
marginDiff: payload.newPrice && payload.buyPrice
|
||||
? (((payload.newPrice - payload.buyPrice) / payload.newPrice) * 100).toFixed(1) + "%"
|
||||
: "N/A",
|
||||
torobFeedReflectEstimate: "< 5 seconds",
|
||||
};
|
||||
} else if (item.category === "PURCHASE_ORDER") {
|
||||
const payload = item.payload as any;
|
||||
testResult = {
|
||||
document: "PO Pre-check",
|
||||
itemsCount: payload.items ? payload.items.length : 1,
|
||||
totalEstimatedCost: payload.totalCost || "محاسبه بر اساس نرخ خرید",
|
||||
fulfillmentCapacity: "انبار آماده پذیرش",
|
||||
};
|
||||
} else {
|
||||
testResult = {
|
||||
executionSafe: true,
|
||||
summary: "تست سلامت اولیه و اعتبارسنجی مقادیر با موفقیت انجام شد.",
|
||||
};
|
||||
}
|
||||
|
||||
return { success: true, testResult };
|
||||
}
|
||||
|
||||
@Put(":id/decide")
|
||||
@ApiOperation({ summary: "تصمیمگیری مدیرعامل (تایید یا رد همراه با یادداشت)" })
|
||||
async decide(@Param("id") id: string, @Body() dto: DecideApprovalDto) {
|
||||
throw new GoneException("Legacy orchestration mutations are retired. Orchestration v4 remains read-only; no replacement mutation is enabled.");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Body,
|
||||
Query,
|
||||
UseGuards,
|
||||
Param,
|
||||
} from "@nestjs/common";
|
||||
import { ApiTags, ApiBearerAuth, ApiOperation } from "@nestjs/swagger";
|
||||
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
|
||||
import { RolesGuard } from "../common/guards/roles.guard";
|
||||
import { Roles } from "../common/decorators/roles.decorator";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
|
||||
@ApiTags("Admin - System Audit & History")
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles("Admin", "SUPER_ADMIN")
|
||||
@Controller("admin/audit-logs")
|
||||
export class AuditLogsController {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: "لیست لاگهای تغییرات دیتابیس و سیستم" })
|
||||
async findAll(@Query() query: any) {
|
||||
const page = Number(query.page) || 1;
|
||||
const limit = Number(query.limit) || 30;
|
||||
const skip = (page - 1) * limit;
|
||||
|
||||
const where: any = {};
|
||||
if (query.entity) where.entity = query.entity;
|
||||
if (query.action) where.action = query.action;
|
||||
if (query.department) where.department = query.department;
|
||||
if (query.search) {
|
||||
where.OR = [
|
||||
{ summary: { contains: query.search, mode: "insensitive" } },
|
||||
{ actor: { contains: query.search, mode: "insensitive" } },
|
||||
{ entityId: { contains: query.search, mode: "insensitive" } },
|
||||
];
|
||||
}
|
||||
|
||||
const [total, items] = await Promise.all([
|
||||
(this.prisma as any).auditLog.count({ where }),
|
||||
(this.prisma as any).auditLog.findMany({
|
||||
where,
|
||||
skip,
|
||||
take: limit,
|
||||
orderBy: { createdAt: "desc" },
|
||||
}),
|
||||
]);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: items,
|
||||
meta: {
|
||||
total,
|
||||
page,
|
||||
limit,
|
||||
totalPages: Math.ceil(total / limit),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@Get("recent")
|
||||
@ApiOperation({ summary: "آخرین رخدادهای سیستم برای ویجت داشبورد" })
|
||||
async getRecent(@Query("limit") limitParam?: string) {
|
||||
const limit = Number(limitParam) || 10;
|
||||
const items = await (this.prisma as any).auditLog.findMany({
|
||||
take: limit,
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
return { success: true, data: items };
|
||||
}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: "ثبت لاگ جدید در تاریخچه سیستم" })
|
||||
async create(@Body() body: any) {
|
||||
const item = await (this.prisma as any).auditLog.create({
|
||||
data: {
|
||||
entity: body.entity,
|
||||
entityId: body.entityId ? String(body.entityId) : null,
|
||||
action: body.action || "UPDATE",
|
||||
department: body.department || "system",
|
||||
actor: body.actor || "ADMIN",
|
||||
summary: body.summary,
|
||||
oldValues: body.oldValues || null,
|
||||
newValues: body.newValues || null,
|
||||
metadata: body.metadata || null,
|
||||
},
|
||||
});
|
||||
return { success: true, data: item };
|
||||
}
|
||||
}
|
||||
@@ -1,117 +0,0 @@
|
||||
import { BadRequestException, ConflictException, NotFoundException } from "@nestjs/common";
|
||||
import { BlogsService } from "./blogs.service";
|
||||
|
||||
// Stateful transactional double: deliberately interleave after snapshot read.
|
||||
// Complements the DB integration test; it does not assert PostgreSQL locking.
|
||||
describe("BlogsService atomic optimistic update", () => {
|
||||
const token = "2026-10-24T23:36:08.501Z";
|
||||
let row: any;
|
||||
let service: BlogsService;
|
||||
let prisma: any;
|
||||
let revalidate: jest.Mock;
|
||||
let afterRead: (() => void) | undefined;
|
||||
let failRelations: boolean;
|
||||
beforeEach(() => {
|
||||
row = { id: "b1", slug: "post", title: "Original", updatedAt: new Date(token), tags: ["old"] };
|
||||
afterRead = undefined;
|
||||
failRelations = false;
|
||||
const blog = {
|
||||
findUnique: jest.fn(async () => {
|
||||
const snapshot = { ...row };
|
||||
afterRead?.();
|
||||
return snapshot;
|
||||
}),
|
||||
updateMany: jest.fn(async ({ where, data }) => {
|
||||
if (row.updatedAt >= where.updatedAt.gte && row.updatedAt < where.updatedAt.lt) {
|
||||
row = { ...row, ...data };
|
||||
return { count: 1 };
|
||||
}
|
||||
return { count: 0 };
|
||||
}),
|
||||
update: jest.fn(async ({ data }) => {
|
||||
if (failRelations) throw new Error("relation failure");
|
||||
row = { ...row, ...data };
|
||||
return { ...row };
|
||||
}),
|
||||
};
|
||||
// Serialize transactions like row locks. Rollback restores only transaction writes.
|
||||
let tail = Promise.resolve();
|
||||
prisma = { blog, $transaction: jest.fn((cb) => {
|
||||
const next = tail.then(async () => {
|
||||
const before = { ...row };
|
||||
try { return await cb({ blog }); } catch (error) { row = before; throw error; }
|
||||
});
|
||||
tail = next.catch(() => undefined);
|
||||
return next;
|
||||
}) };
|
||||
revalidate = jest.fn().mockResolvedValue(true);
|
||||
service = new BlogsService(prisma, { revalidateBlog: revalidate } as any);
|
||||
});
|
||||
|
||||
it.each([null, 0, 123, true, {}, [], "", "garbage", "2026-02-30T00:00:00.000Z", "2026-10-24", "2026-10-24T23:36:08.501001Z"])("rejects invalid token %p without mutations", async (value) => {
|
||||
await expect(service.updateBlog("b1", { title: "bad", expectedUpdatedAt: value })).rejects.toBeInstanceOf(ConflictException);
|
||||
expect(prisma.blog.update).not.toHaveBeenCalled();
|
||||
expect(prisma.blog.updateMany).not.toHaveBeenCalled();
|
||||
expect(revalidate).not.toHaveBeenCalled();
|
||||
});
|
||||
it("rejects stale token and leaves all relations untouched", async () => {
|
||||
await expect(service.updateBlog("b1", { expectedUpdatedAt: "2026-10-20T00:00:00.000Z", tagNames: ["new"], categoryId: "c" })).rejects.toBeInstanceOf(ConflictException);
|
||||
expect(row.tags).toEqual(["old"]);
|
||||
expect(prisma.blog.update).not.toHaveBeenCalled();
|
||||
expect(revalidate).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each([token, "2026-10-25T01:36:08.501+02:00"])("accepts current token %s and atomically includes relations", async (expectedUpdatedAt) => {
|
||||
const result = await service.updateBlog("b1", { title: "new", expectedUpdatedAt, authorId: "a", categoryId: "c", tagNames: ["new"] });
|
||||
expect(result.title).toBe("new");
|
||||
expect(prisma.$transaction).toHaveBeenCalledTimes(1);
|
||||
expect(prisma.blog.updateMany).toHaveBeenCalledWith({ where: { id: "b1", updatedAt: { gte: new Date(token), lt: new Date(new Date(token).getTime() + 1) } }, data: { updatedAt: expect.any(Date) } });
|
||||
expect(prisma.blog.update.mock.calls[0][0].data).toMatchObject({ author: { connect: { id: "a" } }, category: { connect: { id: "c" } }, tags: { set: [], connectOrCreate: expect.any(Array) } });
|
||||
expect(prisma.blog.update.mock.calls[0][0].data).not.toHaveProperty("expectedUpdatedAt");
|
||||
expect(result.updatedAt.getTime()).toBeGreaterThan(new Date(token).getTime());
|
||||
expect(revalidate).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it("detects writer interleaving after read before write", async () => {
|
||||
afterRead = () => { row = { ...row, title: "winner", updatedAt: new Date("2026-10-24T23:36:08.502Z"), tags: ["winner"] }; };
|
||||
await expect(service.updateBlog("b1", { expectedUpdatedAt: token, title: "loser", tagNames: ["loser"] })).rejects.toBeInstanceOf(ConflictException);
|
||||
expect(row.title).toBe("winner");
|
||||
expect(row.tags).toEqual(["winner"]);
|
||||
expect(prisma.blog.update).not.toHaveBeenCalled();
|
||||
expect(revalidate).not.toHaveBeenCalled();
|
||||
});
|
||||
it("permits exactly one of two requests sharing a token", async () => {
|
||||
const results = await Promise.allSettled([service.updateBlog("b1", { expectedUpdatedAt: token, title: "a" }), service.updateBlog("b1", { expectedUpdatedAt: token, title: "b" })]);
|
||||
expect(results.filter(r => r.status === "fulfilled")).toHaveLength(1);
|
||||
const rejected = results.find(r => r.status === "rejected") as PromiseRejectedResult;
|
||||
expect(rejected.reason).toBeInstanceOf(ConflictException);
|
||||
expect(revalidate).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it("advances token even when clock is within same millisecond", async () => {
|
||||
jest.useFakeTimers().setSystemTime(new Date(token));
|
||||
try {
|
||||
await service.updateBlog("b1", { expectedUpdatedAt: token, title: "first" });
|
||||
await expect(service.updateBlog("b1", { expectedUpdatedAt: token, title: "second" })).rejects.toBeInstanceOf(ConflictException);
|
||||
} finally { jest.useRealTimers(); }
|
||||
});
|
||||
it("rolls back claim on nested relation failure without invalidating cache", async () => {
|
||||
failRelations = true;
|
||||
await expect(service.updateBlog("b1", { expectedUpdatedAt: token, tagNames: ["new"] })).rejects.toThrow("relation failure");
|
||||
expect(row.updatedAt.toISOString()).toBe(token);
|
||||
expect(row.tags).toEqual(["old"]);
|
||||
expect(revalidate).not.toHaveBeenCalled();
|
||||
});
|
||||
it("preserves legacy omission without demanding a token", async () => {
|
||||
await service.updateBlog("b1", { title: "legacy" });
|
||||
expect(row.title).toBe("legacy");
|
||||
expect(prisma.$transaction).not.toHaveBeenCalled();
|
||||
});
|
||||
it("returns 404 for a missing blog", async () => {
|
||||
prisma.blog.findUnique.mockResolvedValue(null);
|
||||
await expect(service.updateBlog("missing", { expectedUpdatedAt: token })).rejects.toBeInstanceOf(NotFoundException);
|
||||
});
|
||||
it("does not fail committed writes if revalidation throws", async () => {
|
||||
revalidate.mockRejectedValue(new Error("cache down"));
|
||||
const result = await service.updateBlog("b1", { expectedUpdatedAt: token, title: "saved" });
|
||||
expect(result.cacheRevalidation).toBe("failed");
|
||||
expect(row.title).toBe("saved");
|
||||
});
|
||||
});
|
||||
@@ -54,8 +54,6 @@ describe("Admin BlogsService", () => {
|
||||
}).compile();
|
||||
|
||||
service = module.get<BlogsService>(BlogsService);
|
||||
mockRevalidationService.revalidateBlog.mockReset();
|
||||
mockRevalidationService.revalidateBlog.mockResolvedValue(true);
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
@@ -202,10 +200,7 @@ describe("Admin BlogsService", () => {
|
||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith(
|
||||
"new-health-post",
|
||||
);
|
||||
expect(result).toEqual({
|
||||
...createdBlog,
|
||||
cacheRevalidation: "success",
|
||||
});
|
||||
expect(result).toEqual(createdBlog);
|
||||
});
|
||||
|
||||
it("allowlists create fields and blocks server-owned and unknown fields", async () => {
|
||||
@@ -277,66 +272,6 @@ describe("Admin BlogsService", () => {
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("should expose cacheRevalidation status on create result without failing persistence", async () => {
|
||||
const blogData = {
|
||||
title: "Health Post",
|
||||
slug: "health-post",
|
||||
content: "Content",
|
||||
};
|
||||
const createdBlog = { id: "blog-1", ...blogData };
|
||||
mockPrisma.blog.create.mockResolvedValue(createdBlog);
|
||||
mockRevalidationService.revalidateBlog.mockResolvedValue(true);
|
||||
|
||||
const result = await service.createBlog(blogData, "user-admin-1");
|
||||
|
||||
expect(mockPrisma.blog.create).toHaveBeenCalled();
|
||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith("health-post");
|
||||
expect(result).toEqual({
|
||||
...createdBlog,
|
||||
cacheRevalidation: "success",
|
||||
});
|
||||
});
|
||||
|
||||
it("should return cacheRevalidation 'failed' when revalidation fails without failing persistence", async () => {
|
||||
const blogData = {
|
||||
title: "Health Post",
|
||||
slug: "health-post",
|
||||
content: "Content",
|
||||
};
|
||||
const createdBlog = { id: "blog-1", ...blogData };
|
||||
mockPrisma.blog.create.mockResolvedValue(createdBlog);
|
||||
mockRevalidationService.revalidateBlog.mockResolvedValue(false);
|
||||
|
||||
const result = await service.createBlog(blogData, "user-admin-1");
|
||||
|
||||
expect(mockPrisma.blog.create).toHaveBeenCalled();
|
||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith("health-post");
|
||||
expect(result).toEqual({
|
||||
...createdBlog,
|
||||
cacheRevalidation: "failed",
|
||||
});
|
||||
});
|
||||
|
||||
it("should catch unexpected revalidation exceptions on create and return cacheRevalidation 'failed'", async () => {
|
||||
const blogData = {
|
||||
title: "Health Post",
|
||||
slug: "health-post",
|
||||
content: "Content",
|
||||
};
|
||||
const createdBlog = { id: "blog-1", ...blogData };
|
||||
mockPrisma.blog.create.mockResolvedValue(createdBlog);
|
||||
mockRevalidationService.revalidateBlog.mockRejectedValue(new Error("Frontend offline"));
|
||||
|
||||
const result = await service.createBlog(blogData, "user-admin-1");
|
||||
|
||||
expect(mockPrisma.blog.create).toHaveBeenCalled();
|
||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith("health-post");
|
||||
expect(result).toEqual({
|
||||
...createdBlog,
|
||||
cacheRevalidation: "failed",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("updateBlog", () => {
|
||||
@@ -379,61 +314,7 @@ describe("Admin BlogsService", () => {
|
||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith(
|
||||
"my-post",
|
||||
);
|
||||
expect(result).toEqual({
|
||||
...updated,
|
||||
cacheRevalidation: "success",
|
||||
});
|
||||
});
|
||||
|
||||
it("should expose cacheRevalidation status on update result without failing persistence", async () => {
|
||||
const existing = { id: "b1", slug: "my-post", title: "Old Title" };
|
||||
mockPrisma.blog.findUnique.mockResolvedValue(existing);
|
||||
const updated = { ...existing, title: "New Title" };
|
||||
mockPrisma.blog.update.mockResolvedValue(updated);
|
||||
mockRevalidationService.revalidateBlog.mockResolvedValue(true);
|
||||
|
||||
const result = await service.updateBlog("b1", { title: "New Title" });
|
||||
|
||||
expect(mockPrisma.blog.update).toHaveBeenCalled();
|
||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith("my-post");
|
||||
expect(result).toEqual({
|
||||
...updated,
|
||||
cacheRevalidation: "success",
|
||||
});
|
||||
});
|
||||
|
||||
it("should return cacheRevalidation 'failed' when revalidation fails on update without failing persistence", async () => {
|
||||
const existing = { id: "b1", slug: "my-post", title: "Old Title" };
|
||||
mockPrisma.blog.findUnique.mockResolvedValue(existing);
|
||||
const updated = { ...existing, title: "New Title" };
|
||||
mockPrisma.blog.update.mockResolvedValue(updated);
|
||||
mockRevalidationService.revalidateBlog.mockResolvedValue(false);
|
||||
|
||||
const result = await service.updateBlog("b1", { title: "New Title" });
|
||||
|
||||
expect(mockPrisma.blog.update).toHaveBeenCalled();
|
||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith("my-post");
|
||||
expect(result).toEqual({
|
||||
...updated,
|
||||
cacheRevalidation: "failed",
|
||||
});
|
||||
});
|
||||
|
||||
it("should catch unexpected revalidation exceptions on update and return cacheRevalidation 'failed'", async () => {
|
||||
const existing = { id: "b1", slug: "my-post", title: "Old Title" };
|
||||
mockPrisma.blog.findUnique.mockResolvedValue(existing);
|
||||
const updated = { ...existing, title: "New Title" };
|
||||
mockPrisma.blog.update.mockResolvedValue(updated);
|
||||
mockRevalidationService.revalidateBlog.mockRejectedValue(new Error("Revalidation timeout"));
|
||||
|
||||
const result = await service.updateBlog("b1", { title: "New Title" });
|
||||
|
||||
expect(mockPrisma.blog.update).toHaveBeenCalled();
|
||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith("my-post");
|
||||
expect(result).toEqual({
|
||||
...updated,
|
||||
cacheRevalidation: "failed",
|
||||
});
|
||||
expect(result).toEqual(updated);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
OnModuleInit,
|
||||
@@ -256,21 +255,8 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
},
|
||||
});
|
||||
|
||||
let cacheRevalidation: "success" | "failed" = "failed";
|
||||
try {
|
||||
const revalidated = await this.revalidationService.revalidateBlog(created.slug);
|
||||
cacheRevalidation = revalidated ? "success" : "failed";
|
||||
} catch (err: any) {
|
||||
this.logger.warn(
|
||||
`Cache revalidation failed for created blog [${created.slug}]: ${err?.message}`,
|
||||
);
|
||||
cacheRevalidation = "failed";
|
||||
}
|
||||
|
||||
return {
|
||||
...created,
|
||||
cacheRevalidation,
|
||||
};
|
||||
await this.revalidationService.revalidateBlog(created.slug);
|
||||
return created;
|
||||
}
|
||||
|
||||
async updateBlog(id: string, data: any) {
|
||||
@@ -286,30 +272,8 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
readingTime,
|
||||
markContentUpdated,
|
||||
contentUpdatedAt,
|
||||
expectedUpdatedAt,
|
||||
} = data;
|
||||
|
||||
const conflict = () => new ConflictException(
|
||||
"CONCURRENT_MODIFICATION: Blog has been modified by another process",
|
||||
);
|
||||
let expectedTime: number | undefined;
|
||||
if (expectedUpdatedAt !== undefined) {
|
||||
// Only accept the millisecond, timezone-qualified ISO token returned by GET
|
||||
// (or an equivalent offset). Avoid Date's coercion of null, numbers, arrays,
|
||||
// and its normalization of impossible calendar dates.
|
||||
const match = typeof expectedUpdatedAt === "string" && expectedUpdatedAt.match(
|
||||
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?(Z|[+-]\d{2}:\d{2})$/,
|
||||
);
|
||||
if (!match) throw conflict();
|
||||
expectedTime = Date.parse(expectedUpdatedAt);
|
||||
const calendar = new Date(`${match[1]}-${match[2]}-${match[3]}T00:00:00.000Z`);
|
||||
if (!Number.isFinite(expectedTime) ||
|
||||
calendar.toISOString().slice(0, 10) !== `${match[1]}-${match[2]}-${match[3]}` ||
|
||||
Number(match[4]) > 23 || Number(match[5]) > 59 || Number(match[6]) > 59) {
|
||||
throw conflict();
|
||||
}
|
||||
}
|
||||
|
||||
const mutableScalarFields = [
|
||||
"title",
|
||||
"slug",
|
||||
@@ -426,68 +390,25 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
};
|
||||
}
|
||||
|
||||
const include = {
|
||||
author: { select: { firstName: true, lastName: true } },
|
||||
category: true,
|
||||
tags: true,
|
||||
};
|
||||
// Legacy UI requests without a token intentionally retain last-write-wins.
|
||||
// Guarded requests claim the row using a DB predicate, not the earlier read.
|
||||
const updated = expectedTime === undefined
|
||||
? await this.prisma.blog.update({ where: { id }, data: updatePayload, include })
|
||||
: await this.prisma.$transaction(async (tx) => {
|
||||
// PostgreSQL timestamptz defaults to microseconds; JSON/JS Dates expose
|
||||
// milliseconds. Match the entire represented millisecond, then move
|
||||
// strictly beyond it (including same-ms writes and clock rollback).
|
||||
const claimedAt = new Date(Math.max(Date.now(), expectedTime + 1));
|
||||
const claim = await tx.blog.updateMany({
|
||||
where: {
|
||||
id,
|
||||
updatedAt: {
|
||||
gte: new Date(expectedTime),
|
||||
lt: new Date(expectedTime + 1),
|
||||
},
|
||||
},
|
||||
data: { updatedAt: claimedAt },
|
||||
});
|
||||
if (claim.count !== 1) throw conflict();
|
||||
// The claim holds the row lock until this nested mutation commits.
|
||||
// Any relation failure rolls back both the claim and all data writes.
|
||||
return tx.blog.update({
|
||||
where: { id },
|
||||
data: { ...updatePayload, updatedAt: claimedAt },
|
||||
include,
|
||||
});
|
||||
});
|
||||
const updated = await this.prisma.blog.update({
|
||||
where: { id },
|
||||
data: updatePayload,
|
||||
include: {
|
||||
author: { select: { firstName: true, lastName: true } },
|
||||
category: true,
|
||||
tags: true,
|
||||
},
|
||||
});
|
||||
|
||||
let cacheRevalidation: "success" | "failed" = "failed";
|
||||
try {
|
||||
const revalidated = await this.revalidationService.revalidateBlog(updated.slug);
|
||||
cacheRevalidation = revalidated ? "success" : "failed";
|
||||
} catch (err: any) {
|
||||
this.logger.warn(
|
||||
`Cache revalidation failed for updated blog [${updated.slug}]: ${err?.message}`,
|
||||
);
|
||||
cacheRevalidation = "failed";
|
||||
}
|
||||
|
||||
return {
|
||||
...updated,
|
||||
cacheRevalidation,
|
||||
};
|
||||
await this.revalidationService.revalidateBlog(updated.slug);
|
||||
return updated;
|
||||
}
|
||||
|
||||
async deleteBlog(id: string) {
|
||||
const blog = await this.prisma.blog.findUnique({ where: { id } });
|
||||
if (!blog) throw new NotFoundException("Blog not found");
|
||||
const res = await this.prisma.blog.delete({ where: { id } });
|
||||
try {
|
||||
await this.revalidationService.revalidateBlog(blog.slug);
|
||||
} catch (err: any) {
|
||||
this.logger.warn(
|
||||
`Cache revalidation failed for deleted blog [${blog.slug}]: ${err?.message}`,
|
||||
);
|
||||
}
|
||||
await this.revalidationService.revalidateBlog(blog.slug);
|
||||
return res;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import { BadRequestException } from "@nestjs/common";
|
||||
import { assertTaskCanComplete } from "./department-task-completion.policy";
|
||||
|
||||
describe("department task completion policy", () => {
|
||||
it("rejects model-only output without a live deliverable", () => {
|
||||
expect(() =>
|
||||
assertTaskCanComplete({
|
||||
deliverableUrl: null,
|
||||
acceptanceCriteria: { criteria: ["live URL responds 200"] },
|
||||
executionLogs: [{ status: "COMPLETED_BY_AGENT" }],
|
||||
}),
|
||||
).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("rejects completion without acceptance criteria", () => {
|
||||
expect(() =>
|
||||
assertTaskCanComplete({
|
||||
deliverableUrl: "https://canina.ir/blog/verified",
|
||||
acceptanceCriteria: null,
|
||||
executionLogs: [{ status: "QA_PASSED" }],
|
||||
}),
|
||||
).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("rejects completion without QA evidence", () => {
|
||||
expect(() =>
|
||||
assertTaskCanComplete({
|
||||
deliverableUrl: "https://canina.ir/blog/verified",
|
||||
acceptanceCriteria: { criteria: ["HTTP 200"] },
|
||||
executionLogs: [{ status: "COMPLETED_BY_AGENT" }],
|
||||
}),
|
||||
).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("allows completion with URL, criteria and QA evidence", () => {
|
||||
expect(() =>
|
||||
assertTaskCanComplete({
|
||||
deliverableUrl: "https://canina.ir/blog/verified",
|
||||
acceptanceCriteria: { criteria: ["HTTP 200"] },
|
||||
executionLogs: [{ status: "QA_PASSED" }],
|
||||
}),
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it("rejects pseudo-protocol canina:// deliverable URLs", () => {
|
||||
expect(() =>
|
||||
assertTaskCanComplete({
|
||||
deliverableUrl: "canina://blog/sample-article",
|
||||
acceptanceCriteria: { criteria: ["HTTP 200"] },
|
||||
executionLogs: [{ status: "QA_PASSED" }],
|
||||
}),
|
||||
).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("rejects git://stage staging or repo URLs as verifiable deliverable", () => {
|
||||
expect(() =>
|
||||
assertTaskCanComplete({
|
||||
deliverableUrl: "git://stage/canina-repo#commit123",
|
||||
acceptanceCriteria: { criteria: ["HTTP 200"] },
|
||||
executionLogs: [{ status: "QA_PASSED" }],
|
||||
}),
|
||||
).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("rejects missing or placeholder post-tsk article deliverables", () => {
|
||||
expect(() =>
|
||||
assertTaskCanComplete({
|
||||
deliverableUrl: "https://canina.ir/blog/post-tsk-49102",
|
||||
acceptanceCriteria: { criteria: ["HTTP 200"] },
|
||||
executionLogs: [{ status: "QA_PASSED" }],
|
||||
}),
|
||||
).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("rejects completion when QA evidence reports missing article or 404 error", () => {
|
||||
expect(() =>
|
||||
assertTaskCanComplete({
|
||||
deliverableUrl: "https://canina.ir/blog/verified-article",
|
||||
acceptanceCriteria: { criteria: ["HTTP 200"] },
|
||||
executionLogs: [{ status: "QA_PASSED", note: "HTTP 404 - مقاله یافت نشد" }],
|
||||
}),
|
||||
).toThrow(BadRequestException);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
import { BadRequestException } from "@nestjs/common";
|
||||
|
||||
export interface CompletableTask {
|
||||
code?: string | null;
|
||||
title?: string | null;
|
||||
deliverableUrl?: string | null;
|
||||
acceptanceCriteria?: unknown;
|
||||
executionLogs?: unknown;
|
||||
}
|
||||
|
||||
function hasAcceptanceCriteria(criteria: unknown): boolean {
|
||||
if (!criteria) return false;
|
||||
if (typeof criteria === "string") return criteria.trim().length > 0;
|
||||
if (Array.isArray(criteria)) return criteria.length > 0;
|
||||
if (typeof criteria === "object") {
|
||||
const value = criteria as Record<string, unknown>;
|
||||
const items = value.criteria;
|
||||
return Array.isArray(items) ? items.length > 0 : Object.keys(value).length > 0;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function hasValidQaEvidence(logs: unknown): boolean {
|
||||
if (!Array.isArray(logs)) return false;
|
||||
const validPassStatuses = ["QA_PASSED", "VERIFIED", "PRODUCTION_VERIFIED"];
|
||||
|
||||
let foundValidPass = false;
|
||||
for (const log of logs) {
|
||||
if (!log || typeof log !== "object") continue;
|
||||
const entry = log as Record<string, unknown>;
|
||||
const status = String(entry.status || "").toUpperCase();
|
||||
const note = String(entry.note || "").toLowerCase();
|
||||
|
||||
// Rejection of invalid QA claims: 404, missing article, not found, post-tsk
|
||||
if (
|
||||
note.includes("404") ||
|
||||
note.includes("مقاله یافت نشد") ||
|
||||
note.includes("not found") ||
|
||||
note.includes("missing article") ||
|
||||
note.includes("post-tsk")
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (validPassStatuses.includes(status)) {
|
||||
foundValidPass = true;
|
||||
}
|
||||
}
|
||||
return foundValidPass;
|
||||
}
|
||||
|
||||
export function assertTaskCanComplete(task: CompletableTask): void {
|
||||
const rawUrl = task.deliverableUrl?.trim();
|
||||
if (!rawUrl) {
|
||||
throw new BadRequestException("DONE requires a verifiable deliverable URL");
|
||||
}
|
||||
|
||||
const lowerUrl = rawUrl.toLowerCase();
|
||||
|
||||
// Reject internal pseudo-protocols
|
||||
if (lowerUrl.startsWith("canina://") || lowerUrl.includes("canina://")) {
|
||||
throw new BadRequestException("Deliverable URL cannot use pseudo-protocol canina://; an independently verifiable HTTP(S) URL is required");
|
||||
}
|
||||
|
||||
// Reject git repository pointers or staging branches as production deliverables
|
||||
if (lowerUrl.startsWith("git://") || lowerUrl.includes("git://stage")) {
|
||||
throw new BadRequestException("Deliverable URL cannot be a git staging reference; an independently verifiable HTTP(S) URL is required");
|
||||
}
|
||||
|
||||
// Must be an HTTP or HTTPS URL
|
||||
if (!lowerUrl.startsWith("http://") && !lowerUrl.startsWith("https://")) {
|
||||
throw new BadRequestException("DONE requires an independently verifiable HTTP or HTTPS deliverable URL");
|
||||
}
|
||||
|
||||
// Reject deleted or placeholder post-tsk articles
|
||||
if (/post[-_]?tsk/i.test(rawUrl)) {
|
||||
throw new BadRequestException("Deliverable URL references an unverified or deleted post-tsk placeholder article");
|
||||
}
|
||||
if (task.title && /post[-_]?tsk/i.test(task.title)) {
|
||||
throw new BadRequestException("Task references an unverified or deleted post-tsk article");
|
||||
}
|
||||
if (task.code && /post[-_]?tsk/i.test(task.code)) {
|
||||
throw new BadRequestException("Task references an unverified or deleted post-tsk code");
|
||||
}
|
||||
|
||||
if (!hasAcceptanceCriteria(task.acceptanceCriteria)) {
|
||||
throw new BadRequestException("DONE requires explicit acceptance criteria");
|
||||
}
|
||||
|
||||
if (!hasValidQaEvidence(task.executionLogs)) {
|
||||
throw new BadRequestException("DONE requires QA/production verification evidence");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { GoneException } from '@nestjs/common';
|
||||
import { DepartmentTasksController } from './department-tasks.controller';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
describe('DepartmentTasksController retired mutation boundary',()=>{
|
||||
const access=jest.fn();
|
||||
const prisma=new Proxy({},{get:(_target,key)=>{access(key);throw new Error('Database access forbidden');}});
|
||||
const controller=new DepartmentTasksController(prisma as PrismaService);
|
||||
beforeEach(()=>access.mockClear());
|
||||
it('create {department:SEO,title:Legacy} returns 410 without reading or writing persistence',async()=>{
|
||||
await expect(controller.create({department:'SEO',title:'Legacy'})).rejects.toBeInstanceOf(GoneException);
|
||||
await expect(controller.create({department:'SEO',title:'Legacy'})).rejects.toMatchObject({status:410});
|
||||
expect(access).not.toHaveBeenCalled();
|
||||
});
|
||||
it('updateStatus missing, {status:DONE} returns 410 without reading or writing persistence',async()=>{
|
||||
await expect(controller.updateStatus('missing', {status:'DONE'})).rejects.toBeInstanceOf(GoneException);
|
||||
await expect(controller.updateStatus('missing', {status:'DONE'})).rejects.toMatchObject({status:410});
|
||||
expect(access).not.toHaveBeenCalled();
|
||||
});
|
||||
it('updateStatus missing, {status:TODO} returns 410 without reading or writing persistence',async()=>{
|
||||
await expect(controller.updateStatus('missing', {status:'TODO'})).rejects.toBeInstanceOf(GoneException);
|
||||
await expect(controller.updateStatus('missing', {status:'TODO'})).rejects.toMatchObject({status:410});
|
||||
expect(access).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,127 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Put,
|
||||
Body,
|
||||
Param,
|
||||
Query,
|
||||
UseGuards,
|
||||
NotFoundException,
|
||||
GoneException,
|
||||
} from "@nestjs/common";
|
||||
import { ApiTags, ApiBearerAuth, ApiOperation } from "@nestjs/swagger";
|
||||
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
|
||||
import { RolesGuard } from "../common/guards/roles.guard";
|
||||
import { Roles } from "../common/decorators/roles.decorator";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
|
||||
@ApiTags("Admin - Department & Agent Tasks")
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles("Admin", "SUPER_ADMIN")
|
||||
@Controller("admin/department-tasks")
|
||||
export class DepartmentTasksController {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: "لیست تسکهای دپارتمانها و ایجنتها" })
|
||||
async findAll(@Query() query: any) {
|
||||
const page = Number(query.page) || 1;
|
||||
const limit = Number(query.limit) || 100;
|
||||
const skip = (page - 1) * limit;
|
||||
|
||||
const where: any = {};
|
||||
if (query.department) where.department = query.department;
|
||||
if (query.status) where.status = query.status;
|
||||
if (query.priority) where.priority = query.priority;
|
||||
if (query.search) {
|
||||
where.OR = [
|
||||
{ code: { contains: query.search, mode: "insensitive" } },
|
||||
{ title: { contains: query.search, mode: "insensitive" } },
|
||||
{ description: { contains: query.search, mode: "insensitive" } },
|
||||
];
|
||||
}
|
||||
|
||||
const [total, items] = await Promise.all([
|
||||
(this.prisma as any).departmentTask.count({ where }),
|
||||
(this.prisma as any).departmentTask.findMany({
|
||||
where,
|
||||
skip,
|
||||
take: limit,
|
||||
orderBy: [{ priority: "desc" }, { createdAt: "desc" }],
|
||||
}),
|
||||
]);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: items,
|
||||
meta: {
|
||||
total,
|
||||
page,
|
||||
limit,
|
||||
totalPages: Math.ceil(total / limit),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@Get("stats")
|
||||
@ApiOperation({ summary: "آمار تسکها به تفکیک استیت و دپارتمان" })
|
||||
async getStats() {
|
||||
const tasks = await (this.prisma as any).departmentTask.findMany({
|
||||
select: { department: true, status: true, priority: true },
|
||||
});
|
||||
|
||||
const statusCounts: Record<string, number> = {
|
||||
TODO: 0,
|
||||
IN_PROGRESS: 0,
|
||||
TEST: 0,
|
||||
DONE: 0,
|
||||
BACKLOG: 0,
|
||||
IN_REVIEW: 0,
|
||||
APPROVED: 0,
|
||||
DEPLOYING: 0,
|
||||
};
|
||||
const departmentCounts: Record<string, number> = {};
|
||||
|
||||
for (const t of tasks) {
|
||||
statusCounts[t.status] = (statusCounts[t.status] || 0) + 1;
|
||||
departmentCounts[t.department] = (departmentCounts[t.department] || 0) + 1;
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
total: tasks.length,
|
||||
byStatus: statusCounts,
|
||||
byDepartment: departmentCounts,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@Get(":id")
|
||||
@ApiOperation({ summary: "دریافت جزییات یک تسک" })
|
||||
async findOne(@Param("id") id: string) {
|
||||
const task = await (this.prisma as any).departmentTask.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
if (!task) throw new NotFoundException(`Task ${id} not found`);
|
||||
return { success: true, data: task };
|
||||
}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: "ایجاد تسک جدید سازمانی" })
|
||||
async create(@Body() body: any) {
|
||||
throw new GoneException("Legacy orchestration mutations are retired. Orchestration v4 remains read-only; no replacement mutation is enabled.");
|
||||
}
|
||||
|
||||
@Put(":id/status")
|
||||
@ApiOperation({ summary: "تغییر وضعیت تسک همراه با لاگ اجرا" })
|
||||
async updateStatus(
|
||||
@Param("id") id: string,
|
||||
@Body() body: { status: string; logNote?: string; deliverableUrl?: string }
|
||||
) {
|
||||
throw new GoneException("Legacy orchestration mutations are retired. Orchestration v4 remains read-only; no replacement mutation is enabled.");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsString, IsOptional, IsObject } from "class-validator";
|
||||
|
||||
export class CreateApprovalRequestDto {
|
||||
@ApiProperty({ description: "دپارتمان مبدا (DEV, SUPPLY, FINANCE, SEO, CRM, CONTENT)" })
|
||||
@IsString()
|
||||
department: string;
|
||||
|
||||
@ApiProperty({ description: "دستهبندی (PRICING, PURCHASE_ORDER, CAMPAIGN, DEPLOY, etc)" })
|
||||
@IsString()
|
||||
category: string;
|
||||
|
||||
@ApiProperty({ description: "عنوان مورد تایید" })
|
||||
@IsString()
|
||||
title: string;
|
||||
|
||||
@ApiProperty({ description: "دادههای تغییرات پیشنهادی" })
|
||||
@IsObject()
|
||||
payload: Record<string, any>;
|
||||
|
||||
@ApiPropertyOptional({ description: "دادههای سناریوی تست و ارزیابی" })
|
||||
@IsOptional()
|
||||
@IsObject()
|
||||
testContext?: Record<string, any>;
|
||||
}
|
||||
|
||||
export class DecideApprovalDto {
|
||||
@ApiProperty({ description: "تصمیم: APPROVED یا REJECTED" })
|
||||
@IsString()
|
||||
decision: "APPROVED" | "REJECTED";
|
||||
|
||||
@ApiPropertyOptional({ description: "توضیحات و یادداشت مدیرعامل" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
ceoNotes?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "نتیجه اقدام مدیریتی یا استراتژیک" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
outcome?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "مستندات و مدرک اقدام مدیریتی" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
evidence?: string;
|
||||
}
|
||||
|
||||
export class QueryApprovalDto {
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
department?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
category?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
status?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
page?: number;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
limit?: number;
|
||||
}
|
||||
@@ -5,12 +5,9 @@ import {
|
||||
IsEmail,
|
||||
MinLength,
|
||||
IsNumber,
|
||||
IsIn,
|
||||
} from "class-validator";
|
||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
|
||||
import { ALLOWED_USER_ROLES } from "../user-role-policy";
|
||||
|
||||
export class CreateUserDto {
|
||||
@ApiProperty({ description: "نام کاربر", example: "علی" })
|
||||
@IsNotEmpty({ message: "نام الزامی است" })
|
||||
@@ -44,7 +41,6 @@ export class CreateUserDto {
|
||||
@ApiPropertyOptional({ description: "نقش کاربر", example: "User_PetOwner" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@IsIn(ALLOWED_USER_ROLES)
|
||||
role?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "موجودی اولیه کیف پول", example: 0 })
|
||||
@@ -89,7 +85,6 @@ export class UpdateUserDto {
|
||||
@ApiPropertyOptional({ description: "نقش کاربر", example: "User_PetOwner" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@IsIn(ALLOWED_USER_ROLES)
|
||||
role?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "موجودی کیف پول", example: 500000 })
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
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 ه');
|
||||
});
|
||||
it('bounds pagination and sort keys', () => {
|
||||
expect(pagination({ limit: '100' }).limit).toBe(100);
|
||||
expect(() => pagination({ limit: '101' })).toThrow();
|
||||
expect(() => pagination({ page: '-1' })).toThrow();
|
||||
expect(() => pagination({ sortBy: 'password' })).toThrow();
|
||||
});
|
||||
it('defaults CEO priority and rejects status/command injection', () => {
|
||||
expect(
|
||||
taskInput({
|
||||
title: 'عنوان',
|
||||
description: 'کار',
|
||||
department: 'CONTENT_SEO',
|
||||
}).priority,
|
||||
).toBe('CEO_EXPEDITE');
|
||||
expect(() =>
|
||||
taskInput({
|
||||
title: 'x',
|
||||
description: 'x',
|
||||
department: 'CONTENT_SEO',
|
||||
status: 'DONE',
|
||||
}),
|
||||
).toThrow();
|
||||
expect(() =>
|
||||
taskInput({ title: '', description: 'x', department: 'CONTENT_SEO' }),
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -1,317 +0,0 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
export const departments = [
|
||||
'CONTENT_SEO',
|
||||
'CATALOG_COMMERCE',
|
||||
'WIKI_SCIENTIFIC',
|
||||
'TECH_DEVOPS',
|
||||
'MARKET_INTELLIGENCE',
|
||||
];
|
||||
export const priorities = ['CEO_EXPEDITE', 'CRITICAL', 'HIGH', 'MEDIUM', 'LOW'];
|
||||
export const statuses = [
|
||||
'TODO',
|
||||
'IN_PROGRESS',
|
||||
'TEST',
|
||||
'DONE',
|
||||
'BLOCKED',
|
||||
'REJECTED',
|
||||
'CANCELLED',
|
||||
];
|
||||
export function object(value: unknown, keys: string[]): Record<string, any> {
|
||||
if (
|
||||
!value ||
|
||||
typeof value !== 'object' ||
|
||||
Array.isArray(value) ||
|
||||
Object.keys(value).some((k) => !keys.includes(k))
|
||||
)
|
||||
throw new BadRequestException('Invalid fields');
|
||||
return value as Record<string, any>;
|
||||
}
|
||||
export function text(value: unknown, max = 10000): string {
|
||||
if (typeof value !== 'string' || !value.trim() || value.length > max)
|
||||
throw new BadRequestException('Invalid text');
|
||||
return value.trim();
|
||||
}
|
||||
export function uuid(value: unknown): string {
|
||||
const id = text(value, 36);
|
||||
if (
|
||||
!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(
|
||||
id,
|
||||
)
|
||||
)
|
||||
throw new BadRequestException('Invalid UUID');
|
||||
return id.toLowerCase();
|
||||
}
|
||||
export function choice(value: unknown, values: string[]): string {
|
||||
if (typeof value !== 'string' || !values.includes(value))
|
||||
throw new BadRequestException('Invalid enum');
|
||||
return value;
|
||||
}
|
||||
export function normalizeSearch(value: string): string {
|
||||
return value
|
||||
.normalize('NFKC')
|
||||
.toLowerCase()
|
||||
.replace(/[يى]/g, 'ی')
|
||||
.replace(/ك/g, 'ک')
|
||||
.replace(/ة/g, 'ه')
|
||||
.replace(/[۰-۹٠-٩]/g, (c) =>
|
||||
String(
|
||||
'۰۱۲۳۴۵۶۷۸۹'.includes(c)
|
||||
? '۰۱۲۳۴۵۶۷۸۹'.indexOf(c)
|
||||
: '٠١٢٣٤٥٦٧٨٩'.indexOf(c),
|
||||
),
|
||||
)
|
||||
.replace(/[\u200c\u200d()()]/g, ' ')
|
||||
.replace(/[\u064b-\u065f]/g, '')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
}
|
||||
export function pagination(q: Record<string, any>) {
|
||||
const page = Number(q.page ?? 1),
|
||||
limit = Number(q.limit ?? 20);
|
||||
if (
|
||||
!Number.isSafeInteger(page) ||
|
||||
page < 1 ||
|
||||
page > 1000000 ||
|
||||
!Number.isInteger(limit) ||
|
||||
limit < 1 ||
|
||||
limit > 100
|
||||
)
|
||||
throw new BadRequestException('Invalid pagination');
|
||||
const sortBy = choice(q.sortBy ?? 'createdAt', [
|
||||
'createdAt',
|
||||
'updatedAt',
|
||||
'title',
|
||||
'taskCode',
|
||||
'priority',
|
||||
'status',
|
||||
]);
|
||||
const sortOrder = choice(q.sortOrder ?? 'desc', ['asc', 'desc']) as
|
||||
| 'asc'
|
||||
| 'desc';
|
||||
return { page, limit, skip: (page - 1) * limit, sortBy, sortOrder };
|
||||
}
|
||||
export function meta(total: number, page: number, limit: number) {
|
||||
const totalPages = Math.ceil(total / limit);
|
||||
return {
|
||||
total,
|
||||
page,
|
||||
limit,
|
||||
totalPages,
|
||||
hasNextPage: page < totalPages,
|
||||
hasPrevPage: page > 1,
|
||||
};
|
||||
}
|
||||
export function taskInput(input: unknown) {
|
||||
const b = object(input, [
|
||||
'title',
|
||||
'department',
|
||||
'description',
|
||||
'priority',
|
||||
'parentId',
|
||||
'goalId',
|
||||
'actionType',
|
||||
'dueCycle',
|
||||
]);
|
||||
return {
|
||||
title: text(b.title, 300),
|
||||
description: text(b.description),
|
||||
department: choice(b.department, departments),
|
||||
priority: choice(b.priority ?? 'CEO_EXPEDITE', priorities),
|
||||
parentId: b.parentId === undefined ? undefined : uuid(b.parentId),
|
||||
goalId: b.goalId === undefined ? undefined : uuid(b.goalId),
|
||||
actionType: choice(b.actionType ?? 'CEO_DIRECTIVE', [
|
||||
'CEO_DIRECTIVE',
|
||||
'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')
|
||||
return (
|
||||
'{' +
|
||||
Object.keys(value)
|
||||
.sort()
|
||||
.map((k) => JSON.stringify(k) + ':' + canonical(value[k]))
|
||||
.join(',') +
|
||||
'}'
|
||||
);
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
/** Public projection must also cover nested evidence and child records. */
|
||||
export function publicData(value: any): any {
|
||||
if (value instanceof Date) return value;
|
||||
if (Array.isArray(value)) return value.map(publicData);
|
||||
if (value && typeof value === 'object')
|
||||
return Object.fromEntries(
|
||||
Object.entries(value)
|
||||
.filter(([key]) => key !== 'claimToken')
|
||||
.map(([key, item]) => [key, publicData(item)]),
|
||||
);
|
||||
return value;
|
||||
}
|
||||
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();
|
||||
const u = new URL(raw);
|
||||
const host = u.hostname.toLowerCase();
|
||||
if (
|
||||
u.protocol !== 'https:' ||
|
||||
u.username ||
|
||||
u.password ||
|
||||
!/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/.test(host) ||
|
||||
host === 'localhost' ||
|
||||
host.endsWith('.localhost') ||
|
||||
/(^|\.)example\.(com|org|net)$/.test(host)
|
||||
)
|
||||
throw new Error();
|
||||
return raw;
|
||||
} catch {
|
||||
throw new BadRequestException('Valid HTTPS host URL required');
|
||||
}
|
||||
}
|
||||
export function timestamp(value: unknown, message: string): Date {
|
||||
if (
|
||||
typeof value !== 'string' ||
|
||||
!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/.test(value)
|
||||
)
|
||||
throw new BadRequestException(message);
|
||||
const date = new Date(value);
|
||||
if (
|
||||
!Number.isFinite(date.getTime()) ||
|
||||
date.getTime() > Date.now() ||
|
||||
date.toISOString().slice(0, 19) !== value.slice(0, 19)
|
||||
)
|
||||
throw new BadRequestException(message);
|
||||
return date;
|
||||
}
|
||||
export function evidenceInput(input: unknown) {
|
||||
const b = object(input, [
|
||||
'claimToken',
|
||||
'artifactUri',
|
||||
'sha256',
|
||||
'summary',
|
||||
'tool',
|
||||
'result',
|
||||
]);
|
||||
const uri = text(b.artifactUri, 2000);
|
||||
|
||||
const sha = text(b.sha256, 64);
|
||||
if (!/^[a-f0-9]{64}$/.test(sha))
|
||||
throw new BadRequestException('Invalid digest');
|
||||
if (uri.startsWith('urn:')) {
|
||||
if (uri !== 'urn:sha256:' + sha)
|
||||
throw new BadRequestException('Digest locator mismatch');
|
||||
} else httpsUrl(uri);
|
||||
return {
|
||||
claimToken: uuid(b.claimToken),
|
||||
artifactUri: uri,
|
||||
sha256: sha,
|
||||
summary: text(b.summary),
|
||||
tool: text(b.tool, 100),
|
||||
result: text(b.result),
|
||||
};
|
||||
}
|
||||
@@ -1,138 +0,0 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
Headers,
|
||||
Param,
|
||||
Post,
|
||||
Query,
|
||||
Req,
|
||||
UnauthorizedException,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { JwtAuthGuard } from '../../auth/jwt-auth.guard';
|
||||
import { RolesGuard } from '../../common/guards/roles.guard';
|
||||
import { Roles } from '../../common/decorators/roles.decorator';
|
||||
import { CorporateService } from './corporate.service';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { text } from './corporate-policy';
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin', 'SUPER_ADMIN')
|
||||
@Controller('admin/hermes')
|
||||
export class CorporateController {
|
||||
constructor(private readonly service: CorporateService) {}
|
||||
private actor(req: any) {
|
||||
// API keys must use their authenticated key identity, not an editable worker label.
|
||||
const user = req.user;
|
||||
const id = user?.id ?? user?.sub;
|
||||
if (!id) throw new UnauthorizedException('Authenticated subject required');
|
||||
return (user.isApiKey ? 'apikey:' : 'user:') + text(String(id), 200);
|
||||
}
|
||||
private key(key?: string) {
|
||||
return text(key, 200);
|
||||
}
|
||||
@Get('runtime') runtime() {
|
||||
return {
|
||||
mode: 'MANUAL_DORMANT',
|
||||
schedulesEnabled: false,
|
||||
externalExecutionEnabled: false,
|
||||
};
|
||||
}
|
||||
@Get('tasks') tasks(@Query() query: Record<string, any>) {
|
||||
return this.service.tasks(query);
|
||||
}
|
||||
@Get('tasks/:id') detail(@Param('id') id: string) {
|
||||
return this.service.detail(id);
|
||||
}
|
||||
@Post('tasks') create(
|
||||
@Req() req: any,
|
||||
@Headers('idempotency-key') key: string,
|
||||
@Body() body: unknown,
|
||||
) {
|
||||
return this.service.create(this.actor(req), key ?? randomUUID(), body);
|
||||
}
|
||||
@Post('claims') claim(
|
||||
@Req() req: any,
|
||||
@Headers('idempotency-key') key: string,
|
||||
@Body() body: unknown,
|
||||
) {
|
||||
return this.service.claim(this.actor(req), this.key(key), body);
|
||||
}
|
||||
@Post('tasks/:id/evidence') evidence(
|
||||
@Req() req: any,
|
||||
@Headers('idempotency-key') key: string,
|
||||
@Param('id') id: string,
|
||||
@Body() body: unknown,
|
||||
) {
|
||||
return this.service.submitEvidence(
|
||||
this.actor(req),
|
||||
this.key(key),
|
||||
id,
|
||||
body,
|
||||
);
|
||||
}
|
||||
@Post('tasks/:id/reviews') review(
|
||||
@Req() req: any,
|
||||
@Headers('idempotency-key') key: string,
|
||||
@Param('id') id: string,
|
||||
@Body() body: unknown,
|
||||
) {
|
||||
return this.service.review(this.actor(req), this.key(key), id, body);
|
||||
}
|
||||
@Post('tasks/:id/effects') effect(
|
||||
@Req() req: any,
|
||||
@Headers('idempotency-key') key: string,
|
||||
@Param('id') id: string,
|
||||
@Body() body: unknown,
|
||||
) {
|
||||
return this.service.effect(this.actor(req), this.key(key), id, body);
|
||||
}
|
||||
@Get('market-insights') insights(@Query() q: Record<string, any>) {
|
||||
return this.service.collection('market-insights', q);
|
||||
}
|
||||
@Post('market-insights') research(
|
||||
@Req() req: any,
|
||||
@Headers('idempotency-key') key: string,
|
||||
@Body() body: unknown,
|
||||
) {
|
||||
return this.service.research(this.actor(req), this.key(key), body);
|
||||
}
|
||||
@Get('monthly-roadmap') roadmaps(@Query() q: Record<string, any>) {
|
||||
return this.service.collection('monthly-roadmap', q);
|
||||
}
|
||||
@Post('monthly-roadmap') roadmap(
|
||||
@Req() req: any,
|
||||
@Headers('idempotency-key') key: string,
|
||||
@Body() body: unknown,
|
||||
) {
|
||||
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);
|
||||
}
|
||||
@Post('reports') report(
|
||||
@Req() req: any,
|
||||
@Headers('idempotency-key') key: string,
|
||||
@Body() body: unknown,
|
||||
) {
|
||||
return this.service.report(this.actor(req), this.key(key), body);
|
||||
}
|
||||
}
|
||||
@@ -1,969 +0,0 @@
|
||||
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 { createHash, randomUUID } from 'crypto';
|
||||
import { canonical } from './corporate-policy';
|
||||
import request from 'supertest';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { CorporateController } from './corporate.controller';
|
||||
import { CorporateService } from './corporate.service';
|
||||
import { ApiKeysService } from '../api-keys.service';
|
||||
|
||||
const integration = process.env.CORPORATE_TEST_DATABASE_URL
|
||||
? describe
|
||||
: describe.skip;
|
||||
integration('corporate API / disposable PostgreSQL', () => {
|
||||
let app: INestApplication, db: PrismaService;
|
||||
const key = () => randomUUID();
|
||||
const post = (path: string, body: any, actor = 'executor', op = key()) =>
|
||||
request(app.getHttpServer())
|
||||
.post('/admin/hermes/' + path)
|
||||
.set('x-api-key', actor)
|
||||
.set('Idempotency-Key', op)
|
||||
.send(body);
|
||||
const input = {
|
||||
title: 'كيك ۱۲۳',
|
||||
description: 'integration fixture',
|
||||
department: 'CONTENT_SEO',
|
||||
};
|
||||
beforeAll(async () => {
|
||||
// Explicit disposable loopback opt-in only; never consumes runtime DATABASE_URL.
|
||||
const url = new URL(process.env.CORPORATE_TEST_DATABASE_URL!);
|
||||
if (url.hostname !== '127.0.0.1' || url.pathname !== '/corporate_test')
|
||||
throw new Error('Disposable loopback corporate_test DB required');
|
||||
passport.use(
|
||||
'jwt',
|
||||
new Strategy(
|
||||
{
|
||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
secretOrKey: 'test-only-not-runtime',
|
||||
},
|
||||
(_payload, done) => done(null, false),
|
||||
),
|
||||
);
|
||||
db = new PrismaClient({
|
||||
datasources: { db: { url: process.env.CORPORATE_TEST_DATABASE_URL } },
|
||||
}) as PrismaService;
|
||||
const module = await Test.createTestingModule({
|
||||
controllers: [CorporateController],
|
||||
providers: [
|
||||
CorporateService,
|
||||
{ provide: PrismaService, useValue: db },
|
||||
{
|
||||
provide: ApiKeysService,
|
||||
useValue: {
|
||||
validateKey: async (id: string) => ({
|
||||
id,
|
||||
isApiKey: true,
|
||||
role: 'Admin',
|
||||
scopes: id === 'unscoped' ? [] : ['admin'],
|
||||
}),
|
||||
},
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
app = module.createNestApplication();
|
||||
await app.listen(0, '127.0.0.1');
|
||||
});
|
||||
afterAll(async () => {
|
||||
if (db)
|
||||
await db.$executeRawUnsafe(
|
||||
'TRUNCATE corporate_operations, corporate_reports, corporate_effects, corporate_reviews, corporate_evidence, corporate_events, corporate_tasks, corporate_goals, corporate_roadmaps, corporate_sources, corporate_research CASCADE',
|
||||
);
|
||||
await app?.close();
|
||||
await db?.$disconnect();
|
||||
passport.unuse('jwt');
|
||||
});
|
||||
beforeEach(async () => {
|
||||
await db.$executeRawUnsafe(
|
||||
'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;
|
||||
const ready = new Promise<void>((r) => (locked = r));
|
||||
const hold = new Promise<void>((r) => (release = r));
|
||||
const claiming = db.$transaction(async (tx) => {
|
||||
await tx.$queryRaw`SELECT id FROM corporate_tasks WHERE id=${parent.id}::uuid FOR UPDATE`;
|
||||
await tx.corporateTask.update({
|
||||
where: { id: parent.id },
|
||||
data: {
|
||||
status: 'IN_PROGRESS',
|
||||
claimToken: key(),
|
||||
assignedAgent: 'executor',
|
||||
leasedUntil: new Date(Date.now() + 60000),
|
||||
},
|
||||
});
|
||||
locked();
|
||||
await hold;
|
||||
});
|
||||
await ready;
|
||||
const pending = post('tasks', { ...input, parentId: parent.id }).then(
|
||||
(r) => r,
|
||||
);
|
||||
try {
|
||||
// Observe actual competing PostgreSQL lock wait, not a timing-only race.
|
||||
let waiting = false;
|
||||
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 '%corporate_tasks%'`;
|
||||
if (rows.length) {
|
||||
waiting = true;
|
||||
break;
|
||||
}
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
}
|
||||
expect(waiting).toBe(true);
|
||||
} finally {
|
||||
release();
|
||||
await claiming;
|
||||
}
|
||||
expect((await pending).status).toBe(409);
|
||||
expect(
|
||||
await db.corporateTask.count({ where: { parentId: parent.id } }),
|
||||
).toBe(0);
|
||||
});
|
||||
it('accepts children on TODO and BLOCKED, which prevents parent claiming', async () => {
|
||||
for (const status of ['TODO', 'BLOCKED'] as const) {
|
||||
const parent = (await post('tasks', input).expect(201)).body;
|
||||
await db.corporateTask.update({
|
||||
where: { id: parent.id },
|
||||
data: { status },
|
||||
});
|
||||
const child = (
|
||||
await post('tasks', { ...input, parentId: parent.id }).expect(201)
|
||||
).body;
|
||||
expect((await post('claims', {}).expect(201)).body.task.id).toBe(
|
||||
child.id,
|
||||
);
|
||||
}
|
||||
});
|
||||
it('rejects malformed artifact locators and mismatched digest URNs before persistence', async () => {
|
||||
const task = (await post('tasks', input).expect(201)).body;
|
||||
const claim = (await post('claims', {}).expect(201)).body.task;
|
||||
const body = {
|
||||
claimToken: claim.claimToken,
|
||||
artifactUri: '',
|
||||
sha256: 'a'.repeat(64),
|
||||
summary: 'receipt',
|
||||
tool: 'jest',
|
||||
result: 'passed',
|
||||
};
|
||||
for (const artifactUri of [
|
||||
'https://',
|
||||
'https://?x',
|
||||
'https:///pubmed.ncbi.nlm.nih.gov/x',
|
||||
'https://pubmed.ncbi.nlm.nih.gov./x',
|
||||
'https://bad host/x',
|
||||
'https://user:pass@host.org/a',
|
||||
'https://localhost/a',
|
||||
'https://127.1/a',
|
||||
'https://[::1]/a',
|
||||
'urn:sha256:',
|
||||
'urn:sha256:' + 'b'.repeat(64),
|
||||
]) {
|
||||
await post(`tasks/${task.id}/evidence`, { ...body, artifactUri }).expect(
|
||||
400,
|
||||
);
|
||||
}
|
||||
expect(await db.corporateEvidence.count()).toBe(0);
|
||||
await post(`tasks/${task.id}/evidence`, {
|
||||
...body,
|
||||
artifactUri: 'https://pubmed.ncbi.nlm.nih.gov/123/',
|
||||
}).expect(201);
|
||||
});
|
||||
it('rejects implicit timestamp coercions in source and effect inputs', async () => {
|
||||
const service = app.get(CorporateService);
|
||||
const research = {
|
||||
title: 'research',
|
||||
category: 'TREND',
|
||||
source: 'receipt',
|
||||
opportunity: 'investigate',
|
||||
impact: 'LOW',
|
||||
recommendedAction: 'measure',
|
||||
cadence: 'MONTHLY',
|
||||
provenance: { method: 'test', collector: 'fixture', context: 'isolated' },
|
||||
sources: [
|
||||
{
|
||||
url: 'https://pubmed.ncbi.nlm.nih.gov/',
|
||||
title: 'source',
|
||||
excerpt: 'receipt',
|
||||
retrievedAt: '',
|
||||
sha256: 'a'.repeat(64),
|
||||
},
|
||||
],
|
||||
};
|
||||
for (const time of [
|
||||
null,
|
||||
0,
|
||||
false,
|
||||
[],
|
||||
'2026-01-01',
|
||||
'2026-02-30T00:00:00Z',
|
||||
]) {
|
||||
await expect(
|
||||
Promise.resolve().then(() =>
|
||||
service.research('fixture', key(), {
|
||||
...research,
|
||||
sources: [{ ...research.sources[0], retrievedAt: time }],
|
||||
}),
|
||||
),
|
||||
).rejects.toThrow();
|
||||
await expect(
|
||||
Promise.resolve().then(() =>
|
||||
service.effect('fixture', key(), key(), {
|
||||
metric: 'views',
|
||||
availability: 'UNAVAILABLE',
|
||||
source: 'none',
|
||||
observedAt: time,
|
||||
}),
|
||||
),
|
||||
).rejects.toThrow('Invalid observation time');
|
||||
}
|
||||
for (const url of ['https://', 'https://?bad', 'https://bad host'])
|
||||
await expect(
|
||||
Promise.resolve().then(() =>
|
||||
service.research('fixture', key(), {
|
||||
...research,
|
||||
sources: [
|
||||
{
|
||||
...research.sources[0],
|
||||
retrievedAt: '2026-01-01T00:00:00Z',
|
||||
url,
|
||||
},
|
||||
],
|
||||
}),
|
||||
),
|
||||
).rejects.toThrow();
|
||||
expect(await db.corporateResearch.count()).toBe(0);
|
||||
});
|
||||
it('public reads strip claim tokens recursively while claim and replay retain ownership token', async () => {
|
||||
const parent = (await post('tasks', input).expect(201)).body;
|
||||
const child = (
|
||||
await post('tasks', { ...input, parentId: parent.id }).expect(201)
|
||||
).body;
|
||||
const op = key();
|
||||
const claim = (await post('claims', {}, 'executor', op).expect(201)).body
|
||||
.task;
|
||||
expect(claim.claimToken).toBeTruthy();
|
||||
expect(
|
||||
(await post('claims', {}, 'executor', op).expect(201)).body.task
|
||||
.claimToken,
|
||||
).toBe(claim.claimToken);
|
||||
await post(`tasks/${child.id}/evidence`, {
|
||||
claimToken: claim.claimToken,
|
||||
artifactUri: 'urn:sha256:' + 'a'.repeat(64),
|
||||
sha256: 'a'.repeat(64),
|
||||
summary: 'receipt',
|
||||
tool: 'jest',
|
||||
result: 'passed',
|
||||
}).expect(201);
|
||||
for (const path of ['tasks', 'tasks/' + child.id, 'tasks/' + parent.id]) {
|
||||
const r = await request(app.getHttpServer())
|
||||
.get('/admin/hermes/' + path)
|
||||
.set('x-api-key', 'competitor')
|
||||
.expect(200);
|
||||
expect(JSON.stringify(r.body)).not.toContain('claimToken');
|
||||
expect(JSON.stringify(r.body)).not.toContain(claim.claimToken);
|
||||
}
|
||||
});
|
||||
it('bounds detail relations and report snapshots with explicit truncation and immutable replay', async () => {
|
||||
const task = (await post('tasks', input).expect(201)).body;
|
||||
await db.corporateEvent.createMany({
|
||||
data: Array.from({ length: 105 }, () => ({
|
||||
taskId: task.id,
|
||||
speaker: 'SYSTEM',
|
||||
speakerName: 'fixture',
|
||||
step: 'FIXTURE',
|
||||
content: 'x'.repeat(10000),
|
||||
payload: { nested: ['x'.repeat(10000)] },
|
||||
})),
|
||||
});
|
||||
const detail = await request(app.getHttpServer())
|
||||
.get('/admin/hermes/tasks/' + task.id)
|
||||
.set('x-api-key', 'executor')
|
||||
.expect(200);
|
||||
expect(detail.body.logs).toHaveLength(100);
|
||||
expect(detail.body.relationsMeta.logs).toEqual({
|
||||
total: 106,
|
||||
returned: 100,
|
||||
limit: 100,
|
||||
truncated: true,
|
||||
});
|
||||
const op = key(),
|
||||
body = { day: new Date().toISOString().slice(0, 10), summary: 'bounded' };
|
||||
const report = (await post('reports', body, 'executor', op).expect(201))
|
||||
.body;
|
||||
expect(report.snapshot.events).toHaveLength(100);
|
||||
expect(report.snapshot.meta.events).toEqual({
|
||||
total: 106,
|
||||
returned: 100,
|
||||
limit: 100,
|
||||
truncated: true,
|
||||
});
|
||||
expect(report.snapshot.events.every((e: any) => !('payload' in e))).toBe(
|
||||
true,
|
||||
);
|
||||
expect(report.snapshot.meta.fieldsTruncated).toBe(true);
|
||||
expect(
|
||||
Buffer.byteLength(JSON.stringify(report.body ?? report)),
|
||||
).toBeLessThan(1000000);
|
||||
await db.corporateEvent.deleteMany();
|
||||
expect(
|
||||
(await post('reports', body, 'executor', op).expect(201)).body,
|
||||
).toEqual(report);
|
||||
});
|
||||
it('rolls back oversized mutation responses instead of persisting huge idempotency values', async () => {
|
||||
const service = app.get(CorporateService) as any;
|
||||
const before = await db.corporateTask.count();
|
||||
await expect(
|
||||
service.operation('fixture', 'oversize', key(), {}, async (tx: any) => {
|
||||
await tx.corporateTask.create({
|
||||
data: {
|
||||
title: 'rollback',
|
||||
description: 'fixture',
|
||||
taskCode: key(),
|
||||
normalizedTitle: 'rollback',
|
||||
normalizedCode: key(),
|
||||
department: 'CONTENT_SEO',
|
||||
createdBy: 'fixture',
|
||||
},
|
||||
});
|
||||
return { value: 'x'.repeat(1100000) };
|
||||
}),
|
||||
).rejects.toThrow('Operation response exceeds limit');
|
||||
expect(await db.corporateTask.count()).toBe(before);
|
||||
expect(await db.corporateOperation.count()).toBe(0);
|
||||
});
|
||||
it('auth, UI list contract, normalized search, immutable idempotent replay', async () => {
|
||||
await request(app.getHttpServer()).get('/admin/hermes/tasks').expect(401);
|
||||
await post('tasks', input, 'unscoped').expect(403);
|
||||
const op = key(),
|
||||
a = await post('tasks', input, 'executor', op).expect(201);
|
||||
const b = await post('tasks', input, 'executor', op).expect(201);
|
||||
expect(b.body.id).toBe(a.body.id);
|
||||
await post('tasks', { ...input, title: 'changed' }, 'executor', op).expect(
|
||||
409,
|
||||
);
|
||||
const list = await request(app.getHttpServer())
|
||||
.get('/admin/hermes/tasks?search=کیک%20123&limit=1')
|
||||
.set('x-api-key', 'executor')
|
||||
.expect(200);
|
||||
expect(list.body.meta).toEqual({
|
||||
total: 1,
|
||||
page: 1,
|
||||
limit: 1,
|
||||
totalPages: 1,
|
||||
hasNextPage: false,
|
||||
hasPrevPage: false,
|
||||
});
|
||||
expect(list.body.data[0].priority).toBe('CEO_EXPEDITE');
|
||||
await request(app.getHttpServer())
|
||||
.get('/admin/hermes/tasks?limit=101')
|
||||
.set('x-api-key', 'executor')
|
||||
.expect(400);
|
||||
await request(app.getHttpServer())
|
||||
.get('/admin/hermes/tasks?sortBy=password')
|
||||
.set('x-api-key', 'executor')
|
||||
.expect(400);
|
||||
});
|
||||
it('claims exclusively, expires/reclaims, fences stale executor, requires independent QA', async () => {
|
||||
const task = (await post('tasks', input).expect(201)).body;
|
||||
const claims = await Promise.all([
|
||||
post('claims', {}, 'executor'),
|
||||
post('claims', {}, 'competitor'),
|
||||
]);
|
||||
expect(claims.filter((x) => x.body.task !== null)).toHaveLength(1);
|
||||
const claimed = claims.find((x) => x.body.task !== null)!.body.task;
|
||||
const oldActor = claimed.assignedAgent.replace('apikey:', '');
|
||||
await db.$executeRaw`UPDATE corporate_tasks SET "leasedUntil"=clock_timestamp()-interval '1 second' WHERE id=${task.id}::uuid`;
|
||||
const renewed = (await post('claims', {}, 'new-executor').expect(201)).body
|
||||
.task;
|
||||
expect(renewed.claimToken).not.toBe(claimed.claimToken);
|
||||
const evidence = {
|
||||
claimToken: claimed.claimToken,
|
||||
artifactUri: 'urn:sha256:' + 'a'.repeat(64),
|
||||
sha256: 'a'.repeat(64),
|
||||
summary: 'receipt',
|
||||
tool: 'jest',
|
||||
result: 'passed',
|
||||
};
|
||||
await post(`tasks/${task.id}/evidence`, evidence, oldActor).expect(409);
|
||||
const e = (
|
||||
await post(
|
||||
`tasks/${task.id}/evidence`,
|
||||
{ ...evidence, claimToken: renewed.claimToken },
|
||||
'new-executor',
|
||||
).expect(201)
|
||||
).body;
|
||||
const review = {
|
||||
evidenceId: e.id,
|
||||
passed: true,
|
||||
findings: 'verified',
|
||||
verification: {
|
||||
artifactUri: e.artifactUri,
|
||||
sha256: e.sha256,
|
||||
method: 'digest readback',
|
||||
result: 'match',
|
||||
},
|
||||
};
|
||||
await post(`tasks/${task.id}/reviews`, review, 'new-executor').expect(409);
|
||||
await post(`tasks/${task.id}/reviews`, review, 'reviewer').expect(201);
|
||||
const detail = await request(app.getHttpServer())
|
||||
.get('/admin/hermes/tasks/' + task.id)
|
||||
.set('x-api-key', 'reviewer')
|
||||
.expect(200);
|
||||
expect(detail.body.status).toBe('DONE');
|
||||
expect(detail.body.logs.map((x: any) => x.step)).toContain('QA_PASSED');
|
||||
await post(`tasks/${task.id}/effects`, {
|
||||
metric: 'engagement',
|
||||
availability: 'UNAVAILABLE',
|
||||
observed: 0,
|
||||
source: 'provider unavailable',
|
||||
observedAt: new Date().toISOString(),
|
||||
}).expect(400);
|
||||
});
|
||||
it('skips a held row lock and gives CEO priority before lower priorities', async () => {
|
||||
const urgent = (await post('tasks', input).expect(201)).body;
|
||||
const low = (await post('tasks', { ...input, priority: 'LOW' }).expect(201))
|
||||
.body;
|
||||
let release!: () => void, locked!: () => void;
|
||||
const ready = new Promise<void>((r) => (locked = r)),
|
||||
hold = new Promise<void>((r) => (release = r));
|
||||
const locking = db.$transaction(async (tx) => {
|
||||
await tx.$queryRaw`SELECT id FROM corporate_tasks WHERE id=${urgent.id}::uuid FOR UPDATE`;
|
||||
locked();
|
||||
await hold;
|
||||
});
|
||||
await ready;
|
||||
try {
|
||||
const claim = (await post('claims', {}).expect(201)).body.task;
|
||||
expect(claim.id).toBe(low.id);
|
||||
} finally {
|
||||
release();
|
||||
await locking;
|
||||
}
|
||||
const next = (await post('claims', {}, 'other').expect(201)).body.task;
|
||||
expect(next.id).toBe(urgent.id);
|
||||
});
|
||||
it('serializes simultaneous duplicate mutations into one durable record', async () => {
|
||||
const op = key();
|
||||
const responses = await Promise.all([
|
||||
post('tasks', input, 'executor', op),
|
||||
post('tasks', input, 'executor', op),
|
||||
]);
|
||||
expect(responses.map((r) => r.status)).toEqual([201, 201]);
|
||||
expect(responses[0].body.id).toBe(responses[1].body.id);
|
||||
expect(await db.corporateTask.count()).toBe(1);
|
||||
});
|
||||
it('gates parents on children, persists provenance, roadmap/goals and reports', async () => {
|
||||
const parent = (await post('tasks', input).expect(201)).body;
|
||||
const child = (
|
||||
await post('tasks', { ...input, parentId: parent.id }).expect(201)
|
||||
).body;
|
||||
const claim = (await post('claims', {}).expect(201)).body.task;
|
||||
expect(claim.id).toBe(child.id);
|
||||
const e = (
|
||||
await post(`tasks/${child.id}/evidence`, {
|
||||
claimToken: claim.claimToken,
|
||||
artifactUri: 'urn:sha256:' + 'b'.repeat(64),
|
||||
sha256: 'b'.repeat(64),
|
||||
summary: 'child artifact',
|
||||
tool: 'jest',
|
||||
result: 'receipt',
|
||||
}).expect(201)
|
||||
).body;
|
||||
await post(
|
||||
`tasks/${child.id}/reviews`,
|
||||
{
|
||||
evidenceId: e.id,
|
||||
passed: false,
|
||||
findings: 'needs correction',
|
||||
verification: {
|
||||
artifactUri: e.artifactUri,
|
||||
sha256: e.sha256,
|
||||
method: 'readback',
|
||||
result: 'failed',
|
||||
},
|
||||
},
|
||||
'reviewer',
|
||||
).expect(201);
|
||||
expect(
|
||||
(await db.corporateTask.findUniqueOrThrow({ where: { id: parent.id } }))
|
||||
.status,
|
||||
).toBe('BLOCKED');
|
||||
expect((await post('claims', {}).expect(201)).body.task.id).toBe(child.id);
|
||||
const research = (
|
||||
await post('market-insights', {
|
||||
title: 'fixture research',
|
||||
category: 'TREND',
|
||||
source: 'study receipt',
|
||||
opportunity: 'investigate',
|
||||
impact: 'LOW',
|
||||
recommendedAction: 'measure',
|
||||
cadence: 'MONTHLY',
|
||||
provenance: {
|
||||
method: 'test fixture',
|
||||
collector: 'integration',
|
||||
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,
|
||||
cycleName: 'test',
|
||||
month: '2026-10',
|
||||
seasonalTheme: 'evidence pending seasonal analysis',
|
||||
strategicGoals: ['measure'],
|
||||
plannedArticlesCount: 31,
|
||||
plannedRefreshesCount: 0,
|
||||
plannedCatalogEnrichments: 0,
|
||||
goals: [
|
||||
{
|
||||
title: 'goal',
|
||||
department: 'CONTENT_SEO',
|
||||
acceptanceCriteria: 'QA',
|
||||
metric: 'engagement',
|
||||
},
|
||||
],
|
||||
}).expect(201)
|
||||
).body;
|
||||
expect(roadmap.goals).toHaveLength(1);
|
||||
await post('tasks', { ...input, goalId: roadmap.goals[0].id }).expect(201);
|
||||
for (const path of ['market-insights', 'monthly-roadmap']) {
|
||||
const r = await request(app.getHttpServer())
|
||||
.get('/admin/hermes/' + path)
|
||||
.set('x-api-key', 'executor')
|
||||
.expect(200);
|
||||
expect(r.body.meta.total).toBe(1);
|
||||
}
|
||||
const report = (
|
||||
await post('reports', {
|
||||
day: new Date().toISOString().slice(0, 10),
|
||||
summary: 'test fixture daily report',
|
||||
}).expect(201)
|
||||
).body;
|
||||
expect(report.snapshot.tasks).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
@@ -1,845 +0,0 @@
|
||||
import {
|
||||
Injectable,
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { Prisma, CorporatePriority } from '@prisma/client';
|
||||
import { createHash, randomUUID } from 'crypto';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import {
|
||||
canonical,
|
||||
monthlyPlanInput,
|
||||
planMonth,
|
||||
publicData,
|
||||
choice,
|
||||
departments,
|
||||
evidenceInput,
|
||||
httpsUrl,
|
||||
timestamp,
|
||||
meta,
|
||||
normalizeSearch,
|
||||
object,
|
||||
pagination,
|
||||
priorities,
|
||||
statuses,
|
||||
taskInput,
|
||||
text,
|
||||
uuid,
|
||||
} from './corporate-policy';
|
||||
type Tx = Prisma.TransactionClient;
|
||||
@Injectable()
|
||||
export class CorporateService {
|
||||
constructor(private readonly db: PrismaService) {}
|
||||
private async operation(
|
||||
actor: string,
|
||||
op: string,
|
||||
key: string,
|
||||
body: unknown,
|
||||
fn: (tx: Tx) => Promise<any>,
|
||||
) {
|
||||
text(key, 200);
|
||||
const scoped = createHash('sha256')
|
||||
.update(canonical([actor, op, key]))
|
||||
.digest('hex');
|
||||
const hash = createHash('sha256').update(canonical(body)).digest('hex');
|
||||
return this.db.$transaction(
|
||||
async (tx) => {
|
||||
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${scoped}, 0))`;
|
||||
const prior = await tx.corporateOperation.findUnique({
|
||||
where: { key: scoped },
|
||||
});
|
||||
if (prior) {
|
||||
if (prior.payloadHash !== hash)
|
||||
throw new ConflictException('Idempotency key payload mismatch');
|
||||
return prior.response;
|
||||
}
|
||||
const result = await fn(tx);
|
||||
const serialized = JSON.stringify(result);
|
||||
if (Buffer.byteLength(serialized, 'utf8') > 1000000)
|
||||
throw new BadRequestException('Operation response exceeds limit');
|
||||
const response = JSON.parse(serialized);
|
||||
await tx.corporateOperation.create({
|
||||
data: { key: scoped, payloadHash: hash, response },
|
||||
});
|
||||
return response;
|
||||
},
|
||||
{ maxWait: 10000, timeout: 20000 },
|
||||
);
|
||||
}
|
||||
private event(
|
||||
tx: Tx,
|
||||
taskId: string,
|
||||
actor: string,
|
||||
step: string,
|
||||
content: string,
|
||||
speaker = 'SYSTEM',
|
||||
payload?: any,
|
||||
) {
|
||||
return tx.corporateEvent.create({
|
||||
data: { taskId, speaker, speakerName: actor, step, content, payload },
|
||||
});
|
||||
}
|
||||
private async lock(tx: Tx, id: string) {
|
||||
uuid(id);
|
||||
const rows = await tx.$queryRaw<
|
||||
{ id: string }[]
|
||||
>`SELECT id FROM corporate_tasks WHERE id=${id}::uuid FOR UPDATE`;
|
||||
if (!rows.length) throw new NotFoundException('Task not found');
|
||||
return tx.corporateTask.findUniqueOrThrow({ where: { id } });
|
||||
}
|
||||
private async fenced(tx: Tx, id: string, token: string, actor: string) {
|
||||
const t = await this.lock(tx, id);
|
||||
const rows = await tx.$queryRaw<
|
||||
{ id: string }[]
|
||||
>`SELECT id FROM corporate_tasks WHERE id=${id}::uuid AND "claimToken"=${token}::uuid AND "assignedAgent"=${actor} AND "leasedUntil">clock_timestamp() AND status='IN_PROGRESS'`;
|
||||
if (!rows.length) throw new ConflictException('Stale lease or owner');
|
||||
return t;
|
||||
}
|
||||
async tasks(q: Record<string, any>) {
|
||||
const p = pagination(q),
|
||||
where: Prisma.CorporateTaskWhereInput = {};
|
||||
if (q.department) where.department = choice(q.department, departments);
|
||||
if (q.priority)
|
||||
where.priority = choice(q.priority, priorities) as CorporatePriority;
|
||||
if (q.status) where.status = choice(q.status, statuses) as any;
|
||||
if (q.search) {
|
||||
const search = normalizeSearch(text(q.search, 300));
|
||||
where.OR = [
|
||||
{ normalizedTitle: { contains: search } },
|
||||
{ normalizedCode: { contains: search } },
|
||||
];
|
||||
}
|
||||
if (q.goalId) where.goalId = uuid(q.goalId);
|
||||
return this.db.$transaction(
|
||||
async (tx) => {
|
||||
const total = await tx.corporateTask.count({ where });
|
||||
const data = await tx.corporateTask.findMany({
|
||||
where,
|
||||
skip: p.skip,
|
||||
take: p.limit,
|
||||
orderBy: [{ [p.sortBy]: p.sortOrder }, { id: 'asc' }],
|
||||
});
|
||||
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 },
|
||||
);
|
||||
}
|
||||
async detail(id: string) {
|
||||
uuid(id);
|
||||
return this.db.$transaction(
|
||||
async (tx) => {
|
||||
const order = { id: 'asc' as const };
|
||||
const task = await tx.corporateTask.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
logs: { take: 100, orderBy: [{ timestamp: 'asc' }, order] },
|
||||
evidence: { take: 100, orderBy: order },
|
||||
reviews: { take: 100, orderBy: order },
|
||||
effects: { take: 100, orderBy: order },
|
||||
children: { take: 100, orderBy: order },
|
||||
_count: {
|
||||
select: {
|
||||
logs: true,
|
||||
evidence: true,
|
||||
reviews: true,
|
||||
effects: true,
|
||||
children: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!task) throw new NotFoundException('Task not found');
|
||||
const { _count, ...data } = task;
|
||||
const relationsMeta = Object.fromEntries(
|
||||
Object.entries(_count).map(([name, total]) => [
|
||||
name,
|
||||
{
|
||||
total,
|
||||
returned: Math.min(total, 100),
|
||||
limit: 100,
|
||||
truncated: total > 100,
|
||||
},
|
||||
]),
|
||||
);
|
||||
return publicData({ ...data, relationsMeta });
|
||||
},
|
||||
{ isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead },
|
||||
);
|
||||
}
|
||||
create(actor: string, key: string, input: unknown) {
|
||||
const b = taskInput(input);
|
||||
return this.operation(actor, 'create-task', key, b, async (tx) => {
|
||||
if (b.parentId) {
|
||||
const parent = await this.lock(tx, b.parentId);
|
||||
if (!['TODO', 'BLOCKED'].includes(parent.status))
|
||||
throw new ConflictException('Parent no longer accepts children');
|
||||
}
|
||||
const code = 'TSK-' + randomUUID();
|
||||
const task = await tx.corporateTask.create({
|
||||
data: {
|
||||
...b,
|
||||
priority: b.priority as CorporatePriority,
|
||||
taskCode: code,
|
||||
normalizedCode: normalizeSearch(code),
|
||||
normalizedTitle: normalizeSearch(b.title),
|
||||
createdBy: actor,
|
||||
},
|
||||
});
|
||||
await this.event(tx, task.id, actor, 'CREATED', b.description, 'CEO');
|
||||
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', '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);
|
||||
if (!Number.isInteger(seconds) || seconds < 30 || seconds > 900)
|
||||
throw new BadRequestException('Lease must be 30..900 seconds');
|
||||
return this.operation(
|
||||
actor,
|
||||
'claim',
|
||||
key,
|
||||
{ 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`;
|
||||
if (!candidates.length) return { task: null };
|
||||
const id = candidates[0].id,
|
||||
token = randomUUID();
|
||||
await tx.$executeRaw`UPDATE corporate_tasks SET status='IN_PROGRESS', "assignedAgent"=${actor}, "claimToken"=${token}::uuid, "leasedUntil"=clock_timestamp()+make_interval(secs=>${seconds}::int), "executionCount"="executionCount"+1,"updatedAt"=clock_timestamp() WHERE id=${id}::uuid`;
|
||||
await this.event(tx, id, actor, 'CLAIMED', 'Manual lease acquired');
|
||||
return {
|
||||
task: await tx.corporateTask.findUniqueOrThrow({ where: { id } }),
|
||||
};
|
||||
},
|
||||
);
|
||||
}
|
||||
submitEvidence(actor: string, key: string, id: string, input: unknown) {
|
||||
const b = evidenceInput(input);
|
||||
return this.operation(actor, 'evidence:' + id, key, b, async (tx) => {
|
||||
await this.fenced(tx, id, b.claimToken, actor);
|
||||
const e = await tx.corporateEvidence.create({
|
||||
data: { ...b, taskId: id, executor: actor },
|
||||
});
|
||||
await tx.corporateTask.update({
|
||||
where: { id },
|
||||
data: { status: 'TEST', leasedUntil: null },
|
||||
});
|
||||
await this.event(
|
||||
tx,
|
||||
id,
|
||||
actor,
|
||||
'EVIDENCE_SUBMITTED',
|
||||
b.summary,
|
||||
'AGENT',
|
||||
{ evidenceId: e.id },
|
||||
);
|
||||
return e;
|
||||
});
|
||||
}
|
||||
review(actor: string, key: string, id: string, input: unknown) {
|
||||
const b = object(input, [
|
||||
'evidenceId',
|
||||
'passed',
|
||||
'findings',
|
||||
'verification',
|
||||
]);
|
||||
const evidenceId = uuid(b.evidenceId),
|
||||
findings = text(b.findings);
|
||||
if (typeof b.passed !== 'boolean')
|
||||
throw new BadRequestException('passed must be boolean');
|
||||
const v = object(b.verification, [
|
||||
'artifactUri',
|
||||
'sha256',
|
||||
'method',
|
||||
'result',
|
||||
]);
|
||||
const verification = {
|
||||
artifactUri: text(v.artifactUri, 2000),
|
||||
sha256: text(v.sha256, 64),
|
||||
method: text(v.method, 1000),
|
||||
result: text(v.result),
|
||||
};
|
||||
return this.operation(actor, 'review:' + id, key, b, async (tx) => {
|
||||
uuid(id);
|
||||
const relation = await tx.corporateTask.findUnique({
|
||||
where: { id },
|
||||
select: { parentId: true },
|
||||
});
|
||||
if (relation?.parentId) await this.lock(tx, relation.parentId);
|
||||
const task = await this.lock(tx, id);
|
||||
const evidence = await tx.corporateEvidence.findUnique({
|
||||
where: { id: evidenceId },
|
||||
});
|
||||
if (
|
||||
task.status !== 'TEST' ||
|
||||
!evidence ||
|
||||
evidence.taskId !== id ||
|
||||
evidence.claimToken !== task.claimToken
|
||||
)
|
||||
throw new ConflictException('Current execution evidence required');
|
||||
if (evidence.executor === actor)
|
||||
throw new ConflictException('Independent reviewer required');
|
||||
if (
|
||||
verification.sha256 !== evidence.sha256 ||
|
||||
verification.artifactUri !== evidence.artifactUri
|
||||
)
|
||||
throw new ConflictException('QA must verify exact artifact');
|
||||
if (
|
||||
b.passed &&
|
||||
(await tx.corporateTask.count({
|
||||
where: { parentId: id, status: { not: 'DONE' } },
|
||||
}))
|
||||
)
|
||||
throw new ConflictException('Unfinished children');
|
||||
const r = await tx.corporateReview.create({
|
||||
data: {
|
||||
taskId: id,
|
||||
evidenceId,
|
||||
reviewer: actor,
|
||||
passed: b.passed,
|
||||
findings,
|
||||
verification,
|
||||
},
|
||||
});
|
||||
await tx.corporateTask.update({
|
||||
where: { id },
|
||||
data: {
|
||||
status: b.passed ? 'DONE' : 'TODO',
|
||||
claimToken: null,
|
||||
leasedUntil: null,
|
||||
qaCount: { increment: 1 },
|
||||
rejectionCount: { increment: b.passed ? 0 : 1 },
|
||||
},
|
||||
});
|
||||
if (!b.passed && task.parentId) {
|
||||
await tx.corporateTask.update({
|
||||
where: { id: task.parentId },
|
||||
data: { status: 'BLOCKED' },
|
||||
});
|
||||
await this.event(
|
||||
tx,
|
||||
task.parentId,
|
||||
actor,
|
||||
'CHILD_QA_REJECTED',
|
||||
'Parent blocked pending child correction',
|
||||
'QA',
|
||||
{ childId: id },
|
||||
);
|
||||
}
|
||||
await this.event(
|
||||
tx,
|
||||
id,
|
||||
actor,
|
||||
b.passed ? 'QA_PASSED' : 'QA_REJECTED',
|
||||
findings,
|
||||
'QA',
|
||||
{ reviewId: r.id },
|
||||
);
|
||||
return r;
|
||||
});
|
||||
}
|
||||
async collection(
|
||||
kind: 'market-insights' | 'monthly-roadmap' | 'reports',
|
||||
q: Record<string, any>,
|
||||
) {
|
||||
const p = pagination(q);
|
||||
return this.db.$transaction(
|
||||
async (tx) => {
|
||||
const model =
|
||||
kind === 'market-insights'
|
||||
? tx.corporateResearch
|
||||
: kind === 'monthly-roadmap'
|
||||
? tx.corporateRoadmap
|
||||
: tx.corporateReport;
|
||||
const where: any = {};
|
||||
if (kind === 'market-insights' && q.category)
|
||||
where.category = choice(q.category, [
|
||||
'TREND',
|
||||
'COMPETITOR',
|
||||
'NEW_CHANNEL',
|
||||
'CATALOG_GAP',
|
||||
]);
|
||||
if (kind === 'monthly-roadmap' && q.month)
|
||||
where.month = text(q.month, 40);
|
||||
const delegate = model as any;
|
||||
const total = await delegate.count({ where });
|
||||
const data = await delegate.findMany({
|
||||
where,
|
||||
skip: p.skip,
|
||||
take: p.limit,
|
||||
orderBy: [{ createdAt: 'desc' }, { id: 'asc' }],
|
||||
...(kind === 'market-insights'
|
||||
? { include: { sources: true } }
|
||||
: kind === 'monthly-roadmap'
|
||||
? { include: { goals: true } }
|
||||
: {}),
|
||||
});
|
||||
return publicData({ data, meta: meta(total, p.page, p.limit) });
|
||||
},
|
||||
{ isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead },
|
||||
);
|
||||
}
|
||||
research(actor: string, key: string, input: unknown) {
|
||||
const b = object(input, [
|
||||
'title',
|
||||
'category',
|
||||
'source',
|
||||
'opportunity',
|
||||
'impact',
|
||||
'recommendedAction',
|
||||
'cadence',
|
||||
'provenance',
|
||||
'sources',
|
||||
]);
|
||||
if (!Array.isArray(b.sources) || !b.sources.length || b.sources.length > 30)
|
||||
throw new BadRequestException('1..30 sources required');
|
||||
const sources = b.sources.map((raw) => {
|
||||
const s = object(raw, [
|
||||
'url',
|
||||
'title',
|
||||
'excerpt',
|
||||
'retrievedAt',
|
||||
'sha256',
|
||||
]);
|
||||
const url = httpsUrl(s.url),
|
||||
sha256 = text(s.sha256, 64),
|
||||
retrievedAt = timestamp(s.retrievedAt, 'Invalid source time');
|
||||
if (
|
||||
!url.startsWith('https://') ||
|
||||
!/^[a-f0-9]{64}$/.test(sha256) ||
|
||||
!Number.isFinite(retrievedAt.getTime()) ||
|
||||
retrievedAt.getTime() > Date.now()
|
||||
)
|
||||
throw new BadRequestException('Invalid source');
|
||||
return {
|
||||
url,
|
||||
sha256,
|
||||
retrievedAt,
|
||||
title: text(s.title, 300),
|
||||
excerpt: text(s.excerpt),
|
||||
};
|
||||
});
|
||||
const provenance = object(b.provenance, ['method', 'collector', 'context']);
|
||||
const data = {
|
||||
title: text(b.title, 300),
|
||||
category: choice(b.category, [
|
||||
'TREND',
|
||||
'COMPETITOR',
|
||||
'NEW_CHANNEL',
|
||||
'CATALOG_GAP',
|
||||
]),
|
||||
source: text(b.source, 2000),
|
||||
opportunity: text(b.opportunity),
|
||||
impact: choice(b.impact, ['HIGH', 'MEDIUM', 'LOW']),
|
||||
recommendedAction: text(b.recommendedAction),
|
||||
cadence: choice(b.cadence, ['MONTHLY', 'EVENT']),
|
||||
provenance: {
|
||||
method: text(provenance.method),
|
||||
collector: text(provenance.collector, 300),
|
||||
context: text(provenance.context),
|
||||
},
|
||||
createdBy: actor,
|
||||
};
|
||||
return this.operation(actor, 'research', key, b, (tx) =>
|
||||
tx.corporateResearch.create({
|
||||
data: { ...data, sources: { create: sources } },
|
||||
include: { sources: true },
|
||||
}),
|
||||
);
|
||||
}
|
||||
roadmap(actor: string, key: string, input: unknown) {
|
||||
const b = object(input, [
|
||||
'researchId',
|
||||
'cycleName',
|
||||
'month',
|
||||
'seasonalTheme',
|
||||
'strategicGoals',
|
||||
'plannedArticlesCount',
|
||||
'plannedRefreshesCount',
|
||||
'plannedCatalogEnrichments',
|
||||
'isActive',
|
||||
'goals',
|
||||
]);
|
||||
if (
|
||||
!Array.isArray(b.strategicGoals) ||
|
||||
!b.strategicGoals.length ||
|
||||
b.strategicGoals.length > 30 ||
|
||||
!Array.isArray(b.goals) ||
|
||||
!b.goals.length ||
|
||||
b.goals.length > 100
|
||||
)
|
||||
throw new BadRequestException('Goals required');
|
||||
for (const k of [
|
||||
'plannedArticlesCount',
|
||||
'plannedRefreshesCount',
|
||||
'plannedCatalogEnrichments',
|
||||
])
|
||||
if (!Number.isInteger(b[k]) || b[k] < 0 || b[k] > 10000)
|
||||
throw new BadRequestException('Invalid counts');
|
||||
if (b.isActive !== undefined && typeof b.isActive !== 'boolean')
|
||||
throw new BadRequestException('Invalid active flag');
|
||||
const goals = b.goals.map((raw) => {
|
||||
const g = object(raw, [
|
||||
'title',
|
||||
'department',
|
||||
'acceptanceCriteria',
|
||||
'metric',
|
||||
'target',
|
||||
]);
|
||||
if (
|
||||
g.target !== undefined &&
|
||||
(typeof g.target !== 'number' || !Number.isFinite(g.target))
|
||||
)
|
||||
throw new BadRequestException('Invalid target');
|
||||
return {
|
||||
title: text(g.title, 300),
|
||||
department: choice(g.department, departments),
|
||||
acceptanceCriteria: text(g.acceptanceCriteria),
|
||||
metric: text(g.metric, 300),
|
||||
target: g.target,
|
||||
};
|
||||
});
|
||||
const data = {
|
||||
researchId: uuid(b.researchId),
|
||||
cycleName: text(b.cycleName, 300),
|
||||
month: text(b.month, 40),
|
||||
seasonalTheme: text(b.seasonalTheme),
|
||||
strategicGoals: b.strategicGoals.map((g) => text(g, 1000)),
|
||||
plannedArticlesCount: b.plannedArticlesCount,
|
||||
plannedRefreshesCount: b.plannedRefreshesCount,
|
||||
plannedCatalogEnrichments: b.plannedCatalogEnrichments,
|
||||
isActive: b.isActive ?? false,
|
||||
createdBy: actor,
|
||||
};
|
||||
return this.operation(actor, 'roadmap', key, b, async (tx) => {
|
||||
const research = await tx.corporateResearch.findUnique({
|
||||
where: { id: data.researchId },
|
||||
include: { sources: true },
|
||||
});
|
||||
if (!research || !research.sources.length)
|
||||
throw new ConflictException('Evidence-backed research required');
|
||||
const result = await tx.corporateRoadmap.create({
|
||||
data: { ...data, goals: { create: goals } },
|
||||
include: { goals: true },
|
||||
});
|
||||
await tx.corporateResearch.update({
|
||||
where: { id: research.id },
|
||||
data: { status: 'IN_BACKLOG' },
|
||||
});
|
||||
return result;
|
||||
});
|
||||
}
|
||||
effect(actor: string, key: string, id: string, input: unknown) {
|
||||
const b = object(input, [
|
||||
'metric',
|
||||
'availability',
|
||||
'baseline',
|
||||
'observed',
|
||||
'source',
|
||||
'observedAt',
|
||||
]);
|
||||
const availability = choice(b.availability, [
|
||||
'MEASURED',
|
||||
'UNAVAILABLE',
|
||||
'UNINSTRUMENTED',
|
||||
'BUSINESS_DISABLED',
|
||||
]);
|
||||
for (const k of ['baseline', 'observed'])
|
||||
if (
|
||||
b[k] !== undefined &&
|
||||
b[k] !== null &&
|
||||
(typeof b[k] !== 'number' || !Number.isFinite(b[k]))
|
||||
)
|
||||
throw new BadRequestException('Invalid metric');
|
||||
if (availability === 'MEASURED' && typeof b.observed !== 'number')
|
||||
throw new BadRequestException('Measured value required');
|
||||
if (
|
||||
availability !== 'MEASURED' &&
|
||||
(b.observed != null || b.baseline != null)
|
||||
)
|
||||
throw new BadRequestException('Unavailable is not zero');
|
||||
const observedAt = timestamp(b.observedAt, 'Invalid observation time');
|
||||
if (
|
||||
!Number.isFinite(observedAt.getTime()) ||
|
||||
observedAt.getTime() > Date.now()
|
||||
)
|
||||
throw new BadRequestException('Invalid observation time');
|
||||
return this.operation(actor, 'effect:' + id, key, b, async (tx) => {
|
||||
const task = await this.lock(tx, id);
|
||||
if (task.status !== 'DONE')
|
||||
throw new ConflictException('Effects require completed QA');
|
||||
const e = await tx.corporateEffect.create({
|
||||
data: {
|
||||
taskId: id,
|
||||
metric: text(b.metric, 300),
|
||||
availability,
|
||||
baseline: b.baseline,
|
||||
observed: b.observed,
|
||||
source: text(b.source, 2000),
|
||||
observedAt,
|
||||
recordedBy: actor,
|
||||
},
|
||||
});
|
||||
await this.event(tx, id, actor, 'EFFECT_RECORDED', e.metric, 'SYSTEM', {
|
||||
effectId: e.id,
|
||||
});
|
||||
return e;
|
||||
});
|
||||
}
|
||||
report(actor: string, key: string, input: unknown) {
|
||||
const b = object(input, ['day', 'summary']);
|
||||
const day = text(b.day, 10),
|
||||
summary = text(b.summary);
|
||||
if (
|
||||
!/^\d{4}-\d{2}-\d{2}$/.test(day) ||
|
||||
!Number.isFinite(Date.parse(day + 'T00:00:00Z'))
|
||||
)
|
||||
throw new BadRequestException('ISO day required');
|
||||
return this.operation(actor, 'report', key, b, async (tx) => {
|
||||
const start = new Date(day + 'T00:00:00Z'),
|
||||
end = new Date(start.getTime() + 86400000);
|
||||
const taskWhere = { updatedAt: { gte: start, lt: end } };
|
||||
const eventWhere = { timestamp: { gte: start, lt: end } };
|
||||
const effectWhere = { createdAt: { gte: start, lt: end } };
|
||||
const totals = {
|
||||
tasks: await tx.corporateTask.count({ where: taskWhere }),
|
||||
events: await tx.corporateEvent.count({ where: eventWhere }),
|
||||
effects: await tx.corporateEffect.count({ where: effectWhere }),
|
||||
};
|
||||
const tasks = await tx.corporateTask.findMany({
|
||||
where: taskWhere,
|
||||
take: 100,
|
||||
orderBy: [{ updatedAt: 'asc' }, { id: 'asc' }],
|
||||
select: {
|
||||
id: true,
|
||||
taskCode: true,
|
||||
title: true,
|
||||
status: true,
|
||||
department: true,
|
||||
updatedAt: true,
|
||||
},
|
||||
});
|
||||
const events = await tx.corporateEvent.findMany({
|
||||
where: eventWhere,
|
||||
take: 100,
|
||||
orderBy: [{ timestamp: 'asc' }, { id: 'asc' }],
|
||||
select: {
|
||||
id: true,
|
||||
taskId: true,
|
||||
timestamp: true,
|
||||
speaker: true,
|
||||
speakerName: true,
|
||||
step: true,
|
||||
content: true,
|
||||
},
|
||||
});
|
||||
const effects = await tx.corporateEffect.findMany({
|
||||
where: effectWhere,
|
||||
take: 100,
|
||||
orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],
|
||||
select: {
|
||||
id: true,
|
||||
taskId: true,
|
||||
metric: true,
|
||||
availability: true,
|
||||
baseline: true,
|
||||
observed: true,
|
||||
source: true,
|
||||
observedAt: true,
|
||||
createdAt: true,
|
||||
},
|
||||
});
|
||||
let fieldsTruncated = false;
|
||||
const project = (rows: any[]) =>
|
||||
rows.map((row) =>
|
||||
Object.fromEntries(
|
||||
Object.entries(row).map(([name, value]) => {
|
||||
if (typeof value === 'string' && value.length > 1000) {
|
||||
fieldsTruncated = true;
|
||||
return [name, value.slice(0, 1000)];
|
||||
}
|
||||
return [name, value];
|
||||
}),
|
||||
),
|
||||
);
|
||||
const bounded = {
|
||||
tasks: project(tasks),
|
||||
events: project(events),
|
||||
effects: project(effects),
|
||||
};
|
||||
const counts = Object.fromEntries(
|
||||
Object.entries(totals).map(([name, total]) => [
|
||||
name,
|
||||
{
|
||||
total,
|
||||
returned: Math.min(total, 100),
|
||||
limit: 100,
|
||||
truncated: total > 100,
|
||||
},
|
||||
]),
|
||||
);
|
||||
const snapshot = JSON.parse(
|
||||
JSON.stringify({
|
||||
timezone: 'UTC',
|
||||
...bounded,
|
||||
meta: {
|
||||
...counts,
|
||||
fieldsTruncated,
|
||||
stringLimit: 1000,
|
||||
eventPayloadsOmitted: true,
|
||||
},
|
||||
}),
|
||||
);
|
||||
return tx.corporateReport.create({
|
||||
data: { day, summary, snapshot, createdBy: actor },
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import request from 'supertest';
|
||||
import { ApprovalsController } from './approvals.controller';
|
||||
import { DepartmentTasksController } from './department-tasks.controller';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { RolesGuard } from '../common/guards/roles.guard';
|
||||
|
||||
describe('retired legacy orchestration HTTP boundary', () => {
|
||||
let app: INestApplication;
|
||||
const dbAccess = jest.fn();
|
||||
const prisma = new Proxy({}, {get: (_target, key) => {
|
||||
// Nest inspects provider thenables and lifecycle hooks during setup.
|
||||
if (["then", "onModuleInit", "onApplicationBootstrap", "onModuleDestroy", "beforeApplicationShutdown", "onApplicationShutdown"].includes(String(key))) return undefined;
|
||||
dbAccess(key);
|
||||
throw new Error('Persistence must not be accessed');
|
||||
}});
|
||||
const routes = [
|
||||
['post', '/admin/approvals'],
|
||||
['put', '/admin/approvals/missing/decide'],
|
||||
['post', '/admin/department-tasks'],
|
||||
['put', '/admin/department-tasks/missing/status'],
|
||||
] as const;
|
||||
beforeAll(async () => {
|
||||
const module = await Test.createTestingModule({
|
||||
controllers: [ApprovalsController, DepartmentTasksController],
|
||||
providers: [{provide: PrismaService, useValue: prisma}, RolesGuard],
|
||||
}).overrideGuard(JwtAuthGuard).useValue({canActivate(context: any) {
|
||||
const req = context.switchToHttp().getRequest();
|
||||
if (!req.headers.authorization) return false;
|
||||
req.user = {id: 'test-admin', role: req.headers.authorization};
|
||||
return true;
|
||||
}}).compile();
|
||||
app = module.createNestApplication();
|
||||
await app.init();
|
||||
dbAccess.mockClear();
|
||||
});
|
||||
beforeEach(() => dbAccess.mockClear());
|
||||
afterAll(async () => { if (app) await app.close(); });
|
||||
it.each(routes)('%s %s returns explicit 410 for authorized callers before database access', async (method, path) => {
|
||||
const response = await request(app.getHttpServer())[method](path)
|
||||
.set('Authorization', 'Admin').send({decision:'APPROVED',status:'DONE'}).expect(410);
|
||||
expect(response.body.message).toContain('retired');
|
||||
expect(dbAccess).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each(routes)('%s %s retains anonymous and customer authorization guards', async (method, path) => {
|
||||
await request(app.getHttpServer())[method](path).send({}).expect(403);
|
||||
await request(app.getHttpServer())[method](path).set('Authorization','CUSTOMER').send({}).expect(403);
|
||||
expect(dbAccess).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,274 +0,0 @@
|
||||
import {
|
||||
ConflictException,
|
||||
ForbiddenException,
|
||||
} from "@nestjs/common";
|
||||
import {
|
||||
StageAuthorRestorationService,
|
||||
GENUINE_STAGE_AUTHORS,
|
||||
STAGE_AUTHOR_ROLE,
|
||||
assertStageScope,
|
||||
} from "./stage-author-restoration.service";
|
||||
import { Prisma } from "@prisma/client";
|
||||
|
||||
describe("StageAuthorRestorationService (Unit & TDD)", () => {
|
||||
let service: StageAuthorRestorationService;
|
||||
let mockPrisma: any;
|
||||
let mockTx: any;
|
||||
|
||||
beforeEach(() => {
|
||||
mockTx = {
|
||||
$queryRaw: jest.fn().mockResolvedValue(GENUINE_STAGE_AUTHORS.map((a, i) => ({ authorId: a.id, count: BigInt([16, 2, 3, 14, 17][i]) }))),
|
||||
user: {
|
||||
findUnique: jest.fn(),
|
||||
create: jest.fn(),
|
||||
},
|
||||
};
|
||||
mockPrisma = {
|
||||
$transaction: jest.fn(async (cb) => cb(mockTx)),
|
||||
};
|
||||
service = new StageAuthorRestorationService(mockPrisma as any);
|
||||
});
|
||||
|
||||
describe("assertStageScope environment gating", () => {
|
||||
it("denies execution in default production environment", () => {
|
||||
expect(() =>
|
||||
assertStageScope({ NODE_ENV: "production", APP_ENV: "production" }),
|
||||
).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it("denies execution when neither APP_ENV nor STAGE flag is set", () => {
|
||||
expect(() => assertStageScope({})).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it("denies execution with only APP_ENV is stage", () => {
|
||||
expect(() => assertStageScope({ APP_ENV: "stage" })).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it("denies execution with only STAGE_AUTHOR_RESTORATION_ENABLED is true", () => {
|
||||
expect(() =>
|
||||
assertStageScope({ STAGE_AUTHOR_RESTORATION_ENABLED: "true" }),
|
||||
).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it("denies execution with only DATABASE_URL points to caninodb_stage", () => {
|
||||
expect(() =>
|
||||
assertStageScope({
|
||||
DATABASE_URL: "postgresql://user:pass@db:5432/caninodb_stage",
|
||||
}),
|
||||
).toThrow(ForbiddenException);
|
||||
});
|
||||
});
|
||||
|
||||
describe("restoreStageAuthors TDD lifecycle", () => {
|
||||
const stageEnv = { APP_ENV: "stage", STAGE_AUTHOR_RESTORATION_ENABLED: "true", STAGE_AUTHOR_RESTORATION_MODE: "maintenance", DATABASE_URL: "postgresql://user@canino_db_stage:5432/caninodb_stage" };
|
||||
|
||||
it("rejects a partial existing set before any writes", async () => {
|
||||
mockTx.user.findUnique.mockResolvedValueOnce({ ...GENUINE_STAGE_AUTHORS[0], role: STAGE_AUTHOR_ROLE });
|
||||
mockTx.user.findUnique.mockResolvedValue(null);
|
||||
await expect(service.restoreStageAuthors(stageEnv)).rejects.toThrow(ConflictException);
|
||||
expect(mockTx.user.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not allow enabled production scope", () => {
|
||||
expect(() => assertStageScope({ ...stageEnv, APP_ENV: "production" })).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it("rejects a stage-looking substring in the database identity", () => {
|
||||
expect(() => assertStageScope({ ...stageEnv, DATABASE_URL: "postgresql://user@evil/caninodb_stage_prod" })).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it("requires explicit mode", () => {
|
||||
expect(() => assertStageScope({ ...stageEnv, STAGE_AUTHOR_RESTORATION_MODE: undefined })).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it("rejects unsafe replay even with identical names", async () => {
|
||||
mockTx.user.findUnique.mockImplementation(async ({ where }: any) => ({ ...GENUINE_STAGE_AUTHORS.find(a => a.id === where.id), role: "Admin" }));
|
||||
await expect(service.restoreStageAuthors(stageEnv)).rejects.toThrow(ConflictException);
|
||||
expect(mockTx.user.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses a Serializable transaction", async () => {
|
||||
mockTx.user.findUnique.mockResolvedValue(null);
|
||||
try { await service.restoreStageAuthors(stageEnv); } catch {}
|
||||
expect(mockPrisma.$transaction).toHaveBeenCalledWith(expect.any(Function), { isolationLevel: Prisma.TransactionIsolationLevel.Serializable });
|
||||
});
|
||||
|
||||
it("rejects unexpected orphan distribution without writing", async () => {
|
||||
mockTx.user.findUnique.mockResolvedValue(null);
|
||||
mockTx.$queryRaw = jest.fn().mockResolvedValue([{ authorId: GENUINE_STAGE_AUTHORS[0].id, count: 52n }]);
|
||||
await expect(service.restoreStageAuthors(stageEnv)).rejects.toThrow(ConflictException);
|
||||
expect(mockTx.user.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects replay with remaining orphans", async () => {
|
||||
mockTx.user.findUnique.mockImplementation(async ({ where }: any) => ({ ...GENUINE_STAGE_AUTHORS.find(a => a.id === where.id), role: STAGE_AUTHOR_ROLE, isPublicAuthor: true, mobile: null, email: null, password: null, authExpiresAt: null, walletBalance: new Prisma.Decimal(0), charityDonationTotal: new Prisma.Decimal(0), stageTestGeneration: null, stageTestSession: null }));
|
||||
mockTx.$queryRaw = jest.fn().mockResolvedValue([{ authorId: GENUINE_STAGE_AUTHORS[0].id, count: 1n }]);
|
||||
await expect(service.restoreStageAuthors(stageEnv)).rejects.toThrow(ConflictException);
|
||||
});
|
||||
|
||||
it("accepts a loopback rehearsal database only in rehearsal mode", () => {
|
||||
expect(() => assertStageScope({ ...stageEnv, STAGE_AUTHOR_RESTORATION_MODE: "rehearsal", DATABASE_URL: "postgresql://user@127.0.0.1:5432/rehearsal" })).not.toThrow();
|
||||
});
|
||||
|
||||
it("rejects rehearsal database in maintenance mode", () => {
|
||||
expect(() => assertStageScope({ ...stageEnv, DATABASE_URL: "postgresql://user@127.0.0.1:5432/rehearsal" })).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it("requires both stage identity and enable flag", () => {
|
||||
expect(() => assertStageScope({ ...stageEnv, STAGE_AUTHOR_RESTORATION_ENABLED: undefined })).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it("rejects a URL with conflicting host override", () => {
|
||||
expect(() => assertStageScope({ ...stageEnv, DATABASE_URL: "postgresql://user@canino_db_stage/caninodb_stage?host=prod" })).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it("requires the public-author marker on replay", async () => {
|
||||
mockTx.user.findUnique.mockImplementation(async ({ where }: any) => ({ ...GENUINE_STAGE_AUTHORS.find(a => a.id === where.id), role: STAGE_AUTHOR_ROLE, mobile: null, email: null, password: null, isPublicAuthor: false }));
|
||||
await expect(service.restoreStageAuthors(stageEnv)).rejects.toThrow(ConflictException);
|
||||
expect(mockTx.user.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects malformed URL without database work", async () => {
|
||||
await expect(service.restoreStageAuthors({ ...stageEnv, DATABASE_URL: "not-a-url" })).rejects.toThrow(ForbiddenException);
|
||||
expect(mockPrisma.$transaction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects unexpected scheme", () => {
|
||||
expect(() => assertStageScope({ ...stageEnv, DATABASE_URL: "https://canino_db_stage/caninodb_stage" })).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it("does not allow a production database with a stage query string", () => {
|
||||
expect(() => assertStageScope({ ...stageEnv, DATABASE_URL: "postgresql://user@db/prod?stage=caninodb_stage" })).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it("rejects a credential-bearing replay", async () => {
|
||||
mockTx.user.findUnique.mockImplementation(async ({ where }: any) => ({ ...GENUINE_STAGE_AUTHORS.find(a => a.id === where.id), role: STAGE_AUTHOR_ROLE, isPublicAuthor: true, password: "hash", mobile: null, email: null }));
|
||||
await expect(service.restoreStageAuthors(stageEnv)).rejects.toThrow(ConflictException);
|
||||
expect(mockTx.user.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects no-orphan initial state", async () => {
|
||||
mockTx.user.findUnique.mockResolvedValue(null);
|
||||
mockTx.$queryRaw = jest.fn().mockResolvedValue([]);
|
||||
await expect(service.restoreStageAuthors(stageEnv)).rejects.toThrow(ConflictException);
|
||||
expect(mockTx.user.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("writes the public-author marker", async () => {
|
||||
mockTx.user.findUnique.mockResolvedValue(null);
|
||||
mockTx.user.create.mockImplementation(async ({ data }: any) => data);
|
||||
mockTx.$queryRaw = jest.fn().mockResolvedValue(GENUINE_STAGE_AUTHORS.map((a, i) => ({ authorId: a.id, count: BigInt([16, 2, 3, 14, 17][i]) })));
|
||||
await service.restoreStageAuthors(stageEnv);
|
||||
for (const [call] of mockTx.user.create.mock.calls) expect(call.data.isPublicAuthor).toBe(true);
|
||||
});
|
||||
|
||||
// Legacy lifecycle assertions below also exercise the stricter preflight.
|
||||
|
||||
it("restores all 5 genuine authors when none exist in Stage", async () => {
|
||||
mockTx.user.findUnique.mockResolvedValue(null);
|
||||
mockTx.user.create.mockImplementation(async ({ data }: any) => ({
|
||||
id: data.id,
|
||||
firstName: data.firstName,
|
||||
lastName: data.lastName,
|
||||
role: data.role,
|
||||
}));
|
||||
|
||||
const res = await service.restoreStageAuthors(stageEnv);
|
||||
|
||||
expect(res.success).toBe(true);
|
||||
expect(res.totalConfigured).toBe(5);
|
||||
expect(res.restoredCount).toBe(5);
|
||||
expect(res.existingCount).toBe(0);
|
||||
expect(mockTx.user.create).toHaveBeenCalledTimes(5);
|
||||
|
||||
// Verify safe non-login fields: no credentials, no contact, no elevated role
|
||||
for (const call of mockTx.user.create.mock.calls) {
|
||||
const payload = call[0].data;
|
||||
expect(payload.role).toBe(STAGE_AUTHOR_ROLE);
|
||||
expect(payload.mobile).toBeNull();
|
||||
expect(payload.email).toBeNull();
|
||||
expect(payload.password).toBeNull();
|
||||
expect(payload.walletBalance).toEqual(new Prisma.Decimal(0));
|
||||
// Verify genuine author ID is preserved
|
||||
const match = GENUINE_STAGE_AUTHORS.find((a) => a.id === payload.id);
|
||||
expect(match).toBeDefined();
|
||||
expect(payload.firstName).toBe(match!.firstName);
|
||||
expect(payload.lastName).toBe(match!.lastName);
|
||||
}
|
||||
});
|
||||
|
||||
it("is strictly idempotent: repeated calls report existing and perform no creates", async () => {
|
||||
mockTx.$queryRaw.mockResolvedValue([]);
|
||||
mockTx.user.findUnique.mockImplementation(async ({ where }: any) => {
|
||||
const match = GENUINE_STAGE_AUTHORS.find((a) => a.id === where.id);
|
||||
if (!match) return null;
|
||||
return {
|
||||
id: match.id,
|
||||
firstName: match.firstName,
|
||||
lastName: match.lastName,
|
||||
role: STAGE_AUTHOR_ROLE,
|
||||
mobile: null,
|
||||
email: null,
|
||||
password: null,
|
||||
isPublicAuthor: true,
|
||||
authExpiresAt: null,
|
||||
stageTestGeneration: null,
|
||||
stageTestSession: null,
|
||||
walletBalance: new Prisma.Decimal(0),
|
||||
charityDonationTotal: new Prisma.Decimal(0),
|
||||
};
|
||||
});
|
||||
|
||||
const res = await service.restoreStageAuthors(stageEnv);
|
||||
|
||||
expect(res.success).toBe(true);
|
||||
expect(res.totalConfigured).toBe(5);
|
||||
expect(res.restoredCount).toBe(0);
|
||||
expect(res.existingCount).toBe(5);
|
||||
expect(mockTx.user.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("fails closed with 409 Conflict when existing record has conflicting name", async () => {
|
||||
mockTx.user.findUnique.mockImplementation(async ({ where }: any) => {
|
||||
if (where.id === GENUINE_STAGE_AUTHORS[0].id) {
|
||||
return {
|
||||
id: where.id,
|
||||
firstName: "Fake",
|
||||
lastName: "Impersonator",
|
||||
role: "Admin",
|
||||
};
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
await expect(service.restoreStageAuthors(stageEnv)).rejects.toThrow(
|
||||
ConflictException,
|
||||
);
|
||||
expect(mockTx.user.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("handles partial restoration: restores only missing authors and retains existing identical ones", async () => {
|
||||
mockTx.user.findUnique.mockImplementation(async ({ where }: any) => {
|
||||
if (where.id === GENUINE_STAGE_AUTHORS[0].id) {
|
||||
return {
|
||||
id: where.id,
|
||||
firstName: GENUINE_STAGE_AUTHORS[0].firstName,
|
||||
lastName: GENUINE_STAGE_AUTHORS[0].lastName,
|
||||
role: STAGE_AUTHOR_ROLE,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
mockTx.user.create.mockImplementation(async ({ data }: any) => ({
|
||||
id: data.id,
|
||||
firstName: data.firstName,
|
||||
lastName: data.lastName,
|
||||
role: data.role,
|
||||
}));
|
||||
|
||||
await expect(service.restoreStageAuthors(stageEnv)).rejects.toThrow(ConflictException);
|
||||
expect(mockTx.user.create).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,183 +0,0 @@
|
||||
import {
|
||||
ConflictException,
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
} from "@nestjs/common";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
import { Prisma } from "@prisma/client";
|
||||
|
||||
export const GENUINE_STAGE_AUTHORS = [
|
||||
{
|
||||
id: "14490d36-52fc-40be-8637-b7b04b8302f8",
|
||||
firstName: "کارشناس",
|
||||
lastName: "تغذیه تیم کنینا",
|
||||
},
|
||||
{
|
||||
id: "4e0d830c-0125-4f08-8cb7-c5ae0a38cee7",
|
||||
firstName: "آرزو",
|
||||
lastName: "فراشیانی",
|
||||
},
|
||||
{
|
||||
id: "63d38117-f864-4af6-afa0-ae5b05255f57",
|
||||
firstName: "کارشناس",
|
||||
lastName: "تحقیقات و کنترل کیفیت کنینا",
|
||||
},
|
||||
{
|
||||
id: "7b1e51d1-8c32-4a3c-804f-948d706aef36",
|
||||
firstName: "کارشناس",
|
||||
lastName: "رفتار و نگهداری تیم کنینا",
|
||||
},
|
||||
{
|
||||
id: "f57e0f98-efee-4fa1-90ef-67bf84cafad4",
|
||||
firstName: "دکتر",
|
||||
lastName: "دامپزشک تیم کنینا",
|
||||
},
|
||||
] as const;
|
||||
|
||||
export const STAGE_AUTHOR_ROLE = "User_PetOwner";
|
||||
|
||||
export function assertStageScope(env: NodeJS.ProcessEnv = process.env): void {
|
||||
let identityAllowed = false;
|
||||
try {
|
||||
const url = new URL(env.DATABASE_URL || "");
|
||||
const mode = env.STAGE_AUTHOR_RESTORATION_MODE;
|
||||
identityAllowed =
|
||||
["postgresql:", "postgres:"].includes(url.protocol) &&
|
||||
!url.search && !url.hash &&
|
||||
((mode === "maintenance" && (!url.port || url.port === "5432") && url.hostname === "canino_db_stage" && url.pathname === "/caninodb_stage") ||
|
||||
(mode === "rehearsal" && url.hostname === "127.0.0.1" && url.pathname === "/rehearsal"));
|
||||
} catch {
|
||||
// Malformed and absent URLs are denied without exposing credentials.
|
||||
}
|
||||
if (env.APP_ENV !== "stage" || env.STAGE_AUTHOR_RESTORATION_ENABLED !== "true" || !identityAllowed) {
|
||||
throw new ForbiddenException(
|
||||
"Stage author restoration is strictly restricted to authorized Stage environments",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export interface StageAuthorRestoreResult {
|
||||
success: boolean;
|
||||
totalConfigured: number;
|
||||
restoredCount: number;
|
||||
existingCount: number;
|
||||
authors: Array<{
|
||||
id: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
role: string;
|
||||
status: "restored" | "already_present";
|
||||
}>;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class StageAuthorRestorationService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async restoreStageAuthors(
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): Promise<StageAuthorRestoreResult> {
|
||||
assertStageScope(env);
|
||||
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
const results: StageAuthorRestoreResult["authors"] = [];
|
||||
let restoredCount = 0;
|
||||
let existingCount = 0;
|
||||
|
||||
// Read the entire candidate set and every dangling reference before writing.
|
||||
const candidates = await Promise.all(GENUINE_STAGE_AUTHORS.map(author => tx.user.findUnique({ where: { id: author.id } })));
|
||||
const orphans = await tx.$queryRaw<Array<{ authorId: string; count: bigint }>>`
|
||||
SELECT b.author_id AS "authorId", COUNT(*) AS count
|
||||
FROM blogs b LEFT JOIN users u ON u.id = b.author_id
|
||||
WHERE b.author_id IS NOT NULL AND u.id IS NULL
|
||||
GROUP BY b.author_id
|
||||
`;
|
||||
const present = candidates.filter(Boolean).length;
|
||||
if (present !== 0 && present !== GENUINE_STAGE_AUTHORS.length) {
|
||||
throw new ConflictException("Partial author restoration is not permitted");
|
||||
}
|
||||
if (present === 0) {
|
||||
const counts = [16, 2, 3, 14, 17];
|
||||
if (orphans.length !== 5 || !GENUINE_STAGE_AUTHORS.every((a, i) =>
|
||||
orphans.filter(o => o.authorId === a.id && Number(o.count) === counts[i]).length === 1)) {
|
||||
throw new ConflictException("Expected exactly 52 orphan blogs with the reviewed author distribution");
|
||||
}
|
||||
} else {
|
||||
if (orphans.length !== 0 || !candidates.every((row, i) => row &&
|
||||
row.id === GENUINE_STAGE_AUTHORS[i].id &&
|
||||
row.firstName === GENUINE_STAGE_AUTHORS[i].firstName &&
|
||||
row.lastName === GENUINE_STAGE_AUTHORS[i].lastName &&
|
||||
row.role === STAGE_AUTHOR_ROLE && row.isPublicAuthor === true &&
|
||||
row.mobile === null && row.email === null && row.password === null &&
|
||||
row.authExpiresAt === null && row.stageTestGeneration === null && row.stageTestSession === null &&
|
||||
row.walletBalance.equals(0) && row.charityDonationTotal.equals(0))) {
|
||||
throw new ConflictException("Replay requires all five exact safe author rows and zero orphan blogs");
|
||||
}
|
||||
}
|
||||
|
||||
for (const [index, author] of GENUINE_STAGE_AUTHORS.entries()) {
|
||||
const existing = candidates[index];
|
||||
// Candidate identity was validated atomically above.
|
||||
|
||||
if (existing) {
|
||||
if (
|
||||
existing.firstName !== author.firstName ||
|
||||
existing.lastName !== author.lastName
|
||||
) {
|
||||
throw new ConflictException(
|
||||
`Identity conflict for author UUID ${author.id}: existing name '${existing.firstName} ${existing.lastName}' conflicts with genuine name '${author.firstName} ${author.lastName}'`,
|
||||
);
|
||||
}
|
||||
|
||||
results.push({
|
||||
id: existing.id,
|
||||
firstName: existing.firstName,
|
||||
lastName: existing.lastName,
|
||||
role: existing.role,
|
||||
status: "already_present",
|
||||
});
|
||||
existingCount++;
|
||||
} else {
|
||||
// Create author with safe non-login profile fields only
|
||||
// No synthetic mobile, no synthetic email, no password, no admin privileges
|
||||
const created = await tx.user.create({
|
||||
data: {
|
||||
id: author.id,
|
||||
firstName: author.firstName,
|
||||
lastName: author.lastName,
|
||||
role: STAGE_AUTHOR_ROLE,
|
||||
isPublicAuthor: true,
|
||||
mobile: null,
|
||||
email: null,
|
||||
password: null,
|
||||
walletBalance: new Prisma.Decimal(0),
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
role: true,
|
||||
},
|
||||
});
|
||||
|
||||
results.push({
|
||||
id: created.id,
|
||||
firstName: created.firstName,
|
||||
lastName: created.lastName,
|
||||
role: created.role,
|
||||
status: "restored",
|
||||
});
|
||||
restoredCount++;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
totalConfigured: GENUINE_STAGE_AUTHORS.length,
|
||||
restoredCount,
|
||||
existingCount,
|
||||
authors: results,
|
||||
};
|
||||
}, { isolationLevel: Prisma.TransactionIsolationLevel.Serializable });
|
||||
}
|
||||
}
|
||||
Loaded 100 of 509 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user