Skip to content

πŸ’« Toolkit to help you get started with SDD or any other process!

feat(scripts): add SPECIFY_FEATURE_NO_PERSIST env var to suppress feature.json writes (#4128) (#4129)

Jialong(Bruce) Li0a1b5575fb38
diff --git a/docs/reference/core.md b/docs/reference/core.md
index 685f8aa55..4957e129a 100644
--- a/docs/reference/core.md
+++ b/docs/reference/core.md
@@ -54,6 +54,7 @@ specify init my-project --integration copilot --preset compliance
| `SPECIFY_INIT_DIR` | Target a member project from outside its directory (e.g. a monorepo root) without `cd`, for non-interactive / CI use. Set it to the **project root** β€” the directory *containing* `.specify/` (relative paths resolve against the current directory). The path must exist and contain `.specify/`, otherwise the command errors and does **not** fall back to the current directory. Resolved once in the core root helper (`get_repo_root` in Bash, `Get-RepoRoot` in PowerShell), so it is honored by the core feature scripts (`/speckit.plan`, `/speckit.tasks`, …) and the Git extension's feature-branch creation, which inherit it. The `specify` CLI applies the **same** validation rules to every project-scoped subcommand (`specify integration …`, `specify extension …`, `specify workflow …`, `specify preset …`, and the rest that operate on a `.specify/` project), so those can target a member project too. When unset, Bash/PowerShell helpers keep their existing upward search; the `specify` CLI keeps its project-scoped resolver cwd-only unless a command explicitly defines broader detection (for example, bundle commands). |
| `SPECIFY_FEATURE_DIRECTORY` | Override the active feature directory *within* the resolved project (takes precedence over `.specify/feature.json`). Relative paths resolve under the project root. Combine with `SPECIFY_INIT_DIR` to pick both the project and the feature non-interactively. |
| `SPECIFY_FEATURE` | Explicitly override the active feature **label** (e.g. `001-photo-albums`) β€” the identifier the core helpers report as the current feature/branch (`get_current_branch` in Bash, `Get-CurrentBranch` in PowerShell). Those helpers never inspect Git: when the variable is set they return it verbatim, and when it is unset they return an empty string. The basename fallback happens later β€” `get_feature_paths` / `Get-FeaturePathsEnv` substitute the resolved feature directory's basename so the reported label is still usable β€” so calling the named helpers directly does **not** give you that fallback. You set it yourself: the Bash and Python feature scripts only **print** a commented `export SPECIFY_FEATURE=…` / `$env:SPECIFY_FEATURE = …` hint for you to run, because a child process cannot change its parent's environment, and `/speckit.specify` persists `feature_directory` to `.specify/feature.json` instead of setting this variable. (The PowerShell feature scripts do assign `$env:SPECIFY_FEATURE`, but that only reaches you when the script runs inside your current PowerShell session.) It does **not** locate the feature directory: with only `SPECIFY_FEATURE` set, `get_feature_paths` fails with *"Feature directory not found. Set `SPECIFY_FEATURE_DIRECTORY` or run the specify command to create `.specify/feature.json`."* Use `SPECIFY_FEATURE_DIRECTORY` (above) or `.specify/feature.json` to select the directory. |
+| `SPECIFY_FEATURE_NO_PERSIST` | Set to `1` or `true` to stop every core script from writing `.specify/feature.json`, even when it would otherwise persist `SPECIFY_FEATURE_DIRECTORY` on read. Useful when multiple agents run concurrently against the same checkout, each with its own `SPECIFY_FEATURE_DIRECTORY`: without it, each invocation's persist step can overwrite another agent's pinned feature directory. |
> **Two resolution axes.** `SPECIFY_INIT_DIR` selects the **project** (which directory contains `.specify/`); `SPECIFY_FEATURE_DIRECTORY` / `.specify/feature.json` select the **feature** within that project. They are independent β€” project first, then feature.
diff --git a/scripts/bash/common.sh b/scripts/bash/common.sh
index ce1171e28..59e68099c 100644
--- a/scripts/bash/common.sh
+++ b/scripts/bash/common.sh
@@ -169,6 +169,13 @@ get_feature_paths() {
no_persist=true
shift
fi
+ # SPECIFY_FEATURE_NO_PERSIST is the environment-level equivalent of --no-persist,
+ # letting an orchestrator (multi-agent runner, CI matrix) guarantee that no
+ # script invocation in the process tree writes .specify/feature.json, even
+ # scripts that don't pass --no-persist themselves (#4128).
+ if [[ "${SPECIFY_FEATURE_NO_PERSIST:-}" == "1" || "${SPECIFY_FEATURE_NO_PERSIST:-}" == "true" ]]; then
+ no_persist=true
+ fi
# Split decl/assignment so a SPECIFY_INIT_DIR validation failure in
# get_repo_root propagates as a hard error instead of being masked by `local`.
diff --git a/scripts/bash/create-new-feature.sh b/scripts/bash/create-new-feature.sh
index 94294f20c..136701490 100644
--- a/scripts/bash/create-new-feature.sh
+++ b/scripts/bash/create-new-feature.sh
@@ -383,8 +383,11 @@ if [ "$DRY_RUN" != true ]; then
fi
fi
- # Persist to .specify/feature.json so downstream commands can find the feature
- _persist_feature_json "$REPO_ROOT" "$FEATURE_DIR"
+ # Persist to .specify/feature.json so downstream commands can find the
+ # feature, unless the orchestrator opted out via SPECIFY_FEATURE_NO_PERSIST (#4129).
+ if [[ "${SPECIFY_FEATURE_NO_PERSIST:-}" != "1" && "${SPECIFY_FEATURE_NO_PERSIST:-}" != "true" ]]; then
+ _persist_feature_json "$REPO_ROOT" "$FEATURE_DIR"
+ fi
# Inform the user how to set feature state in their own shell
printf '# To persist: export SPECIFY_FEATURE=%s\n' "$(shell_quote "$BRANCH_NAME")" >&2
diff --git a/scripts/powershell/common.ps1 b/scripts/powershell/common.ps1
index d0489fdf7..d8c9d19bb 100644
--- a/scripts/powershell/common.ps1
+++ b/scripts/powershell/common.ps1
@@ -167,6 +167,12 @@ function Get-FeaturePathsEnv {
[switch]$ReturnNullOnError
)
+ # 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
@@ -184,7 +190,7 @@ function Get-FeaturePathsEnv {
}
# 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) {
+ if (-not $noPersist) {
Save-FeatureJson -RepoRoot $repoRoot -FeatureDirectory $env:SPECIFY_FEATURE_DIRECTORY
}
} elseif (Test-Path $featureJson) {
diff --git a/scripts/powershell/create-new-feature.ps1 b/scripts/powershell/create-new-feature.ps1
index 6a18546de..c90bd26e4 100644
--- a/scripts/powershell/create-new-feature.ps1
+++ b/scripts/powershell/create-new-feature.ps1
@@ -296,8 +296,11 @@ if (-not $DryRun) {
}
}
- # Persist to .specify/feature.json so downstream commands can find the feature
- Save-FeatureJson -RepoRoot $repoRoot -FeatureDirectory $featureDir
+ # 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
diff --git a/scripts/python/common.py b/scripts/python/common.py
index db958dc1c..5a2445a0e 100644
--- a/scripts/python/common.py
+++ b/scripts/python/common.py
@@ -139,6 +139,12 @@ def get_feature_paths(
repo_root = get_repo_root(script_file)
current_branch = get_current_branch()
+ # SPECIFY_FEATURE_NO_PERSIST is the environment-level equivalent of no_persist=True,
+ # letting an orchestrator (multi-agent runner, CI matrix) guarantee that no
+ # script invocation in the process tree writes .specify/feature.json, even
+ # scripts that don't pass no_persist themselves (#4128).
+ no_persist = no_persist or os.environ.get("SPECIFY_FEATURE_NO_PERSIST", "") in ("1", "true")
+
feature_dir_raw = os.environ.get("SPECIFY_FEATURE_DIRECTORY", "")
if feature_dir_raw:
feature_dir = Path(feature_dir_raw)
diff --git a/scripts/python/create_new_feature.py b/scripts/python/create_new_feature.py
index 7f1210c22..e8fadea61 100644
--- a/scripts/python/create_new_feature.py
+++ b/scripts/python/create_new_feature.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import datetime
import json
+import os
import re
import shlex
import sys
@@ -413,8 +414,10 @@ def main(argv: list[str] | None = None) -> int:
)
spec_file.touch()
- # Persist to .specify/feature.json so downstream commands can find the feature.
- persist_feature_json(repo_root, f"specs/{branch_name}")
+ # Persist to .specify/feature.json so downstream commands can find the
+ # feature, unless the orchestrator opted out via SPECIFY_FEATURE_NO_PERSIST (#4129).
+ if os.environ.get("SPECIFY_FEATURE_NO_PERSIST", "") not in ("1", "true"):
+ persist_feature_json(repo_root, f"specs/{branch_name}")
# Inform the user how to set feature state in their own shell.
feature_assignment, directory_assignment = _persistence_assignments(
diff --git a/tests/test_specify_no_persist.py b/tests/test_specify_no_persist.py
new file mode 100644
index 000000000..64ab5dbe2
--- /dev/null
+++ b/tests/test_specify_no_persist.py
@@ -0,0 +1,159 @@
+"""Tests for SPECIFY_FEATURE_NO_PERSIST, the env-level equivalent of --no-persist (#4128).
+
+Scripts like setup-plan/setup-tasks call get_feature_paths() without
+--no-persist, so every invocation with SPECIFY_FEATURE_DIRECTORY set
+overwrites .specify/feature.json. In multi-agent setups where several
+processes each set their own SPECIFY_FEATURE_DIRECTORY, this creates a
+write-write race on the shared file. SPECIFY_FEATURE_NO_PERSIST lets an orchestrator
+suppress that write across every script invocation without having to patch
+each call site.
+"""
+
+import json
+import shutil
+from pathlib import Path
+
+import pytest
+
+from tests.conftest import requires_bash
+from tests.parity_helpers import (
+ HAS_POWERSHELL,
+ PROJECT_ROOT,
+ bash_cmd,
+ clean_env,
+ install_scripts,
+ make_repo,
+ ps_cmd,
+ py_cmd,
+ run,
+)
+
+SCRIPT = "setup-plan"
+PLAN_TEMPLATE = PROJECT_ROOT / "templates" / "plan-template.md"
+
+
+def _setup_repo(tmp_path: Path, name: str = "proj") -> Path:
+ repo = make_repo(tmp_path, name)
+ install_scripts(repo, SCRIPT)
+ templates = repo / ".specify" / "templates"
+ templates.mkdir(parents=True, exist_ok=True)
+ shutil.copy(PLAN_TEMPLATE, templates / "plan-template.md")
+ return repo
+
+
+def _feature_json(repo: Path) -> dict | None:
+ fj = repo / ".specify" / "feature.json"
+ if not fj.is_file():
+ return None
+ return json.loads(fj.read_text(encoding="utf-8"))
+
+
+def repo(tmp_path: Path) -> Path:
+ return _setup_repo(tmp_path)
+
+
+@requires_bash
+def test_bash_persists_by_default(repo: Path) -> None:
+ (repo / "specs" / "001-a").mkdir(parents=True)
+ env = clean_env()
+ env["SPECIFY_FEATURE_DIRECTORY"] = "specs/001-a"
+ result = run(bash_cmd(repo, SCRIPT, "--json"), repo, env)
+ assert result.returncode == 0, result.stderr
+ assert _feature_json(repo) == {"feature_directory": "specs/001-a"}
+
+
+@requires_bash
+def test_bash_specify_no_persist_suppresses_write(repo: Path) -> None:
+ (repo / "specs" / "001-a").mkdir(parents=True)
+ env = clean_env()
+ env["SPECIFY_FEATURE_DIRECTORY"] = "specs/001-a"
+ env["SPECIFY_FEATURE_NO_PERSIST"] = "1"
+ result = run(bash_cmd(repo, SCRIPT, "--json"), repo, env)
+ assert result.returncode == 0, result.stderr
+ assert _feature_json(repo) is None
+
+
+@requires_bash
+def test_bash_specify_no_persist_does_not_clobber_existing_pin(repo: Path) -> None:
+ """A second agent's SPECIFY_FEATURE_DIRECTORY must not overwrite the
+ first agent's persisted feature.json when SPECIFY_FEATURE_NO_PERSIST is set."""
+ (repo / "specs" / "001-a").mkdir(parents=True)
+ (repo / "specs" / "002-b").mkdir(parents=True)
+ env = clean_env()
+ env["SPECIFY_FEATURE_DIRECTORY"] = "specs/001-a"
+ result = run(bash_cmd(repo, SCRIPT, "--json"), repo, env)
+ assert result.returncode == 0, result.stderr
+ assert _feature_json(repo) == {"feature_directory": "specs/001-a"}
+
+ env["SPECIFY_FEATURE_DIRECTORY"] = "specs/002-b"
+ env["SPECIFY_FEATURE_NO_PERSIST"] = "1"
+ result = run(bash_cmd(repo, SCRIPT, "--json"), repo, env)
+ assert result.returncode == 0, result.stderr
+ assert _feature_json(repo) == {"feature_directory": "specs/001-a"}
+
+
[email protected](not HAS_POWERSHELL, reason="no PowerShell available")
+def test_ps_specify_no_persist_suppresses_write(repo: Path) -> None:
+ (repo / "specs" / "001-a").mkdir(parents=True)
+ env = clean_env()
+ env["SPECIFY_FEATURE_DIRECTORY"] = "specs/001-a"
+ env["SPECIFY_FEATURE_NO_PERSIST"] = "true"
+ result = run(ps_cmd(repo, SCRIPT, "-Json"), repo, env)
+ assert result.returncode == 0, result.stderr
+ assert _feature_json(repo) is None
+
+
+def test_py_specify_no_persist_suppresses_write(repo: Path) -> None:
+ (repo / "specs" / "001-a").mkdir(parents=True)
+ env = clean_env()
+ env["SPECIFY_FEATURE_DIRECTORY"] = "specs/001-a"
+ env["SPECIFY_FEATURE_NO_PERSIST"] = "1"
+ result = run(py_cmd(repo, SCRIPT, "--json"), repo, env)
+ assert result.returncode == 0, result.stderr
+ assert _feature_json(repo) is None
+
+
+# create-new-feature writes .specify/feature.json directly (not via
+# get_feature_paths()), so it must honor SPECIFY_FEATURE_NO_PERSIST separately.
+
+CREATE_SCRIPT = "create-new-feature"
+SPEC_TEMPLATE_BODY = "# Spec Template\n\nBody.\n"
+
+
+def _create_feature_repo(tmp_path: Path, name: str = "proj") -> Path:
+ repo = make_repo(tmp_path, name)
+ install_scripts(repo, CREATE_SCRIPT)
+ templates = repo / ".specify" / "templates"
+ templates.mkdir(parents=True, exist_ok=True)
+ (templates / "spec-template.md").write_text(SPEC_TEMPLATE_BODY, encoding="utf-8")
+ return repo
+
+
+@requires_bash
+def test_bash_create_new_feature_no_persist_suppresses_write(tmp_path: Path) -> None:
+ repo = _create_feature_repo(tmp_path)
+ env = clean_env()
+ env["SPECIFY_FEATURE_NO_PERSIST"] = "1"
+ result = run(bash_cmd(repo, CREATE_SCRIPT, "--json", "x"), repo, env)
+ assert result.returncode == 0, result.stderr
+ assert _feature_json(repo) is None
+
+
[email protected](not HAS_POWERSHELL, reason="no PowerShell available")
+def test_ps_create_new_feature_no_persist_suppresses_write(tmp_path: Path) -> None:
+ repo = _create_feature_repo(tmp_path)
+ env = clean_env()
+ env["SPECIFY_FEATURE_NO_PERSIST"] = "true"
+ result = run(ps_cmd(repo, CREATE_SCRIPT, "-Json", "x"), repo, env)
+ assert result.returncode == 0, result.stderr
+ assert _feature_json(repo) is None
+
+
+def test_py_create_new_feature_no_persist_suppresses_write(tmp_path: Path) -> None:
+ repo = _create_feature_repo(tmp_path)
+ env = clean_env()
+ env["SPECIFY_FEATURE_NO_PERSIST"] = "1"
+ result = run(py_cmd(repo, CREATE_SCRIPT, "--json", "x"), repo, env)
+ assert result.returncode == 0, result.stderr
+ assert _feature_json(repo) is None