mirror of
https://github.com/github/spec-kit.git
synced 2026-08-03 06:26:30 +08:00
Compare commits
99 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3b683c2292 | ||
|
|
f36634b5c1 | ||
|
|
6712665bba | ||
|
|
5827db5359 | ||
|
|
afbb2c7b65 | ||
|
|
6337ebfe59 | ||
|
|
e543147ccb | ||
|
|
6033c6957b | ||
|
|
13f2b135cc | ||
|
|
54396780f3 | ||
|
|
db5802b39b | ||
|
|
8394c8d536 | ||
|
|
89126f3a33 | ||
|
|
623466dc42 | ||
|
|
2ef96532d2 | ||
|
|
de54ff73fe | ||
|
|
f4a9b890cc | ||
|
|
b7b0e966cc | ||
|
|
884950f88a | ||
|
|
f8e474d6fd | ||
|
|
1fff7a196d | ||
|
|
b048e339a5 | ||
|
|
d99170fb5e | ||
|
|
f04a36a629 | ||
|
|
be33d2a5f6 | ||
|
|
751eae727e | ||
|
|
4ad7ef2b42 | ||
|
|
6ef96373e2 | ||
|
|
4bc79fe243 | ||
|
|
596a31ee0f | ||
|
|
52a6514e38 | ||
|
|
3dad624e5d | ||
|
|
0231ee056b | ||
|
|
ca2b494335 | ||
|
|
86c4610b7d | ||
|
|
a2b0d0d3c1 | ||
|
|
56b1839fba | ||
|
|
98b2551ade | ||
|
|
9bb7206d3b | ||
|
|
89e204ca3c | ||
|
|
88e997306f | ||
|
|
186ca25c99 | ||
|
|
a9c9905400 | ||
|
|
054fb7723d | ||
|
|
8bfe6e14d1 | ||
|
|
a482fb2fce | ||
|
|
05cb3cba34 | ||
|
|
2e44ed60e8 | ||
|
|
999f8e6497 | ||
|
|
655a3cb8ca | ||
|
|
809b4c5e26 | ||
|
|
1354eade99 | ||
|
|
2a29b534ae | ||
|
|
d8d62756fe | ||
|
|
9602ad2edf | ||
|
|
39f2ac3c63 | ||
|
|
7fc5b236c8 | ||
|
|
118062eac4 | ||
|
|
0117a7b977 | ||
|
|
2355fcb350 | ||
|
|
98c9e67ce2 | ||
|
|
6136706ef3 | ||
|
|
683bfd00c9 | ||
|
|
42c7230aa9 | ||
|
|
e6a3ccfb27 | ||
|
|
962f9f0765 | ||
|
|
c1028e5506 | ||
|
|
9e150cd3b2 | ||
|
|
99dc915ae3 | ||
|
|
103ad73775 | ||
|
|
59e63699b8 | ||
|
|
015d125667 | ||
|
|
3ca0eb169e | ||
|
|
c6cb25cb4a | ||
|
|
eb8108e7b3 | ||
|
|
403fcdc6fd | ||
|
|
2fb94e0f9c | ||
|
|
446ee329b1 | ||
|
|
c0fe0e43cd | ||
|
|
ae0b8ca2b0 | ||
|
|
2fe35bf898 | ||
|
|
73908f798a | ||
|
|
ffe2a7ffd6 | ||
|
|
ae82c74339 | ||
|
|
71e6201790 | ||
|
|
ea6843c1fe | ||
|
|
b0850c97e6 | ||
|
|
781a14a6d2 | ||
|
|
be0c741ebb | ||
|
|
36754522f7 | ||
|
|
391cc0dff8 | ||
|
|
1631c0a50f | ||
|
|
6385250264 | ||
|
|
bfe4772b79 | ||
|
|
c0ba81190b | ||
|
|
e53ddcb0cc | ||
|
|
769acafcab | ||
|
|
2a397aad6c | ||
|
|
4d3a4281bc |
2
.github/ISSUE_TEMPLATE/agent_request.yml
vendored
2
.github/ISSUE_TEMPLATE/agent_request.yml
vendored
@@ -8,7 +8,7 @@ body:
|
||||
value: |
|
||||
Thanks for requesting a new agent! Before submitting, please check if the agent is already supported.
|
||||
|
||||
**Currently supported agents**: Amp, Antigravity, Auggie CLI, Claude Code, Cline, CodeBuddy, Codex CLI, Cursor, Devin for Terminal, Factory Droid, Firebender, Forge, Gemini CLI, GitHub Copilot, Goose, Grok Build, Hermes Agent, IBM Bob, Junie, Kilo Code, Kimi Code, Kiro CLI, Lingma, Mistral Vibe, Oh My Pi, opencode, Pi Coding Agent, Qoder CLI, Qwen Code, RovoDev ACLI, SHAI, Tabnine CLI, Trae, ZCode, Zed
|
||||
**Currently supported agents**: Alquimia AI, Amp, Antigravity, Auggie CLI, Claude Code, Cline, CodeBuddy, Codex CLI, Cursor, Devin for Terminal, Factory Droid, Firebender, Forge, Gemini CLI, GitHub Copilot, Goose, Grok Build, Hermes Agent, IBM Bob, Junie, Kilo Code, Kimi Code, Kiro CLI, Lingma, Mistral Vibe, Oh My Pi, opencode, Pi Coding Agent, Qoder CLI, Qwen Code, RovoDev ACLI, SHAI, Tabnine CLI, Trae, ZCode, Zed
|
||||
|
||||
- type: input
|
||||
id: agent-name
|
||||
|
||||
1
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
1
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
@@ -62,6 +62,7 @@ body:
|
||||
label: AI Agent
|
||||
description: Which AI agent are you using?
|
||||
options:
|
||||
- Alquimia AI
|
||||
- Amp
|
||||
- Antigravity
|
||||
- Auggie CLI
|
||||
|
||||
1
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
1
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
@@ -56,6 +56,7 @@ body:
|
||||
description: Does this feature relate to a specific AI agent?
|
||||
options:
|
||||
- All agents
|
||||
- Alquimia AI
|
||||
- Amp
|
||||
- Antigravity
|
||||
- Auggie CLI
|
||||
|
||||
12
.github/scripts/check_security_requirements.py
vendored
12
.github/scripts/check_security_requirements.py
vendored
@@ -29,12 +29,20 @@ def _dependency_diff_refs() -> tuple[str, str]:
|
||||
def _dependency_inputs_changed() -> bool:
|
||||
base_ref, head_ref = _dependency_diff_refs()
|
||||
try:
|
||||
merge_base = subprocess.run(
|
||||
["git", "merge-base", base_ref, head_ref],
|
||||
check=True,
|
||||
cwd=REPO_ROOT,
|
||||
stderr=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE,
|
||||
text=True,
|
||||
).stdout.strip()
|
||||
result = subprocess.run(
|
||||
[
|
||||
"git",
|
||||
"diff",
|
||||
"--name-only",
|
||||
base_ref,
|
||||
merge_base,
|
||||
head_ref,
|
||||
"--",
|
||||
*DEPENDENCY_INPUTS,
|
||||
@@ -77,6 +85,7 @@ def main() -> int:
|
||||
|
||||
generated_requirements = Path(generated_requirements_env)
|
||||
generated_requirements.parent.mkdir(parents=True, exist_ok=True)
|
||||
generated_requirements.write_bytes(COMMITTED_REQUIREMENTS.read_bytes())
|
||||
|
||||
subprocess.run(
|
||||
[
|
||||
@@ -87,7 +96,6 @@ def main() -> int:
|
||||
"--extra",
|
||||
"test",
|
||||
"--universal",
|
||||
"--upgrade",
|
||||
"--generate-hashes",
|
||||
"--quiet",
|
||||
"--no-header",
|
||||
|
||||
6
.github/security-audit-requirements.txt
vendored
6
.github/security-audit-requirements.txt
vendored
@@ -1,6 +1,6 @@
|
||||
annotated-doc==0.0.4 \
|
||||
--hash=sha256:571ac1dc6991c450b25a9c2d84a3705e2ae7a53467b5d111c24fa8baabbed320 \
|
||||
--hash=sha256:fbcda96e87e9c92ad167c2e53839e57503ecfda18804ea28102353485033faa4
|
||||
annotated-doc==0.0.5 \
|
||||
--hash=sha256:117bac03a25ede5df5440e855b32d556049ca169ead221505badf432fed4b101 \
|
||||
--hash=sha256:c7e58ce09192557605d8bbd92836d7e1d520ac9580096042c0bfd197efacf1bb
|
||||
# via typer
|
||||
click==8.4.2 \
|
||||
--hash=sha256:9a6cea6e60b17ebe0a44c5cc636d94f09bd66142c1cd7d8b4cd731c4917a15f6 \
|
||||
|
||||
16
.github/workflows/add-community-bundle.lock.yml
generated
vendored
16
.github/workflows/add-community-bundle.lock.yml
generated
vendored
@@ -33,10 +33,10 @@
|
||||
# - GITHUB_TOKEN
|
||||
#
|
||||
# Custom actions used:
|
||||
# - actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
||||
# - actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
# - actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
# - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
# - actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
# - actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
# - actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
# - github/gh-aw-actions/setup@c0338fef4749d08c21f8f975fb0e37efa17dda47 # v0.79.8
|
||||
#
|
||||
@@ -162,7 +162,7 @@ jobs:
|
||||
env:
|
||||
COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }}
|
||||
- name: Checkout .github and .agents folders
|
||||
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
sparse-checkout: |
|
||||
@@ -434,7 +434,7 @@ jobs:
|
||||
echo "GH_AW_SAFE_OUTPUTS_TOOLS_PATH=${RUNNER_TEMP}/gh-aw/safeoutputs/tools.json"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
fetch-depth: 0
|
||||
@@ -1352,7 +1352,7 @@ jobs:
|
||||
echo "GH_AW_AGENT_OUTPUT=/tmp/gh-aw/agent_output.json" >> "$GITHUB_OUTPUT"
|
||||
- name: Checkout repository for patch context
|
||||
if: needs.agent.outputs.has_patch == 'true'
|
||||
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
# --- Threat Detection ---
|
||||
@@ -1419,7 +1419,7 @@ jobs:
|
||||
mkdir -p /tmp/gh-aw/threat-detection
|
||||
touch /tmp/gh-aw/threat-detection/detection.log
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
with:
|
||||
node-version: '24'
|
||||
package-manager-cache: false
|
||||
@@ -1678,7 +1678,7 @@ jobs:
|
||||
await main();
|
||||
- name: Checkout repository (trusted default branch for comment events)
|
||||
if: (!cancelled()) && needs.agent.result != 'skipped' && contains(needs.agent.outputs.output_types, 'create_pull_request') && (github.event_name == 'issue_comment' || github.event_name == 'pull_request_review_comment')
|
||||
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: ${{ github.event.repository.default_branch }}
|
||||
token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }}
|
||||
@@ -1686,7 +1686,7 @@ jobs:
|
||||
fetch-depth: 0
|
||||
- name: Checkout repository
|
||||
if: (!cancelled()) && needs.agent.result != 'skipped' && contains(needs.agent.outputs.output_types, 'create_pull_request') && github.event_name != 'issue_comment' && github.event_name != 'pull_request_review_comment'
|
||||
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: ${{ steps.extract-base-branch.outputs.base-branch || github.base_ref || github.event.pull_request.base.ref || github.ref_name || github.event.repository.default_branch }}
|
||||
token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }}
|
||||
|
||||
12
.github/workflows/add-community-extension.lock.yml
generated
vendored
12
.github/workflows/add-community-extension.lock.yml
generated
vendored
@@ -33,7 +33,7 @@
|
||||
# - GITHUB_TOKEN
|
||||
#
|
||||
# Custom actions used:
|
||||
# - actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
# - actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
# - actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
# - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
# - actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
@@ -162,7 +162,7 @@ jobs:
|
||||
env:
|
||||
COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }}
|
||||
- name: Checkout .github and .agents folders
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
sparse-checkout: |
|
||||
@@ -434,7 +434,7 @@ jobs:
|
||||
echo "GH_AW_SAFE_OUTPUTS_TOOLS_PATH=${RUNNER_TEMP}/gh-aw/safeoutputs/tools.json"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
fetch-depth: 0
|
||||
@@ -1332,7 +1332,7 @@ jobs:
|
||||
echo "GH_AW_AGENT_OUTPUT=/tmp/gh-aw/agent_output.json" >> "$GITHUB_OUTPUT"
|
||||
- name: Checkout repository for patch context
|
||||
if: needs.agent.outputs.has_patch == 'true'
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
# --- Threat Detection ---
|
||||
@@ -1658,7 +1658,7 @@ jobs:
|
||||
await main();
|
||||
- name: Checkout repository (trusted default branch for comment events)
|
||||
if: (!cancelled()) && needs.agent.result != 'skipped' && contains(needs.agent.outputs.output_types, 'create_pull_request') && (github.event_name == 'issue_comment' || github.event_name == 'pull_request_review_comment')
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: ${{ github.event.repository.default_branch }}
|
||||
token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }}
|
||||
@@ -1666,7 +1666,7 @@ jobs:
|
||||
fetch-depth: 0
|
||||
- name: Checkout repository
|
||||
if: (!cancelled()) && needs.agent.result != 'skipped' && contains(needs.agent.outputs.output_types, 'create_pull_request') && github.event_name != 'issue_comment' && github.event_name != 'pull_request_review_comment'
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: ${{ steps.extract-base-branch.outputs.base-branch || github.base_ref || github.event.pull_request.base.ref || github.ref_name || github.event.repository.default_branch }}
|
||||
token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }}
|
||||
|
||||
12
.github/workflows/add-community-preset.lock.yml
generated
vendored
12
.github/workflows/add-community-preset.lock.yml
generated
vendored
@@ -33,7 +33,7 @@
|
||||
# - GITHUB_TOKEN
|
||||
#
|
||||
# Custom actions used:
|
||||
# - actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
# - actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
# - actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
# - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
# - actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
@@ -162,7 +162,7 @@ jobs:
|
||||
env:
|
||||
COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }}
|
||||
- name: Checkout .github and .agents folders
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
sparse-checkout: |
|
||||
@@ -434,7 +434,7 @@ jobs:
|
||||
echo "GH_AW_SAFE_OUTPUTS_TOOLS_PATH=${RUNNER_TEMP}/gh-aw/safeoutputs/tools.json"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
fetch-depth: 0
|
||||
@@ -1332,7 +1332,7 @@ jobs:
|
||||
echo "GH_AW_AGENT_OUTPUT=/tmp/gh-aw/agent_output.json" >> "$GITHUB_OUTPUT"
|
||||
- name: Checkout repository for patch context
|
||||
if: needs.agent.outputs.has_patch == 'true'
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
# --- Threat Detection ---
|
||||
@@ -1658,7 +1658,7 @@ jobs:
|
||||
await main();
|
||||
- name: Checkout repository (trusted default branch for comment events)
|
||||
if: (!cancelled()) && needs.agent.result != 'skipped' && contains(needs.agent.outputs.output_types, 'create_pull_request') && (github.event_name == 'issue_comment' || github.event_name == 'pull_request_review_comment')
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: ${{ github.event.repository.default_branch }}
|
||||
token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }}
|
||||
@@ -1666,7 +1666,7 @@ jobs:
|
||||
fetch-depth: 0
|
||||
- name: Checkout repository
|
||||
if: (!cancelled()) && needs.agent.result != 'skipped' && contains(needs.agent.outputs.output_types, 'create_pull_request') && github.event_name != 'issue_comment' && github.event_name != 'pull_request_review_comment'
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: ${{ steps.extract-base-branch.outputs.base-branch || github.base_ref || github.event.pull_request.base.ref || github.ref_name || github.event.repository.default_branch }}
|
||||
token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }}
|
||||
|
||||
8
.github/workflows/bug-assess.lock.yml
generated
vendored
8
.github/workflows/bug-assess.lock.yml
generated
vendored
@@ -32,7 +32,7 @@
|
||||
# - GITHUB_TOKEN
|
||||
#
|
||||
# Custom actions used:
|
||||
# - actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
# - actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
# - actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
# - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
# - actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
@@ -161,7 +161,7 @@ jobs:
|
||||
env:
|
||||
COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }}
|
||||
- name: Checkout .github and .agents folders
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
sparse-checkout: |
|
||||
@@ -430,7 +430,7 @@ jobs:
|
||||
echo "GH_AW_SAFE_OUTPUTS_TOOLS_PATH=${RUNNER_TEMP}/gh-aw/safeoutputs/tools.json"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
fetch-depth: 0
|
||||
@@ -1277,7 +1277,7 @@ jobs:
|
||||
echo "GH_AW_AGENT_OUTPUT=/tmp/gh-aw/agent_output.json" >> "$GITHUB_OUTPUT"
|
||||
- name: Checkout repository for patch context
|
||||
if: needs.agent.outputs.has_patch == 'true'
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
# --- Threat Detection ---
|
||||
|
||||
12
.github/workflows/bug-fix.lock.yml
generated
vendored
12
.github/workflows/bug-fix.lock.yml
generated
vendored
@@ -33,7 +33,7 @@
|
||||
# - GITHUB_TOKEN
|
||||
#
|
||||
# Custom actions used:
|
||||
# - actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
# - actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
# - actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
# - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
# - actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
@@ -162,7 +162,7 @@ jobs:
|
||||
env:
|
||||
COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }}
|
||||
- name: Checkout .github and .agents folders
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
sparse-checkout: |
|
||||
@@ -434,7 +434,7 @@ jobs:
|
||||
echo "GH_AW_SAFE_OUTPUTS_TOOLS_PATH=${RUNNER_TEMP}/gh-aw/safeoutputs/tools.json"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
fetch-depth: 0
|
||||
@@ -1338,7 +1338,7 @@ jobs:
|
||||
echo "GH_AW_AGENT_OUTPUT=/tmp/gh-aw/agent_output.json" >> "$GITHUB_OUTPUT"
|
||||
- name: Checkout repository for patch context
|
||||
if: needs.agent.outputs.has_patch == 'true'
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
# --- Threat Detection ---
|
||||
@@ -1664,7 +1664,7 @@ jobs:
|
||||
await main();
|
||||
- name: Checkout repository (trusted default branch for comment events)
|
||||
if: (!cancelled()) && needs.agent.result != 'skipped' && contains(needs.agent.outputs.output_types, 'create_pull_request') && (github.event_name == 'issue_comment' || github.event_name == 'pull_request_review_comment')
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: ${{ github.event.repository.default_branch }}
|
||||
token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }}
|
||||
@@ -1672,7 +1672,7 @@ jobs:
|
||||
fetch-depth: 0
|
||||
- name: Checkout repository
|
||||
if: (!cancelled()) && needs.agent.result != 'skipped' && contains(needs.agent.outputs.output_types, 'create_pull_request') && github.event_name != 'issue_comment' && github.event_name != 'pull_request_review_comment'
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: ${{ steps.extract-base-branch.outputs.base-branch || github.base_ref || github.event.pull_request.base.ref || github.ref_name || github.event.repository.default_branch }}
|
||||
token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }}
|
||||
|
||||
8
.github/workflows/bug-test.lock.yml
generated
vendored
8
.github/workflows/bug-test.lock.yml
generated
vendored
@@ -32,7 +32,7 @@
|
||||
# - GITHUB_TOKEN
|
||||
#
|
||||
# Custom actions used:
|
||||
# - actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
# - actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
# - actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
# - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
# - actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
@@ -161,7 +161,7 @@ jobs:
|
||||
env:
|
||||
COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }}
|
||||
- name: Checkout .github and .agents folders
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
sparse-checkout: |
|
||||
@@ -431,7 +431,7 @@ jobs:
|
||||
echo "GH_AW_SAFE_OUTPUTS_TOOLS_PATH=${RUNNER_TEMP}/gh-aw/safeoutputs/tools.json"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
fetch-depth: 0
|
||||
@@ -1299,7 +1299,7 @@ jobs:
|
||||
echo "GH_AW_AGENT_OUTPUT=/tmp/gh-aw/agent_output.json" >> "$GITHUB_OUTPUT"
|
||||
- name: Checkout repository for patch context
|
||||
if: needs.agent.outputs.has_patch == 'true'
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
# --- Threat Detection ---
|
||||
|
||||
6
.github/workflows/codeql.yml
vendored
6
.github/workflows/codeql.yml
vendored
@@ -19,14 +19,14 @@ jobs:
|
||||
language: [ 'actions', 'python' ]
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@7188fc363630916deb702c7fdcf4e481b751f97a # v4
|
||||
uses: github/codeql-action/init@e4fba868fa4b1b91e1fdab776edc8cfbe6e9fb81 # v4
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@7188fc363630916deb702c7fdcf4e481b751f97a # v4
|
||||
uses: github/codeql-action/analyze@e4fba868fa4b1b91e1fdab776edc8cfbe6e9fb81 # v4
|
||||
with:
|
||||
category: "/language:${{ matrix.language }}"
|
||||
|
||||
2
.github/workflows/docs.yml
vendored
2
.github/workflows/docs.yml
vendored
@@ -30,7 +30,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
fetch-depth: 0 # Fetch all history for git info
|
||||
|
||||
|
||||
6
.github/workflows/lint.yml
vendored
6
.github/workflows/lint.yml
vendored
@@ -12,7 +12,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
@@ -37,7 +37,7 @@ jobs:
|
||||
fi
|
||||
|
||||
- name: Run markdownlint-cli2
|
||||
uses: DavidAnson/markdownlint-cli2-action@8de2aa07cae85fd17c0b35642db70cf5495f1d25 # v24.0.0
|
||||
uses: DavidAnson/markdownlint-cli2-action@6bf21b07787794f89a243495939cd651942aeabe # v24.1.0
|
||||
with:
|
||||
globs: |
|
||||
'**/*.md'
|
||||
@@ -47,7 +47,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
# shellcheck is preinstalled on ubuntu-latest runners.
|
||||
# Start at --severity=error to block real bugs without flagging style
|
||||
|
||||
6
.github/workflows/publish-pypi.yml
vendored
6
.github/workflows/publish-pypi.yml
vendored
@@ -27,12 +27,12 @@ jobs:
|
||||
fi
|
||||
|
||||
- name: Checkout release tag
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: refs/tags/${{ inputs.tag }}
|
||||
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@11f9893b081a58869d3b5fccaea48c9e9e46f990 # v8.3.2
|
||||
uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6
|
||||
@@ -74,7 +74,7 @@ jobs:
|
||||
path: dist/
|
||||
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@11f9893b081a58869d3b5fccaea48c9e9e46f990 # v8.3.2
|
||||
uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0
|
||||
|
||||
- name: Publish to PyPI
|
||||
run: uv publish
|
||||
|
||||
2
.github/workflows/release-trigger.yml
vendored
2
.github/workflows/release-trigger.yml
vendored
@@ -16,7 +16,7 @@ jobs:
|
||||
pull-requests: write
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
fetch-depth: 0
|
||||
token: ${{ secrets.RELEASE_PAT }}
|
||||
|
||||
2
.github/workflows/release.yml
vendored
2
.github/workflows/release.yml
vendored
@@ -12,7 +12,7 @@ jobs:
|
||||
contents: write
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
fetch-depth: 0
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
10
.github/workflows/security.yml
vendored
10
.github/workflows/security.yml
vendored
@@ -19,12 +19,12 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@11f9893b081a58869d3b5fccaea48c9e9e46f990 # v8.3.2
|
||||
uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6
|
||||
@@ -34,7 +34,7 @@ jobs:
|
||||
- name: Check committed audit requirements are current
|
||||
env:
|
||||
DEPENDENCY_DIFF_BASE: ${{ github.event.pull_request.base.sha || github.event.before || '' }}
|
||||
DEPENDENCY_DIFF_HEAD: ${{ github.sha }}
|
||||
DEPENDENCY_DIFF_HEAD: ${{ github.event.pull_request.head.sha || github.sha }}
|
||||
GENERATED_REQUIREMENTS: ${{ runner.temp }}/security-audit-requirements.txt
|
||||
run: python .github/scripts/check_security_requirements.py
|
||||
|
||||
@@ -52,10 +52,10 @@ jobs:
|
||||
python-version: ["3.11", "3.12", "3.13", "3.14"]
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@11f9893b081a58869d3b5fccaea48c9e9e46f990 # v8.3.2
|
||||
uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0
|
||||
|
||||
- name: Set up Python ${{ matrix.python-version }}
|
||||
uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6
|
||||
|
||||
8
.github/workflows/test.yml
vendored
8
.github/workflows/test.yml
vendored
@@ -13,10 +13,10 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@11f9893b081a58869d3b5fccaea48c9e9e46f990 # v8.3.2
|
||||
uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6
|
||||
@@ -34,10 +34,10 @@ jobs:
|
||||
python-version: ["3.13", "3.14"]
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@11f9893b081a58869d3b5fccaea48c9e9e46f990 # v8.3.2
|
||||
uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0
|
||||
|
||||
- name: Set up Python ${{ matrix.python-version }}
|
||||
uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6
|
||||
|
||||
99
AGENTS.md
99
AGENTS.md
@@ -10,6 +10,20 @@ The toolkit supports multiple AI coding assistants, allowing teams to use their
|
||||
|
||||
---
|
||||
|
||||
## Quickstart — Add a New Integration in 5 Steps
|
||||
|
||||
If you are new to the codebase and want to add support for a new AI agent, here is the shortest path from zero to a working integration:
|
||||
|
||||
1. **Choose a base class** — most agents only need `MarkdownIntegration`. See [Choose a base class](#1-choose-a-base-class).
|
||||
2. **Create a subpackage** — add `src/specify_cli/integrations/<package_dir>/__init__.py` with the required `key`, `config`, and `registrar_config` fields.
|
||||
3. **Register it** — add one import and one `_register()` call in `src/specify_cli/integrations/__init__.py` (both alphabetical).
|
||||
4. **Write a test file** — create `tests/integrations/test_integration_<key>.py` (hyphens in the key become underscores in the filename).
|
||||
5. **Run and verify** — use `specify init --integration <key>` to exercise the full install/uninstall cycle.
|
||||
|
||||
Each step is expanded under [Adding a New Integration](#adding-a-new-integration). Note that agent **context files** (`CLAUDE.md`, `AGENTS.md`, …) are **not** handled by the integration — that is owned by the opt-in `agent-context` extension; see [Context file behavior](#4-context-file-behavior).
|
||||
|
||||
---
|
||||
|
||||
## Integration Architecture
|
||||
|
||||
Each AI agent is a self-contained **integration subpackage** under `src/specify_cli/integrations/<key>/`. The subpackage exposes a single class that declares all metadata and inherits setup/teardown logic from a base class. Built-in integrations are then instantiated and added to the global `INTEGRATION_REGISTRY` by `src/specify_cli/integrations/__init__.py` via `_register_builtins()`.
|
||||
@@ -34,6 +48,30 @@ The registry is the **single source of truth for Python integration metadata**.
|
||||
|
||||
---
|
||||
|
||||
## IntegrationManifest — File Tracking
|
||||
|
||||
`manifest.py` provides the `IntegrationManifest` class, which records every file an integration installs. This record is what makes uninstall reliable and safe.
|
||||
|
||||
### How it works
|
||||
|
||||
`setup()` receives an `IntegrationManifest` and writes files through it rather than touching the filesystem directly:
|
||||
|
||||
```python
|
||||
# Produce a new file and record its hash for later verification.
|
||||
manifest.record_file("commands/speckit.plan.md", processed_content)
|
||||
|
||||
# Adopt a pre-existing file the integration is now responsible for.
|
||||
manifest.record_existing(".vscode/settings.json")
|
||||
```
|
||||
|
||||
The manifest is persisted at `.specify/integrations/<key>.manifest.json` (one per integration, keyed by `key`) and stores a SHA-256 hash per file. When the user runs `specify integration uninstall <key>`, `teardown()` delegates to `manifest.uninstall()`, which removes only files whose current hash still matches the recorded value — so files the user later edited by hand are skipped, not clobbered (use `specify integration uninstall <key> --force` to remove modified tracked files anyway).
|
||||
|
||||
### Why this matters
|
||||
|
||||
Without hash-tracked manifests, uninstall would either remove files it should not (destructive) or leave orphans behind (messy). If you write a custom `setup()`, route **every** file you create through `manifest.record_file(...)` (or `record_existing(...)` for files you adopt) so uninstall can reason about them.
|
||||
|
||||
---
|
||||
|
||||
## Adding a New Integration
|
||||
|
||||
### 1. Choose a base class
|
||||
@@ -64,13 +102,14 @@ class KilocodeIntegration(MarkdownIntegration):
|
||||
key = "kilocode"
|
||||
config = {
|
||||
"name": "Kilo Code",
|
||||
"folder": ".kilocode/",
|
||||
"commands_subdir": "workflows",
|
||||
"folder": ".kilo/",
|
||||
"commands_subdir": "commands",
|
||||
"install_url": None,
|
||||
"requires_cli": False,
|
||||
}
|
||||
registrar_config = {
|
||||
"dir": ".kilocode/workflows",
|
||||
"dir": ".kilo/commands",
|
||||
"legacy_dir": ".kilocode/workflows",
|
||||
"format": "markdown",
|
||||
"args": "$ARGUMENTS",
|
||||
"extension": ".md",
|
||||
@@ -201,8 +240,8 @@ Only add custom setup logic when the agent needs non-standard behavior. Integrat
|
||||
specify init my-project --integration <key>
|
||||
|
||||
# Verify files were created in the commands directory configured by
|
||||
# config["folder"] + config["commands_subdir"] (for example, .kilocode/workflows/)
|
||||
ls -R my-project/.kilocode/workflows/
|
||||
# config["folder"] + config["commands_subdir"] (for example, .kilo/commands/)
|
||||
ls -R my-project/.kilo/commands/
|
||||
|
||||
# Uninstall cleanly
|
||||
cd my-project && specify integration uninstall <key>
|
||||
@@ -510,4 +549,54 @@ Disclosure is **continuous**, not a one-time event. A single AI-disclosure parag
|
||||
|
||||
---
|
||||
|
||||
## Error Handling and Debugging
|
||||
|
||||
### Common Errors and Fixes
|
||||
|
||||
| Symptom | Likely Cause | Fix |
|
||||
|---|---|---|
|
||||
| `Integration '<key>' not found` | Missing `_register()` call | Add `_register(<Name>Integration())` inside `_register_builtins()` |
|
||||
| `NameError: name '<Name>Integration' is not defined` at startup | Missing import | Add `from .<package_dir> import <Name>Integration` inside `_register_builtins()` |
|
||||
| CLI check fails for a `requires_cli: True` agent | `key` does not match the executable name | Set `key` to the exact name `shutil.which(key)` must resolve (e.g. `"cursor-agent"`, not `"cursor"`) |
|
||||
| Command files have the wrong argument syntax | Wrong `args` value in `registrar_config` | Use `$ARGUMENTS` for Markdown agents, `{{args}}` for TOML/YAML agents, or the agent's custom placeholder |
|
||||
| `ModuleNotFoundError` on a brand-new subpackage under pytest only | Ambient interpreter with a stale editable `.pth` | Run inside this tree's own venv (see Common Pitfall 6) |
|
||||
| Uninstall leaves files behind, or skips files you expected removed | Files not recorded via the manifest, or their hash changed after install | Route every created file through `manifest.record_file(...)`; user-edited files are intentionally skipped unless `force=True` |
|
||||
| Context file (`CLAUDE.md`, etc.) not updated | Expecting the CLI to manage it | Context files are owned by the opt-in `agent-context` extension, not the integration — see [Context file behavior](#4-context-file-behavior) |
|
||||
|
||||
### Debugging Tips
|
||||
|
||||
**Inspect the manifest** to see what an installed integration tracks:
|
||||
|
||||
```bash
|
||||
cat .specify/integrations/<key>.manifest.json
|
||||
```
|
||||
|
||||
**Verify a CLI tool is detected** before debugging a `requires_cli` agent:
|
||||
|
||||
```bash
|
||||
which <key> # Should print the executable path if installed
|
||||
```
|
||||
|
||||
**Verify the installed output structure** after `specify init`:
|
||||
|
||||
```bash
|
||||
find my-project/<folder> -type f
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Contribution Checklist
|
||||
|
||||
Before opening or merging an integration PR, confirm the following:
|
||||
|
||||
- [ ] Added the integration subpackage under `src/specify_cli/integrations/<package_dir>/`.
|
||||
- [ ] Registered it (import **and** `_register()`) in `src/specify_cli/integrations/__init__.py`, both alphabetical.
|
||||
- [ ] Added or updated tests in `tests/integrations/test_integration_<key>.py`.
|
||||
- [ ] Verified the install/uninstall flow with `specify init --integration <key>`.
|
||||
- [ ] Did **not** add `context_file` handling to the CLI (that belongs to the `agent-context` extension).
|
||||
- [ ] Updated devcontainer files if the agent needs a VS Code extension or CLI install step.
|
||||
- [ ] Updated this guide or other relevant docs if the integration has special setup or limitations.
|
||||
|
||||
---
|
||||
|
||||
*This documentation should be updated whenever new integrations are added to maintain accuracy and completeness.*
|
||||
|
||||
118
CHANGELOG.md
118
CHANGELOG.md
@@ -2,6 +2,124 @@
|
||||
|
||||
<!-- insert new changelog below this comment -->
|
||||
|
||||
## [0.15.0] - 2026-07-30
|
||||
|
||||
### Changed
|
||||
|
||||
- Add yolo to community workflow catalog (#3864)
|
||||
- fix(workflows): guard the shell step's timeout check against OverflowError (#3865)
|
||||
- Add Intent Reconciliation extension to community catalog (#3858)
|
||||
- fix(workflows): validate prompt step 'timeout' like the shell step (#3847)
|
||||
- fix: add utf-8 encoding to registry file open calls (#3816)
|
||||
- fix: eliminate TOCTOU race in file unlink calls (#3815)
|
||||
- test(workflows): name the condition-rejection tests for the real boundary (#3808)
|
||||
- fix: eliminate TOCTOU race in file unlink calls (#3811)
|
||||
- fix(presets): escape user-supplied catalog name/URL in add/remove output (#3806)
|
||||
- fix: add missing utf-8 encoding to registry file open calls (#3810)
|
||||
- [bug-fix] Fix upgrade-overwrites-copilot-skills: pass force=True to extension skill re-registration after upgrade (#3853)
|
||||
- fix(integrations): don't abort uninstall when the manifest can't be deleted (#3805)
|
||||
- test(extensions): update stale manifest validation message assertion (#3859)
|
||||
- fix(agents): coerce a non-string description in TOML command rendering (#3799)
|
||||
- fix(workflows): make security requirements sync deterministic (#3832)
|
||||
- fix(cli): render the literal [suffix] in --tag help and rejection message (#3800)
|
||||
- fix(integrations): preserve non-UTF-8 VS Code settings (#3833)
|
||||
- fix(bundler): treat an explicit-null manifest field as missing, not the text "None" (#3798)
|
||||
- feat: first-class agent-native runtime hooks for integrations (#3704)
|
||||
- fix(extensions): guard the required manifest sections so one bad extension cannot break `extension list` (#3797)
|
||||
- fix(presets): escape installed preset metadata in Rich output (#3826)
|
||||
- fix(workflows): dispatch prompt steps via the resolved executable (#3793)
|
||||
- chore: release 0.14.4, begin 0.14.5.dev0 development (#3850)
|
||||
|
||||
## [0.14.4] - 2026-07-29
|
||||
|
||||
### Changed
|
||||
|
||||
- fix(bundler): degrade non-UTF-8 config reads into BundlerError (#3784)
|
||||
- fix(workflows): escape the step-progress line so step ids render (and `/` stops failing the run) (#3783)
|
||||
- Update Agent Parity Governance preset to v0.4.1 (#3830)
|
||||
- fix(integrations): reject empty --commands-dir in generic raw_options (#3714)
|
||||
- fix(presets): guard non-list/non-mapping provides.templates in PresetManifest (#3712)
|
||||
- fix(auth): resolve az via shutil.which so azure-cli token works on Windows (#3709)
|
||||
- fix(workflows): reject falsy non-mapping workflow-catalogs.yml top level (#3707)
|
||||
- fix(integrations): render hyphenated /speckit-<name> for Droid (always-slash agent) (#3688)
|
||||
- [preset] Update A11Y Governance preset to v0.4.2 (#3828)
|
||||
- [preset] Update Parallel Autonomous Run Governance to v0.2.4 (#3825)
|
||||
- fix: correct Optional type annotation for _resolved_dir parameter (#3801)
|
||||
- fix: add timeout to prompt step subprocess execution (#3768)
|
||||
- fix: handle tags containing / in GitHub release asset URL resolution (#3767)
|
||||
- fix(presets): escape catalog metadata in discovery output (#3773)
|
||||
- Update Autonomous Run Governance preset to v0.3.3 (#3823)
|
||||
- fix: use bounded read for integration catalog HTTP responses (#3763)
|
||||
- docs: add Simplified Chinese translation of README (#3740)
|
||||
- Update Intake Sequencing Governance preset to v0.2.2 (#3809)
|
||||
- fix(workflows): reject non-string/non-boolean 'condition' in if/while/do-while steps (#3706)
|
||||
- fix(bundle): escape catalog metadata in discovery output (#3774)
|
||||
- fix(workflows,extensions): tolerate non-list catalog tags in search/info display (#3770)
|
||||
- fix: correct nullable resolved directory annotation (#3771)
|
||||
- fix(presets): tolerate non-string and non-list catalog fields in preset search/info (#3769)
|
||||
- fix(integrations): escape catalog metadata in discovery output (#3772)
|
||||
- Update Verify Review Ship extension to v0.4.2 (#3792)
|
||||
- fix(integrations): preserve native skill invocation prefixes (#3663)
|
||||
- Update Intake Review Governance preset to v0.2.0 (#3796)
|
||||
- fix(constitution): stop propagating guidance into templates (#3737) (#3790)
|
||||
- chore: release 0.14.3, begin 0.14.4.dev0 development (#3795)
|
||||
|
||||
## [0.14.3] - 2026-07-28
|
||||
|
||||
### Changed
|
||||
|
||||
- Update Intake Authoring Governance preset to v0.3.0 (#3788)
|
||||
- fix(copilot): honor preset command template overrides (#3592)
|
||||
- clarify: require real interrogatives, ban topic-label questions (#3745)
|
||||
- feat: Add Alquimia AI integration (#2734)
|
||||
- harden: secure extension and preset archive downloads (#3141)
|
||||
- fix: correct Optional type annotation for context_note parameter (#3765)
|
||||
- Update AGENTS.md (#2626)
|
||||
- fix(extensions): tolerate non-string catalog name in display-name lookup (#3747)
|
||||
- fix(presets): coerce non-string catalog tags before joining (#3743)
|
||||
- fix: register extensions for the active integration only (#3459)
|
||||
- fix(extensions): tolerate non-string tags in catalog search (#3746)
|
||||
- fix(extensions): hyphenate command names in 'extension info' listing (#3744)
|
||||
- fix(workflows): escape remaining untrusted fields in `workflow info` (#3731)
|
||||
- fix(extensions): guard non-numeric catalog downloads in search/info rendering (#3710)
|
||||
- fix(agent-context): apply default markers when config markers are blank (bash) (#3736)
|
||||
- fix: escape Rich markup in catalog list output (#3738)
|
||||
- fix(workflows): guard non-mapping 'workflow:' block in WorkflowDefinition (#3694)
|
||||
- fix(bundler): reject unsupported schema_version in _merge_config (align readers) (#3711)
|
||||
- Update Linear Weave extension to v1.0.1 (#3762)
|
||||
- Add Intake Sequencing Governance preset to community catalog (#3761)
|
||||
- Update Quality Gates (Enforcement Layer) extension to v0.3.3 (#3760)
|
||||
- Update Verify Review Ship extension to v0.4.1 (#3759)
|
||||
- fix(agent-context): discover nested plans in Python port mtime fallback (#3734)
|
||||
- fix(extensions): make shipped scripts executable after install (#3723)
|
||||
- docs(assess): clarify the pipeline works on an empty project (#3732)
|
||||
- chore: release 0.14.2, begin 0.14.3.dev0 development (#3730)
|
||||
|
||||
## [0.14.2] - 2026-07-24
|
||||
|
||||
### Changed
|
||||
|
||||
- Update Intake Review Governance preset to v0.1.1 (#3729)
|
||||
- Update Verify Review Ship extension to v0.3.0 (#3728)
|
||||
- Update Architecture Guard extension to v1.13.1 (#3724)
|
||||
- docs(upgrade): Claude Code files live in .claude/skills, not .claude/commands (#3708)
|
||||
- fix(kilocode): install commands under .kilo/commands (#3672)
|
||||
- fix(auth): normalize whitespace in auth-config env-var/id references at store time (#3691)
|
||||
- fix(workflows): guard non-mapping 'inputs:' block in engine._resolve_inputs (#3696)
|
||||
- Update Intake Authoring Governance preset to v0.2.0 (#3721)
|
||||
- docs: clarify shell-step interpolation safety (#3719)
|
||||
- [extension] Add Blueprint Index — Living Architecture Map extension to community catalog (#3718)
|
||||
- fix(github-http): return None on malformed host in resolve_github_release_asset_api_url (#3715)
|
||||
- fix(integrations): declare PiIntegration multi_install_safe (#3652)
|
||||
- harden: remove shell parameter from run_command() (#3716)
|
||||
- chore(deps): bump github/codeql-action/init from 4.37.1 to 4.37.3 (#3699)
|
||||
- fix: auto-correct conflicting feature prefixes (#1829)
|
||||
- chore(deps): bump actions/checkout from 6.0.3 to 7.0.1 (#3703)
|
||||
- chore(deps): bump DavidAnson/markdownlint-cli2-action (#3702)
|
||||
- chore(deps): bump actions/setup-node from 6.4.0 to 7.0.0 (#3701)
|
||||
- chore(deps): bump astral-sh/setup-uv from 8.3.2 to 9.0.0 (#3700)
|
||||
- chore: release 0.14.1, begin 0.14.2.dev0 development (#3698)
|
||||
|
||||
## [0.14.1] - 2026-07-23
|
||||
|
||||
### Changed
|
||||
|
||||
@@ -15,6 +15,11 @@
|
||||
<a href="https://github.github.io/spec-kit/"><img src="https://img.shields.io/badge/docs-GitHub_Pages-blue" alt="Documentation"/></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<strong>English</strong> ·
|
||||
<a href="./README.zh-CN.md">简体中文</a>
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
## Table of Contents
|
||||
|
||||
361
README.zh-CN.md
Normal file
361
README.zh-CN.md
Normal file
@@ -0,0 +1,361 @@
|
||||
<div align="center">
|
||||
<img src="./media/logo_large.webp" alt="Spec Kit Logo" width="200" height="200"/>
|
||||
<h1>🌱 Spec Kit</h1>
|
||||
<h3><em>在动手编码之前,先定义要构建什么 —— 适配任意 AI 编码助手。</em></h3>
|
||||
</div>
|
||||
|
||||
<p align="center">
|
||||
<strong>一个开源工具套件,帮助你借助任意 AI 编码助手构建高质量软件 —— 内置开箱即用的规范驱动流程(也可自带流程),可无限扩展、由社区驱动,并为整个组织的协作而设计。</strong>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/github/spec-kit/releases/latest"><img src="https://img.shields.io/github/v/release/github/spec-kit" alt="Latest Release"/></a>
|
||||
<a href="https://github.com/github/spec-kit/stargazers"><img src="https://img.shields.io/github/stars/github/spec-kit?style=social" alt="GitHub stars"/></a>
|
||||
<a href="https://github.com/github/spec-kit/blob/main/LICENSE"><img src="https://img.shields.io/github/license/github/spec-kit" alt="License"/></a>
|
||||
<a href="https://github.github.io/spec-kit/"><img src="https://img.shields.io/badge/docs-GitHub_Pages-blue" alt="Documentation"/></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="./README.md">English</a> ·
|
||||
<strong>简体中文</strong>
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
## 目录
|
||||
|
||||
- [🤔 什么是规范驱动开发?](#-什么是规范驱动开发)
|
||||
- [⚡ 快速开始](#-快速开始)
|
||||
- [📽️ 视频概览](#️-视频概览)
|
||||
- [🌍 社区](#-社区)
|
||||
- [🤖 支持的 AI 编码助手集成](#-支持的-ai-编码助手集成)
|
||||
- [🔧 Specify CLI 参考](#-specify-cli-参考)
|
||||
- [🧩 打造你自己的 Spec Kit:扩展与预设](#-打造你自己的-spec-kit扩展与预设)
|
||||
- [📦 捆绑包:面向角色的一键配置](#-捆绑包面向角色的一键配置)
|
||||
- [📚 核心理念](#-核心理念)
|
||||
- [🌟 开发阶段](#-开发阶段)
|
||||
- [🎯 实验目标](#-实验目标)
|
||||
- [🔧 环境要求](#-环境要求)
|
||||
- [📖 深入了解](#-深入了解)
|
||||
- [💬 支持](#-支持)
|
||||
- [🙏 致谢](#-致谢)
|
||||
- [📄 许可证](#-许可证)
|
||||
|
||||
## 🤔 什么是规范驱动开发?
|
||||
|
||||
规范驱动开发(Spec-Driven Development)**颠覆了**传统软件开发的思路。几十年来,代码一直是核心 —— 规范只是编码这项"正事"开始前搭起、随后就被丢弃的脚手架。规范驱动开发改变了这一点:**规范本身变得可执行**,它不再只是引导实现,而是直接生成可运行的实现。
|
||||
|
||||
## ⚡ 快速开始
|
||||
|
||||
### 1. 安装 Specify CLI
|
||||
|
||||
需要 **[uv](https://docs.astral.sh/uv/)**([安装 uv](./docs/install/uv.md))。将 `vX.Y.Z` 替换为 [Releases](https://github.com/github/spec-kit/releases) 中最新的发布标签 —— 记得保留开头的 `v`(例如 `v0.12.11`,而不是 `0.12.11`):
|
||||
|
||||
```bash
|
||||
uv tool install specify-cli --from git+https://github.com/github/spec-kit.git@vX.Y.Z
|
||||
```
|
||||
|
||||
更倾向从 PyPI 安装?`specify-cli` 包同样发布在那里:
|
||||
|
||||
```bash
|
||||
uv tool install specify-cli
|
||||
```
|
||||
|
||||
其他安装方式、安装校验、升级以及故障排查,请参阅[安装指南](./docs/installation.md)。
|
||||
|
||||
### 2. 初始化项目
|
||||
|
||||
```bash
|
||||
specify init my-project --integration copilot
|
||||
cd my-project
|
||||
```
|
||||
|
||||
要检查更新或升级已安装的 CLI,可使用自管理命令。更详细的场景和自定义选项请参阅[升级指南](./docs/upgrade.md)。
|
||||
|
||||
```bash
|
||||
# 检查是否有更新版本可用(只读操作 —— 不会修改任何内容)
|
||||
specify self check
|
||||
|
||||
# 预览升级将执行的操作,但不实际升级
|
||||
specify self upgrade --dry-run
|
||||
|
||||
# 就地升级到最新稳定版(自动识别 uv tool 与 pipx 安装方式)
|
||||
specify self upgrade
|
||||
|
||||
# 或锁定到指定的发布标签(将 vX.Y.Z[suffix] 替换为你想要的标签)
|
||||
specify self upgrade --tag vX.Y.Z[suffix]
|
||||
```
|
||||
|
||||
直接运行 `specify self upgrade` 会立即执行,与 `pip install -U`、`npm update` 等命令一样无需额外确认。对于 `uv tool` 安装的情况,它在底层会执行 `uv tool install specify-cli --force --from <git ref>`,因此锁定的发布标签同样有效,包括 dev、alpha/beta/rc 或带构建元数据的后缀。`uvx`(临时运行)和源码检出会被自动识别,此时会给出针对具体路径的操作建议,而不会执行安装程序。可通过设置 `SPECIFY_UPGRADE_TIMEOUT_SECS` 来限制安装子进程的最长运行时间(默认无超时限制 —— 必要时用 `Ctrl+C` 中断)。
|
||||
|
||||
### 3. 确立项目准则
|
||||
|
||||
在项目目录下启动你的编码助手。大多数助手将 spec-kit 暴露为 `/speckit.*` 斜杠命令;处于技能(skills)模式的 Codex CLI 则使用 `$speckit-*`;GitHub Copilot CLI 使用 `/agents` 来选择助手,或直接在提示词中指定它。
|
||||
|
||||
使用 **`/speckit.constitution`** 命令来创建项目的治理准则和开发指南,它们将指导后续所有开发工作。
|
||||
|
||||
```bash
|
||||
/speckit.constitution Create principles focused on code quality, testing standards, user experience consistency, and performance requirements
|
||||
```
|
||||
|
||||
### 4. 编写规范
|
||||
|
||||
使用 **`/speckit.specify`** 命令描述你想构建什么。聚焦于**做什么**和**为什么做**,而不是技术栈。
|
||||
|
||||
```bash
|
||||
/speckit.specify Build an application that can help me organize my photos in separate photo albums. Albums are grouped by date and can be re-organized by dragging and dropping on the main page. Albums are never in other nested albums. Within each album, photos are previewed in a tile-like interface.
|
||||
```
|
||||
|
||||
### 5. 制定技术实现方案
|
||||
|
||||
使用 **`/speckit.plan`** 命令提供你的技术栈和架构选择。
|
||||
|
||||
```bash
|
||||
/speckit.plan The application uses Vite with minimal number of libraries. Use vanilla HTML, CSS, and JavaScript as much as possible. Images are not uploaded anywhere and metadata is stored in a local SQLite database.
|
||||
```
|
||||
|
||||
### 6. 拆解为任务
|
||||
|
||||
使用 **`/speckit.tasks`** 从实现方案生成一份可执行的任务清单。
|
||||
|
||||
```bash
|
||||
/speckit.tasks
|
||||
```
|
||||
|
||||
### 7. 执行实现
|
||||
|
||||
使用 **`/speckit.implement`** 执行所有任务,按方案构建你的功能。
|
||||
|
||||
```bash
|
||||
/speckit.implement
|
||||
```
|
||||
|
||||
详细的分步说明,请参阅我们的[完整指南](./spec-driven.md)。
|
||||
|
||||
## 📽️ 视频概览
|
||||
|
||||
想看看 Spec Kit 的实际效果?观看我们的[视频概览](https://www.youtube.com/watch?v=a9eR1xsfvHg&pp=0gcJCckJAYcqIYzv)!
|
||||
|
||||
[](https://www.youtube.com/watch?v=a9eR1xsfvHg&pp=0gcJCckJAYcqIYzv)
|
||||
|
||||
## 🌍 社区
|
||||
|
||||
在 [Spec Kit 文档站点](https://github.github.io/spec-kit/)上探索由社区贡献的资源:
|
||||
|
||||
- [扩展(Extensions)](https://github.github.io/spec-kit/community/extensions.html) —— 命令、钩子与各类能力
|
||||
- [预设(Presets)](https://github.github.io/spec-kit/community/presets.html) —— 模板与术语覆盖
|
||||
- [捆绑包(Bundles)](https://github.github.io/spec-kit/community/bundles.html) —— 由现有组件组合而成的角色与团队技术栈
|
||||
- [实战演练(Walkthroughs)](https://github.github.io/spec-kit/community/walkthroughs.html) —— 端到端的 SDD 场景
|
||||
- [伙伴项目(Friends)](https://github.github.io/spec-kit/community/friends.html) —— 扩展 Spec Kit 或基于它构建的项目
|
||||
|
||||
> [!NOTE]
|
||||
> 社区贡献由各自的作者独立创建和维护。请在安装前审阅源代码,并自行斟酌使用。
|
||||
|
||||
想要参与贡献?请参阅[扩展发布指南](extensions/EXTENSION-PUBLISHING-GUIDE.md)、[预设发布指南](presets/PUBLISHING.md)或[社区捆绑包指南](docs/community/bundles.md)。
|
||||
|
||||
## 🤖 支持的 AI 编码助手集成
|
||||
|
||||
Spec Kit 可与 30 多个 AI 编码助手协作 —— 既包括 CLI 工具,也包括基于 IDE 的助手。完整列表以及相关说明和使用细节,请参阅[支持的 AI 编码助手集成](https://github.github.io/spec-kit/reference/integrations.html)指南。
|
||||
|
||||
运行 `specify integration list` 可查看当前安装版本中所有可用的集成。
|
||||
|
||||
## 可用的斜杠命令
|
||||
|
||||
运行 `specify init` 后,你的 AI 编码助手就能使用这些斜杠命令来进行结构化开发。对于支持技能模式的集成,传入 `--integration <agent> --integration-options="--skills"` 会安装助手技能,而不是斜杠命令的提示词文件。
|
||||
|
||||
### 核心命令
|
||||
|
||||
规范驱动开发工作流中必不可少的命令:
|
||||
|
||||
| 命令 | 助手技能 | 说明 |
|
||||
| ------------------------ | ---------------------- | ---------------------------------------------------------- |
|
||||
| `/speckit.constitution` | `speckit-constitution` | 创建或更新项目的治理准则和开发指南 |
|
||||
| `/speckit.specify` | `speckit-specify` | 定义你想构建什么(需求与用户故事) |
|
||||
| `/speckit.plan` | `speckit-plan` | 结合所选技术栈制定技术实现方案 |
|
||||
| `/speckit.tasks` | `speckit-tasks` | 生成可执行的实现任务清单 |
|
||||
| `/speckit.taskstoissues` | `speckit-taskstoissues`| 将生成的任务清单转换为 GitHub issue,便于跟踪与执行 |
|
||||
| `/speckit.implement` | `speckit-implement` | 执行所有任务,按方案构建功能 |
|
||||
| `/speckit.converge` | `speckit-converge` | 对照规范/方案/任务评估代码库,并将剩余工作追加为新任务 |
|
||||
|
||||
### 可选命令
|
||||
|
||||
用于提升质量与做校验的额外命令:
|
||||
|
||||
| 命令 | 助手技能 | 说明 |
|
||||
| -------------------- | ---------------------- | ------------------------------------------------------------------------------------------------- |
|
||||
| `/speckit.clarify` | `speckit-clarify` | 澄清描述不充分的部分(建议在 `/speckit.plan` 之前使用;旧称 `/quizme`) |
|
||||
| `/speckit.analyze` | `speckit-analyze` | 跨制品的一致性与覆盖度分析(在 `/speckit.tasks` 之后、`/speckit.implement` 之前运行) |
|
||||
| `/speckit.checklist` | `speckit-checklist` | 生成自定义质量清单,校验需求的完整性、清晰度与一致性(好比"为自然语言写单元测试") |
|
||||
|
||||
## 🔧 Specify CLI 参考
|
||||
|
||||
完整的命令详情、选项与示例,请参阅 [CLI 参考文档](https://github.github.io/spec-kit/reference/overview.html)。
|
||||
|
||||
## 🧩 打造你自己的 Spec Kit:扩展与预设
|
||||
|
||||
Spec Kit 可通过两套互补的机制进行深度定制 —— **扩展(extensions)** 和 **预设(presets)** —— 以及面向单个项目的本地覆盖,用于临时性调整:
|
||||
|
||||
| 优先级 | 组件类型 | 位置 |
|
||||
| -----: | ---------------------------------- | -------------------------------- |
|
||||
| ⬆ 1 | 项目本地覆盖 | `.specify/templates/overrides/` |
|
||||
| 2 | 预设 —— 定制核心与扩展 | `.specify/presets/templates/` |
|
||||
| 3 | 扩展 —— 新增能力 | `.specify/extensions/templates/` |
|
||||
| ⬇ 4 | Spec Kit 核心 —— 内置 SDD 命令与模板 | `.specify/templates/` |
|
||||
|
||||
- **模板**在**运行时**解析 —— Spec Kit 从高到低遍历优先级栈,使用第一个匹配项。
|
||||
- 项目本地覆盖(`.specify/templates/overrides/`)允许对单个项目做一次性调整,无需创建完整的预设。
|
||||
- **扩展/预设命令**在**安装时**生效 —— 当你运行 `specify extension add` 或 `specify preset add` 时,命令文件会被写入助手目录(如 `.claude/commands/`)。
|
||||
- 若多个预设或扩展提供了同一命令,优先级最高的版本生效。移除时,次优先级的版本会自动恢复。
|
||||
- 若不存在任何覆盖或自定义,Spec Kit 使用核心默认配置。
|
||||
|
||||
### 扩展 —— 新增能力
|
||||
|
||||
当你需要 Spec Kit 核心之外的功能时,使用**扩展**。扩展可引入新命令和模板 —— 例如添加核心 SDD 命令未覆盖的领域特定工作流、集成外部工具,或新增全新的开发阶段。它们扩展了 *Spec Kit 能做什么*。
|
||||
|
||||
```bash
|
||||
# 搜索可用扩展
|
||||
specify extension search
|
||||
|
||||
# 安装扩展
|
||||
specify extension add <extension-name>
|
||||
```
|
||||
|
||||
举例来说,扩展可以添加 Jira 集成、实现后代码审查、V 模型测试追溯性,或项目健康诊断等功能。
|
||||
|
||||
完整命令指南请参阅[扩展参考文档](https://github.github.io/spec-kit/reference/extensions.html)。浏览[社区扩展](https://github.github.io/spec-kit/community/extensions.html)了解现有资源。
|
||||
|
||||
### 预设 —— 定制现有工作流
|
||||
|
||||
当你想改变 Spec Kit 的*工作方式*而不是新增能力时,使用**预设**。预设会覆盖核心及已安装扩展中附带的模板和命令 —— 例如强制使用面向合规的规范格式、采用领域特定术语,或对方案和任务应用组织规范。预设定制的是 Spec Kit 及其扩展生成的制品与指令。
|
||||
|
||||
```bash
|
||||
# 搜索可用预设
|
||||
specify preset search
|
||||
|
||||
# 安装预设
|
||||
specify preset add <preset-name>
|
||||
```
|
||||
|
||||
举例来说,预设可以重构规范模板以要求监管追溯性,将工作流适配为你所用的方法论(如敏捷、看板、瀑布、用户任务驱动或领域驱动设计),在方案中添加强制安全审查关卡,强制要求测试优先的任务排序,或将整个工作流本地化为其他语言。[海盗语演示](https://github.com/mnriem/spec-kit-pirate-speak-preset-demo)充分展示了定制的深度。多个预设可按优先级叠加使用。
|
||||
|
||||
完整命令指南以及解析顺序和优先级叠加说明,请参阅[预设参考文档](https://github.github.io/spec-kit/reference/presets.html)。
|
||||
|
||||
## 📦 捆绑包:面向角色的一键配置
|
||||
|
||||
扩展和预设是独立的构建模块。而**捆绑包(bundle)**将一组精选的扩展、预设、步骤和工作流打包成一个带版本、面向角色的配置,从而可以用一条命令为整个团队角色(产品经理、业务分析师、安全研究员、开发者……)完成配置。
|
||||
|
||||
捆绑包由一份手写的 `bundle.yml` 清单描述。它将每个组件锁定到具体版本,并可选择性地面向特定集成;未指定 `integration` 的捆绑包是**中立的**,会沿用项目当前已使用的集成。
|
||||
|
||||
```bash
|
||||
# 在当前激活的目录栈中发现捆绑包
|
||||
specify bundle search [<query>]
|
||||
|
||||
# 查看捆绑包将添加的确切组件集合(与实际安装的内容一致)
|
||||
specify bundle info <bundle-id>
|
||||
|
||||
# 一步安装捆绑包的完整组件集合
|
||||
specify bundle install <bundle-id>
|
||||
|
||||
# 查看已安装内容,然后以非破坏性方式更新或移除
|
||||
specify bundle list
|
||||
specify bundle update <bundle-id> # 或 --all
|
||||
specify bundle remove <bundle-id> # 仅移除此捆绑包的组件
|
||||
```
|
||||
|
||||
捆绑包从一个**按优先级排序的目录栈**(项目 > 用户 > 内置)中解析。每个来源都带有安装策略:`install-allowed` 来源可用于安装,而 `discovery-only` 来源在 `search`/`info` 中可见但拒绝安装。可通过 `specify bundle catalog list|add|remove` 管理目录栈。
|
||||
|
||||
作者在本地校验并打包捆绑包。分发方式是托管构建产物并添加一个目录来源;社区捆绑包投稿请使用 [Bundle Submission](https://github.com/github/spec-kit/issues/new?template=bundle_submission.yml) issue 模板,以便对所需的组件目录和安装证据进行审阅:
|
||||
|
||||
```bash
|
||||
specify bundle validate --path ./my-bundle # 结构与引用检查
|
||||
specify bundle build --path ./my-bundle # 生成带版本的 .zip 产物
|
||||
```
|
||||
|
||||
[`examples/bundles/`](examples/bundles/) 目录下有四份可直接阅读的示例清单(产品经理、业务分析师、安全研究员、开发者)。
|
||||
|
||||
关键保证:`info` 展示的内容与 `install` 添加的内容完全一致(透明性);安装是幂等的,且限定在项目根目录内;`remove` 绝不会触碰其他已安装捆绑包仍需要的组件;所有消费/创作命令都能针对本地或锁定的来源**离线**工作。
|
||||
|
||||
### 何时用哪个
|
||||
|
||||
| 目标 | 使用 |
|
||||
| --- | --- |
|
||||
| 添加全新的命令或工作流 | 扩展 |
|
||||
| 定制规范、方案或任务的格式 | 预设 |
|
||||
| 集成外部工具或服务 | 扩展 |
|
||||
| 强制执行组织或监管规范 | 预设 |
|
||||
| 交付可复用的领域特定模板 | 均可 —— 预设用于模板覆盖,扩展用于随新命令一起打包的模板 |
|
||||
| 用一条命令完成完整的角色配置 | 捆绑包 |
|
||||
|
||||
## 📚 核心理念
|
||||
|
||||
规范驱动开发是一套结构化流程,它强调:
|
||||
|
||||
- **意图驱动开发** —— 让规范先定义"*做什么*",再谈"*怎么做*"
|
||||
- **丰富的规范撰写** —— 借助护栏与组织准则来编写规范
|
||||
- **多步精炼** —— 而非从提示词一次性生成代码
|
||||
- **充分依赖**先进 AI 模型对规范的解读能力
|
||||
|
||||
## 🌟 开发阶段
|
||||
|
||||
| 阶段 | 侧重点 | 关键活动 |
|
||||
| ----------------------------------------- | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| **从 0 到 1 开发**("绿地/Greenfield") | 从零生成 | <ul><li>从高层需求出发</li><li>生成规范</li><li>规划实现步骤</li><li>构建生产就绪的应用</li></ul> |
|
||||
| **创意探索** | 并行实现 | <ul><li>探索多样化的解决方案</li><li>支持多种技术栈与架构</li><li>试验不同的用户体验模式</li></ul> |
|
||||
| **迭代增强**("棕地/Brownfield") | 存量系统现代化 | <ul><li>迭代式添加功能</li><li>现代化改造遗留系统</li><li>调整流程</li></ul> |
|
||||
|
||||
对于已有项目,请将 Spec Kit 工具本身的更新与功能制品的演进分开处理:升级时刷新受管理的项目文件,而在预期行为发生变化时更新 `specs/` 制品。[规范演进指南](./docs/guides/evolving-specs.md)介绍了推荐的棕地迭代循环。
|
||||
|
||||
## 🎯 实验目标
|
||||
|
||||
我们的研究与实验聚焦于:
|
||||
|
||||
### 技术无关性
|
||||
|
||||
- 使用多样化的技术栈构建应用
|
||||
- 验证这一假设:规范驱动开发是一套流程,不与特定技术、编程语言或框架绑定
|
||||
|
||||
### 企业级约束
|
||||
|
||||
- 展示关键业务应用的开发
|
||||
- 纳入组织层面的约束(云服务商、技术栈、工程实践)
|
||||
- 支持企业设计系统与合规要求
|
||||
|
||||
### 以用户为中心的开发
|
||||
|
||||
- 为不同的用户群体和偏好构建应用
|
||||
- 支持多种开发方式(从"氛围编码"到 AI 原生开发)
|
||||
|
||||
### 创意与迭代流程
|
||||
|
||||
- 验证并行实现探索的理念
|
||||
- 提供稳健的迭代式功能开发工作流
|
||||
- 将流程扩展到升级与现代化改造任务
|
||||
|
||||
## 🔧 环境要求
|
||||
|
||||
- **Linux/macOS/Windows**
|
||||
- [受支持的](#-支持的-ai-编码助手集成) AI 编码助手。
|
||||
- [uv](https://docs.astral.sh/uv/) 用于包管理(推荐),或 [pipx](https://pipx.pypa.io/) 用于持久化安装
|
||||
- [Python 3.11+](https://www.python.org/downloads/)
|
||||
- [Git](https://git-scm.com/downloads)
|
||||
|
||||
如果你在使用某个助手时遇到问题,欢迎提交 issue,以便我们完善相应集成。
|
||||
|
||||
## 📖 深入了解
|
||||
|
||||
- **[完整的规范驱动开发方法论](./spec-driven.md)** —— 深入了解整个流程
|
||||
- **[快速上手指南](https://github.github.io/spec-kit/quickstart.html)** —— 分步实现演练
|
||||
|
||||
---
|
||||
|
||||
## 💬 支持
|
||||
|
||||
如需帮助,请提交 [GitHub issue](https://github.com/github/spec-kit/issues/new)。我们欢迎缺陷报告、功能建议,以及关于使用规范驱动开发的各类问题。
|
||||
|
||||
## 🙏 致谢
|
||||
|
||||
本项目深受 [John Lam](https://github.com/jflam) 的工作与研究的影响,并在其基础上构建。
|
||||
|
||||
## 📄 许可证
|
||||
|
||||
本项目基于 MIT 开源许可证的条款授权。完整条款请参阅 [LICENSE](./LICENSE) 文件。
|
||||
@@ -36,6 +36,7 @@ The following community-contributed extensions are available in [`catalog.commun
|
||||
| Archive Extension | Archive merged features into main project memory. | `docs` | Read+Write | [spec-kit-archive](https://github.com/stn1slv/spec-kit-archive) |
|
||||
| Azure DevOps Integration | Sync user stories and tasks to Azure DevOps work items using OAuth authentication | `integration` | Read+Write | [spec-kit-azure-devops](https://github.com/pragya247/spec-kit-azure-devops) |
|
||||
| Blueprint | Stay code-literate in AI-driven development: review a complete code blueprint for every task from spec artifacts before /speckit.implement runs | `docs` | Read+Write | [spec-kit-blueprint](https://github.com/chordpli/spec-kit-blueprint) |
|
||||
| Blueprint Index — Living Architecture Map | A living architecture map for spec-driven projects, kept honest by a deterministic, low-friction, machine-first CI gate (JSON, self-healable) that blocks only when the map contradicts the specs or code. Brownfield or greenfield. | `process` | Read+Write | [spec-kit-blueprint](https://github.com/ogil109/spec-kit-blueprint) |
|
||||
| Branch Convention | Configurable branch and folder naming conventions for /specify with presets and custom patterns | `process` | Read+Write | [spec-kit-branch-convention](https://github.com/Quratulain-bilal/spec-kit-branch-convention) |
|
||||
| Brownfield Bootstrap | Bootstrap spec-kit for existing codebases — auto-discover architecture and adopt SDD incrementally | `process` | Read+Write | [spec-kit-brownfield](https://github.com/Quratulain-bilal/spec-kit-brownfield) |
|
||||
| BrownKit | Evidence-driven capability discovery, security and QA risk assessment for existing codebases | `process` | Read+Write | [BrownKit](https://github.com/MaksimShevtsov/BrownKit) |
|
||||
@@ -65,6 +66,7 @@ The following community-contributed extensions are available in [`catalog.commun
|
||||
| Improve Extension | Audits any codebase as a senior advisor and writes prioritized, self-contained spec prompts under specs/ that the spec-kit lifecycle can process | `process` | Read+Write | [spec-kit-improve](https://github.com/d0whc3r/spec-kit-improve) |
|
||||
| Intake | Normalize PRD, design, HTML SSOT, and test-case evidence into SDD-ready intake artifacts. | `docs` | Read+Write | [spec-kit-intake](https://github.com/bigsmartben/spec-kit-intake) |
|
||||
| Intelligent Agent Orchestrator | Cross-catalog agent discovery and intelligent prompt-to-command routing | `process` | Read+Write | [spec-kit-orchestrator](https://github.com/pragya247/spec-kit-orchestrator) |
|
||||
| Intent Reconciliation | Reconcile implementation-discovered decisions against approved feature intent | `process` | Read+Write | [spec-kit-reconcile](https://github.com/SuhaibAslam/spec-kit-reconcile) |
|
||||
| Iterate | Iterate on spec documents with a two-phase define-and-apply workflow — refine specs mid-implementation and go straight back to building | `docs` | Read+Write | [spec-kit-iterate](https://github.com/imviancagrace/spec-kit-iterate) |
|
||||
| Jira Integration | Create Jira Epics, Stories, and Issues from spec-kit specifications and task breakdowns with configurable hierarchy and custom field support | `integration` | Read+Write | [spec-kit-jira](https://github.com/mbachorik/spec-kit-jira) |
|
||||
| Jira Integration (Sync Engine) | Idempotent, drift-aware, fail-closed reconcile engine mirroring spec-kit specs into Jira (Epic per repo, Story per spec, Subtask per phase) | `integration` | Read+Write | [spec-kit-jira-sync](https://github.com/ashbrener/spec-kit-jira-sync) |
|
||||
@@ -158,7 +160,7 @@ The following community-contributed extensions are available in [`catalog.commun
|
||||
| Token Economy | Token routing, measured savings, and context audit workflows | `process` | Read+Write | [spec-kit-token-economy](https://github.com/formin/spec-kit-token-economy) |
|
||||
| V-Model Extension Pack | Enforces V-Model paired generation of development specs and test specs with full traceability | `docs` | Read+Write | [spec-kit-v-model](https://github.com/leocamello/spec-kit-v-model) |
|
||||
| Verify Extension | Post-implementation quality gate that validates implemented code against specification artifacts | `code` | Read-only | [spec-kit-verify](https://github.com/ismaelJimenez/spec-kit-verify) |
|
||||
| Verify Review Ship | Adds post-implementation verify, review, and ship readiness gates to Spec Kit workflows | `process` | Read-only | [spec-kit-verify-review-ship](https://github.com/cadugevaerd/spec-kit-verify-review-ship) |
|
||||
| Verify Review Ship | Post-convergence operational verification, technical review, learning governance, and transactional delivery. | `process` | Read+Write | [spec-kit-verify-review-ship](https://github.com/cadugevaerd/spec-kit-verify-review-ship) |
|
||||
| Verify Tasks Extension | Detect phantom completions: tasks marked [X] in tasks.md with no real implementation | `code` | Read-only | [spec-kit-verify-tasks](https://github.com/datastone-inc/spec-kit-verify-tasks) |
|
||||
| Version Guard | Verify tech stack versions against live npm registries before planning and implementation | `process` | Read-only | [spec-kit-version-guard](https://github.com/KevinBrown5280/spec-kit-version-guard) |
|
||||
| What-if Analysis | Preview the downstream impact (complexity, effort, tasks, risks) of requirement changes before committing to them | `visibility` | Read-only | [spec-kit-whatif](https://github.com/DevAbdullah90/spec-kit-whatif) |
|
||||
|
||||
@@ -7,11 +7,11 @@ The following community-contributed presets customize how Spec Kit behaves — o
|
||||
|
||||
| Preset | Purpose | Provides | Requires | URL |
|
||||
|--------|---------|----------|----------|-----|
|
||||
| A11Y Governance | Adds WCAG 2.2 AA governance, accessible text/JSON status parity, bilingual DE/EN delivery, CEFR-B2 readability, inclusive content, didactic-comment review, and audit-ready evidence | 10 templates, 3 commands | — | [spec-kit-preset-a11y-governance](https://github.com/hindermath/spec-kit-preset-a11y-governance) |
|
||||
| Agent Parity Governance | Adds shared-guidance and generated-command parity, fleet-completion evidence, secret-free runner/status metadata, audit-ready evidence, and agent-neutral model routing. | 6 templates, 3 commands | — | [spec-kit-preset-agent-parity-governance](https://github.com/hindermath/spec-kit-preset-agent-parity-governance) |
|
||||
| A11Y Governance | Adds accessibility (WCAG 2.2 AA), accessible text and JSON status parity, bilingual DE/EN delivery, CEFR-B2 readability, inclusive-content governance, didactic inline-code-comment review, and audit-ready Spec-Kit run evidence to Spec Kit | 10 templates, 3 commands | — | [spec-kit-preset-a11y-governance](https://github.com/hindermath/spec-kit-preset-a11y-governance) |
|
||||
| Agent Parity Governance | Adds shared-guidance and generated-command parity, repository-fleet completion evidence, secret-free runner/status metadata, audit-ready Spec-Kit run evidence, and agent-neutral model-routing guidance across declared AI-agent surfaces. | 6 templates, 3 commands | — | [spec-kit-preset-agent-parity-governance](https://github.com/hindermath/spec-kit-preset-agent-parity-governance) |
|
||||
| AIDE In-Place Migration | Adapts the AIDE extension workflow for in-place technology migrations (X → Y pattern) — adds migration objectives, verification gates, knowledge documents, and behavioral equivalence criteria | 2 templates, 8 commands | AIDE extension | [spec-kit-presets](https://github.com/mnriem/spec-kit-presets) |
|
||||
| Architecture Governance | Adds secure software architecture, resumable remote-transaction boundaries, STRIDE+CAPEC threat modeling, arc42 security cross-cutting concepts, S-ADRs, Zero Trust applicability, OWASP SAMM governance, BSI C3A cloud autonomy, BSI C5 cloud compliance assurance, and audit-ready Spec Kit run evidence | 13 templates, 3 commands | — | [spec-kit-preset-architecture-governance](https://github.com/hindermath/spec-kit-preset-architecture-governance) |
|
||||
| Autonomous Run Governance | Adds permission-bounded, evidence-first governance for complete autonomous Spec Kit delivery, including validated status, stop, explicit resume, exact-head proof, post-merge closeout, retrospective learning, and an optional policy-driven intake-review gate before feature creation. | 13 templates, 5 commands, 4 scripts | — | [spec-kit-preset-autonomous-run-governance](https://github.com/hindermath/spec-kit-preset-autonomous-run-governance) |
|
||||
| Autonomous Run Governance | Adds permission-bounded autonomous delivery, an optional intake-review gate, and preservation of the project's learner and accessibility contract. | 13 templates, 5 commands, 4 scripts | — | [spec-kit-preset-autonomous-run-governance](https://github.com/hindermath/spec-kit-preset-autonomous-run-governance) |
|
||||
| Canon Core | Adapts original Spec Kit workflow to work together with Canon extension | 2 templates, 8 commands | — | [spec-kit-canon](https://github.com/maximiliamus/spec-kit-canon) |
|
||||
| Claude AskUserQuestion | Upgrades `/speckit.clarify` and `/speckit.checklist` on Claude Code from Markdown-table prompts to the native AskUserQuestion picker, with a recommended option and reasoning on every question | 2 commands | — | [spec-kit-preset-claude-ask-questions](https://github.com/0xrafasec/spec-kit-preset-claude-ask-questions) |
|
||||
| Command Density | Compacts the nine core Spec Kit command prompts while preserving scripts, handoffs, placeholders, hook output blocks, and rule structure | 9 commands | — | [spec-kit-preset-command-density](https://github.com/Xopoko/spec-kit-preset-command-density) |
|
||||
@@ -19,13 +19,14 @@ The following community-contributed presets customize how Spec Kit behaves — o
|
||||
| Explicit Task Dependencies | Adds explicit `(depends on T###)` dependency declarations and an Execution Wave DAG to tasks.md for parallel scheduling | 1 template, 1 command | — | [spec-kit-preset-explicit-task-dependencies](https://github.com/Quratulain-bilal/spec-kit-preset-explicit-task-dependencies) |
|
||||
| Fiction Book Writing | It adapts the Spec-Driven Development workflow for storytelling to create books or audiobooks (with annotations) in 12 languages: features become story elements, specs become story briefs, plans become story structures, and tasks become scene-by-scene writing tasks. Supports single and multi-POV, all major plot structure frameworks, and two style modes: an author voice sample or humanized AI prose principles. Supports interactive elements like brainstorming, interview, roleplay, and extras like statistics, cover builder, illustration builder, and bio command. Export with templates for KDP, D2D, etc. | 26 templates, 34 commands, 2 scripts | — | [speckit-preset-fiction-book-writing](https://github.com/adaumann/speckit-preset-fiction-book-writing) |
|
||||
| Game Narrative Writing | Preset for game narrative design and interactive storytelling. It adapts the Spec-Driven Development workflow for game narratives: features become story mechanics, specs become narrative briefs, plans become story maps, and tasks become dialogue and scene-writing tasks. Supports branching narratives, player agency systems, state machines, and interactive dialogue trees. | 37 templates, 34 commands, 5 scripts | — | [speckit-preset-game-narrative-writing](https://github.com/adaumann/speckit-preset-game-narrative-writing) |
|
||||
| Intake Authoring Governance | Creates traceable Spec Kit intakes from ordered text sources and now truthfully adopts legacy intakes without inventing predecessor receipts. | 7 templates, 2 commands, 2 scripts | — | [spec-kit-preset-intake-authoring-governance](https://github.com/hindermath/spec-kit-preset-intake-authoring-governance) |
|
||||
| Intake Review Governance | Adds hash-bound review, repair, and status gates for single, series, and campaign intake files before interactive, autonomous, or parallel Spec Kit execution. | 8 templates, 3 commands, 2 scripts | — | [spec-kit-preset-intake-review-governance](https://github.com/hindermath/spec-kit-preset-intake-review-governance) |
|
||||
| Intake Authoring Governance | Governs traceable intake CRUD and language-aware requirements collections with atomic migrations, rollback evidence, and safe series authoring. | 12 templates, 5 commands, 7 scripts | — | [spec-kit-preset-intake-authoring-governance](https://github.com/hindermath/spec-kit-preset-intake-authoring-governance) |
|
||||
| Intake Review Governance | Reviews single, series, campaign, and language-aware requirements collections before Spec Kit execution. | 8 templates, 3 commands, 4 scripts | — | [spec-kit-preset-intake-review-governance](https://github.com/hindermath/spec-kit-preset-intake-review-governance) |
|
||||
| Intake Sequencing Governance | Manages language-aware intake-series order, typed dependencies, lifecycle, and authority-neutral next-candidate selection. | 11 templates, 6 commands, 8 scripts | — | [spec-kit-preset-intake-sequencing-governance](https://github.com/hindermath/spec-kit-preset-intake-sequencing-governance) |
|
||||
| iSAQB Architecture Governance | Adds iSAQB/CPSA-F and arc42 architecture governance with audit-ready evidence for goals, views, resumability, partial-failure scenarios, ADRs, risks, and technical debt. | 13 templates, 3 commands | — | [spec-kit-preset-isaqb-architecture-governance](https://github.com/hindermath/spec-kit-preset-isaqb-architecture-governance) |
|
||||
| Jira Issue Tracking | Overrides `speckit.taskstoissues` to create Jira epics, stories, and tasks instead of GitHub Issues via Atlassian MCP tools | 1 command | — | [spec-kit-preset-jira](https://github.com/luno/spec-kit-preset-jira) |
|
||||
| Model Driven Engineering | Focuses on streamlined commands, app repository support, cross-spec support, and capability-aware project memory for model-driven engineering workflows | 6 templates, 11 commands | MDE extension | [spec-kit-preset-mde](https://github.com/AI-MDE/spec-kit-preset-mde) |
|
||||
| Multi-Repo Branching | Coordinates feature branch creation across multiple git repositories (independent repos and submodules) during plan and tasks phases | 2 commands | — | [spec-kit-preset-multi-repo-branching](https://github.com/sakitA/spec-kit-preset-multi-repo-branching) |
|
||||
| Parallel Autonomous Run Governance | Coordinates isolated autonomous Spec Kit campaigns with bounded concurrency, mixed agents, resumable consolidation, governed post-merge closeout, schema 1.2, and an optional current intake-review gate before worker scheduling. | 9 templates, 5 commands, 2 scripts | autonomous-run-governance >=0.3.2; optional: intake-review-governance >=0.1.0 | [spec-kit-preset-parallel-autonomous-run-governance](https://github.com/hindermath/spec-kit-preset-parallel-autonomous-run-governance) |
|
||||
| Parallel Autonomous Run Governance | Coordinates permission-bounded autonomous campaigns while preserving the project's learner and accessibility contract across workers and consolidation. | 9 templates, 5 commands, 2 scripts | autonomous-run-governance >=0.2.2; optional: intake-review-governance >=0.1.0 | [spec-kit-preset-parallel-autonomous-run-governance](https://github.com/hindermath/spec-kit-preset-parallel-autonomous-run-governance) |
|
||||
| Pirate Speak (Full) | Transforms all Spec Kit output into pirate speak — specs become "Voyage Manifests", plans become "Battle Plans", tasks become "Crew Assignments" | 6 templates, 9 commands | — | [spec-kit-presets](https://github.com/mnriem/spec-kit-presets) |
|
||||
| Screenwriting | Spec-Driven Development for screenwriting/scriptwriting/tutorials: feature films, television (pilot, episode, limited series), and stage plays. Adapts the Spec Kit workflow to screenplay craft — slug lines, action lines, act breaks, beat sheets, and industry-standard pitch documents. Supports three-act, Save the Cat, TV pilot, network episode, cable/streaming episode, and stage-play structural frameworks. Export to Fountain, FTX, PDF | 26 templates, 32 commands, 1 script | — | [speckit-preset-screenwriting](https://github.com/adaumann/speckit-preset-screenwriting) |
|
||||
| Security Governance | Adds memory-safe-language and secure-coding governance, exact-head and security-gate evidence, provider-failure classification, ASVS, supply-chain transparency, and EU regulatory screening. | 14 templates, 3 commands | — | [spec-kit-preset-security-governance](https://github.com/hindermath/spec-kit-preset-security-governance) |
|
||||
|
||||
@@ -6,6 +6,7 @@ The Specify CLI supports a wide range of AI coding agents. When you run `specify
|
||||
|
||||
| Agent | Key | Notes |
|
||||
| ------------------------------------------------------------------------------------ | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| [Alquimia AI](https://docs.alquimia.ai) | `alquimia` | Skills-based integration; installs skills into `.alquimia/skills` and invokes them as `/speckit-<command>` |
|
||||
| [Amp](https://ampcode.com/) | `amp` | |
|
||||
| [Antigravity (agy)](https://antigravity.google/) | `agy` | Skills-based integration; skills are installed automatically |
|
||||
| [Auggie CLI](https://docs.augmentcode.com/cli/overview) | `auggie` | |
|
||||
@@ -25,7 +26,7 @@ The Specify CLI supports a wide range of AI coding agents. When you run `specify
|
||||
| [Hermes](https://github.com/NousResearch/hermes-agent) | `hermes` | Skills-based integration; installs skills globally into `~/.hermes/skills/` |
|
||||
| [IBM Bob](https://www.ibm.com/products/bob) | `bob` | Skills-based integration by default; installs skills as `speckit-<command>/SKILL.md` under `.bob/skills/` and invokes them as `/speckit-<command>`. Pass `--integration-options="--legacy-commands"` to scaffold the deprecated Bob 1.x layout (`.bob/commands/*.md`) instead; that flag will be removed in a future release. Existing legacy installs can migrate with `specify integration upgrade bob --integration-options="--skills"`, which converts them to the skills layout and removes the old command files. If preset overrides are installed, the migration is rejected with an actionable error (preset artifacts cannot yet be reconciled across a layout change) — remove the preset(s), migrate, then reinstall them. |
|
||||
| [Junie](https://junie.jetbrains.com/) | `junie` | |
|
||||
| [Kilo Code](https://github.com/Kilo-Org/kilocode) | `kilocode` | |
|
||||
| [Kilo Code](https://github.com/Kilo-Org/kilocode) | `kilocode` | Installs commands into `.kilo/commands`; legacy `.kilocode/workflows` installs remain supported as a registration fallback |
|
||||
| [Kimi Code](https://code.kimi.com/) | `kimi` | Skills-based integration; installs into `.kimi-code/skills/`. `--migrate-legacy` moves old `.kimi/skills/` installs to the new paths |
|
||||
| [Kiro CLI](https://kiro.dev/docs/cli/) | `kiro-cli` | Kiro CLI does not substitute `$ARGUMENTS` in file-based prompts, so Spec Kit ships a prose fallback at render time (see [Manage prompts](https://kiro.dev/docs/cli/chat/manage-prompts/) and issue [#1926](https://github.com/github/spec-kit/issues/1926)). Alias: `--integration kiro` |
|
||||
| [Lingma](https://lingma.aliyun.com/) | `lingma` | Skills-based integration; skills are installed automatically |
|
||||
@@ -94,6 +95,8 @@ Installs the specified integration into the current project. If another integrat
|
||||
|
||||
Installing an additional integration does not change the default integration. Use `specify integration use <key>` to change the default.
|
||||
|
||||
Installed extensions and presets are not registered for a non-default integration at install time — they follow the currently active (default) integration only. `specify integration use <key>` (or `switch <key>`) is what rescaffolds them for the newly active integration.
|
||||
|
||||
> **Note:** All integration management commands require a project already initialized with `specify init`. To start a new project with a specific agent, use `specify init <project> --integration <key>` instead.
|
||||
|
||||
**Version note:** Controlled multi-install support was introduced in Spec Kit 0.8.5. If `specify integration install <key>` says another integration is already installed and only suggests `switch` or `uninstall`, check your local CLI with `specify version` and upgrade it. Running a one-shot command such as `uvx --from git+https://github.com/github/spec-kit.git specify ...` uses a temporary copy for that command only; it does not update the persistent `specify` executable on your `PATH`.
|
||||
@@ -127,7 +130,7 @@ specify integration switch <key>
|
||||
| `--refresh-shared-infra` | Also overwrite shared infrastructure files even if you customized them (otherwise customizations are preserved) |
|
||||
| `--integration-options` | Options for the target integration when it is not already installed |
|
||||
|
||||
If the target integration is not already installed, equivalent to running `uninstall` followed by `install` in a single step. In this mode, `--force` controls whether modified files from the removed integration are deleted. If the target integration is already installed, `switch` only changes the default integration, like `use`; in this mode, `--force` controls whether managed shared templates are overwritten while the default changes. `--integration-options` is rejected for already-installed targets because changing integration options requires reinstalling managed files; run `upgrade <key> --integration-options ...` first, then `use <key>`.
|
||||
If the target integration is not already installed, equivalent to running `uninstall` followed by `install` in a single step. In this mode, `--force` controls whether modified files from the removed integration are deleted. If the target integration is already installed, `switch` only changes the default integration, like `use`; in this mode, `--force` controls whether managed shared templates are overwritten while the default changes. `--integration-options` is rejected for already-installed targets because changing integration options requires reinstalling managed files; run `upgrade <key> --integration-options ...` first, then `use <key>`. Like `use`, `switch` rescaffolds installed extensions and presets for the target integration once it becomes the default.
|
||||
|
||||
## Use an Installed Integration
|
||||
|
||||
@@ -141,6 +144,8 @@ specify integration use <key>
|
||||
|
||||
Sets the default integration without uninstalling any other installed integrations. This also refreshes managed shared templates so command references match the new default integration's invocation style. Modified or untracked shared templates are preserved unless `--force` is used.
|
||||
|
||||
`use` is also the activation point for installed extensions and presets: it re-registers every enabled extension's and preset's command overrides (and skills, for skills-mode agents) for the newly active integration, so artifacts installed while a different integration was active are rescaffolded here rather than at install time.
|
||||
|
||||
## Upgrade an Integration
|
||||
|
||||
```bash
|
||||
@@ -155,6 +160,10 @@ specify integration upgrade [<key>]
|
||||
|
||||
Reinstalls an installed integration with updated templates and commands (e.g., after upgrading Spec Kit). Defaults to the default integration; if a key is provided, it must be one of the installed integrations. Detects locally modified files and blocks the upgrade unless `--force` is used. Stale files from the previous install that are no longer needed are removed automatically. Shared templates stay aligned with the default integration even when upgrading a non-default integration.
|
||||
|
||||
Enabled extensions and presets are re-registered only when upgrading the currently active (default) integration. A non-default upgrade still refreshes that integration's core commands, but does not re-register its extension or preset layers — `use`/`switch` that integration afterward to rescaffold them.
|
||||
|
||||
If an upgrade would change an integration between command and skills layouts while preset artifacts are registered for it, the upgrade is rejected before changing files. Remove the affected presets, run the layout-changing upgrade, then reinstall them.
|
||||
|
||||
## Report Integration Status
|
||||
|
||||
```bash
|
||||
@@ -263,19 +272,23 @@ The currently declared multi-install safe integrations are:
|
||||
|
||||
| Key | Command directory |
|
||||
| --- | ----------------- |
|
||||
| `alquimia` | `.alquimia/skills` |
|
||||
| `auggie` | `.augment/commands` |
|
||||
| `claude` | `.claude/skills` |
|
||||
| `cline` | `.clinerules/workflows` |
|
||||
| `codebuddy` | `.codebuddy/commands` |
|
||||
| `codex` | `.agents/skills` |
|
||||
| `cursor-agent` | `.cursor/skills` |
|
||||
| `droid` | `.factory/skills` |
|
||||
| `firebender` | `.firebender/commands` |
|
||||
| `gemini` | `.gemini/commands` |
|
||||
| `grok` | `.grok/skills` |
|
||||
| `junie` | `.junie/commands` |
|
||||
| `kilocode` | `.kilocode/workflows` |
|
||||
| `kilocode` | `.kilo/commands` |
|
||||
| `kiro-cli` | `.kiro/prompts` |
|
||||
| `lingma` | `.lingma/skills` |
|
||||
| `omp` | `.omp/commands` |
|
||||
| `pi` | `.pi/prompts` |
|
||||
| `qodercli` | `.qoder/commands` |
|
||||
| `qwen` | `.qwen/commands` |
|
||||
| `shai` | `.shai/commands` |
|
||||
@@ -300,3 +313,7 @@ CLI-based integrations (like Claude Code, Gemini CLI) require the tool to be ins
|
||||
### When should I use `upgrade` vs `switch`?
|
||||
|
||||
Use `upgrade` when you've upgraded Spec Kit and want to refresh an installed integration's managed files. Use `switch` when you want to replace the current default with another integration; if the target is already installed, `switch` behaves like `use`.
|
||||
|
||||
### Do extensions and presets I install apply to every installed integration?
|
||||
|
||||
No. Extensions (`specify extension add`) and presets (`specify preset add`) register their command overrides for the currently active (default) integration only, even if other integrations are installed. A non-default integration does not receive those artifacts until it becomes the default: `specify integration use <key>` (or `switch <key>`) rescaffolds every enabled extension and preset for the newly active integration. `specify integration upgrade` follows the same rule — it only re-registers extensions and presets when upgrading the active integration.
|
||||
|
||||
@@ -139,7 +139,7 @@ catalogs:
|
||||
|
||||
Presets can provide command files, template files (like `plan-template.md`), and script files. Each file name is evaluated independently against the priority stack, so different files can come from different layers.
|
||||
|
||||
Templates and scripts are looked up from the stack when Spec Kit needs them. Commands use the same stack for replacement and composition, but are materialized into detected agent directories instead of being re-resolved by agents. During preset install, Spec Kit registers command files for the preset being installed; post-install and post-removal reconciliation then recomputes and writes the effective command content for affected command names based on the active stack. Agents do not re-resolve the stack each time they run a command.
|
||||
Templates and scripts are looked up from the stack when Spec Kit needs them. Commands use the same stack for replacement and composition, but are materialized into the active integration's directory only, instead of being re-resolved by agents or written to every detected agent directory (#2948). During preset install, Spec Kit registers command files for the preset being installed against the currently active integration; post-install and post-removal reconciliation then recomputes and writes the effective command content for affected command names based on the active stack. Install and rescaffold remain active-only, but removal may also update previously targeted inactive directories recorded by the removed preset to restore the surviving command or skill layer. A non-active installed integration does not otherwise receive these command files until it becomes the default — `specify integration use <key>` (or `switch <key>`) rescaffolds enabled presets for the newly active integration. Agents do not re-resolve the stack each time they run a command.
|
||||
|
||||
By default, files use a **replace** strategy: the first match in the priority stack wins and is used entirely. Templates and commands can also use composition strategies: **prepend** places preset content before lower-priority content, **append** places it after lower-priority content, and **wrap** replaces `{CORE_TEMPLATE}` with lower-priority content. Scripts support **replace** and **wrap**; script wrappers use `$CORE_SCRIPT` as the placeholder.
|
||||
|
||||
|
||||
@@ -502,6 +502,32 @@ args: "{{ inputs.spec }}"
|
||||
message: "{{ status | default('pending') }}"
|
||||
```
|
||||
|
||||
### Interpolation and shell safety
|
||||
|
||||
Expressions are resolved by **plain string substitution** — the value of `{{ ... }}` is spliced into the surrounding text exactly as-is, with no quoting or escaping added. That is convenient for building `args` and `message` strings, but it has an important consequence for `shell` steps: a `run` field is handed to the system shell (`/bin/sh -c` on POSIX), so any interpolated value is interpreted as **shell syntax**, not just data.
|
||||
|
||||
If an interpolated value can contain characters like `;`, `|`, `&`, `$( )`, backticks, or quotes, it can change or extend the command that actually runs. This matters most when the value is not fully under the workflow author's control:
|
||||
|
||||
- **Workflow `inputs.*`** — supplied by whoever runs the workflow.
|
||||
- **A prior step's output**, e.g. `{{ steps.plan.output.stdout }}` — for a `prompt` step this is **text produced by the AI agent**, which can in turn be influenced by files, tickets, or web content the agent read. Treat agent output as untrusted when it flows into a `shell` step.
|
||||
|
||||
There is **no shell-escaping filter** in the expression language and **no sandbox** around a `shell` step, so none of the practices below can be treated as a guarantee that a hostile value is neutralised. The only reliable control is to constrain what an interpolated value *can* be, and to keep values you cannot constrain out of `run` fields entirely. Scrutinise every `run` field that interpolates a value you do not control, and at minimum:
|
||||
|
||||
- **Constrain the value at the source with `enum`/an allowlist.** When `inputs.*` feeds a `run` field, restrict it to a fixed set of known-safe values so a caller cannot supply arbitrary shell text at all. This is the strongest control the engine offers — prefer it over any downstream mitigation.
|
||||
|
||||
```yaml
|
||||
inputs:
|
||||
target:
|
||||
type: string
|
||||
enum: [staging, production] # caller cannot inject arbitrary text
|
||||
```
|
||||
|
||||
- **Keep unconstrained values out of `run`.** If a value cannot be constrained to an allowlist — most agent/`prompt` output — do not interpolate it into a `run` field. Branch on it with `if`/`switch` against fixed conditions, or act on it in a `command`/`prompt` step rather than a shell command built from it.
|
||||
- **Quoting is not a security boundary.** Surrounding a substitution with quotes (`'{{ inputs.x }}'`) helps the shell treat a *trusted* value as a single argument and avoids word-splitting on spaces, but a value that itself contains the matching quote character can still break out and inject shell syntax. Quote for correctness on constrained values; never rely on quoting to make an *unconstrained* substitution safe.
|
||||
- **Gates do not inspect the next step, and `message` is printed verbatim.** A `gate` step renders only its own `message`/`show_file` — it does not display, resolve, or sanitise the command that follows it, and approval never neutralises an injectable interpolation. Do **not** interpolate raw untrusted data into `message`: it is printed as-is with no control-character stripping, so agent or caller output could inject terminal/ANSI escapes that alter or hide the approval prompt. Keep `message` to trusted, constrained text, and surface untrusted material for review via `show_file` instead — its path and contents are control/ANSI-stripped before display.
|
||||
|
||||
A `shell` step is an arbitrary-command primitive by design; these practices reduce exposure and keep *which* command runs under the author's control, but they do not eliminate the risk of interpolating values you do not fully control.
|
||||
|
||||
## Shell Step Environment Variables
|
||||
|
||||
Shell steps automatically receive the following environment variables:
|
||||
|
||||
@@ -195,15 +195,13 @@ Some IDE-based agents (like Kilo Code, Cline) may show **duplicate slash command
|
||||
**Example for Kilo Code:**
|
||||
|
||||
```bash
|
||||
# Navigate to the agent's commands folder
|
||||
cd .kilocode/workflows/
|
||||
|
||||
# List files and identify duplicates
|
||||
ls -la
|
||||
# List current and legacy Kilo command folders
|
||||
ls -la .kilo/commands/
|
||||
ls -la .kilocode/workflows/
|
||||
|
||||
# Delete old versions (example filenames - yours may differ)
|
||||
rm speckit.specify-old.md
|
||||
rm speckit.plan-v1.md
|
||||
rm .kilocode/workflows/speckit.specify-old.md
|
||||
rm .kilocode/workflows/speckit.plan-v1.md
|
||||
```
|
||||
|
||||
Restart your IDE to refresh the command list.
|
||||
@@ -248,14 +246,12 @@ specify extension update
|
||||
This happens with IDE-based agents (Kilo Code, Cline, etc.).
|
||||
|
||||
```bash
|
||||
# Find the agent folder (example: .kilocode/workflows/)
|
||||
cd .kilocode/workflows/
|
||||
|
||||
# List all files
|
||||
ls -la
|
||||
# For Kilo Code, inspect both current and legacy command folders
|
||||
ls -la .kilo/commands/
|
||||
ls -la .kilocode/workflows/
|
||||
|
||||
# Delete old command files
|
||||
rm speckit.old-command-name.md
|
||||
rm .kilocode/workflows/speckit.old-command-name.md
|
||||
|
||||
# Restart your IDE
|
||||
```
|
||||
@@ -307,7 +303,7 @@ Alternatively, run the `/speckit.specify` command which creates `.specify/featur
|
||||
2. **For CLI-based agents**, verify files exist:
|
||||
|
||||
```bash
|
||||
ls -la .claude/commands/ # Claude Code
|
||||
ls -la .claude/skills/ # Claude Code
|
||||
ls -la .gemini/commands/ # Gemini
|
||||
ls -la .cursor/skills/ # Cursor
|
||||
ls -la .pi/prompts/ # Pi Coding Agent
|
||||
@@ -356,7 +352,7 @@ This warning appears when you run `specify init --here` (or `specify init .`) in
|
||||
|
||||
Only Spec Kit infrastructure files:
|
||||
|
||||
- Agent command files (`.claude/commands/`, `.github/prompts/`, etc.)
|
||||
- Agent command/skill files (`.claude/skills/`, `.github/prompts/`, etc.)
|
||||
- Scripts in `.specify/scripts/`
|
||||
- Templates in `.specify/templates/`
|
||||
- Missing memory files such as `.specify/memory/constitution.md` may be created from templates; an existing constitution is preserved
|
||||
@@ -445,7 +441,7 @@ Once you've run `specify init`, the slash commands (like `/speckit.specify`, `/s
|
||||
ls -la .github/prompts/
|
||||
|
||||
# For Claude
|
||||
ls -la .claude/commands/
|
||||
ls -la .claude/skills/
|
||||
|
||||
# For Pi
|
||||
ls -la .pi/prompts/
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
"_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",
|
||||
|
||||
@@ -176,13 +176,18 @@ _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_files, 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
|
||||
# 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]}"
|
||||
MARKER_START="${_opts_lines[1]:-}"
|
||||
MARKER_END="${_opts_lines[2]:-}"
|
||||
|
||||
if ! _context_files_raw="$("$_python" - "$CONTEXT_FILES_JSON" <<'PY'
|
||||
import json
|
||||
|
||||
@@ -11,8 +11,9 @@ 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 ``specs/*/plan.md`` only when feature.json is absent or its
|
||||
plan does not exist yet.
|
||||
recently modified ``plan.md`` anywhere under ``specs/`` (including nested scoped
|
||||
layouts such as ``specs/<scope>/<feature>/plan.md``) only when feature.json is
|
||||
absent or its plan does not exist yet.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -173,7 +174,7 @@ def _resolve_plan_path(project_root: str) -> str:
|
||||
if not plan_path:
|
||||
root = Path(project_root).resolve()
|
||||
plans = sorted(
|
||||
(root / "specs").glob("*/plan.md"),
|
||||
(root / "specs").rglob("plan.md"),
|
||||
key=lambda p: p.stat().st_mtime,
|
||||
reverse=True,
|
||||
)
|
||||
|
||||
@@ -6,6 +6,8 @@ Discovery answers *"is this worth building?"* Delivery answers *"how do we build
|
||||
|
||||
## Overview
|
||||
|
||||
`assess` runs inside an initialized Spec Kit project (it writes assessments under `.specify/assessments/`), but that project can be **completely empty of source code** — a freshly initialized project with no code works just as well as an established codebase. The input is just an idea: pasted text, a URL, or a ticket need no existing code, while a codebase pointer lets you assess an idea for code that already exists. Neither starting point is more "correct" than the other.
|
||||
|
||||
Each idea lives in its own directory under `.specify/assessments/<slug>/`, with one Markdown artifact per stage:
|
||||
|
||||
```
|
||||
|
||||
@@ -21,6 +21,8 @@ The user input is the idea and (optionally) a slug. Treat it as one of:
|
||||
3. **A codebase pointer** — phrasing like "an idea for this repo" or a path. Read enough of the repository to record what the idea relates to.
|
||||
4. **A mix** of the above.
|
||||
|
||||
There is **no requirement for existing source code**: within an initialized Spec Kit project, intake works just as well when the project is empty of code as when it already has a codebase. Pasted text or a URL (options 1–2) need no existing codebase; a codebase pointer (option 3) targets existing code. Both are equally valid.
|
||||
|
||||
If the input is empty, ask the user for the idea (interactive), or stop with a note that there is nothing to intake (automated).
|
||||
|
||||
## Slug Resolution
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"schema_version": "1.0",
|
||||
"updated_at": "2026-07-21T00:00:00Z",
|
||||
"updated_at": "2026-07-29T00:00:00Z",
|
||||
"catalog_url": "https://raw.githubusercontent.com/github/spec-kit/main/extensions/catalog.community.json",
|
||||
"extensions": {
|
||||
"aide": {
|
||||
@@ -290,8 +290,8 @@
|
||||
"id": "architecture-guard",
|
||||
"description": "Framework-agnostic architecture review extension for validating implementation against governance and architecture constitutions, detecting architectural drift, and generating non-blocking refactor tasks.",
|
||||
"author": "DyanGalih",
|
||||
"version": "1.8.17",
|
||||
"download_url": "https://github.com/DyanGalih/spec-kit-architecture-guard/archive/refs/tags/v1.8.17.zip",
|
||||
"version": "1.13.1",
|
||||
"download_url": "https://github.com/DyanGalih/spec-kit-architecture-guard/archive/refs/tags/v1.13.1.zip",
|
||||
"repository": "https://github.com/DyanGalih/spec-kit-architecture-guard",
|
||||
"homepage": "https://github.com/DyanGalih/spec-kit-architecture-guard",
|
||||
"documentation": "https://github.com/DyanGalih/spec-kit-architecture-guard/blob/main/docs/architecture-overview.md",
|
||||
@@ -303,7 +303,7 @@
|
||||
"speckit_version": ">=0.1.0"
|
||||
},
|
||||
"provides": {
|
||||
"commands": 10,
|
||||
"commands": 14,
|
||||
"hooks": 3
|
||||
},
|
||||
"tags": [
|
||||
@@ -313,13 +313,14 @@
|
||||
"refactor",
|
||||
"workflow",
|
||||
"governance",
|
||||
"guardrails"
|
||||
"guardrails",
|
||||
"hygiene"
|
||||
],
|
||||
"verified": false,
|
||||
"downloads": 0,
|
||||
"stars": 0,
|
||||
"created_at": "2026-05-05T07:26:00Z",
|
||||
"updated_at": "2026-06-08T00:00:00Z"
|
||||
"updated_at": "2026-07-24T00:00:00Z"
|
||||
},
|
||||
"archive": {
|
||||
"name": "Archive Extension",
|
||||
@@ -489,6 +490,46 @@
|
||||
"created_at": "2026-04-17T00:00:00Z",
|
||||
"updated_at": "2026-04-17T00:00:00Z"
|
||||
},
|
||||
"blueprint-index": {
|
||||
"name": "Blueprint Index — Living Architecture Map",
|
||||
"id": "blueprint-index",
|
||||
"description": "Living architecture map for brownfield and greenfield projects, with a deterministic CI gate that blocks contradictions between the map, specs, and code while warning on non-blocking drift.",
|
||||
"author": "ogil109",
|
||||
"version": "0.2.0",
|
||||
"download_url": "https://github.com/ogil109/spec-kit-blueprint/releases/download/v0.2.0/blueprint.zip",
|
||||
"repository": "https://github.com/ogil109/spec-kit-blueprint",
|
||||
"homepage": "https://github.com/ogil109/spec-kit-blueprint/tree/main",
|
||||
"documentation": "https://github.com/ogil109/spec-kit-blueprint/blob/main/README.md",
|
||||
"changelog": "https://github.com/ogil109/spec-kit-blueprint/blob/main/CHANGELOG.md",
|
||||
"license": "MIT",
|
||||
"category": "process",
|
||||
"effect": "read-write",
|
||||
"requires": {
|
||||
"speckit_version": ">=0.10.0",
|
||||
"tools": [
|
||||
{ "name": "bash", "required": false },
|
||||
{ "name": "git", "required": false }
|
||||
]
|
||||
},
|
||||
"provides": {
|
||||
"commands": 4,
|
||||
"hooks": 0
|
||||
},
|
||||
"tags": [
|
||||
"blueprint",
|
||||
"architecture",
|
||||
"coherence",
|
||||
"drift",
|
||||
"brownfield",
|
||||
"autonomous",
|
||||
"ci"
|
||||
],
|
||||
"verified": false,
|
||||
"downloads": 0,
|
||||
"stars": 0,
|
||||
"created_at": "2026-07-24T00:00:00Z",
|
||||
"updated_at": "2026-07-24T00:00:00Z"
|
||||
},
|
||||
"branch-convention": {
|
||||
"name": "Branch Convention",
|
||||
"id": "branch-convention",
|
||||
@@ -1578,8 +1619,8 @@
|
||||
"id": "gates",
|
||||
"description": "Deterministic quality enforcement for Spec Kit across agent hooks, git checks, and CI pipelines with one policy file and one verify entrypoint for identical results at every boundary.",
|
||||
"author": "schwichtgit",
|
||||
"version": "0.3.2",
|
||||
"download_url": "https://github.com/schwichtgit/spec-gates/releases/download/v0.3.2/gates-0.3.2.zip",
|
||||
"version": "0.3.3",
|
||||
"download_url": "https://github.com/schwichtgit/spec-gates/releases/download/v0.3.3/gates-0.3.3.zip",
|
||||
"repository": "https://github.com/schwichtgit/spec-gates",
|
||||
"homepage": "https://github.com/schwichtgit/spec-gates",
|
||||
"documentation": "https://github.com/schwichtgit/spec-gates/blob/main/docs/how-it-works.md",
|
||||
@@ -1623,7 +1664,7 @@
|
||||
"downloads": 0,
|
||||
"stars": 0,
|
||||
"created_at": "2026-07-09T00:00:00Z",
|
||||
"updated_at": "2026-07-15T00:00:00Z"
|
||||
"updated_at": "2026-07-27T00:00:00Z"
|
||||
},
|
||||
"github-issues": {
|
||||
"name": "GitHub Issues Integration 1",
|
||||
@@ -1820,6 +1861,40 @@
|
||||
"created_at": "2026-06-23T00:00:00Z",
|
||||
"updated_at": "2026-06-30T00:00:00Z"
|
||||
},
|
||||
"intent": {
|
||||
"name": "Intent Reconciliation",
|
||||
"id": "intent",
|
||||
"description": "Reconcile implementation-discovered decisions against approved feature intent",
|
||||
"author": "SuhaibAslam",
|
||||
"version": "1.0.2",
|
||||
"download_url": "https://github.com/SuhaibAslam/spec-kit-reconcile/archive/refs/tags/v1.0.2.zip",
|
||||
"repository": "https://github.com/SuhaibAslam/spec-kit-reconcile",
|
||||
"homepage": "https://github.com/SuhaibAslam/spec-kit-reconcile",
|
||||
"documentation": "https://github.com/SuhaibAslam/spec-kit-reconcile/blob/main/README.md",
|
||||
"changelog": "https://github.com/SuhaibAslam/spec-kit-reconcile/blob/main/CHANGELOG.md",
|
||||
"license": "MIT",
|
||||
"category": "process",
|
||||
"effect": "read-write",
|
||||
"requires": {
|
||||
"speckit_version": ">=0.12.0"
|
||||
},
|
||||
"provides": {
|
||||
"commands": 3,
|
||||
"hooks": 0
|
||||
},
|
||||
"tags": [
|
||||
"intent",
|
||||
"decisions",
|
||||
"reconciliation",
|
||||
"drift",
|
||||
"workflow"
|
||||
],
|
||||
"verified": false,
|
||||
"downloads": 0,
|
||||
"stars": 0,
|
||||
"created_at": "2026-07-29T00:00:00Z",
|
||||
"updated_at": "2026-07-29T00:00:00Z"
|
||||
},
|
||||
"issue": {
|
||||
"name": "GitHub Issues Integration 2",
|
||||
"id": "issue",
|
||||
@@ -2034,11 +2109,11 @@
|
||||
"id": "linear-weave",
|
||||
"description": "Weave Spec Kit into Linear: pull requirements, mirror tasks.md into sub-issues, sync statuses.",
|
||||
"author": "Tony Woodhouse",
|
||||
"version": "1.0.0",
|
||||
"download_url": "https://github.com/tonydwoodhouse/spec-kit-linear-weave/archive/refs/tags/v1.0.0.zip",
|
||||
"version": "1.0.1",
|
||||
"download_url": "https://github.com/tonydwoodhouse/spec-kit-linear-weave/archive/refs/tags/v1.0.1.zip",
|
||||
"repository": "https://github.com/tonydwoodhouse/spec-kit-linear-weave",
|
||||
"homepage": "https://github.com/tonydwoodhouse/spec-kit-linear-weave",
|
||||
"documentation": "https://github.com/tonydwoodhouse/spec-kit-linear-weave#readme",
|
||||
"documentation": "https://github.com/tonydwoodhouse/spec-kit-linear-weave/blob/main/README.md",
|
||||
"changelog": "https://github.com/tonydwoodhouse/spec-kit-linear-weave/blob/main/CHANGELOG.md",
|
||||
"license": "MIT",
|
||||
"category": "integration",
|
||||
@@ -2061,7 +2136,7 @@
|
||||
"downloads": 0,
|
||||
"stars": 0,
|
||||
"created_at": "2026-07-21T00:00:00Z",
|
||||
"updated_at": "2026-07-21T00:00:00Z"
|
||||
"updated_at": "2026-07-27T00:00:00Z"
|
||||
},
|
||||
"loop": {
|
||||
"name": "Loop Engineering",
|
||||
@@ -4777,36 +4852,40 @@
|
||||
"verify-review-ship": {
|
||||
"name": "Verify Review Ship",
|
||||
"id": "verify-review-ship",
|
||||
"description": "Adds post-implementation verify, review, and ship readiness gates to Spec Kit workflows.",
|
||||
"description": "Post-convergence operational verification, technical review, learning governance, and transactional delivery.",
|
||||
"author": "Carlos Eduardo Gevaerd Araujo",
|
||||
"version": "0.1.0",
|
||||
"download_url": "https://github.com/cadugevaerd/spec-kit-verify-review-ship/archive/refs/tags/v0.1.0.zip",
|
||||
"version": "0.4.2",
|
||||
"download_url": "https://github.com/cadugevaerd/spec-kit-verify-review-ship/archive/refs/tags/v0.4.2.zip",
|
||||
"sha256": "71dceef5bf81d7ac54faa26bb5cf279554815a4928ee8d0c8e9bfb4c3e2bb0ab",
|
||||
"repository": "https://github.com/cadugevaerd/spec-kit-verify-review-ship",
|
||||
"homepage": "https://github.com/cadugevaerd/spec-kit-verify-review-ship",
|
||||
"documentation": "https://github.com/cadugevaerd/spec-kit-verify-review-ship/blob/main/README.md",
|
||||
"changelog": "https://github.com/cadugevaerd/spec-kit-verify-review-ship/blob/main/CHANGELOG.md",
|
||||
"license": "MIT",
|
||||
"category": "process",
|
||||
"effect": "read-only",
|
||||
"effect": "read-write",
|
||||
"requires": {
|
||||
"speckit_version": ">=0.1.0"
|
||||
"speckit_version": ">=0.11.2"
|
||||
},
|
||||
"provides": {
|
||||
"commands": 3,
|
||||
"hooks": 1
|
||||
"hooks": 0
|
||||
},
|
||||
"tags": [
|
||||
"quality",
|
||||
"review",
|
||||
"shipping",
|
||||
"workflow",
|
||||
"testing"
|
||||
"merge",
|
||||
"cleanup",
|
||||
"learning",
|
||||
"governance",
|
||||
"agent-skills"
|
||||
],
|
||||
"verified": false,
|
||||
"downloads": 0,
|
||||
"stars": 0,
|
||||
"created_at": "2026-07-10T00:00:00Z",
|
||||
"updated_at": "2026-07-10T00:00:00Z"
|
||||
"updated_at": "2026-07-28T00:00:00Z"
|
||||
},
|
||||
"verify-tasks": {
|
||||
"name": "Verify Tasks Extension",
|
||||
|
||||
@@ -1,8 +1,17 @@
|
||||
{
|
||||
"schema_version": "1.0",
|
||||
"updated_at": "2026-07-17T00:00:00Z",
|
||||
"updated_at": "2026-07-27T00:00:00Z",
|
||||
"catalog_url": "https://raw.githubusercontent.com/github/spec-kit/main/integrations/catalog.json",
|
||||
"integrations": {
|
||||
"alquimia": {
|
||||
"id": "alquimia",
|
||||
"name": "Alquimia AI",
|
||||
"version": "1.0.0",
|
||||
"description": "Alquimia AI CLI integration",
|
||||
"author": "spec-kit-core",
|
||||
"repository": "https://github.com/github/spec-kit",
|
||||
"tags": ["alquimia"]
|
||||
},
|
||||
"claude": {
|
||||
"id": "claude",
|
||||
"name": "Claude Code",
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
{
|
||||
"schema_version": "1.0",
|
||||
"updated_at": "2026-07-23T00:00:00Z",
|
||||
"updated_at": "2026-07-28T00:00:00Z",
|
||||
|
||||
"catalog_url": "https://raw.githubusercontent.com/github/spec-kit/main/presets/catalog.community.json",
|
||||
"presets": {
|
||||
"a11y-governance": {
|
||||
"name": "A11Y Governance",
|
||||
"id": "a11y-governance",
|
||||
"version": "0.4.1",
|
||||
"description": "Adds WCAG 2.2 AA governance, accessible text/JSON status parity, bilingual DE/EN delivery, CEFR-B2 readability, inclusive content, didactic-comment review, and audit-ready evidence.",
|
||||
"version": "0.4.2",
|
||||
"description": "Adds accessibility (WCAG 2.2 AA), accessible text and JSON status parity, bilingual DE/EN delivery, CEFR-B2 readability, inclusive-content governance, didactic inline-code-comment review, and audit-ready Spec-Kit run evidence to Spec Kit.",
|
||||
"author": "Thorsten Hindermann",
|
||||
"repository": "https://github.com/hindermath/spec-kit-preset-a11y-governance",
|
||||
"download_url": "https://github.com/hindermath/spec-kit-preset-a11y-governance/archive/refs/tags/v0.4.1.zip",
|
||||
"download_url": "https://github.com/hindermath/spec-kit-preset-a11y-governance/archive/refs/tags/v0.4.2.zip",
|
||||
"homepage": "https://github.com/hindermath/spec-kit-preset-a11y-governance",
|
||||
"documentation": "https://github.com/hindermath/spec-kit-preset-a11y-governance/blob/v0.4.1/README.md",
|
||||
"documentation": "https://github.com/hindermath/spec-kit-preset-a11y-governance/blob/v0.4.2/README.md",
|
||||
"license": "MIT",
|
||||
"requires": {
|
||||
"speckit_version": ">=0.8.0"
|
||||
@@ -34,18 +34,18 @@
|
||||
"didactic-comments"
|
||||
],
|
||||
"created_at": "2026-04-27T00:00:00Z",
|
||||
"updated_at": "2026-07-23T00:00:00Z"
|
||||
"updated_at": "2026-07-28T00:00:00Z"
|
||||
},
|
||||
"agent-parity-governance": {
|
||||
"name": "Agent Parity Governance",
|
||||
"id": "agent-parity-governance",
|
||||
"version": "0.4.0",
|
||||
"description": "Adds shared-guidance and generated-command parity, fleet-completion evidence, secret-free runner/status metadata, audit-ready evidence, and agent-neutral model routing.",
|
||||
"version": "0.4.1",
|
||||
"description": "Adds shared-guidance and generated-command parity, repository-fleet completion evidence, secret-free runner/status metadata, audit-ready Spec-Kit run evidence, and agent-neutral model-routing guidance across declared AI-agent surfaces.",
|
||||
"author": "Thorsten Hindermann",
|
||||
"repository": "https://github.com/hindermath/spec-kit-preset-agent-parity-governance",
|
||||
"download_url": "https://github.com/hindermath/spec-kit-preset-agent-parity-governance/archive/refs/tags/v0.4.0.zip",
|
||||
"download_url": "https://github.com/hindermath/spec-kit-preset-agent-parity-governance/archive/refs/tags/v0.4.1.zip",
|
||||
"homepage": "https://github.com/hindermath/spec-kit-preset-agent-parity-governance",
|
||||
"documentation": "https://github.com/hindermath/spec-kit-preset-agent-parity-governance/blob/v0.4.0/README.md",
|
||||
"documentation": "https://github.com/hindermath/spec-kit-preset-agent-parity-governance/blob/v0.4.1/README.md",
|
||||
"license": "MIT",
|
||||
"requires": {
|
||||
"speckit_version": ">=0.8.0"
|
||||
@@ -64,7 +64,7 @@
|
||||
"multi-agent"
|
||||
],
|
||||
"created_at": "2026-04-27T00:00:00Z",
|
||||
"updated_at": "2026-07-23T00:00:00Z"
|
||||
"updated_at": "2026-07-28T00:00:00Z"
|
||||
},
|
||||
"aide-in-place": {
|
||||
"name": "AIDE In-Place Migration",
|
||||
@@ -135,13 +135,13 @@
|
||||
"autonomous-run-governance": {
|
||||
"name": "Autonomous Run Governance",
|
||||
"id": "autonomous-run-governance",
|
||||
"version": "0.3.2",
|
||||
"description": "Adds permission-bounded, evidence-first governance for complete autonomous Spec Kit delivery, including validated status, stop, explicit resume, exact-head proof, post-merge closeout, retrospective learning, and an optional policy-driven intake-review gate before feature creation.",
|
||||
"version": "0.3.3",
|
||||
"description": "Adds permission-bounded autonomous delivery, an optional intake-review gate, and preservation of the project's learner and accessibility contract.",
|
||||
"author": "Thorsten Hindermann",
|
||||
"repository": "https://github.com/hindermath/spec-kit-preset-autonomous-run-governance",
|
||||
"download_url": "https://github.com/hindermath/spec-kit-preset-autonomous-run-governance/archive/refs/tags/v0.3.2.zip",
|
||||
"download_url": "https://github.com/hindermath/spec-kit-preset-autonomous-run-governance/archive/refs/tags/v0.3.3.zip",
|
||||
"homepage": "https://github.com/hindermath/spec-kit-preset-autonomous-run-governance",
|
||||
"documentation": "https://github.com/hindermath/spec-kit-preset-autonomous-run-governance/blob/v0.3.2/README.md",
|
||||
"documentation": "https://github.com/hindermath/spec-kit-preset-autonomous-run-governance/blob/v0.3.3/README.md",
|
||||
"license": "MIT",
|
||||
"requires": {
|
||||
"speckit_version": ">=0.8.3"
|
||||
@@ -156,11 +156,10 @@
|
||||
"governance",
|
||||
"evidence",
|
||||
"permissions",
|
||||
"resume",
|
||||
"intake-review"
|
||||
"accessibility"
|
||||
],
|
||||
"created_at": "2026-07-13T00:00:00Z",
|
||||
"updated_at": "2026-07-21T00:00:00Z"
|
||||
"updated_at": "2026-07-28T00:00:00Z"
|
||||
},
|
||||
"canon-core": {
|
||||
"name": "Canon Core",
|
||||
@@ -368,42 +367,42 @@
|
||||
"intake-authoring-governance": {
|
||||
"name": "Intake Authoring Governance",
|
||||
"id": "intake-authoring-governance",
|
||||
"version": "0.1.1",
|
||||
"description": "Creates traceable Spec Kit intakes from ordered text sources and now truthfully adopts legacy intakes without inventing predecessor receipts.",
|
||||
"version": "0.3.0",
|
||||
"description": "Governs traceable intake CRUD and language-aware requirements collections with atomic migrations, rollback evidence, and safe series authoring.",
|
||||
"author": "Thorsten Hindermann",
|
||||
"repository": "https://github.com/hindermath/spec-kit-preset-intake-authoring-governance",
|
||||
"download_url": "https://github.com/hindermath/spec-kit-preset-intake-authoring-governance/archive/refs/tags/v0.1.1.zip",
|
||||
"download_url": "https://github.com/hindermath/spec-kit-preset-intake-authoring-governance/archive/refs/tags/v0.3.0.zip",
|
||||
"homepage": "https://github.com/hindermath/spec-kit-preset-intake-authoring-governance",
|
||||
"documentation": "https://github.com/hindermath/spec-kit-preset-intake-authoring-governance/blob/v0.1.1/README.md",
|
||||
"documentation": "https://github.com/hindermath/spec-kit-preset-intake-authoring-governance/blob/v0.3.0/README.md",
|
||||
"license": "MIT",
|
||||
"requires": {
|
||||
"speckit_version": ">=0.8.3"
|
||||
},
|
||||
"provides": {
|
||||
"templates": 7,
|
||||
"commands": 2,
|
||||
"scripts": 2
|
||||
"templates": 12,
|
||||
"commands": 5,
|
||||
"scripts": 7
|
||||
},
|
||||
"tags": [
|
||||
"intake",
|
||||
"authoring",
|
||||
"governance",
|
||||
"traceability",
|
||||
"legacy-adoption"
|
||||
"requirements",
|
||||
"migration"
|
||||
],
|
||||
"created_at": "2026-07-22T00:00:00Z",
|
||||
"updated_at": "2026-07-23T00:00:00Z"
|
||||
"updated_at": "2026-07-28T00:00:00Z"
|
||||
},
|
||||
"intake-review-governance": {
|
||||
"name": "Intake Review Governance",
|
||||
"id": "intake-review-governance",
|
||||
"version": "0.1.0",
|
||||
"description": "Adds hash-bound review, repair, and status gates for single, series, and campaign intake files before interactive, autonomous, or parallel Spec Kit execution.",
|
||||
"version": "0.2.0",
|
||||
"description": "Reviews single, series, campaign, and language-aware requirements collections before Spec Kit execution.",
|
||||
"author": "Thorsten Hindermann",
|
||||
"repository": "https://github.com/hindermath/spec-kit-preset-intake-review-governance",
|
||||
"download_url": "https://github.com/hindermath/spec-kit-preset-intake-review-governance/archive/refs/tags/v0.1.0.zip",
|
||||
"download_url": "https://github.com/hindermath/spec-kit-preset-intake-review-governance/archive/refs/tags/v0.2.0.zip",
|
||||
"homepage": "https://github.com/hindermath/spec-kit-preset-intake-review-governance",
|
||||
"documentation": "https://github.com/hindermath/spec-kit-preset-intake-review-governance/blob/v0.1.0/README.md",
|
||||
"documentation": "https://github.com/hindermath/spec-kit-preset-intake-review-governance/blob/v0.2.0/README.md",
|
||||
"license": "MIT",
|
||||
"requires": {
|
||||
"speckit_version": ">=0.8.3"
|
||||
@@ -411,17 +410,46 @@
|
||||
"provides": {
|
||||
"templates": 8,
|
||||
"commands": 3,
|
||||
"scripts": 2
|
||||
"scripts": 4
|
||||
},
|
||||
"tags": [
|
||||
"intake",
|
||||
"review",
|
||||
"governance",
|
||||
"quality-gate",
|
||||
"autonomous"
|
||||
"requirements",
|
||||
"quality-gate"
|
||||
],
|
||||
"created_at": "2026-07-21T00:00:00Z",
|
||||
"updated_at": "2026-07-21T00:00:00Z"
|
||||
"updated_at": "2026-07-28T00:00:00Z"
|
||||
},
|
||||
"intake-sequencing-governance": {
|
||||
"name": "Intake Sequencing Governance",
|
||||
"id": "intake-sequencing-governance",
|
||||
"version": "0.2.2",
|
||||
"description": "Manages language-aware intake-series order, typed dependencies, lifecycle, and authority-neutral next-candidate selection.",
|
||||
"author": "Thorsten Hindermann",
|
||||
"repository": "https://github.com/hindermath/spec-kit-preset-intake-sequencing-governance",
|
||||
"download_url": "https://github.com/hindermath/spec-kit-preset-intake-sequencing-governance/archive/refs/tags/v0.2.2.zip",
|
||||
"homepage": "https://github.com/hindermath/spec-kit-preset-intake-sequencing-governance",
|
||||
"documentation": "https://github.com/hindermath/spec-kit-preset-intake-sequencing-governance/blob/v0.2.2/README.md",
|
||||
"license": "MIT",
|
||||
"requires": {
|
||||
"speckit_version": ">=0.8.3"
|
||||
},
|
||||
"provides": {
|
||||
"templates": 11,
|
||||
"commands": 6,
|
||||
"scripts": 8
|
||||
},
|
||||
"tags": [
|
||||
"intake",
|
||||
"sequencing",
|
||||
"governance",
|
||||
"dag",
|
||||
"lifecycle"
|
||||
],
|
||||
"created_at": "2026-07-27T00:00:00Z",
|
||||
"updated_at": "2026-07-28T00:00:00Z"
|
||||
},
|
||||
"isaqb-architecture-governance": {
|
||||
"name": "iSAQB Architecture Governance",
|
||||
@@ -543,16 +571,16 @@
|
||||
"parallel-autonomous-run-governance": {
|
||||
"name": "Parallel Autonomous Run Governance",
|
||||
"id": "parallel-autonomous-run-governance",
|
||||
"version": "0.2.3",
|
||||
"description": "Coordinates isolated autonomous Spec Kit campaigns with bounded concurrency, mixed agents, resumable consolidation, governed post-merge closeout, schema 1.2, and an optional current intake-review gate before worker scheduling.",
|
||||
"version": "0.2.4",
|
||||
"description": "Coordinates permission-bounded autonomous campaigns while preserving the project's learner and accessibility contract across workers and consolidation.",
|
||||
"author": "Thorsten Hindermann",
|
||||
"repository": "https://github.com/hindermath/spec-kit-preset-parallel-autonomous-run-governance",
|
||||
"download_url": "https://github.com/hindermath/spec-kit-preset-parallel-autonomous-run-governance/archive/refs/tags/v0.2.3.zip",
|
||||
"download_url": "https://github.com/hindermath/spec-kit-preset-parallel-autonomous-run-governance/archive/refs/tags/v0.2.4.zip",
|
||||
"homepage": "https://github.com/hindermath/spec-kit-preset-parallel-autonomous-run-governance",
|
||||
"documentation": "https://github.com/hindermath/spec-kit-preset-parallel-autonomous-run-governance/blob/v0.2.3/README.md",
|
||||
"documentation": "https://github.com/hindermath/spec-kit-preset-parallel-autonomous-run-governance/blob/v0.2.4/README.md",
|
||||
"license": "MIT",
|
||||
"requires": {
|
||||
"speckit_version": ">=0.8.3"
|
||||
"speckit_version": ">=0.8.3"
|
||||
},
|
||||
"provides": {
|
||||
"templates": 9,
|
||||
@@ -563,12 +591,11 @@
|
||||
"parallel",
|
||||
"autonomous",
|
||||
"governance",
|
||||
"orchestration",
|
||||
"resume",
|
||||
"intake-review"
|
||||
"accessibility",
|
||||
"orchestration"
|
||||
],
|
||||
"created_at": "2026-07-22T00:00:00Z",
|
||||
"updated_at": "2026-07-22T00:00:00Z"
|
||||
"updated_at": "2026-07-28T00:00:00Z"
|
||||
},
|
||||
"pirate": {
|
||||
"name": "Pirate Speak (Full)",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "specify-cli"
|
||||
version = "0.14.1"
|
||||
version = "0.15.0"
|
||||
description = "Specify CLI, part of GitHub Spec Kit. A tool to bootstrap your projects for Spec-Driven Development (SDD)."
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.11"
|
||||
|
||||
@@ -8,6 +8,7 @@ ALLOW_EXISTING=false
|
||||
SHORT_NAME=""
|
||||
BRANCH_NUMBER=""
|
||||
USE_TIMESTAMP=false
|
||||
NUMBER_EXPLICIT=false
|
||||
ARGS=()
|
||||
i=1
|
||||
while [ $i -le $# ]; do
|
||||
@@ -48,6 +49,9 @@ while [ $i -le $# ]; do
|
||||
exit 1
|
||||
fi
|
||||
BRANCH_NUMBER="$next_arg"
|
||||
if [ -n "$BRANCH_NUMBER" ]; then
|
||||
NUMBER_EXPLICIT=true
|
||||
fi
|
||||
;;
|
||||
--timestamp)
|
||||
USE_TIMESTAMP=true
|
||||
@@ -60,7 +64,7 @@ while [ $i -le $# ]; do
|
||||
echo " --dry-run Compute feature name and paths without creating directories or files"
|
||||
echo " --allow-existing-branch Reuse an existing feature directory if it already exists"
|
||||
echo " --short-name <name> Provide a custom short name (2-4 words) for the feature"
|
||||
echo " --number N Specify branch number manually (overrides auto-detection)"
|
||||
echo " --number N Prefer a feature number (auto-corrected if its specs prefix exists)"
|
||||
echo " --timestamp Use timestamp prefix (YYYYMMDD-HHMMSS) instead of sequential numbering"
|
||||
echo " --help, -h Show this help message"
|
||||
echo ""
|
||||
@@ -91,6 +95,7 @@ if [ -z "$FEATURE_DESCRIPTION" ]; then
|
||||
fi
|
||||
|
||||
MAX_FEATURE_NUMBER=9223372036854775807
|
||||
MAX_BRANCH_LENGTH=244
|
||||
|
||||
is_feature_number_in_range() {
|
||||
local value="$1"
|
||||
@@ -128,12 +133,40 @@ get_highest_from_specs() {
|
||||
echo "$highest"
|
||||
}
|
||||
|
||||
# Return success when a spec directory owns the given numeric prefix.
|
||||
spec_prefix_exists() {
|
||||
local specs_dir="$1"
|
||||
local feature_num="$2"
|
||||
|
||||
for spec_path in "$specs_dir/${feature_num}-"*; do
|
||||
[ -d "$spec_path" ] && return 0
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
# Function to clean and format a branch name
|
||||
clean_branch_name() {
|
||||
local name="$1"
|
||||
echo "$name" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]/-/g' | sed 's/-\+/-/g' | sed 's/^-//' | sed 's/-$//'
|
||||
}
|
||||
|
||||
# Fit a feature prefix and suffix within GitHub's branch-name limit.
|
||||
fit_branch_name() {
|
||||
local feature_num="$1"
|
||||
local branch_suffix="$2"
|
||||
local branch_name="${feature_num}-${branch_suffix}"
|
||||
|
||||
if [ ${#branch_name} -gt $MAX_BRANCH_LENGTH ]; then
|
||||
local prefix_length=$(( ${#feature_num} + 1 ))
|
||||
local max_suffix_length=$((MAX_BRANCH_LENGTH - prefix_length))
|
||||
local truncated_suffix
|
||||
truncated_suffix=$(printf '%s' "$branch_suffix" | cut -c "1-$max_suffix_length" | sed 's/-$//')
|
||||
branch_name="${feature_num}-${truncated_suffix}"
|
||||
fi
|
||||
|
||||
printf '%s' "$branch_name"
|
||||
}
|
||||
|
||||
# Quote a value for POSIX shell reuse, byte-identical to Python's shlex.quote
|
||||
# so the persistence hints match the Python variant exactly (printf %q output
|
||||
# differs between bash versions and from shlex.quote for spaces/metachars).
|
||||
@@ -253,26 +286,41 @@ else
|
||||
|
||||
# Force base-10 interpretation to prevent octal conversion (e.g., 010 → 8 in octal, but should be 10 in decimal)
|
||||
FEATURE_NUM=$(printf "%03d" "$((10#$BRANCH_NUMBER))")
|
||||
BRANCH_NAME="${FEATURE_NUM}-${BRANCH_SUFFIX}"
|
||||
|
||||
# Treat an explicit number as a preference when its prefix is already used
|
||||
# by a feature directory. Auto-detected numbers are already conflict-free.
|
||||
if [ "$NUMBER_EXPLICIT" = true ]; then
|
||||
SPEC_CONFLICT=false
|
||||
REQUESTED_BRANCH_NAME=$(fit_branch_name "$FEATURE_NUM" "$BRANCH_SUFFIX")
|
||||
REQUESTED_DIR="$SPECS_DIR/$REQUESTED_BRANCH_NAME"
|
||||
if [ "$ALLOW_EXISTING" != true ] || [ ! -d "$REQUESTED_DIR" ]; then
|
||||
spec_prefix_exists "$SPECS_DIR" "$FEATURE_NUM" && SPEC_CONFLICT=true
|
||||
fi
|
||||
|
||||
if [ "$SPEC_CONFLICT" = true ]; then
|
||||
REQUESTED_NUM="$FEATURE_NUM"
|
||||
HIGHEST=$(get_highest_from_specs "$SPECS_DIR")
|
||||
BRANCH_NUMBER=$HIGHEST
|
||||
while true; do
|
||||
if [ "$BRANCH_NUMBER" -eq "$MAX_FEATURE_NUMBER" ]; then
|
||||
echo "Error: feature number must be between 0 and $MAX_FEATURE_NUMBER, got '9223372036854775808'" >&2
|
||||
exit 1
|
||||
fi
|
||||
BRANCH_NUMBER=$((BRANCH_NUMBER + 1))
|
||||
FEATURE_NUM=$(printf "%03d" "$((10#$BRANCH_NUMBER))")
|
||||
spec_prefix_exists "$SPECS_DIR" "$FEATURE_NUM" || break
|
||||
done
|
||||
>&2 echo "[specify] Warning: --number $REQUESTED_NUM conflicts with an existing spec directory; using $FEATURE_NUM instead"
|
||||
fi
|
||||
fi
|
||||
|
||||
fi
|
||||
|
||||
# GitHub enforces a 244-byte limit on branch names
|
||||
# Validate and truncate if necessary
|
||||
MAX_BRANCH_LENGTH=244
|
||||
if [ ${#BRANCH_NAME} -gt $MAX_BRANCH_LENGTH ]; then
|
||||
# Calculate how much we need to trim from suffix
|
||||
# Account for prefix length: timestamp (15) + hyphen (1) = 16, or sequential (3) + hyphen (1) = 4
|
||||
PREFIX_LENGTH=$(( ${#FEATURE_NUM} + 1 ))
|
||||
MAX_SUFFIX_LENGTH=$((MAX_BRANCH_LENGTH - PREFIX_LENGTH))
|
||||
|
||||
# Truncate suffix at word boundary if possible
|
||||
TRUNCATED_SUFFIX=$(echo "$BRANCH_SUFFIX" | cut -c1-$MAX_SUFFIX_LENGTH)
|
||||
# Remove trailing hyphen if truncation created one
|
||||
TRUNCATED_SUFFIX=$(echo "$TRUNCATED_SUFFIX" | sed 's/-$//')
|
||||
|
||||
ORIGINAL_BRANCH_NAME="$BRANCH_NAME"
|
||||
BRANCH_NAME="${FEATURE_NUM}-${TRUNCATED_SUFFIX}"
|
||||
|
||||
ORIGINAL_BRANCH_NAME="${FEATURE_NUM}-${BRANCH_SUFFIX}"
|
||||
BRANCH_NAME=$(fit_branch_name "$FEATURE_NUM" "$BRANCH_SUFFIX")
|
||||
if [ "$BRANCH_NAME" != "$ORIGINAL_BRANCH_NAME" ]; then
|
||||
>&2 echo "[specify] Warning: Branch name exceeded GitHub's 244-byte limit"
|
||||
>&2 echo "[specify] Original: $ORIGINAL_BRANCH_NAME (${#ORIGINAL_BRANCH_NAME} bytes)"
|
||||
>&2 echo "[specify] Truncated to: $BRANCH_NAME (${#BRANCH_NAME} bytes)"
|
||||
|
||||
@@ -14,6 +14,7 @@ param(
|
||||
[string[]]$FeatureDescription
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$maxBranchLength = 244
|
||||
|
||||
# Show help if requested
|
||||
if ($Help) {
|
||||
@@ -24,7 +25,7 @@ if ($Help) {
|
||||
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 <name> Provide a custom short name (2-4 words) for the feature"
|
||||
Write-Host " -Number N Specify branch number manually (overrides auto-detection)"
|
||||
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,11 +68,44 @@ function Get-HighestNumberFromSpecs {
|
||||
return $highest
|
||||
}
|
||||
|
||||
function Test-SpecPrefixInUse {
|
||||
param(
|
||||
[string]$SpecsDir,
|
||||
[string]$FeatureNum
|
||||
)
|
||||
|
||||
if (-not (Test-Path -LiteralPath $SpecsDir -PathType Container)) {
|
||||
return $false
|
||||
}
|
||||
|
||||
return $null -ne (Get-ChildItem -LiteralPath $SpecsDir -Directory -ErrorAction SilentlyContinue |
|
||||
Where-Object { $_.Name -like "$FeatureNum-*" } |
|
||||
Select-Object -First 1)
|
||||
}
|
||||
|
||||
function ConvertTo-CleanBranchName {
|
||||
param([string]$Name)
|
||||
|
||||
return $Name.ToLower() -replace '[^a-z0-9]', '-' -replace '-{2,}', '-' -replace '^-', '' -replace '-$', ''
|
||||
}
|
||||
|
||||
function Get-FittedBranchName {
|
||||
param(
|
||||
[string]$FeatureNum,
|
||||
[string]$BranchSuffix
|
||||
)
|
||||
|
||||
$fittedName = "$FeatureNum-$BranchSuffix"
|
||||
if ($fittedName.Length -gt $maxBranchLength) {
|
||||
$prefixLength = $FeatureNum.Length + 1
|
||||
$maxSuffixLength = $maxBranchLength - $prefixLength
|
||||
$truncatedSuffix = $BranchSuffix.Substring(0, [Math]::Min($BranchSuffix.Length, $maxSuffixLength))
|
||||
$truncatedSuffix = $truncatedSuffix -replace '-$', ''
|
||||
$fittedName = "$FeatureNum-$truncatedSuffix"
|
||||
}
|
||||
|
||||
return $fittedName
|
||||
}
|
||||
# Load common functions (includes Get-RepoRoot and Resolve-Template)
|
||||
. "$PSScriptRoot/common.ps1"
|
||||
|
||||
@@ -176,26 +210,40 @@ if ($Timestamp) {
|
||||
}
|
||||
|
||||
$featureNum = ('{0:000}' -f $resolvedNumber)
|
||||
$branchName = "$featureNum-$branchSuffix"
|
||||
|
||||
# Treat an explicit number as a preference when its prefix is already used
|
||||
# by a feature directory. Auto-detected numbers are already conflict-free.
|
||||
$specConflict = $false
|
||||
if ($hasNumber -and (Test-Path -LiteralPath $specsDir -PathType Container)) {
|
||||
$requestedBranchName = Get-FittedBranchName -FeatureNum $featureNum -BranchSuffix $branchSuffix
|
||||
$requestedDir = Join-Path $specsDir $requestedBranchName
|
||||
if (-not $AllowExistingBranch -or -not (Test-Path -LiteralPath $requestedDir -PathType Container)) {
|
||||
$specConflict = Test-SpecPrefixInUse -SpecsDir $specsDir -FeatureNum $featureNum
|
||||
}
|
||||
}
|
||||
|
||||
if ($specConflict) {
|
||||
$requestedNum = $featureNum
|
||||
$highestNumber = Get-HighestNumberFromSpecs -SpecsDir $specsDir
|
||||
$resolvedNumber = $highestNumber
|
||||
do {
|
||||
if ($resolvedNumber -eq [long]::MaxValue) {
|
||||
Write-Error "Error: feature number must be between 0 and $([long]::MaxValue), got '9223372036854775808'"
|
||||
exit 1
|
||||
}
|
||||
$resolvedNumber++
|
||||
$featureNum = ('{0:000}' -f $resolvedNumber)
|
||||
} while (Test-SpecPrefixInUse -SpecsDir $specsDir -FeatureNum $featureNum)
|
||||
[Console]::Error.WriteLine("[specify] Warning: -Number $requestedNum conflicts with an existing spec directory; using $featureNum instead")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
# GitHub enforces a 244-byte limit on branch names
|
||||
# Validate and truncate if necessary
|
||||
$maxBranchLength = 244
|
||||
if ($branchName.Length -gt $maxBranchLength) {
|
||||
# Calculate how much we need to trim from suffix
|
||||
# Account for prefix length: timestamp (15) + hyphen (1) = 16, or sequential (3) + hyphen (1) = 4
|
||||
$prefixLength = $featureNum.Length + 1
|
||||
$maxSuffixLength = $maxBranchLength - $prefixLength
|
||||
|
||||
# Truncate suffix
|
||||
$truncatedSuffix = $branchSuffix.Substring(0, [Math]::Min($branchSuffix.Length, $maxSuffixLength))
|
||||
# Remove trailing hyphen if truncation created one
|
||||
$truncatedSuffix = $truncatedSuffix -replace '-$', ''
|
||||
|
||||
$originalBranchName = $branchName
|
||||
$branchName = "$featureNum-$truncatedSuffix"
|
||||
|
||||
$originalBranchName = "$featureNum-$branchSuffix"
|
||||
$branchName = Get-FittedBranchName -FeatureNum $featureNum -BranchSuffix $branchSuffix
|
||||
if ($branchName -ne $originalBranchName) {
|
||||
[Console]::Error.WriteLine("[specify] Warning: Branch name exceeded GitHub's 244-byte limit")
|
||||
[Console]::Error.WriteLine("[specify] Original: $originalBranchName ($($originalBranchName.Length) bytes)")
|
||||
[Console]::Error.WriteLine("[specify] Truncated to: $branchName ($($branchName.Length) bytes)")
|
||||
|
||||
@@ -76,7 +76,7 @@ Options:
|
||||
--dry-run Compute feature name and paths without creating directories or files
|
||||
--allow-existing-branch Reuse an existing feature directory if it already exists
|
||||
--short-name <name> Provide a custom short name (2-4 words) for the feature
|
||||
--number N Specify branch number manually (overrides auto-detection)
|
||||
--number N Prefer a feature number (auto-corrected if its specs prefix exists)
|
||||
--timestamp Use timestamp prefix (YYYYMMDD-HHMMSS) instead of sequential numbering
|
||||
--help, -h Show this help message
|
||||
|
||||
@@ -204,6 +204,43 @@ def _get_highest_from_specs(specs_dir: Path) -> int:
|
||||
return highest
|
||||
|
||||
|
||||
def _fit_branch_name(feature_num: str, branch_suffix: str) -> str:
|
||||
"""Fit a feature prefix and suffix within GitHub's branch-name limit."""
|
||||
branch_name = f"{feature_num}-{branch_suffix}"
|
||||
if len(branch_name) <= _MAX_BRANCH_LENGTH:
|
||||
return branch_name
|
||||
|
||||
max_suffix_length = _MAX_BRANCH_LENGTH - (len(feature_num) + 1)
|
||||
truncated_suffix = re.sub(r"-$", "", branch_suffix[:max_suffix_length])
|
||||
return f"{feature_num}-{truncated_suffix}"
|
||||
|
||||
|
||||
def _spec_prefix_exists(specs_dir: Path, feature_num: str) -> bool:
|
||||
"""Return whether a spec directory owns the given numeric prefix."""
|
||||
try:
|
||||
return any(
|
||||
entry.is_dir() and entry.name.startswith(f"{feature_num}-")
|
||||
for entry in specs_dir.iterdir()
|
||||
)
|
||||
except OSError:
|
||||
# Match Bash globbing and PowerShell's ErrorAction=SilentlyContinue.
|
||||
return False
|
||||
|
||||
|
||||
def _has_spec_prefix_conflict(
|
||||
specs_dir: Path,
|
||||
feature_num: str,
|
||||
requested_dir: Path,
|
||||
*,
|
||||
allow_existing: bool,
|
||||
) -> bool:
|
||||
"""Return whether another spec directory owns the requested prefix."""
|
||||
if allow_existing and requested_dir.is_dir():
|
||||
return False
|
||||
|
||||
return _spec_prefix_exists(specs_dir, feature_num)
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
argv0 = sys.argv[0]
|
||||
args = _parse_args(list(argv if argv is not None else sys.argv[1:]), argv0)
|
||||
@@ -261,18 +298,48 @@ def main(argv: list[str] | None = None) -> int:
|
||||
return 1
|
||||
feature_num = f"{number:03d}"
|
||||
|
||||
# Treat an explicit number as a preference when its prefix is already used
|
||||
# by a feature directory. Auto-detected numbers are already conflict-free.
|
||||
if branch_number:
|
||||
requested_branch_name = _fit_branch_name(feature_num, branch_suffix)
|
||||
requested_dir = specs_dir / requested_branch_name
|
||||
spec_conflict = _has_spec_prefix_conflict(
|
||||
specs_dir,
|
||||
feature_num,
|
||||
requested_dir,
|
||||
allow_existing=args.allow_existing,
|
||||
)
|
||||
if spec_conflict:
|
||||
requested_num = feature_num
|
||||
number = _get_highest_from_specs(specs_dir)
|
||||
while True:
|
||||
number += 1
|
||||
if number > _MAX_FEATURE_NUMBER:
|
||||
print(
|
||||
f"Error: feature number must be between 0 and "
|
||||
f"{_MAX_FEATURE_NUMBER}, got '{number}'",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 1
|
||||
feature_num = f"{number:03d}"
|
||||
if not _spec_prefix_exists(specs_dir, feature_num):
|
||||
break
|
||||
print(
|
||||
f"[specify] Warning: --number {requested_num} conflicts with "
|
||||
f"an existing spec directory; using {feature_num} instead",
|
||||
file=sys.stderr,
|
||||
)
|
||||
|
||||
max_suffix_length = _MAX_BRANCH_LENGTH - (len(feature_num) + 1)
|
||||
if max_suffix_length <= 0:
|
||||
print("Error: feature number is too long for a branch name", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
branch_name = f"{feature_num}-{branch_suffix}"
|
||||
original_branch_name = f"{feature_num}-{branch_suffix}"
|
||||
branch_name = _fit_branch_name(feature_num, branch_suffix)
|
||||
|
||||
# GitHub enforces a 244-byte limit on branch names.
|
||||
if len(branch_name) > _MAX_BRANCH_LENGTH:
|
||||
truncated_suffix = re.sub(r"-$", "", branch_suffix[:max_suffix_length])
|
||||
original_branch_name = branch_name
|
||||
branch_name = f"{feature_num}-{truncated_suffix}"
|
||||
if branch_name != original_branch_name:
|
||||
print(
|
||||
"[specify] Warning: Branch name exceeded GitHub's 244-byte limit",
|
||||
file=sys.stderr,
|
||||
|
||||
@@ -114,6 +114,7 @@ def _refresh_shared_templates(
|
||||
project_path: Path,
|
||||
*,
|
||||
invoke_separator: str,
|
||||
invoke_prefix: str = "/",
|
||||
force: bool = False,
|
||||
) -> None:
|
||||
"""Refresh default-sensitive shared templates without touching scripts."""
|
||||
@@ -124,6 +125,7 @@ def _refresh_shared_templates(
|
||||
repo_root=_repo_root(),
|
||||
console=console,
|
||||
invoke_separator=invoke_separator,
|
||||
invoke_prefix=invoke_prefix,
|
||||
force=force,
|
||||
)
|
||||
|
||||
@@ -134,6 +136,7 @@ def _install_shared_infra(
|
||||
tracker: StepTracker | None = None,
|
||||
force: bool = False,
|
||||
invoke_separator: str = ".",
|
||||
invoke_prefix: str = "/",
|
||||
refresh_managed: bool = False,
|
||||
refresh_hint: str | None = None,
|
||||
) -> bool:
|
||||
@@ -177,6 +180,7 @@ def _install_shared_infra(
|
||||
console=console,
|
||||
force=force,
|
||||
invoke_separator=invoke_separator,
|
||||
invoke_prefix=invoke_prefix,
|
||||
refresh_managed=refresh_managed,
|
||||
refresh_hint=refresh_hint,
|
||||
)
|
||||
@@ -188,6 +192,7 @@ def _install_shared_infra_or_exit(
|
||||
tracker: StepTracker | None = None,
|
||||
force: bool = False,
|
||||
invoke_separator: str = ".",
|
||||
invoke_prefix: str = "/",
|
||||
refresh_managed: bool = False,
|
||||
refresh_hint: str | None = None,
|
||||
) -> bool:
|
||||
@@ -198,6 +203,7 @@ def _install_shared_infra_or_exit(
|
||||
tracker=tracker,
|
||||
force=force,
|
||||
invoke_separator=invoke_separator,
|
||||
invoke_prefix=invoke_prefix,
|
||||
refresh_managed=refresh_managed,
|
||||
refresh_hint=refresh_hint,
|
||||
)
|
||||
@@ -508,6 +514,11 @@ _register_extension_cmds(app)
|
||||
from .integrations._commands import register as _register_integration_cmds # noqa: E402
|
||||
_register_integration_cmds(app)
|
||||
|
||||
|
||||
# ===== Event Commands =====
|
||||
from .commands.event import register as _register_event_cmds # noqa: E402
|
||||
_register_event_cmds(app)
|
||||
|
||||
# Re-export selected helpers to preserve the public import surface.
|
||||
from .integrations._helpers import ( # noqa: E402
|
||||
_clear_init_options_for_integration as _clear_init_options_for_integration,
|
||||
|
||||
@@ -1,10 +1,19 @@
|
||||
"""Helpers for bounded HTTP downloads."""
|
||||
"""Helpers for bounded downloads and archive extraction."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import re
|
||||
import socket
|
||||
import stat
|
||||
import struct
|
||||
import unicodedata
|
||||
import zipfile
|
||||
from collections.abc import Iterator
|
||||
from contextlib import ExitStack, contextmanager
|
||||
from ipaddress import IPv4Address, IPv6Address, ip_address
|
||||
from itertools import pairwise
|
||||
from pathlib import Path, PurePosixPath, PureWindowsPath
|
||||
from typing import NoReturn, TypeVar
|
||||
from urllib.parse import ParseResult, urlparse
|
||||
|
||||
@@ -12,17 +21,52 @@ from urllib.parse import ParseResult, urlparse
|
||||
ErrorT = TypeVar("ErrorT", bound=Exception)
|
||||
|
||||
MAX_DOWNLOAD_BYTES = 50 * 1024 * 1024
|
||||
MAX_ZIP_ENTRIES = 512
|
||||
MAX_ZIP_MEMBER_BYTES = 10 * 1024 * 1024
|
||||
MAX_ZIP_TOTAL_BYTES = 50 * 1024 * 1024
|
||||
MAX_ZIP_PATH_BYTES = 4096
|
||||
MAX_ZIP_COMPONENT_BYTES = 255
|
||||
# ``ZipFile`` reads this whole structure into memory. Four MiB leaves roughly
|
||||
# 8 KiB of filename/extra/comment metadata for each of the 512 allowed entries.
|
||||
MAX_ZIP_CENTRAL_DIRECTORY_BYTES = 4 * 1024 * 1024
|
||||
READ_CHUNK_SIZE = 64 * 1024
|
||||
|
||||
# Tighter ceiling for responses that are read fully into memory and parsed as
|
||||
# Tighter ceilings for responses that are read fully into memory and parsed as
|
||||
# JSON. The 50 MiB MAX_DOWNLOAD_BYTES default is sized for archive/payload
|
||||
# downloads; JSON metadata responses are far smaller, so capping them close to
|
||||
# their real size shrinks the memory-DoS surface and keeps the "too large"
|
||||
# error reachable (rather than only triggering on tens of MiB). Pass it
|
||||
# downloads; JSON responses are far smaller, so capping them close to their real
|
||||
# size shrinks the memory-DoS surface and keeps the "too large" error reachable
|
||||
# (rather than only triggering on tens of MiB). Pass the matching constant
|
||||
# explicitly at each JSON call site so the intended bound is pinned there.
|
||||
# METADATA covers fixed-shape single-object responses (an OAuth token, one
|
||||
# release's metadata): a few KiB in practice, 1 MiB is already generous.
|
||||
# * METADATA - fixed-shape single-object responses (an OAuth token, one
|
||||
# release's metadata): a few KiB in practice, 1 MiB is already generous.
|
||||
# * CATALOG - listings that grow with the number of published items. The
|
||||
# largest bundled catalog is ~130 KiB today, so 8 MiB leaves ~60x headroom
|
||||
# for growth while staying well under the download ceiling.
|
||||
MAX_JSON_METADATA_BYTES = 1 * 1024 * 1024
|
||||
MAX_JSON_CATALOG_BYTES = 8 * 1024 * 1024
|
||||
|
||||
_WINDOWS_INVALID_FILENAME_CHARS = frozenset('<>:"|?*')
|
||||
_WINDOWS_RESERVED_FILENAME = re.compile(
|
||||
r"^(?:con|prn|aux|nul|conin\$|conout\$|"
|
||||
r"com[1-9\u00b9\u00b2\u00b3]|lpt[1-9\u00b9\u00b2\u00b3])$",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_ZIP_EOCD = struct.Struct("<4s4H2LH")
|
||||
_ZIP_EOCD_SIGNATURE = b"PK\x05\x06"
|
||||
_ZIP64_LOCATOR_SIGNATURE = b"PK\x06\x07"
|
||||
_ZIP_CENTRAL_HEADER_SIZE = 46
|
||||
_ZIP_CENTRAL_SIGNATURE = b"PK\x01\x02"
|
||||
_ZIP_LOCAL_HEADER_SIZE = 30
|
||||
_ZIP_LOCAL_SIGNATURE = b"PK\x03\x04"
|
||||
_ZIP_EXTRA_HEADER = struct.Struct("<HH")
|
||||
_ZIP64_EXTRA_FIELD_ID = 0x0001
|
||||
_ZIP64_MIN_EXTRACT_VERSION = 45
|
||||
_ZIP_UINT16_MAX = (1 << 16) - 1
|
||||
_ZIP_UINT32_MAX = (1 << 32) - 1
|
||||
_ZIP_MAX_COMMENT_BYTES = (1 << 16) - 1
|
||||
_BOUNDED_ZIP_COMPRESSION_METHODS = frozenset(
|
||||
(zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED)
|
||||
)
|
||||
|
||||
|
||||
def _ip_address_without_scope(
|
||||
@@ -179,6 +223,41 @@ def _raise(error_type: type[ErrorT], message: str) -> NoReturn:
|
||||
raise error_type(message)
|
||||
|
||||
|
||||
def _raise_from(error_type: type[ErrorT], message: str, exc: Exception) -> NoReturn:
|
||||
raise error_type(message) from exc
|
||||
|
||||
|
||||
class _ReadLimitExceeded(Exception):
|
||||
"""Internal signal used to keep domain-specific errors at call sites."""
|
||||
|
||||
|
||||
def _validate_non_negative_int(value: int, name: str) -> None:
|
||||
if isinstance(value, bool) or not isinstance(value, int):
|
||||
raise TypeError(f"{name} must be an integer")
|
||||
if value < 0:
|
||||
raise ValueError(f"{name} must be non-negative")
|
||||
|
||||
|
||||
def _validate_max_bytes(max_bytes: int) -> None:
|
||||
_validate_non_negative_int(max_bytes, "max_bytes")
|
||||
|
||||
|
||||
def _read_limited(response, max_bytes: int) -> bytes:
|
||||
"""Read a stream with bounded requests and without retaining fragments."""
|
||||
output = io.BytesIO()
|
||||
total = 0
|
||||
limit = max_bytes + 1
|
||||
while total < limit:
|
||||
chunk = response.read(min(READ_CHUNK_SIZE, limit - total))
|
||||
if not chunk:
|
||||
break
|
||||
total += len(chunk)
|
||||
if total > max_bytes:
|
||||
raise _ReadLimitExceeded
|
||||
output.write(chunk)
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
def read_response_limited(
|
||||
response,
|
||||
*,
|
||||
@@ -199,20 +278,619 @@ def read_response_limited(
|
||||
explicit value so the intended bound is pinned at the call site rather than
|
||||
tracking changes to the shared default.
|
||||
"""
|
||||
if isinstance(max_bytes, bool) or not isinstance(max_bytes, int):
|
||||
raise TypeError("max_bytes must be an integer")
|
||||
if max_bytes < 0:
|
||||
raise ValueError("max_bytes must be non-negative")
|
||||
_validate_max_bytes(max_bytes)
|
||||
try:
|
||||
return _read_limited(response, max_bytes)
|
||||
except _ReadLimitExceeded:
|
||||
_raise(error_type, f"{label!r} exceeds maximum size of {max_bytes} bytes")
|
||||
|
||||
output = io.BytesIO()
|
||||
total = 0
|
||||
limit = max_bytes + 1
|
||||
while total < limit:
|
||||
chunk = response.read(min(READ_CHUNK_SIZE, limit - total))
|
||||
if not chunk:
|
||||
break
|
||||
total += len(chunk)
|
||||
if total > max_bytes:
|
||||
_raise(error_type, f"{label} exceeds maximum size of {max_bytes} bytes")
|
||||
output.write(chunk)
|
||||
return output.getvalue()
|
||||
|
||||
def build_safe_download_path(
|
||||
target_dir: Path,
|
||||
identifier: object,
|
||||
version: object,
|
||||
*,
|
||||
error_type: type[ErrorT] = ValueError,
|
||||
label: str = "archive",
|
||||
) -> Path:
|
||||
"""Build a portable single-component archive path inside *target_dir*."""
|
||||
if not isinstance(identifier, str) or not isinstance(version, str):
|
||||
_raise(
|
||||
error_type,
|
||||
f"Unsafe {label} download filename derived from "
|
||||
f"{identifier!r} and {version!r}",
|
||||
)
|
||||
|
||||
filename = f"{identifier}-{version}.zip"
|
||||
try:
|
||||
filename_too_long = (
|
||||
len(filename.encode("utf-8")) > MAX_ZIP_COMPONENT_BYTES
|
||||
)
|
||||
except UnicodeEncodeError:
|
||||
filename_too_long = True
|
||||
posix_path = PurePosixPath(filename)
|
||||
windows_path = PureWindowsPath(filename)
|
||||
if (
|
||||
filename_too_long
|
||||
or posix_path.name != filename
|
||||
or windows_path.name != filename
|
||||
or any(unicodedata.category(character) == "Cc" for character in filename)
|
||||
or any(
|
||||
character in _WINDOWS_INVALID_FILENAME_CHARS
|
||||
for character in filename
|
||||
)
|
||||
or filename.endswith((" ", "."))
|
||||
):
|
||||
_raise(
|
||||
error_type,
|
||||
f"Unsafe {label} download filename derived from "
|
||||
f"{identifier!r} and {version!r}",
|
||||
)
|
||||
return Path(target_dir) / filename
|
||||
|
||||
|
||||
def read_zip_member_limited(
|
||||
zf: zipfile.ZipFile,
|
||||
name: str,
|
||||
*,
|
||||
max_bytes: int = MAX_ZIP_MEMBER_BYTES,
|
||||
error_type: type[ErrorT] = ValueError,
|
||||
label: str | None = None,
|
||||
) -> bytes:
|
||||
"""Read a single ZIP member into memory under a hard size cap.
|
||||
|
||||
Reading a member with ``zf.open(name).read()`` is unbounded: a crafted
|
||||
archive can declare a tiny ``file_size`` yet decompress to many gigabytes (a
|
||||
"zip bomb"), exhausting memory before the caller ever inspects the data.
|
||||
This rejects members whose *declared* size already exceeds *max_bytes* and,
|
||||
to defend against headers that lie, also reads in bounded chunks and stops
|
||||
one byte past the limit.
|
||||
|
||||
Use this for any inline manifest/metadata read that happens *before*
|
||||
:func:`safe_extract_zip` (which already enforces the same per-member bound
|
||||
during extraction); a raw ``zf.open(...).read()`` bypasses that protection.
|
||||
"""
|
||||
_validate_max_bytes(max_bytes)
|
||||
member_label = label or name
|
||||
try:
|
||||
info = zf.getinfo(name)
|
||||
except KeyError as exc:
|
||||
_raise_from(error_type, f"ZIP member not found: {name!r}", exc)
|
||||
if info.file_size > max_bytes:
|
||||
_raise(
|
||||
error_type,
|
||||
f"ZIP member {member_label!r} exceeds maximum size of {max_bytes} bytes",
|
||||
)
|
||||
|
||||
try:
|
||||
with zf.open(name, "r") as source:
|
||||
return _read_limited(source, max_bytes)
|
||||
except _ReadLimitExceeded:
|
||||
_raise(
|
||||
error_type,
|
||||
f"ZIP member {member_label!r} exceeds maximum size of {max_bytes} bytes",
|
||||
)
|
||||
except Exception as exc:
|
||||
_raise_from(
|
||||
error_type,
|
||||
f"Failed to read ZIP member {member_label!r}: {exc!r}",
|
||||
exc,
|
||||
)
|
||||
|
||||
|
||||
def normalize_zip_member_name(
|
||||
name: str,
|
||||
*,
|
||||
error_type: type[ErrorT] = ValueError,
|
||||
) -> str:
|
||||
"""Return a normalized, portable ZIP member name or raise if unsafe."""
|
||||
if "\x00" in name:
|
||||
_raise(error_type, f"Unsafe path in ZIP archive: {name!r}")
|
||||
|
||||
normalized = name.replace("\\", "/")
|
||||
try:
|
||||
encoded_name = normalized.encode("utf-8")
|
||||
except UnicodeEncodeError:
|
||||
_raise(error_type, f"Unsafe path in ZIP archive: {name!r}")
|
||||
if len(encoded_name) > MAX_ZIP_PATH_BYTES:
|
||||
_raise(
|
||||
error_type,
|
||||
f"Unsafe path in ZIP archive: {name!r} "
|
||||
"(not portable across supported filesystems)",
|
||||
)
|
||||
path = PurePosixPath(normalized)
|
||||
raw_parts = normalized.split("/")
|
||||
# Strip a single trailing empty segment, i.e. the one-slash directory
|
||||
# marker that legitimate ZIPs use ("mydir/", "mydir/subdir/"). Anything
|
||||
# else that produces an empty segment - consecutive slashes ("a//b") or a
|
||||
# second trailing slash - is left in place and rejected below as malformed.
|
||||
if raw_parts and raw_parts[-1] == "":
|
||||
raw_parts = raw_parts[:-1]
|
||||
has_windows_drive = re.match(r"^[A-Za-z]:", normalized) is not None
|
||||
if (
|
||||
not raw_parts
|
||||
or path.is_absolute()
|
||||
or has_windows_drive
|
||||
or any(part in {"", ".", ".."} for part in raw_parts)
|
||||
):
|
||||
_raise(
|
||||
error_type,
|
||||
f"Unsafe path in ZIP archive: {name!r} (potential path traversal)",
|
||||
)
|
||||
for part in raw_parts:
|
||||
reserved_stem = part.partition(".")[0].partition(":")[0].rstrip(" ")
|
||||
if (
|
||||
len(part.encode("utf-8")) > MAX_ZIP_COMPONENT_BYTES
|
||||
or any(
|
||||
unicodedata.category(character) == "Cc"
|
||||
for character in part
|
||||
)
|
||||
or any(character in _WINDOWS_INVALID_FILENAME_CHARS for character in part)
|
||||
or part.startswith(" ")
|
||||
or part.endswith((" ", "."))
|
||||
or _WINDOWS_RESERVED_FILENAME.fullmatch(reserved_stem)
|
||||
):
|
||||
_raise(
|
||||
error_type,
|
||||
f"Unsafe path in ZIP archive: {name!r} "
|
||||
"(not portable across supported filesystems)",
|
||||
)
|
||||
return normalized
|
||||
|
||||
|
||||
def portable_zip_path_key(name: str) -> tuple[str, ...]:
|
||||
"""Return a comparison key for filesystems with case/Unicode folding."""
|
||||
normalized_name = name.replace("\\", "/")
|
||||
return tuple(
|
||||
unicodedata.normalize("NFC", part.casefold())
|
||||
for part in normalized_name.removesuffix("/").split("/")
|
||||
)
|
||||
|
||||
|
||||
def _raise_zip64(error_type: type[ErrorT]) -> NoReturn:
|
||||
_raise(
|
||||
error_type,
|
||||
"ZIP64 archives are not supported by the bounded extractor",
|
||||
)
|
||||
|
||||
|
||||
def _preflight_zip_entry_features(
|
||||
extract_version: int,
|
||||
compression_method: int,
|
||||
*,
|
||||
error_type: type[ErrorT],
|
||||
) -> None:
|
||||
"""Enforce the formats whose output can be bounded by ``ZipExtFile``.
|
||||
|
||||
Python's BZIP2 and LZMA ``ZipExtFile`` paths do not pass the requested
|
||||
output length to the decompressor; only STORED and DEFLATED preserve this
|
||||
module's hard memory bound. APPNOTE assigns extract version 4.5 to ZIP64
|
||||
size extensions. Because this field declares the minimum extractor feature
|
||||
level, reject 4.5 and every newer level for the supported methods,
|
||||
independently of the usual size sentinels and extra field.
|
||||
"""
|
||||
if compression_method not in _BOUNDED_ZIP_COMPRESSION_METHODS:
|
||||
_raise(
|
||||
error_type,
|
||||
f"Unsupported ZIP compression method {compression_method}; "
|
||||
"the bounded extractor supports only STORED and DEFLATED",
|
||||
)
|
||||
if extract_version >= _ZIP64_MIN_EXTRACT_VERSION:
|
||||
_raise(
|
||||
error_type,
|
||||
"ZIP64 or newer ZIP features requiring extractor version 4.5 or "
|
||||
"newer are not supported by the bounded extractor",
|
||||
)
|
||||
|
||||
|
||||
def _reject_zip64_extra_fields(
|
||||
extra: bytes,
|
||||
zip_path: Path,
|
||||
*,
|
||||
error_type: type[ErrorT],
|
||||
) -> None:
|
||||
"""Reject ZIP64 extra fields and malformed complete extra records."""
|
||||
offset = 0
|
||||
while offset + _ZIP_EXTRA_HEADER.size <= len(extra):
|
||||
field_id, field_size = _ZIP_EXTRA_HEADER.unpack_from(extra, offset)
|
||||
field_end = offset + _ZIP_EXTRA_HEADER.size + field_size
|
||||
if field_id == _ZIP64_EXTRA_FIELD_ID:
|
||||
_raise_zip64(error_type)
|
||||
if field_end > len(extra):
|
||||
_raise(error_type, f"Invalid ZIP archive: {zip_path}")
|
||||
offset = field_end
|
||||
|
||||
|
||||
def _preflight_zip_local_header(
|
||||
archive_file,
|
||||
zip_path: Path,
|
||||
*,
|
||||
error_type: type[ErrorT],
|
||||
archive_prefix_size: int,
|
||||
central_directory_start: int,
|
||||
local_header_offset: int,
|
||||
) -> None:
|
||||
"""Reject local-entry ZIP64 indicators before ``ZipFile`` is constructed."""
|
||||
physical_offset = archive_prefix_size + local_header_offset
|
||||
if (
|
||||
physical_offset < archive_prefix_size
|
||||
or physical_offset + _ZIP_LOCAL_HEADER_SIZE > central_directory_start
|
||||
):
|
||||
_raise(error_type, f"Invalid ZIP archive: {zip_path}")
|
||||
|
||||
archive_file.seek(physical_offset)
|
||||
header = archive_file.read(_ZIP_LOCAL_HEADER_SIZE)
|
||||
if (
|
||||
len(header) != _ZIP_LOCAL_HEADER_SIZE
|
||||
or header[:4] != _ZIP_LOCAL_SIGNATURE
|
||||
):
|
||||
_raise(error_type, f"Invalid ZIP archive: {zip_path}")
|
||||
|
||||
extract_version = struct.unpack_from("<H", header, 4)[0]
|
||||
compression_method = struct.unpack_from("<H", header, 8)[0]
|
||||
_preflight_zip_entry_features(
|
||||
extract_version,
|
||||
compression_method,
|
||||
error_type=error_type,
|
||||
)
|
||||
|
||||
compressed_size, uncompressed_size = struct.unpack_from("<LL", header, 18)
|
||||
if (
|
||||
compressed_size == _ZIP_UINT32_MAX
|
||||
or uncompressed_size == _ZIP_UINT32_MAX
|
||||
):
|
||||
_raise_zip64(error_type)
|
||||
|
||||
filename_size, extra_size = struct.unpack_from("<HH", header, 26)
|
||||
extra_offset = physical_offset + _ZIP_LOCAL_HEADER_SIZE + filename_size
|
||||
if extra_offset + extra_size > central_directory_start:
|
||||
_raise(error_type, f"Invalid ZIP archive: {zip_path}")
|
||||
|
||||
archive_file.seek(extra_offset)
|
||||
extra = archive_file.read(extra_size)
|
||||
if len(extra) != extra_size:
|
||||
_raise(error_type, f"Invalid ZIP archive: {zip_path}")
|
||||
_reject_zip64_extra_fields(extra, zip_path, error_type=error_type)
|
||||
|
||||
|
||||
def _preflight_zip_central_directory(
|
||||
archive_file,
|
||||
zip_path: Path,
|
||||
*,
|
||||
error_type: type[ErrorT],
|
||||
max_entries: int,
|
||||
) -> None:
|
||||
"""Bound and count the central directory before ``ZipFile`` materializes it."""
|
||||
archive_file.seek(0, 2)
|
||||
file_size = archive_file.tell()
|
||||
tail_size = min(file_size, _ZIP_EOCD.size + _ZIP_MAX_COMMENT_BYTES)
|
||||
archive_file.seek(file_size - tail_size)
|
||||
tail = archive_file.read(tail_size)
|
||||
|
||||
# ZipFile selects the last EOCD signature in the search window. Inspect
|
||||
# exactly that record too: falling back to an earlier signature would let
|
||||
# the preflight validate one central directory while ZipFile materializes
|
||||
# another.
|
||||
eocd_index = tail.rfind(_ZIP_EOCD_SIGNATURE)
|
||||
if eocd_index < 0 or eocd_index + _ZIP_EOCD.size > len(tail):
|
||||
_raise(error_type, f"Invalid ZIP archive: {zip_path}")
|
||||
eocd = _ZIP_EOCD.unpack_from(tail, eocd_index)
|
||||
comment_size = eocd[-1]
|
||||
if eocd_index + _ZIP_EOCD.size + comment_size != len(tail):
|
||||
_raise(error_type, f"Invalid ZIP archive: {zip_path}")
|
||||
|
||||
eocd_offset = file_size - len(tail) + eocd_index
|
||||
if eocd_offset >= 20:
|
||||
archive_file.seek(eocd_offset - 20)
|
||||
if archive_file.read(4) == _ZIP64_LOCATOR_SIGNATURE:
|
||||
_raise_zip64(error_type)
|
||||
|
||||
(
|
||||
_signature,
|
||||
disk_number,
|
||||
central_directory_disk,
|
||||
entries_on_disk,
|
||||
declared_entries,
|
||||
central_directory_size,
|
||||
central_directory_offset,
|
||||
_comment_size,
|
||||
) = eocd
|
||||
if (
|
||||
disk_number != 0
|
||||
or central_directory_disk != 0
|
||||
or entries_on_disk != declared_entries
|
||||
):
|
||||
_raise(error_type, "Multi-disk ZIP archives are not supported")
|
||||
if (
|
||||
declared_entries == _ZIP_UINT16_MAX
|
||||
or central_directory_size == _ZIP_UINT32_MAX
|
||||
or central_directory_offset == _ZIP_UINT32_MAX
|
||||
):
|
||||
_raise_zip64(error_type)
|
||||
if declared_entries > max_entries:
|
||||
_raise(
|
||||
error_type,
|
||||
f"ZIP archive contains too many entries "
|
||||
f"({declared_entries} > {max_entries})",
|
||||
)
|
||||
if central_directory_size > MAX_ZIP_CENTRAL_DIRECTORY_BYTES:
|
||||
_raise(
|
||||
error_type,
|
||||
f"ZIP central directory exceeds maximum size of "
|
||||
f"{MAX_ZIP_CENTRAL_DIRECTORY_BYTES} bytes",
|
||||
)
|
||||
|
||||
central_directory_start = eocd_offset - central_directory_size
|
||||
if (
|
||||
central_directory_start < 0
|
||||
or central_directory_offset > central_directory_start
|
||||
):
|
||||
_raise(error_type, f"Invalid ZIP archive: {zip_path}")
|
||||
archive_prefix_size = central_directory_start - central_directory_offset
|
||||
|
||||
consumed = 0
|
||||
actual_entries = 0
|
||||
local_header_offsets: list[int] = []
|
||||
while consumed < central_directory_size:
|
||||
archive_file.seek(central_directory_start + consumed)
|
||||
remaining = central_directory_size - consumed
|
||||
if remaining < _ZIP_CENTRAL_HEADER_SIZE:
|
||||
_raise(error_type, f"Invalid ZIP archive: {zip_path}")
|
||||
header = archive_file.read(_ZIP_CENTRAL_HEADER_SIZE)
|
||||
if (
|
||||
len(header) != _ZIP_CENTRAL_HEADER_SIZE
|
||||
or header[:4] != _ZIP_CENTRAL_SIGNATURE
|
||||
):
|
||||
_raise(error_type, f"Invalid ZIP archive: {zip_path}")
|
||||
|
||||
extract_version = struct.unpack_from("<H", header, 6)[0]
|
||||
compression_method = struct.unpack_from("<H", header, 10)[0]
|
||||
_preflight_zip_entry_features(
|
||||
extract_version,
|
||||
compression_method,
|
||||
error_type=error_type,
|
||||
)
|
||||
|
||||
compressed_size, uncompressed_size = struct.unpack_from("<LL", header, 20)
|
||||
disk_number_start = struct.unpack_from("<H", header, 34)[0]
|
||||
local_header_offset = struct.unpack_from("<L", header, 42)[0]
|
||||
if (
|
||||
compressed_size == _ZIP_UINT32_MAX
|
||||
or uncompressed_size == _ZIP_UINT32_MAX
|
||||
or local_header_offset == _ZIP_UINT32_MAX
|
||||
or disk_number_start == _ZIP_UINT16_MAX
|
||||
):
|
||||
_raise_zip64(error_type)
|
||||
if disk_number_start != 0:
|
||||
_raise(error_type, "Multi-disk ZIP archives are not supported")
|
||||
|
||||
filename_size, extra_size, comment_size = struct.unpack_from(
|
||||
"<HHH", header, 28
|
||||
)
|
||||
variable_size = filename_size + extra_size + comment_size
|
||||
record_size = _ZIP_CENTRAL_HEADER_SIZE + variable_size
|
||||
if record_size > remaining:
|
||||
_raise(error_type, f"Invalid ZIP archive: {zip_path}")
|
||||
variable_data = archive_file.read(variable_size)
|
||||
if len(variable_data) != variable_size:
|
||||
_raise(error_type, f"Invalid ZIP archive: {zip_path}")
|
||||
extra = variable_data[filename_size : filename_size + extra_size]
|
||||
_reject_zip64_extra_fields(extra, zip_path, error_type=error_type)
|
||||
local_header_offsets.append(local_header_offset)
|
||||
|
||||
consumed += record_size
|
||||
actual_entries += 1
|
||||
if actual_entries > max_entries:
|
||||
_raise(
|
||||
error_type,
|
||||
f"ZIP archive contains too many entries "
|
||||
f"({actual_entries} > {max_entries})",
|
||||
)
|
||||
|
||||
if actual_entries != declared_entries:
|
||||
_raise(error_type, f"Invalid ZIP archive: {zip_path}")
|
||||
|
||||
for local_header_offset in local_header_offsets:
|
||||
_preflight_zip_local_header(
|
||||
archive_file,
|
||||
zip_path,
|
||||
error_type=error_type,
|
||||
archive_prefix_size=archive_prefix_size,
|
||||
central_directory_start=central_directory_start,
|
||||
local_header_offset=local_header_offset,
|
||||
)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def open_zip_bounded(
|
||||
zip_path: Path,
|
||||
*,
|
||||
error_type: type[ErrorT] = ValueError,
|
||||
max_entries: int = MAX_ZIP_ENTRIES,
|
||||
) -> Iterator[zipfile.ZipFile]:
|
||||
"""Open an untrusted ZIP after a bounded-memory header preflight."""
|
||||
_validate_non_negative_int(max_entries, "max_entries")
|
||||
zip_path = Path(zip_path)
|
||||
with ExitStack() as stack:
|
||||
try:
|
||||
archive_file = stack.enter_context(zip_path.open("rb"))
|
||||
except OSError as exc:
|
||||
_raise_from(error_type, f"Invalid ZIP archive: {zip_path}", exc)
|
||||
try:
|
||||
_preflight_zip_central_directory(
|
||||
archive_file,
|
||||
zip_path,
|
||||
error_type=error_type,
|
||||
max_entries=max_entries,
|
||||
)
|
||||
except OSError as exc:
|
||||
_raise_from(error_type, f"Invalid ZIP archive: {zip_path}", exc)
|
||||
try:
|
||||
archive_file.seek(0)
|
||||
zf = stack.enter_context(zipfile.ZipFile(archive_file, "r"))
|
||||
except Exception as exc:
|
||||
_raise_from(error_type, f"Invalid ZIP archive: {zip_path}", exc)
|
||||
yield zf
|
||||
|
||||
|
||||
def safe_extract_zip(
|
||||
zip_path: Path,
|
||||
target_dir: Path,
|
||||
*,
|
||||
error_type: type[ErrorT] = ValueError,
|
||||
max_entries: int = MAX_ZIP_ENTRIES,
|
||||
max_member_bytes: int = MAX_ZIP_MEMBER_BYTES,
|
||||
max_total_bytes: int = MAX_ZIP_TOTAL_BYTES,
|
||||
) -> None:
|
||||
"""Extract a ZIP archive after path, symlink, and size validation."""
|
||||
_validate_non_negative_int(max_member_bytes, "max_member_bytes")
|
||||
_validate_non_negative_int(max_total_bytes, "max_total_bytes")
|
||||
try:
|
||||
target_root = target_dir.resolve()
|
||||
except OSError as exc:
|
||||
_raise_from(error_type, f"Invalid ZIP extraction target: {target_dir}", exc)
|
||||
|
||||
with open_zip_bounded(
|
||||
zip_path,
|
||||
error_type=error_type,
|
||||
max_entries=max_entries,
|
||||
) as zf:
|
||||
try:
|
||||
members = zf.infolist()
|
||||
except zipfile.BadZipFile as exc:
|
||||
_raise_from(error_type, f"Invalid ZIP archive: {zip_path}", exc)
|
||||
if len(members) > max_entries:
|
||||
_raise(
|
||||
error_type,
|
||||
f"ZIP archive contains too many entries ({len(members)} > {max_entries})",
|
||||
)
|
||||
|
||||
normalized_members: list[tuple[zipfile.ZipInfo, str, bool]] = []
|
||||
validated_paths: dict[tuple[str, ...], tuple[str, bool]] = {}
|
||||
total_size = 0
|
||||
for member in members:
|
||||
normalized_name = normalize_zip_member_name(
|
||||
member.filename,
|
||||
error_type=error_type,
|
||||
)
|
||||
is_dir = member.is_dir() or normalized_name.endswith("/")
|
||||
path_key = portable_zip_path_key(normalized_name)
|
||||
|
||||
existing = validated_paths.get(path_key)
|
||||
if existing is not None:
|
||||
_raise(
|
||||
error_type,
|
||||
f"Conflicting path in ZIP archive: {member.filename} conflicts "
|
||||
f"with {existing[0]}",
|
||||
)
|
||||
validated_paths[path_key] = (member.filename, is_dir)
|
||||
|
||||
mode = member.external_attr >> 16
|
||||
if stat.S_ISLNK(mode):
|
||||
_raise(error_type, f"Unsafe symlink in ZIP archive: {member.filename}")
|
||||
|
||||
member_path = (target_dir / normalized_name).resolve()
|
||||
try:
|
||||
member_path.relative_to(target_root)
|
||||
except ValueError:
|
||||
_raise(
|
||||
error_type,
|
||||
f"Unsafe path in ZIP archive: {member.filename} "
|
||||
"(potential path traversal)",
|
||||
)
|
||||
|
||||
if not is_dir:
|
||||
if member.file_size > max_member_bytes:
|
||||
_raise(
|
||||
error_type,
|
||||
f"ZIP member {member.filename} exceeds maximum size "
|
||||
f"of {max_member_bytes} bytes",
|
||||
)
|
||||
total_size += member.file_size
|
||||
if total_size > max_total_bytes:
|
||||
_raise(
|
||||
error_type,
|
||||
f"ZIP archive exceeds maximum uncompressed size "
|
||||
f"of {max_total_bytes} bytes",
|
||||
)
|
||||
|
||||
normalized_members.append((member, normalized_name, is_dir))
|
||||
|
||||
# Tuple sorting places every path immediately before its descendants.
|
||||
# One adjacent comparison per entry detects file/directory conflicts
|
||||
# without repeatedly rebuilding every path prefix.
|
||||
for (
|
||||
(path_key, (original, is_dir)),
|
||||
(next_key, (next_original, _next_is_dir)),
|
||||
) in pairwise(sorted(validated_paths.items())):
|
||||
if (
|
||||
not is_dir
|
||||
and len(next_key) > len(path_key)
|
||||
and next_key[: len(path_key)] == path_key
|
||||
):
|
||||
_raise(
|
||||
error_type,
|
||||
f"Conflicting path in ZIP archive: {original} conflicts "
|
||||
f"with {next_original}",
|
||||
)
|
||||
|
||||
# The loop above bounds the *declared* total via member.file_size, but a
|
||||
# crafted archive can understate those headers. Mirror the per-member
|
||||
# guard below with a cumulative count of the bytes actually written so
|
||||
# the total-size bound holds even when the headers lie.
|
||||
total_written = 0
|
||||
for member, normalized_name, is_dir in normalized_members:
|
||||
member_path = target_dir / normalized_name
|
||||
if is_dir:
|
||||
try:
|
||||
member_path.mkdir(parents=True, exist_ok=True)
|
||||
except OSError as exc:
|
||||
_raise_from(
|
||||
error_type,
|
||||
f"Failed to create ZIP directory {member.filename}: {exc}",
|
||||
exc,
|
||||
)
|
||||
continue
|
||||
|
||||
try:
|
||||
member_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
except OSError as exc:
|
||||
_raise_from(
|
||||
error_type,
|
||||
f"Failed to create parent directory for ZIP member {member.filename}: {exc}",
|
||||
exc,
|
||||
)
|
||||
written = 0
|
||||
# Raised outside the try below: if error_type subclasses OSError or
|
||||
# RuntimeError, raising inside would re-wrap the limit error as
|
||||
# "Failed to extract" and lose the size-bound message.
|
||||
limit_error: str | None = None
|
||||
try:
|
||||
with zf.open(member, "r") as source, member_path.open("wb") as dest:
|
||||
while True:
|
||||
chunk = source.read(READ_CHUNK_SIZE)
|
||||
if not chunk:
|
||||
break
|
||||
written += len(chunk)
|
||||
if written > max_member_bytes:
|
||||
limit_error = (
|
||||
f"ZIP member {member.filename} exceeds maximum size "
|
||||
f"of {max_member_bytes} bytes"
|
||||
)
|
||||
break
|
||||
total_written += len(chunk)
|
||||
if total_written > max_total_bytes:
|
||||
limit_error = (
|
||||
f"ZIP archive exceeds maximum uncompressed size "
|
||||
f"of {max_total_bytes} bytes"
|
||||
)
|
||||
break
|
||||
dest.write(chunk)
|
||||
except Exception as exc:
|
||||
_raise_from(
|
||||
error_type,
|
||||
f"Failed to extract ZIP member {member.filename}: {exc}",
|
||||
exc,
|
||||
)
|
||||
if limit_error is not None:
|
||||
_raise(error_type, limit_error)
|
||||
|
||||
@@ -102,8 +102,17 @@ def resolve_github_release_asset_api_url(
|
||||
|
||||
from specify_cli._download_security import read_response_limited
|
||||
|
||||
parsed = urlparse(download_url)
|
||||
hostname = (parsed.hostname or "").lower()
|
||||
# Accessing ``.hostname`` (like ``.port`` below) raises ValueError on a
|
||||
# malformed authority, e.g. an invalid bracketed IPv6 host
|
||||
# ``https://[not-an-ip]/...``. The function's contract is to return None for
|
||||
# anything it can't resolve, not to raise, so guard the read. ``download_url``
|
||||
# is server-controlled here (a catalog ``download_url`` payload), so a
|
||||
# malformed value must not leak a raw traceback past the caller.
|
||||
try:
|
||||
parsed = urlparse(download_url)
|
||||
hostname = (parsed.hostname or "").lower()
|
||||
except ValueError:
|
||||
return None
|
||||
parts = [unquote(part) for part in parsed.path.strip("/").split("/")]
|
||||
|
||||
is_ghes = (
|
||||
@@ -150,8 +159,9 @@ def resolve_github_release_asset_api_url(
|
||||
if len(parts) < 6 or parts[2:4] != ["releases", "download"]:
|
||||
return None
|
||||
|
||||
owner, repo, tag = parts[0], parts[1], parts[4]
|
||||
asset_name = "/".join(parts[5:])
|
||||
owner, repo = parts[0], parts[1]
|
||||
tag = "/".join(parts[4:-1])
|
||||
asset_name = parts[-1]
|
||||
encoded_tag = quote(tag, safe="")
|
||||
release_url = f"{api_base}/repos/{owner}/{repo}/releases/tags/{encoded_tag}"
|
||||
|
||||
|
||||
@@ -3,12 +3,22 @@
|
||||
import json
|
||||
from collections.abc import Mapping
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from typing import Any, Union
|
||||
|
||||
|
||||
INIT_OPTIONS_FILE = ".specify/init-options.json"
|
||||
|
||||
|
||||
class _MissingInitOptionsFile:
|
||||
"""Sentinel: init-options.json does not exist at all (legacy layout)."""
|
||||
|
||||
def __repr__(self) -> str: # pragma: no cover - debug aid only
|
||||
return "MISSING_INIT_OPTIONS_FILE"
|
||||
|
||||
|
||||
MISSING_INIT_OPTIONS_FILE = _MissingInitOptionsFile()
|
||||
|
||||
|
||||
def save_init_options(project_path: Path, options: dict[str, Any]) -> None:
|
||||
"""Persist the CLI options used during ``specify init``."""
|
||||
dest = project_path / INIT_OPTIONS_FILE
|
||||
@@ -34,3 +44,40 @@ def load_init_options(project_path: Path) -> dict[str, Any]:
|
||||
def is_ai_skills_enabled(opts: Mapping[str, Any] | None) -> bool:
|
||||
"""Return True only when init options explicitly enable AI skills."""
|
||||
return isinstance(opts, Mapping) and opts.get("ai_skills") is True
|
||||
|
||||
|
||||
def resolve_active_agent_for_registration(
|
||||
project_path: Path,
|
||||
) -> Union[str, None, _MissingInitOptionsFile]:
|
||||
"""Resolve the active integration key for active-only registration (#2948).
|
||||
|
||||
``load_init_options`` collapses "no file", "unreadable/malformed file",
|
||||
and "valid file with no recorded active agent" into the same ``{}``
|
||||
result, which previously made corrupted-but-present init-options behave
|
||||
like a legacy pre-init-options project and fall back to registering
|
||||
every detected agent. This helper distinguishes those cases explicitly:
|
||||
|
||||
- Returns :data:`MISSING_INIT_OPTIONS_FILE` when init-options.json does
|
||||
not exist at all (pre-init-options layout or direct library use).
|
||||
Callers should fall back to detection-based registration for all
|
||||
agents, matching the original pre-#2948 behavior for such projects.
|
||||
- Returns ``None`` when init-options.json exists but could not provide a
|
||||
valid non-empty string active agent (malformed/unreadable JSON,
|
||||
non-object payload, or a non-string/empty ``ai`` value). Callers must
|
||||
fail closed (register nothing) rather than treat this like "no file"
|
||||
or pass a non-string key into agent-config lookups.
|
||||
- Returns the active agent key (a non-empty string) otherwise.
|
||||
"""
|
||||
path = project_path / INIT_OPTIONS_FILE
|
||||
# A dangling symlink's target doesn't exist, so Path.exists() (which
|
||||
# follows symlinks) returns False even though the path itself is
|
||||
# present as a broken/corrupted entry. Treat any symlink as "present"
|
||||
# so a dangling one fails closed via the invalid-file branch below
|
||||
# instead of being mistaken for "no file at all" (legacy fallback).
|
||||
if not path.is_symlink() and not path.exists():
|
||||
return MISSING_INIT_OPTIONS_FILE
|
||||
|
||||
active_agent = load_init_options(project_path).get("ai")
|
||||
if isinstance(active_agent, str) and active_agent:
|
||||
return active_agent
|
||||
return None
|
||||
|
||||
@@ -12,7 +12,7 @@ from __future__ import annotations
|
||||
DOLLAR_SKILLS_AGENTS: frozenset[str] = frozenset({"codex", "zcode"})
|
||||
|
||||
# Agents that always render /speckit-<name>, regardless of ai_skills.
|
||||
ALWAYS_SLASH_AGENTS: frozenset[str] = frozenset({"devin", "grok", "trae", "zed"})
|
||||
ALWAYS_SLASH_AGENTS: frozenset[str] = frozenset({"devin", "droid", "grok", "trae", "zed"})
|
||||
|
||||
# Agents that render /speckit-<name> only when ai_skills is enabled.
|
||||
CONDITIONAL_SLASH_AGENTS: frozenset[str] = frozenset(
|
||||
@@ -29,6 +29,9 @@ CONDITIONAL_SLASH_AGENTS: frozenset[str] = frozenset(
|
||||
}
|
||||
)
|
||||
|
||||
# Agents that render /skill:<name> (skill-colon invocation) when in skills mode.
|
||||
SKILL_COLON_AGENTS: frozenset[str] = frozenset({"kimi"})
|
||||
|
||||
|
||||
def is_dollar_skills_agent(selected_ai: str | None, ai_skills_enabled: bool) -> bool:
|
||||
"""Return ``True`` if *selected_ai* uses ``$speckit-<name>`` invocations.
|
||||
@@ -41,6 +44,21 @@ def is_dollar_skills_agent(selected_ai: str | None, ai_skills_enabled: bool) ->
|
||||
return selected_ai in DOLLAR_SKILLS_AGENTS and ai_skills_enabled
|
||||
|
||||
|
||||
def get_invocation_prefix(selected_ai: str | None, ai_skills_enabled: bool) -> str:
|
||||
"""Return the native invocation prefix for *selected_ai* in skills mode.
|
||||
|
||||
Returns ``"$"`` for dollar-skills agents (Codex, ZCode),
|
||||
``"/skill:"`` for skill-colon agents (Kimi), and ``"/"`` for all others.
|
||||
"""
|
||||
if not isinstance(selected_ai, str):
|
||||
return "/"
|
||||
if selected_ai in DOLLAR_SKILLS_AGENTS and ai_skills_enabled:
|
||||
return "$"
|
||||
if selected_ai in SKILL_COLON_AGENTS and ai_skills_enabled:
|
||||
return "/skill:"
|
||||
return "/"
|
||||
|
||||
|
||||
def is_slash_skills_agent(selected_ai: str | None, ai_skills_enabled: bool) -> bool:
|
||||
"""Return ``True`` if *selected_ai* uses ``/speckit-<name>`` invocations.
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import yaml
|
||||
from pathlib import Path, PurePosixPath, PureWindowsPath
|
||||
from typing import Any
|
||||
from ._console import console
|
||||
from ._download_security import normalize_zip_member_name
|
||||
|
||||
CLAUDE_LOCAL_PATH = Path.home() / ".claude" / "local" / "claude"
|
||||
CLAUDE_NPM_LOCAL_PATH = Path.home() / ".claude" / "local" / "node_modules" / ".bin" / "claude"
|
||||
@@ -27,19 +28,22 @@ def relative_extension_path_violation(value: Any) -> str | None:
|
||||
``None`` when it is an acceptable relative path within the extension
|
||||
directory.
|
||||
|
||||
Policy: the value must be a non-empty string with no leading/trailing
|
||||
whitespace, no absolute/anchored form, and no ``..`` traversal. The value is
|
||||
Policy: the value must be a non-empty, portable file path with no
|
||||
leading/trailing whitespace, absolute/anchored form, ``..`` traversal,
|
||||
platform-reserved component, or directory-only suffix. The value is
|
||||
evaluated under both POSIX and Windows path semantics because a native
|
||||
``Path`` is OS-dependent (a ``PurePosixPath`` on POSIX does not interpret
|
||||
Windows drive/UNC forms, and ``C:foo`` is anchored but not ``is_absolute()``
|
||||
yet resolves against the CWD on its drive). Rejecting any non-empty anchor
|
||||
covers POSIX-absolute (``/abs``), Windows drive-relative (``C:foo``), Windows
|
||||
absolute (``C:\\foo``), and UNC/rooted forms.
|
||||
Windows drive/UNC forms, and ``C:foo`` is anchored but not
|
||||
``is_absolute()`` yet resolves against the CWD on its drive). Rejecting any
|
||||
non-empty anchor covers POSIX-absolute (``/abs``), Windows drive-relative
|
||||
(``C:foo``), Windows absolute (``C:\\foo``), and UNC/rooted forms.
|
||||
"""
|
||||
if not isinstance(value, str) or not value:
|
||||
return "must be a non-empty string"
|
||||
if value.strip() != value:
|
||||
return "must not have leading or trailing whitespace"
|
||||
if "\\" in value:
|
||||
return "must use forward slashes as path separators"
|
||||
posix_path = PurePosixPath(value)
|
||||
win_path = PureWindowsPath(value)
|
||||
if (
|
||||
@@ -52,6 +56,15 @@ def relative_extension_path_violation(value: Any) -> str | None:
|
||||
"must be a relative path within the extension directory "
|
||||
"(no absolute paths, drive letters, or '..' segments)"
|
||||
)
|
||||
if value.endswith(("/", "\\")):
|
||||
return "must name a file or command, not a directory"
|
||||
try:
|
||||
normalize_zip_member_name(value)
|
||||
except ValueError:
|
||||
return (
|
||||
"must use portable path components "
|
||||
"(no reserved names or platform-invalid characters)"
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
@@ -69,21 +82,14 @@ def run_command(
|
||||
cmd: list[str],
|
||||
check_return: bool = True,
|
||||
capture: bool = False,
|
||||
shell: bool = False,
|
||||
) -> str | None:
|
||||
"""Run a command without invoking a shell and optionally capture output.
|
||||
|
||||
The ``shell`` parameter is kept in the signature so existing keyword
|
||||
callers (and the re-export from ``specify_cli``) don't raise ``TypeError``,
|
||||
but only the default ``shell=False`` is honoured. ``shell=True`` is
|
||||
rejected with ``ValueError`` rather than silently ignored, so the
|
||||
unsupported mode fails loudly instead of running with a different meaning.
|
||||
Commands are always executed with ``shell=False`` and must be passed as an
|
||||
argv ``list[str]``. There is deliberately no ``shell`` parameter: the
|
||||
argv-list contract makes shell interpolation impossible by construction, so
|
||||
the shell-injection surface cannot be re-enabled at a call site.
|
||||
"""
|
||||
if shell:
|
||||
raise ValueError(
|
||||
"run_command() does not support shell=True; pass argv as a list"
|
||||
)
|
||||
|
||||
try:
|
||||
if capture:
|
||||
result = subprocess.run(cmd, check=check_return, capture_output=True, text=True)
|
||||
|
||||
@@ -27,6 +27,7 @@ from pathlib import Path
|
||||
|
||||
import typer
|
||||
from packaging.version import InvalidVersion, Version
|
||||
from rich.markup import escape as _escape_markup
|
||||
|
||||
from ._download_security import MAX_JSON_METADATA_BYTES, read_response_limited
|
||||
from ._console import console
|
||||
@@ -1230,7 +1231,10 @@ def self_upgrade(
|
||||
tag: str | None = typer.Option(
|
||||
None,
|
||||
"--tag",
|
||||
help="Pin the target version (vX.Y.Z[suffix]). Without --tag, the "
|
||||
# Typer renders help through Rich, so escape the literal bracket (\[)
|
||||
# or `[suffix]` is parsed as a style tag and dropped -- `--help` then
|
||||
# advertises only `(vX.Y.Z)`, contradicting docs/upgrade.md and README.
|
||||
help="Pin the target version (vX.Y.Z\\[suffix]). Without --tag, the "
|
||||
"latest stable release is resolved via GitHub Releases.",
|
||||
),
|
||||
) -> None:
|
||||
@@ -1270,7 +1274,14 @@ def self_upgrade(
|
||||
try:
|
||||
tag = _validate_tag(tag)
|
||||
except typer.BadParameter as exc:
|
||||
console.print(str(exc), soft_wrap=True)
|
||||
# Escape at the print site rather than baking `\[` into
|
||||
# _INVALID_TAG_MESSAGE: the message is also raised through
|
||||
# typer.BadParameter, which Click renders without Rich, so the
|
||||
# constant must stay plain text. Unescaped, Rich parses the literal
|
||||
# `[suffix]` as a style tag and drops it, leaving the user with
|
||||
# "expected vMAJOR.MINOR.PATCH" -- implying a bare vX.Y.Z is the only
|
||||
# accepted form when -rc1 / .dev0 / +build.42 are all valid.
|
||||
console.print(_escape_markup(str(exc)), soft_wrap=True)
|
||||
raise typer.Exit(1) from exc
|
||||
|
||||
plan, failure_reason = _build_upgrade_plan(target_tag_override=tag)
|
||||
|
||||
@@ -10,11 +10,12 @@ import os
|
||||
import re
|
||||
from copy import deepcopy
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional
|
||||
from typing import Any, Dict, Iterable, List, Optional
|
||||
|
||||
import yaml
|
||||
|
||||
from ._init_options import is_ai_skills_enabled, load_init_options
|
||||
from ._invocation_style import get_invocation_prefix
|
||||
from ._toml_string import escape_toml_basic as _escape_toml_basic
|
||||
from ._toml_string import has_illegal_toml_control as _has_illegal_toml_control
|
||||
from ._utils import relative_extension_path_violation
|
||||
@@ -270,7 +271,7 @@ class CommandRegistrar:
|
||||
return text
|
||||
|
||||
def render_markdown_command(
|
||||
self, frontmatter: dict, body: str, source_id: str, context_note: str = None
|
||||
self, frontmatter: dict, body: str, source_id: str, context_note: Optional[str] = None
|
||||
) -> str:
|
||||
"""Render command in Markdown format.
|
||||
|
||||
@@ -301,8 +302,20 @@ class CommandRegistrar:
|
||||
toml_lines = []
|
||||
|
||||
if "description" in frontmatter:
|
||||
# Frontmatter comes from ``yaml.safe_load``, so ``description`` can
|
||||
# be any YAML type: ``description:`` with no value yields None,
|
||||
# ``description: 2`` an int, an unquoted ``true`` a bool.
|
||||
# ``_render_basic_toml_string`` iterates the value and calls ord()
|
||||
# on each character, so a non-string raises a raw TypeError -- and a
|
||||
# list of single-character items is silently concatenated into a
|
||||
# wrong value (``["a", "b"]`` -> ``"ab"``). Coerce first, matching
|
||||
# ``render_yaml_command`` below and ``TomlIntegration
|
||||
# ._extract_description``, which both normalise it already.
|
||||
description = frontmatter["description"]
|
||||
if not isinstance(description, str):
|
||||
description = str(description) if description is not None else ""
|
||||
toml_lines.append(
|
||||
f"description = {self._render_basic_toml_string(frontmatter['description'])}"
|
||||
f"description = {self._render_basic_toml_string(description)}"
|
||||
)
|
||||
toml_lines.append("")
|
||||
|
||||
@@ -597,8 +610,8 @@ class CommandRegistrar:
|
||||
source_id: str,
|
||||
source_dir: Path,
|
||||
project_root: Path,
|
||||
context_note: str = None,
|
||||
_resolved_dir: Path = None,
|
||||
context_note: Optional[str] = None,
|
||||
_resolved_dir: Optional[Path] = None,
|
||||
link_outputs: bool = False,
|
||||
extension_id: Optional[str] = None,
|
||||
) -> List[str]:
|
||||
@@ -659,22 +672,38 @@ class CommandRegistrar:
|
||||
# correct when a stale ``.bob/skills`` directory coexists with
|
||||
# ``.bob/commands``.
|
||||
_sep = agent_config.get("invoke_separator", ".")
|
||||
registrar_writes_skills = agent_config.get("extension") == "/SKILL.md"
|
||||
try:
|
||||
from specify_cli.integrations import get_integration # noqa: PLC0415
|
||||
|
||||
_integ = get_integration(agent_name)
|
||||
if _integ is not None:
|
||||
registrar_writes_skills = (
|
||||
agent_config.get("extension") == "/SKILL.md"
|
||||
)
|
||||
_sep = _integ.invoke_separator_for_mode(registrar_writes_skills)
|
||||
except Exception:
|
||||
pass
|
||||
_prefix = get_invocation_prefix(agent_name, registrar_writes_skills)
|
||||
|
||||
for cmd_info in commands:
|
||||
cmd_name = cmd_info["name"]
|
||||
aliases = cmd_info.get("aliases", [])
|
||||
cmd_file = cmd_info["file"]
|
||||
name_reason = relative_extension_path_violation(cmd_name)
|
||||
if name_reason:
|
||||
raise ValueError(
|
||||
f"Invalid command name {cmd_name!r}: {name_reason}"
|
||||
)
|
||||
if aliases is None:
|
||||
aliases = []
|
||||
if not isinstance(aliases, list):
|
||||
raise ValueError(
|
||||
f"Aliases for command {cmd_name!r} must be a list"
|
||||
)
|
||||
for alias in aliases:
|
||||
alias_reason = relative_extension_path_violation(alias)
|
||||
if alias_reason:
|
||||
raise ValueError(
|
||||
f"Invalid command alias {alias!r}: {alias_reason}"
|
||||
)
|
||||
|
||||
# Guard against path traversal using the single shared policy in
|
||||
# relative_extension_path_violation(), so the runtime guard stays
|
||||
@@ -755,7 +784,7 @@ class CommandRegistrar:
|
||||
# (base.py itself imports CommandRegistrar lazily).
|
||||
from specify_cli.integrations.base import IntegrationBase # noqa: PLC0415
|
||||
|
||||
body = IntegrationBase.resolve_command_refs(body, _sep)
|
||||
body = IntegrationBase.resolve_command_refs(body, _sep, _prefix)
|
||||
|
||||
output_name = self._compute_output_name(agent_name, cmd_name, agent_config)
|
||||
|
||||
@@ -957,10 +986,16 @@ class CommandRegistrar:
|
||||
project_root: Path to project root
|
||||
cmd_name: Command name (e.g. 'speckit.my-ext.example')
|
||||
"""
|
||||
name_reason = relative_extension_path_violation(cmd_name)
|
||||
if name_reason:
|
||||
raise ValueError(
|
||||
f"Invalid Copilot prompt name {cmd_name!r}: {name_reason}"
|
||||
)
|
||||
prompts_dir = project_root / ".github" / "prompts"
|
||||
prompts_dir.mkdir(parents=True, exist_ok=True)
|
||||
prompt_file = prompts_dir / f"{cmd_name}.prompt.md"
|
||||
CommandRegistrar._ensure_inside(prompt_file, prompts_dir)
|
||||
prompt_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
prompt_file.write_text(f"---\nagent: {cmd_name}\n---\n", encoding="utf-8")
|
||||
|
||||
@staticmethod
|
||||
@@ -1016,10 +1051,11 @@ class CommandRegistrar:
|
||||
source_id: str,
|
||||
source_dir: Path,
|
||||
project_root: Path,
|
||||
context_note: str = None,
|
||||
context_note: Optional[str] = None,
|
||||
link_outputs: bool = False,
|
||||
create_missing_active_skills_dir: bool = False,
|
||||
extension_id: Optional[str] = None,
|
||||
only_agent: Optional[str] = None,
|
||||
) -> Dict[str, List[str]]:
|
||||
"""Register commands for all detected agents in the project.
|
||||
|
||||
@@ -1037,6 +1073,8 @@ class CommandRegistrar:
|
||||
skills directory) and is skipped when safe resolution or
|
||||
creation fails.
|
||||
extension_id: Extension id when rendering extension-owned commands.
|
||||
only_agent: If set, restrict registration to this single agent
|
||||
while keeping all detection and recovery safeguards (#2948).
|
||||
|
||||
Returns:
|
||||
Dictionary mapping agent names to list of registered commands
|
||||
@@ -1060,6 +1098,8 @@ class CommandRegistrar:
|
||||
)
|
||||
active_created_skills_dir: Optional[Path] = None
|
||||
for agent_name, agent_config in self.AGENT_CONFIGS.items():
|
||||
if only_agent is not None and agent_name != only_agent:
|
||||
continue
|
||||
active_skills_output = (
|
||||
agent_name == active_skills_agent
|
||||
and agent_config.get("extension") == "/SKILL.md"
|
||||
@@ -1165,6 +1205,8 @@ class CommandRegistrar:
|
||||
context_note: Optional[str] = None,
|
||||
link_outputs: bool = False,
|
||||
extension_id: Optional[str] = None,
|
||||
only_agent: Optional[str] = None,
|
||||
extra_agents: Optional[Iterable[str]] = None,
|
||||
) -> Dict[str, List[str]]:
|
||||
"""Register commands for all non-skill agents in the project.
|
||||
|
||||
@@ -1181,13 +1223,29 @@ class CommandRegistrar:
|
||||
link_outputs: If True, create dev-mode symlinks for rendered
|
||||
command files when supported by the OS.
|
||||
extension_id: Extension id when rendering extension-owned commands.
|
||||
only_agent: If set, restrict registration to this single agent
|
||||
(#2948). An agent name that matches no configured agent
|
||||
(e.g. an empty string) yields no registrations at all.
|
||||
extra_agents: Additional agent names to register for besides
|
||||
``only_agent``. Used by post-removal reconciliation to also
|
||||
restore surviving content into historical agent directories
|
||||
a just-removed preset actually wrote to, not only the
|
||||
currently active agent (#2948). Ignored when ``only_agent``
|
||||
is ``None`` (already unrestricted).
|
||||
|
||||
Returns:
|
||||
Dictionary mapping agent names to list of registered commands
|
||||
"""
|
||||
results = {}
|
||||
self._ensure_configs()
|
||||
extra_agents_set = frozenset(extra_agents) if extra_agents else frozenset()
|
||||
for agent_name, agent_config in self.AGENT_CONFIGS.items():
|
||||
if (
|
||||
only_agent is not None
|
||||
and agent_name != only_agent
|
||||
and agent_name not in extra_agents_set
|
||||
):
|
||||
continue
|
||||
if agent_config.get("extension") == "/SKILL.md":
|
||||
continue
|
||||
detect_dir_str = agent_config.get("detect_dir")
|
||||
|
||||
@@ -5,6 +5,7 @@ from __future__ import annotations
|
||||
import base64
|
||||
import json as _json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
@@ -71,9 +72,27 @@ class AzureDevOpsAuth(AuthProvider):
|
||||
def _acquire_via_az_cli() -> str | None:
|
||||
"""Run ``az account get-access-token`` and return the access token."""
|
||||
try:
|
||||
# Windows: ``subprocess.run`` calls ``CreateProcess``, which does
|
||||
# not consult ``PATHEXT``, so a bare ``"az"`` (installed as
|
||||
# ``az.cmd``) fails with ``WinError 2`` even after ``az login``.
|
||||
# Resolve via ``shutil.which`` (which honors ``PATHEXT``) so the
|
||||
# ``.cmd`` shim works. On POSIX this is a harmless lookup that
|
||||
# returns the same executable.
|
||||
#
|
||||
# Require an ABSOLUTE result: on Windows ``shutil.which`` prepends
|
||||
# the current directory to the search path (unless
|
||||
# ``NoDefaultCurrentDirectoryInExePath`` is set), so a stray
|
||||
# ``.\az.cmd`` in the working directory would otherwise be resolved
|
||||
# ahead of the real Azure CLI and run for a credential operation. A
|
||||
# legitimate install always resolves to an absolute path, so this
|
||||
# costs nothing; falling back to the bare ``"az"`` preserves the
|
||||
# prior behavior (and the existing OSError path) when ``az`` is
|
||||
# absent.
|
||||
resolved = shutil.which("az")
|
||||
az = resolved if resolved and os.path.isabs(resolved) else "az"
|
||||
result = subprocess.run( # noqa: S603, S607
|
||||
[
|
||||
"az",
|
||||
az,
|
||||
"account",
|
||||
"get-access-token",
|
||||
"--resource",
|
||||
|
||||
@@ -13,6 +13,7 @@ import stat
|
||||
from dataclasses import dataclass
|
||||
from fnmatch import fnmatch
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib.parse import urlparse
|
||||
|
||||
|
||||
@@ -53,6 +54,19 @@ def _is_valid_host_pattern(pattern: str) -> bool:
|
||||
return pattern.startswith("*.") and "*" not in pattern[2:]
|
||||
|
||||
|
||||
def _norm(value: Any) -> Any:
|
||||
"""Strip surrounding whitespace from a whitespace-insignificant string
|
||||
config reference (env-var names, tenant/client ids) before it is stored.
|
||||
|
||||
These fields are validated on their ``.strip()``ed form, so an accidentally
|
||||
padded value passes validation but then silently breaks the verbatim
|
||||
``os.environ.get(...)`` / URL lookups downstream. Normalizing at store time
|
||||
mirrors how ``hosts`` is already handled (``h.strip().lower()``). Non-string
|
||||
values (e.g. ``None``) pass through unchanged.
|
||||
"""
|
||||
return value.strip() if isinstance(value, str) else value
|
||||
|
||||
|
||||
def load_auth_config(
|
||||
path: Path | None = None,
|
||||
) -> list[AuthConfigEntry]:
|
||||
@@ -182,10 +196,10 @@ def load_auth_config(
|
||||
provider=provider,
|
||||
auth=auth,
|
||||
token=token,
|
||||
token_env=token_env,
|
||||
tenant_id=entry_raw.get("tenant_id"),
|
||||
client_id=entry_raw.get("client_id"),
|
||||
client_secret_env=entry_raw.get("client_secret_env"),
|
||||
token_env=_norm(token_env),
|
||||
tenant_id=_norm(entry_raw.get("tenant_id")),
|
||||
client_id=_norm(entry_raw.get("client_id")),
|
||||
client_secret_env=_norm(entry_raw.get("client_secret_env")),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@@ -14,14 +14,13 @@ from .. import BundlerError
|
||||
from ..lib.yamlio import dump_yaml, ensure_within, load_yaml
|
||||
from ..models.catalog import (
|
||||
CONFIG_FILENAME,
|
||||
CONFIG_SCHEMA_VERSION,
|
||||
BUILTIN_DEFAULT_STACK,
|
||||
CatalogSource,
|
||||
InstallPolicy,
|
||||
Scope,
|
||||
)
|
||||
|
||||
CONFIG_SCHEMA_VERSION = "1.0"
|
||||
|
||||
_BUILTIN_IDS = {raw["id"] for raw in BUILTIN_DEFAULT_STACK}
|
||||
|
||||
# Windows absolute paths like ``C:\catalog.json`` parse with a single-letter
|
||||
@@ -153,6 +152,8 @@ def add_source(
|
||||
# keeps that ValueError inside the guard instead of leaking a raw
|
||||
# traceback past the CLI's `except BundlerError`. Reuse the value below.
|
||||
hostname = parsed.hostname
|
||||
# Accessing ``port`` performs urllib's syntax/range validation.
|
||||
_ = parsed.port
|
||||
except ValueError as exc:
|
||||
raise BundlerError(f"Invalid catalog url: '{url}'.") from exc
|
||||
if not (parsed.scheme or parsed.path):
|
||||
|
||||
@@ -58,7 +58,12 @@ def load_yaml(path: Path) -> Any:
|
||||
raise BundlerError(f"File not found: {path}")
|
||||
try:
|
||||
text = path.read_text(encoding="utf-8")
|
||||
except OSError as exc:
|
||||
except (OSError, UnicodeError) as exc:
|
||||
# A non-UTF-8 file raises UnicodeDecodeError, which is a ValueError --
|
||||
# NOT an OSError -- so it escaped this module's "IO failures degrade
|
||||
# into actionable BundlerError" contract as a raw traceback. Realistic
|
||||
# on Windows, where PowerShell 5.1's `Out-File`/`>` default to UTF-16.
|
||||
# Matches the sibling catalog readers (catalogs.py, workflows/catalog.py).
|
||||
raise BundlerError(f"Could not read {path}: {exc}") from exc
|
||||
try:
|
||||
has_node = yaml.compose(text) is not None
|
||||
@@ -98,9 +103,15 @@ def load_json(path: Path) -> Any:
|
||||
try:
|
||||
with path.open("r", encoding="utf-8") as handle:
|
||||
return json.load(handle)
|
||||
# JSONDecodeError stays FIRST: it and UnicodeDecodeError are sibling
|
||||
# ValueError subclasses (neither subsumes the other), so malformed-but-
|
||||
# decodable JSON keeps its more specific "Invalid JSON" message while a
|
||||
# decode failure falls through to the read-error clause below.
|
||||
except json.JSONDecodeError as exc:
|
||||
raise BundlerError(f"Invalid JSON in {path}: {exc}") from exc
|
||||
except OSError as exc:
|
||||
except (OSError, UnicodeError) as exc:
|
||||
# See load_yaml: a non-UTF-8 file raises UnicodeDecodeError, which is
|
||||
# not an OSError, and previously escaped as a raw traceback.
|
||||
raise BundlerError(f"Could not read {path}: {exc}") from exc
|
||||
|
||||
|
||||
|
||||
@@ -15,6 +15,11 @@ from .. import BundlerError
|
||||
from ..lib.yamlio import ensure_within, load_yaml
|
||||
|
||||
CONFIG_FILENAME = "bundle-catalogs.yml"
|
||||
# Supported bundle-catalogs.yml schema (major version). Both readers of the
|
||||
# file — this module's _merge_config and commands_impl/catalog_config._read —
|
||||
# reject an unsupported major version so a file written by a newer/incompatible
|
||||
# Spec Kit fails fast instead of being parsed under the wrong assumptions.
|
||||
CONFIG_SCHEMA_VERSION = "1.0"
|
||||
|
||||
|
||||
class InstallPolicy(str, Enum):
|
||||
@@ -139,6 +144,7 @@ class CatalogEntry:
|
||||
license: str
|
||||
download_url: str
|
||||
requires_speckit_version: str
|
||||
sha256: str | None = None
|
||||
provides: dict[str, int] = field(default_factory=dict)
|
||||
repository: str | None = None
|
||||
tags: tuple[str, ...] = ()
|
||||
@@ -181,6 +187,11 @@ class CatalogEntry:
|
||||
license=str(data.get("license", "")).strip(),
|
||||
download_url=str(data.get("download_url", "")).strip(),
|
||||
requires_speckit_version=str(requires.get("speckit_version", "")).strip(),
|
||||
sha256=(
|
||||
None
|
||||
if data.get("sha256") is None
|
||||
else str(data["sha256"]).strip()
|
||||
),
|
||||
provides=dict(provides_raw),
|
||||
repository=(str(data["repository"]) if data.get("repository") else None),
|
||||
tags=_parse_tags(data.get("tags"), entry_id),
|
||||
@@ -193,6 +204,7 @@ class CatalogEntry:
|
||||
description=self.description, author=self.author, license=self.license,
|
||||
download_url=self.download_url,
|
||||
requires_speckit_version=self.requires_speckit_version,
|
||||
sha256=self.sha256,
|
||||
provides=self.provides, repository=self.repository, tags=self.tags,
|
||||
verified=self.verified, source_id=source.id,
|
||||
source_policy=source.install_policy,
|
||||
@@ -267,6 +279,23 @@ def _merge_config(by_id: dict[str, CatalogSource], config_path: Path, scope: Sco
|
||||
f"Malformed catalog config at {config_path}: expected a mapping at "
|
||||
f"the top level, got {type(data).__name__}."
|
||||
)
|
||||
# Reject an unsupported major schema version, matching the sibling reader
|
||||
# commands_impl/catalog_config._read. Without this, a file written by a
|
||||
# newer/incompatible Spec Kit was silently parsed under v1 assumptions on
|
||||
# the resolution path (bundle search/install), while the other reader
|
||||
# rejected it — the two readers disagreed. An absent schema_version stays
|
||||
# valid (backward compatible with configs that omit it).
|
||||
schema_version = data.get("schema_version")
|
||||
if schema_version is not None and (
|
||||
str(schema_version).strip().split(".")[0]
|
||||
!= CONFIG_SCHEMA_VERSION.split(".")[0]
|
||||
):
|
||||
raise BundlerError(
|
||||
f"Unsupported catalog config schema version "
|
||||
f"'{str(schema_version).strip()}' at {config_path}; this Spec Kit "
|
||||
f"understands version {CONFIG_SCHEMA_VERSION}. The file may have been "
|
||||
"written by a newer version or is corrupt."
|
||||
)
|
||||
catalogs = data.get("catalogs")
|
||||
if catalogs is None:
|
||||
return
|
||||
|
||||
@@ -96,19 +96,19 @@ class BundleManifest:
|
||||
if not isinstance(data, dict):
|
||||
raise BundlerError("Manifest must be a YAML mapping at the top level.")
|
||||
|
||||
schema_version = str(data.get("schema_version", "")).strip()
|
||||
schema_version = _text(data.get("schema_version"))
|
||||
|
||||
bundle_raw = data.get("bundle")
|
||||
if not isinstance(bundle_raw, dict):
|
||||
raise BundlerError("Manifest is missing the required 'bundle' mapping.")
|
||||
meta = BundleMeta(
|
||||
id=str(bundle_raw.get("id", "")).strip(),
|
||||
name=str(bundle_raw.get("name", "")).strip(),
|
||||
version=str(bundle_raw.get("version", "")).strip(),
|
||||
role=str(bundle_raw.get("role", "")).strip(),
|
||||
description=str(bundle_raw.get("description", "")).strip(),
|
||||
author=str(bundle_raw.get("author", "")).strip(),
|
||||
license=str(bundle_raw.get("license", "")).strip(),
|
||||
id=_text(bundle_raw.get("id")),
|
||||
name=_text(bundle_raw.get("name")),
|
||||
version=_text(bundle_raw.get("version")),
|
||||
role=_text(bundle_raw.get("role")),
|
||||
description=_text(bundle_raw.get("description")),
|
||||
author=_text(bundle_raw.get("author")),
|
||||
license=_text(bundle_raw.get("license")),
|
||||
)
|
||||
|
||||
requires_raw = data.get("requires")
|
||||
@@ -117,7 +117,7 @@ class BundleManifest:
|
||||
elif not isinstance(requires_raw, dict):
|
||||
raise BundlerError("'requires' must be a mapping when present.")
|
||||
requires = Requires(
|
||||
speckit_version=str(requires_raw.get("speckit_version", "")).strip(),
|
||||
speckit_version=_text(requires_raw.get("speckit_version")),
|
||||
tools=_parse_str_list(requires_raw.get("tools"), "requires.tools"),
|
||||
mcp=_parse_str_list(requires_raw.get("mcp"), "requires.mcp"),
|
||||
)
|
||||
@@ -220,6 +220,22 @@ class BundleManifest:
|
||||
return self.integration is None
|
||||
|
||||
|
||||
def _text(raw: Any) -> str:
|
||||
"""Coerce a manifest scalar into stripped text, mapping an explicit null to ``""``.
|
||||
|
||||
A ``.get(key, "")`` default only covers a *missing* key. A key that is
|
||||
present but null -- how YAML spells an empty field (``author:`` with nothing
|
||||
after it) -- yields ``None``, and ``str(None)`` is the literal ``"None"``.
|
||||
That text is non-empty, so it sailed past the ``if not value`` required-field
|
||||
checks in :meth:`BundleManifest.structural_errors`: an empty required field
|
||||
was silently accepted and the bundle shipped ``"None"`` as its
|
||||
author/license/description.
|
||||
"""
|
||||
if raw is None:
|
||||
return ""
|
||||
return str(raw).strip()
|
||||
|
||||
|
||||
def _parse_str_list(raw: Any, field_name: str) -> tuple[str, ...]:
|
||||
"""Coerce a manifest list-of-strings field into a tuple of strings.
|
||||
|
||||
@@ -247,7 +263,7 @@ def _parse_refs(kind: str, raw: Any) -> list[ComponentRef]:
|
||||
refs.append(
|
||||
ComponentRef(
|
||||
kind=kind,
|
||||
id=str(item.get("id", "")).strip(),
|
||||
id=_text(item.get("id")),
|
||||
version=(str(item["version"]).strip() if item.get("version") else None),
|
||||
source=(str(item["source"]).strip() if item.get("source") else None),
|
||||
priority=priority,
|
||||
|
||||
@@ -16,6 +16,7 @@ from urllib.parse import ParseResult, urlparse
|
||||
from urllib.request import url2pathname
|
||||
|
||||
from ..._assets import _locate_core_pack, _repo_root
|
||||
from ..._download_security import MAX_JSON_CATALOG_BYTES, read_response_limited
|
||||
from .. import BundlerError
|
||||
from ..lib.yamlio import loads_json
|
||||
from ..models.catalog import CatalogSource
|
||||
@@ -76,6 +77,8 @@ def _validate_remote_url(source_id: str, url: str) -> None:
|
||||
try:
|
||||
parsed = urlparse(url)
|
||||
hostname = parsed.hostname
|
||||
# Accessing ``port`` performs urllib's syntax/range validation.
|
||||
_ = parsed.port
|
||||
except ValueError:
|
||||
raise BundlerError(
|
||||
f"Catalog '{source_id}' URL is malformed: {url}"
|
||||
@@ -117,7 +120,15 @@ def make_catalog_fetcher(*, allow_network: bool = True):
|
||||
|
||||
def fetch(source: CatalogSource) -> dict:
|
||||
url = source.url
|
||||
parsed = urlparse(url)
|
||||
try:
|
||||
parsed = urlparse(url)
|
||||
# Keep malformed authorities and ports inside the BundlerError
|
||||
# contract even when a config file was edited by hand.
|
||||
_ = parsed.port
|
||||
except ValueError:
|
||||
raise BundlerError(
|
||||
f"Catalog {source.id!r} URL is malformed: {url!r}"
|
||||
) from None
|
||||
scheme = parsed.scheme.lower()
|
||||
|
||||
if scheme == "builtin":
|
||||
@@ -180,7 +191,12 @@ def _http_get_json(source_id: str, url: str) -> dict:
|
||||
) as response:
|
||||
final_url = response.geturl()
|
||||
_validate_remote_url(source_id, final_url)
|
||||
raw = response.read().decode("utf-8")
|
||||
raw = read_response_limited(
|
||||
response,
|
||||
max_bytes=MAX_JSON_CATALOG_BYTES,
|
||||
error_type=BundlerError,
|
||||
label=f"bundle catalog '{source_id}'",
|
||||
).decode("utf-8")
|
||||
except BundlerError:
|
||||
raise
|
||||
except Exception as exc: # noqa: BLE001
|
||||
|
||||
@@ -12,8 +12,10 @@ import re
|
||||
from pathlib import Path
|
||||
|
||||
import typer
|
||||
from rich.markup import escape as _escape_markup
|
||||
|
||||
from ..._console import console, err_console
|
||||
from ..._download_security import MAX_DOWNLOAD_BYTES, read_response_limited
|
||||
from ...bundler import BundlerError
|
||||
from ...bundler.lib.project import (
|
||||
active_integration,
|
||||
@@ -184,11 +186,16 @@ def bundle_search(
|
||||
else ""
|
||||
)
|
||||
console.print(
|
||||
f" [bold]{r.entry.id}[/bold] v{r.entry.version} — {r.entry.name} "
|
||||
f"[dim]({r.entry.role})[/dim] {_trust_badge(r.entry.verified)} {policy}"
|
||||
f" [bold]{_escape_markup(str(r.entry.id))}[/bold] "
|
||||
f"v{_escape_markup(str(r.entry.version))} — "
|
||||
f"{_escape_markup(str(r.entry.name))} "
|
||||
f"[dim]({_escape_markup(str(r.entry.role))})[/dim] "
|
||||
f"{_trust_badge(r.entry.verified)} {policy}"
|
||||
)
|
||||
console.print(f" {_escape_markup(str(r.entry.description))}")
|
||||
console.print(
|
||||
f" [dim]source: {_escape_markup(str(r.source.id))}[/dim]"
|
||||
)
|
||||
console.print(f" {r.entry.description}")
|
||||
console.print(f" [dim]source: {r.source.id}[/dim]")
|
||||
|
||||
|
||||
@bundle_app.command("info")
|
||||
@@ -241,16 +248,31 @@ def bundle_info(
|
||||
print(_json.dumps(payload, indent=2))
|
||||
return
|
||||
|
||||
console.print(f"\n[bold cyan]{entry.id}[/bold cyan] v{entry.version} — {entry.name}")
|
||||
console.print(f" Role: {entry.role}")
|
||||
console.print(f" {entry.description}")
|
||||
console.print(f" Author: {entry.author} License: {entry.license}")
|
||||
console.print(f" Source: {resolved.source.id} ({resolved.source.install_policy.value})")
|
||||
console.print(
|
||||
f"\n[bold cyan]{_escape_markup(str(entry.id))}[/bold cyan] "
|
||||
f"v{_escape_markup(str(entry.version))} — "
|
||||
f"{_escape_markup(str(entry.name))}"
|
||||
)
|
||||
console.print(f" Role: {_escape_markup(str(entry.role))}")
|
||||
console.print(f" {_escape_markup(str(entry.description))}")
|
||||
console.print(
|
||||
f" Author: {_escape_markup(str(entry.author))} "
|
||||
f"License: {_escape_markup(str(entry.license))}"
|
||||
)
|
||||
console.print(
|
||||
f" Source: {_escape_markup(str(resolved.source.id))} "
|
||||
f"({resolved.source.install_policy.value})"
|
||||
)
|
||||
console.print(f" Trust: {_trust_badge(entry.verified)}")
|
||||
if entry.requires_speckit_version:
|
||||
console.print(f" Requires Spec Kit: {entry.requires_speckit_version}")
|
||||
console.print(
|
||||
f" Requires Spec Kit: "
|
||||
f"{_escape_markup(str(entry.requires_speckit_version))}"
|
||||
)
|
||||
if manifest and manifest.integration:
|
||||
console.print(f" Integration: {manifest.integration.id}")
|
||||
console.print(
|
||||
f" Integration: {_escape_markup(str(manifest.integration.id))}"
|
||||
)
|
||||
|
||||
if components:
|
||||
console.print("\n [bold]Components[/bold] (added on install):")
|
||||
@@ -260,18 +282,22 @@ def bundle_info(
|
||||
continue
|
||||
console.print(f" [bold]{kind}:[/bold]")
|
||||
for item in items:
|
||||
console.print(f" - {_format_component(item)}")
|
||||
console.print(
|
||||
f" - {_escape_markup(_format_component(item))}"
|
||||
)
|
||||
else:
|
||||
console.print("\n [bold]Provides:[/bold]")
|
||||
for kind in ("extensions", "presets", "steps", "workflows"):
|
||||
count = entry.provides.get(kind, 0)
|
||||
if count:
|
||||
console.print(f" {kind}: {count}")
|
||||
console.print(f" {kind}: {_escape_markup(str(count))}")
|
||||
|
||||
if overlaps:
|
||||
console.print("\n [yellow]Overlaps with already-installed bundles:[/yellow]")
|
||||
for overlap in overlaps:
|
||||
console.print(f" [yellow]-[/yellow] {overlap}")
|
||||
console.print(
|
||||
f" [yellow]-[/yellow] {_escape_markup(str(overlap))}"
|
||||
)
|
||||
|
||||
if not resolved.install_allowed:
|
||||
console.print(
|
||||
@@ -337,6 +363,10 @@ def bundle_install(
|
||||
local_manifest = _local_manifest_source(bundle_id)
|
||||
if local_manifest is not None:
|
||||
manifest = local_manifest
|
||||
_validate_manifest_structure(
|
||||
manifest,
|
||||
source=f"Local bundle source {bundle_id!r}",
|
||||
)
|
||||
else:
|
||||
stack = _build_stack(project_root or Path.cwd(), offline=offline)
|
||||
resolved = stack.resolve(bundle_id)
|
||||
@@ -350,6 +380,16 @@ def bundle_install(
|
||||
|
||||
if project_root is None:
|
||||
init_integration = _resolve_init_integration(integration, manifest)
|
||||
# Resolve all hard compatibility gates before ``specify init``.
|
||||
# Otherwise an incompatible but structurally valid bundle would
|
||||
# initialize a project and only then fail its version/integration
|
||||
# checks, leaving state behind after a failed install.
|
||||
resolve_install_plan(
|
||||
manifest,
|
||||
speckit_version=_speckit_version(),
|
||||
active_integration=init_integration,
|
||||
integration_explicit=True,
|
||||
)
|
||||
console.print(
|
||||
f"[cyan]No Spec Kit project here; initializing with integration "
|
||||
f"'{init_integration}'…[/cyan]"
|
||||
@@ -711,17 +751,24 @@ def _local_manifest_source(arg: str):
|
||||
|
||||
if candidate.suffix == ".zip":
|
||||
import io
|
||||
import zipfile
|
||||
|
||||
import yaml as _yaml
|
||||
|
||||
with zipfile.ZipFile(candidate) as archive:
|
||||
from ..._download_security import open_zip_bounded, read_zip_member_limited
|
||||
|
||||
with open_zip_bounded(candidate, error_type=BundlerError) as archive:
|
||||
try:
|
||||
raw = archive.read("bundle.yml")
|
||||
archive.getinfo("bundle.yml")
|
||||
except KeyError as exc:
|
||||
raise BundlerError(
|
||||
f"Artifact '{candidate}' does not contain a bundle.yml."
|
||||
) from exc
|
||||
raw = read_zip_member_limited(
|
||||
archive,
|
||||
"bundle.yml",
|
||||
error_type=BundlerError,
|
||||
label="bundle manifest",
|
||||
)
|
||||
data = _yaml.safe_load(io.BytesIO(raw))
|
||||
return BundleManifest.from_dict(data)
|
||||
|
||||
@@ -805,7 +852,13 @@ def _download_manifest(resolved, *, offline: bool):
|
||||
f"Network access disabled; cannot download bundle '{resolved.entry.id}' "
|
||||
f"from {url}."
|
||||
)
|
||||
return _download_remote_manifest(resolved.entry.id, url)
|
||||
manifest = _download_remote_manifest(
|
||||
resolved.entry.id,
|
||||
url,
|
||||
expected_sha256=getattr(resolved.entry, "sha256", None),
|
||||
)
|
||||
_validate_catalog_manifest(resolved.entry, manifest)
|
||||
return manifest
|
||||
|
||||
|
||||
def _require_https(label: str, url: str) -> None:
|
||||
@@ -817,6 +870,8 @@ def _require_https(label: str, url: str) -> None:
|
||||
try:
|
||||
parsed = urlparse(url)
|
||||
hostname = parsed.hostname
|
||||
# Accessing ``port`` performs urllib's syntax/range validation.
|
||||
_ = parsed.port
|
||||
except ValueError:
|
||||
raise BundlerError(
|
||||
f"Refusing to download {label}: URL is malformed: {url}"
|
||||
@@ -830,7 +885,12 @@ def _require_https(label: str, url: str) -> None:
|
||||
raise BundlerError(f"Refusing to download {label} from URL with no host: {url}")
|
||||
|
||||
|
||||
def _download_remote_manifest(entry_id: str, url: str):
|
||||
def _download_remote_manifest(
|
||||
entry_id: str,
|
||||
url: str,
|
||||
*,
|
||||
expected_sha256: str | None = None,
|
||||
):
|
||||
"""Fetch a remote bundle artifact over HTTPS and extract its manifest."""
|
||||
import io
|
||||
import tempfile
|
||||
@@ -842,6 +902,7 @@ def _download_remote_manifest(entry_id: str, url: str):
|
||||
from ...authentication.http import github_provider_hosts, open_url
|
||||
from ..._github_http import resolve_github_release_asset_api_url
|
||||
from ...bundler.models.manifest import BundleManifest
|
||||
from ...shared_infra import verify_archive_sha256
|
||||
|
||||
def _validate_redirect(old_url: str, new_url: str) -> None:
|
||||
_require_https(f"bundle '{entry_id}'", new_url)
|
||||
@@ -879,7 +940,18 @@ def _download_remote_manifest(entry_id: str, url: str):
|
||||
extra_headers=extra_headers,
|
||||
) as resp:
|
||||
_require_https(f"bundle '{entry_id}'", resp.geturl())
|
||||
raw = resp.read()
|
||||
raw = read_response_limited(
|
||||
resp,
|
||||
max_bytes=MAX_DOWNLOAD_BYTES,
|
||||
error_type=BundlerError,
|
||||
label=f"bundle '{entry_id}' download",
|
||||
)
|
||||
verify_archive_sha256(
|
||||
raw,
|
||||
expected_sha256,
|
||||
entry_id,
|
||||
BundlerError,
|
||||
)
|
||||
except BundlerError:
|
||||
raise
|
||||
except Exception as exc: # noqa: BLE001
|
||||
@@ -940,6 +1012,38 @@ def _download_remote_manifest(entry_id: str, url: str):
|
||||
) from exc
|
||||
|
||||
|
||||
def _validate_manifest_structure(manifest, *, source: str) -> None:
|
||||
"""Reject a malformed manifest before any project mutation can occur."""
|
||||
from ...bundler.services.validator import validate_manifest
|
||||
|
||||
report = validate_manifest(manifest)
|
||||
if report.ok:
|
||||
return
|
||||
raise BundlerError(
|
||||
f"{source} contains an invalid bundle manifest:\n - "
|
||||
+ "\n - ".join(report.errors)
|
||||
)
|
||||
|
||||
|
||||
def _validate_catalog_manifest(entry, manifest) -> None:
|
||||
"""Bind a downloaded manifest to the catalog identity that selected it."""
|
||||
if manifest.bundle.id != entry.id:
|
||||
raise BundlerError(
|
||||
f"Downloaded bundle id mismatch: catalog entry {entry.id!r} points to "
|
||||
f"a manifest for {manifest.bundle.id!r}."
|
||||
)
|
||||
if manifest.bundle.version != entry.version:
|
||||
raise BundlerError(
|
||||
f"Downloaded bundle version mismatch for {entry.id!r}: catalog declares "
|
||||
f"{entry.version!r}, but the manifest declares "
|
||||
f"{manifest.bundle.version!r}."
|
||||
)
|
||||
_validate_manifest_structure(
|
||||
manifest,
|
||||
source=f"Downloaded bundle {entry.id!r}",
|
||||
)
|
||||
|
||||
|
||||
def register(app: typer.Typer) -> None:
|
||||
"""Attach the bundle command group to the root Typer app."""
|
||||
app.add_typer(bundle_app, name="bundle")
|
||||
|
||||
39
src/specify_cli/commands/event.py
Normal file
39
src/specify_cli/commands/event.py
Normal file
@@ -0,0 +1,39 @@
|
||||
"""specify event * command handlers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import typer
|
||||
|
||||
event_app = typer.Typer(
|
||||
name="event",
|
||||
help="Manage and execute event-driven commands",
|
||||
add_completion=False,
|
||||
)
|
||||
|
||||
|
||||
@event_app.command("run")
|
||||
def event_run(
|
||||
command_name: str = typer.Argument(..., help="Name of the command to execute"),
|
||||
event_name: str = typer.Argument(..., help="Canonical event name (e.g., session_start)"),
|
||||
timeout: int = typer.Argument(
|
||||
120, help="Per-handler timeout in seconds (passed through from the native hook config)"
|
||||
),
|
||||
):
|
||||
"""Resolve and run an event-driven command script with stdin payload."""
|
||||
from ..events import resolve_and_run_event_command
|
||||
|
||||
# Read payload from stdin if available
|
||||
payload = sys.stdin.read() if not sys.stdin.isatty() else "{}"
|
||||
|
||||
# Run the event command
|
||||
project_root = Path.cwd() # The agent runs events from project root
|
||||
exit_code = resolve_and_run_event_command(
|
||||
command_name, event_name, payload, project_root, timeout=timeout
|
||||
)
|
||||
raise typer.Exit(code=exit_code)
|
||||
|
||||
|
||||
def register(app: typer.Typer) -> None:
|
||||
app.add_typer(event_app, name="event")
|
||||
@@ -183,6 +183,7 @@ def register(app: typer.Typer) -> None:
|
||||
save_init_options,
|
||||
)
|
||||
from ..integration_runtime import (
|
||||
invoke_prefix_for_integration as _invoke_prefix_for_integration,
|
||||
with_integration_setting as _with_integration_setting,
|
||||
)
|
||||
from ..integrations._commands import (
|
||||
@@ -442,12 +443,20 @@ def register(app: typer.Typer) -> None:
|
||||
if extra:
|
||||
integration_parsed_options.update(extra)
|
||||
|
||||
from ..events import resolve_events
|
||||
events_map = resolve_events(
|
||||
resolved_integration.key,
|
||||
resolved_integration.config,
|
||||
project_path,
|
||||
integration_parsed_options or None,
|
||||
)
|
||||
resolved_integration.setup(
|
||||
project_path,
|
||||
manifest,
|
||||
parsed_options=integration_parsed_options or None,
|
||||
script_type=selected_script,
|
||||
raw_options=integration_options,
|
||||
events=events_map,
|
||||
)
|
||||
manifest.save()
|
||||
|
||||
@@ -481,6 +490,12 @@ def register(app: typer.Typer) -> None:
|
||||
invoke_separator=resolved_integration.effective_invoke_separator(
|
||||
integration_parsed_options, project_root=project_path
|
||||
),
|
||||
invoke_prefix=_invoke_prefix_for_integration(
|
||||
resolved_integration,
|
||||
resolved_integration.key,
|
||||
integration_parsed_options,
|
||||
project_path,
|
||||
),
|
||||
)
|
||||
tracker.complete(
|
||||
"shared-infra", f"scripts ({selected_script}) + templates"
|
||||
|
||||
2096
src/specify_cli/events.py
Normal file
2096
src/specify_cli/events.py
Normal file
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -5,6 +5,7 @@ from __future__ import annotations
|
||||
from collections.abc import Callable
|
||||
from typing import Any
|
||||
|
||||
from ._invocation_style import get_invocation_prefix
|
||||
from .integration_state import integration_setting, integration_settings
|
||||
|
||||
|
||||
@@ -99,3 +100,14 @@ def invoke_separator_for_integration(
|
||||
return integration.effective_invoke_separator(stored_parsed, project_root)
|
||||
|
||||
return integration.effective_invoke_separator(None, project_root)
|
||||
|
||||
|
||||
def invoke_prefix_for_integration(
|
||||
integration: Any,
|
||||
key: str,
|
||||
parsed_options: dict[str, Any] | None = None,
|
||||
project_root: Any = None,
|
||||
) -> str:
|
||||
"""Resolve the native invocation prefix for an integration's output mode."""
|
||||
skills_mode = integration.is_skills_mode(parsed_options, project_root)
|
||||
return get_invocation_prefix(key, skills_mode)
|
||||
|
||||
@@ -48,6 +48,7 @@ def _register_builtins() -> None:
|
||||
"""
|
||||
# -- Imports (alphabetical) -------------------------------------------
|
||||
from .agy import AgyIntegration
|
||||
from .alquimia import AlquimiaAIIntegration
|
||||
from .amp import AmpIntegration
|
||||
from .auggie import AuggieIntegration
|
||||
from .bob import BobIntegration
|
||||
@@ -86,6 +87,7 @@ def _register_builtins() -> None:
|
||||
|
||||
# -- Registration (alphabetical) --------------------------------------
|
||||
_register(AgyIntegration())
|
||||
_register(AlquimiaAIIntegration())
|
||||
_register(AmpIntegration())
|
||||
_register(AuggieIntegration())
|
||||
_register(BobIntegration())
|
||||
|
||||
@@ -11,6 +11,7 @@ from rich.markup import escape
|
||||
from .._agent_config import SCRIPT_TYPE_CHOICES
|
||||
from .._console import console
|
||||
from ..integration_runtime import (
|
||||
invoke_prefix_for_integration as _invoke_prefix_for_integration,
|
||||
invoke_separator_for_integration as _invoke_separator_for_integration,
|
||||
resolve_integration_options as _resolve_integration_options_impl,
|
||||
with_integration_setting as _with_integration_setting,
|
||||
@@ -120,8 +121,7 @@ def _clear_init_options_for_integration(project_root: Path, integration_key: str
|
||||
def _remove_integration_json(project_root: Path) -> None:
|
||||
"""Remove ``.specify/integration.json`` if it exists."""
|
||||
path = project_root / INTEGRATION_JSON
|
||||
if path.exists():
|
||||
path.unlink()
|
||||
path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -333,6 +333,9 @@ def _set_default_integration(
|
||||
integration, {"integration_settings": settings}, key, parsed_options,
|
||||
project_root=project_root,
|
||||
),
|
||||
invoke_prefix=_invoke_prefix_for_integration(
|
||||
integration, key, parsed_options, project_root
|
||||
),
|
||||
force=refresh_templates_force,
|
||||
refresh_managed=True,
|
||||
refresh_hint=refresh_hint,
|
||||
@@ -391,23 +394,24 @@ def _register_extensions_for_agent(
|
||||
agent_key: str,
|
||||
*,
|
||||
continuing: str,
|
||||
force: bool = False,
|
||||
) -> None:
|
||||
"""Register all enabled extensions' commands/skills for ``agent_key``.
|
||||
|
||||
``use`` / ``switch`` re-register enabled extensions for the agent they
|
||||
activate; ``upgrade`` backfills them for the refreshed agent. Plain
|
||||
``install`` deliberately does not call this helper so adding a secondary
|
||||
integration has no extension side effects until it is selected or upgraded.
|
||||
See issue #2886.
|
||||
activate (rescaffold); ``upgrade`` does so only for the *active*
|
||||
integration. Plain ``install`` and upgrade of a non-active integration
|
||||
deliberately skip this helper so a secondary integration has no extension
|
||||
side effects until it is selected. See issues #2886 and #2948.
|
||||
|
||||
Known limitation: extension *skill* rendering is scoped to the active
|
||||
agent (init-options track a single ``ai`` / ``ai_skills`` pair). A
|
||||
skills-mode agent registered while it is *not* the active agent (e.g.
|
||||
Copilot ``--skills`` registered while non-active) therefore
|
||||
receives command files rather than skills here — matching ``extension
|
||||
add``'s multi-agent behavior. ``use`` / ``switch`` avoid this because they
|
||||
make the target the active agent first. Per-agent skills parity is tracked in
|
||||
#2948.
|
||||
Callers always pass the active agent (use/switch activate the target
|
||||
before registering), so extension *skill* rendering — which is scoped to
|
||||
the active ``ai`` / ``ai_skills`` init-options — matches ``agent_key``.
|
||||
|
||||
When ``force=True``, existing skill files are overwritten even when they
|
||||
are not dev-mode symlinks. Pass ``force=True`` in the upgrade path so that
|
||||
extension content is layered on top of the core-template files that
|
||||
``setup()`` just regenerated (fixes the skip-guard bug for skills mode).
|
||||
|
||||
Best-effort: never aborts the surrounding integration operation. Callers
|
||||
invoke it *after* the use/upgrade/switch transaction has committed so a
|
||||
@@ -416,7 +420,7 @@ def _register_extensions_for_agent(
|
||||
_best_effort_extension_op(
|
||||
project_root,
|
||||
agent_key,
|
||||
lambda mgr, key: mgr.register_enabled_extensions_for_agent(key),
|
||||
lambda mgr, key: mgr.register_enabled_extensions_for_agent(key, force=force),
|
||||
phase="register extension artifacts for",
|
||||
continuing=continuing,
|
||||
)
|
||||
@@ -443,6 +447,91 @@ def _unregister_extensions_for_agent(
|
||||
)
|
||||
|
||||
|
||||
def _register_presets_for_agent(
|
||||
project_root: Path,
|
||||
agent_key: str,
|
||||
*,
|
||||
continuing: str,
|
||||
) -> None:
|
||||
"""Register all enabled presets' command overrides/skills for ``agent_key``.
|
||||
|
||||
Presets follow the same single-active rule as extensions (#2948):
|
||||
``use`` / ``switch`` re-register enabled presets for the agent they
|
||||
activate (rescaffold), so a preset installed while a different
|
||||
integration was active is not left targeting that inactive integration.
|
||||
|
||||
Best-effort: never aborts the surrounding integration operation.
|
||||
"""
|
||||
try:
|
||||
from ..presets import PresetManager
|
||||
|
||||
preset_mgr = PresetManager(project_root)
|
||||
preset_mgr.register_enabled_presets_for_agent(agent_key)
|
||||
except Exception as preset_err:
|
||||
from .. import _print_cli_warning
|
||||
|
||||
_print_cli_warning(
|
||||
"register preset artifacts for",
|
||||
"integration",
|
||||
agent_key,
|
||||
preset_err,
|
||||
continuing=continuing,
|
||||
)
|
||||
|
||||
|
||||
def _unregister_presets_for_agent(
|
||||
project_root: Path,
|
||||
agent_key: str,
|
||||
*,
|
||||
continuing: str,
|
||||
) -> None:
|
||||
"""Best-effort removal of ``agent_key``'s preset command/skill artifacts.
|
||||
|
||||
Mirrors ``_unregister_extensions_for_agent``: used by ``switch`` when
|
||||
uninstalling the previous integration so its preset command overrides
|
||||
and skill mirrors don't linger as orphans in the old agent's directory
|
||||
once a different (possibly not-yet-installed) integration becomes
|
||||
active (#2948).
|
||||
|
||||
Best-effort: never aborts the surrounding integration operation.
|
||||
"""
|
||||
try:
|
||||
from ..presets import PresetManager
|
||||
|
||||
preset_mgr = PresetManager(project_root)
|
||||
preset_mgr.unregister_agent_artifacts(agent_key)
|
||||
except Exception as preset_err:
|
||||
from .. import _print_cli_warning
|
||||
|
||||
_print_cli_warning(
|
||||
"clean up preset artifacts for",
|
||||
"integration",
|
||||
agent_key,
|
||||
preset_err,
|
||||
continuing=continuing,
|
||||
)
|
||||
|
||||
|
||||
def _unregister_enabled_extension_commands_for_agent(
|
||||
project_root: Path,
|
||||
agent_key: str,
|
||||
*,
|
||||
continuing: str,
|
||||
) -> None:
|
||||
"""Best-effort removal of enabled extension command artifacts for ``agent_key``."""
|
||||
_best_effort_extension_op(
|
||||
project_root,
|
||||
agent_key,
|
||||
lambda mgr, key: mgr.unregister_agent_artifacts(
|
||||
key,
|
||||
enabled_only=True,
|
||||
commands_only=True,
|
||||
),
|
||||
phase="clean up enabled extension command artifacts for",
|
||||
continuing=continuing,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# CLI formatting helpers (re-exported from _commands.py)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -8,6 +8,7 @@ import typer
|
||||
from .._console import console
|
||||
from .._utils import _display_project_path
|
||||
from ..integration_runtime import (
|
||||
invoke_prefix_for_integration as _invoke_prefix_for_integration,
|
||||
invoke_separator_for_integration as _invoke_separator_for_integration,
|
||||
with_integration_setting as _with_integration_setting,
|
||||
)
|
||||
@@ -130,6 +131,9 @@ def integration_install(
|
||||
infra_integration, current, infra_key, infra_parsed,
|
||||
project_root=project_root,
|
||||
),
|
||||
invoke_prefix=_invoke_prefix_for_integration(
|
||||
infra_integration, infra_key, infra_parsed, project_root
|
||||
),
|
||||
)
|
||||
if os.name != "nt":
|
||||
from .. import ensure_executable_scripts
|
||||
@@ -139,12 +143,21 @@ def integration_install(
|
||||
integration.key, project_root, version=_get_speckit_version()
|
||||
)
|
||||
|
||||
from ..events import resolve_events
|
||||
events_map = resolve_events(
|
||||
integration.key,
|
||||
integration.config,
|
||||
project_root,
|
||||
parsed_options,
|
||||
)
|
||||
|
||||
try:
|
||||
integration.setup(
|
||||
project_root, manifest,
|
||||
parsed_options=parsed_options,
|
||||
script_type=selected_script,
|
||||
raw_options=raw_options,
|
||||
events=events_map,
|
||||
)
|
||||
manifest.save()
|
||||
new_installed = _dedupe_integration_keys([*installed_keys, integration.key])
|
||||
|
||||
@@ -9,6 +9,7 @@ import typer
|
||||
|
||||
from .._console import console
|
||||
from ..integration_runtime import (
|
||||
invoke_prefix_for_integration as _invoke_prefix_for_integration,
|
||||
invoke_separator_for_integration as _invoke_separator_for_integration,
|
||||
with_integration_setting as _with_integration_setting,
|
||||
)
|
||||
@@ -29,13 +30,16 @@ from ._helpers import (
|
||||
_read_integration_json,
|
||||
_refresh_init_options_speckit_version,
|
||||
_register_extensions_for_agent,
|
||||
_register_presets_for_agent,
|
||||
_remove_integration_json,
|
||||
_resolve_integration_options,
|
||||
_resolve_integration_script_type,
|
||||
_resolve_script_type,
|
||||
_set_default_integration,
|
||||
_set_default_integration_or_exit,
|
||||
_unregister_enabled_extension_commands_for_agent,
|
||||
_unregister_extensions_for_agent,
|
||||
_unregister_presets_for_agent,
|
||||
_update_init_options_for_integration,
|
||||
_write_integration_json,
|
||||
)
|
||||
@@ -54,6 +58,66 @@ def _manifest_tracks_skill_layout(manifest) -> bool:
|
||||
return any(str(rel).endswith("/SKILL.md") for rel in manifest.files)
|
||||
|
||||
|
||||
def _manifest_path_under(rel_path: str, root: str) -> bool:
|
||||
"""Return True when manifest key *rel_path* is inside project-relative *root*."""
|
||||
normalized_root = PurePath(root).as_posix().strip("/")
|
||||
normalized_rel = PurePath(rel_path).as_posix().strip("/")
|
||||
if not normalized_root:
|
||||
return False
|
||||
return normalized_rel == normalized_root or normalized_rel.startswith(
|
||||
f"{normalized_root}/"
|
||||
)
|
||||
|
||||
|
||||
def _legacy_command_root_changed(
|
||||
integration,
|
||||
project_root: Path,
|
||||
old_manifest,
|
||||
new_manifest,
|
||||
) -> bool:
|
||||
"""Return True when command artifacts moved from legacy_dir to canonical dir."""
|
||||
config = integration.registrar_config or {}
|
||||
canonical = config.get("dir")
|
||||
legacy = config.get("legacy_dir")
|
||||
if (
|
||||
not isinstance(canonical, str)
|
||||
or not canonical.strip()
|
||||
or not isinstance(legacy, str)
|
||||
or not legacy.strip()
|
||||
or PurePath(canonical).as_posix() == PurePath(legacy).as_posix()
|
||||
):
|
||||
return False
|
||||
|
||||
canonical_dir = project_root / canonical
|
||||
legacy_dir = project_root / legacy
|
||||
if not canonical_dir.is_dir() or not legacy_dir.is_dir():
|
||||
return False
|
||||
|
||||
old_had_legacy = any(
|
||||
_manifest_path_under(rel, legacy) for rel in old_manifest.files
|
||||
)
|
||||
new_has_canonical = any(
|
||||
_manifest_path_under(rel, canonical) for rel in new_manifest.files
|
||||
)
|
||||
return old_had_legacy and new_has_canonical
|
||||
|
||||
|
||||
def _legacy_command_root_upgrade_pending(integration, old_manifest) -> bool:
|
||||
"""Return True when the old manifest tracks command files under legacy_dir."""
|
||||
config = integration.registrar_config or {}
|
||||
canonical = config.get("dir")
|
||||
legacy = config.get("legacy_dir")
|
||||
if (
|
||||
not isinstance(canonical, str)
|
||||
or not canonical.strip()
|
||||
or not isinstance(legacy, str)
|
||||
or not legacy.strip()
|
||||
or PurePath(canonical).as_posix() == PurePath(legacy).as_posix()
|
||||
):
|
||||
return False
|
||||
return any(_manifest_path_under(rel, legacy) for rel in old_manifest.files)
|
||||
|
||||
|
||||
class _PresetRegistryUnreadableError(Exception):
|
||||
"""Raised when an existing preset registry cannot be read or parsed.
|
||||
|
||||
@@ -64,16 +128,21 @@ class _PresetRegistryUnreadableError(Exception):
|
||||
"""
|
||||
|
||||
|
||||
def _installed_presets_affecting_agent(project_root, agent_key: str) -> list[str]:
|
||||
def _installed_presets_affecting_agent(
|
||||
project_root,
|
||||
agent_key: str,
|
||||
*,
|
||||
include_skills: bool = True,
|
||||
) -> list[str]:
|
||||
"""Return IDs of installed presets with artifacts registered for *agent_key*.
|
||||
|
||||
Presets register command overrides for every detected agent and mirror
|
||||
skills for the active skills agent, tracking the result in each preset's
|
||||
``registered_commands`` / ``registered_skills`` metadata. There is no
|
||||
agent-scoped preset re-registration mechanism, so a command↔skills *layout
|
||||
change* cannot reconcile those artifacts (see ``integration_upgrade``).
|
||||
Callers use this to detect the unsafe case and reject the migration rather
|
||||
than silently orphaning preset files / leaving stale registry entries.
|
||||
Preset registration is active-agent-only (#2948): command overrides are
|
||||
written for the active non-skills agent and skills for the active skills
|
||||
agent, tracked per preset in ``registered_commands`` /
|
||||
``registered_skills``. Entries for *other* agents may still exist from
|
||||
when those agents were active. Callers use this to reject command-root or
|
||||
command↔skills layout migrations before mutation: preset rescaffolding is
|
||||
best-effort and cannot guarantee every tracked artifact has a replacement.
|
||||
|
||||
Fails **closed**: a genuinely absent registry (no presets ever installed)
|
||||
returns an empty list, but if the registry file exists and cannot be read
|
||||
@@ -112,22 +181,53 @@ def _installed_presets_affecting_agent(project_root, agent_key: str) -> list[str
|
||||
f"preset '{preset_id}' entry is malformed"
|
||||
)
|
||||
registered_commands = meta.get("registered_commands", {})
|
||||
if not isinstance(registered_commands, dict):
|
||||
if not isinstance(registered_commands, dict) or not all(
|
||||
isinstance(names, list) for names in registered_commands.values()
|
||||
):
|
||||
raise _PresetRegistryUnreadableError(
|
||||
f"preset '{preset_id}' registered_commands is malformed"
|
||||
)
|
||||
registered_skills = meta.get("registered_skills", [])
|
||||
if not isinstance(registered_skills, (list, tuple)):
|
||||
if isinstance(registered_skills, dict):
|
||||
# Per-agent provenance ({agent: [skill names]}): only entries for
|
||||
# *this* agent make the preset affect it. Values must be lists —
|
||||
# anything else (e.g. null) leaves ownership undecidable, so fail
|
||||
# closed rather than read it as "no artifacts".
|
||||
if not all(
|
||||
isinstance(names, list) for names in registered_skills.values()
|
||||
):
|
||||
raise _PresetRegistryUnreadableError(
|
||||
f"preset '{preset_id}' registered_skills is malformed"
|
||||
)
|
||||
has_skills = include_skills and bool(
|
||||
registered_skills.get(agent_key)
|
||||
)
|
||||
elif isinstance(registered_skills, (list, tuple)):
|
||||
# Legacy flat list: not agent-scoped, so any recorded skill may
|
||||
# belong to this agent — fail closed and count it as affecting.
|
||||
has_skills = include_skills and bool(registered_skills)
|
||||
else:
|
||||
raise _PresetRegistryUnreadableError(
|
||||
f"preset '{preset_id}' registered_skills is malformed"
|
||||
)
|
||||
has_commands = bool(registered_commands.get(agent_key))
|
||||
has_skills = bool(registered_skills)
|
||||
if has_commands or has_skills:
|
||||
affected.append(preset_id)
|
||||
return affected
|
||||
|
||||
|
||||
def _installed_command_presets_affecting_agent(
|
||||
project_root,
|
||||
agent_key: str,
|
||||
) -> list[str]:
|
||||
"""Return installed presets with command artifacts registered for *agent_key*."""
|
||||
return _installed_presets_affecting_agent(
|
||||
project_root,
|
||||
agent_key,
|
||||
include_skills=False,
|
||||
)
|
||||
|
||||
|
||||
@integration_app.command("switch")
|
||||
def integration_switch(
|
||||
target: str = typer.Argument(help="Integration key to switch to"),
|
||||
@@ -218,6 +318,14 @@ def integration_switch(
|
||||
"need re-registration."
|
||||
),
|
||||
)
|
||||
_register_presets_for_agent(
|
||||
project_root,
|
||||
target,
|
||||
continuing=(
|
||||
"The integration switch succeeded, but installed presets may "
|
||||
"need re-registration."
|
||||
),
|
||||
)
|
||||
console.print(f"\n[green]✓[/green] Default integration set to [bold]{target}[/bold].")
|
||||
raise typer.Exit(0)
|
||||
|
||||
@@ -275,6 +383,19 @@ def integration_switch(
|
||||
continuing="Continuing with integration switch; old extension artifacts may need manual cleanup.",
|
||||
)
|
||||
|
||||
# Unregister preset commands/skills for the old agent for the same
|
||||
# reason: without this, a preset's command overrides (including
|
||||
# custom preset commands) and skill mirrors rendered for
|
||||
# installed_key would remain orphaned in its directory once a
|
||||
# different, possibly not-yet-installed integration becomes active
|
||||
# (#2948). Scoped strictly to installed_key; other agents' files,
|
||||
# tracking, and the preset packs themselves are untouched.
|
||||
_unregister_presets_for_agent(
|
||||
project_root,
|
||||
installed_key,
|
||||
continuing="Continuing with integration switch; old preset artifacts may need manual cleanup.",
|
||||
)
|
||||
|
||||
# Clear metadata so a failed Phase 2 doesn't leave stale references
|
||||
installed_keys = [installed for installed in installed_keys if installed != installed_key]
|
||||
_clear_init_options_for_integration(project_root, installed_key)
|
||||
@@ -327,6 +448,9 @@ def integration_switch(
|
||||
target_integration, current, target, parsed_options,
|
||||
project_root=project_root,
|
||||
),
|
||||
invoke_prefix=_invoke_prefix_for_integration(
|
||||
target_integration, target, parsed_options, project_root
|
||||
),
|
||||
refresh_hint=(
|
||||
"To overwrite customizations, re-run with "
|
||||
"[cyan]specify integration switch ... --refresh-shared-infra[/cyan]."
|
||||
@@ -342,12 +466,20 @@ def integration_switch(
|
||||
target_integration.key, project_root, version=_get_speckit_version()
|
||||
)
|
||||
|
||||
from ..events import resolve_events
|
||||
events_map = resolve_events(
|
||||
target_integration.key,
|
||||
target_integration.config,
|
||||
project_root,
|
||||
parsed_options,
|
||||
)
|
||||
try:
|
||||
target_integration.setup(
|
||||
project_root, manifest,
|
||||
parsed_options=parsed_options,
|
||||
script_type=selected_script,
|
||||
raw_options=raw_options,
|
||||
events=events_map,
|
||||
)
|
||||
manifest.save()
|
||||
_set_default_integration(
|
||||
@@ -396,6 +528,24 @@ def integration_switch(
|
||||
f"[yellow]Warning:[/yellow] Failed to restore default "
|
||||
f"integration '{fallback_key}': {restore_err}"
|
||||
)
|
||||
else:
|
||||
# Under active-only registration the fallback may never
|
||||
# have received any extension/preset artifacts (it was
|
||||
# installed while another integration was active), and
|
||||
# Phase 1 already unregistered the outgoing agent's
|
||||
# artifacts. Rescaffold so the restored default is
|
||||
# actually usable. Both helpers are best-effort and
|
||||
# cannot raise past this point.
|
||||
_register_extensions_for_agent(
|
||||
project_root,
|
||||
fallback_key,
|
||||
continuing="The switch was rolled back; installed extensions may need re-registration.",
|
||||
)
|
||||
_register_presets_for_agent(
|
||||
project_root,
|
||||
fallback_key,
|
||||
continuing="The switch was rolled back; installed presets may need re-registration.",
|
||||
)
|
||||
else:
|
||||
_write_integration_json(
|
||||
project_root, fallback_key, installed_keys, _integration_settings(current)
|
||||
@@ -416,6 +566,11 @@ def integration_switch(
|
||||
target,
|
||||
continuing="The integration switch succeeded, but installed extensions may need re-registration.",
|
||||
)
|
||||
_register_presets_for_agent(
|
||||
project_root,
|
||||
target,
|
||||
continuing="The integration switch succeeded, but installed presets may need re-registration.",
|
||||
)
|
||||
|
||||
name = (target_integration.config or {}).get("name", target)
|
||||
console.print(f"\n[green]✓[/green] Switched to integration '{name}'")
|
||||
@@ -487,18 +642,65 @@ def integration_upgrade(
|
||||
integration, current, key, integration_options
|
||||
)
|
||||
|
||||
# Guard: reject a command↔skills layout change while preset overrides are
|
||||
# installed for this agent (review #3415). A dual-mode agent (e.g. Bob)
|
||||
# can flip layout across an upgrade (``--skills`` / ``--legacy-commands``).
|
||||
# Extension artifacts are reconciled after the flip (see below), but preset
|
||||
# artifacts cannot be: there is no agent-scoped preset re-registration
|
||||
# anywhere in the CLI, so migrating would delete a preset's old-layout
|
||||
# files without recreating them in the new layout and leave the preset
|
||||
# registry claiming artifacts that no longer exist. Detect the intended
|
||||
# layout (``is_skills_mode`` reflects the resolved flags/disk state, so a
|
||||
# plain same-layout upgrade is unaffected) and bail out *before* any
|
||||
# mutation with an actionable error so the project is never left in a
|
||||
# half-migrated, inconsistent state.
|
||||
legacy_command_root_upgrade_pending = _legacy_command_root_upgrade_pending(
|
||||
integration,
|
||||
old_manifest,
|
||||
)
|
||||
|
||||
# Guard: Kilo's legacy command root moves from .kilocode/workflows to
|
||||
# .kilo/commands. Preset command artifacts are tracked outside the
|
||||
# integration manifest, and their agent-scoped rescaffold is best-effort,
|
||||
# not transactional with command-root cleanup. Refuse before setup writes
|
||||
# .kilo/commands rather than risking orphaned legacy files or missing
|
||||
# registry-tracked overrides in the canonical directory.
|
||||
if key == "kilocode" and legacy_command_root_upgrade_pending:
|
||||
config = integration.registrar_config or {}
|
||||
legacy = config.get("legacy_dir", "legacy command directory")
|
||||
canonical = config.get("dir", "canonical command directory")
|
||||
try:
|
||||
affected_presets = _installed_command_presets_affecting_agent(
|
||||
project_root,
|
||||
key,
|
||||
)
|
||||
except _PresetRegistryUnreadableError as exc:
|
||||
console.print(
|
||||
f"[red]Error:[/red] Cannot migrate '{key}' command directory "
|
||||
f"from [cyan]{legacy}[/cyan] to [cyan]{canonical}[/cyan]: "
|
||||
"the preset registry could not be read to verify installed presets."
|
||||
)
|
||||
console.print(f"[dim]Details:[/dim] {_cli_error_detail(exc)}")
|
||||
console.print(
|
||||
"A command directory migration cannot reconcile preset command "
|
||||
"artifacts while the preset registry state is unknown. Fix or "
|
||||
"restore [cyan].specify/presets/.registry[/cyan] and retry."
|
||||
)
|
||||
raise typer.Exit(1)
|
||||
if affected_presets:
|
||||
preset_list = ", ".join(sorted(affected_presets))
|
||||
console.print(
|
||||
f"[red]Error:[/red] Cannot migrate '{key}' command directory "
|
||||
f"from [cyan]{legacy}[/cyan] to [cyan]{canonical}[/cyan] while "
|
||||
f"preset override(s) are installed: [bold]{preset_list}[/bold]."
|
||||
)
|
||||
console.print(
|
||||
"Preset command artifacts cannot yet be reconciled across this "
|
||||
"command directory migration, so the upgrade is refused before "
|
||||
"changing files."
|
||||
)
|
||||
console.print(
|
||||
"Remove the preset(s), run the upgrade, then reinstall them:\n"
|
||||
f" [cyan]specify preset remove <id>[/cyan]\n"
|
||||
f" [cyan]specify integration upgrade {key} --script {selected_script} --force[/cyan]\n"
|
||||
f" [cyan]specify preset add <id>[/cyan]"
|
||||
)
|
||||
raise typer.Exit(1)
|
||||
|
||||
# Reject command↔skills layout changes while preset artifacts are tracked
|
||||
# for the integration (review #3415). Preset rescaffolding is best-effort:
|
||||
# an enabled preset can still have a missing/corrupt manifest or command
|
||||
# source, or fail during a write. Phase 2 would otherwise delete the
|
||||
# old-layout file before a replacement is known to exist. Refuse before
|
||||
# any mutation; same-layout upgrades still rescaffold the active agent.
|
||||
if _manifest_tracks_skill_layout(old_manifest) != integration.is_skills_mode(
|
||||
parsed_options, project_root
|
||||
):
|
||||
@@ -524,9 +726,9 @@ def integration_upgrade(
|
||||
f"preset override(s) are installed: [bold]{preset_list}[/bold]."
|
||||
)
|
||||
console.print(
|
||||
"Preset artifacts cannot yet be reconciled across a command↔skills "
|
||||
"layout change, so the migration would orphan their files and leave "
|
||||
"the preset registry inconsistent."
|
||||
"Preset artifacts cannot be safely reconciled across a "
|
||||
"command↔skills layout change, so the migration is refused "
|
||||
"before changing files."
|
||||
)
|
||||
console.print(
|
||||
"Remove the preset(s), run the upgrade, then reinstall them:\n"
|
||||
@@ -557,6 +759,9 @@ def integration_upgrade(
|
||||
infra_integration, current, infra_key, infra_parsed,
|
||||
project_root=project_root,
|
||||
),
|
||||
invoke_prefix=_invoke_prefix_for_integration(
|
||||
infra_integration, infra_key, infra_parsed, project_root
|
||||
),
|
||||
)
|
||||
if os.name != "nt":
|
||||
from .. import ensure_executable_scripts
|
||||
@@ -566,6 +771,13 @@ def integration_upgrade(
|
||||
console.print(f"Upgrading integration: [cyan]{key}[/cyan]")
|
||||
new_manifest = IntegrationManifest(key, project_root, version=_get_speckit_version())
|
||||
|
||||
from ..events import resolve_events
|
||||
events_map = resolve_events(
|
||||
key,
|
||||
integration.config,
|
||||
project_root,
|
||||
parsed_options,
|
||||
)
|
||||
try:
|
||||
integration.setup(
|
||||
project_root,
|
||||
@@ -573,6 +785,7 @@ def integration_upgrade(
|
||||
parsed_options=parsed_options,
|
||||
script_type=selected_script,
|
||||
raw_options=raw_options,
|
||||
events=events_map,
|
||||
)
|
||||
settings = _with_integration_setting(
|
||||
current,
|
||||
@@ -592,6 +805,9 @@ def integration_upgrade(
|
||||
integration, {"integration_settings": settings}, key, parsed_options,
|
||||
project_root=project_root,
|
||||
),
|
||||
invoke_prefix=_invoke_prefix_for_integration(
|
||||
integration, key, parsed_options, project_root
|
||||
),
|
||||
force=force,
|
||||
refresh_managed=True,
|
||||
)
|
||||
@@ -646,66 +862,38 @@ def integration_upgrade(
|
||||
if stale_removed:
|
||||
console.print(f" Removed {len(stale_removed)} stale file(s) from previous install")
|
||||
|
||||
# Re-register enabled extensions for the upgraded agent so its extension
|
||||
# commands are (re)created — including agents installed before this
|
||||
# back-fill existed. Mirrors switch for command registration; see #2886.
|
||||
# Done after the upgrade has fully settled (Phase 2 included) and outside
|
||||
# the try/except above so this best-effort step cannot affect upgrade
|
||||
# success.
|
||||
#
|
||||
# Layout-change reconciliation: a dual-mode agent (e.g. Bob) can flip
|
||||
# between the legacy commands layout and the skills layout across an
|
||||
# upgrade (``upgrade bob --integration-options "--skills"`` / reverse
|
||||
# ``--legacy-commands``). Phase 2 above only removes stale files tracked by
|
||||
# the *integration* manifest (core commands); extension artifacts are
|
||||
# tracked separately in the extension registry, so the old layout's
|
||||
# extension command/skill files would otherwise linger as orphans. When the
|
||||
# layout actually changed, first unregister the agent's extension artifacts
|
||||
# (removing old-layout files and clearing per-agent registry entries) so the
|
||||
# re-registration below recreates them in the new layout. ``upgrade``s that
|
||||
# don't change layout skip this to avoid needless remove/re-add churn.
|
||||
#
|
||||
# Only the *active* integration is reconciled this way (``installed_key ==
|
||||
# key``). ``ExtensionManager.unregister_agent_artifacts`` treats the
|
||||
# per-extension ``registered_skills`` list as belonging to the passed agent
|
||||
# and, when that agent's skills directory is absent, falls back to scanning
|
||||
# every agent's skills directory — so running it for a *secondary*
|
||||
# (non-active) agent could delete or untrack the *active* agent's extension
|
||||
# skills. The subsequent re-registration cannot repair that because
|
||||
# extension skill rendering is intentionally scoped to the active agent
|
||||
# (#2948). Extension skills only ever exist for the active agent, so
|
||||
# skipping the unregister for a secondary agent orphans nothing new: a
|
||||
# secondary agent only has extension *command* files, which the
|
||||
# re-registration below rewrites in place regardless of layout.
|
||||
#
|
||||
# Known limitation: preset command/skill artifacts are NOT reconciled on a
|
||||
# layout change. There is no agent-scoped preset re-registration mechanism
|
||||
# anywhere in the CLI — ``use`` / ``switch`` / ``upgrade`` never reconcile
|
||||
# presets for any agent (presets are only (un)registered at preset
|
||||
# install/remove time). Rather than silently orphan them, the guard near
|
||||
# the top of this function rejects a layout-changing upgrade while preset
|
||||
# overrides are installed, so control only reaches here (with a changed
|
||||
# layout) when no preset artifacts are at stake. Full preset reconciliation
|
||||
# would require a new cross-cutting PresetManager subsystem affecting every
|
||||
# dual-layout agent, which is out of scope for this Bob migration.
|
||||
if (
|
||||
installed_key == key
|
||||
and _manifest_tracks_skill_layout(old_manifest)
|
||||
!= _manifest_tracks_skill_layout(new_manifest)
|
||||
):
|
||||
_unregister_extensions_for_agent(
|
||||
legacy_command_root_changed = _legacy_command_root_changed(
|
||||
integration,
|
||||
project_root,
|
||||
old_manifest,
|
||||
new_manifest,
|
||||
)
|
||||
if legacy_command_root_changed:
|
||||
_unregister_enabled_extension_commands_for_agent(
|
||||
project_root,
|
||||
key,
|
||||
continuing=(
|
||||
"The integration layout changed, but old-layout extension "
|
||||
"artifacts may need manual cleanup."
|
||||
"The integration command directory changed, but legacy enabled "
|
||||
"extension artifacts may need manual cleanup."
|
||||
),
|
||||
)
|
||||
_register_extensions_for_agent(
|
||||
project_root,
|
||||
key,
|
||||
continuing="The integration was upgraded, but installed extensions may need re-registration.",
|
||||
)
|
||||
|
||||
# Re-register enabled extensions and presets only when upgrading the
|
||||
# active integration. Inactive integrations remain untouched until
|
||||
# `use` or `switch` activates and rescaffolds them (#2948). This runs
|
||||
# after the core upgrade transaction, so failures remain best-effort.
|
||||
if key == installed_key:
|
||||
_register_extensions_for_agent(
|
||||
project_root,
|
||||
key,
|
||||
force=True,
|
||||
continuing="The integration was upgraded, but installed extensions may need re-registration.",
|
||||
)
|
||||
_register_presets_for_agent(
|
||||
project_root,
|
||||
key,
|
||||
continuing="The integration was upgraded, but installed presets may need re-registration.",
|
||||
)
|
||||
|
||||
name = (integration.config or {}).get("name", key)
|
||||
console.print(f"\n[green]✓[/green] Integration '{name}' upgraded successfully")
|
||||
|
||||
@@ -18,6 +18,7 @@ from ._commands import integration_app, integration_catalog_app
|
||||
from ._helpers import (
|
||||
_read_integration_json,
|
||||
_register_extensions_for_agent,
|
||||
_register_presets_for_agent,
|
||||
_resolve_integration_options,
|
||||
_set_default_integration_or_exit,
|
||||
)
|
||||
@@ -248,6 +249,11 @@ def integration_use(
|
||||
key,
|
||||
continuing="The integration was selected, but installed extensions may need re-registration.",
|
||||
)
|
||||
_register_presets_for_agent(
|
||||
project_root,
|
||||
key,
|
||||
continuing="The integration was selected, but installed presets may need re-registration.",
|
||||
)
|
||||
console.print(f"[green]✓[/green] Default integration set to [bold]{key}[/bold].")
|
||||
|
||||
|
||||
@@ -312,22 +318,26 @@ def integration_search(
|
||||
|
||||
console.print(f"\n[green]Found {len(results)} integration(s):[/green]\n")
|
||||
for integ in sorted(results, key=lambda e: e.get("id", "")):
|
||||
iid = integ.get("id", "?")
|
||||
name = integ.get("name", iid)
|
||||
version = integ.get("version", "?")
|
||||
iid_value = str(integ.get("id", "?"))
|
||||
iid = _rich_escape(iid_value)
|
||||
name = _rich_escape(str(integ.get("name", iid_value)))
|
||||
version = _rich_escape(str(integ.get("version", "?")))
|
||||
console.print(f"[bold]{name}[/bold] ({iid}) v{version}")
|
||||
desc = integ.get("description", "")
|
||||
if desc:
|
||||
console.print(f" {desc}")
|
||||
console.print(f" {_rich_escape(str(desc))}")
|
||||
|
||||
console.print(f"\n [dim]Author:[/dim] {integ.get('author', 'Unknown')}")
|
||||
author_value = _rich_escape(str(integ.get("author", "Unknown")))
|
||||
console.print(f"\n [dim]Author:[/dim] {author_value}")
|
||||
tags = integ.get("tags", [])
|
||||
if isinstance(tags, list) and tags:
|
||||
console.print(f" [dim]Tags:[/dim] {', '.join(str(t) for t in tags)}")
|
||||
safe_tags = _rich_escape(", ".join(str(t) for t in tags))
|
||||
console.print(f" [dim]Tags:[/dim] {safe_tags}")
|
||||
|
||||
cat_name = integ.get("_catalog_name", "")
|
||||
cat_name_value = integ.get("_catalog_name", "")
|
||||
cat_name = _rich_escape(str(cat_name_value))
|
||||
install_allowed = integ.get("_install_allowed", True)
|
||||
if cat_name:
|
||||
if cat_name_value:
|
||||
if install_allowed:
|
||||
console.print(f" [dim]Catalog:[/dim] {cat_name}")
|
||||
else:
|
||||
@@ -336,9 +346,9 @@ def integration_search(
|
||||
"[yellow](discovery only — not installable)[/yellow]"
|
||||
)
|
||||
|
||||
if iid == installed_key:
|
||||
if iid_value == installed_key:
|
||||
console.print("\n [green]✓ Installed[/green] (currently active)")
|
||||
elif iid in INTEGRATION_REGISTRY:
|
||||
elif iid_value in INTEGRATION_REGISTRY:
|
||||
console.print(f"\n [cyan]Install:[/cyan] specify integration install {iid}")
|
||||
elif install_allowed:
|
||||
console.print(
|
||||
@@ -368,6 +378,7 @@ def integration_info(
|
||||
project_root = _require_specify_project()
|
||||
catalog = IntegrationCatalog(project_root)
|
||||
installed_key = _default_integration_key(_read_integration_json(project_root))
|
||||
safe_integration_id = _rich_escape(str(integration_id))
|
||||
|
||||
try:
|
||||
info = catalog.get_integration_info(integration_id)
|
||||
@@ -380,29 +391,38 @@ def integration_info(
|
||||
catalog_error = None
|
||||
|
||||
if info:
|
||||
name = info.get("name", integration_id)
|
||||
version = info.get("version", "?")
|
||||
console.print(f"\n[bold cyan]{name}[/bold cyan] ({integration_id}) v{version}")
|
||||
name = _rich_escape(str(info.get("name", integration_id)))
|
||||
version = _rich_escape(str(info.get("version", "?")))
|
||||
console.print(
|
||||
f"\n[bold cyan]{name}[/bold cyan] ({safe_integration_id}) v{version}"
|
||||
)
|
||||
if info.get("description"):
|
||||
console.print(f" {info['description']}")
|
||||
console.print(f" {_rich_escape(str(info['description']))}")
|
||||
console.print()
|
||||
|
||||
console.print(f" [dim]Author:[/dim] {info.get('author', 'Unknown')}")
|
||||
author_value = _rich_escape(str(info.get("author", "Unknown")))
|
||||
console.print(f" [dim]Author:[/dim] {author_value}")
|
||||
if info.get("license"):
|
||||
console.print(f" [dim]License:[/dim] {info['license']}")
|
||||
console.print(
|
||||
f" [dim]License:[/dim] {_rich_escape(str(info['license']))}"
|
||||
)
|
||||
|
||||
tags = info.get("tags", [])
|
||||
if isinstance(tags, list) and tags:
|
||||
console.print(f" [dim]Tags:[/dim] {', '.join(str(t) for t in tags)}")
|
||||
safe_tags = _rich_escape(", ".join(str(t) for t in tags))
|
||||
console.print(f" [dim]Tags:[/dim] {safe_tags}")
|
||||
|
||||
cat_name = info.get("_catalog_name", "")
|
||||
cat_name_value = info.get("_catalog_name", "")
|
||||
cat_name = _rich_escape(str(cat_name_value))
|
||||
install_allowed = info.get("_install_allowed", True)
|
||||
if cat_name:
|
||||
if cat_name_value:
|
||||
install_note = "" if install_allowed else " [yellow](discovery only)[/yellow]"
|
||||
console.print(f" [dim]Source catalog:[/dim] {cat_name}{install_note}")
|
||||
|
||||
if info.get("repository"):
|
||||
console.print(f" [dim]Repository:[/dim] {info['repository']}")
|
||||
console.print(
|
||||
f" [dim]Repository:[/dim] {_rich_escape(str(info['repository']))}"
|
||||
)
|
||||
|
||||
if integration_id == installed_key:
|
||||
console.print("\n [green]✓ Installed[/green] (currently active)")
|
||||
@@ -438,7 +458,7 @@ def integration_info(
|
||||
else:
|
||||
console.print("\nTry again when online, or use a built-in integration ID directly.")
|
||||
else:
|
||||
console.print(f"[red]Error:[/red] Integration '{integration_id}' not found")
|
||||
console.print(f"[red]Error:[/red] Integration '{safe_integration_id}' not found")
|
||||
console.print("\nTry: specify integration search")
|
||||
raise typer.Exit(1)
|
||||
|
||||
@@ -489,13 +509,14 @@ def integration_catalog_list():
|
||||
display_name = str(raw_name).strip() if raw_name is not None else ""
|
||||
if not display_name:
|
||||
display_name = f"catalog-{i + 1}"
|
||||
safe_name = _rich_escape(display_name)
|
||||
if env_override or project_configs is None:
|
||||
console.print(f" - [bold]{display_name}[/bold] — {install_status}")
|
||||
console.print(f" - [bold]{safe_name}[/bold] — {install_status}")
|
||||
else:
|
||||
console.print(f" [{i}] [bold]{display_name}[/bold] — {install_status}")
|
||||
console.print(f" {cfg.get('url', '')}")
|
||||
console.print(f" [{i}] [bold]{safe_name}[/bold] — {install_status}")
|
||||
console.print(f" {_rich_escape(str(cfg.get('url', '')))}")
|
||||
if cfg.get("description"):
|
||||
console.print(f" [dim]{cfg['description']}[/dim]")
|
||||
console.print(f" [dim]{_rich_escape(str(cfg['description']))}[/dim]")
|
||||
console.print()
|
||||
|
||||
|
||||
|
||||
165
src/specify_cli/integrations/alquimia/__init__.py
Normal file
165
src/specify_cli/integrations/alquimia/__init__.py
Normal file
@@ -0,0 +1,165 @@
|
||||
"""Alquimia AI integration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from ..._utils import dump_frontmatter
|
||||
from ..base import SkillsIntegration
|
||||
|
||||
# Mapping of command template stem → argument-hint text shown inline
|
||||
# when a user invokes the slash command in Alquimia AI.
|
||||
ARGUMENT_HINTS: dict[str, str] = {
|
||||
"specify": "Describe the feature you want to specify",
|
||||
"plan": "Optional guidance for the planning phase",
|
||||
"tasks": "Optional task generation constraints",
|
||||
"implement": "Optional implementation guidance or task filter",
|
||||
"analyze": "Optional focus areas for analysis",
|
||||
"clarify": "Optional areas to clarify in the spec",
|
||||
"constitution": "Principles or values for the project constitution",
|
||||
"checklist": "Domain or focus area for the checklist",
|
||||
"taskstoissues": "Optional filter or label for GitHub issues",
|
||||
}
|
||||
|
||||
|
||||
class AlquimiaAIIntegration(SkillsIntegration):
|
||||
"""Integration for Alquimia AI skills."""
|
||||
|
||||
key = "alquimia"
|
||||
config = {
|
||||
"name": "Alquimia AI",
|
||||
"folder": ".alquimia/",
|
||||
"commands_subdir": "skills",
|
||||
"install_url": "https://docs.alquimia.ai",
|
||||
"requires_cli": True,
|
||||
}
|
||||
registrar_config = {
|
||||
"dir": ".alquimia/skills",
|
||||
"format": "markdown",
|
||||
"args": "$ARGUMENTS",
|
||||
"extension": "/SKILL.md",
|
||||
}
|
||||
multi_install_safe = True
|
||||
|
||||
def _render_skill(
|
||||
self, template_name: str, frontmatter: dict[str, Any], body: str
|
||||
) -> str:
|
||||
"""Render a processed command template as an Alquimia skill."""
|
||||
skill_name = f"speckit-{template_name.replace('.', '-')}"
|
||||
description = frontmatter.get(
|
||||
"description",
|
||||
f"Spec-kit workflow command: {template_name}",
|
||||
)
|
||||
skill_frontmatter = self._build_skill_fm(
|
||||
skill_name, description, f"templates/commands/{template_name}.md"
|
||||
)
|
||||
frontmatter_text = dump_frontmatter(skill_frontmatter)
|
||||
return f"---\n{frontmatter_text}\n---\n\n{body.strip()}\n"
|
||||
|
||||
def _build_skill_fm(self, name: str, description: str, source: str) -> dict:
|
||||
from specify_cli.agents import CommandRegistrar
|
||||
|
||||
return CommandRegistrar.build_skill_frontmatter(
|
||||
self.key, name, description, source
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def inject_argument_hint(content: str, hint: str) -> str:
|
||||
"""Insert ``argument-hint`` after the first ``description:`` in YAML frontmatter.
|
||||
|
||||
Skips injection if ``argument-hint:`` already exists in the
|
||||
frontmatter to avoid duplicate keys.
|
||||
"""
|
||||
lines = content.splitlines(keepends=True)
|
||||
|
||||
# Pre-scan: bail out if argument-hint already present in frontmatter
|
||||
dash_count = 0
|
||||
for line in lines:
|
||||
stripped = line.rstrip("\n\r")
|
||||
if stripped == "---":
|
||||
dash_count += 1
|
||||
if dash_count == 2:
|
||||
break
|
||||
continue
|
||||
if dash_count == 1 and stripped.startswith("argument-hint:"):
|
||||
return content # already present
|
||||
|
||||
out: list[str] = []
|
||||
in_fm = False
|
||||
dash_count = 0
|
||||
injected = False
|
||||
for line in lines:
|
||||
stripped = line.rstrip("\n\r")
|
||||
if stripped == "---":
|
||||
dash_count += 1
|
||||
in_fm = dash_count == 1
|
||||
out.append(line)
|
||||
continue
|
||||
if in_fm and not injected and stripped.startswith("description:"):
|
||||
out.append(line)
|
||||
# Preserve the exact line-ending style (\r\n vs \n)
|
||||
if line.endswith("\r\n"):
|
||||
eol = "\r\n"
|
||||
elif line.endswith("\n"):
|
||||
eol = "\n"
|
||||
else:
|
||||
eol = ""
|
||||
escaped = hint.replace("\\", "\\\\").replace('"', '\\"')
|
||||
out.append(f'argument-hint: "{escaped}"{eol}')
|
||||
injected = True
|
||||
continue
|
||||
out.append(line)
|
||||
return "".join(out)
|
||||
|
||||
@staticmethod
|
||||
def _inject_frontmatter_flag(content: str, key: str, value: str = "true") -> str:
|
||||
"""Insert ``key: value`` before the closing ``---`` if not already present."""
|
||||
lines = content.splitlines(keepends=True)
|
||||
|
||||
# Pre-scan: bail out if already present in frontmatter
|
||||
dash_count = 0
|
||||
for line in lines:
|
||||
stripped = line.rstrip("\n\r")
|
||||
if stripped == "---":
|
||||
dash_count += 1
|
||||
if dash_count == 2:
|
||||
break
|
||||
continue
|
||||
if dash_count == 1 and stripped.startswith(f"{key}:"):
|
||||
return content
|
||||
|
||||
# Inject before the closing --- of frontmatter
|
||||
out: list[str] = []
|
||||
dash_count = 0
|
||||
injected = False
|
||||
for line in lines:
|
||||
stripped = line.rstrip("\n\r")
|
||||
if stripped == "---":
|
||||
dash_count += 1
|
||||
if dash_count == 2 and not injected:
|
||||
if line.endswith("\r\n"):
|
||||
eol = "\r\n"
|
||||
elif line.endswith("\n"):
|
||||
eol = "\n"
|
||||
else:
|
||||
eol = ""
|
||||
out.append(f"{key}: {value}{eol}")
|
||||
injected = True
|
||||
out.append(line)
|
||||
return "".join(out)
|
||||
|
||||
def post_process_skill_content(self, content: str) -> str:
|
||||
"""Inject Alquimia-specific frontmatter flags, hints and hook notes."""
|
||||
updated = super().post_process_skill_content(content)
|
||||
updated = self._inject_frontmatter_flag(updated, "user-invocable")
|
||||
updated = self._inject_frontmatter_flag(
|
||||
updated, "disable-model-invocation", "false"
|
||||
)
|
||||
for line in updated.splitlines():
|
||||
if line.startswith("name:"):
|
||||
name = line.removeprefix("name:").strip().strip("\"'")
|
||||
hint = ARGUMENT_HINTS.get(name.removeprefix("speckit-"))
|
||||
if hint:
|
||||
updated = self.inject_argument_hint(updated, hint)
|
||||
break
|
||||
return updated
|
||||
@@ -27,14 +27,16 @@ from typing import TYPE_CHECKING, Any
|
||||
|
||||
import yaml
|
||||
|
||||
from .._invocation_style import get_invocation_prefix, is_dollar_skills_agent
|
||||
from .._toml_string import escape_toml_basic as _escape_toml_basic
|
||||
from .._toml_string import has_illegal_toml_control as _has_illegal_toml_control
|
||||
from ..events import install_integration_events, remove_integration_events
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .manifest import IntegrationManifest
|
||||
|
||||
_HOOK_COMMAND_NOTE = (
|
||||
"- When constructing slash commands from hook command names, "
|
||||
"- When constructing command invocations from hook command names, "
|
||||
"replace dots (`.`) with hyphens (`-`). "
|
||||
"For example, `speckit.git.commit` → `/speckit-git-commit`.\n"
|
||||
)
|
||||
@@ -158,7 +160,17 @@ class IntegrationBase(ABC):
|
||||
@classmethod
|
||||
def options(cls) -> list[IntegrationOption]:
|
||||
"""Return options this integration accepts. Default: none."""
|
||||
return []
|
||||
opts = []
|
||||
if bool(getattr(cls, "CANONICAL_TO_NATIVE", None) and getattr(cls, "events_config_file", None)):
|
||||
opts.append(
|
||||
IntegrationOption(
|
||||
"--events",
|
||||
is_flag=False,
|
||||
default="true",
|
||||
help="Enable/disable runtime events (true|false, default: true)",
|
||||
)
|
||||
)
|
||||
return opts
|
||||
|
||||
def effective_invoke_separator(
|
||||
self,
|
||||
@@ -479,7 +491,11 @@ class IntegrationBase(ABC):
|
||||
tracking) would otherwise be deleted even though they are still
|
||||
managed. Subclasses list such paths here to protect them.
|
||||
"""
|
||||
return set()
|
||||
exclusions = set()
|
||||
if self.supports_events():
|
||||
from ..events import events_stale_exclusions
|
||||
exclusions.update(events_stale_exclusions(self.key))
|
||||
return exclusions
|
||||
|
||||
def commands_dest(self, project_root: Path) -> Path:
|
||||
"""Return the absolute path to the commands output directory.
|
||||
@@ -601,7 +617,9 @@ class IntegrationBase(ABC):
|
||||
return created
|
||||
|
||||
@staticmethod
|
||||
def resolve_command_refs(content: str, separator: str = ".") -> str:
|
||||
def resolve_command_refs(
|
||||
content: str, separator: str = ".", prefix: str = "/"
|
||||
) -> str:
|
||||
"""Replace ``__SPECKIT_COMMAND_<NAME>__`` placeholders with invocations.
|
||||
|
||||
Each placeholder encodes a command name in upper-case with
|
||||
@@ -611,10 +629,16 @@ class IntegrationBase(ABC):
|
||||
|
||||
* ``separator="."`` → ``/speckit.plan``, ``/speckit.git.commit``
|
||||
* ``separator="-"`` → ``/speckit-plan``, ``/speckit-git-commit``
|
||||
|
||||
*prefix* defaults to ``"/"`` but may be ``"$"`` for agents whose
|
||||
native skills invocation uses dollar-prefixed chat commands.
|
||||
"""
|
||||
return re.sub(
|
||||
r"__SPECKIT_COMMAND_([A-Z][A-Z0-9_]*)__",
|
||||
lambda m: "/speckit" + separator + m.group(1).lower().replace("_", separator),
|
||||
lambda m: prefix
|
||||
+ "speckit"
|
||||
+ separator
|
||||
+ m.group(1).lower().replace("_", separator),
|
||||
content,
|
||||
)
|
||||
|
||||
@@ -838,7 +862,12 @@ class IntegrationBase(ABC):
|
||||
content = CommandRegistrar.rewrite_project_relative_paths(content)
|
||||
|
||||
# 8. Replace __SPECKIT_COMMAND_<NAME>__ with invocation strings
|
||||
content = IntegrationBase.resolve_command_refs(content, invoke_separator)
|
||||
invocation_prefix = get_invocation_prefix(
|
||||
agent_name, invoke_separator == "-"
|
||||
)
|
||||
content = IntegrationBase.resolve_command_refs(
|
||||
content, invoke_separator, invocation_prefix
|
||||
)
|
||||
|
||||
return content
|
||||
|
||||
@@ -902,8 +931,32 @@ class IntegrationBase(ABC):
|
||||
|
||||
Returns ``(removed, skipped)`` file lists.
|
||||
"""
|
||||
self.remove_events(project_root, manifest)
|
||||
return manifest.uninstall(project_root, force=force)
|
||||
|
||||
def emit_events(
|
||||
self,
|
||||
project_root: Path,
|
||||
manifest: IntegrationManifest,
|
||||
events: dict[str, dict[str, Any]] | None = None,
|
||||
parsed_options: dict[str, Any] | None = None,
|
||||
**opts: Any,
|
||||
) -> list[Path]:
|
||||
"""Emit native event configuration for this integration."""
|
||||
return install_integration_events(self, project_root, manifest, events or {})
|
||||
|
||||
def remove_events(
|
||||
self,
|
||||
project_root: Path,
|
||||
manifest: IntegrationManifest,
|
||||
) -> None:
|
||||
"""Remove Specify-authored event entries from native config."""
|
||||
remove_integration_events(self, project_root, manifest)
|
||||
|
||||
def supports_events(self) -> bool:
|
||||
"""Return True if this integration supports agent-native events."""
|
||||
return bool(getattr(self, "CANONICAL_TO_NATIVE", None) and getattr(self, "events_config_file", None))
|
||||
|
||||
# -- Convenience helpers for subclasses -------------------------------
|
||||
|
||||
def install(
|
||||
@@ -1008,6 +1061,12 @@ class MarkdownIntegration(IntegrationBase):
|
||||
created.append(dst_file)
|
||||
|
||||
|
||||
# Install agent runtime events
|
||||
event_files = self.emit_events(
|
||||
project_root, manifest, events=opts.get("events"), parsed_options=parsed_options
|
||||
)
|
||||
created.extend(event_files)
|
||||
|
||||
return created
|
||||
|
||||
|
||||
@@ -1215,6 +1274,12 @@ class TomlIntegration(IntegrationBase):
|
||||
created.append(dst_file)
|
||||
|
||||
|
||||
# Install agent runtime events
|
||||
event_files = self.emit_events(
|
||||
project_root, manifest, events=opts.get("events"), parsed_options=parsed_options
|
||||
)
|
||||
created.extend(event_files)
|
||||
|
||||
return created
|
||||
|
||||
|
||||
@@ -1451,6 +1516,12 @@ class YamlIntegration(IntegrationBase):
|
||||
created.append(dst_file)
|
||||
|
||||
|
||||
# Install agent runtime events
|
||||
event_files = self.emit_events(
|
||||
project_root, manifest, events=opts.get("events"), parsed_options=parsed_options
|
||||
)
|
||||
created.extend(event_files)
|
||||
|
||||
return created
|
||||
|
||||
|
||||
@@ -1520,18 +1591,21 @@ class SkillsIntegration(IntegrationBase):
|
||||
return project_root / folder / subdir
|
||||
|
||||
def build_command_invocation(self, command_name: str, args: str = "") -> str:
|
||||
"""Skills use ``/speckit-<stem>`` (hyphenated directory name)."""
|
||||
"""Build the agent's native invocation for a hyphenated skill name."""
|
||||
stem = command_name
|
||||
if stem.startswith("speckit."):
|
||||
stem = stem[len("speckit."):]
|
||||
|
||||
invocation = "/speckit-" + stem.replace(".", "-")
|
||||
prefix = "$" if is_dollar_skills_agent(self.key, True) else "/"
|
||||
invocation = prefix + "speckit-" + stem.replace(".", "-")
|
||||
if args:
|
||||
invocation = f"{invocation} {args}"
|
||||
return invocation
|
||||
|
||||
@staticmethod
|
||||
def _inject_hook_command_note(content: str) -> str:
|
||||
def _inject_hook_command_note(
|
||||
content: str, invocation_prefix: str = "/"
|
||||
) -> str:
|
||||
"""Insert a dot-to-hyphen note before each hook output instruction.
|
||||
|
||||
Targets the line ``- For each executable hook, output the following``
|
||||
@@ -1540,6 +1614,11 @@ class SkillsIntegration(IntegrationBase):
|
||||
above them.
|
||||
"""
|
||||
note = _HOOK_COMMAND_NOTE.rstrip("\n")
|
||||
if invocation_prefix != "/":
|
||||
note = note.replace(
|
||||
"`/speckit-git-commit`",
|
||||
f"`{invocation_prefix}speckit-git-commit`",
|
||||
)
|
||||
|
||||
def repl(m: re.Match[str]) -> str:
|
||||
indent = m.group(1)
|
||||
@@ -1573,10 +1652,13 @@ class SkillsIntegration(IntegrationBase):
|
||||
Called by external skill generators (presets, extensions) to let
|
||||
the integration inject agent-specific frontmatter or body
|
||||
transformations. The base implementation injects shared skills
|
||||
guidance for converting dotted hook command names to hyphenated
|
||||
slash commands. Subclasses may override — see ``ClaudeIntegration``.
|
||||
guidance for converting dotted hook command names to the agent-native
|
||||
hyphenated command invocation (e.g. ``/speckit-git-commit`` or
|
||||
``$speckit-git-commit``). Subclasses may override -- see
|
||||
``ClaudeIntegration``.
|
||||
"""
|
||||
return self._inject_hook_command_note(content)
|
||||
invocation_prefix = get_invocation_prefix(self.key, True)
|
||||
return self._inject_hook_command_note(content, invocation_prefix)
|
||||
|
||||
def setup(
|
||||
self,
|
||||
@@ -1627,13 +1709,27 @@ class SkillsIntegration(IntegrationBase):
|
||||
command_name = src_file.stem # e.g. "plan"
|
||||
skill_name = f"speckit-{command_name.replace('.', '-')}"
|
||||
|
||||
# Parse frontmatter for description
|
||||
# Parse frontmatter for description. Locate the closing ``---`` on
|
||||
# its own line rather than with ``raw.split("---", 2)`` — a bare
|
||||
# substring split stops at the first ``---`` *anywhere*, including
|
||||
# one inside a value such as ``description: Separate sections
|
||||
# with ---``, which truncates the frontmatter and drops later keys.
|
||||
# The block between the delimiters is parsed unstripped so trailing
|
||||
# newlines in literal (``|``) block scalars survive.
|
||||
frontmatter: dict[str, Any] = {}
|
||||
if raw.startswith("---"):
|
||||
parts = raw.split("---", 2)
|
||||
if len(parts) >= 3:
|
||||
fm_lines = raw.splitlines(keepends=True)
|
||||
fm_close = next(
|
||||
(
|
||||
i
|
||||
for i in range(1, len(fm_lines))
|
||||
if fm_lines[i].rstrip() == "---"
|
||||
),
|
||||
None,
|
||||
)
|
||||
if fm_close is not None:
|
||||
try:
|
||||
fm = yaml.safe_load(parts[1])
|
||||
fm = yaml.safe_load("".join(fm_lines[1:fm_close]))
|
||||
if isinstance(fm, dict):
|
||||
frontmatter = fm
|
||||
except yaml.YAMLError:
|
||||
@@ -1648,11 +1744,27 @@ class SkillsIntegration(IntegrationBase):
|
||||
# Strip the processed frontmatter — we rebuild it for skills.
|
||||
# Preserve leading whitespace in the body to match release ZIP
|
||||
# output byte-for-byte (the template body starts with \n after
|
||||
# the closing ---).
|
||||
# the closing ---). Scan for the closing ``---`` on its own line
|
||||
# rather than ``split("---", 2)`` so a ``---`` embedded in a value
|
||||
# does not truncate the frontmatter and spill it into the body.
|
||||
if processed_body.startswith("---"):
|
||||
parts = processed_body.split("---", 2)
|
||||
if len(parts) >= 3:
|
||||
processed_body = parts[2]
|
||||
body_lines = processed_body.splitlines(keepends=True)
|
||||
close_idx = next(
|
||||
(
|
||||
i
|
||||
for i in range(1, len(body_lines))
|
||||
if body_lines[i].rstrip() == "---"
|
||||
),
|
||||
None,
|
||||
)
|
||||
if close_idx is not None:
|
||||
# Keep whatever trails the ``---`` marker on the closing
|
||||
# line (normally just the newline) so the body stays
|
||||
# byte-for-byte identical to ``split("---", 2)[2]``. The
|
||||
# line-anchored check guarantees ``---`` sits at index 0.
|
||||
processed_body = body_lines[close_idx][3:] + "".join(
|
||||
body_lines[close_idx + 1 :]
|
||||
)
|
||||
|
||||
# Select description — use the original template description
|
||||
# to stay byte-for-byte identical with release ZIP output.
|
||||
@@ -1686,4 +1798,10 @@ class SkillsIntegration(IntegrationBase):
|
||||
created.append(dst)
|
||||
|
||||
|
||||
# Install agent runtime events
|
||||
event_files = self.emit_events(
|
||||
project_root, manifest, events=opts.get("events"), parsed_options=parsed_options
|
||||
)
|
||||
created.extend(event_files)
|
||||
|
||||
return created
|
||||
|
||||
@@ -21,6 +21,7 @@ from typing import Any, Dict, List, Optional, Tuple
|
||||
import yaml
|
||||
from packaging import version as pkg_version
|
||||
|
||||
from .._download_security import MAX_JSON_METADATA_BYTES, read_response_limited
|
||||
from ..catalogs import CatalogEntry, CatalogStackBase
|
||||
|
||||
|
||||
@@ -200,7 +201,14 @@ class IntegrationCatalog(CatalogStackBase):
|
||||
final_url = resp.geturl()
|
||||
if final_url != entry.url:
|
||||
self._validate_catalog_url(final_url)
|
||||
catalog_data = json.loads(resp.read())
|
||||
catalog_data = json.loads(
|
||||
read_response_limited(
|
||||
resp,
|
||||
max_bytes=MAX_JSON_METADATA_BYTES,
|
||||
error_type=IntegrationCatalogError,
|
||||
label=f"catalog from {entry.url}",
|
||||
)
|
||||
)
|
||||
|
||||
shape_error = _catalog_shape_error(catalog_data)
|
||||
if shape_error is not None:
|
||||
|
||||
@@ -54,6 +54,17 @@ class ClaudeIntegration(SkillsIntegration):
|
||||
}
|
||||
multi_install_safe = True
|
||||
|
||||
CANONICAL_TO_NATIVE = {
|
||||
"session_start": "SessionStart",
|
||||
"pre_tool_use": "PreToolUse",
|
||||
"post_tool_use": "PostToolUse",
|
||||
"session_end": "SessionEnd",
|
||||
"user_prompt_submit": "UserPromptSubmit",
|
||||
"stop": "Stop",
|
||||
}
|
||||
events_config_file = ".claude/settings.json"
|
||||
events_format = "json-nested"
|
||||
|
||||
@staticmethod
|
||||
def inject_argument_hint(content: str, hint: str) -> str:
|
||||
"""Insert ``argument-hint`` after the first ``description:`` in YAML frontmatter.
|
||||
|
||||
@@ -29,6 +29,17 @@ class CodexIntegration(SkillsIntegration):
|
||||
dev_no_symlink = True
|
||||
multi_install_safe = True
|
||||
|
||||
CANONICAL_TO_NATIVE = {
|
||||
"session_start": "SessionStart",
|
||||
"pre_tool_use": "PreToolUse",
|
||||
"post_tool_use": "PostToolUse",
|
||||
"session_end": "SessionEnd",
|
||||
"user_prompt_submit": "UserPromptSubmit",
|
||||
"stop": "Stop",
|
||||
}
|
||||
events_config_file = ".codex/config.toml"
|
||||
events_format = "toml"
|
||||
|
||||
def build_exec_args(
|
||||
self,
|
||||
prompt: str,
|
||||
@@ -49,11 +60,13 @@ class CodexIntegration(SkillsIntegration):
|
||||
|
||||
@classmethod
|
||||
def options(cls) -> list[IntegrationOption]:
|
||||
return [
|
||||
opts = super().options()
|
||||
opts.append(
|
||||
IntegrationOption(
|
||||
"--skills",
|
||||
is_flag=True,
|
||||
default=True,
|
||||
help="Install as agent skills (default for Codex)",
|
||||
),
|
||||
]
|
||||
)
|
||||
)
|
||||
return opts
|
||||
|
||||
@@ -118,6 +118,19 @@ class CopilotIntegration(IntegrationBase):
|
||||
"extension": ".agent.md",
|
||||
}
|
||||
|
||||
CANONICAL_TO_NATIVE = {
|
||||
"session_start": "sessionStart",
|
||||
"pre_tool_use": "preToolUse",
|
||||
"post_tool_use": "postToolUse",
|
||||
"session_end": "sessionEnd",
|
||||
"user_prompt_submit": "userPromptSubmitted",
|
||||
# Copilot CLI supports the canonical per-turn stop lifecycle as native
|
||||
# agentStop (U3); mapping it so an extension's stop handler fires.
|
||||
"stop": "agentStop",
|
||||
}
|
||||
events_config_file = ".github/hooks/speckit.json"
|
||||
events_format = "copilot-json"
|
||||
|
||||
# Mutable flag set by setup() — indicates the active scaffolding mode.
|
||||
_skills_mode: bool = False
|
||||
|
||||
@@ -162,14 +175,19 @@ class CopilotIntegration(IntegrationBase):
|
||||
|
||||
@classmethod
|
||||
def options(cls) -> list[IntegrationOption]:
|
||||
return [
|
||||
# Compose with super() so the base class declares --events for this
|
||||
# event-capable integration; otherwise --integration-options
|
||||
# "--events false" is rejected as unknown (#9).
|
||||
opts = super().options()
|
||||
opts.append(
|
||||
IntegrationOption(
|
||||
"--skills",
|
||||
is_flag=True,
|
||||
default=False,
|
||||
help="Scaffold commands as agent skills (speckit-<name>/SKILL.md) instead of .agent.md files",
|
||||
),
|
||||
]
|
||||
)
|
||||
return opts
|
||||
|
||||
def _resolve_executable(self) -> str:
|
||||
"""Return the Copilot CLI executable, respecting the env-var override.
|
||||
@@ -328,7 +346,9 @@ class CopilotIntegration(IntegrationBase):
|
||||
be flagged stale and deleted, destroying user settings (and the file
|
||||
the integration still manages).
|
||||
"""
|
||||
return {".vscode/settings.json"}
|
||||
exclusions = super().stale_cleanup_exclusions()
|
||||
exclusions.add(".vscode/settings.json")
|
||||
return exclusions
|
||||
|
||||
def post_process_skill_content(self, content: str) -> str:
|
||||
"""Inject shared hook guidance into Copilot skill content.
|
||||
@@ -355,10 +375,18 @@ class CopilotIntegration(IntegrationBase):
|
||||
parsed_options = parsed_options or {}
|
||||
self._skills_mode = bool(parsed_options.get("skills"))
|
||||
if self._skills_mode:
|
||||
return self._setup_skills(project_root, manifest, parsed_options, **opts)
|
||||
if "skills" not in parsed_options:
|
||||
_warn_legacy_markdown_default()
|
||||
return self._setup_default(project_root, manifest, parsed_options, **opts)
|
||||
created = self._setup_skills(project_root, manifest, parsed_options, **opts)
|
||||
else:
|
||||
if "skills" not in parsed_options:
|
||||
_warn_legacy_markdown_default()
|
||||
created = self._setup_default(project_root, manifest, parsed_options, **opts)
|
||||
|
||||
# Install agent runtime events
|
||||
event_files = self.emit_events(
|
||||
project_root, manifest, events=opts.get("events"), parsed_options=parsed_options
|
||||
)
|
||||
created.extend(event_files)
|
||||
return created
|
||||
|
||||
def _setup_default(
|
||||
self,
|
||||
@@ -379,6 +407,10 @@ class CopilotIntegration(IntegrationBase):
|
||||
if not templates:
|
||||
return []
|
||||
|
||||
from ...presets import PresetResolver
|
||||
|
||||
preset_resolver = PresetResolver(project_root_resolved)
|
||||
|
||||
dest = self.commands_dest(project_root)
|
||||
dest_resolved = dest.resolve()
|
||||
try:
|
||||
@@ -396,7 +428,11 @@ class CopilotIntegration(IntegrationBase):
|
||||
|
||||
# 1. Process and write command files as .agent.md
|
||||
for src_file in templates:
|
||||
raw = src_file.read_text(encoding="utf-8")
|
||||
resolved_template = preset_resolver.resolve(
|
||||
f"speckit.{src_file.stem}", template_type="command"
|
||||
)
|
||||
source_path = resolved_template or src_file
|
||||
raw = source_path.read_text(encoding="utf-8")
|
||||
processed = self.process_template(
|
||||
raw, self.key, script_type, arg_placeholder,
|
||||
project_root=project_root,
|
||||
@@ -489,7 +525,7 @@ class CopilotIntegration(IntegrationBase):
|
||||
"""
|
||||
try:
|
||||
existing = json.loads(dst.read_text(encoding="utf-8"))
|
||||
except (json.JSONDecodeError, OSError):
|
||||
except (json.JSONDecodeError, UnicodeDecodeError, OSError):
|
||||
# Cannot parse existing file (likely JSONC with comments).
|
||||
# Skip merge to preserve the user's settings, but show
|
||||
# what they should add manually.
|
||||
|
||||
@@ -38,6 +38,17 @@ class CursorAgentIntegration(SkillsIntegration):
|
||||
|
||||
multi_install_safe = True
|
||||
|
||||
CANONICAL_TO_NATIVE = {
|
||||
"session_start": "sessionStart",
|
||||
"pre_tool_use": "preToolUse",
|
||||
"post_tool_use": "postToolUse",
|
||||
"session_end": "sessionEnd",
|
||||
"user_prompt_submit": "beforeSubmitPrompt",
|
||||
"stop": "stop",
|
||||
}
|
||||
events_config_file = ".cursor/hooks.json"
|
||||
events_format = "json-flat"
|
||||
|
||||
def build_exec_args(
|
||||
self,
|
||||
prompt: str,
|
||||
@@ -92,11 +103,13 @@ class CursorAgentIntegration(SkillsIntegration):
|
||||
|
||||
@classmethod
|
||||
def options(cls) -> list[IntegrationOption]:
|
||||
return [
|
||||
opts = super().options()
|
||||
opts.append(
|
||||
IntegrationOption(
|
||||
"--skills",
|
||||
is_flag=True,
|
||||
default=True,
|
||||
help="Install as agent skills (recommended for Cursor)",
|
||||
),
|
||||
]
|
||||
)
|
||||
)
|
||||
return opts
|
||||
|
||||
@@ -31,6 +31,20 @@ class DevinIntegration(SkillsIntegration):
|
||||
"extension": "/SKILL.md",
|
||||
}
|
||||
|
||||
CANONICAL_TO_NATIVE = {
|
||||
"session_start": "SessionStart",
|
||||
"pre_tool_use": "PreToolUse",
|
||||
"post_tool_use": "PostToolUse",
|
||||
"session_end": "SessionEnd",
|
||||
"user_prompt_submit": "UserPromptSubmit",
|
||||
"stop": "Stop",
|
||||
}
|
||||
events_config_file = ".devin/hooks.v1.json"
|
||||
# Devin's hooks.v1.json is a root event map ({"PreToolUse": [...]}) with no
|
||||
# top-level "hooks" wrapper (U2), unlike the settings.json formats. The
|
||||
# json-root-nested writer/remover operate directly on the root event keys.
|
||||
events_format = "json-root-nested"
|
||||
|
||||
def build_exec_args(
|
||||
self,
|
||||
prompt: str,
|
||||
@@ -55,11 +69,16 @@ class DevinIntegration(SkillsIntegration):
|
||||
|
||||
@classmethod
|
||||
def options(cls) -> list[IntegrationOption]:
|
||||
return [
|
||||
# Compose with super() so the base class declares --events for this
|
||||
# event-capable integration; otherwise --integration-options
|
||||
# "--events false" is rejected as unknown (#8).
|
||||
opts = super().options()
|
||||
opts.append(
|
||||
IntegrationOption(
|
||||
"--skills",
|
||||
is_flag=True,
|
||||
default=True,
|
||||
help="Install as agent skills (default for Devin)",
|
||||
),
|
||||
]
|
||||
)
|
||||
return opts
|
||||
|
||||
@@ -19,3 +19,22 @@ class GeminiIntegration(TomlIntegration):
|
||||
"extension": ".toml",
|
||||
}
|
||||
multi_install_safe = True
|
||||
|
||||
CANONICAL_TO_NATIVE = {
|
||||
"session_start": "SessionStart",
|
||||
"pre_tool_use": "BeforeTool",
|
||||
"post_tool_use": "AfterTool",
|
||||
"session_end": "SessionEnd",
|
||||
# Gemini exposes BeforeAgent for the per-turn prompt-submit lifecycle
|
||||
# point (S6); its own Claude-hook migration maps UserPromptSubmit to
|
||||
# BeforeAgent. Mapping it so extension handlers fire.
|
||||
"user_prompt_submit": "BeforeAgent",
|
||||
"stop": "AfterAgent",
|
||||
}
|
||||
events_config_file = ".gemini/settings.json"
|
||||
events_format = "json-nested"
|
||||
# Gemini measures hook timeouts in milliseconds, unlike Claude/Cursor/Codex
|
||||
# which use seconds. The shared formatter converts via _native_timeout (#7)
|
||||
# so the default 60s becomes 60000ms instead of terminating the dispatcher
|
||||
# after 60ms.
|
||||
events_timeout_unit = "ms"
|
||||
|
||||
@@ -53,8 +53,16 @@ class GenericIntegration(MarkdownIntegration):
|
||||
"""
|
||||
parsed_options = parsed_options or {}
|
||||
|
||||
# Accept a value only when it is non-BLANK. An empty value resolves to
|
||||
# the project root (``project_root / ""``) and a whitespace-only one to
|
||||
# a directory literally named " ", so either would silently scatter
|
||||
# command files instead of failing with the documented "required"
|
||||
# error. ``strip()`` is used ONLY to decide blankness -- the value
|
||||
# itself is returned verbatim, so a deliberate (if unusual) padded
|
||||
# directory name still targets exactly what the user asked for. Both
|
||||
# branches below apply the same rule so they cannot drift apart.
|
||||
commands_dir = parsed_options.get("commands_dir")
|
||||
if commands_dir:
|
||||
if commands_dir and (not isinstance(commands_dir, str) or commands_dir.strip()):
|
||||
return commands_dir
|
||||
|
||||
# Fall back to raw_options (--integration-options="--commands-dir ...")
|
||||
@@ -64,9 +72,13 @@ class GenericIntegration(MarkdownIntegration):
|
||||
tokens = shlex.split(raw)
|
||||
for i, token in enumerate(tokens):
|
||||
if token == "--commands-dir" and i + 1 < len(tokens):
|
||||
return tokens[i + 1]
|
||||
candidate = tokens[i + 1]
|
||||
if candidate.strip():
|
||||
return candidate
|
||||
if token.startswith("--commands-dir="):
|
||||
return token.split("=", 1)[1]
|
||||
candidate = token.split("=", 1)[1]
|
||||
if candidate.strip():
|
||||
return candidate
|
||||
|
||||
raise ValueError(
|
||||
"--commands-dir is required for the generic integration"
|
||||
|
||||
@@ -7,13 +7,14 @@ class KilocodeIntegration(MarkdownIntegration):
|
||||
key = "kilocode"
|
||||
config = {
|
||||
"name": "Kilo Code",
|
||||
"folder": ".kilocode/",
|
||||
"commands_subdir": "workflows",
|
||||
"folder": ".kilo/",
|
||||
"commands_subdir": "commands",
|
||||
"install_url": None,
|
||||
"requires_cli": False,
|
||||
}
|
||||
registrar_config = {
|
||||
"dir": ".kilocode/workflows",
|
||||
"dir": ".kilo/commands",
|
||||
"legacy_dir": ".kilocode/workflows",
|
||||
"format": "markdown",
|
||||
"args": "$ARGUMENTS",
|
||||
"extension": ".md",
|
||||
|
||||
@@ -59,8 +59,7 @@ class KimiIntegration(SkillsIntegration):
|
||||
|
||||
def post_process_skill_content(self, content: str) -> str:
|
||||
"""Ensure in-skill cross-command references use Kimi's `/skill:` syntax."""
|
||||
content = super().post_process_skill_content(content)
|
||||
return content.replace("/speckit-", "/skill:speckit-")
|
||||
return super().post_process_skill_content(content)
|
||||
|
||||
@classmethod
|
||||
def options(cls) -> list[IntegrationOption]:
|
||||
|
||||
@@ -400,7 +400,19 @@ class IntegrationManifest:
|
||||
# Remove the manifest file itself
|
||||
manifest = root / ".specify" / "integrations" / f"{self.key}.manifest.json"
|
||||
if remove_manifest and manifest.exists():
|
||||
manifest.unlink()
|
||||
try:
|
||||
manifest.unlink()
|
||||
except OSError:
|
||||
# An undeletable manifest (read-only file, a directory left at
|
||||
# the path, a Windows lock) must not abort the uninstall after
|
||||
# the tracked files were already removed: the caller would lose
|
||||
# the (removed, skipped) result and never run its post-uninstall
|
||||
# bookkeeping. Report it like any other file we could not
|
||||
# remove, mirroring the path.unlink() guard above. The
|
||||
# empty-parent cleanup below is left unconditional: with the
|
||||
# manifest still on disk its parent is non-empty, so the first
|
||||
# rmdir() raises and breaks immediately.
|
||||
skipped.append(manifest)
|
||||
parent = manifest.parent
|
||||
while parent != root:
|
||||
try:
|
||||
|
||||
@@ -20,6 +20,15 @@ class OpencodeIntegration(MarkdownIntegration):
|
||||
"extension": ".md",
|
||||
}
|
||||
|
||||
CANONICAL_TO_NATIVE = {
|
||||
"pre_tool_use": "tool.execute.before",
|
||||
"post_tool_use": "tool.execute.after",
|
||||
"session_start": "session.created",
|
||||
"session_end": "session.deleted",
|
||||
}
|
||||
events_config_file = "opencode.json"
|
||||
events_format = "ts-plugin"
|
||||
|
||||
def build_exec_args(
|
||||
self,
|
||||
prompt: str,
|
||||
|
||||
@@ -18,3 +18,4 @@ class PiIntegration(MarkdownIntegration):
|
||||
"args": "$ARGUMENTS",
|
||||
"extension": ".md",
|
||||
}
|
||||
multi_install_safe = True
|
||||
|
||||
@@ -19,3 +19,20 @@ class QwenIntegration(MarkdownIntegration):
|
||||
"extension": ".md",
|
||||
}
|
||||
multi_install_safe = True
|
||||
|
||||
CANONICAL_TO_NATIVE = {
|
||||
"session_start": "SessionStart",
|
||||
"pre_tool_use": "PreToolUse",
|
||||
"post_tool_use": "PostToolUse",
|
||||
"session_end": "SessionEnd",
|
||||
"user_prompt_submit": "UserPromptSubmit",
|
||||
"stop": "Stop",
|
||||
}
|
||||
events_config_file = ".qwen/settings.json"
|
||||
events_format = "json-nested"
|
||||
# Qwen Code's command hooks measure timeout in milliseconds (default
|
||||
# 60000), per the Qwen Code hooks documentation. Declaring the unit makes
|
||||
# the shared formatter convert the 60s default to 60000ms instead of
|
||||
# emitting timeout: 60 (60 ms), which would terminate the dispatcher
|
||||
# before it starts (U1).
|
||||
events_timeout_unit = "ms"
|
||||
|
||||
@@ -19,3 +19,23 @@ class TabnineIntegration(TomlIntegration):
|
||||
"extension": ".toml",
|
||||
}
|
||||
multi_install_safe = True
|
||||
|
||||
CANONICAL_TO_NATIVE = {
|
||||
"session_start": "SessionStart",
|
||||
"pre_tool_use": "BeforeTool",
|
||||
"post_tool_use": "AfterTool",
|
||||
"session_end": "SessionEnd",
|
||||
# Tabnine's Gemini-compatible schema also provides BeforeAgent and
|
||||
# AfterAgent (S7); mapping them so user_prompt_submit and stop
|
||||
# extension handlers fire instead of being skipped.
|
||||
"user_prompt_submit": "BeforeAgent",
|
||||
"stop": "AfterAgent",
|
||||
}
|
||||
events_config_file = ".tabnine/agent/settings.json"
|
||||
events_format = "json-nested"
|
||||
# Tabnine mirrors Gemini's hook schema (BeforeTool/AfterTool) and, like
|
||||
# Gemini, measures hook timeouts in milliseconds. Declaring the unit makes
|
||||
# the shared formatter convert the 60s default to 60000ms instead of
|
||||
# emitting timeout: 60 (60 ms), which would terminate the dispatcher
|
||||
# before it starts (R5).
|
||||
events_timeout_unit = "ms"
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -19,6 +19,7 @@ from .._console import console
|
||||
from .._download_security import (
|
||||
is_https_or_localhost_http,
|
||||
is_safe_download_redirect,
|
||||
read_response_limited,
|
||||
)
|
||||
|
||||
preset_app = typer.Typer(
|
||||
@@ -58,10 +59,14 @@ def preset_list():
|
||||
for pack in installed:
|
||||
status = "[green]enabled[/green]" if pack.get("enabled", True) else "[red]disabled[/red]"
|
||||
pri = pack.get('priority', 10)
|
||||
console.print(f" [bold]{pack['name']}[/bold] ({pack['id']}) v{pack['version']} — {status} — priority {pri}")
|
||||
console.print(f" {pack['description']}")
|
||||
if pack.get("tags"):
|
||||
tags_str = ", ".join(pack["tags"])
|
||||
name = _escape_markup(str(pack['name']))
|
||||
pack_id = _escape_markup(str(pack['id']))
|
||||
version = _escape_markup(str(pack['version']))
|
||||
console.print(f" [bold]{name}[/bold] ({pack_id}) v{version} — {status} — priority {pri}")
|
||||
console.print(f" {_escape_markup(str(pack['description']))}")
|
||||
tags = pack.get("tags", [])
|
||||
if isinstance(tags, list) and tags:
|
||||
tags_str = _escape_markup(", ".join(str(t) for t in tags))
|
||||
console.print(f" [dim]Tags: {tags_str}[/dim]")
|
||||
console.print(f" [dim]Templates: {pack['template_count']}[/dim]")
|
||||
console.print()
|
||||
@@ -126,15 +131,15 @@ def preset_add(
|
||||
|
||||
if not is_https_or_localhost_http(from_url):
|
||||
console.print(
|
||||
"[red]Error:[/red] URL must use HTTPS with a hostname, "
|
||||
"or HTTP for localhost/loopback."
|
||||
"[red]Error:[/red] URL must use HTTPS with a hostname and be "
|
||||
"a valid URL with a host. HTTP is only allowed for localhost, "
|
||||
"127.0.0.1, and ::1."
|
||||
)
|
||||
raise typer.Exit(1)
|
||||
|
||||
console.print(f"Installing preset from [cyan]{_escape_markup(from_url)}[/cyan]...")
|
||||
import urllib.error
|
||||
import tempfile
|
||||
import shutil
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
zip_path = Path(tmpdir) / "preset.zip"
|
||||
@@ -162,16 +167,21 @@ def preset_add(
|
||||
console.print(
|
||||
"[red]Error:[/red] Preset URL redirected to a disallowed URL: "
|
||||
f"{final_url}. Redirect targets must use HTTPS with a hostname, "
|
||||
"or HTTP for localhost/loopback."
|
||||
"or HTTP for localhost (127.0.0.1, ::1)."
|
||||
)
|
||||
raise typer.Exit(1)
|
||||
with zip_path.open("wb") as output:
|
||||
try:
|
||||
shutil.copyfileobj(response, output)
|
||||
except TypeError:
|
||||
output.write(response.read())
|
||||
except urllib.error.URLError as e:
|
||||
console.print(f"[red]Error:[/red] Failed to download: {_escape_markup(str(e))}")
|
||||
zip_path.write_bytes(
|
||||
read_response_limited(
|
||||
response,
|
||||
error_type=PresetError,
|
||||
label=f"preset {from_url}",
|
||||
)
|
||||
)
|
||||
except (urllib.error.URLError, PresetError) as e:
|
||||
console.print(
|
||||
f"[red]Error:[/red] Failed to download: "
|
||||
f"{_escape_markup(str(e))}"
|
||||
)
|
||||
raise typer.Exit(1)
|
||||
|
||||
manifest = manager.install_from_zip(zip_path, speckit_version, priority)
|
||||
@@ -285,10 +295,16 @@ def preset_search(
|
||||
|
||||
console.print(f"\n[bold cyan]Presets ({len(results)} found):[/bold cyan]\n")
|
||||
for pack in results:
|
||||
console.print(f" [bold]{pack.get('name', pack['id'])}[/bold] ({pack['id']}) v{pack.get('version', '?')}")
|
||||
console.print(f" {pack.get('description', '')}")
|
||||
if pack.get("tags"):
|
||||
tags_str = ", ".join(pack["tags"])
|
||||
name = _escape_markup(str(pack.get("name", pack["id"])))
|
||||
pack_id = _escape_markup(str(pack["id"]))
|
||||
version = _escape_markup(str(pack.get("version", "?")))
|
||||
console.print(f" [bold]{name}[/bold] ({pack_id}) v{version}")
|
||||
console.print(
|
||||
f" {_escape_markup(str(pack.get('description', '')))}"
|
||||
)
|
||||
tags = pack.get("tags", [])
|
||||
if isinstance(tags, list) and tags:
|
||||
tags_str = _escape_markup(", ".join(str(t) for t in tags))
|
||||
console.print(f" [dim]Tags: {tags_str}[/dim]")
|
||||
console.print()
|
||||
|
||||
@@ -304,13 +320,20 @@ def preset_resolve(
|
||||
project_root = _require_specify_project()
|
||||
resolver = PresetResolver(project_root)
|
||||
layers = resolver.collect_all_layers(template_name)
|
||||
safe_template_name = _escape_markup(str(template_name))
|
||||
|
||||
if layers:
|
||||
# Use the highest-priority layer for display because the final output
|
||||
# may be composed and may not map to resolve_with_source()'s single path.
|
||||
display_layer = layers[0]
|
||||
console.print(f" [bold]{template_name}[/bold]: {display_layer['path']}")
|
||||
console.print(f" [dim](top layer from: {display_layer['source']})[/dim]")
|
||||
console.print(
|
||||
f" [bold]{safe_template_name}[/bold]: "
|
||||
f"{_escape_markup(str(display_layer['path']))}"
|
||||
)
|
||||
console.print(
|
||||
f" [dim](top layer from: "
|
||||
f"{_escape_markup(str(display_layer['source']))})[/dim]"
|
||||
)
|
||||
|
||||
has_composition = (
|
||||
layers[0]["strategy"] != "replace"
|
||||
@@ -322,7 +345,10 @@ def preset_resolve(
|
||||
composed = resolver.resolve_content(template_name)
|
||||
except Exception as exc:
|
||||
composed = None
|
||||
console.print(f" [yellow]Warning: composition error: {exc}[/yellow]")
|
||||
console.print(
|
||||
f" [yellow]Warning: composition error: "
|
||||
f"{_escape_markup(str(exc))}[/yellow]"
|
||||
)
|
||||
if composed is None:
|
||||
console.print(" [yellow]Warning: composition cannot produce output (no base layer with 'replace' strategy)[/yellow]")
|
||||
else:
|
||||
@@ -345,15 +371,27 @@ def preset_resolve(
|
||||
strategy_label = layer["strategy"]
|
||||
if strategy_label == "replace" and i == 0:
|
||||
strategy_label = "base"
|
||||
console.print(f" {i + 1}. [{strategy_label}] {layer['source']} → {layer['path']}")
|
||||
# Escape the literal bracket (\[) so Rich renders `[<strategy>]`
|
||||
# instead of parsing it as a style tag and swallowing the label,
|
||||
# mirroring `workflow info`'s step-graph line.
|
||||
console.print(
|
||||
f" {i + 1}. \\[{_escape_markup(str(strategy_label))}] "
|
||||
f"{_escape_markup(str(layer['source']))} → "
|
||||
f"{_escape_markup(str(layer['path']))}"
|
||||
)
|
||||
else:
|
||||
# No layers found — fall back to resolve_with_source for non-composition cases
|
||||
result = resolver.resolve_with_source(template_name)
|
||||
if result:
|
||||
console.print(f" [bold]{template_name}[/bold]: {result['path']}")
|
||||
console.print(f" [dim](from: {result['source']})[/dim]")
|
||||
console.print(
|
||||
f" [bold]{safe_template_name}[/bold]: "
|
||||
f"{_escape_markup(str(result['path']))}"
|
||||
)
|
||||
console.print(
|
||||
f" [dim](from: {_escape_markup(str(result['source']))})[/dim]"
|
||||
)
|
||||
else:
|
||||
console.print(f" [yellow]{template_name}[/yellow]: not found")
|
||||
console.print(f" [yellow]{safe_template_name}[/yellow]: not found")
|
||||
console.print(" [dim]No template with this name exists in the resolution stack[/dim]")
|
||||
|
||||
|
||||
@@ -367,28 +405,38 @@ def preset_info(
|
||||
from . import PresetCatalog, PresetManager, PresetError
|
||||
|
||||
project_root = _require_specify_project()
|
||||
safe_preset_id = _escape_markup(str(preset_id))
|
||||
# Check if installed locally first
|
||||
manager = PresetManager(project_root)
|
||||
local_pack = manager.get_pack(preset_id)
|
||||
|
||||
if local_pack:
|
||||
console.print(f"\n[bold cyan]Preset: {local_pack.name}[/bold cyan]\n")
|
||||
console.print(f" ID: {local_pack.id}")
|
||||
console.print(f" Version: {local_pack.version}")
|
||||
console.print(f" Description: {local_pack.description}")
|
||||
console.print(
|
||||
f"\n[bold cyan]Preset: {_escape_markup(str(local_pack.name))}[/bold cyan]\n"
|
||||
)
|
||||
console.print(f" ID: {_escape_markup(str(local_pack.id))}")
|
||||
console.print(f" Version: {_escape_markup(str(local_pack.version))}")
|
||||
console.print(
|
||||
f" Description: {_escape_markup(str(local_pack.description))}"
|
||||
)
|
||||
if local_pack.author:
|
||||
console.print(f" Author: {local_pack.author}")
|
||||
if local_pack.tags:
|
||||
console.print(f" Tags: {', '.join(local_pack.tags)}")
|
||||
console.print(f" Author: {_escape_markup(str(local_pack.author))}")
|
||||
local_tags = local_pack.tags
|
||||
if isinstance(local_tags, list) and local_tags:
|
||||
tags_str = _escape_markup(", ".join(str(t) for t in local_tags))
|
||||
console.print(f" Tags: {tags_str}")
|
||||
console.print(f" Templates: {len(local_pack.templates)}")
|
||||
for tmpl in local_pack.templates:
|
||||
console.print(f" - {tmpl['name']} ({tmpl['type']}): {tmpl.get('description', '')}")
|
||||
tmpl_name = _escape_markup(str(tmpl['name']))
|
||||
tmpl_type = _escape_markup(str(tmpl['type']))
|
||||
tmpl_desc = _escape_markup(str(tmpl.get('description', '')))
|
||||
console.print(f" - {tmpl_name} ({tmpl_type}): {tmpl_desc}")
|
||||
repo = local_pack.data.get("preset", {}).get("repository")
|
||||
if repo:
|
||||
console.print(f" Repository: {repo}")
|
||||
console.print(f" Repository: {_escape_markup(str(repo))}")
|
||||
license_val = local_pack.data.get("preset", {}).get("license")
|
||||
if license_val:
|
||||
console.print(f" License: {license_val}")
|
||||
console.print(f" License: {_escape_markup(str(license_val))}")
|
||||
console.print("\n [green]Status: installed[/green]")
|
||||
# Get priority from registry
|
||||
pack_metadata = manager.registry.get(preset_id)
|
||||
@@ -408,20 +456,33 @@ def preset_info(
|
||||
console.print(f"[red]Error:[/red] Preset '{preset_id}' not found (not installed and not in catalog)")
|
||||
raise typer.Exit(1)
|
||||
|
||||
console.print(f"\n[bold cyan]Preset: {pack_info.get('name', preset_id)}[/bold cyan]\n")
|
||||
console.print(f" ID: {pack_info['id']}")
|
||||
console.print(f" Version: {pack_info.get('version', '?')}")
|
||||
console.print(f" Description: {pack_info.get('description', '')}")
|
||||
name = _escape_markup(str(pack_info.get("name", preset_id)))
|
||||
console.print(f"\n[bold cyan]Preset: {name}[/bold cyan]\n")
|
||||
console.print(f" ID: {_escape_markup(str(pack_info['id']))}")
|
||||
console.print(
|
||||
f" Version: {_escape_markup(str(pack_info.get('version', '?')))}"
|
||||
)
|
||||
console.print(
|
||||
f" Description: {_escape_markup(str(pack_info.get('description', '')))}"
|
||||
)
|
||||
if pack_info.get("author"):
|
||||
console.print(f" Author: {pack_info['author']}")
|
||||
if pack_info.get("tags"):
|
||||
console.print(f" Tags: {', '.join(pack_info['tags'])}")
|
||||
console.print(
|
||||
f" Author: {_escape_markup(str(pack_info['author']))}"
|
||||
)
|
||||
catalog_tags = pack_info.get("tags", [])
|
||||
if isinstance(catalog_tags, list) and catalog_tags:
|
||||
catalog_tags_str = _escape_markup(", ".join(str(t) for t in catalog_tags))
|
||||
console.print(f" Tags: {catalog_tags_str}")
|
||||
if pack_info.get("repository"):
|
||||
console.print(f" Repository: {pack_info['repository']}")
|
||||
console.print(
|
||||
f" Repository: {_escape_markup(str(pack_info['repository']))}"
|
||||
)
|
||||
if pack_info.get("license"):
|
||||
console.print(f" License: {pack_info['license']}")
|
||||
console.print(
|
||||
f" License: {_escape_markup(str(pack_info['license']))}"
|
||||
)
|
||||
console.print("\n [yellow]Status: not installed[/yellow]")
|
||||
console.print(f" Install with: [cyan]specify preset add {preset_id}[/cyan]")
|
||||
console.print(f" Install with: [cyan]specify preset add {safe_preset_id}[/cyan]")
|
||||
console.print()
|
||||
|
||||
|
||||
@@ -580,10 +641,10 @@ def preset_catalog_list():
|
||||
if entry.install_allowed
|
||||
else "[yellow]discovery only[/yellow]"
|
||||
)
|
||||
console.print(f" [bold]{entry.name}[/bold] (priority {entry.priority})")
|
||||
console.print(f" [bold]{_escape_markup(str(entry.name))}[/bold] (priority {entry.priority})")
|
||||
if entry.description:
|
||||
console.print(f" {entry.description}")
|
||||
console.print(f" URL: {entry.url}")
|
||||
console.print(f" {_escape_markup(str(entry.description))}")
|
||||
console.print(f" URL: {_escape_markup(str(entry.url))}")
|
||||
console.print(f" Install: {install_str}")
|
||||
console.print()
|
||||
|
||||
@@ -656,10 +717,15 @@ def preset_catalog_add(
|
||||
console.print("[red]Error:[/red] Invalid catalog config: 'catalogs' must be a list.")
|
||||
raise typer.Exit(1)
|
||||
|
||||
# Only rendering is escaped — the raw values are what get persisted and
|
||||
# compared below, so a name containing markup still round-trips exactly.
|
||||
safe_name = _escape_markup(str(name))
|
||||
safe_url = _escape_markup(str(url))
|
||||
|
||||
# Check for duplicate name
|
||||
for existing in catalogs:
|
||||
if isinstance(existing, dict) and existing.get("name") == name:
|
||||
console.print(f"[yellow]Warning:[/yellow] A catalog named '{name}' already exists.")
|
||||
console.print(f"[yellow]Warning:[/yellow] A catalog named '{safe_name}' already exists.")
|
||||
console.print("Use 'specify preset catalog remove' first, or choose a different name.")
|
||||
raise typer.Exit(1)
|
||||
|
||||
@@ -675,10 +741,11 @@ def preset_catalog_add(
|
||||
config_path.write_text(yaml.safe_dump(config, default_flow_style=False, sort_keys=False, allow_unicode=True), encoding="utf-8")
|
||||
|
||||
install_label = "install allowed" if install_allowed else "discovery only"
|
||||
console.print(f"\n[green]✓[/green] Added catalog '[bold]{name}[/bold]' ({install_label})")
|
||||
console.print(f" URL: {url}")
|
||||
console.print(f"\n[green]✓[/green] Added catalog '[bold]{safe_name}[/bold]' ({install_label})")
|
||||
console.print(f" URL: {safe_url}")
|
||||
console.print(f" Priority: {priority}")
|
||||
console.print(f"\nConfig saved to {_display_project_path(project_root, config_path)}")
|
||||
config_label = _escape_markup(str(_display_project_path(project_root, config_path)))
|
||||
console.print(f"\nConfig saved to {config_label}")
|
||||
|
||||
|
||||
@preset_catalog_app.command("remove")
|
||||
@@ -706,17 +773,20 @@ def preset_catalog_remove(
|
||||
if not isinstance(catalogs, list):
|
||||
console.print("[red]Error:[/red] Invalid catalog config: 'catalogs' must be a list.")
|
||||
raise typer.Exit(1)
|
||||
# Rendering only — the raw name drives the comparison below.
|
||||
safe_name = _escape_markup(str(name))
|
||||
|
||||
original_count = len(catalogs)
|
||||
catalogs = [c for c in catalogs if isinstance(c, dict) and c.get("name") != name]
|
||||
|
||||
if len(catalogs) == original_count:
|
||||
console.print(f"[red]Error:[/red] Catalog '{name}' not found.")
|
||||
console.print(f"[red]Error:[/red] Catalog '{safe_name}' not found.")
|
||||
raise typer.Exit(1)
|
||||
|
||||
config["catalogs"] = catalogs
|
||||
config_path.write_text(yaml.safe_dump(config, default_flow_style=False, sort_keys=False, allow_unicode=True), encoding="utf-8")
|
||||
|
||||
console.print(f"[green]✓[/green] Removed catalog '{name}'")
|
||||
console.print(f"[green]✓[/green] Removed catalog '{safe_name}'")
|
||||
if not catalogs:
|
||||
console.print("\n[dim]No catalogs remain in config. Built-in defaults will be used.[/dim]")
|
||||
|
||||
|
||||
@@ -272,27 +272,56 @@ _BASH_FORMAT_COMMAND_RE = re.compile(
|
||||
_POWERSHELL_FORMAT_COMMAND_RE = re.compile(
|
||||
r"Format-SpecKitCommand\s+-CommandName\s+(['\"])([A-Za-z0-9_.-]+)\1(?:\s+-RepoRoot\s+[^\r\n]+)?"
|
||||
)
|
||||
_PYTHON_FORMAT_COMMAND_RETURN_RE = re.compile(
|
||||
r'return f"/speckit\{separator\}\{name\}"'
|
||||
)
|
||||
_BASH_FORMATTER_RETURN_RE = re.compile(
|
||||
r'''printf '/speckit%s%s\\n' "\$separator" "\$command_name"'''
|
||||
)
|
||||
_POWERSHELL_FORMATTER_RETURN_RE = re.compile(
|
||||
r'return "/speckit\$separator\$name"'
|
||||
)
|
||||
|
||||
|
||||
def _format_speckit_command(command_name: str, separator: str) -> str:
|
||||
def _format_speckit_command(
|
||||
command_name: str, separator: str, prefix: str = "/"
|
||||
) -> str:
|
||||
name = command_name.strip().lstrip("/")
|
||||
if name.startswith("speckit."):
|
||||
name = name[len("speckit.") :]
|
||||
elif name.startswith("speckit-"):
|
||||
name = name[len("speckit-") :]
|
||||
name = name.replace(".", separator)
|
||||
return f"/speckit{separator}{name}"
|
||||
return f"{prefix}speckit{separator}{name}"
|
||||
|
||||
|
||||
def _resolve_dynamic_command_refs(content: str, separator: str) -> str:
|
||||
def _resolve_dynamic_command_refs(
|
||||
content: str, separator: str, prefix: str = "/"
|
||||
) -> str:
|
||||
"""Render script runtime command helpers for managed shared infra copies."""
|
||||
|
||||
bash_prefix = r"\$" if prefix == "$" else prefix
|
||||
content = _BASH_FORMAT_COMMAND_RE.sub(
|
||||
lambda match: _format_speckit_command(match.group(2), separator),
|
||||
lambda match: _format_speckit_command(
|
||||
match.group(2), separator, bash_prefix
|
||||
),
|
||||
content,
|
||||
)
|
||||
return _POWERSHELL_FORMAT_COMMAND_RE.sub(
|
||||
lambda match: f"'{_format_speckit_command(match.group(2), separator)}'",
|
||||
content = _POWERSHELL_FORMAT_COMMAND_RE.sub(
|
||||
lambda match: f"'{_format_speckit_command(match.group(2), separator, prefix)}'",
|
||||
content,
|
||||
)
|
||||
content = _BASH_FORMATTER_RETURN_RE.sub(
|
||||
f'''printf '{prefix}speckit%s%s\\\\n' "$separator" "$command_name"''',
|
||||
content,
|
||||
)
|
||||
powershell_prefix = "`$" if prefix == "$" else prefix
|
||||
content = _POWERSHELL_FORMATTER_RETURN_RE.sub(
|
||||
f'return "{powershell_prefix}speckit$separator$name"',
|
||||
content,
|
||||
)
|
||||
return _PYTHON_FORMAT_COMMAND_RETURN_RE.sub(
|
||||
f'return f"{prefix}speckit{{separator}}{{name}}"',
|
||||
content,
|
||||
)
|
||||
|
||||
@@ -305,6 +334,7 @@ def refresh_shared_templates(
|
||||
repo_root: Path,
|
||||
console: Any,
|
||||
invoke_separator: str,
|
||||
invoke_prefix: str = "/",
|
||||
force: bool = False,
|
||||
) -> None:
|
||||
"""Refresh default-sensitive shared templates without touching scripts."""
|
||||
@@ -336,7 +366,9 @@ def refresh_shared_templates(
|
||||
continue
|
||||
|
||||
content = src.read_text(encoding="utf-8")
|
||||
content = IntegrationBase.resolve_command_refs(content, invoke_separator)
|
||||
content = IntegrationBase.resolve_command_refs(
|
||||
content, invoke_separator, invoke_prefix
|
||||
)
|
||||
planned_updates.append((dst, rel, content))
|
||||
|
||||
for dst, rel, content in planned_updates:
|
||||
@@ -363,6 +395,7 @@ def install_shared_infra(
|
||||
console: Any,
|
||||
force: bool = False,
|
||||
invoke_separator: str = ".",
|
||||
invoke_prefix: str = "/",
|
||||
refresh_managed: bool = False,
|
||||
refresh_hint: str | None = None,
|
||||
) -> bool:
|
||||
@@ -516,8 +549,12 @@ def install_shared_infra(
|
||||
if not _ensure_or_bucket_dir(dst_path.parent):
|
||||
continue
|
||||
content = src_path.read_text(encoding="utf-8")
|
||||
content = IntegrationBase.resolve_command_refs(content, invoke_separator)
|
||||
content = _resolve_dynamic_command_refs(content, invoke_separator)
|
||||
content = IntegrationBase.resolve_command_refs(
|
||||
content, invoke_separator, invoke_prefix
|
||||
)
|
||||
content = _resolve_dynamic_command_refs(
|
||||
content, invoke_separator, invoke_prefix
|
||||
)
|
||||
planned_copies.append(
|
||||
(
|
||||
dst_path,
|
||||
@@ -566,7 +603,9 @@ def install_shared_infra(
|
||||
continue
|
||||
|
||||
content = src.read_text(encoding="utf-8")
|
||||
content = IntegrationBase.resolve_command_refs(content, invoke_separator)
|
||||
content = IntegrationBase.resolve_command_refs(
|
||||
content, invoke_separator, invoke_prefix
|
||||
)
|
||||
planned_templates.append((dst, rel, content))
|
||||
|
||||
for dst_path, rel, content, mode in planned_copies:
|
||||
|
||||
@@ -12,7 +12,7 @@ import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from pathlib import Path, PurePosixPath
|
||||
from typing import Any
|
||||
|
||||
import typer
|
||||
@@ -401,6 +401,12 @@ def _reject_insecure_download_redirect(old_url: str, new_url: str) -> None:
|
||||
# a ceiling any legitimate workflow definition should ever approach.
|
||||
_MAX_WORKFLOW_YAML_BYTES = 5 * 1024 * 1024 # 5 MiB
|
||||
_DOWNLOAD_CHUNK_SIZE = 65536
|
||||
# Custom step packages contain executable Python, metadata, and optional helper
|
||||
# files downloaded one-by-one rather than as an archive. Mirror the archive
|
||||
# ceilings so a catalog cannot turn individually valid files into an unbounded
|
||||
# aggregate download.
|
||||
_MAX_STEP_PACKAGE_FILES = 512
|
||||
_MAX_STEP_PACKAGE_BYTES = 50 * 1024 * 1024 # 50 MiB
|
||||
|
||||
|
||||
def _read_response_within_limit(response, max_bytes: int | None = None) -> bytes:
|
||||
@@ -1048,7 +1054,18 @@ def workflow_run(
|
||||
load_custom_steps(project_root)
|
||||
engine = WorkflowEngine(project_root)
|
||||
if not json_output:
|
||||
engine.on_step_start = lambda sid, label: console.print(f" \u25b8 [{sid}] {label} \u2026")
|
||||
# Escape the literal bracket (\[) so Rich renders `[<step id>]` instead
|
||||
# of parsing it as a style tag named after the step id -- which it
|
||||
# silently swallows (losing the only identifying content on the line),
|
||||
# applies as formatting when the id happens to be a real style such as
|
||||
# `bold`, or raises MarkupError when the id forms a closing tag (`/`),
|
||||
# failing the whole run. Escape the interpolated values too, since both
|
||||
# come from workflow YAML. Mirrors the `\[<type>]` step-graph precedent
|
||||
# in workflow_info below.
|
||||
engine.on_step_start = lambda sid, label: console.print(
|
||||
f" \u25b8 \\[{_escape_markup(str(sid))}] "
|
||||
f"{_escape_markup(str(label))} \u2026"
|
||||
)
|
||||
|
||||
err = _error_console(json_output)
|
||||
|
||||
@@ -1170,7 +1187,18 @@ def workflow_resume(
|
||||
load_custom_steps(project_root)
|
||||
engine = WorkflowEngine(project_root)
|
||||
if not json_output:
|
||||
engine.on_step_start = lambda sid, label: console.print(f" \u25b8 [{sid}] {label} \u2026")
|
||||
# Escape the literal bracket (\[) so Rich renders `[<step id>]` instead
|
||||
# of parsing it as a style tag named after the step id -- which it
|
||||
# silently swallows (losing the only identifying content on the line),
|
||||
# applies as formatting when the id happens to be a real style such as
|
||||
# `bold`, or raises MarkupError when the id forms a closing tag (`/`),
|
||||
# failing the whole run. Escape the interpolated values too, since both
|
||||
# come from workflow YAML. Mirrors the `\[<type>]` step-graph precedent
|
||||
# in workflow_info below.
|
||||
engine.on_step_start = lambda sid, label: console.print(
|
||||
f" \u25b8 \\[{_escape_markup(str(sid))}] "
|
||||
f"{_escape_markup(str(label))} \u2026"
|
||||
)
|
||||
|
||||
inputs = _parse_input_values(input_values, json_output=json_output)
|
||||
err = _error_console(json_output)
|
||||
@@ -2320,7 +2348,7 @@ def workflow_search(
|
||||
if desc:
|
||||
console.print(f" {_escape_markup(str(desc))}")
|
||||
tags = wf.get("tags", [])
|
||||
if tags:
|
||||
if isinstance(tags, list) and tags:
|
||||
safe_tags = _escape_markup(", ".join(str(t) for t in tags))
|
||||
console.print(f" [dim]Tags: {safe_tags}[/dim]")
|
||||
console.print()
|
||||
@@ -2354,14 +2382,25 @@ def workflow_info(
|
||||
raise typer.Exit(1)
|
||||
|
||||
if definition:
|
||||
console.print(f"\n[bold cyan]{definition.name}[/bold cyan] ({definition.id})")
|
||||
console.print(f" Version: {definition.version}")
|
||||
# Escape every user-controlled field: workflow.yml values (name,
|
||||
# version, author, description, integration, input names/types) are not
|
||||
# trusted, and console.print has Rich markup enabled, so an unescaped
|
||||
# `[...]` in any of them is parsed as a style tag and silently swallowed
|
||||
# (same defect fixed for the step graph below; the sibling workflow_list
|
||||
# already escapes all of these).
|
||||
console.print(
|
||||
f"\n[bold cyan]{_escape_markup(str(definition.name))}[/bold cyan] "
|
||||
f"({_escape_markup(str(definition.id))})"
|
||||
)
|
||||
console.print(f" Version: {_escape_markup(str(definition.version))}")
|
||||
if definition.author:
|
||||
console.print(f" Author: {definition.author}")
|
||||
console.print(f" Author: {_escape_markup(str(definition.author))}")
|
||||
if definition.description:
|
||||
console.print(f" Description: {definition.description}")
|
||||
console.print(f" Description: {_escape_markup(str(definition.description))}")
|
||||
if definition.default_integration:
|
||||
console.print(f" Integration: {definition.default_integration}")
|
||||
console.print(
|
||||
f" Integration: {_escape_markup(str(definition.default_integration))}"
|
||||
)
|
||||
if installed:
|
||||
console.print(" [green]Installed[/green]")
|
||||
|
||||
@@ -2370,7 +2409,10 @@ def workflow_info(
|
||||
for name, inp in definition.inputs.items():
|
||||
if isinstance(inp, dict):
|
||||
req = "required" if inp.get("required") else "optional"
|
||||
console.print(f" {name} ({inp.get('type', 'string')}) — {req}")
|
||||
console.print(
|
||||
f" {_escape_markup(str(name))} "
|
||||
f"({_escape_markup(str(inp.get('type', 'string')))}) — {req}"
|
||||
)
|
||||
|
||||
if definition.steps:
|
||||
console.print(f"\n [bold]Steps ({len(definition.steps)}):[/bold]")
|
||||
@@ -2395,15 +2437,24 @@ def workflow_info(
|
||||
info = None
|
||||
|
||||
if info:
|
||||
console.print(f"\n[bold cyan]{info.get('name', workflow_id)}[/bold cyan] ({workflow_id})")
|
||||
console.print(f" Version: {info.get('version', '?')}")
|
||||
# Catalog-derived fields are untrusted; escape them so bracketed content
|
||||
# is rendered literally rather than parsed (and swallowed) as Rich markup.
|
||||
console.print(
|
||||
f"\n[bold cyan]{_escape_markup(str(info.get('name', workflow_id)))}[/bold cyan] "
|
||||
f"({_escape_markup(str(workflow_id))})"
|
||||
)
|
||||
console.print(f" Version: {_escape_markup(str(info.get('version', '?')))}")
|
||||
if info.get("description"):
|
||||
console.print(f" Description: {info['description']}")
|
||||
if info.get("tags"):
|
||||
console.print(f" Tags: {', '.join(info['tags'])}")
|
||||
console.print(f" Description: {_escape_markup(str(info['description']))}")
|
||||
info_tags = info.get("tags", [])
|
||||
if isinstance(info_tags, list) and info_tags:
|
||||
safe_tags = _escape_markup(", ".join(str(t) for t in info_tags))
|
||||
console.print(f" Tags: {safe_tags}")
|
||||
console.print(" [yellow]Not installed[/yellow]")
|
||||
else:
|
||||
console.print(f"[red]Error:[/red] Workflow '{workflow_id}' not found")
|
||||
console.print(
|
||||
f"[red]Error:[/red] Workflow '{_escape_markup(str(workflow_id))}' not found"
|
||||
)
|
||||
raise typer.Exit(1)
|
||||
|
||||
|
||||
@@ -2424,10 +2475,10 @@ def workflow_catalog_list():
|
||||
console.print("\n[bold cyan]Workflow Catalog Sources:[/bold cyan]\n")
|
||||
for i, cfg in enumerate(configs):
|
||||
install_status = "[green]install allowed[/green]" if cfg["install_allowed"] else "[yellow]discovery only[/yellow]"
|
||||
console.print(f" [{i}] [bold]{cfg['name']}[/bold] — {install_status}")
|
||||
console.print(f" {cfg['url']}")
|
||||
console.print(f" [{i}] [bold]{_escape_markup(str(cfg['name']))}[/bold] — {install_status}")
|
||||
console.print(f" {_escape_markup(str(cfg['url']))}")
|
||||
if cfg.get("description"):
|
||||
console.print(f" [dim]{cfg['description']}[/dim]")
|
||||
console.print(f" [dim]{_escape_markup(str(cfg['description']))}[/dim]")
|
||||
console.print()
|
||||
|
||||
|
||||
@@ -2636,14 +2687,39 @@ def workflow_step_add(
|
||||
)
|
||||
raise typer.Exit(1)
|
||||
|
||||
step_yml_url = info.get("step_yml_url") or info.get("url")
|
||||
if not step_yml_url:
|
||||
declared_step_yml_url = info.get("step_yml_url")
|
||||
if declared_step_yml_url is not None and not isinstance(
|
||||
declared_step_yml_url, str
|
||||
):
|
||||
console.print(
|
||||
f"[red]Error:[/red] Catalog entry for '{step_id}' has a malformed "
|
||||
"step.yml URL; expected a non-empty string"
|
||||
)
|
||||
raise typer.Exit(1)
|
||||
step_yml_url = declared_step_yml_url or info.get("url")
|
||||
if step_yml_url is None or (
|
||||
isinstance(step_yml_url, str) and not step_yml_url.strip()
|
||||
):
|
||||
console.print(f"[red]Error:[/red] Catalog entry for '{step_id}' has no URL")
|
||||
raise typer.Exit(1)
|
||||
if not isinstance(step_yml_url, str):
|
||||
console.print(
|
||||
f"[red]Error:[/red] Catalog entry for '{step_id}' has a malformed "
|
||||
"step.yml URL; expected a non-empty string"
|
||||
)
|
||||
raise typer.Exit(1)
|
||||
|
||||
# Derive __init__.py URL: replace trailing step.yml with __init__.py
|
||||
# or use explicit init_url if provided.
|
||||
init_url = info.get("init_url")
|
||||
if init_url is not None and (
|
||||
not isinstance(init_url, str) or not init_url.strip()
|
||||
):
|
||||
console.print(
|
||||
f"[red]Error:[/red] Catalog entry for '{step_id}' has a malformed "
|
||||
"__init__.py URL; expected a non-empty string"
|
||||
)
|
||||
raise typer.Exit(1)
|
||||
if not init_url:
|
||||
if step_yml_url.endswith("step.yml"):
|
||||
init_url = step_yml_url[: -len("step.yml")] + "__init__.py"
|
||||
@@ -2654,6 +2730,41 @@ def workflow_step_add(
|
||||
)
|
||||
raise typer.Exit(1)
|
||||
|
||||
# Preflight the declared file count before creating a staging directory or
|
||||
# issuing any request. The two required files are always part of the package;
|
||||
# duplicate declarations for them in extra_files are ignored below and do
|
||||
# not count twice.
|
||||
extra_files = info.get("extra_files")
|
||||
if extra_files is not None and not isinstance(extra_files, dict):
|
||||
console.print(
|
||||
"[yellow]Warning:[/yellow] Catalog entry 'extra_files' is not a mapping; "
|
||||
"additional package files will not be downloaded."
|
||||
)
|
||||
extra_files = {}
|
||||
|
||||
def _is_required_package_file(rel_path: object) -> bool:
|
||||
"""Match portable path/case aliases of the two required package files."""
|
||||
if not isinstance(rel_path, str):
|
||||
return False
|
||||
parts = PurePosixPath(rel_path.replace("\\", "/")).parts
|
||||
return len(parts) == 1 and parts[0].casefold() in {
|
||||
"step.yml",
|
||||
"__init__.py",
|
||||
}
|
||||
|
||||
declared_extra_count = sum(
|
||||
1
|
||||
for rel_path in (extra_files or {})
|
||||
if not _is_required_package_file(rel_path)
|
||||
)
|
||||
package_file_count = 2 + declared_extra_count
|
||||
if package_file_count > _MAX_STEP_PACKAGE_FILES:
|
||||
console.print(
|
||||
f"[red]Error:[/red] Step package declares {package_file_count} files, "
|
||||
f"exceeding the {_MAX_STEP_PACKAGE_FILES}-file limit"
|
||||
)
|
||||
raise typer.Exit(1)
|
||||
|
||||
from specify_cli.authentication.http import open_url as _open_url
|
||||
|
||||
def _safe_fetch(url: str) -> bytes:
|
||||
@@ -2710,6 +2821,14 @@ def workflow_step_add(
|
||||
console.print(f"[red]Error:[/red] Failed to download step files: {exc}")
|
||||
raise typer.Exit(1)
|
||||
|
||||
package_bytes = len(step_yml_content) + len(init_py_content)
|
||||
if package_bytes > _MAX_STEP_PACKAGE_BYTES:
|
||||
console.print(
|
||||
f"[red]Error:[/red] Step package exceeds the "
|
||||
f"{_MAX_STEP_PACKAGE_BYTES}-byte total size limit"
|
||||
)
|
||||
raise typer.Exit(1)
|
||||
|
||||
# Validate step.yml
|
||||
try:
|
||||
import yaml as _yaml
|
||||
@@ -2754,13 +2873,6 @@ def workflow_step_add(
|
||||
# relative-path → URL. step.yml and __init__.py are ignored here (already
|
||||
# written). Paths are validated to stay within the step package directory to
|
||||
# prevent path-traversal attacks.
|
||||
extra_files = info.get("extra_files")
|
||||
if extra_files is not None and not isinstance(extra_files, dict):
|
||||
console.print(
|
||||
"[yellow]Warning:[/yellow] Catalog entry 'extra_files' is not a mapping; "
|
||||
"additional package files will not be downloaded."
|
||||
)
|
||||
extra_files = {}
|
||||
for rel_path, file_url in (extra_files or {}).items():
|
||||
if not isinstance(rel_path, str) or not rel_path.strip():
|
||||
console.print(
|
||||
@@ -2768,7 +2880,7 @@ def workflow_step_add(
|
||||
"empty or non-string path key"
|
||||
)
|
||||
raise typer.Exit(1)
|
||||
if rel_path in ("step.yml", "__init__.py"):
|
||||
if _is_required_package_file(rel_path):
|
||||
continue # already written above
|
||||
# Reject dot-path segments ('', '.', '..') that would refer to the
|
||||
# package directory itself (IsADirectoryError) or escape it.
|
||||
@@ -2804,6 +2916,13 @@ def workflow_step_add(
|
||||
f"[red]Error:[/red] Failed to download extra file '{rel_path}': {exc}"
|
||||
)
|
||||
raise typer.Exit(1)
|
||||
package_bytes += len(file_content)
|
||||
if package_bytes > _MAX_STEP_PACKAGE_BYTES:
|
||||
console.print(
|
||||
f"[red]Error:[/red] Step package exceeds the "
|
||||
f"{_MAX_STEP_PACKAGE_BYTES}-byte total size limit"
|
||||
)
|
||||
raise typer.Exit(1)
|
||||
try:
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
dest.write_bytes(file_content)
|
||||
@@ -3067,10 +3186,10 @@ def workflow_step_catalog_list():
|
||||
if cfg["install_allowed"]
|
||||
else "[yellow]discovery only[/yellow]"
|
||||
)
|
||||
console.print(f" [{i}] [bold]{cfg['name']}[/bold] — {install_status}")
|
||||
console.print(f" {cfg['url']}")
|
||||
console.print(f" [{i}] [bold]{_escape_markup(str(cfg['name']))}[/bold] — {install_status}")
|
||||
console.print(f" {_escape_markup(str(cfg['url']))}")
|
||||
if cfg.get("description"):
|
||||
console.print(f" [dim]{cfg['description']}[/dim]")
|
||||
console.print(f" [dim]{_escape_markup(str(cfg['description']))}[/dim]")
|
||||
console.print()
|
||||
|
||||
|
||||
|
||||
@@ -22,6 +22,8 @@ from typing import Any
|
||||
|
||||
import yaml
|
||||
|
||||
from .._download_security import MAX_JSON_CATALOG_BYTES, read_response_limited
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Errors
|
||||
@@ -308,7 +310,8 @@ class WorkflowCatalog:
|
||||
try:
|
||||
parsed = urlparse(url)
|
||||
hostname = parsed.hostname
|
||||
except ValueError:
|
||||
_ = parsed.port
|
||||
except (TypeError, ValueError):
|
||||
raise WorkflowValidationError(
|
||||
f"Catalog URL is malformed: {url}"
|
||||
) from None
|
||||
@@ -332,26 +335,45 @@ class WorkflowCatalog:
|
||||
if not config_path.exists():
|
||||
return None
|
||||
try:
|
||||
data = yaml.safe_load(config_path.read_text(encoding="utf-8")) or {}
|
||||
data = yaml.safe_load(config_path.read_text(encoding="utf-8"))
|
||||
except (yaml.YAMLError, OSError, UnicodeError) as exc:
|
||||
raise WorkflowValidationError(
|
||||
f"Failed to read catalog config {config_path}: {exc}"
|
||||
) from exc
|
||||
# An empty document (or explicit ``null``) parses to None -> this config
|
||||
# layer contributes nothing, so ``get_active_catalogs`` moves on to the
|
||||
# next layer (this loader serves both the project and user configs;
|
||||
# the built-in defaults apply only once every layer has returned None).
|
||||
# Do NOT coerce with ``or {}`` here: that also turns a FALSY non-mapping
|
||||
# (top-level ``[]``, ``false``, ``0``, ``''``) into ``{}`` and silently
|
||||
# swallows it, while a TRUTHY non-mapping (``5``, a bare list) correctly
|
||||
# raises below -- an inconsistency. Only None means "no document".
|
||||
if data is None:
|
||||
return None
|
||||
if not isinstance(data, dict):
|
||||
raise WorkflowValidationError(
|
||||
f"Invalid catalog config: expected a mapping, "
|
||||
f"got {type(data).__name__}"
|
||||
)
|
||||
catalogs_data = data.get("catalogs", [])
|
||||
if not catalogs_data:
|
||||
# Empty catalogs list (e.g. after removing last entry)
|
||||
# is valid — fall back to built-in defaults.
|
||||
# Same asymmetry as the top level above, one nesting level down: the
|
||||
# shape check has to run BEFORE the emptiness check, or a FALSY non-list
|
||||
# (``catalogs: {}``/``''``/``0``/``false``) is silently swallowed as
|
||||
# "no catalogs" while a TRUTHY non-list (``catalogs: 5``) correctly
|
||||
# raises. An absent key, an explicit ``catalogs:`` null, and an empty
|
||||
# list all keep their existing "nothing configured here" behavior --
|
||||
# only the misreported shapes change.
|
||||
catalogs_data = data.get("catalogs")
|
||||
if catalogs_data is None:
|
||||
return None
|
||||
if not isinstance(catalogs_data, list):
|
||||
raise WorkflowValidationError(
|
||||
f"Invalid catalog config: 'catalogs' must be a list, "
|
||||
f"got {type(catalogs_data).__name__}"
|
||||
)
|
||||
if not catalogs_data:
|
||||
# Empty catalogs list (e.g. after removing last entry)
|
||||
# is valid — fall back to built-in defaults.
|
||||
return None
|
||||
|
||||
entries: list[WorkflowCatalogEntry] = []
|
||||
for idx, item in enumerate(catalogs_data):
|
||||
@@ -505,7 +527,8 @@ class WorkflowCatalog:
|
||||
try:
|
||||
parsed = urlparse(url)
|
||||
hostname = parsed.hostname
|
||||
except ValueError:
|
||||
_ = parsed.port
|
||||
except (TypeError, ValueError):
|
||||
raise WorkflowCatalogError(
|
||||
f"Refusing to fetch catalog from malformed URL: {url}"
|
||||
) from None
|
||||
@@ -538,7 +561,14 @@ class WorkflowCatalog:
|
||||
entry.url, timeout=30, redirect_validator=_validate_redirect
|
||||
) as resp:
|
||||
_validate_catalog_url(resp.geturl())
|
||||
data = json.loads(resp.read().decode("utf-8"))
|
||||
data = json.loads(
|
||||
read_response_limited(
|
||||
resp,
|
||||
max_bytes=MAX_JSON_CATALOG_BYTES,
|
||||
error_type=WorkflowCatalogError,
|
||||
label="workflow catalog",
|
||||
).decode("utf-8")
|
||||
)
|
||||
except Exception as exc:
|
||||
# Fall back to cache if available
|
||||
if cache_file.exists():
|
||||
@@ -982,7 +1012,8 @@ class StepCatalog:
|
||||
try:
|
||||
parsed = urlparse(url)
|
||||
hostname = parsed.hostname
|
||||
except ValueError:
|
||||
_ = parsed.port
|
||||
except (TypeError, ValueError):
|
||||
raise StepValidationError(
|
||||
f"Catalog URL is malformed: {url}"
|
||||
) from None
|
||||
@@ -1006,24 +1037,33 @@ class StepCatalog:
|
||||
if not config_path.exists():
|
||||
return None
|
||||
try:
|
||||
data = yaml.safe_load(config_path.read_text(encoding="utf-8")) or {}
|
||||
data = yaml.safe_load(config_path.read_text(encoding="utf-8"))
|
||||
except (yaml.YAMLError, OSError, UnicodeError) as exc:
|
||||
raise StepValidationError(
|
||||
f"Failed to read catalog config {config_path}: {exc}"
|
||||
) from exc
|
||||
# Same two guards as WorkflowCatalog._load_catalog_config above, kept in
|
||||
# lockstep: this is the step-catalog twin of that loader and read the
|
||||
# same way. Dropping ``or {}`` stops a falsy non-mapping top level from
|
||||
# being coerced past the isinstance check, and the ``catalogs`` shape
|
||||
# check runs before the emptiness check for the same reason.
|
||||
if data is None:
|
||||
return None
|
||||
if not isinstance(data, dict):
|
||||
raise StepValidationError(
|
||||
f"Invalid catalog config: expected a mapping, "
|
||||
f"got {type(data).__name__}"
|
||||
)
|
||||
catalogs_data = data.get("catalogs", [])
|
||||
if not catalogs_data:
|
||||
catalogs_data = data.get("catalogs")
|
||||
if catalogs_data is None:
|
||||
return None
|
||||
if not isinstance(catalogs_data, list):
|
||||
raise StepValidationError(
|
||||
f"Invalid catalog config: 'catalogs' must be a list, "
|
||||
f"got {type(catalogs_data).__name__}"
|
||||
)
|
||||
if not catalogs_data:
|
||||
return None
|
||||
|
||||
entries: list[StepCatalogEntry] = []
|
||||
for idx, item in enumerate(catalogs_data):
|
||||
@@ -1178,7 +1218,8 @@ class StepCatalog:
|
||||
try:
|
||||
parsed = urlparse(url)
|
||||
hostname = parsed.hostname
|
||||
except ValueError:
|
||||
_ = parsed.port
|
||||
except (TypeError, ValueError):
|
||||
raise StepCatalogError(
|
||||
f"Refusing to fetch catalog from malformed URL: {url}"
|
||||
) from None
|
||||
@@ -1211,7 +1252,14 @@ class StepCatalog:
|
||||
entry.url, timeout=30, redirect_validator=_validate_redirect
|
||||
) as resp:
|
||||
_validate_url(resp.geturl())
|
||||
data = json.loads(resp.read().decode("utf-8"))
|
||||
data = json.loads(
|
||||
read_response_limited(
|
||||
resp,
|
||||
max_bytes=MAX_JSON_CATALOG_BYTES,
|
||||
error_type=StepCatalogError,
|
||||
label="step catalog",
|
||||
).decode("utf-8")
|
||||
)
|
||||
except Exception as exc:
|
||||
if cache_safe and cache_file.exists():
|
||||
try:
|
||||
|
||||
@@ -42,6 +42,17 @@ class WorkflowDefinition:
|
||||
self.source_path = source_path
|
||||
|
||||
workflow = data.get("workflow", {})
|
||||
# A present-but-non-mapping ``workflow:`` block (bare ``workflow:`` ->
|
||||
# None, or ``workflow: <str/list>``) would crash the following
|
||||
# ``workflow.get(...)`` calls with AttributeError, so construction fails
|
||||
# before any validation can run. Normalize the local to {} instead: the
|
||||
# header fields fall back to their defaults and ``validate_workflow``
|
||||
# (which reads those parsed attributes) reports the missing
|
||||
# ``workflow.id``/``workflow.name``. ``self.data`` is deliberately left
|
||||
# holding the raw value, since it is what gets written back out when a
|
||||
# definition is serialized. Mirrors the default_options guard below.
|
||||
if not isinstance(workflow, dict):
|
||||
workflow = {}
|
||||
self.id: str = workflow.get("id", "")
|
||||
self.name: str = workflow.get("name", "")
|
||||
self.version: str = workflow.get("version", "0.0.0")
|
||||
@@ -1400,6 +1411,14 @@ class WorkflowEngine:
|
||||
) -> dict[str, Any]:
|
||||
"""Resolve workflow inputs against definitions and provided values."""
|
||||
resolved: dict[str, Any] = {}
|
||||
# execute()/resume() accept UNVALIDATED definitions (load_workflow does
|
||||
# not validate). A non-mapping ``inputs:`` block (bare ``inputs:`` ->
|
||||
# None, or ``inputs: []``) is stored raw, so iterating ``.items()`` here
|
||||
# would crash the run with AttributeError. Treat a non-mapping inputs
|
||||
# block as "no inputs"; validate_workflow reports the malformed shape
|
||||
# via its own isinstance check.
|
||||
if not isinstance(definition.inputs, dict):
|
||||
return {}
|
||||
for name, input_def in definition.inputs.items():
|
||||
if not isinstance(input_def, dict):
|
||||
continue
|
||||
|
||||
@@ -70,6 +70,24 @@ class DoWhileStep(StepBase):
|
||||
f"Do-while step {config.get('id', '?')!r} is missing "
|
||||
f"'condition' field."
|
||||
)
|
||||
elif not isinstance(config["condition"], (str, bool)):
|
||||
# The engine re-evaluates 'condition' via evaluate_condition() after
|
||||
# each iteration. That call first delegates to
|
||||
# evaluate_expression() -- which returns a non-string unchanged --
|
||||
# and then coerces the result with bool(). So a list/dict/number
|
||||
# condition silently resolves to its truthiness (e.g.
|
||||
# condition: [1, 2] is always truthy, looping to max_iterations)
|
||||
# with no error. Reject those at validation, mirroring the
|
||||
# prompt/shell/command 'must be a string' checks.
|
||||
#
|
||||
# A literal ``bool`` stays valid: an unquoted ``condition: false``
|
||||
# is idiomatic YAML and evaluate_condition() already resolves it
|
||||
# exactly (bool passthrough, then a no-op bool()). "true"/"false"
|
||||
# and an expression like "{{ ... }}" stay valid too.
|
||||
errors.append(
|
||||
f"Do-while step {config.get('id', '?')!r}: 'condition' must be a "
|
||||
f"string or boolean, got {type(config['condition']).__name__}."
|
||||
)
|
||||
max_iter = config.get("max_iterations")
|
||||
if max_iter is not None:
|
||||
# bool is a subclass of int, so isinstance(True, int) is True and
|
||||
|
||||
@@ -61,6 +61,24 @@ class IfThenStep(StepBase):
|
||||
errors.append(
|
||||
f"If step {config.get('id', '?')!r} is missing 'condition' field."
|
||||
)
|
||||
elif not isinstance(config["condition"], (str, bool)):
|
||||
# execute() feeds 'condition' to evaluate_condition(), which first
|
||||
# delegates to evaluate_expression() -- that returns a non-string
|
||||
# unchanged -- and then coerces the result with bool(). So a
|
||||
# list/dict/number condition silently resolves to its truthiness
|
||||
# (e.g. condition: [1, 2] is always True) with no error, branching
|
||||
# wrongly on an authoring mistake. Reject those at validation,
|
||||
# mirroring the prompt/shell/command 'must be a string' checks.
|
||||
#
|
||||
# A literal ``bool`` stays valid: an unquoted ``condition: false``
|
||||
# is idiomatic YAML, evaluate_condition() already resolves it
|
||||
# exactly (bool passthrough, then a no-op bool()), and this step
|
||||
# itself defaults ``condition`` to ``False``. "true"/"false" and an
|
||||
# expression like "{{ ... }}" are strings, so they stay valid too.
|
||||
errors.append(
|
||||
f"If step {config.get('id', '?')!r}: 'condition' must be a "
|
||||
f"string or boolean, got {type(config['condition']).__name__}."
|
||||
)
|
||||
if "then" not in config:
|
||||
errors.append(
|
||||
f"If step {config.get('id', '?')!r} is missing 'then' field."
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
@@ -88,9 +89,19 @@ class PromptStep(StepBase):
|
||||
),
|
||||
)
|
||||
|
||||
# An invalid timeout reaches subprocess.run() and raises a raw
|
||||
# TypeError ("unsupported operand type(s) for +: 'float' and 'str'")
|
||||
# or ValueError, which the engine re-raises — taking down the whole
|
||||
# run with a message that names neither the step nor 'timeout'. Fail
|
||||
# this step cleanly instead, mirroring the shell step.
|
||||
timeout_error = self._timeout_error(config)
|
||||
if timeout_error is not None:
|
||||
return StepResult(status=StepStatus.FAILED, error=timeout_error)
|
||||
|
||||
# Attempt CLI dispatch
|
||||
timeout = config.get("timeout", 300)
|
||||
dispatch_result = self._try_dispatch(
|
||||
prompt, integration, model, context
|
||||
prompt, integration, model, context, timeout=timeout
|
||||
)
|
||||
|
||||
output: dict[str, Any] = {
|
||||
@@ -130,12 +141,48 @@ class PromptStep(StepBase):
|
||||
),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _timeout_error(config: dict[str, Any]) -> str | None:
|
||||
"""Return an error message if ``config['timeout']`` is invalid, else None.
|
||||
|
||||
Shared by execute() and validate() so both paths reject the same
|
||||
values with the same message, mirroring the shell step. An absent
|
||||
``timeout`` is valid (the default is used). bool is a subclass of int,
|
||||
but ``timeout: true`` is a config error rather than a duration, so it
|
||||
is rejected explicitly. Non-finite floats (YAML ``.inf``/``.nan``) pass
|
||||
a plain ``> 0`` check but would raise in subprocess.run(), and a
|
||||
non-positive timeout makes subprocess.run() report an immediate
|
||||
TimeoutExpired, so both are rejected too.
|
||||
"""
|
||||
if "timeout" not in config:
|
||||
return None
|
||||
timeout = config["timeout"]
|
||||
try:
|
||||
valid_timeout = (
|
||||
not isinstance(timeout, bool)
|
||||
and isinstance(timeout, (int, float))
|
||||
and timeout > 0
|
||||
and math.isfinite(timeout)
|
||||
)
|
||||
except OverflowError:
|
||||
# An int too large to convert to float (e.g. a 400-digit YAML
|
||||
# scalar) clears every clause above and raises here — and would
|
||||
# raise the same from subprocess.run(timeout=...).
|
||||
valid_timeout = False
|
||||
if not valid_timeout:
|
||||
return (
|
||||
f"Prompt step {config.get('id', '?')!r}: 'timeout' must be a "
|
||||
f"positive number of seconds, got {timeout!r}."
|
||||
)
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _try_dispatch(
|
||||
prompt: str,
|
||||
integration_key: str | None,
|
||||
model: str | None,
|
||||
context: StepContext,
|
||||
timeout: int = 300,
|
||||
) -> dict[str, Any] | None:
|
||||
"""Dispatch *prompt* directly through the integration CLI."""
|
||||
if not integration_key or not isinstance(integration_key, str) or not prompt:
|
||||
@@ -167,6 +214,17 @@ class PromptStep(StepBase):
|
||||
if not exec_args:
|
||||
return None
|
||||
|
||||
# Windows: ``subprocess.run`` calls ``CreateProcess``, which does not
|
||||
# consult ``PATHEXT``, so a bare command name like ``claude`` installed
|
||||
# as ``claude.cmd`` (the usual npm shim layout) fails with
|
||||
# ``WinError 2``. That OSError is swallowed below and reported as "CLI
|
||||
# not found or not installed" -- even though the preflight above just
|
||||
# found it. Reuse the already-resolved path so the shim is executed,
|
||||
# mirroring ``IntegrationBase.dispatch_command``, which the ``command``
|
||||
# step already goes through. On POSIX this is the same executable.
|
||||
if fallback_cli_path:
|
||||
exec_args = [fallback_cli_path, *exec_args[1:]]
|
||||
|
||||
import subprocess
|
||||
|
||||
project_root = (
|
||||
@@ -178,6 +236,7 @@ class PromptStep(StepBase):
|
||||
exec_args,
|
||||
text=True,
|
||||
cwd=str(project_root),
|
||||
timeout=timeout,
|
||||
)
|
||||
return {
|
||||
"exit_code": result.returncode,
|
||||
@@ -190,6 +249,12 @@ class PromptStep(StepBase):
|
||||
"stdout": "",
|
||||
"stderr": "Interrupted by user",
|
||||
}
|
||||
except subprocess.TimeoutExpired:
|
||||
return {
|
||||
"exit_code": -1,
|
||||
"stdout": "",
|
||||
"stderr": f"Prompt timed out after {timeout} seconds.",
|
||||
}
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
@@ -230,4 +295,7 @@ class PromptStep(StepBase):
|
||||
f"Prompt step {config.get('id', '?')!r}: 'model' must be a "
|
||||
f"string, got {type(model).__name__}."
|
||||
)
|
||||
timeout_error = self._timeout_error(config)
|
||||
if timeout_error is not None:
|
||||
errors.append(timeout_error)
|
||||
return errors
|
||||
|
||||
@@ -121,12 +121,20 @@ class ShellStep(StepBase):
|
||||
if "timeout" not in config:
|
||||
return None
|
||||
timeout = config["timeout"]
|
||||
if (
|
||||
isinstance(timeout, bool)
|
||||
or not isinstance(timeout, (int, float))
|
||||
or not math.isfinite(timeout)
|
||||
or timeout <= 0
|
||||
):
|
||||
try:
|
||||
invalid_timeout = (
|
||||
isinstance(timeout, bool)
|
||||
or not isinstance(timeout, (int, float))
|
||||
or not math.isfinite(timeout)
|
||||
or timeout <= 0
|
||||
)
|
||||
except OverflowError:
|
||||
# An int too large to convert to float (e.g. a 400-digit YAML
|
||||
# scalar) is not a bool and *is* an int, so it clears every clause
|
||||
# before ``isfinite()`` and raises there — and would raise the same
|
||||
# from subprocess.run(timeout=...). Mirrors the prompt step.
|
||||
invalid_timeout = True
|
||||
if invalid_timeout:
|
||||
return (
|
||||
f"Shell step {config.get('id', '?')!r}: 'timeout' must be a "
|
||||
f"positive number of seconds, got {timeout!r}."
|
||||
|
||||
@@ -79,6 +79,24 @@ class WhileStep(StepBase):
|
||||
f"While step {config.get('id', '?')!r} is missing "
|
||||
f"'condition' field."
|
||||
)
|
||||
elif not isinstance(config["condition"], (str, bool)):
|
||||
# execute() feeds 'condition' to evaluate_condition(), which first
|
||||
# delegates to evaluate_expression() -- that returns a non-string
|
||||
# unchanged -- and then coerces the result with bool(). So a
|
||||
# list/dict/number condition silently resolves to its truthiness
|
||||
# (e.g. condition: [1, 2] is always truthy, spinning the loop to
|
||||
# max_iterations) with no error. Reject those at validation,
|
||||
# mirroring the prompt/shell/command 'must be a string' checks.
|
||||
#
|
||||
# A literal ``bool`` stays valid: an unquoted ``condition: false``
|
||||
# is idiomatic YAML, evaluate_condition() already resolves it
|
||||
# exactly (bool passthrough, then a no-op bool()), and this step
|
||||
# itself defaults ``condition`` to ``False``. "true"/"false" and an
|
||||
# expression like "{{ ... }}" are strings, so they stay valid too.
|
||||
errors.append(
|
||||
f"While step {config.get('id', '?')!r}: 'condition' must be a "
|
||||
f"string or boolean, got {type(config['condition']).__name__}."
|
||||
)
|
||||
max_iter = config.get("max_iterations")
|
||||
if max_iter is not None:
|
||||
# bool is a subclass of int, so isinstance(True, int) is True and
|
||||
|
||||
@@ -139,6 +139,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:** <interrogative>?` or `**Question:** <interrogative>? (FR-023)`. Never put the id before the `?`, and never use the id (alone or with a topic label) as the whole prompt.
|
||||
- Immediately after the question line, add one plain-language "Why it matters" sentence (the stake for acceptance or shipping) before the recommendation/options.
|
||||
- Use everyday wording; introduce jargon only if defined in the same sentence. Self-check: a reader who does not know Spec Kit must be able to answer from the Question line alone. Terse is fine; cryptic labels are not.
|
||||
- For multiple‑choice questions:
|
||||
- **Analyze all options** and determine the **most suitable option** based on:
|
||||
- Best practices for the project type
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
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.
|
||||
handoffs:
|
||||
- label: Build Specification
|
||||
agent: speckit.specify
|
||||
@@ -16,8 +16,8 @@ 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 and propagating
|
||||
constitution-driven changes to the dependent artifacts identified in this command.
|
||||
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.
|
||||
@@ -25,7 +25,7 @@ constitution-driven changes to the dependent artifacts identified in this comman
|
||||
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 and its required propagation.
|
||||
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
|
||||
@@ -70,7 +70,7 @@ constitution-driven changes to the dependent artifacts identified in this comman
|
||||
|
||||
## 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.
|
||||
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 and (b) fill the template precisely.
|
||||
|
||||
**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.
|
||||
|
||||
@@ -96,32 +96,24 @@ Follow this execution flow:
|
||||
- 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 installed Spec Kit command file for your agent (including this one) — named `speckit.*` or `speckit-*` (dot or hyphen depending on the agent), or laid out as `speckit-<name>/SKILL.md` for skills-based integrations, e.g. in `.github/agents/`, `.github/skills/`, `.claude/skills/`, or your agent's equivalent commands directory — to verify no outdated references (CLAUDE-only or other agent-specific names) 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 (prepend as an HTML comment at top of the constitution file after update):
|
||||
- Version change: old → new
|
||||
- List of modified principles (old title → new title if renamed)
|
||||
- Added sections
|
||||
- Removed sections
|
||||
- Templates requiring updates (✅ updated / ⚠ pending) with file paths
|
||||
- Follow-up TODOs if any placeholders intentionally deferred.
|
||||
|
||||
6. Validation before final output:
|
||||
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.
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ from typer.testing import CliRunner
|
||||
|
||||
from specify_cli import app
|
||||
from specify_cli.bundler.services.packager import build_bundle
|
||||
from tests.conftest import strip_ansi
|
||||
from tests.bundler_helpers import (
|
||||
catalog_entry_dict,
|
||||
valid_manifest_dict,
|
||||
@@ -25,6 +26,42 @@ from tests.bundler_helpers import (
|
||||
|
||||
runner = CliRunner()
|
||||
|
||||
MARKUP_BUNDLE_ID = "[red]markup-id[/red]"
|
||||
MARKUP_SOURCE_ID = "[underline]markup-source[/underline]"
|
||||
|
||||
|
||||
def _configure_markup_catalog(project: Path, **overrides: object) -> dict:
|
||||
entry = catalog_entry_dict(
|
||||
MARKUP_BUNDLE_ID,
|
||||
name="[green]Markup Name[/green]",
|
||||
version="[blue]1.0.0[/blue]",
|
||||
role="[magenta]Markup Role[/magenta]",
|
||||
description="[yellow]Markup Description[/yellow]",
|
||||
author="[cyan]Markup Author[/cyan]",
|
||||
license="[bold]Markup License[/bold]",
|
||||
download_url="https://example.com/markup-bundle.zip",
|
||||
requires={"speckit_version": "[italic]>=0.1.0[/italic]"},
|
||||
**overrides,
|
||||
)
|
||||
catalog = project / "markup-catalog.json"
|
||||
write_catalog_file(catalog, {MARKUP_BUNDLE_ID: entry})
|
||||
config = {
|
||||
"schema_version": "1.0",
|
||||
"catalogs": [
|
||||
{
|
||||
"id": MARKUP_SOURCE_ID,
|
||||
"url": str(catalog),
|
||||
"priority": 1,
|
||||
"install_policy": "install-allowed",
|
||||
}
|
||||
],
|
||||
}
|
||||
(project / ".specify" / "bundle-catalogs.yml").write_text(
|
||||
yaml.safe_dump(config),
|
||||
encoding="utf-8",
|
||||
)
|
||||
return entry
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def project(tmp_path: Path, monkeypatch) -> Path:
|
||||
@@ -124,6 +161,24 @@ def test_search_works_without_a_project(tmp_path: Path, monkeypatch):
|
||||
assert result.output.strip().startswith("[")
|
||||
|
||||
|
||||
def test_search_escapes_catalog_markup(project: Path):
|
||||
entry = _configure_markup_catalog(project)
|
||||
|
||||
result = runner.invoke(app, ["bundle", "search", "--offline"])
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
output = " ".join(strip_ansi(result.output).split())
|
||||
for value in (
|
||||
entry["id"],
|
||||
entry["name"],
|
||||
entry["version"],
|
||||
entry["role"],
|
||||
entry["description"],
|
||||
MARKUP_SOURCE_ID,
|
||||
):
|
||||
assert value in output
|
||||
|
||||
|
||||
def test_info_unknown_bundle_without_project_reports_not_found(tmp_path: Path, monkeypatch):
|
||||
monkeypatch.chdir(tmp_path) # no .specify/
|
||||
result = runner.invoke(app, ["bundle", "info", "does-not-exist", "--offline"])
|
||||
@@ -261,6 +316,83 @@ def test_info_expands_full_component_set(project: Path, monkeypatch):
|
||||
assert "Trust" in text.output
|
||||
|
||||
|
||||
def test_info_escapes_catalog_markup(project: Path, monkeypatch):
|
||||
entry = _configure_markup_catalog(project)
|
||||
bundle_dir = project / "markup-bundle"
|
||||
bundle_dir.mkdir()
|
||||
manifest_data = valid_manifest_dict()
|
||||
manifest_data["bundle"]["id"] = MARKUP_BUNDLE_ID
|
||||
manifest_data["integration"] = {
|
||||
"id": "[conceal]markup-integration[/conceal]"
|
||||
}
|
||||
manifest_path = bundle_dir / "bundle.yml"
|
||||
manifest_path.write_text(yaml.safe_dump(manifest_data), encoding="utf-8")
|
||||
_mock_manifest_download(monkeypatch, manifest_path)
|
||||
monkeypatch.setattr(
|
||||
"specify_cli.commands.bundle._manifest_component_view",
|
||||
lambda manifest: [
|
||||
{
|
||||
"kind": "extensions",
|
||||
"id": "[reverse]markup-component[/reverse]",
|
||||
"version": "[strike]2.0.0[/strike]",
|
||||
}
|
||||
],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"specify_cli.commands.bundle._bundle_overlaps",
|
||||
lambda project_root, manifest, *, offline: [
|
||||
"[blink]markup-overlap[/blink]"
|
||||
],
|
||||
)
|
||||
|
||||
result = runner.invoke(
|
||||
app,
|
||||
["bundle", "info", MARKUP_BUNDLE_ID, "--offline"],
|
||||
)
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
output = " ".join(strip_ansi(result.output).split())
|
||||
for value in (
|
||||
entry["id"],
|
||||
entry["name"],
|
||||
entry["version"],
|
||||
entry["role"],
|
||||
entry["description"],
|
||||
entry["author"],
|
||||
entry["license"],
|
||||
entry["requires"]["speckit_version"],
|
||||
MARKUP_SOURCE_ID,
|
||||
"[conceal]markup-integration[/conceal]",
|
||||
"[reverse]markup-component[/reverse]",
|
||||
"[strike]2.0.0[/strike]",
|
||||
"[blink]markup-overlap[/blink]",
|
||||
):
|
||||
assert value in output
|
||||
|
||||
|
||||
def test_info_escapes_catalog_provides_fallback_markup(project: Path, monkeypatch):
|
||||
markup_count = "[bold]markup-count[/bold]"
|
||||
_configure_markup_catalog(
|
||||
project,
|
||||
provides={"extensions": markup_count},
|
||||
)
|
||||
bundle_dir = project / "markup-bundle"
|
||||
bundle_dir.mkdir()
|
||||
manifest_data = valid_manifest_dict(provides={})
|
||||
manifest_data["bundle"]["id"] = MARKUP_BUNDLE_ID
|
||||
manifest_path = bundle_dir / "bundle.yml"
|
||||
manifest_path.write_text(yaml.safe_dump(manifest_data), encoding="utf-8")
|
||||
_mock_manifest_download(monkeypatch, manifest_path)
|
||||
|
||||
result = runner.invoke(
|
||||
app,
|
||||
["bundle", "info", MARKUP_BUNDLE_ID, "--offline"],
|
||||
)
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert markup_count in strip_ansi(result.output)
|
||||
|
||||
|
||||
def test_info_expands_discovery_only_bundle(project: Path, monkeypatch):
|
||||
# Discovery-only bundles must still be fully inspectable via `info`;
|
||||
# only `install` is refused for them.
|
||||
|
||||
@@ -113,6 +113,44 @@ def test_absent_or_empty_catalogs_is_noop(tmp_path: Path, body: str):
|
||||
assert len(sources) > 0
|
||||
|
||||
|
||||
def test_load_source_stack_rejects_unknown_schema_version(tmp_path: Path):
|
||||
"""A bundle-catalogs.yml with an unsupported MAJOR schema_version must raise
|
||||
on the resolution path (load_source_stack -> _merge_config), matching the
|
||||
sibling reader commands_impl/catalog_config._read. Without this a file
|
||||
written by a newer/incompatible Spec Kit was silently parsed under v1
|
||||
assumptions on the install/search path, while the other reader rejected it."""
|
||||
make_project(tmp_path)
|
||||
config = {
|
||||
"schema_version": "2.0",
|
||||
"catalogs": [{"id": "corp", "url": "https://corp/catalog.json",
|
||||
"priority": 1, "install_policy": "install-allowed"}],
|
||||
}
|
||||
(tmp_path / ".specify" / "bundle-catalogs.yml").write_text(
|
||||
yaml.safe_dump(config), encoding="utf-8"
|
||||
)
|
||||
with pytest.raises(BundlerError, match="Unsupported catalog config schema version"):
|
||||
load_source_stack(tmp_path)
|
||||
|
||||
|
||||
def test_load_source_stack_accepts_matching_or_absent_schema_version(tmp_path: Path):
|
||||
"""A matching major version (1.x) and an absent schema_version both stay
|
||||
valid — the guard rejects only a different major, so existing configs that
|
||||
omit the key are unaffected."""
|
||||
make_project(tmp_path)
|
||||
cfg = tmp_path / ".specify" / "bundle-catalogs.yml"
|
||||
cfg.write_text(yaml.safe_dump({
|
||||
"schema_version": "1.5", # same major as CONFIG_SCHEMA_VERSION (1.0)
|
||||
"catalogs": [{"id": "corp", "url": "https://corp/catalog.json",
|
||||
"priority": 1, "install_policy": "install-allowed"}],
|
||||
}), encoding="utf-8")
|
||||
assert "corp" in {s.id for s in load_source_stack(tmp_path)}
|
||||
cfg.write_text(yaml.safe_dump({ # no schema_version key
|
||||
"catalogs": [{"id": "corp2", "url": "https://corp2/catalog.json",
|
||||
"priority": 1, "install_policy": "install-allowed"}],
|
||||
}), encoding="utf-8")
|
||||
assert "corp2" in {s.id for s in load_source_stack(tmp_path)}
|
||||
|
||||
|
||||
def test_project_config_overrides_same_id(tmp_path: Path):
|
||||
make_project(tmp_path)
|
||||
config = {
|
||||
@@ -209,6 +247,25 @@ def test_catalog_entry_rejects_non_boolean_verified():
|
||||
CatalogEntry.from_dict(data)
|
||||
|
||||
|
||||
def test_catalog_entry_preserves_sha256_through_provenance():
|
||||
digest = "a" * 64
|
||||
payload = catalog_payload(
|
||||
{"demo": catalog_entry_dict("demo", sha256=f"sha256:{digest}")}
|
||||
)
|
||||
|
||||
entry = load_catalog_payload(payload)["demo"]
|
||||
source = CatalogSource(
|
||||
id="team",
|
||||
url="https://example.com/catalog.json",
|
||||
priority=10,
|
||||
install_policy=InstallPolicy.INSTALL_ALLOWED,
|
||||
scope=Scope.PROJECT,
|
||||
)
|
||||
|
||||
assert entry.sha256 == f"sha256:{digest}"
|
||||
assert entry.with_provenance(source).sha256 == f"sha256:{digest}"
|
||||
|
||||
|
||||
def test_load_payload_rejects_id_key_mismatch():
|
||||
# The enclosing key is authoritative; an entry whose own id disagrees with
|
||||
# the key must be rejected so a catalog can't list a spoofed/unresolvable id.
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user