diff --git a/.claude/skills/speckit-agent-context-update/SKILL.md b/.claude/skills/speckit-agent-context-update/SKILL.md index 667e84b..46688e0 100644 --- a/.claude/skills/speckit-agent-context-update/SKILL.md +++ b/.claude/skills/speckit-agent-context-update/SKILL.md @@ -1,9 +1,9 @@ --- name: speckit-agent-context-update -description: Refresh the managed Spec Kit section in the coding agent context file +description: Refresh the managed Spec Kit section in coding agent context file(s) compatibility: Requires spec-kit project structure with .specify/ directory metadata: - author: github-spec-kit + author: spec-kit-core source: agent-context:commands/speckit.agent-context.update.md --- @@ -17,15 +17,16 @@ 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_files` — optional project-relative paths for multiple coding agent context files. When non-empty, the script updates each listed file and the list takes precedence over `context_file`. - `context_markers.start` / `.end` — the delimiters surrounding the managed section. Defaults to `` and `` 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//plan.md`). +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 (any `plan.md` under `specs/`, including nested scoped layouts such as `specs///plan.md`). -If `context_file` is empty or the file cannot be located, the command reports nothing to do and exits successfully. +If `context_files` and `context_file` are empty, the command reports nothing to do and exits successfully. Context file paths must stay project-relative; absolute paths, Windows drive paths, backslash separators, and `..` path segments are rejected. ## 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`. \ No newline at end of file +When `plan_path` is omitted, the script auto-detects the most recently modified `specs/**/plan.md` (searched recursively, so nested scoped layouts are discovered). \ No newline at end of file diff --git a/.claude/skills/speckit-analyze/SKILL.md b/.claude/skills/speckit-analyze/SKILL.md index 700a27c..218081f 100644 --- a/.claude/skills/speckit-analyze/SKILL.md +++ b/.claude/skills/speckit-analyze/SKILL.md @@ -24,12 +24,12 @@ You **MUST** consider the user input before proceeding (if not empty). **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 +- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally - Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default. - For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions: - If the hook has no `condition` field, or it is null/empty, treat the hook as executable - If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation -- When constructing slash commands from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`. +- When constructing command invocations 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`): ``` @@ -52,6 +52,7 @@ You **MUST** consider the user input before proceeding (if not empty). Wait for the result of the hook command before proceeding to the Goal. ``` + After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook. - If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently ## Goal @@ -68,7 +69,7 @@ Identify inconsistencies, duplications, ambiguities, and underspecified items ac ### 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: +Run `.specify/scripts/powershell/check-prerequisites.ps1 -Json -RequireSpec -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 @@ -210,12 +211,12 @@ Ask the user: "Would you like me to suggest concrete remediation edits for the t 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 +- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally - Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default. - For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions: - If the hook has no `condition` field, or it is null/empty, treat the hook as executable - If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation -- When constructing slash commands from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`. +- When constructing command invocations 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`): ``` @@ -236,6 +237,7 @@ After reporting, check if `.specify/extensions.yml` exists in the project root. Executing: `/{command}` EXECUTE_COMMAND: {command} ``` + After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook. - If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently ## Operating Principles diff --git a/.claude/skills/speckit-checklist/SKILL.md b/.claude/skills/speckit-checklist/SKILL.md index fbd969a..f8e6b75 100644 --- a/.claude/skills/speckit-checklist/SKILL.md +++ b/.claude/skills/speckit-checklist/SKILL.md @@ -32,6 +32,15 @@ disable-model-invocation: false **Metaphor**: If your spec is code written in English, the checklist is its unit test suite. You're testing whether the requirements are well-written, complete, unambiguous, and ready for implementation - NOT whether the implementation works. +**Ownership and checkbox lifecycle**: + +- Custom checklists generated by this command are reviewer-owned requirements-quality review artifacts. +- `[x]` means the reviewer determined the requirements-quality criterion is satisfied. +- `[x]` does NOT mean implementation work is complete. +- This command generates or appends checklist items; it MUST NOT mark generated items `[x]`. +- An agent may assist with evaluating items only when explicitly asked by the reviewer. +- `checklists/requirements.md` is a separate built-in spec-quality checklist maintained by `/speckit-specify` and `/speckit-clarify`; do not treat that exception as applying to custom checklists generated here. + ## User Input ```text @@ -45,12 +54,12 @@ You **MUST** consider the user input before proceeding (if not empty). **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 +- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally - Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default. - For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions: - If the hook has no `condition` field, or it is null/empty, treat the hook as executable - If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation -- When constructing slash commands from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`. +- When constructing command invocations 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`): ``` @@ -73,11 +82,12 @@ You **MUST** consider the user input before proceeding (if not empty). Wait for the result of the hook command before proceeding to the Execution Steps. ``` + After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook. - If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently ## Execution Steps -1. **Setup**: Run `.specify/scripts/powershell/check-prerequisites.ps1 -Json` from repo root and parse JSON for FEATURE_DIR and AVAILABLE_DOCS list. +1. **Setup**: Run `.specify/scripts/powershell/check-prerequisites.ps1 -Json -Template checklist-template` from repo root and parse JSON for FEATURE_DIR, AVAILABLE_DOCS list, and TEMPLATE_CONTENT. - All file paths must be absolute. - For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot"). @@ -132,7 +142,7 @@ You **MUST** consider the user input before proceeding (if not empty). - 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": +6. **Generate checklist** - Use TEMPLATE_CONTENT as the structural template and create "Unit Tests for Requirements": - Create `FEATURE_DIR/checklists/` directory if it doesn't exist - Generate unique checklist filename: - Use short, descriptive name based on domain (e.g., `ux.md`, `api.md`, `security.md`) @@ -141,6 +151,7 @@ You **MUST** consider the user input before proceeding (if not empty). - If file does NOT exist: Create new file and number items starting from CHK001 - If file exists: Append new items to existing file, continuing from the last CHK ID (e.g., if last item is CHK015, start new items at CHK016) - Never delete or replace existing checklist content - always preserve and append + - Leave every newly generated item unchecked (`[ ]`); checkbox state belongs to the reviewer **CORE PRINCIPLE - Test the Requirements, Not the Implementation**: Every checklist item MUST evaluate the REQUIREMENTS THEMSELVES for: @@ -250,7 +261,7 @@ You **MUST** consider the user input before proceeding (if not empty). - ✅ "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### ` lines with globally incrementing IDs starting at CHK001. +7. **Structure Reference**: Generate the checklist following the canonical template in `.specify/templates/checklist-template.md` for title, meta section, category headings, ownership note, notes section, and ID formatting. If template is unavailable, use: H1 title, purpose/created meta lines, an ownership note explaining that `[x]` means reviewer approval of requirements quality, `##` category sections containing `- [ ] CHK### ` lines with globally incrementing IDs starting at CHK001, and notes that `/speckit-implement` reads checklist state but does not modify markers. 8. **Report**: Output full path to checklist file, item count, and summarize whether the run created a new file or appended to an existing one. Summarize: - Focus areas selected @@ -345,12 +356,12 @@ Sample items: **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 +- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally - Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default. - For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions: - If the hook has no `condition` field, or it is null/empty, treat the hook as executable - If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation -- When constructing slash commands from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`. +- When constructing command invocations 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`): ``` @@ -371,4 +382,5 @@ Check if `.specify/extensions.yml` exists in the project root. Executing: `/{command}` EXECUTE_COMMAND: {command} ``` + After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook. - If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently diff --git a/.claude/skills/speckit-clarify/SKILL.md b/.claude/skills/speckit-clarify/SKILL.md index 5fb7e6f..130f8c7 100644 --- a/.claude/skills/speckit-clarify/SKILL.md +++ b/.claude/skills/speckit-clarify/SKILL.md @@ -24,12 +24,12 @@ You **MUST** consider the user input before proceeding (if not empty). **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 +- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally - Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default. - For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions: - If the hook has no `condition` field, or it is null/empty, treat the hook as executable - If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation -- When constructing slash commands from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`. +- When constructing command invocations 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`): ``` @@ -52,6 +52,7 @@ You **MUST** consider the user input before proceeding (if not empty). Wait for the result of the hook command before proceeding to the Outline. ``` + After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook. - If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently ## Outline @@ -125,7 +126,7 @@ Execution steps: 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) + - The item is specifically about implementation method, tech-stack comparison, or task breakdown (note internally) 4. Generate (internally) a prioritized queue of candidate clarification questions (maximum 5). Do NOT output them all at once. Apply these constraints: - Maximum of 5 total questions across the whole session. @@ -140,6 +141,12 @@ Execution steps: 5. Sequential questioning loop (interactive): - Present EXACTLY ONE question at a time. + - **Question writing quality (applies to every question, MC or short-answer):** + - Lead with `**Question:**` followed by a full interrogative that ends with `?`. The question text before the `?` must make sense on its own. + - NEVER use a topic label, section heading, or requirement id as the question itself. For example, `Acceptance device/runtime matrix (FR-023)` is INVALID — it is a label, not a question. + - After the `?`, the only permitted suffix is an optional parenthesized requirement/question id. Exact format: `**Question:** ?` or `**Question:** ? (FR-023)`. Never put the id before the `?`, and never use the id (alone or with a topic label) as the whole prompt. + - Immediately after the question line, add one plain-language "Why it matters" sentence (the stake for acceptance or shipping) before the recommendation/options. + - Use everyday wording; introduce jargon only if defined in the same sentence. Self-check: a reader who does not know Spec Kit must be able to answer from the Question line alone. Terse is fine; cryptic labels are not. - For multiple‑choice questions: - **Analyze all options** and determine the **most suitable option** based on: - Best practices for the project type @@ -240,12 +247,12 @@ Context for prioritization: $ARGUMENTS 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. +- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue to the Completion Report. - Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default. - For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions: - If the hook has no `condition` field, or it is null/empty, treat the hook as executable - If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation -- When constructing slash commands from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`. +- When constructing command invocations 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**: ``` @@ -255,6 +262,7 @@ Check if `.specify/extensions.yml` exists in the project root. Executing: `/{command}` EXECUTE_COMMAND: {command} ``` + After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook. - **Optional hook** (`optional: true`): ``` ## Extension Hooks @@ -274,7 +282,7 @@ Report completion (after questioning loop ends or early termination): - 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). +- Coverage summary table listing each taxonomy category with Status: Resolved (was Partial/Missing and addressed), Deferred (exceeds question quota, or remaining item is specifically implementation method, tech-stack comparison, or task breakdown), Clear (already sufficient), Outstanding (still Partial/Missing but low impact). - If any Outstanding or Deferred remain, recommend whether to proceed to `/speckit-plan` or run `/speckit-clarify` again later post-plan. - Suggested next command. diff --git a/.claude/skills/speckit-constitution/SKILL.md b/.claude/skills/speckit-constitution/SKILL.md index 5897d74..505c092 100644 --- a/.claude/skills/speckit-constitution/SKILL.md +++ b/.claude/skills/speckit-constitution/SKILL.md @@ -1,6 +1,6 @@ --- name: "speckit-constitution" -description: "Create or update the project constitution from interactive or provided principle inputs, ensuring all dependent templates stay in sync." +description: "Create or update the project constitution from interactive or provided principle inputs." argument-hint: "Principles or values for the project constitution" compatibility: "Requires spec-kit project structure with .specify/ directory" metadata: @@ -19,17 +19,36 @@ $ARGUMENTS You **MUST** consider the user input before proceeding (if not empty). +## Scope Guard + +This command's own work is limited to updating the project constitution itself. Dependent templates +and commands read the constitution at runtime and are not modified here. + +- Classify every part of the user input as either constitution content or a separate, + non-governance intent. +- If the input includes feature implementation, code generation, refactoring, building, or + deployment requests, you **MUST NOT** execute them. Extract them as deferred intents instead. +- You **MUST NOT** create, modify, or delete application source files, feature routes, + components, tests, deployment files, or other artifacts unrelated to the constitution + workflow. +- If it is unclear whether an instruction is constitution content, ask for clarification before + making changes. +- After completing the constitution update, include a `Next Actions` section for each deferred + intent. List the original intent and suggest the appropriate follow-up Spec Kit command, such + as `/speckit-specify`, without invoking it. +- If there are no non-governance intents, omit the `Next Actions` section. + ## Pre-Execution Checks **Check for extension hooks (before constitution update)**: - Check if `.specify/extensions.yml` exists in the project root. - If it exists, read it and look for entries under the `hooks.before_constitution` key -- If the YAML cannot be parsed or is invalid, skip hook checking silently and continue normally +- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally - Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default. - For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions: - If the hook has no `condition` field, or it is null/empty, treat the hook as executable - If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation -- When constructing slash commands from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`. +- When constructing command invocations 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`): ``` @@ -52,17 +71,27 @@ You **MUST** consider the user input before proceeding (if not empty). Wait for the result of the hook command before proceeding to the Outline. ``` + After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook. - If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently ## Outline -You are updating the project constitution at `.specify/memory/constitution.md`. 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. +You are updating the project constitution at `.specify/memory/constitution.md`. The active +constitution scaffold is resolved at command time from `constitution-template` through the Spec Kit +preset/template resolution stack. Follow this execution flow: -1. Load the existing constitution at `.specify/memory/constitution.md`. +1. Run `.specify/scripts/powershell/resolve-template.ps1 constitution-template -Json` from the repository root and parse `TEMPLATE_CONTENT` as the active template. + - The shared resolver applies project overrides, composing preset layers, and extension layers + before the core template fallback. It MUST succeed before continuing. + - If it fails, stop and report the resolution error; do not continue with only one contributing + template layer. + - If `.specify/memory/constitution.md` exists, load it as the source of current project-specific + values and amendments. Preserve information that is still applicable when applying the newly + resolved scaffold. + - If it does not exist, use the resolved template as the initial document. + - Do not write back to any versioned template layer. - Identify every placeholder token of the form `[ALL_CAPS_IDENTIFIER]`. **IMPORTANT**: The user might require less or more principles than the ones used in the template. If a number is specified, respect that - follow the general template. You will update the doc accordingly. @@ -76,39 +105,34 @@ Follow this execution flow: - PATCH: Clarifications, wording, typo fixes, non-semantic refinements. - If version bump type ambiguous, propose reasoning before finalizing. -3. Draft the updated constitution content: +3. Draft the updated constitution content using the resolved template as the required structure: - Replace every placeholder with concrete text (no bracketed tokens left except intentionally retained template slots that the project has chosen not to define yet—explicitly justify any left). - Preserve heading hierarchy and comments can be removed once replaced unless they still add clarifying guidance. - Ensure each Principle section: succinct name line, paragraph (or bullet list) capturing non‑negotiable rules, explicit rationale if not obvious. - Ensure Governance section lists amendment procedure, versioning policy, and compliance review expectations. -4. 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): +4. Produce a Sync Impact Report as an HTML comment at the top of the constitution file after update. + This report is temporary scratch material for human review of the amendment, not governance + content; it is expected to be removed before the amended constitution file is committed. - Version change: old → new - List of modified principles (old title → new title if renamed) - Added sections - Removed sections - - Templates requiring updates (✅ updated / ⚠ pending) with file paths - Follow-up TODOs if any placeholders intentionally deferred. -6. Validation before final output: +5. Validation before final output: - No remaining unexplained bracket tokens. - Version line matches report. - Dates ISO format YYYY-MM-DD. - Principles are declarative, testable, and free of vague language ("should" → replace with MUST/SHOULD rationale where appropriate). -7. Write the completed constitution back to `.specify/memory/constitution.md` (overwrite). +6. Write the completed constitution back to `.specify/memory/constitution.md` (overwrite). -8. Output a final summary to the user with: +7. Output a final summary to the user with: - New version and bump rationale. - - Any files flagged for manual follow-up. + - Any TODO placeholders or deferred items requiring manual follow-up. - Suggested commit message (e.g., `docs: amend constitution to vX.Y.Z (principle additions + governance update)`). + - A `Next Actions` section for any deferred non-governance intents. Formatting & Style Requirements: @@ -121,19 +145,19 @@ If the user supplies partial updates (e.g., only one principle revision), still If critical info missing (e.g., ratification date truly unknown), insert `TODO(): 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. +Write only `.specify/memory/constitution.md`; do not create or modify template source files. ## Post-Execution Checks **Check for extension hooks (after constitution update)**: Check if `.specify/extensions.yml` exists in the project root. - If it exists, read it and look for entries under the `hooks.after_constitution` key -- If the YAML cannot be parsed or is invalid, skip hook checking silently and continue normally +- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally - Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default. - For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions: - If the hook has no `condition` field, or it is null/empty, treat the hook as executable - If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation -- When constructing slash commands from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`. +- When constructing command invocations 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`): ``` @@ -154,4 +178,5 @@ Check if `.specify/extensions.yml` exists in the project root. Executing: `/{command}` EXECUTE_COMMAND: {command} ``` + After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook. - If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently diff --git a/.claude/skills/speckit-converge/SKILL.md b/.claude/skills/speckit-converge/SKILL.md new file mode 100644 index 0000000..07bee86 --- /dev/null +++ b/.claude/skills/speckit-converge/SKILL.md @@ -0,0 +1,285 @@ +--- +name: "speckit-converge" +description: "Assess the current codebase against the feature's spec, plan, and tasks, then append any remaining unbuilt work as new tasks to tasks.md so implement can complete it." +compatibility: "Requires spec-kit project structure with .specify/ directory" +metadata: + author: "github-spec-kit" + source: "templates/commands/converge.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 convergence)**: + +- Check if `.specify/extensions.yml` exists in the project root. +- If it exists, read it and look for entries under the `hooks.before_converge` key +- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally +- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default. +- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions: + - If the hook has no `condition` field, or it is null/empty, treat the hook as executable + - If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation +- When constructing command invocations 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`): + + ```text + ## Extension Hooks + + **Optional Pre-Hook**: {extension} + Command: `/{command}` + Description: {description} + + Prompt: {prompt} + To execute: `/{command}` + ``` + + - **Mandatory hook** (`optional: false`): + + ```text + ## Extension Hooks + + **Automatic Pre-Hook**: {extension} + Executing: `/{command}` + EXECUTE_COMMAND: {command} + + Wait for the result of the hook command before proceeding to the Goal. + ``` + After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook. + +- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently + +## Goal + +Close the gap between what a feature's specification, plan, and tasks call for and what the +codebase currently implements. Read `spec.md`, `plan.md`, and `tasks.md` as the **sole +source of intent** (with the constitution as governing constraints), assess the current +state of the code, determine which requirements, acceptance criteria, plan decisions, and +existing tasks are unmet, incomplete, or only partially satisfied, and **append each piece +of remaining work as a new, traceable task** at the bottom of `tasks.md` so that +`/speckit-implement` can complete it. This command MUST run only after +`/speckit-implement` has run on the current `tasks.md`, and after `/speckit-tasks` has produced a complete `tasks.md`. + +This is **not** a diff tool and does **not** track changes. It assesses the present state +of the code relative to the feature's artifacts — no git, no branch comparison, no history. + +## Operating Constraints + +**APPEND-ONLY, NEVER REWRITE**: The command's **only** write is appending a new +`## Phase N: Convergence` section to `tasks.md`. It MUST NOT: + +- modify `spec.md` or `plan.md` in any way; +- rewrite, renumber, reorder, or delete any existing task (including tasks from a prior + Convergence phase); +- modify, create, or delete any application code — completing the appended tasks is the + job of `/speckit-implement`. + +When the codebase already satisfies everything, the command MUST leave `tasks.md` +**byte-for-byte unchanged** (no empty Convergence header) and report a clean result. + +**Constitution Authority**: The project constitution (`.specify/memory/constitution.md`) is +**non-negotiable**. Code that violates a MUST principle is the highest-severity finding and +produces a corresponding remediation task. If the constitution is an unfilled template, +skip constitution checks gracefully rather than failing. + +## Execution Steps + +### 1. Initialize Convergence Context + +Run `.specify/scripts/powershell/check-prerequisites.ps1 -Json -RequireSpec -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 +- CONSTITUTION = `.specify/memory/constitution.md` (if present) +If `spec.md`, `plan.md`, or `tasks.md` is missing, STOP with a clear, actionable message naming the +prerequisite command to run (`/speckit-specify` for a missing spec, `/speckit-plan` for a missing plan, +`/speckit-tasks` for missing tasks). Do not produce partial output. +For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot"). + +### 2. Load Artifacts (Progressive Disclosure) + +Load only the minimal necessary context from each artifact: + +**From spec.md:** + +- Functional Requirements (FR-###) +- Success Criteria (SC-###) — include only items requiring buildable work; exclude + post-launch outcome metrics and business KPIs +- User Stories and their Acceptance Scenarios +- Edge Cases (if present) + +**From plan.md:** + +- Architecture/stack choices and technical decisions +- Data Model references +- Phases and named touch-points (files/components the plan says will be created or edited) +- Technical constraints + +**From tasks.md:** + +- Task IDs (to compute the next ID and next phase number) +- Descriptions, phase grouping, and referenced file paths + +**From constitution (if not an unfilled template):** + +- Principle names and MUST/SHOULD normative statements + +### 3. Build the Intent Inventory + +Create an internal model (do not echo raw artifacts): + +- **Requirements inventory**: one stable key per FR-### / SC-### / user-story acceptance + scenario (e.g. `US1/AC2`), plus the plan decisions and constitution principles that + impose buildable obligations. +- **Code-scope map**: from the file paths named in `plan.md` and `tasks.md`, plus a keyword + search for the concepts each requirement describes, derive the set of source files and + components in scope for assessment. Bound the assessment to these — do **not** infer + scope beyond what the artifacts define. + +### 4. Assess the Codebase and Classify Findings + +Include every existing task in the intent inventory, regardless of checkbox state or +Convergence phase: completion claims are not evidence. Verify current behavior against +the spec, plan, tasks, and constitution; for corrective task chains, assess the resulting +behavior, not superseded implementation details. Check both unmet obligations and +implementation that contradicts, exceeds, or falls outside the stated intent. + +For each item in the intent inventory, inspect the current code in scope and produce a +`Finding` only where there is a gap. Classify every finding by **gap type**: + +- **`missing`**: the required work is absent from the code entirely. +- **`partial`**: the work exists but does not yet fully satisfy the requirement / + acceptance criterion / plan decision. +- **`contradicts`**: the code does something that conflicts with stated intent or a + constitution MUST principle. +- **`unrequested`**: the code contains work not called for by the spec, plan, or tasks + (surfaced for awareness — converge does **not** delete code, it only appends a task to + review/justify or remove it). + +Each `Finding` records: a stable id, the `source-ref` it traces to, the `gap-type`, a +severity, and a short human-readable description with the evidence (the file/area observed). + +**Edge cases:** + +- **Little or no code yet**: treat the entire specified scope as `missing` remaining work + rather than failing. +- **Nothing remains**: produce zero findings and follow the converged branch in Step 7. + +### 5. Assign Severity + +- **CRITICAL**: violates a constitution MUST principle, or a `missing`/`contradicts` gap + that blocks baseline functionality of a P1 user story. +- **HIGH**: a `missing` or `partial` gap on a core functional requirement or acceptance + criterion. +- **MEDIUM**: a `partial` gap on a secondary requirement, or an `unrequested` addition with + unclear justification. +- **LOW**: minor partial gaps, polish, or low-risk `unrequested` additions. + +### 6. Present the In-Session Findings Summary + +Before appending anything, output a compact, severity-graded summary (no file writes yet): + +## Convergence Findings + +| ID | Gap Type | Severity | Source | Evidence | Remaining Work | +|----|----------|----------|--------|----------|----------------| +| F1 | missing | HIGH | FR-008 | Example: no append-only guard detected in path/to/module.py when writing tasks.md | Add append-only enforcement | + +**Summary metrics:** + +- Requirements / acceptance criteria checked +- Plan decisions checked +- Constitution principles checked (or "skipped — template") +- Findings by gap type (missing / partial / contradicts / unrequested) +- Findings by severity + +### 7. Append Convergence Tasks (or report converged) + +**If there are one or more actionable findings** (`tasks_appended` outcome): + +Append to the **end** of `tasks.md`, per the append contract: + +1. Scan all existing task IDs; let `M` be the maximum. Determine the next phase number `N` + (highest existing phase + 1). +2. Write a single new section header `## Phase N: Convergence`. +3. Emit one checklist item per actionable finding, ordered CRITICAL/HIGH first, assigning + zero-padded IDs `T{M+1:03d}, T{M+2:03d}, …`: + + ```markdown + - [ ] T042 per () + ``` + + `` traces the task to its origin: e.g. `FR-003`, `SC-002`, + `US1/AC2`, `plan: storage decision`, `Constitution II`. + + `` is one of `missing`, `partial`, `contradicts`, `unrequested`. + + Constitution-violation tasks MUST be emitted first and described as + `CRITICAL`. +4. Never reuse or renumber existing IDs. If a prior Convergence phase exists, add a new, + separately-numbered one below it — do not touch the old one. + +**If there are no actionable findings** (`converged` outcome): + +- Do **not** modify `tasks.md` at all — no empty phase header. +- Report: **"✅ Converged — the implementation satisfies the spec, plan, and tasks."** +- Include the summary counts of what was checked. + +### 8. Provide Next Actions (Handoff) + +- On `tasks_appended`: state how many tasks were appended under which phase, and recommend + running `/speckit-implement` to complete them; note that a follow-up converge + run will find fewer or no remaining items. +- On `converged`: recommend proceeding to review / opening a PR. No further implement pass + is needed for this feature's specified scope. + +### 9. Check for extension hooks + +After producing the result, check if `.specify/extensions.yml` exists in the project root. + +- If it exists, read it and look for entries under the `hooks.after_converge` key +- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally +- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default. +- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions: + - If the hook has no `condition` field, or it is null/empty, treat the hook as executable + - If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation +- Report the convergence outcome (`converged` or `tasks_appended`) in-session before listing + any hooks, so users can decide whether to run optional follow-up commands. +- When constructing command invocations 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`): + + ```text + ## Extension Hooks + + **Optional Hook**: {extension} + Command: `/{command}` + Description: {description} + + Prompt: {prompt} + To execute: `/{command}` + ``` + + - **Mandatory hook** (`optional: false`): + + ```text + ## Extension Hooks + + **Automatic Hook**: {extension} + Executing: `/{command}` + EXECUTE_COMMAND: {command} + ``` + After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook. + +- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently diff --git a/.claude/skills/speckit-git-commit/SKILL.md b/.claude/skills/speckit-git-commit/SKILL.md index 6d1f29a..dfaad3b 100644 --- a/.claude/skills/speckit-git-commit/SKILL.md +++ b/.claude/skills/speckit-git-commit/SKILL.md @@ -3,7 +3,7 @@ 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 + author: spec-kit-core source: git:commands/speckit.git.commit.md --- @@ -19,23 +19,37 @@ This command is invoked as a hook after (or before) core commands. It: 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 +5. Determines the commit message based on `commit_style` (see below) 6. If enabled and there are uncommitted changes, runs `git add .` + `git commit` +## Commit Message Styles + +Controlled by the `commit_style` key in `.specify/extensions/git/git-config.yml`: + +- **`fixed`** (default): use the per-command `message` if configured, otherwise a generic `[Spec Kit] Auto-commit ` message. +- **`conventional`**: inspect the actual changes (`git diff` / `git status`) since the last commit and generate a single-line [Conventional Commit](https://www.conventionalcommits.org/) message (`type(scope): subject`, e.g. `feat: add OAuth specification` or `docs: update implementation plan`) that accurately summarizes the change. Write this message to a temporary file and pass the file's path to the script (see Execution below). The configured `message` values are ignored in this mode. + ## 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 ` -- **PowerShell**: `.specify/extensions/git/scripts/powershell/auto-commit.ps1 ` +- **Bash**: `.specify/extensions/git/scripts/bash/auto-commit.sh [--message-file ]` +- **PowerShell**: `.specify/extensions/git/scripts/powershell/auto-commit.ps1 [-MessageFile ]` -Replace `` with the actual hook event (e.g., `after_specify`, `before_plan`, `after_implement`). +Replace `` with the actual hook event (e.g., `after_specify`, `before_plan`, `after_implement`). Only pass a generated message when `commit_style: conventional` is configured — first check `.specify/extensions/git/git-config.yml` for the value of `commit_style`: + +- If `conventional`: inspect the diff and generate a Conventional Commit message. **Do not interpolate the generated message directly into a shell command string** — its content is derived from repository changes and may contain characters (quotes, `$(...)`, backticks) that a shell would execute or that would break command quoting. Instead, write the message to a temporary file using your file-editing tool (not a shell `echo`/`printf`), then pass that file's path via `--message-file ` (Bash) or `-MessageFile ` (PowerShell). +- If `fixed` or absent: run the script with just ``; it uses the configured/static message. ## Configuration In `.specify/extensions/git/git-config.yml`: ```yaml +# "fixed" (default) uses the messages below; "conventional" asks the agent +# to generate a Conventional Commit message from the diff instead. +commit_style: fixed + auto_commit: default: false # Global toggle — set true to enable for all commands after_specify: @@ -50,4 +64,5 @@ auto_commit: - 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 \ No newline at end of file +- If no changes to commit: skips with a message +- If `commit_style: conventional` is set and no generated message was supplied: fails with a clear error instead of silently falling back to the fixed message format \ No newline at end of file diff --git a/.claude/skills/speckit-git-feature/SKILL.md b/.claude/skills/speckit-git-feature/SKILL.md index 79b3ec9..4b0fada 100644 --- a/.claude/skills/speckit-git-feature/SKILL.md +++ b/.claude/skills/speckit-git-feature/SKILL.md @@ -3,7 +3,7 @@ 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 + author: spec-kit-core source: git:commands/speckit.git.feature.md --- @@ -24,7 +24,7 @@ You **MUST** consider the user input before proceeding (if not empty). 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 +- `FEATURE_NUM` is extracted when the final path segment starts with a numeric or timestamp feature marker (for example `042-name`, `feat/042-name`, or `jdoe/app/042-name`), otherwise set to the full branch name ## Prerequisites @@ -36,8 +36,22 @@ If the user explicitly provided `GIT_BRANCH_NAME` (e.g., via environment variabl 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 +2. Check `.specify/init-options.json` for `feature_numbering` value (inherit from core) +3. Check `.specify/init-options.json` for `branch_numbering` value (deprecated, backward compatibility — will be removed in a future release) +4. Default to `sequential` if none of the above exist + +## Branch Name Template + +Check `.specify/extensions/git/git-config.yml` for an optional `branch_template` value. If it is empty or missing, use the default branch shape `{number}-{slug}`. If it is set, `{slug}` must not appear before `{number}`, its final path segment must start with `{number}-`, and the script expands these tokens: + +- `{author}`: sanitized Git config author (`user.name`, falling back to the email local part) +- `{app}`: sanitized Spec Kit init directory name +- `{number}`: sequential number or timestamp +- `{slug}`: generated short branch slug + +For monorepos, a template such as `{author}/{app}/{number}-{slug}` creates names like `jdoe/web/008-guided-tour` while preserving per-project feature numbering. + +The script also accepts `branch_prefix` as a shorthand for simple namespaces; it expands to `/{number}-{slug}`. ## Execution @@ -48,16 +62,17 @@ Generate a concise short name (2-4 words) for the branch: Run the appropriate script based on your platform: -- **Bash**: `.specify/extensions/git/scripts/bash/create-new-feature.sh --json --short-name "" ""` -- **Bash (timestamp)**: `.specify/extensions/git/scripts/bash/create-new-feature.sh --json --timestamp --short-name "" ""` -- **PowerShell**: `.specify/extensions/git/scripts/powershell/create-new-feature.ps1 -Json -ShortName "" ""` -- **PowerShell (timestamp)**: `.specify/extensions/git/scripts/powershell/create-new-feature.ps1 -Json -Timestamp -ShortName "" ""` +- **Bash**: `.specify/extensions/git/scripts/bash/create-new-feature-branch.sh --json --short-name "" ""` +- **Bash (timestamp)**: `.specify/extensions/git/scripts/bash/create-new-feature-branch.sh --json --timestamp --short-name "" ""` +- **PowerShell**: `.specify/extensions/git/scripts/powershell/create-new-feature-branch.ps1 -Json -ShortName "" ""` +- **PowerShell (timestamp)**: `.specify/extensions/git/scripts/powershell/create-new-feature-branch.ps1 -Json -Timestamp -ShortName "" ""` **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` +- Do not manually expand `branch_template`; the script reads the git extension config and applies it consistently ## Graceful Degradation @@ -68,5 +83,5 @@ If Git is not installed or the current directory is not a Git repository: ## Output The script outputs JSON with: -- `BRANCH_NAME`: The branch name (e.g., `003-user-auth` or `20260319-143022-user-auth`) +- `BRANCH_NAME`: The branch name (e.g., `003-user-auth`, `20260319-143022-user-auth`, or `jdoe/web/003-user-auth`) - `FEATURE_NUM`: The numeric or timestamp prefix used \ No newline at end of file diff --git a/.claude/skills/speckit-git-initialize/SKILL.md b/.claude/skills/speckit-git-initialize/SKILL.md index e4d28f4..c5b3bf1 100644 --- a/.claude/skills/speckit-git-initialize/SKILL.md +++ b/.claude/skills/speckit-git-initialize/SKILL.md @@ -3,7 +3,7 @@ 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 + author: spec-kit-core source: git:commands/speckit.git.initialize.md --- diff --git a/.claude/skills/speckit-git-remote/SKILL.md b/.claude/skills/speckit-git-remote/SKILL.md index 50bfc3d..c6361dc 100644 --- a/.claude/skills/speckit-git-remote/SKILL.md +++ b/.claude/skills/speckit-git-remote/SKILL.md @@ -3,7 +3,7 @@ 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 + author: spec-kit-core source: git:commands/speckit.git.remote.md --- diff --git a/.claude/skills/speckit-git-validate/SKILL.md b/.claude/skills/speckit-git-validate/SKILL.md index 7655e3a..528c8c4 100644 --- a/.claude/skills/speckit-git-validate/SKILL.md +++ b/.claude/skills/speckit-git-validate/SKILL.md @@ -3,7 +3,7 @@ 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 + author: spec-kit-core source: git:commands/speckit.git.validate.md --- @@ -27,24 +27,24 @@ Get the current branch name: git rev-parse --abbrev-ref HEAD ``` -The branch name must match one of these patterns: +The branch name's final path segment must start with one of these feature markers: -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`) +1. **Sequential**: `[0-9]{3,}-` (e.g., `001-feature-name`, `042-fix-bug`, `1000-big-feature`, `jdoe/web/008-guided-tour`) +2. **Timestamp**: `[0-9]{8}-[0-9]{6}-` (e.g., `20260319-143022-feature-name`, `jdoe/web/20260319-143022-feature-name`) ## Execution If on a feature branch (matches either pattern): - Output: `✓ On feature branch: ` - Check if the corresponding spec directory exists under `specs/`: - - For sequential branches, look for `specs/-*` where prefix matches the numeric portion - - For timestamp branches, look for `specs/-*` where prefix matches the `YYYYMMDD-HHMMSS` portion + - For sequential branches, look for `specs/-*` where prefix matches the numeric portion, regardless of branch namespace prefixes + - For timestamp branches, look for `specs/-*` where prefix matches the `YYYYMMDD-HHMMSS` portion, regardless of branch namespace prefixes - If spec directory exists: `✓ Spec directory found: ` - If spec directory missing: `⚠ No spec directory found for prefix ` If NOT on a feature branch: - Output: `✗ Not on a feature branch. Current branch: ` -- Output: `Feature branches should be named like: 001-feature-name or 20260319-143022-feature-name` +- Output: `Feature branches should be named like: 001-feature-name, 20260319-143022-feature-name, or /001-feature-name` ## Graceful Degradation diff --git a/.claude/skills/speckit-implement/SKILL.md b/.claude/skills/speckit-implement/SKILL.md index de5a8ee..b720f4b 100644 --- a/.claude/skills/speckit-implement/SKILL.md +++ b/.claude/skills/speckit-implement/SKILL.md @@ -24,12 +24,12 @@ You **MUST** consider the user input before proceeding (if not empty). **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 +- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally - Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default. - For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions: - If the hook has no `condition` field, or it is null/empty, treat the hook as executable - If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation -- When constructing slash commands from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`. +- When constructing command invocations 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`): ``` @@ -49,9 +49,10 @@ You **MUST** consider the user input before proceeding (if not empty). **Automatic Pre-Hook**: {extension} Executing: `/{command}` EXECUTE_COMMAND: {command} - + Wait for the result of the hook command before proceeding to the Outline. ``` + After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook. - If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently ## Outline @@ -59,33 +60,36 @@ You **MUST** consider the user input before proceeding (if not empty). 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): + - Treat checklist markers as a read-only gate: scan checkbox state, report status, and ask before proceeding when needed; do NOT modify checklist files or markers + - `checklists/requirements.md` is the built-in spec-quality checklist maintained by `/speckit-specify` and `/speckit-clarify`; custom checklists generated by `/speckit-checklist` are reviewer-owned requirements-quality review artifacts + - For custom checklists, `[x]` means the reviewer determined the requirements-quality criterion is satisfied; it does NOT mean implementation work is complete - Scan all checklist files in the checklists/ directory - For each checklist, count: - Total items: All lines matching `- [ ]` or `- [X]` or `- [x]` - - Completed items: Lines matching `- [X]` or `- [x]` - - Incomplete items: Lines matching `- [ ]` + - Checked items: Lines matching `- [X]` or `- [x]` + - Unchecked 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 | + | Checklist | Total | Checked | Unchecked | Status | + |-----------|-------|---------|-----------|--------| + | ux.md | 12 | 12 | 0 | ✓ PASS | + | test.md | 8 | 5 | 3 | ✗ FAIL | + | security.md | 6 | 6 | 0 | ✓ PASS | ``` - Calculate overall status: - - **PASS**: All checklists have 0 incomplete items - - **FAIL**: One or more checklists have incomplete items + - **PASS**: All checklists have 0 unchecked items + - **FAIL**: One or more checklists have unchecked 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)" + - **If any checklist has unchecked items**: + - Display the table with unchecked item counts + - **STOP** and ask: "Some checklists have unchecked items. Do you want to proceed with implementation anyway? (yes/no)" - Wait for user response before continuing - If user says "no" or "wait" or "stop", halt execution - If user says "yes" or "proceed" or "continue", proceed to step 3 - - **If all checklists are complete**: + - **If all checklists are checked**: - Display the table showing all checklists passed - Automatically proceed to step 3 @@ -150,7 +154,7 @@ You **MUST** consider the user input before proceeding (if not empty). 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 + - **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 @@ -185,12 +189,12 @@ Note: This command assumes a complete task breakdown exists in tasks.md. If task 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. +- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue to the Completion Report. - Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default. - For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions: - If the hook has no `condition` field, or it is null/empty, treat the hook as executable - If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation -- When constructing slash commands from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`. +- When constructing command invocations 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**: ``` @@ -200,6 +204,7 @@ Check if `.specify/extensions.yml` exists in the project root. Executing: `/{command}` EXECUTE_COMMAND: {command} ``` + After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook. - **Optional hook** (`optional: true`): ``` ## Extension Hooks diff --git a/.claude/skills/speckit-plan/SKILL.md b/.claude/skills/speckit-plan/SKILL.md index 05b4c9e..ca5ea6b 100644 --- a/.claude/skills/speckit-plan/SKILL.md +++ b/.claude/skills/speckit-plan/SKILL.md @@ -24,12 +24,12 @@ You **MUST** consider the user input before proceeding (if not empty). **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 +- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally - Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default. - For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions: - If the hook has no `condition` field, or it is null/empty, treat the hook as executable - If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation -- When constructing slash commands from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`. +- When constructing command invocations 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`): ``` @@ -52,11 +52,12 @@ You **MUST** consider the user input before proceeding (if not empty). Wait for the result of the hook command before proceeding to the Outline. ``` + After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook. - If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently ## Outline -1. **Setup**: Run `.specify/scripts/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"). +1. **Setup**: Run `.specify/scripts/powershell/setup-plan.ps1 -Json` from repo root and parse JSON for FEATURE_SPEC, IMPL_PLAN, FEATURE_DIR, BRANCH. For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot"). 2. **Load context**: Read FEATURE_SPEC and `.specify/memory/constitution.md`. Load IMPL_PLAN template (already copied). @@ -66,7 +67,6 @@ You **MUST** consider the user input before proceeding (if not empty). - 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 @@ -76,12 +76,12 @@ You **MUST** consider the user input before proceeding (if not empty). 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. +- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue to the Completion Report. - Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default. - For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions: - If the hook has no `condition` field, or it is null/empty, treat the hook as executable - If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation -- When constructing slash commands from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`. +- When constructing command invocations 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**: ``` @@ -91,6 +91,7 @@ Check if `.specify/extensions.yml` exists in the project root. Executing: `/{command}` EXECUTE_COMMAND: {command} ``` + After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook. - **Optional hook** (`optional: true`): ``` ## Extension Hooks @@ -105,7 +106,7 @@ Check if `.specify/extensions.yml` exists in the project root. ## Completion Report -Command ends after Phase 2 planning. Report branch, IMPL_PLAN path, and generated artifacts. +Command ends after Phase 1 design. Report branch, IMPL_PLAN path, and generated artifacts. ## Phases @@ -154,14 +155,11 @@ Command ends after Phase 2 planning. Report branch, IMPL_PLAN path, and generate - Do not include full implementation code, model/service/controller bodies, migrations, or complete test suites - Keep this artifact as a validation/run guide; implementation details belong in `tasks.md` and the implementation phase -4. **Agent context update**: - - Update the plan reference between the `` and `` 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 +**Output**: data-model.md, /contracts/*, quickstart.md ## Key rules -- Use absolute paths for filesystem operations; use project-relative paths for references in documentation and agent context files +- Use absolute paths for filesystem operations; use project-relative paths for references in documentation - ERROR on gate failures or unresolved clarifications ## Done When diff --git a/.claude/skills/speckit-specify/SKILL.md b/.claude/skills/speckit-specify/SKILL.md index 43d05d9..25daab1 100644 --- a/.claude/skills/speckit-specify/SKILL.md +++ b/.claude/skills/speckit-specify/SKILL.md @@ -24,12 +24,12 @@ You **MUST** consider the user input before proceeding (if not empty). **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 +- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally - Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default. - For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions: - If the hook has no `condition` field, or it is null/empty, treat the hook as executable - If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation -- When constructing slash commands from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`. +- When constructing command invocations 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`): ``` @@ -52,6 +52,7 @@ You **MUST** consider the user input before proceeding (if not empty). Wait for the result of the hook command before proceeding to the Outline. ``` + After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook. - If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently ## Outline @@ -85,11 +86,12 @@ Given that feature description, do this: **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` + - Check `.specify/init-options.json` for `feature_numbering` (preferred) or `branch_numbering` (deprecated, migration only — will be removed in a future release) - If `"timestamp"`: prefix is `YYYYMMDD-HHMMSS` (current timestamp) - If `"sequential"` or absent: prefix is `NNN` (next available 3-digit number after scanning existing directories in `specs/`) - Construct the directory name: `-` (e.g., `003-user-auth` or `20260319-143022-user-auth`) - Set `SPECIFY_FEATURE_DIRECTORY` to `specs/` + - If `branch_numbering` was used (and `feature_numbering` was absent), emit a one-line warning: "⚠️ `branch_numbering` in init-options.json is deprecated. Rename to `feature_numbering`." **Create the directory and spec file**: - `mkdir -p SPECIFY_FEATURE_DIRECTORY` @@ -139,28 +141,28 @@ Given that feature description, do this: 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. 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: +8. **Specification Quality Validation**: After writing the initial spec, validate it against quality criteria: a. **Create Spec Quality Checklist**: Generate a checklist file at `SPECIFY_FEATURE_DIRECTORY/checklists/requirements.md` using the checklist template structure with these validation items: ```markdown # Specification Quality Checklist: [FEATURE NAME] - + **Purpose**: Validate specification completeness and quality before proceeding to planning **Created**: [DATE] **Feature**: [Link to spec.md] - + ## Content Quality - + - [ ] No implementation details (languages, frameworks, APIs) - [ ] Focused on user value and business needs - [ ] Written for non-technical stakeholders - [ ] All mandatory sections completed - + ## Requirement Completeness - + - [ ] No [NEEDS CLARIFICATION] markers remain - [ ] Requirements are testable and unambiguous - [ ] Success criteria are measurable @@ -169,16 +171,16 @@ Given that feature description, do this: - [ ] 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` ``` @@ -203,20 +205,20 @@ Given that feature description, do this: ```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]_ ``` @@ -240,12 +242,12 @@ Given that feature description, do this: 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. +- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue to the Completion Report. - Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default. - For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions: - If the hook has no `condition` field, or it is null/empty, treat the hook as executable - If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation -- When constructing slash commands from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`. +- When constructing command invocations 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**: ``` @@ -255,6 +257,7 @@ Check if `.specify/extensions.yml` exists in the project root. Executing: `/{command}` EXECUTE_COMMAND: {command} ``` + After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook. - **Optional hook** (`optional: true`): ``` ## Extension Hooks diff --git a/.claude/skills/speckit-tasks/SKILL.md b/.claude/skills/speckit-tasks/SKILL.md index 9c7eb2b..4993eb4 100644 --- a/.claude/skills/speckit-tasks/SKILL.md +++ b/.claude/skills/speckit-tasks/SKILL.md @@ -24,12 +24,12 @@ You **MUST** consider the user input before proceeding (if not empty). **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 +- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally - Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default. - For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions: - If the hook has no `condition` field, or it is null/empty, treat the hook as executable - If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation -- When constructing slash commands from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`. +- When constructing command invocations 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`): ``` @@ -49,14 +49,15 @@ You **MUST** consider the user input before proceeding (if not empty). **Automatic Pre-Hook**: {extension} Executing: `/{command}` EXECUTE_COMMAND: {command} - + Wait for the result of the hook command before proceeding to the Outline. ``` + After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook. - If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently ## Outline -1. **Setup**: Run `.specify/scripts/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"). +1. **Setup**: Run `.specify/scripts/powershell/setup-tasks.ps1 -Json` from repo root and parse FEATURE_DIR, TASKS_TEMPLATE_CONTENT, TASKS_TEMPLATE, and AVAILABLE_DOCS list. `FEATURE_DIR` and `TASKS_TEMPLATE` must be absolute paths when provided. `AVAILABLE_DOCS` is a list of document names/relative paths available under `FEATURE_DIR` (for example `research.md` or `contracts/`). For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot"). 2. **Load design documents**: Read from FEATURE_DIR: - **Required**: plan.md (tech stack, libraries, structure), spec.md (user stories with priorities) @@ -75,7 +76,7 @@ You **MUST** consider the user input before proceeding (if not empty). - 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: +4. **Generate tasks.md**: Use TASKS_TEMPLATE_CONTENT (from the JSON output above) as the structure. For compatibility with older setup scripts that omit TASKS_TEMPLATE_CONTENT, read TASKS_TEMPLATE instead. Fill with: - Correct feature name from plan.md - Phase 1: Setup tasks (project initialization) - Phase 2: Foundational tasks (blocking prerequisites for all user stories) @@ -95,12 +96,12 @@ You **MUST** consider the user input before proceeding (if not empty). 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. +- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue to the Completion Report. - Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default. - For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions: - If the hook has no `condition` field, or it is null/empty, treat the hook as executable - If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation -- When constructing slash commands from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`. +- When constructing command invocations 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**: ``` @@ -110,6 +111,7 @@ Check if `.specify/extensions.yml` exists in the project root. Executing: `/{command}` EXECUTE_COMMAND: {command} ``` + After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook. - **Optional hook** (`optional: true`): ``` ## Extension Hooks @@ -158,7 +160,7 @@ Every task MUST strictly follow this format: 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 + - 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 @@ -193,6 +195,7 @@ Every task MUST strictly follow this format: - Map each entity to the user story(ies) that need it - If entity serves multiple stories: Put in earliest story or Setup phase - Relationships → service layer tasks in appropriate story phase + - For each field with constraints in data-model.md (max length, nullable/required, enum values, validation rules), quote the constraint verbatim in the task description so it is not left to implementation-time discretion 4. **From Setup/Infrastructure**: - Shared infrastructure → Setup phase (Phase 1) diff --git a/.claude/skills/speckit-taskstoissues/SKILL.md b/.claude/skills/speckit-taskstoissues/SKILL.md index fc0cb73..7ec800a 100644 --- a/.claude/skills/speckit-taskstoissues/SKILL.md +++ b/.claude/skills/speckit-taskstoissues/SKILL.md @@ -24,12 +24,12 @@ You **MUST** consider the user input before proceeding (if not empty). **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 +- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally - Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default. - For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions: - If the hook has no `condition` field, or it is null/empty, treat the hook as executable - If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation -- When constructing slash commands from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`. +- When constructing command invocations 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`): ``` @@ -52,6 +52,7 @@ You **MUST** consider the user input before proceeding (if not empty). Wait for the result of the hook command before proceeding to the Outline. ``` + After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook. - If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently ## Outline @@ -68,7 +69,10 @@ 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. +1. **Fetch existing issues for deduplication**: Before creating anything, build the set of task IDs you are about to process from `tasks.md` (each is a `T` followed by **at least** three digits, e.g. `T001` — `/speckit-converge` assigns new IDs with `T{M+1:03d}`, which is a floor rather than a cap, so once a file has more than 999 tasks the IDs are four digits or longer). Then use the GitHub MCP server's `list_issues` tool to look for issues that already cover those IDs. Do not pass a `state` value, since omitting it makes the tool return both open and closed issues. Request `perPage: 100` to keep the number of calls down, and since the tool uses cursor-based pagination, request pages with the `after` parameter (using the `endCursor` from the previous response). For each issue title, match it against the task ID pattern `\bT\d{3,}\b` (the `{3,}` accepts four-digit and longer IDs — with `\d{3}` a title containing `T1000` would not match at all, because the trailing `\b` cannot fall between two digits, so that task would be silently neither deduplicated nor created; word boundaries still stop a token like `ST001` from matching, and force the whole digit run to be consumed so `T100` can never match inside `T1000`; this also recognises titles written as `T001 ...`, `T001: ...` or `[T001] ...`) and, when it matches one of your task IDs, mark that ID as already having an issue. Stop paginating as soon as every task ID has been matched, or when there are no more pages, so you do not keep fetching the whole repository's issue history once all task IDs are accounted for. This bounds the number of calls on repos with large issue histories and still prevents duplicates when the command is re-run after `tasks.md` is regenerated or the skill is re-invoked. +1. For each task in the list, use the GitHub MCP server to create a new issue in the repository that is representative of the Git remote. Task lines in `tasks.md` start with a markdown checkbox, so first strip the leading `- [ ]` (and any `[P]` / `[US#]` markers) to recover the task ID and its description. Create the issue with a single canonical title of the form `T001: `, with the ID written once followed by the task description (for example, the line `- [ ] T001 Create project structure` becomes the title `T001: Create project structure`). + - **Skip** any task whose ID is already present in the set of existing issues from the previous step, and report it (for example, `T001 already has an issue, skipping`). + - Only create issues for tasks that do not yet have a matching issue. > [!CAUTION] > UNDER NO CIRCUMSTANCES EVER CREATE ISSUES IN REPOSITORIES THAT DO NOT MATCH THE REMOTE URL @@ -78,12 +82,12 @@ git config --get remote.origin.url **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 +- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally - Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default. - For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions: - If the hook has no `condition` field, or it is null/empty, treat the hook as executable - If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation -- When constructing slash commands from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`. +- When constructing command invocations 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`): ``` @@ -104,4 +108,5 @@ Check if `.specify/extensions.yml` exists in the project root. Executing: `/{command}` EXECUTE_COMMAND: {command} ``` + After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook. - If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ede4717..f1fcf56 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -48,6 +48,12 @@ jobs: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITLEAKS_CONFIG: .gitleaks.toml + # The solution source must hold environment variable definitions only, + # never their values, and no email address (spec 004, FR-028/FR-030). + - name: Check solution source for environment variable values + shell: pwsh + run: ./scripts/ci/assert-no-envvar-values.ps1 -Path solution/src + - name: Lint workflow files (actionlint) shell: bash run: | diff --git a/.github/workflows/deploy.reusable.yml b/.github/workflows/deploy.reusable.yml index ca6529d..0170c62 100644 --- a/.github/workflows/deploy.reusable.yml +++ b/.github/workflows/deploy.reusable.yml @@ -76,6 +76,20 @@ jobs: solution-file: out/MedTrackCore.zip solution-type: Unmanaged + # Binds the reminder flow's connection references and sets the time + # zone and the app link for this environment. No address is among + # these values: the reminder goes to the Dataverse connection's own + # user in Teams (spec 004, FR-028). + - name: Render deployment settings + shell: pwsh + env: + PP_CONN_DATAVERSE_ID: ${{ vars.PP_CONN_DATAVERSE_ID }} + PP_CONN_TEAMS_ID: ${{ vars.PP_CONN_TEAMS_ID }} + REMINDER_TIME_ZONE: ${{ vars.REMINDER_TIME_ZONE }} + PP_ENVIRONMENT_ID: ${{ vars.PP_ENVIRONMENT_ID }} + PP_APP_ID: ${{ vars.PP_APP_ID }} + run: ./scripts/ci/render-deployment-settings.ps1 + - name: Import solution uses: microsoft/powerplatform-actions/import-solution@v1 with: @@ -84,6 +98,8 @@ jobs: client-secret: ${{ secrets.PP_CLIENT_SECRET }} tenant-id: ${{ secrets.PP_TENANT_ID }} solution-file: out/MedTrackCore.zip + use-deployment-settings-file: true + deployment-settings-file: solution/deployment-settings.json - name: Publish solution customizations uses: microsoft/powerplatform-actions/publish-solution@v1 @@ -93,6 +109,17 @@ jobs: client-secret: ${{ secrets.PP_CLIENT_SECRET }} tenant-id: ${{ secrets.PP_TENANT_ID }} + # A flow left off after import sends no reminders and raises no error, + # so fail the deploy unless it is on and owned by the service principal. + - name: Configure reminder flow + shell: pwsh + env: + PP_CLIENT_ID: ${{ secrets.PP_CLIENT_ID }} + PP_CLIENT_SECRET: ${{ secrets.PP_CLIENT_SECRET }} + PP_TENANT_ID: ${{ secrets.PP_TENANT_ID }} + PP_ENVIRONMENT_URL: ${{ vars.PP_ENVIRONMENT_URL }} + run: ./scripts/deploy/configure-reminder-flow.ps1 + # --- App (US2, FR-005): pac code push and pac data import (below) use # the pac CLI directly, so authenticate immediately before them here # rather than earlier — a profile created before the actions above ran diff --git a/.github/workflows/promote-prod.yml b/.github/workflows/promote-prod.yml index 65c9970..b401146 100644 --- a/.github/workflows/promote-prod.yml +++ b/.github/workflows/promote-prod.yml @@ -53,6 +53,16 @@ jobs: solution-file: out/MedTrackCore.zip solution-type: Unmanaged + - name: Render deployment settings (dev) + shell: pwsh + env: + PP_CONN_DATAVERSE_ID: ${{ vars.PP_CONN_DATAVERSE_ID }} + PP_CONN_TEAMS_ID: ${{ vars.PP_CONN_TEAMS_ID }} + REMINDER_TIME_ZONE: ${{ vars.REMINDER_TIME_ZONE }} + PP_ENVIRONMENT_ID: ${{ vars.PP_ENVIRONMENT_ID }} + PP_APP_ID: ${{ vars.PP_APP_ID }} + run: ./scripts/ci/render-deployment-settings.ps1 + - name: Sync dev to source-controlled solution uses: microsoft/powerplatform-actions/import-solution@v1 with: @@ -61,6 +71,8 @@ jobs: client-secret: ${{ secrets.PP_CLIENT_SECRET }} tenant-id: ${{ secrets.PP_TENANT_ID }} solution-file: out/MedTrackCore.zip + use-deployment-settings-file: true + deployment-settings-file: solution/deployment-settings.json - name: Publish dev customizations uses: microsoft/powerplatform-actions/publish-solution@v1 @@ -81,6 +93,14 @@ jobs: solution-output-file: out/MedTrackCore_managed.zip managed: true + # Must stay BEFORE the upload below. The artifact of a public + # repository is downloadable, so this is the step that stops an + # environment variable value (the time zone, the app link) or any email + # address from being published with the solution (spec 004, FR-028). + - name: Check exported solution for environment variable values + shell: pwsh + run: ./scripts/ci/assert-no-envvar-values.ps1 -Zip out/MedTrackCore_managed.zip + - name: Upload managed solution artifact uses: actions/upload-artifact@v4 with: @@ -136,6 +156,17 @@ jobs: name: managed-solution path: out + # Rendered from the `production` GitHub Environment's own variables. + - name: Render deployment settings (production) + shell: pwsh + env: + PP_CONN_DATAVERSE_ID: ${{ vars.PP_CONN_DATAVERSE_ID }} + PP_CONN_TEAMS_ID: ${{ vars.PP_CONN_TEAMS_ID }} + REMINDER_TIME_ZONE: ${{ vars.REMINDER_TIME_ZONE }} + PP_ENVIRONMENT_ID: ${{ vars.PP_ENVIRONMENT_ID }} + PP_APP_ID: ${{ vars.PP_APP_ID }} + run: ./scripts/ci/render-deployment-settings.ps1 + - name: Import solution (Managed) uses: microsoft/powerplatform-actions/import-solution@v1 with: @@ -144,6 +175,8 @@ jobs: client-secret: ${{ secrets.PP_CLIENT_SECRET }} tenant-id: ${{ secrets.PP_TENANT_ID }} solution-file: out/MedTrackCore_managed.zip + use-deployment-settings-file: true + deployment-settings-file: solution/deployment-settings.json - name: Publish solution customizations uses: microsoft/powerplatform-actions/publish-solution@v1 @@ -153,6 +186,17 @@ jobs: client-secret: ${{ secrets.PP_CLIENT_SECRET }} tenant-id: ${{ secrets.PP_TENANT_ID }} + # A flow left off after import sends no reminders and raises no error, + # so fail the deploy unless it is on and owned by the service principal. + - name: Configure reminder flow + shell: pwsh + env: + PP_CLIENT_ID: ${{ secrets.PP_CLIENT_ID }} + PP_CLIENT_SECRET: ${{ secrets.PP_CLIENT_SECRET }} + PP_TENANT_ID: ${{ secrets.PP_TENANT_ID }} + PP_ENVIRONMENT_URL: ${{ vars.PP_ENVIRONMENT_URL }} + run: ./scripts/deploy/configure-reminder-flow.ps1 + # --- App (US2, FR-005): pac code push and pac data import (below) use # the pac CLI directly, so authenticate immediately before them here # rather than earlier — a profile created before the actions above ran diff --git a/.gitignore b/.gitignore index dbf1c9d..fe494e2 100644 --- a/.gitignore +++ b/.gitignore @@ -34,6 +34,7 @@ dist-ssr # Sensitive / environment-specific material — never committed (see # specs/003-github-actions-cicd/contracts/secrets-and-environments.contract.md) power.config.json +solution/deployment-settings.json localhost*.pem *.pfx *.key diff --git a/.gitleaks.toml b/.gitleaks.toml index 8749928..8e2e559 100644 --- a/.gitleaks.toml +++ b/.gitleaks.toml @@ -13,3 +13,39 @@ regexes = [ paths = [ '''(.*?)(pnpm|npm|package)-lock\.json''', ] + +# The reminder address must never reach this public repository (spec 004, +# FR-028/FR-030). Any email address in committed content is a finding unless it +# is on the allowlist below. Documentation, tests and seed data use +# reminder@example.com. +[[rules]] +id = "email-address" +description = "Email address (only example.com / example.org / noreply addresses may be committed)" +# The domain must end in a letters-only TLD, so version pins such as +# `pkg@1.2.3` and `actions/checkout@v6` are not matched. +regex = '''[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}''' +keywords = ["@"] + + [[rules.allowlists]] + description = "Reserved example domains and noreply addresses" + regexTarget = "match" + regexes = [ + '''(?i)@example\.(com|org)$''', + '''(?i)@users\.noreply\.github\.com$''', + '''(?i)^noreply@anthropic\.com$''', + # Microsoft's fictitious sample domain, used in the vendored skill docs. + '''(?i)@contoso\.com$''', + ] + + [[rules.allowlists]] + description = "Not email addresses: OData annotations and the git SSH user" + regexTarget = "match" + regexes = [ + # `ppa_Medication@odata.bind`, `x@odata.type`, `x@OData.Community.Display.V1.FormattedValue` + '''(?i)@odata\.''', + # `x@Microsoft.Dynamics.CRM.lookuplogicalname` + '''@Microsoft\.''', + '''^git@github\.com$''', + # The pattern placeholder used in the spec 004 documents. + '''^local@domain\.tld$''', + ] diff --git a/.specify/.gitignore b/.specify/.gitignore new file mode 100644 index 0000000..dd13a5e --- /dev/null +++ b/.specify/.gitignore @@ -0,0 +1,12 @@ +# Machine-local Spec Kit state — not meant to be shared. +# Managed by the Specify CLI; safe to edit (your changes are preserved on refresh). + +# Local pointer to the current feature directory. Rewritten every time you +# switch features, so it is per-checkout state rather than something to share. +feature.json + +# Per-machine extension config overrides. +extensions/*/local-config.yml + +# Extension catalog download cache. +extensions/.cache/ diff --git a/.specify/extensions.yml b/.specify/extensions.yml index 651400d..6b645c5 100644 --- a/.specify/extensions.yml +++ b/.specify/extensions.yml @@ -4,11 +4,46 @@ installed: settings: auto_execute_hooks: true hooks: + after_specify: + - extension: git + command: speckit.git.commit + enabled: true + optional: true + priority: 10 + prompt: Commit specification changes? + description: Auto-commit after specification + condition: null + - extension: agent-context + command: speckit.agent-context.update + enabled: true + optional: true + priority: 10 + prompt: Execute speckit.agent-context.update? + description: Refresh agent context after specification + condition: null + after_plan: + - extension: git + command: speckit.git.commit + enabled: true + optional: true + priority: 10 + prompt: Commit plan changes? + description: Auto-commit after implementation planning + condition: null + - extension: agent-context + command: speckit.agent-context.update + enabled: true + optional: true + priority: 10 + prompt: Execute speckit.agent-context.update? + description: Refresh agent context after planning + condition: null before_constitution: - extension: git command: speckit.git.initialize enabled: true optional: false + priority: 10 prompt: Execute speckit.git.initialize? description: Initialize Git repository before constitution setup condition: null @@ -17,6 +52,7 @@ hooks: command: speckit.git.feature enabled: true optional: false + priority: 10 prompt: Execute speckit.git.feature? description: Create feature branch before specification condition: null @@ -25,6 +61,7 @@ hooks: command: speckit.git.commit enabled: true optional: true + priority: 10 prompt: Commit outstanding changes before clarification? description: Auto-commit before spec clarification condition: null @@ -33,6 +70,7 @@ hooks: command: speckit.git.commit enabled: true optional: true + priority: 10 prompt: Commit outstanding changes before planning? description: Auto-commit before implementation planning condition: null @@ -41,6 +79,7 @@ hooks: command: speckit.git.commit enabled: true optional: true + priority: 10 prompt: Commit outstanding changes before task generation? description: Auto-commit before task generation condition: null @@ -49,6 +88,7 @@ hooks: command: speckit.git.commit enabled: true optional: true + priority: 10 prompt: Commit outstanding changes before implementation? description: Auto-commit before implementation condition: null @@ -57,6 +97,7 @@ hooks: command: speckit.git.commit enabled: true optional: true + priority: 10 prompt: Commit outstanding changes before checklist? description: Auto-commit before checklist generation condition: null @@ -65,6 +106,7 @@ hooks: command: speckit.git.commit enabled: true optional: true + priority: 10 prompt: Commit outstanding changes before analysis? description: Auto-commit before analysis condition: null @@ -73,6 +115,7 @@ hooks: command: speckit.git.commit enabled: true optional: true + priority: 10 prompt: Commit outstanding changes before issue sync? description: Auto-commit before tasks-to-issues conversion condition: null @@ -81,52 +124,25 @@ hooks: command: speckit.git.commit enabled: true optional: true + priority: 10 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 + priority: 10 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 + priority: 10 prompt: Commit task changes? description: Auto-commit after task generation condition: null @@ -135,6 +151,7 @@ hooks: command: speckit.git.commit enabled: true optional: true + priority: 10 prompt: Commit implementation changes? description: Auto-commit after implementation condition: null @@ -143,6 +160,7 @@ hooks: command: speckit.git.commit enabled: true optional: true + priority: 10 prompt: Commit checklist changes? description: Auto-commit after checklist generation condition: null @@ -151,6 +169,7 @@ hooks: command: speckit.git.commit enabled: true optional: true + priority: 10 prompt: Commit analysis results? description: Auto-commit after analysis condition: null @@ -159,6 +178,7 @@ hooks: command: speckit.git.commit enabled: true optional: true + priority: 10 prompt: Commit after syncing issues? description: Auto-commit after tasks-to-issues conversion condition: null diff --git a/.specify/extensions/.registry b/.specify/extensions/.registry index 2816a73..b9246ee 100644 --- a/.specify/extensions/.registry +++ b/.specify/extensions/.registry @@ -2,9 +2,12 @@ "schema_version": "1.0", "extensions": { "git": { - "version": "1.0.0", - "source": "local", - "manifest_hash": "sha256:9731aa8143a72fbebfdb440f155038ab42642517c2b2bdbbf67c8fdbe076ed79", + "version": "1.0.1", + "source": { + "kind": "catalog", + "catalog": "default" + }, + "manifest_hash": "sha256:698cc7089602db44622de39730555db4999cda94ab47195bcfe18f41d08b430a", "enabled": true, "priority": 10, "registered_commands": { @@ -20,9 +23,12 @@ "installed_at": "2026-06-16T06:08:47.448156+00:00" }, "agent-context": { - "version": "1.0.0", - "source": "local", - "manifest_hash": "sha256:9a1dc02d2d0139bb03860392ecacef79183be2c442feda2f9ccaa4e5907b1e47", + "version": "1.0.2", + "source": { + "kind": "catalog", + "catalog": "default" + }, + "manifest_hash": "sha256:270100175bb742c37b8d549f2233c5b79114869dac754883dbecac2a4813beef", "enabled": true, "priority": 10, "registered_commands": { diff --git a/.specify/extensions/agent-context/README.md b/.specify/extensions/agent-context/README.md index dba004e..53602c3 100644 --- a/.specify/extensions/agent-context/README.md +++ b/.specify/extensions/agent-context/README.md @@ -2,45 +2,55 @@ 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: `` / ``). +It owns the lifecycle of the managed section delimited by the configurable start/end markers (defaults: `` / ``). For `.mdc` files, it also ensures the YAML frontmatter (the metadata block at the top of the file) contains `alwaysApply: true`. Otherwise, everything outside the managed section is untouched. + +> NOTE: Spec Kit itself never touches your agent context file. This extension is the only thing that does, and it's opt-in: install it if you want the block kept in sync, skip it if you'd rather manage that file yourself. ## 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: +Not every Spec Kit user wants Spec Kit to write into the coding agent's context file. Keeping this behavior in a dedicated, **opt-in** 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`). +- **Choose whether to install it at all** - `specify init` does **not** install it. Add it explicitly when you want Spec Kit to manage the agent context file; when it is absent, the file is never modified, and when it is disabled, its automatic hooks do not run. +- **Customize the markers** by editing `.specify/extensions/agent-context/agent-context-config.yml` ([agent-context-config.yml](./agent-context-config.yml) in this repo) - the bundled scripts honor the `context_markers` value. +- **Synchronize multiple agent anchors** by setting `context_files` when a project intentionally uses more than one coding agent context file, such as `AGENTS.md` and `CLAUDE.md`. +- **Refresh on demand** by running the `speckit.agent-context.update` command in your agent, or automatically through the hooks declared in [extension.yml](./extension.yml) (`after_specify`, `after_plan`). -## Commands +## Installation -| Command | Description | -|---------|-------------| -| `speckit.agent-context.update` | Refresh the managed section in the agent context file with the current plan path. | +To install the extension, from the root of an initialized Spec Kit project, run: -## Configuration +```bash +specify extension add agent-context +``` -All configuration flows through the extension's own config file at -`.specify/extensions/agent-context/agent-context-config.yml`: +## Disabling -```yaml -# Path to the coding agent context file managed by this extension -context_file: CLAUDE.md +```bash +specify extension disable agent-context -# Delimiters for the managed Spec Kit section -context_markers: - start: "" - end: "" +# Re-enable it +specify extension enable agent-context ``` -- `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. +While this extension is disabled (or not installed), nothing in Spec Kit creates, updates, or removes the managed block - the `__CONTEXT_FILE__` placeholder in any template is left as-is, and the extension's own config is never read. + +## Commands + +| Command | Description | +| ------------------------------ | --------------------------------------------------------------------------------- | +| `speckit.agent-context.update` | Refresh the managed section in the agent context file with the current plan path. | + +> NOTE: The command ID above is canonical. Invoke it using the syntax for your integration: `/speckit.agent-context.update` for dot-command integrations; `/speckit-agent-context-update` for hyphen/skills integrations (including Forge and Cline); `$speckit-agent-context-update` for Codex or ZCode in skills mode; or `/skill:speckit-agent-context-update` for Kimi. + +## Configuration + +All configuration flows through the extension's own config file at `.specify/extensions/agent-context/agent-context-config.yml` ([agent-context-config.yml](./agent-context-config.yml) in the repo). ## 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: +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 @@ -48,10 +58,6 @@ pip install pyyaml /path/to/speckit-python -m pip install pyyaml ``` -## Disable - -```bash -specify extension disable agent-context -``` +## Issues -When disabled, Spec Kit skips context file creation, updates, and removal (the gates are inside `upsert_context_section()` and `remove_context_section()`). +For any other issues, please create an issue in the [official GitHub repo](https://github.com/github/spec-kit/issues). diff --git a/.specify/extensions/agent-context/agent-context-defaults.json b/.specify/extensions/agent-context/agent-context-defaults.json new file mode 100644 index 0000000..a00b1d5 --- /dev/null +++ b/.specify/extensions/agent-context/agent-context-defaults.json @@ -0,0 +1,44 @@ +{ + "_comment": "Default coding agent context file per integration, owned by the agent-context extension. Used to self-seed agent-context-config.yml when it declares no context_file/context_files. Keyed by the Spec Kit integration key recorded in .specify/init-options.json. This mapping is independent of the Specify CLI by design.", + "agents": { + "agy": "AGENTS.md", + "alquimia": "ALQUIMIA.md", + "amp": "AGENTS.md", + "auggie": ".augment/rules/specify-rules.md", + "bob": "AGENTS.md", + "claude": "CLAUDE.md", + "cline": ".clinerules/specify-rules.md", + "codebuddy": "CODEBUDDY.md", + "codex": "AGENTS.md", + "copilot": ".github/copilot-instructions.md", + "cursor-agent": ".cursor/rules/specify-rules.mdc", + "devin": "AGENTS.md", + "firebender": ".firebender/rules/specify-rules.mdc", + "forge": "AGENTS.md", + "gemini": "GEMINI.md", + "generic": "AGENTS.md", + "goose": "AGENTS.md", + "grok": "AGENTS.md", + "hermes": "AGENTS.md", + "junie": ".junie/AGENTS.md", + "kilocode": ".kilocode/rules/specify-rules.md", + "kimi": "AGENTS.md", + "kiro-cli": "AGENTS.md", + "lingma": ".lingma/rules/specify-rules.md", + "mcode": "AGENTS.md", + "muse": "AGENTS.md", + "omp": "AGENTS.md", + "opencode": "AGENTS.md", + "pi": "AGENTS.md", + "qodercli": "QODER.md", + "qwen": "QWEN.md", + "rovodev": "AGENTS.md", + "shai": "SHAI.md", + "tabnine": "TABNINE.md", + "trae": ".trae/rules/project_rules.md", + "vibe": "AGENTS.md", + "windsurf": ".windsurf/rules/specify-rules.md", + "zcode": "ZCODE.md", + "zed": "AGENTS.md" + } +} diff --git a/.specify/extensions/agent-context/commands/speckit.agent-context.update.md b/.specify/extensions/agent-context/commands/speckit.agent-context.update.md index 02f1706..71c85f5 100644 --- a/.specify/extensions/agent-context/commands/speckit.agent-context.update.md +++ b/.specify/extensions/agent-context/commands/speckit.agent-context.update.md @@ -1,5 +1,5 @@ --- -description: "Refresh the managed Spec Kit section in the coding agent context file" +description: "Refresh the managed Spec Kit section in coding agent context file(s)" --- # Update Coding Agent Context @@ -12,15 +12,16 @@ 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_files` — optional project-relative paths for multiple coding agent context files. When non-empty, the script updates each listed file and the list takes precedence over `context_file`. - `context_markers.start` / `.end` — the delimiters surrounding the managed section. Defaults to `` and `` 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//plan.md`). +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 (any `plan.md` under `specs/`, including nested scoped layouts such as `specs///plan.md`). -If `context_file` is empty or the file cannot be located, the command reports nothing to do and exits successfully. +If `context_files` and `context_file` are empty, the command reports nothing to do and exits successfully. Context file paths must stay project-relative; absolute paths, Windows drive paths, backslash separators, and `..` path segments are rejected. ## 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`. +When `plan_path` is omitted, the script auto-detects the most recently modified `specs/**/plan.md` (searched recursively, so nested scoped layouts are discovered). diff --git a/.specify/extensions/agent-context/extension.yml b/.specify/extensions/agent-context/extension.yml index 191069e..7f9e986 100644 --- a/.specify/extensions/agent-context/extension.yml +++ b/.specify/extensions/agent-context/extension.yml @@ -3,7 +3,7 @@ schema_version: "1.0" extension: id: agent-context name: "Coding Agent Context" - version: "1.0.0" + version: "1.0.2" 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 diff --git a/.specify/extensions/agent-context/scripts/bash/update-agent-context.sh b/.specify/extensions/agent-context/scripts/bash/update-agent-context.sh index 42ce44d..7fbe3ef 100755 --- a/.specify/extensions/agent-context/scripts/bash/update-agent-context.sh +++ b/.specify/extensions/agent-context/scripts/bash/update-agent-context.sh @@ -1,18 +1,18 @@ #!/usr/bin/env bash # update-agent-context.sh # -# Refresh the managed Spec Kit section in the coding agent's context file +# Refresh the managed Spec Kit section in the coding agent's context file(s) # (e.g. CLAUDE.md, .github/copilot-instructions.md, AGENTS.md). # -# Reads `context_file` and `context_markers.{start,end}` from the +# Reads `context_files` or `context_file`, plus `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. +# When `plan_path` is omitted, the script derives it from `.specify/feature.json` +# (written by /speckit-specify). Falls back to the most recently modified +# `specs/**/plan.md` only when feature.json is absent or its plan does not exist yet. set -euo pipefail @@ -26,22 +26,48 @@ if [[ ! -f "$EXT_CONFIG" ]]; then exit 0 fi -# Locate a suitable Python interpreter (python3, then python). +# Locate a Python 3 interpreter with PyYAML available. _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 +_python_candidates=() +[[ -n "${SPECKIT_PYTHON:-}" ]] && _python_candidates+=("$SPECKIT_PYTHON") +_python_candidates+=("python3" "python") +for _candidate in "${_python_candidates[@]}"; do + if command -v "$_candidate" >/dev/null 2>&1 \ + && "$_candidate" - <<'PY' >/dev/null 2>&1 +import sys +try: + import yaml # noqa: F401 +except ImportError: + sys.exit(1) +sys.exit(0 if sys.version_info[0] == 3 else 1) +PY + then + _python="$_candidate" + break + fi +done +unset _candidate _python_candidates if [[ -z "$_python" ]]; then - echo "agent-context: Python 3 not found on PATH; skipping update." >&2 + echo "agent-context: Python 3 with PyYAML not found on PATH; skipping update." >&2 + echo " To resolve: pip install pyyaml (or install it into the environment used by python3)." >&2 exit 0 fi +_case_insensitive_context_files=0 +case "$(uname -s 2>/dev/null || true)" in + MINGW*|MSYS*|CYGWIN*) _case_insensitive_context_files=1 ;; +esac -# Parse extension config once; emit three newline-separated fields: -# context_file, context_markers.start, context_markers.end -if ! _raw_opts="$("$_python" - "$EXT_CONFIG" <<'PY' +# Parse extension config once; emit context files as JSON, followed by marker strings. +# +# NOTE (bash 3.2 / macOS portability): the embedded Python heredocs below run +# inside $(...) command substitution. bash 3.2 (the system /bin/bash on macOS) +# mis-parses a single-quote/apostrophe in a heredoc body nested in $(...), +# failing with "unexpected EOF while looking for matching `''". Keep these +# $(...)-nested heredoc bodies free of apostrophes (use double quotes in Python +# string literals and avoid contractions in comments). +if ! _raw_opts="$("$_python" - "$EXT_CONFIG" "$_case_insensitive_context_files" "$PROJECT_ROOT" <<'PY' +import json import sys try: import yaml @@ -73,7 +99,71 @@ def get_str(obj, *keys): else: return "" return node if isinstance(node, str) else "" -print(get_str(data, "context_file")) +context_files = [] +seen_context_files = set() +case_insensitive = sys.argv[2] == "1" or sys.platform.startswith(("win32", "cygwin")) +def add_context_file(value): + if not isinstance(value, str): + return + candidate = value.strip() + if not candidate: + return + key = candidate.casefold() if case_insensitive else candidate + if key in seen_context_files: + return + context_files.append(candidate) + seen_context_files.add(key) +raw_files = data.get("context_files") +if isinstance(raw_files, list): + for value in raw_files: + add_context_file(value) +if not context_files: + add_context_file(get_str(data, "context_file")) +if not context_files: + # Self-seed: the agent-context extension manages its own lifecycle, so when + # its config declares no target, it derives one from the active integration + # recorded in init-options.json, mapped through the bundled + # agent-context-defaults.json file. This is independent of the Specify CLI + # by design; nothing here imports specify_cli. + project_root = sys.argv[3] if len(sys.argv) > 3 else "." + integration_key = "" + try: + with open( + f"{project_root}/.specify/init-options.json", "r", encoding="utf-8" + ) as fh: + opts = json.load(fh) + if isinstance(opts, dict): + value = opts.get("integration") or opts.get("ai") or "" + integration_key = value if isinstance(value, str) else "" + except Exception: + integration_key = "" + if integration_key: + defaults_path = ( + f"{project_root}/.specify/extensions/agent-context/" + "agent-context-defaults.json" + ) + mapping = {} + try: + with open(defaults_path, "r", encoding="utf-8") as fh: + loaded = json.load(fh) + agents = loaded.get("agents", {}) if isinstance(loaded, dict) else {} + mapping = agents if isinstance(agents, dict) else {} + except Exception: + print( + "agent-context: unable to read %s; cannot self-seed the context " + "file. Set context_file in the extension config." % defaults_path, + file=sys.stderr, + ) + mapping = {} + add_context_file(mapping.get(integration_key, "") or "") + if not context_files: + print( + "agent-context: no default context file is known for integration " + "%s. Set context_file in the extension config to choose one." + % integration_key, + file=sys.stderr, + ) +print(json.dumps(context_files)) print(get_str(data, "context_markers", "start")) print(get_str(data, "context_markers", "end")) PY @@ -86,32 +176,77 @@ _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 +if (( ${#_opts_lines[@]} < 1 )); then + echo "agent-context: malformed config parser output; expected at least the context_files line, got ${#_opts_lines[@]}; skipping update." >&2 exit 0 fi -CONTEXT_FILE="${_opts_lines[0]}" -MARKER_START="${_opts_lines[1]}" -MARKER_END="${_opts_lines[2]}" +# The marker lines may be absent: the $(...) capture above strips trailing +# newlines, so blank markers (the config omitting context_markers and relying on +# defaults) collapse the 3-line output to fewer lines. Default them to empty here +# and let the DEFAULT_START/END substitution below fill them in, matching the +# Python and PowerShell ports. +CONTEXT_FILES_JSON="${_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 +if ! _context_files_raw="$("$_python" - "$CONTEXT_FILES_JSON" <<'PY' +import json +import sys +try: + data = json.loads(sys.argv[1]) +except Exception: + data = [] +if not isinstance(data, list): + data = [] +for value in data: + if isinstance(value, str) and value: + print(value) +PY +)"; then + echo "agent-context: malformed context_files parser output; skipping update." >&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 +CONTEXT_FILES=() +while IFS= read -r _line || [[ -n "$_line" ]]; do + [[ -n "$_line" ]] && CONTEXT_FILES+=("$_line") +done < <(printf '%s\n' "$_context_files_raw") + +if (( ${#CONTEXT_FILES[@]} == 0 )); then + echo "agent-context: context_files/context_file not set in extension config; nothing to do." >&2 + exit 0 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 + +for CONTEXT_FILE in "${CONTEXT_FILES[@]}"; do + # Reject absolute paths, backslash separators, and '..' path segments in context files + if [[ "$CONTEXT_FILE" == /* ]] || [[ "$CONTEXT_FILE" =~ ^[A-Za-z]: ]]; then + echo "agent-context: context files must be project-relative paths; got '$CONTEXT_FILE'." >&2 + exit 1 + fi + if [[ "$CONTEXT_FILE" == *\\* ]]; then + echo "agent-context: context files 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 files must not contain '..' path segments; got '$CONTEXT_FILE'." >&2 + exit 1 + fi + done + if ! "$_python" - "$PROJECT_ROOT" "$CONTEXT_FILE" <<'PY' +import sys +from pathlib import Path + +root = Path(sys.argv[1]).resolve() +target = (root / sys.argv[2]).resolve(strict=False) +try: + target.relative_to(root) +except ValueError: + sys.exit(1) +PY + then + echo "agent-context: context file path resolves outside the project root; got '$CONTEXT_FILE'." >&2 exit 1 fi done @@ -122,28 +257,92 @@ unset _cf_parts _seg PLAN_PATH="${1:-}" if [[ -z "$PLAN_PATH" ]]; then - # Pick the most recently modified plan.md one level deep (specs//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 + # Prefer .specify/feature.json (written by /speckit-specify) over mtime heuristic. + _feature_json="$PROJECT_ROOT/.specify/feature.json" + if [[ -f "$_feature_json" ]]; then + _feature_dir="$("$_python" - "$_feature_json" <<'PY' +import sys, json +try: + with open(sys.argv[1], encoding="utf-8") as fh: + d = json.load(fh) + val = d.get("feature_directory", "") + print(val if isinstance(val, str) else "") +except Exception: + print("") +PY +)" + # Normalize backslashes (written by PS on Windows) to forward slashes before path ops. + _feature_dir="$(printf '%s' "$_feature_dir" | tr '\\' '/')" + _feature_dir="${_feature_dir%/}" + if [[ -n "$_feature_dir" ]]; then + # feature_directory may be relative or absolute (absolute paths outside PROJECT_ROOT + # are preserved as-is by _persist_feature_json in common.sh). + # Also match drive-qualified paths (C:/...) written by PowerShell on Windows. + if [[ "$_feature_dir" == /* ]] || [[ "$_feature_dir" =~ ^[A-Za-z]:/ ]]; then + _candidate="$_feature_dir/plan.md" + else + _candidate="$PROJECT_ROOT/$_feature_dir/plan.md" + fi + if [[ -f "$_candidate" ]]; then + # Resolve symlinks before comparing so paths like /var/… vs /private/var/… + # (macOS) are treated as equivalent. Mirrors the mtime-fallback approach. + PLAN_PATH="$("$_python" - "$PROJECT_ROOT" "$_candidate" <<'PY' +import sys 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 "") +root = Path(sys.argv[1]).resolve() +cand = Path(sys.argv[2]).resolve() +try: + print(cand.relative_to(root).as_posix()) +except ValueError: + # Outside project root: emit the resolved path in POSIX form. + # as_posix() converts backslashes correctly on native Windows Python. + print(cand.as_posix()) PY )" - if [[ -n "$_plan_abs" ]]; then - PLAN_PATH="${_plan_abs#"$PROJECT_ROOT/"}" + fi + fi fi -fi -CTX_PATH="$PROJECT_ROOT/$CONTEXT_FILE" -mkdir -p "$(dirname "$CTX_PATH")" + # Fall back to mtime only when feature.json is absent or its plan does not exist yet. + # Python emits a project-relative POSIX path directly to avoid bash prefix-strip + # issues with backslash paths on Windows (Git bash / MSYS2). + if [[ -z "$PLAN_PATH" ]]; then + _plan_rel="$("$_python" - "$PROJECT_ROOT" <<'PY' +import sys +from pathlib import Path +root = Path(sys.argv[1]).resolve() +specs = root / "specs" + +def _resolved_rel(p): + # Resolve symlinks before checking containment: relative_to() is lexical + # and would otherwise accept a plan reached through a specs/ symlink that + # points outside the project, emitting an in-project-looking path for an + # out-of-project file (or picking it as "most recent"). + try: + return p.resolve().relative_to(root) + except (OSError, ValueError): + return None + +# Recurse (rather than the old one-level specs/*/plan.md glob) so scoped layouts +# created via SPECIFY_FEATURE_DIRECTORY, e.g. specs///plan.md, +# are still discovered when feature.json is absent (#3024). +candidates = [] +for p in specs.rglob("plan.md"): + rel = _resolved_rel(p) + if rel: + candidates.append((p, rel)) +candidates.sort(key=lambda pr: pr[0].stat().st_mtime, reverse=True) +if candidates: + print(candidates[0][1].as_posix()) +else: + print("") +PY +)" + if [[ -n "$_plan_rel" ]]; then + PLAN_PATH="$_plan_rel" + fi + fi +fi # Build the managed section TMP_SECTION="$(mktemp)" @@ -158,12 +357,63 @@ trap 'rm -f "$TMP_SECTION"' EXIT echo "$MARKER_END" } > "$TMP_SECTION" -"$_python" - "$CTX_PATH" "$MARKER_START" "$MARKER_END" "$TMP_SECTION" <<'PY' -import sys, os +for CONTEXT_FILE in "${CONTEXT_FILES[@]}"; do + CTX_PATH="$PROJECT_ROOT/$CONTEXT_FILE" + mkdir -p "$(dirname "$CTX_PATH")" + + "$_python" - "$CTX_PATH" "$MARKER_START" "$MARKER_END" "$TMP_SECTION" <<'PY' +import os +import re +import sys + 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" + +def ensure_mdc_frontmatter(content): + """Ensure ``.mdc`` content has YAML frontmatter with ``alwaysApply: true``. + + Cursor only auto-loads ``.mdc`` rule files that carry frontmatter with + ``alwaysApply: true``. Prepend it when missing, or repair the value while + preserving any existing frontmatter comments/formatting. + """ + leading_ws = len(content) - len(content.lstrip()) + leading = content[:leading_ws] + stripped = content[leading_ws:] + + if not stripped.startswith("---"): + return "---\nalwaysApply: true\n---\n\n" + content + + match = re.match( + r"^(---[ \t]*\r?\n)(.*?)(\r?\n---[ \t]*)(\r?\n|$)(.*)", + stripped, + re.DOTALL, + ) + if not match: + return "---\nalwaysApply: true\n---\n\n" + content + + opening, fm_text, closing, sep, rest = match.groups() + newline = "\r\n" if "\r\n" in opening else "\n" + + if re.search(r"(?m)^[ \t]*alwaysApply[ \t]*:[ \t]*true[ \t]*(?:#.*)?$", fm_text): + return content + + if re.search(r"(?m)^[ \t]*alwaysApply[ \t]*:", fm_text): + fm_text = re.sub( + r"(?m)^([ \t]*)alwaysApply[ \t]*:.*?([ \t]*(?:#.*)?)$", + r"\1alwaysApply: true\2", + fm_text, + count=1, + ) + elif fm_text.strip(): + fm_text = fm_text + newline + "alwaysApply: true" + else: + fm_text = "alwaysApply: true" + + return f"{leading}{opening}{fm_text}{closing}{sep}{rest}" + + if os.path.exists(ctx_path): with open(ctx_path, "r", encoding="utf-8-sig") as fh: content = fh.read() @@ -193,8 +443,11 @@ else: new_content = section new_content = new_content.replace("\r\n", "\n").replace("\r", "\n") +if ctx_path.casefold().endswith(".mdc"): + new_content = ensure_mdc_frontmatter(new_content) with open(ctx_path, "wb") as fh: fh.write(new_content.encode("utf-8")) PY -echo "agent-context: updated $CONTEXT_FILE" + echo "agent-context: updated $CONTEXT_FILE" +done diff --git a/.specify/extensions/agent-context/scripts/powershell/update-agent-context.ps1 b/.specify/extensions/agent-context/scripts/powershell/update-agent-context.ps1 index dad309c..91d067c 100644 --- a/.specify/extensions/agent-context/scripts/powershell/update-agent-context.ps1 +++ b/.specify/extensions/agent-context/scripts/powershell/update-agent-context.ps1 @@ -1,14 +1,18 @@ #!/usr/bin/env pwsh # update-agent-context.ps1 # -# Refresh the managed Spec Kit section in the coding agent's context file +# Refresh the managed Spec Kit section in the coding agent's context file(s) # (e.g. CLAUDE.md, .github/copilot-instructions.md, AGENTS.md). # -# Reads `context_file` and `context_markers.{start,end}` from the +# Reads `context_files` or `context_file`, plus `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] +# +# When `plan_path` is omitted, the script derives it from `.specify/feature.json` +# (written by /speckit-specify). Falls back to the most recently modified +# `specs/**/plan.md` only when feature.json is absent or its plan does not exist yet. [CmdletBinding()] param( @@ -16,6 +20,56 @@ param( [string]$PlanPath ) +function Add-MdcFrontmatter { + <# + Ensure .mdc content has YAML frontmatter with alwaysApply: true. + + Cursor only auto-loads .mdc rule files that carry frontmatter with + alwaysApply: true. Prepend it when missing, or repair the value while + preserving any existing frontmatter comments/formatting. + #> + param([Parameter(Mandatory = $true)][AllowEmptyString()][string]$Content) + + $leading = '' + $stripped = $Content + $m = [regex]::Match($Content, '^\s*') + if ($m.Success) { + $leading = $m.Value + $stripped = $Content.Substring($m.Length) + } + + if (-not $stripped.StartsWith('---')) { + return "---`nalwaysApply: true`n---`n`n" + $Content + } + + $fm = [regex]::Match($stripped, '^(---[ \t]*\r?\n)(.*?)(\r?\n---[ \t]*)(\r?\n|$)(.*)', [System.Text.RegularExpressions.RegexOptions]::Singleline) + if (-not $fm.Success) { + return "---`nalwaysApply: true`n---`n`n" + $Content + } + + $opening = $fm.Groups[1].Value + $fmText = $fm.Groups[2].Value + $closing = $fm.Groups[3].Value + $sep = $fm.Groups[4].Value + $rest = $fm.Groups[5].Value + $newline = if ($opening.Contains("`r`n")) { "`r`n" } else { "`n" } + + if ([regex]::IsMatch($fmText, '(?m)^[ \t]*alwaysApply[ \t]*:[ \t]*true[ \t]*(?:#.*)?$')) { + return $Content + } + + if ([regex]::IsMatch($fmText, '(?m)^[ \t]*alwaysApply[ \t]*:')) { + $alwaysApplyRegex = [regex]'(?m)^([ \t]*)alwaysApply[ \t]*:.*?([ \t]*(?:#.*)?)$' + $fmText = $alwaysApplyRegex.Replace($fmText, '${1}alwaysApply: true${2}', 1) + } elseif ($fmText.Trim()) { + $fmText = $fmText + $newline + 'alwaysApply: true' + } else { + $fmText = 'alwaysApply: true' + } + + return "$leading$opening$fmText$closing$sep$rest" +} + function Get-ConfigValue { param( [AllowNull()][object]$Object, @@ -52,6 +106,66 @@ function Test-ConfigObject { return $false } +function Resolve-ContextPath { + param( + [Parameter(Mandatory = $true)][string]$Root, + [Parameter(Mandatory = $true)][string]$RelativePath + ) + + $rootFull = [System.IO.Path]::GetFullPath($Root) + $segments = $RelativePath -split '/' + $resolved = $rootFull + + foreach ($segment in $segments) { + if ([string]::IsNullOrWhiteSpace($segment) -or $segment -eq '.') { + continue + } + + $candidate = [System.IO.Path]::GetFullPath((Join-Path $resolved $segment)) + if (Test-Path -LiteralPath $candidate) { + $item = Get-Item -LiteralPath $candidate -Force + if ($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint) { + $target = $item.Target + if ($target -is [System.Array]) { + $target = $target[0] + } + if ($target) { + if ([System.IO.Path]::IsPathRooted($target)) { + $candidate = [System.IO.Path]::GetFullPath($target) + } else { + $candidate = [System.IO.Path]::GetFullPath( + (Join-Path (Split-Path -Parent $candidate) $target) + ) + } + } + } + } + $resolved = $candidate + } + + return $resolved +} + +function Test-IsSubPath { + param( + [Parameter(Mandatory = $true)][string]$Root, + [Parameter(Mandatory = $true)][string]$Path + ) + + $comparison = if ([System.Environment]::OSVersion.Platform -eq [System.PlatformID]::Win32NT) { + [System.StringComparison]::OrdinalIgnoreCase + } else { + [System.StringComparison]::Ordinal + } + $rootFull = [System.IO.Path]::GetFullPath($Root).TrimEnd( + [System.IO.Path]::DirectorySeparatorChar, + [System.IO.Path]::AltDirectorySeparatorChar + ) + $pathFull = [System.IO.Path]::GetFullPath($Path) + return $pathFull.Equals($rootFull, $comparison) -or + $pathFull.StartsWith($rootFull + [System.IO.Path]::DirectorySeparatorChar, $comparison) +} + $ErrorActionPreference = 'Stop' $DefaultStart = '' $DefaultEnd = '' @@ -66,20 +180,37 @@ if (-not (Test-Path -LiteralPath $ExtConfig)) { $Options = $null if (Get-Command ConvertFrom-Yaml -ErrorAction SilentlyContinue) { try { - $Options = Get-Content -LiteralPath $ExtConfig -Raw | ConvertFrom-Yaml -ErrorAction Stop + $Options = Get-Content -LiteralPath $ExtConfig -Raw -Encoding UTF8 | ConvertFrom-Yaml -ErrorAction Stop } catch { - # fall through to Python fallback + # fall through to ConvertFrom-Json fallback } } if ($null -eq $Options) { - # ConvertFrom-Yaml unavailable or failed; fall back to Python+PyYAML. + # ConvertFrom-Yaml unavailable or failed; try ConvertFrom-Json (no external deps, + # works when the config file is valid JSON, which is a subset of YAML). + try { + $raw = Get-Content -LiteralPath $ExtConfig -Raw -Encoding UTF8 + $Options = $raw | ConvertFrom-Json -ErrorAction Stop + if (-not (Test-ConfigObject -Object $Options)) { $Options = $null } + } catch { + $Options = $null + } +} + +if ($null -eq $Options) { + # ConvertFrom-Yaml/Json unavailable or failed; fall back to Python+PyYAML. $pythonCmd = $null - foreach ($candidate in @('python3', 'python')) { + $pythonCandidates = @() + if ($env:SPECKIT_PYTHON) { + $pythonCandidates += $env:SPECKIT_PYTHON + } + $pythonCandidates += @('python3', 'python') + foreach ($candidate in $pythonCandidates) { if (Get-Command $candidate -ErrorAction SilentlyContinue) { - # Verify it is Python 3 - $verOut = & $candidate --version 2>&1 - if ($verOut -match 'Python 3') { + # Verify it is Python 3 with PyYAML available. + $null = & $candidate -c "import sys; import yaml; sys.exit(0 if sys.version_info[0] == 3 else 1)" 2>$null + if ($LASTEXITCODE -eq 0) { $pythonCmd = $candidate break } @@ -87,8 +218,10 @@ if ($null -eq $Options) { } if ($pythonCmd) { + $pyScript = $null try { - $jsonOut = & $pythonCmd -c @' + $pyScript = [System.IO.Path]::GetTempFileName() + Set-Content -LiteralPath $pyScript -Encoding UTF8 -Value @' import json import sys try: @@ -114,12 +247,17 @@ if not isinstance(data, dict): data = {} print(json.dumps(data)) -'@ $ExtConfig +'@ + $jsonOut = & $pythonCmd $pyScript $ExtConfig if ($LASTEXITCODE -eq 0 -and $jsonOut) { $Options = $jsonOut | ConvertFrom-Json -ErrorAction Stop } } catch { $Options = $null + } finally { + if ($pyScript -and (Test-Path -LiteralPath $pyScript)) { + Remove-Item -LiteralPath $pyScript -Force -ErrorAction SilentlyContinue + } } } @@ -134,21 +272,100 @@ if (-not (Test-ConfigObject -Object $Options)) { 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.' +$ConfiguredContextFiles = Get-ConfigValue -Object $Options -Key 'context_files' +$ContextFiles = @() +if ($null -ne $ConfiguredContextFiles) { + foreach ($item in @($ConfiguredContextFiles)) { + if ($item -is [string] -and -not [string]::IsNullOrWhiteSpace($item)) { + $ContextFiles += $item.Trim() + } + } +} +if ($ContextFiles.Count -eq 0) { + $ContextFile = Get-ConfigValue -Object $Options -Key 'context_file' + if ($ContextFile -is [string] -and -not [string]::IsNullOrWhiteSpace($ContextFile)) { + $ContextFiles += $ContextFile.Trim() + } +} +$pathComparison = if ([System.Environment]::OSVersion.Platform -eq [System.PlatformID]::Win32NT) { + [System.StringComparer]::OrdinalIgnoreCase +} else { + [System.StringComparer]::Ordinal +} +$seenContextFiles = [System.Collections.Generic.HashSet[string]]::new($pathComparison) +$dedupedContextFiles = @() +foreach ($ContextFile in $ContextFiles) { + if ($seenContextFiles.Add($ContextFile)) { + $dedupedContextFiles += $ContextFile + } +} +$ContextFiles = $dedupedContextFiles +if ($ContextFiles.Count -eq 0) { + # Self-seed: the agent-context extension owns its lifecycle, so when its + # own config declares no target it derives one from the active integration + # recorded in init-options.json, using the extension's OWN bundled mapping + # (agent-context-defaults.json). Independent of the Specify CLI by design. + $initOptionsPath = Join-Path $ProjectRoot '.specify/init-options.json' + if (Test-Path -LiteralPath $initOptionsPath) { + try { + $initOpts = Get-Content -LiteralPath $initOptionsPath -Raw | ConvertFrom-Json -ErrorAction Stop + $integrationKey = $null + if ($initOpts.PSObject.Properties['integration'] -and $initOpts.integration) { + $integrationKey = [string]$initOpts.integration + } elseif ($initOpts.PSObject.Properties['ai'] -and $initOpts.ai) { + $integrationKey = [string]$initOpts.ai + } + if ($integrationKey) { + $defaultsPath = Join-Path $ProjectRoot '.specify/extensions/agent-context/agent-context-defaults.json' + if (Test-Path -LiteralPath $defaultsPath) { + $defaults = Get-Content -LiteralPath $defaultsPath -Raw | ConvertFrom-Json -ErrorAction Stop + $derived = $null + if ($defaults.PSObject.Properties['agents'] -and $defaults.agents.PSObject.Properties[$integrationKey]) { + $derived = [string]$defaults.agents.PSObject.Properties[$integrationKey].Value + } + if ($derived -and -not [string]::IsNullOrWhiteSpace($derived)) { + $ContextFiles += $derived.Trim() + } else { + Write-Warning ("agent-context: no default context file is known for integration '{0}'; set 'context_file' in the extension config to choose one." -f $integrationKey) + } + } else { + Write-Warning ("agent-context: unable to read {0}; cannot self-seed the context file. Set 'context_file' in the extension config." -f $defaultsPath) + } + } + } catch { + # Non-fatal: fall through to the nothing-to-do guard below. + } + } +} +if ($ContextFiles.Count -eq 0) { + Write-Warning 'agent-context: context_files/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 +foreach ($ContextFile in $ContextFiles) { + # Reject absolute paths, drive-qualified paths, backslash separators, and '..' path segments in context files + if ($ContextFile -match '^[A-Za-z]:') { + Write-Warning "agent-context: context files must be project-relative paths; got '$ContextFile'." + exit 1 + } + if ([System.IO.Path]::IsPathRooted($ContextFile)) { + Write-Warning "agent-context: context files must be project-relative paths; got '$ContextFile'." + exit 1 + } + if ($ContextFile.Contains('\')) { + Write-Warning "agent-context: context files must not contain backslash separators; got '$ContextFile'." + exit 1 + } + $cfSegments = $ContextFile -split '[/\\]' + if ($cfSegments -contains '..') { + Write-Warning "agent-context: context files must not contain '..' path segments; got '$ContextFile'." + exit 1 + } + $resolvedTarget = Resolve-ContextPath -Root $ProjectRoot -RelativePath $ContextFile + if (-not (Test-IsSubPath -Root $ProjectRoot -Path $resolvedTarget)) { + Write-Warning "agent-context: context file path resolves outside the project root; got '$ContextFile'." + exit 1 + } } $MarkerStart = $DefaultStart @@ -166,28 +383,72 @@ if ($cm) { } if (-not $PlanPath) { - # Discover plan.md exactly one level deep (specs//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('\','/') + # Prefer .specify/feature.json (written by /speckit-specify) over mtime heuristic. + $FeatureJson = Join-Path $ProjectRoot '.specify/feature.json' + if (Test-Path -LiteralPath $FeatureJson) { + try { + $fj = Get-Content -LiteralPath $FeatureJson -Raw -Encoding UTF8 | ConvertFrom-Json + $featureDir = $fj.feature_directory + if ($featureDir -isnot [string] -or -not $featureDir) { + $featureDir = $null + } else { + $featureDir = $featureDir.TrimEnd('\', '/') + } + if ($featureDir) { + # Join-Path on Unix does not treat absolute ChildPath as "wins"; check explicitly. + if ([System.IO.Path]::IsPathRooted($featureDir)) { + $candidatePlan = Join-Path $featureDir 'plan.md' + } else { + $candidatePlan = Join-Path (Join-Path $ProjectRoot $featureDir) 'plan.md' + } + if (Test-Path -LiteralPath $candidatePlan) { + # Resolve ./ .. segments before relativizing (mirrors bash Path.resolve()). + # GetFullPath is available in .NET Framework 4.x (PS 5.1 compatible). + $resolvedPlan = [System.IO.Path]::GetFullPath($candidatePlan) + $resolvedDir = [System.IO.Path]::GetDirectoryName($resolvedPlan) + $normRoot = $ProjectRoot.TrimEnd('\', '/') + [System.IO.Path]::DirectorySeparatorChar + $normDir = $resolvedDir.TrimEnd('\', '/') + [System.IO.Path]::DirectorySeparatorChar + $cmp = if ([System.Environment]::OSVersion.Platform -eq [System.PlatformID]::Win32NT) { [System.StringComparison]::OrdinalIgnoreCase } else { [System.StringComparison]::Ordinal } + if ($normDir.StartsWith($normRoot, $cmp)) { + $relDir = $normDir.Substring($normRoot.Length).TrimEnd('\', '/') + $PlanPath = if ($relDir) { $relDir.Replace('\', '/') + '/plan.md' } else { 'plan.md' } + } else { + $PlanPath = $resolvedPlan.Replace('\', '/') + } + } + } + } catch { + # Non-fatal: fall through to mtime heuristic. } - } 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 + # Fall back to mtime only when feature.json is absent or its plan does not exist yet. + if (-not $PlanPath) { + try { + $specsDir = Join-Path $ProjectRoot 'specs' + # Recurse (rather than the old one-level specs/*/plan.md scan) so scoped + # layouts created via SPECIFY_FEATURE_DIRECTORY, e.g. + # specs///plan.md, are still discovered when + # feature.json is absent (#3024). + $candidate = Get-ChildItem -Path $specsDir -Filter 'plan.md' -File -Recurse -ErrorAction SilentlyContinue | + Sort-Object LastWriteTime -Descending | + Select-Object -First 1 + if ($candidate) { + # GetRelativePath is .NET 5+ only; strip prefix manually for PS 5.1 compat. + # Use case-insensitive comparison on Windows only (matches common.ps1 pattern). + $fullPath = $candidate.FullName.Replace('\', '/') + $normRoot = $ProjectRoot.Replace('\', '/').TrimEnd('/') + '/' + $cmp = if ([System.Environment]::OSVersion.Platform -eq [System.PlatformID]::Win32NT) { [System.StringComparison]::OrdinalIgnoreCase } else { [System.StringComparison]::Ordinal } + if ($fullPath.StartsWith($normRoot, $cmp)) { + $PlanPath = $fullPath.Substring($normRoot.Length) + } else { + $PlanPath = $fullPath + } + } + } catch { + # Non-fatal: continue without a plan path. + } + } } $lines = @($MarkerStart, @@ -199,39 +460,50 @@ if ($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) +foreach ($ContextFile in $ContextFiles) { + $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 + } + + 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 { - if ($content -and -not $content.EndsWith("`n")) { $content += "`n" } - if ($content) { $newContent = $content + "`n" + $Section } else { $newContent = $Section } + $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))) + $newContent = $newContent.Replace("`r`n", "`n").Replace("`r", "`n") + if ($ContextFile -match '\.mdc$') { + $newContent = Add-MdcFrontmatter -Content $newContent + } + [System.IO.File]::WriteAllText($CtxPath, $newContent, (New-Object System.Text.UTF8Encoding($false))) -Write-Host "agent-context: updated $ContextFile" + Write-Host "agent-context: updated $ContextFile" +} diff --git a/.specify/extensions/agent-context/scripts/python/update_agent_context.py b/.specify/extensions/agent-context/scripts/python/update_agent_context.py new file mode 100644 index 0000000..669ec5b --- /dev/null +++ b/.specify/extensions/agent-context/scripts/python/update_agent_context.py @@ -0,0 +1,368 @@ +#!/usr/bin/env python3 +"""Refresh the managed Spec Kit section in the coding agent's context file(s). + +Python port of ``update-agent-context.sh`` / ``update-agent-context.ps1``. + +Reads ``context_files`` or ``context_file``, plus ``context_markers.{start,end}``, +from the agent-context extension config: + .specify/extensions/agent-context/agent-context-config.yml + +Usage: update_agent_context.py [plan_path] + +When ``plan_path`` is omitted, the script derives it from +``.specify/feature.json`` (written by /speckit-specify). Falls back to the most +recently modified ``plan.md`` found anywhere under ``specs/`` — scoped layouts +nest it as ``specs///plan.md`` — only when feature.json is +absent or its plan does not exist yet. +""" + +from __future__ import annotations + +import json +import os +import re +import sys +from pathlib import Path + +DEFAULT_START = "" +DEFAULT_END = "" + + +def _err(message: str) -> None: + print(message, file=sys.stderr) + + +def _get_str(obj: object, *keys: str) -> str: + node = obj + for key in keys: + if isinstance(node, dict) and key in node: + node = node[key] + else: + return "" + return node if isinstance(node, str) else "" + + +def _collect_context_files(data: dict, project_root: str) -> list[str]: + """Resolve the managed context files from config, mirroring the bash logic.""" + context_files: list[str] = [] + seen: set[str] = set() + case_insensitive = sys.platform.startswith(("win32", "cygwin", "msys")) + + def add(value: object) -> None: + if not isinstance(value, str): + return + candidate = value.strip() + if not candidate: + return + key = candidate.casefold() if case_insensitive else candidate + if key in seen: + return + context_files.append(candidate) + seen.add(key) + + raw_files = data.get("context_files") + if isinstance(raw_files, list): + for value in raw_files: + add(value) + if not context_files: + add(_get_str(data, "context_file")) + if not context_files: + # Self-seed: when the config declares no target, derive one from the + # active integration recorded in init-options.json, mapped through the + # bundled agent-context-defaults.json file. Independent of the Specify + # CLI by design. + integration_key = "" + try: + with open( + f"{project_root}/.specify/init-options.json", "r", encoding="utf-8" + ) as fh: + opts = json.load(fh) + if isinstance(opts, dict): + value = opts.get("integration") or opts.get("ai") or "" + integration_key = value if isinstance(value, str) else "" + except Exception: + integration_key = "" + if integration_key: + defaults_path = ( + f"{project_root}/.specify/extensions/agent-context/" + "agent-context-defaults.json" + ) + mapping = {} + try: + with open(defaults_path, "r", encoding="utf-8") as fh: + loaded = json.load(fh) + agents = loaded.get("agents", {}) if isinstance(loaded, dict) else {} + mapping = agents if isinstance(agents, dict) else {} + except Exception: + _err( + "agent-context: unable to read %s; cannot self-seed the context " + "file. Set context_file in the extension config." % defaults_path + ) + mapping = {} + add(mapping.get(integration_key, "") or "") + if not context_files: + _err( + "agent-context: no default context file is known for integration " + "%s. Set context_file in the extension config to choose one." + % integration_key + ) + return context_files + + +def _validate_context_file(project_root: str, context_file: str) -> str | None: + """Return an error message when the path escapes the project root.""" + if context_file.startswith("/") or re.match(r"^[A-Za-z]:", context_file): + return ( + "agent-context: context files must be project-relative paths; " + f"got '{context_file}'." + ) + if "\\" in context_file: + return ( + "agent-context: context files must not contain backslash separators; " + f"got '{context_file}'." + ) + if ".." in context_file.split("/"): + return ( + "agent-context: context files must not contain '..' path segments; " + f"got '{context_file}'." + ) + root = Path(project_root).resolve() + target = (root / context_file).resolve() + try: + target.relative_to(root) + except ValueError: + return ( + "agent-context: context file path resolves outside the project root; " + f"got '{context_file}'." + ) + return None + + +def _resolve_plan_path(project_root: str) -> str: + """Derive the plan path: feature.json first, then the mtime fallback.""" + plan_path = "" + feature_json = Path(project_root) / ".specify" / "feature.json" + if feature_json.is_file(): + feature_dir = "" + try: + with open(feature_json, "r", encoding="utf-8") as fh: + data = json.load(fh) + value = data.get("feature_directory", "") + feature_dir = value if isinstance(value, str) else "" + except Exception: + feature_dir = "" + # Normalize backslashes (written by PS on Windows) before path ops. + feature_dir = feature_dir.replace("\\", "/").rstrip("/") + if feature_dir: + # feature_directory may be relative or absolute (absolute paths + # outside the project root are preserved as-is), including + # drive-qualified paths (C:/...) written by PowerShell on Windows. + if feature_dir.startswith("/") or re.match(r"^[A-Za-z]:/", feature_dir): + candidate = Path(feature_dir) / "plan.md" + else: + candidate = Path(project_root) / feature_dir / "plan.md" + if candidate.is_file(): + # Resolve symlinks before comparing so paths like /var/… vs + # /private/var/… (macOS) are treated as equivalent. + root = Path(project_root).resolve() + resolved = candidate.resolve() + try: + plan_path = resolved.relative_to(root).as_posix() + except ValueError: + plan_path = resolved.as_posix() + + if not plan_path: + root = Path(project_root).resolve() + specs = root / "specs" + + def _resolved_rel(p: Path) -> Path | None: + # Resolve symlinks before checking containment: relative_to() is + # lexical and would otherwise accept a plan reached through a specs/ + # symlink that points outside the project, emitting an + # in-project-looking path for an out-of-project file (or picking it + # as "most recent"). + try: + return p.resolve().relative_to(root) + except (OSError, ValueError): + return None + + # Recurse (rather than the old one-level specs/*/plan.md glob) so scoped + # layouts created via SPECIFY_FEATURE_DIRECTORY, e.g. + # specs///plan.md, are still discovered when + # feature.json is absent (#3024). Mirrors the bash and PowerShell twins. + candidates = [] + for p in specs.rglob("plan.md"): + rel = _resolved_rel(p) + if rel is not None: + candidates.append((p, rel)) + candidates.sort(key=lambda pr: pr[0].stat().st_mtime, reverse=True) + if candidates: + plan_path = candidates[0][1].as_posix() + return plan_path + + +def _build_section(marker_start: str, marker_end: str, plan_path: str) -> str: + lines = [ + marker_start, + "For additional context about technologies to be used, project structure,", + "shell commands, and other important information, read the current plan", + ] + if plan_path: + lines.append(f"at {plan_path}") + lines.append(marker_end) + return "\n".join(lines) + "\n" + + +def ensure_mdc_frontmatter(content: str) -> str: + """Ensure ``.mdc`` content has YAML frontmatter with ``alwaysApply: true``. + + Cursor only auto-loads ``.mdc`` rule files that carry frontmatter with + ``alwaysApply: true``. Prepend it when missing, or repair the value while + preserving any existing frontmatter comments/formatting. + """ + leading_ws = len(content) - len(content.lstrip()) + leading = content[:leading_ws] + stripped = content[leading_ws:] + + if not stripped.startswith("---"): + return "---\nalwaysApply: true\n---\n\n" + content + + match = re.match( + r"^(---[ \t]*\r?\n)(.*?)(\r?\n---[ \t]*)(\r?\n|$)(.*)", + stripped, + re.DOTALL, + ) + if not match: + return "---\nalwaysApply: true\n---\n\n" + content + + opening, fm_text, closing, sep, rest = match.groups() + newline = "\r\n" if "\r\n" in opening else "\n" + + if re.search(r"(?m)^[ \t]*alwaysApply[ \t]*:[ \t]*true[ \t]*(?:#.*)?$", fm_text): + return content + + if re.search(r"(?m)^[ \t]*alwaysApply[ \t]*:", fm_text): + fm_text = re.sub( + r"(?m)^([ \t]*)alwaysApply[ \t]*:.*?([ \t]*(?:#.*)?)$", + r"\1alwaysApply: true\2", + fm_text, + count=1, + ) + elif fm_text.strip(): + fm_text = fm_text + newline + "alwaysApply: true" + else: + fm_text = "alwaysApply: true" + + return f"{leading}{opening}{fm_text}{closing}{sep}{rest}" + + +def _upsert_section( + ctx_path: str, marker_start: str, marker_end: str, section: str +) -> None: + """Insert or replace the managed section, then normalize and write.""" + if os.path.exists(ctx_path): + with open(ctx_path, "r", encoding="utf-8-sig") as fh: + content = fh.read() + s = content.find(marker_start) + e = content.find(marker_end, s if s != -1 else 0) + if s != -1 and e != -1 and e > s: + end_of_marker = e + len(marker_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(marker_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") + if ctx_path.casefold().endswith(".mdc"): + new_content = ensure_mdc_frontmatter(new_content) + with open(ctx_path, "wb") as fh: + fh.write(new_content.encode("utf-8")) + + +def main(argv: list[str] | None = None) -> int: + args = sys.argv[1:] if argv is None else argv + project_root = os.getcwd() + ext_config = ( + f"{project_root}/.specify/extensions/agent-context/agent-context-config.yml" + ) + + if not os.path.isfile(ext_config): + _err(f"agent-context: {ext_config} not found; nothing to do.") + return 0 + + try: + import yaml + except ImportError: + _err( + "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." + ) + _err("agent-context: skipping update (see above for details).") + return 0 + + try: + with open(ext_config, "r", encoding="utf-8") as fh: + data = yaml.safe_load(fh) + except Exception as exc: + _err( + f"agent-context: unable to parse {ext_config} ({exc}); " + "cannot update context." + ) + _err("agent-context: skipping update (see above for details).") + return 0 + if not isinstance(data, dict): + data = {} + + context_files = _collect_context_files(data, project_root) + if not context_files: + _err( + "agent-context: context_files/context_file not set in extension config; " + "nothing to do." + ) + return 0 + + for context_file in context_files: + error = _validate_context_file(project_root, context_file) + if error: + _err(error) + return 1 + + marker_start = _get_str(data, "context_markers", "start") or DEFAULT_START + marker_end = _get_str(data, "context_markers", "end") or DEFAULT_END + + plan_path = args[0] if args else "" + if not plan_path: + plan_path = _resolve_plan_path(project_root) + + section = _build_section(marker_start, marker_end, plan_path) + + for context_file in context_files: + ctx_path = os.path.join(project_root, context_file) + os.makedirs(os.path.dirname(ctx_path) or ".", exist_ok=True) + _upsert_section(ctx_path, marker_start, marker_end, section) + print(f"agent-context: updated {context_file}") + + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.specify/extensions/git/README.md b/.specify/extensions/git/README.md index 31ba75c..c0cb7b5 100644 --- a/.specify/extensions/git/README.md +++ b/.specify/extensions/git/README.md @@ -7,10 +7,10 @@ Git repository initialization, feature branch creation, numbering (sequential/ti 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 +- **Feature branch creation** with sequential (`001-feature-name`) or timestamp (`20260319-143022-feature-name`) numbering and optional templates for branch namespaces - **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) +- **Auto-commit** after core commands (configurable per-command with custom messages, or Conventional Commit messages generated by the agent) ## Commands @@ -53,9 +53,24 @@ Configuration is stored in `.specify/extensions/git/git-config.yml`: # Branch numbering strategy: "sequential" or "timestamp" branch_numbering: sequential +# Optional branch name template. Leave empty for the default "{number}-{slug}". +# Supported tokens: {author}, {app}, {number}, {slug}; {slug} must not appear +# before {number}, and the final path segment must start with {number}-. +# Example for monorepos: "{author}/{app}/{number}-{slug}" +branch_template: "" + +# Optional shorthand namespace. Leave empty to use branch_template/default behavior. +# Example: "features/{app}" expands to "features/{app}/{number}-{slug}" +branch_prefix: "" + # Custom commit message for git init init_commit_message: "[Spec Kit] Initial commit" +# Commit message style for auto-commit hooks: "fixed" (default) uses the +# messages below; "conventional" asks the agent to generate a Conventional +# Commit message (e.g. "feat: add OAuth spec") from the diff instead. +commit_style: fixed + # Auto-commit per command (all disabled by default) # Example: enable auto-commit after specify auto_commit: @@ -65,6 +80,10 @@ auto_commit: message: "[Spec Kit] Add specification" ``` +`{author}` is derived from Git config and sanitized for branch names. `{app}` is derived from the Spec Kit init directory name. Custom templates must not put `{slug}` before `{number}`, and must put `{number}-` at the start of the final path segment so generated names remain valid feature branches. For a monorepo project at `apps/web/.specify/`, a template such as `{author}/{app}/{number}-{slug}` produces branches like `jdoe/web/008-guided-tour`. + +For simple namespace-only customization, `branch_prefix` is also accepted as a shorthand and expands to `/{number}-{slug}`. + ## Installation ```bash @@ -94,7 +113,7 @@ When Git is not installed or the directory is not a Git repository: The extension bundles cross-platform scripts: -- `scripts/bash/create-new-feature.sh` — Bash implementation +- `scripts/bash/create-new-feature-branch.sh` — Bash implementation (branch creation only) - `scripts/bash/git-common.sh` — Shared Git utilities (Bash) -- `scripts/powershell/create-new-feature.ps1` — PowerShell implementation +- `scripts/powershell/create-new-feature-branch.ps1` — PowerShell implementation (branch creation only) - `scripts/powershell/git-common.ps1` — Shared Git utilities (PowerShell) diff --git a/.specify/extensions/git/commands/speckit.git.commit.md b/.specify/extensions/git/commands/speckit.git.commit.md index e606f91..3270eb2 100644 --- a/.specify/extensions/git/commands/speckit.git.commit.md +++ b/.specify/extensions/git/commands/speckit.git.commit.md @@ -14,23 +14,37 @@ This command is invoked as a hook after (or before) core commands. It: 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 +5. Determines the commit message based on `commit_style` (see below) 6. If enabled and there are uncommitted changes, runs `git add .` + `git commit` +## Commit Message Styles + +Controlled by the `commit_style` key in `.specify/extensions/git/git-config.yml`: + +- **`fixed`** (default): use the per-command `message` if configured, otherwise a generic `[Spec Kit] Auto-commit ` message. +- **`conventional`**: inspect the actual changes (`git diff` / `git status`) since the last commit and generate a single-line [Conventional Commit](https://www.conventionalcommits.org/) message (`type(scope): subject`, e.g. `feat: add OAuth specification` or `docs: update implementation plan`) that accurately summarizes the change. Write this message to a temporary file and pass the file's path to the script (see Execution below). The configured `message` values are ignored in this mode. + ## 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 ` -- **PowerShell**: `.specify/extensions/git/scripts/powershell/auto-commit.ps1 ` +- **Bash**: `.specify/extensions/git/scripts/bash/auto-commit.sh [--message-file ]` +- **PowerShell**: `.specify/extensions/git/scripts/powershell/auto-commit.ps1 [-MessageFile ]` -Replace `` with the actual hook event (e.g., `after_specify`, `before_plan`, `after_implement`). +Replace `` with the actual hook event (e.g., `after_specify`, `before_plan`, `after_implement`). Only pass a generated message when `commit_style: conventional` is configured — first check `.specify/extensions/git/git-config.yml` for the value of `commit_style`: + +- If `conventional`: inspect the diff and generate a Conventional Commit message. **Do not interpolate the generated message directly into a shell command string** — its content is derived from repository changes and may contain characters (quotes, `$(...)`, backticks) that a shell would execute or that would break command quoting. Instead, write the message to a temporary file using your file-editing tool (not a shell `echo`/`printf`), then pass that file's path via `--message-file ` (Bash) or `-MessageFile ` (PowerShell). +- If `fixed` or absent: run the script with just ``; it uses the configured/static message. ## Configuration In `.specify/extensions/git/git-config.yml`: ```yaml +# "fixed" (default) uses the messages below; "conventional" asks the agent +# to generate a Conventional Commit message from the diff instead. +commit_style: fixed + auto_commit: default: false # Global toggle — set true to enable for all commands after_specify: @@ -46,3 +60,4 @@ auto_commit: - 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 +- If `commit_style: conventional` is set and no generated message was supplied: fails with a clear error instead of silently falling back to the fixed message format diff --git a/.specify/extensions/git/commands/speckit.git.feature.md b/.specify/extensions/git/commands/speckit.git.feature.md index 5bed9e5..01f664f 100644 --- a/.specify/extensions/git/commands/speckit.git.feature.md +++ b/.specify/extensions/git/commands/speckit.git.feature.md @@ -19,7 +19,7 @@ You **MUST** consider the user input before proceeding (if not empty). 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 +- `FEATURE_NUM` is extracted when the final path segment starts with a numeric or timestamp feature marker (for example `042-name`, `feat/042-name`, or `jdoe/app/042-name`), otherwise set to the full branch name ## Prerequisites @@ -31,8 +31,22 @@ If the user explicitly provided `GIT_BRANCH_NAME` (e.g., via environment variabl 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 +2. Check `.specify/init-options.json` for `feature_numbering` value (inherit from core) +3. Check `.specify/init-options.json` for `branch_numbering` value (deprecated, backward compatibility — will be removed in a future release) +4. Default to `sequential` if none of the above exist + +## Branch Name Template + +Check `.specify/extensions/git/git-config.yml` for an optional `branch_template` value. If it is empty or missing, use the default branch shape `{number}-{slug}`. If it is set, `{slug}` must not appear before `{number}`, its final path segment must start with `{number}-`, and the script expands these tokens: + +- `{author}`: sanitized Git config author (`user.name`, falling back to the email local part) +- `{app}`: sanitized Spec Kit init directory name +- `{number}`: sequential number or timestamp +- `{slug}`: generated short branch slug + +For monorepos, a template such as `{author}/{app}/{number}-{slug}` creates names like `jdoe/web/008-guided-tour` while preserving per-project feature numbering. + +The script also accepts `branch_prefix` as a shorthand for simple namespaces; it expands to `/{number}-{slug}`. ## Execution @@ -43,16 +57,17 @@ Generate a concise short name (2-4 words) for the branch: Run the appropriate script based on your platform: -- **Bash**: `.specify/extensions/git/scripts/bash/create-new-feature.sh --json --short-name "" ""` -- **Bash (timestamp)**: `.specify/extensions/git/scripts/bash/create-new-feature.sh --json --timestamp --short-name "" ""` -- **PowerShell**: `.specify/extensions/git/scripts/powershell/create-new-feature.ps1 -Json -ShortName "" ""` -- **PowerShell (timestamp)**: `.specify/extensions/git/scripts/powershell/create-new-feature.ps1 -Json -Timestamp -ShortName "" ""` +- **Bash**: `.specify/extensions/git/scripts/bash/create-new-feature-branch.sh --json --short-name "" ""` +- **Bash (timestamp)**: `.specify/extensions/git/scripts/bash/create-new-feature-branch.sh --json --timestamp --short-name "" ""` +- **PowerShell**: `.specify/extensions/git/scripts/powershell/create-new-feature-branch.ps1 -Json -ShortName "" ""` +- **PowerShell (timestamp)**: `.specify/extensions/git/scripts/powershell/create-new-feature-branch.ps1 -Json -Timestamp -ShortName "" ""` **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` +- Do not manually expand `branch_template`; the script reads the git extension config and applies it consistently ## Graceful Degradation @@ -63,5 +78,5 @@ If Git is not installed or the current directory is not a Git repository: ## Output The script outputs JSON with: -- `BRANCH_NAME`: The branch name (e.g., `003-user-auth` or `20260319-143022-user-auth`) +- `BRANCH_NAME`: The branch name (e.g., `003-user-auth`, `20260319-143022-user-auth`, or `jdoe/web/003-user-auth`) - `FEATURE_NUM`: The numeric or timestamp prefix used diff --git a/.specify/extensions/git/commands/speckit.git.validate.md b/.specify/extensions/git/commands/speckit.git.validate.md index dd84618..c7feeb2 100644 --- a/.specify/extensions/git/commands/speckit.git.validate.md +++ b/.specify/extensions/git/commands/speckit.git.validate.md @@ -22,24 +22,24 @@ Get the current branch name: git rev-parse --abbrev-ref HEAD ``` -The branch name must match one of these patterns: +The branch name's final path segment must start with one of these feature markers: -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`) +1. **Sequential**: `[0-9]{3,}-` (e.g., `001-feature-name`, `042-fix-bug`, `1000-big-feature`, `jdoe/web/008-guided-tour`) +2. **Timestamp**: `[0-9]{8}-[0-9]{6}-` (e.g., `20260319-143022-feature-name`, `jdoe/web/20260319-143022-feature-name`) ## Execution If on a feature branch (matches either pattern): - Output: `✓ On feature branch: ` - Check if the corresponding spec directory exists under `specs/`: - - For sequential branches, look for `specs/-*` where prefix matches the numeric portion - - For timestamp branches, look for `specs/-*` where prefix matches the `YYYYMMDD-HHMMSS` portion + - For sequential branches, look for `specs/-*` where prefix matches the numeric portion, regardless of branch namespace prefixes + - For timestamp branches, look for `specs/-*` where prefix matches the `YYYYMMDD-HHMMSS` portion, regardless of branch namespace prefixes - If spec directory exists: `✓ Spec directory found: ` - If spec directory missing: `⚠ No spec directory found for prefix ` If NOT on a feature branch: - Output: `✗ Not on a feature branch. Current branch: ` -- Output: `Feature branches should be named like: 001-feature-name or 20260319-143022-feature-name` +- Output: `Feature branches should be named like: 001-feature-name, 20260319-143022-feature-name, or /001-feature-name` ## Graceful Degradation diff --git a/.specify/extensions/git/config-template.yml b/.specify/extensions/git/config-template.yml index 8c414ba..2ea3471 100644 --- a/.specify/extensions/git/config-template.yml +++ b/.specify/extensions/git/config-template.yml @@ -4,9 +4,26 @@ # Branch numbering strategy: "sequential" (001, 002, ...) or "timestamp" (YYYYMMDD-HHMMSS) branch_numbering: sequential +# Optional branch name template. Leave empty for the default "{number}-{slug}". +# Supported tokens: {author}, {app}, {number}, {slug} +# {slug} must not appear before {number}; final path segment must start with {number}-. +# Example for monorepos: "{author}/{app}/{number}-{slug}" +branch_template: "" + +# Optional shorthand namespace. Leave empty to use branch_template/default behavior. +# Example: "features/{app}" expands to "features/{app}/{number}-{slug}" +branch_prefix: "" + # Commit message used by `git commit` during repository initialization init_commit_message: "[Spec Kit] Initial commit" +# Commit message style used by auto-commit hooks (speckit.git.commit): +# "fixed" - default; use the configured/static messages below. +# "conventional" - ask the agent to inspect the diff and generate a +# Conventional Commit message (e.g. "feat: add OAuth spec") +# instead of using the messages configured below. +commit_style: fixed + # 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. diff --git a/.specify/extensions/git/extension.yml b/.specify/extensions/git/extension.yml index 13c1977..90a7e56 100644 --- a/.specify/extensions/git/extension.yml +++ b/.specify/extensions/git/extension.yml @@ -3,8 +3,8 @@ 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" + version: "1.0.1" + description: "Feature branch creation, numbering (sequential/timestamp), templating, validation, and Git remote detection" author: spec-kit-core repository: https://github.com/github/spec-kit license: MIT @@ -19,7 +19,7 @@ provides: commands: - name: speckit.git.feature file: commands/speckit.git.feature.md - description: "Create a feature branch with sequential or timestamp numbering" + description: "Create a feature branch with sequential or timestamp numbering and optional templates" - name: speckit.git.validate file: commands/speckit.git.validate.md description: "Validate current branch follows feature branch naming conventions" @@ -137,4 +137,6 @@ tags: config: defaults: branch_numbering: sequential + branch_template: "" + branch_prefix: "" init_commit_message: "[Spec Kit] Initial commit" diff --git a/.specify/extensions/git/scripts/bash/auto-commit.sh b/.specify/extensions/git/scripts/bash/auto-commit.sh index f0b4231..17fec66 100755 --- a/.specify/extensions/git/scripts/bash/auto-commit.sh +++ b/.specify/extensions/git/scripts/bash/auto-commit.sh @@ -3,16 +3,57 @@ # Automatically commit changes after a Spec Kit command completes. # Checks per-command config keys in git-config.yml before committing. # -# Usage: auto-commit.sh +# Usage: auto-commit.sh [generated_message] +# auto-commit.sh --message-file # e.g.: auto-commit.sh after_specify +# e.g.: auto-commit.sh after_specify --message-file /tmp/commit-msg.txt (commit_style: conventional) +# +# --message-file is the preferred way to supply an agent-generated commit +# message: it reads the message from a file instead of a shell argument, +# so message content (which may contain quotes, `$(...)`, backticks, etc.) +# is never interpolated into a shell command line. set -e EVENT_NAME="${1:-}" if [ -z "$EVENT_NAME" ]; then - echo "Usage: $0 " >&2 + echo "Usage: $0 [generated_message | --message-file ]" >&2 exit 1 fi +shift || true + +# Optional second argument: an agent-generated commit message (used when +# commit_style: conventional is configured). Prefer --message-file over +# passing the message directly as a shell argument. +GENERATED_MESSAGE="" +while [ $# -gt 0 ]; do + case "$1" in + --message-file) + _message_file="${2:-}" + if [ -z "$_message_file" ]; then + echo "[specify] Error: --message-file requires a path argument" >&2 + exit 1 + fi + if [ ! -f "$_message_file" ]; then + echo "[specify] Error: message file '$_message_file' not found" >&2 + exit 1 + fi + GENERATED_MESSAGE="$(cat "$_message_file")" + # The message file is a transport-only artifact: its content is + # now captured above, so remove it immediately. Otherwise, if it + # was written inside the worktree, it would be picked up as an + # untracked change by both the "any changes?" check below and by + # `git add .`, polluting the commit or defeating the no-changes + # short-circuit even when nothing else changed. + rm -f "$_message_file" + shift 2 + ;; + *) + GENERATED_MESSAGE="$1" + shift + ;; + esac +done SCRIPT_DIR="$(CDPATH="" cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" @@ -46,8 +87,22 @@ fi _config_file="$REPO_ROOT/.specify/extensions/git/git-config.yml" _enabled=false _commit_msg="" +_commit_style="fixed" if [ -f "$_config_file" ]; then + # Top-level scalar key: commit_style (fixed | conventional) + _style_val=$(grep -m1 '^commit_style:' "$_config_file" 2>/dev/null | sed 's/^commit_style:[[:space:]]*//' | sed 's/[[:space:]]\{1,\}#.*$//' | sed 's/[[:space:]]*$//' | sed 's/^["'\'']//' | sed 's/["'\'']*$//' | tr '[:upper:]' '[:lower:]') + if [ -n "$_style_val" ]; then + case "$_style_val" in + fixed|conventional) + _commit_style="$_style_val" + ;; + *) + echo "[specify] Warning: unknown commit_style '$_style_val' in git-config.yml (expected 'fixed' or 'conventional'); defaulting to 'fixed'" >&2 + ;; + esac + fi + # Parse the auto_commit section for this event. # Look for auto_commit..enabled and .message # Also check auto_commit.default as fallback. @@ -94,7 +149,12 @@ if [ -f "$_config_file" ]; then [ "$_val" = "false" ] && _enabled=false fi if echo "$_line" | grep -Eq '[[:space:]]+message:'; then - _commit_msg=$(echo "$_line" | sed 's/^[^:]*:[[:space:]]*//' | sed 's/^["'\'']//' | sed 's/["'\'']*$//') + # Trim trailing whitespace before stripping the closing quote: + # a value like `message: "Done" ` (trailing spaces after the + # quote) would otherwise leave the quote dangling (`Done" `), + # since the closing-quote strip is anchored to end-of-string. + # The PowerShell twin .Trim()s first; match it for parity. + _commit_msg=$(echo "$_line" | sed 's/^[^:]*:[[:space:]]*//' | sed 's/[[:space:]]*$//' | sed 's/^["'\'']//' | sed 's/["'\'']*$//') fi fi fi @@ -123,6 +183,17 @@ if git diff --quiet HEAD 2>/dev/null && git diff --cached --quiet 2>/dev/null && exit 0 fi +# In conventional mode, the commit message must be supplied by the agent +# (via the generated_message argument); never fall back to the fixed message. +if [ "$_commit_style" = "conventional" ]; then + if [ -n "$GENERATED_MESSAGE" ]; then + _commit_msg="$GENERATED_MESSAGE" + else + echo "[specify] Error: commit_style is 'conventional' but no generated commit message was supplied; aborting auto-commit (pass --message-file , or a raw message as arg 2, or set commit_style: fixed)" >&2 + exit 1 + fi +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_//') diff --git a/.specify/extensions/git/scripts/bash/create-new-feature.sh b/.specify/extensions/git/scripts/bash/create-new-feature-branch.sh similarity index 62% rename from .specify/extensions/git/scripts/bash/create-new-feature.sh rename to .specify/extensions/git/scripts/bash/create-new-feature-branch.sh index f7aa316..5303bb9 100755 --- a/.specify/extensions/git/scripts/bash/create-new-feature.sh +++ b/.specify/extensions/git/scripts/bash/create-new-feature-branch.sh @@ -1,6 +1,7 @@ #!/usr/bin/env bash -# Git extension: create-new-feature.sh -# Adapted from core scripts/bash/create-new-feature.sh for extension layout. +# Git extension: create-new-feature-branch.sh +# Creates a git feature branch only. The feature directory and spec file +# are created by the core create-new-feature.sh script. # Sources common.sh from the project's installed scripts, falling back to # git-common.sh for minimal git helpers. @@ -74,6 +75,10 @@ while [ $i -le $# ]; do echo "Environment variables:" echo " GIT_BRANCH_NAME Use this exact branch name, bypassing all prefix/suffix generation" echo "" + echo "Configuration:" + echo " branch_template Optional git-config.yml template with {author}, {app}, {number}, {slug}" + echo " branch_prefix Optional shorthand namespace expanded before {number}-{slug}" + echo "" echo "Examples:" echo " $0 'Add user authentication system' --short-name 'user-auth'" echo " $0 'Implement OAuth2 integration for API' --number 5" @@ -126,16 +131,28 @@ get_highest_from_specs() { # 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 + local scope_prefix="${1:-}" + git branch -a 2>/dev/null | sed -E 's/^[+*][[:space:]]+//; s/^[[:space:]]+//; s|^remotes/[^/]*/||' | _extract_highest_number "$scope_prefix" } # Extract the highest sequential feature number from a list of ref names (one per line). _extract_highest_number() { + local scope_prefix="${1:-}" 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") + if [ -n "$scope_prefix" ]; then + case "$name" in + "$scope_prefix"*) name="${name#"$scope_prefix"}" ;; + *) continue ;; + esac + fi + name="${name##*/}" + if echo "$name" | grep -Eq '^[0-9]{3,}-' \ + && ! echo "$name" | grep -Eq '^[0-9]{8}-[0-9]{6}-' \ + && ! echo "$name" | grep -Eq '^[0-9]{7}-[0-9]{6}-' \ + && ! echo "$name" | grep -Eq '^[0-9]{7,8}-[0-9]{6}$'; then + number=$(echo "$name" | grep -Eo '^[0-9]{3,}-' | sed -E 's/-$//' || echo "0") number=$((10#$number)) if [ "$number" -gt "$highest" ]; then highest=$number @@ -147,11 +164,12 @@ _extract_highest_number() { # Function to get highest number from remote branches without fetching (side-effect-free) get_highest_from_remote_refs() { + local scope_prefix="${1:-}" 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) + remote_highest=$(GIT_TERMINAL_PROMPT=0 git ls-remote --heads "$remote" 2>/dev/null | sed 's|.*refs/heads/||' | _extract_highest_number "$scope_prefix") if [ "$remote_highest" -gt "$highest" ]; then highest=$remote_highest fi @@ -164,16 +182,17 @@ get_highest_from_remote_refs() { check_existing_branches() { local specs_dir="$1" local skip_fetch="${2:-false}" + local scope_prefix="${3:-}" if [ "$skip_fetch" = true ]; then - local highest_remote=$(get_highest_from_remote_refs) - local highest_branch=$(get_highest_from_branches) + local highest_remote=$(get_highest_from_remote_refs "$scope_prefix") + local highest_branch=$(get_highest_from_branches "$scope_prefix") 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) + local highest_branch=$(get_highest_from_branches "$scope_prefix") fi local highest_spec=$(get_highest_from_specs "$specs_dir") @@ -187,9 +206,18 @@ check_existing_branches() { } # Function to clean and format a branch name +# +# Three details keep this byte-identical to the Python and PowerShell twins: +# * LC_ALL=C -- in a UTF-8 locale glibc resolves the a-z *range* through +# collation, so [^a-z0-9] keeps accented lowercase letters that +# re.sub(r"[^a-z0-9]", ...) and .NET's -replace both strip. +# * `--*` instead of the GNU-only `\+`, which POSIX/BSD sed reads as a literal +# '+', leaving repeated separators uncollapsed on macOS. +# * printf instead of echo, so a name of "-n"/"-e"/"-E" is text, not options. clean_branch_name() { local name="$1" - echo "$name" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]/-/g' | sed 's/-\+/-/g' | sed 's/^-//' | sed 's/-$//' + local -x LC_ALL=C + printf '%s\n' "$name" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]/-/g' | sed 's/--*/-/g' | sed 's/^-//' | sed 's/-$//' } # --------------------------------------------------------------------------- @@ -234,9 +262,19 @@ if [ "$_common_loaded" != "true" ]; then exit 1 fi -# Resolve repository root +# SPECIFY_INIT_DIR is resolved (and validated) by the core resolver. If only the +# minimal git-common.sh was loaded, or an older core common.sh without the +# resolver was loaded, refuse rather than silently falling back to the wrong root. +if [ -n "${SPECIFY_INIT_DIR:-}" ] && ! type resolve_specify_init_dir >/dev/null 2>&1; then + echo "Error: SPECIFY_INIT_DIR requires updated Spec Kit core scripts (common.sh with resolve_specify_init_dir), which were not found." >&2 + exit 1 +fi + +# Resolve repository root. When the core scripts are present, get_repo_root +# honors SPECIFY_INIT_DIR (the explicit project override for non-interactive / +# CI use) and hard-fails on an invalid value with no silent fallback. if type get_repo_root >/dev/null 2>&1; then - REPO_ROOT=$(get_repo_root) + REPO_ROOT=$(get_repo_root) || exit 1 elif git rev-parse --show-toplevel >/dev/null 2>&1; then REPO_ROOT=$(git rev-parse --show-toplevel) elif [ -n "$_PROJECT_ROOT" ]; then @@ -262,6 +300,152 @@ fi cd "$REPO_ROOT" SPECS_DIR="$REPO_ROOT/specs" +CONFIG_FILE="$REPO_ROOT/.specify/extensions/git/git-config.yml" + +read_git_config_value() { + local key="$1" + [ -f "$CONFIG_FILE" ] || return 0 + grep -E "^[[:space:]]*${key}:" "$CONFIG_FILE" 2>/dev/null \ + | head -n 1 \ + | sed -E "s/^[[:space:]]*${key}:[[:space:]]*//" \ + | sed -E 's/[[:space:]]+#.*$//' \ + | sed -E 's/^[[:space:]]+|[[:space:]]+$//g' \ + | sed -E 's/^"//; s/"$//' \ + | sed -E "s/^'//; s/'$//" +} + +branch_token() { + local value="$1" + local fallback="$2" + local cleaned + cleaned=$(clean_branch_name "$value") + if [ -n "$cleaned" ]; then + printf '%s\n' "$cleaned" + else + printf '%s\n' "$fallback" + fi +} + +get_author_token() { + local author="" + if command -v git >/dev/null 2>&1; then + author=$(git config user.name 2>/dev/null || true) + if [ -z "$author" ]; then + author=$(git config user.email 2>/dev/null | sed 's/@.*$//' || true) + fi + fi + if [ -z "$author" ]; then + author="${USER:-unknown}" + fi + branch_token "$author" "unknown" +} + +get_app_token() { + branch_token "$(basename "$REPO_ROOT")" "app" +} + +resolve_branch_template() { + local template + local prefix + template=$(read_git_config_value "branch_template") + if [ -n "$template" ]; then + printf '%s\n' "$template" + return + fi + + prefix=$(read_git_config_value "branch_prefix") + if [ -z "$prefix" ]; then + printf '%s\n' "" + return + fi + case "$prefix" in + */) printf '%s%s\n' "$prefix" "{number}-{slug}" ;; + *) printf '%s/%s\n' "$prefix" "{number}-{slug}" ;; + esac +} + +render_branch_template() { + local template="$1" + local feature_num="$2" + local branch_suffix="$3" + local rendered="$template" + rendered=${rendered//\{author\}/$AUTHOR_TOKEN} + rendered=${rendered//\{app\}/$APP_TOKEN} + rendered=${rendered//\{number\}/$feature_num} + rendered=${rendered//\{slug\}/$branch_suffix} + printf '%s\n' "$rendered" +} + +validate_branch_template() { + local template="$1" + [ -n "$template" ] || return 0 + local feature_segment + feature_segment="${template##*/}" + case "$template" in + *"{number}"*) ;; + *) + >&2 echo "Error: branch_template must include the {number} token so generated branches remain valid feature branches." + exit 1 + ;; + esac + case "$template" in + *"{slug}"*"{number}"*) + >&2 echo "Error: branch_template must not place {slug} before {number}; use {slug} only in the final feature segment." + exit 1 + ;; + esac + case "$feature_segment" in + "{number}-"*) ;; + *) + >&2 echo "Error: branch_template must put {number}- at the start of the final path segment so generated branches remain valid feature branches." + exit 1 + ;; + esac +} + +build_branch_name() { + local feature_num="$1" + local branch_suffix="$2" + if [ -n "$BRANCH_TEMPLATE" ]; then + render_branch_template "$BRANCH_TEMPLATE" "$feature_num" "$branch_suffix" + else + printf '%s-%s\n' "$feature_num" "$branch_suffix" + fi +} + +branch_scope_prefix() { + local template="$1" + local prefix="$template" + [ -n "$prefix" ] || return 0 + case "$prefix" in + *"{number}"*) prefix="${prefix%%\{number\}*}" ;; + *"{slug}"*) prefix="${prefix%%\{slug\}*}" ;; + *) return 0 ;; + esac + render_branch_template "$prefix" "" "$BRANCH_SUFFIX" +} + +extract_feature_num_from_branch() { + local branch_name="$1" + local feature_segment="${branch_name##*/}" + local match + match=$(printf '%s\n' "$feature_segment" | grep -Eo '^[0-9]{8}-[0-9]{6}-' | head -n 1 || true) + if [ -n "$match" ]; then + printf '%s\n' "$match" | sed -E 's/-$//' + return + fi + match=$(printf '%s\n' "$feature_segment" | grep -Eo '^[0-9]+-' | head -n 1 || true) + if [ -n "$match" ]; then + printf '%s\n' "$match" | sed -E 's/-$//' + return + fi + printf '%s\n' "$branch_name" +} + +AUTHOR_TOKEN=$(get_author_token) +APP_TOKEN=$(get_app_token) +BRANCH_TEMPLATE=$(resolve_branch_template) +validate_branch_template "$BRANCH_TEMPLATE" # Function to generate branch name with stop word filtering generate_branch_name() { @@ -269,7 +453,11 @@ generate_branch_name() { 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') + # LC_ALL=C for the same collation reason documented on clean_branch_name, + # and so the `grep -qw` acronym probe below uses ASCII word boundaries like + # the Python twin's (?&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}" + TRUNCATED_SUFFIX="$BRANCH_SUFFIX" + while [ "$(_byte_length "$BRANCH_NAME")" -gt "$MAX_BRANCH_LENGTH" ] && [ -n "$TRUNCATED_SUFFIX" ]; do + TRUNCATED_SUFFIX="${TRUNCATED_SUFFIX%?}" + TRUNCATED_SUFFIX="${TRUNCATED_SUFFIX%-}" + BRANCH_NAME=$(build_branch_name "$FEATURE_NUM" "$TRUNCATED_SUFFIX") + done + if [ "$(_byte_length "$BRANCH_NAME")" -gt "$MAX_BRANCH_LENGTH" ]; then + >&2 echo "Error: Branch template prefix exceeds GitHub's 244-byte branch name limit." + exit 1 + fi >&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)" + ORIGINAL_BRANCH_BYTE_LEN=$(_byte_length "$ORIGINAL_BRANCH_NAME") + TRUNCATED_BRANCH_BYTE_LEN=$(_byte_length "$BRANCH_NAME") + >&2 echo "[specify] Original: $ORIGINAL_BRANCH_NAME (${ORIGINAL_BRANCH_BYTE_LEN} bytes)" + >&2 echo "[specify] Truncated to: $BRANCH_NAME (${TRUNCATED_BRANCH_BYTE_LEN} bytes)" fi if [ "$DRY_RUN" != true ]; then diff --git a/.specify/extensions/git/scripts/bash/git-common.sh b/.specify/extensions/git/scripts/bash/git-common.sh index b78356d..60bb79c 100755 --- a/.specify/extensions/git/scripts/bash/git-common.sh +++ b/.specify/extensions/git/scripts/bash/git-common.sh @@ -23,8 +23,9 @@ spec_kit_effective_branch_name() { } # 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. +# Accepts sequential (###-* with >=3 digits) or timestamp (YYYYMMDD-HHMMSS-*) formats, +# either at the start of the branch or after path-style namespace prefixes. +# Logic aligned with the git extension's PowerShell Test-FeatureBranch twin. check_feature_branch() { local raw="$1" local has_git_repo="$2" @@ -37,16 +38,17 @@ check_feature_branch() { local branch branch=$(spec_kit_effective_branch_name "$raw") + local feature_segment="${branch##*/}" # 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 + if [[ "$feature_segment" =~ ^[0-9]{3,}- ]] && [[ ! "$feature_segment" =~ ^[0-9]{7}-[0-9]{6}- ]] && [[ ! "$feature_segment" =~ ^[0-9]{7,8}-[0-9]{6}$ ]]; then is_sequential=true fi - if [[ "$is_sequential" != "true" ]] && [[ ! "$branch" =~ ^[0-9]{8}-[0-9]{6}- ]]; then + if [[ "$is_sequential" != "true" ]] && [[ ! "$feature_segment" =~ ^[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 + echo "Feature branches should be named like: 001-feature-name, 1234-feature-name, 20260319-143022-feature-name, or /001-feature-name" >&2 return 1 fi diff --git a/.specify/extensions/git/scripts/bash/initialize-repo.sh b/.specify/extensions/git/scripts/bash/initialize-repo.sh index 296e363..c10876e 100755 --- a/.specify/extensions/git/scripts/bash/initialize-repo.sh +++ b/.specify/extensions/git/scripts/bash/initialize-repo.sh @@ -51,4 +51,4 @@ _git_out=$(git init -q 2>&1) || { echo "[specify] Error: git init failed: $_git_ _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 +echo "[OK] Git repository initialized" >&2 diff --git a/.specify/extensions/git/scripts/powershell/auto-commit.ps1 b/.specify/extensions/git/scripts/powershell/auto-commit.ps1 index 34767f8..d27b484 100644 --- a/.specify/extensions/git/scripts/powershell/auto-commit.ps1 +++ b/.specify/extensions/git/scripts/powershell/auto-commit.ps1 @@ -3,14 +3,47 @@ # Automatically commit changes after a Spec Kit command completes. # Checks per-command config keys in git-config.yml before committing. # -# Usage: auto-commit.ps1 +# Usage: auto-commit.ps1 [generated_message] +# auto-commit.ps1 -MessageFile # e.g.: auto-commit.ps1 after_specify +# e.g.: auto-commit.ps1 after_specify -MessageFile C:\temp\commit-msg.txt (commit_style: conventional) +# +# -MessageFile is the preferred way to supply an agent-generated commit +# message: it reads the message from a file instead of a shell argument, +# so message content (which may contain quotes, $(...), backticks, etc.) +# is never interpolated into a shell command line. param( [Parameter(Position = 0, Mandatory = $true)] - [string]$EventName + [string]$EventName, + + # Optional agent-generated commit message (used when commit_style: conventional is configured). + # Prefer -MessageFile over passing the message directly as a shell argument. + [Parameter(Position = 1, Mandatory = $false)] + [string]$GeneratedMessage = "", + + [Parameter(Mandatory = $false)] + [string]$MessageFile = "" ) $ErrorActionPreference = 'Stop' +if ($MessageFile) { + if (-not (Test-Path $MessageFile -PathType Leaf)) { + Write-Warning "[specify] Error: message file '$MessageFile' not found" + exit 1 + } + $GeneratedMessage = (Get-Content -Path $MessageFile -Raw) + if ($null -ne $GeneratedMessage) { + $GeneratedMessage = $GeneratedMessage.TrimEnd("`r", "`n") + } + # The message file is a transport-only artifact: its content is now + # captured above, so remove it immediately. Otherwise, if it was written + # inside the worktree, it would be picked up as an untracked change by + # both the "any changes?" check below and by `git add .`, polluting the + # commit or defeating the no-changes short-circuit even when nothing + # else changed. + Remove-Item -Path $MessageFile -Force -ErrorAction SilentlyContinue +} + function Find-ProjectRoot { param([string]$StartDir) $current = Resolve-Path $StartDir @@ -55,8 +88,25 @@ if (-not $isRepo) { $configFile = Join-Path $repoRoot ".specify/extensions/git/git-config.yml" $enabled = $false $commitMsg = "" +$commitStyle = "fixed" if (Test-Path $configFile) { + # Top-level scalar key: commit_style (fixed | conventional) + foreach ($line in Get-Content $configFile) { + if ($line -match '^commit_style:\s*(.+)$') { + $styleVal = (($matches[1] -replace '\s+#.*$', '').Trim()) -replace '^["'']' -replace '["'']$' + if ($styleVal) { + $styleVal = $styleVal.ToLower() + if ($styleVal -eq 'fixed' -or $styleVal -eq 'conventional') { + $commitStyle = $styleVal + } else { + Write-Warning "[specify] Warning: unknown commit_style '$styleVal' in git-config.yml (expected 'fixed' or 'conventional'); defaulting to 'fixed'" + } + } + break + } + } + # Parse YAML to find auto_commit section $inAutoCommit = $false $inEvent = $false @@ -140,6 +190,17 @@ if ($d1 -eq 0 -and $d2 -eq 0 -and -not $untracked) { exit 0 } +# In conventional mode, the commit message must be supplied by the agent +# (via the GeneratedMessage argument); never fall back to the fixed message. +if ($commitStyle -eq 'conventional') { + if ($GeneratedMessage) { + $commitMsg = $GeneratedMessage + } else { + Write-Warning "[specify] Error: commit_style is 'conventional' but no generated commit message was supplied; aborting auto-commit (pass -MessageFile , or a raw message as arg 2, or set commit_style: fixed)" + exit 1 + } +} + # Derive a human-readable command name from the event $commandName = $EventName -replace '^after_', '' -replace '^before_', '' $phase = if ($EventName -match '^before_') { 'before' } else { 'after' } diff --git a/.specify/extensions/git/scripts/powershell/create-new-feature.ps1 b/.specify/extensions/git/scripts/powershell/create-new-feature-branch.ps1 similarity index 53% rename from .specify/extensions/git/scripts/powershell/create-new-feature.ps1 rename to .specify/extensions/git/scripts/powershell/create-new-feature-branch.ps1 index b579f05..4d06a11 100644 --- a/.specify/extensions/git/scripts/powershell/create-new-feature.ps1 +++ b/.specify/extensions/git/scripts/powershell/create-new-feature-branch.ps1 @@ -1,6 +1,7 @@ #!/usr/bin/env pwsh -# Git extension: create-new-feature.ps1 -# Adapted from core scripts/powershell/create-new-feature.ps1 for extension layout. +# Git extension: create-new-feature-branch.ps1 +# Creates a git feature branch only. The feature directory and spec file +# are created by the core create-new-feature.ps1 script. # Sources common.ps1 from the project's installed scripts, falling back to # git-common.ps1 for minimal git helpers. [CmdletBinding()] @@ -19,7 +20,7 @@ param( $ErrorActionPreference = 'Stop' if ($Help) { - Write-Host "Usage: ./create-new-feature.ps1 [-Json] [-DryRun] [-AllowExistingBranch] [-ShortName ] [-Number N] [-Timestamp] " + Write-Host "Usage: ./create-new-feature-branch.ps1 [-Json] [-DryRun] [-AllowExistingBranch] [-ShortName ] [-Number N] [-Timestamp] " Write-Host "" Write-Host "Options:" Write-Host " -Json Output in JSON format" @@ -33,11 +34,25 @@ if ($Help) { Write-Host "Environment variables:" Write-Host " GIT_BRANCH_NAME Use this exact branch name, bypassing all prefix/suffix generation" Write-Host "" + Write-Host "Configuration:" + Write-Host " branch_template Optional git-config.yml template with {author}, {app}, {number}, {slug}" + Write-Host " branch_prefix Optional shorthand namespace expanded before {number}-{slug}" + Write-Host "" exit 0 } +# -Number is [long], so PowerShell binds "-5" as -5 rather than rejecting it +# the way the bash/Python twins do (`^[0-9]+$`). A negative value would format +# via '{0:000}' to e.g. "-005" and produce a branch name starting with "-", +# which git refuses (refs cannot begin with a dash). Reject it here, before the +# description check, matching the bash twin's parse-time validation order. +if ($Number -lt 0) { + Write-Error 'Error: --number must be a non-negative integer' + exit 1 +} + if (-not $FeatureDescription -or $FeatureDescription.Count -eq 0) { - Write-Error "Usage: ./create-new-feature.ps1 [-Json] [-DryRun] [-AllowExistingBranch] [-ShortName ] [-Number N] [-Timestamp] " + Write-Error "Usage: ./create-new-feature-branch.ps1 [-Json] [-DryRun] [-AllowExistingBranch] [-ShortName ] [-Number N] [-Timestamp] " exit 1 } @@ -66,11 +81,23 @@ function Get-HighestNumberFromSpecs { } function Get-HighestNumberFromNames { - param([string[]]$Names) + param( + [string[]]$Names, + [string]$ScopePrefix = '' + ) [long]$highest = 0 foreach ($name in $Names) { - if ($name -match '^(\d{3,})-' -and $name -notmatch '^\d{8}-\d{6}-') { + if ($ScopePrefix -and -not $name.StartsWith($ScopePrefix, [System.StringComparison]::Ordinal)) { + continue + } + if ($ScopePrefix) { + $name = $name.Substring($ScopePrefix.Length) + } + $name = ($name -split '/')[-1] + $hasTimestampPrefix = $name -match '^\d{8}-\d{6}-' + $hasMalformedTimestamp = ($name -match '^\d{7}-\d{6}-') -or ($name -match '^(?:\d{7}|\d{8})-\d{6}$') + if ($name -match '^(\d{3,})-' -and -not $hasTimestampPrefix -and -not $hasMalformedTimestamp) { [long]$num = 0 if ([long]::TryParse($matches[1], [ref]$num) -and $num -gt $highest) { $highest = $num @@ -81,15 +108,15 @@ function Get-HighestNumberFromNames { } function Get-HighestNumberFromBranches { - param() + param([string]$ScopePrefix = '') try { $branches = git branch -a 2>$null if ($LASTEXITCODE -eq 0 -and $branches) { $cleanNames = $branches | ForEach-Object { - $_.Trim() -replace '^\*?\s+', '' -replace '^remotes/[^/]+/', '' + $_.Trim() -replace '^[+*]?\s+', '' -replace '^remotes/[^/]+/', '' } - return Get-HighestNumberFromNames -Names $cleanNames + return Get-HighestNumberFromNames -Names $cleanNames -ScopePrefix $ScopePrefix } } catch { Write-Verbose "Could not check Git branches: $_" @@ -98,6 +125,8 @@ function Get-HighestNumberFromBranches { } function Get-HighestNumberFromRemoteRefs { + param([string]$ScopePrefix = '') + [long]$highest = 0 try { $remotes = git remote 2>$null @@ -110,7 +139,7 @@ function Get-HighestNumberFromRemoteRefs { $refNames = $refs | ForEach-Object { if ($_ -match 'refs/heads/(.+)$') { $matches[1] } } | Where-Object { $_ } - $remoteHighest = Get-HighestNumberFromNames -Names $refNames + $remoteHighest = Get-HighestNumberFromNames -Names $refNames -ScopePrefix $ScopePrefix if ($remoteHighest -gt $highest) { $highest = $remoteHighest } } } @@ -124,18 +153,19 @@ function Get-HighestNumberFromRemoteRefs { function Get-NextBranchNumber { param( [string]$SpecsDir, - [switch]$SkipFetch + [switch]$SkipFetch, + [string]$ScopePrefix = '' ) if ($SkipFetch) { - $highestBranch = Get-HighestNumberFromBranches - $highestRemote = Get-HighestNumberFromRemoteRefs + $highestBranch = Get-HighestNumberFromBranches -ScopePrefix $ScopePrefix + $highestRemote = Get-HighestNumberFromRemoteRefs -ScopePrefix $ScopePrefix $highestBranch = [Math]::Max($highestBranch, $highestRemote) } else { try { git fetch --all --prune 2>$null | Out-Null } catch { } - $highestBranch = Get-HighestNumberFromBranches + $highestBranch = Get-HighestNumberFromBranches -ScopePrefix $ScopePrefix } $highestSpec = Get-HighestNumberFromSpecs -SpecsDir $SpecsDir @@ -196,7 +226,16 @@ if (-not $commonLoaded) { throw "Unable to locate common script file. Please ensure the Specify core scripts are installed." } -# Resolve repository root +# SPECIFY_INIT_DIR is resolved (and validated) by the core resolver. If only the +# minimal git-common.ps1 was loaded, or an older core common.ps1 without the +# resolver was loaded, refuse rather than silently falling back to the wrong root. +if ($env:SPECIFY_INIT_DIR -and -not (Get-Command Resolve-SpecifyInitDir -CommandType Function -ErrorAction SilentlyContinue)) { + throw "SPECIFY_INIT_DIR requires updated Spec Kit core scripts (common.ps1 with Resolve-SpecifyInitDir), which were not found." +} + +# Resolve repository root. When the core scripts are present, Get-RepoRoot +# honors SPECIFY_INIT_DIR (the explicit project override for non-interactive / +# CI use) and hard-fails on an invalid value with no silent fallback. if (Get-Command Get-RepoRoot -ErrorAction SilentlyContinue) { $repoRoot = Get-RepoRoot } elseif ($projectRoot) { @@ -222,6 +261,145 @@ if (Get-Command Test-HasGit -ErrorAction SilentlyContinue) { Set-Location $repoRoot $specsDir = Join-Path $repoRoot 'specs' +$configFile = Join-Path $repoRoot ".specify/extensions/git/git-config.yml" + +function Read-GitConfigValue { + param([string]$Key) + + if (-not (Test-Path -LiteralPath $configFile -PathType Leaf)) { return '' } + $escapedKey = [regex]::Escape($Key) + foreach ($line in Get-Content -LiteralPath $configFile) { + if ($line -match "^\s*$escapedKey\s*:\s*(.*)$") { + $val = ($matches[1] -replace '\s+#.*$', '').Trim() + $val = $val -replace '^["'']', '' -replace '["'']$', '' + return $val + } + } + return '' +} + +function ConvertTo-BranchToken { + param( + [string]$Value, + [string]$Fallback + ) + + $cleaned = ConvertTo-CleanBranchName -Name $Value + if ($cleaned) { return $cleaned } + return $Fallback +} + +function Get-GitAuthorToken { + $author = '' + if (Get-Command git -ErrorAction SilentlyContinue) { + try { $author = (git config user.name 2>$null | Out-String).Trim() } catch {} + if (-not $author) { + try { + $email = (git config user.email 2>$null | Out-String).Trim() + if ($email) { $author = ($email -split '@')[0] } + } catch {} + } + } + if (-not $author) { $author = if ($env:USER) { $env:USER } elseif ($env:USERNAME) { $env:USERNAME } else { 'unknown' } } + return ConvertTo-BranchToken -Value $author -Fallback 'unknown' +} + +function Get-AppToken { + return ConvertTo-BranchToken -Value (Split-Path $repoRoot -Leaf) -Fallback 'app' +} + +function Resolve-BranchTemplate { + $template = Read-GitConfigValue -Key 'branch_template' + if ($template) { return $template } + + $prefix = Read-GitConfigValue -Key 'branch_prefix' + if (-not $prefix) { return '' } + if ($prefix.EndsWith('/')) { return "${prefix}{number}-{slug}" } + return "$prefix/{number}-{slug}" +} + +function Expand-BranchTemplate { + param( + [string]$Template, + [string]$FeatureNum, + [string]$BranchSuffix + ) + + $rendered = $Template.Replace('{author}', $authorToken) + $rendered = $rendered.Replace('{app}', $appToken) + $rendered = $rendered.Replace('{number}', $FeatureNum) + $rendered = $rendered.Replace('{slug}', $BranchSuffix) + return $rendered +} + +function Assert-BranchTemplateValid { + param([string]$Template) + + if ($Template -and -not $Template.Contains('{number}')) { + throw "branch_template must include the {number} token so generated branches remain valid feature branches." + } + if ($Template) { + $numberIndex = $Template.IndexOf('{number}', [System.StringComparison]::Ordinal) + $slugIndex = $Template.IndexOf('{slug}', [System.StringComparison]::Ordinal) + if ($slugIndex -ge 0 -and $slugIndex -lt $numberIndex) { + throw "branch_template must not place {slug} before {number}; use {slug} only in the final feature segment." + } + $featureSegment = ($Template -split '/')[-1] + if (-not $featureSegment.StartsWith('{number}-', [System.StringComparison]::Ordinal)) { + throw "branch_template must put {number}- at the start of the final path segment so generated branches remain valid feature branches." + } + } +} + +function New-BranchName { + param( + [string]$FeatureNum, + [string]$BranchSuffix + ) + + if ($branchTemplate) { + return Expand-BranchTemplate -Template $branchTemplate -FeatureNum $FeatureNum -BranchSuffix $BranchSuffix + } + return "$FeatureNum-$BranchSuffix" +} + +function Get-BranchScopePrefix { + param( + [string]$Template, + [string]$BranchSuffix + ) + + if (-not $Template) { return '' } + $numberIndex = $Template.IndexOf('{number}', [System.StringComparison]::Ordinal) + $slugIndex = $Template.IndexOf('{slug}', [System.StringComparison]::Ordinal) + $indexes = @($numberIndex, $slugIndex) | Where-Object { $_ -ge 0 } | Sort-Object + if (-not $indexes) { return '' } + $prefix = $Template.Substring(0, $indexes[0]) + return Expand-BranchTemplate -Template $prefix -FeatureNum '' -BranchSuffix $BranchSuffix +} + +function Get-FeatureNumberFromBranchName { + param([string]$BranchName) + + $featureSegment = ($BranchName -split '/')[-1] + if ($featureSegment -match '^(\d{8}-\d{6})-') { + return $matches[1] + } + if ($featureSegment -match '^(\d+)-') { + return $matches[1] + } + return $BranchName +} + +function Get-Utf8ByteCount { + param([string]$Value) + return [System.Text.Encoding]::UTF8.GetByteCount($Value) +} + +$authorToken = Get-GitAuthorToken +$appToken = Get-AppToken +$branchTemplate = Resolve-BranchTemplate +Assert-BranchTemplateValid -Template $branchTemplate function Get-BranchName { param([string]$Description) @@ -242,7 +420,13 @@ function Get-BranchName { if ($stopWords -contains $word) { continue } if ($word.Length -ge 3) { $meaningfulWords += $word - } elseif ($Description -match "\b$($word.ToUpper())\b") { + } elseif ($Description -cmatch "(?/001-feature-name") return $false } return $true diff --git a/.specify/extensions/git/scripts/python/auto_commit.py b/.specify/extensions/git/scripts/python/auto_commit.py new file mode 100644 index 0000000..c669289 --- /dev/null +++ b/.specify/extensions/git/scripts/python/auto_commit.py @@ -0,0 +1,195 @@ +#!/usr/bin/env python3 +"""Git extension: auto_commit.py + +Automatically commit changes after a Spec Kit command completes. +Python port of ``auto-commit.sh`` / ``auto-commit.ps1``. +Checks per-command config keys in git-config.yml before committing. + +Usage: auto_commit.py + e.g.: auto_commit.py after_specify +""" + +from __future__ import annotations + +import re +import shutil +import subprocess +import sys +from pathlib import Path + + +def _find_project_root(start: Path) -> Path | None: + current = start + while True: + if (current / ".specify").is_dir() or (current / ".git").exists(): + return current + if current.parent == current: + return None + current = current.parent + + +def _value_after_colon(line: str) -> str: + return re.sub(r"^[^:]*:\s*", "", line) + + +def _strip_quotes(value: str) -> str: + """Strip surrounding whitespace, then one leading quote and all trailing quotes. + + Trimming first matters when the YAML value has trailing whitespace after a + closing quote (``message: "Done" ``): stripping quotes anchored to the end + of string would leave the closing quote dangling (``Done" ``) because the + quote is no longer at the end. The PowerShell twin ``.Trim()``s before + stripping, so trim here too to keep all three script variants in parity. + """ + value = value.strip() + value = re.sub(r"^[\"']", "", value) + return re.sub(r"[\"']*$", "", value) + + +def _parse_auto_commit_config( + config_file: Path, event_name: str +) -> tuple[bool, str]: + """Parse the auto_commit section for this event, mirroring the bash line parser. + + Returns (enabled, commit_msg). Looks for auto_commit..enabled + and .message, with auto_commit.default as fallback. + """ + enabled = False + commit_msg = "" + default_enabled = False + in_auto_commit = False + in_event = False + + try: + content = config_file.read_text(encoding="utf-8") + except (OSError, UnicodeDecodeError): + # Unreadable or non-UTF-8 config is treated like a missing one: + # auto-commit stays disabled instead of crashing with a traceback. + return False, "" + for record in content.splitlines(keepends=True): + if not record.endswith("\n"): + break + line = record[:-1] + if line.startswith("auto_commit:"): + in_auto_commit = True + in_event = False + continue + + # Exit auto_commit section on next top-level key + if in_auto_commit and re.match(r"^[a-z]", line): + break + + if not in_auto_commit: + continue + + if re.match(r"^\s+default:\s", line): + value = re.sub(r"\s", "", _value_after_colon(line)).lower() + if value == "true": + default_enabled = True + + if re.match(rf"^\s+{re.escape(event_name)}:", line): + in_event = True + continue + + if in_event: + # Exit on next sibling key (same indent level as event name) + if re.match(r"^\s{2}[a-z]", line) and not re.match(r"^\s{4}", line): + in_event = False + continue + if re.search(r"\s+enabled:", line): + value = re.sub(r"\s", "", _value_after_colon(line)).lower() + if value == "true": + enabled = True + elif value == "false": + enabled = False + if re.search(r"\s+message:", line): + commit_msg = _strip_quotes(_value_after_colon(line)) + + # If event-specific key not found, use default — but only if the event + # section didn't exist at all (an explicit false must win). + if not enabled and default_enabled: + if not re.search(rf"^\s*{re.escape(event_name)}:", content, re.MULTILINE): + enabled = True + + return enabled, commit_msg + + +def main(argv: list[str]) -> int: + event_name = argv[0] if argv else "" + if not event_name: + print(f"Usage: {Path(sys.argv[0]).name} ", file=sys.stderr) + return 1 + + script_dir = Path(__file__).resolve().parent + repo_root = _find_project_root(script_dir) or Path.cwd() + + if shutil.which("git") is None: + print("[specify] Warning: Git not found; skipped auto-commit", file=sys.stderr) + return 0 + + probe = subprocess.run( + ["git", "rev-parse", "--is-inside-work-tree"], + cwd=repo_root, + capture_output=True, + text=True, + ) + if probe.returncode != 0: + print( + "[specify] Warning: Not a Git repository; skipped auto-commit", + file=sys.stderr, + ) + return 0 + + config_file = repo_root / ".specify" / "extensions" / "git" / "git-config.yml" + if not config_file.is_file(): + # No config file — auto-commit disabled by default + return 0 + + enabled, commit_msg = _parse_auto_commit_config(config_file, event_name) + if not enabled: + return 0 + + # Check if there are changes to commit + def _quiet(*args: str) -> bool: + return ( + subprocess.run( + ["git", *args], cwd=repo_root, capture_output=True, text=True + ).returncode + == 0 + ) + + untracked = subprocess.run( + ["git", "ls-files", "--others", "--exclude-standard"], + cwd=repo_root, + capture_output=True, + text=True, + ).stdout.strip() + if _quiet("diff", "--quiet", "HEAD") and _quiet("diff", "--cached", "--quiet") and not untracked: + print(f"[specify] No changes to commit after {event_name}", file=sys.stderr) + return 0 + + # Derive a human-readable command name from the event + # e.g., after_specify -> specify, before_plan -> plan + command_name = re.sub(r"^(after_|before_)", "", event_name) + phase = "before" if event_name.startswith("before_") else "after" + + if not commit_msg: + commit_msg = f"[Spec Kit] Auto-commit {phase} {command_name}" + + steps = [ + (["git", "add", "."], "git add"), + (["git", "commit", "-q", "-m", commit_msg], "git commit"), + ] + for cmd, label in steps: + result = subprocess.run(cmd, cwd=repo_root, capture_output=True, text=True) + if result.returncode != 0: + output = (result.stdout + result.stderr).strip() + print(f"[specify] Error: {label} failed: {output}", file=sys.stderr) + return 1 + + print(f"[OK] Changes committed {phase} {command_name}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv[1:])) diff --git a/.specify/extensions/git/scripts/python/create_new_feature_branch.py b/.specify/extensions/git/scripts/python/create_new_feature_branch.py new file mode 100644 index 0000000..202b1f7 --- /dev/null +++ b/.specify/extensions/git/scripts/python/create_new_feature_branch.py @@ -0,0 +1,641 @@ +#!/usr/bin/env python3 +"""Git extension: create_new_feature_branch.py + +Creates a git feature branch only. The feature directory and spec file are +created by the core create-new-feature script. Python port of +``create-new-feature-branch.sh`` / ``create-new-feature-branch.ps1``. + +Loads the core Python helpers from the project's installed scripts when +available, falling back to the minimal git helpers next to this script. +""" + +from __future__ import annotations + +import importlib.util +import json +import os +import re +import shutil +import subprocess +import sys +from dataclasses import dataclass, field +from datetime import datetime +from pathlib import Path + +SCRIPT_DIR = Path(__file__).resolve().parent +MAX_BRANCH_LENGTH = 244 # GitHub enforces a 244-byte limit on branch names + +USAGE = ( + "Usage: create_new_feature_branch.py [--json] [--dry-run] " + "[--allow-existing-branch] [--short-name ] [--number N] " + "[--timestamp] " +) + +HELP_TEXT = f"""{USAGE} + +Options: + --json Output in JSON format + --dry-run Compute branch name without creating the branch + --allow-existing-branch Switch to branch if it already exists instead of failing + --short-name Provide a custom short name (2-4 words) for the branch + --number N Specify branch number manually (overrides auto-detection) + --timestamp Use timestamp prefix (YYYYMMDD-HHMMSS) instead of sequential numbering + --help, -h Show this help message + +Environment variables: + GIT_BRANCH_NAME Use this exact branch name, bypassing all prefix/suffix generation + +Configuration: + branch_template Optional git-config.yml template with {{author}}, {{app}}, {{number}}, {{slug}} + branch_prefix Optional shorthand namespace expanded before {{number}}-{{slug}} + +Examples: + create_new_feature_branch.py 'Add user authentication system' --short-name 'user-auth' + create_new_feature_branch.py 'Implement OAuth2 integration for API' --number 5 + create_new_feature_branch.py --timestamp --short-name 'user-auth' 'Add user authentication' + GIT_BRANCH_NAME=my-branch create_new_feature_branch.py 'feature description' +""" + +STOP_WORDS = frozenset( + "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".split() +) + + +def _err(message: str) -> None: + print(message, file=sys.stderr) + + +def _persist_hint(var_name: str, value: str) -> str: + """Shell-appropriate guidance for persisting an env var in the caller's shell.""" + if os.name == "nt": + escaped_value = value.replace("'", "''") + return f"$env:{var_name} = '{escaped_value}'" + escaped_value = re.sub(r"([^\w@%+=:,./-])", r"\\\1", value) + return f"export {var_name}={escaped_value}" + + +@dataclass +class Args: + json_mode: bool = False + dry_run: bool = False + allow_existing: bool = False + short_name: str = "" + branch_number: str = "" + use_timestamp: bool = False + description_parts: list[str] = field(default_factory=list) + + +def parse_args(argv: list[str]) -> Args: + args = Args() + i = 0 + while i < len(argv): + arg = argv[i] + if arg == "--json": + args.json_mode = True + elif arg == "--dry-run": + args.dry_run = True + elif arg == "--allow-existing-branch": + args.allow_existing = True + elif arg == "--short-name": + if i + 1 >= len(argv) or argv[i + 1].startswith("--"): + _err("Error: --short-name requires a value") + raise SystemExit(1) + i += 1 + args.short_name = argv[i] + elif arg == "--number": + if i + 1 >= len(argv) or argv[i + 1].startswith("--"): + _err("Error: --number requires a value") + raise SystemExit(1) + i += 1 + args.branch_number = argv[i] + if not re.fullmatch(r"[0-9]+", args.branch_number): + _err("Error: --number must be a non-negative integer") + raise SystemExit(1) + elif arg == "--timestamp": + args.use_timestamp = True + elif arg in ("--help", "-h"): + print(HELP_TEXT) + raise SystemExit(0) + else: + args.description_parts.append(arg) + i += 1 + return args + + +# ── Core helpers loading ───────────────────────────────────────────────────── + + +def _find_project_root(start: Path) -> Path | None: + current = start + while True: + if (current / ".specify").is_dir() or (current / ".git").exists(): + return current + if current.parent == current: + return None + current = current.parent + + +def _load_core_common(project_root: Path | None): + """Load the core common.py from the project's installed scripts. + + Search locations in priority order, mirroring the bash script: + 1. .specify/scripts/python/common.py (installed project) + 2. scripts/python/common.py (source checkout fallback) + Returns the loaded module or None. + """ + if project_root is None: + return None + for relative in (".specify/scripts/python/common.py", "scripts/python/common.py"): + candidate = project_root / relative + if candidate.is_file(): + spec = importlib.util.spec_from_file_location("speckit_core_common", candidate) + if spec is None or spec.loader is None: + continue + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + return None + + +def _local_has_git(repo_root: Path) -> bool: + git_marker = repo_root / ".git" + if not (git_marker.is_dir() or git_marker.is_file()): + return False + if shutil.which("git") is None: + return False + return ( + subprocess.run( + ["git", "-C", str(repo_root), "rev-parse", "--is-inside-work-tree"], + capture_output=True, + text=True, + ).returncode + == 0 + ) + + +# ── Numbering ──────────────────────────────────────────────────────────────── + + +def get_highest_from_specs(specs_dir: Path) -> int: + highest = 0 + if specs_dir.is_dir(): + for entry in specs_dir.iterdir(): + if not entry.is_dir(): + continue + name = entry.name + # Match sequential prefixes (>=3 digits), but skip timestamp dirs. + if re.match(r"^[0-9]{3,}-", name) and not re.match( + r"^[0-9]{8}-[0-9]{6}-", name + ): + number = int(re.match(r"^[0-9]+", name).group(0)) + highest = max(highest, number) + return highest + + +def _extract_highest_number(names: list[str], scope_prefix: str) -> int: + """Extract the highest sequential feature number from a list of ref names.""" + highest = 0 + for name in names: + if not name: + continue + if scope_prefix: + if not name.startswith(scope_prefix): + continue + name = name[len(scope_prefix) :] + name = name.rsplit("/", 1)[-1] + if ( + re.match(r"^[0-9]{3,}-", name) + and not re.match(r"^[0-9]{8}-[0-9]{6}-", name) + and not re.match(r"^[0-9]{7}-[0-9]{6}-", name) + and not re.fullmatch(r"[0-9]{7,8}-[0-9]{6}", name) + ): + match = re.match(r"^([0-9]{3,})-", name) + number = int(match.group(1)) if match else 0 + highest = max(highest, number) + return highest + + +def _git_lines(repo_root: Path, *args: str, env_extra: dict | None = None) -> list[str]: + if shutil.which("git") is None: + return [] + env = {**os.environ, **(env_extra or {})} + result = subprocess.run( + ["git", *args], cwd=repo_root, capture_output=True, text=True, env=env + ) + if result.returncode != 0: + return [] + return result.stdout.splitlines() + + +def get_highest_from_branches(repo_root: Path, scope_prefix: str) -> int: + names = [] + for line in _git_lines(repo_root, "branch", "-a"): + line = re.sub(r"^[+*]\s+", "", line) + line = line.lstrip() + line = re.sub(r"^remotes/[^/]*/", "", line) + names.append(line) + return _extract_highest_number(names, scope_prefix) + + +def get_highest_from_remote_refs(repo_root: Path, scope_prefix: str) -> int: + """Highest number from remote branches without fetching (side-effect-free).""" + highest = 0 + for remote in _git_lines(repo_root, "remote"): + refs = _git_lines( + repo_root, + "ls-remote", + "--heads", + remote, + env_extra={"GIT_TERMINAL_PROMPT": "0"}, + ) + names = [re.sub(r".*refs/heads/", "", ref) for ref in refs] + highest = max(highest, _extract_highest_number(names, scope_prefix)) + return highest + + +def check_existing_branches( + repo_root: Path, specs_dir: Path, skip_fetch: bool, scope_prefix: str +) -> int: + """Check existing branches and return the next available number.""" + if skip_fetch: + highest_branch = max( + get_highest_from_remote_refs(repo_root, scope_prefix), + get_highest_from_branches(repo_root, scope_prefix), + ) + else: + subprocess.run( + ["git", "fetch", "--all", "--prune"], + cwd=repo_root, + capture_output=True, + text=True, + ) + highest_branch = get_highest_from_branches(repo_root, scope_prefix) + + return max(highest_branch, get_highest_from_specs(specs_dir)) + 1 + + +# ── Branch naming ──────────────────────────────────────────────────────────── + + +def clean_branch_name(name: str) -> str: + name = re.sub(r"[^a-z0-9]", "-", name.lower()) + name = re.sub(r"-+", "-", name) + return name.strip("-") + + +def generate_branch_name(description: str) -> str: + """Generate a branch suffix from the description with stop word filtering.""" + clean_name = re.sub(r"[^a-z0-9]", " ", description.lower()) + + meaningful_words = [] + for word in clean_name.split(): + if word in STOP_WORDS: + continue + if len(word) >= 3: + meaningful_words.append(word) + # Keep short words only when they appear uppercased in the original + # description (acronyms like "API" or "DB"). The boundaries are spelled + # out as ASCII rather than using \b: \b is Unicode-aware on str, so + # "\u00e9DB\u00e9 cache" would hide the acronym behind a non-ASCII word + # character, while the bash twin's `grep -qw` runs under LC_ALL=C and + # sees a boundary there. + elif re.search( + rf"(? str: + cleaned = clean_branch_name(value) + return cleaned if cleaned else fallback + + +def get_author_token(repo_root: Path) -> str: + author = "" + if shutil.which("git") is not None: + lines = _git_lines(repo_root, "config", "user.name") + author = lines[0] if lines else "" + if not author: + lines = _git_lines(repo_root, "config", "user.email") + email = lines[0] if lines else "" + author = email.split("@")[0] + if not author: + author = os.environ.get("USER") or os.environ.get("USERNAME") or "unknown" + return branch_token(author, "unknown") + + +def get_app_token(repo_root: Path) -> str: + return branch_token(repo_root.name, "app") + + +def read_git_config_value(config_file: Path, key: str) -> str: + if not config_file.is_file(): + return "" + try: + lines = config_file.read_text(encoding="utf-8").splitlines() + except (OSError, UnicodeDecodeError): + return "" + for line in lines: + if re.match(rf"^\s*{re.escape(key)}:", line): + value = re.sub(rf"^\s*{re.escape(key)}:\s*", "", line) + value = re.sub(r"\s+#.*$", "", value) + value = value.strip() + value = re.sub(r'^"|"$', "", value) + value = re.sub(r"^'|'$", "", value) + return value + return "" + + +def resolve_branch_template(config_file: Path) -> str: + template = read_git_config_value(config_file, "branch_template") + if template: + return template + + prefix = read_git_config_value(config_file, "branch_prefix") + if not prefix: + return "" + if prefix.endswith("/"): + return f"{prefix}{{number}}-{{slug}}" + return f"{prefix}/{{number}}-{{slug}}" + + +def validate_branch_template(template: str) -> None: + if not template: + return + if "{number}" not in template: + _err( + "Error: branch_template must include the {number} token so generated " + "branches remain valid feature branches." + ) + raise SystemExit(1) + slug_index = template.find("{slug}") + if slug_index != -1 and "{number}" in template[slug_index:]: + _err( + "Error: branch_template must not place {slug} before {number}; " + "use {slug} only in the final feature segment." + ) + raise SystemExit(1) + feature_segment = template.rsplit("/", 1)[-1] + if not feature_segment.startswith("{number}-"): + _err( + "Error: branch_template must put {number}- at the start of the final " + "path segment so generated branches remain valid feature branches." + ) + raise SystemExit(1) + + +def render_branch_template( + template: str, feature_num: str, branch_suffix: str, author_token: str, app_token: str +) -> str: + rendered = template + rendered = rendered.replace("{author}", author_token) + rendered = rendered.replace("{app}", app_token) + rendered = rendered.replace("{number}", feature_num) + rendered = rendered.replace("{slug}", branch_suffix) + return rendered + + +def extract_feature_num_from_branch(branch_name: str) -> str: + feature_segment = branch_name.rsplit("/", 1)[-1] + match = re.match(r"^[0-9]{8}-[0-9]{6}-", feature_segment) + if match: + return match.group(0).rstrip("-") + match = re.match(r"^[0-9]+-", feature_segment) + if match: + return match.group(0).rstrip("-") + return branch_name + + +def _byte_length(value: str) -> int: + return len(value.encode("utf-8")) + + +# ── Main ───────────────────────────────────────────────────────────────────── + + +def main(argv: list[str]) -> int: + args = parse_args(argv) + + feature_description = " ".join(args.description_parts) + if not feature_description: + _err(USAGE) + return 1 + feature_description = feature_description.strip() + if not feature_description: + _err("Error: Feature description cannot be empty or contain only whitespace") + return 1 + + project_root = _find_project_root(SCRIPT_DIR) + core = _load_core_common(project_root) + + # SPECIFY_INIT_DIR is resolved (and validated) by the core resolver. If the + # core helpers were not found, refuse rather than silently falling back to + # the wrong root. + if os.environ.get("SPECIFY_INIT_DIR") and ( + core is None or not hasattr(core, "resolve_specify_init_dir") + ): + _err( + "Error: SPECIFY_INIT_DIR requires updated Spec Kit core scripts " + "(common.py with resolve_specify_init_dir), which were not found." + ) + return 1 + + if core is not None and hasattr(core, "get_repo_root"): + # Pass script path so cwd-outside-repo callers land on the same + # fallback the bash twin does. Older cores don't accept the kwarg — + # fall back to the no-arg call for compatibility. + try: + repo_root = core.get_repo_root(script_file=Path(__file__)) + except TypeError: + repo_root = core.get_repo_root() + else: + toplevel = _git_lines(Path.cwd(), "rev-parse", "--show-toplevel") + if toplevel: + repo_root = Path(toplevel[0]) + elif project_root is not None: + repo_root = project_root + else: + _err("Error: Could not determine repository root.") + return 1 + repo_root = Path(repo_root) + + has_git_repo = _local_has_git(repo_root) + + specs_dir = repo_root / "specs" + config_file = repo_root / ".specify" / "extensions" / "git" / "git-config.yml" + + author_token = get_author_token(repo_root) + app_token = get_app_token(repo_root) + branch_template = resolve_branch_template(config_file) + validate_branch_template(branch_template) + + def build_branch_name(feature_num: str, branch_suffix: str) -> str: + if branch_template: + return render_branch_template( + branch_template, feature_num, branch_suffix, author_token, app_token + ) + return f"{feature_num}-{branch_suffix}" + + branch_number = args.branch_number + + # Check for GIT_BRANCH_NAME env var override (exact name, no prefix/suffix) + env_branch_name = os.environ.get("GIT_BRANCH_NAME", "") + if env_branch_name: + branch_name = env_branch_name + feature_num = extract_feature_num_from_branch(branch_name) + branch_suffix = branch_name + else: + if args.short_name: + branch_suffix = clean_branch_name(args.short_name) + else: + branch_suffix = generate_branch_name(feature_description) + + if args.use_timestamp and branch_number: + _err("[specify] Warning: --number is ignored when --timestamp is used") + branch_number = "" + + if args.use_timestamp: + feature_num = datetime.now().strftime("%Y%m%d-%H%M%S") + branch_name = build_branch_name(feature_num, branch_suffix) + else: + scope_prefix = "" + if branch_template: + prefix_template = branch_template.split("{number}")[0] + scope_prefix = render_branch_template( + prefix_template, "", branch_suffix, author_token, app_token + ) + if not branch_number: + if args.dry_run and has_git_repo: + branch_number = check_existing_branches( + repo_root, specs_dir, True, scope_prefix + ) + elif args.dry_run: + branch_number = get_highest_from_specs(specs_dir) + 1 + elif has_git_repo: + branch_number = check_existing_branches( + repo_root, specs_dir, False, scope_prefix + ) + else: + branch_number = get_highest_from_specs(specs_dir) + 1 + + feature_num = f"{int(branch_number):03d}" + branch_name = build_branch_name(feature_num, branch_suffix) + + branch_byte_len = _byte_length(branch_name) + if env_branch_name and branch_byte_len > MAX_BRANCH_LENGTH: + _err( + "Error: GIT_BRANCH_NAME must be 244 bytes or fewer in UTF-8. " + f"Provided value is {branch_byte_len} bytes." + ) + return 1 + if branch_byte_len > MAX_BRANCH_LENGTH: + original_branch_name = branch_name + truncated_suffix = branch_suffix + while _byte_length(branch_name) > MAX_BRANCH_LENGTH and truncated_suffix: + truncated_suffix = truncated_suffix[:-1] + truncated_suffix = truncated_suffix.rstrip("-") + branch_name = build_branch_name(feature_num, truncated_suffix) + if _byte_length(branch_name) > MAX_BRANCH_LENGTH: + _err("Error: Branch template prefix exceeds GitHub's 244-byte branch name limit.") + return 1 + + _err("[specify] Warning: Branch name exceeded GitHub's 244-byte limit") + _err( + f"[specify] Original: {original_branch_name} " + f"({_byte_length(original_branch_name)} bytes)" + ) + _err(f"[specify] Truncated to: {branch_name} ({_byte_length(branch_name)} bytes)") + + if not args.dry_run: + if has_git_repo: + create = subprocess.run( + ["git", "checkout", "-q", "-b", branch_name], + cwd=repo_root, + capture_output=True, + text=True, + ) + if create.returncode != 0: + current_branch_lines = _git_lines( + repo_root, "rev-parse", "--abbrev-ref", "HEAD" + ) + current_branch = current_branch_lines[0] if current_branch_lines else "" + branch_exists = bool( + _git_lines(repo_root, "branch", "--list", branch_name) + ) + if branch_exists: + if args.allow_existing: + if current_branch != branch_name: + switch = subprocess.run( + ["git", "checkout", "-q", branch_name], + cwd=repo_root, + capture_output=True, + text=True, + ) + if switch.returncode != 0: + _err( + f"Error: Failed to switch to existing branch '{branch_name}'. " + "Please resolve any local changes or conflicts and try again." + ) + if switch.stderr.strip(): + _err(switch.stderr.strip()) + return 1 + elif args.use_timestamp: + _err( + f"Error: Branch '{branch_name}' already exists. Rerun to get " + "a new timestamp or use a different --short-name." + ) + return 1 + else: + _err( + f"Error: Branch '{branch_name}' already exists. Please use a " + "different feature name or specify a different number with --number." + ) + return 1 + else: + _err(f"Error: Failed to create git branch '{branch_name}'.") + if create.stderr.strip(): + _err(create.stderr.strip()) + else: + _err("Please check your git configuration and try again.") + return 1 + else: + _err( + "[specify] Warning: Git repository not detected; skipped branch " + f"creation for {branch_name}" + ) + + _err(f"# To persist: {_persist_hint('SPECIFY_FEATURE', branch_name)}") + + if args.json_mode: + payload: dict[str, object] = { + "BRANCH_NAME": branch_name, + "FEATURE_NUM": feature_num, + } + if args.dry_run: + payload["DRY_RUN"] = True + print(json.dumps(payload, ensure_ascii=False, separators=(",", ":"))) + else: + print(f"BRANCH_NAME: {branch_name}") + print(f"FEATURE_NUM: {feature_num}") + if not args.dry_run: + print( + "# To persist in your shell: " + f"{_persist_hint('SPECIFY_FEATURE', branch_name)}" + ) + + return 0 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv[1:])) diff --git a/.specify/extensions/git/scripts/python/git_common.py b/.specify/extensions/git/scripts/python/git_common.py new file mode 100644 index 0000000..9b23fba --- /dev/null +++ b/.specify/extensions/git/scripts/python/git_common.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +"""Git-specific common helpers for the git extension. + +Python port of ``git-common.sh`` / ``git-common.ps1`` — contains only +git-specific branch validation and detection logic. +""" + +from __future__ import annotations + +import re +import shutil +import subprocess +import sys +from pathlib import Path + + +def has_git(repo_root: Path | None = None) -> bool: + """Check if we have git available at the repo root.""" + root = Path(repo_root) if repo_root is not None else Path.cwd() + git_marker = root / ".git" + if not (git_marker.is_dir() or git_marker.is_file()): + return False + if shutil.which("git") is None: + return False + result = subprocess.run( + ["git", "-C", str(root), "rev-parse", "--is-inside-work-tree"], + capture_output=True, + text=True, + ) + return result.returncode == 0 + + +def effective_branch_name(raw: str) -> str: + """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. + """ + match = re.fullmatch(r"([^/]+)/([^/]+)", raw) + if match: + return match.group(2) + return raw + + +def check_feature_branch(raw: str, has_git_repo: bool) -> bool: + """Validate that a branch name matches the expected feature branch pattern. + + Accepts sequential (###-* with >=3 digits) or timestamp (YYYYMMDD-HHMMSS-*) + formats, either at the start of the branch or after path-style namespace + prefixes. Logic aligned with the bash/PowerShell twins. + """ + if not has_git_repo: + print( + "[specify] Warning: Git repository not detected; skipped branch validation", + file=sys.stderr, + ) + return True + + branch = effective_branch_name(raw) + feature_segment = branch.rsplit("/", 1)[-1] + + # Accept sequential prefix (3+ digits) but exclude malformed timestamps: + # 7-or-8 digit date + 6-digit time with no trailing slug. + is_sequential = bool( + re.match(r"^[0-9]{3,}-", feature_segment) + and not re.match(r"^[0-9]{7}-[0-9]{6}-", feature_segment) + and not re.fullmatch(r"[0-9]{7,8}-[0-9]{6}", feature_segment) + ) + is_timestamp = bool(re.match(r"^[0-9]{8}-[0-9]{6}-", feature_segment)) + + if not is_sequential and not is_timestamp: + print(f"ERROR: Not on a feature branch. Current branch: {raw}", file=sys.stderr) + print( + "Feature branches should be named like: 001-feature-name, " + "1234-feature-name, 20260319-143022-feature-name, or " + "/001-feature-name", + file=sys.stderr, + ) + return False + + return True diff --git a/.specify/extensions/git/scripts/python/initialize_repo.py b/.specify/extensions/git/scripts/python/initialize_repo.py new file mode 100644 index 0000000..eaf604c --- /dev/null +++ b/.specify/extensions/git/scripts/python/initialize_repo.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +"""Git extension: initialize_repo.py + +Initialize a Git repository with an initial commit. +Python port of ``initialize-repo.sh`` / ``initialize-repo.ps1``. +Customizable — replace this script to add .gitignore templates, +default branch config, git-flow, LFS, signing, etc. +""" + +from __future__ import annotations + +import re +import shutil +import subprocess +import sys +from pathlib import Path + + +def _find_project_root(start: Path) -> Path | None: + current = start + while True: + if (current / ".specify").is_dir() or (current / ".git").exists(): + return current + if current.parent == current: + return None + current = current.parent + + +def _read_commit_message(repo_root: Path) -> str: + """Read init_commit_message from git-config.yml, mirroring the bash sed pipeline.""" + default = "[Spec Kit] Initial commit" + config_file = repo_root / ".specify" / "extensions" / "git" / "git-config.yml" + if not config_file.is_file(): + return default + try: + lines = config_file.read_text(encoding="utf-8").splitlines() + except (OSError, UnicodeDecodeError): + return default + for line in lines: + if line.startswith("init_commit_message:"): + value = re.sub(r"^init_commit_message:\s*", "", line) + value = re.sub(r"^[\"']", "", value) + value = re.sub(r"[\"']*$", "", value) + if value: + return value + return default + + +def main() -> int: + script_dir = Path(__file__).resolve().parent + repo_root = _find_project_root(script_dir) or Path.cwd() + + commit_msg = _read_commit_message(repo_root) + + if shutil.which("git") is None: + print( + "[specify] Warning: Git not found; skipped repository initialization", + file=sys.stderr, + ) + return 0 + + probe = subprocess.run( + ["git", "rev-parse", "--is-inside-work-tree"], + cwd=repo_root, + capture_output=True, + text=True, + ) + if probe.returncode == 0: + print("[specify] Git repository already initialized; skipping", file=sys.stderr) + return 0 + + steps = [ + (["git", "init", "-q"], "git init"), + (["git", "add", "."], "git add"), + (["git", "commit", "--allow-empty", "-q", "-m", commit_msg], "git commit"), + ] + for cmd, label in steps: + result = subprocess.run(cmd, cwd=repo_root, capture_output=True, text=True) + if result.returncode != 0: + output = (result.stdout + result.stderr).strip() + print(f"[specify] Error: {label} failed: {output}", file=sys.stderr) + return 1 + + print("[OK] Git repository initialized", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/.specify/feature.json b/.specify/feature.json index a18aae8..1495c1a 100644 --- a/.specify/feature.json +++ b/.specify/feature.json @@ -1,3 +1,3 @@ { - "feature_directory": "specs/003-github-actions-cicd" + "feature_directory": "specs/004-schedule-page-reminders" } diff --git a/.specify/init-options.json b/.specify/init-options.json index 81fa58e..9886e95 100644 --- a/.specify/init-options.json +++ b/.specify/init-options.json @@ -5,5 +5,5 @@ "here": false, "integration": "claude", "script": "ps", - "speckit_version": "0.9.4" -} \ No newline at end of file + "speckit_version": "1.1.0" +} diff --git a/.specify/integration.json b/.specify/integration.json index 8e63ea1..731f9ef 100644 --- a/.specify/integration.json +++ b/.specify/integration.json @@ -1,5 +1,5 @@ { - "version": "0.9.4", + "version": "1.1.0", "integration_state_schema": 1, "installed_integrations": [ "claude" diff --git a/.specify/integrations/claude.manifest.json b/.specify/integrations/claude.manifest.json index 669bf46..4a012ef 100644 --- a/.specify/integrations/claude.manifest.json +++ b/.specify/integrations/claude.manifest.json @@ -1,16 +1,17 @@ { "integration": "claude", - "version": "0.9.4", - "installed_at": "2026-06-16T06:08:47.374110+00:00", + "version": "1.1.0", + "installed_at": "2026-10-05T04:31:09.576197+00:00", "files": { - ".claude/skills/speckit-analyze/SKILL.md": "adb9c4baed1d0e27cebd08e506a7247c1357ee721b6ea340201553d5792e6c8a", - ".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": "08e693951151193ea45fe4a42079c520e223999eb803e10a89190e070f089949", - ".claude/skills/speckit-checklist/SKILL.md": "82a54d9ce969ae87c0034ffce77539bc708290efc26a6160efe928b248c712c4", - ".claude/skills/speckit-specify/SKILL.md": "bafe529c22cb971cd2537ca6c5381ba100de0f91f439c62941a2c541fa067f7e", - ".claude/skills/speckit-tasks/SKILL.md": "84c276f7037693ebc69eef74dce0af127280eda1d8e6af18d29ff8440b028d3f", - ".claude/skills/speckit-taskstoissues/SKILL.md": "e326c30c89a6bb67a9251cbe038178bc4dd1281948267d1921d361d8c327a0d9" + ".claude/skills/speckit-analyze/SKILL.md": "299d136fbc16ff71592dc8e7b765914d55d571b9cd95ddd378593619a9b5fe5d", + ".claude/skills/speckit-clarify/SKILL.md": "b7ed324427867c31b025b0acb01f6eba80c69252b9d69edf2bf8013d384b9b9c", + ".claude/skills/speckit-constitution/SKILL.md": "fcac0fbd9c99c987abcaab97df79eaf54f106f5aa16f6dd2b4b7f5324221877c", + ".claude/skills/speckit-implement/SKILL.md": "d8822195af8c04155179c914cc67323cbe4228cda75c8bff0b3b3e209abf4941", + ".claude/skills/speckit-converge/SKILL.md": "1f7a90a1b03b94d14687d96fd1125e0173bd20a19017e12519017d57f63312c5", + ".claude/skills/speckit-plan/SKILL.md": "db4fd9659ecd7b42843d56961607e26dc66439fffec92c733027fb016f83e679", + ".claude/skills/speckit-checklist/SKILL.md": "bd6eaf7623befcad231f8ee8bf6ae3f03bb49ee6264887fbe13c5102ce417aa4", + ".claude/skills/speckit-specify/SKILL.md": "d4d93f2444355136e78bb533988aa2dd560dc4b258f4923f67b1a437e7de38f8", + ".claude/skills/speckit-tasks/SKILL.md": "78f32c4d6892f19e8249fbc319e0c5cf2e15c2339e3f50baf0cecb0358de695e", + ".claude/skills/speckit-taskstoissues/SKILL.md": "341be56e99263d77fdc974489675499576b3cd96ca7ec55cf27fb681c5b0ab9f" } } diff --git a/.specify/integrations/speckit.manifest.json b/.specify/integrations/speckit.manifest.json index 3679731..87a9dfa 100644 --- a/.specify/integrations/speckit.manifest.json +++ b/.specify/integrations/speckit.manifest.json @@ -1,17 +1,19 @@ { "integration": "speckit", - "version": "0.9.4", + "version": "1.1.0", "installed_at": "2026-06-16T06:08:47.392405+00:00", "files": { - ".specify/scripts/powershell/setup-tasks.ps1": "76f14accb3782530bc0b813374e2363334c3ad2969c208b57613521591879fff", - ".specify/scripts/powershell/check-prerequisites.ps1": "851b3eb02593e7cf3dca97c4bb5f518e321b1f5fbe5865529d663b5fddd1e62b", - ".specify/scripts/powershell/common.ps1": "5127db8f0b58305ea40dd14d3fc3745ea36b0d655bb59420c87127545fa04d6d", - ".specify/scripts/powershell/setup-plan.ps1": "c4421bd2544a3b25fa07858f1c7cb854ef56a26a972853302e9763107da023cd", - ".specify/scripts/powershell/create-new-feature.ps1": "24b07de9e1084ebe11f3dc65466d279b0aa4dbff7e7b011dcf303d299e994c9d", + ".specify/scripts/powershell/setup-tasks.ps1": "57cd05e12bd472c60ac0554ad61b89770c278d50c48e484fb824196f44f75076", + ".specify/scripts/powershell/check-prerequisites.ps1": "af4b8f5e8d373827726b79532cf57c567b1538c0494058d8095683c7fe107c49", + ".specify/scripts/powershell/common.ps1": "9837a02a1ca9e61a16a1ff7ec7429c95d8e1c87ec49400cc2807133bb89a5317", + ".specify/scripts/powershell/setup-plan.ps1": "3b8173f1553bbf67ae021af949a29e2d3e3bb35805be95e4ba8d0ab83173c66f", + ".specify/scripts/powershell/create-new-feature.ps1": "481c7368541a816b1679e5ed65fa9e5aea84b09f8be3a02ff8a340e3b48dd58a", ".specify/templates/constitution-template.md": "ce7549540fa45543cca797a150201d868e64495fdff39dc38246fb17bd4024b3", - ".specify/templates/checklist-template.md": "c37695297e5d3153d64f82c21223509940b13932046c7961c42d1d669516130c", + ".specify/templates/checklist-template.md": "856532b3cb66171c662cc16f16b31a5856e4655a8666aad1e545bbfc7f603ca1", ".specify/templates/tasks-template.md": "fc29a233f6f5a27ca31f1aa46b596af6500c627441c6e62b2bc4a1d721525842", ".specify/templates/spec-template.md": "3945437fc35cd30a5b2bf7beea680337c3516826d3efa5a6b92c4a7eca1ba28e", - ".specify/templates/plan-template.md": "cc7f7979cf8d8836ec26492785affd80791d3422a2b745062ec695be8c985ef7" + ".specify/templates/plan-template.md": "7e637502d41eccf0ca672496636365691fdca62ef37b27ec07fcb412dbfa90d4", + ".specify/scripts/powershell/resolve-template.ps1": "e49c565a09902e4ebd4b5a51c4e014d5067fdee5b1592f15cb44ef31f430d745", + ".specify/.gitignore": "8c908410d177a1ef3d0dee16d7ad55f2ac3333df3104c4d4adee1c9b82f1dbc1" } } diff --git a/.specify/scripts/powershell/check-prerequisites.ps1 b/.specify/scripts/powershell/check-prerequisites.ps1 index 8cb514c..bee3a62 100644 --- a/.specify/scripts/powershell/check-prerequisites.ps1 +++ b/.specify/scripts/powershell/check-prerequisites.ps1 @@ -9,17 +9,21 @@ # # OPTIONS: # -Json Output in JSON format +# -RequireSpec Require spec.md to exist (for analysis phase) # -RequireTasks Require tasks.md to exist (for implementation phase) # -IncludeTasks Include tasks.md in AVAILABLE_DOCS list # -PathsOnly Only output path variables (no validation) +# -Template NAME Include composed template content in JSON output # -Help, -h Show help message [CmdletBinding()] param( [switch]$Json, + [switch]$RequireSpec, [switch]$RequireTasks, [switch]$IncludeTasks, [switch]$PathsOnly, + [string]$Template, [switch]$Help ) @@ -34,18 +38,20 @@ Consolidated prerequisite checking for Spec-Driven Development workflow. OPTIONS: -Json Output in JSON format + -RequireSpec Require spec.md to exist (for analysis phase) -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) + -Template NAME Include composed template content in JSON output -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 @@ -56,8 +62,14 @@ EXAMPLES: # Source common functions . "$PSScriptRoot/common.ps1" -# Get feature paths -$paths = Get-FeaturePathsEnv +# Get feature paths. +# In -PathsOnly mode this is pure resolution, so pass -NoPersist to opt out of +# the feature.json write side effect (issue #3025). +if ($PathsOnly) { + $paths = Get-FeaturePathsEnv -NoPersist +} else { + $paths = Get-FeaturePathsEnv +} # If paths-only mode, output paths and exit (no validation) if ($PathsOnly) { @@ -81,31 +93,34 @@ if ($PathsOnly) { 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)" + [Console]::Error.WriteLine("ERROR: Feature directory not found: $($paths.FEATURE_DIR)") $specifyCommand = '/speckit-specify' - Write-Output "Run $specifyCommand first to create the feature structure." + [Console]::Error.WriteLine("Run $specifyCommand 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)" + [Console]::Error.WriteLine("ERROR: plan.md not found in $($paths.FEATURE_DIR)") $planCommand = '/speckit-plan' - Write-Output "Run $planCommand first to create the implementation plan." + [Console]::Error.WriteLine("Run $planCommand first to create the implementation plan.") + exit 1 +} + +# Check for spec.md if required +if ($RequireSpec -and -not (Test-Path $paths.FEATURE_SPEC -PathType Leaf)) { + [Console]::Error.WriteLine("ERROR: spec.md not found in $($paths.FEATURE_DIR)") + $specifyCommand = '/speckit-specify' + [Console]::Error.WriteLine("Run $specifyCommand first to create the feature specification.") 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)" + [Console]::Error.WriteLine("ERROR: tasks.md not found in $($paths.FEATURE_DIR)") $tasksCommand = '/speckit-tasks' - Write-Output "Run $tasksCommand first to create the task list." + [Console]::Error.WriteLine("Run $tasksCommand first to create the task list.") exit 1 } @@ -117,36 +132,54 @@ 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.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' +if ($IncludeTasks -and (Test-Path $paths.TASKS)) { + $docs += 'tasks.md' +} + +$templateContent = $null +if ($Template) { + $templateContent = Resolve-TemplateContent -TemplateName $Template -RepoRoot $paths.REPO_ROOT + if ($null -eq $templateContent) { + [Console]::Error.WriteLine("ERROR: Could not resolve required $Template from the template override stack for $($paths.REPO_ROOT)") + exit 1 + } } # Output results if ($Json) { # JSON output - [PSCustomObject]@{ + $result = [ordered]@{ FEATURE_DIR = $paths.FEATURE_DIR - AVAILABLE_DOCS = $docs - } | ConvertTo-Json -Compress + AVAILABLE_DOCS = $docs + } + if ($Template) { + $result.TEMPLATE_CONTENT = $templateContent + } + [PSCustomObject]$result | 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 - + + # Show status of each potential document. + # These helpers report their line with Write-Output and ALSO return a + # bool, both on the Success stream, so 'Out-Null' discarded the report + # line along with the return value and left AVAILABLE_DOCS empty. Drop + # only the boolean so the per-document lines reach stdout like the + # bash and Python twins. + Test-FileExists -Path $paths.RESEARCH -Description 'research.md' | Where-Object { $_ -isnot [bool] } + Test-FileExists -Path $paths.DATA_MODEL -Description 'data-model.md' | Where-Object { $_ -isnot [bool] } + Test-DirHasFiles -Path $paths.CONTRACTS_DIR -Description 'contracts/' | Where-Object { $_ -isnot [bool] } + Test-FileExists -Path $paths.QUICKSTART -Description 'quickstart.md' | Where-Object { $_ -isnot [bool] } + if ($IncludeTasks) { - Test-FileExists -Path $paths.TASKS -Description 'tasks.md' | Out-Null + Test-FileExists -Path $paths.TASKS -Description 'tasks.md' | Where-Object { $_ -isnot [bool] } } } diff --git a/.specify/scripts/powershell/common.ps1 b/.specify/scripts/powershell/common.ps1 index d0df7cd..c90308e 100644 --- a/.specify/scripts/powershell/common.ps1 +++ b/.specify/scripts/powershell/common.ps1 @@ -1,6 +1,7 @@ #!/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 { @@ -24,272 +25,162 @@ function Find-SpecifyRoot { } } -# Get repository root, prioritizing .specify directory over git -# This prevents using a parent git repo when spec-kit is initialized in a subdirectory +# Resolve an explicit SPECIFY_INIT_DIR project override (the directory that +# *contains* .specify/), for non-interactive / CI use -- e.g. running a Spec Kit +# command against a member project from a monorepo root without cd. +# +# Precondition: $env:SPECIFY_INIT_DIR is set. Returns the validated project root, +# or writes an error and exits 1 unless -ReturnNullOnError is set. Strict by +# design: the path must exist and +# contain .specify/, with no silent fallback. (An empty string is falsy, so the +# caller's `if ($env:SPECIFY_INIT_DIR)` guard treats empty as unset.) +# +# This is the single resolver: bundled extensions inherit it by sourcing core +# (e.g. the git extension's create-new-feature-branch) rather than duplicating it. +function Resolve-SpecifyInitDir { + param([switch]$ReturnNullOnError) + + $initDir = $env:SPECIFY_INIT_DIR + # Normalize: relative paths resolve against the current directory. + if (-not [System.IO.Path]::IsPathRooted($initDir)) { + $initDir = Join-Path (Get-Location).Path $initDir + } + $resolved = Resolve-Path -LiteralPath $initDir -ErrorAction SilentlyContinue + # Resolve-Path also succeeds for files, so check the resolved path is a + # directory; otherwise a file value would slip through to the less accurate + # "not a Spec Kit project" error below. + if (-not $resolved -or -not (Test-Path -LiteralPath $resolved.Path -PathType Container)) { + [Console]::Error.WriteLine("ERROR: SPECIFY_INIT_DIR does not point to an existing directory: $($env:SPECIFY_INIT_DIR)") + if ($ReturnNullOnError) { return $null } + exit 1 + } + # Resolve-Path echoes back any trailing separator from the input; trim it so + # the returned root matches the bash resolver, whose `cd && pwd` never yields + # one. TrimEnd (not [Path]::TrimEndingDirectorySeparator, which is .NET Core + # only) keeps this working on Windows PowerShell 5.1 / .NET Framework, as + # Get-FeaturePathsEnv already does below. Unlike a bare TrimEnd, the + # GetPathRoot check preserves a path that *is* its own root ('C:\' must not + # become 'C:', which every later API re-resolves against the current + # directory instead of the drive root). No-op on a path with no trailing + # separator. + $initRoot = $resolved.Path.TrimEnd('/', '\') + if ($initRoot.Length -lt [System.IO.Path]::GetPathRoot($resolved.Path).Length) { + $initRoot = $resolved.Path + } + if (-not (Test-Path -LiteralPath (Join-Path $initRoot '.specify') -PathType Container)) { + [Console]::Error.WriteLine("ERROR: SPECIFY_INIT_DIR is not a Spec Kit project (no .specify/ directory): $initRoot") + if ($ReturnNullOnError) { return $null } + exit 1 + } + return $initRoot +} + +# Get repository root, prioritizing .specify directory +# This prevents using a parent repository when spec-kit is initialized in a subdirectory function Get-RepoRoot { + param([switch]$ReturnNullOnError) + + # Explicit project override wins (see Resolve-SpecifyInitDir). + if ($env:SPECIFY_INIT_DIR) { + return (Resolve-SpecifyInitDir -ReturnNullOnError:$ReturnNullOnError) + } + # 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 + # Final fallback to script location # 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 + # Return feature name from explicit state only. + # Feature state is set by SPECIFY_FEATURE (from create-new-feature or + # the git extension) or implicitly via .specify/feature.json. 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 + # No explicit feature set - return empty to signal "unknown". + return "" } -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 { +# Persist a feature_directory value to .specify/feature.json. +# Writes only when the file is missing or the value differs from what's stored. +function Save-FeatureJson { param( [Parameter(Mandatory = $true)][string]$RepoRoot, - [Parameter(Mandatory = $true)][string]$ActiveFeatureDir + [Parameter(Mandatory = $true)][string]$FeatureDirectory ) - $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 + # Strip repo root prefix if the value is absolute and under repo root. + # Use case-insensitive comparison on Windows only (case-sensitive filesystems elsewhere). + $prefix = $RepoRoot + [System.IO.Path]::DirectorySeparatorChar + if ($null -ne $IsWindows) { $onWin = $IsWindows } else { $onWin = $true } + if ($onWin) { + $cmp = [System.StringComparison]::OrdinalIgnoreCase } else { - $onWindows = $true + $cmp = [System.StringComparison]::Ordinal } - - if ($onWindows) { - $comparison = [System.StringComparison]::OrdinalIgnoreCase - } else { - $comparison = [System.StringComparison]::Ordinal + if ($FeatureDirectory.StartsWith($prefix, $cmp)) { + $FeatureDirectory = $FeatureDirectory.Substring($prefix.Length) } - return [string]::Equals($normJson, $normActive, $comparison) -} + $fjPath = Join-Path (Join-Path $RepoRoot '.specify') 'feature.json' -# Resolve specs/ 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) + # Read current value and skip write when unchanged + if (Test-Path -LiteralPath $fjPath -PathType Leaf) { + try { + $raw = [System.IO.File]::ReadAllText($fjPath, [System.Text.Encoding]::UTF8) + $cfg = $raw | ConvertFrom-Json + if ($cfg.feature_directory -eq $FeatureDirectory) { + return + } + } catch { + # File is corrupt or unreadable - overwrite it + } } - $dirMatches = @() - if (Test-Path -LiteralPath $specsDir -PathType Container) { - $dirMatches = @(Get-ChildItem -LiteralPath $specsDir -Filter "$prefix-*" -Directory -ErrorAction SilentlyContinue) + # Ensure .specify/ directory exists + $specifyDir = Join-Path $RepoRoot '.specify' + if (-not (Test-Path -LiteralPath $specifyDir -PathType Container)) { + New-Item -ItemType Directory -Path $specifyDir -Force | Out-Null } - 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 + # Write feature.json + $json = @{ feature_directory = $FeatureDirectory } | ConvertTo-Json -Compress + $utf8NoBom = New-Object System.Text.UTF8Encoding($false) + [System.IO.File]::WriteAllText($fjPath, $json, $utf8NoBom) } -# Branch-based prefix resolution; mirrors bash get_feature_paths failure (stderr + exit 1). -function Get-FeatureDirFromBranchPrefixOrExit { +function Get-FeaturePathsEnv { + # Read-only callers (e.g. check-prerequisites.ps1 -PathsOnly) pass -NoPersist + # so pure path resolution never writes .specify/feature.json, which would + # dirty the working tree or overwrite a pinned value (issue #3025). param( - [Parameter(Mandatory = $true)][string]$RepoRoot, - [Parameter(Mandatory = $true)][string]$CurrentBranch + [switch]$NoPersist, + [switch]$ReturnNullOnError ) - $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 + # SPECIFY_FEATURE_NO_PERSIST is the environment-level equivalent of -NoPersist, + # letting an orchestrator (multi-agent runner, CI matrix) guarantee that no + # script invocation in the process tree writes .specify/feature.json, even + # scripts that don't pass -NoPersist themselves (#4128). + $noPersist = [bool]$NoPersist -or $env:SPECIFY_FEATURE_NO_PERSIST -eq '1' -or $env:SPECIFY_FEATURE_NO_PERSIST -eq 'true' + + $repoRoot = Get-RepoRoot -ReturnNullOnError:$ReturnNullOnError + if (-not $repoRoot) { return $null } $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) + # 2. .specify/feature.json "feature_directory" key (persisted by specify command) + # 3. Error - no feature context available $featureJson = Join-Path $repoRoot '.specify/feature.json' if ($env:SPECIFY_FEATURE_DIRECTORY) { $featureDir = $env:SPECIFY_FEATURE_DIRECTORY @@ -297,12 +188,18 @@ function Get-FeaturePathsEnv { if (-not [System.IO.Path]::IsPathRooted($featureDir)) { $featureDir = Join-Path $repoRoot $featureDir } + # Persist to feature.json so future sessions without the env var still + # work - unless the caller opted out for read-only resolution (#3025). + if (-not $noPersist) { + Save-FeatureJson -RepoRoot $repoRoot -FeatureDirectory $env:SPECIFY_FEATURE_DIRECTORY + } } elseif (Test-Path $featureJson) { - $featureJsonRaw = Get-Content -LiteralPath $featureJson -Raw + $featureJsonRaw = [System.IO.File]::ReadAllText($featureJson, [System.Text.Encoding]::UTF8) try { $featureConfig = $featureJsonRaw | ConvertFrom-Json } catch { - [Console]::Error.WriteLine("ERROR: Failed to parse .specify/feature.json: $_") + [Console]::Error.WriteLine("ERROR: Feature directory not found. Set SPECIFY_FEATURE_DIRECTORY or ensure .specify/feature.json contains feature_directory.") + if ($ReturnNullOnError) { return $null } exit 1 } if ($featureConfig.feature_directory) { @@ -312,16 +209,30 @@ function Get-FeaturePathsEnv { $featureDir = Join-Path $repoRoot $featureDir } } else { - $featureDir = Get-FeatureDirFromBranchPrefixOrExit -RepoRoot $repoRoot -CurrentBranch $currentBranch + [Console]::Error.WriteLine("ERROR: Feature directory not found. Set SPECIFY_FEATURE_DIRECTORY or ensure .specify/feature.json contains feature_directory.") + if ($ReturnNullOnError) { return $null } + exit 1 } } else { - $featureDir = Get-FeatureDirFromBranchPrefixOrExit -RepoRoot $repoRoot -CurrentBranch $currentBranch + [Console]::Error.WriteLine("ERROR: Feature directory not found. Set SPECIFY_FEATURE_DIRECTORY or run the specify command to create .specify/feature.json.") + if ($ReturnNullOnError) { return $null } + exit 1 + } + + # When no branch context exists (no SPECIFY_FEATURE, feature resolved via + # SPECIFY_FEATURE_DIRECTORY or feature.json), fall back to the feature + # directory basename so CURRENT_BRANCH is a usable identifier rather than + # an empty, misleading value (issue #3026). + if (-not $currentBranch) { + # TrimEnd (not [Path]::TrimEndingDirectorySeparator, which is .NET Core + # only) keeps this working on Windows PowerShell 5.1 / .NET Framework. + $featureDirTrimmed = $featureDir.TrimEnd('/', '\') + $currentBranch = Split-Path -Leaf $featureDirTrimmed } - + [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' @@ -346,7 +257,13 @@ function Test-FileExists { 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)) { + # A directory counts as non-empty when Get-ChildItem returns any entry + # (files or subdirectories) -- matching the JSON contracts checks in + # check-prerequisites.ps1 / setup-tasks.ps1, and treating a directory whose + # only contents are subdirectories (e.g. contracts/v1/openapi.yaml) as + # non-empty like bash check_dir. Filtering out subdirectories would + # mis-report such a directory as empty. + if ((Test-Path -Path $Path -PathType Container) -and (Get-ChildItem -Path $Path -ErrorAction SilentlyContinue | Select-Object -First 1)) { Write-Output " [OK] $Description" return $true } else { @@ -410,6 +327,16 @@ function Format-SpecKitCommand { # 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 { + # SPECKIT_PYTHON_EXECUTABLE is the canonical override; SPECKIT_PYTHON is + # kept as a deprecated fallback (still used by update-agent-context.sh). + $override = if ($env:SPECKIT_PYTHON_EXECUTABLE) { $env:SPECKIT_PYTHON_EXECUTABLE } else { $env:SPECKIT_PYTHON } + if ($override -and (Get-Command $override -ErrorAction SilentlyContinue)) { + $ver = & $override --version 2>&1 + if ($ver -match 'Python 3') { + & $override -c 'import yaml' *> $null + if ($LASTEXITCODE -eq 0) { return @($override) } + } + } if (Get-Command python3 -ErrorAction SilentlyContinue) { return @('python3') } if (Get-Command python -ErrorAction SilentlyContinue) { $ver = & python --version 2>&1 @@ -422,6 +349,82 @@ function Get-Python3Command { return $null } +function Get-NormalizedPriority { + param($Value) + + if ($Value -is [bool]) { return 10 } + if ($Value -is [string]) { + $integerText = $Value.Trim() + if ($integerText -cnotmatch '^[+-]?[0-9]+(?:_[0-9]+)*$') { return 10 } + $Value = $integerText.Replace('_', '') + } + try { + $parsedPriority = [System.Numerics.BigInteger]$Value + } catch { + return 10 + } + return $(if ($parsedPriority -ge 1) { $parsedPriority } else { 10 }) +} + +function Get-SortedExtensionIds { + param([Parameter(Mandatory=$true)][string]$ExtensionsDir) + + $registeredNames = @() + $ranked = @() + $registryFile = Join-Path $ExtensionsDir '.registry' + # Detect any filesystem entry at the registry path without following symlinks. + # Test-Path follows links and reports $false for a dangling symlink, so a + # broken .registry symlink would otherwise bypass this guard and let the + # directory scan below enable every on-disk extension. Enumerating the parent + # directory still observes a broken symlink as an entry. + $registryEntry = Get-ChildItem -LiteralPath $ExtensionsDir -Force -ErrorAction SilentlyContinue | + Where-Object { $_.Name -eq '.registry' } | + Select-Object -First 1 + if ($registryEntry) { + if (-not (Test-Path -LiteralPath $registryFile -PathType Leaf)) { + throw "Invalid extension registry ${registryFile}: not a regular file" + } + try { + $data = [System.IO.File]::ReadAllText($registryFile, [System.Text.Encoding]::UTF8) | ConvertFrom-Json + } catch { + throw "Invalid extension registry ${registryFile}: $($_.Exception.Message)" + } + if ($null -eq $data -or $data -isnot [PSCustomObject]) { + throw "Invalid extension registry ${registryFile}: root must be a mapping" + } + $extensionsProperty = $data.PSObject.Properties['extensions'] + if ($extensionsProperty) { + if ($extensionsProperty.Value -isnot [PSCustomObject]) { + throw "Invalid extension registry ${registryFile}: 'extensions' must be a mapping" + } + $extensions = $extensionsProperty.Value + } else { + $extensions = [PSCustomObject]@{} + } + $registeredNames = @($extensions.PSObject.Properties | ForEach-Object { $_.Name }) + foreach ($entry in $extensions.PSObject.Properties) { + if ($entry.Name -cnotmatch '^[a-z0-9-]+$' -or $entry.Value -isnot [PSCustomObject]) { + continue + } + $enabledProperty = $entry.Value.PSObject.Properties['enabled'] + if ($enabledProperty -and -not [bool]$enabledProperty.Value) { continue } + $priority = 10 + $priorityProperty = $entry.Value.PSObject.Properties['priority'] + if ($priorityProperty) { + $priority = Get-NormalizedPriority -Value $priorityProperty.Value + } + $ranked += [PSCustomObject]@{ Priority = $priority; Id = $entry.Name } + } + } + + foreach ($directory in Get-ChildItem -Path $ExtensionsDir -Directory -ErrorAction SilentlyContinue) { + if ($directory.Name -cmatch '^[a-z0-9-]+$' -and $directory.Name -cnotin $registeredNames) { + $ranked += [PSCustomObject]@{ Priority = 10; Id = $directory.Name } + } + } + return $ranked | Sort-Object Priority, Id | ForEach-Object { $_.Id } +} + # Resolve a template name to a file path using the priority stack: # 1. .specify/templates/overrides/ # 2. .specify/presets//templates/ (sorted by priority from .registry) @@ -433,6 +436,8 @@ function Resolve-Template { [Parameter(Mandatory=$true)][string]$RepoRoot ) + if ($TemplateName -cnotmatch '^[a-z0-9-]+$') { return $null } + $base = Join-Path $RepoRoot '.specify/templates' # Priority 1: Project overrides @@ -444,32 +449,60 @@ function Resolve-Template { if (Test-Path $presetsDir) { $registryFile = Join-Path $presetsDir '.registry' $sortedPresets = @() + $registryParsed = $false 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 } } | + $registryData = [System.IO.File]::ReadAllText($registryFile, [System.Text.Encoding]::UTF8) | ConvertFrom-Json + if ($null -eq $registryData -or $registryData -isnot [PSCustomObject]) { + throw 'Registry root must be an object' + } + $presetsProperty = $registryData.PSObject.Properties['presets'] + if ($presetsProperty) { + $presets = $presetsProperty.Value + if ($null -eq $presets -or $presets -isnot [PSCustomObject]) { + throw 'Registry presets must be an object' + } + $presetEntries = @($presets.PSObject.Properties) + $priorityFor = { + param($Entry) + if ($Entry.Value -is [PSCustomObject]) { + $priorityProperty = $Entry.Value.PSObject.Properties['priority'] + if ($priorityProperty) { + return Get-NormalizedPriority -Value $priorityProperty.Value + } + } + return 10 + } + $sortedPresets = $presetEntries | + Where-Object { $_.Value -is [PSCustomObject] } | + Where-Object { + $enabled = $_.Value.PSObject.Properties['enabled'] + -not $enabled -or [bool]$enabled.Value + } | + Where-Object { $_.Name -cmatch '^[a-z0-9-]+$' } | + Sort-Object @{ Expression = { & $priorityFor $_ } }, @{ Expression = { $_.Name } } | ForEach-Object { $_.Name } } + $registryParsed = $true } catch { - # Fallback: alphabetical directory order - $sortedPresets = @() + $registryParsed = $false } } - if ($sortedPresets.Count -gt 0) { + if ($registryParsed) { foreach ($presetId in $sortedPresets) { $candidate = Join-Path $presetsDir "$presetId/templates/$TemplateName.md" if (Test-Path $candidate) { return $candidate } + $candidate = Join-Path $presetsDir "$presetId/$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 '.*' }) { + foreach ($preset in Get-ChildItem -Path $presetsDir -Directory -ErrorAction SilentlyContinue | Where-Object { $_.Name -notlike '.*' } | Sort-Object Name) { $candidate = Join-Path $preset.FullName "templates/$TemplateName.md" if (Test-Path $candidate) { return $candidate } + $candidate = Join-Path $preset.FullName "$TemplateName.md" + if (Test-Path $candidate) { return $candidate } } } } @@ -477,8 +510,11 @@ function Resolve-Template { # 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" + foreach ($extensionId in Get-SortedExtensionIds -ExtensionsDir $extDir) { + $candidate = Join-Path $extDir "$extensionId/templates/$TemplateName.md" + if (-not (Test-Path $candidate)) { + $candidate = Join-Path $extDir "$extensionId/$TemplateName.md" + } if (Test-Path $candidate) { return $candidate } } } @@ -499,6 +535,10 @@ function Resolve-TemplateContent { [Parameter(Mandatory=$true)][string]$RepoRoot ) + if ($TemplateName -cnotmatch '^[a-z0-9-]+$') { + return $null + } + $base = Join-Path $RepoRoot '.specify/templates' # Collect all layers (highest priority first) @@ -508,49 +548,77 @@ function Resolve-TemplateContent { # Priority 1: Project overrides (always "replace") $override = Join-Path $base "overrides/$TemplateName.md" if (Test-Path $override) { - $layerPaths += $override - $layerStrategies += 'replace' + return [System.IO.File]::ReadAllText( + $override, + [System.Text.Encoding]::UTF8 + ) } + $effectiveBaseFound = $false + # 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 = @() + $registryParsed = $false 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 } } | + $registryData = [System.IO.File]::ReadAllText($registryFile, [System.Text.Encoding]::UTF8) | ConvertFrom-Json + if ($null -eq $registryData -or $registryData -isnot [PSCustomObject]) { + throw 'Registry root must be an object' + } + $presetsProperty = $registryData.PSObject.Properties['presets'] + if ($presetsProperty) { + $presets = $presetsProperty.Value + if ($null -eq $presets -or $presets -isnot [PSCustomObject]) { + throw 'Registry presets must be an object' + } + $presetEntries = @($presets.PSObject.Properties) + $priorityFor = { + param($Entry) + if ($Entry.Value -is [PSCustomObject]) { + $priorityProperty = $Entry.Value.PSObject.Properties['priority'] + if ($priorityProperty) { + return Get-NormalizedPriority -Value $priorityProperty.Value + } + } + return 10 + } + $sortedPresets = $presetEntries | + Where-Object { $_.Value -is [PSCustomObject] } | + Where-Object { + $enabled = $_.Value.PSObject.Properties['enabled'] + -not $enabled -or [bool]$enabled.Value + } | + Where-Object { $_.Name -cmatch '^[a-z0-9-]+$' } | + Sort-Object @{ Expression = { & $priorityFor $_ } }, @{ Expression = { $_.Name } } | ForEach-Object { $_.Name } } + $registryParsed = $true } catch { - $sortedPresets = @() + $registryParsed = $false } } - 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) { + if (-not $registryParsed) { + $sortedPresets = Get-ChildItem -Path $presetsDir -Directory -ErrorAction SilentlyContinue | + Where-Object { $_.Name -cmatch '^[a-z0-9-]+$' } | + Sort-Object Name | + ForEach-Object { $_.Name } + } + + $pyCmd = @(Get-Python3Command) + foreach ($presetId in $sortedPresets) { # Read strategy and file path from preset manifest $strategy = 'replace' $manifestFilePath = '' + $manifestDeclared = $false $manifest = Join-Path $presetsDir "$presetId/preset.yml" - if ((Test-Path $manifest) -and $pyCmd) { + if ((Test-Path $manifest) -and -not $pyCmd) { + throw "Python 3 and PyYAML are required to resolve preset template composition" + } + if (Test-Path $manifest) { try { # Use Python to parse YAML manifest for strategy and file path $pyArgs = if ($pyCmd.Count -gt 1) { $pyCmd[1..($pyCmd.Count-1)] } else { @() } @@ -561,32 +629,71 @@ try: import yaml except ImportError: print('yaml_missing', file=sys.stderr) - print('replace\t') - sys.exit(0) + sys.exit(2) try: - with open(sys.argv[1]) as f: + with open(sys.argv[1], encoding='utf-8') as f: data = yaml.safe_load(f) - for t in data.get('provides', {}).get('templates', []): + if not isinstance(data, dict): + raise ValueError('manifest root must be a mapping') + if 'provides' not in data: + raise ValueError('manifest missing provides section') + provides = data['provides'] + if not isinstance(provides, dict): + raise ValueError('manifest provides must be a mapping') + if 'templates' not in provides: + raise ValueError('manifest provides missing templates') + templates = provides['templates'] + if not isinstance(templates, list): + raise ValueError('manifest templates must be a list') + if not templates: + raise ValueError('manifest must provide at least one template') + valid_types = ('template', 'command', 'script') + valid_strategies = ('replace', 'prepend', 'append', 'wrap') + for t in templates: + if not isinstance(t, dict): + raise ValueError('manifest template entries must be mappings') + if 'type' not in t or 'name' not in t or 'file' not in t: + raise ValueError('manifest template entry missing type, name, or file') + for field in ('type', 'name', 'file'): + if not isinstance(t[field], str): + raise ValueError('manifest template ' + field + ' must be a string') + if t['type'] not in valid_types: + raise ValueError('invalid manifest template type') + strategy = t.get('strategy', 'replace') + if not isinstance(strategy, str): + raise ValueError('manifest template strategy must be a string') + strategy = strategy.lower() + if strategy not in valid_strategies: + raise ValueError('invalid manifest template strategy') + if t['type'] == 'script' and strategy not in ('replace', 'wrap'): + raise ValueError('invalid manifest script strategy') + for t in templates: if t.get('name') == sys.argv[2] and t.get('type', 'template') == 'template': - print(t.get('strategy', 'replace') + '\t' + t.get('file', '')) + file_value = t.get('file', '') + strategy = t.get('strategy', 'replace') + print('found\t' + strategy + '\t' + file_value) sys.exit(0) - print('replace\t') -except Exception: - print('replace\t') + print('absent\treplace\t') +except Exception as exc: + print(f'manifest_invalid: {exc}', file=sys.stderr) + sys.exit(3) "@ $manifest $TemplateName 2>$pyStderrFile + if ($LASTEXITCODE -ne 0) { + if ($LASTEXITCODE -eq 2) { + throw "PyYAML is required to resolve preset template composition" + } + throw "Invalid preset manifest $manifest" + } 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 + $parts = $stratResult.Trim() -split "`t", 3 + $manifestDeclared = $parts[0] -eq 'found' + $strategy = $parts[1].ToLowerInvariant() + if ($parts.Count -gt 2 -and $parts[2]) { $manifestFilePath = $parts[2] } } Remove-Item $pyStderrFile -Force -ErrorAction SilentlyContinue } catch { - $strategy = 'replace' if ($pyStderrFile) { Remove-Item $pyStderrFile -Force -ErrorAction SilentlyContinue } + throw } } # Try manifest file path first, then convention path @@ -601,42 +708,45 @@ except Exception: $mf = Join-Path $presetsDir "$presetId/$manifestFilePath" if (Test-Path $mf) { $candidate = $mf } } - if (-not $candidate) { + if (-not $candidate -and -not $manifestDeclared) { $cf = Join-Path $presetsDir "$presetId/templates/$TemplateName.md" if (Test-Path $cf) { $candidate = $cf } + if (-not $candidate) { + $cf = Join-Path $presetsDir "$presetId/$TemplateName.md" + if (Test-Path $cf) { $candidate = $cf } + } } if ($candidate) { $layerPaths += $candidate $layerStrategies += $strategy + if ($strategy -eq 'replace') { + $effectiveBaseFound = $true + break + } } } - } 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 (-not $effectiveBaseFound -and (Test-Path $extDir)) { + foreach ($extensionId in Get-SortedExtensionIds -ExtensionsDir $extDir) { + $candidate = Join-Path $extDir "$extensionId/templates/$TemplateName.md" + if (-not (Test-Path $candidate)) { + $candidate = Join-Path $extDir "$extensionId/$TemplateName.md" + } if (Test-Path $candidate) { $layerPaths += $candidate $layerStrategies += 'replace' + $effectiveBaseFound = $true + break } } } # Priority 4: Core templates (always "replace") $core = Join-Path $base "$TemplateName.md" - if (Test-Path $core) { + if (-not $effectiveBaseFound -and (Test-Path $core)) { $layerPaths += $core $layerStrategies += 'replace' } @@ -646,7 +756,7 @@ except Exception: # 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) + return [System.IO.File]::ReadAllText($layerPaths[0], [System.Text.Encoding]::UTF8) } # Check if any layer uses a non-replace strategy @@ -656,7 +766,7 @@ except Exception: } if (-not $hasComposition) { - return (Get-Content $layerPaths[0] -Raw) + return [System.IO.File]::ReadAllText($layerPaths[0], [System.Text.Encoding]::UTF8) } # Find the effective base: scan from highest priority (index 0) downward @@ -668,14 +778,22 @@ except Exception: break } } - if ($baseIdx -lt 0) { return $null } + if ($baseIdx -lt 0) { + throw "Template '$TemplateName' has composing layers but no replace base" + } - $content = Get-Content $layerPaths[$baseIdx] -Raw + $content = [System.IO.File]::ReadAllText( + $layerPaths[$baseIdx], + [System.Text.Encoding]::UTF8 + ) for ($i = $baseIdx - 1; $i -ge 0; $i--) { $path = $layerPaths[$i] $strat = $layerStrategies[$i] - $layerContent = Get-Content $path -Raw + $layerContent = [System.IO.File]::ReadAllText( + $path, + [System.Text.Encoding]::UTF8 + ) switch ($strat) { 'replace' { $content = $layerContent } diff --git a/.specify/scripts/powershell/create-new-feature.ps1 b/.specify/scripts/powershell/create-new-feature.ps1 index 19cd1b0..cd8a2d2 100644 --- a/.specify/scripts/powershell/create-new-feature.ps1 +++ b/.specify/scripts/powershell/create-new-feature.ps1 @@ -7,13 +7,14 @@ param( [switch]$DryRun, [string]$ShortName, [Parameter()] - [long]$Number = 0, + [string]$Number = '', [switch]$Timestamp, [switch]$Help, [Parameter(Position = 0, ValueFromRemainingArguments = $true)] [string[]]$FeatureDescription ) $ErrorActionPreference = 'Stop' +$maxBranchLength = 244 # Show help if requested if ($Help) { @@ -21,10 +22,10 @@ if ($Help) { 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 Provide a custom short name (2-4 words) for the branch" - Write-Host " -Number N Specify branch number manually (overrides auto-detection)" + Write-Host " -DryRun Compute feature name and paths without creating directories or files" + Write-Host " -AllowExistingBranch Reuse an existing feature directory if it already exists" + Write-Host " -ShortName Provide a custom short name (2-4 words) for the feature" + Write-Host " -Number N Prefer a feature number (auto-corrected if its specs prefix exists)" Write-Host " -Timestamp Use timestamp prefix (YYYYMMDD-HHMMSS) instead of sequential numbering" Write-Host " -Help Show this help message" Write-Host "" @@ -67,111 +68,77 @@ function Get-HighestNumberFromSpecs { 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) +function Test-SpecPrefixInUse { + param( + [string]$SpecsDir, + [string]$FeatureNum + ) - [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 - } - } + if (-not (Test-Path -LiteralPath $SpecsDir -PathType Container)) { + return $false } - return $highest + + return $null -ne (Get-ChildItem -LiteralPath $SpecsDir -Directory -ErrorAction SilentlyContinue | + Where-Object { $_.Name -like "$FeatureNum-*" } | + Select-Object -First 1) } -function Get-HighestNumberFromBranches { - param() +function ConvertTo-AsciiLower { + param([string]$Name) - 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 + return [regex]::Replace($Name, '[A-Z]', { param($match) $match.Value.ToLowerInvariant() }) } -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 } - } +function ConvertTo-UnicodeWords { + param([string]$Name, [string]$Separator) + + $lowerName = ConvertTo-AsciiLower -Name $Name + return [regex]::Replace($lowerName, '[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\p{L}\p{Nd}]', { + param($match) + if ($match.Length -eq 2) { + $category = [System.Globalization.CharUnicodeInfo]::GetUnicodeCategory($match.Value, 0) + if ($category.ToString() -match '(Letter|DecimalDigitNumber)$') { + return $match.Value } } - } catch { - Write-Verbose "Could not query remote refs: $_" - } - return $highest + return $Separator + }) +} + +function ConvertTo-CleanBranchName { + param([string]$Name) + + return (ConvertTo-UnicodeWords -Name $Name -Separator '-') -replace '-{2,}', '-' -replace '^-', '' -replace '-$', '' } -# Return next available branch number. When SkipFetch is true, queries remotes -# via ls-remote (read-only) instead of fetching. -function Get-NextBranchNumber { +function Get-FittedBranchName { param( - [string]$SpecsDir, - [switch]$SkipFetch + [string]$FeatureNum, + [string]$BranchSuffix ) - 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 + $fittedName = "$FeatureNum-$BranchSuffix" + if ([System.Text.Encoding]::UTF8.GetByteCount($fittedName) -gt $maxBranchLength) { + $prefixLength = $FeatureNum.Length + 1 + $maxSuffixLength = $maxBranchLength - $prefixLength + $bytes = [System.Text.Encoding]::UTF8.GetBytes($BranchSuffix) + $bytesToUse = $maxSuffixLength + while ($bytesToUse -gt 0 -and ($bytes[$bytesToUse] -band 0xC0) -eq 0x80) { + $bytesToUse-- } - $highestBranch = Get-HighestNumberFromBranches + $truncatedSuffix = [System.Text.Encoding]::UTF8.GetString($bytes, 0, $bytesToUse) + $truncatedSuffix = $truncatedSuffix -replace '-$', '' + $fittedName = "$FeatureNum-$truncatedSuffix" } - # 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 '-$', '' + return $fittedName } -# Load common functions (includes Get-RepoRoot, Test-HasGit, Resolve-Template) +# Load common functions (includes Get-RepoRoot and Resolve-Template) . "$PSScriptRoot/common.ps1" -# Use common.ps1 functions which prioritize .specify over git +# Use common.ps1 functions which prioritize .specify $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' @@ -192,21 +159,27 @@ function Get-BranchName { 'want', 'need', 'add', 'get', 'set' ) - # Convert to lowercase and extract words (alphanumeric only) - $cleanName = $Description.ToLower() -replace '[^a-z0-9\s]', ' ' + # Lowercase ASCII and extract Unicode words, matching the shell variant. + $cleanName = ConvertTo-UnicodeWords -Name $Description -Separator ' ' $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 } + if ($stopWords -ccontains $word) { continue } - # Keep words that are length >= 3 OR appear as uppercase in original (likely acronyms) - if ($word.Length -ge 3) { + # Keep Unicode words even when short; ASCII words still need three + # characters or an uppercase acronym in the original. + if ($word.Length -ge 3 -or $word -match '[^\x00-\x7F]') { $meaningfulWords += $word - } elseif ($Description -match "\b$($word.ToUpper())\b") { - # Keep short words if they appear as uppercase in original (likely acronyms) + } elseif ($Description -cmatch "(?&1 | Out-String - if ($LASTEXITCODE -eq 0) { - $branchCreated = $true - } - } catch { - $branchCreateError = $_.Exception.Message + if ((Test-Path -LiteralPath $featureDir -PathType Container) -and -not $AllowExistingBranch) { + if ($Timestamp) { + Write-Error "Error: Feature directory '$featureDir' already exists. Rerun to get a new timestamp or use a different -ShortName." + } else { + Write-Error "Error: Feature directory '$featureDir' already exists. Please use a different feature name or specify a different number with -Number." } + exit 1 + } - 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" + $needsSpec = -not (Test-Path -PathType Leaf $specFile) + $content = $null + if ($needsSpec) { + $content = Resolve-TemplateContent -TemplateName 'spec-template' -RepoRoot $repoRoot } 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) + if ($needsSpec) { + if ($null -ne $content) { $utf8NoBom = New-Object System.Text.UTF8Encoding($false) [System.IO.File]::WriteAllText($specFile, $content, $utf8NoBom) } else { + # Match the bash twin (create-new-feature.sh): warn on stderr that no + # spec template was found before creating an empty spec file, so the + # missing-template signal is not silently swallowed on Windows. + [Console]::Error.WriteLine("Warning: Spec template not found; created empty spec file") New-Item -ItemType File -Path $specFile -Force | Out-Null } } - # Set the SPECIFY_FEATURE environment variable for the current session + # Persist to .specify/feature.json so downstream commands can find the + # feature, unless the orchestrator opted out via SPECIFY_FEATURE_NO_PERSIST (#4129). + if ($env:SPECIFY_FEATURE_NO_PERSIST -ne '1' -and $env:SPECIFY_FEATURE_NO_PERSIST -ne 'true') { + Save-FeatureJson -RepoRoot $repoRoot -FeatureDirectory $featureDir + } + + # Set environment variables for the current session $env:SPECIFY_FEATURE = $branchName + $env:SPECIFY_FEATURE_DIRECTORY = $featureDir + + $quotedBranchName = "'" + $branchName.Replace("'", "''") + "'" + $quotedFeatureDir = "'" + $featureDir.Replace("'", "''") + "'" + $featureAssignment = '$env:SPECIFY_FEATURE = ' + $quotedBranchName + $directoryAssignment = '$env:SPECIFY_FEATURE_DIRECTORY = ' + $quotedFeatureDir + [Console]::Error.WriteLine("# To persist: $featureAssignment") + [Console]::Error.WriteLine("# $directoryAssignment") } if ($Json) { @@ -368,7 +341,6 @@ if ($Json) { BRANCH_NAME = $branchName SPEC_FILE = $specFile FEATURE_NUM = $featureNum - HAS_GIT = $hasGit } if ($DryRun) { $obj | Add-Member -NotePropertyName 'DRY_RUN' -NotePropertyValue $true @@ -378,8 +350,8 @@ if ($Json) { 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" + Write-Output "# To persist in your shell: $featureAssignment" + Write-Output "# $directoryAssignment" } } diff --git a/.specify/scripts/powershell/resolve-template.ps1 b/.specify/scripts/powershell/resolve-template.ps1 new file mode 100644 index 0000000..70aee0a --- /dev/null +++ b/.specify/scripts/powershell/resolve-template.ps1 @@ -0,0 +1,38 @@ +#!/usr/bin/env pwsh + +param( + [Parameter(Position=0)] + [string]$TemplateName, + [switch]$Json, + [switch]$Help +) + +$ErrorActionPreference = 'Stop' + +if ($Help) { + Write-Output "Usage: resolve-template.ps1 [-Json]" + exit 0 +} + +if (-not $TemplateName) { + [Console]::Error.WriteLine("ERROR: Template name is required") + exit 1 +} + +. "$PSScriptRoot/common.ps1" + +$repoRoot = Get-RepoRoot +$templateContent = Resolve-TemplateContent -TemplateName $TemplateName -RepoRoot $repoRoot +if ($null -eq $templateContent) { + [Console]::Error.WriteLine("ERROR: Could not resolve required $TemplateName from the template override stack for $repoRoot") + exit 1 +} + +if ($Json) { + [PSCustomObject]@{ + TEMPLATE_NAME = $TemplateName + TEMPLATE_CONTENT = $templateContent + } | ConvertTo-Json -Compress +} else { + [Console]::Out.Write($templateContent) +} diff --git a/.specify/scripts/powershell/setup-plan.ps1 b/.specify/scripts/powershell/setup-plan.ps1 index d9eecdf..036a54e 100644 --- a/.specify/scripts/powershell/setup-plan.ps1 +++ b/.specify/scripts/powershell/setup-plan.ps1 @@ -4,7 +4,10 @@ [CmdletBinding()] param( [switch]$Json, - [switch]$Help + [switch]$Help, + # Capture extra positional arguments to match Bash/Python behavior. + [Parameter(ValueFromRemainingArguments = $true)] + [string[]]$RemainingArgs ) $ErrorActionPreference = 'Stop' @@ -17,17 +20,19 @@ if ($Help) { exit 0 } +if ($RemainingArgs.Count -gt 0) { + [Console]::Error.WriteLine("ERROR: Unknown option '$($RemainingArgs[0])'") + exit 1 +} + # 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 - } +$paths = Get-FeaturePathsEnv -ReturnNullOnError +if (-not $paths) { + [Console]::Error.WriteLine("ERROR: Failed to resolve feature paths") + exit 1 } # Ensure the feature directory exists @@ -41,14 +46,26 @@ if (Test-Path $paths.IMPL_PLAN -PathType Leaf) { 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) + $content = Resolve-TemplateContent -TemplateName 'plan-template' -RepoRoot $paths.REPO_ROOT + if ($null -ne $content) { $utf8NoBom = New-Object System.Text.UTF8Encoding($false) [System.IO.File]::WriteAllText($paths.IMPL_PLAN, $content, $utf8NoBom) + # Emit the copy status like the bash twin (setup-plan.sh); route to stderr + # in -Json mode so stdout stays pure JSON, matching the sibling messages. + if ($Json) { + [Console]::Error.WriteLine("Copied plan template to $($paths.IMPL_PLAN)") + } else { + Write-Output "Copied plan template to $($paths.IMPL_PLAN)" + } } else { - Write-Warning "Plan template not found" + # Match the bash twin's wording and stream routing (stderr in -Json so + # stdout stays pure JSON, stdout otherwise), consistent with the sibling + # "Copied plan template" message above. + if ($Json) { + [Console]::Error.WriteLine("Warning: Plan template not found") + } else { + Write-Output "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 } @@ -56,18 +73,16 @@ if (Test-Path $paths.IMPL_PLAN -PathType Leaf) { # Output results if ($Json) { - $result = [PSCustomObject]@{ + $result = [PSCustomObject]@{ FEATURE_SPEC = $paths.FEATURE_SPEC IMPL_PLAN = $paths.IMPL_PLAN - SPECS_DIR = $paths.FEATURE_DIR + FEATURE_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 "FEATURE_DIR: $($paths.FEATURE_DIR)" Write-Output "BRANCH: $($paths.CURRENT_BRANCH)" - Write-Output "HAS_GIT: $($paths.HAS_GIT)" } diff --git a/.specify/scripts/powershell/setup-tasks.ps1 b/.specify/scripts/powershell/setup-tasks.ps1 index 7d2c36c..46b1bf9 100644 --- a/.specify/scripts/powershell/setup-tasks.ps1 +++ b/.specify/scripts/powershell/setup-tasks.ps1 @@ -3,27 +3,33 @@ [CmdletBinding()] param( [switch]$Json, - [switch]$Help + [switch]$Help, + [Parameter(ValueFromRemainingArguments = $true)] + [string[]]$RemainingArgs ) $ErrorActionPreference = 'Stop' +# Help wins over unknown-argument validation to match the Bash/Python +# variants, which stop at --help and exit 0. if ($Help) { Write-Output "Usage: setup-tasks.ps1 [-Json] [-Help]" exit 0 } +if ($RemainingArgs.Count -gt 0) { + [Console]::Error.WriteLine("ERROR: Unknown option '$($RemainingArgs[0])'") + exit 1 +} + # 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 - } +# Get feature paths +$paths = Get-FeaturePathsEnv -ReturnNullOnError +if (-not $paths) { + [Console]::Error.WriteLine("ERROR: Failed to resolve feature paths") + exit 1 } if (-not (Test-Path $paths.IMPL_PLAN -PathType Leaf)) { @@ -51,12 +57,17 @@ 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.") +$tasksTemplateContent = Resolve-TemplateContent -TemplateName 'tasks-template' -RepoRoot $paths.REPO_ROOT +if ($null -eq $tasksTemplateContent) { + [Console]::Error.WriteLine("ERROR: Could not resolve required tasks-template from the template override stack for $($paths.REPO_ROOT)") + [Console]::Error.WriteLine("Template 'tasks-template' was not found in any supported location (overrides, presets, extensions, or shared core). Add an override at .specify/templates/overrides/tasks-template.md, or run 'specify init' / reinstall shared infra to restore the core .specify/templates/tasks-template.md template.") exit 1 } -$tasksTemplate = (Resolve-Path -LiteralPath $tasksTemplate).Path +if ($tasksTemplate -and (Test-Path -LiteralPath $tasksTemplate -PathType Leaf)) { + $tasksTemplate = (Resolve-Path -LiteralPath $tasksTemplate).Path +} else { + $tasksTemplate = '' +} # Output results if ($Json) { @@ -64,13 +75,19 @@ if ($Json) { FEATURE_DIR = $paths.FEATURE_DIR AVAILABLE_DOCS = $docs TASKS_TEMPLATE = $tasksTemplate + TASKS_TEMPLATE_CONTENT = $tasksTemplateContent } | 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 + # These helpers report their line with Write-Output and ALSO return a + # bool, both on the Success stream, so 'Out-Null' discarded the report + # line along with the return value and left AVAILABLE_DOCS empty. Drop + # only the boolean so the per-document lines reach stdout like the + # bash and Python twins. + Test-FileExists -Path $paths.RESEARCH -Description 'research.md' | Where-Object { $_ -isnot [bool] } + Test-FileExists -Path $paths.DATA_MODEL -Description 'data-model.md' | Where-Object { $_ -isnot [bool] } + Test-DirHasFiles -Path $paths.CONTRACTS_DIR -Description 'contracts/' | Where-Object { $_ -isnot [bool] } + Test-FileExists -Path $paths.QUICKSTART -Description 'quickstart.md' | Where-Object { $_ -isnot [bool] } } diff --git a/.specify/templates/checklist-template.md b/.specify/templates/checklist-template.md index c4aa166..c4c4ffb 100644 --- a/.specify/templates/checklist-template.md +++ b/.specify/templates/checklist-template.md @@ -4,18 +4,20 @@ **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. +**Note**: This custom checklist is generated by the `/speckit-checklist` command based on feature context and requirements. +**Review Ownership**: This checklist is a reviewer-owned requirements-quality review artifact. Mark an item `[x]` only when the reviewer determines the requirements-quality criterion is satisfied. +**Marker Semantics**: `[x]` means the criterion has been reviewed and satisfied for requirements quality. It does not mean implementation work is complete. - @@ -34,7 +36,10 @@ ## Notes -- Check items off as completed: `[x]` +- Mark items `[x]` only after review confirms the requirement-quality criterion is satisfied +- Leave items unchecked when they still require clarification, correction, or reviewer evaluation +- `/speckit-implement` reads checklist checkbox state as a gate and must not modify markers +- `checklists/requirements.md` has a separate built-in lifecycle maintained by `/speckit-specify` and `/speckit-clarify` - Add comments or findings inline - Link to relevant resources or documentation - Items are numbered sequentially for easy reference diff --git a/.specify/templates/plan-template.md b/.specify/templates/plan-template.md index 92b96c7..be1aa88 100644 --- a/.specify/templates/plan-template.md +++ b/.specify/templates/plan-template.md @@ -4,7 +4,7 @@ **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. +**Note**: This template is filled in by the `/speckit-plan` command; its definition describes the execution workflow. ## Summary diff --git a/CONTEXT.md b/CONTEXT.md index b253c0d..3d842e3 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -55,3 +55,23 @@ _Avoid_: Due time (that's the concept; Scheduled For is the field name) **Reminder Time**: A time-of-day stored on a Medication (`ppa_remindertime`, `HH:mm` format). Determines when a Dose becomes Overdue and is copied to Scheduled For when logging. _Avoid_: Due time, alarm + +**Past Due**: +A Medication with a Missed Intake from an earlier day, shown on its card. Stays until the intake is logged as Taken or Skipped. Never persisted in Dataverse. +_Avoid_: Overdue — Overdue is a Dose due today whose Reminder Time has passed + +**Next Intake**: +The date a Medication is next due. For an Injection it rolls forward from the last Taken or Skipped Intake Log; for every other method it follows the fixed schedule. +_Avoid_: Next dose, due date + +**Missed Intake**: +A due date that ended with no Taken or Skipped Intake Log. Derived from the schedule, never stored. Distinct from the Missed status the user records on an Intake Log. +_Avoid_: Missed (alone) — that is the Intake Log status + +**Follow-up**: +A reminder on the 1st, 3rd, 5th or 7th day after a Missed Intake. Stops after the 7th day, or as soon as the intake is logged. +_Avoid_: Nag, repeat reminder + +**Reminder Run**: +One row per day (`ppa_reminderrun`) recording the daily check's outcome: Started, Sent, Nothing To Send or Failed. Also the guard that keeps the check to one reminder message a day. +_Avoid_: Reminder log, run history (that is Power Automate's own record) diff --git a/README.md b/README.md index 870ef63..d2af2fe 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,8 @@ MedTrack is a **React 19 + TypeScript Power Apps Code App** backed by **Microsof | **Log Intake** | Segmented Taken / Skipped / Missed control; interactive body map for injection sites | | **Calendar** | Month view with colour-coded dose history; tap any day to log or edit | | **Analytics** | Adherence trend charts across 3-month, 6-month, and 1-year windows; CSV export | -| **Medications** | Add, edit, deactivate, and archive medications; Active / Inactive grouping | +| **Medications** | Add, edit, deactivate, and archive medications; Active / Inactive grouping; last taken and next intake on every card | +| **Daily reminder** | One Teams message a day listing what is due, with follow-ups for a week after a missed intake | **Adherence is computed from first principles** — `Taken ÷ non-Skipped`. *Skipped* is deliberately neutral: a clinical choice that doesn't count for or against the user. That's an [Architecture Decision Record](docs/adr/0001-skipped-doses-neutral.md), not an accident. @@ -91,6 +92,42 @@ Manual promotion --- +## Daily reminder + +A scheduled cloud flow, **MedTrack – Daily Reminder**, checks once a day at local midnight and posts one message in Microsoft Teams, as a chat from the Flow bot (shown as "Workflows"). With Teams on your phone, that is a notification: + +- **Due today** — every Active Medication due that day. Injections count from the last dose; everything else follows its fixed schedule. +- **Follow-ups** — a Medication whose intake was missed, on the 1st, 3rd, 5th and 7th day afterwards. Logging it as Taken or Skipped stops the follow-ups. + +The first line holds counts only ("MedTrack: 2 due today, 1 follow-up"), so a lock-screen preview shows no Medication name. The message ends with an "Open MedTrack" link to the app. + +Nothing due and nothing missed means no message. Switching a Medication to Inactive is the only reminder switch. The flow reads Medications and Intake Logs and never changes them. The rules are the same ones the Medications page uses; both are tested against one decision table in [`contracts/schedule-rules.contract.md`](specs/004-schedule-page-reminders/contracts/schedule-rules.contract.md). + +### One-time setup per environment + +1. Create a **Microsoft Dataverse** connection and a **Microsoft Teams** connection, both signed in as the person whose Medications are tracked. Share each with the deployment service principal as "Can use". +2. On the GitHub Environment (`dev`, `production`), set the variables `PP_CONN_DATAVERSE_ID`, `PP_CONN_TEAMS_ID` and `REMINDER_TIME_ZONE` (a Windows time zone name such as `Eastern Standard Time`). The app link is built from `PP_ENVIRONMENT_ID` and `PP_APP_ID`, which the pipeline already uses. +3. Deploy. The deploy binds the connections, sets the time zone and the app link, and turns the flow on. Then open the flow's Details page and confirm it is not reported as unlicensed: the service principal owns the flow and the Dataverse connector is premium. +4. Install Microsoft Teams on your phone, sign in with the same account, and allow notifications. + +### No address is stored anywhere + +The message goes to the user behind the Dataverse connection. The flow reads that account from Dataverse at run time, so there is no reminder address to configure, and none in this repository, in the solution or in GitHub. + +Earlier versions of this feature sent email, first through the Mail connector and then through Office 365 Outlook. The checks that kept an address out of this public repository are still in place: + +- CI rejects a committed email address (gitleaks rule `email-address`) and an environment variable value in `solution/src`. The solution holds variable **definitions** only. +- The production promotion checks the exported solution zip again before it is uploaded as an artifact. + +### Good to know + +- **Teams holds back phone notifications while you are active in Teams on a computer.** The message is in the chat either way. +- **A failed check notifies nobody.** Power Automate sends failure notices to the flow's owner, and the owner is a service principal. The record of each day is a row in the **Reminder Run** table (`ppa_reminderrun`) — outcome Sent, Nothing To Send or Failed, with the step that failed — and the flow's run history. A day with no row at all means the flow could not reach Dataverse. +- **At most one message a day.** A second run on the same day stops at the Reminder Run row. A failed run is retried on the hour until 03:00 local time. +- **Testing by hand works only in the first four hours of the local day.** The flow's Run button obeys the same time gate as the schedule. + +--- + ## Project structure ``` @@ -98,7 +135,7 @@ src/ ├── components/ # UI components (dashboard, calendar, analytics, medications, intake) ├── generated/ # Auto-generated Dataverse service layer (the only data access path) ├── hooks/ # TanStack Query hooks (use-medications, use-intake-logs, use-adherence…) -├── lib/ # Pure domain logic (adherence.ts, date-utils.ts, injection-sites.ts…) +├── lib/ # Pure domain logic (adherence.ts, schedule.ts, date-utils.ts, injection-sites.ts…) ├── pages/ # Route-level page components ├── stores/ # Zustand UI state (log-intake-store, ui-store) └── mocks/ # MSW mock service layer for testing @@ -106,6 +143,7 @@ src/ specs/ # Spec Kit artifacts — the paper trail for every feature docs/adr/ # Architecture Decision Records solution/ # Dataverse schema as an unpacked, source-controlled solution +scripts/reminder/ # Scripts the owner runs by hand: reminder schema, test scenarios .github/workflows/ # CI/CD pipeline ``` diff --git a/scripts/ci/assert-no-envvar-values.ps1 b/scripts/ci/assert-no-envvar-values.ps1 new file mode 100644 index 0000000..1de6c98 --- /dev/null +++ b/scripts/ci/assert-no-envvar-values.ps1 @@ -0,0 +1,117 @@ +#Requires -Version 7.0 +<# +Fails when solution content could publish an environment's settings or an address +(specs/004-schedule-page-reminders/contracts/privacy-and-deployment.contract.md): + + 1. any environmentvariablevalues.json file -- environment variable *values* + never belong in the solution, only their definitions; or + 2. any file containing an email address outside the allowlist. + +Two modes: + -Path the unpacked solution source (solution/src), run on every + pull request in ci.yml + -Zip an exported solution zip, run in promote-prod.yml before the + artifact is uploaded -- the one automated step that publishes + solution content + +On failure only the offending file path is printed, never the matched text: +this script's output lands in public workflow logs. + +The address pattern is the one in the `email-address` rule of .gitleaks.toml; +keep the two in step. The allowlist here is deliberately shorter: the two +documentation-only entries in .gitleaks.toml have no place in solution content. +#> +[CmdletBinding(DefaultParameterSetName = 'Path')] +param( + [Parameter(Mandatory, ParameterSetName = 'Path')] + [string]$Path, + + [Parameter(Mandatory, ParameterSetName = 'Zip')] + [string]$Zip +) + +$ErrorActionPreference = 'Stop' + +$valueFileName = 'environmentvariablevalues.json' +$emailPattern = [regex]'[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}' + +# Addresses that may be committed, and strings that only look like addresses. +$allowed = @( + [regex]'(?i)@example\.(com|org)$' + [regex]'(?i)@users\.noreply\.github\.com$' + [regex]'(?i)^noreply@anthropic\.com$' + # OData annotations: ppa_Medication@odata.bind, x@OData.Community.Display.V1.FormattedValue + [regex]'(?i)@odata\.' + # x@Microsoft.Dynamics.CRM.lookuplogicalname + [regex]'@Microsoft\.' + [regex]'^git@github\.com$' +) + +function Test-HasDisallowedAddress { + param([string]$Text) + foreach ($match in $emailPattern.Matches($Text)) { + $candidate = $match.Value + if (-not ($allowed | Where-Object { $_.IsMatch($candidate) })) { return $true } + } + return $false +} + +# Returns the reasons a file fails, given its display path and a way to read it. +function Get-Problems { + param([string]$DisplayPath, [string]$FileName, [scriptblock]$ReadText) + $problems = @() + if ($FileName -ieq $valueFileName) { + $problems += "${DisplayPath}: environment variable value file" + } + if (Test-HasDisallowedAddress (& $ReadText)) { + $problems += "${DisplayPath}: contains an email address outside the allowlist" + } + return $problems +} + +$problems = @() +$scanned = 0 + +if ($PSCmdlet.ParameterSetName -eq 'Path') { + if (-not (Test-Path $Path -PathType Container)) { + throw "Directory not found: $Path" + } + $root = (Resolve-Path $Path).Path + foreach ($file in Get-ChildItem -Path $root -Recurse -File -Force) { + $relative = [IO.Path]::GetRelativePath($root, $file.FullName).Replace('\', '/') + $fullName = $file.FullName + $problems += Get-Problems -DisplayPath $relative -FileName $file.Name -ReadText { [IO.File]::ReadAllText($fullName) } + $scanned++ + } + $target = $Path +} else { + if (-not (Test-Path $Zip -PathType Leaf)) { + throw "Zip file not found: $Zip" + } + Add-Type -AssemblyName System.IO.Compression.FileSystem + $archive = [IO.Compression.ZipFile]::OpenRead((Resolve-Path $Zip).Path) + try { + foreach ($entry in $archive.Entries) { + if ($entry.FullName.EndsWith('/')) { continue } # directory entry + $current = $entry + $problems += Get-Problems -DisplayPath $entry.FullName -FileName $entry.Name -ReadText { + $reader = [IO.StreamReader]::new($current.Open()) + try { $reader.ReadToEnd() } finally { $reader.Dispose() } + } + $scanned++ + } + } finally { + $archive.Dispose() + } + $target = $Zip +} + +if ($problems.Count -gt 0) { + Write-Host "Solution content check FAILED for $target ($($problems.Count) problem(s)):" + foreach ($problem in $problems) { Write-Host " - $problem" } + Write-Host "Environment variable values and email addresses must not be part of the solution." + Write-Host "See specs/004-schedule-page-reminders/contracts/privacy-and-deployment.contract.md." + exit 1 +} + +Write-Host "Solution content check passed for $target ($scanned file(s) scanned)." diff --git a/scripts/ci/render-deployment-settings.ps1 b/scripts/ci/render-deployment-settings.ps1 new file mode 100644 index 0000000..07f5da8 --- /dev/null +++ b/scripts/ci/render-deployment-settings.ps1 @@ -0,0 +1,61 @@ +#Requires -Version 7.0 +<# +Renders solution/deployment-settings.json from +solution/deployment-settings.template.json by substituting its placeholders +with values from environment variables: + + __CONN_DATAVERSE_ID__ PP_CONN_DATAVERSE_ID + __CONN_TEAMS_ID__ PP_CONN_TEAMS_ID + __REMINDER_TIME_ZONE__ REMINDER_TIME_ZONE + __ENVIRONMENT_ID__ PP_ENVIRONMENT_ID (with __APP_ID__, the app link + __APP_ID__ PP_APP_ID in the reminder) + +Run this immediately before the solution import in a deploy job, and pass the +rendered file to the import. + +The rendered file is git-ignored. No value is printed. + +The reminder is a Teams message to the user behind the Dataverse connection, +so no address is among these values (see +specs/004-schedule-page-reminders/contracts/privacy-and-deployment.contract.md). +#> + +$ErrorActionPreference = 'Stop' + +$repoRoot = Resolve-Path (Join-Path $PSScriptRoot '../..') +$templatePath = Join-Path $repoRoot 'solution/deployment-settings.template.json' +$outputPath = Join-Path $repoRoot 'solution/deployment-settings.json' + +if (-not (Test-Path $templatePath)) { + throw "Template not found at $templatePath" +} + +$placeholders = [ordered]@{ + '__CONN_DATAVERSE_ID__' = 'PP_CONN_DATAVERSE_ID' + '__CONN_TEAMS_ID__' = 'PP_CONN_TEAMS_ID' + '__REMINDER_TIME_ZONE__' = 'REMINDER_TIME_ZONE' + '__ENVIRONMENT_ID__' = 'PP_ENVIRONMENT_ID' + '__APP_ID__' = 'PP_APP_ID' +} + +$missing = $placeholders.Values | Where-Object { [string]::IsNullOrWhiteSpace((Get-Item -Path "env:$_" -ErrorAction SilentlyContinue).Value) } +if ($missing.Count -gt 0) { + throw "Missing required variable(s): $($missing -join ', '). Set them as GitHub Environment variables for the target stage." +} + +$content = Get-Content -Path $templatePath -Raw +foreach ($placeholder in $placeholders.Keys) { + $value = (Get-Item -Path "env:$($placeholders[$placeholder])").Value.Trim() + # JSON-escape the value so it cannot break out of its string. + $escaped = ($value | ConvertTo-Json -Compress) + $content = $content.Replace($placeholder, $escaped.Substring(1, $escaped.Length - 2)) +} + +if ($content -match '__[A-Z_]+__') { + throw "The rendered settings still contain an unresolved placeholder. Check $templatePath against this script." +} +# Fail here, not at import time, if the result is not valid JSON. +$null = $content | ConvertFrom-Json + +Set-Content -Path $outputPath -Value $content -NoNewline +Write-Host "Rendered solution/deployment-settings.json ($($placeholders.Count) values substituted)." diff --git a/scripts/deploy/configure-reminder-flow.ps1 b/scripts/deploy/configure-reminder-flow.ps1 new file mode 100644 index 0000000..5cc0f62 --- /dev/null +++ b/scripts/deploy/configure-reminder-flow.ps1 @@ -0,0 +1,111 @@ +#Requires -Version 7.0 +<# +Confirms the "MedTrack – Daily Reminder" cloud flow is in place after a +solution import: it exists, the deployment service principal owns it, and it +is turned on. Turns it on when it is off. Changes no ownership. + +Run after "Publish solution customizations" in a deploy job. A solution +import can leave a flow turned off (for example when a connection reference +was not bound), and a flow that is off sends no reminders without any error +anywhere -- so this step fails the deploy instead. + +Idempotent. Authenticates independently via OAuth client-credentials rather +than depending on a `pac auth create` CLI profile, which was found not to be +reliably present across steps. Prints no secrets. + +Required environment variables: + PP_CLIENT_ID Service principal application (client) ID + PP_CLIENT_SECRET Service principal client secret + PP_TENANT_ID Entra tenant ID + PP_ENVIRONMENT_URL Target Power Platform environment URL +#> +param( + # The flow's unique name in Dataverse (workflow.uniquename). + [string]$FlowUniqueName = 'ppa_MedTrackDailyReminder' +) + +$ErrorActionPreference = 'Stop' + +$required = @('PP_CLIENT_ID', 'PP_CLIENT_SECRET', 'PP_TENANT_ID', 'PP_ENVIRONMENT_URL') +$missing = $required | Where-Object { [string]::IsNullOrWhiteSpace((Get-Item -Path "env:$_" -ErrorAction SilentlyContinue).Value) } +if ($missing.Count -gt 0) { + throw "Missing required Power Platform environment variable(s): $($missing -join ', ')." +} + +$envUrl = $env:PP_ENVIRONMENT_URL.TrimEnd('/') +$apiBase = "$envUrl/api/data/v9.2" + +Write-Host "Acquiring Dataverse access token for $envUrl..." +$tokenResponse = Invoke-RestMethod -Method Post ` + -Uri "https://login.microsoftonline.com/$($env:PP_TENANT_ID)/oauth2/v2.0/token" ` + -ContentType 'application/x-www-form-urlencoded' ` + -Body @{ + grant_type = 'client_credentials' + client_id = $env:PP_CLIENT_ID + client_secret = $env:PP_CLIENT_SECRET + scope = "$envUrl/.default" + } + +$headers = @{ + Authorization = "Bearer $($tokenResponse.access_token)" + 'OData-Version' = '4.0' + Accept = 'application/json' +} + +# HTTP status + Dataverse error message from a failed request. +function Get-SafeErrorReason { + param($ErrorRecord) + $status = $ErrorRecord.Exception.Response.StatusCode + $reason = $ErrorRecord.Exception.Message + if ($ErrorRecord.ErrorDetails.Message) { + try { + $parsed = $ErrorRecord.ErrorDetails.Message | ConvertFrom-Json + if ($parsed.error.message) { $reason = $parsed.error.message } + } catch { + # Response body wasn't JSON; fall back to the exception message. + } + } + return "[$status] $reason" +} + +# The service principal's own application user in this environment. +$servicePrincipalUserId = (Invoke-RestMethod -Method Get -Uri "$apiBase/WhoAmI" -Headers $headers).UserId + +# category 5 = modern (cloud) flow +$flowQuery = "$apiBase/workflows?" + '$select=workflowid,name,statecode,_ownerid_value&$filter=' + "category eq 5 and uniquename eq '$FlowUniqueName'" +$flows = @((Invoke-RestMethod -Method Get -Uri $flowQuery -Headers $headers).value) + +if ($flows.Count -eq 0) { + throw "Cloud flow '$FlowUniqueName' was not found in $envUrl. The solution import did not bring it in." +} +if ($flows.Count -gt 1) { + throw "Found $($flows.Count) cloud flows with the unique name '$FlowUniqueName'; expected exactly one." +} +$flow = $flows[0] +Write-Host "Found flow '$($flow.name)'." + +if ($flow._ownerid_value -ne $servicePrincipalUserId) { + throw "Flow '$($flow.name)' is not owned by the deployment service principal. Ownership is not changed by this script; reassign it deliberately or re-import the solution as the service principal." +} +Write-Host "Owner is the deployment service principal." + +# statecode 1 = Activated (on), 0 = Draft (off) +if ($flow.statecode -eq 1) { + Write-Host "Flow is already on." + return +} + +Write-Host "Flow is off -- turning it on..." +try { + Invoke-RestMethod -Method Patch -Uri "$apiBase/workflows($($flow.workflowid))" ` + -Headers ($headers + @{ 'Content-Type' = 'application/json; charset=utf-8' }) ` + -Body (@{ statecode = 1; statuscode = 2 } | ConvertTo-Json -Compress) | Out-Null +} catch { + throw "Could not turn the flow on: $(Get-SafeErrorReason $_). Check that both connection references are bound and that the connections are shared with the service principal." +} + +$stateQuery = "$apiBase/workflows($($flow.workflowid))" + '?$select=statecode' +if ((Invoke-RestMethod -Method Get -Uri $stateQuery -Headers $headers).statecode -ne 1) { + throw "The flow did not stay on after being activated." +} +Write-Host "Flow is on." diff --git a/scripts/reminder/assert-reminder-run.ps1 b/scripts/reminder/assert-reminder-run.ps1 new file mode 100644 index 0000000..1b4c93a --- /dev/null +++ b/scripts/reminder/assert-reminder-run.ps1 @@ -0,0 +1,175 @@ +#Requires -Version 7.0 +<# +.SYNOPSIS + Checks today's Reminder Run row against the outcome and the Medications + the daily reminder was expected to list. + +.DESCRIPTION + Local developer use -- the acceptance check for the "MedTrack – Daily + Reminder" flow. Reads the ppa_reminderrun row whose ppa_name is today's + local date, parses ppa_summary + + Due: ; ; … + Follow-up: ; ; … + + (a group with no entries is written as "–"), and compares the decision-table + ids at the start of each name ("S01 Daily pill…" → S01) with the expected + ids. Exits 1 with a diff when anything differs. + + Medications that are not from the seed set (no S prefix) are reported + and ignored, so the check also works in an environment that holds other + Medications. Pass -Strict to fail when any are listed. + +.PARAMETER EnvironmentUrl + Power Platform environment URL. Defaults to MedTrackDev. + +.PARAMETER TimeZone + Time zone that defines "today" (Windows or IANA name). Defaults to this + machine's zone; must match ppa_ReminderTimeZone. + +.PARAMETER ExpectOutcome + Started, Sent, NothingToSend or Failed. Defaults to Sent. + +.PARAMETER ExpectDue + Decision-table ids expected under "Due", e.g. S01,S03,S04. + +.PARAMETER ExpectFollowUp + Decision-table ids expected under "Follow-up". + +.EXAMPLE + pwsh scripts/reminder/assert-reminder-run.ps1 -ExpectOutcome Sent -ExpectDue S01,S03,S04,S12,S17,S18,S25,S27,S29 -ExpectFollowUp S06,S08,S09,S13,S21,S23,S26 + pwsh scripts/reminder/assert-reminder-run.ps1 -ExpectOutcome NothingToSend +#> +param( + [string]$EnvironmentUrl = 'https://org9c89b427.crm.dynamics.com', + [string]$TimeZone, + [ValidateSet('Started', 'Sent', 'NothingToSend', 'Failed')] + [string]$ExpectOutcome = 'Sent', + [string[]]$ExpectDue = @(), + [string[]]$ExpectFollowUp = @(), + [switch]$Strict +) + +$ErrorActionPreference = 'Stop' +$envUrl = $EnvironmentUrl.TrimEnd('/') +$apiBase = "$envUrl/api/data/v9.2" + +$OutcomeNames = @{ 894250000 = 'Started'; 894250001 = 'Sent'; 894250002 = 'NothingToSend'; 894250003 = 'Failed' } + +# `pwsh file.ps1 -ExpectDue S01,S03` passes one string, not an array, when it +# is started from a non-PowerShell shell; accept both forms. +function Split-Ids { + param([string[]]$Values) + return @($Values | ForEach-Object { $_ -split ',' } | ForEach-Object { $_.Trim() } | Where-Object { $_ } | Sort-Object -Unique) +} +# @(...) keeps an empty result an empty array; a function returning no items yields $null. +$dueExpected = @(Split-Ids $ExpectDue) +$followUpExpected = @(Split-Ids $ExpectFollowUp) + +$zone = if ($TimeZone) { [TimeZoneInfo]::FindSystemTimeZoneById($TimeZone) } else { [TimeZoneInfo]::Local } +$today = [TimeZoneInfo]::ConvertTimeFromUtc([DateTime]::UtcNow, $zone).ToString('yyyy-MM-dd') + +$token = az account get-access-token --resource "$envUrl/" --query accessToken -o tsv 2>&1 +if (-not $token -or $token -like '*ERROR*') { + throw "Token acquisition failed. Run 'az login' and try again. Detail: $token" +} +$headers = @{ + Authorization = "Bearer $token" + 'OData-Version' = '4.0' + Accept = 'application/json' +} + +$uri = "$apiBase/ppa_reminderruns?" + '$select=ppa_name,ppa_outcome,ppa_duecount,ppa_followupcount,ppa_summary,ppa_errorstep,ppa_attempts&$filter=' + "ppa_name eq '$today'" +$rows = @((Invoke-RestMethod -Method Get -Uri $uri -Headers $headers).value) + +Write-Host "" +Write-Host "Reminder Run for $today ($($zone.Id)) in $envUrl" +Write-Host "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" + +if ($rows.Count -eq 0) { + Write-Host "✗ No Reminder Run row for $today. The flow has not run, or could not reach Dataverse." + exit 1 +} +$run = $rows[0] + +# "Due: a; b" → @('a', 'b'); "Due: –" → @() +function Get-Group { + param([string]$Summary, [string]$Label) + foreach ($line in ($Summary -split "\r?\n")) { + if ($line -match "^\s*$([regex]::Escape($Label)):\s*(.*)$") { + $value = $Matches[1].Trim() + if ($value -in @('', '–', '-')) { return @() } + return @($value -split ';' | ForEach-Object { $_.Trim() } | Where-Object { $_ }) + } + } + return @() +} + +# Names from the seed set start with their decision-table id. +function Split-Names { + param([string[]]$Names) + $ids = @() + $other = @() + foreach ($name in $Names) { + if ($name -match '^(S\d{2})\b') { $ids += $Matches[1] } else { $other += $name } + } + return @{ Ids = @($ids | Sort-Object -Unique); Other = $other } +} + +$dueNames = Get-Group -Summary $run.ppa_summary -Label 'Due' +$followUpNames = Get-Group -Summary $run.ppa_summary -Label 'Follow-up' +$due = Split-Names $dueNames +$followUp = Split-Names $followUpNames +$actualOutcome = $OutcomeNames[[int]$run.ppa_outcome] + +$problems = @() + +function Compare-Ids { + param([string]$Group, [string[]]$Expected, [string[]]$Actual) + $missing = @($Expected | Where-Object { $_ -and $_ -notin $Actual }) + $unexpected = @($Actual | Where-Object { $_ -and $_ -notin $Expected }) + $found = @() + if ($missing.Count -gt 0) { $found += "$Group — expected but not listed: $($missing -join ', ')" } + if ($unexpected.Count -gt 0) { $found += "$Group — listed but not expected: $($unexpected -join ', ')" } + return $found +} + +if ($actualOutcome -ne $ExpectOutcome) { + $detail = if ($run.ppa_errorstep) { " (error step: $($run.ppa_errorstep))" } else { '' } + $problems += "Outcome — expected $ExpectOutcome, got $actualOutcome$detail" +} +$problems += Compare-Ids -Group 'Due' -Expected $dueExpected -Actual $due.Ids +$problems += Compare-Ids -Group 'Follow-up' -Expected $followUpExpected -Actual $followUp.Ids + +# The counts on the row must agree with the names in its own summary. +if ([int]$run.ppa_duecount -ne $dueNames.Count) { + $problems += "Due count — row says $($run.ppa_duecount), summary lists $($dueNames.Count)" +} +if ([int]$run.ppa_followupcount -ne $followUpNames.Count) { + $problems += "Follow-up count — row says $($run.ppa_followupcount), summary lists $($followUpNames.Count)" +} +$both = @($due.Ids | Where-Object { $_ -in $followUp.Ids }) +if ($both.Count -gt 0) { + $problems += "Listed under both Due and Follow-up: $($both -join ', ')" +} + +$otherCount = $due.Other.Count + $followUp.Other.Count +if ($otherCount -gt 0) { + Write-Host " $otherCount listed Medication(s) are not from the seed set$(if ($Strict) { '' } else { ' (ignored)' })." + if ($Strict) { $problems += "-Strict: $otherCount listed Medication(s) are not from the seed set" } +} + +Write-Host " Outcome : $actualOutcome (attempts: $($run.ppa_attempts))" +Write-Host " Due : $($due.Ids.Count) from the seed set — $($due.Ids -join ', ')" +Write-Host " Follow-up : $($followUp.Ids.Count) from the seed set — $($followUp.Ids -join ', ')" +Write-Host "" + +if ($problems.Count -gt 0) { + Write-Host "✗ Reminder Run does not match:" + foreach ($problem in $problems) { Write-Host " - $problem" } + Write-Host "" + exit 1 +} + +Write-Host "✓ Reminder Run matches." +Write-Host "" diff --git a/scripts/reminder/create-reminder-schema.ps1 b/scripts/reminder/create-reminder-schema.ps1 new file mode 100644 index 0000000..f1b2665 --- /dev/null +++ b/scripts/reminder/create-reminder-schema.ps1 @@ -0,0 +1,357 @@ +#Requires -Version 7.0 +<# +.SYNOPSIS + Creates the Dataverse components the daily reminder needs, inside + MedTrackSolution, using the current Azure CLI user session. + +.DESCRIPTION + Local developer use against the dev environment -- not for CI. Other + environments receive these components through the solution import in the + pipeline. Idempotent: every component is looked up first and created only + when it is missing, so the script is safe to re-run. + + What gets created (specs/004-schedule-page-reminders/data-model.md): + Table ppa_ReminderRun (user-owned; notes, activities and + auditing off), its columns and the alternate key + ppa_reminderrun_date on ppa_name + Environment variables ppa_ReminderTimeZone (default UTC), + ppa_MedTrackAppUrl (default "not-configured": the + reminder carries no link until a value is set) + Connection references ppa_MedTrackDataverse, ppa_MedTrackTeams + + Table name, column types and ownership type are permanent in Dataverse. + + The reminder is a Teams message to the user behind the Dataverse + connection, so no address is configured anywhere. + +.PARAMETER EnvironmentUrl + Power Platform environment URL. Defaults to MedTrackDev. + +.PARAMETER RemoveRetired + Also removes what the email version of the reminder used and the Teams + version does not: connection reference ppa_MedTrackMail and environment + variable ppa_ReminderRecipientEmail, including its stored value. Run this + only after the flow has been updated; Dataverse refuses to delete a + component the flow still uses. + +.EXAMPLE + pwsh scripts/reminder/create-reminder-schema.ps1 +#> +param( + [string]$EnvironmentUrl = 'https://org9c89b427.crm.dynamics.com', + [switch]$RemoveRetired +) + +$ErrorActionPreference = 'Stop' +$envUrl = $EnvironmentUrl.TrimEnd('/') +$apiBase = "$envUrl/api/data/v9.2" +$solutionName = 'MedTrackSolution' +$tableLogical = 'ppa_reminderrun' + +Write-Host "" +Write-Host "MedTrack reminder schema → $envUrl" +Write-Host "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" + +# ── Auth ───────────────────────────────────────────────────────────────────── +Write-Host "→ Acquiring access token (az account get-access-token)..." +$token = az account get-access-token --resource "$envUrl/" --query accessToken -o tsv 2>&1 +if (-not $token -or $token -like '*ERROR*') { + throw "Token acquisition failed. Run 'az login' and try again. Detail: $token" +} + +$readHeaders = @{ + Authorization = "Bearer $token" + 'OData-Version' = '4.0' + Accept = 'application/json' +} +# Every component is created as part of MedTrackSolution. +$writeHeaders = $readHeaders + @{ + 'Content-Type' = 'application/json; charset=utf-8' + 'MSCRM.SolutionUniqueName' = $solutionName +} + +function Get-DVErrorReason { + param($ErrorRecord) + $reason = $ErrorRecord.Exception.Message + if ($ErrorRecord.ErrorDetails.Message) { + try { + $parsed = $ErrorRecord.ErrorDetails.Message | ConvertFrom-Json + if ($parsed.error.message) { $reason = $parsed.error.message } + } catch { + # Response body wasn't JSON; fall back to the exception message. + } + } + return $reason +} + +# GET that returns $null on 404 instead of throwing. +function Get-DVOrNull { + param([string]$Uri) + try { + return Invoke-RestMethod -Method Get -Uri $Uri -Headers $readHeaders + } catch { + if ($_.Exception.Response.StatusCode.value__ -eq 404) { return $null } + throw "GET $Uri failed: $(Get-DVErrorReason $_)" + } +} + +function New-DV { + param([string]$Uri, [hashtable]$Body, [string]$What) + try { + Invoke-RestMethod -Method Post -Uri $Uri -Headers $writeHeaders -Body ($Body | ConvertTo-Json -Depth 20 -Compress) | Out-Null + } catch { + throw "Creating $What failed: $(Get-DVErrorReason $_)" + } +} + +function New-Label { + param([string]$Text) + return @{ + '@odata.type' = 'Microsoft.Dynamics.CRM.Label' + LocalizedLabels = @( + @{ '@odata.type' = 'Microsoft.Dynamics.CRM.LocalizedLabel'; Label = $Text; LanguageCode = 1033 } + ) + } +} + +# ── 0. Solution must exist ─────────────────────────────────────────────────── +$solution = Get-DVOrNull ("$apiBase/solutions?" + '$select=solutionid&$filter=' + "uniquename eq '$solutionName'") +if (-not $solution -or $solution.value.Count -eq 0) { + throw "Solution '$solutionName' was not found in $envUrl." +} + +# ── 1. Table ───────────────────────────────────────────────────────────────── +$tableUri = "$apiBase/EntityDefinitions(LogicalName='$tableLogical')" +if (Get-DVOrNull ($tableUri + '?$select=MetadataId')) { + Write-Host " = table ppa_ReminderRun already exists" +} else { + Write-Host "→ Creating table ppa_ReminderRun..." + New-DV -Uri "$apiBase/EntityDefinitions" -What 'table ppa_ReminderRun' -Body @{ + '@odata.type' = 'Microsoft.Dynamics.CRM.EntityMetadata' + SchemaName = 'ppa_ReminderRun' + DisplayName = New-Label 'Reminder Run' + DisplayCollectionName = New-Label 'Reminder Runs' + Description = New-Label 'One row per day recording the outcome of the daily reminder check.' + OwnershipType = 'UserOwned' + HasNotes = $false + HasActivities = $false + IsActivity = $false + IsAuditEnabled = @{ Value = $false } + Attributes = @( + @{ + '@odata.type' = 'Microsoft.Dynamics.CRM.StringAttributeMetadata' + SchemaName = 'ppa_name' + DisplayName = New-Label 'Run Date' + Description = New-Label 'The local date of the run, yyyy-MM-dd.' + IsPrimaryName = $true + RequiredLevel = @{ Value = 'ApplicationRequired' } + MaxLength = 10 + FormatName = @{ Value = 'Text' } + } + ) + } + Write-Host " ✓ table ppa_ReminderRun" +} + +# ── 2. Columns ─────────────────────────────────────────────────────────────── +function New-Option { + param([int]$Value, [string]$Text) + return @{ Value = $Value; Label = New-Label $Text } +} + +function New-WholeNumber { + param([string]$SchemaName, [string]$Display, [string]$Description, [int]$Min, [int]$Max) + return @{ + '@odata.type' = 'Microsoft.Dynamics.CRM.IntegerAttributeMetadata' + SchemaName = $SchemaName + DisplayName = New-Label $Display + Description = New-Label $Description + RequiredLevel = @{ Value = 'ApplicationRequired' } + Format = 'None' + MinValue = $Min + MaxValue = $Max + } +} + +$columns = @( + @{ + '@odata.type' = 'Microsoft.Dynamics.CRM.PicklistAttributeMetadata' + SchemaName = 'ppa_Outcome' + DisplayName = New-Label 'Outcome' + Description = New-Label 'What the daily check did.' + RequiredLevel = @{ Value = 'ApplicationRequired' } + OptionSet = @{ + '@odata.type' = 'Microsoft.Dynamics.CRM.OptionSetMetadata' + IsGlobal = $false + OptionSetType = 'Picklist' + Options = @( + (New-Option 894250000 'Started') + (New-Option 894250001 'Sent') + (New-Option 894250002 'Nothing To Send') + (New-Option 894250003 'Failed') + ) + } + } + (New-WholeNumber 'ppa_DueCount' 'Due Count' 'Medications listed as due today.' 0 1000) + (New-WholeNumber 'ppa_FollowUpCount' 'Follow-up Count' 'Medications listed as follow-ups.' 0 1000) + @{ + '@odata.type' = 'Microsoft.Dynamics.CRM.MemoAttributeMetadata' + SchemaName = 'ppa_Summary' + DisplayName = New-Label 'Summary' + Description = New-Label 'Names of the Medications listed, in two labelled groups.' + RequiredLevel = @{ Value = 'None' } + Format = 'TextArea' + MaxLength = 4000 + } + @{ + '@odata.type' = 'Microsoft.Dynamics.CRM.StringAttributeMetadata' + SchemaName = 'ppa_ErrorStep' + DisplayName = New-Label 'Error Step' + Description = New-Label 'Name and status code of the step that failed. Never raw error text.' + RequiredLevel = @{ Value = 'None' } + MaxLength = 200 + FormatName = @{ Value = 'Text' } + } + (New-WholeNumber 'ppa_Attempts' 'Attempts' '1 on the first run, plus 1 on each retry after a failure.' 1 24) +) + +foreach ($column in $columns) { + $logical = $column.SchemaName.ToLowerInvariant() + if (Get-DVOrNull ("$tableUri/Attributes(LogicalName='$logical')" + '?$select=MetadataId')) { + Write-Host " = column $($column.SchemaName) already exists" + continue + } + New-DV -Uri "$tableUri/Attributes" -What "column $($column.SchemaName)" -Body $column + Write-Host " ✓ column $($column.SchemaName)" +} + +# ── 3. Alternate key: one row per day ──────────────────────────────────────── +$keyName = 'ppa_reminderrun_date' +function Get-Key { + $keys = Get-DVOrNull ("$tableUri/Keys" + '?$select=SchemaName,EntityKeyIndexStatus') + return $keys.value | Where-Object { $_.SchemaName -eq $keyName } +} + +if (Get-Key) { + Write-Host " = alternate key $keyName already exists" +} else { + New-DV -Uri "$tableUri/Keys" -What "alternate key $keyName" -Body @{ + SchemaName = $keyName + DisplayName = New-Label 'Run Date' + KeyAttributes = @('ppa_name') + } + Write-Host " ✓ alternate key $keyName" +} + +# The key's index is built asynchronously. The flow's guard relies on it, so +# wait until it is Active rather than reporting success early. +Write-Host "→ Waiting for the alternate key index..." +$keyStatus = $null +for ($i = 0; $i -lt 36; $i++) { + $keyStatus = (Get-Key).EntityKeyIndexStatus + if ($keyStatus -eq 'Active') { break } + if ($keyStatus -eq 'Failed') { throw "Alternate key $keyName failed to build. Check for duplicate ppa_name values." } + Start-Sleep -Seconds 5 +} +if ($keyStatus -ne 'Active') { + throw "Alternate key $keyName is still '$keyStatus' after 3 minutes. Re-run the script to check again." +} +Write-Host " ✓ alternate key $keyName is Active" + +# ── 4. Environment variable definitions ────────────────────────────────────── +# Both have a default, so the flow can be turned on before a value is set. +# Current values are set per environment and are never part of the solution. +$variables = @( + @{ + schemaname = 'ppa_ReminderTimeZone' + displayname = 'Reminder Time Zone' + description = 'Windows time zone name that defines "today" and "midnight" for the daily reminder.' + type = 100000000 + defaultvalue = 'UTC' + } + @{ + schemaname = 'ppa_MedTrackAppUrl' + displayname = 'MedTrack App URL' + description = 'Address of the MedTrack app in this environment, added to the daily reminder as a link. The link is left out unless the value starts with https://.' + type = 100000000 + defaultvalue = 'not-configured' + } +) + +foreach ($variable in $variables) { + $existing = Get-DVOrNull ("$apiBase/environmentvariabledefinitions?" + '$select=environmentvariabledefinitionid&$filter=' + "schemaname eq '$($variable.schemaname)'") + if ($existing.value.Count -gt 0) { + Write-Host " = environment variable $($variable.schemaname) already exists" + continue + } + New-DV -Uri "$apiBase/environmentvariabledefinitions" -What "environment variable $($variable.schemaname)" -Body $variable + Write-Host " ✓ environment variable $($variable.schemaname)" +} + +# ── 5. Connection references ───────────────────────────────────────────────── +$connectionReferences = @( + @{ + connectionreferencelogicalname = 'ppa_MedTrackDataverse' + connectionreferencedisplayname = 'MedTrack Dataverse' + description = 'The owner''s Dataverse connection used by the daily reminder flow.' + connectorid = '/providers/Microsoft.PowerApps/apis/shared_commondataserviceforapps' + } + @{ + connectionreferencelogicalname = 'ppa_MedTrackTeams' + connectionreferencedisplayname = 'MedTrack Teams' + description = 'The owner''s Microsoft Teams connection used to post the daily reminder.' + connectorid = '/providers/Microsoft.PowerApps/apis/shared_teams' + } +) + +foreach ($reference in $connectionReferences) { + $name = $reference.connectionreferencelogicalname + $existing = Get-DVOrNull ("$apiBase/connectionreferences?" + '$select=connectionreferenceid&$filter=' + "connectionreferencelogicalname eq '$name'") + if ($existing.value.Count -gt 0) { + Write-Host " = connection reference $name already exists" + continue + } + New-DV -Uri "$apiBase/connectionreferences" -What "connection reference $name" -Body $reference + Write-Host " ✓ connection reference $name" +} + +# ── 6. Retired components (only with -RemoveRetired) ──────────────────────── +if ($RemoveRetired) { + Write-Host "→ Removing components of the email version..." + $retired = @( + @{ Set = 'connectionreferences'; Id = 'connectionreferenceid'; Filter = "connectionreferencelogicalname eq 'ppa_MedTrackMail'"; What = 'connection reference ppa_MedTrackMail' } + # Deleting the definition also deletes its value: the stored address. + @{ Set = 'environmentvariabledefinitions'; Id = 'environmentvariabledefinitionid'; Filter = "schemaname eq 'ppa_ReminderRecipientEmail'"; What = 'environment variable ppa_ReminderRecipientEmail and its value' } + ) + foreach ($item in $retired) { + $found = Get-DVOrNull ("$apiBase/$($item.Set)?" + '$select=' + $item.Id + '&$filter=' + $item.Filter) + if ($found.value.Count -eq 0) { + Write-Host " = $($item.What): not present" + continue + } + try { + Invoke-RestMethod -Method Delete -Uri "$apiBase/$($item.Set)($($found.value[0].($item.Id)))" -Headers $readHeaders | Out-Null + } catch { + throw "Could not remove $($item.What): $(Get-DVErrorReason $_). If the flow still uses it, update the flow first." + } + Write-Host " ✓ removed $($item.What)" + } +} + +# ── 7. Publish ─────────────────────────────────────────────────────────────── +Write-Host "→ Publishing..." +try { + Invoke-RestMethod -Method Post -Uri "$apiBase/PublishXml" -Headers $writeHeaders -Body (@{ + ParameterXml = "$tableLogical" + } | ConvertTo-Json -Compress) | Out-Null +} catch { + throw "PublishXml failed: $(Get-DVErrorReason $_)" +} + +Write-Host "" +Write-Host "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" +Write-Host "✓ Reminder schema is in place in $solutionName." +Write-Host "" +Write-Host " Next: the owner creates a Microsoft Dataverse and a Microsoft Teams" +Write-Host " connection and picks them for the two connection references." +Write-Host "" diff --git a/scripts/reminder/seed-reminder-scenarios.ps1 b/scripts/reminder/seed-reminder-scenarios.ps1 new file mode 100644 index 0000000..765f140 --- /dev/null +++ b/scripts/reminder/seed-reminder-scenarios.ps1 @@ -0,0 +1,248 @@ +#Requires -Version 7.0 +<# +.SYNOPSIS + Seeds the schedule decision table (S01-S33) into a Dataverse environment so + the "MedTrack – Daily Reminder" flow can be checked against it. + +.DESCRIPTION + Local developer use against the dev environment -- not for CI. Authenticates + via `az account get-access-token` (the signed-in user), so the rows belong to + that user, which is what the flow's owner filter expects. + + Reads tests/fixtures/schedule-cases.json -- the same file the Vitest suite + uses -- and creates one Medication per case, named "