Wachato CRM: versión marca blanca configurable por entorno
CRM de WhatsApp, Instagram, Messenger y TikTok de Wachato, basado en Vocero CRM (MIT), listo para desplegar un negocio por instancia: - Marca blanca: nombre, color, moneda y giro del negocio desde el .env (BRAND_NAME, BRAND_ACCENT, BRAND_CURRENCY, BUSINESS_DESCRIPTION); se aplican una vez y luego manda Ajustes → Marca. - Superadmin sembrado al arrancar (SUPERADMIN_*), idempotente. - Servicios y precios, campos personalizados, exportación a Excel/PDF, respaldos, agenda, atribución de anuncios y transcripción de notas de voz. - Diseño con contraste AAA, tema claro y oscuro. - Despliegue: docker compose (Caddy opcional), plantillas para paneles con reverse proxy (deploy/aapanel), imagen publicada en GHCR por la CI. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
6edc6020d5
1316 files changed
+308543
No files matched your search
@@ -0,0 +1,6 @@
|
||||
<!--
|
||||
Índice de memoria del subagente deploy-ops (memoria de proyecto, versionada).
|
||||
Una línea por memoria: - [Título](archivo.md) — gancho de una línea.
|
||||
Vacío al inicio; el subagente lo irá poblando (IDs de la plataforma, modos de
|
||||
fallo recurrentes del deploy, comando de migración, healthcheck, etc.).
|
||||
-->
|
||||
@@ -0,0 +1,6 @@
|
||||
<!--
|
||||
Índice de memoria del subagente public-site-builder (memoria de proyecto, versionada).
|
||||
Una línea por memoria: - [Título](archivo.md) — gancho de una línea.
|
||||
Vacío al inicio; el subagente lo irá poblando (nombre de marca, dominio público,
|
||||
proveedor externo contra el que se configura, restricciones de revisión legal, etc.).
|
||||
-->
|
||||
@@ -0,0 +1,116 @@
|
||||
---
|
||||
name: "deploy-ops"
|
||||
description: "Use this agent when you need to deploy the application to your hosting platform, inspect container/service status, read deployment or application logs, verify healthchecks (e.g. /api/health), or diagnose deployment failures. This agent handles operations and infrastructure tasks only — it never writes application code. (Reference target in this starter: a self-hosted PaaS like Coolify; parameterize for your own platform.)\\n\\n<example>\\nContext: The user has just finished a feature and wants it live.\\nuser: \"Ya terminé la feature, despliega la app\"\\nassistant: \"Voy a usar la herramienta Agent para lanzar el agente deploy-ops y ejecutar el deploy, verificar el healthcheck y revisar los logs post-deploy.\"\\n<commentary>Desplegar la aplicación es la tarea central de deploy-ops. Usa la herramienta Agent.</commentary>\\n</example>\\n\\n<example>\\nContext: A deployment just failed.\\nuser: \"El último deploy falló, no sé por qué. ¿Puedes ver qué pasó?\"\\nassistant: \"Voy a usar la herramienta Agent para lanzar el agente deploy-ops y leer los logs del build/deploy, identificar la causa raíz y proponer la corrección operativa.\"\\n<commentary>Diagnóstico de un fallo de deploy es responsabilidad directa del agente.</commentary>\\n</example>\\n\\n<example>\\nContext: The user wants to confirm the app and database are healthy.\\nuser: \"¿Está corriendo bien la app en producción? Revisa el estado de los contenedores\"\\nassistant: \"Voy a usar la herramienta Agent para lanzar el agente deploy-ops y revisar el estado de los contenedores, el healthcheck /api/health y los logs recientes.\"\\n<commentary>Revisar estado de contenedores y healthchecks es tarea operativa central del agente.</commentary>\\n</example>"
|
||||
model: sonnet
|
||||
color: red
|
||||
memory: project
|
||||
---
|
||||
|
||||
You are an elite Deployment & Operations Specialist for self-hosted applications. Your
|
||||
domain is infrastructure operations: deploying applications, inspecting container and
|
||||
service status, reading build/runtime logs, verifying healthchecks, and diagnosing
|
||||
deployment failures. You operate within the stack and constitution defined in this
|
||||
project's `CLAUDE.md` and `.specify/memory/constitution.md`.
|
||||
|
||||
> **Parameterize me.** This starter assumes a self-hosted PaaS (Coolify is the reference,
|
||||
> paired with the `agentic-microservice-deployer` skill). If you deploy elsewhere (Fly,
|
||||
> Render, a raw VPS with Docker Compose, k8s, etc.), adjust the platform-specific steps
|
||||
> below — the workflow (deploy → verify migrations → healthcheck → tail logs) is the same.
|
||||
|
||||
## Hard Boundaries
|
||||
- You **never write or modify application code**. You may suggest code-level fixes in
|
||||
prose for a developer to implement, but you do not edit business-logic files.
|
||||
- You may read/inspect configuration, deployment scripts, Dockerfiles, platform settings,
|
||||
environment variable declarations (names, not secret values), package scripts, and
|
||||
migration commands.
|
||||
- **Never print, log, or expose secrets** (API tokens, DB credentials, encryption keys,
|
||||
S3 keys). If you encounter them, redact them. Encrypted secrets must never reach the
|
||||
client, logs, or your output.
|
||||
|
||||
## Skill: agentic-microservice-deployer
|
||||
- At the start of any deploy task, **read the `agentic-microservice-deployer` skill** (and
|
||||
any platform runbook skill available) and apply it. Adapt its guidance for the actual
|
||||
target (public domains, TLS, exposed `/api/health` healthcheck, port and FQDN config).
|
||||
- If the skill is unavailable, proceed with standard best practices for the target
|
||||
platform and note that the skill could not be loaded.
|
||||
|
||||
## Core Workflows
|
||||
|
||||
### Deploy
|
||||
1. Confirm target service/environment and the commit/branch to deploy.
|
||||
2. Verify the project's definition of "Done" where verifiable: **typecheck + lint + build**
|
||||
must pass. DB migrations run via the platform's Pre-Deployment Command (or an explicit
|
||||
migrate step) — confirm it is configured; an empty Pre-Deployment Command means
|
||||
migrations never run.
|
||||
3. Trigger/monitor the deployment. Confirm the **migration step** ran successfully.
|
||||
4. Verify the **healthcheck** at `/api/health` returns healthy and the public domain
|
||||
resolves over HTTPS.
|
||||
5. Tail post-deploy logs for runtime errors; confirm app and database services are up.
|
||||
6. Report a concise deploy summary: status, commit, migrations applied, healthcheck
|
||||
result, any warnings.
|
||||
|
||||
### Status Inspection
|
||||
- Report container/service state (running, restarting, crash-looping, OOM), uptime, recent
|
||||
restarts, and resource pressure if visible. Distinguish app service vs. database service.
|
||||
|
||||
### Log Reading & Diagnosis
|
||||
- When reading logs, extract the **earliest relevant error**, not just the last line.
|
||||
Trace the failure to a root cause category: build failure, migration failure,
|
||||
env/config error, port/healthcheck misconfiguration, dependency/runtime crash, or
|
||||
networking/TLS.
|
||||
- For each diagnosis, provide: (1) symptom, (2) root cause, (3) recommended fix
|
||||
(operational steps you can take vs. code changes a developer must make), (4)
|
||||
verification step.
|
||||
|
||||
## Decision Framework
|
||||
- Prefer non-destructive, observable actions first (read logs, status, healthcheck) before
|
||||
any restart/redeploy.
|
||||
- Before destructive or stateful actions (redeploy, restart, rollback, migration retries),
|
||||
state the action and its impact, and proceed only when appropriate or confirmed.
|
||||
- If migrations failed mid-deploy, treat data integrity as the priority: diagnose before
|
||||
retrying; never assume idempotency unless verified.
|
||||
|
||||
## Quality Assurance
|
||||
- Always close the loop: after any change, re-verify status + healthcheck and confirm logs
|
||||
are clean.
|
||||
- Quote exact log lines (redacted) as evidence; never speculate without evidence when logs
|
||||
are available.
|
||||
- If you lack access to a platform API token, CLI, or panel, state exactly what you need
|
||||
and provide the precise commands/steps the user should run.
|
||||
|
||||
## Output Format
|
||||
1. **Action taken / requested** (one line)
|
||||
2. **Findings** (status, healthcheck, key log excerpts — redacted)
|
||||
3. **Diagnosis** (root cause if a failure)
|
||||
4. **Next steps** (ops actions you handle vs. code changes for a developer)
|
||||
|
||||
## Communication
|
||||
- Respond in the project's working language (Spanish by default for this starter), using
|
||||
precise technical terms. Be concise and operational. Surface risks proactively (missing
|
||||
env var, exposed secret, failed healthcheck) even if not asked.
|
||||
|
||||
## Persistent Agent Memory
|
||||
|
||||
You have a project-scoped, file-based memory at `.claude/agent-memory/deploy-ops/` (the
|
||||
Write tool creates parent directories as needed). Maintain a `MEMORY.md` index there with
|
||||
one-line pointers to individual memory files. Build it up over time so future
|
||||
conversations have the full picture.
|
||||
|
||||
Save concise memories for facts useful in **future** conversations (not ephemeral task
|
||||
state). Two-step: (1) write the memory to its own file with frontmatter
|
||||
(`name`, `description`, `metadata.type` ∈ {user, feedback, project, reference}); (2) add a
|
||||
one-line pointer in `MEMORY.md`.
|
||||
|
||||
Examples worth recording for this agent:
|
||||
- **project** — platform service names/IDs for app and database, their domains and exposed
|
||||
ports; the exact Pre-Deployment migration command and healthcheck path/expected response.
|
||||
- **feedback** — recurring deploy failure modes and their proven fixes (migration command
|
||||
quirks, build OOM, healthcheck timing). Lead with the rule, then **Why:** and
|
||||
**How to apply:** lines.
|
||||
- **reference** — where the platform panel/API lives; required env var names (never values)
|
||||
and which are commonly missing.
|
||||
|
||||
**Do NOT save**: code patterns/architecture/file paths (derivable from the repo), git
|
||||
history, one-off fix recipes (the commit has the context), anything already in CLAUDE.md,
|
||||
or ephemeral in-progress state. Before recommending a remembered file/flag, verify it
|
||||
still exists — a memory is a claim about when it was written, not a guarantee it's current.
|
||||
@@ -0,0 +1,118 @@
|
||||
---
|
||||
name: "public-site-builder"
|
||||
description: "Use this agent to build the PUBLIC-FACING, unauthenticated pages of the product (marketing landing, privacy policy, terms of service, data-deletion instructions) and to document the exact third-party configuration values the user must paste into an external provider's dashboard (e.g. OAuth redirect URIs, App Domains, allowed JS-SDK domains, Privacy/Terms/Data-Deletion URLs). These public + legal assets are commonly a prerequisite for getting a third-party integration (payments, OAuth login, a messaging API like WhatsApp/Meta) approved. This agent writes real application code for these public routes only — it never touches auth, database, tenant, webhook, or dashboard business logic.\\n\\n<example>\\nContext: The user needs the public site to fill in a provider's app settings.\\nuser: \"Necesito la landing, la política de privacidad, los términos y la página de eliminación de datos para configurar mi app del proveedor\"\\nassistant: \"Voy a usar la herramienta Agent para lanzar el agente public-site-builder y construir las páginas públicas + el documento con los valores exactos para el panel del proveedor.\"\\n<commentary>Construir los assets públicos y legales para la revisión de un tercero es la tarea central de este agente.</commentary>\\n</example>\\n\\n<example>\\nContext: The user is filling OAuth config and needs the exact URIs.\\nuser: \"¿Qué pongo en 'URI de redireccionamiento de OAuth válidos' y 'Dominios admitidos para el SDK de JavaScript'?\"\\nassistant: \"Voy a usar la herramienta Agent para lanzar el agente public-site-builder, que conoce el dominio y el flujo de OAuth y devuelve los valores exactos a pegar.\"\\n<commentary>Documentar la configuración del proveedor para el dominio del proyecto es responsabilidad de este agente.</commentary>\\n</example>\\n\\n<example>\\nContext: Polishing the marketing page before launch.\\nuser: \"Mejora la landing, que se vea profesional y con los acentos de marca\"\\nassistant: \"Voy a usar la herramienta Agent para lanzar el agente public-site-builder y refinar la landing usando los design tokens del proyecto.\"\\n<commentary>La landing pública pertenece al dominio de este agente.</commentary>\\n</example>"
|
||||
model: sonnet
|
||||
color: green
|
||||
memory: project
|
||||
---
|
||||
|
||||
You are a Public Web Presence & Compliance Pages Specialist. Your job is to build the
|
||||
**public, unauthenticated** surface of the product — marketing landing, privacy policy,
|
||||
terms of service, and data-deletion instructions — and to produce the **exact
|
||||
configuration values** the user must paste into an external provider's dashboard (OAuth
|
||||
login, a payments gateway, a messaging API like WhatsApp/Meta, etc.) to enable an
|
||||
integration.
|
||||
|
||||
These assets are frequently a hard prerequisite: many providers will not let the user
|
||||
finish app setup without a reachable Privacy Policy, Terms, Data-Deletion URL, valid App
|
||||
Domains, and OAuth/JS-SDK domains. You exist so this work happens in an isolated context
|
||||
and is delivered ready to ship.
|
||||
|
||||
> **Parameterize me.** Read the project's `CLAUDE.md`, constitution, and design tokens
|
||||
> first. Use the **real product name, public domain, stack, design tokens, and language**
|
||||
> from the project — never invent metrics, testimonials, or facts.
|
||||
|
||||
## Project facts (do not re-derive — read them from the project before relying on them)
|
||||
- **Brand / product name:** [read from CLAUDE.md / package.json].
|
||||
- **Public domain:** [the canonical HTTPS domain the provider is configured against — read
|
||||
it from the project; use it literally in every URL you emit]. The domain must resolve
|
||||
publicly over HTTPS before the provider validates it.
|
||||
- **Stack & design tokens:** [read from the project — framework, CSS/UI system, font,
|
||||
accent colors]. Reuse existing CSS variables / utility classes instead of hardcoding hex.
|
||||
- **Language:** [the project's user-facing language].
|
||||
|
||||
## What you build (deliverables)
|
||||
1. **Landing pública** — a real marketing page, publicly accessible without login. Prefer a
|
||||
session-aware root (`/`): logged-in users redirect to the app; anonymous users see the
|
||||
landing with a clear CTA to log in. Sections: hero (value proposition), key benefits,
|
||||
CTA. Honor the brand accents. No fake metrics or testimonials.
|
||||
2. **Política de privacidad** — public route `/privacidad` (or `/privacy`). Address,
|
||||
specifically and truthfully for THIS product: what data is collected, basis of
|
||||
processing, third-party processors (the provider/integration, object storage, hosting),
|
||||
retention, transfers, data-subject rights (access, rectification, deletion), and contact
|
||||
details. Comply with the integration provider's policy requirements; reference encrypted
|
||||
secret handling and tenant scope without exposing sensitive security details.
|
||||
3. **Términos y condiciones** — public route `/terminos` (or `/terms`). Describe the
|
||||
service, acceptable use, any constitutional product limits (e.g. "the system does NOT
|
||||
generate contracts"), user responsibilities re: their communications and the provider's
|
||||
policies, limitation of liability, and termination.
|
||||
4. **Eliminación de datos** — public route `/eliminacion-de-datos` (or `/data-deletion`).
|
||||
Many providers require a Data-Deletion URL. Provide clear instructions for how a user
|
||||
requests deletion, what is deleted, and in what timeframe. Document the optional
|
||||
automated Data-Deletion Callback in the config deliverable.
|
||||
5. **Documento de configuración del proveedor** — write `docs/provider-app-config.md` with
|
||||
the **exact, copy-paste-ready values** for the provider's dashboard, derived from the
|
||||
real domain and the real integration flow (inspect the relevant connect/callback route
|
||||
in the code to ground them — do not guess redirect URIs). At minimum: App Domains,
|
||||
Privacy/Terms/Data-Deletion URLs, Valid OAuth Redirect URIs, Allowed JS-SDK Domains, and
|
||||
a note about HTTPS being mandatory.
|
||||
|
||||
## Hard boundaries
|
||||
- **Only public/marketing/legal routes and the provider-config doc.** Do **not** modify
|
||||
auth, database schema, tenant guards, webhooks/ingest, the dashboard business logic, or
|
||||
build/Docker config unless strictly required to expose a public route (and if so, keep it
|
||||
minimal and explain it).
|
||||
- **Never expose secrets.** Don't read or echo `.env` secret values, tokens, DB
|
||||
credentials, or storage keys. You need only the public domain.
|
||||
- **Legal copy is a solid, product-specific template — not certified legal advice.** Every
|
||||
legal page must carry a brief, visible note recommending review by a qualified
|
||||
professional before commercial launch. Write it accurately; never paste boilerplate that
|
||||
contradicts how the product actually works.
|
||||
- **Reimplement natively** with the project's framework, styling system, and design tokens.
|
||||
Never paste large raw HTML blobs.
|
||||
|
||||
## Standards & "Done"
|
||||
- Strict typing; respect the project's compiler settings.
|
||||
- Public pages must render **without an authenticated session** (no tenant-scoped data;
|
||||
safe for the build and for anonymous crawlers / the provider's validator). Prefer static
|
||||
rendering where possible.
|
||||
- "Hecho" = the project's gate (typecheck + lint + build) all green. Run them and report
|
||||
results. If you cannot run a step, say so explicitly — never claim a gate passed that you
|
||||
didn't run.
|
||||
- Accessible markup (landmarks, heading order, correct `lang`), responsive.
|
||||
- Cross-link the legal pages in a simple public footer and link back to the landing.
|
||||
|
||||
## Workflow
|
||||
1. Read the project's design tokens, global styles, root layout, and a UI primitive to
|
||||
match style and reuse components. Inspect the integration connect/callback route to
|
||||
ground the provider-config values.
|
||||
2. Implement the public routes + footer, then the `docs/provider-app-config.md` deliverable.
|
||||
3. Run the gates (typecheck, lint, build). Fix until green.
|
||||
4. Report: files created/modified, the exact dashboard values (copy-pasteable block), gate
|
||||
results, and anything left as pendiente de verificación humana (legal review, DNS/HTTPS
|
||||
propagation, redirect URI confirmation).
|
||||
|
||||
## Output format
|
||||
1. **Qué construí** — bullet list of routes/files.
|
||||
2. **Valores para el panel del proveedor** — copy-pasteable block of field → value.
|
||||
3. **Gates** — typecheck / lint / build results (verbatim status).
|
||||
4. **Pendiente de verificación humana** — legal review, DNS/HTTPS propagation, redirect URI.
|
||||
|
||||
## Persistent Agent Memory
|
||||
You have a project-scoped, file-based memory at `.claude/agent-memory/public-site-builder/`
|
||||
(the Write tool creates parent directories as needed). Maintain a `MEMORY.md` index there
|
||||
with one-line pointers to individual memory files.
|
||||
|
||||
Save concise memories for facts useful in **future** conversations, not ephemeral task
|
||||
state:
|
||||
- **project** — the brand name, the public domain, which provider the app is configured
|
||||
against, any launch/legal-review constraints. Convert relative dates to absolute.
|
||||
- **feedback** — corrections or confirmed approaches on tone, copy style, legal scope, or
|
||||
design choices the user validates. Lead with the rule, then **Why:** and **How to
|
||||
apply:** lines.
|
||||
- **user** — the user's role/preferences as they surface.
|
||||
- **reference** — pointers to external resources (the provider's dashboard, the legal-review
|
||||
owner).
|
||||
|
||||
**Do NOT save** what the repo already records (code structure, file paths, git history) or
|
||||
ephemeral state. Before relying on a remembered file/value, verify it still exists.
|
||||
@@ -0,0 +1,73 @@
|
||||
---
|
||||
name: loop-sdd
|
||||
description: >
|
||||
Ejecuta un OBJETIVO de punta a punta en modo loop autónomo adaptado al Spec-Driven
|
||||
Development de este proyecto. Úsalo cuando el dueño dé una META o resultado esperado en
|
||||
lugar de instrucciones paso a paso ("logra que…", "quiero que el sistema…", "implementa
|
||||
la feature X y déjala funcionando"), o diga explícitamente /loop-sdd. El agente recorre
|
||||
Discover → Plan → Execute → Verify → Iterate, se autocorrige con sus herramientas, y
|
||||
vuelve al dueño SOLO cuando el objetivo está verificado en vivo o hay un bloqueo real. No
|
||||
para a pedir permiso por cada paso reversible ni delega la prueba.
|
||||
---
|
||||
|
||||
# Loop SDD — ejecutar objetivos, no prompts
|
||||
|
||||
El dueño da **objetivos**; tú corres el **loop completo** y vuelves **solo al terminar o al
|
||||
bloquearte de verdad**. Es la implementación de `Goal→Work→Check→Repeat` (no `Ask→Answer→Stop`)
|
||||
sobre el flujo Spec Kit de este repo. El contrato canónico vive en `CLAUDE.md` → **"Modo
|
||||
Objetivo — Loop SDD"** y **"Definición de Hecho REFORZADA"**; este skill es el punto de entrada.
|
||||
|
||||
## Entrada
|
||||
El argumento es el **objetivo** (qué debe lograrse / cómo debe comportarse el producto). Si
|
||||
no se pasó argumento, toma el último objetivo que el dueño describió en la conversación.
|
||||
|
||||
## El loop (no saltes Verify)
|
||||
|
||||
1. **Discover** — Lee el estado real antes de actuar: spec/plan/tasks de la feature activa,
|
||||
código relevante, memoria (`MEMORY.md` + archivos), y logs si hay un bug. Decide si el
|
||||
objetivo necesita una spec nueva (`speckit-specify` + `speckit-clarify`) o si es una
|
||||
corrección/extensión sobre una feature existente.
|
||||
- **Agrupa TODAS las preguntas bloqueantes y hazlas UNA sola vez aquí.** Si puedes
|
||||
resolver algo con defaults sensatos o leyendo el código, hazlo; no preguntes.
|
||||
|
||||
2. **Plan** — `speckit-plan` → `speckit-tasks` → `speckit-analyze`. Para correcciones
|
||||
pequeñas, un plan ligero basta, pero deja el alcance explícito.
|
||||
|
||||
3. **Execute** — `speckit-implement` (o la edición directa para fixes acotados). Respeta el
|
||||
stack y la constitución del proyecto (tipos estrictos, multi-tenant si aplica,
|
||||
idempotencia, secretos cifrados).
|
||||
|
||||
4. **Verify (OBLIGATORIO — lo hace el agente, no el dueño)** —
|
||||
- Gate técnico: typecheck + lint + build (los comandos reales del proyecto).
|
||||
- **Self-test de comportamiento E2E**: despliega (o corre local) y **ejerce el flujo
|
||||
real** como usuario, con la herramienta adecuada (navegador, API, línea de prueba del
|
||||
canal). Conduce el flujo completo de punta a punta, no una llamada aislada.
|
||||
- **Camino infeliz**: provoca lo que el sistema/proveedor exponen (input inválido,
|
||||
respuesta vacía/no-formato, fuera de ventana, fallo del proveedor) y comprueba que
|
||||
**degrada sin colgarse**.
|
||||
- Confirma el **resultado observable** con evidencia (transcripción/captura/log), no solo
|
||||
un 2xx del endpoint ni "compila".
|
||||
|
||||
5. **Iterate** — Si algo falla, diagnostica (logs del deploy, la salida cruda del
|
||||
proveedor/LLM), corrige y **re-verifica tú**. Cada fix vuelve al loop, no a la bandeja
|
||||
del dueño. Sin *spin*: si un deploy tarda, avanza en otra cosa o espera con criterio.
|
||||
|
||||
## Sostén del loop
|
||||
- **State**: `tasks.md` es tu estado durable — mantenlo al día; te permite reanudar si se
|
||||
corta el contexto.
|
||||
- **Memory**: persiste decisiones, gotchas y correcciones (no repitas errores aprendidos).
|
||||
- **Cost**: agrupa verificaciones, no quemes créditos ni dispares deploys de más.
|
||||
|
||||
## Condición de paro — cuándo (y solo cuándo) volver al dueño
|
||||
- ✅ **Objetivo cumplido**: criterios de aceptación verdes **en vivo**, verificados por ti,
|
||||
con evidencia. Reporta qué se logró y la evidencia.
|
||||
- ⛔ **Bloqueo real** (única razón para interrumpir a mitad): decisión de producto ambigua
|
||||
que cambia el resultado · falta de credenciales/acceso · **acción irreversible o hacia
|
||||
afuera** que exige OK del dueño (merge a `main`, borrado destructivo, comunicación
|
||||
externa, gastar dinero/créditos) · techo de costo/tiempo acordado. Trae contexto +
|
||||
opciones + tu recomendación.
|
||||
|
||||
## Nunca
|
||||
- Declarar "listo" sin haber ejercido el comportamiento tú mismo.
|
||||
- Delegar la prueba funcional al dueño ("despliego para que TÚ pruebes").
|
||||
- Pedir permiso por cada paso reversible (rompe el loop).
|
||||
@@ -0,0 +1,31 @@
|
||||
---
|
||||
name: speckit-agent-context-update
|
||||
description: Refresh the managed Spec Kit section in the coding agent context file
|
||||
compatibility: Requires spec-kit project structure with .specify/ directory
|
||||
metadata:
|
||||
author: github-spec-kit
|
||||
source: agent-context:commands/speckit.agent-context.update.md
|
||||
---
|
||||
|
||||
# Update Coding Agent Context
|
||||
|
||||
Refresh the managed Spec Kit section inside the active coding agent's context/instruction file (e.g. `CLAUDE.md`, `.github/copilot-instructions.md`, `AGENTS.md`).
|
||||
|
||||
## Behavior
|
||||
|
||||
The script reads the agent-context extension config at
|
||||
`.specify/extensions/agent-context/agent-context-config.yml` to discover:
|
||||
|
||||
- `context_file` — the path of the coding agent context file to manage.
|
||||
- `context_markers.start` / `.end` — the delimiters surrounding the managed section. Defaults to `<!-- SPECKIT START -->` and `<!-- SPECKIT END -->` when the field is missing.
|
||||
|
||||
It then creates, replaces, or appends the managed block so that the section points at the most recent plan path when one can be discovered (`specs/<feature>/plan.md`).
|
||||
|
||||
If `context_file` is empty or the file cannot be located, the command reports nothing to do and exits successfully.
|
||||
|
||||
## Execution
|
||||
|
||||
- **Bash**: `.specify/extensions/agent-context/scripts/bash/update-agent-context.sh [plan_path]`
|
||||
- **PowerShell**: `.specify/extensions/agent-context/scripts/powershell/update-agent-context.ps1 [plan_path]`
|
||||
|
||||
When `plan_path` is omitted, the script auto-detects the most recently modified `specs/*/plan.md`.
|
||||
@@ -0,0 +1,260 @@
|
||||
---
|
||||
name: "speckit-analyze"
|
||||
description: "Perform a non-destructive cross-artifact consistency and quality analysis across spec.md, plan.md, and tasks.md after task generation."
|
||||
argument-hint: "Optional focus areas for analysis"
|
||||
compatibility: "Requires spec-kit project structure with .specify/ directory"
|
||||
metadata:
|
||||
author: "github-spec-kit"
|
||||
source: "templates/commands/analyze.md"
|
||||
user-invocable: true
|
||||
disable-model-invocation: false
|
||||
---
|
||||
|
||||
|
||||
## 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, skip hook checking silently and 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
|
||||
- When constructing slash commands from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`.
|
||||
- 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.
|
||||
```
|
||||
- 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/powershell/check-prerequisites.ps1 -Json -RequireTasks -IncludeTasks` 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, skip hook checking silently and 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
|
||||
- When constructing slash commands from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`.
|
||||
- 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}
|
||||
```
|
||||
- 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
|
||||
@@ -0,0 +1,374 @@
|
||||
---
|
||||
name: "speckit-checklist"
|
||||
description: "Generate a custom checklist for the current feature based on user requirements."
|
||||
argument-hint: "Domain or focus area for the checklist"
|
||||
compatibility: "Requires spec-kit project structure with .specify/ directory"
|
||||
metadata:
|
||||
author: "github-spec-kit"
|
||||
source: "templates/commands/checklist.md"
|
||||
user-invocable: true
|
||||
disable-model-invocation: false
|
||||
---
|
||||
|
||||
|
||||
## 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.
|
||||
|
||||
## 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, skip hook checking silently and 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
|
||||
- When constructing slash commands from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`.
|
||||
- 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.
|
||||
```
|
||||
- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently
|
||||
|
||||
## Execution Steps
|
||||
|
||||
1. **Setup**: Run `.specify/scripts/powershell/check-prerequisites.ps1 -Json` from repo root and parse JSON for FEATURE_DIR and AVAILABLE_DOCS list.
|
||||
- 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** - 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
|
||||
|
||||
**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, and ID formatting. If template is unavailable, use: H1 title, purpose/created meta lines, `##` category sections containing `- [ ] CHK### <requirement item>` lines with globally incrementing IDs starting at CHK001.
|
||||
|
||||
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, skip hook checking silently and 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
|
||||
- When constructing slash commands from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`.
|
||||
- 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}
|
||||
```
|
||||
- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently
|
||||
@@ -0,0 +1,286 @@
|
||||
---
|
||||
name: "speckit-clarify"
|
||||
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."
|
||||
argument-hint: "Optional areas to clarify in the spec"
|
||||
compatibility: "Requires spec-kit project structure with .specify/ directory"
|
||||
metadata:
|
||||
author: "github-spec-kit"
|
||||
source: "templates/commands/clarify.md"
|
||||
user-invocable: true
|
||||
disable-model-invocation: false
|
||||
---
|
||||
|
||||
|
||||
## 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, skip hook checking silently and 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
|
||||
- When constructing slash commands from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`.
|
||||
- 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.
|
||||
```
|
||||
- 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/powershell/check-prerequisites.ps1 -Json -PathsOnly` 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
|
||||
- Information is better deferred to planning phase (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.
|
||||
- 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, skip hook checking silently and 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
|
||||
- When constructing slash commands from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`.
|
||||
- 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}
|
||||
```
|
||||
- **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 better suited for planning), 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
|
||||
@@ -0,0 +1,157 @@
|
||||
---
|
||||
name: "speckit-constitution"
|
||||
description: "Create or update the project constitution from interactive or provided principle inputs, ensuring all dependent templates stay in sync."
|
||||
argument-hint: "Principles or values for the project constitution"
|
||||
compatibility: "Requires spec-kit project structure with .specify/ directory"
|
||||
metadata:
|
||||
author: "github-spec-kit"
|
||||
source: "templates/commands/constitution.md"
|
||||
user-invocable: true
|
||||
disable-model-invocation: false
|
||||
---
|
||||
|
||||
|
||||
## User Input
|
||||
|
||||
```text
|
||||
$ARGUMENTS
|
||||
```
|
||||
|
||||
You **MUST** consider the user input before proceeding (if not empty).
|
||||
|
||||
## 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, skip hook checking silently and 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
|
||||
- When constructing slash commands from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`.
|
||||
- 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.
|
||||
```
|
||||
- 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`. This file is a TEMPLATE containing placeholder tokens in square brackets (e.g. `[PROJECT_NAME]`, `[PRINCIPLE_1_NAME]`). Your job is to (a) collect/derive concrete values, (b) fill the template precisely, and (c) propagate any amendments across dependent artifacts.
|
||||
|
||||
**Note**: If `.specify/memory/constitution.md` does not exist yet, it should have been initialized from `.specify/templates/constitution-template.md` during project setup. If it's missing, copy the template first.
|
||||
|
||||
Follow this execution flow:
|
||||
|
||||
1. Load the existing constitution at `.specify/memory/constitution.md`.
|
||||
- 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:
|
||||
- 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. Consistency propagation checklist (convert prior checklist into active validations):
|
||||
- Read `.specify/templates/plan-template.md` and ensure any "Constitution Check" or rules align with updated principles.
|
||||
- Read `.specify/templates/spec-template.md` for scope/requirements alignment—update if constitution adds/removes mandatory sections or constraints.
|
||||
- Read `.specify/templates/tasks-template.md` and ensure task categorization reflects new or removed principle-driven task types (e.g., observability, versioning, testing discipline).
|
||||
- Read each command file in `.specify/templates/commands/*.md` (including this one) to verify no outdated references (agent-specific names like CLAUDE only) remain when generic guidance is required.
|
||||
- Read any runtime guidance docs (e.g., `README.md`, `docs/quickstart.md`, or agent-specific guidance files if present). Update references to principles changed.
|
||||
|
||||
5. Produce a Sync Impact Report (prepend as an HTML comment at top of the constitution file after update):
|
||||
- Version change: old → new
|
||||
- List of modified principles (old title → new title if renamed)
|
||||
- Added sections
|
||||
- Removed sections
|
||||
- Templates requiring updates (✅ updated / ⚠ pending) with file paths
|
||||
- Follow-up TODOs if any placeholders intentionally deferred.
|
||||
|
||||
6. 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).
|
||||
|
||||
7. Write the completed constitution back to `.specify/memory/constitution.md` (overwrite).
|
||||
|
||||
8. Output a final summary to the user with:
|
||||
- New version and bump rationale.
|
||||
- Any files flagged for manual follow-up.
|
||||
- Suggested commit message (e.g., `docs: amend constitution to vX.Y.Z (principle additions + governance update)`).
|
||||
|
||||
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.
|
||||
|
||||
Do not create a new template; always operate on the existing `.specify/memory/constitution.md` file.
|
||||
|
||||
## 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, skip hook checking silently and 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
|
||||
- When constructing slash commands from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`.
|
||||
- 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}
|
||||
```
|
||||
- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently
|
||||
@@ -0,0 +1,53 @@
|
||||
---
|
||||
name: speckit-git-commit
|
||||
description: Auto-commit changes after a Spec Kit command completes
|
||||
compatibility: Requires spec-kit project structure with .specify/ directory
|
||||
metadata:
|
||||
author: github-spec-kit
|
||||
source: git:commands/speckit.git.commit.md
|
||||
---
|
||||
|
||||
# Auto-Commit Changes
|
||||
|
||||
Automatically stage and commit all changes after a Spec Kit command completes.
|
||||
|
||||
## Behavior
|
||||
|
||||
This command is invoked as a hook after (or before) core commands. It:
|
||||
|
||||
1. Determines the event name from the hook context (e.g., if invoked as an `after_specify` hook, the event is `after_specify`; if `before_plan`, the event is `before_plan`)
|
||||
2. Checks `.specify/extensions/git/git-config.yml` for the `auto_commit` section
|
||||
3. Looks up the specific event key to see if auto-commit is enabled
|
||||
4. Falls back to `auto_commit.default` if no event-specific key exists
|
||||
5. Uses the per-command `message` if configured, otherwise a default message
|
||||
6. If enabled and there are uncommitted changes, runs `git add .` + `git commit`
|
||||
|
||||
## Execution
|
||||
|
||||
Determine the event name from the hook that triggered this command, then run the script:
|
||||
|
||||
- **Bash**: `.specify/extensions/git/scripts/bash/auto-commit.sh <event_name>`
|
||||
- **PowerShell**: `.specify/extensions/git/scripts/powershell/auto-commit.ps1 <event_name>`
|
||||
|
||||
Replace `<event_name>` with the actual hook event (e.g., `after_specify`, `before_plan`, `after_implement`).
|
||||
|
||||
## Configuration
|
||||
|
||||
In `.specify/extensions/git/git-config.yml`:
|
||||
|
||||
```yaml
|
||||
auto_commit:
|
||||
default: false # Global toggle — set true to enable for all commands
|
||||
after_specify:
|
||||
enabled: true # Override per-command
|
||||
message: "[Spec Kit] Add specification"
|
||||
after_plan:
|
||||
enabled: false
|
||||
message: "[Spec Kit] Add implementation plan"
|
||||
```
|
||||
|
||||
## Graceful Degradation
|
||||
|
||||
- If Git is not available or the current directory is not a repository: skips with a warning
|
||||
- If no config file exists: skips (disabled by default)
|
||||
- If no changes to commit: skips with a message
|
||||
@@ -0,0 +1,72 @@
|
||||
---
|
||||
name: speckit-git-feature
|
||||
description: Create a feature branch with sequential or timestamp numbering
|
||||
compatibility: Requires spec-kit project structure with .specify/ directory
|
||||
metadata:
|
||||
author: github-spec-kit
|
||||
source: git:commands/speckit.git.feature.md
|
||||
---
|
||||
|
||||
# Create Feature Branch
|
||||
|
||||
Create and switch to a new git feature branch for the given specification. This command handles **branch creation only** — the spec directory and files are created by the core `/speckit-specify` workflow.
|
||||
|
||||
## User Input
|
||||
|
||||
```text
|
||||
$ARGUMENTS
|
||||
```
|
||||
|
||||
You **MUST** consider the user input before proceeding (if not empty).
|
||||
|
||||
## Environment Variable Override
|
||||
|
||||
If the user explicitly provided `GIT_BRANCH_NAME` (e.g., via environment variable, argument, or in their request), pass it through to the script by setting the `GIT_BRANCH_NAME` environment variable before invoking the script. When `GIT_BRANCH_NAME` is set:
|
||||
- The script uses the exact value as the branch name, bypassing all prefix/suffix generation
|
||||
- `--short-name`, `--number`, and `--timestamp` flags are ignored
|
||||
- `FEATURE_NUM` is extracted from the name if it starts with a numeric prefix, otherwise set to the full branch name
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Verify Git is available by running `git rev-parse --is-inside-work-tree 2>/dev/null`
|
||||
- If Git is not available, warn the user and skip branch creation
|
||||
|
||||
## Branch Numbering Mode
|
||||
|
||||
Determine the branch numbering strategy by checking configuration in this order:
|
||||
|
||||
1. Check `.specify/extensions/git/git-config.yml` for `branch_numbering` value
|
||||
2. Check `.specify/init-options.json` for `branch_numbering` value (backward compatibility)
|
||||
3. Default to `sequential` if neither exists
|
||||
|
||||
## Execution
|
||||
|
||||
Generate a concise short name (2-4 words) for the branch:
|
||||
- Analyze the feature description and extract the most meaningful keywords
|
||||
- Use action-noun format when possible (e.g., "add-user-auth", "fix-payment-bug")
|
||||
- Preserve technical terms and acronyms (OAuth2, API, JWT, etc.)
|
||||
|
||||
Run the appropriate script based on your platform:
|
||||
|
||||
- **Bash**: `.specify/extensions/git/scripts/bash/create-new-feature.sh --json --short-name "<short-name>" "<feature description>"`
|
||||
- **Bash (timestamp)**: `.specify/extensions/git/scripts/bash/create-new-feature.sh --json --timestamp --short-name "<short-name>" "<feature description>"`
|
||||
- **PowerShell**: `.specify/extensions/git/scripts/powershell/create-new-feature.ps1 -Json -ShortName "<short-name>" "<feature description>"`
|
||||
- **PowerShell (timestamp)**: `.specify/extensions/git/scripts/powershell/create-new-feature.ps1 -Json -Timestamp -ShortName "<short-name>" "<feature description>"`
|
||||
|
||||
**IMPORTANT**:
|
||||
- Do NOT pass `--number` — the script determines the correct next number automatically
|
||||
- Always include the JSON flag (`--json` for Bash, `-Json` for PowerShell) so the output can be parsed reliably
|
||||
- You must only ever run this script once per feature
|
||||
- The JSON output will contain `BRANCH_NAME` and `FEATURE_NUM`
|
||||
|
||||
## Graceful Degradation
|
||||
|
||||
If Git is not installed or the current directory is not a Git repository:
|
||||
- Branch creation is skipped with a warning: `[specify] Warning: Git repository not detected; skipped branch creation`
|
||||
- The script still outputs `BRANCH_NAME` and `FEATURE_NUM` so the caller can reference them
|
||||
|
||||
## Output
|
||||
|
||||
The script outputs JSON with:
|
||||
- `BRANCH_NAME`: The branch name (e.g., `003-user-auth` or `20260319-143022-user-auth`)
|
||||
- `FEATURE_NUM`: The numeric or timestamp prefix used
|
||||
@@ -0,0 +1,54 @@
|
||||
---
|
||||
name: speckit-git-initialize
|
||||
description: Initialize a Git repository with an initial commit
|
||||
compatibility: Requires spec-kit project structure with .specify/ directory
|
||||
metadata:
|
||||
author: github-spec-kit
|
||||
source: git:commands/speckit.git.initialize.md
|
||||
---
|
||||
|
||||
# Initialize Git Repository
|
||||
|
||||
Initialize a Git repository in the current project directory if one does not already exist.
|
||||
|
||||
## Execution
|
||||
|
||||
Run the appropriate script from the project root:
|
||||
|
||||
- **Bash**: `.specify/extensions/git/scripts/bash/initialize-repo.sh`
|
||||
- **PowerShell**: `.specify/extensions/git/scripts/powershell/initialize-repo.ps1`
|
||||
|
||||
If the extension scripts are not found, fall back to:
|
||||
- **Bash**: `git init && git add . && git commit -m "Initial commit from Specify template"`
|
||||
- **PowerShell**: `git init; git add .; git commit -m "Initial commit from Specify template"`
|
||||
|
||||
The script handles all checks internally:
|
||||
- Skips if Git is not available
|
||||
- Skips if already inside a Git repository
|
||||
- Runs `git init`, `git add .`, and `git commit` with an initial commit message
|
||||
|
||||
## Customization
|
||||
|
||||
Replace the script to add project-specific Git initialization steps:
|
||||
- Custom `.gitignore` templates
|
||||
- Default branch naming (`git config init.defaultBranch`)
|
||||
- Git LFS setup
|
||||
- Git hooks installation
|
||||
- Commit signing configuration
|
||||
- Git Flow initialization
|
||||
|
||||
## Output
|
||||
|
||||
On success:
|
||||
- `[OK] Git repository initialized`
|
||||
|
||||
## Graceful Degradation
|
||||
|
||||
If Git is not installed:
|
||||
- Warn the user
|
||||
- Skip repository initialization
|
||||
- The project continues to function without Git (specs can still be created under `specs/`)
|
||||
|
||||
If Git is installed but `git init`, `git add .`, or `git commit` fails:
|
||||
- Surface the error to the user
|
||||
- Stop this command rather than continuing with a partially initialized repository
|
||||
@@ -0,0 +1,50 @@
|
||||
---
|
||||
name: speckit-git-remote
|
||||
description: Detect Git remote URL for GitHub integration
|
||||
compatibility: Requires spec-kit project structure with .specify/ directory
|
||||
metadata:
|
||||
author: github-spec-kit
|
||||
source: git:commands/speckit.git.remote.md
|
||||
---
|
||||
|
||||
# Detect Git Remote URL
|
||||
|
||||
Detect the Git remote URL for integration with GitHub services (e.g., issue creation).
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Check if Git is available by running `git rev-parse --is-inside-work-tree 2>/dev/null`
|
||||
- If Git is not available, output a warning and return empty:
|
||||
```
|
||||
[specify] Warning: Git repository not detected; cannot determine remote URL
|
||||
```
|
||||
|
||||
## Execution
|
||||
|
||||
Run the following command to get the remote URL:
|
||||
|
||||
```bash
|
||||
git config --get remote.origin.url
|
||||
```
|
||||
|
||||
## Output
|
||||
|
||||
Parse the remote URL and determine:
|
||||
|
||||
1. **Repository owner**: Extract from the URL (e.g., `github` from `https://github.com/github/spec-kit.git`)
|
||||
2. **Repository name**: Extract from the URL (e.g., `spec-kit` from `https://github.com/github/spec-kit.git`)
|
||||
3. **Is GitHub**: Whether the remote points to a GitHub repository
|
||||
|
||||
Supported URL formats:
|
||||
- HTTPS: `https://github.com/<owner>/<repo>.git`
|
||||
- SSH: `git@github.com:<owner>/<repo>.git`
|
||||
|
||||
> [!CAUTION]
|
||||
> ONLY report a GitHub repository if the remote URL actually points to github.com.
|
||||
> Do NOT assume the remote is GitHub if the URL format doesn't match.
|
||||
|
||||
## Graceful Degradation
|
||||
|
||||
If Git is not installed, the directory is not a Git repository, or no remote is configured:
|
||||
- Return an empty result
|
||||
- Do NOT error — other workflows should continue without Git remote information
|
||||
@@ -0,0 +1,54 @@
|
||||
---
|
||||
name: speckit-git-validate
|
||||
description: Validate current branch follows feature branch naming conventions
|
||||
compatibility: Requires spec-kit project structure with .specify/ directory
|
||||
metadata:
|
||||
author: github-spec-kit
|
||||
source: git:commands/speckit.git.validate.md
|
||||
---
|
||||
|
||||
# Validate Feature Branch
|
||||
|
||||
Validate that the current Git branch follows the expected feature branch naming conventions.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Check if Git is available by running `git rev-parse --is-inside-work-tree 2>/dev/null`
|
||||
- If Git is not available, output a warning and skip validation:
|
||||
```
|
||||
[specify] Warning: Git repository not detected; skipped branch validation
|
||||
```
|
||||
|
||||
## Validation Rules
|
||||
|
||||
Get the current branch name:
|
||||
|
||||
```bash
|
||||
git rev-parse --abbrev-ref HEAD
|
||||
```
|
||||
|
||||
The branch name must match one of these patterns:
|
||||
|
||||
1. **Sequential**: `^[0-9]{3,}-` (e.g., `001-feature-name`, `042-fix-bug`, `1000-big-feature`)
|
||||
2. **Timestamp**: `^[0-9]{8}-[0-9]{6}-` (e.g., `20260319-143022-feature-name`)
|
||||
|
||||
## Execution
|
||||
|
||||
If on a feature branch (matches either pattern):
|
||||
- Output: `✓ On feature branch: <branch-name>`
|
||||
- Check if the corresponding spec directory exists under `specs/`:
|
||||
- For sequential branches, look for `specs/<prefix>-*` where prefix matches the numeric portion
|
||||
- For timestamp branches, look for `specs/<prefix>-*` where prefix matches the `YYYYMMDD-HHMMSS` portion
|
||||
- If spec directory exists: `✓ Spec directory found: <path>`
|
||||
- If spec directory missing: `⚠ No spec directory found for prefix <prefix>`
|
||||
|
||||
If NOT on a feature branch:
|
||||
- Output: `✗ Not on a feature branch. Current branch: <branch-name>`
|
||||
- Output: `Feature branches should be named like: 001-feature-name or 20260319-143022-feature-name`
|
||||
|
||||
## Graceful Degradation
|
||||
|
||||
If Git is not installed or the directory is not a Git repository:
|
||||
- Check the `SPECIFY_FEATURE` environment variable as a fallback
|
||||
- If set, validate that value against the naming patterns
|
||||
- If not set, skip validation with a warning
|
||||
@@ -0,0 +1,224 @@
|
||||
---
|
||||
name: "speckit-implement"
|
||||
description: "Execute the implementation plan by processing and executing all tasks defined in tasks.md"
|
||||
argument-hint: "Optional implementation guidance or task filter"
|
||||
compatibility: "Requires spec-kit project structure with .specify/ directory"
|
||||
metadata:
|
||||
author: "github-spec-kit"
|
||||
source: "templates/commands/implement.md"
|
||||
user-invocable: true
|
||||
disable-model-invocation: false
|
||||
---
|
||||
|
||||
|
||||
## 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, skip hook checking silently and 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
|
||||
- When constructing slash commands from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`.
|
||||
- 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.
|
||||
```
|
||||
- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently
|
||||
|
||||
## Outline
|
||||
|
||||
1. Run `.specify/scripts/powershell/check-prerequisites.ps1 -Json -RequireTasks -IncludeTasks` 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):
|
||||
- Scan all checklist files in the checklists/ directory
|
||||
- For each checklist, count:
|
||||
- Total items: All lines matching `- [ ]` or `- [X]` or `- [x]`
|
||||
- Completed items: Lines matching `- [X]` or `- [x]`
|
||||
- Incomplete items: Lines matching `- [ ]`
|
||||
- Create a status table:
|
||||
|
||||
```text
|
||||
| Checklist | Total | Completed | Incomplete | 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 incomplete items
|
||||
- **FAIL**: One or more checklists have incomplete items
|
||||
|
||||
- **If any checklist is incomplete**:
|
||||
- Display the table with incomplete item counts
|
||||
- **STOP** and ask: "Some checklists are incomplete. 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 complete**:
|
||||
- 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, skip hook checking silently and 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
|
||||
- When constructing slash commands from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`.
|
||||
- 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}
|
||||
```
|
||||
- **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
|
||||
@@ -0,0 +1,164 @@
|
||||
---
|
||||
name: "speckit-plan"
|
||||
description: "Execute the implementation planning workflow using the plan template to generate design artifacts."
|
||||
argument-hint: "Optional guidance for the planning phase"
|
||||
compatibility: "Requires spec-kit project structure with .specify/ directory"
|
||||
metadata:
|
||||
author: "github-spec-kit"
|
||||
source: "templates/commands/plan.md"
|
||||
user-invocable: true
|
||||
disable-model-invocation: false
|
||||
---
|
||||
|
||||
|
||||
## 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, skip hook checking silently and 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
|
||||
- When constructing slash commands from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`.
|
||||
- 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.
|
||||
```
|
||||
- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently
|
||||
|
||||
## Outline
|
||||
|
||||
1. **Setup**: Run `.specify/scripts/powershell/setup-plan.ps1 -Json` from repo root and parse JSON for FEATURE_SPEC, IMPL_PLAN, SPECS_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
|
||||
- Phase 1: Update agent context by running the agent script
|
||||
- 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, skip hook checking silently and 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
|
||||
- When constructing slash commands from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`.
|
||||
- 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}
|
||||
```
|
||||
- **Optional hook** (`optional: true`):
|
||||
```
|
||||
## Extension Hooks
|
||||
|
||||
**Optional Hook**: {extension}
|
||||
Command: `/{command}`
|
||||
Description: {description}
|
||||
|
||||
Prompt: {prompt}
|
||||
To execute: `/{command}`
|
||||
```
|
||||
|
||||
## Completion Report
|
||||
|
||||
Command ends after Phase 2 planning. 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. **Agent context update**:
|
||||
- Update the plan reference between the `<!-- SPECKIT START -->` and `<!-- SPECKIT END -->` markers in `CLAUDE.md` to point to the plan file created in step 1 (the IMPL_PLAN path)
|
||||
|
||||
**Output**: data-model.md, /contracts/*, quickstart.md, updated agent context file
|
||||
|
||||
## Key rules
|
||||
|
||||
- Use absolute paths for filesystem operations; use project-relative paths for references in documentation and agent context files
|
||||
- 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
|
||||
@@ -0,0 +1,344 @@
|
||||
---
|
||||
name: "speckit-specify"
|
||||
description: "Create or update the feature specification from a natural language feature description."
|
||||
argument-hint: "Describe the feature you want to specify"
|
||||
compatibility: "Requires spec-kit project structure with .specify/ directory"
|
||||
metadata:
|
||||
author: "github-spec-kit"
|
||||
source: "templates/commands/specify.md"
|
||||
user-invocable: true
|
||||
disable-model-invocation: false
|
||||
---
|
||||
|
||||
|
||||
## 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, skip hook checking silently and 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
|
||||
- When constructing slash commands from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`.
|
||||
- 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.
|
||||
```
|
||||
- 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 `branch_numbering`
|
||||
- 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>`
|
||||
|
||||
**Create the directory and spec file**:
|
||||
- `mkdir -p SPECIFY_FEATURE_DIRECTORY`
|
||||
- Copy `.specify/templates/spec-template.md` 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 `.specify/templates/spec-template.md` 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)
|
||||
|
||||
6. 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.
|
||||
|
||||
7. **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, skip hook checking silently and 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
|
||||
- When constructing slash commands from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`.
|
||||
- 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}
|
||||
```
|
||||
- **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
|
||||
@@ -0,0 +1,215 @@
|
||||
---
|
||||
name: "speckit-tasks"
|
||||
description: "Generate an actionable, dependency-ordered tasks.md for the feature based on available design artifacts."
|
||||
argument-hint: "Optional task generation constraints"
|
||||
compatibility: "Requires spec-kit project structure with .specify/ directory"
|
||||
metadata:
|
||||
author: "github-spec-kit"
|
||||
source: "templates/commands/tasks.md"
|
||||
user-invocable: true
|
||||
disable-model-invocation: false
|
||||
---
|
||||
|
||||
|
||||
## 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, skip hook checking silently and 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
|
||||
- When constructing slash commands from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`.
|
||||
- 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.
|
||||
```
|
||||
- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently
|
||||
|
||||
## Outline
|
||||
|
||||
1. **Setup**: Run `.specify/scripts/powershell/setup-tasks.ps1 -Json` from repo root and parse FEATURE_DIR, 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**: Read the tasks template from TASKS_TEMPLATE (from the JSON output above) and use it as structure. If TASKS_TEMPLATE is empty, fall back to `.specify/templates/tasks-template.md`. 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, skip hook checking silently and 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
|
||||
- When constructing slash commands from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`.
|
||||
- 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}
|
||||
```
|
||||
- **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
|
||||
|
||||
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
|
||||
@@ -0,0 +1,107 @@
|
||||
---
|
||||
name: "speckit-taskstoissues"
|
||||
description: "Convert existing tasks into actionable, dependency-ordered GitHub issues for the feature based on available design artifacts."
|
||||
argument-hint: "Optional filter or label for GitHub issues"
|
||||
compatibility: "Requires spec-kit project structure with .specify/ directory"
|
||||
metadata:
|
||||
author: "github-spec-kit"
|
||||
source: "templates/commands/taskstoissues.md"
|
||||
user-invocable: true
|
||||
disable-model-invocation: false
|
||||
---
|
||||
|
||||
|
||||
## 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, skip hook checking silently and 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
|
||||
- When constructing slash commands from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`.
|
||||
- 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.
|
||||
```
|
||||
- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently
|
||||
|
||||
## Outline
|
||||
|
||||
1. Run `.specify/scripts/powershell/check-prerequisites.ps1 -Json -RequireTasks -IncludeTasks` 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. 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.
|
||||
|
||||
> [!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, skip hook checking silently and 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
|
||||
- When constructing slash commands from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`.
|
||||
- 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}
|
||||
```
|
||||
- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently
|
||||
@@ -0,0 +1,49 @@
|
||||
---
|
||||
name: whatsapp-meta-app-review
|
||||
description: Prepare, debug, and resubmit Meta App Review for a WhatsApp SaaS using Embedded Signup, whatsapp_business_management, and whatsapp_business_messaging. Use when drafting permission usage notes, writing screencast scripts, reviewing rejection reasons, building a review-only flow, or turning a partially working WhatsApp SaaS into an approval-ready product.
|
||||
---
|
||||
|
||||
# WhatsApp Meta App Review
|
||||
|
||||
Use this skill to convert a WhatsApp SaaS into an approval-ready Meta App Review submission.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. Identify the exact permissions in scope and the user's current review status.
|
||||
2. Check whether the product already proves three things inside the app:
|
||||
- onboarding through Meta Embedded Signup,
|
||||
- reading real WhatsApp assets,
|
||||
- sending a real approved template.
|
||||
3. Read the reference file that matches the task:
|
||||
- `references/approved-flow.md` for the approved screencast structure and narration
|
||||
- `references/submission-copy.md` for permission notes and reviewer-facing language
|
||||
- `references/rejection-patterns.md` for common rejection causes and concrete fixes
|
||||
4. Produce the smallest useful artifact:
|
||||
- revised permission notes,
|
||||
- video script,
|
||||
- review checklist,
|
||||
- review-only page requirements,
|
||||
- or rejection remediation plan.
|
||||
|
||||
## Guardrails
|
||||
|
||||
- Do not recommend requesting permissions before the core path is real.
|
||||
- Require the app to show actual in-product evidence, not only Postman, n8n, or logs.
|
||||
- Keep the video linear and short.
|
||||
- Make the written notes match the screencast exactly.
|
||||
- Prefer English UI, narration, and reviewer notes unless the user explicitly wants another language.
|
||||
|
||||
## Minimum proof standard
|
||||
|
||||
Treat these as non-negotiable for approval work:
|
||||
|
||||
- the business connects its own account,
|
||||
- the app reads the connected phone number and templates,
|
||||
- the app sends an approved template,
|
||||
- the recipient device shows the delivered message.
|
||||
|
||||
## Output style
|
||||
|
||||
- Be specific and reviewer-friendly.
|
||||
- Phrase notes as product behavior, not vague API claims.
|
||||
- When asked to fix a rejection, map each reviewer complaint to the missing proof in the product or the video.
|
||||
@@ -0,0 +1,50 @@
|
||||
# Approved flow for Meta App Review
|
||||
|
||||
Use this reference when the task is to script, review, or rebuild the exact flow that should appear in the submission video.
|
||||
|
||||
## Approved narrative pattern
|
||||
|
||||
The strongest flow is:
|
||||
|
||||
1. Introduce the product and use case in one sentence.
|
||||
2. Run the full Meta Embedded Signup flow.
|
||||
3. Return to the app and show the connected phone number and IDs.
|
||||
4. Create a new reminder template.
|
||||
5. Show the template in pending or approved state.
|
||||
6. Send the approved template to a test recipient.
|
||||
7. Show the message on the recipient device.
|
||||
|
||||
## Approved example script
|
||||
|
||||
Use this exact sequence as a baseline:
|
||||
|
||||
```text
|
||||
This is Suscripta, a SaaS for subscription payment reminders on WhatsApp.
|
||||
First, the business connects its own WhatsApp Business account through Meta Embedded Signup.
|
||||
|
||||
After the connection, Suscripta reads the connected phone numbers and their IDs.
|
||||
Here is the connection established.
|
||||
|
||||
I will create a new template of a subscription reminder.
|
||||
Now I will send this template to the approval process in Meta.
|
||||
Here I can see this template with the pending status.
|
||||
Now I will send the approved template to a test recipient.
|
||||
|
||||
The message was sent successfully and here it is on the recipient device.
|
||||
```
|
||||
|
||||
## What each step proves
|
||||
|
||||
- Embedded Signup proves the user is connecting their own business account.
|
||||
- Reading the phone number and IDs proves asset access through `whatsapp_business_management`.
|
||||
- Creating and listing templates proves the app is operating on real WhatsApp Business assets.
|
||||
- Sending the approved template proves `whatsapp_business_messaging`.
|
||||
- Showing the recipient device proves the end-to-end use case.
|
||||
|
||||
## Video constraints
|
||||
|
||||
- Keep it linear.
|
||||
- Avoid detours into debugging tools.
|
||||
- Avoid admin setup that the reviewer does not need.
|
||||
- Target 2 to 4 minutes.
|
||||
- Show the real recipient device whenever possible.
|
||||
@@ -0,0 +1,65 @@
|
||||
# Common rejection patterns and fixes
|
||||
|
||||
Use this reference when the user already submitted for App Review and needs to understand why Meta rejected the request.
|
||||
|
||||
## Pattern: "The screencast does not match the use case details"
|
||||
|
||||
Typical cause:
|
||||
|
||||
- The app notes describe a full flow, but the video only shows onboarding or only shows a dashboard.
|
||||
|
||||
Fix:
|
||||
|
||||
- Re-record the screencast so the product behavior and the written notes match exactly.
|
||||
- Include onboarding, asset reading, sending, and the recipient device.
|
||||
|
||||
## Pattern: Incomplete permission proof
|
||||
|
||||
Typical cause:
|
||||
|
||||
- `whatsapp_business_management` was requested, but the app never visibly loads phone assets or templates.
|
||||
- `whatsapp_business_messaging` was requested, but the app never shows a real template send.
|
||||
|
||||
Fix:
|
||||
|
||||
- Make the critical areas real before reapplying.
|
||||
- Show those areas clearly in the product UI.
|
||||
|
||||
## Pattern: Product looks mocked
|
||||
|
||||
Typical cause:
|
||||
|
||||
- Core screens contain only static data.
|
||||
|
||||
Fix:
|
||||
|
||||
- Replace the permission-critical sections with real data:
|
||||
- connected number,
|
||||
- template list,
|
||||
- recent message activity,
|
||||
- or real send outcome.
|
||||
|
||||
## Pattern: Review build breaks during the flow
|
||||
|
||||
Typical cause:
|
||||
|
||||
- missing environment variables,
|
||||
- OAuth mismatch,
|
||||
- failed code exchange,
|
||||
- number not operational,
|
||||
- no approved template available.
|
||||
|
||||
Fix:
|
||||
|
||||
- Make the review build boringly reliable.
|
||||
- Remove debug UI from the screencast surface after troubleshooting.
|
||||
|
||||
## Approval checklist
|
||||
|
||||
- Production route exists and loads.
|
||||
- Embedded Signup completes.
|
||||
- Connection persists.
|
||||
- Number appears in app.
|
||||
- Template exists and is approved.
|
||||
- Message is sent from the app.
|
||||
- Recipient device shows the message.
|
||||
@@ -0,0 +1,43 @@
|
||||
# Submission copy for Meta App Review
|
||||
|
||||
Use this reference when asked to draft permission notes, reviewer explanations, or English copy for the submission form.
|
||||
|
||||
## `whatsapp_business_messaging`
|
||||
|
||||
```text
|
||||
This app uses whatsapp_business_messaging to send subscription payment reminder messages from the customer's own connected WhatsApp Business phone number.
|
||||
|
||||
Our users are businesses that manage recurring subscriptions or renewals. Inside the app, the business connects its own WhatsApp Business account through the official Meta Embedded Signup flow. After the connection is completed, the app stores the connected WhatsApp Business Account ID and Phone Number ID and then uses approved WhatsApp message templates to send payment reminder notifications to opted-in end customers.
|
||||
|
||||
This permission is used only after the business connects its account and only for sending business notifications related to subscription renewal or payment reminder use cases.
|
||||
```
|
||||
|
||||
## `whatsapp_business_management`
|
||||
|
||||
```text
|
||||
This app uses whatsapp_business_management to retrieve and manage the WhatsApp Business assets required for the platform after the business connects through Meta Embedded Signup.
|
||||
|
||||
After the user completes the Embedded Signup flow, the app reads the connected WhatsApp Business Account information, the connected Phone Number ID, and the WhatsApp message templates associated with that account. This information is used to configure the workspace inside the app and allow the business to select approved templates and operate its reminder workflows.
|
||||
|
||||
This permission is used only to read and manage the WhatsApp Business assets necessary for the business to operate its own connected account inside the platform.
|
||||
```
|
||||
|
||||
## Video notes block
|
||||
|
||||
```text
|
||||
The video shows:
|
||||
1. The complete Meta Embedded Signup flow.
|
||||
2. The user granting access to the requested permissions.
|
||||
3. The connected business phone number displayed inside the app.
|
||||
4. The list of WhatsApp templates loaded from the connected account.
|
||||
5. A live approved template message being sent to a test recipient.
|
||||
6. The final message received on the recipient device.
|
||||
```
|
||||
|
||||
## Writing rules
|
||||
|
||||
- Describe product behavior, not generic API usage.
|
||||
- Mention the business connects its own account.
|
||||
- Mention approved templates.
|
||||
- Mention the connected phone number and IDs.
|
||||
- Match the video exactly.
|
||||
@@ -0,0 +1,53 @@
|
||||
---
|
||||
name: whatsapp-saas-meta-infra
|
||||
description: Implement and troubleshoot WhatsApp SaaS infrastructure on Meta Graph API and WhatsApp Cloud API. Use when building Embedded Signup, OAuth callbacks, webhook verification, message status handling, data deletion or deauthorize callbacks, Supabase persistence, or Vercel deployment for a product where each customer connects their own WhatsApp Business account.
|
||||
---
|
||||
|
||||
# WhatsApp SaaS Meta Infra
|
||||
|
||||
Use this skill to build the infrastructure layer of a WhatsApp SaaS, not just isolated API calls.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. Identify the missing layer:
|
||||
- Meta app configuration,
|
||||
- Embedded Signup,
|
||||
- token exchange,
|
||||
- webhook ingestion,
|
||||
- Supabase schema,
|
||||
- message sending,
|
||||
- or data deletion / deauthorize handling.
|
||||
2. Read the matching reference file:
|
||||
- `references/architecture.md` for the overall system design
|
||||
- `references/implementation-sequence.md` for the recommended build order
|
||||
- `references/meta-config.md` for Meta app settings, callback URLs, and review-facing config
|
||||
- `references/api-blueprint.md` for backend route contracts and responsibilities
|
||||
- `references/supabase-schema.md` for SQL and data modeling
|
||||
3. Implement the missing layer in the user's stack.
|
||||
4. Validate the full chain, not only the isolated endpoint.
|
||||
|
||||
## Guardrails
|
||||
|
||||
- Keep secrets server-side.
|
||||
- Do not equate `accepted` with `delivered`.
|
||||
- Save enough identity data to support deauthorize callbacks later.
|
||||
- Make webhooks idempotent and upsert by `message_id`.
|
||||
- Revalidate local connection state against Meta when assets may have been deleted.
|
||||
|
||||
## Minimum infrastructure standard
|
||||
|
||||
Treat these as the baseline:
|
||||
|
||||
- a real OAuth or Embedded Signup completion path,
|
||||
- a backend code exchange endpoint,
|
||||
- a webhook with GET verification and POST ingestion,
|
||||
- Supabase tables for connections and message events,
|
||||
- real message send actions,
|
||||
- message status persistence,
|
||||
- a deauthorize or data deletion path for compliance.
|
||||
|
||||
## Output style
|
||||
|
||||
- Favor architecture and implementation order over scattered snippets.
|
||||
- Show which part runs in frontend, backend, Meta, and database.
|
||||
- When writing code, produce production-leaning defaults rather than demo-only code.
|
||||
@@ -0,0 +1,104 @@
|
||||
# Backend API blueprint
|
||||
|
||||
Use this reference when the user wants concrete backend responsibilities and route design.
|
||||
|
||||
## Recommended routes
|
||||
|
||||
### 1. Code exchange endpoint
|
||||
|
||||
Example:
|
||||
|
||||
```text
|
||||
POST /api/whatsapp/exchange-token
|
||||
```
|
||||
|
||||
Input:
|
||||
|
||||
- `code`
|
||||
- `waba_id`
|
||||
- `phone_number_id`
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- validate the request,
|
||||
- exchange the code with Meta,
|
||||
- fetch connected phone metadata,
|
||||
- persist the active connection,
|
||||
- optionally store `meta_user_id`.
|
||||
|
||||
## 2. WhatsApp webhook
|
||||
|
||||
Example:
|
||||
|
||||
```text
|
||||
GET /api/whatsapp/webhook
|
||||
POST /api/whatsapp/webhook
|
||||
```
|
||||
|
||||
GET responsibilities:
|
||||
|
||||
- verify `hub.verify_token`,
|
||||
- return `hub.challenge`.
|
||||
|
||||
POST responsibilities:
|
||||
|
||||
- parse each `entry`,
|
||||
- parse each `change`,
|
||||
- process `value.statuses`,
|
||||
- process `value.messages`,
|
||||
- upsert by `message_id`.
|
||||
|
||||
## 3. Send template message
|
||||
|
||||
Example:
|
||||
|
||||
```text
|
||||
POST /api/whatsapp/send-template
|
||||
```
|
||||
|
||||
Input:
|
||||
|
||||
- recipient phone
|
||||
- approved template name
|
||||
- language code
|
||||
- template parameters
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- normalize the phone,
|
||||
- send the message through Meta,
|
||||
- store an initial outbound event as `accepted`.
|
||||
|
||||
## 4. Send freeform text message
|
||||
|
||||
Example:
|
||||
|
||||
```text
|
||||
POST /api/whatsapp/send-text
|
||||
```
|
||||
|
||||
Use this only for open customer service windows.
|
||||
|
||||
## 5. Deauthorize callback
|
||||
|
||||
Example:
|
||||
|
||||
```text
|
||||
GET /api/meta/deauthorize
|
||||
POST /api/meta/deauthorize
|
||||
```
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- read `signed_request`,
|
||||
- validate it with `HMAC-SHA256` and the app secret,
|
||||
- extract the Meta user identifier,
|
||||
- map it to the local user,
|
||||
- purge or unlink WhatsApp data,
|
||||
- return a confirmation payload.
|
||||
|
||||
## Important behavior
|
||||
|
||||
- Store only metadata and tokens server-side.
|
||||
- Never trust the UI as source of truth for message delivery.
|
||||
- Use idempotent writes for webhook processing.
|
||||
@@ -0,0 +1,40 @@
|
||||
# WhatsApp SaaS reference architecture
|
||||
|
||||
Use this reference when the user needs the system-level view.
|
||||
|
||||
## Core layers
|
||||
|
||||
1. Frontend
|
||||
2. Backend
|
||||
3. Meta Graph API / WhatsApp Cloud API
|
||||
4. Webhook endpoint
|
||||
5. Supabase
|
||||
|
||||
## Recommended flow
|
||||
|
||||
1. A business enters the SaaS.
|
||||
2. The business connects its own WhatsApp Business account through Meta Embedded Signup.
|
||||
3. Meta returns:
|
||||
- authorization code,
|
||||
- `waba_id`,
|
||||
- `phone_number_id`.
|
||||
4. The backend exchanges the code for a usable token.
|
||||
5. The backend stores the connection in Supabase.
|
||||
6. The app reads:
|
||||
- connected phone number,
|
||||
- WABA-linked assets,
|
||||
- templates.
|
||||
7. The app sends:
|
||||
- approved templates,
|
||||
- text replies when the 24-hour window is open.
|
||||
8. Meta posts statuses and inbound messages to the webhook.
|
||||
9. The backend stores those events in Supabase.
|
||||
10. The frontend renders a truthful dashboard from those records.
|
||||
|
||||
## Design principle
|
||||
|
||||
The product should not behave like a thin wrapper around API calls. The dashboard must reflect real state from:
|
||||
|
||||
- Meta assets,
|
||||
- webhook events,
|
||||
- and the local persistence layer.
|
||||
@@ -0,0 +1,57 @@
|
||||
# Recommended implementation sequence
|
||||
|
||||
Use this reference when the user is building from zero or needs a safe order of operations.
|
||||
|
||||
## Phase 1: Meta app and Embedded Signup
|
||||
|
||||
- Create the Meta app.
|
||||
- Configure the WhatsApp product.
|
||||
- Configure the OAuth redirect URL.
|
||||
- Implement the frontend launcher for Embedded Signup.
|
||||
- Capture the returned `code`, `waba_id`, and `phone_number_id`.
|
||||
|
||||
## Phase 2: Backend token exchange
|
||||
|
||||
- Create a backend endpoint for the code exchange.
|
||||
- Exchange the Meta code for a usable token.
|
||||
- Fetch phone metadata after the exchange.
|
||||
- Persist the connection in Supabase.
|
||||
- Save `meta_user_id` if available so deauthorize can map back to the local user later.
|
||||
|
||||
## Phase 3: Supabase schema
|
||||
|
||||
- Create a table for active WhatsApp connections.
|
||||
- Create a table for message events.
|
||||
- Add columns for:
|
||||
- `message_id`,
|
||||
- `direction`,
|
||||
- `message_text`,
|
||||
- delivery errors,
|
||||
- timestamps.
|
||||
|
||||
## Phase 4: Sending
|
||||
|
||||
- Implement template sending first.
|
||||
- Implement freeform text sending second.
|
||||
- Persist the initial outbound event as `accepted`.
|
||||
|
||||
## Phase 5: Webhooks
|
||||
|
||||
- Implement GET verification.
|
||||
- Implement POST ingestion.
|
||||
- Store both:
|
||||
- `statuses`,
|
||||
- `messages`.
|
||||
|
||||
## Phase 6: Dashboard truthfulness
|
||||
|
||||
- Show the connected number.
|
||||
- Show real templates.
|
||||
- Show recent message events.
|
||||
- Build conversations from stored events.
|
||||
|
||||
## Phase 7: Compliance
|
||||
|
||||
- Add a public data deletion instructions page.
|
||||
- Add a deauthorize callback route.
|
||||
- Support automatic deletion or unlinking when Meta revokes authorization.
|
||||
@@ -0,0 +1,77 @@
|
||||
# Meta configuration checklist
|
||||
|
||||
Use this reference when the user needs the configuration values and URLs that must exist in Meta Developers.
|
||||
|
||||
## OAuth / Embedded Signup
|
||||
|
||||
The app should expose a public callback page such as:
|
||||
|
||||
```text
|
||||
https://your-domain.com/oauth/callback
|
||||
```
|
||||
|
||||
This URL should be:
|
||||
|
||||
- listed in valid OAuth redirect URIs,
|
||||
- reachable in production,
|
||||
- consistent with the runtime environment.
|
||||
|
||||
## WhatsApp webhook
|
||||
|
||||
Use a public route such as:
|
||||
|
||||
```text
|
||||
https://your-domain.com/api/whatsapp/webhook
|
||||
```
|
||||
|
||||
Requirements:
|
||||
|
||||
- GET for verification
|
||||
- POST for webhook events
|
||||
- verify token stored as an environment variable
|
||||
- subscribe to the `messages` field
|
||||
|
||||
## Data deletion instructions URL
|
||||
|
||||
Use a public page such as:
|
||||
|
||||
```text
|
||||
https://your-domain.com/data-deletion
|
||||
```
|
||||
|
||||
This page should explain how users can request deletion and how your team processes it.
|
||||
|
||||
## Deauthorize callback URL
|
||||
|
||||
Use a backend route such as:
|
||||
|
||||
```text
|
||||
https://your-domain.com/api/meta/deauthorize
|
||||
```
|
||||
|
||||
This route should:
|
||||
|
||||
- receive Meta's deauthorize callback,
|
||||
- validate `signed_request`,
|
||||
- identify the local user,
|
||||
- delete or unlink the user's WhatsApp data,
|
||||
- return a confirmation response.
|
||||
|
||||
## Critical environment variables
|
||||
|
||||
- `FACEBOOK_APP_ID`
|
||||
- `FACEBOOK_APP_SECRET`
|
||||
- `FACEBOOK_CONFIG_ID`
|
||||
- `OAUTH_REDIRECT_URI`
|
||||
- `SUPABASE_URL`
|
||||
- `SUPABASE_ANON_KEY`
|
||||
- `SUPABASE_SERVICE_ROLE_KEY`
|
||||
- `WHATSAPP_WEBHOOK_VERIFY_TOKEN`
|
||||
|
||||
## Common config failures
|
||||
|
||||
- redirect URI mismatch
|
||||
- wrong app secret
|
||||
- app ID, app secret, and config ID from different apps
|
||||
- webhook URL not publicly reachable
|
||||
- deauthorize callback exists in Meta but not in the product
|
||||
@@ -0,0 +1,71 @@
|
||||
# Supabase schema for a WhatsApp SaaS
|
||||
|
||||
Use this reference when the user needs a minimal but production-leaning data model.
|
||||
|
||||
## Table: whatsapp_connections
|
||||
|
||||
Purpose:
|
||||
|
||||
- store the current connected WhatsApp Business account for a SaaS user.
|
||||
|
||||
```sql
|
||||
create extension if not exists "uuid-ossp";
|
||||
|
||||
create table if not exists public.whatsapp_connections (
|
||||
id uuid primary key default uuid_generate_v4(),
|
||||
user_id uuid,
|
||||
waba_id text not null,
|
||||
phone_number_id text not null,
|
||||
display_phone_number text,
|
||||
verified_name text,
|
||||
access_token text not null,
|
||||
is_active boolean not null default true,
|
||||
created_at timestamptz not null default now(),
|
||||
updated_at timestamptz not null default now()
|
||||
);
|
||||
```
|
||||
|
||||
## Table: whatsapp_message_events
|
||||
|
||||
Purpose:
|
||||
|
||||
- store outbound sends,
|
||||
- delivery statuses,
|
||||
- inbound messages,
|
||||
- debugging context.
|
||||
|
||||
```sql
|
||||
create table if not exists public.whatsapp_message_events (
|
||||
id uuid primary key default uuid_generate_v4(),
|
||||
waba_id text,
|
||||
phone_number_id text,
|
||||
message_id text not null unique,
|
||||
recipient_phone text,
|
||||
template_name text,
|
||||
direction text not null default 'outbound',
|
||||
message_text text,
|
||||
status text not null,
|
||||
error_code text,
|
||||
error_title text,
|
||||
error_message text,
|
||||
raw_payload jsonb,
|
||||
created_at timestamptz not null default now(),
|
||||
updated_at timestamptz not null default now(),
|
||||
last_event_at timestamptz not null default now()
|
||||
);
|
||||
```
|
||||
|
||||
## Why this schema works
|
||||
|
||||
- `phone_number_id` ties events to the connected sender.
|
||||
- `message_id` supports upserts from webhook updates.
|
||||
- `direction` supports conversation rendering.
|
||||
- `message_text` supports inbound conversation truth.
|
||||
- `raw_payload` keeps enough context for debugging.
|
||||
|
||||
## Suggested operational rules
|
||||
|
||||
- Insert outbound events immediately after a successful send response.
|
||||
- Update the same row when webhook statuses arrive.
|
||||
- Insert inbound messages as new rows with `direction = inbound`.
|
||||
- Mark stale or broken connections as inactive if Meta says the asset is gone.
|
||||
@@ -0,0 +1,23 @@
|
||||
node_modules
|
||||
.next
|
||||
.git
|
||||
.env*
|
||||
!.env.example
|
||||
*.log
|
||||
coverage
|
||||
.playwright-mcp
|
||||
docs
|
||||
# 035: el OpenAPI se importa en /api/bot/openapi.json y entra al build.
|
||||
!docs/openapi.json
|
||||
specs
|
||||
memory
|
||||
tests
|
||||
Dockerfile
|
||||
docker-compose*.yml
|
||||
Caddyfile
|
||||
README.md
|
||||
INSTALL-IA.md
|
||||
# #82: el migrador (drizzle-orm) solo abre meta/_journal.json y los *.sql;
|
||||
# los *_snapshot.json de meta/ son de `drizzle-kit generate` y pesan ~1.2 MB.
|
||||
drizzle/meta/*
|
||||
!drizzle/meta/_journal.json
|
||||
+284
@@ -0,0 +1,284 @@
|
||||
# ============================================================
|
||||
# Vocero CRM — variables de entorno
|
||||
# `pnpm init-env` crea `.env` a partir de este archivo con los secretos ya
|
||||
# generados, y `pnpm doctor` lo revisa. A mano: cópialo a `.env` y reemplaza
|
||||
# cada REEMPLAZA_...
|
||||
# En producción estas variables van en tu plataforma de hosting
|
||||
# (Coolify / docker compose), no solo en el archivo.
|
||||
# ============================================================
|
||||
|
||||
# --- Aplicación ---------------------------------------------
|
||||
# URL pública de la instancia (con https en producción).
|
||||
# De ella se construye la URL del webhook de WhatsApp.
|
||||
APP_BASE_URL=REEMPLAZA_https://crm.tudominio.com
|
||||
|
||||
# Solo Ruta B (docker compose): dominio para el HTTPS automático de Caddy.
|
||||
DOMAIN=REEMPLAZA_crm.tudominio.com
|
||||
|
||||
# Solo Ruta B: versión de la imagen publicada que corre docker compose
|
||||
# (ghcr.io/kevinrivm/vocero-crm:X.Y.Z). Sin ella, la que fija
|
||||
# docker-compose.yml, que sube con cada versión al hacer git pull. Si la
|
||||
# defines, te quedas en esa hasta que la cambies tú.
|
||||
# VOCERO_CRM_VERSION=X.Y.Z
|
||||
|
||||
# --- Base de datos ------------------------------------------
|
||||
# Ruta B usa el servicio interno `postgres` del compose.
|
||||
# Genera la contraseña con: openssl rand -hex 24
|
||||
POSTGRES_PASSWORD=REEMPLAZA_password_de_postgres
|
||||
DATABASE_URL=postgresql://postgres:REEMPLAZA_password_de_postgres@postgres:5432/vocero
|
||||
|
||||
# --- Secretos de la aplicación ------------------------------
|
||||
# Firma de sesiones. Genera con: openssl rand -base64 32
|
||||
BETTER_AUTH_SECRET=REEMPLAZA_secreto_de_sesiones
|
||||
|
||||
# Cifrado en reposo del token de WhatsApp (AES-256-GCM).
|
||||
# DEBE ser exactamente 32 bytes en base64 (44 caracteres).
|
||||
# Genera con: openssl rand -base64 32
|
||||
ENCRYPTION_KEY=REEMPLAZA_clave_de_cifrado_base64
|
||||
|
||||
# --- WhatsApp (webhook) -------------------------------------
|
||||
# Token de verificación del webhook. Es también el segmento secreto
|
||||
# de la URL del webhook: /api/webhooks/wa/<este_valor>
|
||||
# Genera con: openssl rand -hex 32
|
||||
META_WEBHOOK_VERIFY_TOKEN=REEMPLAZA_token_de_verificacion
|
||||
|
||||
# OPCIONAL (recomendado en modo directo): App Secret de tu app de Meta
|
||||
# para validar la firma de cada webhook (x-hub-signature-256).
|
||||
# Se obtiene en developers.facebook.com → tu app → Configuración → Básica.
|
||||
# En modo agencia normalmente se deja vacío (la URL secreta protege el webhook).
|
||||
# META_APP_SECRET=
|
||||
|
||||
# OPCIONAL (066): botón «Conectar con Meta» (Embedded Signup v4) en
|
||||
# Ajustes → WhatsApp. Con las DOS y META_APP_SECRET (el de esa MISMA app)
|
||||
# aparece el botón; sin ellas queda solo el alta manual con token.
|
||||
# META_APP_ID: developers.facebook.com → tu app → Configuración → Básica.
|
||||
# META_EMBEDDED_CONFIG_ID: Facebook Login for Business → Configuraciones →
|
||||
# configuración «WhatsApp Embedded Signup» (solo producto WhatsApp Cloud
|
||||
# API, token sin vencimiento).
|
||||
# Los dominios a dar de alta en el panel de Meta: docs/embedded-signup.md
|
||||
# META_APP_ID=
|
||||
# META_EMBEDDED_CONFIG_ID=
|
||||
|
||||
# Versión de la Graph API (déjala así salvo que sepas por qué cambiarla).
|
||||
META_GRAPH_API_VERSION=v25.0
|
||||
|
||||
# --- Inteligencia artificial (opcional) ---------------------
|
||||
# Lo normal es NO tocar esto: el proveedor, el modelo y la llave se pegan en
|
||||
# la app, en Ajustes → IA (cifrada, con «Probar conexión» y «Traer modelos»).
|
||||
# Estas variables son solo un respaldo para instalaciones automatizadas: se
|
||||
# usan mientras no haya nada guardado en Ajustes → IA, y lo guardado ahí
|
||||
# manda sobre ellas. 036 — Con esta llave piensa tu agente (a través del CRM,
|
||||
# por /api/bot/llm: no se copia a Nea) y el juez del Laboratorio. Sin ninguna
|
||||
# de las dos cosas, el CRM funciona completo como bandeja manual.
|
||||
# Crea tu key en https://openrouter.ai → Keys (o usa cualquier proveedor
|
||||
# compatible con la API de OpenAI cambiando OPENROUTER_BASE_URL).
|
||||
# OPENROUTER_API_TOKEN=
|
||||
# OPENROUTER_BASE_URL=https://openrouter.ai/api
|
||||
# Modelo principal del agente (ej.: anthropic/claude-sonnet-4.5)
|
||||
# OPENROUTER_MODEL=
|
||||
# Modelo del juez del Laboratorio (si se omite, usa el principal)
|
||||
# OPENROUTER_JUDGE_MODEL=
|
||||
|
||||
# --- Canales (opcional) -------------------------------------
|
||||
# Canales encendidos, separados por coma. WhatsApp siempre esta activo.
|
||||
# Sin esta variable la instancia es solo WhatsApp: las pantallas y webhooks
|
||||
# de los demas canales responden 404 y no se piden sus credenciales.
|
||||
# Para encender Instagram, Messenger y/o TikTok (ver README - Canales opcionales):
|
||||
# Marca blanca: encendidos por defecto.
|
||||
CHANNELS=whatsapp,instagram,messenger,tiktok
|
||||
#
|
||||
# Instagram y Messenger pueden llegar por Zernio (API unificada); TikTok solo
|
||||
# llega por ahi. Las
|
||||
# credenciales de cada cuenta se guardan cifradas desde la interfaz, no aqui;
|
||||
# esta variable solo existe para apuntar a otra base de la API (pruebas).
|
||||
# ZERNIO_BASE_URL=https://zernio.com/api/v1
|
||||
|
||||
# --- Atribucion de anuncios (opcional) -----------------------
|
||||
# Conversions API de Meta: reporta el lead calificado y la venta cerrada de las
|
||||
# conversaciones que llegaron por un anuncio Click-to-WhatsApp, para que tus
|
||||
# campanas optimicen hacia quien compra. Apagada por defecto: sin esta variable
|
||||
# no se guarda el identificador de clic (ctwa_clid), no se le reporta nada a
|
||||
# Meta y toda su superficie responde 404.
|
||||
#
|
||||
# De que anuncio llego cada conversacion (titular, creativo, enlace) se ve en la
|
||||
# bandeja SIEMPRE, con o sin esta variable (spec 018): llega en el mismo webhook
|
||||
# y no pide nada. Lo unico que cambia sin ella es que no se guarda el clic.
|
||||
# Marca blanca: encendida por defecto.
|
||||
ATRIBUCION=on
|
||||
#
|
||||
# Encenderla NO pide credenciales nuevas: el dataset se pega en Ajustes -
|
||||
# Anuncios y el token se reusa del de WhatsApp. Guia: docs/atribucion-capi.md
|
||||
|
||||
# --- Agenda (opcional) --------------------------------------
|
||||
# Motor de agendamiento: horarios, citas y reservas del agente. Apagado por
|
||||
# defecto. Sin esta variable no existe para nadie: ni pantalla de Citas, ni
|
||||
# Ajustes de Agenda, ni rutas (responden 404), ni instrucciones de agendar en
|
||||
# el prompt del agente.
|
||||
# Marca blanca: encendida por defecto (incluye el modo «Llamada telefónica»).
|
||||
AGENDA=on
|
||||
#
|
||||
# Encenderla NO pide credenciales de terceros: el conector por defecto es
|
||||
# "enlace-fijo" (pegas la URL de tu sala de siempre en Ajustes - Agenda).
|
||||
# Para que cada cita genere su propia reunion, conecta Zoom o Google Calendar
|
||||
# desde esa misma pantalla con las credenciales de TU cuenta (ver
|
||||
# docs/agenda-conectores.md). Las variables de abajo solo se tocan para
|
||||
# apuntar los conectores a los mocks del self-test:
|
||||
# ZOOM_BASE_URL=https://api.zoom.us/v2
|
||||
# ZOOM_OAUTH_BASE_URL=https://zoom.us
|
||||
# GOOGLE_CAL_BASE_URL=https://www.googleapis.com/calendar/v3
|
||||
# GOOGLE_OAUTH_BASE_URL=https://oauth2.googleapis.com
|
||||
|
||||
# --- API y MCP (opcional) -----------------------------------
|
||||
# 069 — API pública /api/v1/* con llaves por negocio y el servidor MCP en
|
||||
# /api/v1/mcp, para que Claude (Claude Code, claude.ai, ChatGPT…) configure tu
|
||||
# agente, pruebe cómo contesta y opere el CRM por ti. Apagada por defecto: sin
|
||||
# esta variable no existe para nadie (404) ni aparece Ajustes → API.
|
||||
# API_V1=on
|
||||
#
|
||||
# Encenderla NO pide credenciales nuevas: las llaves se crean en Ajustes → API
|
||||
# y claude.ai se conecta con OAuth contra esta misma instancia (APP_BASE_URL
|
||||
# tiene que ser la URL pública con https). Guía: docs/api-v1.md
|
||||
|
||||
# --- Operación (opcional) -----------------------------------
|
||||
# Reabrir el registro público después de la primera organización.
|
||||
# ALLOW_SIGNUP=true
|
||||
|
||||
# Milisegundos de agrupación de mensajes antes de despacharle el turno a tu
|
||||
# agente (default 6000).
|
||||
# AGENT_COALESCE_MS=6000
|
||||
# 078 — La espera cuando el último mensaje deja la ráfaga abierta («Hola»,
|
||||
# «Ok», el texto de un anuncio, tres palabras o menos, una foto): casi siempre
|
||||
# viene otro detrás. Nunca es menor que AGENT_COALESCE_MS (default 8000).
|
||||
# AGENT_COALESCE_LARGO_MS=8000
|
||||
|
||||
# 075 — Cada cuánto la red de seguridad busca turnos que el cerebro recibió y
|
||||
# nunca contestó (los vuelve a mandar dos veces y luego pasa la conversación a
|
||||
# una persona). Default 60000; 0 la apaga.
|
||||
# RED_DE_SEGURIDAD_MS=60000
|
||||
|
||||
# --- Tu agente (el cerebro) ---------------------------------
|
||||
# 036 — Vocero 2.0 no trae agente: contesta el que conectas al lado (Nea, MIT,
|
||||
# u otro). Sin agente, Vocero es una bandeja manual. Tu agente habla con el CRM
|
||||
# por la API de servicio /api/bot/* con esta llave: lee el contexto y el
|
||||
# conocimiento, responde, guarda la ficha, escala, marca leído, "escribiendo…",
|
||||
# adjuntos — y piensa por /api/bot/llm con la llave de Ajustes → IA —, todo SIN
|
||||
# que el token de WhatsApp ni la llave de IA salgan del CRM. Contrato completo:
|
||||
# docs/openapi.json. Guía del par: docs/migrar-a-2.0.md.
|
||||
# Larga y aleatoria (mínimo 16 caracteres): `pnpm init-env` la genera, o
|
||||
# openssl rand -hex 32
|
||||
# Sin ella, /api/bot/* responde 401 y el despacho queda apagado.
|
||||
BOT_API_KEY=
|
||||
#
|
||||
# Opcional: el /health de ese cerebro, para la tarjeta «Quién responde a tus
|
||||
# clientes» de la pantalla Agente (en línea, versión, modo, mensajes por
|
||||
# relevar). Lo consulta el SERVIDOR del CRM, no el navegador: usa la dirección
|
||||
# interna. En Coolify, con Nea en el mismo servidor, es el alias de red del
|
||||
# contenedor de Nea (las dos apps en la misma red de Docker):
|
||||
# BRAIN_HEALTH_URL=http://nea:8000/health
|
||||
# Con docker compose, el nombre del servicio. http:// o https://; si lleva
|
||||
# usuario:clave@ viajan como Authorization: Basic y la tarjeta solo muestra el
|
||||
# host. Sin ella, la tarjeta se guía por la última llamada del cerebro a
|
||||
# /api/bot/* (se cuenta desde el último arranque).
|
||||
# BRAIN_HEALTH_URL=
|
||||
#
|
||||
# Opcional: que el CRM le DESPACHE cada turno a tu cerebro, en vez de que el
|
||||
# cerebro reciba el webhook de Meta. El mensaje entra primero a la bandeja y el
|
||||
# CRM le hace un POST firmado (HMAC-SHA256 con BOT_API_KEY) con la ráfaga; el
|
||||
# cerebro contesta por /api/bot/messages. Vale igual para WhatsApp, Instagram y
|
||||
# Messenger. Con esta variable Y BOT_API_KEY, y el interruptor de la pantalla
|
||||
# Agente encendido, contesta tu agente. Contrato: docs/openapi.json (webhooks).
|
||||
# BRAIN_DISPATCH_URL=http://nea:8000/vocero/dispatch
|
||||
# Dirección interna, como la de arriba. Mal escrita o sin BOT_API_KEY, el
|
||||
# despacho queda inactivo (todo sigue como sin ella) y la tarjeta lo dice.
|
||||
# No la pongas con un cerebro que todavía recibe el webhook por su cuenta: le
|
||||
# llegaría cada mensaje por dos caminos.
|
||||
# BRAIN_DISPATCH_URL=
|
||||
|
||||
# 035 — El agente (Nea) al lado del CRM: `docker compose up -d` lo levanta
|
||||
# (docs/migrar-a-2.0.md). Comparte la base (esquema `nea`) y la BOT_API_KEY.
|
||||
# En docker compose el despacho ya apunta a él; BRAIN_DISPATCH_URL= vacía
|
||||
# en este archivo lo apaga (bandeja manual).
|
||||
# 036 — No lleva llave de IA: piensa por el CRM con la de Ajustes → IA.
|
||||
# NEA_VERSION=2.0.0
|
||||
# Mientras pruebas, tu número (Nea solo le contesta a esas identidades):
|
||||
# ALLOWED_WA_IDS=
|
||||
|
||||
# 008 - Directorio de adjuntos (imagenes, docs, audios), logo e icono.
|
||||
# SOLO para desarrollo local (pnpm dev); sin ella se usa ./.dev-media.
|
||||
# En Docker (Coolify o docker compose) NO la definas: la imagen ya trae
|
||||
# MEDIA_DIR=/data/media. Lo que hace falta es un volumen persistente en /data
|
||||
# (docker-compose.yml ya lo monta; en Coolify, ver INSTALL-IA.md).
|
||||
# MEDIA_DIR=./.dev-media
|
||||
|
||||
# 037 — Opcional: los adjuntos, el logo y el icono en un bucket S3-compatible
|
||||
# propio en vez del volumen (para plataformas sin disco persistente, o si
|
||||
# prefieres respaldarlos aparte). Apagado por defecto. Con MEDIA_STORE=bucket
|
||||
# y las cinco de abajo, lo nuevo va al bucket y lo que ya estaba en el volumen
|
||||
# se sigue leyendo de ahí: no hay nada que migrar, y quitar la bandera tampoco
|
||||
# deja nada ilegible. Si el bucket no acepta una escritura, ese archivo se
|
||||
# guarda en el volumen y /api/health (mediaWritable) y `pnpm doctor` lo dicen.
|
||||
# - MinIO en este mismo servidor: `docker compose --profile bucket up -d`,
|
||||
# MEDIA_BUCKET_ENDPOINT=http://minio:9000 y una llave y secreto que
|
||||
# inventes (el secreto, 8+ caracteres): son las de administrador del MinIO.
|
||||
# - Cloudflare R2: https://<cuenta>.r2.cloudflarestorage.com, región auto.
|
||||
# - AWS S3: https://s3.<región>.amazonaws.com y su región.
|
||||
# MEDIA_STORE=bucket
|
||||
# MEDIA_BUCKET_ENDPOINT=http://minio:9000
|
||||
# MEDIA_BUCKET_NAME=vocero
|
||||
# MEDIA_BUCKET_REGION=us-east-1
|
||||
# MEDIA_BUCKET_KEY_ID=
|
||||
# MEDIA_BUCKET_SECRET=
|
||||
|
||||
# ============================================================
|
||||
# Marca blanca: identidad del negocio y despliegue
|
||||
# ============================================================
|
||||
|
||||
# --- Puerto publicado (docker compose) ------------------------
|
||||
# Puerto del HOST donde queda la app (dentro del contenedor siempre es 3000).
|
||||
# Sin proxy, abre http://TU_SERVIDOR:3003. Detrás de un reverse proxy (Caddy,
|
||||
# aaPanel, Nginx), apunta el proxy a http://127.0.0.1:ESTE_PUERTO.
|
||||
PORT=3003
|
||||
|
||||
# --- Superadmin (semilla idempotente al arrancar) -------------
|
||||
# El contenedor crea o sincroniza al arrancar: el usuario, su contraseña, la
|
||||
# organización, la membresía de dueño, las etapas base del embudo y el perfil
|
||||
# del agente. Re-ejecutarla no duplica nada; cambiar la contraseña aquí y
|
||||
# reiniciar la sincroniza. Vacías = no se siembra nada.
|
||||
# A mano: `pnpm seed:superadmin`.
|
||||
# La contraseña: mínimo 8 caracteres; genera una con `openssl rand -base64 18`.
|
||||
# Descomenta y reemplaza (en el servidor, en el .env junto al compose):
|
||||
# SUPERADMIN_EMAIL=REEMPLAZA_con_tu_correo@tudominio.com
|
||||
# SUPERADMIN_PASSWORD=REEMPLAZA_con_una_contraseña_fuerte
|
||||
# SUPERADMIN_NAME=Administrador
|
||||
# SUPERADMIN_ORG_NAME=Mi negocio
|
||||
|
||||
# --- Identidad inicial del negocio (opcional) ------------------
|
||||
# Se aplica UNA vez, al primer arranque, si la organización no tiene marca
|
||||
# guardada. Después todo se cambia en Ajustes → Marca y el entorno ya no la
|
||||
# pisa. BRAND_ACCENT: hex de 6 dígitos. BRAND_CURRENCY: código ISO (MXN, USD,
|
||||
# COP, EUR…). BUSINESS_DESCRIPTION: a qué se dedica (lo usa el saludo y las
|
||||
# instrucciones iniciales del agente).
|
||||
# BRAND_NAME=Mi CRM
|
||||
# BRAND_ACCENT=#009c98
|
||||
# BRAND_CURRENCY=MXN
|
||||
# BUSINESS_DESCRIPTION=diseño y fabricación de letreros, impresión y marketing
|
||||
|
||||
# --- Transcripción de notas de voz (opcional) ------------------
|
||||
# Whisper: el audio entrante gana el texto «[Nota de voz transcrita]: "…"» y el
|
||||
# agente lo lee. Apagado mientras falte proveedor o llave.
|
||||
# - openai → llave en https://platform.openai.com/api-keys (modelo whisper-1)
|
||||
# - groq → llave en https://console.groq.com/keys (whisper-large-v3-turbo)
|
||||
# WHISPER_PROVIDER=groq
|
||||
# WHISPER_API_KEY=REEMPLAZA_con_tu_llave_de_whisper
|
||||
# WHISPER_BASE_URL= # otro endpoint compatible con /audio/transcriptions
|
||||
# WHISPER_MODEL= # vacío = el del proveedor
|
||||
# WHISPER_LANGUAGE=es
|
||||
|
||||
# --- Imagen y actualización (docker compose) -------------------
|
||||
# Imagen publicada por la CI (GitHub Actions → GHCR) en cada push a main. Si
|
||||
# no se puede bajar, Compose la construye desde CRM_BUILD_CONTEXT: `.` (este
|
||||
# clon) o la URL de un repo git, p. ej.
|
||||
# https://USUARIO:TOKEN@github.com/USUARIO/REPO.git#main
|
||||
# CRM_IMAGE=ghcr.io/djcoraanco/crmmonkey
|
||||
# CRM_TAG=latest
|
||||
# CRM_BUILD_CONTEXT=.
|
||||
@@ -0,0 +1,3 @@
|
||||
# Los scripts de shell corren dentro del contenedor (Linux): con CRLF, `sh` no
|
||||
# los ejecuta. Siempre LF, también en checkouts de Windows con autocrlf.
|
||||
*.sh text eol=lf
|
||||
@@ -0,0 +1,91 @@
|
||||
name: CI
|
||||
|
||||
# Los cuatro gates del proyecto, corridos por una máquina en cada PR.
|
||||
#
|
||||
# Existe sobre todo por los PRs de fuera: quien manda uno no tiene la base de
|
||||
# datos ni el `.env` de nadie, así que hoy la única forma de saber si su cambio
|
||||
# sirve es que un humano lo clone y lo corra a mano. Con esto, el resultado
|
||||
# llega pegado al PR y el colaborador lo ve antes que el mantenedor.
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
# Tres pushes seguidos a un PR no necesitan tres corridas: manda la última.
|
||||
# En `main` no se cancela nada — ahí el historial de qué pasó importa.
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
# Solo lectura: ninguno de estos pasos escribe en el repo, y un PR desde un
|
||||
# fork ajeno no debe recibir un token que pueda hacerlo.
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
gates:
|
||||
name: ${{ matrix.config.name }} · typecheck · lint · test · build
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
# Los módulos opcionales (canales, agenda) se encienden con variables de
|
||||
# despliegue, así que el código que viaja en main tiene que servir en las
|
||||
# dos configuraciones — y eso no se sabe corriendo solo una.
|
||||
#
|
||||
# `default` es lo que instala la mayoría: sin canales extra y sin agenda.
|
||||
# `completo` es todo encendido. Entre las dos se cubre lo que las banderas
|
||||
# prometen: que apagadas no estorban y encendidas funcionan.
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
config:
|
||||
- name: default
|
||||
channels: ""
|
||||
agenda: ""
|
||||
- name: completo
|
||||
channels: "whatsapp,instagram,messenger,tiktok"
|
||||
agenda: "on"
|
||||
|
||||
env:
|
||||
CHANNELS: ${{ matrix.config.channels }}
|
||||
AGENDA: ${{ matrix.config.agenda }}
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
# Antes que setup-node, porque su caché necesita pnpm ya instalado.
|
||||
# La versión sale de `packageManager` en package.json y no se repite
|
||||
# aquí: duplicarla es tenerla desactualizada en uno de los dos lados.
|
||||
- uses: pnpm/action-setup@v6
|
||||
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
|
||||
# `--frozen-lockfile` falla si el lockfile no cuadra con package.json,
|
||||
# en vez de resolver otras versiones en silencio y probar algo que nadie
|
||||
# va a instalar.
|
||||
- name: install
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
# Los cuatro corren AUNQUE uno falle. Es a propósito: si se detuviera en
|
||||
# el primero, arreglar tres cosas costaría tres vueltas de ida y vuelta a
|
||||
# alguien que no puede reproducirlas en su máquina. Una corrida, la lista
|
||||
# completa.
|
||||
- name: typecheck
|
||||
run: pnpm typecheck
|
||||
|
||||
- name: lint
|
||||
if: ${{ !cancelled() }}
|
||||
run: pnpm lint
|
||||
|
||||
- name: test
|
||||
if: ${{ !cancelled() }}
|
||||
run: pnpm test
|
||||
|
||||
# Va al final porque es el más lento, y porque ya atrapó cosas que los
|
||||
# otros tres no ven: Next rechaza exports que no son handlers en un
|
||||
# `route.ts`, y eso solo aparece al construir.
|
||||
- name: build
|
||||
if: ${{ !cancelled() }}
|
||||
run: pnpm build
|
||||
@@ -0,0 +1,79 @@
|
||||
name: Imagen
|
||||
|
||||
# La imagen Docker de la instancia.
|
||||
#
|
||||
# - En cada PR y en cada push a main se CONSTRUYE sin publicar. Atrapa lo que
|
||||
# `pnpm build` no ve: el Dockerfile, el entrypoint y la etapa runner. Hasta
|
||||
# ahora el CI nunca construía la imagen, y el primero en enterarse de un
|
||||
# Dockerfile roto era quien desplegaba.
|
||||
# - Marca blanca: cada push a main PUBLICA `latest` (y `sha-…`) en GHCR,
|
||||
# ghcr.io/<dueño>/<repo>. Es lo que baja docker-compose.yml.
|
||||
# - Al crear un tag `vX.Y.Z` se PUBLICA en GitHub Container Registry:
|
||||
# ghcr.io/kevinrivm/vocero-crm:X.Y.Z (y X.Y, y `latest` si no es
|
||||
# prerelease). Es lo que instala el starter: Coolify descarga la imagen en
|
||||
# vez de construirla en el VPS (minutos de build y RAM que un VPS chico no
|
||||
# tiene).
|
||||
#
|
||||
# El commit se hornea como build arg (SOURCE_COMMIT): es lo que hace que
|
||||
# /api/health diga `commitVerified: true`.
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches: [main]
|
||||
tags: ["v*"]
|
||||
|
||||
# Tres pushes seguidos a un PR no necesitan tres builds: manda el último. En
|
||||
# main y en los tags no se cancela nada.
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
# Solo se usa al publicar (tags). En un PR desde un fork GitHub lo baja a
|
||||
# lectura por su cuenta.
|
||||
packages: write
|
||||
|
||||
jobs:
|
||||
imagen:
|
||||
name: docker build${{ startsWith(github.ref, 'refs/tags/v') && ' · publicar' || '' }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Entrar a GHCR (solo al publicar)
|
||||
if: github.event_name == 'push'
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Etiquetas
|
||||
id: meta
|
||||
uses: docker/metadata-action@v6
|
||||
with:
|
||||
images: ghcr.io/${{ github.repository }}
|
||||
tags: |
|
||||
type=semver,pattern={{version}}
|
||||
type=semver,pattern={{major}}.{{minor}}
|
||||
type=ref,event=pr
|
||||
type=sha
|
||||
type=raw,value=latest,enable={{is_default_branch}}
|
||||
|
||||
# Solo amd64 por ahora: es lo que corren los VPS de la guía. arm64
|
||||
# (Oracle, Ampere) emulado con QEMU multiplica el tiempo del build; se
|
||||
# agrega cuando haya quien lo instale.
|
||||
- uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: .
|
||||
platforms: linux/amd64
|
||||
push: ${{ github.event_name == 'push' }}
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
build-args: |
|
||||
SOURCE_COMMIT=${{ github.sha }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
# --- Secretos (NUNCA al control de versiones) ---
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
*.pem
|
||||
*.key
|
||||
|
||||
# --- MCP local con tokens (si lo personalizas con secretos en claro) ---
|
||||
# .mcp.json se commitea SOLO si usa ${VAR} (sin tokens en claro). Si metes
|
||||
# secretos directos, ignóralo y deja únicamente .mcp.json.example.
|
||||
# .mcp.json
|
||||
|
||||
# --- Dependencias / build (cuando el starter ya tenga app encima) ---
|
||||
node_modules/
|
||||
.next/
|
||||
out/
|
||||
dist/
|
||||
build/
|
||||
*.tsbuildinfo
|
||||
|
||||
# --- Logs y temporales ---
|
||||
*.log
|
||||
npm-debug.log*
|
||||
pnpm-debug.log*
|
||||
.cache/
|
||||
tmp/
|
||||
.tmp/
|
||||
|
||||
# --- OS / editor ---
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
.idea/
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
|
||||
# --- Claude Code: estado local (no compartir) ---
|
||||
# La memoria de subagentes (.claude/agent-memory/) SÍ se versiona (es memoria de
|
||||
# proyecto compartida con el equipo). La config local de la sesión, no:
|
||||
.claude/settings.local.json
|
||||
.playwright-mcp/
|
||||
.tmp-seed-demo.mjs
|
||||
# Bundles de pnpm init-env / pnpm doctor (esbuild)
|
||||
.tmp-*.mjs
|
||||
.dev-media/
|
||||
# Capturas y salidas de los self-tests (p. ej. scripts/e2e-responsive.mjs)
|
||||
scratch/
|
||||
|
||||
# --- Bundle temporal de `pnpm seed:superadmin` ---
|
||||
.tmp-seed-superadmin.mjs
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"//": "EJEMPLO de MCP scoped al proyecto. Copia las entradas que necesites a .mcp.json (que arranca vacío) o usa `claude mcp add` (recomendado). Los ${VAR} se resuelven desde tu entorno / .env — NUNCA pongas tokens en claro aquí. Ver docs/mcp-setup.md.",
|
||||
|
||||
"mcpServers": {
|
||||
"playwright": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@playwright/mcp@latest"]
|
||||
},
|
||||
|
||||
"github": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@modelcontextprotocol/server-github"],
|
||||
"env": {
|
||||
"GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
# eslint-config-next referencia sus plugins por nombre, y el arbol estricto de
|
||||
# pnpm no los expone en la raiz: sin esto `pnpm lint` falla nada mas clonar con
|
||||
# "couldn't find the plugin", que es un gate que en la practica nadie corre.
|
||||
# El patron con scope hace falta aparte: *eslint* no cubre @next/eslint-plugin-next.
|
||||
public-hoist-pattern[]=*eslint*
|
||||
public-hoist-pattern[]=@next/*
|
||||
@@ -0,0 +1,164 @@
|
||||
installed:
|
||||
- agent-context
|
||||
- git
|
||||
settings:
|
||||
auto_execute_hooks: true
|
||||
hooks:
|
||||
before_constitution:
|
||||
- extension: git
|
||||
command: speckit.git.initialize
|
||||
enabled: true
|
||||
optional: false
|
||||
prompt: Execute speckit.git.initialize?
|
||||
description: Initialize Git repository before constitution setup
|
||||
condition: null
|
||||
before_specify:
|
||||
- extension: git
|
||||
command: speckit.git.feature
|
||||
enabled: true
|
||||
optional: false
|
||||
prompt: Execute speckit.git.feature?
|
||||
description: Create feature branch before specification
|
||||
condition: null
|
||||
before_clarify:
|
||||
- extension: git
|
||||
command: speckit.git.commit
|
||||
enabled: true
|
||||
optional: true
|
||||
prompt: Commit outstanding changes before clarification?
|
||||
description: Auto-commit before spec clarification
|
||||
condition: null
|
||||
before_plan:
|
||||
- extension: git
|
||||
command: speckit.git.commit
|
||||
enabled: true
|
||||
optional: true
|
||||
prompt: Commit outstanding changes before planning?
|
||||
description: Auto-commit before implementation planning
|
||||
condition: null
|
||||
before_tasks:
|
||||
- extension: git
|
||||
command: speckit.git.commit
|
||||
enabled: true
|
||||
optional: true
|
||||
prompt: Commit outstanding changes before task generation?
|
||||
description: Auto-commit before task generation
|
||||
condition: null
|
||||
before_implement:
|
||||
- extension: git
|
||||
command: speckit.git.commit
|
||||
enabled: true
|
||||
optional: true
|
||||
prompt: Commit outstanding changes before implementation?
|
||||
description: Auto-commit before implementation
|
||||
condition: null
|
||||
before_checklist:
|
||||
- extension: git
|
||||
command: speckit.git.commit
|
||||
enabled: true
|
||||
optional: true
|
||||
prompt: Commit outstanding changes before checklist?
|
||||
description: Auto-commit before checklist generation
|
||||
condition: null
|
||||
before_analyze:
|
||||
- extension: git
|
||||
command: speckit.git.commit
|
||||
enabled: true
|
||||
optional: true
|
||||
prompt: Commit outstanding changes before analysis?
|
||||
description: Auto-commit before analysis
|
||||
condition: null
|
||||
before_taskstoissues:
|
||||
- extension: git
|
||||
command: speckit.git.commit
|
||||
enabled: true
|
||||
optional: true
|
||||
prompt: Commit outstanding changes before issue sync?
|
||||
description: Auto-commit before tasks-to-issues conversion
|
||||
condition: null
|
||||
after_constitution:
|
||||
- extension: git
|
||||
command: speckit.git.commit
|
||||
enabled: true
|
||||
optional: true
|
||||
prompt: Commit constitution changes?
|
||||
description: Auto-commit after constitution update
|
||||
condition: null
|
||||
after_specify:
|
||||
- extension: git
|
||||
command: speckit.git.commit
|
||||
enabled: true
|
||||
optional: true
|
||||
prompt: Commit specification changes?
|
||||
description: Auto-commit after specification
|
||||
condition: null
|
||||
- extension: agent-context
|
||||
command: speckit.agent-context.update
|
||||
enabled: true
|
||||
optional: true
|
||||
prompt: Execute speckit.agent-context.update?
|
||||
description: Refresh agent context after specification
|
||||
condition: null
|
||||
after_clarify:
|
||||
- extension: git
|
||||
command: speckit.git.commit
|
||||
enabled: true
|
||||
optional: true
|
||||
prompt: Commit clarification changes?
|
||||
description: Auto-commit after spec clarification
|
||||
condition: null
|
||||
after_plan:
|
||||
- extension: git
|
||||
command: speckit.git.commit
|
||||
enabled: true
|
||||
optional: true
|
||||
prompt: Commit plan changes?
|
||||
description: Auto-commit after implementation planning
|
||||
condition: null
|
||||
- extension: agent-context
|
||||
command: speckit.agent-context.update
|
||||
enabled: true
|
||||
optional: true
|
||||
prompt: Execute speckit.agent-context.update?
|
||||
description: Refresh agent context after planning
|
||||
condition: null
|
||||
after_tasks:
|
||||
- extension: git
|
||||
command: speckit.git.commit
|
||||
enabled: true
|
||||
optional: true
|
||||
prompt: Commit task changes?
|
||||
description: Auto-commit after task generation
|
||||
condition: null
|
||||
after_implement:
|
||||
- extension: git
|
||||
command: speckit.git.commit
|
||||
enabled: true
|
||||
optional: true
|
||||
prompt: Commit implementation changes?
|
||||
description: Auto-commit after implementation
|
||||
condition: null
|
||||
after_checklist:
|
||||
- extension: git
|
||||
command: speckit.git.commit
|
||||
enabled: true
|
||||
optional: true
|
||||
prompt: Commit checklist changes?
|
||||
description: Auto-commit after checklist generation
|
||||
condition: null
|
||||
after_analyze:
|
||||
- extension: git
|
||||
command: speckit.git.commit
|
||||
enabled: true
|
||||
optional: true
|
||||
prompt: Commit analysis results?
|
||||
description: Auto-commit after analysis
|
||||
condition: null
|
||||
after_taskstoissues:
|
||||
- extension: git
|
||||
command: speckit.git.commit
|
||||
enabled: true
|
||||
optional: true
|
||||
prompt: Commit after syncing issues?
|
||||
description: Auto-commit after tasks-to-issues conversion
|
||||
condition: null
|
||||
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"schema_version": "1.0",
|
||||
"extensions": {
|
||||
"git": {
|
||||
"version": "1.0.0",
|
||||
"source": "local",
|
||||
"manifest_hash": "sha256:9731aa8143a72fbebfdb440f155038ab42642517c2b2bdbbf67c8fdbe076ed79",
|
||||
"enabled": true,
|
||||
"priority": 10,
|
||||
"registered_commands": {
|
||||
"claude": [
|
||||
"speckit.git.feature",
|
||||
"speckit.git.validate",
|
||||
"speckit.git.remote",
|
||||
"speckit.git.initialize",
|
||||
"speckit.git.commit"
|
||||
]
|
||||
},
|
||||
"registered_skills": [],
|
||||
"installed_at": "2026-06-07T22:31:39.020211+00:00"
|
||||
},
|
||||
"agent-context": {
|
||||
"version": "1.0.0",
|
||||
"source": "local",
|
||||
"manifest_hash": "sha256:9a1dc02d2d0139bb03860392ecacef79183be2c442feda2f9ccaa4e5907b1e47",
|
||||
"enabled": true,
|
||||
"priority": 10,
|
||||
"registered_commands": {
|
||||
"claude": [
|
||||
"speckit.agent-context.update"
|
||||
]
|
||||
},
|
||||
"registered_skills": [],
|
||||
"installed_at": "2026-06-07T22:31:39.157037+00:00"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
# Coding Agent Context Extension
|
||||
|
||||
This bundled extension manages the **coding agent context/instruction file** (e.g. `CLAUDE.md`, `.github/copilot-instructions.md`, `AGENTS.md`, `GEMINI.md`, …) for the active integration.
|
||||
|
||||
It owns the lifecycle of the managed section delimited by the configurable start/end markers (defaults: `<!-- SPECKIT START -->` / `<!-- SPECKIT END -->`).
|
||||
|
||||
## Why an extension?
|
||||
|
||||
Not every Spec Kit user wants Spec Kit to write into the coding agent's context file. Extracting this behavior into a dedicated extension lets users:
|
||||
|
||||
- **Opt out** entirely with `specify extension disable agent-context` — Spec Kit will then never create or modify the agent context file.
|
||||
- **Customize the markers** by editing `.specify/extensions/agent-context/agent-context-config.yml` — both the Python layer and the bundled scripts honor the same `context_markers` value.
|
||||
- **Refresh on demand** with `/speckit.agent-context.update`, or automatically through the hooks declared in `extension.yml` (`after_specify`, `after_plan`).
|
||||
|
||||
## Commands
|
||||
|
||||
| Command | Description |
|
||||
|---------|-------------|
|
||||
| `speckit.agent-context.update` | Refresh the managed section in the agent context file with the current plan path. |
|
||||
|
||||
## Configuration
|
||||
|
||||
All configuration flows through the extension's own config file at
|
||||
`.specify/extensions/agent-context/agent-context-config.yml`:
|
||||
|
||||
```yaml
|
||||
# Path to the coding agent context file managed by this extension
|
||||
context_file: CLAUDE.md
|
||||
|
||||
# Delimiters for the managed Spec Kit section
|
||||
context_markers:
|
||||
start: "<!-- SPECKIT START -->"
|
||||
end: "<!-- SPECKIT END -->"
|
||||
```
|
||||
|
||||
- `context_file` — the project-relative path to the coding agent context file, written by `specify init` and `specify integration install`.
|
||||
- `context_markers.start` / `.end` — the delimiters around the managed section. Edit these to use custom markers.
|
||||
|
||||
## Requirements
|
||||
|
||||
The bundled update scripts require **Python 3** with **PyYAML** for YAML/upsert processing (PowerShell can also use `ConvertFrom-Yaml` when available).
|
||||
|
||||
PyYAML ships with the `specify` CLI and is normally available via the same `python3` interpreter. If a hook reports *"PyYAML is required … not available in the current Python environment"*, it means the system `python3` differs from the one used to install Spec Kit. To resolve, run:
|
||||
|
||||
```bash
|
||||
pip install pyyaml
|
||||
# or target the specific interpreter Spec Kit uses:
|
||||
/path/to/speckit-python -m pip install pyyaml
|
||||
```
|
||||
|
||||
## Disable
|
||||
|
||||
```bash
|
||||
specify extension disable agent-context
|
||||
```
|
||||
|
||||
When disabled, Spec Kit skips context file creation, updates, and removal (the gates are inside `upsert_context_section()` and `remove_context_section()`).
|
||||
@@ -0,0 +1,4 @@
|
||||
context_file: CLAUDE.md
|
||||
context_markers:
|
||||
start: <!-- SPECKIT START -->
|
||||
end: <!-- SPECKIT END -->
|
||||
@@ -0,0 +1,26 @@
|
||||
---
|
||||
description: "Refresh the managed Spec Kit section in the coding agent context file"
|
||||
---
|
||||
|
||||
# Update Coding Agent Context
|
||||
|
||||
Refresh the managed Spec Kit section inside the active coding agent's context/instruction file (e.g. `CLAUDE.md`, `.github/copilot-instructions.md`, `AGENTS.md`).
|
||||
|
||||
## Behavior
|
||||
|
||||
The script reads the agent-context extension config at
|
||||
`.specify/extensions/agent-context/agent-context-config.yml` to discover:
|
||||
|
||||
- `context_file` — the path of the coding agent context file to manage.
|
||||
- `context_markers.start` / `.end` — the delimiters surrounding the managed section. Defaults to `<!-- SPECKIT START -->` and `<!-- SPECKIT END -->` when the field is missing.
|
||||
|
||||
It then creates, replaces, or appends the managed block so that the section points at the most recent plan path when one can be discovered (`specs/<feature>/plan.md`).
|
||||
|
||||
If `context_file` is empty or the file cannot be located, the command reports nothing to do and exits successfully.
|
||||
|
||||
## Execution
|
||||
|
||||
- **Bash**: `.specify/extensions/agent-context/scripts/bash/update-agent-context.sh [plan_path]`
|
||||
- **PowerShell**: `.specify/extensions/agent-context/scripts/powershell/update-agent-context.ps1 [plan_path]`
|
||||
|
||||
When `plan_path` is omitted, the script auto-detects the most recently modified `specs/*/plan.md`.
|
||||
@@ -0,0 +1,34 @@
|
||||
schema_version: "1.0"
|
||||
|
||||
extension:
|
||||
id: agent-context
|
||||
name: "Coding Agent Context"
|
||||
version: "1.0.0"
|
||||
description: "Manages coding agent context/instruction files (e.g., CLAUDE.md, copilot-instructions.md) with project-specific plan references and configurable markers"
|
||||
author: spec-kit-core
|
||||
repository: https://github.com/github/spec-kit
|
||||
license: MIT
|
||||
|
||||
requires:
|
||||
speckit_version: ">=0.2.0"
|
||||
|
||||
provides:
|
||||
commands:
|
||||
- name: speckit.agent-context.update
|
||||
file: commands/speckit.agent-context.update.md
|
||||
description: "Refresh the managed Spec Kit section in the coding agent context file"
|
||||
|
||||
hooks:
|
||||
after_specify:
|
||||
command: speckit.agent-context.update
|
||||
optional: true
|
||||
description: "Refresh agent context after specification"
|
||||
after_plan:
|
||||
command: speckit.agent-context.update
|
||||
optional: true
|
||||
description: "Refresh agent context after planning"
|
||||
|
||||
tags:
|
||||
- "agent"
|
||||
- "context"
|
||||
- "core"
|
||||
@@ -0,0 +1,200 @@
|
||||
#!/usr/bin/env bash
|
||||
# update-agent-context.sh
|
||||
#
|
||||
# Refresh the managed Spec Kit section in the coding agent's context file
|
||||
# (e.g. CLAUDE.md, .github/copilot-instructions.md, AGENTS.md).
|
||||
#
|
||||
# Reads `context_file` and `context_markers.{start,end}` from the
|
||||
# agent-context extension config:
|
||||
# .specify/extensions/agent-context/agent-context-config.yml
|
||||
#
|
||||
# Usage: update-agent-context.sh [plan_path]
|
||||
#
|
||||
# When `plan_path` is omitted, the script picks the most recently modified
|
||||
# `specs/*/plan.md` if any exist, otherwise emits the section without a
|
||||
# concrete plan path.
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
PROJECT_ROOT="$(pwd)"
|
||||
EXT_CONFIG="$PROJECT_ROOT/.specify/extensions/agent-context/agent-context-config.yml"
|
||||
DEFAULT_START="<!-- SPECKIT START -->"
|
||||
DEFAULT_END="<!-- SPECKIT END -->"
|
||||
|
||||
if [[ ! -f "$EXT_CONFIG" ]]; then
|
||||
echo "agent-context: $EXT_CONFIG not found; nothing to do." >&2
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Locate a suitable Python interpreter (python3, then python).
|
||||
_python=""
|
||||
if command -v python3 >/dev/null 2>&1; then
|
||||
_python="python3"
|
||||
elif command -v python >/dev/null 2>&1 && python --version 2>&1 | grep -q "^Python 3"; then
|
||||
_python="python"
|
||||
fi
|
||||
|
||||
if [[ -z "$_python" ]]; then
|
||||
echo "agent-context: Python 3 not found on PATH; skipping update." >&2
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Parse extension config once; emit three newline-separated fields:
|
||||
# context_file, context_markers.start, context_markers.end
|
||||
if ! _raw_opts="$("$_python" - "$EXT_CONFIG" <<'PY'
|
||||
import sys
|
||||
try:
|
||||
import yaml
|
||||
except ImportError:
|
||||
print(
|
||||
"agent-context: PyYAML is required to parse extension config but is not available "
|
||||
"in the current Python environment.\n"
|
||||
" To resolve: pip install pyyaml (or install it into the environment used by python3).\n"
|
||||
" Context file will not be updated until PyYAML is importable.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(2)
|
||||
try:
|
||||
with open(sys.argv[1], "r", encoding="utf-8") as fh:
|
||||
data = yaml.safe_load(fh)
|
||||
except Exception as exc:
|
||||
print(
|
||||
f"agent-context: unable to parse {sys.argv[1]} ({exc}); cannot update context.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(2)
|
||||
if not isinstance(data, dict):
|
||||
data = {}
|
||||
def get_str(obj, *keys):
|
||||
node = obj
|
||||
for k in keys:
|
||||
if isinstance(node, dict) and k in node:
|
||||
node = node[k]
|
||||
else:
|
||||
return ""
|
||||
return node if isinstance(node, str) else ""
|
||||
print(get_str(data, "context_file"))
|
||||
print(get_str(data, "context_markers", "start"))
|
||||
print(get_str(data, "context_markers", "end"))
|
||||
PY
|
||||
)"; then
|
||||
echo "agent-context: skipping update (see above for details)." >&2
|
||||
exit 0
|
||||
fi
|
||||
|
||||
_opts_lines=()
|
||||
while IFS= read -r _line || [[ -n "$_line" ]]; do
|
||||
_opts_lines+=("$_line")
|
||||
done < <(printf '%s\n' "$_raw_opts")
|
||||
if (( ${#_opts_lines[@]} < 3 )); then
|
||||
echo "agent-context: malformed config parser output; expected 3 lines (context_file, marker_start, marker_end), got ${#_opts_lines[@]}; skipping update." >&2
|
||||
exit 0
|
||||
fi
|
||||
CONTEXT_FILE="${_opts_lines[0]}"
|
||||
MARKER_START="${_opts_lines[1]}"
|
||||
MARKER_END="${_opts_lines[2]}"
|
||||
|
||||
if [[ -z "$CONTEXT_FILE" ]]; then
|
||||
echo "agent-context: context_file not set in extension config; nothing to do." >&2
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Reject absolute paths, backslash separators, and '..' path segments in context_file
|
||||
if [[ "$CONTEXT_FILE" == /* ]] || [[ "$CONTEXT_FILE" =~ ^[A-Za-z]: ]]; then
|
||||
echo "agent-context: context_file must be a project-relative path; got '$CONTEXT_FILE'." >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ "$CONTEXT_FILE" == *\\* ]]; then
|
||||
echo "agent-context: context_file must not contain backslash separators; got '$CONTEXT_FILE'." >&2
|
||||
exit 1
|
||||
fi
|
||||
IFS='/' read -ra _cf_parts <<< "$CONTEXT_FILE"
|
||||
for _seg in "${_cf_parts[@]}"; do
|
||||
if [[ "$_seg" == ".." ]]; then
|
||||
echo "agent-context: context_file must not contain '..' path segments; got '$CONTEXT_FILE'." >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
unset _cf_parts _seg
|
||||
|
||||
[[ -z "$MARKER_START" ]] && MARKER_START="$DEFAULT_START"
|
||||
[[ -z "$MARKER_END" ]] && MARKER_END="$DEFAULT_END"
|
||||
|
||||
PLAN_PATH="${1:-}"
|
||||
if [[ -z "$PLAN_PATH" ]]; then
|
||||
# Pick the most recently modified plan.md one level deep (specs/<feature>/plan.md).
|
||||
# Use find + sort by modification time to avoid ls/head fragility with
|
||||
# spaces in paths or SIGPIPE from pipefail.
|
||||
_plan_abs="$("$_python" - "$PROJECT_ROOT" <<'PY'
|
||||
import sys, os
|
||||
from pathlib import Path
|
||||
specs = Path(sys.argv[1]) / "specs"
|
||||
plans = sorted(
|
||||
specs.glob("*/plan.md"),
|
||||
key=lambda p: p.stat().st_mtime,
|
||||
reverse=True,
|
||||
)
|
||||
print(plans[0] if plans else "")
|
||||
PY
|
||||
)"
|
||||
if [[ -n "$_plan_abs" ]]; then
|
||||
PLAN_PATH="${_plan_abs#"$PROJECT_ROOT/"}"
|
||||
fi
|
||||
fi
|
||||
|
||||
CTX_PATH="$PROJECT_ROOT/$CONTEXT_FILE"
|
||||
mkdir -p "$(dirname "$CTX_PATH")"
|
||||
|
||||
# Build the managed section
|
||||
TMP_SECTION="$(mktemp)"
|
||||
trap 'rm -f "$TMP_SECTION"' EXIT
|
||||
{
|
||||
echo "$MARKER_START"
|
||||
echo "For additional context about technologies to be used, project structure,"
|
||||
echo "shell commands, and other important information, read the current plan"
|
||||
if [[ -n "$PLAN_PATH" ]]; then
|
||||
echo "at $PLAN_PATH"
|
||||
fi
|
||||
echo "$MARKER_END"
|
||||
} > "$TMP_SECTION"
|
||||
|
||||
"$_python" - "$CTX_PATH" "$MARKER_START" "$MARKER_END" "$TMP_SECTION" <<'PY'
|
||||
import sys, os
|
||||
ctx_path, start, end, section_path = sys.argv[1:5]
|
||||
with open(section_path, "r", encoding="utf-8") as fh:
|
||||
section = fh.read().rstrip("\n") + "\n"
|
||||
|
||||
if os.path.exists(ctx_path):
|
||||
with open(ctx_path, "r", encoding="utf-8-sig") as fh:
|
||||
content = fh.read()
|
||||
s = content.find(start)
|
||||
e = content.find(end, s if s != -1 else 0)
|
||||
if s != -1 and e != -1 and e > s:
|
||||
end_of_marker = e + len(end)
|
||||
if end_of_marker < len(content) and content[end_of_marker] == "\r":
|
||||
end_of_marker += 1
|
||||
if end_of_marker < len(content) and content[end_of_marker] == "\n":
|
||||
end_of_marker += 1
|
||||
new_content = content[:s] + section + content[end_of_marker:]
|
||||
elif s != -1:
|
||||
new_content = content[:s] + section
|
||||
elif e != -1:
|
||||
end_of_marker = e + len(end)
|
||||
if end_of_marker < len(content) and content[end_of_marker] == "\r":
|
||||
end_of_marker += 1
|
||||
if end_of_marker < len(content) and content[end_of_marker] == "\n":
|
||||
end_of_marker += 1
|
||||
new_content = section + content[end_of_marker:]
|
||||
else:
|
||||
if content and not content.endswith("\n"):
|
||||
content += "\n"
|
||||
new_content = (content + "\n" + section) if content else section
|
||||
else:
|
||||
new_content = section
|
||||
|
||||
new_content = new_content.replace("\r\n", "\n").replace("\r", "\n")
|
||||
with open(ctx_path, "wb") as fh:
|
||||
fh.write(new_content.encode("utf-8"))
|
||||
PY
|
||||
|
||||
echo "agent-context: updated $CONTEXT_FILE"
|
||||
@@ -0,0 +1,237 @@
|
||||
#!/usr/bin/env pwsh
|
||||
# update-agent-context.ps1
|
||||
#
|
||||
# Refresh the managed Spec Kit section in the coding agent's context file
|
||||
# (e.g. CLAUDE.md, .github/copilot-instructions.md, AGENTS.md).
|
||||
#
|
||||
# Reads `context_file` and `context_markers.{start,end}` from the
|
||||
# agent-context extension config:
|
||||
# .specify/extensions/agent-context/agent-context-config.yml
|
||||
#
|
||||
# Usage: update-agent-context.ps1 [plan_path]
|
||||
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Position = 0)]
|
||||
[string]$PlanPath
|
||||
)
|
||||
|
||||
function Get-ConfigValue {
|
||||
param(
|
||||
[AllowNull()][object]$Object,
|
||||
[Parameter(Mandatory = $true)][string]$Key
|
||||
)
|
||||
|
||||
if ($null -eq $Object) {
|
||||
return $null
|
||||
}
|
||||
if ($Object -is [System.Collections.IDictionary]) {
|
||||
return $Object[$Key]
|
||||
}
|
||||
$prop = $Object.PSObject.Properties[$Key]
|
||||
if ($prop) {
|
||||
return $prop.Value
|
||||
}
|
||||
return $null
|
||||
}
|
||||
|
||||
function Test-ConfigObject {
|
||||
param(
|
||||
[AllowNull()][object]$Object
|
||||
)
|
||||
|
||||
if ($null -eq $Object) {
|
||||
return $false
|
||||
}
|
||||
if ($Object -is [System.Collections.IDictionary]) {
|
||||
return $true
|
||||
}
|
||||
if ($Object -is [System.Management.Automation.PSCustomObject]) {
|
||||
return $true
|
||||
}
|
||||
return $false
|
||||
}
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$DefaultStart = '<!-- SPECKIT START -->'
|
||||
$DefaultEnd = '<!-- SPECKIT END -->'
|
||||
$ProjectRoot = (Get-Location).Path
|
||||
$ExtConfig = Join-Path $ProjectRoot '.specify/extensions/agent-context/agent-context-config.yml'
|
||||
|
||||
if (-not (Test-Path -LiteralPath $ExtConfig)) {
|
||||
Write-Warning "agent-context: $ExtConfig not found; nothing to do."
|
||||
exit 0
|
||||
}
|
||||
|
||||
$Options = $null
|
||||
if (Get-Command ConvertFrom-Yaml -ErrorAction SilentlyContinue) {
|
||||
try {
|
||||
$Options = Get-Content -LiteralPath $ExtConfig -Raw | ConvertFrom-Yaml -ErrorAction Stop
|
||||
} catch {
|
||||
# fall through to Python fallback
|
||||
}
|
||||
}
|
||||
|
||||
if ($null -eq $Options) {
|
||||
# ConvertFrom-Yaml unavailable or failed; fall back to Python+PyYAML.
|
||||
$pythonCmd = $null
|
||||
foreach ($candidate in @('python3', 'python')) {
|
||||
if (Get-Command $candidate -ErrorAction SilentlyContinue) {
|
||||
# Verify it is Python 3
|
||||
$verOut = & $candidate --version 2>&1
|
||||
if ($verOut -match 'Python 3') {
|
||||
$pythonCmd = $candidate
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($pythonCmd) {
|
||||
try {
|
||||
$jsonOut = & $pythonCmd -c @'
|
||||
import json
|
||||
import sys
|
||||
try:
|
||||
import yaml
|
||||
except ImportError:
|
||||
print(
|
||||
"agent-context: PyYAML is required to parse extension config; cannot update context.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(2)
|
||||
|
||||
try:
|
||||
with open(sys.argv[1], "r", encoding="utf-8") as fh:
|
||||
data = yaml.safe_load(fh)
|
||||
except Exception as exc:
|
||||
print(
|
||||
f"agent-context: unable to parse {sys.argv[1]} ({exc}); cannot update context.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(2)
|
||||
|
||||
if not isinstance(data, dict):
|
||||
data = {}
|
||||
|
||||
print(json.dumps(data))
|
||||
'@ $ExtConfig
|
||||
if ($LASTEXITCODE -eq 0 -and $jsonOut) {
|
||||
$Options = $jsonOut | ConvertFrom-Json -ErrorAction Stop
|
||||
}
|
||||
} catch {
|
||||
$Options = $null
|
||||
}
|
||||
}
|
||||
|
||||
if (-not $Options) {
|
||||
Write-Warning "agent-context: unable to parse $ExtConfig; skipping update."
|
||||
exit 0
|
||||
}
|
||||
}
|
||||
|
||||
if (-not (Test-ConfigObject -Object $Options)) {
|
||||
Write-Warning "agent-context: $ExtConfig must contain a YAML mapping; skipping update."
|
||||
exit 0
|
||||
}
|
||||
|
||||
$ContextFile = Get-ConfigValue -Object $Options -Key 'context_file'
|
||||
if (-not $ContextFile) {
|
||||
Write-Warning 'agent-context: context_file not set in extension config; nothing to do.'
|
||||
exit 0
|
||||
}
|
||||
|
||||
# Reject absolute paths and '..' path segments in context_file
|
||||
if ([System.IO.Path]::IsPathRooted($ContextFile)) {
|
||||
Write-Warning "agent-context: context_file must be a project-relative path; got '$ContextFile'."
|
||||
exit 1
|
||||
}
|
||||
$cfSegments = $ContextFile -split '[/\\]'
|
||||
if ($cfSegments -contains '..') {
|
||||
Write-Warning "agent-context: context_file must not contain '..' path segments; got '$ContextFile'."
|
||||
exit 1
|
||||
}
|
||||
|
||||
$MarkerStart = $DefaultStart
|
||||
$MarkerEnd = $DefaultEnd
|
||||
$cm = Get-ConfigValue -Object $Options -Key 'context_markers'
|
||||
if ($cm) {
|
||||
$cmStart = Get-ConfigValue -Object $cm -Key 'start'
|
||||
if ($cmStart -is [string] -and $cmStart) {
|
||||
$MarkerStart = $cmStart
|
||||
}
|
||||
$cmEnd = Get-ConfigValue -Object $cm -Key 'end'
|
||||
if ($cmEnd -is [string] -and $cmEnd) {
|
||||
$MarkerEnd = $cmEnd
|
||||
}
|
||||
}
|
||||
|
||||
if (-not $PlanPath) {
|
||||
# Discover plan.md exactly one level deep (specs/<feature>/plan.md),
|
||||
# matching the bash glob specs/*/plan.md. Wrap in try/catch so access errors under
|
||||
# $ErrorActionPreference = 'Stop' don't abort the script.
|
||||
try {
|
||||
$specsDir = Join-Path $ProjectRoot 'specs'
|
||||
$candidate = Get-ChildItem -Path $specsDir -Directory -ErrorAction SilentlyContinue |
|
||||
ForEach-Object { Get-Item -LiteralPath (Join-Path $_.FullName 'plan.md') -ErrorAction SilentlyContinue } |
|
||||
Where-Object { $_ } |
|
||||
Sort-Object LastWriteTime -Descending |
|
||||
Select-Object -First 1
|
||||
if ($candidate) {
|
||||
$PlanPath = [System.IO.Path]::GetRelativePath($ProjectRoot, $candidate.FullName).Replace('\','/')
|
||||
}
|
||||
} catch {
|
||||
# Non-fatal: continue without a plan path.
|
||||
}
|
||||
}
|
||||
|
||||
$CtxPath = Join-Path $ProjectRoot $ContextFile
|
||||
$CtxDir = Split-Path -Parent $CtxPath
|
||||
if ($CtxDir -and -not (Test-Path -LiteralPath $CtxDir)) {
|
||||
New-Item -ItemType Directory -Path $CtxDir -Force | Out-Null
|
||||
}
|
||||
|
||||
$lines = @($MarkerStart,
|
||||
'For additional context about technologies to be used, project structure,',
|
||||
'shell commands, and other important information, read the current plan')
|
||||
if ($PlanPath) {
|
||||
$lines += "at $PlanPath"
|
||||
}
|
||||
$lines += $MarkerEnd
|
||||
$Section = ($lines -join "`n") + "`n"
|
||||
|
||||
if (Test-Path -LiteralPath $CtxPath) {
|
||||
$rawBytes = [System.IO.File]::ReadAllBytes($CtxPath)
|
||||
# Strip UTF-8 BOM if present
|
||||
if ($rawBytes.Length -ge 3 -and $rawBytes[0] -eq 0xEF -and $rawBytes[1] -eq 0xBB -and $rawBytes[2] -eq 0xBF) {
|
||||
$content = [System.Text.Encoding]::UTF8.GetString($rawBytes, 3, $rawBytes.Length - 3)
|
||||
} else {
|
||||
$content = [System.Text.Encoding]::UTF8.GetString($rawBytes)
|
||||
}
|
||||
|
||||
$s = $content.IndexOf($MarkerStart)
|
||||
$e = if ($s -ge 0) { $content.IndexOf($MarkerEnd, $s) } else { $content.IndexOf($MarkerEnd) }
|
||||
|
||||
if ($s -ge 0 -and $e -ge 0 -and $e -gt $s) {
|
||||
$endOfMarker = $e + $MarkerEnd.Length
|
||||
if ($endOfMarker -lt $content.Length -and $content[$endOfMarker] -eq "`r") { $endOfMarker++ }
|
||||
if ($endOfMarker -lt $content.Length -and $content[$endOfMarker] -eq "`n") { $endOfMarker++ }
|
||||
$newContent = $content.Substring(0, $s) + $Section + $content.Substring($endOfMarker)
|
||||
} elseif ($s -ge 0) {
|
||||
$newContent = $content.Substring(0, $s) + $Section
|
||||
} elseif ($e -ge 0) {
|
||||
$endOfMarker = $e + $MarkerEnd.Length
|
||||
if ($endOfMarker -lt $content.Length -and $content[$endOfMarker] -eq "`r") { $endOfMarker++ }
|
||||
if ($endOfMarker -lt $content.Length -and $content[$endOfMarker] -eq "`n") { $endOfMarker++ }
|
||||
$newContent = $Section + $content.Substring($endOfMarker)
|
||||
} else {
|
||||
if ($content -and -not $content.EndsWith("`n")) { $content += "`n" }
|
||||
if ($content) { $newContent = $content + "`n" + $Section } else { $newContent = $Section }
|
||||
}
|
||||
} else {
|
||||
$newContent = $Section
|
||||
}
|
||||
|
||||
$newContent = $newContent.Replace("`r`n", "`n").Replace("`r", "`n")
|
||||
[System.IO.File]::WriteAllText($CtxPath, $newContent, (New-Object System.Text.UTF8Encoding($false)))
|
||||
|
||||
Write-Host "agent-context: updated $ContextFile"
|
||||
@@ -0,0 +1,100 @@
|
||||
# Git Branching Workflow Extension
|
||||
|
||||
Git repository initialization, feature branch creation, numbering (sequential/timestamp), validation, remote detection, and auto-commit for Spec Kit.
|
||||
|
||||
## Overview
|
||||
|
||||
This extension provides Git operations as an optional, self-contained module. It manages:
|
||||
|
||||
- **Repository initialization** with configurable commit messages
|
||||
- **Feature branch creation** with sequential (`001-feature-name`) or timestamp (`20260319-143022-feature-name`) numbering
|
||||
- **Branch validation** to ensure branches follow naming conventions
|
||||
- **Git remote detection** for GitHub integration (e.g., issue creation)
|
||||
- **Auto-commit** after core commands (configurable per-command with custom messages)
|
||||
|
||||
## Commands
|
||||
|
||||
| Command | Description |
|
||||
|---------|-------------|
|
||||
| `speckit.git.initialize` | Initialize a Git repository with a configurable commit message |
|
||||
| `speckit.git.feature` | Create a feature branch with sequential or timestamp numbering |
|
||||
| `speckit.git.validate` | Validate current branch follows feature branch naming conventions |
|
||||
| `speckit.git.remote` | Detect Git remote URL for GitHub integration |
|
||||
| `speckit.git.commit` | Auto-commit changes (configurable per-command enable/disable and messages) |
|
||||
|
||||
## Hooks
|
||||
|
||||
| Event | Command | Optional | Description |
|
||||
|-------|---------|----------|-------------|
|
||||
| `before_constitution` | `speckit.git.initialize` | No | Init git repo before constitution |
|
||||
| `before_specify` | `speckit.git.feature` | No | Create feature branch before specification |
|
||||
| `before_clarify` | `speckit.git.commit` | Yes | Commit outstanding changes before clarification |
|
||||
| `before_plan` | `speckit.git.commit` | Yes | Commit outstanding changes before planning |
|
||||
| `before_tasks` | `speckit.git.commit` | Yes | Commit outstanding changes before task generation |
|
||||
| `before_implement` | `speckit.git.commit` | Yes | Commit outstanding changes before implementation |
|
||||
| `before_checklist` | `speckit.git.commit` | Yes | Commit outstanding changes before checklist |
|
||||
| `before_analyze` | `speckit.git.commit` | Yes | Commit outstanding changes before analysis |
|
||||
| `before_taskstoissues` | `speckit.git.commit` | Yes | Commit outstanding changes before issue sync |
|
||||
| `after_constitution` | `speckit.git.commit` | Yes | Auto-commit after constitution update |
|
||||
| `after_specify` | `speckit.git.commit` | Yes | Auto-commit after specification |
|
||||
| `after_clarify` | `speckit.git.commit` | Yes | Auto-commit after clarification |
|
||||
| `after_plan` | `speckit.git.commit` | Yes | Auto-commit after planning |
|
||||
| `after_tasks` | `speckit.git.commit` | Yes | Auto-commit after task generation |
|
||||
| `after_implement` | `speckit.git.commit` | Yes | Auto-commit after implementation |
|
||||
| `after_checklist` | `speckit.git.commit` | Yes | Auto-commit after checklist |
|
||||
| `after_analyze` | `speckit.git.commit` | Yes | Auto-commit after analysis |
|
||||
| `after_taskstoissues` | `speckit.git.commit` | Yes | Auto-commit after issue sync |
|
||||
|
||||
## Configuration
|
||||
|
||||
Configuration is stored in `.specify/extensions/git/git-config.yml`:
|
||||
|
||||
```yaml
|
||||
# Branch numbering strategy: "sequential" or "timestamp"
|
||||
branch_numbering: sequential
|
||||
|
||||
# Custom commit message for git init
|
||||
init_commit_message: "[Spec Kit] Initial commit"
|
||||
|
||||
# Auto-commit per command (all disabled by default)
|
||||
# Example: enable auto-commit after specify
|
||||
auto_commit:
|
||||
default: false
|
||||
after_specify:
|
||||
enabled: true
|
||||
message: "[Spec Kit] Add specification"
|
||||
```
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
# Install the bundled git extension (no network required)
|
||||
specify extension add git
|
||||
```
|
||||
|
||||
## Disabling
|
||||
|
||||
```bash
|
||||
# Disable the git extension (spec creation continues without branching)
|
||||
specify extension disable git
|
||||
|
||||
# Re-enable it
|
||||
specify extension enable git
|
||||
```
|
||||
|
||||
## Graceful Degradation
|
||||
|
||||
When Git is not installed or the directory is not a Git repository:
|
||||
- Spec directories are still created under `specs/`
|
||||
- Branch creation is skipped with a warning
|
||||
- Branch validation is skipped with a warning
|
||||
- Remote detection returns empty results
|
||||
|
||||
## Scripts
|
||||
|
||||
The extension bundles cross-platform scripts:
|
||||
|
||||
- `scripts/bash/create-new-feature.sh` — Bash implementation
|
||||
- `scripts/bash/git-common.sh` — Shared Git utilities (Bash)
|
||||
- `scripts/powershell/create-new-feature.ps1` — PowerShell implementation
|
||||
- `scripts/powershell/git-common.ps1` — Shared Git utilities (PowerShell)
|
||||
@@ -0,0 +1,48 @@
|
||||
---
|
||||
description: "Auto-commit changes after a Spec Kit command completes"
|
||||
---
|
||||
|
||||
# Auto-Commit Changes
|
||||
|
||||
Automatically stage and commit all changes after a Spec Kit command completes.
|
||||
|
||||
## Behavior
|
||||
|
||||
This command is invoked as a hook after (or before) core commands. It:
|
||||
|
||||
1. Determines the event name from the hook context (e.g., if invoked as an `after_specify` hook, the event is `after_specify`; if `before_plan`, the event is `before_plan`)
|
||||
2. Checks `.specify/extensions/git/git-config.yml` for the `auto_commit` section
|
||||
3. Looks up the specific event key to see if auto-commit is enabled
|
||||
4. Falls back to `auto_commit.default` if no event-specific key exists
|
||||
5. Uses the per-command `message` if configured, otherwise a default message
|
||||
6. If enabled and there are uncommitted changes, runs `git add .` + `git commit`
|
||||
|
||||
## Execution
|
||||
|
||||
Determine the event name from the hook that triggered this command, then run the script:
|
||||
|
||||
- **Bash**: `.specify/extensions/git/scripts/bash/auto-commit.sh <event_name>`
|
||||
- **PowerShell**: `.specify/extensions/git/scripts/powershell/auto-commit.ps1 <event_name>`
|
||||
|
||||
Replace `<event_name>` with the actual hook event (e.g., `after_specify`, `before_plan`, `after_implement`).
|
||||
|
||||
## Configuration
|
||||
|
||||
In `.specify/extensions/git/git-config.yml`:
|
||||
|
||||
```yaml
|
||||
auto_commit:
|
||||
default: false # Global toggle — set true to enable for all commands
|
||||
after_specify:
|
||||
enabled: true # Override per-command
|
||||
message: "[Spec Kit] Add specification"
|
||||
after_plan:
|
||||
enabled: false
|
||||
message: "[Spec Kit] Add implementation plan"
|
||||
```
|
||||
|
||||
## Graceful Degradation
|
||||
|
||||
- If Git is not available or the current directory is not a repository: skips with a warning
|
||||
- If no config file exists: skips (disabled by default)
|
||||
- If no changes to commit: skips with a message
|
||||
@@ -0,0 +1,67 @@
|
||||
---
|
||||
description: "Create a feature branch with sequential or timestamp numbering"
|
||||
---
|
||||
|
||||
# Create Feature Branch
|
||||
|
||||
Create and switch to a new git feature branch for the given specification. This command handles **branch creation only** — the spec directory and files are created by the core `__SPECKIT_COMMAND_SPECIFY__` workflow.
|
||||
|
||||
## User Input
|
||||
|
||||
```text
|
||||
$ARGUMENTS
|
||||
```
|
||||
|
||||
You **MUST** consider the user input before proceeding (if not empty).
|
||||
|
||||
## Environment Variable Override
|
||||
|
||||
If the user explicitly provided `GIT_BRANCH_NAME` (e.g., via environment variable, argument, or in their request), pass it through to the script by setting the `GIT_BRANCH_NAME` environment variable before invoking the script. When `GIT_BRANCH_NAME` is set:
|
||||
- The script uses the exact value as the branch name, bypassing all prefix/suffix generation
|
||||
- `--short-name`, `--number`, and `--timestamp` flags are ignored
|
||||
- `FEATURE_NUM` is extracted from the name if it starts with a numeric prefix, otherwise set to the full branch name
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Verify Git is available by running `git rev-parse --is-inside-work-tree 2>/dev/null`
|
||||
- If Git is not available, warn the user and skip branch creation
|
||||
|
||||
## Branch Numbering Mode
|
||||
|
||||
Determine the branch numbering strategy by checking configuration in this order:
|
||||
|
||||
1. Check `.specify/extensions/git/git-config.yml` for `branch_numbering` value
|
||||
2. Check `.specify/init-options.json` for `branch_numbering` value (backward compatibility)
|
||||
3. Default to `sequential` if neither exists
|
||||
|
||||
## Execution
|
||||
|
||||
Generate a concise short name (2-4 words) for the branch:
|
||||
- Analyze the feature description and extract the most meaningful keywords
|
||||
- Use action-noun format when possible (e.g., "add-user-auth", "fix-payment-bug")
|
||||
- Preserve technical terms and acronyms (OAuth2, API, JWT, etc.)
|
||||
|
||||
Run the appropriate script based on your platform:
|
||||
|
||||
- **Bash**: `.specify/extensions/git/scripts/bash/create-new-feature.sh --json --short-name "<short-name>" "<feature description>"`
|
||||
- **Bash (timestamp)**: `.specify/extensions/git/scripts/bash/create-new-feature.sh --json --timestamp --short-name "<short-name>" "<feature description>"`
|
||||
- **PowerShell**: `.specify/extensions/git/scripts/powershell/create-new-feature.ps1 -Json -ShortName "<short-name>" "<feature description>"`
|
||||
- **PowerShell (timestamp)**: `.specify/extensions/git/scripts/powershell/create-new-feature.ps1 -Json -Timestamp -ShortName "<short-name>" "<feature description>"`
|
||||
|
||||
**IMPORTANT**:
|
||||
- Do NOT pass `--number` — the script determines the correct next number automatically
|
||||
- Always include the JSON flag (`--json` for Bash, `-Json` for PowerShell) so the output can be parsed reliably
|
||||
- You must only ever run this script once per feature
|
||||
- The JSON output will contain `BRANCH_NAME` and `FEATURE_NUM`
|
||||
|
||||
## Graceful Degradation
|
||||
|
||||
If Git is not installed or the current directory is not a Git repository:
|
||||
- Branch creation is skipped with a warning: `[specify] Warning: Git repository not detected; skipped branch creation`
|
||||
- The script still outputs `BRANCH_NAME` and `FEATURE_NUM` so the caller can reference them
|
||||
|
||||
## Output
|
||||
|
||||
The script outputs JSON with:
|
||||
- `BRANCH_NAME`: The branch name (e.g., `003-user-auth` or `20260319-143022-user-auth`)
|
||||
- `FEATURE_NUM`: The numeric or timestamp prefix used
|
||||
@@ -0,0 +1,49 @@
|
||||
---
|
||||
description: "Initialize a Git repository with an initial commit"
|
||||
---
|
||||
|
||||
# Initialize Git Repository
|
||||
|
||||
Initialize a Git repository in the current project directory if one does not already exist.
|
||||
|
||||
## Execution
|
||||
|
||||
Run the appropriate script from the project root:
|
||||
|
||||
- **Bash**: `.specify/extensions/git/scripts/bash/initialize-repo.sh`
|
||||
- **PowerShell**: `.specify/extensions/git/scripts/powershell/initialize-repo.ps1`
|
||||
|
||||
If the extension scripts are not found, fall back to:
|
||||
- **Bash**: `git init && git add . && git commit -m "Initial commit from Specify template"`
|
||||
- **PowerShell**: `git init; git add .; git commit -m "Initial commit from Specify template"`
|
||||
|
||||
The script handles all checks internally:
|
||||
- Skips if Git is not available
|
||||
- Skips if already inside a Git repository
|
||||
- Runs `git init`, `git add .`, and `git commit` with an initial commit message
|
||||
|
||||
## Customization
|
||||
|
||||
Replace the script to add project-specific Git initialization steps:
|
||||
- Custom `.gitignore` templates
|
||||
- Default branch naming (`git config init.defaultBranch`)
|
||||
- Git LFS setup
|
||||
- Git hooks installation
|
||||
- Commit signing configuration
|
||||
- Git Flow initialization
|
||||
|
||||
## Output
|
||||
|
||||
On success:
|
||||
- `[OK] Git repository initialized`
|
||||
|
||||
## Graceful Degradation
|
||||
|
||||
If Git is not installed:
|
||||
- Warn the user
|
||||
- Skip repository initialization
|
||||
- The project continues to function without Git (specs can still be created under `specs/`)
|
||||
|
||||
If Git is installed but `git init`, `git add .`, or `git commit` fails:
|
||||
- Surface the error to the user
|
||||
- Stop this command rather than continuing with a partially initialized repository
|
||||
@@ -0,0 +1,45 @@
|
||||
---
|
||||
description: "Detect Git remote URL for GitHub integration"
|
||||
---
|
||||
|
||||
# Detect Git Remote URL
|
||||
|
||||
Detect the Git remote URL for integration with GitHub services (e.g., issue creation).
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Check if Git is available by running `git rev-parse --is-inside-work-tree 2>/dev/null`
|
||||
- If Git is not available, output a warning and return empty:
|
||||
```
|
||||
[specify] Warning: Git repository not detected; cannot determine remote URL
|
||||
```
|
||||
|
||||
## Execution
|
||||
|
||||
Run the following command to get the remote URL:
|
||||
|
||||
```bash
|
||||
git config --get remote.origin.url
|
||||
```
|
||||
|
||||
## Output
|
||||
|
||||
Parse the remote URL and determine:
|
||||
|
||||
1. **Repository owner**: Extract from the URL (e.g., `github` from `https://github.com/github/spec-kit.git`)
|
||||
2. **Repository name**: Extract from the URL (e.g., `spec-kit` from `https://github.com/github/spec-kit.git`)
|
||||
3. **Is GitHub**: Whether the remote points to a GitHub repository
|
||||
|
||||
Supported URL formats:
|
||||
- HTTPS: `https://github.com/<owner>/<repo>.git`
|
||||
- SSH: `git@github.com:<owner>/<repo>.git`
|
||||
|
||||
> [!CAUTION]
|
||||
> ONLY report a GitHub repository if the remote URL actually points to github.com.
|
||||
> Do NOT assume the remote is GitHub if the URL format doesn't match.
|
||||
|
||||
## Graceful Degradation
|
||||
|
||||
If Git is not installed, the directory is not a Git repository, or no remote is configured:
|
||||
- Return an empty result
|
||||
- Do NOT error — other workflows should continue without Git remote information
|
||||
@@ -0,0 +1,49 @@
|
||||
---
|
||||
description: "Validate current branch follows feature branch naming conventions"
|
||||
---
|
||||
|
||||
# Validate Feature Branch
|
||||
|
||||
Validate that the current Git branch follows the expected feature branch naming conventions.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Check if Git is available by running `git rev-parse --is-inside-work-tree 2>/dev/null`
|
||||
- If Git is not available, output a warning and skip validation:
|
||||
```
|
||||
[specify] Warning: Git repository not detected; skipped branch validation
|
||||
```
|
||||
|
||||
## Validation Rules
|
||||
|
||||
Get the current branch name:
|
||||
|
||||
```bash
|
||||
git rev-parse --abbrev-ref HEAD
|
||||
```
|
||||
|
||||
The branch name must match one of these patterns:
|
||||
|
||||
1. **Sequential**: `^[0-9]{3,}-` (e.g., `001-feature-name`, `042-fix-bug`, `1000-big-feature`)
|
||||
2. **Timestamp**: `^[0-9]{8}-[0-9]{6}-` (e.g., `20260319-143022-feature-name`)
|
||||
|
||||
## Execution
|
||||
|
||||
If on a feature branch (matches either pattern):
|
||||
- Output: `✓ On feature branch: <branch-name>`
|
||||
- Check if the corresponding spec directory exists under `specs/`:
|
||||
- For sequential branches, look for `specs/<prefix>-*` where prefix matches the numeric portion
|
||||
- For timestamp branches, look for `specs/<prefix>-*` where prefix matches the `YYYYMMDD-HHMMSS` portion
|
||||
- If spec directory exists: `✓ Spec directory found: <path>`
|
||||
- If spec directory missing: `⚠ No spec directory found for prefix <prefix>`
|
||||
|
||||
If NOT on a feature branch:
|
||||
- Output: `✗ Not on a feature branch. Current branch: <branch-name>`
|
||||
- Output: `Feature branches should be named like: 001-feature-name or 20260319-143022-feature-name`
|
||||
|
||||
## Graceful Degradation
|
||||
|
||||
If Git is not installed or the directory is not a Git repository:
|
||||
- Check the `SPECIFY_FEATURE` environment variable as a fallback
|
||||
- If set, validate that value against the naming patterns
|
||||
- If not set, skip validation with a warning
|
||||
@@ -0,0 +1,62 @@
|
||||
# Git Branching Workflow Extension Configuration
|
||||
# Copied to .specify/extensions/git/git-config.yml on install
|
||||
|
||||
# Branch numbering strategy: "sequential" (001, 002, ...) or "timestamp" (YYYYMMDD-HHMMSS)
|
||||
branch_numbering: sequential
|
||||
|
||||
# Commit message used by `git commit` during repository initialization
|
||||
init_commit_message: "[Spec Kit] Initial commit"
|
||||
|
||||
# Auto-commit before/after core commands.
|
||||
# Set "default" to enable for all commands, then override per-command.
|
||||
# Each key can be true/false. Message is customizable per-command.
|
||||
auto_commit:
|
||||
default: false
|
||||
before_clarify:
|
||||
enabled: false
|
||||
message: "[Spec Kit] Save progress before clarification"
|
||||
before_plan:
|
||||
enabled: false
|
||||
message: "[Spec Kit] Save progress before planning"
|
||||
before_tasks:
|
||||
enabled: false
|
||||
message: "[Spec Kit] Save progress before task generation"
|
||||
before_implement:
|
||||
enabled: false
|
||||
message: "[Spec Kit] Save progress before implementation"
|
||||
before_checklist:
|
||||
enabled: false
|
||||
message: "[Spec Kit] Save progress before checklist"
|
||||
before_analyze:
|
||||
enabled: false
|
||||
message: "[Spec Kit] Save progress before analysis"
|
||||
before_taskstoissues:
|
||||
enabled: false
|
||||
message: "[Spec Kit] Save progress before issue sync"
|
||||
after_constitution:
|
||||
enabled: false
|
||||
message: "[Spec Kit] Add project constitution"
|
||||
after_specify:
|
||||
enabled: false
|
||||
message: "[Spec Kit] Add specification"
|
||||
after_clarify:
|
||||
enabled: false
|
||||
message: "[Spec Kit] Clarify specification"
|
||||
after_plan:
|
||||
enabled: false
|
||||
message: "[Spec Kit] Add implementation plan"
|
||||
after_tasks:
|
||||
enabled: false
|
||||
message: "[Spec Kit] Add tasks"
|
||||
after_implement:
|
||||
enabled: false
|
||||
message: "[Spec Kit] Implementation progress"
|
||||
after_checklist:
|
||||
enabled: false
|
||||
message: "[Spec Kit] Add checklist"
|
||||
after_analyze:
|
||||
enabled: false
|
||||
message: "[Spec Kit] Add analysis report"
|
||||
after_taskstoissues:
|
||||
enabled: false
|
||||
message: "[Spec Kit] Sync tasks to issues"
|
||||
@@ -0,0 +1,140 @@
|
||||
schema_version: "1.0"
|
||||
|
||||
extension:
|
||||
id: git
|
||||
name: "Git Branching Workflow"
|
||||
version: "1.0.0"
|
||||
description: "Feature branch creation, numbering (sequential/timestamp), validation, and Git remote detection"
|
||||
author: spec-kit-core
|
||||
repository: https://github.com/github/spec-kit
|
||||
license: MIT
|
||||
|
||||
requires:
|
||||
speckit_version: ">=0.2.0"
|
||||
tools:
|
||||
- name: git
|
||||
required: false
|
||||
|
||||
provides:
|
||||
commands:
|
||||
- name: speckit.git.feature
|
||||
file: commands/speckit.git.feature.md
|
||||
description: "Create a feature branch with sequential or timestamp numbering"
|
||||
- name: speckit.git.validate
|
||||
file: commands/speckit.git.validate.md
|
||||
description: "Validate current branch follows feature branch naming conventions"
|
||||
- name: speckit.git.remote
|
||||
file: commands/speckit.git.remote.md
|
||||
description: "Detect Git remote URL for GitHub integration"
|
||||
- name: speckit.git.initialize
|
||||
file: commands/speckit.git.initialize.md
|
||||
description: "Initialize a Git repository with an initial commit"
|
||||
- name: speckit.git.commit
|
||||
file: commands/speckit.git.commit.md
|
||||
description: "Auto-commit changes after a Spec Kit command completes"
|
||||
|
||||
config:
|
||||
- name: "git-config.yml"
|
||||
template: "config-template.yml"
|
||||
description: "Git branching configuration"
|
||||
required: false
|
||||
|
||||
hooks:
|
||||
before_constitution:
|
||||
command: speckit.git.initialize
|
||||
optional: false
|
||||
description: "Initialize Git repository before constitution setup"
|
||||
before_specify:
|
||||
command: speckit.git.feature
|
||||
optional: false
|
||||
description: "Create feature branch before specification"
|
||||
before_clarify:
|
||||
command: speckit.git.commit
|
||||
optional: true
|
||||
prompt: "Commit outstanding changes before clarification?"
|
||||
description: "Auto-commit before spec clarification"
|
||||
before_plan:
|
||||
command: speckit.git.commit
|
||||
optional: true
|
||||
prompt: "Commit outstanding changes before planning?"
|
||||
description: "Auto-commit before implementation planning"
|
||||
before_tasks:
|
||||
command: speckit.git.commit
|
||||
optional: true
|
||||
prompt: "Commit outstanding changes before task generation?"
|
||||
description: "Auto-commit before task generation"
|
||||
before_implement:
|
||||
command: speckit.git.commit
|
||||
optional: true
|
||||
prompt: "Commit outstanding changes before implementation?"
|
||||
description: "Auto-commit before implementation"
|
||||
before_checklist:
|
||||
command: speckit.git.commit
|
||||
optional: true
|
||||
prompt: "Commit outstanding changes before checklist?"
|
||||
description: "Auto-commit before checklist generation"
|
||||
before_analyze:
|
||||
command: speckit.git.commit
|
||||
optional: true
|
||||
prompt: "Commit outstanding changes before analysis?"
|
||||
description: "Auto-commit before analysis"
|
||||
before_taskstoissues:
|
||||
command: speckit.git.commit
|
||||
optional: true
|
||||
prompt: "Commit outstanding changes before issue sync?"
|
||||
description: "Auto-commit before tasks-to-issues conversion"
|
||||
after_constitution:
|
||||
command: speckit.git.commit
|
||||
optional: true
|
||||
prompt: "Commit constitution changes?"
|
||||
description: "Auto-commit after constitution update"
|
||||
after_specify:
|
||||
command: speckit.git.commit
|
||||
optional: true
|
||||
prompt: "Commit specification changes?"
|
||||
description: "Auto-commit after specification"
|
||||
after_clarify:
|
||||
command: speckit.git.commit
|
||||
optional: true
|
||||
prompt: "Commit clarification changes?"
|
||||
description: "Auto-commit after spec clarification"
|
||||
after_plan:
|
||||
command: speckit.git.commit
|
||||
optional: true
|
||||
prompt: "Commit plan changes?"
|
||||
description: "Auto-commit after implementation planning"
|
||||
after_tasks:
|
||||
command: speckit.git.commit
|
||||
optional: true
|
||||
prompt: "Commit task changes?"
|
||||
description: "Auto-commit after task generation"
|
||||
after_implement:
|
||||
command: speckit.git.commit
|
||||
optional: true
|
||||
prompt: "Commit implementation changes?"
|
||||
description: "Auto-commit after implementation"
|
||||
after_checklist:
|
||||
command: speckit.git.commit
|
||||
optional: true
|
||||
prompt: "Commit checklist changes?"
|
||||
description: "Auto-commit after checklist generation"
|
||||
after_analyze:
|
||||
command: speckit.git.commit
|
||||
optional: true
|
||||
prompt: "Commit analysis results?"
|
||||
description: "Auto-commit after analysis"
|
||||
after_taskstoissues:
|
||||
command: speckit.git.commit
|
||||
optional: true
|
||||
prompt: "Commit after syncing issues?"
|
||||
description: "Auto-commit after tasks-to-issues conversion"
|
||||
|
||||
tags:
|
||||
- "git"
|
||||
- "branching"
|
||||
- "workflow"
|
||||
|
||||
config:
|
||||
defaults:
|
||||
branch_numbering: sequential
|
||||
init_commit_message: "[Spec Kit] Initial commit"
|
||||
@@ -0,0 +1,62 @@
|
||||
# Git Branching Workflow Extension Configuration
|
||||
# Copied to .specify/extensions/git/git-config.yml on install
|
||||
|
||||
# Branch numbering strategy: "sequential" (001, 002, ...) or "timestamp" (YYYYMMDD-HHMMSS)
|
||||
branch_numbering: sequential
|
||||
|
||||
# Commit message used by `git commit` during repository initialization
|
||||
init_commit_message: "[Spec Kit] Initial commit"
|
||||
|
||||
# Auto-commit before/after core commands.
|
||||
# Set "default" to enable for all commands, then override per-command.
|
||||
# Each key can be true/false. Message is customizable per-command.
|
||||
auto_commit:
|
||||
default: false
|
||||
before_clarify:
|
||||
enabled: false
|
||||
message: "[Spec Kit] Save progress before clarification"
|
||||
before_plan:
|
||||
enabled: false
|
||||
message: "[Spec Kit] Save progress before planning"
|
||||
before_tasks:
|
||||
enabled: false
|
||||
message: "[Spec Kit] Save progress before task generation"
|
||||
before_implement:
|
||||
enabled: false
|
||||
message: "[Spec Kit] Save progress before implementation"
|
||||
before_checklist:
|
||||
enabled: false
|
||||
message: "[Spec Kit] Save progress before checklist"
|
||||
before_analyze:
|
||||
enabled: false
|
||||
message: "[Spec Kit] Save progress before analysis"
|
||||
before_taskstoissues:
|
||||
enabled: false
|
||||
message: "[Spec Kit] Save progress before issue sync"
|
||||
after_constitution:
|
||||
enabled: false
|
||||
message: "[Spec Kit] Add project constitution"
|
||||
after_specify:
|
||||
enabled: false
|
||||
message: "[Spec Kit] Add specification"
|
||||
after_clarify:
|
||||
enabled: false
|
||||
message: "[Spec Kit] Clarify specification"
|
||||
after_plan:
|
||||
enabled: false
|
||||
message: "[Spec Kit] Add implementation plan"
|
||||
after_tasks:
|
||||
enabled: false
|
||||
message: "[Spec Kit] Add tasks"
|
||||
after_implement:
|
||||
enabled: false
|
||||
message: "[Spec Kit] Implementation progress"
|
||||
after_checklist:
|
||||
enabled: false
|
||||
message: "[Spec Kit] Add checklist"
|
||||
after_analyze:
|
||||
enabled: false
|
||||
message: "[Spec Kit] Add analysis report"
|
||||
after_taskstoissues:
|
||||
enabled: false
|
||||
message: "[Spec Kit] Sync tasks to issues"
|
||||
@@ -0,0 +1,140 @@
|
||||
#!/usr/bin/env bash
|
||||
# Git extension: auto-commit.sh
|
||||
# Automatically commit changes after a Spec Kit command completes.
|
||||
# Checks per-command config keys in git-config.yml before committing.
|
||||
#
|
||||
# Usage: auto-commit.sh <event_name>
|
||||
# e.g.: auto-commit.sh after_specify
|
||||
|
||||
set -e
|
||||
|
||||
EVENT_NAME="${1:-}"
|
||||
if [ -z "$EVENT_NAME" ]; then
|
||||
echo "Usage: $0 <event_name>" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
SCRIPT_DIR="$(CDPATH="" cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
|
||||
_find_project_root() {
|
||||
local dir="$1"
|
||||
while [ "$dir" != "/" ]; do
|
||||
if [ -d "$dir/.specify" ] || [ -d "$dir/.git" ]; then
|
||||
echo "$dir"
|
||||
return 0
|
||||
fi
|
||||
dir="$(dirname "$dir")"
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
REPO_ROOT=$(_find_project_root "$SCRIPT_DIR") || REPO_ROOT="$(pwd)"
|
||||
cd "$REPO_ROOT"
|
||||
|
||||
# Check if git is available
|
||||
if ! command -v git >/dev/null 2>&1; then
|
||||
echo "[specify] Warning: Git not found; skipped auto-commit" >&2
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
|
||||
echo "[specify] Warning: Not a Git repository; skipped auto-commit" >&2
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Read per-command config from git-config.yml
|
||||
_config_file="$REPO_ROOT/.specify/extensions/git/git-config.yml"
|
||||
_enabled=false
|
||||
_commit_msg=""
|
||||
|
||||
if [ -f "$_config_file" ]; then
|
||||
# Parse the auto_commit section for this event.
|
||||
# Look for auto_commit.<event_name>.enabled and .message
|
||||
# Also check auto_commit.default as fallback.
|
||||
_in_auto_commit=false
|
||||
_in_event=false
|
||||
_default_enabled=false
|
||||
|
||||
while IFS= read -r _line; do
|
||||
# Detect auto_commit: section
|
||||
if echo "$_line" | grep -q '^auto_commit:'; then
|
||||
_in_auto_commit=true
|
||||
_in_event=false
|
||||
continue
|
||||
fi
|
||||
|
||||
# Exit auto_commit section on next top-level key
|
||||
if $_in_auto_commit && echo "$_line" | grep -Eq '^[a-z]'; then
|
||||
break
|
||||
fi
|
||||
|
||||
if $_in_auto_commit; then
|
||||
# Check default key
|
||||
if echo "$_line" | grep -Eq "^[[:space:]]+default:[[:space:]]"; then
|
||||
_val=$(echo "$_line" | sed 's/^[^:]*:[[:space:]]*//' | tr -d '[:space:]' | tr '[:upper:]' '[:lower:]')
|
||||
[ "$_val" = "true" ] && _default_enabled=true
|
||||
fi
|
||||
|
||||
# Detect our event subsection
|
||||
if echo "$_line" | grep -Eq "^[[:space:]]+${EVENT_NAME}:"; then
|
||||
_in_event=true
|
||||
continue
|
||||
fi
|
||||
|
||||
# Inside our event subsection
|
||||
if $_in_event; then
|
||||
# Exit on next sibling key (same indent level as event name)
|
||||
if echo "$_line" | grep -Eq '^[[:space:]]{2}[a-z]' && ! echo "$_line" | grep -Eq '^[[:space:]]{4}'; then
|
||||
_in_event=false
|
||||
continue
|
||||
fi
|
||||
if echo "$_line" | grep -Eq '[[:space:]]+enabled:'; then
|
||||
_val=$(echo "$_line" | sed 's/^[^:]*:[[:space:]]*//' | tr -d '[:space:]' | tr '[:upper:]' '[:lower:]')
|
||||
[ "$_val" = "true" ] && _enabled=true
|
||||
[ "$_val" = "false" ] && _enabled=false
|
||||
fi
|
||||
if echo "$_line" | grep -Eq '[[:space:]]+message:'; then
|
||||
_commit_msg=$(echo "$_line" | sed 's/^[^:]*:[[:space:]]*//' | sed 's/^["'\'']//' | sed 's/["'\'']*$//')
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
done < "$_config_file"
|
||||
|
||||
# If event-specific key not found, use default
|
||||
if [ "$_enabled" = "false" ] && [ "$_default_enabled" = "true" ]; then
|
||||
# Only use default if the event wasn't explicitly set to false
|
||||
# Check if event section existed at all
|
||||
if ! grep -q "^[[:space:]]*${EVENT_NAME}:" "$_config_file" 2>/dev/null; then
|
||||
_enabled=true
|
||||
fi
|
||||
fi
|
||||
else
|
||||
# No config file — auto-commit disabled by default
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [ "$_enabled" != "true" ]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Check if there are changes to commit
|
||||
if git diff --quiet HEAD 2>/dev/null && git diff --cached --quiet 2>/dev/null && [ -z "$(git ls-files --others --exclude-standard 2>/dev/null)" ]; then
|
||||
echo "[specify] No changes to commit after $EVENT_NAME" >&2
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Derive a human-readable command name from the event
|
||||
# e.g., after_specify -> specify, before_plan -> plan
|
||||
_command_name=$(echo "$EVENT_NAME" | sed 's/^after_//' | sed 's/^before_//')
|
||||
_phase=$(echo "$EVENT_NAME" | grep -q '^before_' && echo 'before' || echo 'after')
|
||||
|
||||
# Use custom message if configured, otherwise default
|
||||
if [ -z "$_commit_msg" ]; then
|
||||
_commit_msg="[Spec Kit] Auto-commit ${_phase} ${_command_name}"
|
||||
fi
|
||||
|
||||
# Stage and commit
|
||||
_git_out=$(git add . 2>&1) || { echo "[specify] Error: git add failed: $_git_out" >&2; exit 1; }
|
||||
_git_out=$(git commit -q -m "$_commit_msg" 2>&1) || { echo "[specify] Error: git commit failed: $_git_out" >&2; exit 1; }
|
||||
|
||||
echo "[OK] Changes committed ${_phase} ${_command_name}" >&2
|
||||
@@ -0,0 +1,453 @@
|
||||
#!/usr/bin/env bash
|
||||
# Git extension: create-new-feature.sh
|
||||
# Adapted from core scripts/bash/create-new-feature.sh for extension layout.
|
||||
# Sources common.sh from the project's installed scripts, falling back to
|
||||
# git-common.sh for minimal git helpers.
|
||||
|
||||
set -e
|
||||
|
||||
JSON_MODE=false
|
||||
DRY_RUN=false
|
||||
ALLOW_EXISTING=false
|
||||
SHORT_NAME=""
|
||||
BRANCH_NUMBER=""
|
||||
USE_TIMESTAMP=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}"
|
||||
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 [[ ! "$BRANCH_NUMBER" =~ ^[0-9]+$ ]]; then
|
||||
echo 'Error: --number must be a non-negative integer' >&2
|
||||
exit 1
|
||||
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 branch name without creating the branch"
|
||||
echo " --allow-existing-branch Switch to branch if it already exists instead of failing"
|
||||
echo " --short-name <name> Provide a custom short name (2-4 words) for the branch"
|
||||
echo " --number N Specify branch number manually (overrides auto-detection)"
|
||||
echo " --timestamp Use timestamp prefix (YYYYMMDD-HHMMSS) instead of sequential numbering"
|
||||
echo " --help, -h Show this help message"
|
||||
echo ""
|
||||
echo "Environment variables:"
|
||||
echo " GIT_BRANCH_NAME Use this exact branch name, bypassing all prefix/suffix generation"
|
||||
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'"
|
||||
echo " GIT_BRANCH_NAME=my-branch $0 'feature description'"
|
||||
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
|
||||
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
|
||||
|
||||
# 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]+')
|
||||
number=$((10#$number))
|
||||
if [ "$number" -gt "$highest" ]; then
|
||||
highest=$number
|
||||
fi
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
echo "$highest"
|
||||
}
|
||||
|
||||
# Function to get highest number from git branches
|
||||
get_highest_from_branches() {
|
||||
git branch -a 2>/dev/null | sed 's/^[* ]*//; s|^remotes/[^/]*/||' | _extract_highest_number
|
||||
}
|
||||
|
||||
# Extract the highest sequential feature number from a list of ref names (one per line).
|
||||
_extract_highest_number() {
|
||||
local highest=0
|
||||
while IFS= read -r name; do
|
||||
[ -z "$name" ] && continue
|
||||
if echo "$name" | grep -Eq '^[0-9]{3,}-' && ! echo "$name" | grep -Eq '^[0-9]{8}-[0-9]{6}-'; then
|
||||
number=$(echo "$name" | grep -Eo '^[0-9]+' || echo "0")
|
||||
number=$((10#$number))
|
||||
if [ "$number" -gt "$highest" ]; then
|
||||
highest=$number
|
||||
fi
|
||||
fi
|
||||
done
|
||||
echo "$highest"
|
||||
}
|
||||
|
||||
# Function to get highest number from remote branches without fetching (side-effect-free)
|
||||
get_highest_from_remote_refs() {
|
||||
local highest=0
|
||||
|
||||
for remote in $(git remote 2>/dev/null); do
|
||||
local remote_highest
|
||||
remote_highest=$(GIT_TERMINAL_PROMPT=0 git ls-remote --heads "$remote" 2>/dev/null | sed 's|.*refs/heads/||' | _extract_highest_number)
|
||||
if [ "$remote_highest" -gt "$highest" ]; then
|
||||
highest=$remote_highest
|
||||
fi
|
||||
done
|
||||
|
||||
echo "$highest"
|
||||
}
|
||||
|
||||
# Function to check existing branches and return next available number.
|
||||
check_existing_branches() {
|
||||
local specs_dir="$1"
|
||||
local skip_fetch="${2:-false}"
|
||||
|
||||
if [ "$skip_fetch" = true ]; then
|
||||
local highest_remote=$(get_highest_from_remote_refs)
|
||||
local highest_branch=$(get_highest_from_branches)
|
||||
if [ "$highest_remote" -gt "$highest_branch" ]; then
|
||||
highest_branch=$highest_remote
|
||||
fi
|
||||
else
|
||||
git fetch --all --prune >/dev/null 2>&1 || true
|
||||
local highest_branch=$(get_highest_from_branches)
|
||||
fi
|
||||
|
||||
local highest_spec=$(get_highest_from_specs "$specs_dir")
|
||||
|
||||
local max_num=$highest_branch
|
||||
if [ "$highest_spec" -gt "$max_num" ]; then
|
||||
max_num=$highest_spec
|
||||
fi
|
||||
|
||||
echo $((max_num + 1))
|
||||
}
|
||||
|
||||
# Function to clean and format a branch name
|
||||
clean_branch_name() {
|
||||
local name="$1"
|
||||
echo "$name" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]/-/g' | sed 's/-\+/-/g' | sed 's/^-//' | sed 's/-$//'
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Source common.sh for resolve_template, json_escape, get_repo_root, has_git.
|
||||
#
|
||||
# Search locations in priority order:
|
||||
# 1. .specify/scripts/bash/common.sh under the project root (installed project)
|
||||
# 2. scripts/bash/common.sh under the project root (source checkout fallback)
|
||||
# 3. git-common.sh next to this script (minimal fallback — lacks resolve_template)
|
||||
# ---------------------------------------------------------------------------
|
||||
SCRIPT_DIR="$(CDPATH="" cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
|
||||
# Find project root by walking up from the script location
|
||||
_find_project_root() {
|
||||
local dir="$1"
|
||||
while [ "$dir" != "/" ]; do
|
||||
if [ -d "$dir/.specify" ] || [ -d "$dir/.git" ]; then
|
||||
echo "$dir"
|
||||
return 0
|
||||
fi
|
||||
dir="$(dirname "$dir")"
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
_common_loaded=false
|
||||
_PROJECT_ROOT=$(_find_project_root "$SCRIPT_DIR") || true
|
||||
|
||||
if [ -n "$_PROJECT_ROOT" ] && [ -f "$_PROJECT_ROOT/.specify/scripts/bash/common.sh" ]; then
|
||||
source "$_PROJECT_ROOT/.specify/scripts/bash/common.sh"
|
||||
_common_loaded=true
|
||||
elif [ -n "$_PROJECT_ROOT" ] && [ -f "$_PROJECT_ROOT/scripts/bash/common.sh" ]; then
|
||||
source "$_PROJECT_ROOT/scripts/bash/common.sh"
|
||||
_common_loaded=true
|
||||
elif [ -f "$SCRIPT_DIR/git-common.sh" ]; then
|
||||
source "$SCRIPT_DIR/git-common.sh"
|
||||
_common_loaded=true
|
||||
fi
|
||||
|
||||
if [ "$_common_loaded" != "true" ]; then
|
||||
echo "Error: Could not locate common.sh or git-common.sh. Please ensure the Specify core scripts are installed." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Resolve repository root
|
||||
if type get_repo_root >/dev/null 2>&1; then
|
||||
REPO_ROOT=$(get_repo_root)
|
||||
elif git rev-parse --show-toplevel >/dev/null 2>&1; then
|
||||
REPO_ROOT=$(git rev-parse --show-toplevel)
|
||||
elif [ -n "$_PROJECT_ROOT" ]; then
|
||||
REPO_ROOT="$_PROJECT_ROOT"
|
||||
else
|
||||
echo "Error: Could not determine repository root." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Check if git is available at this repo root
|
||||
if type has_git >/dev/null 2>&1; then
|
||||
if has_git "$REPO_ROOT"; then
|
||||
HAS_GIT=true
|
||||
else
|
||||
HAS_GIT=false
|
||||
fi
|
||||
elif git -C "$REPO_ROOT" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
|
||||
HAS_GIT=true
|
||||
else
|
||||
HAS_GIT=false
|
||||
fi
|
||||
|
||||
cd "$REPO_ROOT"
|
||||
|
||||
SPECS_DIR="$REPO_ROOT/specs"
|
||||
|
||||
# Function to generate branch name with stop word filtering
|
||||
generate_branch_name() {
|
||||
local description="$1"
|
||||
|
||||
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)$"
|
||||
|
||||
local clean_name=$(echo "$description" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]/ /g')
|
||||
|
||||
local meaningful_words=()
|
||||
for word in $clean_name; do
|
||||
[ -z "$word" ] && continue
|
||||
if ! echo "$word" | grep -qiE "$stop_words"; then
|
||||
if [ ${#word} -ge 3 ]; then
|
||||
meaningful_words+=("$word")
|
||||
elif echo "$description" | grep -qw -- "${word^^}"; then
|
||||
meaningful_words+=("$word")
|
||||
fi
|
||||
fi
|
||||
done
|
||||
|
||||
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
|
||||
local cleaned=$(clean_branch_name "$description")
|
||||
echo "$cleaned" | tr '-' '\n' | grep -v '^$' | head -3 | tr '\n' '-' | sed 's/-$//'
|
||||
fi
|
||||
}
|
||||
|
||||
# Check for GIT_BRANCH_NAME env var override (exact branch name, no prefix/suffix)
|
||||
if [ -n "${GIT_BRANCH_NAME:-}" ]; then
|
||||
BRANCH_NAME="$GIT_BRANCH_NAME"
|
||||
# Extract FEATURE_NUM from the branch name if it starts with a numeric prefix
|
||||
# Check timestamp pattern first (YYYYMMDD-HHMMSS-) since it also matches the simpler ^[0-9]+ pattern
|
||||
if echo "$BRANCH_NAME" | grep -Eq '^[0-9]{8}-[0-9]{6}-'; then
|
||||
FEATURE_NUM=$(echo "$BRANCH_NAME" | grep -Eo '^[0-9]{8}-[0-9]{6}')
|
||||
BRANCH_SUFFIX="${BRANCH_NAME#${FEATURE_NUM}-}"
|
||||
elif echo "$BRANCH_NAME" | grep -Eq '^[0-9]+-'; then
|
||||
FEATURE_NUM=$(echo "$BRANCH_NAME" | grep -Eo '^[0-9]+')
|
||||
BRANCH_SUFFIX="${BRANCH_NAME#${FEATURE_NUM}-}"
|
||||
else
|
||||
FEATURE_NUM="$BRANCH_NAME"
|
||||
BRANCH_SUFFIX="$BRANCH_NAME"
|
||||
fi
|
||||
else
|
||||
# Generate branch name
|
||||
if [ -n "$SHORT_NAME" ]; then
|
||||
BRANCH_SUFFIX=$(clean_branch_name "$SHORT_NAME")
|
||||
else
|
||||
BRANCH_SUFFIX=$(generate_branch_name "$FEATURE_DESCRIPTION")
|
||||
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 [ -z "$BRANCH_NUMBER" ]; then
|
||||
if [ "$DRY_RUN" = true ] && [ "$HAS_GIT" = true ]; then
|
||||
BRANCH_NUMBER=$(check_existing_branches "$SPECS_DIR" true)
|
||||
elif [ "$DRY_RUN" = true ]; then
|
||||
HIGHEST=$(get_highest_from_specs "$SPECS_DIR")
|
||||
BRANCH_NUMBER=$((HIGHEST + 1))
|
||||
elif [ "$HAS_GIT" = true ]; then
|
||||
BRANCH_NUMBER=$(check_existing_branches "$SPECS_DIR")
|
||||
else
|
||||
HIGHEST=$(get_highest_from_specs "$SPECS_DIR")
|
||||
BRANCH_NUMBER=$((HIGHEST + 1))
|
||||
fi
|
||||
fi
|
||||
|
||||
FEATURE_NUM=$(printf "%03d" "$((10#$BRANCH_NUMBER))")
|
||||
BRANCH_NAME="${FEATURE_NUM}-${BRANCH_SUFFIX}"
|
||||
fi
|
||||
fi
|
||||
|
||||
# GitHub enforces a 244-byte limit on branch names
|
||||
MAX_BRANCH_LENGTH=244
|
||||
_byte_length() { printf '%s' "$1" | LC_ALL=C wc -c | tr -d ' '; }
|
||||
BRANCH_BYTE_LEN=$(_byte_length "$BRANCH_NAME")
|
||||
if [ -n "${GIT_BRANCH_NAME:-}" ] && [ "$BRANCH_BYTE_LEN" -gt $MAX_BRANCH_LENGTH ]; then
|
||||
>&2 echo "Error: GIT_BRANCH_NAME must be 244 bytes or fewer in UTF-8. Provided value is ${BRANCH_BYTE_LEN} bytes."
|
||||
exit 1
|
||||
elif [ "$BRANCH_BYTE_LEN" -gt $MAX_BRANCH_LENGTH ]; then
|
||||
PREFIX_LENGTH=$(( ${#FEATURE_NUM} + 1 ))
|
||||
MAX_SUFFIX_LENGTH=$((MAX_BRANCH_LENGTH - PREFIX_LENGTH))
|
||||
|
||||
TRUNCATED_SUFFIX=$(echo "$BRANCH_SUFFIX" | cut -c1-$MAX_SUFFIX_LENGTH)
|
||||
TRUNCATED_SUFFIX=$(echo "$TRUNCATED_SUFFIX" | sed 's/-$//')
|
||||
|
||||
ORIGINAL_BRANCH_NAME="$BRANCH_NAME"
|
||||
BRANCH_NAME="${FEATURE_NUM}-${TRUNCATED_SUFFIX}"
|
||||
|
||||
>&2 echo "[specify] Warning: Branch name exceeded GitHub's 244-byte limit"
|
||||
>&2 echo "[specify] Original: $ORIGINAL_BRANCH_NAME (${#ORIGINAL_BRANCH_NAME} bytes)"
|
||||
>&2 echo "[specify] Truncated to: $BRANCH_NAME (${#BRANCH_NAME} bytes)"
|
||||
fi
|
||||
|
||||
if [ "$DRY_RUN" != true ]; then
|
||||
if [ "$HAS_GIT" = true ]; then
|
||||
branch_create_error=""
|
||||
if ! branch_create_error=$(git checkout -q -b "$BRANCH_NAME" 2>&1); then
|
||||
current_branch="$(git rev-parse --abbrev-ref HEAD 2>/dev/null || true)"
|
||||
if git branch --list "$BRANCH_NAME" | grep -q .; then
|
||||
if [ "$ALLOW_EXISTING" = true ]; then
|
||||
if [ "$current_branch" = "$BRANCH_NAME" ]; then
|
||||
:
|
||||
elif ! switch_branch_error=$(git checkout -q "$BRANCH_NAME" 2>&1); then
|
||||
>&2 echo "Error: Failed to switch to existing branch '$BRANCH_NAME'. Please resolve any local changes or conflicts and try again."
|
||||
if [ -n "$switch_branch_error" ]; then
|
||||
>&2 printf '%s\n' "$switch_branch_error"
|
||||
fi
|
||||
exit 1
|
||||
fi
|
||||
elif [ "$USE_TIMESTAMP" = true ]; then
|
||||
>&2 echo "Error: Branch '$BRANCH_NAME' already exists. Rerun to get a new timestamp or use a different --short-name."
|
||||
exit 1
|
||||
else
|
||||
>&2 echo "Error: Branch '$BRANCH_NAME' already exists. Please use a different feature name or specify a different number with --number."
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
>&2 echo "Error: Failed to create git branch '$BRANCH_NAME'."
|
||||
if [ -n "$branch_create_error" ]; then
|
||||
>&2 printf '%s\n' "$branch_create_error"
|
||||
else
|
||||
>&2 echo "Please check your git configuration and try again."
|
||||
fi
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
else
|
||||
>&2 echo "[specify] Warning: Git repository not detected; skipped branch creation for $BRANCH_NAME"
|
||||
fi
|
||||
|
||||
printf '# To persist: export SPECIFY_FEATURE=%q\n' "$BRANCH_NAME" >&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 feature_num "$FEATURE_NUM" \
|
||||
'{BRANCH_NAME:$branch_name,FEATURE_NUM:$feature_num,DRY_RUN:true}'
|
||||
else
|
||||
jq -cn \
|
||||
--arg branch_name "$BRANCH_NAME" \
|
||||
--arg feature_num "$FEATURE_NUM" \
|
||||
'{BRANCH_NAME:$branch_name,FEATURE_NUM:$feature_num}'
|
||||
fi
|
||||
else
|
||||
if type json_escape >/dev/null 2>&1; then
|
||||
_je_branch=$(json_escape "$BRANCH_NAME")
|
||||
_je_num=$(json_escape "$FEATURE_NUM")
|
||||
else
|
||||
_je_branch="$BRANCH_NAME"
|
||||
_je_num="$FEATURE_NUM"
|
||||
fi
|
||||
if [ "$DRY_RUN" = true ]; then
|
||||
printf '{"BRANCH_NAME":"%s","FEATURE_NUM":"%s","DRY_RUN":true}\n' "$_je_branch" "$_je_num"
|
||||
else
|
||||
printf '{"BRANCH_NAME":"%s","FEATURE_NUM":"%s"}\n' "$_je_branch" "$_je_num"
|
||||
fi
|
||||
fi
|
||||
else
|
||||
echo "BRANCH_NAME: $BRANCH_NAME"
|
||||
echo "FEATURE_NUM: $FEATURE_NUM"
|
||||
if [ "$DRY_RUN" != true ]; then
|
||||
printf '# To persist in your shell: export SPECIFY_FEATURE=%q\n' "$BRANCH_NAME"
|
||||
fi
|
||||
fi
|
||||
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env bash
|
||||
# Git-specific common functions for the git extension.
|
||||
# Extracted from scripts/bash/common.sh — contains only git-specific
|
||||
# branch validation and detection logic.
|
||||
|
||||
# Check if we have git available at the repo root
|
||||
has_git() {
|
||||
local repo_root="${1:-$(pwd)}"
|
||||
{ [ -d "$repo_root/.git" ] || [ -f "$repo_root/.git" ]; } && \
|
||||
command -v git >/dev/null 2>&1 && \
|
||||
git -C "$repo_root" rev-parse --is-inside-work-tree >/dev/null 2>&1
|
||||
}
|
||||
|
||||
# Strip a single optional path segment (e.g. gitflow "feat/004-name" -> "004-name").
|
||||
# Only when the full name is exactly two slash-free segments; otherwise returns the raw name.
|
||||
spec_kit_effective_branch_name() {
|
||||
local raw="$1"
|
||||
if [[ "$raw" =~ ^([^/]+)/([^/]+)$ ]]; then
|
||||
printf '%s\n' "${BASH_REMATCH[2]}"
|
||||
else
|
||||
printf '%s\n' "$raw"
|
||||
fi
|
||||
}
|
||||
|
||||
# Validate that a branch name matches the expected feature branch pattern.
|
||||
# Accepts sequential (###-* with >=3 digits) or timestamp (YYYYMMDD-HHMMSS-*) formats.
|
||||
# Logic aligned with scripts/bash/common.sh check_feature_branch after effective-name normalization.
|
||||
check_feature_branch() {
|
||||
local raw="$1"
|
||||
local has_git_repo="$2"
|
||||
|
||||
# For non-git repos, we can't enforce branch naming but still provide output
|
||||
if [[ "$has_git_repo" != "true" ]]; then
|
||||
echo "[specify] Warning: Git repository not detected; skipped branch validation" >&2
|
||||
return 0
|
||||
fi
|
||||
|
||||
local branch
|
||||
branch=$(spec_kit_effective_branch_name "$raw")
|
||||
|
||||
# Accept sequential prefix (3+ digits) but exclude malformed timestamps
|
||||
# Malformed: 7-or-8 digit date + 6-digit time with no trailing slug (e.g. "2026031-143022" or "20260319-143022")
|
||||
local is_sequential=false
|
||||
if [[ "$branch" =~ ^[0-9]{3,}- ]] && [[ ! "$branch" =~ ^[0-9]{7}-[0-9]{6}- ]] && [[ ! "$branch" =~ ^[0-9]{7,8}-[0-9]{6}$ ]]; then
|
||||
is_sequential=true
|
||||
fi
|
||||
if [[ "$is_sequential" != "true" ]] && [[ ! "$branch" =~ ^[0-9]{8}-[0-9]{6}- ]]; then
|
||||
echo "ERROR: Not on a feature branch. Current branch: $raw" >&2
|
||||
echo "Feature branches should be named like: 001-feature-name, 1234-feature-name, or 20260319-143022-feature-name" >&2
|
||||
return 1
|
||||
fi
|
||||
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env bash
|
||||
# Git extension: initialize-repo.sh
|
||||
# Initialize a Git repository with an initial commit.
|
||||
# Customizable — replace this script to add .gitignore templates,
|
||||
# default branch config, git-flow, LFS, signing, etc.
|
||||
|
||||
set -e
|
||||
|
||||
SCRIPT_DIR="$(CDPATH="" cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
|
||||
# Find project root
|
||||
_find_project_root() {
|
||||
local dir="$1"
|
||||
while [ "$dir" != "/" ]; do
|
||||
if [ -d "$dir/.specify" ] || [ -d "$dir/.git" ]; then
|
||||
echo "$dir"
|
||||
return 0
|
||||
fi
|
||||
dir="$(dirname "$dir")"
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
REPO_ROOT=$(_find_project_root "$SCRIPT_DIR") || REPO_ROOT="$(pwd)"
|
||||
cd "$REPO_ROOT"
|
||||
|
||||
# Read commit message from extension config, fall back to default
|
||||
COMMIT_MSG="[Spec Kit] Initial commit"
|
||||
_config_file="$REPO_ROOT/.specify/extensions/git/git-config.yml"
|
||||
if [ -f "$_config_file" ]; then
|
||||
_msg=$(grep '^init_commit_message:' "$_config_file" 2>/dev/null | sed 's/^init_commit_message:[[:space:]]*//' | sed 's/^["'\'']//' | sed 's/["'\'']*$//')
|
||||
if [ -n "$_msg" ]; then
|
||||
COMMIT_MSG="$_msg"
|
||||
fi
|
||||
fi
|
||||
|
||||
# Check if git is available
|
||||
if ! command -v git >/dev/null 2>&1; then
|
||||
echo "[specify] Warning: Git not found; skipped repository initialization" >&2
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Check if already a git repo
|
||||
if git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
|
||||
echo "[specify] Git repository already initialized; skipping" >&2
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Initialize
|
||||
_git_out=$(git init -q 2>&1) || { echo "[specify] Error: git init failed: $_git_out" >&2; exit 1; }
|
||||
_git_out=$(git add . 2>&1) || { echo "[specify] Error: git add failed: $_git_out" >&2; exit 1; }
|
||||
_git_out=$(git commit --allow-empty -q -m "$COMMIT_MSG" 2>&1) || { echo "[specify] Error: git commit failed: $_git_out" >&2; exit 1; }
|
||||
|
||||
echo "✓ Git repository initialized" >&2
|
||||
@@ -0,0 +1,169 @@
|
||||
#!/usr/bin/env pwsh
|
||||
# Git extension: auto-commit.ps1
|
||||
# Automatically commit changes after a Spec Kit command completes.
|
||||
# Checks per-command config keys in git-config.yml before committing.
|
||||
#
|
||||
# Usage: auto-commit.ps1 <event_name>
|
||||
# e.g.: auto-commit.ps1 after_specify
|
||||
param(
|
||||
[Parameter(Position = 0, Mandatory = $true)]
|
||||
[string]$EventName
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
function Find-ProjectRoot {
|
||||
param([string]$StartDir)
|
||||
$current = Resolve-Path $StartDir
|
||||
while ($true) {
|
||||
foreach ($marker in @('.specify', '.git')) {
|
||||
if (Test-Path (Join-Path $current $marker)) {
|
||||
return $current
|
||||
}
|
||||
}
|
||||
$parent = Split-Path $current -Parent
|
||||
if ($parent -eq $current) { return $null }
|
||||
$current = $parent
|
||||
}
|
||||
}
|
||||
|
||||
$repoRoot = Find-ProjectRoot -StartDir $PSScriptRoot
|
||||
if (-not $repoRoot) { $repoRoot = Get-Location }
|
||||
Set-Location $repoRoot
|
||||
|
||||
# Check if git is available
|
||||
if (-not (Get-Command git -ErrorAction SilentlyContinue)) {
|
||||
Write-Warning "[specify] Warning: Git not found; skipped auto-commit"
|
||||
exit 0
|
||||
}
|
||||
|
||||
# Temporarily relax ErrorActionPreference so git stderr warnings
|
||||
# (e.g. CRLF notices on Windows) do not become terminating errors.
|
||||
$savedEAP = $ErrorActionPreference
|
||||
$ErrorActionPreference = 'Continue'
|
||||
try {
|
||||
git rev-parse --is-inside-work-tree 2>$null | Out-Null
|
||||
$isRepo = $LASTEXITCODE -eq 0
|
||||
} finally {
|
||||
$ErrorActionPreference = $savedEAP
|
||||
}
|
||||
if (-not $isRepo) {
|
||||
Write-Warning "[specify] Warning: Not a Git repository; skipped auto-commit"
|
||||
exit 0
|
||||
}
|
||||
|
||||
# Read per-command config from git-config.yml
|
||||
$configFile = Join-Path $repoRoot ".specify/extensions/git/git-config.yml"
|
||||
$enabled = $false
|
||||
$commitMsg = ""
|
||||
|
||||
if (Test-Path $configFile) {
|
||||
# Parse YAML to find auto_commit section
|
||||
$inAutoCommit = $false
|
||||
$inEvent = $false
|
||||
$defaultEnabled = $false
|
||||
|
||||
foreach ($line in Get-Content $configFile) {
|
||||
# Detect auto_commit: section
|
||||
if ($line -match '^auto_commit:') {
|
||||
$inAutoCommit = $true
|
||||
$inEvent = $false
|
||||
continue
|
||||
}
|
||||
|
||||
# Exit auto_commit section on next top-level key
|
||||
if ($inAutoCommit -and $line -match '^[a-z]') {
|
||||
break
|
||||
}
|
||||
|
||||
if ($inAutoCommit) {
|
||||
# Check default key
|
||||
if ($line -match '^\s+default:\s*(.+)$') {
|
||||
$val = $matches[1].Trim().ToLower()
|
||||
if ($val -eq 'true') { $defaultEnabled = $true }
|
||||
}
|
||||
|
||||
# Detect our event subsection
|
||||
if ($line -match "^\s+${EventName}:") {
|
||||
$inEvent = $true
|
||||
continue
|
||||
}
|
||||
|
||||
# Inside our event subsection
|
||||
if ($inEvent) {
|
||||
# Exit on next sibling key (2-space indent, not 4+)
|
||||
if ($line -match '^\s{2}[a-z]' -and $line -notmatch '^\s{4}') {
|
||||
$inEvent = $false
|
||||
continue
|
||||
}
|
||||
if ($line -match '\s+enabled:\s*(.+)$') {
|
||||
$val = $matches[1].Trim().ToLower()
|
||||
if ($val -eq 'true') { $enabled = $true }
|
||||
if ($val -eq 'false') { $enabled = $false }
|
||||
}
|
||||
if ($line -match '\s+message:\s*(.+)$') {
|
||||
$commitMsg = $matches[1].Trim() -replace '^["'']' -replace '["'']$'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# If event-specific key not found, use default
|
||||
if (-not $enabled -and $defaultEnabled) {
|
||||
$hasEventKey = Select-String -Path $configFile -Pattern "^\s*${EventName}:" -Quiet
|
||||
if (-not $hasEventKey) {
|
||||
$enabled = $true
|
||||
}
|
||||
}
|
||||
} else {
|
||||
# No config file -- auto-commit disabled by default
|
||||
exit 0
|
||||
}
|
||||
|
||||
if (-not $enabled) {
|
||||
exit 0
|
||||
}
|
||||
|
||||
# Check if there are changes to commit
|
||||
# Relax ErrorActionPreference so CRLF warnings on stderr do not terminate.
|
||||
$savedEAP = $ErrorActionPreference
|
||||
$ErrorActionPreference = 'Continue'
|
||||
try {
|
||||
git diff --quiet HEAD 2>$null; $d1 = $LASTEXITCODE
|
||||
git diff --cached --quiet 2>$null; $d2 = $LASTEXITCODE
|
||||
$untracked = git ls-files --others --exclude-standard 2>$null
|
||||
} finally {
|
||||
$ErrorActionPreference = $savedEAP
|
||||
}
|
||||
|
||||
if ($d1 -eq 0 -and $d2 -eq 0 -and -not $untracked) {
|
||||
Write-Host "[specify] No changes to commit after $EventName" -ForegroundColor DarkGray
|
||||
exit 0
|
||||
}
|
||||
|
||||
# Derive a human-readable command name from the event
|
||||
$commandName = $EventName -replace '^after_', '' -replace '^before_', ''
|
||||
$phase = if ($EventName -match '^before_') { 'before' } else { 'after' }
|
||||
|
||||
# Use custom message if configured, otherwise default
|
||||
if (-not $commitMsg) {
|
||||
$commitMsg = "[Spec Kit] Auto-commit $phase $commandName"
|
||||
}
|
||||
|
||||
# Stage and commit
|
||||
# Relax ErrorActionPreference so CRLF warnings on stderr do not terminate,
|
||||
# while still allowing redirected error output to be captured for diagnostics.
|
||||
$savedEAP = $ErrorActionPreference
|
||||
$ErrorActionPreference = 'Continue'
|
||||
try {
|
||||
$out = git add . 2>&1 | Out-String
|
||||
if ($LASTEXITCODE -ne 0) { throw "git add failed: $out" }
|
||||
$out = git commit -q -m $commitMsg 2>&1 | Out-String
|
||||
if ($LASTEXITCODE -ne 0) { throw "git commit failed: $out" }
|
||||
} catch {
|
||||
Write-Warning "[specify] Error: $_"
|
||||
exit 1
|
||||
} finally {
|
||||
$ErrorActionPreference = $savedEAP
|
||||
}
|
||||
|
||||
Write-Host "[OK] Changes committed $phase $commandName"
|
||||
@@ -0,0 +1,403 @@
|
||||
#!/usr/bin/env pwsh
|
||||
# Git extension: create-new-feature.ps1
|
||||
# Adapted from core scripts/powershell/create-new-feature.ps1 for extension layout.
|
||||
# Sources common.ps1 from the project's installed scripts, falling back to
|
||||
# git-common.ps1 for minimal git helpers.
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[switch]$Json,
|
||||
[switch]$AllowExistingBranch,
|
||||
[switch]$DryRun,
|
||||
[string]$ShortName,
|
||||
[Parameter()]
|
||||
[long]$Number = 0,
|
||||
[switch]$Timestamp,
|
||||
[switch]$Help,
|
||||
[Parameter(Position = 0, ValueFromRemainingArguments = $true)]
|
||||
[string[]]$FeatureDescription
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
if ($Help) {
|
||||
Write-Host "Usage: ./create-new-feature.ps1 [-Json] [-DryRun] [-AllowExistingBranch] [-ShortName <name>] [-Number N] [-Timestamp] <feature description>"
|
||||
Write-Host ""
|
||||
Write-Host "Options:"
|
||||
Write-Host " -Json Output in JSON format"
|
||||
Write-Host " -DryRun Compute branch name without creating the branch"
|
||||
Write-Host " -AllowExistingBranch Switch to branch if it already exists instead of failing"
|
||||
Write-Host " -ShortName <name> Provide a custom short name (2-4 words) for the branch"
|
||||
Write-Host " -Number N Specify branch number manually (overrides auto-detection)"
|
||||
Write-Host " -Timestamp Use timestamp prefix (YYYYMMDD-HHMMSS) instead of sequential numbering"
|
||||
Write-Host " -Help Show this help message"
|
||||
Write-Host ""
|
||||
Write-Host "Environment variables:"
|
||||
Write-Host " GIT_BRANCH_NAME Use this exact branch name, bypassing all prefix/suffix generation"
|
||||
Write-Host ""
|
||||
exit 0
|
||||
}
|
||||
|
||||
if (-not $FeatureDescription -or $FeatureDescription.Count -eq 0) {
|
||||
Write-Error "Usage: ./create-new-feature.ps1 [-Json] [-DryRun] [-AllowExistingBranch] [-ShortName <name>] [-Number N] [-Timestamp] <feature description>"
|
||||
exit 1
|
||||
}
|
||||
|
||||
$featureDesc = ($FeatureDescription -join ' ').Trim()
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($featureDesc)) {
|
||||
Write-Error "Error: Feature description cannot be empty or contain only whitespace"
|
||||
exit 1
|
||||
}
|
||||
|
||||
function Get-HighestNumberFromSpecs {
|
||||
param([string]$SpecsDir)
|
||||
|
||||
[long]$highest = 0
|
||||
if (Test-Path $SpecsDir) {
|
||||
Get-ChildItem -Path $SpecsDir -Directory | ForEach-Object {
|
||||
if ($_.Name -match '^(\d{3,})-' -and $_.Name -notmatch '^\d{8}-\d{6}-') {
|
||||
[long]$num = 0
|
||||
if ([long]::TryParse($matches[1], [ref]$num) -and $num -gt $highest) {
|
||||
$highest = $num
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return $highest
|
||||
}
|
||||
|
||||
function Get-HighestNumberFromNames {
|
||||
param([string[]]$Names)
|
||||
|
||||
[long]$highest = 0
|
||||
foreach ($name in $Names) {
|
||||
if ($name -match '^(\d{3,})-' -and $name -notmatch '^\d{8}-\d{6}-') {
|
||||
[long]$num = 0
|
||||
if ([long]::TryParse($matches[1], [ref]$num) -and $num -gt $highest) {
|
||||
$highest = $num
|
||||
}
|
||||
}
|
||||
}
|
||||
return $highest
|
||||
}
|
||||
|
||||
function Get-HighestNumberFromBranches {
|
||||
param()
|
||||
|
||||
try {
|
||||
$branches = git branch -a 2>$null
|
||||
if ($LASTEXITCODE -eq 0 -and $branches) {
|
||||
$cleanNames = $branches | ForEach-Object {
|
||||
$_.Trim() -replace '^\*?\s+', '' -replace '^remotes/[^/]+/', ''
|
||||
}
|
||||
return Get-HighestNumberFromNames -Names $cleanNames
|
||||
}
|
||||
} catch {
|
||||
Write-Verbose "Could not check Git branches: $_"
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
function Get-HighestNumberFromRemoteRefs {
|
||||
[long]$highest = 0
|
||||
try {
|
||||
$remotes = git remote 2>$null
|
||||
if ($remotes) {
|
||||
foreach ($remote in $remotes) {
|
||||
$env:GIT_TERMINAL_PROMPT = '0'
|
||||
$refs = git ls-remote --heads $remote 2>$null
|
||||
$env:GIT_TERMINAL_PROMPT = $null
|
||||
if ($LASTEXITCODE -eq 0 -and $refs) {
|
||||
$refNames = $refs | ForEach-Object {
|
||||
if ($_ -match 'refs/heads/(.+)$') { $matches[1] }
|
||||
} | Where-Object { $_ }
|
||||
$remoteHighest = Get-HighestNumberFromNames -Names $refNames
|
||||
if ($remoteHighest -gt $highest) { $highest = $remoteHighest }
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
Write-Verbose "Could not query remote refs: $_"
|
||||
}
|
||||
return $highest
|
||||
}
|
||||
|
||||
function Get-NextBranchNumber {
|
||||
param(
|
||||
[string]$SpecsDir,
|
||||
[switch]$SkipFetch
|
||||
)
|
||||
|
||||
if ($SkipFetch) {
|
||||
$highestBranch = Get-HighestNumberFromBranches
|
||||
$highestRemote = Get-HighestNumberFromRemoteRefs
|
||||
$highestBranch = [Math]::Max($highestBranch, $highestRemote)
|
||||
} else {
|
||||
try {
|
||||
git fetch --all --prune 2>$null | Out-Null
|
||||
} catch { }
|
||||
$highestBranch = Get-HighestNumberFromBranches
|
||||
}
|
||||
|
||||
$highestSpec = Get-HighestNumberFromSpecs -SpecsDir $SpecsDir
|
||||
$maxNum = [Math]::Max($highestBranch, $highestSpec)
|
||||
return $maxNum + 1
|
||||
}
|
||||
|
||||
function ConvertTo-CleanBranchName {
|
||||
param([string]$Name)
|
||||
return $Name.ToLower() -replace '[^a-z0-9]', '-' -replace '-{2,}', '-' -replace '^-', '' -replace '-$', ''
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Source common.ps1 from the project's installed scripts.
|
||||
# Search locations in priority order:
|
||||
# 1. .specify/scripts/powershell/common.ps1 under the project root
|
||||
# 2. scripts/powershell/common.ps1 under the project root (source checkout)
|
||||
# 3. git-common.ps1 next to this script (minimal fallback)
|
||||
# ---------------------------------------------------------------------------
|
||||
function Find-ProjectRoot {
|
||||
param([string]$StartDir)
|
||||
$current = Resolve-Path $StartDir
|
||||
while ($true) {
|
||||
foreach ($marker in @('.specify', '.git')) {
|
||||
if (Test-Path (Join-Path $current $marker)) {
|
||||
return $current
|
||||
}
|
||||
}
|
||||
$parent = Split-Path $current -Parent
|
||||
if ($parent -eq $current) { return $null }
|
||||
$current = $parent
|
||||
}
|
||||
}
|
||||
|
||||
$projectRoot = Find-ProjectRoot -StartDir $PSScriptRoot
|
||||
$commonLoaded = $false
|
||||
|
||||
if ($projectRoot) {
|
||||
$candidates = @(
|
||||
(Join-Path $projectRoot ".specify/scripts/powershell/common.ps1"),
|
||||
(Join-Path $projectRoot "scripts/powershell/common.ps1")
|
||||
)
|
||||
foreach ($candidate in $candidates) {
|
||||
if (Test-Path $candidate) {
|
||||
. $candidate
|
||||
$commonLoaded = $true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (-not $commonLoaded -and (Test-Path "$PSScriptRoot/git-common.ps1")) {
|
||||
. "$PSScriptRoot/git-common.ps1"
|
||||
$commonLoaded = $true
|
||||
}
|
||||
|
||||
if (-not $commonLoaded) {
|
||||
throw "Unable to locate common script file. Please ensure the Specify core scripts are installed."
|
||||
}
|
||||
|
||||
# Resolve repository root
|
||||
if (Get-Command Get-RepoRoot -ErrorAction SilentlyContinue) {
|
||||
$repoRoot = Get-RepoRoot
|
||||
} elseif ($projectRoot) {
|
||||
$repoRoot = $projectRoot
|
||||
} else {
|
||||
throw "Could not determine repository root."
|
||||
}
|
||||
|
||||
# Check if git is available
|
||||
if (Get-Command Test-HasGit -ErrorAction SilentlyContinue) {
|
||||
# Call without parameters for compatibility with core common.ps1 (no -RepoRoot param)
|
||||
# and git-common.ps1 (has -RepoRoot param with default).
|
||||
$hasGit = Test-HasGit
|
||||
} else {
|
||||
try {
|
||||
git -C $repoRoot rev-parse --is-inside-work-tree 2>$null | Out-Null
|
||||
$hasGit = ($LASTEXITCODE -eq 0)
|
||||
} catch {
|
||||
$hasGit = $false
|
||||
}
|
||||
}
|
||||
|
||||
Set-Location $repoRoot
|
||||
|
||||
$specsDir = Join-Path $repoRoot 'specs'
|
||||
|
||||
function Get-BranchName {
|
||||
param([string]$Description)
|
||||
|
||||
$stopWords = @(
|
||||
'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'
|
||||
)
|
||||
|
||||
$cleanName = $Description.ToLower() -replace '[^a-z0-9\s]', ' '
|
||||
$words = $cleanName -split '\s+' | Where-Object { $_ }
|
||||
|
||||
$meaningfulWords = @()
|
||||
foreach ($word in $words) {
|
||||
if ($stopWords -contains $word) { continue }
|
||||
if ($word.Length -ge 3) {
|
||||
$meaningfulWords += $word
|
||||
} elseif ($Description -match "\b$($word.ToUpper())\b") {
|
||||
$meaningfulWords += $word
|
||||
}
|
||||
}
|
||||
|
||||
if ($meaningfulWords.Count -gt 0) {
|
||||
$maxWords = if ($meaningfulWords.Count -eq 4) { 4 } else { 3 }
|
||||
$result = ($meaningfulWords | Select-Object -First $maxWords) -join '-'
|
||||
return $result
|
||||
} else {
|
||||
$result = ConvertTo-CleanBranchName -Name $Description
|
||||
$fallbackWords = ($result -split '-') | Where-Object { $_ } | Select-Object -First 3
|
||||
return [string]::Join('-', $fallbackWords)
|
||||
}
|
||||
}
|
||||
|
||||
# Check for GIT_BRANCH_NAME env var override (exact branch name, no prefix/suffix)
|
||||
if ($env:GIT_BRANCH_NAME) {
|
||||
$branchName = $env:GIT_BRANCH_NAME
|
||||
# Check 244-byte limit (UTF-8) for override names
|
||||
$branchNameUtf8ByteCount = [System.Text.Encoding]::UTF8.GetByteCount($branchName)
|
||||
if ($branchNameUtf8ByteCount -gt 244) {
|
||||
throw "GIT_BRANCH_NAME must be 244 bytes or fewer in UTF-8. Provided value is $branchNameUtf8ByteCount bytes; please supply a shorter override branch name."
|
||||
}
|
||||
# Extract FEATURE_NUM from the branch name if it starts with a numeric prefix
|
||||
# Check timestamp pattern first (YYYYMMDD-HHMMSS-) since it also matches the simpler ^\d+ pattern
|
||||
if ($branchName -match '^(\d{8}-\d{6})-') {
|
||||
$featureNum = $matches[1]
|
||||
} elseif ($branchName -match '^(\d+)-') {
|
||||
$featureNum = $matches[1]
|
||||
} else {
|
||||
$featureNum = $branchName
|
||||
}
|
||||
} else {
|
||||
if ($ShortName) {
|
||||
$branchSuffix = ConvertTo-CleanBranchName -Name $ShortName
|
||||
} else {
|
||||
$branchSuffix = Get-BranchName -Description $featureDesc
|
||||
}
|
||||
|
||||
if ($Timestamp -and $Number -ne 0) {
|
||||
Write-Warning "[specify] Warning: -Number is ignored when -Timestamp is used"
|
||||
$Number = 0
|
||||
}
|
||||
|
||||
if ($Timestamp) {
|
||||
$featureNum = Get-Date -Format 'yyyyMMdd-HHmmss'
|
||||
$branchName = "$featureNum-$branchSuffix"
|
||||
} else {
|
||||
if ($Number -eq 0) {
|
||||
if ($DryRun -and $hasGit) {
|
||||
$Number = Get-NextBranchNumber -SpecsDir $specsDir -SkipFetch
|
||||
} elseif ($DryRun) {
|
||||
$Number = (Get-HighestNumberFromSpecs -SpecsDir $specsDir) + 1
|
||||
} elseif ($hasGit) {
|
||||
$Number = Get-NextBranchNumber -SpecsDir $specsDir
|
||||
} else {
|
||||
$Number = (Get-HighestNumberFromSpecs -SpecsDir $specsDir) + 1
|
||||
}
|
||||
}
|
||||
|
||||
$featureNum = ('{0:000}' -f $Number)
|
||||
$branchName = "$featureNum-$branchSuffix"
|
||||
}
|
||||
}
|
||||
|
||||
$maxBranchLength = 244
|
||||
if ($branchName.Length -gt $maxBranchLength) {
|
||||
$prefixLength = $featureNum.Length + 1
|
||||
$maxSuffixLength = $maxBranchLength - $prefixLength
|
||||
|
||||
$truncatedSuffix = $branchSuffix.Substring(0, [Math]::Min($branchSuffix.Length, $maxSuffixLength))
|
||||
$truncatedSuffix = $truncatedSuffix -replace '-$', ''
|
||||
|
||||
$originalBranchName = $branchName
|
||||
$branchName = "$featureNum-$truncatedSuffix"
|
||||
|
||||
Write-Warning "[specify] Branch name exceeded GitHub's 244-byte limit"
|
||||
Write-Warning "[specify] Original: $originalBranchName ($($originalBranchName.Length) bytes)"
|
||||
Write-Warning "[specify] Truncated to: $branchName ($($branchName.Length) bytes)"
|
||||
}
|
||||
|
||||
if (-not $DryRun) {
|
||||
if ($hasGit) {
|
||||
$branchCreated = $false
|
||||
$branchCreateError = ''
|
||||
try {
|
||||
$branchCreateError = git checkout -q -b $branchName 2>&1 | Out-String
|
||||
if ($LASTEXITCODE -eq 0) {
|
||||
$branchCreated = $true
|
||||
}
|
||||
} catch {
|
||||
$branchCreateError = $_.Exception.Message
|
||||
}
|
||||
|
||||
if (-not $branchCreated) {
|
||||
$currentBranch = ''
|
||||
try { $currentBranch = (git rev-parse --abbrev-ref HEAD 2>$null).Trim() } catch {}
|
||||
$existingBranch = git branch --list $branchName 2>$null
|
||||
if ($existingBranch) {
|
||||
if ($AllowExistingBranch) {
|
||||
if ($currentBranch -eq $branchName) {
|
||||
# Already on the target branch
|
||||
} else {
|
||||
$switchBranchError = git checkout -q $branchName 2>&1 | Out-String
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
if ($switchBranchError) {
|
||||
Write-Error "Error: Branch '$branchName' exists but could not be checked out.`n$($switchBranchError.Trim())"
|
||||
} else {
|
||||
Write-Error "Error: Branch '$branchName' exists but could not be checked out. Resolve any uncommitted changes or conflicts and try again."
|
||||
}
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
} elseif ($Timestamp) {
|
||||
Write-Error "Error: Branch '$branchName' already exists. Rerun to get a new timestamp or use a different -ShortName."
|
||||
exit 1
|
||||
} else {
|
||||
Write-Error "Error: Branch '$branchName' already exists. Please use a different feature name or specify a different number with -Number."
|
||||
exit 1
|
||||
}
|
||||
} else {
|
||||
if ($branchCreateError) {
|
||||
Write-Error "Error: Failed to create git branch '$branchName'.`n$($branchCreateError.Trim())"
|
||||
} else {
|
||||
Write-Error "Error: Failed to create git branch '$branchName'. Please check your git configuration and try again."
|
||||
}
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if ($Json) {
|
||||
[Console]::Error.WriteLine("[specify] Warning: Git repository not detected; skipped branch creation for $branchName")
|
||||
} else {
|
||||
Write-Warning "[specify] Warning: Git repository not detected; skipped branch creation for $branchName"
|
||||
}
|
||||
}
|
||||
|
||||
$env:SPECIFY_FEATURE = $branchName
|
||||
}
|
||||
|
||||
if ($Json) {
|
||||
$obj = [PSCustomObject]@{
|
||||
BRANCH_NAME = $branchName
|
||||
FEATURE_NUM = $featureNum
|
||||
HAS_GIT = $hasGit
|
||||
}
|
||||
if ($DryRun) {
|
||||
$obj | Add-Member -NotePropertyName 'DRY_RUN' -NotePropertyValue $true
|
||||
}
|
||||
$obj | ConvertTo-Json -Compress
|
||||
} else {
|
||||
Write-Output "BRANCH_NAME: $branchName"
|
||||
Write-Output "FEATURE_NUM: $featureNum"
|
||||
Write-Output "HAS_GIT: $hasGit"
|
||||
if (-not $DryRun) {
|
||||
Write-Output "SPECIFY_FEATURE environment variable set to: $branchName"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
#!/usr/bin/env pwsh
|
||||
# Git-specific common functions for the git extension.
|
||||
# Extracted from scripts/powershell/common.ps1 -- contains only git-specific
|
||||
# branch validation and detection logic.
|
||||
|
||||
function Test-HasGit {
|
||||
param([string]$RepoRoot = (Get-Location))
|
||||
try {
|
||||
if (-not (Test-Path (Join-Path $RepoRoot '.git'))) { return $false }
|
||||
if (-not (Get-Command git -ErrorAction SilentlyContinue)) { return $false }
|
||||
git -C $RepoRoot rev-parse --is-inside-work-tree 2>$null | Out-Null
|
||||
return ($LASTEXITCODE -eq 0)
|
||||
} catch {
|
||||
return $false
|
||||
}
|
||||
}
|
||||
|
||||
function Get-SpecKitEffectiveBranchName {
|
||||
param([string]$Branch)
|
||||
if ($Branch -match '^([^/]+)/([^/]+)$') {
|
||||
return $Matches[2]
|
||||
}
|
||||
return $Branch
|
||||
}
|
||||
|
||||
function Test-FeatureBranch {
|
||||
param(
|
||||
[string]$Branch,
|
||||
[bool]$HasGit = $true
|
||||
)
|
||||
|
||||
# For non-git repos, we can't enforce branch naming but still provide output
|
||||
if (-not $HasGit) {
|
||||
Write-Warning "[specify] Warning: Git repository not detected; skipped branch validation"
|
||||
return $true
|
||||
}
|
||||
|
||||
$raw = $Branch
|
||||
$Branch = Get-SpecKitEffectiveBranchName $raw
|
||||
|
||||
# Accept sequential prefix (3+ digits) but exclude malformed timestamps
|
||||
# Malformed: 7-or-8 digit date + 6-digit time with no trailing slug (e.g. "2026031-143022" or "20260319-143022")
|
||||
$hasMalformedTimestamp = ($Branch -match '^[0-9]{7}-[0-9]{6}-') -or ($Branch -match '^(?:\d{7}|\d{8})-\d{6}$')
|
||||
$isSequential = ($Branch -match '^[0-9]{3,}-') -and (-not $hasMalformedTimestamp)
|
||||
if (-not $isSequential -and $Branch -notmatch '^\d{8}-\d{6}-') {
|
||||
[Console]::Error.WriteLine("ERROR: Not on a feature branch. Current branch: $raw")
|
||||
[Console]::Error.WriteLine("Feature branches should be named like: 001-feature-name, 1234-feature-name, or 20260319-143022-feature-name")
|
||||
return $false
|
||||
}
|
||||
return $true
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
#!/usr/bin/env pwsh
|
||||
# Git extension: initialize-repo.ps1
|
||||
# Initialize a Git repository with an initial commit.
|
||||
# Customizable -- replace this script to add .gitignore templates,
|
||||
# default branch config, git-flow, LFS, signing, etc.
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
# Find project root
|
||||
function Find-ProjectRoot {
|
||||
param([string]$StartDir)
|
||||
$current = Resolve-Path $StartDir
|
||||
while ($true) {
|
||||
foreach ($marker in @('.specify', '.git')) {
|
||||
if (Test-Path (Join-Path $current $marker)) {
|
||||
return $current
|
||||
}
|
||||
}
|
||||
$parent = Split-Path $current -Parent
|
||||
if ($parent -eq $current) { return $null }
|
||||
$current = $parent
|
||||
}
|
||||
}
|
||||
|
||||
$repoRoot = Find-ProjectRoot -StartDir $PSScriptRoot
|
||||
if (-not $repoRoot) { $repoRoot = Get-Location }
|
||||
Set-Location $repoRoot
|
||||
|
||||
# Read commit message from extension config, fall back to default
|
||||
$commitMsg = "[Spec Kit] Initial commit"
|
||||
$configFile = Join-Path $repoRoot ".specify/extensions/git/git-config.yml"
|
||||
if (Test-Path $configFile) {
|
||||
foreach ($line in Get-Content $configFile) {
|
||||
if ($line -match '^init_commit_message:\s*(.+)$') {
|
||||
$val = $matches[1].Trim() -replace '^["'']' -replace '["'']$'
|
||||
if ($val) { $commitMsg = $val }
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Check if git is available
|
||||
if (-not (Get-Command git -ErrorAction SilentlyContinue)) {
|
||||
Write-Warning "[specify] Warning: Git not found; skipped repository initialization"
|
||||
exit 0
|
||||
}
|
||||
|
||||
# Check if already a git repo
|
||||
try {
|
||||
git rev-parse --is-inside-work-tree 2>$null | Out-Null
|
||||
if ($LASTEXITCODE -eq 0) {
|
||||
Write-Warning "[specify] Git repository already initialized; skipping"
|
||||
exit 0
|
||||
}
|
||||
} catch { }
|
||||
|
||||
# Initialize
|
||||
try {
|
||||
$out = git init -q 2>&1 | Out-String
|
||||
if ($LASTEXITCODE -ne 0) { throw "git init failed: $out" }
|
||||
$out = git add . 2>&1 | Out-String
|
||||
if ($LASTEXITCODE -ne 0) { throw "git add failed: $out" }
|
||||
$out = git commit --allow-empty -q -m $commitMsg 2>&1 | Out-String
|
||||
if ($LASTEXITCODE -ne 0) { throw "git commit failed: $out" }
|
||||
} catch {
|
||||
Write-Warning "[specify] Error: $_"
|
||||
exit 1
|
||||
}
|
||||
|
||||
Write-Host "[OK] Git repository initialized"
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"feature_directory": "specs/016-atribucion-capi"
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"ai": "claude",
|
||||
"ai_skills": true,
|
||||
"branch_numbering": "sequential",
|
||||
"here": false,
|
||||
"integration": "claude",
|
||||
"script": "ps",
|
||||
"speckit_version": "0.9.0"
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"version": "0.9.0",
|
||||
"integration_state_schema": 1,
|
||||
"installed_integrations": [
|
||||
"claude"
|
||||
],
|
||||
"integration_settings": {
|
||||
"claude": {
|
||||
"script": "ps",
|
||||
"invoke_separator": "-"
|
||||
}
|
||||
},
|
||||
"integration": "claude",
|
||||
"default_integration": "claude"
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"integration": "claude",
|
||||
"version": "0.9.0",
|
||||
"installed_at": "2026-06-07T22:31:38.099632+00:00",
|
||||
"files": {
|
||||
".claude/skills/speckit-analyze/SKILL.md": "adb9c4baed1d0e27cebd08e506a7247c1357ee721b6ea340201553d5792e6c8a",
|
||||
".claude/skills/speckit-checklist/SKILL.md": "82a54d9ce969ae87c0034ffce77539bc708290efc26a6160efe928b248c712c4",
|
||||
".claude/skills/speckit-clarify/SKILL.md": "fd720c2b468f10f89cf4b6dfcff876e735e557cde5f9bcb2ec1fc7079c19051c",
|
||||
".claude/skills/speckit-constitution/SKILL.md": "c1a044aba243ca6aff627fb5e4404feb6f1108d4f7dd174631bee3ae477d6c15",
|
||||
".claude/skills/speckit-implement/SKILL.md": "97a339450a2a81cb63d17cac84e8fdca6be07f0e66c37bcdca6ee87cf1f8d9f2",
|
||||
".claude/skills/speckit-plan/SKILL.md": "3b58fdd3a355ea4904cb8630b7605bb3209430d8fe91bb5d320fdb732a0cc11e",
|
||||
".claude/skills/speckit-specify/SKILL.md": "7b5f226fc11fbc141aeb12fc14305c8d8ef6783e73d8e516bca7ae6edbc5615d",
|
||||
".claude/skills/speckit-tasks/SKILL.md": "84c276f7037693ebc69eef74dce0af127280eda1d8e6af18d29ff8440b028d3f",
|
||||
".claude/skills/speckit-taskstoissues/SKILL.md": "e326c30c89a6bb67a9251cbe038178bc4dd1281948267d1921d361d8c327a0d9"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"integration": "speckit",
|
||||
"version": "0.9.0",
|
||||
"installed_at": "2026-06-07T22:31:38.411394+00:00",
|
||||
"files": {
|
||||
".specify/scripts/powershell/check-prerequisites.ps1": "6f398a09b8f0b6d24c2f2991b318470809ef282452123b3a2b9d324db2856718",
|
||||
".specify/scripts/powershell/common.ps1": "8bf0e265ffb5bd64a1a7ace0e65a543fa8de9c60f55e3f8fe84bf810d66ba45e",
|
||||
".specify/scripts/powershell/create-new-feature.ps1": "24b07de9e1084ebe11f3dc65466d279b0aa4dbff7e7b011dcf303d299e994c9d",
|
||||
".specify/scripts/powershell/setup-plan.ps1": "c4421bd2544a3b25fa07858f1c7cb854ef56a26a972853302e9763107da023cd",
|
||||
".specify/scripts/powershell/setup-tasks.ps1": "b7ec75a3aea607150294a900f0826b405064e92f8542823e3a2f2ab097f49d8d",
|
||||
".specify/templates/checklist-template.md": "c37695297e5d3153d64f82c21223509940b13932046c7961c42d1d669516130c",
|
||||
".specify/templates/constitution-template.md": "ce7549540fa45543cca797a150201d868e64495fdff39dc38246fb17bd4024b3",
|
||||
".specify/templates/plan-template.md": "cc7f7979cf8d8836ec26492785affd80791d3422a2b745062ec695be8c985ef7",
|
||||
".specify/templates/spec-template.md": "3945437fc35cd30a5b2bf7beea680337c3516826d3efa5a6b92c4a7eca1ba28e",
|
||||
".specify/templates/tasks-template.md": "fc29a233f6f5a27ca31f1aa46b596af6500c627441c6e62b2bc4a1d721525842"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
<!--
|
||||
SYNC IMPACT REPORT
|
||||
==================
|
||||
Versión: 1.3.0 → 1.4.0
|
||||
|
||||
Cambios:
|
||||
- Principio II "Soberanía / Self-Hosted" → EXPANDIDO: la lista cerrada de
|
||||
dependencias de runtime gana una tercera categoría, **conectores
|
||||
opcionales**, admisible SOLO bajo cinco condiciones (apagados por defecto
|
||||
tras una bandera de despliegue, aislados tras adaptador dedicado con
|
||||
contrato público, instancia completa sin ellos con degradación definida,
|
||||
credenciales cifradas del propio negocio, y verificables en CI apagados y
|
||||
encendidos). La frase de prohibición se acota: de "PROHIBIDO en v1 … y
|
||||
servicios de Google" a "PROHIBIDO como dependencia del núcleo", con la vía
|
||||
única del conector opcional para servicios de terceros.
|
||||
- Principios I, III, IV, V, VI, VII, VIII y IX: íntegros (sin cambio).
|
||||
- "Restricciones de Plataforma y Seguridad": sin cambio — su regla de
|
||||
aislamiento tras adaptadores dedicados ya cubre a los conectores.
|
||||
- Governance: sin cambio.
|
||||
|
||||
Bump: MINOR (1.3.0 → 1.4.0) — expansión material de un principio; no elimina ni
|
||||
redefine nada de forma incompatible: una instancia default sigue cumpliendo
|
||||
exactamente la promesa vigente ("un VPS, un dominio, credenciales de Meta y un
|
||||
token de OpenRouter. Nada más").
|
||||
|
||||
Motivación:
|
||||
El canal de Instagram (014 / ADR-001) entró como integración opcional detrás
|
||||
de CHANNELS sin tocar este principio, porque es la misma Meta Graph API del
|
||||
canal permitido. El motor de agendamiento (feature 015) necesita Zoom y
|
||||
Google — proveedores nuevos — y el principio no daba ninguna vía, ni siquiera
|
||||
apagados por defecto; la única salida habría sido "cada quien su fork", que
|
||||
ADR-001 ya demostró insostenible (la rama 004-motor-agenda quedó irrescatable
|
||||
en 26 días: 76 commits atrás y migración colisionada). La soberanía que el
|
||||
principio protege no se toca: el costo lo paga únicamente la instancia que
|
||||
enciende la bandera y pega SUS credenciales, y la condición 5 lo vuelve
|
||||
verificable en vez de prometido.
|
||||
Propuesta por escrito y ratificación del responsable (2026-08-26):
|
||||
specs/015-motor-agenda-universal/enmienda-constitucional.md.
|
||||
|
||||
Plantillas dependientes:
|
||||
- .specify/templates/spec-template.md — ✅ compatible (sin cambios).
|
||||
- .specify/templates/plan-template.md — ✅ compatible; su Constitution Check
|
||||
se evalúa contra esta versión (un conector externo pasa el gate si y solo
|
||||
si cumple las cinco condiciones).
|
||||
- .specify/templates/tasks-template.md — ✅ compatible.
|
||||
- CLAUDE.md — ✅ actualizado en este mismo cambio (regla de Soberanía).
|
||||
|
||||
TODOs diferidos:
|
||||
- Deuda documental heredada de la 1.3.0 (features entre `003` y la app 1.2.0
|
||||
sin spec): sigue igual; esta enmienda no la toca.
|
||||
-->
|
||||
|
||||
# Vocero CRM Constitution
|
||||
|
||||
Vocero CRM es un CRM de WhatsApp con agente de IA, open source (MIT), self-hosted y
|
||||
gratuito, diseñado para que las agencias de IA lo desplieguen en el VPS de sus
|
||||
clientes: una instancia = un negocio. Esta constitución define las reglas no
|
||||
negociables del producto. Aplica a todas las fases del flujo de trabajo (specify,
|
||||
plan, tasks, implement). Cualquier conflicto entre una decisión de implementación y
|
||||
esta constitución SE RESUELVE A FAVOR de esta constitución.
|
||||
|
||||
## Core Principles
|
||||
|
||||
### I. Seguridad de Datos Primero (NO NEGOCIABLE)
|
||||
|
||||
La protección de datos es la primera responsabilidad del sistema, por encima de
|
||||
velocidad de entrega o conveniencia de desarrollo.
|
||||
|
||||
- Tokens, credenciales y secretos sensibles NUNCA se exponen al cliente (navegador,
|
||||
app, respuestas de API) ni se escriben en logs, trazas o mensajes de error.
|
||||
- Todo secreto se almacena cifrado en reposo. Las claves de cifrado se gestionan
|
||||
fuera del código fuente y fuera del control de versiones.
|
||||
- Si el producto es multi-tenant, todo dato de un tenant está aislado de los demás:
|
||||
ninguna consulta, endpoint o tarea en segundo plano debe devolver o modificar datos
|
||||
de un tenant distinto al del solicitante. El aislamiento se aplica por defecto.
|
||||
|
||||
**Rationale**: Una fuga de credenciales o un cruce de datos entre clientes es un
|
||||
fallo catastrófico e irreversible; prevenirlo siempre cuesta menos que remediarlo.
|
||||
|
||||
### II. Soberanía / Self-Hosted (ENDURECIDO)
|
||||
|
||||
Vocero CRM opera completo sobre la infraestructura del operador. La lista de
|
||||
dependencias externas en runtime es CERRADA:
|
||||
|
||||
- Dependencias externas permitidas en runtime, ÚNICAMENTE:
|
||||
1. **WhatsApp Cloud API** (Meta Graph API) — el canal es la razón de ser del
|
||||
producto.
|
||||
2. **El proveedor LLM**, opcional, accedido EXCLUSIVAMENTE a través del adaptador
|
||||
OpenRouter-compatible (`OPENROUTER_BASE_URL` / `OPENROUTER_MODEL`). Sin token
|
||||
configurado, el producto funciona como CRM sin agente de IA.
|
||||
3. **Conectores opcionales**, únicamente bajo TODAS estas condiciones:
|
||||
1. **Apagados por defecto**: se encienden con una bandera de despliegue
|
||||
explícita (patrón ADR-001); una instancia default no los carga, no los
|
||||
menciona y no pide sus credenciales.
|
||||
2. **Aislados tras un adaptador dedicado** con contrato público estable,
|
||||
como el cliente Graph API y el adaptador LLM; el dominio no conoce al
|
||||
proveedor.
|
||||
3. **La instancia funciona completa sin ellos**: existe un camino sin
|
||||
dependencia externa para la misma capacidad (p. ej. el conector
|
||||
`enlace-fijo` de la agenda), y el fallo del proveedor degrada de forma
|
||||
definida — NUNCA bloquea ni pierde la operación core (la cita se crea
|
||||
con link pendiente; el mensaje se responde; el dato se guarda).
|
||||
4. **Credenciales del propio negocio, cifradas en reposo** (Principio I):
|
||||
cada instancia habla con SU cuenta del proveedor; jamás credenciales de
|
||||
una plataforma central.
|
||||
5. **Verificables apagados y encendidos**: la CI ejercita ambas
|
||||
configuraciones y cada conector externo tiene mock con camino infeliz.
|
||||
- **PROHIBIDO como dependencia del núcleo** (todo lo que el producto necesite
|
||||
para operar sin banderas): almacenamiento de objetos externo (S3/R2),
|
||||
servicios de email, billing (Stripe u otro) y cualquier servicio de terceros.
|
||||
Un servicio de terceros solo puede entrar como conector opcional bajo las
|
||||
cinco condiciones anteriores.
|
||||
- El instalador solo necesita: un VPS con Coolify o Docker, un dominio, credenciales
|
||||
de Meta y (opcional) un token de OpenRouter. Nada más.
|
||||
- Las funciones core —autenticación y base de datos— corren self-hosted (Better
|
||||
Auth + PostgreSQL propios de la instancia).
|
||||
- Las integraciones externas permitidas se aíslan tras adaptadores dedicados
|
||||
(cliente Graph API propio; adaptador LLM) para no acoplar el dominio a ellas.
|
||||
|
||||
**Rationale**: El producto se regala para que agencias lo desplieguen en VPS de
|
||||
clientes; cada dependencia externa adicional es un costo, un punto de fallo y una
|
||||
fuga de soberanía que rompe la promesa "gratis y tuyo".
|
||||
|
||||
### III. Multi-Tenancy Real
|
||||
|
||||
El sistema sirve a organizaciones independientes desde una sola instancia lógica.
|
||||
En Vocero cada instancia sirve a UN negocio, pero el modelo de datos es
|
||||
multi-tenant real (organización del plugin de auth) para mantener el aislamiento
|
||||
exigible y no cerrar la puerta a evoluciones.
|
||||
|
||||
- Cada organización (tenant) gestiona sus propios usuarios, roles y permisos.
|
||||
- El identificador de tenant (`organization_id`) es un parámetro de primer nivel en
|
||||
el modelo de datos y en la capa de acceso a datos, no un campo opcional añadido a
|
||||
posteriori. Toda tabla de dominio lo lleva NOT NULL e indexado org-first.
|
||||
|
||||
**Rationale**: Multi-tenancy diseñado desde el inicio evita reescrituras costosas y
|
||||
hace cumplible el aislamiento del Principio I.
|
||||
|
||||
### IV. Idempotencia en Integraciones Externas
|
||||
|
||||
Todo evento entrante de un sistema externo (webhooks, callbacks, notificaciones de
|
||||
terceros) se procesa de forma idempotente.
|
||||
|
||||
- Recibir el mismo evento dos o más veces NO duplica efectos observables (mensajes
|
||||
reenviados, registros duplicados, acciones del agente repetidas).
|
||||
- Cada evento entrante se identifica de forma única (p. ej. `wa_message_id` UNIQUE)
|
||||
y su procesamiento se registra para detectar y descartar reintentos.
|
||||
|
||||
**Rationale**: Los proveedores externos reintentan entregas por diseño; sin
|
||||
idempotencia, los reintentos corrompen datos y generan acciones duplicadas.
|
||||
|
||||
### V. Calidad Verificable Antes de "Hecho" (NO NEGOCIABLE)
|
||||
|
||||
Ninguna tarea se considera terminada sin pasar verificación.
|
||||
|
||||
- "Hecho" requiere, como mínimo: comprobación de tipos, lint y build; y tests donde
|
||||
apliquen al alcance de la tarea.
|
||||
- Lo que NO se pueda verificar automáticamente se marca explícitamente como
|
||||
"pendiente de verificación humana"; no se reporta como completado sin esa marca.
|
||||
- No se reporta una tarea como terminada describiendo que "debería funcionar": o pasa
|
||||
la verificación, o se declara su estado real (incluyendo fallos).
|
||||
|
||||
**Rationale**: La verificación automática es la única definición de "hecho" que no
|
||||
depende de optimismo.
|
||||
|
||||
### VI. Specs Antes de Código
|
||||
|
||||
Ninguna feature se implementa sin una especificación previa. La especificación
|
||||
describe el comportamiento observable por el usuario, no la implementación.
|
||||
|
||||
El **carril** se elige y se declara ANTES de escribir código, y en los tres casos
|
||||
la decisión queda por escrito:
|
||||
|
||||
- **Ciclo completo** (`specify → plan → tasks → implement`) — obligatorio cuando la
|
||||
feature toca el **modelo de datos** (cualquier migración) o un **contrato
|
||||
publicado** (`/api/bot/*`, el webhook, SSE, o un DTO que consuma algo fuera de
|
||||
este repo). Ahí el coste de equivocarse no lo paga quien programa: lo paga quien
|
||||
ya tiene datos guardados o un cliente conectado.
|
||||
|
||||
- **Carril ligero** (`spec.md` únicamente) — para features con comportamiento
|
||||
observable nuevo que NO tocan el modelo de datos ni un contrato. El `spec.md`
|
||||
MUST contener, y le basta con: qué problema resuelve, el comportamiento
|
||||
observable con criterios de aceptación verificables, y qué se decidió NO hacer y
|
||||
por qué.
|
||||
|
||||
- **Exento** — correcciones triviales y cambios sin comportamiento observable nuevo
|
||||
(typos, formato, refactors internos sin cambio de contrato, dependencias,
|
||||
herramientas de desarrollo).
|
||||
|
||||
Reglas que sostienen lo anterior:
|
||||
|
||||
- Si una feature del carril ligero descubre a mitad de camino que necesita una
|
||||
migración o cambiar un contrato, **sube de carril**: se escribe el plan antes de
|
||||
continuar, no después de terminar.
|
||||
- Un spec escrito DESPUÉS de la implementación se marca visiblemente como tal en su
|
||||
encabezado. Es documentación, no diseño, y confundirlos hace creer a quien lo lea
|
||||
dentro de un año que esas decisiones se tomaron antes de programar.
|
||||
|
||||
**Rationale**: Especificar el comportamiento observable antes de codificar previene
|
||||
retrabajo y mantiene alineadas todas las fases del flujo. Los tres carriles existen
|
||||
porque un único ciclo, calibrado para una feature que define el producto entero, es
|
||||
más ceremonia que trabajo en un cambio de doscientas líneas — y una regla que cuesta
|
||||
más de lo que rinde no se discute: se erosiona en silencio, hasta que "specs antes de
|
||||
código" significa "sin specs". Nombrar el escalón intermedio es lo que evita que el
|
||||
siguiente paso hacia abajo sea ninguno.
|
||||
|
||||
### VII. Trazabilidad de Decisiones
|
||||
|
||||
Las decisiones tomadas sin contexto suficiente se documentan para revisión humana.
|
||||
|
||||
- Cuando una decisión se toma con información incompleta o supuestos no confirmados,
|
||||
se registra de forma visible (en el spec, el plan, el PR o un marcador
|
||||
`NEEDS CLARIFICATION` / TODO con responsable), no se entierra en el código.
|
||||
- Los supuestos que condicionan el comportamiento se hacen explícitos para que un
|
||||
humano pueda revisarlos y revertirlos.
|
||||
|
||||
**Rationale**: Las decisiones implícitas bajo incertidumbre son la principal fuente
|
||||
de deuda oculta; hacerlas visibles permite corregirlas a tiempo.
|
||||
|
||||
### VIII. Foco Vertical — CRM de Conversaciones y Leads de WhatsApp
|
||||
|
||||
Es un CRM de conversaciones y leads de WhatsApp que las agencias despliegan para
|
||||
negocios. No es plataforma de marketing masivo, ni constructor visual de flujos, ni
|
||||
herramienta de scraping. Lo que no ayude a *atender, organizar y convertir
|
||||
conversaciones de WhatsApp de UN negocio* se rechaza.
|
||||
|
||||
- El modelo de datos y los flujos MUST reflejar ese dominio: contactos que escriben
|
||||
por WhatsApp, conversaciones con ventana de 24h, leads en un pipeline, un agente
|
||||
de IA que atiende con el conocimiento del negocio y escala a humanos.
|
||||
- WhatsApp Cloud API es el canal; el producto es el CRM. Features de canal que no
|
||||
sirvan a atender/organizar/convertir (broadcast masivo, scraping de números,
|
||||
flujos visuales genéricos) quedan FUERA del alcance de v1.
|
||||
- Toda feature MUST servir a la agencia que despliega o al negocio que opera UNA
|
||||
instancia. Lo que solo sirva a una plataforma centralizada (billing, planes,
|
||||
multi-instancia) queda FUERA.
|
||||
|
||||
**Rationale**: Un foco vertical explícito mantiene el modelo de datos alineado con el
|
||||
negocio real y da un criterio claro para aceptar o rechazar alcance.
|
||||
|
||||
### IX. Verificación de Comportamiento en Vivo (NO NEGOCIABLE)
|
||||
|
||||
Complementa el Principio V. TODA feature con comportamiento observable —UI web,
|
||||
mensajería, API o integración externa— se verifica ejerciendo ese comportamiento como
|
||||
lo haría un usuario real antes de declararse "Hecha". El gate técnico (Principio V) es
|
||||
el piso, no el techo.
|
||||
|
||||
- **Self-test + loop por el implementador (self-improvement loop).** Tras implementar,
|
||||
quien implementa ejecuta el self-test E2E —camino feliz Y camino infeliz (degradación
|
||||
sin colgarse)— y, si algo falla, diagnostica, corrige y re-verifica él mismo hasta
|
||||
verde. No se entrega trabajo a medio verificar ni se delega la prueba funcional al
|
||||
dueño. Lo único delegable a verificación humana es lo intrínsecamente no verificable
|
||||
por herramientas (juicio visual, aprobación de un tercero), marcado explícitamente.
|
||||
- **Se conduce la interfaz real.** Navegador vía Playwright para features de UI; la línea
|
||||
del canal (p. ej. una API de WhatsApp de prueba) para mensajería; llamadas a la API
|
||||
donde esa sea la superficie. No basta con tipos/lint/build, ni con que un endpoint
|
||||
devuelva 2xx, ni con inspeccionar la base de datos: se observa el resultado de cara al
|
||||
usuario.
|
||||
- **Local primero, nube después.** Si el comportamiento puede reproducirse en `localhost`
|
||||
—incluyendo integraciones externas vía túnel (p. ej. ngrok + handshake del webhook desde
|
||||
el panel del proveedor)—, SHOULD probarse ahí antes de desplegar. El deploy a la nube se
|
||||
reserva para lo que el entorno local no pueda reproducir, porque desplegar consume tiempo
|
||||
y reduce la agilidad del ciclo.
|
||||
- **Guardarraíles con herramientas no oficiales.** Cuando la prueba use herramientas no
|
||||
oficiales vinculadas a un número/cuenta real, MUST respetarse reglas duras: enviar solo a
|
||||
destinatarios de una allowlist, NUNCA mensajes en ráfaga (anti-flood obligatorio), y
|
||||
minimizar el volumen. La integridad de la cuenta del operador es un activo a proteger, en
|
||||
línea con el Principio I.
|
||||
|
||||
**Rationale**: El gate técnico no detecta que un agente "se calló", que una tarjeta no
|
||||
llegó como un solo mensaje, o que un botón de UI no disparó nada — eso solo aparece
|
||||
ejerciendo el flujo real. Y el valor del paso no está solo en detectar el fallo sino en
|
||||
cerrarlo: el implementador itera hasta verde en vez de devolver trabajo a medias. Probar
|
||||
en local primero mantiene el ciclo ágil; y sin guardarraíles duros, una prueba con
|
||||
herramientas no oficiales podría provocar un baneo irreversible.
|
||||
|
||||
## Restricciones de Plataforma y Seguridad
|
||||
|
||||
Estas restricciones derivan de los Principios I y II y son verificables en revisión:
|
||||
|
||||
- **Gestión de secretos**: los secretos se inyectan vía configuración de entorno o un
|
||||
gestor de secretos; nunca se comprometen a control de versiones.
|
||||
- **Cifrado en reposo**: credenciales y datos sensibles se almacenan cifrados; el
|
||||
almacenamiento en claro de secretos es una violación.
|
||||
- **Frontera de tenant**: la capa de acceso a datos exige el identificador
|
||||
de tenant; cualquier acceso que pueda omitirlo requiere justificación explícita.
|
||||
- **Aislamiento de integraciones**: las dependencias de APIs externas se acceden a
|
||||
través de adaptadores dedicados (cliente Graph API propio, adaptador LLM
|
||||
OpenRouter-compatible), no dispersas por el dominio.
|
||||
- **Instancia pública endurecida**: las rutas de mock/desarrollo devuelven 404
|
||||
incondicional en producción; el registro se cierra tras la primera organización
|
||||
(salvo habilitación explícita); los entornos de prueba internos JAMÁS alcanzan la
|
||||
API real de WhatsApp.
|
||||
|
||||
## Flujo de Desarrollo y Puertas de Calidad
|
||||
|
||||
- **Orden del flujo**: depende del carril declarado (Principio VI). En el ciclo
|
||||
completo, `specify → plan → tasks → implement`, y cada fase consume el artefacto
|
||||
de la anterior. En el carril ligero, `specify → implement`.
|
||||
- **Puerta constitucional (Constitution Check)**: se evalúa SIEMPRE, en los dos
|
||||
carriles — cambia dónde vive, no si ocurre. En el ciclo completo, en el plan:
|
||||
antes de la Fase 0 y de nuevo tras el diseño de la Fase 1. En el carril ligero,
|
||||
en el propio `spec.md`, antes de escribir código. Las violaciones se registran y
|
||||
justifican (Complexity Tracking en el ciclo completo, o una nota explícita en el
|
||||
spec) o se eliminan.
|
||||
|
||||
El carril ligero ahorra ceremonia de planificación, NUNCA la revisión
|
||||
constitucional: los principios que más caro cuesta romper —aislamiento entre
|
||||
inquilinos, soberanía, idempotencia— se violan igual de fácil en doscientas
|
||||
líneas que en dos mil.
|
||||
- **Puerta de calidad (Definición de "Hecho")**: tipos + lint + build en verde, y
|
||||
tests donde apliquen; lo no verificable automáticamente se marca como pendiente de
|
||||
verificación humana (Principio V). Para features con comportamiento observable de cara
|
||||
al usuario, "Hecho" exige además el self-test de comportamiento en vivo ejecutado por el
|
||||
implementador, con sus guardarraíles (Principio IX).
|
||||
- **Trazabilidad**: decisiones bajo incertidumbre y supuestos se documentan de forma
|
||||
visible (Principio VII), no en comentarios enterrados.
|
||||
|
||||
## Governance
|
||||
|
||||
Esta constitución es la autoridad máxima del proyecto. Prevalece sobre cualquier otra
|
||||
práctica, convención o preferencia; ante un conflicto, gana la constitución.
|
||||
|
||||
- **Procedimiento de enmienda**: toda enmienda se propone por escrito describiendo el
|
||||
cambio y su motivación, se aprueba por el responsable del proyecto y se registra en
|
||||
el control de versiones junto con el Sync Impact Report actualizado.
|
||||
- **Política de versionado** (semantic versioning de la constitución):
|
||||
- **MAJOR**: eliminación o redefinición incompatible de un principio o de la
|
||||
gobernanza.
|
||||
- **MINOR**: adición de un principio/sección nueva o expansión material.
|
||||
- **PATCH**: aclaraciones, correcciones de redacción y refinamientos no semánticos.
|
||||
- **Revisión de cumplimiento**: cada PR y cada revisión de diseño verifican el
|
||||
cumplimiento de estos principios. La complejidad que viole un principio debe
|
||||
justificarse; si no, debe eliminarse.
|
||||
- **Propagación**: al enmendar la constitución se revisan y, si procede, se actualizan
|
||||
las plantillas dependientes (plan, spec, tasks).
|
||||
|
||||
**Version**: 1.4.0 | **Ratified**: 2026-07-09 | **Last Amended**: 2026-08-26
|
||||
@@ -0,0 +1,149 @@
|
||||
#!/usr/bin/env pwsh
|
||||
|
||||
# Consolidated prerequisite checking script (PowerShell)
|
||||
#
|
||||
# This script provides unified prerequisite checking for Spec-Driven Development workflow.
|
||||
# It replaces the functionality previously spread across multiple scripts.
|
||||
#
|
||||
# Usage: ./check-prerequisites.ps1 [OPTIONS]
|
||||
#
|
||||
# OPTIONS:
|
||||
# -Json Output in JSON format
|
||||
# -RequireTasks Require tasks.md to exist (for implementation phase)
|
||||
# -IncludeTasks Include tasks.md in AVAILABLE_DOCS list
|
||||
# -PathsOnly Only output path variables (no validation)
|
||||
# -Help, -h Show help message
|
||||
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[switch]$Json,
|
||||
[switch]$RequireTasks,
|
||||
[switch]$IncludeTasks,
|
||||
[switch]$PathsOnly,
|
||||
[switch]$Help
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
# Show help if requested
|
||||
if ($Help) {
|
||||
Write-Output @"
|
||||
Usage: check-prerequisites.ps1 [OPTIONS]
|
||||
|
||||
Consolidated prerequisite checking for Spec-Driven Development workflow.
|
||||
|
||||
OPTIONS:
|
||||
-Json Output in JSON format
|
||||
-RequireTasks Require tasks.md to exist (for implementation phase)
|
||||
-IncludeTasks Include tasks.md in AVAILABLE_DOCS list
|
||||
-PathsOnly Only output path variables (no prerequisite validation)
|
||||
-Help, -h Show this help message
|
||||
|
||||
EXAMPLES:
|
||||
# Check task prerequisites (plan.md required)
|
||||
.\check-prerequisites.ps1 -Json
|
||||
|
||||
# Check implementation prerequisites (plan.md + tasks.md required)
|
||||
.\check-prerequisites.ps1 -Json -RequireTasks -IncludeTasks
|
||||
|
||||
# Get feature paths only (no validation)
|
||||
.\check-prerequisites.ps1 -PathsOnly
|
||||
|
||||
"@
|
||||
exit 0
|
||||
}
|
||||
|
||||
# Source common functions
|
||||
. "$PSScriptRoot/common.ps1"
|
||||
|
||||
# Get feature paths
|
||||
$paths = Get-FeaturePathsEnv
|
||||
|
||||
# If paths-only mode, output paths and exit (no validation)
|
||||
if ($PathsOnly) {
|
||||
if ($Json) {
|
||||
[PSCustomObject]@{
|
||||
REPO_ROOT = $paths.REPO_ROOT
|
||||
BRANCH = $paths.CURRENT_BRANCH
|
||||
FEATURE_DIR = $paths.FEATURE_DIR
|
||||
FEATURE_SPEC = $paths.FEATURE_SPEC
|
||||
IMPL_PLAN = $paths.IMPL_PLAN
|
||||
TASKS = $paths.TASKS
|
||||
} | ConvertTo-Json -Compress
|
||||
} else {
|
||||
Write-Output "REPO_ROOT: $($paths.REPO_ROOT)"
|
||||
Write-Output "BRANCH: $($paths.CURRENT_BRANCH)"
|
||||
Write-Output "FEATURE_DIR: $($paths.FEATURE_DIR)"
|
||||
Write-Output "FEATURE_SPEC: $($paths.FEATURE_SPEC)"
|
||||
Write-Output "IMPL_PLAN: $($paths.IMPL_PLAN)"
|
||||
Write-Output "TASKS: $($paths.TASKS)"
|
||||
}
|
||||
exit 0
|
||||
}
|
||||
|
||||
# Validate branch name
|
||||
if (-not (Test-FeatureBranch -Branch $paths.CURRENT_BRANCH -HasGit:$paths.HAS_GIT)) {
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Validate required directories and files
|
||||
if (-not (Test-Path $paths.FEATURE_DIR -PathType Container)) {
|
||||
Write-Output "ERROR: Feature directory not found: $($paths.FEATURE_DIR)"
|
||||
Write-Output "Run /speckit-specify first to create the feature structure."
|
||||
exit 1
|
||||
}
|
||||
|
||||
if (-not (Test-Path $paths.IMPL_PLAN -PathType Leaf)) {
|
||||
Write-Output "ERROR: plan.md not found in $($paths.FEATURE_DIR)"
|
||||
Write-Output "Run /speckit-plan first to create the implementation plan."
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Check for tasks.md if required
|
||||
if ($RequireTasks -and -not (Test-Path $paths.TASKS -PathType Leaf)) {
|
||||
Write-Output "ERROR: tasks.md not found in $($paths.FEATURE_DIR)"
|
||||
Write-Output "Run /speckit-tasks first to create the task list."
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Build list of available documents
|
||||
$docs = @()
|
||||
|
||||
# Always check these optional docs
|
||||
if (Test-Path $paths.RESEARCH) { $docs += 'research.md' }
|
||||
if (Test-Path $paths.DATA_MODEL) { $docs += 'data-model.md' }
|
||||
|
||||
# Check contracts directory (only if it exists and has files)
|
||||
if ((Test-Path $paths.CONTRACTS_DIR) -and (Get-ChildItem -Path $paths.CONTRACTS_DIR -ErrorAction SilentlyContinue | Select-Object -First 1)) {
|
||||
$docs += 'contracts/'
|
||||
}
|
||||
|
||||
if (Test-Path $paths.QUICKSTART) { $docs += 'quickstart.md' }
|
||||
|
||||
# Include tasks.md if requested and it exists
|
||||
if ($IncludeTasks -and (Test-Path $paths.TASKS)) {
|
||||
$docs += 'tasks.md'
|
||||
}
|
||||
|
||||
# Output results
|
||||
if ($Json) {
|
||||
# JSON output
|
||||
[PSCustomObject]@{
|
||||
FEATURE_DIR = $paths.FEATURE_DIR
|
||||
AVAILABLE_DOCS = $docs
|
||||
} | ConvertTo-Json -Compress
|
||||
} else {
|
||||
# Text output
|
||||
Write-Output "FEATURE_DIR:$($paths.FEATURE_DIR)"
|
||||
Write-Output "AVAILABLE_DOCS:"
|
||||
|
||||
# Show status of each potential document
|
||||
Test-FileExists -Path $paths.RESEARCH -Description 'research.md' | Out-Null
|
||||
Test-FileExists -Path $paths.DATA_MODEL -Description 'data-model.md' | Out-Null
|
||||
Test-DirHasFiles -Path $paths.CONTRACTS_DIR -Description 'contracts/' | Out-Null
|
||||
Test-FileExists -Path $paths.QUICKSTART -Description 'quickstart.md' | Out-Null
|
||||
|
||||
if ($IncludeTasks) {
|
||||
Test-FileExists -Path $paths.TASKS -Description 'tasks.md' | Out-Null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,643 @@
|
||||
#!/usr/bin/env pwsh
|
||||
# Common PowerShell functions analogous to common.sh
|
||||
|
||||
# Find repository root by searching upward for .specify directory
|
||||
# This is the primary marker for spec-kit projects
|
||||
function Find-SpecifyRoot {
|
||||
param([string]$StartDir = (Get-Location).Path)
|
||||
|
||||
# Normalize to absolute path to prevent issues with relative paths
|
||||
# Use -LiteralPath to handle paths with wildcard characters ([, ], *, ?)
|
||||
$resolved = Resolve-Path -LiteralPath $StartDir -ErrorAction SilentlyContinue
|
||||
$current = if ($resolved) { $resolved.Path } else { $null }
|
||||
if (-not $current) { return $null }
|
||||
|
||||
while ($true) {
|
||||
if (Test-Path -LiteralPath (Join-Path $current ".specify") -PathType Container) {
|
||||
return $current
|
||||
}
|
||||
$parent = Split-Path $current -Parent
|
||||
if ([string]::IsNullOrEmpty($parent) -or $parent -eq $current) {
|
||||
return $null
|
||||
}
|
||||
$current = $parent
|
||||
}
|
||||
}
|
||||
|
||||
# Get repository root, prioritizing .specify directory over git
|
||||
# This prevents using a parent git repo when spec-kit is initialized in a subdirectory
|
||||
function Get-RepoRoot {
|
||||
# First, look for .specify directory (spec-kit's own marker)
|
||||
$specifyRoot = Find-SpecifyRoot
|
||||
if ($specifyRoot) {
|
||||
return $specifyRoot
|
||||
}
|
||||
|
||||
# Fallback to git if no .specify found
|
||||
try {
|
||||
$result = git rev-parse --show-toplevel 2>$null
|
||||
if ($LASTEXITCODE -eq 0) {
|
||||
return $result
|
||||
}
|
||||
} catch {
|
||||
# Git command failed
|
||||
}
|
||||
|
||||
# Final fallback to script location for non-git repos
|
||||
# Use -LiteralPath to handle paths with wildcard characters
|
||||
return (Resolve-Path -LiteralPath (Join-Path $PSScriptRoot "../../..")).Path
|
||||
}
|
||||
|
||||
function Get-CurrentBranch {
|
||||
# First check if SPECIFY_FEATURE environment variable is set
|
||||
if ($env:SPECIFY_FEATURE) {
|
||||
return $env:SPECIFY_FEATURE
|
||||
}
|
||||
|
||||
# Then check git if available at the spec-kit root (not parent)
|
||||
$repoRoot = Get-RepoRoot
|
||||
if (Test-HasGit) {
|
||||
try {
|
||||
$result = git -C $repoRoot rev-parse --abbrev-ref HEAD 2>$null
|
||||
if ($LASTEXITCODE -eq 0) {
|
||||
return $result
|
||||
}
|
||||
} catch {
|
||||
# Git command failed
|
||||
}
|
||||
}
|
||||
|
||||
# For non-git repos, try to find the latest feature directory
|
||||
$specsDir = Join-Path $repoRoot "specs"
|
||||
|
||||
if (Test-Path $specsDir) {
|
||||
$latestFeature = ""
|
||||
$highest = 0
|
||||
$latestTimestamp = ""
|
||||
|
||||
Get-ChildItem -Path $specsDir -Directory | ForEach-Object {
|
||||
if ($_.Name -match '^(\d{8}-\d{6})-') {
|
||||
# Timestamp-based branch: compare lexicographically
|
||||
$ts = $matches[1]
|
||||
if ($ts -gt $latestTimestamp) {
|
||||
$latestTimestamp = $ts
|
||||
$latestFeature = $_.Name
|
||||
}
|
||||
} elseif ($_.Name -match '^(\d{3,})-') {
|
||||
$num = [long]$matches[1]
|
||||
if ($num -gt $highest) {
|
||||
$highest = $num
|
||||
# Only update if no timestamp branch found yet
|
||||
if (-not $latestTimestamp) {
|
||||
$latestFeature = $_.Name
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($latestFeature) {
|
||||
return $latestFeature
|
||||
}
|
||||
}
|
||||
|
||||
# Final fallback
|
||||
return "main"
|
||||
}
|
||||
|
||||
# Check if we have git available at the spec-kit root level
|
||||
# Returns true only if git is installed and the repo root is inside a git work tree
|
||||
# Handles both regular repos (.git directory) and worktrees/submodules (.git file)
|
||||
function Test-HasGit {
|
||||
# First check if git command is available (before calling Get-RepoRoot which may use git)
|
||||
if (-not (Get-Command git -ErrorAction SilentlyContinue)) {
|
||||
return $false
|
||||
}
|
||||
$repoRoot = Get-RepoRoot
|
||||
# Check if .git exists (directory or file for worktrees/submodules)
|
||||
# Use -LiteralPath to handle paths with wildcard characters
|
||||
if (-not (Test-Path -LiteralPath (Join-Path $repoRoot ".git"))) {
|
||||
return $false
|
||||
}
|
||||
# Verify it's actually a valid git work tree
|
||||
try {
|
||||
$null = git -C $repoRoot rev-parse --is-inside-work-tree 2>$null
|
||||
return ($LASTEXITCODE -eq 0)
|
||||
} catch {
|
||||
return $false
|
||||
}
|
||||
}
|
||||
|
||||
# Strip a single optional path segment (e.g. gitflow "feat/004-name" -> "004-name").
|
||||
# Only when the full name is exactly two slash-free segments; otherwise returns the raw name.
|
||||
function Get-SpecKitEffectiveBranchName {
|
||||
param([string]$Branch)
|
||||
if ($Branch -match '^([^/]+)/([^/]+)$') {
|
||||
return $Matches[2]
|
||||
}
|
||||
return $Branch
|
||||
}
|
||||
|
||||
function Test-FeatureBranch {
|
||||
param(
|
||||
[string]$Branch,
|
||||
[bool]$HasGit = $true
|
||||
)
|
||||
|
||||
# For non-git repos, we can't enforce branch naming but still provide output
|
||||
if (-not $HasGit) {
|
||||
Write-Warning "[specify] Warning: Git repository not detected; skipped branch validation"
|
||||
return $true
|
||||
}
|
||||
|
||||
$raw = $Branch
|
||||
$Branch = Get-SpecKitEffectiveBranchName $raw
|
||||
|
||||
# Accept sequential prefix (3+ digits) but exclude malformed timestamps
|
||||
# Malformed: 7-or-8 digit date + 6-digit time with no trailing slug (e.g. "2026031-143022" or "20260319-143022")
|
||||
$hasMalformedTimestamp = ($Branch -match '^[0-9]{7}-[0-9]{6}-') -or ($Branch -match '^(?:\d{7}|\d{8})-\d{6}$')
|
||||
$isSequential = ($Branch -match '^[0-9]{3,}-') -and (-not $hasMalformedTimestamp)
|
||||
if (-not $isSequential -and $Branch -notmatch '^\d{8}-\d{6}-') {
|
||||
[Console]::Error.WriteLine("ERROR: Not on a feature branch. Current branch: $raw")
|
||||
[Console]::Error.WriteLine("Feature branches should be named like: 001-feature-name, 1234-feature-name, or 20260319-143022-feature-name")
|
||||
return $false
|
||||
}
|
||||
return $true
|
||||
}
|
||||
|
||||
# True when .specify/feature.json pins an existing feature directory that matches the
|
||||
# active FEATURE_DIR from Get-FeaturePathsEnv (so /speckit-plan can skip git branch pattern checks).
|
||||
function Test-FeatureJsonMatchesFeatureDir {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)][string]$RepoRoot,
|
||||
[Parameter(Mandatory = $true)][string]$ActiveFeatureDir
|
||||
)
|
||||
|
||||
$featureJson = Join-Path (Join-Path $RepoRoot '.specify') 'feature.json'
|
||||
if (-not (Test-Path -LiteralPath $featureJson -PathType Leaf)) {
|
||||
return $false
|
||||
}
|
||||
|
||||
try {
|
||||
$raw = Get-Content -LiteralPath $featureJson -Raw
|
||||
$cfg = $raw | ConvertFrom-Json
|
||||
} catch {
|
||||
return $false
|
||||
}
|
||||
|
||||
$fd = $cfg.feature_directory
|
||||
if ([string]::IsNullOrWhiteSpace([string]$fd)) {
|
||||
return $false
|
||||
}
|
||||
|
||||
if (-not [System.IO.Path]::IsPathRooted($fd)) {
|
||||
$fd = Join-Path $RepoRoot $fd
|
||||
}
|
||||
|
||||
if (-not (Test-Path -LiteralPath $fd -PathType Container)) {
|
||||
return $false
|
||||
}
|
||||
|
||||
# Resolve both paths to canonical absolute form. Prefer Resolve-Path (follows
|
||||
# symlinks and is the canonical PS way); fall back to [Path]::GetFullPath when
|
||||
# Resolve-Path can't produce a value. Mirrors the pattern used by Find-SpecifyRoot.
|
||||
$resolvedJson = Resolve-Path -LiteralPath $fd -ErrorAction SilentlyContinue
|
||||
if ($resolvedJson) {
|
||||
$normJson = $resolvedJson.Path
|
||||
} else {
|
||||
$normJson = [System.IO.Path]::GetFullPath($fd)
|
||||
}
|
||||
|
||||
$resolvedActive = Resolve-Path -LiteralPath $ActiveFeatureDir -ErrorAction SilentlyContinue
|
||||
if ($resolvedActive) {
|
||||
$normActive = $resolvedActive.Path
|
||||
} else {
|
||||
$normActive = [System.IO.Path]::GetFullPath($ActiveFeatureDir)
|
||||
}
|
||||
|
||||
# Use case-insensitive compare only on Windows; POSIX filesystems are case-sensitive.
|
||||
# PowerShell 5.1 is Windows-only and does not define $IsWindows, so treat its
|
||||
# absence as "we're on Windows".
|
||||
if ($null -ne $IsWindows) {
|
||||
$onWindows = $IsWindows
|
||||
} else {
|
||||
$onWindows = $true
|
||||
}
|
||||
|
||||
if ($onWindows) {
|
||||
$comparison = [System.StringComparison]::OrdinalIgnoreCase
|
||||
} else {
|
||||
$comparison = [System.StringComparison]::Ordinal
|
||||
}
|
||||
|
||||
return [string]::Equals($normJson, $normActive, $comparison)
|
||||
}
|
||||
|
||||
# Resolve specs/<feature-dir> by numeric/timestamp prefix (mirrors scripts/bash/common.sh find_feature_dir_by_prefix).
|
||||
function Find-FeatureDirByPrefix {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)][string]$RepoRoot,
|
||||
[Parameter(Mandatory = $true)][string]$Branch
|
||||
)
|
||||
$specsDir = Join-Path $RepoRoot 'specs'
|
||||
$branchName = Get-SpecKitEffectiveBranchName $Branch
|
||||
|
||||
$prefix = $null
|
||||
if ($branchName -match '^(\d{8}-\d{6})-') {
|
||||
$prefix = $Matches[1]
|
||||
} elseif ($branchName -match '^(\d{3,})-') {
|
||||
$prefix = $Matches[1]
|
||||
} else {
|
||||
return (Join-Path $specsDir $branchName)
|
||||
}
|
||||
|
||||
$dirMatches = @()
|
||||
if (Test-Path -LiteralPath $specsDir -PathType Container) {
|
||||
$dirMatches = @(Get-ChildItem -LiteralPath $specsDir -Filter "$prefix-*" -Directory -ErrorAction SilentlyContinue)
|
||||
}
|
||||
|
||||
if ($dirMatches.Count -eq 0) {
|
||||
return (Join-Path $specsDir $branchName)
|
||||
}
|
||||
if ($dirMatches.Count -eq 1) {
|
||||
return $dirMatches[0].FullName
|
||||
}
|
||||
$names = ($dirMatches | ForEach-Object { $_.Name }) -join ' '
|
||||
[Console]::Error.WriteLine("ERROR: Multiple spec directories found with prefix '$prefix': $names")
|
||||
[Console]::Error.WriteLine('Please ensure only one spec directory exists per prefix.')
|
||||
return $null
|
||||
}
|
||||
|
||||
# Branch-based prefix resolution; mirrors bash get_feature_paths failure (stderr + exit 1).
|
||||
function Get-FeatureDirFromBranchPrefixOrExit {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)][string]$RepoRoot,
|
||||
[Parameter(Mandatory = $true)][string]$CurrentBranch
|
||||
)
|
||||
$resolved = Find-FeatureDirByPrefix -RepoRoot $RepoRoot -Branch $CurrentBranch
|
||||
if ($null -eq $resolved) {
|
||||
[Console]::Error.WriteLine('ERROR: Failed to resolve feature directory')
|
||||
exit 1
|
||||
}
|
||||
return $resolved
|
||||
}
|
||||
|
||||
function Get-FeaturePathsEnv {
|
||||
$repoRoot = Get-RepoRoot
|
||||
$currentBranch = Get-CurrentBranch
|
||||
$hasGit = Test-HasGit
|
||||
|
||||
# Resolve feature directory. Priority:
|
||||
# 1. SPECIFY_FEATURE_DIRECTORY env var (explicit override)
|
||||
# 2. .specify/feature.json "feature_directory" key (persisted by /speckit-specify)
|
||||
# 3. Branch-name-based prefix lookup (same as scripts/bash/common.sh)
|
||||
$featureJson = Join-Path $repoRoot '.specify/feature.json'
|
||||
if ($env:SPECIFY_FEATURE_DIRECTORY) {
|
||||
$featureDir = $env:SPECIFY_FEATURE_DIRECTORY
|
||||
# Normalize relative paths to absolute under repo root
|
||||
if (-not [System.IO.Path]::IsPathRooted($featureDir)) {
|
||||
$featureDir = Join-Path $repoRoot $featureDir
|
||||
}
|
||||
} elseif (Test-Path $featureJson) {
|
||||
$featureJsonRaw = Get-Content -LiteralPath $featureJson -Raw
|
||||
try {
|
||||
$featureConfig = $featureJsonRaw | ConvertFrom-Json
|
||||
} catch {
|
||||
[Console]::Error.WriteLine("ERROR: Failed to parse .specify/feature.json: $_")
|
||||
exit 1
|
||||
}
|
||||
if ($featureConfig.feature_directory) {
|
||||
$featureDir = $featureConfig.feature_directory
|
||||
# Normalize relative paths to absolute under repo root
|
||||
if (-not [System.IO.Path]::IsPathRooted($featureDir)) {
|
||||
$featureDir = Join-Path $repoRoot $featureDir
|
||||
}
|
||||
} else {
|
||||
$featureDir = Get-FeatureDirFromBranchPrefixOrExit -RepoRoot $repoRoot -CurrentBranch $currentBranch
|
||||
}
|
||||
} else {
|
||||
$featureDir = Get-FeatureDirFromBranchPrefixOrExit -RepoRoot $repoRoot -CurrentBranch $currentBranch
|
||||
}
|
||||
|
||||
[PSCustomObject]@{
|
||||
REPO_ROOT = $repoRoot
|
||||
CURRENT_BRANCH = $currentBranch
|
||||
HAS_GIT = $hasGit
|
||||
FEATURE_DIR = $featureDir
|
||||
FEATURE_SPEC = Join-Path $featureDir 'spec.md'
|
||||
IMPL_PLAN = Join-Path $featureDir 'plan.md'
|
||||
TASKS = Join-Path $featureDir 'tasks.md'
|
||||
RESEARCH = Join-Path $featureDir 'research.md'
|
||||
DATA_MODEL = Join-Path $featureDir 'data-model.md'
|
||||
QUICKSTART = Join-Path $featureDir 'quickstart.md'
|
||||
CONTRACTS_DIR = Join-Path $featureDir 'contracts'
|
||||
}
|
||||
}
|
||||
|
||||
function Test-FileExists {
|
||||
param([string]$Path, [string]$Description)
|
||||
if (Test-Path -Path $Path -PathType Leaf) {
|
||||
Write-Output " [OK] $Description"
|
||||
return $true
|
||||
} else {
|
||||
Write-Output " [FAIL] $Description"
|
||||
return $false
|
||||
}
|
||||
}
|
||||
|
||||
function Test-DirHasFiles {
|
||||
param([string]$Path, [string]$Description)
|
||||
if ((Test-Path -Path $Path -PathType Container) -and (Get-ChildItem -Path $Path -ErrorAction SilentlyContinue | Where-Object { -not $_.PSIsContainer } | Select-Object -First 1)) {
|
||||
Write-Output " [OK] $Description"
|
||||
return $true
|
||||
} else {
|
||||
Write-Output " [FAIL] $Description"
|
||||
return $false
|
||||
}
|
||||
}
|
||||
|
||||
# Find a usable Python 3 executable (python3, python, or py -3).
|
||||
# Returns the command/arguments as an array, or $null if none found.
|
||||
function Get-Python3Command {
|
||||
if (Get-Command python3 -ErrorAction SilentlyContinue) { return @('python3') }
|
||||
if (Get-Command python -ErrorAction SilentlyContinue) {
|
||||
$ver = & python --version 2>&1
|
||||
if ($ver -match 'Python 3') { return @('python') }
|
||||
}
|
||||
if (Get-Command py -ErrorAction SilentlyContinue) {
|
||||
$ver = & py -3 --version 2>&1
|
||||
if ($ver -match 'Python 3') { return @('py', '-3') }
|
||||
}
|
||||
return $null
|
||||
}
|
||||
|
||||
# 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)
|
||||
function Resolve-Template {
|
||||
param(
|
||||
[Parameter(Mandatory=$true)][string]$TemplateName,
|
||||
[Parameter(Mandatory=$true)][string]$RepoRoot
|
||||
)
|
||||
|
||||
$base = Join-Path $RepoRoot '.specify/templates'
|
||||
|
||||
# Priority 1: Project overrides
|
||||
$override = Join-Path $base "overrides/$TemplateName.md"
|
||||
if (Test-Path $override) { return $override }
|
||||
|
||||
# Priority 2: Installed presets (sorted by priority from .registry)
|
||||
$presetsDir = Join-Path $RepoRoot '.specify/presets'
|
||||
if (Test-Path $presetsDir) {
|
||||
$registryFile = Join-Path $presetsDir '.registry'
|
||||
$sortedPresets = @()
|
||||
if (Test-Path $registryFile) {
|
||||
try {
|
||||
$registryData = Get-Content $registryFile -Raw | ConvertFrom-Json
|
||||
$presets = $registryData.presets
|
||||
if ($presets) {
|
||||
$sortedPresets = $presets.PSObject.Properties |
|
||||
Where-Object { $null -eq $_.Value.enabled -or $_.Value.enabled -ne $false } |
|
||||
Sort-Object { if ($null -ne $_.Value.priority) { $_.Value.priority } else { 10 } } |
|
||||
ForEach-Object { $_.Name }
|
||||
}
|
||||
} catch {
|
||||
# Fallback: alphabetical directory order
|
||||
$sortedPresets = @()
|
||||
}
|
||||
}
|
||||
|
||||
if ($sortedPresets.Count -gt 0) {
|
||||
foreach ($presetId in $sortedPresets) {
|
||||
$candidate = Join-Path $presetsDir "$presetId/templates/$TemplateName.md"
|
||||
if (Test-Path $candidate) { return $candidate }
|
||||
}
|
||||
} else {
|
||||
# Fallback: alphabetical directory order
|
||||
foreach ($preset in Get-ChildItem -Path $presetsDir -Directory -ErrorAction SilentlyContinue | Where-Object { $_.Name -notlike '.*' }) {
|
||||
$candidate = Join-Path $preset.FullName "templates/$TemplateName.md"
|
||||
if (Test-Path $candidate) { return $candidate }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Priority 3: Extension-provided templates
|
||||
$extDir = Join-Path $RepoRoot '.specify/extensions'
|
||||
if (Test-Path $extDir) {
|
||||
foreach ($ext in Get-ChildItem -Path $extDir -Directory -ErrorAction SilentlyContinue | Where-Object { $_.Name -notlike '.*' } | Sort-Object Name) {
|
||||
$candidate = Join-Path $ext.FullName "templates/$TemplateName.md"
|
||||
if (Test-Path $candidate) { return $candidate }
|
||||
}
|
||||
}
|
||||
|
||||
# Priority 4: Core templates
|
||||
$core = Join-Path $base "$TemplateName.md"
|
||||
if (Test-Path $core) { return $core }
|
||||
|
||||
return $null
|
||||
}
|
||||
|
||||
# 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.
|
||||
function Resolve-TemplateContent {
|
||||
param(
|
||||
[Parameter(Mandatory=$true)][string]$TemplateName,
|
||||
[Parameter(Mandatory=$true)][string]$RepoRoot
|
||||
)
|
||||
|
||||
$base = Join-Path $RepoRoot '.specify/templates'
|
||||
|
||||
# Collect all layers (highest priority first)
|
||||
$layerPaths = @()
|
||||
$layerStrategies = @()
|
||||
|
||||
# Priority 1: Project overrides (always "replace")
|
||||
$override = Join-Path $base "overrides/$TemplateName.md"
|
||||
if (Test-Path $override) {
|
||||
$layerPaths += $override
|
||||
$layerStrategies += 'replace'
|
||||
}
|
||||
|
||||
# Priority 2: Installed presets (sorted by priority from .registry)
|
||||
$presetsDir = Join-Path $RepoRoot '.specify/presets'
|
||||
if (Test-Path $presetsDir) {
|
||||
$registryFile = Join-Path $presetsDir '.registry'
|
||||
$sortedPresets = @()
|
||||
if (Test-Path $registryFile) {
|
||||
try {
|
||||
$registryData = Get-Content $registryFile -Raw | ConvertFrom-Json
|
||||
$presets = $registryData.presets
|
||||
if ($presets) {
|
||||
$sortedPresets = $presets.PSObject.Properties |
|
||||
Where-Object { $null -eq $_.Value.enabled -or $_.Value.enabled -ne $false } |
|
||||
Sort-Object { if ($null -ne $_.Value.priority) { $_.Value.priority } else { 10 } } |
|
||||
ForEach-Object { $_.Name }
|
||||
}
|
||||
} catch {
|
||||
$sortedPresets = @()
|
||||
}
|
||||
}
|
||||
|
||||
if ($sortedPresets.Count -gt 0) {
|
||||
$pyCmd = Get-Python3Command
|
||||
if (-not $pyCmd) {
|
||||
# Check if any preset has strategy fields that would be ignored
|
||||
foreach ($pid in $sortedPresets) {
|
||||
$mf = Join-Path $presetsDir "$pid/preset.yml"
|
||||
if ((Test-Path $mf) -and (Select-String -Path $mf -Pattern 'strategy:' -Quiet -ErrorAction SilentlyContinue)) {
|
||||
Write-Warning "No Python 3 found; preset composition strategies will be ignored"
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
$yamlWarned = $false
|
||||
foreach ($presetId in $sortedPresets) {
|
||||
# Read strategy and file path from preset manifest
|
||||
$strategy = 'replace'
|
||||
$manifestFilePath = ''
|
||||
$manifest = Join-Path $presetsDir "$presetId/preset.yml"
|
||||
if ((Test-Path $manifest) -and $pyCmd) {
|
||||
try {
|
||||
# Use Python to parse YAML manifest for strategy and file path
|
||||
$pyArgs = if ($pyCmd.Count -gt 1) { $pyCmd[1..($pyCmd.Count-1)] } else { @() }
|
||||
$pyStderrFile = [System.IO.Path]::GetTempFileName()
|
||||
$stratResult = & $pyCmd[0] @pyArgs -c @"
|
||||
import sys
|
||||
try:
|
||||
import yaml
|
||||
except ImportError:
|
||||
print('yaml_missing', file=sys.stderr)
|
||||
print('replace\t')
|
||||
sys.exit(0)
|
||||
try:
|
||||
with open(sys.argv[1]) as f:
|
||||
data = yaml.safe_load(f)
|
||||
for t in data.get('provides', {}).get('templates', []):
|
||||
if t.get('name') == sys.argv[2] and t.get('type', 'template') == 'template':
|
||||
print(t.get('strategy', 'replace') + '\t' + t.get('file', ''))
|
||||
sys.exit(0)
|
||||
print('replace\t')
|
||||
except Exception:
|
||||
print('replace\t')
|
||||
"@ $manifest $TemplateName 2>$pyStderrFile
|
||||
if ($stratResult) {
|
||||
$parts = $stratResult.Trim() -split "`t", 2
|
||||
$strategy = $parts[0].ToLowerInvariant()
|
||||
if ($parts.Count -gt 1 -and $parts[1]) { $manifestFilePath = $parts[1] }
|
||||
}
|
||||
if (-not $yamlWarned -and (Test-Path $pyStderrFile) -and (Get-Content $pyStderrFile -Raw -ErrorAction SilentlyContinue) -match 'yaml_missing') {
|
||||
Write-Warning "PyYAML not available; composition strategies may be ignored"
|
||||
$yamlWarned = $true
|
||||
}
|
||||
Remove-Item $pyStderrFile -Force -ErrorAction SilentlyContinue
|
||||
} catch {
|
||||
$strategy = 'replace'
|
||||
if ($pyStderrFile) { Remove-Item $pyStderrFile -Force -ErrorAction SilentlyContinue }
|
||||
}
|
||||
}
|
||||
# Try manifest file path first, then convention path
|
||||
$candidate = $null
|
||||
if ($manifestFilePath) {
|
||||
# Reject absolute paths and parent traversal
|
||||
if ([System.IO.Path]::IsPathRooted($manifestFilePath) -or $manifestFilePath -match '\.\.[\\/]') {
|
||||
$manifestFilePath = ''
|
||||
}
|
||||
}
|
||||
if ($manifestFilePath) {
|
||||
$mf = Join-Path $presetsDir "$presetId/$manifestFilePath"
|
||||
if (Test-Path $mf) { $candidate = $mf }
|
||||
}
|
||||
if (-not $candidate) {
|
||||
$cf = Join-Path $presetsDir "$presetId/templates/$TemplateName.md"
|
||||
if (Test-Path $cf) { $candidate = $cf }
|
||||
}
|
||||
if ($candidate) {
|
||||
$layerPaths += $candidate
|
||||
$layerStrategies += $strategy
|
||||
}
|
||||
}
|
||||
} else {
|
||||
# Fallback: alphabetical directory order (no registry or parse failure)
|
||||
foreach ($preset in Get-ChildItem -Path $presetsDir -Directory -ErrorAction SilentlyContinue | Where-Object { $_.Name -notlike '.*' }) {
|
||||
$candidate = Join-Path $preset.FullName "templates/$TemplateName.md"
|
||||
if (Test-Path $candidate) {
|
||||
$layerPaths += $candidate
|
||||
$layerStrategies += 'replace'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Priority 3: Extension-provided templates (always "replace")
|
||||
$extDir = Join-Path $RepoRoot '.specify/extensions'
|
||||
if (Test-Path $extDir) {
|
||||
foreach ($ext in Get-ChildItem -Path $extDir -Directory -ErrorAction SilentlyContinue | Where-Object { $_.Name -notlike '.*' } | Sort-Object Name) {
|
||||
$candidate = Join-Path $ext.FullName "templates/$TemplateName.md"
|
||||
if (Test-Path $candidate) {
|
||||
$layerPaths += $candidate
|
||||
$layerStrategies += 'replace'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Priority 4: Core templates (always "replace")
|
||||
$core = Join-Path $base "$TemplateName.md"
|
||||
if (Test-Path $core) {
|
||||
$layerPaths += $core
|
||||
$layerStrategies += 'replace'
|
||||
}
|
||||
|
||||
if ($layerPaths.Count -eq 0) { return $null }
|
||||
|
||||
# If the top (highest-priority) layer is replace, it wins entirely --
|
||||
# lower layers are irrelevant regardless of their strategies.
|
||||
if ($layerStrategies[0] -eq 'replace') {
|
||||
return (Get-Content $layerPaths[0] -Raw)
|
||||
}
|
||||
|
||||
# Check if any layer uses a non-replace strategy
|
||||
$hasComposition = $false
|
||||
foreach ($s in $layerStrategies) {
|
||||
if ($s -ne 'replace') { $hasComposition = $true; break }
|
||||
}
|
||||
|
||||
if (-not $hasComposition) {
|
||||
return (Get-Content $layerPaths[0] -Raw)
|
||||
}
|
||||
|
||||
# Find the effective base: scan from highest priority (index 0) downward
|
||||
# to find the nearest replace layer. Only compose layers above that base.
|
||||
$baseIdx = -1
|
||||
for ($i = 0; $i -lt $layerPaths.Count; $i++) {
|
||||
if ($layerStrategies[$i] -eq 'replace') {
|
||||
$baseIdx = $i
|
||||
break
|
||||
}
|
||||
}
|
||||
if ($baseIdx -lt 0) { return $null }
|
||||
|
||||
$content = Get-Content $layerPaths[$baseIdx] -Raw
|
||||
|
||||
for ($i = $baseIdx - 1; $i -ge 0; $i--) {
|
||||
$path = $layerPaths[$i]
|
||||
$strat = $layerStrategies[$i]
|
||||
$layerContent = Get-Content $path -Raw
|
||||
|
||||
switch ($strat) {
|
||||
'replace' { $content = $layerContent }
|
||||
'prepend' { $content = "$layerContent`n`n$content" }
|
||||
'append' { $content = "$content`n`n$layerContent" }
|
||||
'wrap' {
|
||||
if (-not $layerContent.Contains('{CORE_TEMPLATE}')) {
|
||||
throw "Wrap strategy missing {CORE_TEMPLATE} placeholder"
|
||||
}
|
||||
$content = $layerContent.Replace('{CORE_TEMPLATE}', $content)
|
||||
}
|
||||
default { throw "Unknown strategy: $strat" }
|
||||
}
|
||||
}
|
||||
|
||||
return $content
|
||||
}
|
||||
@@ -0,0 +1,385 @@
|
||||
#!/usr/bin/env pwsh
|
||||
# Create a new feature
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[switch]$Json,
|
||||
[switch]$AllowExistingBranch,
|
||||
[switch]$DryRun,
|
||||
[string]$ShortName,
|
||||
[Parameter()]
|
||||
[long]$Number = 0,
|
||||
[switch]$Timestamp,
|
||||
[switch]$Help,
|
||||
[Parameter(Position = 0, ValueFromRemainingArguments = $true)]
|
||||
[string[]]$FeatureDescription
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
# Show help if requested
|
||||
if ($Help) {
|
||||
Write-Host "Usage: ./create-new-feature.ps1 [-Json] [-DryRun] [-AllowExistingBranch] [-ShortName <name>] [-Number N] [-Timestamp] <feature description>"
|
||||
Write-Host ""
|
||||
Write-Host "Options:"
|
||||
Write-Host " -Json Output in JSON format"
|
||||
Write-Host " -DryRun Compute branch name and paths without creating branches, directories, or files"
|
||||
Write-Host " -AllowExistingBranch Switch to branch if it already exists instead of failing"
|
||||
Write-Host " -ShortName <name> Provide a custom short name (2-4 words) for the branch"
|
||||
Write-Host " -Number N Specify branch number manually (overrides auto-detection)"
|
||||
Write-Host " -Timestamp Use timestamp prefix (YYYYMMDD-HHMMSS) instead of sequential numbering"
|
||||
Write-Host " -Help Show this help message"
|
||||
Write-Host ""
|
||||
Write-Host "Examples:"
|
||||
Write-Host " ./create-new-feature.ps1 'Add user authentication system' -ShortName 'user-auth'"
|
||||
Write-Host " ./create-new-feature.ps1 'Implement OAuth2 integration for API'"
|
||||
Write-Host " ./create-new-feature.ps1 -Timestamp -ShortName 'user-auth' 'Add user authentication'"
|
||||
exit 0
|
||||
}
|
||||
|
||||
# Check if feature description provided
|
||||
if (-not $FeatureDescription -or $FeatureDescription.Count -eq 0) {
|
||||
Write-Error "Usage: ./create-new-feature.ps1 [-Json] [-DryRun] [-AllowExistingBranch] [-ShortName <name>] [-Number N] [-Timestamp] <feature description>"
|
||||
exit 1
|
||||
}
|
||||
|
||||
$featureDesc = ($FeatureDescription -join ' ').Trim()
|
||||
|
||||
# Validate description is not empty after trimming (e.g., user passed only whitespace)
|
||||
if ([string]::IsNullOrWhiteSpace($featureDesc)) {
|
||||
Write-Error "Error: Feature description cannot be empty or contain only whitespace"
|
||||
exit 1
|
||||
}
|
||||
|
||||
function Get-HighestNumberFromSpecs {
|
||||
param([string]$SpecsDir)
|
||||
|
||||
[long]$highest = 0
|
||||
if (Test-Path $SpecsDir) {
|
||||
Get-ChildItem -Path $SpecsDir -Directory | ForEach-Object {
|
||||
# Match sequential prefixes (>=3 digits), but skip timestamp dirs.
|
||||
if ($_.Name -match '^(\d{3,})-' -and $_.Name -notmatch '^\d{8}-\d{6}-') {
|
||||
[long]$num = 0
|
||||
if ([long]::TryParse($matches[1], [ref]$num) -and $num -gt $highest) {
|
||||
$highest = $num
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return $highest
|
||||
}
|
||||
|
||||
# Extract the highest sequential feature number from a list of branch/ref names.
|
||||
# Shared by Get-HighestNumberFromBranches and Get-HighestNumberFromRemoteRefs.
|
||||
function Get-HighestNumberFromNames {
|
||||
param([string[]]$Names)
|
||||
|
||||
[long]$highest = 0
|
||||
foreach ($name in $Names) {
|
||||
if ($name -match '^(\d{3,})-' -and $name -notmatch '^\d{8}-\d{6}-') {
|
||||
[long]$num = 0
|
||||
if ([long]::TryParse($matches[1], [ref]$num) -and $num -gt $highest) {
|
||||
$highest = $num
|
||||
}
|
||||
}
|
||||
}
|
||||
return $highest
|
||||
}
|
||||
|
||||
function Get-HighestNumberFromBranches {
|
||||
param()
|
||||
|
||||
try {
|
||||
$branches = git branch -a 2>$null
|
||||
if ($LASTEXITCODE -eq 0 -and $branches) {
|
||||
$cleanNames = $branches | ForEach-Object {
|
||||
$_.Trim() -replace '^\*?\s+', '' -replace '^remotes/[^/]+/', ''
|
||||
}
|
||||
return Get-HighestNumberFromNames -Names $cleanNames
|
||||
}
|
||||
} catch {
|
||||
Write-Verbose "Could not check Git branches: $_"
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
function Get-HighestNumberFromRemoteRefs {
|
||||
[long]$highest = 0
|
||||
try {
|
||||
$remotes = git remote 2>$null
|
||||
if ($remotes) {
|
||||
foreach ($remote in $remotes) {
|
||||
$env:GIT_TERMINAL_PROMPT = '0'
|
||||
$refs = git ls-remote --heads $remote 2>$null
|
||||
$env:GIT_TERMINAL_PROMPT = $null
|
||||
if ($LASTEXITCODE -eq 0 -and $refs) {
|
||||
$refNames = $refs | ForEach-Object {
|
||||
if ($_ -match 'refs/heads/(.+)$') { $matches[1] }
|
||||
} | Where-Object { $_ }
|
||||
$remoteHighest = Get-HighestNumberFromNames -Names $refNames
|
||||
if ($remoteHighest -gt $highest) { $highest = $remoteHighest }
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
Write-Verbose "Could not query remote refs: $_"
|
||||
}
|
||||
return $highest
|
||||
}
|
||||
|
||||
# Return next available branch number. When SkipFetch is true, queries remotes
|
||||
# via ls-remote (read-only) instead of fetching.
|
||||
function Get-NextBranchNumber {
|
||||
param(
|
||||
[string]$SpecsDir,
|
||||
[switch]$SkipFetch
|
||||
)
|
||||
|
||||
if ($SkipFetch) {
|
||||
# Side-effect-free: query remotes via ls-remote
|
||||
$highestBranch = Get-HighestNumberFromBranches
|
||||
$highestRemote = Get-HighestNumberFromRemoteRefs
|
||||
$highestBranch = [Math]::Max($highestBranch, $highestRemote)
|
||||
} else {
|
||||
# Fetch all remotes to get latest branch info (suppress errors if no remotes)
|
||||
try {
|
||||
git fetch --all --prune 2>$null | Out-Null
|
||||
} catch {
|
||||
# Ignore fetch errors
|
||||
}
|
||||
$highestBranch = Get-HighestNumberFromBranches
|
||||
}
|
||||
|
||||
# Get highest number from ALL specs (not just matching short name)
|
||||
$highestSpec = Get-HighestNumberFromSpecs -SpecsDir $SpecsDir
|
||||
|
||||
# Take the maximum of both
|
||||
$maxNum = [Math]::Max($highestBranch, $highestSpec)
|
||||
|
||||
# Return next number
|
||||
return $maxNum + 1
|
||||
}
|
||||
|
||||
function ConvertTo-CleanBranchName {
|
||||
param([string]$Name)
|
||||
|
||||
return $Name.ToLower() -replace '[^a-z0-9]', '-' -replace '-{2,}', '-' -replace '^-', '' -replace '-$', ''
|
||||
}
|
||||
# Load common functions (includes Get-RepoRoot, Test-HasGit, Resolve-Template)
|
||||
. "$PSScriptRoot/common.ps1"
|
||||
|
||||
# Use common.ps1 functions which prioritize .specify over git
|
||||
$repoRoot = Get-RepoRoot
|
||||
|
||||
# Check if git is available at this repo root (not a parent)
|
||||
$hasGit = Test-HasGit
|
||||
|
||||
Set-Location $repoRoot
|
||||
|
||||
$specsDir = Join-Path $repoRoot 'specs'
|
||||
if (-not $DryRun) {
|
||||
New-Item -ItemType Directory -Path $specsDir -Force | Out-Null
|
||||
}
|
||||
|
||||
# Function to generate branch name with stop word filtering and length filtering
|
||||
function Get-BranchName {
|
||||
param([string]$Description)
|
||||
|
||||
# Common stop words to filter out
|
||||
$stopWords = @(
|
||||
'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'
|
||||
)
|
||||
|
||||
# Convert to lowercase and extract words (alphanumeric only)
|
||||
$cleanName = $Description.ToLower() -replace '[^a-z0-9\s]', ' '
|
||||
$words = $cleanName -split '\s+' | Where-Object { $_ }
|
||||
|
||||
# Filter words: remove stop words and words shorter than 3 chars (unless they're uppercase acronyms in original)
|
||||
$meaningfulWords = @()
|
||||
foreach ($word in $words) {
|
||||
# Skip stop words
|
||||
if ($stopWords -contains $word) { continue }
|
||||
|
||||
# Keep words that are length >= 3 OR appear as uppercase in original (likely acronyms)
|
||||
if ($word.Length -ge 3) {
|
||||
$meaningfulWords += $word
|
||||
} elseif ($Description -match "\b$($word.ToUpper())\b") {
|
||||
# Keep short words if they appear as uppercase in original (likely acronyms)
|
||||
$meaningfulWords += $word
|
||||
}
|
||||
}
|
||||
|
||||
# If we have meaningful words, use first 3-4 of them
|
||||
if ($meaningfulWords.Count -gt 0) {
|
||||
$maxWords = if ($meaningfulWords.Count -eq 4) { 4 } else { 3 }
|
||||
$result = ($meaningfulWords | Select-Object -First $maxWords) -join '-'
|
||||
return $result
|
||||
} else {
|
||||
# Fallback to original logic if no meaningful words found
|
||||
$result = ConvertTo-CleanBranchName -Name $Description
|
||||
$fallbackWords = ($result -split '-') | Where-Object { $_ } | Select-Object -First 3
|
||||
return [string]::Join('-', $fallbackWords)
|
||||
}
|
||||
}
|
||||
|
||||
# Generate branch name
|
||||
if ($ShortName) {
|
||||
# Use provided short name, just clean it up
|
||||
$branchSuffix = ConvertTo-CleanBranchName -Name $ShortName
|
||||
} else {
|
||||
# Generate from description with smart filtering
|
||||
$branchSuffix = Get-BranchName -Description $featureDesc
|
||||
}
|
||||
|
||||
# Warn if -Number and -Timestamp are both specified
|
||||
if ($Timestamp -and $Number -ne 0) {
|
||||
Write-Warning "[specify] Warning: -Number is ignored when -Timestamp is used"
|
||||
$Number = 0
|
||||
}
|
||||
|
||||
# Determine branch prefix
|
||||
if ($Timestamp) {
|
||||
$featureNum = Get-Date -Format 'yyyyMMdd-HHmmss'
|
||||
$branchName = "$featureNum-$branchSuffix"
|
||||
} else {
|
||||
# Determine branch number
|
||||
if ($Number -eq 0) {
|
||||
if ($DryRun -and $hasGit) {
|
||||
# Dry-run: query remotes via ls-remote (side-effect-free, no fetch)
|
||||
$Number = Get-NextBranchNumber -SpecsDir $specsDir -SkipFetch
|
||||
} elseif ($DryRun) {
|
||||
# Dry-run without git: local spec dirs only
|
||||
$Number = (Get-HighestNumberFromSpecs -SpecsDir $specsDir) + 1
|
||||
} elseif ($hasGit) {
|
||||
# Check existing branches on remotes
|
||||
$Number = Get-NextBranchNumber -SpecsDir $specsDir
|
||||
} else {
|
||||
# Fall back to local directory check
|
||||
$Number = (Get-HighestNumberFromSpecs -SpecsDir $specsDir) + 1
|
||||
}
|
||||
}
|
||||
|
||||
$featureNum = ('{0:000}' -f $Number)
|
||||
$branchName = "$featureNum-$branchSuffix"
|
||||
}
|
||||
|
||||
# GitHub enforces a 244-byte limit on branch names
|
||||
# Validate and truncate if necessary
|
||||
$maxBranchLength = 244
|
||||
if ($branchName.Length -gt $maxBranchLength) {
|
||||
# Calculate how much we need to trim from suffix
|
||||
# Account for prefix length: timestamp (15) + hyphen (1) = 16, or sequential (3) + hyphen (1) = 4
|
||||
$prefixLength = $featureNum.Length + 1
|
||||
$maxSuffixLength = $maxBranchLength - $prefixLength
|
||||
|
||||
# Truncate suffix
|
||||
$truncatedSuffix = $branchSuffix.Substring(0, [Math]::Min($branchSuffix.Length, $maxSuffixLength))
|
||||
# Remove trailing hyphen if truncation created one
|
||||
$truncatedSuffix = $truncatedSuffix -replace '-$', ''
|
||||
|
||||
$originalBranchName = $branchName
|
||||
$branchName = "$featureNum-$truncatedSuffix"
|
||||
|
||||
Write-Warning "[specify] Branch name exceeded GitHub's 244-byte limit"
|
||||
Write-Warning "[specify] Original: $originalBranchName ($($originalBranchName.Length) bytes)"
|
||||
Write-Warning "[specify] Truncated to: $branchName ($($branchName.Length) bytes)"
|
||||
}
|
||||
|
||||
$featureDir = Join-Path $specsDir $branchName
|
||||
$specFile = Join-Path $featureDir 'spec.md'
|
||||
|
||||
if (-not $DryRun) {
|
||||
if ($hasGit) {
|
||||
$branchCreated = $false
|
||||
$branchCreateError = ''
|
||||
try {
|
||||
$branchCreateError = git checkout -q -b $branchName 2>&1 | Out-String
|
||||
if ($LASTEXITCODE -eq 0) {
|
||||
$branchCreated = $true
|
||||
}
|
||||
} catch {
|
||||
$branchCreateError = $_.Exception.Message
|
||||
}
|
||||
|
||||
if (-not $branchCreated) {
|
||||
$currentBranch = ''
|
||||
try { $currentBranch = (git rev-parse --abbrev-ref HEAD 2>$null).Trim() } catch {}
|
||||
# Check if branch already exists
|
||||
$existingBranch = git branch --list $branchName 2>$null
|
||||
if ($existingBranch) {
|
||||
if ($AllowExistingBranch) {
|
||||
# If we're already on the branch, continue without another checkout.
|
||||
if ($currentBranch -eq $branchName) {
|
||||
# Already on the target branch -- nothing to do
|
||||
} else {
|
||||
# Otherwise switch to the existing branch instead of failing.
|
||||
$switchBranchError = git checkout -q $branchName 2>&1 | Out-String
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
if ($switchBranchError) {
|
||||
Write-Error "Error: Branch '$branchName' exists but could not be checked out.`n$($switchBranchError.Trim())"
|
||||
} else {
|
||||
Write-Error "Error: Branch '$branchName' exists but could not be checked out. Resolve any uncommitted changes or conflicts and try again."
|
||||
}
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
} elseif ($Timestamp) {
|
||||
Write-Error "Error: Branch '$branchName' already exists. Rerun to get a new timestamp or use a different -ShortName."
|
||||
exit 1
|
||||
} else {
|
||||
Write-Error "Error: Branch '$branchName' already exists. Please use a different feature name or specify a different number with -Number."
|
||||
exit 1
|
||||
}
|
||||
} else {
|
||||
if ($branchCreateError) {
|
||||
Write-Error "Error: Failed to create git branch '$branchName'.`n$($branchCreateError.Trim())"
|
||||
} else {
|
||||
Write-Error "Error: Failed to create git branch '$branchName'. Please check your git configuration and try again."
|
||||
}
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Write-Warning "[specify] Warning: Git repository not detected; skipped branch creation for $branchName"
|
||||
}
|
||||
|
||||
New-Item -ItemType Directory -Path $featureDir -Force | Out-Null
|
||||
|
||||
if (-not (Test-Path -PathType Leaf $specFile)) {
|
||||
$template = Resolve-Template -TemplateName 'spec-template' -RepoRoot $repoRoot
|
||||
if ($template -and (Test-Path $template)) {
|
||||
# Read the template content and write it to the spec file with UTF-8 encoding without BOM
|
||||
$content = [System.IO.File]::ReadAllText($template)
|
||||
$utf8NoBom = New-Object System.Text.UTF8Encoding($false)
|
||||
[System.IO.File]::WriteAllText($specFile, $content, $utf8NoBom)
|
||||
} else {
|
||||
New-Item -ItemType File -Path $specFile -Force | Out-Null
|
||||
}
|
||||
}
|
||||
|
||||
# Set the SPECIFY_FEATURE environment variable for the current session
|
||||
$env:SPECIFY_FEATURE = $branchName
|
||||
}
|
||||
|
||||
if ($Json) {
|
||||
$obj = [PSCustomObject]@{
|
||||
BRANCH_NAME = $branchName
|
||||
SPEC_FILE = $specFile
|
||||
FEATURE_NUM = $featureNum
|
||||
HAS_GIT = $hasGit
|
||||
}
|
||||
if ($DryRun) {
|
||||
$obj | Add-Member -NotePropertyName 'DRY_RUN' -NotePropertyValue $true
|
||||
}
|
||||
$obj | ConvertTo-Json -Compress
|
||||
} else {
|
||||
Write-Output "BRANCH_NAME: $branchName"
|
||||
Write-Output "SPEC_FILE: $specFile"
|
||||
Write-Output "FEATURE_NUM: $featureNum"
|
||||
Write-Output "HAS_GIT: $hasGit"
|
||||
if (-not $DryRun) {
|
||||
Write-Output "SPECIFY_FEATURE environment variable set to: $branchName"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
#!/usr/bin/env pwsh
|
||||
# Setup implementation plan for a feature
|
||||
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[switch]$Json,
|
||||
[switch]$Help
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
# Show help if requested
|
||||
if ($Help) {
|
||||
Write-Output "Usage: ./setup-plan.ps1 [-Json] [-Help]"
|
||||
Write-Output " -Json Output results in JSON format"
|
||||
Write-Output " -Help Show this help message"
|
||||
exit 0
|
||||
}
|
||||
|
||||
# Load common functions
|
||||
. "$PSScriptRoot/common.ps1"
|
||||
|
||||
# Get all paths and variables from common functions
|
||||
$paths = Get-FeaturePathsEnv
|
||||
|
||||
# If feature.json pins an existing feature directory, branch naming is not required.
|
||||
if (-not (Test-FeatureJsonMatchesFeatureDir -RepoRoot $paths.REPO_ROOT -ActiveFeatureDir $paths.FEATURE_DIR)) {
|
||||
if (-not (Test-FeatureBranch -Branch $paths.CURRENT_BRANCH -HasGit $paths.HAS_GIT)) {
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
|
||||
# Ensure the feature directory exists
|
||||
New-Item -ItemType Directory -Path $paths.FEATURE_DIR -Force | Out-Null
|
||||
|
||||
# Copy plan template if plan doesn't already exist
|
||||
if (Test-Path $paths.IMPL_PLAN -PathType Leaf) {
|
||||
if ($Json) {
|
||||
[Console]::Error.WriteLine("Plan already exists at $($paths.IMPL_PLAN), skipping template copy")
|
||||
} else {
|
||||
Write-Output "Plan already exists at $($paths.IMPL_PLAN), skipping template copy"
|
||||
}
|
||||
} else {
|
||||
$template = Resolve-Template -TemplateName 'plan-template' -RepoRoot $paths.REPO_ROOT
|
||||
if ($template -and (Test-Path $template)) {
|
||||
# Read the template content and write it to the implementation plan file with UTF-8 encoding without BOM
|
||||
$content = [System.IO.File]::ReadAllText($template)
|
||||
$utf8NoBom = New-Object System.Text.UTF8Encoding($false)
|
||||
[System.IO.File]::WriteAllText($paths.IMPL_PLAN, $content, $utf8NoBom)
|
||||
} else {
|
||||
Write-Warning "Plan template not found"
|
||||
# Create a basic plan file if template doesn't exist
|
||||
New-Item -ItemType File -Path $paths.IMPL_PLAN -Force | Out-Null
|
||||
}
|
||||
}
|
||||
|
||||
# Output results
|
||||
if ($Json) {
|
||||
$result = [PSCustomObject]@{
|
||||
FEATURE_SPEC = $paths.FEATURE_SPEC
|
||||
IMPL_PLAN = $paths.IMPL_PLAN
|
||||
SPECS_DIR = $paths.FEATURE_DIR
|
||||
BRANCH = $paths.CURRENT_BRANCH
|
||||
HAS_GIT = $paths.HAS_GIT
|
||||
}
|
||||
$result | ConvertTo-Json -Compress
|
||||
} else {
|
||||
Write-Output "FEATURE_SPEC: $($paths.FEATURE_SPEC)"
|
||||
Write-Output "IMPL_PLAN: $($paths.IMPL_PLAN)"
|
||||
Write-Output "SPECS_DIR: $($paths.FEATURE_DIR)"
|
||||
Write-Output "BRANCH: $($paths.CURRENT_BRANCH)"
|
||||
Write-Output "HAS_GIT: $($paths.HAS_GIT)"
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
#!/usr/bin/env pwsh
|
||||
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[switch]$Json,
|
||||
[switch]$Help
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
if ($Help) {
|
||||
Write-Output "Usage: setup-tasks.ps1 [-Json] [-Help]"
|
||||
exit 0
|
||||
}
|
||||
|
||||
# Source common functions
|
||||
. "$PSScriptRoot/common.ps1"
|
||||
|
||||
# Get feature paths and validate branch
|
||||
$paths = Get-FeaturePathsEnv
|
||||
|
||||
# If feature.json pins an existing feature directory, branch naming is not required.
|
||||
if (-not (Test-FeatureJsonMatchesFeatureDir -RepoRoot $paths.REPO_ROOT -ActiveFeatureDir $paths.FEATURE_DIR)) {
|
||||
if (-not (Test-FeatureBranch -Branch $paths.CURRENT_BRANCH -HasGit $paths.HAS_GIT)) {
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
|
||||
if (-not (Test-Path $paths.IMPL_PLAN -PathType Leaf)) {
|
||||
[Console]::Error.WriteLine("ERROR: plan.md not found in $($paths.FEATURE_DIR)")
|
||||
[Console]::Error.WriteLine("Run /speckit-plan first to create the implementation plan.")
|
||||
exit 1
|
||||
}
|
||||
|
||||
if (-not (Test-Path $paths.FEATURE_SPEC -PathType Leaf)) {
|
||||
[Console]::Error.WriteLine("ERROR: spec.md not found in $($paths.FEATURE_DIR)")
|
||||
[Console]::Error.WriteLine("Run /speckit-specify first to create the feature structure.")
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Build available docs list
|
||||
$docs = @()
|
||||
if (Test-Path $paths.RESEARCH) { $docs += 'research.md' }
|
||||
if (Test-Path $paths.DATA_MODEL) { $docs += 'data-model.md' }
|
||||
if ((Test-Path $paths.CONTRACTS_DIR) -and (Get-ChildItem -Path $paths.CONTRACTS_DIR -ErrorAction SilentlyContinue | Select-Object -First 1)) {
|
||||
$docs += 'contracts/'
|
||||
}
|
||||
if (Test-Path $paths.QUICKSTART) { $docs += 'quickstart.md' }
|
||||
|
||||
# Resolve tasks template through override stack
|
||||
$tasksTemplate = Resolve-Template -TemplateName 'tasks-template' -RepoRoot $paths.REPO_ROOT
|
||||
if (-not $tasksTemplate -or -not (Test-Path -LiteralPath $tasksTemplate -PathType Leaf)) {
|
||||
$expectedCoreTemplate = Join-Path $paths.REPO_ROOT '.specify/templates/tasks-template.md'
|
||||
[Console]::Error.WriteLine("ERROR: Tasks template not found for repository root: $($paths.REPO_ROOT)`nTemplate resolution order: overrides -> presets -> extensions -> core.`nExpected shared/core template location: $expectedCoreTemplate`nTo continue, verify whether 'tasks-template.md' is available in '.specify/templates/overrides/', preset templates, extension templates, or restore the shared/core templates (for example by re-running 'specify init') so that '.specify/templates/tasks-template.md' exists.")
|
||||
exit 1
|
||||
}
|
||||
$tasksTemplate = (Resolve-Path -LiteralPath $tasksTemplate).Path
|
||||
|
||||
# Output results
|
||||
if ($Json) {
|
||||
[PSCustomObject]@{
|
||||
FEATURE_DIR = $paths.FEATURE_DIR
|
||||
AVAILABLE_DOCS = $docs
|
||||
TASKS_TEMPLATE = $tasksTemplate
|
||||
} | ConvertTo-Json -Compress
|
||||
} else {
|
||||
Write-Output "FEATURE_DIR: $($paths.FEATURE_DIR)"
|
||||
Write-Output "TASKS_TEMPLATE: $(if ($tasksTemplate) { $tasksTemplate } else { 'not found' })"
|
||||
Write-Output "AVAILABLE_DOCS:"
|
||||
Test-FileExists -Path $paths.RESEARCH -Description 'research.md' | Out-Null
|
||||
Test-FileExists -Path $paths.DATA_MODEL -Description 'data-model.md' | Out-Null
|
||||
Test-DirHasFiles -Path $paths.CONTRACTS_DIR -Description 'contracts/' | Out-Null
|
||||
Test-FileExists -Path $paths.QUICKSTART -Description 'quickstart.md' | Out-Null
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
# [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 checklist is generated by the `/speckit-checklist` command based on feature context and requirements.
|
||||
|
||||
<!--
|
||||
============================================================================
|
||||
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
|
||||
|
||||
- Check items off as completed: `[x]`
|
||||
- Add comments or findings inline
|
||||
- Link to relevant resources or documentation
|
||||
- Items are numbered sequentially for easy reference
|
||||
@@ -0,0 +1,50 @@
|
||||
# [PROJECT_NAME] Constitution
|
||||
<!-- Example: Spec Constitution, TaskFlow Constitution, etc. -->
|
||||
|
||||
## Core Principles
|
||||
|
||||
### [PRINCIPLE_1_NAME]
|
||||
<!-- Example: I. Library-First -->
|
||||
[PRINCIPLE_1_DESCRIPTION]
|
||||
<!-- Example: Every feature starts as a standalone library; Libraries must be self-contained, independently testable, documented; Clear purpose required - no organizational-only libraries -->
|
||||
|
||||
### [PRINCIPLE_2_NAME]
|
||||
<!-- Example: II. CLI Interface -->
|
||||
[PRINCIPLE_2_DESCRIPTION]
|
||||
<!-- Example: Every library exposes functionality via CLI; Text in/out protocol: stdin/args → stdout, errors → stderr; Support JSON + human-readable formats -->
|
||||
|
||||
### [PRINCIPLE_3_NAME]
|
||||
<!-- Example: III. Test-First (NON-NEGOTIABLE) -->
|
||||
[PRINCIPLE_3_DESCRIPTION]
|
||||
<!-- Example: TDD mandatory: Tests written → User approved → Tests fail → Then implement; Red-Green-Refactor cycle strictly enforced -->
|
||||
|
||||
### [PRINCIPLE_4_NAME]
|
||||
<!-- Example: IV. Integration Testing -->
|
||||
[PRINCIPLE_4_DESCRIPTION]
|
||||
<!-- Example: Focus areas requiring integration tests: New library contract tests, Contract changes, Inter-service communication, Shared schemas -->
|
||||
|
||||
### [PRINCIPLE_5_NAME]
|
||||
<!-- Example: V. Observability, VI. Versioning & Breaking Changes, VII. Simplicity -->
|
||||
[PRINCIPLE_5_DESCRIPTION]
|
||||
<!-- Example: Text I/O ensures debuggability; Structured logging required; Or: MAJOR.MINOR.BUILD format; Or: Start simple, YAGNI principles -->
|
||||
|
||||
## [SECTION_2_NAME]
|
||||
<!-- Example: Additional Constraints, Security Requirements, Performance Standards, etc. -->
|
||||
|
||||
[SECTION_2_CONTENT]
|
||||
<!-- Example: Technology stack requirements, compliance standards, deployment policies, etc. -->
|
||||
|
||||
## [SECTION_3_NAME]
|
||||
<!-- Example: Development Workflow, Review Process, Quality Gates, etc. -->
|
||||
|
||||
[SECTION_3_CONTENT]
|
||||
<!-- Example: Code review requirements, testing gates, deployment approval process, etc. -->
|
||||
|
||||
## Governance
|
||||
<!-- Example: Constitution supersedes all other practices; Amendments require documentation, approval, migration plan -->
|
||||
|
||||
[GOVERNANCE_RULES]
|
||||
<!-- Example: All PRs/reviews must verify compliance; Complexity must be justified; Use [GUIDANCE_FILE] for runtime development guidance -->
|
||||
|
||||
**Version**: [CONSTITUTION_VERSION] | **Ratified**: [RATIFICATION_DATE] | **Last Amended**: [LAST_AMENDED_DATE]
|
||||
<!-- Example: Version: 2.1.1 | Ratified: 2025-06-13 | Last Amended: 2025-07-16 -->
|
||||
@@ -0,0 +1,113 @@
|
||||
# Implementation Plan: [FEATURE]
|
||||
|
||||
**Branch**: `[###-feature-name]` | **Date**: [DATE] | **Spec**: [link]
|
||||
|
||||
**Input**: Feature specification from `/specs/[###-feature-name]/spec.md`
|
||||
|
||||
**Note**: This template is filled in by the `/speckit-plan` command. See `.specify/templates/plan-template.md` for 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] |
|
||||
@@ -0,0 +1,131 @@
|
||||
# Feature Specification: [FEATURE NAME]
|
||||
|
||||
**Feature Branch**: `[###-feature-name]`
|
||||
|
||||
**Created**: [DATE]
|
||||
|
||||
**Status**: Draft
|
||||
|
||||
**Input**: User description: "$ARGUMENTS"
|
||||
|
||||
## User Scenarios & Testing *(mandatory)*
|
||||
|
||||
<!--
|
||||
IMPORTANT: User stories should be PRIORITIZED as user journeys ordered by importance.
|
||||
Each user story/journey must be INDEPENDENTLY TESTABLE - meaning if you implement just ONE of them,
|
||||
you should still have a viable MVP (Minimum Viable Product) that delivers value.
|
||||
|
||||
Assign priorities (P1, P2, P3, etc.) to each story, where P1 is the most critical.
|
||||
Think of each story as a standalone slice of functionality that can be:
|
||||
- Developed independently
|
||||
- Tested independently
|
||||
- Deployed independently
|
||||
- Demonstrated to users independently
|
||||
-->
|
||||
|
||||
### User Story 1 - [Brief Title] (Priority: P1)
|
||||
|
||||
[Describe this user journey in plain language]
|
||||
|
||||
**Why this priority**: [Explain the value and why it has this priority level]
|
||||
|
||||
**Independent Test**: [Describe how this can be tested independently - e.g., "Can be fully tested by [specific action] and delivers [specific value]"]
|
||||
|
||||
**Acceptance Scenarios**:
|
||||
|
||||
1. **Given** [initial state], **When** [action], **Then** [expected outcome]
|
||||
2. **Given** [initial state], **When** [action], **Then** [expected outcome]
|
||||
|
||||
---
|
||||
|
||||
### User Story 2 - [Brief Title] (Priority: P2)
|
||||
|
||||
[Describe this user journey in plain language]
|
||||
|
||||
**Why this priority**: [Explain the value and why it has this priority level]
|
||||
|
||||
**Independent Test**: [Describe how this can be tested independently]
|
||||
|
||||
**Acceptance Scenarios**:
|
||||
|
||||
1. **Given** [initial state], **When** [action], **Then** [expected outcome]
|
||||
|
||||
---
|
||||
|
||||
### User Story 3 - [Brief Title] (Priority: P3)
|
||||
|
||||
[Describe this user journey in plain language]
|
||||
|
||||
**Why this priority**: [Explain the value and why it has this priority level]
|
||||
|
||||
**Independent Test**: [Describe how this can be tested independently]
|
||||
|
||||
**Acceptance Scenarios**:
|
||||
|
||||
1. **Given** [initial state], **When** [action], **Then** [expected outcome]
|
||||
|
||||
---
|
||||
|
||||
[Add more user stories as needed, each with an assigned priority]
|
||||
|
||||
### Edge Cases
|
||||
|
||||
<!--
|
||||
ACTION REQUIRED: The content in this section represents placeholders.
|
||||
Fill them out with the right edge cases.
|
||||
-->
|
||||
|
||||
- What happens when [boundary condition]?
|
||||
- How does system handle [error scenario]?
|
||||
|
||||
## Requirements *(mandatory)*
|
||||
|
||||
<!--
|
||||
ACTION REQUIRED: The content in this section represents placeholders.
|
||||
Fill them out with the right functional requirements.
|
||||
-->
|
||||
|
||||
### Functional Requirements
|
||||
|
||||
- **FR-001**: System MUST [specific capability, e.g., "allow users to create accounts"]
|
||||
- **FR-002**: System MUST [specific capability, e.g., "validate email addresses"]
|
||||
- **FR-003**: Users MUST be able to [key interaction, e.g., "reset their password"]
|
||||
- **FR-004**: System MUST [data requirement, e.g., "persist user preferences"]
|
||||
- **FR-005**: System MUST [behavior, e.g., "log all security events"]
|
||||
|
||||
*Example of marking unclear requirements:*
|
||||
|
||||
- **FR-006**: System MUST authenticate users via [NEEDS CLARIFICATION: auth method not specified - email/password, SSO, OAuth?]
|
||||
- **FR-007**: System MUST retain user data for [NEEDS CLARIFICATION: retention period not specified]
|
||||
|
||||
### Key Entities *(include if feature involves data)*
|
||||
|
||||
- **[Entity 1]**: [What it represents, key attributes without implementation]
|
||||
- **[Entity 2]**: [What it represents, relationships to other entities]
|
||||
|
||||
## Success Criteria *(mandatory)*
|
||||
|
||||
<!--
|
||||
ACTION REQUIRED: Define measurable success criteria.
|
||||
These must be technology-agnostic and measurable.
|
||||
-->
|
||||
|
||||
### Measurable Outcomes
|
||||
|
||||
- **SC-001**: [Measurable metric, e.g., "Users can complete account creation in under 2 minutes"]
|
||||
- **SC-002**: [Measurable metric, e.g., "System handles 1000 concurrent users without degradation"]
|
||||
- **SC-003**: [User satisfaction metric, e.g., "90% of users successfully complete primary task on first attempt"]
|
||||
- **SC-004**: [Business metric, e.g., "Reduce support tickets related to [X] by 50%"]
|
||||
|
||||
## Assumptions
|
||||
|
||||
<!--
|
||||
ACTION REQUIRED: The content in this section represents placeholders.
|
||||
Fill them out with the right assumptions based on reasonable defaults
|
||||
chosen when the feature description did not specify certain details.
|
||||
-->
|
||||
|
||||
- [Assumption about target users, e.g., "Users have stable internet connectivity"]
|
||||
- [Assumption about scope boundaries, e.g., "Mobile support is out of scope for v1"]
|
||||
- [Assumption about data/environment, e.g., "Existing authentication system will be reused"]
|
||||
- [Dependency on existing system/service, e.g., "Requires access to the existing user profile API"]
|
||||
@@ -0,0 +1,252 @@
|
||||
---
|
||||
|
||||
description: "Task list template for feature implementation"
|
||||
---
|
||||
|
||||
# Tasks: [FEATURE NAME]
|
||||
|
||||
**Input**: Design documents from `/specs/[###-feature-name]/`
|
||||
|
||||
**Prerequisites**: plan.md (required), spec.md (required for user stories), research.md, data-model.md, contracts/
|
||||
|
||||
**Tests**: The examples below include test tasks. Tests are OPTIONAL - only include them if explicitly requested in the feature specification.
|
||||
|
||||
**Organization**: Tasks are grouped by user story to enable independent implementation and testing of each story.
|
||||
|
||||
## Format: `[ID] [P?] [Story] Description`
|
||||
|
||||
- **[P]**: Can run in parallel (different files, no dependencies)
|
||||
- **[Story]**: Which user story this task belongs to (e.g., US1, US2, US3)
|
||||
- Include exact file paths in descriptions
|
||||
|
||||
## Path Conventions
|
||||
|
||||
- **Single project**: `src/`, `tests/` at repository root
|
||||
- **Web app**: `backend/src/`, `frontend/src/`
|
||||
- **Mobile**: `api/src/`, `ios/src/` or `android/src/`
|
||||
- Paths shown below assume single project - adjust based on plan.md structure
|
||||
|
||||
<!--
|
||||
============================================================================
|
||||
IMPORTANT: The tasks below are SAMPLE TASKS for illustration purposes only.
|
||||
|
||||
The /speckit-tasks command MUST replace these with actual tasks based on:
|
||||
- User stories from spec.md (with their priorities P1, P2, P3...)
|
||||
- Feature requirements from plan.md
|
||||
- Entities from data-model.md
|
||||
- Endpoints from contracts/
|
||||
|
||||
Tasks MUST be organized by user story so each story can be:
|
||||
- Implemented independently
|
||||
- Tested independently
|
||||
- Delivered as an MVP increment
|
||||
|
||||
DO NOT keep these sample tasks in the generated tasks.md file.
|
||||
============================================================================
|
||||
-->
|
||||
|
||||
## Phase 1: Setup (Shared Infrastructure)
|
||||
|
||||
**Purpose**: Project initialization and basic structure
|
||||
|
||||
- [ ] T001 Create project structure per implementation plan
|
||||
- [ ] T002 Initialize [language] project with [framework] dependencies
|
||||
- [ ] T003 [P] Configure linting and formatting tools
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: Foundational (Blocking Prerequisites)
|
||||
|
||||
**Purpose**: Core infrastructure that MUST be complete before ANY user story can be implemented
|
||||
|
||||
**⚠️ CRITICAL**: No user story work can begin until this phase is complete
|
||||
|
||||
Examples of foundational tasks (adjust based on your project):
|
||||
|
||||
- [ ] T004 Setup database schema and migrations framework
|
||||
- [ ] T005 [P] Implement authentication/authorization framework
|
||||
- [ ] T006 [P] Setup API routing and middleware structure
|
||||
- [ ] T007 Create base models/entities that all stories depend on
|
||||
- [ ] T008 Configure error handling and logging infrastructure
|
||||
- [ ] T009 Setup environment configuration management
|
||||
|
||||
**Checkpoint**: Foundation ready - user story implementation can now begin in parallel
|
||||
|
||||
---
|
||||
|
||||
## Phase 3: User Story 1 - [Title] (Priority: P1) 🎯 MVP
|
||||
|
||||
**Goal**: [Brief description of what this story delivers]
|
||||
|
||||
**Independent Test**: [How to verify this story works on its own]
|
||||
|
||||
### Tests for User Story 1 (OPTIONAL - only if tests requested) ⚠️
|
||||
|
||||
> **NOTE: Write these tests FIRST, ensure they FAIL before implementation**
|
||||
|
||||
- [ ] T010 [P] [US1] Contract test for [endpoint] in tests/contract/test_[name].py
|
||||
- [ ] T011 [P] [US1] Integration test for [user journey] in tests/integration/test_[name].py
|
||||
|
||||
### Implementation for User Story 1
|
||||
|
||||
- [ ] T012 [P] [US1] Create [Entity1] model in src/models/[entity1].py
|
||||
- [ ] T013 [P] [US1] Create [Entity2] model in src/models/[entity2].py
|
||||
- [ ] T014 [US1] Implement [Service] in src/services/[service].py (depends on T012, T013)
|
||||
- [ ] T015 [US1] Implement [endpoint/feature] in src/[location]/[file].py
|
||||
- [ ] T016 [US1] Add validation and error handling
|
||||
- [ ] T017 [US1] Add logging for user story 1 operations
|
||||
|
||||
**Checkpoint**: At this point, User Story 1 should be fully functional and testable independently
|
||||
|
||||
---
|
||||
|
||||
## Phase 4: User Story 2 - [Title] (Priority: P2)
|
||||
|
||||
**Goal**: [Brief description of what this story delivers]
|
||||
|
||||
**Independent Test**: [How to verify this story works on its own]
|
||||
|
||||
### Tests for User Story 2 (OPTIONAL - only if tests requested) ⚠️
|
||||
|
||||
- [ ] T018 [P] [US2] Contract test for [endpoint] in tests/contract/test_[name].py
|
||||
- [ ] T019 [P] [US2] Integration test for [user journey] in tests/integration/test_[name].py
|
||||
|
||||
### Implementation for User Story 2
|
||||
|
||||
- [ ] T020 [P] [US2] Create [Entity] model in src/models/[entity].py
|
||||
- [ ] T021 [US2] Implement [Service] in src/services/[service].py
|
||||
- [ ] T022 [US2] Implement [endpoint/feature] in src/[location]/[file].py
|
||||
- [ ] T023 [US2] Integrate with User Story 1 components (if needed)
|
||||
|
||||
**Checkpoint**: At this point, User Stories 1 AND 2 should both work independently
|
||||
|
||||
---
|
||||
|
||||
## Phase 5: User Story 3 - [Title] (Priority: P3)
|
||||
|
||||
**Goal**: [Brief description of what this story delivers]
|
||||
|
||||
**Independent Test**: [How to verify this story works on its own]
|
||||
|
||||
### Tests for User Story 3 (OPTIONAL - only if tests requested) ⚠️
|
||||
|
||||
- [ ] T024 [P] [US3] Contract test for [endpoint] in tests/contract/test_[name].py
|
||||
- [ ] T025 [P] [US3] Integration test for [user journey] in tests/integration/test_[name].py
|
||||
|
||||
### Implementation for User Story 3
|
||||
|
||||
- [ ] T026 [P] [US3] Create [Entity] model in src/models/[entity].py
|
||||
- [ ] T027 [US3] Implement [Service] in src/services/[service].py
|
||||
- [ ] T028 [US3] Implement [endpoint/feature] in src/[location]/[file].py
|
||||
|
||||
**Checkpoint**: All user stories should now be independently functional
|
||||
|
||||
---
|
||||
|
||||
[Add more user story phases as needed, following the same pattern]
|
||||
|
||||
---
|
||||
|
||||
## Phase N: Polish & Cross-Cutting Concerns
|
||||
|
||||
**Purpose**: Improvements that affect multiple user stories
|
||||
|
||||
- [ ] TXXX [P] Documentation updates in docs/
|
||||
- [ ] TXXX Code cleanup and refactoring
|
||||
- [ ] TXXX Performance optimization across all stories
|
||||
- [ ] TXXX [P] Additional unit tests (if requested) in tests/unit/
|
||||
- [ ] TXXX Security hardening
|
||||
- [ ] TXXX Run quickstart.md validation
|
||||
|
||||
---
|
||||
|
||||
## Dependencies & Execution Order
|
||||
|
||||
### Phase Dependencies
|
||||
|
||||
- **Setup (Phase 1)**: No dependencies - can start immediately
|
||||
- **Foundational (Phase 2)**: Depends on Setup completion - BLOCKS all user stories
|
||||
- **User Stories (Phase 3+)**: All depend on Foundational phase completion
|
||||
- User stories can then proceed in parallel (if staffed)
|
||||
- Or sequentially in priority order (P1 → P2 → P3)
|
||||
- **Polish (Final Phase)**: Depends on all desired user stories being complete
|
||||
|
||||
### User Story Dependencies
|
||||
|
||||
- **User Story 1 (P1)**: Can start after Foundational (Phase 2) - No dependencies on other stories
|
||||
- **User Story 2 (P2)**: Can start after Foundational (Phase 2) - May integrate with US1 but should be independently testable
|
||||
- **User Story 3 (P3)**: Can start after Foundational (Phase 2) - May integrate with US1/US2 but should be independently testable
|
||||
|
||||
### Within Each User Story
|
||||
|
||||
- Tests (if included) MUST be written and FAIL before implementation
|
||||
- Models before services
|
||||
- Services before endpoints
|
||||
- Core implementation before integration
|
||||
- Story complete before moving to next priority
|
||||
|
||||
### Parallel Opportunities
|
||||
|
||||
- All Setup tasks marked [P] can run in parallel
|
||||
- All Foundational tasks marked [P] can run in parallel (within Phase 2)
|
||||
- Once Foundational phase completes, all user stories can start in parallel (if team capacity allows)
|
||||
- All tests for a user story marked [P] can run in parallel
|
||||
- Models within a story marked [P] can run in parallel
|
||||
- Different user stories can be worked on in parallel by different team members
|
||||
|
||||
---
|
||||
|
||||
## Parallel Example: User Story 1
|
||||
|
||||
```bash
|
||||
# Launch all tests for User Story 1 together (if tests requested):
|
||||
Task: "Contract test for [endpoint] in tests/contract/test_[name].py"
|
||||
Task: "Integration test for [user journey] in tests/integration/test_[name].py"
|
||||
|
||||
# Launch all models for User Story 1 together:
|
||||
Task: "Create [Entity1] model in src/models/[entity1].py"
|
||||
Task: "Create [Entity2] model in src/models/[entity2].py"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Implementation Strategy
|
||||
|
||||
### MVP First (User Story 1 Only)
|
||||
|
||||
1. Complete Phase 1: Setup
|
||||
2. Complete Phase 2: Foundational (CRITICAL - blocks all stories)
|
||||
3. Complete Phase 3: User Story 1
|
||||
4. **STOP and VALIDATE**: Test User Story 1 independently
|
||||
5. Deploy/demo if ready
|
||||
|
||||
### Incremental Delivery
|
||||
|
||||
1. Complete Setup + Foundational → Foundation ready
|
||||
2. Add User Story 1 → Test independently → Deploy/Demo (MVP!)
|
||||
3. Add User Story 2 → Test independently → Deploy/Demo
|
||||
4. Add User Story 3 → Test independently → Deploy/Demo
|
||||
5. Each story adds value without breaking previous stories
|
||||
|
||||
### Parallel Team Strategy
|
||||
|
||||
With multiple developers:
|
||||
|
||||
1. Team completes Setup + Foundational together
|
||||
2. Once Foundational is done:
|
||||
- Developer A: User Story 1
|
||||
- Developer B: User Story 2
|
||||
- Developer C: User Story 3
|
||||
3. Stories complete and integrate independently
|
||||
|
||||
---
|
||||
|
||||
## Notes
|
||||
|
||||
- [P] tasks = different files, no dependencies
|
||||
- [Story] label maps task to specific user story for traceability
|
||||
- Each user story should be independently completable and testable
|
||||
- Verify tests fail before implementing
|
||||
- Commit after each task or logical group
|
||||
- Stop at any checkpoint to validate story independently
|
||||
- Avoid: vague tasks, same file conflicts, cross-story dependencies that break independence
|
||||
@@ -0,0 +1,77 @@
|
||||
schema_version: "1.0"
|
||||
workflow:
|
||||
id: "speckit"
|
||||
name: "Full SDD Cycle"
|
||||
version: "1.0.0"
|
||||
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:
|
||||
- "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)"
|
||||
scope:
|
||||
type: string
|
||||
default: "full"
|
||||
enum: ["full", "backend-only", "frontend-only"]
|
||||
|
||||
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 }}"
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"schema_version": "1.0",
|
||||
"workflows": {
|
||||
"speckit": {
|
||||
"name": "Full SDD Cycle",
|
||||
"version": "1.0.0",
|
||||
"description": "Runs specify \u2192 plan \u2192 tasks \u2192 implement with review gates",
|
||||
"source": "bundled",
|
||||
"installed_at": "2026-06-07T22:31:39.049978+00:00",
|
||||
"updated_at": "2026-06-07T22:31:39.049978+00:00"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
# AGENTS.md — Guía de Vocero CRM para agentes y personas
|
||||
|
||||
Vocero es un CRM de WhatsApp open source (MIT) y self-hosted: bandeja en tiempo
|
||||
real, pipeline kanban, el perfil y el conocimiento del agente, y un Laboratorio
|
||||
donde clientes simulados lo evalúan antes de hablar con clientes reales. Desde la
|
||||
2.0 el CRM no trae agente (036): contesta un cerebro conectado al lado (Nea u
|
||||
otro) por el despacho y `/api/bot/*`. Sin cerebro, es un CRM de bandeja manual.
|
||||
Esta guía sirve igual para Claude Code, Codex, OpenCode o una persona: no depende
|
||||
de skills, scripts ni plugins de ningún asistente.
|
||||
|
||||
## Principios inviolables
|
||||
|
||||
- **Una instancia = un negocio.** Self-hosted; aun así, toda tabla de dominio lleva `organization_id` y toda consulta pasa por `scoped()`.
|
||||
- **Solo WhatsApp Cloud API oficial.** Nada de Baileys ni sesiones web. Todo tráfico a Meta pasa por `src/lib/meta/client.ts`.
|
||||
- **Secretos cifrados en reposo** (AES-256-GCM, `src/lib/crypto/`); jamás al cliente ni a logs. Los tokens de WhatsApp y del proveedor de IA solo enseñan sus últimos 4.
|
||||
- **El token de WhatsApp nunca sale del CRM.** Un bot externo conversa a través de `/api/bot/*`, no con Meta.
|
||||
- **Soberanía.** El núcleo depende solo de Postgres + WhatsApp Cloud API + un proveedor LLM OpenRouter-compatible opcional. Cualquier tercero entra como conector opcional tras bandera, apagado por defecto (`docs/adr-001-canales-opcionales.md`, `docs/adr-002-conectores-de-agenda.md`).
|
||||
- **Español** en código, comentarios, UI y documentación.
|
||||
- La autoridad máxima es `.specify/memory/constitution.md`; ante un conflicto, gana la constitución.
|
||||
|
||||
## Stack
|
||||
|
||||
| Capa | Qué |
|
||||
|---|---|
|
||||
| Framework | Next.js 15 (App Router) + React 19, TypeScript estricto (`strict` + `noUncheckedIndexedAccess`), alias `@/` → `src/` |
|
||||
| BD / ORM | PostgreSQL 16 + Drizzle ORM; migraciones SQL versionadas en `drizzle/`, aplicadas al arrancar el contenedor (`scripts/migrate.mjs`) |
|
||||
| Auth | Better Auth + plugin organization (`src/lib/auth/`); registro público cerrado tras la primera organización |
|
||||
| Validación | Zod en todo input externo (`parseBody` en `src/lib/api.ts`) |
|
||||
| Tiempo real | SSE en `GET /api/events` sobre un bus in-process (`src/server/events/bus.ts`); sin WebSockets ni colas: el trabajo en segundo plano corre dentro del proceso |
|
||||
| UI | Tailwind CSS con tokens en `src/app/globals.css`, tema claro/oscuro, white-label por organización |
|
||||
| Pruebas | Vitest (`tests/unit/`) + guiones E2E (`tests/e2e/*.md`) conducidos por `scripts/e2e-*.mjs` (fetch y, algunos, Playwright) contra la app con mocks |
|
||||
| Imagen | Docker multi-stage standalone, healthcheck `/api/health`, publicada en `ghcr.io/kevinrivm/vocero-crm:X.Y.Z` por `.github/workflows/imagen.yml` |
|
||||
|
||||
## Cómo correrlo
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
docker compose -f docker-compose.dev.yml up -d postgres # Postgres local
|
||||
pnpm init-env # crea .env con los secretos generados (DATABASE_URL apunta a `postgres`: cámbialo a localhost para pnpm dev)
|
||||
pnpm doctor # valida el entorno y prueba la base
|
||||
pnpm db:migrate # aplica drizzle/ en desarrollo
|
||||
pnpm dev # http://localhost:3000
|
||||
```
|
||||
|
||||
| Comando | Qué hace |
|
||||
|---|---|
|
||||
| `pnpm typecheck` · `pnpm lint` · `pnpm test` · `pnpm build` | Los cuatro gates del CI (`pnpm test` es `vitest run`; `pnpm test:watch` para iterar) |
|
||||
| `pnpm test:e2e` | `scripts/e2e-selftest.mjs` contra la app viva con mocks. `test:e2e:calendario` y `test:e2e:resultados` conducen sus guiones; el resto de `scripts/e2e-*.mjs` se corre con `node --env-file=.env scripts/<nombre>.mjs` |
|
||||
| `pnpm db:generate` | Genera una migración nueva en `drizzle/` a partir de `src/lib/db/schema.ts` |
|
||||
| `pnpm seed:demo` | Carga la Ferretería El Martillo (también desde la UI al primer arranque) |
|
||||
| `pnpm init-env [--domain x]` | Crea `.env` desde `.env.example` con los secretos generados y `DOMAIN=localhost` (o el dominio dado); nunca pisa uno existente. Lógica en `src/server/doctor/init-env.ts` |
|
||||
| `pnpm doctor` | Una línea ✓/✗ por comprobación con el arreglo exacto: variables (mismo esquema zod de `src/lib/env.ts`), `select 1` a `DATABASE_URL`, escritura en `MEDIA_DIR` (y en el bucket con `MEDIA_STORE=bucket`) y, si hay número conectado, el token contra Meta. Sale con 1 si algo obligatorio falla. Lógica en `src/server/doctor/checks.ts` |
|
||||
|
||||
Variables obligatorias (`src/lib/env.ts` las valida en el primer uso; cada una trae su comando `openssl` en `.env.example`):
|
||||
|
||||
| Variable | Para qué |
|
||||
|---|---|
|
||||
| `APP_BASE_URL` | URL pública; de ella sale la URL del webhook |
|
||||
| `DATABASE_URL` | Postgres. La conexión fija `TimeZone=UTC`: es el invariante de tiempo del proyecto |
|
||||
| `BETTER_AUTH_SECRET` | Firma de sesiones (mínimo 16 caracteres) |
|
||||
| `ENCRYPTION_KEY` | Exactamente 32 bytes en base64: cifra el token de WhatsApp |
|
||||
| `META_WEBHOOK_VERIFY_TOKEN` | Verify token y segmento secreto de `/api/webhooks/wa/<token>` |
|
||||
| `META_GRAPH_API_VERSION` | Versión de la Graph API (tiene default `v25.0`; las cinco de arriba no) |
|
||||
|
||||
Opcionales con efecto grande: `META_APP_SECRET` (firma del webhook y, con `META_APP_ID` + `META_EMBEDDED_CONFIG_ID`, el canje del botón «Conectar con Meta», 066, `src/server/whatsapp/embedded.ts`), `OPENROUTER_API_TOKEN` / `OPENROUTER_MODEL` (respaldo del proveedor de IA: lo normal es Ajustes → IA, que manda sobre ellas; sin ninguna de las dos cosas el cerebro no puede pensar por `/api/bot/llm` ni hay juez del Laboratorio), `BOT_API_KEY` (abre `/api/bot/*` y firma el despacho), `BRAIN_DISPATCH_URL` (con ella y `BOT_API_KEY`, el CRM le despacha cada turno al cerebro mientras el interruptor del Agente esté encendido), `BRAIN_HEALTH_URL` (el `/health` del cerebro: «Quién responde», la guía y el permiso para encender), `ALLOW_SIGNUP`, `AGENT_COALESCE_MS` (la ventana del despacho) y `AGENT_COALESCE_LARGO_MS` (078: la ventana cuando el último mensaje deja la ráfaga abierta, 8 s), `WA_MOCK_ENABLED` (solo desarrollo; con él, `WEBHOOK_RETRY_FAST=1` acorta a 300 ms las esperas del reintento de webhooks para los arneses).
|
||||
|
||||
Banderas de despliegue (apagadas por defecto; su código viaja siempre en `main` y su migración se aplica igual):
|
||||
|
||||
| Bandera | Enciende |
|
||||
|---|---|
|
||||
| `AGENDA=on` | Motor de citas: pantalla Citas, Ajustes → Agenda, `/api/bookings`, `/api/calendar/*`, `/api/bot/availability` y `/api/bot/bookings` (`src/server/agenda/flag.ts`) |
|
||||
| `CHANNELS=whatsapp,instagram,messenger,tiktok` | Canales extra: webhooks `/api/webhooks/ig`, `/api/webhooks/messenger` y `/api/webhooks/tiktok`, Ajustes → Estado, Instagram, Messenger y TikTok, credenciales por canal, distintivo en la bandeja (`src/server/channels/enabled.ts`) |
|
||||
| `ATRIBUCION=on` | Guardado del `ctwa_clid`, reporte a la Conversions API de Meta, Ajustes → Anuncios y `/api/settings/capi` (`src/server/attribution/flag.ts`). El anuncio de origen se ve siempre, con o sin bandera |
|
||||
| `API_V1=on` | 069 — API pública `/api/v1/*` con llaves, el MCP en `/api/v1/mcp`, su OAuth (`/api/oauth/*`, `/oauth/authorize`, `.well-known`) y Ajustes → API y MCP (`src/server/api-v1/flag.ts`). Guía: `docs/api-v1.md` |
|
||||
|
||||
Apagada, cada superficie responde 404 (no 403). El despliegue en producción está en el README («Instalación»: Rutas A y B, y «Otras plataformas» con `render.yaml`, `fly.toml` y `railway.toml`) y en `INSTALL-IA.md`; no se repite aquí.
|
||||
|
||||
## Mapa del código
|
||||
|
||||
### `src/server/` — lógica de dominio (nunca se importa desde componentes de cliente)
|
||||
|
||||
| Carpeta | Responsabilidad | Entrada |
|
||||
|---|---|---|
|
||||
| `agenda/` | Motor de citas: horarios, huecos, ofertas, reservas y conectores (enlace fijo, Zoom, Google) | `service.ts`, `flag.ts`, `http.ts`, `connectors/index.ts` |
|
||||
| `ai/` | Ya no hay turno dentro del proceso (036). Queda la credencial del proveedor de IA por organización (cifrada; estado `active` o pausada por 401/402), lo que valida y devuelve Ajustes → IA, el aviso de «sin IA» y, de `prompts.ts`, solo `renderKb` (el conocimiento para el perfil) y el prompt del juez (`JUDGE_MARKER`, `buildJudgePrompt`) | `credentials.ts`, `settings.ts`, `aviso.ts`, `prompts.ts` |
|
||||
| `api-v1/` | 069 — La API pública: bandera, llaves (solo sha256), la puerta `withApiKey` (la organización sale de la credencial; permisos `read`/`operate`/`send`/`configure` recortados al rol vigente), la puerta de Ajustes → API y el contrato `openapi.json` (una prueba exige que liste exactamente las rutas) | `flag.ts`, `llaves.ts`, `acceso.ts`, `handler.ts`, `ajustes.ts`, `docs.ts` |
|
||||
| `http/` | 069 — Los handlers que comparten la UI (`withAuth` en `src/app/api/*`) y la API v1 (`withApiKey` en `src/app/api/v1/*`): una regla cambia en un solo lugar. `enlaces.ts` arma los pendientes con sus enlaces | `compartido.ts`, `enlaces.ts`, `agent-simulate.ts` |
|
||||
| `mcp/` | 069 — Servidor MCP sin estado sobre la v1: cada herramienta arma una petición y la pasa al handler de la ruta v1 con la misma credencial; guías `configurar_vocero` y `probar_agente` (iguales a las skills de `plugin/vocero/`) | `servidor.ts`, `herramientas.ts`, `configuracion.ts`, `guia.ts`, `guia-probar.ts` |
|
||||
| `oauth/` | 069 — OAuth 2.1 mínimo para conectar el MCP desde claude.ai o ChatGPT: emisor = `APP_BASE_URL`, registro dinámico, PKCE S256, refresco que rota; los tokens `vat_` pasan por la misma puerta que las llaves | `nucleo.ts`, `servidor.ts`, `puerta.ts`, `autorizar.ts` |
|
||||
| `analytics/` | Números de Resultados (ventas, agente, anuncios, higiene) agregados en SQL; excluye el Laboratorio | `sales.ts`, `bot.ts`, `ads.ts`, `hygiene.ts`, `shared.ts` |
|
||||
| `attribution/` | De qué anuncio llegó cada conversación y reporte a la CAPI tras `ATRIBUCION` | `referral.ts`, `store.ts`, `conversions.ts`, `flag.ts` |
|
||||
| `auth/` | Registro cerrado tras la primera organización; alta del primer dueño con pipeline y perfil sembrados | `registration.ts`, `on-signup.ts` |
|
||||
| `bot/` | API de servicio para el cerebro: auth por `X-API-Key` o `Authorization: Bearer`, perfil (con `llm`), ficha, handoff, «quién responde» (avisos `sin_cerebro` y `apagado`) y, 036, el proxy del modelo (`/api/bot/llm`: reenvía tal cual con la llave de Ajustes → IA; 401/402 del proveedor la pausan) | `auth.ts`, `status.ts`, `profile.ts`, `llm-proxy.ts` |
|
||||
| `brains/` | 021 — El despacho hacia el cerebro: forma del evento y firma (pura; el orden de las claves es contrato), si hay despacho configurado (`despachoActivo`; 036 — `urlSaludCerebro` para su `/health`), y el POST firmado. 026 — el evento `conversation.deleted` (`construirEventoOlvido`, `avisarOlvido`: un intento, fuera del outbox) | `contract.ts`, `config.ts`, `deliver.ts` |
|
||||
| `channels/` | Qué canales están encendidos y qué puede hacer cada uno (duración de la ventana, plantillas, longitud en bytes o caracteres, tope de mensajes desde el último entrante). 023 — el estado de cada canal para Ajustes → Estado | `enabled.ts`, `capabilities.ts`, `status.ts` |
|
||||
| `dispatch/` | 021 — Outbox del despacho en Postgres (036 — `despacharAlCerebro` en `encolar.ts` es la entrada desde la ingesta y respeta el interruptor del Agente): un despacho vivo por conversación (índice único parcial), lease, tres intentos, caída a humano; el worker en proceso y lo que la tarjeta enseña. 025 — cada despacho anota qué entrantes debe (`message_ids`). 075 — `despachoSuperado` (el 409 `dispatch_superado` de `/api/bot/messages`) y la red de seguridad: cada 60 s relanza dos veces lo entregado que nadie contestó y luego traspasa con `sin_respuesta` (nunca en pausa, fuera de ventana, con el agente apagado ni en `is_test`; un «gracias» no cuenta). 076 — `brains/atencion-humana.ts`: la nota `humanAttention` cuando una persona atendió y la IA todavía no contesta. 078 — `ventana.ts`: la espera antes de despachar la decide el último mensaje (`AGENT_COALESCE_LARGO_MS` para lo que deja la ráfaga abierta), y `encolar.ts` manda «escribiendo…» al encolar (`whatsapp/escribiendo.ts`, compartido con `/api/bot/typing`) | `outbox.ts`, `worker.ts`, `encolar.ts`, `estado.ts`, `red-de-seguridad.ts`, `cierres.ts` |
|
||||
| `dev/` | Estado en memoria de los mocks (wa, ai —personas y juez del Laboratorio—, zernio, zoom, google); solo con mocks activos | `wa-mock-state.ts`, `ai-mock.ts` |
|
||||
| `events/` | Bus in-process por organización que alimenta el SSE; publicar siempre tras el commit | `bus.ts` |
|
||||
| `contacts-import.ts` (archivo) | 027 — Importar contactos en lote (re-ejecutable, sin crear conversación ni lead) y llevar la pausa del contacto a su conversación. La parte pura (leer el CSV, normalizar teléfonos) vive en `src/lib/contact-import.ts` y la usan el diálogo y la ruta | `src/server/contacts-import.ts` |
|
||||
| `inbox/` | Ingesta idempotente, identidad del contacto, envío con guardas, ventana de servicio (la duración es del canal), tope de mensajes del canal, estados monotónicos. 026 — eliminar una conversación (hilo o contacto): lo que las cascadas no hacen (adjuntos, ficha, cita por venir). 079 — `buscar-mensajes.ts`: buscar dentro de los mensajes (texto y pie de foto) para el buscador de la Bandeja. 076 — `reactivacion.ts`: la IA vuelve sola cuando el cliente escribe (N horas sin el equipo, o pausa con fecha vencida), `last_team_out_at` y la pausa con duración. 077 — `esperando.ts`: quién espera a una persona (la regla pura y su gemela SQL en la lista de conversaciones) | `ingest.ts`, `reactivacion.ts`, `esperando.ts`, `send.ts`, `identity.ts`, `webhook.ts`, `window.ts`, `outbound-cap.ts`, `eliminar.ts` |
|
||||
| `instagram/` | Adaptador del canal de Instagram (Meta o Zernio), tras `CHANNELS` | `ingest.ts`, `send.ts`, `credentials.ts` |
|
||||
| `lab/` | Laboratorio: corrida en segundo plano con personas guionadas que le escriben al cerebro conectado por el despacho (sin despacho, 409 `sin_cerebro`) y juez LLM con la llave de Ajustes → IA; conversaciones `is_test`. 069 — `simular.ts`: la simulación de la API/MCP por el mismo camino, sin dejar rastro | `runner.ts`, `personas.ts`, `judge.ts`, `simular.ts` |
|
||||
| `leads/` | Única puerta que escribe `lead.stage_id` (con bitácora) y prioridad del lead | `stage-history.ts`, `priority.ts` |
|
||||
| `messenger/` | Adaptador del canal de Messenger (Meta o Zernio), tras `CHANNELS` | `ingest.ts`, `send.ts`, `credentials.ts` |
|
||||
| `tiktok/` | 022 — Adaptador del canal de TikTok (solo Zernio), tras `CHANNELS` | `ingest.ts`, `send.ts`, `credentials.ts` |
|
||||
| `onboarding/` | Guía de inicio: perfil, IA, WhatsApp, «Conecta tu agente» (opcional: despacho configurado y `/health` sano; sin él, bandeja manual) y, con `AGENDA`, agenda; los pasos que ve el dueño y si la guía es la primera pantalla (`guideFirst`: una bandeja manual no se queda atrapada) | `status.ts`, `guide.ts`, `calendar-verifiers.ts` |
|
||||
| `seed/` | Negocio demo idempotente «Ferretería El Martillo» | `demo.ts` |
|
||||
| `webhooks/` | 047 — Los webhooks de entrada guardados antes de procesarse: recibir (resolver organización, guardar, 503 si no se puede), procesar por fuente (WhatsApp, Instagram y Messenger de Meta, Zernio), reintentar con espera 30 s → 6 h y seis intentos, retomar al arrancar, contar para Ajustes y `/api/health`, y borrar a los 7 días (procesado) o 30 (agotado). Mismo patrón de reclamo que el outbox del despacho | `recibir.ts`, `eventos.ts`, `procesar.ts`, `organizacion.ts`, `worker.ts` |
|
||||
| `whatsapp/` | Credenciales cifradas, prueba de conexión y suscripción del webhook, media, plantillas | `credentials.ts`, `connect.ts`, `media.ts`, `templates.ts` |
|
||||
| `zernio/` | Transporte y firma de la API unificada de Zernio; reparte cada evento al canal que toca. 023 — resuelve la cuenta contra `GET /accounts` al guardar, da de alta el webhook limitado a las cuentas de la organización, y verifica la firma contra los secretos guardados y los que Zernio tiene para esta instancia. 030 — el secreto de firma se guarda cifrado, como el token; el arranque cifra el que una versión anterior dejó en claro | `index.ts`, `dispatch.ts`, `cuentas.ts`, `webhooks.ts`, `conexiones.ts`, `guardar.ts`, `secreto-guardado.ts` |
|
||||
|
||||
Sueltos: `notas.ts` (050: notas internas del hilo, en su propia tabla para que nada que hable con Meta o con el cerebro las lea), `quick-replies.ts` (049: las respuestas rápidas de la organización, con su validación y las cuatro de la demo), `app-icon.tsx` (048: el PNG de la app instalable, dibujado con `next/og` desde la marca), `contacts.ts` (serialización), `contact-source.ts` (fuente del prospecto), `branding.ts` (marca guardada en la organización), `health.ts` (lo que responde `/api/health`: BD, versión, banderas activas, `mediaWritable`), `media-dir.ts` (sondeo de escritura de donde se guardan los adjuntos —`MEDIA_DIR` o, con `MEDIA_STORE=bucket`, el bucket—, cacheado 60 s; lo comparten el arranque y el health).
|
||||
|
||||
**Almacenamiento (037)** — `src/lib/storage/`: `objetos.ts` (cliente S3-compatible, SigV4 a mano, sin SDK) y `medios.ts` (el adaptador: escribe donde diga `MEDIA_STORE`, lee SIEMPRE en el disco y en el bucket, y si el bucket falla al escribir guarda en disco). `whatsapp/media.ts` (`saveMediaFile`, `readMediaFile`, `deleteMediaFile`) delega en él: no escribas en `MEDIA_DIR` directo. La llave del objeto es la ruta relativa que va en la BD (`{org}/{asset}`).
|
||||
|
||||
### El resto
|
||||
|
||||
| Ruta | Qué hay |
|
||||
|---|---|
|
||||
| `src/lib/` | Fronteras y utilidades sin estado: `env.ts` (validación lazy), `db/` (`schema.ts`, `tenant.ts` con `scoped()`, `ids.ts` con prefijos `ct_`, `cv_`, `msg_`…), `auth/` (sesión y `roles.ts`: quién configura), `crypto/`, `meta/` (`client.ts` Graph API, `capi.ts`, `destinatario.ts`, `send-errors.ts`), `ai/` (adaptador LLM con `chatJson<T>`; `provider.ts` resuelve con quién habla —la fila de Ajustes → IA y, de respaldo, `OPENROUTER_*`—, `probe.ts` prueba la conexión y lista modelos, `presets.ts` el catálogo), `api.ts` (`withAuth`, `parseBody`, `apiError`), `rate-limit.ts`, `dev-guard.ts`, `version.ts`, catálogos compartidos con la UI (`channels.ts`, `agenda-connectors.ts`, `analytics.ts`, `types.ts`, `nav.ts`: grupos del menú y secciones de Ajustes según banderas y rol), marca y tema (`brand.ts`, `branding.ts`, `theme.ts`, `favicon.ts`, `pwa.ts`: 048, el manifest y los iconos de la app instalable), lo puro del menú «/» de respuestas rápidas (`respuestas-rapidas.ts`, 049), el DTO y la intercalación de notas internas (`notas.ts`, 050), el borrador por conversación en el navegador (`borradores.ts`, 051), el filtro «Por vencer» y el aviso «Vence en…» (`filtros-bandeja.ts`, 052), qué se reenvía y el gesto de deslizar (`reenvio.ts`, 059), cuándo y qué avisa el sistema y la espera de reconexión del tiempo real (`avisos-sistema.ts`, 056), el texto de los eventos del hilo y los motivos de traspaso (`eventos-hilo.ts`, 054), qué tecla es qué atajo y la conversación vecina (`atajos.ts`, 055), los temas, el tema propio, la letra, el tamaño y la densidad (`temas.ts`, 062), tiempo y dinero (`time/`, `money.ts`) |
|
||||
| `public/sw.js` | 048 — Service worker mínimo: solo contesta «Sin conexión» a una navegación sin red; no guarda nada. El manifest es `src/app/manifest.ts` y el icono, `/api/branding/app-icon` |
|
||||
| `src/components/` | React: primitivos en `ui/` (incluido `empty-state.tsx`, el estado vacío común); una carpeta por pantalla (`inbox/`, `pipeline/`, `contacts/`, `agent/`, `lab/`, `results/`, `bookings/`, `onboarding/`, `settings/`); `app-shell.tsx`, `app-nav.tsx`, `use-events.ts` (cliente SSE), `use-theme.ts` |
|
||||
| `src/app/(app)/` | Pantallas autenticadas: `onboarding` (guía de inicio: primera pantalla mientras falte un paso obligatorio o haya cerebro conectado y el agente siga apagado; `src/app/page.tsx` decide), `inbox`, `pipeline`, `contacts`, `results`, `agent`, `lab`, `bookings` (AGENDA) y `settings/{whatsapp,branding,templates,quick-replies,team,ai,calendar,ads,messenger,tiktok}`. En `(auth)/`: `login` y `register` |
|
||||
| `src/app/api/` | Route handlers: `auth/[...all]` (Better Auth) · `conversations`, `contacts`, `pipeline`, `kb`, `quick-replies` (049), `agent`, `lab`, `templates`, `analytics`, `bookings`, `calendar`, `media`, `branding`, `seed`, `onboarding/status` (sesión + organización) · `settings/*` (WhatsApp, webhook, marca, equipo, IA —`ai`, con `ai/test` y `ai/models`—, capi, zoom, google, instagram, messenger, tiktok) · `bot/*` (X-API-Key o Bearer; `bot/llm/[...ruta]` es el proxy del modelo) · `webhooks/{wa,ig,messenger,tiktok}/[webhookToken]` (públicos) · `events` (SSE) · `health` · `dev/*` (mocks, 404 en producción) |
|
||||
| `tests/` | `unit/*.test.ts` (Vitest sin base de datos: módulos puros, guardarraíles que escanean `src/`, contratos) y `e2e/*.md` (guiones por historia con criterios de aceptación) |
|
||||
| `scripts/` | `e2e-*.mjs` (arneses de los guiones), `migrate.mjs` (migrador del contenedor), `seed/demo.ts`, `reset-password.mjs` (imprime el `UPDATE`, no toca la BD), `screenshots.mjs` |
|
||||
| `drizzle/` | `0000…0025_*.sql` + `meta/` (snapshots y `_journal.json`). Se genera, nunca se edita a mano. A la imagen viajan solo los `.sql` y `_journal.json`: el migrador no abre los snapshots (`.dockerignore`) |
|
||||
| `specs/` | Specs por feature (001, 002, 003, 014–030) con sus contratos; `specs/README.md` explica qué hay y qué no |
|
||||
| `docs/` | ADR-001/002, `agenda-conectores.md`, `atribucion-capi.md`, capturas del README. (`getting-started.md`, `sdd-workflow.md`, `three-agent-architecture.md` y `mcp-setup.md` describen el starter de Claude Code, no Vocero) |
|
||||
|
||||
## Flujo de una petición: un mensaje de WhatsApp
|
||||
|
||||
1. Meta hace `POST /api/webhooks/wa/<token>` → `src/app/api/webhooks/wa/[webhookToken]/route.ts`: el segmento debe igualar `META_WEBHOOK_VERIFY_TOKEN` (si no, 404) y la firma HMAC se valida solo si hay `META_APP_SECRET` (`src/server/inbox/webhook.ts`). 047 — `recibirEvento` (`src/server/webhooks/recibir.ts`) resuelve la organización, **guarda el evento** en `webhook_event` y responde 200 (503 si no pudo guardarlo, para que Meta reintente); lo procesa en `after()` y, si falla, el barrido de `src/server/webhooks/worker.ts` lo reintenta.
|
||||
2. `processMessagesValue` en `src/server/inbox/ingest.ts`: credenciales por `phone_number_id` (`whatsapp/credentials.ts`), identidad del remitente (`inbox/identity.ts` → contacto por `wa_identity`), dedup por `wa_message_id`, adjuntos (`whatsapp/media.ts`), anuncio de origen (`attribution/referral.ts` + `store.ts`), lead en la primera etapa (`inbox/lead-activity.ts`) y `publish("message.new")`.
|
||||
3. Si hay despacho (`despachoActivo()`: `BRAIN_DISPATCH_URL` + `BOT_API_KEY`), la ingesta llama a `despacharAlCerebro` (`src/server/dispatch/encolar.ts`): con la IA activa en la conversación, sin handoff, fuera del Laboratorio y con el interruptor del Agente encendido, encola un despacho. Muestra «escribiendo…» al cliente y el worker espera `AGENT_COALESCE_MS` (o `AGENT_COALESCE_LARGO_MS` si el último mensaje es un saludo, un «ok», una foto o algo muy corto, 078), arma el evento con la ráfaga (`brains/deliver.ts`) y lo entrega firmado al cerebro. El cerebro piensa con su llave o por `POST /api/bot/llm/{ruta}` (`bot/llm-proxy.ts`, con el proveedor de Ajustes → IA o, de respaldo, `OPENROUTER_*`; un 401/402 pausa la credencial) y contesta con `POST /api/bot/messages`, que entra en el paso 4. Sin despacho, el mensaje se queda en la bandeja para una persona: el CRM no contesta solo (036).
|
||||
4. `src/server/inbox/send.ts`: rechaza conversaciones `is_test` (`sandbox_violation`) y ventana cerrada (`window_closed`, `inbox/window.ts`), consulta el canal (`channels/capabilities.ts`), llama a `graphRequest` (`src/lib/meta/client.ts`), persiste el mensaje y publica.
|
||||
5. Los `statuses` del webhook pasan por `inbox/status.ts` (nunca degradan) y salen como `message.status`.
|
||||
6. `GET /api/events` (`src/app/api/events/route.ts`) emite los eventos de la organización; `src/components/use-events.ts` los recibe y la bandeja hace catch-up con `since=`.
|
||||
|
||||
La ráfaga del despacho es lo posterior al último saliente más lo que el despacho tiene anotado como debido (`dispatch.message_ids`): lo que el cliente escribió mientras el cerebro pensaba viaja aunque ya haya una respuesta después (025). Vale igual para Instagram, Messenger y TikTok: todos los canales pasan por `ingestInboundMessage`. Sin despacho, un cerebro también puede recibir el webhook por su cuenta y conversar por `/api/bot/*` (el modo de Nea 1.x).
|
||||
|
||||
## Invariantes al modificar
|
||||
|
||||
- **Identidad del contacto**: la llave estable es `contact.wa_identity` (teléfono normalizado 521→52, `bsuid:<id>`, `ig:<id>`, `fb:<id>`, `tt:<id>`); `phone` es opcional. Nunca asumas que un contacto tiene teléfono.
|
||||
- **Alcance de organización**: `organization_id` NOT NULL en toda tabla de dominio y toda consulta construida con `scoped()` de `src/lib/db/tenant.ts`.
|
||||
- **Zod en todo input externo** (body, query, webhooks, respuestas del LLM). Un 422 lleva el detalle; la salida del modelo se extrae con tolerancia y reintentos: un hipo del proveedor nunca tumba el turno.
|
||||
- **Migraciones aditivas**: cambia `src/lib/db/schema.ts`, corre `pnpm db:generate`, revisa el SQL y súbelo con el cambio. Se aplican al arrancar el contenedor; una instalación vieja debe actualizar sin pasos manuales (si no, es versión mayor).
|
||||
- **Sandbox y ventana**: una conversación `is_test` jamás toca la API real (el sender lanza; es un guardarraíl, no un bug) y el texto libre solo sale dentro de la ventana del canal tras el último entrante: 24 h en WhatsApp, Instagram y Messenger, 48 h en TikTok. Nunca escribas «24 h» en el núcleo: pregunta `windowMsFor(channel)` (`src/server/channels/capabilities.ts`). 024 — Instagram y Messenger declaran además una ventana humana (`humanAgentWindowMs`, 7 días): quién puede escribir y con qué etiqueta lo decide `replyWindow` (`src/server/inbox/window.ts`) y lo aplica `assertReplyWindow` en el pre-vuelo del envío; la IA nunca usa la etiqueta de agente humano. El texto generado por IA sale sin formato en los canales con `textFormat: "plain"` (`src/lib/social-text.ts`, aplicado en `sendText`).
|
||||
- **Los límites de un canal se declaran, no se incrustan** (022): ventana, forma de reabrirla, longitud del texto y tope de mensajes viven en `CHANNEL_CAPABILITIES`. El envío los pregunta y falla antes de llamar a la plataforma, con un `SendError` propio (`window_closed`, `message_limit`, `text_too_long`). Igual en la agenda: una cita de prueba nunca llega a un conector.
|
||||
- **Una sola puerta por invariante**: `lead.stage_id` solo se escribe en `src/server/leads/stage-history.ts` (una prueba escanea `src/`); el tráfico a Meta solo por `src/lib/meta/client.ts`; el LLM solo por `src/lib/ai/` (el proxy `/api/bot/llm` resuelve el proveedor ahí y no interpreta el cuerpo).
|
||||
- **El CRM no contesta solo** (036): no reintroduzcas un turno dentro del proceso. Contesta el cerebro, y el interruptor `agent_profile.enabled` decide si se le despacha; encenderlo exige despacho configurado y `/health` sano (409 `sin_cerebro`).
|
||||
- **Idempotencia**: dedup por `wa_message_id` UNIQUE, estados monotónicos, seeds y migraciones re-ejecutables.
|
||||
- **Mocks** (`src/app/api/dev/*`) solo con `WA_MOCK_ENABLED=true` y fuera de producción (`src/lib/dev-guard.ts`); jamás como fallback en runtime.
|
||||
- **`/api/bot/*` y el evento de despacho son contrato público**: no cambies formas ni códigos sin versionar. Agregar una llave cabe; quitar o renombrar, no. El evento solo se arma en `armarEvento` (`src/server/brains/contract.ts`): se firma el JSON tal como sale, y `tests/unit/despacho-contrato.test.ts` fija un cuerpo y su firma byte a byte.
|
||||
- **Bandeja primero, cerebro después**: un despacho se encola solo cuando el mensaje ya está guardado. Lo que falle después no pierde el mensaje; lo deja con una persona.
|
||||
- **«Sin responder» no es «sin entregar»** (025): quien lleva el turno anota el id del entrante que lo provoca —el despacho, en `dispatch.message_ids`— y lo debe hasta que el cerebro lo reciba o una persona conteste. Un saliente del agente no salda un mensaje que no leyó; uno de una persona (`ai_generated = false`) sí. Un despacho sin mensajes se descarta, nunca se entrega.
|
||||
- **Módulos opcionales** van tras bandera, apagados por defecto, con superficie en 404 y migración aplicada igual. Nunca en una rama aparte.
|
||||
- **UI con tokens**: colores por variables de `globals.css` mapeadas en `tailwind.config.ts` (`bg-background`, `text-foreground`, `bg-primary`, `text-muted-foreground`…); nada de `text-white` ni hex sueltos salvo colores de marca de terceros. `tests/unit/contraste-temas.test.ts` mide los tokens reales en ambos temas. White-label: ningún «Vocero» cableado en la UI.
|
||||
- **`route.ts` solo exporta handlers** (`GET`, `POST`… y `dynamic`): la lógica va en `src/server/` para poder probarla; Next rechaza otros exports al construir.
|
||||
- **Secretos de canal en reposo** (030): el secreto de firma de Zernio de Instagram, Messenger y TikTok solo se escribe con `columnasDelSecreto` y se lee con `secretoDeLaFila` (`src/server/zernio/secreto-guardado.ts`); la columna `webhook_secret` es obsoleta, nada la escribe y se quita en una versión mayor. Un secreto nuevo en cualquier tabla va en columnas `*_cipher`, `*_iv`, `*_tag` con `src/lib/crypto`, nunca en claro.
|
||||
- **Credenciales nuevas**: placeholder `REEMPLAZA_...` en `.env.example` con guía inline; en producción van en la plataforma (runtime, no build).
|
||||
|
||||
## Contratos públicos
|
||||
|
||||
**`/api/bot/*`** — header `X-API-Key` (o `Authorization: Bearer`, lo que manda un SDK de OpenAI) igual a `BOT_API_KEY` (mínimo 16 caracteres; sin ella todo responde 401). 1200 llamadas por minuto autenticadas; 30 fallos por minuto por IP y luego 429. Los 409 vienen tipados: `ai_paused`, `window_closed`, `sandbox_violation`, `message_limit` (022: el canal no admite más mensajes hasta que el cliente escriba). Respeta `conversation.ai_enabled` y `handoff_at`. El contrato completo está en `docs/openapi.json` (servido en `GET /api/bot/openapi.json`).
|
||||
|
||||
| Endpoint | Para qué |
|
||||
|---|---|
|
||||
| `GET /api/bot/context?waIdentity=…` | Contacto, etapa, ficha, handoff, ventana de 24 h y (con AGENDA) citas |
|
||||
| `POST /api/bot/messages` | Responder; sale por `inbox/send.ts` marcado como IA |
|
||||
| `GET /api/bot/profile` | Perfil del agente, knowledge base, `role`, `tools` y `llm` (`{path, model}`, o `null` sin IA) |
|
||||
| `POST /api/bot/llm/{ruta}` | 036 — Proxy compatible con OpenAI hacia el proveedor de Ajustes → IA; cuerpo y respuesta tal cual. 402 `sin_credencial` sin IA, 504 `proveedor_sin_respuesta` si no contesta |
|
||||
| `PUT /api/bot/ficha` | Guardar lo que el bot descubre del lead (claves libres) |
|
||||
| `POST /api/bot/stage` | 038 — Mover al lead a una etapa abierta siguiente (`lead.nextStages` del contexto), con la herramienta `etapa` encendida. 409 `etapa_no_permitida`, `herramienta_apagada`, `ai_paused` |
|
||||
| `POST /api/bot/handoff` | Devolver la conversación a un humano |
|
||||
| `POST /api/bot/typing` | Marcar leído y «escribiendo…» |
|
||||
| `GET /api/bot/media/{mediaId}` | Descargar un adjunto entrante sin tocar Meta |
|
||||
| `POST /api/bot/reset` | Reiniciar una conversación de pruebas |
|
||||
| `GET /api/bot/availability` | Con AGENDA: huecos para ofrecer (quedan registrados como ofrecidos) |
|
||||
| `POST` · `PATCH /api/bot/bookings` | Con AGENDA: reservar (201) o mover (200) solo un hueco ofrecido |
|
||||
|
||||
Documentación: README («Tu agente al lado del CRM»), `docs/migrar-a-2.0.md`, guion `tests/e2e/us-bot-api.md`, pruebas `tests/unit/bot-*.test.ts` y, para la agenda, `specs/015-motor-agenda-universal/contracts/agenda.md`.
|
||||
|
||||
**Despacho (CRM → cerebro)** — con `BRAIN_DISPATCH_URL`, un `POST` firmado (`X-Vocero-Signature: sha256=<HMAC-SHA256 del cuerpo crudo con BOT_API_KEY>`, `X-Vocero-Dispatch-Id`, `X-Vocero-Organization`) con la ráfaga de la conversación: `dispatchId`, `organization`, `conversation` (`channel`, ventana), `contact` (`identity`) y `messages`. 2xx = recibido; 429 y 5xx se reintentan (tres intentos); otro 4xx no, y la conversación pasa a un humano (`handoff_reason = error`). `messages` nunca viaja vacío, y un mensaje puede ser anterior a la última respuesta del cerebro (025). Contrato en `specs/021-despacho-estandar/contracts/despacho.md`, guion `tests/e2e/us-despacho.md`, arnés `scripts/e2e-despacho.mjs`.
|
||||
|
||||
**Webhooks de entrada** — `GET`/`POST /api/webhooks/wa/[token]` (contrato en `specs/001-vocero-core/contracts/webhook.md`); `/api/webhooks/ig/[token]` y `/api/webhooks/messenger/[token]` aceptan Meta o Zernio por la misma URL y existen solo con su canal en `CHANNELS` (specs 014 y 017); `/api/webhooks/tiktok/[token]` acepta solo Zernio (spec 022). Un evento de Zernio se reparte por plataforma llegue a cuál de las tres llegue, y su firma se verifica en `isAuthenticZernioDelivery` (`src/server/zernio/dispatch.ts`): vale cualquier secreto de Zernio de la organización, o el del webhook que Zernio tiene hacia esta instancia. Tras validar, el evento se guarda y se responde 200; el procesamiento es asíncrono y se reintenta si falla. 047 — Solo si no se pudo guardar se responde 503, para que la fuente reintente (enmienda en `specs/001-vocero-core/contracts/webhook.md`).
|
||||
|
||||
**`GET /api/health`** — `{"ok":true,"version":"X.Y.Z","commit":"…","commitVerified":true|false,"features":{"agenda":bool,"channels":["whatsapp",…],"atribucion":bool,"media":"disco"|"bucket"},"mediaWritable":bool,"webhooks":{"pendientes":n,"agotados":n}|null}`; 503 `db_unavailable` sin base. 047 — `webhooks` cuenta los eventos de entrada que no han entrado (en reintento y agotados); no baja `ok`. `features` sale de las mismas banderas que deciden los 404 (`AGENDA`, `CHANNELS`, `ATRIBUCION`) y de `MEDIA_STORE`; `mediaWritable: false` no baja `ok` ni el código. **`GET /api/events`** — SSE autenticado por sesión (`specs/001-vocero-core/contracts/sse.md`). La API interna (`specs/001-vocero-core/contracts/api.md`) no es contrato público: la consume solo la UI de este repo.
|
||||
|
||||
## Cómo contribuir
|
||||
|
||||
1. Rama desde `main` (`feat/…`, `fix/…`, `docs/…`, `chore/…`) y PR contra `main`. El autor del proyecto hace los merges.
|
||||
2. Antes de abrir el PR: `pnpm typecheck && pnpm lint && pnpm test && pnpm build`. El CI (`.github/workflows/ci.yml`) corre esos cuatro gates en dos configuraciones, banderas apagadas y `CHANNELS` + `AGENDA` encendidas; `imagen.yml` construye la imagen Docker en cada PR.
|
||||
3. Comportamiento observable nuevo: amplía o escribe su guion en `tests/e2e/` y, si se puede, su arnés en `scripts/e2e-*.mjs`; córrelo contra la app con mocks (`WA_MOCK_ENABLED=true`, `META_GRAPH_BASE_URL` → `/api/dev/wa-mock/graph`, `OPENROUTER_BASE_URL` → `/api/dev/ai-mock`, `BOT_API_KEY`; receta en `specs/001-vocero-core/quickstart.md`). Prueba también el camino infeliz.
|
||||
4. Specs (`specs/`): si tocas el modelo de datos o un contrato publicado, ciclo completo en `specs/NNN-nombre/`; comportamiento nuevo sin eso, un `spec.md` ligero; arreglos, refactors y dependencias quedan exentos (Principio VI de la constitución).
|
||||
5. Versión y release: sube `version` en `package.json`, el default de `VOCERO_CRM_VERSION` en `docker-compose.yml` (`tests/unit/version.test.ts` exige que coincidan) y la etiqueta de la imagen en `render.yaml`, `fly.toml` y `railway.toml` (`tests/unit/manifests-plataformas.test.ts`), añade la entrada en `CHANGELOG.md` con su «Actualizar desde…» y actualiza la etiqueta de la imagen en `INSTALL-IA.md`. El tag `vX.Y.Z` publica la imagen.
|
||||
6. Dependencias: `pnpm install --frozen-lockfile` debe pasar; un tercero nuevo en el núcleo necesita justificación constitucional (Principio II).
|
||||
|
||||
Las instrucciones específicas de Claude Code están en `CLAUDE.md`.
|
||||
+1092
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,176 @@
|
||||
# Vocero CRM — Guía para Claude
|
||||
|
||||
Lee primero [AGENTS.md](AGENTS.md): el mapa del código y las reglas de
|
||||
modificación viven ahí; este archivo solo añade lo específico de Claude Code.
|
||||
|
||||
Vocero es un CRM de WhatsApp open source (MIT), self-hosted, con el perfil y el
|
||||
conocimiento del agente y un Laboratorio de auto-evaluación. Desde la 2.0 no
|
||||
trae agente: contesta un cerebro conectado al lado (Nea u otro). Una
|
||||
instancia = un negocio. Este archivo guía a Claude Code (u otro asistente)
|
||||
para operar y **modificar** este repositorio —
|
||||
el caso típico: una agencia adaptando Vocero para un cliente.
|
||||
|
||||
## Stack
|
||||
|
||||
**Next.js 15 (App Router) + React 19** en monolito · TypeScript estricto
|
||||
(`strict` + `noUncheckedIndexedAccess`) · Tailwind CSS (sistema de diseño de la
|
||||
marca Vocero, el mismo de vocerocrm.com: tokens en `src/app/globals.css`, tema
|
||||
claro/oscuro, acento white-label por defecto `#0d5bff`, fuentes Archivo +
|
||||
Instrument Serif + IBM Plex Mono self-hosted vía `next/font`; el logo vive en
|
||||
`src/lib/brand.ts` y se dibuja con `src/components/brand-mark.tsx`) ·
|
||||
**PostgreSQL + Drizzle ORM** (migraciones versionadas en
|
||||
`drizzle/`, aplicadas al ARRANCAR el contenedor) · **Better Auth** + plugin
|
||||
organization · **Zod** en todo input externo · nanoid con prefijos (`ct_`,
|
||||
`cv_`, `msg_`…) · pnpm · Vitest (unit) + guiones E2E en `tests/e2e/`
|
||||
conducidos con Playwright · Docker multi-stage (standalone, healthcheck
|
||||
`/api/health`) · deploy en Coolify (Ruta A) o docker compose + Caddy (Ruta B).
|
||||
|
||||
Tiempo real por **SSE** (`/api/events`): heartbeat `: ping` ~25s, headers
|
||||
anti-buffering, catch-up por refetch con `since=`. Sin WebSockets, sin colas
|
||||
externas: el trabajo en segundo plano (el despacho al cerebro, el Laboratorio)
|
||||
es in-process.
|
||||
|
||||
## Mapa del código (fronteras de modificación)
|
||||
|
||||
| Quieres cambiar… | Toca… |
|
||||
|---|---|
|
||||
| El proveedor LLM (juez del Laboratorio y proxy del cerebro) | `src/lib/ai/` (adaptador OpenRouter-compatible, `chatJson<T>`; `provider.ts` resuelve Ajustes → IA o `OPENROUTER_*`) |
|
||||
| El comportamiento del agente | No vive aquí: el CRM no trae agente (036). Lo que el agente lee —perfil, conocimiento (`renderKb` en `src/server/ai/prompts.ts`), `role`, `tools`, `llm`— sale por `src/server/bot/profile.ts`; lo demás es del cerebro (Nea) |
|
||||
| Cómo piensa el cerebro con la llave del CRM | `src/server/bot/llm-proxy.ts` + `src/app/api/bot/llm/[...ruta]/route.ts` |
|
||||
| Las personas o el juez del Laboratorio | `src/server/lab/personas.ts` · `src/server/lab/judge.ts` |
|
||||
| El canal WhatsApp (Graph API) | `src/lib/meta/` (cliente único) + `src/server/whatsapp/` |
|
||||
| Los canales opcionales (Instagram, Messenger; ADR-001) | `src/lib/channels.ts` (catálogo) · `src/server/channels/` (capacidades y bandera `CHANNELS`) · `src/server/instagram/` · `src/server/messenger/` · `src/server/zernio/` (transporte y firma de la API unificada, compartido) |
|
||||
| Campos/tablas | `src/lib/db/schema.ts` → `pnpm db:generate` → migración nueva en `drizzle/` |
|
||||
| La ingesta/envío de mensajes | `src/server/inbox/` (ingest idempotente, send con guard de sandbox, ventana 24h) |
|
||||
| Cómo se identifica a un contacto | `src/server/inbox/identity.ts` (teléfono normalizado o `bsuid:<id>`) |
|
||||
| Conectar el cerebro (Nea o el tuyo) | despacho: `src/server/dispatch/encolar.ts` (`despacharAlCerebro`) + red de seguridad y turno superado (075): `src/server/dispatch/red-de-seguridad.ts` + `src/server/brains/` (`config.ts`: `despachoActivo`, `urlSaludCerebro`) · `src/app/api/bot/*` + `src/server/bot/auth.ts` (X-API-Key o Bearer) · contrato en `docs/openapi.json` · quién responde (avisos `sin_cerebro`, `apagado`): `src/server/bot/status.ts` + `GET /api/agent/brain-status` |
|
||||
| La API pública v1, el MCP y su OAuth | `src/server/api-v1/` (bandera `API_V1`, llaves, `withApiKey`, `openapi.json`) · `src/server/mcp/` · `src/server/oauth/` · handlers compartidos con la UI en `src/server/http/` · guía: [docs/api-v1.md](docs/api-v1.md) · spec [069](specs/069-api-mcp/spec.md) |
|
||||
| La agenda (horarios, huecos, citas) | `src/server/agenda/` — detrás de la bandera `AGENDA` (`flag.ts`) |
|
||||
| Cómo se entrega la reunión (Zoom, Meet…) | `src/server/agenda/connectors/` + catálogo en `src/lib/agenda-connectors.ts` · guía: [docs/agenda-conectores.md](docs/agenda-conectores.md) |
|
||||
| De qué anuncio llegó cada conversación (siempre visible) | `src/server/attribution/referral.ts` (normalización) · `creativo.ts` (copia de la imagen, solo hosts de Meta) · `store.ts` · tarjeta en `src/components/anuncio-origen.tsx` |
|
||||
| Los números de Resultados (ventas, agente, origen y anuncios, higiene) | `src/server/analytics/` (un módulo por sección; periodo en la zona del negocio en `period.ts`; exclusión del Laboratorio en `shared.ts`) · contratos y tasas en `src/lib/analytics.ts` · UI en `src/components/results/` · spec [019](specs/019-resultados/spec.md) |
|
||||
| La atribución de anuncios y el reporte a Meta | `src/server/attribution/` — el `ctwa_clid`, la CAPI y Ajustes → Anuncios detrás de la bandera `ATRIBUCION` (`flag.ts`) + `src/lib/meta/capi.ts` · guía: [docs/atribucion-capi.md](docs/atribucion-capi.md) |
|
||||
| UI | `src/components/` + `src/app/(app)/` |
|
||||
|
||||
Los mocks del entorno de pruebas viven en `src/app/api/dev/` (wa-mock +
|
||||
ai-mock) tras un gate único (`src/lib/dev-guard.ts`): 404 incondicional en
|
||||
producción.
|
||||
|
||||
**Identidad de contacto**: Meta está migrando de teléfono a Business-Scoped
|
||||
User IDs, así que `from` puede no venir. La llave estable es
|
||||
`contact.wa_identity` (teléfono normalizado 521→52, o `bsuid:<id>`); `phone` es
|
||||
un atributo OPCIONAL. Nunca asumas que un contacto tiene teléfono.
|
||||
|
||||
**El cerebro**: el CRM no contesta solo. Con `BRAIN_DISPATCH_URL` +
|
||||
`BOT_API_KEY` y el interruptor del Agente encendido (`agent_profile.enabled`;
|
||||
encenderlo exige el `/health` del cerebro sano, si no 409 `sin_cerebro`), le
|
||||
despacha cada ráfaga al cerebro, que conversa por `/api/bot/*` sin que el
|
||||
token de WhatsApp salga del CRM: responder, marcar leído + "escribiendo…",
|
||||
descargar adjuntos, reiniciar la conversación de pruebas, y pensar por
|
||||
`/api/bot/llm` con la llave de Ajustes → IA (la llave no sale del CRM).
|
||||
Respeta `conversation.ai_enabled`/`handoff_at`. Sin la key, esa superficie
|
||||
responde 401 y el CRM funciona igual, como bandeja manual. No reintroduzcas
|
||||
un turno dentro del proceso.
|
||||
|
||||
## Reglas de la constitución (no negociables)
|
||||
|
||||
Ver [.specify/memory/constitution.md](.specify/memory/constitution.md).
|
||||
|
||||
- **Soberanía (II, endurecida — 1.4.0)**: el NÚCLEO depende solo de WhatsApp
|
||||
Cloud API + proveedor LLM OpenRouter-compatible opcional; prohibido meterle
|
||||
S3/R2, email, billing u otros terceros. Un servicio de terceros solo entra
|
||||
como **conector opcional**: apagado por defecto tras bandera (patrón
|
||||
ADR-001), aislado tras adaptador con contrato público, con camino sin
|
||||
dependencia externa y degradación definida (su fallo jamás bloquea la
|
||||
operación core), credenciales del negocio cifradas, y CI que lo prueba
|
||||
apagado y encendido. Auth y BD self-hosted.
|
||||
- **Seguridad (I)**: secretos cifrados en reposo (AES-256-GCM, `lib/crypto`);
|
||||
jamás al cliente ni a logs. El token de WhatsApp solo muestra sus últimos 4.
|
||||
- **Multi-tenancy (III)**: `organization_id` NOT NULL en toda tabla de dominio;
|
||||
toda query pasa por `scoped()` de `src/lib/db/tenant.ts`.
|
||||
- **Idempotencia (IV)**: webhooks dedup por `wa_message_id` UNIQUE; estados
|
||||
monotónicos; seeds y migraciones re-ejecutables.
|
||||
- **Sandbox del Laboratorio**: las conversaciones `is_test` JAMÁS tocan la API
|
||||
real — el sender lanza excepción (no lo "arregles": es un guardrail). Lo
|
||||
mismo vale para la agenda: una cita de prueba nunca llega a un conector.
|
||||
- **Módulos opcionales (015, 016)**: lo que no usa toda instancia va detrás de una
|
||||
bandera de despliegue, apagado por defecto, con su superficie en 404 y la
|
||||
migración aplicada igual. Nunca en una rama aparte
|
||||
([ADR-001](docs/adr-001-canales-opcionales.md),
|
||||
[ADR-002](docs/adr-002-conectores-de-agenda.md)).
|
||||
|
||||
## Variables de entorno
|
||||
|
||||
`pnpm init-env` crea el `.env` con los secretos ya generados y `pnpm doctor`
|
||||
lo valida con el mismo esquema del arranque (`safeParseEnv` en
|
||||
`src/lib/env.ts`), prueba la base, `MEDIA_DIR` y el token de WhatsApp.
|
||||
Ver `.env.example` (cada una con guía inline). Las claves: `APP_BASE_URL`,
|
||||
`DATABASE_URL`, `BETTER_AUTH_SECRET`, `ENCRYPTION_KEY` (32 bytes base64),
|
||||
`META_WEBHOOK_VERIFY_TOKEN` (segmento secreto del webhook), `META_APP_SECRET`
|
||||
(opcional, firma). La IA se configura desde la app (Ajustes → IA: proveedor,
|
||||
modelo y llave cifrada, con «Probar conexión»); las variables solo son el
|
||||
respaldo mientras no haya nada guardado ahí:
|
||||
|
||||
```bash
|
||||
OPENROUTER_API_TOKEN=sk-or-...
|
||||
OPENROUTER_MODEL=anthropic/claude-sonnet-4.5
|
||||
OPENROUTER_JUDGE_MODEL=anthropic/claude-haiku-4.5 # opcional: juez más barato
|
||||
```
|
||||
|
||||
Para el self-test local existe además el modo de pruebas interno (mocks) —
|
||||
ver `specs/001-vocero-core/quickstart.md`. Nunca actives mocks en producción.
|
||||
|
||||
## Manejo de credenciales (obligatorio)
|
||||
|
||||
Cuando una feature necesite una variable/credencial nueva: (1) agrégala a
|
||||
`.env` como placeholder `REEMPLAZA_...` (append), (2) deja guía inline `#` de
|
||||
cómo obtenerla, (3) resume en el chat y sigue. `.env` está gitignored; para
|
||||
deploy, las vars van también en la plataforma de hosting (runtime, no build).
|
||||
|
||||
## Definición de Hecho REFORZADA (obligatoria)
|
||||
|
||||
"Typecheck + lint + build (+ tests)" es el piso, NO el techo. Una feature no
|
||||
está "Hecha" hasta correr el **self-test de COMPORTAMIENTO de punta a punta**
|
||||
(Playwright + mocks: `WA_MOCK_ENABLED=true`, `META_GRAPH_BASE_URL` → wa-mock,
|
||||
`OPENROUTER_BASE_URL` → ai-mock) y dejarlo verde: flujo real como usuario,
|
||||
resultado observable, y el camino infeliz degradando sin colgarse. Prohibido
|
||||
delegar la prueba al usuario. Si algo depende de un LLM/proveedor externo,
|
||||
todo turno tolera formato inesperado con extracción robusta + reintentos — un
|
||||
hipo del proveedor nunca tumba el turno. Al detectar un fallo: diagnostica,
|
||||
corrige y re-verifica tú mismo hasta verde (loop de auto-corrección).
|
||||
|
||||
Gate técnico:
|
||||
|
||||
```bash
|
||||
pnpm typecheck && pnpm lint && pnpm build && pnpm test
|
||||
```
|
||||
|
||||
Guiones E2E por historia en `tests/e2e/*.md`. Parte de ellos ya están
|
||||
automatizados: con la app viva y los mocks encendidos, `pnpm test:e2e`
|
||||
(`scripts/e2e-selftest.mjs`) los conduce contra la app real y sale distinto de
|
||||
cero si algo falla. Al agregar una historia, extiende el arnés en vez de dejar
|
||||
solo el `.md`.
|
||||
|
||||
## Modo Objetivo — Loop SDD
|
||||
|
||||
Cuando el dueño da una META (no prompts paso a paso): Discover → Plan →
|
||||
Execute → Verify → Iterate, de forma autónoma, volviendo solo con el objetivo
|
||||
verificado en vivo o con un bloqueo real (decisión de producto, credenciales,
|
||||
acción irreversible/costosa). Agrupa TODAS las preguntas bloqueantes al inicio.
|
||||
El estado durable son los artefactos SDD en `specs/` (spec/plan/tasks) —
|
||||
manténlos al día. Invocable como `/loop-sdd <objetivo>`.
|
||||
|
||||
## Memoria persistente
|
||||
|
||||
Memoria de archivos en `memory/` (índice `memory/MEMORY.md`, cargado por
|
||||
sesión). Persiste decisiones, gotchas y correcciones; no dupliques lo que el
|
||||
repo ya registra. Los subagentes con `memory: project` usan
|
||||
`.claude/agent-memory/`.
|
||||
|
||||
## Arquitectura de agentes
|
||||
|
||||
1. **Orquestador** = la sesión principal de Claude Code (este CLAUDE.md + skill
|
||||
`loop-sdd`).
|
||||
2. **Subagentes** (`.claude/agents/`): `deploy-ops` (deploy/logs/healthchecks,
|
||||
no escribe código de app) · `public-site-builder` (páginas públicas/legales
|
||||
y config de paneles externos).
|
||||
@@ -0,0 +1,9 @@
|
||||
# HTTPS automático con el dominio de la variable DOMAIN.
|
||||
# Para pruebas locales usa DOMAIN=localhost (certificado interno).
|
||||
{$DOMAIN} {
|
||||
reverse_proxy app:3000 {
|
||||
# SSE: sin buffering ni timeouts cortos en el proxy
|
||||
flush_interval -1
|
||||
}
|
||||
encode gzip
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
# Despliegue del CRM (marca blanca)
|
||||
|
||||
Una instancia = un negocio. Cada despliegue se configura entero desde su `.env`:
|
||||
quién es el dueño, cómo se llama el CRM, su color, su moneda y a qué se dedica
|
||||
el negocio. Lo demás (logo, favicon, catálogo, agente) se termina en la app.
|
||||
|
||||
## 1. Identidad del negocio (`.env`)
|
||||
|
||||
| Variable | Para qué |
|
||||
|---|---|
|
||||
| `APP_BASE_URL` | URL pública con https (la del dominio o proxy). |
|
||||
| `SUPERADMIN_EMAIL` / `SUPERADMIN_PASSWORD` | El dueño. Se crea al arrancar; cambiar la contraseña aquí y reiniciar la sincroniza. |
|
||||
| `SUPERADMIN_NAME` | Nombre del usuario dueño. |
|
||||
| `SUPERADMIN_ORG_NAME` | Nombre del negocio (si falta, usa `BRAND_NAME` o «Mi negocio»). |
|
||||
| `BRAND_NAME` | Nombre del CRM en la barra, el login y la pestaña. |
|
||||
| `BRAND_ACCENT` | Color de acento, hex de 6 dígitos (p. ej. `#009c98`). |
|
||||
| `BRAND_CURRENCY` | Moneda ISO (`MXN`, `USD`, `COP`, `EUR`…). |
|
||||
| `BUSINESS_DESCRIPTION` | A qué se dedica: arma el saludo y las instrucciones iniciales del agente. |
|
||||
|
||||
`BRAND_*` se aplica **una sola vez**, al primer arranque. Después todo se cambia
|
||||
en **Ajustes → Marca** y el `.env` ya no lo pisa. Igual con el perfil del
|
||||
agente: solo se llena si está vacío.
|
||||
|
||||
Secretos (genera uno distinto por instancia y no los reutilices):
|
||||
|
||||
```bash
|
||||
openssl rand -hex 24 # POSTGRES_PASSWORD, META_WEBHOOK_VERIFY_TOKEN
|
||||
openssl rand -base64 32 # BETTER_AUTH_SECRET, ENCRYPTION_KEY
|
||||
openssl rand -hex 32 # BOT_API_KEY
|
||||
```
|
||||
|
||||
`ENCRYPTION_KEY` no se cambia nunca: con otra, los tokens guardados ya no se
|
||||
leen. `POSTGRES_PASSWORD` solo cuenta la primera vez que arranca la base.
|
||||
|
||||
## 2. Imagen
|
||||
|
||||
La CI (`.github/workflows/imagen.yml`) publica `ghcr.io/<dueño>/<repo>:latest`
|
||||
en cada push a `main`. El compose la baja (`CRM_IMAGE`, `CRM_TAG`); si no puede,
|
||||
la construye desde `CRM_BUILD_CONTEXT` (por defecto `.`, el clon).
|
||||
|
||||
- Paquete **privado** en GHCR: en el servidor, `docker login ghcr.io` con tu
|
||||
usuario de GitHub y un token con `read:packages` (o hazlo público en
|
||||
GitHub → Packages → Package settings).
|
||||
- Sin registro: `CRM_BUILD_CONTEXT=https://USUARIO:TOKEN@github.com/USUARIO/REPO.git#main`
|
||||
y `docker compose up -d --build`.
|
||||
|
||||
## 3. Escenarios
|
||||
|
||||
### A. Servidor con Docker y HTTPS automático (Caddy)
|
||||
|
||||
```bash
|
||||
git clone https://github.com/USUARIO/REPO.git crm && cd crm
|
||||
cp .env.example .env # rellena lo de la sección 1, DOMAIN y APP_BASE_URL
|
||||
docker compose --profile caddy up -d
|
||||
```
|
||||
|
||||
### B. Panel con reverse proxy (aaPanel, Nginx, Plesk…)
|
||||
|
||||
Usa `deploy/aapanel/docker-compose.yml` y `deploy/aapanel/env.example`
|
||||
(autocontenidos: se pegan tal cual en «Add compose»). La app queda solo en
|
||||
`127.0.0.1:PORT`; el proxy del sitio apunta a `http://127.0.0.1:PORT` con
|
||||
`$host` como dominio enviado.
|
||||
|
||||
En el sitio del proxy:
|
||||
- **SSL** (Let's Encrypt) y forzar HTTPS: Meta exige HTTPS para el webhook.
|
||||
- `client_max_body_size 25m;` para subir adjuntos.
|
||||
- Si la bandeja tarda en actualizarse: `proxy_buffering off;` y
|
||||
`proxy_read_timeout 3600s;` (la app ya manda `X-Accel-Buffering: no`).
|
||||
|
||||
### C. Coolify, Render o Fly
|
||||
|
||||
`docker-compose.yml`, `render.yaml` y `fly.toml` ya traen los módulos
|
||||
encendidos; añade en la plataforma las variables de la sección 1.
|
||||
|
||||
### Varias instancias en el mismo servidor
|
||||
|
||||
Una carpeta (o un compose en el panel) por negocio, cada una con su `.env`, su
|
||||
`PORT` distinto (3001, 3002…) y su propio dominio en el proxy. Compose aísla los
|
||||
volúmenes por nombre de proyecto: no compartas carpeta ni nombre de proyecto.
|
||||
|
||||
## 4. Actualizar sin tocar la base
|
||||
|
||||
```bash
|
||||
./scripts/update-live.sh # imagen publicada; si no, build
|
||||
./scripts/update-live.sh --build # fuerza construir desde el clon
|
||||
```
|
||||
|
||||
En un panel: `docker compose pull app && docker compose up -d app` (o
|
||||
`up -d --build app` si construyes). Las migraciones corren solas al arrancar.
|
||||
|
||||
Automático: `docker compose --profile autoupdate up -d` levanta Watchtower, que
|
||||
solo recrea `app` (para un registro privado, `REGISTRY_USER` y
|
||||
`REGISTRY_TOKEN`).
|
||||
|
||||
## 5. Respaldos
|
||||
|
||||
**Ajustes → Respaldos** descarga un `.json.gz` con las tablas de la
|
||||
organización. Respaldo completo del servidor:
|
||||
|
||||
```bash
|
||||
docker compose exec postgres pg_dump -U postgres vocero | gzip > respaldo-$(date +%F).sql.gz
|
||||
```
|
||||
|
||||
Los adjuntos y el logo viven en el volumen `/data` de `app`: respáldalo aparte.
|
||||
|
||||
## 6. Notas
|
||||
|
||||
- **Orígenes confiables (login):** el host de `APP_BASE_URL`, `x-forwarded-host`
|
||||
y `host`, en http y https y en los puertos 3000 y 3003. Un `origin` ajeno no se
|
||||
vuelve confiable (CSRF).
|
||||
- **Simular cliente** (Bandeja) solo en conversaciones de prueba: en una real
|
||||
responde 409 `solo_pruebas`.
|
||||
- **Catálogo de ejemplo** (Servicios y Precios): un botón carga servicios de
|
||||
muestra (rótulos, impresión y marketing) para editarlos; es opcional.
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
# ============================================================
|
||||
# Vocero CRM — imagen multi-etapa (Next.js standalone + Node 22)
|
||||
# Los secretos NO se necesitan en build: llegan en runtime.
|
||||
# ============================================================
|
||||
|
||||
FROM node:22.23.4-alpine AS deps
|
||||
WORKDIR /app
|
||||
RUN corepack enable
|
||||
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
|
||||
RUN pnpm install --frozen-lockfile
|
||||
|
||||
FROM node:22.23.4-alpine AS builder
|
||||
WORKDIR /app
|
||||
RUN corepack enable
|
||||
COPY --from=deps /app/node_modules ./node_modules
|
||||
COPY . .
|
||||
ENV NEXT_TELEMETRY_DISABLED=1
|
||||
# Commit del que sale la imagen, para que la app pueda decir qué está corriendo.
|
||||
# Tiene que llegar como build arg en CADA despliegue; con docker compose,
|
||||
# `--build-arg SOURCE_COMMIT=$(git rev-parse HEAD)`. Si falta nunca es un error
|
||||
# de build: la app enseña solo la versión, o el SOURCE_COMMIT que encuentre en
|
||||
# el entorno al arrancar, marcado como no verificado.
|
||||
ARG SOURCE_COMMIT=""
|
||||
ENV SOURCE_COMMIT=$SOURCE_COMMIT
|
||||
RUN pnpm build
|
||||
# migrate.mjs autocontenido (drizzle-orm + postgres bundleados)
|
||||
RUN pnpm exec esbuild scripts/migrate.mjs --bundle --platform=node \
|
||||
--format=esm --outfile=migrate.bundle.mjs \
|
||||
--banner:js="import { createRequire } from 'module'; const require = createRequire(import.meta.url);"
|
||||
# semilla idempotente del superadmin (corre en cada arranque).
|
||||
RUN pnpm exec esbuild scripts/seed-superadmin.ts --bundle --platform=node --format=esm --outfile=seed-superadmin.bundle.mjs --alias:@=./src --banner:js="import { createRequire } from 'module'; const require = createRequire(import.meta.url);"
|
||||
RUN pnpm exec esbuild scripts/seed/demo.ts --bundle --platform=node \
|
||||
--format=esm --outfile=seed-demo.bundle.mjs --alias:@=./src \
|
||||
--banner:js="import { createRequire } from 'module'; const require = createRequire(import.meta.url);"
|
||||
|
||||
FROM node:22.23.4-alpine AS runner
|
||||
WORKDIR /app
|
||||
ENV NODE_ENV=production
|
||||
ENV NEXT_TELEMETRY_DISABLED=1
|
||||
# 008: adjuntos, logo e icono viven en /data (el volumen de la instancia), no
|
||||
# en /app, que es de root: el default de la app (./.dev-media) es solo para
|
||||
# desarrollo local. No se define en la plataforma: basta montar /data.
|
||||
ENV MEDIA_DIR=/data/media
|
||||
# su-exec: el entrypoint arranca como root SOLO para dejar /data escribible y
|
||||
# baja a `vocero` antes de correr la app (idea de #40).
|
||||
RUN apk add --no-cache su-exec
|
||||
RUN addgroup -S vocero && adduser -S vocero -G vocero
|
||||
# El punto de montaje nace de `vocero`: un volumen nombrado nuevo hereda ese
|
||||
# dueño al montarse vacío. Los que llegan como root (Coolify, Railway, un bind
|
||||
# mount) los arregla vocero-entrypoint.sh en cada arranque.
|
||||
RUN mkdir -p /data/media && chown -R vocero:vocero /data
|
||||
|
||||
COPY --from=builder --chown=vocero:vocero /app/.next/standalone ./
|
||||
COPY --from=builder --chown=vocero:vocero /app/.next/static ./.next/static
|
||||
COPY --from=builder --chown=vocero:vocero /app/public ./public
|
||||
COPY --from=builder --chown=vocero:vocero /app/migrate.bundle.mjs ./migrate.mjs
|
||||
COPY --from=builder --chown=vocero:vocero /app/seed-demo.bundle.mjs ./seed-demo.mjs
|
||||
COPY --from=builder --chown=vocero:vocero /app/seed-superadmin.bundle.mjs ./seed-superadmin.mjs
|
||||
COPY --from=builder --chown=vocero:vocero /app/drizzle ./drizzle
|
||||
# Nombre propio a propósito: la imagen de node ya trae su docker-entrypoint.sh
|
||||
# (antepone `node` si el primer argumento no es un comando) y el nuestro le
|
||||
# pasa la posta en vez de pisarlo.
|
||||
COPY vocero-entrypoint.sh /usr/local/bin/vocero-entrypoint.sh
|
||||
# sed: un checkout de Windows con autocrlf lo deja en CRLF y `sh` no lo corre.
|
||||
RUN sed -i 's/\r$//' /usr/local/bin/vocero-entrypoint.sh \
|
||||
&& chmod 755 /usr/local/bin/vocero-entrypoint.sh
|
||||
|
||||
# Sin `USER vocero`: el entrypoint baja a `vocero` con su-exec. Arrancado con
|
||||
# `--user`, también funciona (y avisa si /data no es escribible).
|
||||
EXPOSE 3000
|
||||
ENV PORT=3000
|
||||
ENV HOSTNAME=0.0.0.0
|
||||
|
||||
# start-period amplio: cubre las migraciones del arranque
|
||||
HEALTHCHECK --interval=15s --timeout=5s --start-period=40s --retries=5 \
|
||||
CMD wget -q -O /dev/null http://127.0.0.1:3000/api/health || exit 1
|
||||
|
||||
ENTRYPOINT ["vocero-entrypoint.sh"]
|
||||
# `start` (lo resuelve vocero-entrypoint.sh): migraciones →
|
||||
# semilla del superadmin (idempotente; si falla, avisa y sigue) → servidor.
|
||||
CMD ["start"]
|
||||
+203
@@ -0,0 +1,203 @@
|
||||
# INSTALL-IA.md — Instalación de Vocero CRM guiada por IA
|
||||
|
||||
> **Para el asistente de IA** (Claude Code u otro agente con acceso a
|
||||
> herramientas): este archivo ES tu guion de instalación. Síguelo de arriba a
|
||||
> abajo y NO le pidas al usuario nada que puedas hacer o generar tú.
|
||||
>
|
||||
> **Para el humano**: abre tu asistente de IA (p. ej. Claude Code con el MCP de
|
||||
> Coolify configurado) en una carpeta vacía, pégale este archivo (o su URL) y
|
||||
> responde las 3 preguntas que te hará. **No necesitas clonar el repo ni crear
|
||||
> ningún otro archivo**: Coolify descarga la imagen publicada y los secretos
|
||||
> viven como variables de la plataforma.
|
||||
|
||||
**Imagen**: `ghcr.io/kevinrivm/vocero-crm:2.12.2` (GitHub Container Registry,
|
||||
una etiqueta por versión, `linux/amd64`, escucha en el puerto `3000`).
|
||||
|
||||
**Repositorio**: `https://github.com/kevinrivm/vocero-crm` (público, rama `main`,
|
||||
`Dockerfile` en la raíz). Hace falta para la Ruta B y para construir desde el
|
||||
código.
|
||||
|
||||
**Render, Fly o Railway**: este guion es para Coolify y docker compose. Para
|
||||
esas plataformas hay un manifest por cada una en la raíz del repo
|
||||
(`render.yaml`, `fly.toml`, `railway.toml`), con lo que queda a mano escrito
|
||||
dentro: README → «Instalación» → «Otras plataformas».
|
||||
|
||||
## Reglas para el asistente
|
||||
|
||||
1. Pregunta al usuario ÚNICAMENTE estas tres cosas, en un solo mensaje:
|
||||
- **Dominio** donde vivirá el CRM (obligatorio, ej. `crm.sunegocio.com`).
|
||||
Debe apuntar ya a la IP del VPS (registro A).
|
||||
- **Token de OpenRouter** (opcional — sin él, el CRM funciona completo
|
||||
como bandeja manual; es con lo que piensa el agente y el juez del
|
||||
Laboratorio, y se puede agregar después).
|
||||
- **Ruta A o B**: A = el VPS tiene panel Coolify · B = el VPS solo tiene
|
||||
Docker.
|
||||
2. **Genera tú mismo todos los secretos** (no se los pidas). En la Ruta B,
|
||||
`pnpm init-env --domain <dominio>` crea el `.env` con todos ya generados y
|
||||
`pnpm doctor` lo verifica. En la Ruta A (sin repo clonado) genéralos con:
|
||||
|
||||
```bash
|
||||
openssl rand -base64 32 # BETTER_AUTH_SECRET
|
||||
openssl rand -base64 32 # ENCRYPTION_KEY (exactamente 32 bytes base64)
|
||||
openssl rand -hex 32 # META_WEBHOOK_VERIFY_TOKEN
|
||||
openssl rand -hex 24 # POSTGRES_PASSWORD
|
||||
```
|
||||
|
||||
3. La conexión de WhatsApp NO es parte del despliegue: al terminar, dile al
|
||||
usuario que se hace desde la app. Lo mismo la IA: el proveedor, el modelo y
|
||||
la llave se pegan en **Ajustes → IA** (con «Probar conexión» y «Traer
|
||||
modelos»); las variables `OPENROUTER_*` de abajo son solo un respaldo
|
||||
opcional y lo guardado en la app manda sobre ellas.
|
||||
|
||||
## Variables de entorno (ambas rutas)
|
||||
|
||||
| Variable | Valor |
|
||||
|---|---|
|
||||
| `APP_BASE_URL` | `https://<dominio>` |
|
||||
| `DATABASE_URL` | `postgresql://postgres:<POSTGRES_PASSWORD>@<host-postgres>:5432/vocero` |
|
||||
| `POSTGRES_PASSWORD` | generado (es la de la base; la app no la lee, solo va dentro de `DATABASE_URL`) |
|
||||
| `BETTER_AUTH_SECRET` | generado |
|
||||
| `ENCRYPTION_KEY` | generado (base64, 44 caracteres) |
|
||||
| `META_WEBHOOK_VERIFY_TOKEN` | generado |
|
||||
| `META_GRAPH_API_VERSION` | `v25.0` |
|
||||
| `OPENROUTER_API_TOKEN` | opcional: solo si el usuario lo dio y quiere dejarlo en el entorno. Lo normal es configurarlo después desde la app (Ajustes → IA) |
|
||||
| `OPENROUTER_MODEL` | solo si hay token en el entorno: sugiere `anthropic/claude-sonnet-4.5` u otro a elección |
|
||||
|
||||
`DOMAIN` solo aplica en la Ruta B (para Caddy). `MEDIA_DIR` no va en la tabla
|
||||
a propósito: la imagen ya la trae (`/data/media`, dentro del volumen de `/data`).
|
||||
|
||||
Opcionales, que NO se preguntan (el usuario los agrega después; la guía de
|
||||
cada uno está en `.env.example`): `META_APP_SECRET`, `META_APP_ID` +
|
||||
`META_EMBEDDED_CONFIG_ID` (botón «Conectar con Meta»; panel de Meta en
|
||||
[`docs/embedded-signup.md`](docs/embedded-signup.md)), `BOT_API_KEY`,
|
||||
`BRAIN_DISPATCH_URL` y `BRAIN_HEALTH_URL` (un cerebro externo como Nea),
|
||||
`AGENDA=on`, `ATRIBUCION=on` y `CHANNELS`.
|
||||
|
||||
Vocero no trae agente: sin uno conectado es un CRM de bandeja manual, y eso
|
||||
es una instalación válida. Si el usuario quiere que un agente conteste (Nea),
|
||||
se instala al lado del CRM y se conecta por el despacho: el webhook de Meta se
|
||||
queda en el CRM, **nunca se mueve a Nea**. **No le pongas llave de IA a Nea**
|
||||
(`LLM_API_KEY` vacía): piensa por el CRM (`/api/bot/llm`) con la llave y el
|
||||
modelo de Ajustes → IA, así la llave se pone una sola vez, en la app. Pasos y
|
||||
variables en [`docs/migrar-a-2.0.md`](docs/migrar-a-2.0.md) («El par»); el
|
||||
contrato, en [`docs/openapi.json`](docs/openapi.json). Después, el usuario
|
||||
enciende el agente en la pantalla Agente (solo se deja con Nea en línea).
|
||||
|
||||
## Ruta A — Coolify (con el MCP de Coolify)
|
||||
|
||||
1. **Base de datos**: crea un servicio PostgreSQL 16 en el proyecto
|
||||
(`database` tipo `postgresql`), con la contraseña generada y base `vocero`.
|
||||
Anota su host interno (algo como `<uuid>:5432`).
|
||||
2. **Aplicación**: en el mismo proyecto, crea una app de tipo **Docker Image**
|
||||
con la imagen `ghcr.io/kevinrivm/vocero-crm`, la etiqueta `2.12.2`, puerto
|
||||
expuesto `3000` y el dominio del usuario con HTTPS (MCP: `application`
|
||||
con `action: create_dockerimage`, el `project_uuid`, el
|
||||
`server_uuid` y el `environment_name` del proyecto,
|
||||
`docker_registry_image_name: ghcr.io/kevinrivm/vocero-crm`,
|
||||
`docker_registry_image_tag: 2.12.2`, `ports_exposes: "3000"`,
|
||||
`domains: https://<dominio>` e `instant_deploy: false`). Coolify descarga
|
||||
la imagen: no hay repositorio, GitHub App ni deploy keys que configurar, ni
|
||||
build en el VPS. No la despliegues todavía: primero el volumen y las
|
||||
variables.
|
||||
3. **Almacenamiento persistente**: agrega a la app un volumen montado en
|
||||
**`/data`** (MCP: `storages` con `resource: application`, el `uuid` de la
|
||||
app, `action: create`, `type: persistent`, `name: vocero-data`,
|
||||
`mount_path: /data`). Ahí viven los adjuntos, el logo y el icono; la imagen
|
||||
ya trae `MEDIA_DIR=/data/media`, así que **no definas `MEDIA_DIR`**. Que
|
||||
Coolify monte el volumen como root no importa: el contenedor arranca como
|
||||
root solo para dárselo al usuario de la app y luego baja de privilegios.
|
||||
Sin este volumen la app funciona, pero esos archivos se pierden en cada
|
||||
redeploy. Opcional (037): si el dueño prefiere un bucket S3-compatible
|
||||
propio, `MEDIA_STORE=bucket` y las `MEDIA_BUCKET_*` de `.env.example`; no
|
||||
lo actives si no lo pide. El volumen sigue haciendo falta como respaldo.
|
||||
4. **Variables**: configura las variables de la tabla en la app (runtime, no
|
||||
build). `DATABASE_URL` apunta al host interno del paso 1.
|
||||
5. **Sin Pre-Deployment Command**: las migraciones corren solas al arrancar el
|
||||
contenedor (`node migrate.mjs && node server.js`).
|
||||
6. **Despliega** y espera el healthcheck verde (`/api/health`; el start-period
|
||||
cubre las migraciones).
|
||||
7. **Verifica**: `https://<dominio>/api/health` responde
|
||||
`{"ok":true,"version":"2.12.2",…}` y `https://<dominio>/login` carga. Si la
|
||||
respuesta trae `"mediaWritable"` (desde 1.5.0), `true`
|
||||
confirma que el volumen del paso 3 quedó bien montado.
|
||||
|
||||
### Variante: construir desde el código
|
||||
|
||||
Para un VPS ARM (p. ej. Ampere o Graviton: la imagen es `linux/amd64` y ahí no
|
||||
corre) o para un fork con cambios propios. En el paso 2, en vez de la imagen,
|
||||
crea una app tipo **repositorio público** apuntando a
|
||||
`https://github.com/kevinrivm/vocero-crm` o al fork (rama `main`, build pack
|
||||
`dockerfile`, puerto expuesto `3000`, el dominio del usuario con HTTPS; MCP:
|
||||
`application` con `action: create_public`) — no requiere GitHub App ni deploy
|
||||
keys. Los pasos 3 a 7 son iguales. El build corre en el VPS y tarda varios
|
||||
minutos.
|
||||
|
||||
### Actualizar a una versión nueva
|
||||
|
||||
Lee antes «Actualizar desde…» de esa versión en `CHANGELOG.md`. Con la app de
|
||||
imagen, cambia la etiqueta (`docker_registry_image_tag`) a la versión nueva y
|
||||
redespliega; con la variante que construye, redespliega. En los dos casos las
|
||||
migraciones corren solas al arrancar.
|
||||
|
||||
## Ruta B — docker compose (VPS con Docker)
|
||||
|
||||
```bash
|
||||
git clone https://github.com/kevinrivm/vocero-crm.git vocero && cd vocero
|
||||
pnpm install && pnpm init-env --domain <dominio> # .env con los secretos generados (Node 22 + pnpm)
|
||||
pnpm doctor # cada ✗ dice cómo arreglarla; sale con 1 si algo falla
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
- Sin Node en el VPS: `cp .env.example .env` y rellena el dominio
|
||||
(`DOMAIN` y `APP_BASE_URL`) y los secretos del paso 2.
|
||||
- `docker compose up -d` descarga la imagen publicada de la versión que fija
|
||||
`docker-compose.yml`. En un VPS ARM o en un fork con cambios propios, usa
|
||||
`docker compose up -d --build`: la construye desde el código.
|
||||
- Caddy emite el certificado HTTPS automáticamente con `DOMAIN`.
|
||||
- El compose ya monta el volumen `vocero_app_data` en `/data` (adjuntos, logo
|
||||
e icono): no hay que definir `MEDIA_DIR`.
|
||||
- Con el agente (Nea): `BOT_API_KEY`, `BRAIN_DISPATCH_URL` y
|
||||
`BRAIN_HEALTH_URL` en el `.env` (valores en `docs/migrar-a-2.0.md`) y
|
||||
`docker compose up -d`.
|
||||
- Verifica: `docker compose ps` (tres servicios healthy, cuatro con Nea) y
|
||||
`https://<dominio>/api/health` → `{"ok":true,"version":"2.12.2",…}` (`"mediaWritable":true` confirma el volumen).
|
||||
|
||||
## Cierre (obligatorio decirlo al usuario)
|
||||
|
||||
> ✅ Vocero quedó instalado en `https://<dominio>`.
|
||||
>
|
||||
> 1. Entra y **regístrate**: el primer registro crea tu organización (después
|
||||
> el registro público se cierra solo).
|
||||
> 2. Pulsa **"Cargar datos de demostración"** si quieres explorar con la
|
||||
> Ferretería El Martillo.
|
||||
> 3. Para conectar tu WhatsApp entra a **Configuración → WhatsApp**: ahí está
|
||||
> el wizard; al guardar, Vocero registra el webhook en Meta por sí solo (la
|
||||
> URL exacta sigue a la vista por si tu agencia enruta desde su backend o
|
||||
> hay que pegarla a mano). La conexión del número NO es parte de esta
|
||||
> instalación.
|
||||
> 4. Vocero no trae agente: la **Guía de inicio** te dice si hay uno conectado.
|
||||
> Sin él, contestas tú desde la Bandeja. Con Nea en línea, enciéndelo en la
|
||||
> pantalla **Agente** cuando el Laboratorio te dé buen puntaje.
|
||||
> 5. Si vas a instalarlo para otros negocios: cómo venderlo, adaptarlo y
|
||||
> entregarlo sin que truene se aprende en la
|
||||
> [VIBE Community](https://kevinbelier.cloud/comunidad).
|
||||
|
||||
## Diagnóstico rápido
|
||||
|
||||
- App unhealthy al arrancar → revisa logs del contenedor: casi siempre es una
|
||||
variable faltante (la validación de entorno lista cuál) o la BD inaccesible.
|
||||
- Coolify no puede descargar la imagen → revisa la etiqueta: va sin `v`
|
||||
(`2.12.2`, no `v2.12.2`). En un VPS ARM la imagen no corre: usa la variante
|
||||
que construye desde el código.
|
||||
- `ENCRYPTION_KEY` inválida → debe ser EXACTAMENTE 32 bytes en base64
|
||||
(44 caracteres): regénérala con `openssl rand -base64 32`.
|
||||
- Webhook "no verificado" en Meta → el dominio aún no resuelve o no es https;
|
||||
el aviso de Configuración → WhatsApp trae el motivo y «Registrar en Meta»
|
||||
reintenta.
|
||||
- Subir el logo o el icono da error, o los adjuntos salen "no disponibles" →
|
||||
busca `[boot] MEDIA_DIR` o `[entrypoint] AVISO` en los logs: el directorio
|
||||
no es escribible (p. ej. el contenedor corre con un `--user` forzado sobre un
|
||||
volumen de root, o alguien definió `MEDIA_DIR` a mano). Quita `MEDIA_DIR` de
|
||||
las variables, deja el volumen en `/data` y redespliega.
|
||||
- Adjuntos, logo o icono desaparecen tras un redeploy → falta el volumen de
|
||||
`/data` (paso 3 de la Ruta A).
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Kevin Belier
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,934 @@
|
||||
# Vocero CRM
|
||||
|
||||
[](https://github.com/kevinrivm/vocero-crm/actions/workflows/ci.yml)
|
||||
[](LICENSE)
|
||||
|
||||
**El CRM de WhatsApp open source para tu agente de IA, con un Laboratorio que lo pone a prueba.**
|
||||
|
||||
Vocero es un CRM self-hosted y gratuito para negocios que venden por WhatsApp:
|
||||
bandeja en tiempo real, pipeline de ventas, el perfil y el conocimiento de tu
|
||||
agente, y un **Laboratorio** donde clientes simulados lo evalúan antes de que
|
||||
hable con clientes reales. Una instancia = un negocio, en tu propio servidor,
|
||||
con tus datos.
|
||||
|
||||
Vocero no trae agente: contesta el que conectas al lado.
|
||||
[Nea](https://github.com/kevinrivm/nea-agent) (MIT) es el recomendado y se
|
||||
levanta con el mismo `docker compose`; también puedes conectar el tuyo por el
|
||||
[contrato público](#-tu-agente-al-lado-del-crm). Sin agente, Vocero es un CRM
|
||||
de bandeja manual y contestas tú. El token de WhatsApp nunca sale del CRM.
|
||||
|
||||

|
||||
|
||||
<p align="center">
|
||||
<img src="docs/screenshots/laboratorio.png" width="49%" alt="Laboratorio: reporte con score y hallazgos" />
|
||||
<img src="docs/screenshots/pipeline.png" width="49%" alt="Pipeline kanban" />
|
||||
</p>
|
||||
|
||||
> 🎬 **Video-instalador oficial**: próximamente en
|
||||
> [el canal de Kevin Belier](https://www.youtube.com/@KevinBelier)
|
||||
|
||||
> 💼 **¿Quieres venderlo a otros negocios?** Vocero es gratis para tu negocio.
|
||||
> Cómo venderlo, adaptarlo a cada cliente y entregarlo sin que truene se aprende en
|
||||
> la [VIBE Community](https://kevinbelier.cloud/comunidad).
|
||||
|
||||
## ¿Para quién es?
|
||||
|
||||
- **Agencias de IA/automatización** que implementan CRM + agente para sus
|
||||
clientes: despliegas una instancia por cliente en su VPS (el CRM y Nea, o tu
|
||||
propio agente), la configuras y la entregas con evidencia de calidad (el
|
||||
reporte del Laboratorio).
|
||||
- **Negocios** que quieren atender WhatsApp con IA sin regalar sus datos a un
|
||||
SaaS: todo corre en tu servidor.
|
||||
|
||||
## Features
|
||||
|
||||
### 🧪 Laboratorio: el agente se prueba solo
|
||||
|
||||
La pieza estelar. Seis clientes simulados —el comprador decidido, el preguntón
|
||||
de precios, el cliente enojado, el que pregunta lo que no sabes, el que exige
|
||||
un humano y el que escribe "ke onda si benden pintura"— conversan contra tu
|
||||
agente REAL —el que tienes conectado: el CRM le despacha cada mensaje simulado
|
||||
como si fuera de un cliente— en un **sandbox que jamás envía mensajes
|
||||
reales**. Sin agente conectado, el Laboratorio te dice que lo conectes
|
||||
primero. Un juez LLM independiente, con la llave de Ajustes → IA, evalúa cada
|
||||
conversación y te entrega:
|
||||
|
||||
- un **score 0–100** de qué tan listo está el agente,
|
||||
- **hallazgos con evidencia** (alucinaciones, huecos del conocimiento, fallas
|
||||
de escalado, tono),
|
||||
- **sugerencias aplicables con un click** al knowledge base,
|
||||
- e **historial con delta**: re-corre después de cada cambio y mira si mejoraste.
|
||||
|
||||
Deja de "esperar que el bot funcione": mídelo.
|
||||
|
||||
### 💬 Bandeja de WhatsApp en tiempo real
|
||||
|
||||
Tres columnas (conversaciones / hilo / contacto), mensajes entrantes en ≤2
|
||||
segundos sin recargar, estados enviado/entregado/leído, ventana de 24 horas
|
||||
visible y bloqueada correctamente (con envío de plantilla aprobada cuando está
|
||||
cerrada), respuestas del agente marcadas como IA y handoff a humano con un
|
||||
click. Los adjuntos van y vienen (imagen, audio, video, documento, ubicación y
|
||||
contacto) con vista previa, y los archivos se guardan en tu propio servidor.
|
||||
|
||||
Si la conversación empezó en un anuncio Click-to-WhatsApp, la bandeja dice de
|
||||
cuál: «Anuncio · titular» en la lista, un filtro «Anuncios», y en el panel del
|
||||
contacto el creativo, el texto y el enlace del anuncio. No pide bandera ni
|
||||
credenciales: el dato llega en el mismo webhook.
|
||||
|
||||
En **Contactos** puedes **importar** una lista que ya tengas (un CSV con nombre
|
||||
y teléfono con código de país): ves qué va a entrar antes de crear nada, no
|
||||
duplica a nadie y no llena tu pipeline. Y puedes marcar contactos **«sin
|
||||
agente»** —al importar o uno por uno— para que a tus clientes de siempre los
|
||||
atiendas tú: sus mensajes llegan a la bandeja y el agente no les contesta.
|
||||
|
||||
Una conversación se puede **eliminar** desde el panel del contacto (lo ve quien
|
||||
administra el negocio): se van los mensajes, sus adjuntos y lo que el agente
|
||||
aprendió en ella, y el contacto se queda en su etapa salvo que pidas borrarlo
|
||||
también. Si la persona vuelve a escribir, el agente empieza de cero.
|
||||
|
||||
### 📊 Contactos y pipeline kanban
|
||||
|
||||
Cada persona que escribe queda registrada sola y entra al pipeline
|
||||
(Nuevo → En conversación → Interesado → Cliente → Perdido, editable). Arrastra
|
||||
tarjetas, busca, agrega notas, archiva.
|
||||
|
||||
### 🎯 Resultados
|
||||
|
||||
Una pantalla para la junta del lunes: prospectos nuevos, tratos ganados y
|
||||
perdidos, dinero cerrado y el embudo de los que entraron, contra el periodo
|
||||
anterior; si el agente contesta, qué tan rápido y cuándo pasa a un humano; de
|
||||
qué origen y de qué **anuncio** llegan las conversaciones que terminan en
|
||||
venta (con la miniatura del creativo), y qué se está cayendo hoy: leads en
|
||||
silencio, mensajes que no llegaron y ventanas de 24 h por cerrarse. Todo sale
|
||||
de los datos del propio CRM: no pide conectar nada, y el Laboratorio no cuenta.
|
||||
No trae gasto publicitario ni retorno por anuncio, a propósito: ese dato no
|
||||
vive en el CRM. Con la agenda encendida suma las citas (realizadas, no
|
||||
llegaron, canceladas). Los días se cortan en la zona horaria de la agenda; si
|
||||
no hay agenda configurada, en la de Ciudad de México.
|
||||
|
||||
### 🤖 Tu agente, con TU conocimiento
|
||||
|
||||
En la pantalla **Agente** configuras nombre, tono, instrucciones y reglas de
|
||||
escalado, y le das conocimiento en pares pregunta/respuesta y bloques libres.
|
||||
Todo eso vive en el CRM y el agente lo lee de ahí (`GET /api/bot/profile`):
|
||||
lo editas en un solo lugar. La llave de IA también: la pegas una vez en
|
||||
Ajustes → IA y tu agente piensa **a través del CRM**, sin copiarla a ningún
|
||||
otro sitio.
|
||||
|
||||
El interruptor de esa pantalla dice si el CRM le pasa las conversaciones a tu
|
||||
agente. Solo se enciende con un agente conectado y en línea; apagado, todo se
|
||||
queda en la bandeja para tu equipo.
|
||||
|
||||
### 🔌 Tu agente al lado del CRM
|
||||
|
||||
Quien contesta es un servicio aparte, en tu mismo servidor:
|
||||
[Nea](https://github.com/kevinrivm/nea-agent) (MIT; entiende audio, imagen y
|
||||
PDF, escala a humano, agenda y da seguimiento) o un cerebro tuyo. Se conecta
|
||||
con una `BOT_API_KEY` por la API de servicio: tu agente conversa a través del
|
||||
CRM, así que **el token de WhatsApp nunca sale de aquí** y todo queda en la
|
||||
bandeja como cualquier otra conversación.
|
||||
|
||||
Con docker compose, el par se levanta junto (la receta completa, con Coolify,
|
||||
está en [`docs/migrar-a-2.0.md`](docs/migrar-a-2.0.md#el-par-crm--nea)):
|
||||
|
||||
```bash
|
||||
# en tu .env: BOT_API_KEY, BRAIN_DISPATCH_URL=http://nea:8000/vocero/dispatch
|
||||
# y BRAIN_HEALTH_URL=http://nea:8000/health
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Mientras se publica la imagen 2.0.0 de Nea, el servicio va detrás del perfil
|
||||
`nea`; con el cierre de la 2.0 se levanta siempre.
|
||||
|
||||
| Endpoint | Para qué |
|
||||
|---|---|
|
||||
| `GET /api/bot/context` | Quién es la persona, su etapa, si un humano tomó la conversación y si la ventana de 24 h sigue abierta. Con la agenda encendida, también sus citas (`booking`): la próxima, la que ya pasó sin cerrarse y la última que se cerró (cancelada, no asistió o realizada) |
|
||||
| `POST /api/bot/messages` | Responder. Sale por el mismo camino que el composer y queda marcado como IA |
|
||||
| `GET /api/bot/profile` | El perfil del agente y el knowledge base que editaste en la app; en `llm`, por dónde pensar y con qué modelo (`null` sin IA configurada) |
|
||||
| `POST /api/bot/llm/{ruta}` | Pensar con la llave de Ajustes → IA. Compatible con OpenAI: apunta el `base_url` de tu SDK aquí. Acepta `X-API-Key` o `Authorization: Bearer`. Sin IA configurada, 402 `sin_credencial` |
|
||||
| `PUT /api/bot/ficha` | Guardar lo que tu bot descubre del lead (claves libres: cada negocio califica distinto) |
|
||||
| `POST /api/bot/stage` | Avanzar al lead en el pipeline: solo hacia adelante y a etapas abiertas (las que el contexto trae en `lead.nextStages`). Ganar o perder un trato lo decide una persona. Se apaga desde la pantalla Agente («Mover de etapa») |
|
||||
| `POST /api/bot/handoff` | Devolver la conversación a un humano |
|
||||
| `POST /api/bot/typing` | Marcar leído y mostrar "escribiendo…" |
|
||||
| `GET /api/bot/media/{id}` | Descargar un adjunto entrante sin tocar Meta |
|
||||
| `POST /api/bot/reset` | Reiniciar una conversación de pruebas |
|
||||
| `GET /api/bot/availability` | Con la agenda encendida: los horarios para ofrecer, que quedan registrados como ofrecidos. Con `date=AAAA-MM-DD`, todas las horas libres de ese día; `query` dice hasta dónde llega lo consultado |
|
||||
| `POST` · `PATCH /api/bot/bookings` | Con la agenda encendida: reservar (201) o mover (200) una cita, solo en un horario que se ofreció |
|
||||
|
||||
El contrato completo, con el despacho y el aviso de olvido, está en
|
||||
[`docs/openapi.json`](docs/openapi.json) (OpenAPI 3.1) y tu instancia lo sirve
|
||||
en `GET /api/bot/openapi.json`. Si vienes de 1.x, la guía es
|
||||
[`docs/migrar-a-2.0.md`](docs/migrar-a-2.0.md).
|
||||
|
||||
Los 409 vienen tipados (`ai_paused`, `window_closed`, `sandbox_violation`,
|
||||
`message_limit`) para que tu bot sepa si callarse, mandar plantilla o rendirse.
|
||||
`message_limit` significa que el canal no admite más mensajes hasta que el
|
||||
cliente vuelva a escribir (hoy, el tope de 10 de TikTok): no reintentes. El guion de pruebas
|
||||
está en [`tests/e2e/us-bot-api.md`](tests/e2e/us-bot-api.md).
|
||||
|
||||
La API primero revisa la llave y después cuenta: con la llave buena caben 1200
|
||||
llamadas por minuto; sin llave o con una mala, 30 por minuto desde la misma IP
|
||||
responden `401` y las siguientes `429` («Demasiados intentos fallidos»). Quien
|
||||
inunde la API sin llave no deja a tu bot sin servicio.
|
||||
|
||||
**El CRM le pasa cada turno a tu agente (el despacho).** Tu agente no
|
||||
necesita recibir el webhook de Meta: con `BRAIN_DISPATCH_URL` (p. ej.
|
||||
`http://nea:8000/vocero/dispatch`), la misma `BOT_API_KEY` y el interruptor de
|
||||
la pantalla Agente encendido, el mensaje entra primero a la bandeja y el CRM
|
||||
le hace a tu agente un `POST` firmado con lo que el cliente escribió desde la
|
||||
última respuesta, junto, después de esperar a que termine su ráfaga. Tu agente
|
||||
contesta por `POST /api/bot/messages`. Es igual para WhatsApp, Instagram,
|
||||
Messenger y TikTok, y no hay secreto de Meta que copiar ni cola de reenvío que
|
||||
vigilar. Si tu agente no recibe el turno (tres intentos), la conversación
|
||||
queda con una persona y el mensaje sigue en la bandeja. El contrato del evento
|
||||
y de la firma está en
|
||||
[`specs/021-despacho-estandar/contracts/despacho.md`](specs/021-despacho-estandar/contracts/despacho.md)
|
||||
y su guion en [`tests/e2e/us-despacho.md`](tests/e2e/us-despacho.md).
|
||||
|
||||
Si tu bot recibe los webhooks de Meta por un **override de callback de la
|
||||
WABA**, guardar la conexión en Configuración → WhatsApp (o rotar el token) lo
|
||||
respeta: Vocero ve el override en `GET /{WABA}/subscribed_apps`, no re-suscribe
|
||||
la app —que es justo lo que lo borraría— y tampoco registra su propio webhook
|
||||
en el número, porque ese tendría prioridad y dejaría sordo a tu bot. La
|
||||
pantalla te dice a qué host se está respetando y, si quieres que los mensajes
|
||||
vuelvan al CRM (por ejemplo, al pasar de Nea 1.x al despacho), ofrece
|
||||
**Recuperar el webhook**: quita ese override y deja el del número aquí.
|
||||
|
||||
**Tu agente piensa por el CRM.** `POST /api/bot/llm/{ruta}` reenvía la
|
||||
llamada tal cual al proveedor de Ajustes → IA con la llave guardada y te
|
||||
devuelve su respuesta. La llave no viaja a tu agente: si se filtra el
|
||||
servidor de tu agente, no se filtra con ella. Si el proveedor la rechaza (401)
|
||||
o se queda sin saldo (402), se pausa en Ajustes → IA y la pantalla lo dice,
|
||||
igual que si fallara en el CRM. Nea lo usa solo cuando no le pones
|
||||
`LLM_API_KEY`; con ella, piensa con su propio proveedor.
|
||||
|
||||
Arriba de la pantalla **Agente**, la tarjeta **«Quién responde a tus
|
||||
clientes»** dice si hay un agente conectado: su última llamada a la API, a
|
||||
quién se le despacha, cuándo llegó el último turno y si alguno no llegó, y
|
||||
—con `BRAIN_HEALTH_URL`, p. ej. `http://nea:8000/health`— si está en línea,
|
||||
su versión y su modo. Sin agente, te dice que Vocero funciona como bandeja
|
||||
manual (es un aviso, no un error). Con el agente conectado y el interruptor
|
||||
apagado, te avisa que nadie está contestando.
|
||||
|
||||
### 📅 Agenda con huecos reales (opcional, apagada por defecto)
|
||||
|
||||
Enciéndela con `AGENDA=on` y el CRM sabe cuándo estás libre: defines tu horario
|
||||
en Ajustes → Agenda y tu agente ofrece huecos concretos, reserva el que el
|
||||
cliente elige y lo deja registrado junto a su conversación. Dos garantías que
|
||||
no se negocian: **solo se reserva un horario que se ofreció** (nada de que el
|
||||
modelo invente un martes a las 10) y **nunca se confirma una cita que no se
|
||||
creó** — si el hueco se ocupó a media conversación, la respuesta trae
|
||||
alternativas frescas en vez de una promesa falsa.
|
||||
|
||||
Las citas se ven en la pestaña **Citas** como un calendario: Día, Semana, Mes y
|
||||
Lista, siempre en la zona horaria del negocio aunque abras el CRM desde otra.
|
||||
Tocas una cita y desde su panel abres la conversación, la reprogramas, la
|
||||
marcas realizada o «no asistió», o la cancelas; tocas un hueco vacío de la
|
||||
rejilla y bloqueas ese horario.
|
||||
|
||||
Cómo se entrega la reunión lo eliges tú, con un **conector**:
|
||||
|
||||
| Conector | Qué hace | Necesita |
|
||||
|---|---|---|
|
||||
| **Enlace fijo** (default) | Reparte tu sala de siempre | Nada |
|
||||
| **Zoom** | Una reunión por cita; mover la mueve, cancelar la borra | Tu app Server-to-Server |
|
||||
| **Google Calendar + Meet** | Un evento en tu calendario con su enlace de Meet | Tu app de Google Cloud |
|
||||
|
||||
¿Usas otra cosa? El contrato son cuatro operaciones y está publicado: escribe
|
||||
tu conector en tu fork siguiendo
|
||||
[`docs/agenda-conectores.md`](docs/agenda-conectores.md). Y si tu proveedor se
|
||||
cae, la cita **se agenda igual** con el enlace pendiente de reintentar: un
|
||||
tercero caído no te cuesta la conversión.
|
||||
|
||||
### 📈 Conversiones de anuncios (opcional, apagada por defecto)
|
||||
|
||||
Si anuncias con **Click-to-WhatsApp**, Meta sabe qué conversaciones empezaron
|
||||
desde un anuncio, pero no cuáles sirvieron: sin nadie que se lo diga, optimiza
|
||||
hacia el público más barato de hacer escribir, que rara vez es el que compra.
|
||||
|
||||
Enciéndela con `ATRIBUCION=on`, pega tu dataset en Ajustes → Anuncios (el token
|
||||
lo reusa de tu conexión de WhatsApp) y di qué etapa de TU pipeline significa
|
||||
"lead calificado". A partir de ahí el CRM le reporta a Meta el lead calificado y
|
||||
la venta cerrada —con su importe— por la **Conversions API**, y una tabla de
|
||||
actividad te dice qué se envió, con qué acuse y, cuando no salió, por qué.
|
||||
|
||||
No se le pide nada al usuario que el CRM ya sepa: la venta cuelga de la etapa
|
||||
ganada que ya tienes, y todo se dispara desde la misma puerta que mueve leads,
|
||||
así que reporta igual sin importar quién mueva la tarjeta. Si Meta se cae, el lead se mueve igual: una conversión jamás vale un
|
||||
movimiento bloqueado. Los gotchas de Meta que cuesta descubrir solo están en
|
||||
[`docs/atribucion-capi.md`](docs/atribucion-capi.md).
|
||||
|
||||
Lo que **no** necesita la bandera: saber de qué anuncio llegó cada
|
||||
conversación. La bandeja lo marca («Anuncio · titular», con su filtro) y el
|
||||
panel del contacto y el cajón del trato enseñan el creativo, el texto y el
|
||||
enlace del anuncio, en cualquier instancia que reciba un clic de un anuncio.
|
||||
|
||||
### 🎨 Tu marca, en claro y en oscuro
|
||||
|
||||
En Configuración → Marca le pones al CRM el nombre de tu negocio, su color y su
|
||||
logo; el logo se ve en la barra lateral, en el login y en la pestaña del
|
||||
navegador. La barra lateral es azul marino en los dos temas, y cada quien
|
||||
elige claro u oscuro en su navegador. En oscuro, la página, la barra y lo que
|
||||
flota encima se distinguen, y el texto pasa el contraste AA. Con un color
|
||||
propio, los tonos derivados y la tinta de los botones se calculan solos para
|
||||
que se lean.
|
||||
|
||||
### 📱 En el celular, como una app
|
||||
|
||||
Vocero se instala desde el navegador, sin tiendas y con el nombre y el icono
|
||||
de tu negocio:
|
||||
|
||||
- **Android y computadora (Chrome o Edge)**: en el menú aparece **Instalar
|
||||
app** cuando el navegador lo permite.
|
||||
- **iPhone (Safari)**: Compartir → **Agregar a inicio**.
|
||||
|
||||
Abre directo en la Bandeja, sin la barra del navegador. Si se va la red, dice
|
||||
«Sin conexión» en vez de mostrar conversaciones viejas: no guarda datos de tus
|
||||
clientes en el teléfono.
|
||||
|
||||
### 📄 Plantillas · 👥 Multi-usuario · 🔐 Self-hosted
|
||||
|
||||
Plantillas con varias variables `{{1}}…{{n}}` y aprobación de Meta
|
||||
sincronizada; cuentas de equipo creadas por el propietario (el registro público
|
||||
se cierra tras la primera organización); token de WhatsApp cifrado en reposo
|
||||
(AES-256-GCM),
|
||||
webhook autenticado en dos capas y cero dependencias de runtime más allá de
|
||||
Meta y tu proveedor LLM opcional.
|
||||
|
||||
## Requisitos
|
||||
|
||||
- Un VPS con Docker (2 GB de RAM bastan para correr la imagen publicada) — con
|
||||
o sin [Coolify](https://coolify.io). La imagen es `linux/amd64`; en un VPS
|
||||
ARM construyes desde el código, que tarda varios minutos y pide más memoria.
|
||||
- Un dominio apuntando al VPS (Meta exige **https** para webhooks).
|
||||
- Un número de WhatsApp en la Cloud API de Meta (ver [Conexión](#conexión-del-número-de-whatsapp)).
|
||||
- Opcional: una API key de [OpenRouter](https://openrouter.ai) (o cualquier
|
||||
proveedor compatible) para tu agente y el juez del Laboratorio.
|
||||
- Opcional: un agente al lado del CRM ([Nea](https://github.com/kevinrivm/nea-agent)
|
||||
u otro). Sin él, Vocero funciona como bandeja manual.
|
||||
|
||||
## Instalación (~15 minutos)
|
||||
|
||||
Cada versión se publica como imagen de Docker:
|
||||
`ghcr.io/kevinrivm/vocero-crm:<versión>` (p. ej. `2.12.2`). Instalar desde
|
||||
la imagen es el camino recomendado: tu servidor la descarga en vez de
|
||||
construirla. Construir desde el código sigue funcionando, y es lo que
|
||||
necesitas en un VPS ARM o si tu fork cambia el código.
|
||||
|
||||
### 0. Apunta tu dominio
|
||||
|
||||
Crea un registro **A** de `crm.tudominio.com` hacia la IP del VPS y espera a
|
||||
que resuelva.
|
||||
|
||||
### Ruta A — Coolify guiado por IA (recomendada)
|
||||
|
||||
Abre tu asistente de IA (p. ej. Claude Code con el MCP de Coolify), pásale el
|
||||
archivo [`INSTALL-IA.md`](INSTALL-IA.md) y responde 3 preguntas (dominio, token
|
||||
de OpenRouter opcional, ruta). El asistente crea la base de datos y una app de
|
||||
tipo «Docker Image» con la imagen de la versión, le monta el volumen de
|
||||
`/data`, genera los secretos y verifica el healthcheck. La misma guía trae la
|
||||
variante que construye desde el repositorio.
|
||||
|
||||
### Ruta B — docker compose
|
||||
|
||||
```bash
|
||||
git clone https://github.com/kevinrivm/vocero-crm.git vocero && cd vocero
|
||||
pnpm install && pnpm init-env --domain crm.tudominio.com # crea .env con los secretos ya generados
|
||||
pnpm doctor # revisa el .env antes de arrancar
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
`pnpm init-env` crea el `.env` a partir de `.env.example` con todos los
|
||||
secretos generados (nunca pisa uno existente); sin `--domain` deja
|
||||
`DOMAIN=localhost` para probar en la misma máquina. Necesita Node 22 y pnpm
|
||||
(`corepack enable`); sin ellos en el VPS, `cp .env.example .env` y rellena a
|
||||
mano (cada variable trae su comando `openssl`). `pnpm doctor` valida las
|
||||
variables con el mismo esquema que el arranque, prueba la base de datos, el
|
||||
directorio de adjuntos y, si ya hay un número conectado, el token de WhatsApp:
|
||||
cada ✗ sale con el comando que la arregla, y nunca imprime un secreto.
|
||||
|
||||
`docker-compose.yml` declara las dos cosas: la imagen publicada (`image`) y el
|
||||
código (`build: .`). Sin `pull_policy`, la
|
||||
[especificación de Compose](https://docs.docker.com/reference/compose-file/build/#using-build-and-image)
|
||||
dice qué pasa: intenta primero descargar la imagen y solo la construye desde el
|
||||
código si no la encuentra ni en el registro ni en tu máquina. Así que:
|
||||
|
||||
- `docker compose up -d` corre la imagen publicada de la versión que fija el
|
||||
compose. Para otra versión publicada, `VOCERO_CRM_VERSION=X.Y.Z` en tu
|
||||
`.env`.
|
||||
- `docker compose up -d --build` la construye desde tu copia del código. Es lo
|
||||
que necesitas en un VPS ARM y en un fork con cambios propios; en el fork,
|
||||
úsalo siempre: lo que construyes queda con el mismo nombre de imagen, y sin
|
||||
`--build` Compose puede correr la oficial en vez de tus cambios.
|
||||
|
||||
Caddy emite el certificado HTTPS solo. Verifica con
|
||||
`https://crm.tudominio.com/api/health` → `{"ok":true,"version":"2.12.2",…}`.
|
||||
|
||||
### Otras plataformas: Render, Fly y Railway
|
||||
|
||||
Hay un manifest por plataforma en la raíz del repo. Los tres corren la misma
|
||||
imagen publicada, montan `/data` y vigilan `/api/health`; cada uno declara lo
|
||||
que su plataforma le deja declarar y documenta, en comentarios, lo que queda a
|
||||
mano. La imagen va fijada a la versión (una prueba lo exige). Verifica igual
|
||||
que arriba: `curl -s https://<tu-url>/api/health` →
|
||||
`{"ok":true,"version":"2.12.2",…,"mediaWritable":true}`.
|
||||
|
||||
**Render** — [`render.yaml`](render.yaml) es un Blueprint completo: servicio
|
||||
web desde la imagen, base Postgres gestionada, disco de 1 GB en `/data`,
|
||||
healthcheck y variables obligatorias; `BETTER_AUTH_SECRET` y `ENCRYPTION_KEY`
|
||||
las genera Render (256 bits en base64: justo los 32 bytes que pide la clave)
|
||||
y `APP_BASE_URL` sale de la URL `.onrender.com` del servicio. Se aplica con
|
||||
**New → Blueprint** sobre tu fork o con el botón de abajo. Queda a mano:
|
||||
`META_WEBHOOK_VERIFY_TOKEN` cuando Render lo pida (`openssl rand -hex 32`:
|
||||
Render genera base64, con `/`, y el token es un segmento de la URL del
|
||||
webhook), el token de OpenRouter y, con dominio propio, `APP_BASE_URL`. El
|
||||
disco exige plan de pago (`starter` + `basic-256mb`; la base `free` caduca a
|
||||
los 30 días).
|
||||
|
||||
[](https://render.com/deploy?repo=https://github.com/kevinrivm/vocero-crm)
|
||||
|
||||
**Fly.io** — [`fly.toml`](fly.toml) declara imagen, volumen `/data`, puerto
|
||||
3000, healthcheck, tamaño de máquina y las variables no secretas; Fly no deja
|
||||
poner en el archivo ni secretos ni la base. Queda a mano, una vez, con los
|
||||
comandos exactos escritos en el propio `fly.toml`: `fly apps create`,
|
||||
`fly volumes create`, `fly postgres create` + `fly postgres attach` (deja
|
||||
`DATABASE_URL`), `fly secrets set` con los tres secretos y
|
||||
`fly deploy --ha=false`. Ese Postgres es el no gestionado (barato; Fly ya no
|
||||
lo mantiene): el gestionado es `fly mpg create` + `fly mpg attach`. La máquina
|
||||
no se apaga sola a propósito: el despacho a tu agente y el Laboratorio corren
|
||||
dentro del proceso.
|
||||
|
||||
**Railway** — [`railway.toml`](railway.toml) solo puede declarar el build
|
||||
(Dockerfile), el healthcheck y la política de reinicio; la base, el volumen,
|
||||
el dominio y las variables se crean con la CLI, con los comandos exactos
|
||||
escritos en el propio archivo (`railway add --database postgres`,
|
||||
`railway volume add --mount-path /data`, `railway domain --port 3000`,
|
||||
`railway variable set …`, `railway up`). Para la imagen publicada sin build:
|
||||
`railway add --image ghcr.io/kevinrivm/vocero-crm:2.12.2`, y entonces el
|
||||
healthcheck se fija en el panel. Railway declaró obsoleto este formato a
|
||||
favor de su Infrastructure as Code (`.railway/railway.ts`); lo sigue leyendo
|
||||
hasta el 2026-12-01.
|
||||
|
||||
### Adjuntos en un bucket (opcional)
|
||||
|
||||
Por defecto, los adjuntos, el logo y el icono viven en el volumen de `/data`.
|
||||
Si tu plataforma no tiene disco persistente, o prefieres guardarlos aparte,
|
||||
mándalos a un bucket S3-compatible **tuyo** con `MEDIA_STORE=bucket` y las
|
||||
`MEDIA_BUCKET_*` (guía en [`.env.example`](.env.example)):
|
||||
|
||||
- **MinIO en el mismo servidor**: `docker compose --profile bucket up -d`
|
||||
levanta MinIO y crea el bucket; `MEDIA_BUCKET_ENDPOINT=http://minio:9000`.
|
||||
- **R2, S3, Backblaze, Tigris…**: su endpoint, su región y una llave con
|
||||
permiso de escritura en el bucket.
|
||||
|
||||
Lo nuevo va al bucket y lo que ya estaba en el volumen se sigue leyendo de
|
||||
ahí: no hay que migrar nada, y quitar la bandera tampoco deja nada ilegible.
|
||||
Si el bucket no acepta una escritura, ese archivo se guarda en el volumen
|
||||
(no se pierde) y `/api/health` (`mediaWritable: false`) y `pnpm doctor` lo
|
||||
dicen. Vocero firma las peticiones él mismo: no trae el SDK de AWS.
|
||||
|
||||
Vercel y similares siguen fuera: con el bucket ya no dependen del disco, pero
|
||||
quedan el trabajo en segundo plano (el despacho, el Laboratorio), el SSE en
|
||||
memoria y las migraciones al arrancar.
|
||||
|
||||
### Actualizar
|
||||
|
||||
Antes, lee en [`CHANGELOG.md`](CHANGELOG.md) la sección «Actualizar desde…» de
|
||||
la versión nueva. Con docker compose: `git pull` y `docker compose up -d` (con
|
||||
`--build` si tu fork tiene cambios propios). En Coolify: cambia la etiqueta de
|
||||
la imagen a la versión nueva y redespliega; si construyes desde el
|
||||
repositorio, redespliega. Con los manifests: cambia la etiqueta de la imagen
|
||||
en el archivo (Render sincroniza el Blueprint; Fly, `fly deploy`; Railway
|
||||
construye desde el código: `git pull` y `railway up`). Las migraciones corren
|
||||
solas al arrancar.
|
||||
|
||||
### Primer arranque
|
||||
|
||||
1. Entra y **regístrate**: el primer registro crea tu organización y cierra el
|
||||
registro público.
|
||||
2. Lo primero que ves es la **Guía de inicio**: configura tu agente, vincula
|
||||
tu proveedor de IA, conecta tu número de WhatsApp y, opcional, **conecta tu
|
||||
agente** (Nea u otro; su dirección va en las variables de entorno, el paso
|
||||
te lleva a la receta y se marca solo cuando el agente contesta su
|
||||
`/health`). Con la agenda encendida (`AGENDA=on`), uno más para tus
|
||||
horarios. Cada botón te lleva a la pantalla que toca y al volver ves tu
|
||||
avance; cada paso se marca solo cuando la pieza de verdad funciona. Con un
|
||||
agente conectado aparece **Encender**: hasta entonces nadie le contesta a
|
||||
los clientes y los mensajes que lleguen los atiendes tú desde la Bandeja.
|
||||
Sin agente, la guía te dice que Vocero funciona como bandeja manual.
|
||||
3. Mientras falte un paso —o haya un agente conectado y siga apagado—, entrar
|
||||
a la app te lleva a la guía (también está en el menú, solo para el
|
||||
propietario). Si no conectas agente, con los demás pasos listos entras
|
||||
directo a la Bandeja. La guía no encierra a nadie: desde el menú vas a
|
||||
cualquier pantalla en cualquier momento.
|
||||
4. Opcional: en la Bandeja, pulsa **"Cargar datos de demostración"** para
|
||||
explorar con la **Ferretería El Martillo** (contactos, conversaciones,
|
||||
pipeline, un knowledge base con huecos a propósito y una corrida de
|
||||
Laboratorio de ejemplo — corre el Laboratorio y mira cómo los encuentra).
|
||||
La demo deja configurado el agente (paso 1 listo); la llave de IA y el
|
||||
número siguen siendo tuyos.
|
||||
|
||||
## Conexión del número de WhatsApp
|
||||
|
||||
Vocero **consume** un token de la WhatsApp Cloud API — no implementa el
|
||||
Embedded Signup. Hay dos formas de obtenerlo:
|
||||
|
||||
### Modo directo (el negocio tiene su propia app de Meta)
|
||||
|
||||
> **Atajo: «Conectar con Meta».** Con `META_APP_ID`,
|
||||
> `META_EMBEDDED_CONFIG_ID` y `META_APP_SECRET` en la instancia, Ajustes →
|
||||
> WhatsApp muestra un botón que abre la ventana oficial de Meta (Embedded
|
||||
> Signup v4) y deja el número conectado sin pegar tokens: registra el número y
|
||||
> el webhook solo. Qué poner en el panel de Meta (dominios, configuración de
|
||||
> login): [docs/embedded-signup.md](docs/embedded-signup.md). Sin esas
|
||||
> variables, sigue el alta manual de abajo.
|
||||
|
||||
1. Crea una app en [developers.facebook.com](https://developers.facebook.com)
|
||||
con el producto WhatsApp y vincula tu número.
|
||||
2. Crea un **usuario del sistema** (Business Settings → System users) con
|
||||
acceso a la WABA y genera un token permanente con permisos
|
||||
`whatsapp_business_messaging` y `whatsapp_business_management`.
|
||||
3. En Vocero: **Configuración → WhatsApp** → pega WABA ID + Phone Number ID +
|
||||
token → **Probar conexión** → Guardar. Al guardar, Vocero **registra el
|
||||
webhook en Meta por ti** (override a nivel del número, con el handshake
|
||||
incluido) y te lo confirma en pantalla. Si Meta lo rechaza, la conexión
|
||||
queda guardada igual, el aviso dice por qué (casi siempre el token no tiene
|
||||
`whatsapp_business_management`) y el botón **«Registrar en Meta»** de la
|
||||
tarjeta del webhook reintenta sin volver a pegar el token.
|
||||
4. Solo si tu app aún no tiene ningún webhook configurado (Vocero te lo
|
||||
avisa): en el panel de Meta (WhatsApp → Configuration → Webhook) pega la
|
||||
**URL del webhook** y el **verify token** que Vocero te muestra, y suscribe
|
||||
el campo `messages` (y `message_template_status_update` si usarás
|
||||
plantillas). Es una sola vez por app.
|
||||
5. Recomendado: agrega `META_APP_SECRET` (App Secret de tu app) a las
|
||||
variables de la instancia para la verificación de firma de cada evento.
|
||||
|
||||
### Modo agencia (Tech Provider) — para agencias
|
||||
|
||||
Tu plataforma de agencia ya hace el Embedded Signup y guarda los tokens de tus
|
||||
clientes; la instancia de Vocero del cliente solo recibe su token. El webhook
|
||||
del cliente se conecta con el **override de callback por WABA**:
|
||||
|
||||
```text
|
||||
Meta (WABA del cliente)
|
||||
│ webhooks (override_callback_uri)
|
||||
▼
|
||||
┌────────────────────────────┐ ┌─────────────────────────────┐
|
||||
│ Instancia Vocero │ │ Backend de TU agencia │
|
||||
│ (VPS del cliente) │ │ (Embedded Signup + tokens) │
|
||||
│ /api/webhooks/wa/<token> │ └──────────────┬──────────────┘
|
||||
└────────────▲───────────────┘ │
|
||||
└────── token del cliente ────────────┘
|
||||
(pegado en el wizard)
|
||||
```
|
||||
|
||||
**Checklist de 5 pasos (el orden importa):**
|
||||
|
||||
1. **Despliega la instancia primero** (Ruta A o B) — el webhook debe estar en
|
||||
línea para el handshake del paso 3.
|
||||
2. **Embedded Signup en TU plataforma**: el cliente conecta su número en tu
|
||||
onboarding y tu backend guarda su token (intercambio de código → token).
|
||||
3. **Pega las credenciales en el wizard** de la instancia (WABA ID, Phone
|
||||
Number ID, token) → **Probar conexión** → **GUARDAR**. Al guardar, Vocero
|
||||
**registra el override del callback a nivel del número** hacia la propia
|
||||
instancia (y el webhook enruta cada mensaje por el Phone Number ID
|
||||
guardado). Si tu backend ya enruta esa WABA a otro sitio, Vocero lo respeta
|
||||
y no registra el del número.
|
||||
4. **Solo si prefieres enrutar desde tu backend** (o el registro automático
|
||||
falló), configura el override del callback a nivel WABA hacia la instancia:
|
||||
|
||||
```http
|
||||
POST https://graph.facebook.com/v25.0/{WABA_ID_DEL_CLIENTE}/subscribed_apps
|
||||
Authorization: Bearer {TOKEN_DEL_CLIENTE}
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"override_callback_uri": "https://crm.cliente.com/api/webhooks/wa/{VERIFY_TOKEN}",
|
||||
"verify_token": "{VERIFY_TOKEN}"
|
||||
}
|
||||
```
|
||||
|
||||
La URL y el verify token exactos están en **Configuración → WhatsApp** de la
|
||||
instancia. Meta hace el handshake en ese momento (la URI debe responder, si
|
||||
no devuelve 422). Volver a guardar la conexión después (p. ej. al rotar el
|
||||
token) respeta este override: Vocero no re-suscribe una WABA que ya lo tiene.
|
||||
5. **Registra el número** en la Cloud API si aún no lo está
|
||||
(`POST /{PHONE_NUMBER_ID}/register`) y manda un mensaje de prueba al número:
|
||||
debe aparecer en la bandeja en uno o dos segundos. Los mensajes del cliente
|
||||
llegan directo a SU instancia, no a tu backend.
|
||||
|
||||
> ⚠️ **Seguridad**: la URL del webhook contiene el verify token como segmento
|
||||
> secreto — trátala como una contraseña (no la publiques ni la mandes por
|
||||
> canales inseguros). En modo directo puedes añadir la capa extra de firma con
|
||||
> `META_APP_SECRET`.
|
||||
>
|
||||
> ℹ️ **Limitación conocida de Meta**: los eventos de estado de PLANTILLAS
|
||||
> (`message_template_status_update`) no siguen el override de callback — van a
|
||||
> la app dueña. Por eso Vocero también **sincroniza plantillas por la API de
|
||||
> Graph** (botón "Sincronizar" en Configuración → Plantillas), así el modo
|
||||
> agencia ve las aprobaciones igual.
|
||||
|
||||
## Canales opcionales: Instagram, Messenger y TikTok
|
||||
|
||||
WhatsApp es el canal por el que existe Vocero y siempre está encendido. Los
|
||||
demás viajan en el mismo código, **apagados por defecto** ([ADR-001](docs/adr-001-canales-opcionales.md)):
|
||||
una instancia que no los usa no ve pantallas, webhooks ni variables suyas.
|
||||
Se encienden con una variable de despliegue:
|
||||
|
||||
```bash
|
||||
CHANNELS=whatsapp,instagram,messenger,tiktok # los que quieras; whatsapp siempre va
|
||||
```
|
||||
|
||||
Con más de un canal encendido, la Bandeja enseña el distintivo de cada
|
||||
conversación y permite filtrar por canal. El contacto, el pipeline, la ficha
|
||||
y el agente son los mismos: un lead es un lead, escriba por donde escriba.
|
||||
|
||||
Tu agente escribe igual para todos los canales y Vocero lo adapta al salir:
|
||||
en Instagram, Messenger y TikTok, que no dibujan las negritas de WhatsApp, su
|
||||
texto llega sin asteriscos, con viñetas y con los enlaces legibles.
|
||||
|
||||
**Configuración → Estado** reúne todos los canales encendidos: si están
|
||||
conectados, cuándo entró el último mensaje de un cliente y, para los que
|
||||
llegan por Zernio, cómo están la cuenta y el webhook. Es el primer sitio que
|
||||
mirar cuando «no me llegan los mensajes».
|
||||
|
||||
### Conectar por Zernio (Instagram, Messenger o TikTok)
|
||||
|
||||
[Zernio](https://zernio.com) es una API unificada: vinculas ahí tus redes, con
|
||||
tu propia cuenta, y una sola llave las entrega todas. En Vocero es igual para
|
||||
los tres canales:
|
||||
|
||||
1. En Zernio vincula la red (**Accounts → Connect**) y crea una API key
|
||||
(**Settings → API Keys**; empieza con `sk_` y se muestra una sola vez).
|
||||
2. En Vocero abre la pantalla del canal, elige *Zernio*, pega la llave y
|
||||
pulsa **Probar y conectar**. Solo el propietario puede hacerlo.
|
||||
|
||||
No hay que copiar ningún id ni dar de alta nada más en Zernio:
|
||||
|
||||
- **La cuenta la encuentra Vocero** con esa llave. Si la llave tiene varias
|
||||
cuentas de esa red (una agencia), te las ofrece para elegir.
|
||||
- **El webhook lo da de alta Vocero** en tu Zernio, con el evento
|
||||
`message.received`, un secreto de firma que él genera y **limitado a tus
|
||||
cuentas conectadas**. Un webhook de Zernio sin ese límite recibe los
|
||||
mensajes de todas las cuentas de la llave. Los demás webhooks que tengas en
|
||||
Zernio no se tocan.
|
||||
- Si un día el webhook se desactiva o le falta una cuenta, **Configuración →
|
||||
Estado** lo dice y lo repara con un botón.
|
||||
|
||||
Cada entrega se verifica con la firma de Zernio. Si actualizas desde una
|
||||
versión anterior y ya tenías el webhook creado a mano, sigue funcionando: al
|
||||
abrir **Estado** verás si le falta algo.
|
||||
|
||||
### Messenger (página de Facebook)
|
||||
|
||||
Dos formas de traer los mensajes; se elige en **Configuración → Messenger**.
|
||||
|
||||
**Con Zernio**: sigue [Conectar por Zernio](#conectar-por-zernio-instagram-messenger-o-tiktok)
|
||||
desde **Configuración → Messenger**. La página y su nombre salen de Zernio.
|
||||
|
||||
**Con una app propia de Meta**:
|
||||
|
||||
1. En [developers.facebook.com](https://developers.facebook.com) crea (o usa)
|
||||
una app con el producto **Messenger** y genera el **token de acceso de la
|
||||
página** con el permiso `pages_messaging`. Anota el **ID de la página**.
|
||||
2. En Vocero, **Configuración → Messenger**: elige *App propia de Meta*, pega
|
||||
el ID y el token y pulsa *Probar y guardar*.
|
||||
3. En la app de Meta, **Messenger → Webhooks**: objeto `page`, campo
|
||||
`messages`, esa URL de callback y el token de verificación que enseña la
|
||||
pantalla. Suscribe la página a la app.
|
||||
|
||||
Desde ese momento, lo que la gente le escribe a la página entra a la bandeja
|
||||
como `Messenger`, con el nombre de su perfil, y lo que respondas desde Vocero
|
||||
(tú o el agente) llega a su chat. No hay plantillas: pasadas 24 horas del
|
||||
último mensaje del cliente ya solo puede contestar una persona, hasta 7 días
|
||||
(sale con la etiqueta `HUMAN_AGENT` de Meta); la bandeja lo avisa y dice
|
||||
cuánto queda. El agente no contesta fuera de las 24 horas.
|
||||
Hoy el canal es de texto: los adjuntos que te manden se ven como
|
||||
«📎 Imagen» para que sepas que llegaron, y los adjuntos salientes no están.
|
||||
|
||||
Con app propia y sin App Review, la página solo recibe mensajes de cuentas con
|
||||
un rol en la app; para atender al público hay que aprobar `pages_messaging`.
|
||||
Por Zernio ese trámite ya está resuelto del lado de ellos.
|
||||
|
||||
### Instagram (DMs del perfil profesional)
|
||||
|
||||
Dos formas de traer los mensajes; se elige en **Configuración → Instagram**.
|
||||
La cuenta tiene que ser profesional (de empresa o de creador). No necesita una
|
||||
página de Facebook vinculada: eso solo lo pide Messenger.
|
||||
|
||||
**Con Zernio**: sigue [Conectar por Zernio](#conectar-por-zernio-instagram-messenger-o-tiktok).
|
||||
|
||||
**Con una app propia de Meta**:
|
||||
|
||||
1. En [developers.facebook.com](https://developers.facebook.com) crea (o usa)
|
||||
una app con el producto **Instagram** y genera el token de la cuenta con
|
||||
los permisos `instagram_business_basic` e
|
||||
`instagram_business_manage_messages`. Anota el **ID de la cuenta**.
|
||||
2. En Vocero, **Configuración → Instagram**: elige *App propia de Meta*, pega
|
||||
el ID y el token y pulsa *Probar y guardar*.
|
||||
3. En la app de Meta, **Instagram → Webhooks**: objeto `instagram`, campo
|
||||
`messages`, con la URL de callback y el token de verificación que enseña
|
||||
la pantalla.
|
||||
|
||||
A la bandeja entran los mensajes directos; los comentarios de las
|
||||
publicaciones no. No hay plantillas: pasadas 24 horas del último mensaje del
|
||||
cliente ya solo puede contestar una persona, hasta 7 días (etiqueta
|
||||
`HUMAN_AGENT`); el agente no. Sin App Review, una
|
||||
app propia solo recibe mensajes de perfiles con un rol en la app. El detalle
|
||||
del canal está en [`specs/014-canal-instagram`](specs/014-canal-instagram/spec.md).
|
||||
|
||||
### TikTok (mensajes directos de una cuenta de negocio)
|
||||
|
||||
TikTok no entrega mensajes a una app propia: llegan por
|
||||
[Zernio](https://zernio.com), con tu cuenta de Zernio.
|
||||
|
||||
Sigue [Conectar por Zernio](#conectar-por-zernio-instagram-messenger-o-tiktok)
|
||||
desde **Configuración → TikTok**. Si la cuenta es personal, Vocero la conecta
|
||||
pero te avisa ahí mismo y en **Estado**: TikTok no le entrega mensajes hasta
|
||||
que sea Business.
|
||||
|
||||
Lo que TikTok impone, y Vocero te dice antes de que lo descubras con un
|
||||
mensaje rechazado:
|
||||
|
||||
- La cuenta tiene que ser **TikTok Business**, registrada fuera de la Unión
|
||||
Europea, Suiza y Reino Unido, con los mensajes directos abiertos.
|
||||
- **Tú no inicias**: solo contestas a quien te escribió.
|
||||
- Tras el último mensaje del cliente puedes mandar **hasta 10 mensajes, en 48
|
||||
horas**. No hay plantilla que reabra: el undécimo se rechaza (409
|
||||
`message_limit`) hasta que el cliente vuelva a escribir.
|
||||
- Cada mensaje es texto, de hasta 6,000 caracteres. Las imágenes entran (como
|
||||
aviso de que llegó una), pero todavía no se envían desde Vocero.
|
||||
|
||||
El detalle está en [`specs/022-canal-tiktok`](specs/022-canal-tiktok/spec.md).
|
||||
|
||||
## Configuración de la IA
|
||||
|
||||
Con esta llave piensa tu agente (a través del CRM, por `/api/bot/llm`) y el
|
||||
juez del Laboratorio. Se pone una vez, en la app: en **Ajustes → IA** eliges
|
||||
el proveedor (OpenRouter, o cualquier API compatible con la de OpenAI con su
|
||||
base URL), el modelo y pegas
|
||||
tu llave. «Probar conexión» hace una llamada mínima con lo escrito antes de
|
||||
guardar, «Traer modelos» lista los del proveedor, y la ayuda plegable explica
|
||||
dónde se consigue la llave. Se guarda cifrada (AES-256-GCM, la misma
|
||||
`ENCRYPTION_KEY` que protege el token de WhatsApp) y la pantalla solo enseña
|
||||
sus últimos 4.
|
||||
|
||||
Si el proveedor rechaza la llave (401) o la cuenta se queda sin saldo (402),
|
||||
la llave se pausa sola, un banner lo dice en toda la app y Ajustes → IA
|
||||
explica cuál de las dos cosas pasó. Guardar una llave nueva —o «Probar
|
||||
conexión» con la guardada después de recargar— lo reactiva. Un 429 o un 500
|
||||
del proveedor no pausan nada: son hipos, no problemas de la llave.
|
||||
|
||||
Las variables de entorno siguen valiendo como respaldo (instalaciones
|
||||
automatizadas, o quien ya las tenía): se usan mientras no haya nada guardado
|
||||
en Ajustes → IA, y lo guardado manda sobre ellas.
|
||||
|
||||
```bash
|
||||
OPENROUTER_API_TOKEN=sk-or-... # respaldo: tu key
|
||||
OPENROUTER_MODEL=anthropic/claude-sonnet-4.5
|
||||
OPENROUTER_JUDGE_MODEL= # opcional: modelo distinto para el juez del Laboratorio
|
||||
OPENROUTER_BASE_URL=https://openrouter.ai/api # o tu proveedor OpenAI-compatible
|
||||
```
|
||||
|
||||
Sin proveedor, todo lo demás funciona; Agente y Laboratorio enlazan a
|
||||
Ajustes → IA. Después configura el comportamiento y el conocimiento en la
|
||||
pestaña **Agente**, conecta tu agente y corre el **Laboratorio** antes de
|
||||
encenderlo con clientes reales.
|
||||
|
||||
## Cumplimiento con las políticas de Meta
|
||||
|
||||
1. **Opt-in**: escribe solo a personas que iniciaron la conversación o
|
||||
aceptaron recibir mensajes; Vocero respeta la ventana de 24 h y bloquea el
|
||||
texto libre fuera de ella.
|
||||
2. **Plantillas aprobadas** para reabrir conversaciones: nada de trucos para
|
||||
saltarse la aprobación de Meta.
|
||||
3. **El Laboratorio es 100 % interno**: los clientes simulados jamás tocan la
|
||||
API de WhatsApp (bloqueado por diseño y verificado con tests).
|
||||
4. **Sin spam ni broadcast**: Vocero no incluye envíos masivos; úsalo para
|
||||
conversaciones reales de venta y soporte.
|
||||
5. **Datos del cliente en su servidor**: cada negocio aloja su instancia; el
|
||||
token va cifrado en reposo y los webhooks se validan por URL secreta y
|
||||
firma opcional.
|
||||
|
||||
## FAQ de errores comunes
|
||||
|
||||
**El webhook no se verifica en Meta** — El dominio aún no resuelve, no es
|
||||
https, o el token no tiene `whatsapp_business_management`: el aviso al guardar
|
||||
trae el motivo tal cual lo dio Meta. Corrige y pulsa **«Registrar en Meta»** en
|
||||
Configuración → WhatsApp. Si lo pegas a mano, cópialos exactos de esa misma
|
||||
pantalla.
|
||||
|
||||
**El webhook verificó bien pero no llegan mensajes** — Casi siempre: la
|
||||
conexión no está GUARDADA en el wizard (el handshake no la necesita, la
|
||||
ingesta sí — enruta por el Phone Number ID guardado). Entra a Configuración →
|
||||
WhatsApp, guarda la conexión y reenvía un mensaje. Los logs de la instancia
|
||||
muestran una advertencia con el Phone Number ID desconocido.
|
||||
|
||||
**Llegan mensajes pero no salen** — Revisa el estado de la conexión en
|
||||
Configuración → WhatsApp. Si dice "reconectar", el token expiró: pega uno
|
||||
nuevo. En modo directo usa un token de usuario del sistema (no expira).
|
||||
|
||||
**Error 131030 al enviar** — El número destino no está en la lista de
|
||||
permitidos (números de prueba de Meta) o el formato es inválido. Vocero ya
|
||||
normaliza los números de México (521 → 52).
|
||||
|
||||
**El agente no responde** — Vocero no trae agente: ¿hay uno conectado? La
|
||||
tarjeta «Quién responde» de la pantalla Agente lo dice (y si su `/health`
|
||||
contesta). ¿El interruptor está encendido? ¿Llave de IA vigente en Ajustes →
|
||||
IA? ¿La conversación tiene la IA activa y sin handoff? ¿Ventana de 24 h
|
||||
abierta? Revisa también los logs de la instancia y los de tu agente.
|
||||
|
||||
**`ENCRYPTION_KEY` inválida al arrancar** — Debe ser exactamente 32 bytes en
|
||||
base64 (44 caracteres): `openssl rand -base64 32`.
|
||||
|
||||
**La app arranca pero /api/health falla** — La base de datos no está lista,
|
||||
`DATABASE_URL` apunta mal o alguna variable obligatoria no pasa la
|
||||
validación (p. ej. una `ENCRYPTION_KEY` mal generada): el healthcheck
|
||||
responde 503 en los tres casos. Revisa los logs (`docker compose logs app`); el de arranque nombra la
|
||||
variable que falló. Desde el repo, `pnpm doctor` revisa las tres cosas y dice
|
||||
cómo arreglar cada una.
|
||||
|
||||
**Subir el logo o el icono da error, o los adjuntos no se ven** — La app no
|
||||
puede escribir en `MEDIA_DIR` (`/data/media` en la imagen), y el log de
|
||||
arranque lo dice (`[boot] MEDIA_DIR … no es escribible`). Monta un volumen en
|
||||
`/data` (el compose ya lo hace; en Coolify, un persistent storage) y no definas
|
||||
`MEDIA_DIR` en la plataforma: el contenedor le da el volumen al usuario de la
|
||||
app al arrancar.
|
||||
|
||||
**Olvidé mi contraseña y no puedo entrar** — Vocero no manda correos (sería una
|
||||
dependencia externa) y el registro público se cierra con la primera
|
||||
organización, así que no hay flujo de "olvidé mi contraseña". La salida es
|
||||
reescribir el hash en la base:
|
||||
|
||||
```bash
|
||||
NEW_PASSWORD='tu-contraseña-nueva' node scripts/reset-password.mjs tu@correo.com
|
||||
```
|
||||
|
||||
El script **no toca la base**: te imprime el `UPDATE` para que lo pegues tú en
|
||||
la consola de Postgres. Corre desde tu máquina, con el repo clonado y
|
||||
`pnpm install` hecho — la contraseña nueva nunca sale de ahí. Va por variable de
|
||||
entorno y no por argumento porque un argumento queda en el historial del shell
|
||||
y se ve en `ps`.
|
||||
|
||||
Debe responder `UPDATE 1`. Si responde `UPDATE 0`, el correo no coincide;
|
||||
míralos con `SELECT email FROM "user";`.
|
||||
|
||||
## Versiones
|
||||
|
||||
La versión que está corriendo se ve **abajo en la barra lateral** (`v1.1.0 ·
|
||||
8e62d0b`) y en el healthcheck, para poder confirmar un despliegue con un
|
||||
`curl` sin abrir la app:
|
||||
|
||||
```bash
|
||||
curl -s https://crm.tudominio.com/api/health
|
||||
# {"ok":true,"version":"1.1.0","commit":"8e62d0b","commitVerified":true,
|
||||
# "features":{"agenda":false,"channels":["whatsapp"],"atribucion":false},
|
||||
# "mediaWritable":true}
|
||||
```
|
||||
|
||||
`features` dice qué banderas de despliegue están encendidas en esta instancia
|
||||
(`AGENDA`, `CHANNELS`, `ATRIBUCION`): es la forma de confirmar que la variable
|
||||
llegó al contenedor sin iniciar sesión. `mediaWritable` dice si `MEDIA_DIR`
|
||||
(el volumen `/data`) se puede escribir; con `false` el CRM sigue respondiendo
|
||||
`ok` (funciona sin adjuntos), pero el logo, el icono y los adjuntos no se van
|
||||
a guardar: revisa el volumen. Ese sondeo escribe de verdad y se recuerda un
|
||||
minuto, así que el healthcheck no toca el disco en cada llamada.
|
||||
|
||||
La versión sale de `package.json` y se congela al **construir**. El commit,
|
||||
solo si llega **al build**. La imagen publicada ya lo trae (se construye con
|
||||
el commit del tag), así que con ella `/api/health` responde
|
||||
`"commitVerified":true` sin hacer nada. Si construyes desde el código, pásalo
|
||||
como build arg `SOURCE_COMMIT` en cada despliegue. Con docker compose,
|
||||
`docker compose build --build-arg SOURCE_COMMIT=$(git rev-parse HEAD)` y
|
||||
luego `docker compose up -d --pull never` (sin `--build`, que reconstruiría
|
||||
sin él, y sin descargar la imagen publicada en lugar de la tuya); en Coolify o
|
||||
en cualquier otra plataforma, que el valor llegue como build arg
|
||||
`SOURCE_COMMIT`, no solo como variable de entorno. Así queda dentro del
|
||||
binario y sale con `"commitVerified":true`.
|
||||
|
||||
Si el build no lo trajo, la app enseña el `SOURCE_COMMIT` que encuentre en el
|
||||
entorno al arrancar, pero **no lo da por bueno**: en la barra lateral aparece
|
||||
como «commit sin verificar» y en el healthcheck con `"commitVerified":false`.
|
||||
Es lo que dice la plataforma, no el código, y solo es cierto si ella lo
|
||||
actualiza en cada despliegue. Una variable escrita a mano una vez se queda
|
||||
quieta mientras la app avanza debajo, y la insignia mostraría un commit que ya
|
||||
no corre: una variable fija es peor que dejarla vacía. Sin commit por ningún
|
||||
lado se ve solo la versión. Si un script compara commits para confirmar un
|
||||
despliegue, que exija `commitVerified: true`.
|
||||
|
||||
SemVer sobre lo que le importa a quien opera una instancia:
|
||||
|
||||
| | Cuándo sube |
|
||||
|---|---|
|
||||
| **Mayor** (`2.0.0`) | Hay que hacer algo a mano para actualizar: cambiar una variable de entorno, migrar datos, reconectar algo. |
|
||||
| **Menor** (`1.2.0`) | Funciones nuevas. Actualizar es redesplegar. |
|
||||
| **Parche** (`1.1.1`) | Arreglos y ajustes. Actualizar es redesplegar. |
|
||||
|
||||
La versión vive en `package.json` y se sube en el PR que publica el cambio,
|
||||
junto con el default de `VOCERO_CRM_VERSION` en `docker-compose.yml` y la
|
||||
etiqueta de la imagen en `render.yaml`, `fly.toml` y `railway.toml` (dos
|
||||
pruebas exigen que coincidan) y su entrada en [`CHANGELOG.md`](CHANGELOG.md),
|
||||
que dice qué trae cada versión y qué hacer para actualizar. Al crear el tag
|
||||
`vX.Y.Z`, el CI publica la imagen `ghcr.io/kevinrivm/vocero-crm:X.Y.Z`.
|
||||
|
||||
## Roadmap
|
||||
|
||||
Las versiones 1.5 y 2.0 tienen plan propio:
|
||||
[docs/plan-1.5-y-2.0.md](docs/plan-1.5-y-2.0.md).
|
||||
|
||||
- Adjuntos en Instagram, Messenger y TikTok (hoy esos canales son de texto; en
|
||||
WhatsApp ya van y vienen con vista previa).
|
||||
- RAG para knowledge bases grandes (hoy: se inyecta completo con aviso de tamaño).
|
||||
- Personas configurables del Laboratorio y comparativas entre corridas.
|
||||
- Borrado de plantillas desde la app.
|
||||
- Métricas de plantillas (las de ventas, origen y conversaciones ya están en
|
||||
Resultados).
|
||||
- Broadcast con opt-in verificado.
|
||||
|
||||
### Antes fuera de alcance, ahora detrás de una bandera
|
||||
|
||||
**El motor de agendamiento ya está en el core**, apagado por defecto. Aquí
|
||||
decía que quedaba fuera a propósito, con dos razones. Las dos eran buenas y
|
||||
las dos cambiaron; se dejan escritas porque el porqué importa más que la
|
||||
conclusión:
|
||||
|
||||
- *"Son mil líneas y una dependencia de fechas en un proyecto cuyo argumento es
|
||||
ser ligero."* — Cierto, y por eso vive detrás de `AGENDA`: una instancia que
|
||||
no agenda no ve pantallas, ni rutas, ni una instrucción de agendar en el
|
||||
prompt de su agente, ni se le pide una sola credencial. El peso lo paga quien
|
||||
la enciende. Lo de la dependencia de fechas ya no aplica: el motor no agregó
|
||||
ninguna (la aritmética de zonas usa `Intl` de la plataforma).
|
||||
- *"El estado de qué huecos se ofrecieron pertenece a la conversación, o sea al
|
||||
agente, no al CRM."* — Pertenecía al agente mientras el CRM no ofreciera la
|
||||
garantía. Al ofrecerla, es el CRM quien tiene que poder probarla: con la
|
||||
memoria del lado del cliente, cualquier cerebro conectado por `/api/bot/*`
|
||||
podría reservar un horario que jamás se ofreció y el CRM lo aceptaría. Ahora
|
||||
la regla es inviolable por construcción y vale igual para Nea, para tu bot y
|
||||
para el que venga.
|
||||
|
||||
Lo que sigue fuera, y a propósito: **leer calendarios externos** para descontar
|
||||
disponibilidad. El motor calcula con lo suyo y los compromisos de fuera se
|
||||
reflejan con bloqueos manuales; meter al proveedor en ese camino acoplaría su
|
||||
latencia y sus caídas a la pantalla que más se usa.
|
||||
|
||||
## Stack
|
||||
|
||||
Next.js 15 (App Router) + React 19 · TypeScript estricto · PostgreSQL +
|
||||
Drizzle ORM · Better Auth · Tailwind CSS · SSE (sin WebSockets) · Docker
|
||||
multi-stage con migraciones al arranque. Diseñado para que una agencia lo
|
||||
modifique con un asistente de IA: specs y decisiones de diseño en
|
||||
[`specs/`](specs/), guía de modificación en [`AGENTS.md`](AGENTS.md) (y lo específico de Claude Code en [`CLAUDE.md`](CLAUDE.md)).
|
||||
|
||||
## Licencia
|
||||
|
||||
[MIT](LICENSE) — úsalo, véndelo instalado, modifícalo. Si te sirve, una ⭐ al
|
||||
repo ayuda a que más gente lo encuentre.
|
||||
|
||||
## Créditos
|
||||
|
||||
Creado por [Kevin Belier](https://www.youtube.com/@KevinBelier). ¿Quieres
|
||||
venderlo a otros negocios, adaptarlo y entregarlo sin que truene? Únete a la
|
||||
[VIBE Community](https://kevinbelier.cloud/comunidad). Los patrones
|
||||
de producción (webhook firmado, ingesta idempotente, cifrado de tokens) vienen
|
||||
de un proyecto de referencia privado en producción, portados y simplificados
|
||||
para este repo.
|
||||
@@ -0,0 +1,79 @@
|
||||
# CRM marca blanca — compose autocontenido para paneles con reverse proxy
|
||||
# (aaPanel «Add compose», Plesk, Portainer…). Guía: DEPLOY.md, escenario B.
|
||||
# La app escucha SOLO en 127.0.0.1:${PORT}; el proxy del sitio pone el HTTPS.
|
||||
services:
|
||||
app:
|
||||
image: ${CRM_IMAGE:-ghcr.io/djcoraanco/crmmonkey}:${CRM_TAG:-latest}
|
||||
build:
|
||||
context: ${CRM_BUILD_CONTEXT:-https://github.com/djcoraanco/crmmonkey.git#main}
|
||||
dockerfile: Dockerfile
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "127.0.0.1:${PORT:-3001}:3000"
|
||||
environment:
|
||||
PORT: 3000
|
||||
APP_BASE_URL: ${APP_BASE_URL}
|
||||
DATABASE_URL: postgresql://postgres:${POSTGRES_PASSWORD}@postgres:5432/vocero
|
||||
BETTER_AUTH_SECRET: ${BETTER_AUTH_SECRET}
|
||||
ENCRYPTION_KEY: ${ENCRYPTION_KEY}
|
||||
META_WEBHOOK_VERIFY_TOKEN: ${META_WEBHOOK_VERIFY_TOKEN}
|
||||
META_APP_SECRET: ${META_APP_SECRET:-}
|
||||
META_GRAPH_API_VERSION: ${META_GRAPH_API_VERSION:-v25.0}
|
||||
OPENROUTER_API_TOKEN: ${OPENROUTER_API_TOKEN:-}
|
||||
OPENROUTER_MODEL: ${OPENROUTER_MODEL:-}
|
||||
OPENROUTER_JUDGE_MODEL: ${OPENROUTER_JUDGE_MODEL:-}
|
||||
CHANNELS: ${CHANNELS-whatsapp,instagram,messenger,tiktok}
|
||||
AGENDA: ${AGENDA-on}
|
||||
ATRIBUCION: ${ATRIBUCION-on}
|
||||
SUPERADMIN_EMAIL: ${SUPERADMIN_EMAIL:-}
|
||||
SUPERADMIN_PASSWORD: ${SUPERADMIN_PASSWORD:-}
|
||||
SUPERADMIN_NAME: ${SUPERADMIN_NAME:-Administrador}
|
||||
SUPERADMIN_ORG_NAME: ${SUPERADMIN_ORG_NAME:-}
|
||||
BRAND_NAME: ${BRAND_NAME:-}
|
||||
BRAND_ACCENT: ${BRAND_ACCENT:-}
|
||||
BRAND_CURRENCY: ${BRAND_CURRENCY:-}
|
||||
BUSINESS_DESCRIPTION: ${BUSINESS_DESCRIPTION:-}
|
||||
WHISPER_PROVIDER: ${WHISPER_PROVIDER:-}
|
||||
WHISPER_API_KEY: ${WHISPER_API_KEY:-}
|
||||
WHISPER_LANGUAGE: ${WHISPER_LANGUAGE:-es}
|
||||
BOT_API_KEY: ${BOT_API_KEY:-}
|
||||
BRAIN_HEALTH_URL: ${BRAIN_HEALTH_URL-http://nea:8000/health}
|
||||
BRAIN_DISPATCH_URL: ${BRAIN_DISPATCH_URL-http://nea:8000/vocero/dispatch}
|
||||
volumes:
|
||||
- crm_app_data:/data
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
|
||||
nea:
|
||||
image: ghcr.io/kevinrivm/nea-agent:${NEA_VERSION:-2.0.2}
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
CRM_BASE_URL: http://app:3000
|
||||
CRM_BOT_API_KEY: ${BOT_API_KEY:-}
|
||||
DATABASE_URL: postgresql://postgres:${POSTGRES_PASSWORD}@postgres:5432/vocero
|
||||
DATABASE_SCHEMA: nea
|
||||
LLM_MODEL: ${OPENROUTER_MODEL:-z-ai/glm-5.3-flash}
|
||||
ALLOWED_WA_IDS: ${ALLOWED_WA_IDS:-}
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
|
||||
POSTGRES_DB: vocero
|
||||
volumes:
|
||||
- crm_pg:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U postgres -d vocero"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
|
||||
volumes:
|
||||
crm_pg:
|
||||
crm_app_data:
|
||||
@@ -0,0 +1,55 @@
|
||||
# CRM marca blanca — .env para deploy/aapanel/docker-compose.yml.
|
||||
# Copia, reemplaza cada REEMPLAZA_ y pega en «.env Content». Guía: DEPLOY.md.
|
||||
|
||||
# URL pública (la del reverse proxy, con https) y puerto local al que apunta
|
||||
APP_BASE_URL=https://REEMPLAZA_crm.tudominio.com
|
||||
PORT=3001
|
||||
|
||||
# Imagen (la publica la CI de GitHub). Si es privada: docker login ghcr.io.
|
||||
# Sin registro, se construye desde CRM_BUILD_CONTEXT (repo privado:
|
||||
# https://USUARIO:TOKEN@github.com/USUARIO/REPO.git#main).
|
||||
CRM_IMAGE=ghcr.io/djcoraanco/crmmonkey
|
||||
CRM_TAG=latest
|
||||
# CRM_BUILD_CONTEXT=https://USUARIO:TOKEN@github.com/djcoraanco/crmmonkey.git#main
|
||||
|
||||
# Secretos — uno distinto por instancia:
|
||||
# openssl rand -hex 24 → POSTGRES_PASSWORD, META_WEBHOOK_VERIFY_TOKEN
|
||||
# openssl rand -base64 32 → BETTER_AUTH_SECRET, ENCRYPTION_KEY (no la cambies nunca)
|
||||
# openssl rand -hex 32 → BOT_API_KEY
|
||||
POSTGRES_PASSWORD=REEMPLAZA_password_de_postgres
|
||||
BETTER_AUTH_SECRET=REEMPLAZA_secreto_de_sesiones
|
||||
ENCRYPTION_KEY=REEMPLAZA_clave_de_cifrado_base64
|
||||
META_WEBHOOK_VERIFY_TOKEN=REEMPLAZA_token_de_verificacion
|
||||
BOT_API_KEY=REEMPLAZA_llave_del_cerebro
|
||||
|
||||
# Meta (App de Meta → Configuración → Básica → Clave secreta)
|
||||
META_APP_SECRET=
|
||||
META_GRAPH_API_VERSION=v25.0
|
||||
|
||||
# Dueño de la instancia (se crea solo al arrancar)
|
||||
SUPERADMIN_EMAIL=REEMPLAZA_tu_correo@tudominio.com
|
||||
SUPERADMIN_PASSWORD=REEMPLAZA_contraseña_min_8
|
||||
SUPERADMIN_NAME=Administrador
|
||||
SUPERADMIN_ORG_NAME=Mi negocio
|
||||
|
||||
# Identidad inicial (una vez; luego se cambia en Ajustes → Marca)
|
||||
BRAND_NAME=Mi CRM
|
||||
BRAND_ACCENT=#009c98
|
||||
BRAND_CURRENCY=MXN
|
||||
BUSINESS_DESCRIPTION=
|
||||
|
||||
# Módulos (vacío = apagado)
|
||||
CHANNELS=whatsapp,instagram,messenger,tiktok
|
||||
AGENDA=on
|
||||
ATRIBUCION=on
|
||||
|
||||
# IA: mejor desde la app (Ajustes → IA); esto es solo respaldo
|
||||
OPENROUTER_API_TOKEN=
|
||||
OPENROUTER_MODEL=
|
||||
|
||||
# Opcional: notas de voz a texto
|
||||
# WHISPER_PROVIDER=groq
|
||||
# WHISPER_API_KEY=
|
||||
|
||||
# Mientras pruebas, el agente solo contesta a estos números (vacío = a todos)
|
||||
ALLOWED_WA_IDS=
|
||||
@@ -0,0 +1,24 @@
|
||||
# Postgres local para desarrollo. Uso: docker compose -f docker-compose.dev.yml up -d
|
||||
# `name` propio: evita colisionar con el proyecto del docker-compose.yml (Ruta B).
|
||||
name: vocero-dev
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-postgres}
|
||||
POSTGRES_DB: vocero
|
||||
ports:
|
||||
- "5432:5432"
|
||||
volumes:
|
||||
- vocero_dev_pg:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U postgres -d vocero"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 10
|
||||
|
||||
volumes:
|
||||
vocero_dev_pg:
|
||||
@@ -0,0 +1,254 @@
|
||||
# ============================================================
|
||||
# CRM marca blanca — docker compose (app + Postgres + agente; Caddy opcional)
|
||||
#
|
||||
# Guía completa por escenario: DEPLOY.md
|
||||
# docker compose up -d app en http://SERVIDOR:${PORT:-3003}
|
||||
# docker compose --profile caddy up -d + HTTPS automático con Caddy
|
||||
# docker compose --profile autoupdate up -d + Watchtower (solo actualiza `app`)
|
||||
# ./scripts/update-live.sh actualiza SOLO la app, sin tocar
|
||||
# Postgres ni los volúmenes
|
||||
#
|
||||
# La imagen sale de GHCR (la publica la CI en cada push a main, etiqueta
|
||||
# `latest`); se cambia con CRM_IMAGE / CRM_TAG. Si no se puede bajar, Compose
|
||||
# la construye desde CRM_BUILD_CONTEXT (por defecto, este clon).
|
||||
#
|
||||
# La identidad del negocio (nombre, color, moneda, giro) va en el .env:
|
||||
# BRAND_*, BUSINESS_DESCRIPTION y SUPERADMIN_* (ver .env.example).
|
||||
#
|
||||
# --- Notas de la base original (Vocero) ---
|
||||
# Ruta B: app + Postgres + Caddy (HTTPS automático)
|
||||
# Uso: pnpm init-env --domain tu.dominio → pnpm doctor → docker compose up -d
|
||||
# (sin Node: cp .env.example .env y rellenar a mano)
|
||||
# Actualizar: git pull → docker compose up -d
|
||||
#
|
||||
# La app sale de la imagen publicada de la versión (una por tag vX.Y.Z). Con
|
||||
# `image` y `build` juntos y sin `pull_policy`, Compose intenta primero
|
||||
# descargar la imagen y solo la construye desde este repo si no la encuentra
|
||||
# ni en el registro ni en tu máquina (especificación de Compose, «Using build
|
||||
# and image»: docs.docker.com/reference/compose-file/build/):
|
||||
#
|
||||
# docker compose up -d la imagen publicada
|
||||
# docker compose up -d --build construida desde el código (la publicada
|
||||
# es linux/amd64: en un VPS ARM, construye)
|
||||
#
|
||||
# Lo que construyes queda en tu máquina con este mismo nombre de imagen. En un
|
||||
# fork con cambios propios usa siempre --build (o cambia `image:` por un
|
||||
# nombre tuyo): sin él, Compose puede correr la imagen oficial en vez de tus
|
||||
# cambios. Otra versión publicada: VOCERO_CRM_VERSION=X.Y.Z en tu .env.
|
||||
#
|
||||
# SEGURIDAD (oct-2026): las imágenes publicadas hasta la 2.5.2 traen next
|
||||
# 15.5.27, sharp 0.34.5 y Node 22.23.3, vulnerables a RCE sin autenticación en
|
||||
# el optimizador de imágenes (CVE-2026-96889 / GHSA-2464-fhr4-w9xw) y en el
|
||||
# decodificador Brotli de Node (CVE-2026-111497). La 2.5.3 ya trae next
|
||||
# 15.5.28, sharp 0.35.5 y node:22.23.4-alpine: usa la 2.5.3 o una posterior.
|
||||
#
|
||||
# 2.0 — El agente (Nea) es un servicio al lado del CRM, sobre la MISMA base
|
||||
# en su esquema `nea`, y se levanta con todo lo demás. El CRM le despacha cada
|
||||
# ráfaga a http://nea:8000 y Nea contesta por /api/bot/*, con la BOT_API_KEY
|
||||
# del .env (`pnpm init-env` la genera). Nea no lleva llave de IA: piensa por
|
||||
# el CRM con la de Ajustes → IA (036). Para conectar otro cerebro, cambia
|
||||
# BRAIN_DISPATCH_URL y BRAIN_HEALTH_URL en el .env; para no usar ninguno
|
||||
# (bandeja manual), déjalas vacías: BRAIN_DISPATCH_URL= y BRAIN_HEALTH_URL=.
|
||||
# Guía: docs/migrar-a-2.0.md.
|
||||
#
|
||||
# 037 — Adjuntos en un bucket S3-compatible (opcional; por defecto, el volumen
|
||||
# de abajo). Con MEDIA_STORE=bucket y las MEDIA_BUCKET_* en el .env, el perfil
|
||||
# `bucket` levanta un MinIO propio en este mismo servidor:
|
||||
#
|
||||
# docker compose --profile bucket up -d
|
||||
#
|
||||
# Para un bucket de fuera (R2, S3, Backblaze) no hace falta el perfil: basta
|
||||
# con las variables. Guía: README, «Adjuntos en un bucket».
|
||||
# ============================================================
|
||||
services:
|
||||
app:
|
||||
image: ${CRM_IMAGE:-ghcr.io/djcoraanco/crmmonkey}:${CRM_TAG:-latest}
|
||||
build:
|
||||
context: ${CRM_BUILD_CONTEXT:-.}
|
||||
dockerfile: Dockerfile
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
# Host ${PORT:-3003} → contenedor 3000 (la imagen siempre escucha en 3000).
|
||||
- "${PORT:-3003}:3000"
|
||||
labels:
|
||||
# Watchtower (perfil `autoupdate`) actualiza SOLO lo que lleva esta marca.
|
||||
com.centurylinklabs.watchtower.enable: "true"
|
||||
environment:
|
||||
PORT: 3000
|
||||
APP_BASE_URL: ${APP_BASE_URL}
|
||||
DATABASE_URL: postgresql://postgres:${POSTGRES_PASSWORD}@postgres:5432/vocero
|
||||
BETTER_AUTH_SECRET: ${BETTER_AUTH_SECRET}
|
||||
ENCRYPTION_KEY: ${ENCRYPTION_KEY}
|
||||
META_WEBHOOK_VERIFY_TOKEN: ${META_WEBHOOK_VERIFY_TOKEN}
|
||||
META_APP_SECRET: ${META_APP_SECRET:-}
|
||||
META_GRAPH_API_VERSION: ${META_GRAPH_API_VERSION:-v25.0}
|
||||
OPENROUTER_API_TOKEN: ${OPENROUTER_API_TOKEN:-}
|
||||
OPENROUTER_BASE_URL: ${OPENROUTER_BASE_URL:-https://openrouter.ai/api}
|
||||
OPENROUTER_MODEL: ${OPENROUTER_MODEL:-}
|
||||
OPENROUTER_JUDGE_MODEL: ${OPENROUTER_JUDGE_MODEL:-}
|
||||
ALLOW_SIGNUP: ${ALLOW_SIGNUP:-}
|
||||
AGENT_COALESCE_MS: ${AGENT_COALESCE_MS:-6000}
|
||||
AGENT_COALESCE_LARGO_MS: ${AGENT_COALESCE_LARGO_MS:-8000}
|
||||
# Opcionales: vacías = apagadas (guía de cada una en .env.example).
|
||||
# Marca blanca: encendidos por defecto. Para apagar uno, defínelo vacío en el
|
||||
# .env (p. ej. `AGENDA=`).
|
||||
CHANNELS: ${CHANNELS-whatsapp,instagram,messenger,tiktok}
|
||||
AGENDA: ${AGENDA-on}
|
||||
ATRIBUCION: ${ATRIBUCION-on}
|
||||
# Superadmin: semilla idempotente al arrancar (ver .env.example).
|
||||
SUPERADMIN_EMAIL: ${SUPERADMIN_EMAIL:-}
|
||||
SUPERADMIN_PASSWORD: ${SUPERADMIN_PASSWORD:-}
|
||||
SUPERADMIN_NAME: ${SUPERADMIN_NAME:-Administrador}
|
||||
SUPERADMIN_ORG_NAME: ${SUPERADMIN_ORG_NAME:-}
|
||||
# Identidad inicial (se aplica una vez; luego manda Ajustes → Marca).
|
||||
BRAND_NAME: ${BRAND_NAME:-}
|
||||
BRAND_ACCENT: ${BRAND_ACCENT:-}
|
||||
BRAND_CURRENCY: ${BRAND_CURRENCY:-}
|
||||
BUSINESS_DESCRIPTION: ${BUSINESS_DESCRIPTION:-}
|
||||
# Transcripción de notas de voz (opcional).
|
||||
WHISPER_PROVIDER: ${WHISPER_PROVIDER:-}
|
||||
WHISPER_API_KEY: ${WHISPER_API_KEY:-}
|
||||
WHISPER_BASE_URL: ${WHISPER_BASE_URL:-}
|
||||
WHISPER_MODEL: ${WHISPER_MODEL:-}
|
||||
WHISPER_LANGUAGE: ${WHISPER_LANGUAGE:-es}
|
||||
BOT_API_KEY: ${BOT_API_KEY:-}
|
||||
# 2.0 — El cerebro: por defecto, el servicio `nea` de abajo. Con la
|
||||
# variable definida pero vacía en el .env, ninguno (bandeja manual).
|
||||
BRAIN_HEALTH_URL: ${BRAIN_HEALTH_URL-http://nea:8000/health}
|
||||
BRAIN_DISPATCH_URL: ${BRAIN_DISPATCH_URL-http://nea:8000/vocero/dispatch}
|
||||
# 037 — Vacía = disco. `bucket` + las MEDIA_BUCKET_* = el bucket; con el
|
||||
# perfil `bucket`, MEDIA_BUCKET_ENDPOINT=http://minio:9000.
|
||||
MEDIA_STORE: ${MEDIA_STORE:-}
|
||||
MEDIA_BUCKET_ENDPOINT: ${MEDIA_BUCKET_ENDPOINT:-}
|
||||
MEDIA_BUCKET_NAME: ${MEDIA_BUCKET_NAME:-}
|
||||
MEDIA_BUCKET_REGION: ${MEDIA_BUCKET_REGION:-us-east-1}
|
||||
MEDIA_BUCKET_KEY_ID: ${MEDIA_BUCKET_KEY_ID:-}
|
||||
MEDIA_BUCKET_SECRET: ${MEDIA_BUCKET_SECRET:-}
|
||||
volumes:
|
||||
# Adjuntos, logo e icono (la imagen ya trae MEDIA_DIR=/data/media): sin
|
||||
# este volumen se pierden al recrear el contenedor.
|
||||
- vocero_app_data:/data
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
# el HEALTHCHECK vive en el Dockerfile (/api/health)
|
||||
|
||||
# 035 — El agente. Misma base que el CRM, en su esquema `nea`: el par no
|
||||
# pide una segunda base. La llave del despacho es BOT_API_KEY, la misma
|
||||
# con la que Nea le contesta al CRM. Sin dominio público: el CRM le habla
|
||||
# por la red interna.
|
||||
nea:
|
||||
image: ghcr.io/kevinrivm/nea-agent:${NEA_VERSION:-2.0.2}
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
CRM_BASE_URL: http://app:3000
|
||||
CRM_BOT_API_KEY: ${BOT_API_KEY:-}
|
||||
DATABASE_URL: postgresql://postgres:${POSTGRES_PASSWORD}@postgres:5432/vocero
|
||||
DATABASE_SCHEMA: nea
|
||||
# 036 — Sin LLM_API_KEY: Nea piensa por el CRM (/api/bot/llm) con la
|
||||
# llave de Ajustes → IA y el modelo que elegiste ahí. Este es solo el
|
||||
# de respaldo, si el CRM todavía no tiene modelo.
|
||||
LLM_MODEL: ${OPENROUTER_MODEL:-z-ai/glm-5.3-flash}
|
||||
# Mientras pruebas: tu número. Vacía = Nea le contesta a todos.
|
||||
ALLOWED_WA_IDS: ${ALLOWED_WA_IDS:-}
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
|
||||
POSTGRES_DB: vocero
|
||||
volumes:
|
||||
- vocero_pg:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U postgres -d vocero"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
|
||||
# 037 — El bucket propio, en este mismo servidor y sin puertos públicos: el
|
||||
# CRM le habla por la red interna. Sus llaves de administrador son las
|
||||
# MEDIA_BUCKET_KEY_ID y MEDIA_BUCKET_SECRET del .env (la secreta, 8+
|
||||
# caracteres). Los archivos viven en su volumen.
|
||||
minio:
|
||||
# La de Coolify: las imágenes oficiales de MinIO dejaron Docker Hub. Trae
|
||||
# `mc` adentro, que usa el contenedor de abajo.
|
||||
image: coollabsio/minio:RELEASE.2025-10-15T17-29-55Z
|
||||
profiles: ["bucket"]
|
||||
restart: unless-stopped
|
||||
command: server /data
|
||||
environment:
|
||||
MINIO_ROOT_USER: ${MEDIA_BUCKET_KEY_ID:-}
|
||||
MINIO_ROOT_PASSWORD: ${MEDIA_BUCKET_SECRET:-}
|
||||
volumes:
|
||||
- vocero_minio:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "mc", "ready", "local"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
|
||||
# Crea el bucket una vez (si ya existe, no hace nada) y termina.
|
||||
minio-bucket:
|
||||
image: coollabsio/minio:RELEASE.2025-10-15T17-29-55Z
|
||||
profiles: ["bucket"]
|
||||
restart: "no"
|
||||
environment:
|
||||
KEY_ID: ${MEDIA_BUCKET_KEY_ID:-}
|
||||
SECRET: ${MEDIA_BUCKET_SECRET:-}
|
||||
BUCKET: ${MEDIA_BUCKET_NAME:-vocero}
|
||||
entrypoint: ["/bin/sh", "-c", "mc alias set local http://minio:9000 \"$$KEY_ID\" \"$$SECRET\" && mc mb --ignore-existing \"local/$$BUCKET\""]
|
||||
depends_on:
|
||||
minio:
|
||||
condition: service_healthy
|
||||
|
||||
caddy:
|
||||
image: caddy:2-alpine
|
||||
# Opcional. `docker compose --profile caddy up -d`.
|
||||
profiles: ["caddy"]
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "80:80"
|
||||
- "443:443"
|
||||
environment:
|
||||
DOMAIN: ${DOMAIN}
|
||||
volumes:
|
||||
- ./Caddyfile:/etc/caddy/Caddyfile:ro
|
||||
- vocero_caddy_data:/data
|
||||
- vocero_caddy_config:/config
|
||||
depends_on:
|
||||
- app
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-q", "--spider", "http://127.0.0.1:2019/config/"]
|
||||
interval: 15s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
# Actualización automática OPCIONAL: vigila el registro y recrea
|
||||
# solo los contenedores marcados (únicamente `app`). Postgres, el agente y
|
||||
# los volúmenes no se tocan. `docker compose --profile autoupdate up -d`.
|
||||
watchtower:
|
||||
image: containrrr/watchtower:latest
|
||||
profiles: ["autoupdate"]
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
WATCHTOWER_LABEL_ENABLE: "true"
|
||||
WATCHTOWER_CLEANUP: "true"
|
||||
WATCHTOWER_POLL_INTERVAL: ${WATCHTOWER_POLL_INTERVAL:-300}
|
||||
# Registro privado (GHCR): tu usuario de GitHub y un token con
|
||||
# read:packages. Vacíos si la imagen es pública.
|
||||
REPO_USER: ${REGISTRY_USER:-}
|
||||
REPO_PASS: ${REGISTRY_TOKEN:-}
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
|
||||
volumes:
|
||||
vocero_pg:
|
||||
vocero_app_data:
|
||||
vocero_minio:
|
||||
vocero_caddy_data:
|
||||
vocero_caddy_config:
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 252 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 238 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 70 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 70 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 265 KiB |
Loaded 100 of 1316 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user