Compare commits
2
Commits
e19aa2e27c
...
6159c6373c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6159c6373c | ||
|
|
79694fbaa2 |
No files matched your search
+29
-6
@@ -48,6 +48,10 @@ jobs:
|
|||||||
python-version: '3.12'
|
python-version: '3.12'
|
||||||
- name: Compile Python sources
|
- name: Compile Python sources
|
||||||
run: python -m compileall -q scripts shared
|
run: python -m compileall -q scripts shared
|
||||||
|
- name: Lint Python
|
||||||
|
run: |
|
||||||
|
python -m pip install --quiet --disable-pip-version-check ruff==0.17.1
|
||||||
|
python -m ruff check --output-format=github .
|
||||||
- name: Run Python tests
|
- name: Run Python tests
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
@@ -107,6 +111,16 @@ jobs:
|
|||||||
bash scripts/commands/build.sh --summary
|
bash scripts/commands/build.sh --summary
|
||||||
after=$(find generated -type f -print0 | sort -z | xargs -0 sha256sum)
|
after=$(find generated -type f -print0 | sort -z | xargs -0 sha256sum)
|
||||||
test "$before" = "$after"
|
test "$before" = "$after"
|
||||||
|
# Later jobs test these exact packages instead of rebuilding them. A tarball keeps file modes,
|
||||||
|
# which artifact uploads would otherwise drop.
|
||||||
|
- name: Pack generated packages
|
||||||
|
run: tar -czf generated.tar.gz generated
|
||||||
|
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||||
|
with:
|
||||||
|
name: generated-packages
|
||||||
|
path: generated.tar.gz
|
||||||
|
retention-days: 1
|
||||||
|
if-no-files-found: error
|
||||||
|
|
||||||
shell-integration:
|
shell-integration:
|
||||||
name: Bash integration and installation guards
|
name: Bash integration and installation guards
|
||||||
@@ -115,13 +129,15 @@ jobs:
|
|||||||
needs: [build]
|
needs: [build]
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||||
- name: Build packages for integration checks
|
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||||
env:
|
with:
|
||||||
REQUIRE_CODEX_SCHEMA: 'false'
|
name: generated-packages
|
||||||
run: bash scripts/commands/build.sh --summary
|
- name: Unpack generated packages
|
||||||
|
run: tar -xzf generated.tar.gz && rm generated.tar.gz
|
||||||
- name: Run integration tests
|
- name: Run integration tests
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
bash scripts/tests/test-capabilities.sh --summary
|
||||||
bash scripts/tests/test-install-guards.sh --summary
|
bash scripts/tests/test-install-guards.sh --summary
|
||||||
bash scripts/tests/test-plugin-selection.sh --summary
|
bash scripts/tests/test-plugin-selection.sh --summary
|
||||||
bash scripts/tests/test-quick-update.sh --summary
|
bash scripts/tests/test-quick-update.sh --summary
|
||||||
@@ -149,8 +165,11 @@ jobs:
|
|||||||
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
|
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
|
||||||
with:
|
with:
|
||||||
python-version: '3.12'
|
python-version: '3.12'
|
||||||
- name: Build packages
|
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||||
run: bash scripts/commands/build.sh --summary
|
with:
|
||||||
|
name: generated-packages
|
||||||
|
- name: Unpack generated packages
|
||||||
|
run: tar -xzf generated.tar.gz && rm generated.tar.gz
|
||||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v22.16.0
|
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v22.16.0
|
||||||
with:
|
with:
|
||||||
node-version: '24'
|
node-version: '24'
|
||||||
@@ -184,6 +203,8 @@ jobs:
|
|||||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v22.16.0
|
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v22.16.0
|
||||||
with:
|
with:
|
||||||
node-version: '24'
|
node-version: '24'
|
||||||
|
- name: Check JavaScript module syntax
|
||||||
|
run: git ls-files -z '*.mjs' | xargs -0 -r -n1 node --check
|
||||||
# CI runs model-free tests only; real-model integration requires a suitable local machine.
|
# CI runs model-free tests only; real-model integration requires a suitable local machine.
|
||||||
- name: Install QMD test dependency
|
- name: Install QMD test dependency
|
||||||
run: npm install --prefix "$QMD_PACKAGE_DIR" --ignore-scripts --no-package-lock --no-audit --no-fund yaml@2.9.0
|
run: npm install --prefix "$QMD_PACKAGE_DIR" --ignore-scripts --no-package-lock --no-audit --no-fund yaml@2.9.0
|
||||||
@@ -206,6 +227,8 @@ jobs:
|
|||||||
! grep -RInE "$unsafe_patterns" .gitea/workflows
|
! grep -RInE "$unsafe_patterns" .gitea/workflows
|
||||||
test "$(grep -Roh 'runs-on: ubuntu-latest' .gitea/workflows | wc -l)" -ge 1
|
test "$(grep -Roh 'runs-on: ubuntu-latest' .gitea/workflows | wc -l)" -ge 1
|
||||||
test "$(grep -Roh 'uses: actions/[^@]*@[0-9a-f]\{40\}' .gitea/workflows | wc -l)" -ge 1
|
test "$(grep -Roh 'uses: actions/[^@]*@[0-9a-f]\{40\}' .gitea/workflows | wc -l)" -ge 1
|
||||||
|
# Every action, including artifact transfer, must be pinned to a full commit SHA.
|
||||||
|
! grep -RhE '^[[:space:]-]*uses:' .gitea/workflows | grep -vE 'uses:[[:space:]]*[^@[:space:]]+@[0-9a-f]{40}([[:space:]]|$)'
|
||||||
- name: Check for tracked secrets
|
- name: Check for tracked secrets
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|||||||
@@ -105,7 +105,7 @@ Install and update also rebuild internally; the explicit build above lets you ch
|
|||||||
|
|
||||||
- PowerShell 5.1 or newer; PowerShell 7 is supported as well.
|
- PowerShell 5.1 or newer; PowerShell 7 is supported as well.
|
||||||
- Bash 4.3 or newer, with standard utilities such as `awk`, `sed`, and `sha256sum`.
|
- Bash 4.3 or newer, with standard utilities such as `awk`, `sed`, and `sha256sum`.
|
||||||
- Python 3.11 or newer for configuration validation and task-state hooks/helpers (`python` for PowerShell scripts, `python3` for Bash scripts).
|
- Python 3.11 or newer for configuration validation and the Python-based hooks and helpers. Scripts and hooks try `python`, `python3`, and the `py -3` launcher (Bash: `python3` first) and use the first one that actually runs Python 3.11+, so the Windows Store app execution alias is ignored. Without Python, build and capability checks stop with an actionable message, doctor reports a failure, and the registered Python-based hooks are skipped.
|
||||||
- `jq` for Claude's Bash status line; without it, that status line produces no output.
|
- `jq` for Claude's Bash status line; without it, that status line produces no output.
|
||||||
- Node.js 22 or newer and `npm` when local QMD search or MCPorter is selected.
|
- Node.js 22 or newer and `npm` when local QMD search or MCPorter is selected.
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
role tools
|
role tools
|
||||||
architect Read,Grep,Glob,WebFetch,WebSearch,__SHELL__
|
architect Read,Grep,Glob,WebFetch,WebSearch,__SHELL_TOOL__
|
||||||
researcher Read,Grep,Glob,WebFetch,WebSearch,__SHELL__
|
researcher Read,Grep,Glob,WebFetch,WebSearch,__SHELL_TOOL__
|
||||||
reviewer Read,Grep,Glob,__SHELL__
|
reviewer Read,Grep,Glob,__SHELL_TOOL__
|
||||||
verifier Read,Grep,Glob,__SHELL__
|
verifier Read,Grep,Glob,__SHELL_TOOL__
|
||||||
implementer Read,Grep,Glob,Edit,Write,__SHELL__
|
implementer Read,Grep,Glob,Edit,Write,__SHELL_TOOL__
|
||||||
|
@@ -1,8 +1,8 @@
|
|||||||
{
|
{
|
||||||
"permissions": {
|
"permissions": {
|
||||||
"defaultMode": "auto",
|
"defaultMode": "auto",
|
||||||
"allow": __CLAUDE_ALLOW_RULES__,
|
"allow": ["Agent", "__SHELL_TOOL__(mcporter call context7.*)"],
|
||||||
"deny": __CLAUDE_DENY_RULES__
|
"deny": ["PowerShell(git reset --hard*)", "PowerShell(git clean*)", "PowerShell(Remove-Item *-Recurse*)", "Bash(git reset --hard*)", "Bash(git clean*)", "Bash(rm -rf*)"]
|
||||||
},
|
},
|
||||||
"sandbox": __CLAUDE_SANDBOX__,
|
"sandbox": __CLAUDE_SANDBOX__,
|
||||||
"env": {
|
"env": {
|
||||||
@@ -15,6 +15,7 @@
|
|||||||
"command": "__STATUSLINE_COMMAND__ \"__AI_CONFIG_ROOT__/statusline/__STATUSLINE_SCRIPT__\""
|
"command": "__STATUSLINE_COMMAND__ \"__AI_CONFIG_ROOT__/statusline/__STATUSLINE_SCRIPT__\""
|
||||||
},
|
},
|
||||||
"hooks": {
|
"hooks": {
|
||||||
|
"PreToolUse": [{"matcher": "Bash|PowerShell", "hooks": [{"type": "command", "command": "__HOOK_COMMAND__ \"__AI_CONFIG_ROOT__/hooks/scripts/__COMMAND_SAFETY_SCRIPT__\"", "timeout": 6}]}],
|
||||||
"PreCompact": [{"hooks": [{"type": "command", "command": "__HOOK_COMMAND__ \"__AI_CONFIG_ROOT__/hooks/scripts/__COMPACT_SCRIPT__\"", "timeout": 4}]}],
|
"PreCompact": [{"hooks": [{"type": "command", "command": "__HOOK_COMMAND__ \"__AI_CONFIG_ROOT__/hooks/scripts/__COMPACT_SCRIPT__\"", "timeout": 4}]}],
|
||||||
"SessionStart": [
|
"SessionStart": [
|
||||||
{"hooks": [{"type": "command", "command": "__HOOK_COMMAND__ \"__AI_CONFIG_ROOT__/hooks/scripts/__SESSION_POINTER_SCRIPT__\"", "timeout": 4}]},
|
{"hooks": [{"type": "command", "command": "__HOOK_COMMAND__ \"__AI_CONFIG_ROOT__/hooks/scripts/__SESSION_POINTER_SCRIPT__\"", "timeout": 4}]},
|
||||||
|
|||||||
@@ -41,3 +41,10 @@ type = "command"
|
|||||||
command = '__HOOK_COMMAND__ "__AI_CONFIG_ROOT__/hooks/scripts/__QMD_WARM_SCRIPT__"'
|
command = '__HOOK_COMMAND__ "__AI_CONFIG_ROOT__/hooks/scripts/__QMD_WARM_SCRIPT__"'
|
||||||
command_windows = '__POWERSHELL_HOOK_COMMAND__ "__AI_CONFIG_ROOT__/hooks/scripts/__QMD_WARM_SCRIPT__"'
|
command_windows = '__POWERSHELL_HOOK_COMMAND__ "__AI_CONFIG_ROOT__/hooks/scripts/__QMD_WARM_SCRIPT__"'
|
||||||
timeout = 4
|
timeout = 4
|
||||||
|
|
||||||
|
[[hooks.PreToolUse]]
|
||||||
|
[[hooks.PreToolUse.hooks]]
|
||||||
|
type = "command"
|
||||||
|
command = '__HOOK_COMMAND__ "__AI_CONFIG_ROOT__/hooks/scripts/__COMMAND_SAFETY_SCRIPT__"'
|
||||||
|
command_windows = '__POWERSHELL_HOOK_COMMAND__ "__AI_CONFIG_ROOT__/hooks/scripts/__COMMAND_SAFETY_SCRIPT__"'
|
||||||
|
timeout = 6
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
placeholder powershell bash
|
||||||
|
__HOOK_COMMAND__ __POWERSHELL_COMMAND__ bash
|
||||||
|
__POWERSHELL_HOOK_COMMAND__ __POWERSHELL_COMMAND__ bash
|
||||||
|
__STATUSLINE_COMMAND__ __POWERSHELL_COMMAND__ bash
|
||||||
|
__HOOK_SCRIPT__ flashbang.ps1 flashbang.sh
|
||||||
|
__POWERSHELL_HOOK_SCRIPT__ flashbang.ps1 flashbang.sh
|
||||||
|
__STATUSLINE_SCRIPT__ statusline.ps1 statusline.sh
|
||||||
|
__COMPACT_SCRIPT__ Record-Compact.ps1 record-compact.sh
|
||||||
|
__SESSION_POINTER_SCRIPT__ Show-SessionStatePointer.ps1 show-session-state-pointer.sh
|
||||||
|
__QMD_WARM_SCRIPT__ Start-QmdWarm.ps1 start-qmd-warm.sh
|
||||||
|
__CORRECTION_PROMPT_SCRIPT__ Show-CorrectionPrompt.ps1 show-correction-prompt.sh
|
||||||
|
__COMPLETION_EVIDENCE_SCRIPT__ Check-CompletionEvidence.ps1 check-completion-evidence.sh
|
||||||
|
__COMMAND_SAFETY_SCRIPT__ Validate-CommandSafety.ps1 validate-command-safety.sh
|
||||||
|
__SHELL_TOOL__ PowerShell Bash
|
||||||
|
__SCRIPT_EXTENSION__ ps1 sh
|
||||||
|
@@ -4,24 +4,24 @@
|
|||||||
"permanent_context_hard_limit_tokens": 15000,
|
"permanent_context_hard_limit_tokens": 15000,
|
||||||
"metrics": {
|
"metrics": {
|
||||||
"permanent_context_tokens": {
|
"permanent_context_tokens": {
|
||||||
"claude": 5451,
|
"claude": 5959,
|
||||||
"codex": 3767
|
"codex": 4100
|
||||||
},
|
},
|
||||||
"instruction_tokens": {
|
"instruction_tokens": {
|
||||||
"claude": 1485,
|
"claude": 1670,
|
||||||
"codex": 1485
|
"codex": 1670
|
||||||
},
|
},
|
||||||
"skill_metadata_tokens": {
|
"skill_metadata_tokens": {
|
||||||
"claude": 3163,
|
"claude": 3354,
|
||||||
"codex": 1554
|
"codex": 1575
|
||||||
},
|
},
|
||||||
"auto_loaded_rule_tokens": {
|
"auto_loaded_rule_tokens": {
|
||||||
"claude": 678,
|
"claude": 732,
|
||||||
"codex": 678
|
"codex": 731
|
||||||
},
|
},
|
||||||
"rule_catalog_tokens": {
|
"rule_catalog_tokens": {
|
||||||
"claude": 28818,
|
"claude": 36519,
|
||||||
"codex": 8510
|
"codex": 8944
|
||||||
},
|
},
|
||||||
"agent_metadata_tokens": {
|
"agent_metadata_tokens": {
|
||||||
"claude": 204,
|
"claude": 204,
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
metric client baseline_tokens
|
metric client baseline_tokens
|
||||||
permanent_context_tokens claude 5451
|
permanent_context_tokens claude 5959
|
||||||
permanent_context_tokens codex 3767
|
permanent_context_tokens codex 4100
|
||||||
instruction_tokens claude 1485
|
instruction_tokens claude 1670
|
||||||
instruction_tokens codex 1485
|
instruction_tokens codex 1670
|
||||||
skill_metadata_tokens claude 3163
|
skill_metadata_tokens claude 3354
|
||||||
skill_metadata_tokens codex 1554
|
skill_metadata_tokens codex 1575
|
||||||
auto_loaded_rule_tokens claude 678
|
auto_loaded_rule_tokens claude 732
|
||||||
auto_loaded_rule_tokens codex 678
|
auto_loaded_rule_tokens codex 731
|
||||||
rule_catalog_tokens claude 28818
|
rule_catalog_tokens claude 36519
|
||||||
rule_catalog_tokens codex 8510
|
rule_catalog_tokens codex 8944
|
||||||
agent_metadata_tokens claude 204
|
agent_metadata_tokens claude 204
|
||||||
agent_metadata_tokens codex 124
|
agent_metadata_tokens codex 124
|
||||||
|
@@ -6,6 +6,8 @@ Shared definitions are the source of truth. Rebuild after every semantic change.
|
|||||||
|
|
||||||
Create cross-cutting rules such as Git or Microsoft guidance as focused Markdown files directly in `shared/rules/`. Put each language, framework, or library in its own directory with an `index.md` and focused files under `references/`; put security rules in `shared/rules/security/`. Add the matching loading condition and generated Claude skill name to `shared/global-instructions.md` and the directory index. The build copies rule trees to Codex and generates Claude skills from each rule file. Put always-applicable guidance in `general.md`, which the build embeds for both clients; a new rule file is not automatically embedded.
|
Create cross-cutting rules such as Git or Microsoft guidance as focused Markdown files directly in `shared/rules/`. Put each language, framework, or library in its own directory with an `index.md` and focused files under `references/`; put security rules in `shared/rules/security/`. Add the matching loading condition and generated Claude skill name to `shared/global-instructions.md` and the directory index. The build copies rule trees to Codex and generates Claude skills from each rule file. Put always-applicable guidance in `general.md`, which the build embeds for both clients; a new rule file is not automatically embedded.
|
||||||
|
|
||||||
|
Start every rule file with a unique level-1 heading followed by an "Apply these rules when ..." line: the heading becomes the generated Claude skill description, and the scope line tells an agent loading the file cold whether it applies. Language and framework rules contain only language-specific mechanics and point to the shared security, UI/UX, or parent-language rules instead of restating them. The build rejects rule files without a level-1 heading, duplicate titles, reference files missing from their index, index links to missing files, and routes in the global instructions to rules or skills that do not exist.
|
||||||
|
|
||||||
## Add a skill
|
## Add a skill
|
||||||
|
|
||||||
Create `shared/skills/<skill>/SKILL.md` for a standalone skill, or `shared/skills/<category>/<skill>/SKILL.md` for a grouped workflow. Each leaf skill directory must contain a readable `SKILL.md` with valid YAML frontmatter. Keep the initial workflow focused; place longer supporting material under `references/`. Reference shared rules instead of repeating persistent standards.
|
Create `shared/skills/<skill>/SKILL.md` for a standalone skill, or `shared/skills/<category>/<skill>/SKILL.md` for a grouped workflow. Each leaf skill directory must contain a readable `SKILL.md` with valid YAML frontmatter. Keep the initial workflow focused; place longer supporting material under `references/`. Reference shared rules instead of repeating persistent standards.
|
||||||
@@ -13,3 +15,11 @@ Create `shared/skills/<skill>/SKILL.md` for a standalone skill, or `shared/skill
|
|||||||
## Add an agent
|
## Add an agent
|
||||||
|
|
||||||
Create `shared/agents/<agent>/agent.yml` and `instructions.md`. Keep semantic behavior in these shared files; the build renders the Codex and Claude Code formats.
|
Create `shared/agents/<agent>/agent.yml` and `instructions.md`. Keep semantic behavior in these shared files; the build renders the Codex and Claude Code formats.
|
||||||
|
|
||||||
|
## Add a hook or shell-specific script
|
||||||
|
|
||||||
|
Add the script for both shells under `shared/hooks/scripts/` (PowerShell `Verb-Noun.ps1`, Bash `verb-noun.sh`), register it in `adapters/claude/config/settings.json` and `adapters/codex/config/config.toml` with a placeholder such as `__MY_HOOK_SCRIPT__`, and add one row with the PowerShell and Bash values to `adapters/placeholders.tsv`. Both builds read that table, so neither build script needs a change; the build fails on any placeholder left unresolved. Put hook logic that needs more than a few lines into one Python file that both wrappers call, and resolve the interpreter through `Resolve-Python.ps1`/`resolve-python.sh`. If the installer should recognize the hook as setup-owned when merging with local settings, add its name to `OWNED_HOOK_PATTERN` in `scripts/lib/install-options.py`.
|
||||||
|
|
||||||
|
## Add evals to a skill
|
||||||
|
|
||||||
|
Give every skill an `evals/evals.json` with a few realistic prompts, the expected behavior, and concrete assertions taken from the skill's own instructions. Include at least one negative or near-miss case, such as a prompt where a naive answer would skip a mandated step. Follow the format of the existing files (`skill_name`, and `evals` entries with `id`, `prompt`, `expected_output`, `assertions`, `files`).
|
||||||
+8
-1
@@ -6,6 +6,7 @@ The adapters register these events:
|
|||||||
|
|
||||||
| Client | Event | Action |
|
| Client | Event | Action |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
|
| Codex and Claude | `PreToolUse` | Block clearly destructive shell commands (`Validate-CommandSafety`/`validate-command-safety.sh`); Claude matches the `Bash` and `PowerShell` tools. |
|
||||||
| Codex and Claude | `Stop` | Run the finish notification (`flashbang`). |
|
| Codex and Claude | `Stop` | Run the finish notification (`flashbang`). |
|
||||||
| Codex and Claude | `Stop` | Push back once on an unbacked completion claim (`Check-CompletionEvidence`/`check-completion-evidence.sh`). |
|
| Codex and Claude | `Stop` | Push back once on an unbacked completion claim (`Check-CompletionEvidence`/`check-completion-evidence.sh`). |
|
||||||
| Codex and Claude | `UserPromptSubmit` | Ask the agent to propose a durable rule when a prompt looks like a correction (`Show-CorrectionPrompt`/`show-correction-prompt.sh`). |
|
| Codex and Claude | `UserPromptSubmit` | Ask the agent to propose a durable rule when a prompt looks like a correction (`Show-CorrectionPrompt`/`show-correction-prompt.sh`). |
|
||||||
@@ -21,6 +22,12 @@ When enabled during installation or update, Flashbang runs on `Stop`, after the
|
|||||||
|
|
||||||
The completion hook blocks a stop only when the last message claims completion, names no check, and the Git working tree has non-prose changes. It uses the message wording, not command output, so it is a nudge rather than proof, and it never blocks twice in a row. The correction hook matches German and English phrases, adds a fixed instruction, and stores nothing; it skips slash commands and prompts over 2,000 characters. Rules change only after user approval. Both hooks need Python and fail open. Codex skips new or changed hooks until they are trusted through `/hooks`.
|
The completion hook blocks a stop only when the last message claims completion, names no check, and the Git working tree has non-prose changes. It uses the message wording, not command output, so it is a nudge rather than proof, and it never blocks twice in a row. The correction hook matches German and English phrases, adds a fixed instruction, and stores nothing; it skips slash commands and prompts over 2,000 characters. Rules change only after user approval. Both hooks need Python and fail open. Codex skips new or changed hooks until they are trusted through `/hooks`.
|
||||||
|
|
||||||
`Validate-CommandSafety`/`validate-command-safety.sh` and `Invoke-PostChangeVerification`/`invoke-post-change-verification.sh` are unregistered utilities. The safety utilities check command text for selected dangerous patterns; the PowerShell variant also checks some absolute paths. Neither is a complete security boundary. The verification utilities explicitly run the repository build when invoked; they are not an automatic requirement after each change.
|
The command-safety hook parses the command (quote-aware splitting on `;`, `&&`, `||`, `|`, and newlines; nested `bash -c`, `pwsh -Command`, `cmd /c`, and `eval`) and exits 2 with a reason for `rm` with recursive and force flags in any order, `git reset --hard`, `git clean -f`, `Remove-Item -Recurse` (including `ri` and, outside Bash, the `rm`/`del`/`rd` aliases), `del`/`rd /s /q`, and `format <drive>:`. The logic lives once in `command-safety.py`; the shell wrappers only resolve Python. Called with a command argument (`-Command`/first argument), the wrappers check that command and also reject absolute paths outside the workspace. Like the client deny rules, the hook is a guard rail against accidents, not a security boundary: it sees only command text, not what scripts, aliases, or variables expand to, and it fails open on unparsable input or missing Python.
|
||||||
|
|
||||||
|
The Claude `permissions.deny` patterns (`Bash(rm -rf*)`, `PowerShell(Remove-Item *-Recurse*)`, and the `git reset --hard`/`git clean` patterns) match only the literal command prefix. They do not catch `rm -fr`, `rm -r -f`, or a destructive command after `cd x &&`; the PreToolUse hook covers those variants. Treat both layers as hurdles, and rely on the sandbox, approvals, and version control for real protection.
|
||||||
|
|
||||||
|
`Invoke-PostChangeVerification`/`invoke-post-change-verification.sh` is an unregistered utility that explicitly runs the repository build when invoked; it is not an automatic requirement after each change.
|
||||||
|
|
||||||
|
All Python-based hooks find their interpreter through `Resolve-Python.ps1`/`resolve-python.sh`, which skip PATH entries that cannot run Python 3.11+ (such as the Windows Store alias). Without Python these hooks are skipped silently; `doctor` reports that case as a failure.
|
||||||
|
|
||||||
`Test-SessionConfig`/`test-session-config.sh` checks required repository inputs and is called by the build. Build and doctor do not execute the registered notification or session-state hooks. Claude's status line is a separate `statusLine` command, not a hook event.
|
`Test-SessionConfig`/`test-session-config.sh` checks required repository inputs and is called by the build. Build and doctor do not execute the registered notification or session-state hooks. Claude's status line is a separate `statusLine` command, not a hook event.
|
||||||
+6
-4
@@ -51,7 +51,7 @@ The A/B benchmark measures whole sessions. Auto selection of local QMD search us
|
|||||||
|
|
||||||
## Checks and tests
|
## Checks and tests
|
||||||
|
|
||||||
Gitea Actions runs the repository checks from `.gitea/workflows/ci.yml`.
|
Gitea Actions runs the repository checks from `.gitea/workflows/ci.yml`. The `build` job builds the packages once, checks that a rebuild is identical, and passes `generated/` as an artifact to the integration and client smoke-test jobs. Python is linted with ruff (default rules, configured in `ruff.toml`; benchmark task fixtures are excluded), JavaScript modules with `node --check`, and Bash with shellcheck. Every action is pinned to a full commit SHA.
|
||||||
|
|
||||||
Doctor captures native-command diagnostics and checks exit codes. A warning on stderr does not abort the
|
Doctor captures native-command diagnostics and checks exit codes. A warning on stderr does not abort the
|
||||||
PowerShell 5.1 script; failed version or configuration checks contribute to the final failure summary.
|
PowerShell 5.1 script; failed version or configuration checks contribute to the final failure summary.
|
||||||
@@ -59,9 +59,11 @@ On Windows, an unavailable profile-folder lookup falls back to PowerShell's home
|
|||||||
|
|
||||||
| Script | Purpose |
|
| Script | Purpose |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `checks/validate-config.py` | Validate generated Codex TOML and Claude JSON. |
|
| `checks/validate-config.py` | Validate generated Codex TOML and Claude JSON, generated rule skills, agent tool names, and the rule catalog structure and routing. |
|
||||||
| `tests/test-build-validation.ps1`, `tests/test-build-validation.sh` | Validate build failures and generated output. |
|
| `tests/test-build-validation.ps1`, `tests/test-build-validation.sh` | Validate build failures and generated output. |
|
||||||
| `tests/test-capabilities.ps1` | Guard PowerShell capability detection. |
|
| `tests/test-capabilities.ps1`, `tests/test-capabilities.sh` | Check that Python resolution skips a broken interpreter on PATH (such as the Windows Store alias) and that the capability check reports the resolved interpreter. |
|
||||||
|
| `tests/test-rule-structure.py` | Validate the rule-structure checks in `checks/validate-config.py`: level-1 headings, unique titles, complete indexes, and existing routing targets. |
|
||||||
|
| `tests/test-command-safety.py` | Validate the command-safety hook: destructive Bash, PowerShell, and cmd variants are blocked, ordinary commands pass, unusable input fails open, and both shell wrappers pass stdin and exit codes through. |
|
||||||
| `tests/test-install-guards.ps1`, `tests/test-install-guards.sh` | Validate install and update guard conditions. |
|
| `tests/test-install-guards.ps1`, `tests/test-install-guards.sh` | Validate install and update guard conditions. |
|
||||||
| `tests/test-config-effects.py` | Check that generated limits and permissions take effect: Codex keeps the V1 multi-agent implementation that honors `agents.max_depth`; with `AI_CONFIG_LIVE_TESTS=1`, short Haiku sessions confirm that Claude withholds the Agent tool from subagents, refuses subagents above the concurrency limit, and blocks `git reset --hard` in every shell tool. |
|
| `tests/test-config-effects.py` | Check that generated limits and permissions take effect: Codex keeps the V1 multi-agent implementation that honors `agents.max_depth`; with `AI_CONFIG_LIVE_TESTS=1`, short Haiku sessions confirm that Claude withholds the Agent tool from subagents, refuses subagents above the concurrency limit, and blocks `git reset --hard` in every shell tool. |
|
||||||
| `tests/test-client-smoke.py` | Install a package into a temporary home with foreign settings and ask the installed Claude and Codex CLIs which skills, agents, and hooks they discover, without completing a model request. Skips a client whose CLI is unavailable unless `AI_CONFIG_REQUIRE_CLIENTS=1`, which the CI `client-smoke` job sets. |
|
| `tests/test-client-smoke.py` | Install a package into a temporary home with foreign settings and ask the installed Claude and Codex CLIs which skills, agents, and hooks they discover, without completing a model request. Skips a client whose CLI is unavailable unless `AI_CONFIG_REQUIRE_CLIENTS=1`, which the CI `client-smoke` job sets. |
|
||||||
@@ -138,7 +140,7 @@ Benchmark fixture READMEs describe the starting task state and are retained as t
|
|||||||
| Script | Purpose |
|
| Script | Purpose |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `lib/install-options.ps1`, `lib/install-options.sh` | Read installation options and calculate client-specific choices. |
|
| `lib/install-options.ps1`, `lib/install-options.sh` | Read installation options and calculate client-specific choices. |
|
||||||
| `lib/credentials.ps1`, `lib/with-credential.sh` | Write a tool credential to Windows Credential Manager and expose it to one child process. |
|
| `lib/with-credential.ps1`, `lib/with-credential.sh` | Write a tool credential to Windows Credential Manager and expose it to one child process. |
|
||||||
| `lib/install-options.py` | Filter configuration templates and merge setup-owned client settings with local configuration. |
|
| `lib/install-options.py` | Filter configuration templates and merge setup-owned client settings with local configuration. |
|
||||||
| `lib/install-targets.ps1`, `lib/install-targets.sh` | Resolve configuration targets for the selected client and shell. |
|
| `lib/install-targets.ps1`, `lib/install-targets.sh` | Resolve configuration targets for the selected client and shell. |
|
||||||
| `lib/manifest.ps1`, `lib/manifest.sh` | Synchronize managed files and their ownership manifest. |
|
| `lib/manifest.ps1`, `lib/manifest.sh` | Synchronize managed files and their ownership manifest. |
|
||||||
|
|||||||
+1
-1
@@ -19,7 +19,7 @@ General planning, debugging, code review, and completion verification workflows
|
|||||||
|
|
||||||
The shared `plugin-workflow` skill coordinates automatic plugin use: Superpowers for process, Ponytail for implementation and review, Impeccable for UI, and i-have-adhd with Caveman for responses. Global instructions require it for development tasks, on resume, and at phase changes; questions and prose-only changes skip it. It routes to installed skills, preserves explicit opt-outs, and handles missing or manual-only plugins without replacing upstream workflows.
|
The shared `plugin-workflow` skill coordinates automatic plugin use: Superpowers for process, Ponytail for implementation and review, Impeccable for UI, and i-have-adhd with Caveman for responses. Global instructions require it for development tasks, on resume, and at phase changes; questions and prose-only changes skip it. It routes to installed skills, preserves explicit opt-outs, and handles missing or manual-only plugins without replacing upstream workflows.
|
||||||
|
|
||||||
Each skill defines a focused workflow with the investigation, decision points, and output expected for that task. Keep guidance specific to the skill; shared repository constraints belong in the rules.
|
Each skill defines a focused workflow with the investigation, decision points, and output expected for that task. Each skill also has an `evals/evals.json` with test prompts and checkable assertions derived from its instructions, including negative and near-miss cases; some assertions about tool use or skill loading can only be graded from a session transcript. Keep guidance specific to the skill; shared repository constraints belong in the rules.
|
||||||
|
|
||||||
The single catalog in `shared/skills/` includes development skills and focused skills for writing, image assets, content and site structure, positioning, psychology, and conversion. The image skill has a short core and five focused references loaded only when relevant: optimization, OG metadata, marketing workflows, design tools, and common mistakes. AI-generation guides, model comparisons, prompting recipes, and fixed social-platform size catalogs are omitted. Builds include every retained skill for both clients. Updating a managed installation backs up and removes unchanged setup-owned skills deleted from the catalog; local changes are backed up and retained.
|
The single catalog in `shared/skills/` includes development skills and focused skills for writing, image assets, content and site structure, positioning, psychology, and conversion. The image skill has a short core and five focused references loaded only when relevant: optimization, OG metadata, marketing workflows, design tools, and common mistakes. AI-generation guides, model comparisons, prompting recipes, and fixed social-platform size catalogs are omitted. Builds include every retained skill for both clients. Updating a managed installation backs up and removes unchanged setup-owned skills deleted from the catalog; local changes are backed up and retained.
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
# Lint configuration for the repository's own Python. Benchmark task fixtures are deliberately
|
||||||
|
# defective sample projects, so they are excluded.
|
||||||
|
target-version = "py311"
|
||||||
|
extend-exclude = ["scripts/benchmarks/tasks", "generated", "generated.*"]
|
||||||
|
|
||||||
|
[lint]
|
||||||
|
# Pin the rule set: newer ruff releases widen the default selection.
|
||||||
|
select = ["E4", "E7", "E9", "F"]
|
||||||
@@ -183,7 +183,8 @@ def codex_provenance(arm, args, cwd):
|
|||||||
server = AppServer(codex_env(arm, args), cwd)
|
server = AppServer(codex_env(arm, args), cwd)
|
||||||
try:
|
try:
|
||||||
config = server.call('config/read', {})['config']
|
config = server.call('config/read', {})['config']
|
||||||
listing = lambda: server.call('skills/list', {'cwds': [str(cwd)], 'forceReload': True})['data'][0]['skills']
|
def listing():
|
||||||
|
return server.call('skills/list', {'cwds': [str(cwd)], 'forceReload': True})['data'][0]['skills']
|
||||||
skills = listing()
|
skills = listing()
|
||||||
if arm == 'baseline':
|
if arm == 'baseline':
|
||||||
# Codex reads ~/.agents/skills from the real profile even with another CODEX_HOME; disable those skills there.
|
# Codex reads ~/.agents/skills from the real profile even with another CODEX_HOME; disable those skills there.
|
||||||
@@ -396,7 +397,8 @@ def summarize(results):
|
|||||||
category = json.loads(spec.read_text(encoding='utf-8')).get('category', '?') if spec.is_file() else '?'
|
category = json.loads(spec.read_text(encoding='utf-8')).get('category', '?') if spec.is_file() else '?'
|
||||||
groups.setdefault((category, result['client'], result['arm']), []).append(result)
|
groups.setdefault((category, result['client'], result['arm']), []).append(result)
|
||||||
for (category, client, arm), runs in sorted(groups.items()):
|
for (category, client, arm), runs in sorted(groups.items()):
|
||||||
median = lambda key: statistics.median(run[key] for run in runs)
|
def median(key):
|
||||||
|
return statistics.median(run[key] for run in runs)
|
||||||
lines.append(f'| {category} | {client} | {arm} | {len(runs)} | {sum(run["passed"] for run in runs) / len(runs):.0%} | '
|
lines.append(f'| {category} | {client} | {arm} | {len(runs)} | {sum(run["passed"] for run in runs) / len(runs):.0%} | '
|
||||||
f'{sum(run["first_try"] for run in runs) / len(runs):.0%} | {sum(run["rework_turns"] for run in runs)} | '
|
f'{sum(run["first_try"] for run in runs) / len(runs):.0%} | {sum(run["rework_turns"] for run in runs)} | '
|
||||||
f'{median("seconds"):.0f} | {median("input_tokens"):.0f} | {median("output_tokens"):.0f} | {median("tool_calls"):.0f} | '
|
f'{median("seconds"):.0f} | {median("input_tokens"):.0f} | {median("output_tokens"):.0f} | {median("tool_calls"):.0f} | '
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
|
import re
|
||||||
import sys
|
import sys
|
||||||
import tomllib
|
import tomllib
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@@ -89,6 +90,43 @@ def validate_agent_tools(package: Path) -> None:
|
|||||||
fail(f"{path}: unknown Claude tool name(s): {', '.join(unknown)}")
|
fail(f"{path}: unknown Claude tool name(s): {', '.join(unknown)}")
|
||||||
|
|
||||||
|
|
||||||
|
RULE_PATH = re.compile(r"`(rules/[A-Za-z0-9_./-]+\.md)`")
|
||||||
|
RULE_SKILL = re.compile(r"`(rules-[a-z0-9-]+)`")
|
||||||
|
REFERENCE_LINK = re.compile(r"`(references/[A-Za-z0-9_./-]+\.md)`")
|
||||||
|
|
||||||
|
|
||||||
|
def validate_rule_tree(codex_package: Path) -> None:
|
||||||
|
"""Keep the rule catalog routable: unique H1 titles, complete indexes, and no dangling links."""
|
||||||
|
rules = codex_package / "rules"
|
||||||
|
titles: dict[str, Path] = {}
|
||||||
|
for path in sorted(rules.rglob("*.md")):
|
||||||
|
first = next((line for line in path.read_text(encoding="utf-8-sig").splitlines() if line.strip()), "")
|
||||||
|
if not first.startswith("# "):
|
||||||
|
fail(f"{path}: a rule must start with a level-1 heading; it becomes the Claude skill description")
|
||||||
|
title = first[2:].strip().lower()
|
||||||
|
if title in titles:
|
||||||
|
fail(f"{path}: title duplicates {titles[title]}; rule titles must be unique")
|
||||||
|
titles[title] = path
|
||||||
|
for index in sorted(rules.rglob("index.md")):
|
||||||
|
linked = set(REFERENCE_LINK.findall(index.read_text(encoding="utf-8-sig")))
|
||||||
|
for link in linked:
|
||||||
|
if not (index.parent / link).is_file():
|
||||||
|
fail(f"{index}: links missing rule {link}")
|
||||||
|
for reference in sorted((index.parent / "references").glob("*.md")):
|
||||||
|
if f"references/{reference.name}" not in linked:
|
||||||
|
fail(f"{reference}: not linked from {index}")
|
||||||
|
for link in RULE_PATH.findall((codex_package / "AGENTS.md").read_text(encoding="utf-8-sig")):
|
||||||
|
if not (codex_package / link).is_file():
|
||||||
|
fail(f"{codex_package / 'AGENTS.md'}: routes to missing rule {link}")
|
||||||
|
|
||||||
|
|
||||||
|
def validate_rule_routing(claude_package: Path) -> None:
|
||||||
|
instructions = claude_package / "CLAUDE.md"
|
||||||
|
for skill in set(RULE_SKILL.findall(instructions.read_text(encoding="utf-8-sig"))):
|
||||||
|
if not (claude_package / "skills" / skill / "SKILL.md").is_file():
|
||||||
|
fail(f"{instructions}: routes to missing skill {skill}")
|
||||||
|
|
||||||
|
|
||||||
def main() -> int:
|
def main() -> int:
|
||||||
if len(sys.argv) != 3:
|
if len(sys.argv) != 3:
|
||||||
print("usage: validate-config.py <codex-toml> <claude-json>", file=sys.stderr)
|
print("usage: validate-config.py <codex-toml> <claude-json>", file=sys.stderr)
|
||||||
@@ -97,6 +135,8 @@ def main() -> int:
|
|||||||
validate_claude(Path(sys.argv[2]))
|
validate_claude(Path(sys.argv[2]))
|
||||||
validate_rule_skills(Path(sys.argv[2]).parent)
|
validate_rule_skills(Path(sys.argv[2]).parent)
|
||||||
validate_agent_tools(Path(sys.argv[2]).parent)
|
validate_agent_tools(Path(sys.argv[2]).parent)
|
||||||
|
validate_rule_tree(Path(sys.argv[1]).parent)
|
||||||
|
validate_rule_routing(Path(sys.argv[2]).parent)
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ $root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
|
|||||||
. (Join-Path $root 'scripts/lib/install-targets.ps1')
|
. (Join-Path $root 'scripts/lib/install-targets.ps1')
|
||||||
$selectedClient = $Client
|
$selectedClient = $Client
|
||||||
$selectedKey = $Key
|
$selectedKey = $Key
|
||||||
. (Join-Path $root 'scripts/lib/credentials.ps1')
|
. (Join-Path $root 'scripts/lib/with-credential.ps1')
|
||||||
$Client = $selectedClient
|
$Client = $selectedClient
|
||||||
$Key = $selectedKey
|
$Key = $selectedKey
|
||||||
|
|
||||||
@@ -28,8 +28,8 @@ if ($ValueFromStdin) {
|
|||||||
|
|
||||||
$bin = Join-Path $HomePath '.my-ai-configuration/bin'
|
$bin = Join-Path $HomePath '.my-ai-configuration/bin'
|
||||||
New-Item -ItemType Directory -Path $bin -Force | Out-Null
|
New-Item -ItemType Directory -Path $bin -Force | Out-Null
|
||||||
foreach ($source in @('credentials.ps1', 'with-credential.sh')) {
|
foreach ($source in @('with-credential.ps1', 'with-credential.sh')) {
|
||||||
$destination = Join-Path $bin $(if ($source -eq 'credentials.ps1') { 'with-credential.ps1' } else { $source })
|
$destination = Join-Path $bin $source
|
||||||
if (-not (Test-Path -LiteralPath $destination)) { Copy-Item (Join-Path $root "scripts/lib/$source") $destination }
|
if (-not (Test-Path -LiteralPath $destination)) { Copy-Item (Join-Path $root "scripts/lib/$source") $destination }
|
||||||
}
|
}
|
||||||
foreach ($target in $(if ($Client -eq 'Both') { @('Codex', 'Claude') } else { @($Client) })) {
|
foreach ($target in $(if ($Client -eq 'Both') { @('Codex', 'Claude') } else { @($Client) })) {
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ param(
|
|||||||
)
|
)
|
||||||
$ErrorActionPreference = 'Stop'
|
$ErrorActionPreference = 'Stop'
|
||||||
$root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
|
$root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
|
||||||
|
. (Join-Path $root 'shared/hooks/scripts/Resolve-Python.ps1')
|
||||||
. (Join-Path $root 'scripts/lib/install-targets.ps1')
|
. (Join-Path $root 'scripts/lib/install-targets.ps1')
|
||||||
|
|
||||||
if (-not $Client) { $Client = Read-InstallClient -Client $Client }
|
if (-not $Client) { $Client = Read-InstallClient -Client $Client }
|
||||||
@@ -19,7 +20,7 @@ foreach ($target in $(if ($Client -eq 'Both') { @('codex','claude') } else { @($
|
|||||||
$path = Join-Path $directory "$target.md"
|
$path = Join-Path $directory "$target.md"
|
||||||
$prefix = if ((Test-Path -LiteralPath $path) -and (Get-Item -LiteralPath $path).Length -gt 0 -and -not (Get-Content -LiteralPath $path -Raw).EndsWith([Environment]::NewLine)) { [Environment]::NewLine } else { '' }
|
$prefix = if ((Test-Path -LiteralPath $path) -and (Get-Item -LiteralPath $path).Length -gt 0 -and -not (Get-Content -LiteralPath $path -Raw).EndsWith([Environment]::NewLine)) { [Environment]::NewLine } else { '' }
|
||||||
[System.IO.File]::AppendAllText($path, $prefix + $Instruction.TrimEnd() + [Environment]::NewLine, [System.Text.UTF8Encoding]::new($false))
|
[System.IO.File]::AppendAllText($path, $prefix + $Instruction.TrimEnd() + [Environment]::NewLine, [System.Text.UTF8Encoding]::new($false))
|
||||||
& python (Join-Path $root 'scripts/lib/personal_instructions.py') --home $HomePath --client $target
|
Invoke-Python (Join-Path $root 'scripts/lib/personal_instructions.py') --home $HomePath --client $target
|
||||||
if ($LASTEXITCODE -ne 0) { throw 'Could not refresh the personal instruction rule.' }
|
if ($LASTEXITCODE -ne 0) { throw 'Could not refresh the personal instruction rule.' }
|
||||||
Write-Output "Instruction added for $target."
|
Write-Output "Instruction added for $target."
|
||||||
}
|
}
|
||||||
@@ -34,13 +34,14 @@ case "$home_path" in /*|[A-Za-z]:[\\/]*) ;; *) printf 'Home path must be absolut
|
|||||||
|
|
||||||
directory="$home_path/.my-ai-configuration/instructions"
|
directory="$home_path/.my-ai-configuration/instructions"
|
||||||
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
|
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
|
||||||
python_command=$(command -v python || command -v python3 || true)
|
# shellcheck source=../../shared/hooks/scripts/resolve-python.sh
|
||||||
[ -n "$python_command" ] || { printf 'Python is required to add instructions.\n' >&2; exit 1; }
|
. "$script_dir/../../shared/hooks/scripts/resolve-python.sh"
|
||||||
|
resolve_python || { python_missing_message >&2; exit 1; }
|
||||||
mkdir -p -- "$directory"
|
mkdir -p -- "$directory"
|
||||||
for target in "${targets[@]}"; do
|
for target in "${targets[@]}"; do
|
||||||
path="$directory/$target.md"
|
path="$directory/$target.md"
|
||||||
[ ! -s "$path" ] || [ "$(tail -c 1 -- "$path" | wc -l)" -eq 1 ] || printf '\n' >> "$path"
|
[ ! -s "$path" ] || [ "$(tail -c 1 -- "$path" | wc -l)" -eq 1 ] || printf '\n' >> "$path"
|
||||||
printf '%s\n' "$instruction" >> "$path"
|
printf '%s\n' "$instruction" >> "$path"
|
||||||
"$python_command" "$script_dir/../lib/personal_instructions.py" --home "$home_path" --client "$target"
|
run_python "$script_dir/../lib/personal_instructions.py" --home "$home_path" --client "$target"
|
||||||
printf 'Instruction added for %s.\n' "$target"
|
printf 'Instruction added for %s.\n' "$target"
|
||||||
done
|
done
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
$ErrorActionPreference = 'Stop'
|
$ErrorActionPreference = 'Stop'
|
||||||
$root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
|
$root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
|
||||||
& python (Join-Path $root 'scripts/benchmarks/ab.py') @args
|
. (Join-Path $root 'shared/hooks/scripts/Resolve-Python.ps1')
|
||||||
|
Invoke-Python (Join-Path $root 'scripts/benchmarks/ab.py') @args
|
||||||
exit $LASTEXITCODE
|
exit $LASTEXITCODE
|
||||||
@@ -1,4 +1,7 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)
|
root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)
|
||||||
exec python3 "$root/scripts/benchmarks/ab.py" "$@"
|
# shellcheck source=../../shared/hooks/scripts/resolve-python.sh
|
||||||
|
. "$root/shared/hooks/scripts/resolve-python.sh"
|
||||||
|
resolve_python || { python_missing_message >&2; exit 127; }
|
||||||
|
run_python "$root/scripts/benchmarks/ab.py" "$@"
|
||||||
+28
-31
@@ -2,12 +2,15 @@
|
|||||||
param([switch]$Summary)
|
param([switch]$Summary)
|
||||||
$ErrorActionPreference = 'Stop'
|
$ErrorActionPreference = 'Stop'
|
||||||
$root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
|
$root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
|
||||||
|
. (Join-Path $root 'shared/hooks/scripts/Resolve-Python.ps1')
|
||||||
$shared = Join-Path $root 'shared'
|
$shared = Join-Path $root 'shared'
|
||||||
$final = Join-Path $root 'generated'
|
$final = Join-Path $root 'generated'
|
||||||
# Keep the name short: it lengthens every generated path, and Windows PowerShell 5.1 fails beyond 260 characters.
|
# Keep the name short: it lengthens every generated path, and Windows PowerShell 5.1 fails beyond 260 characters.
|
||||||
$output = Join-Path $root ("generated.build-ps$PID-" + [Guid]::NewGuid().ToString('N').Substring(0, 6))
|
$output = Join-Path $root ("generated.build-ps$PID-" + [Guid]::NewGuid().ToString('N').Substring(0, 6))
|
||||||
# A trap covers the whole script scope, so every terminating error discards this run's tree.
|
# A trap covers the whole script scope, so every terminating error discards this run's tree.
|
||||||
trap { Remove-Item -LiteralPath $output -Recurse -Force -ErrorAction SilentlyContinue; break }
|
trap { Remove-Item -LiteralPath $output -Recurse -Force -ErrorAction SilentlyContinue; break }
|
||||||
|
# Fail early with an actionable message instead of a generic validation error after the build.
|
||||||
|
$null = Get-PythonCommand -Required
|
||||||
$sandboxSupported = [Environment]::OSVersion.Platform -eq [PlatformID]::Unix
|
$sandboxSupported = [Environment]::OSVersion.Platform -eq [PlatformID]::Unix
|
||||||
if ($sandboxSupported) {
|
if ($sandboxSupported) {
|
||||||
$kernel = (& uname -r 2>$null | Out-String).Trim()
|
$kernel = (& uname -r 2>$null | Out-String).Trim()
|
||||||
@@ -16,6 +19,21 @@ if ($sandboxSupported) {
|
|||||||
$claudeSandbox = if ($sandboxSupported) { '{"enabled": true, "allowUnsandboxedCommands": false, "failIfUnavailable": true, "network": {"allowedDomains": ["mcp.context7.com"]}}' } else { '{"enabled": false}' }
|
$claudeSandbox = if ($sandboxSupported) { '{"enabled": true, "allowUnsandboxedCommands": false, "failIfUnavailable": true, "network": {"allowedDomains": ["mcp.context7.com"]}}' } else { '{"enabled": false}' }
|
||||||
$pluginManifest = Join-Path $root 'adapters/plugins.tsv'
|
$pluginManifest = Join-Path $root 'adapters/plugins.tsv'
|
||||||
$capabilityManifest = Join-Path $root 'adapters/claude/capabilities.tsv'
|
$capabilityManifest = Join-Path $root 'adapters/claude/capabilities.tsv'
|
||||||
|
$placeholderManifest = Join-Path $root 'adapters/placeholders.tsv'
|
||||||
|
|
||||||
|
# Shell-specific template values live in one table shared with build.sh, so adding a hook or
|
||||||
|
# script means adding one row instead of editing both builds.
|
||||||
|
if (-not (Test-Path -LiteralPath $placeholderManifest)) { throw "Missing placeholder manifest: $placeholderManifest" }
|
||||||
|
$placeholders = @(Import-Csv -LiteralPath $placeholderManifest -Delimiter ([char]9))
|
||||||
|
foreach ($placeholder in $placeholders) {
|
||||||
|
if ($placeholder.placeholder -cnotmatch '^__[A-Z0-9_]+__$' -or [string]::IsNullOrEmpty($placeholder.powershell) -or [string]::IsNullOrEmpty($placeholder.bash)) {
|
||||||
|
throw "Invalid placeholder manifest row: $($placeholder.placeholder)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function Expand-ShellPlaceholders([string]$text, [string]$shell) {
|
||||||
|
foreach ($placeholder in $placeholders) { $text = $text.Replace($placeholder.placeholder, $placeholder.$shell) }
|
||||||
|
return $text
|
||||||
|
}
|
||||||
|
|
||||||
if (-not (Test-Path -LiteralPath $pluginManifest)) { throw "Missing plugin manifest: $pluginManifest" }
|
if (-not (Test-Path -LiteralPath $pluginManifest)) { throw "Missing plugin manifest: $pluginManifest" }
|
||||||
$pluginEntries = @(Import-Csv -LiteralPath $pluginManifest -Delimiter ([char]9))
|
$pluginEntries = @(Import-Csv -LiteralPath $pluginManifest -Delimiter ([char]9))
|
||||||
@@ -158,17 +176,11 @@ foreach ($shell in @('powershell','bash')) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$sharedTemplate = Get-Content (Join-Path $shared 'global-instructions.md') -Raw
|
|
||||||
$generalContent = Get-Content (Join-Path $shared 'rules/general.md') -Raw
|
$generalContent = Get-Content (Join-Path $shared 'rules/general.md') -Raw
|
||||||
$credentialHelperExtension = if ($shell -eq 'powershell') { 'ps1' } else { 'sh' }
|
$instructionsContent = Expand-ShellPlaceholders (Get-Content (Join-Path $shared 'global-instructions.md') -Raw) $shell
|
||||||
|
$instructionsContent = $instructionsContent.TrimEnd() + "`r`n`r`n---`r`n`r`n$generalContent"
|
||||||
$agentsContent = $sharedTemplate.Replace('__CLIENT__', 'codex').Replace('__SHELL__', $credentialHelperExtension)
|
Set-Content (Join-Path $output "codex-$shell/AGENTS.md") $instructionsContent -Encoding UTF8
|
||||||
$agentsContent = $agentsContent.TrimEnd() + "`r`n`r`n---`r`n`r`n$generalContent"
|
Set-Content (Join-Path $output "claude-$shell/CLAUDE.md") $instructionsContent -Encoding UTF8
|
||||||
Set-Content (Join-Path $output "codex-$shell/AGENTS.md") $agentsContent -Encoding UTF8
|
|
||||||
|
|
||||||
$claudeContent = $sharedTemplate.Replace('__CLIENT__', 'claude').Replace('__SHELL__', $credentialHelperExtension)
|
|
||||||
$claudeContent = $claudeContent.TrimEnd() + "`r`n`r`n---`r`n`r`n$generalContent"
|
|
||||||
Set-Content (Join-Path $output "claude-$shell/CLAUDE.md") $claudeContent -Encoding UTF8
|
|
||||||
|
|
||||||
Copy-Item (Join-Path $root 'adapters/codex/config/config.toml') (Join-Path $output "codex-$shell/config.toml") -Force
|
Copy-Item (Join-Path $root 'adapters/codex/config/config.toml') (Join-Path $output "codex-$shell/config.toml") -Force
|
||||||
Copy-Item (Join-Path $root 'adapters/claude/config/settings.json') (Join-Path $output "claude-$shell/settings.json") -Force
|
Copy-Item (Join-Path $root 'adapters/claude/config/settings.json') (Join-Path $output "claude-$shell/settings.json") -Force
|
||||||
@@ -185,9 +197,8 @@ foreach ($shell in @('powershell','bash')) {
|
|||||||
if ($client -eq 'codex') {
|
if ($client -eq 'codex') {
|
||||||
Set-Content (Join-Path $agentsOutput "$name.toml") "name = $(Quote-Toml $name)`r`ndescription = $(Quote-Toml $description)`r`ndeveloper_instructions = $(Quote-Toml $instructions)" -Encoding UTF8
|
Set-Content (Join-Path $agentsOutput "$name.toml") "name = $(Quote-Toml $name)`r`ndescription = $(Quote-Toml $description)`r`ndeveloper_instructions = $(Quote-Toml $instructions)" -Encoding UTF8
|
||||||
} else {
|
} else {
|
||||||
$shellTool = if ($shell -eq 'powershell') { 'PowerShell' } else { 'Bash' }
|
|
||||||
$tools = $agentTools[$name]
|
$tools = $agentTools[$name]
|
||||||
if ($tools) { $tools = $tools.Replace('__SHELL__', $shellTool) }
|
if ($tools) { $tools = Expand-ShellPlaceholders $tools $shell }
|
||||||
$frontmatter = "---`r`nname: $name`r`ndescription: $description`r`n"
|
$frontmatter = "---`r`nname: $name`r`ndescription: $description`r`n"
|
||||||
if ($tools) { $frontmatter += "tools: $tools`r`n" }
|
if ($tools) { $frontmatter += "tools: $tools`r`n" }
|
||||||
Set-Content (Join-Path $agentsOutput "$name.md") ($frontmatter + "---`r`n`r`n$instructions") -Encoding UTF8
|
Set-Content (Join-Path $agentsOutput "$name.md") ($frontmatter + "---`r`n`r`n$instructions") -Encoding UTF8
|
||||||
@@ -195,30 +206,16 @@ foreach ($shell in @('powershell','bash')) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach ($client in @('codex','claude')) {
|
foreach ($path in @((Join-Path $output "codex-$shell/config.toml"), (Join-Path $output "claude-$shell/settings.json"))) {
|
||||||
$file = if ($client -eq 'codex') { 'config.toml' } else { 'settings.json' }
|
$content = Expand-ShellPlaceholders (Get-Content -LiteralPath $path -Raw) $shell
|
||||||
$path = Join-Path $output "$client-$shell/$file"
|
# The sandbox depends on the build platform, not the shell, so it is not part of the placeholder table.
|
||||||
$command = if ($shell -eq 'powershell') { '__POWERSHELL_COMMAND__' } else { 'bash' }
|
$content = $content.Replace('__CLAUDE_SANDBOX__', $claudeSandbox)
|
||||||
$script = if ($shell -eq 'powershell') { 'flashbang.ps1' } else { 'flashbang.sh' }
|
|
||||||
$statusLineScript = if ($shell -eq 'powershell') { 'statusline.ps1' } else { 'statusline.sh' }
|
|
||||||
$content = Get-Content -LiteralPath $path -Raw
|
|
||||||
# Claude can offer both shell tools on Windows, so every package denies the destructive commands in both.
|
|
||||||
$denyRules = @('PowerShell(git reset --hard*)','PowerShell(git clean*)','PowerShell(Remove-Item *-Recurse*)','Bash(git reset --hard*)','Bash(git clean*)','Bash(rm -rf*)')
|
|
||||||
$denyRulesJson = ConvertTo-Json -InputObject $denyRules -Compress
|
|
||||||
$shellTool = if ($shell -eq 'powershell') { 'PowerShell' } else { 'Bash' }
|
|
||||||
$allowRulesJson = ConvertTo-Json -InputObject @('Agent', "$shellTool(mcporter call context7.*)") -Compress
|
|
||||||
$compactScript = if ($shell -eq 'powershell') { 'Record-Compact.ps1' } else { 'record-compact.sh' }
|
|
||||||
$pointerScript = if ($shell -eq 'powershell') { 'Show-SessionStatePointer.ps1' } else { 'show-session-state-pointer.sh' }
|
|
||||||
$qmdWarmScript = if ($shell -eq 'powershell') { 'Start-QmdWarm.ps1' } else { 'qmd-warm.sh' }
|
|
||||||
$correctionPromptScript = if ($shell -eq 'powershell') { 'Show-CorrectionPrompt.ps1' } else { 'show-correction-prompt.sh' }
|
|
||||||
$completionEvidenceScript = if ($shell -eq 'powershell') { 'Check-CompletionEvidence.ps1' } else { 'check-completion-evidence.sh' }
|
|
||||||
$content = $content.Replace('__HOOK_COMMAND__', $command).Replace('__POWERSHELL_HOOK_COMMAND__', $command).Replace('__HOOK_SCRIPT__', $script).Replace('__POWERSHELL_HOOK_SCRIPT__', $script).Replace('__COMPACT_SCRIPT__', $compactScript).Replace('__SESSION_POINTER_SCRIPT__', $pointerScript).Replace('__QMD_WARM_SCRIPT__', $qmdWarmScript).Replace('__CORRECTION_PROMPT_SCRIPT__', $correctionPromptScript).Replace('__COMPLETION_EVIDENCE_SCRIPT__', $completionEvidenceScript).Replace('__STATUSLINE_COMMAND__', $command).Replace('__STATUSLINE_SCRIPT__', $statusLineScript).Replace('__CLAUDE_SANDBOX__', $claudeSandbox).Replace('__CLAUDE_DENY_RULES__', $denyRulesJson).Replace('__CLAUDE_ALLOW_RULES__', $allowRulesJson)
|
|
||||||
Set-Content -LiteralPath $path -Value $content -Encoding UTF8
|
Set-Content -LiteralPath $path -Value $content -Encoding UTF8
|
||||||
}
|
}
|
||||||
|
|
||||||
$tomlPath = Join-Path $output "codex-$shell/config.toml"
|
$tomlPath = Join-Path $output "codex-$shell/config.toml"
|
||||||
$settingsPath = Join-Path $output "claude-$shell/settings.json"
|
$settingsPath = Join-Path $output "claude-$shell/settings.json"
|
||||||
& python (Join-Path $root 'scripts/checks/validate-config.py') $tomlPath $settingsPath
|
Invoke-Python (Join-Path $root 'scripts/checks/validate-config.py') $tomlPath $settingsPath
|
||||||
if ($LASTEXITCODE -ne 0) { throw "Generated configuration validation failed for $shell." }
|
if ($LASTEXITCODE -ne 0) { throw "Generated configuration validation failed for $shell." }
|
||||||
Test-CodexSchema $tomlPath
|
Test-CodexSchema $tomlPath
|
||||||
}
|
}
|
||||||
|
|||||||
+39
-60
@@ -9,6 +9,10 @@ while [ $# -gt 0 ]; do
|
|||||||
done
|
done
|
||||||
|
|
||||||
root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)
|
root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)
|
||||||
|
# shellcheck source=../../shared/hooks/scripts/resolve-python.sh
|
||||||
|
. "$root/shared/hooks/scripts/resolve-python.sh"
|
||||||
|
# Fail early with an actionable message instead of a generic validation error after the build.
|
||||||
|
resolve_python || { python_missing_message >&2; exit 1; }
|
||||||
shared="$root/shared"
|
shared="$root/shared"
|
||||||
final="$root/generated"
|
final="$root/generated"
|
||||||
sandbox_supported=false
|
sandbox_supported=false
|
||||||
@@ -27,6 +31,32 @@ sandbox='{"enabled": false}'
|
|||||||
[ "$sandbox_supported" != true ] || sandbox='{"enabled": true, "allowUnsandboxedCommands": false, "failIfUnavailable": true, "network": {"allowedDomains": ["mcp.context7.com"]}}'
|
[ "$sandbox_supported" != true ] || sandbox='{"enabled": true, "allowUnsandboxedCommands": false, "failIfUnavailable": true, "network": {"allowedDomains": ["mcp.context7.com"]}}'
|
||||||
plugin_manifest="$root/adapters/plugins.tsv"
|
plugin_manifest="$root/adapters/plugins.tsv"
|
||||||
capability_manifest="$root/adapters/claude/capabilities.tsv"
|
capability_manifest="$root/adapters/claude/capabilities.tsv"
|
||||||
|
placeholder_manifest="$root/adapters/placeholders.tsv"
|
||||||
|
|
||||||
|
# Shell-specific template values live in one table shared with build.ps1, so adding a hook or
|
||||||
|
# script means adding one row instead of editing both builds.
|
||||||
|
[ -f "$placeholder_manifest" ] || { printf 'Missing placeholder manifest: %s\n' "$placeholder_manifest" >&2; exit 1; }
|
||||||
|
placeholder_names=()
|
||||||
|
placeholder_powershell=()
|
||||||
|
placeholder_bash=()
|
||||||
|
while IFS=$'\t' read -r placeholder powershell_value bash_value; do
|
||||||
|
bash_value=${bash_value%$'\r'}
|
||||||
|
[ "$placeholder" != placeholder ] || continue
|
||||||
|
[ -n "$placeholder" ] || continue
|
||||||
|
[[ "$placeholder" =~ ^__[A-Z0-9_]+__$ ]] && [ -n "$powershell_value" ] && [ -n "$bash_value" ] || { printf 'Invalid placeholder manifest row: %s\n' "$placeholder" >&2; exit 1; }
|
||||||
|
placeholder_names+=("$placeholder")
|
||||||
|
placeholder_powershell+=("$powershell_value")
|
||||||
|
placeholder_bash+=("$bash_value")
|
||||||
|
done < "$placeholder_manifest"
|
||||||
|
|
||||||
|
expand_shell_placeholders() {
|
||||||
|
local text=$1 shell=$2 index value
|
||||||
|
for index in "${!placeholder_names[@]}"; do
|
||||||
|
if [ "$shell" = powershell ]; then value=${placeholder_powershell[$index]}; else value=${placeholder_bash[$index]}; fi
|
||||||
|
text=${text//"${placeholder_names[$index]}"/"$value"}
|
||||||
|
done
|
||||||
|
printf '%s' "$text"
|
||||||
|
}
|
||||||
|
|
||||||
[ -f "$plugin_manifest" ] || { printf 'Missing plugin manifest: %s\n' "$plugin_manifest" >&2; exit 1; }
|
[ -f "$plugin_manifest" ] || { printf 'Missing plugin manifest: %s\n' "$plugin_manifest" >&2; exit 1; }
|
||||||
awk -F '\t' 'NR == 1 { next } NF == 0 { next } $1 == "" || $3 == "" || $6 == "" { print "Invalid plugin manifest row." > "/dev/stderr"; exit 1 } seen[$1]++ { print "Duplicate plugin name in manifest: " $1 > "/dev/stderr"; exit 1 }' "$plugin_manifest"
|
awk -F '\t' 'NR == 1 { next } NF == 0 { next } $1 == "" || $3 == "" || $6 == "" { print "Invalid plugin manifest row." > "/dev/stderr"; exit 1 } seen[$1]++ { print "Duplicate plugin name in manifest: " $1 > "/dev/stderr"; exit 1 }' "$plugin_manifest"
|
||||||
@@ -151,18 +181,10 @@ while IFS= read -r rule_path; do
|
|||||||
fi
|
fi
|
||||||
done < <(find "$shared/rules" -mindepth 1 -type f -name '*.md' -printf '%P\n' | sort)
|
done < <(find "$shared/rules" -mindepth 1 -type f -name '*.md' -printf '%P\n' | sort)
|
||||||
|
|
||||||
shared_template=$(<"$shared/global-instructions.md")
|
instructions_content=$(expand_shell_placeholders "$(<"$shared/global-instructions.md")" "$shell")
|
||||||
general_content=$(<"$shared/rules/general.md")
|
general_content=$(<"$shared/rules/general.md")
|
||||||
credential_helper_extension='sh'
|
printf '%s\n\n---\n\n%s\n' "${instructions_content%$'\n'}" "$general_content" > "$output/codex-$shell/AGENTS.md"
|
||||||
[ "$shell" != powershell ] || credential_helper_extension='ps1'
|
printf '%s\n\n---\n\n%s\n' "${instructions_content%$'\n'}" "$general_content" > "$output/claude-$shell/CLAUDE.md"
|
||||||
|
|
||||||
agents_content=${shared_template//__CLIENT__/codex}
|
|
||||||
agents_content=${agents_content//__SHELL__/$credential_helper_extension}
|
|
||||||
printf '%s\n\n---\n\n%s\n' "${agents_content%$'\n'}" "$general_content" > "$output/codex-$shell/AGENTS.md"
|
|
||||||
|
|
||||||
claude_content=${shared_template//__CLIENT__/claude}
|
|
||||||
claude_content=${claude_content//__SHELL__/$credential_helper_extension}
|
|
||||||
printf '%s\n\n---\n\n%s\n' "${claude_content%$'\n'}" "$general_content" > "$output/claude-$shell/CLAUDE.md"
|
|
||||||
|
|
||||||
cp "$root/adapters/codex/config/config.toml" "$output/codex-$shell/config.toml"
|
cp "$root/adapters/codex/config/config.toml" "$output/codex-$shell/config.toml"
|
||||||
cp "$root/adapters/claude/config/settings.json" "$output/claude-$shell/settings.json"
|
cp "$root/adapters/claude/config/settings.json" "$output/claude-$shell/settings.json"
|
||||||
@@ -178,65 +200,22 @@ for client in codex claude; do
|
|||||||
if [ "$client" = codex ]; then
|
if [ "$client" = codex ]; then
|
||||||
printf 'name = %s\ndescription = %s\ndeveloper_instructions = %s\n' "$(quote_toml "$name")" "$(quote_toml "$description")" "$(quote_toml "$instructions")" > "$agents_output/$name.toml"
|
printf 'name = %s\ndescription = %s\ndeveloper_instructions = %s\n' "$(quote_toml "$name")" "$(quote_toml "$description")" "$(quote_toml "$instructions")" > "$agents_output/$name.toml"
|
||||||
else
|
else
|
||||||
tools=${agent_tools[$name]:-}
|
tools=$(expand_shell_placeholders "${agent_tools[$name]:-}" "$shell")
|
||||||
shell_tool=Bash
|
|
||||||
[ "$shell" != powershell ] || shell_tool=PowerShell
|
|
||||||
tools=${tools//__SHELL__/$shell_tool}
|
|
||||||
if [ -n "$tools" ]; then printf '%s\nname: %s\ndescription: %s\ntools: %s\n%s\n\n%s\n' '---' "$name" "$description" "$tools" '---' "$instructions" > "$agents_output/$name.md"; else printf '%s\nname: %s\ndescription: %s\n%s\n\n%s\n' '---' "$name" "$description" '---' "$instructions" > "$agents_output/$name.md"; fi
|
if [ -n "$tools" ]; then printf '%s\nname: %s\ndescription: %s\ntools: %s\n%s\n\n%s\n' '---' "$name" "$description" "$tools" '---' "$instructions" > "$agents_output/$name.md"; else printf '%s\nname: %s\ndescription: %s\n%s\n\n%s\n' '---' "$name" "$description" '---' "$instructions" > "$agents_output/$name.md"; fi
|
||||||
fi
|
fi
|
||||||
done
|
done
|
||||||
done
|
done
|
||||||
|
|
||||||
for client in codex claude; do
|
for path in "$output/codex-$shell/config.toml" "$output/claude-$shell/settings.json"; do
|
||||||
file=config.toml
|
content=$(expand_shell_placeholders "$(<"$path")" "$shell")
|
||||||
[ "$client" != claude ] || file=settings.json
|
# The sandbox depends on the build platform, not the shell, so it is not part of the placeholder table.
|
||||||
command=bash
|
content=${content//__CLAUDE_SANDBOX__/"$sandbox"}
|
||||||
script=flashbang.sh
|
|
||||||
statusline_script=statusline.sh
|
|
||||||
compact_script=record-compact.sh
|
|
||||||
pointer_script=show-session-state-pointer.sh
|
|
||||||
qmd_warm_script=qmd-warm.sh
|
|
||||||
correction_prompt_script=show-correction-prompt.sh
|
|
||||||
completion_evidence_script=check-completion-evidence.sh
|
|
||||||
if [ "$shell" = powershell ]; then
|
|
||||||
command='__POWERSHELL_COMMAND__'
|
|
||||||
script=flashbang.ps1
|
|
||||||
statusline_script=statusline.ps1
|
|
||||||
compact_script=Record-Compact.ps1
|
|
||||||
pointer_script=Show-SessionStatePointer.ps1
|
|
||||||
qmd_warm_script=Start-QmdWarm.ps1
|
|
||||||
correction_prompt_script=Show-CorrectionPrompt.ps1
|
|
||||||
completion_evidence_script=Check-CompletionEvidence.ps1
|
|
||||||
fi
|
|
||||||
path="$output/$client-$shell/$file"
|
|
||||||
content=$(<"$path")
|
|
||||||
# Claude can offer both shell tools on Windows, so every package denies the destructive commands in both.
|
|
||||||
deny_rules='["PowerShell(git reset --hard*)","PowerShell(git clean*)","PowerShell(Remove-Item *-Recurse*)","Bash(git reset --hard*)","Bash(git clean*)","Bash(rm -rf*)"]'
|
|
||||||
if [ "$shell" = powershell ]; then
|
|
||||||
allow_rules='["Agent","PowerShell(mcporter call context7.*)"]'
|
|
||||||
else
|
|
||||||
allow_rules='["Agent","Bash(mcporter call context7.*)"]'
|
|
||||||
fi
|
|
||||||
content=${content//__HOOK_COMMAND__/$command}
|
|
||||||
content=${content//__POWERSHELL_HOOK_COMMAND__/$command}
|
|
||||||
content=${content//__HOOK_SCRIPT__/$script}
|
|
||||||
content=${content//__POWERSHELL_HOOK_SCRIPT__/$script}
|
|
||||||
content=${content//__COMPACT_SCRIPT__/$compact_script}
|
|
||||||
content=${content//__SESSION_POINTER_SCRIPT__/$pointer_script}
|
|
||||||
content=${content//__QMD_WARM_SCRIPT__/$qmd_warm_script}
|
|
||||||
content=${content//__CORRECTION_PROMPT_SCRIPT__/$correction_prompt_script}
|
|
||||||
content=${content//__COMPLETION_EVIDENCE_SCRIPT__/$completion_evidence_script}
|
|
||||||
content=${content//__STATUSLINE_COMMAND__/$command}
|
|
||||||
content=${content//__STATUSLINE_SCRIPT__/$statusline_script}
|
|
||||||
content=${content//__CLAUDE_SANDBOX__/$sandbox}
|
|
||||||
content=${content//__CLAUDE_DENY_RULES__/$deny_rules}
|
|
||||||
content=${content//__CLAUDE_ALLOW_RULES__/$allow_rules}
|
|
||||||
printf '%s\n' "$content" > "$path"
|
printf '%s\n' "$content" > "$path"
|
||||||
done
|
done
|
||||||
|
|
||||||
toml_path="$output/codex-$shell/config.toml"
|
toml_path="$output/codex-$shell/config.toml"
|
||||||
settings_path="$output/claude-$shell/settings.json"
|
settings_path="$output/claude-$shell/settings.json"
|
||||||
python3 "$root/scripts/checks/validate-config.py" "$toml_path" "$settings_path"
|
run_python "$root/scripts/checks/validate-config.py" "$toml_path" "$settings_path"
|
||||||
if command -v codex >/dev/null; then
|
if command -v codex >/dev/null; then
|
||||||
schema_home=$(mktemp -d)
|
schema_home=$(mktemp -d)
|
||||||
cp "$toml_path" "$schema_home/config.toml"
|
cp "$toml_path" "$schema_home/config.toml"
|
||||||
|
|||||||
@@ -11,14 +11,12 @@ function Check-Version([string]$name, [string]$version, [version]$minimum) { if
|
|||||||
Check-Version 'PowerShell' $PSVersionTable.PSVersion.ToString() ([version]'5.1')
|
Check-Version 'PowerShell' $PSVersionTable.PSVersion.ToString() ([version]'5.1')
|
||||||
if (Get-Command jq -ErrorAction SilentlyContinue) { Pass 'jq available for Claude Bash status line' }
|
if (Get-Command jq -ErrorAction SilentlyContinue) { Pass 'jq available for Claude Bash status line' }
|
||||||
else { Write-Warning 'jq unavailable; Claude Bash status line is disabled' }
|
else { Write-Warning 'jq unavailable; Claude Bash status line is disabled' }
|
||||||
$pythonVersion = $null
|
. (Join-Path (Split-Path (Split-Path $PSScriptRoot -Parent) -Parent) 'shared/hooks/scripts/Resolve-Python.ps1')
|
||||||
foreach ($python in @('python', 'python3')) {
|
$python = Get-PythonCommand
|
||||||
if (-not (Get-Command $python -ErrorAction SilentlyContinue)) { continue }
|
if ($python) {
|
||||||
$candidate = & $python --version 2>$null
|
$pythonVersion = (& $python.Path @($python.Arguments) -c 'import platform; print(platform.python_version())' 2>$null | Out-String).Trim()
|
||||||
$pythonExitCode = $LASTEXITCODE
|
Check-Version 'Python' $pythonVersion ([version]'3.11')
|
||||||
if ($pythonExitCode -eq 0) { $pythonVersion = $candidate -replace '^Python\s+', ''; break }
|
} else { Fail (Get-PythonMissingMessage) }
|
||||||
}
|
|
||||||
if ($null -ne $pythonVersion) { Check-Version 'Python' $pythonVersion ([version]'3.11') } else { Fail 'Python 3.11 or newer is required' }
|
|
||||||
|
|
||||||
if ($failed) { Write-Error 'Capability check: FAIL'; exit 1 }
|
if ($failed) { Write-Error 'Capability check: FAIL'; exit 1 }
|
||||||
Write-Output 'Capability check: PASS'
|
Write-Output 'Capability check: PASS'
|
||||||
@@ -8,7 +8,7 @@ require_command() {
|
|||||||
if command -v "$1" >/dev/null 2>&1; then pass "$1 available"; else fail "$1 is required"; fi
|
if command -v "$1" >/dev/null 2>&1; then pass "$1 available"; else fail "$1 is required"; fi
|
||||||
}
|
}
|
||||||
version_at_least() {
|
version_at_least() {
|
||||||
awk -F. -v required="$2" 'BEGIN { split(required,r) } { split($1,v); if (v[1]+0 > r[1]+0 || (v[1]+0 == r[1]+0 && v[2]+0 >= r[2]+0)) exit 0; exit 1 }' <<<"$1"
|
awk -v required="$2" 'BEGIN { split(required,r,".") } { split($0,v,"."); if (v[1]+0 > r[1]+0 || (v[1]+0 == r[1]+0 && v[2]+0 >= r[2]+0)) exit 0; exit 1 }' <<<"$1"
|
||||||
}
|
}
|
||||||
check_version() {
|
check_version() {
|
||||||
local name=$1 version=$2 required=$3
|
local name=$1 version=$2 required=$3
|
||||||
@@ -18,11 +18,12 @@ check_version() {
|
|||||||
check_version Bash "${BASH_VERSINFO[0]}.${BASH_VERSINFO[1]}" 4.3
|
check_version Bash "${BASH_VERSINFO[0]}.${BASH_VERSINFO[1]}" 4.3
|
||||||
require_command awk; require_command sed; require_command sha256sum
|
require_command awk; require_command sed; require_command sha256sum
|
||||||
if command -v jq >/dev/null 2>&1; then pass 'jq available for Claude Bash status line'; else printf 'WARN jq unavailable; Claude Bash status line is disabled\n' >&2; fi
|
if command -v jq >/dev/null 2>&1; then pass 'jq available for Claude Bash status line'; else printf 'WARN jq unavailable; Claude Bash status line is disabled\n' >&2; fi
|
||||||
require_command python3
|
# shellcheck source=../../shared/hooks/scripts/resolve-python.sh
|
||||||
if command -v python3 >/dev/null 2>&1 && python3 -c 'import sys; raise SystemExit(sys.version_info < (3, 11))' >/dev/null 2>&1; then
|
. "$(dirname -- "${BASH_SOURCE[0]}")/../../shared/hooks/scripts/resolve-python.sh"
|
||||||
pass "Python $(python3 --version 2>&1 | awk '{print $2}') (minimum 3.11)"
|
if resolve_python; then
|
||||||
|
check_version Python "$(run_python -c 'import platform; print(platform.python_version())')" 3.11
|
||||||
else
|
else
|
||||||
fail 'Python 3.11 or newer is required'
|
fail "$(python_missing_message)"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [ "$failed" = true ]; then printf 'Capability check: FAIL\n' >&2; exit 1; fi
|
if [ "$failed" = true ]; then printf 'Capability check: FAIL\n' >&2; exit 1; fi
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
$ErrorActionPreference = 'Stop'
|
$ErrorActionPreference = 'Stop'
|
||||||
$root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
|
$root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
|
||||||
& python (Join-Path $root 'scripts/benchmarks/context.py') @args
|
. (Join-Path $root 'shared/hooks/scripts/Resolve-Python.ps1')
|
||||||
|
Invoke-Python (Join-Path $root 'scripts/benchmarks/context.py') @args
|
||||||
exit $LASTEXITCODE
|
exit $LASTEXITCODE
|
||||||
@@ -1,4 +1,7 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)
|
root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)
|
||||||
exec python3 "$root/scripts/benchmarks/context.py" "$@"
|
# shellcheck source=../../shared/hooks/scripts/resolve-python.sh
|
||||||
|
. "$root/shared/hooks/scripts/resolve-python.sh"
|
||||||
|
resolve_python || { python_missing_message >&2; exit 127; }
|
||||||
|
run_python "$root/scripts/benchmarks/context.py" "$@"
|
||||||
@@ -3,6 +3,7 @@ param([switch]$Summary)
|
|||||||
$ErrorActionPreference = 'Stop'
|
$ErrorActionPreference = 'Stop'
|
||||||
$root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
|
$root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
|
||||||
. (Join-Path $root 'scripts/lib/manifest.ps1')
|
. (Join-Path $root 'scripts/lib/manifest.ps1')
|
||||||
|
. (Join-Path $root 'shared/hooks/scripts/Resolve-Python.ps1')
|
||||||
$homePath = [Environment]::GetFolderPath('UserProfile')
|
$homePath = [Environment]::GetFolderPath('UserProfile')
|
||||||
if ([string]::IsNullOrWhiteSpace($homePath)) { $homePath = $HOME }
|
if ([string]::IsNullOrWhiteSpace($homePath)) { $homePath = $HOME }
|
||||||
$script:fail = $false
|
$script:fail = $false
|
||||||
@@ -37,6 +38,9 @@ foreach ($tool in @('codex','claude')) {
|
|||||||
} else { Result 'WARN' "$tool unavailable" }
|
} else { Result 'WARN' "$tool unavailable" }
|
||||||
}
|
}
|
||||||
if (Get-Command jq -ErrorAction SilentlyContinue) { Result 'PASS' 'jq available for Claude Bash status line' } else { Result 'WARN' 'jq unavailable; Claude Bash status line is disabled' }
|
if (Get-Command jq -ErrorAction SilentlyContinue) { Result 'PASS' 'jq available for Claude Bash status line' } else { Result 'WARN' 'jq unavailable; Claude Bash status line is disabled' }
|
||||||
|
$python = Get-PythonCommand
|
||||||
|
if ($python) { Result 'PASS' "Python available ($($python.Display))" }
|
||||||
|
else { Result 'FAIL' "$(Get-PythonMissingMessage) Without it, build validation fails and the completion-evidence, correction-prompt, and session-state hooks are silently skipped." }
|
||||||
|
|
||||||
$sourceAgentCount = @(Get-ChildItem (Join-Path $root 'shared/agents') -Directory -ErrorAction SilentlyContinue).Count
|
$sourceAgentCount = @(Get-ChildItem (Join-Path $root 'shared/agents') -Directory -ErrorAction SilentlyContinue).Count
|
||||||
$sourceSkillCount = @(Get-ChildItem (Join-Path $root 'shared/skills') -Filter 'SKILL.md' -Recurse -ErrorAction SilentlyContinue).Count
|
$sourceSkillCount = @(Get-ChildItem (Join-Path $root 'shared/skills') -Filter 'SKILL.md' -Recurse -ErrorAction SilentlyContinue).Count
|
||||||
@@ -71,8 +75,11 @@ if (Test-Path -LiteralPath $settingsPath) {
|
|||||||
}
|
}
|
||||||
$configTomlPath = Join-Path $homePath '.codex/config.toml'
|
$configTomlPath = Join-Path $homePath '.codex/config.toml'
|
||||||
if (Test-Path -LiteralPath $configTomlPath) {
|
if (Test-Path -LiteralPath $configTomlPath) {
|
||||||
$parseResult = Invoke-DoctorCommand -Command 'python' -Arguments @('-c', "import sys,tomllib,pathlib; tomllib.loads(pathlib.Path(sys.argv[1]).read_text(encoding='utf-8-sig'))", $configTomlPath)
|
if (-not $python) { Result 'WARN' 'Python unavailable; skipped installed .codex/config.toml TOML check' }
|
||||||
|
else {
|
||||||
|
$parseResult = Invoke-DoctorCommand -Command $python.Path -Arguments (@($python.Arguments) + @('-c', "import sys,tomllib,pathlib; tomllib.loads(pathlib.Path(sys.argv[1]).read_text(encoding='utf-8-sig'))", $configTomlPath))
|
||||||
if ($parseResult.ExitCode -eq 0) { Result 'PASS' 'installed .codex/config.toml parses as TOML' } else { Result 'FAIL' "installed .codex/config.toml is invalid TOML: $($parseResult.Output -join ' ')" }
|
if ($parseResult.ExitCode -eq 0) { Result 'PASS' 'installed .codex/config.toml parses as TOML' } else { Result 'FAIL' "installed .codex/config.toml is invalid TOML: $($parseResult.Output -join ' ')" }
|
||||||
|
}
|
||||||
if (Get-Command codex -ErrorAction SilentlyContinue) {
|
if (Get-Command codex -ErrorAction SilentlyContinue) {
|
||||||
$previousCodexHome = $env:CODEX_HOME
|
$previousCodexHome = $env:CODEX_HOME
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -10,6 +10,9 @@ while [ $# -gt 0 ]; do
|
|||||||
done
|
done
|
||||||
|
|
||||||
root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)
|
root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)
|
||||||
|
# shellcheck source=../../shared/hooks/scripts/resolve-python.sh
|
||||||
|
. "$root/shared/hooks/scripts/resolve-python.sh"
|
||||||
|
resolve_python || true
|
||||||
. "$root/scripts/lib/manifest.sh"
|
. "$root/scripts/lib/manifest.sh"
|
||||||
home_path=${HOME:?HOME is required}
|
home_path=${HOME:?HOME is required}
|
||||||
failed=false
|
failed=false
|
||||||
@@ -33,6 +36,11 @@ for tool in codex claude; do
|
|||||||
else result WARN "$tool unavailable"; fi
|
else result WARN "$tool unavailable"; fi
|
||||||
done
|
done
|
||||||
command -v jq >/dev/null && result PASS 'jq available for Claude Bash status line' || result WARN 'jq unavailable; Claude Bash status line is disabled'
|
command -v jq >/dev/null && result PASS 'jq available for Claude Bash status line' || result WARN 'jq unavailable; Claude Bash status line is disabled'
|
||||||
|
if resolve_python; then
|
||||||
|
result PASS "Python available ($(python_display))"
|
||||||
|
else
|
||||||
|
result FAIL "$(python_missing_message) Without it, build validation fails and the completion-evidence, correction-prompt, and session-state hooks are silently skipped."
|
||||||
|
fi
|
||||||
|
|
||||||
source_agent_count=$(find "$root/shared/agents" -mindepth 1 -maxdepth 1 -type d 2>/dev/null | wc -l)
|
source_agent_count=$(find "$root/shared/agents" -mindepth 1 -maxdepth 1 -type d 2>/dev/null | wc -l)
|
||||||
source_skill_count=$(find "$root/shared/skills" -name SKILL.md | wc -l)
|
source_skill_count=$(find "$root/shared/skills" -name SKILL.md | wc -l)
|
||||||
@@ -62,8 +70,8 @@ done
|
|||||||
if [ -f "$home_path/.claude/settings.json" ]; then
|
if [ -f "$home_path/.claude/settings.json" ]; then
|
||||||
if command -v jq >/dev/null 2>&1; then
|
if command -v jq >/dev/null 2>&1; then
|
||||||
if jq empty "$home_path/.claude/settings.json" >/dev/null 2>&1; then result PASS 'installed .claude/settings.json is valid JSON'; else result FAIL 'installed .claude/settings.json is not valid JSON'; fi
|
if jq empty "$home_path/.claude/settings.json" >/dev/null 2>&1; then result PASS 'installed .claude/settings.json is valid JSON'; else result FAIL 'installed .claude/settings.json is not valid JSON'; fi
|
||||||
elif command -v python3 >/dev/null 2>&1 && python3 --version >/dev/null 2>&1; then
|
elif resolve_python; then
|
||||||
if python3 -c 'import json,sys; json.load(open(sys.argv[1], encoding="utf-8"))' "$home_path/.claude/settings.json" 2>/dev/null; then
|
if run_python -c 'import json,sys; json.load(open(sys.argv[1], encoding="utf-8"))' "$home_path/.claude/settings.json" 2>/dev/null; then
|
||||||
result PASS 'installed .claude/settings.json is valid JSON'
|
result PASS 'installed .claude/settings.json is valid JSON'
|
||||||
else
|
else
|
||||||
result FAIL 'installed .claude/settings.json is not valid JSON'
|
result FAIL 'installed .claude/settings.json is not valid JSON'
|
||||||
@@ -71,7 +79,9 @@ if [ -f "$home_path/.claude/settings.json" ]; then
|
|||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
if [ -f "$home_path/.codex/config.toml" ]; then
|
if [ -f "$home_path/.codex/config.toml" ]; then
|
||||||
if python3 -c 'import sys,tomllib,pathlib; tomllib.loads(pathlib.Path(sys.argv[1]).read_text(encoding="utf-8-sig"))' "$home_path/.codex/config.toml"; then
|
if ! resolve_python; then
|
||||||
|
result WARN 'Python unavailable; skipped installed .codex/config.toml TOML check'
|
||||||
|
elif run_python -c 'import sys,tomllib,pathlib; tomllib.loads(pathlib.Path(sys.argv[1]).read_text(encoding="utf-8-sig"))' "$home_path/.codex/config.toml"; then
|
||||||
result PASS 'installed .codex/config.toml parses as TOML'
|
result PASS 'installed .codex/config.toml parses as TOML'
|
||||||
else
|
else
|
||||||
result FAIL 'installed .codex/config.toml is invalid TOML'
|
result FAIL 'installed .codex/config.toml is invalid TOML'
|
||||||
|
|||||||
@@ -2,11 +2,12 @@
|
|||||||
param([switch]$Summary)
|
param([switch]$Summary)
|
||||||
$ErrorActionPreference = 'Stop'
|
$ErrorActionPreference = 'Stop'
|
||||||
$root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
|
$root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
|
||||||
|
. (Join-Path $root 'shared/hooks/scripts/Resolve-Python.ps1')
|
||||||
$budgetScript = Join-Path $root 'scripts/lib/prompt-budget.py'
|
$budgetScript = Join-Path $root 'scripts/lib/prompt-budget.py'
|
||||||
$budgetArgs = @()
|
$budgetArgs = @()
|
||||||
if ($Summary) { $budgetArgs += '--summary' }
|
if ($Summary) { $budgetArgs += '--summary' }
|
||||||
& python $budgetScript @budgetArgs
|
Invoke-Python $budgetScript @budgetArgs
|
||||||
$budgetExit = $LASTEXITCODE
|
$budgetExit = $LASTEXITCODE
|
||||||
& python (Join-Path $root 'scripts/lib/prompt-inventory.py') --home ([Environment]::GetFolderPath('UserProfile'))
|
Invoke-Python (Join-Path $root 'scripts/lib/prompt-inventory.py') --home ([Environment]::GetFolderPath('UserProfile'))
|
||||||
if ($LASTEXITCODE -ne 0) { throw 'Prompt inventory failed.' }
|
if ($LASTEXITCODE -ne 0) { throw 'Prompt inventory failed.' }
|
||||||
exit $budgetExit
|
exit $budgetExit
|
||||||
@@ -3,9 +3,12 @@ set -euo pipefail
|
|||||||
summary=false
|
summary=false
|
||||||
for arg in "$@"; do case "$arg" in --summary) summary=true;; *) printf 'Unknown argument: %s\n' "$arg" >&2; exit 1;; esac; done
|
for arg in "$@"; do case "$arg" in --summary) summary=true;; *) printf 'Unknown argument: %s\n' "$arg" >&2; exit 1;; esac; done
|
||||||
root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)
|
root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)
|
||||||
|
# shellcheck source=../../shared/hooks/scripts/resolve-python.sh
|
||||||
|
. "$root/shared/hooks/scripts/resolve-python.sh"
|
||||||
|
resolve_python || true
|
||||||
budget_args=()
|
budget_args=()
|
||||||
[ "$summary" = false ] || budget_args+=(--summary)
|
[ "$summary" = false ] || budget_args+=(--summary)
|
||||||
budget_status=0
|
budget_status=0
|
||||||
python3 "$root/scripts/lib/prompt-budget.py" "${budget_args[@]}" || budget_status=$?
|
run_python "$root/scripts/lib/prompt-budget.py" "${budget_args[@]}" || budget_status=$?
|
||||||
python3 "$root/scripts/lib/prompt-inventory.py" --home "${HOME:?HOME is required}"
|
run_python "$root/scripts/lib/prompt-inventory.py" --home "${HOME:?HOME is required}"
|
||||||
exit "$budget_status"
|
exit "$budget_status"
|
||||||
@@ -8,7 +8,7 @@ $root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
|
|||||||
. (Join-Path $root 'scripts/lib/install-targets.ps1')
|
. (Join-Path $root 'scripts/lib/install-targets.ps1')
|
||||||
$selectedClient = $Client
|
$selectedClient = $Client
|
||||||
$selectedKey = $Key
|
$selectedKey = $Key
|
||||||
. (Join-Path $root 'scripts/lib/credentials.ps1')
|
. (Join-Path $root 'scripts/lib/with-credential.ps1')
|
||||||
$Client = $selectedClient
|
$Client = $selectedClient
|
||||||
$Key = $selectedKey
|
$Key = $selectedKey
|
||||||
|
|
||||||
|
|||||||
@@ -6,10 +6,11 @@ param(
|
|||||||
)
|
)
|
||||||
$ErrorActionPreference = 'Stop'
|
$ErrorActionPreference = 'Stop'
|
||||||
$root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
|
$root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
|
||||||
|
. (Join-Path $root 'shared/hooks/scripts/Resolve-Python.ps1')
|
||||||
. (Join-Path $root 'scripts/lib/install-targets.ps1')
|
. (Join-Path $root 'scripts/lib/install-targets.ps1')
|
||||||
|
|
||||||
if (-not $Client) { $Client = Read-InstallClient -Client $Client }
|
if (-not $Client) { $Client = Read-InstallClient -Client $Client }
|
||||||
if (-not $PSBoundParameters.ContainsKey('Instruction')) { $Instruction = Read-Host 'Instruction to remove' }
|
if (-not $PSBoundParameters.ContainsKey('Instruction')) { $Instruction = Read-Host 'Instruction to remove' }
|
||||||
if ([string]::IsNullOrWhiteSpace($Instruction) -or $Instruction.Length -gt 65536) { throw 'Instruction must contain between 1 and 65536 characters.' }
|
if ([string]::IsNullOrWhiteSpace($Instruction) -or $Instruction.Length -gt 65536) { throw 'Instruction must contain between 1 and 65536 characters.' }
|
||||||
& python (Join-Path $root 'scripts/lib/remove-instruction.py') --client $Client.ToLowerInvariant() --instruction $Instruction.TrimEnd() --home $HomePath
|
Invoke-Python (Join-Path $root 'scripts/lib/remove-instruction.py') --client $Client.ToLowerInvariant() --instruction $Instruction.TrimEnd() --home $HomePath
|
||||||
if ($LASTEXITCODE -ne 0) { throw 'Instruction removal failed.' }
|
if ($LASTEXITCODE -ne 0) { throw 'Instruction removal failed.' }
|
||||||
@@ -19,6 +19,7 @@ case "$client" in codex|Codex|claude|Claude|both|Both) ;; *) printf 'Unknown --c
|
|||||||
case "$home_path" in /*|[A-Za-z]:[\\/]*) ;; *) printf 'Home path must be absolute.\n' >&2; exit 1 ;; esac
|
case "$home_path" in /*|[A-Za-z]:[\\/]*) ;; *) printf 'Home path must be absolute.\n' >&2; exit 1 ;; esac
|
||||||
|
|
||||||
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
|
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
|
||||||
python_command=$(command -v python || command -v python3 || true)
|
# shellcheck source=../../shared/hooks/scripts/resolve-python.sh
|
||||||
[ -n "$python_command" ] || { printf 'Python is required to remove instructions.\n' >&2; exit 1; }
|
. "$script_dir/../../shared/hooks/scripts/resolve-python.sh"
|
||||||
"$python_command" "$script_dir/../lib/remove-instruction.py" --client "${client,,}" --instruction "$instruction" --home "$home_path"
|
resolve_python || { python_missing_message >&2; exit 1; }
|
||||||
|
run_python "$script_dir/../lib/remove-instruction.py" --client "${client,,}" --instruction "$instruction" --home "$home_path"
|
||||||
@@ -27,5 +27,7 @@ if ($Pointer) { $arguments += '--pointer' }
|
|||||||
if ($Reset) { $arguments += '--reset' }
|
if ($Reset) { $arguments += '--reset' }
|
||||||
$payload = $values | ConvertTo-Json -Depth 4 -Compress
|
$payload = $values | ConvertTo-Json -Depth 4 -Compress
|
||||||
$payload = [regex]::Replace($payload, '[^\x00-\x7F]', { param($match) '\u{0:x4}' -f [int][char]$match.Value })
|
$payload = [regex]::Replace($payload, '[^\x00-\x7F]', { param($match) '\u{0:x4}' -f [int][char]$match.Value })
|
||||||
$payload | & python @arguments
|
. (Join-Path $PSScriptRoot '../../shared/hooks/scripts/Resolve-Python.ps1')
|
||||||
|
$python = Get-PythonCommand -Required
|
||||||
|
$payload | & $python.Path @($python.Arguments) @arguments
|
||||||
exit $LASTEXITCODE
|
exit $LASTEXITCODE
|
||||||
@@ -1,6 +1,9 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)
|
root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)
|
||||||
|
# shellcheck source=../../shared/hooks/scripts/resolve-python.sh
|
||||||
|
. "$root/shared/hooks/scripts/resolve-python.sh"
|
||||||
|
resolve_python || true
|
||||||
arguments=()
|
arguments=()
|
||||||
if [ "${AI_TASK_GOAL+x}" = x ]; then arguments+=(--goal "$AI_TASK_GOAL"); fi
|
if [ "${AI_TASK_GOAL+x}" = x ]; then arguments+=(--goal "$AI_TASK_GOAL"); fi
|
||||||
python3 "$root/shared/hooks/scripts/session-state.py" "${arguments[@]}" "$@"
|
run_python "$root/shared/hooks/scripts/session-state.py" "${arguments[@]}" "$@"
|
||||||
@@ -2,10 +2,13 @@
|
|||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
[ "${AI_CONFIG_TELEMETRY:-1}" = 0 ] && exit 0
|
[ "${AI_CONFIG_TELEMETRY:-1}" = 0 ] && exit 0
|
||||||
root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd); dir="$root/.ai-session"; path="$dir/telemetry.jsonl"; mkdir -p "$dir"
|
root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd); dir="$root/.ai-session"; path="$dir/telemetry.jsonl"; mkdir -p "$dir"
|
||||||
|
# shellcheck source=../../shared/hooks/scripts/resolve-python.sh
|
||||||
|
. "$root/shared/hooks/scripts/resolve-python.sh"
|
||||||
|
resolve_python || true
|
||||||
action=${1:-record}; shift || true
|
action=${1:-record}; shift || true
|
||||||
case "$action" in
|
case "$action" in
|
||||||
rotate) [ -f "$path" ] && mv -f "$path" "$path.1"; exit 0;;
|
rotate) [ -f "$path" ] && mv -f "$path" "$path.1"; exit 0;;
|
||||||
summary) [ -f "$path" ] || { printf 'Telemetry: no events\n'; exit 0; }; python3 - "$path" <<'PY' || exit 0
|
summary) [ -f "$path" ] || { printf 'Telemetry: no events\n'; exit 0; }; run_python - "$path" <<'PY' || exit 0
|
||||||
import json,sys,statistics
|
import json,sys,statistics
|
||||||
rows=[]
|
rows=[]
|
||||||
for line in open(sys.argv[1],encoding='utf-8',errors='replace'):
|
for line in open(sys.argv[1],encoding='utf-8',errors='replace'):
|
||||||
@@ -20,7 +23,7 @@ PY
|
|||||||
exit 0;;
|
exit 0;;
|
||||||
record) event=${1:?event required}; shift;; *) printf 'Unknown action: %s\n' "$action" >&2; exit 1;;
|
record) event=${1:?event required}; shift;; *) printf 'Unknown action: %s\n' "$action" >&2; exit 1;;
|
||||||
esac
|
esac
|
||||||
python3 - "$path" "$event" "$@" <<'PY' || exit 0
|
run_python - "$path" "$event" "$@" <<'PY' || exit 0
|
||||||
import json,sys,datetime
|
import json,sys,datetime
|
||||||
path,event=sys.argv[1:3]; args=sys.argv[3:]
|
path,event=sys.argv[1:3]; args=sys.argv[3:]
|
||||||
record={'event':event,'timestamp':datetime.datetime.now(datetime.timezone.utc).isoformat()}
|
record={'event':event,'timestamp':datetime.datetime.now(datetime.timezone.utc).isoformat()}
|
||||||
|
|||||||
@@ -8,13 +8,17 @@ import tomllib
|
|||||||
from personal_instructions import CLIENT_FILES, render
|
from personal_instructions import CLIENT_FILES, render
|
||||||
|
|
||||||
|
|
||||||
|
# Hook scripts this configuration installs; merges replace these and keep any foreign hooks.
|
||||||
|
OWNED_HOOK_PATTERN = r'(?:flashbang|statusline|record-compact|session-state-pointer|qmd-warm|Start-QmdWarm|completion-?evidence|correction-?prompt|command-?safety)\.(?:ps1|sh)'
|
||||||
|
|
||||||
|
|
||||||
def is_flashbang(hook):
|
def is_flashbang(hook):
|
||||||
return any(re.search(r'(?:[/\\\s"\x27]|^)flashbang\.(?:ps1|sh)(?:[\s"\x27]|$)', str(hook.get(key, '')), re.I)
|
return any(re.search(r'(?:[/\\\s"\x27]|^)flashbang\.(?:ps1|sh)(?:[\s"\x27]|$)', str(hook.get(key, '')), re.I)
|
||||||
for key in ('command', 'command_windows'))
|
for key in ('command', 'command_windows'))
|
||||||
|
|
||||||
|
|
||||||
def is_qmd_warm(hook):
|
def is_qmd_warm(hook):
|
||||||
return any(re.search(r'(?:[/\\\s"\x27]|^)(?:qmd-warm\.sh|Start-QmdWarm\.ps1)(?:[\s"\x27]|$)', str(hook.get(key, '')), re.I)
|
return any(re.search(r'(?:[/\\\s"\x27]|^)(?:(?:start-)?qmd-warm\.sh|Start-QmdWarm\.ps1)(?:[\s"\x27]|$)', str(hook.get(key, '')), re.I)
|
||||||
for key in ('command', 'command_windows'))
|
for key in ('command', 'command_windows'))
|
||||||
|
|
||||||
|
|
||||||
@@ -108,7 +112,7 @@ def merge_json(current, managed):
|
|||||||
for key, value in managed.items():
|
for key, value in managed.items():
|
||||||
if key == 'hooks' and isinstance(value, dict) and isinstance(result.get(key), dict):
|
if key == 'hooks' and isinstance(value, dict) and isinstance(result.get(key), dict):
|
||||||
hooks = dict(result[key])
|
hooks = dict(result[key])
|
||||||
for event in set(value) | {'Stop', 'SessionStart', 'UserPromptSubmit'}:
|
for event in set(value) | {'Stop', 'SessionStart', 'UserPromptSubmit', 'PreToolUse'}:
|
||||||
groups = value.get(event, [])
|
groups = value.get(event, [])
|
||||||
old_groups = hooks.get(event, [])
|
old_groups = hooks.get(event, [])
|
||||||
if isinstance(groups, list) and isinstance(old_groups, list):
|
if isinstance(groups, list) and isinstance(old_groups, list):
|
||||||
@@ -118,7 +122,7 @@ def merge_json(current, managed):
|
|||||||
retained.append(group)
|
retained.append(group)
|
||||||
continue
|
continue
|
||||||
foreign = [hook for hook in group['hooks'] if not (isinstance(hook, dict) and re.search(
|
foreign = [hook for hook in group['hooks'] if not (isinstance(hook, dict) and re.search(
|
||||||
r'(?:flashbang|statusline|record-compact|session-state-pointer|qmd-warm|Start-QmdWarm|completion-?evidence|correction-?prompt)\.(?:ps1|sh)',
|
OWNED_HOOK_PATTERN,
|
||||||
str(hook.get('command', '')) + str(hook.get('command_windows', '')), re.I))]
|
str(hook.get('command', '')) + str(hook.get('command_windows', '')), re.I))]
|
||||||
if foreign:
|
if foreign:
|
||||||
retained.append(dict(group, hooks=foreign))
|
retained.append(dict(group, hooks=foreign))
|
||||||
@@ -167,7 +171,7 @@ def merge_toml(current_text, managed_text, statusline_enabled=True):
|
|||||||
managed_headers = {header for header, _ in managed_sections}
|
managed_headers = {header for header, _ in managed_sections}
|
||||||
extras = []
|
extras = []
|
||||||
fields_by_header = {}
|
fields_by_header = {}
|
||||||
owned_pattern = r'(?:flashbang|statusline|record-compact|session-state-pointer|qmd-warm|Start-QmdWarm|completion-?evidence|correction-?prompt)\.(?:ps1|sh)'
|
owned_pattern = OWNED_HOOK_PATTERN
|
||||||
for index, (header, block) in enumerate(current_sections):
|
for index, (header, block) in enumerate(current_sections):
|
||||||
plugin_table = re.match(r'^\[(?:plugins|marketplaces)(?:\.|\])', header)
|
plugin_table = re.match(r'^\[(?:plugins|marketplaces)(?:\.|\])', header)
|
||||||
array_table = header.startswith('[[')
|
array_table = header.startswith('[[')
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
# shellcheck disable=SC2154
|
# shellcheck disable=SC2154
|
||||||
|
# shellcheck source=../../shared/hooks/scripts/resolve-python.sh
|
||||||
|
. "$(dirname -- "${BASH_SOURCE[0]}")/../../shared/hooks/scripts/resolve-python.sh"
|
||||||
|
resolve_python || true
|
||||||
|
|
||||||
read_install_boolean() {
|
read_install_boolean() {
|
||||||
local prompt=$1 default=$2 hint=y/N answer
|
local prompt=$1 default=$2 hint=y/N answer
|
||||||
@@ -22,7 +25,7 @@ read_install_options() {
|
|||||||
semantic_retrieval=false
|
semantic_retrieval=false
|
||||||
local saved key value
|
local saved key value
|
||||||
if [ -f "$home_path/.my-ai-configuration/selection.json" ]; then
|
if [ -f "$home_path/.my-ai-configuration/selection.json" ]; then
|
||||||
if saved=$(python3 "$root/scripts/lib/selection-state.py" read --home "$home_path" --manifest "$root/adapters/plugins.tsv" --format tsv --allow-legacy); then
|
if saved=$(run_python "$root/scripts/lib/selection-state.py" read --home "$home_path" --manifest "$root/adapters/plugins.tsv" --format tsv --allow-legacy); then
|
||||||
while IFS=$'\t' read -r key value; do
|
while IFS=$'\t' read -r key value; do
|
||||||
value=${value%$'\r'}
|
value=${value%$'\r'}
|
||||||
case "$key" in flashbang) flashbang=$value ;; statusline) statusline=$value ;; semantic_retrieval) semantic_retrieval=$value ;; esac
|
case "$key" in flashbang) flashbang=$value ;; statusline) statusline=$value ;; semantic_retrieval) semantic_retrieval=$value ;; esac
|
||||||
|
|||||||
@@ -333,7 +333,8 @@ class Manager:
|
|||||||
if client == 'claude' and item.get('enabled') is False:
|
if client == 'claude' and item.get('enabled') is False:
|
||||||
self.command([client, 'plugin', 'enable', selector])
|
self.command([client, 'plugin', 'enable', selector])
|
||||||
if record is not None and item.get('version') is not None:
|
if record is not None and item.get('version') is not None:
|
||||||
record['version'] = item['version']; self.save()
|
record['version'] = item['version']
|
||||||
|
self.save()
|
||||||
return
|
return
|
||||||
if item is not None and client == 'claude':
|
if item is not None and client == 'claude':
|
||||||
self.command([client, 'plugin', 'marketplace', 'update', selector.rsplit('@', 1)[1]])
|
self.command([client, 'plugin', 'marketplace', 'update', selector.rsplit('@', 1)[1]])
|
||||||
@@ -343,7 +344,9 @@ class Manager:
|
|||||||
if record is not None:
|
if record is not None:
|
||||||
self.cache.pop(client, None)
|
self.cache.pop(client, None)
|
||||||
version = self.installed(client).get(selector, {}).get('version')
|
version = self.installed(client).get(selector, {}).get('version')
|
||||||
if version is not None: record['version'] = version; self.save()
|
if version is not None:
|
||||||
|
record['version'] = version
|
||||||
|
self.save()
|
||||||
return
|
return
|
||||||
marketplace = entry[client + '_marketplace']
|
marketplace = entry[client + '_marketplace']
|
||||||
if marketplace not in ('', '-', 'openai-curated-remote'):
|
if marketplace not in ('', '-', 'openai-curated-remote'):
|
||||||
@@ -363,7 +366,8 @@ class Manager:
|
|||||||
resolved_version = self.installed(client).get(selector, {}).get('version')
|
resolved_version = self.installed(client).get(selector, {}).get('version')
|
||||||
if record is None:
|
if record is None:
|
||||||
record = dict(client=client, name=entry['name'], kind='plugin', selector=selector, source=entry.get(client + '_marketplace', '-'))
|
record = dict(client=client, name=entry['name'], kind='plugin', selector=selector, source=entry.get(client + '_marketplace', '-'))
|
||||||
if resolved_version is not None: record['version'] = resolved_version
|
if resolved_version is not None:
|
||||||
|
record['version'] = resolved_version
|
||||||
self.state['resources'].append(record)
|
self.state['resources'].append(record)
|
||||||
self.save()
|
self.save()
|
||||||
self.cache[client][selector] = {'scope': 'user'}
|
self.cache[client][selector] = {'scope': 'user'}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
. (Join-Path $PSScriptRoot '../../shared/hooks/scripts/Resolve-Python.ps1')
|
||||||
function Get-ManagedManifestPath {
|
function Get-ManagedManifestPath {
|
||||||
param([Parameter(Mandatory=$true)][string]$Destination)
|
param([Parameter(Mandatory=$true)][string]$Destination)
|
||||||
return (Join-Path $Destination '.ai-config-manifest.tsv')
|
return (Join-Path $Destination '.ai-config-manifest.tsv')
|
||||||
@@ -117,7 +118,7 @@ function Invoke-InstallOptions {
|
|||||||
[System.IO.File]::WriteAllBytes($managedPath, $Managed)
|
[System.IO.File]::WriteAllBytes($managedPath, $Managed)
|
||||||
$Arguments += @('--managed', $managedPath)
|
$Arguments += @('--managed', $managedPath)
|
||||||
}
|
}
|
||||||
& python (Join-Path $PSScriptRoot 'install-options.py') @Arguments --output $outputPath
|
Invoke-Python (Join-Path $PSScriptRoot 'install-options.py') @Arguments --output $outputPath
|
||||||
if ($LASTEXITCODE -ne 0) { throw $ErrorMessage }
|
if ($LASTEXITCODE -ne 0) { throw $ErrorMessage }
|
||||||
return [System.IO.File]::ReadAllText($outputPath, (New-Object System.Text.UTF8Encoding($false)))
|
return [System.IO.File]::ReadAllText($outputPath, (New-Object System.Text.UTF8Encoding($false)))
|
||||||
} finally {
|
} finally {
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
|
# shellcheck source=../../shared/hooks/scripts/resolve-python.sh
|
||||||
|
. "$(dirname -- "${BASH_SOURCE[0]}")/../../shared/hooks/scripts/resolve-python.sh"
|
||||||
|
resolve_python || true
|
||||||
# Managed-file manifest: tracks every file this setup previously installed into a
|
# Managed-file manifest: tracks every file this setup previously installed into a
|
||||||
# destination so a later run can detect stale files (removed from the source) or
|
# destination so a later run can detect stale files (removed from the source) or
|
||||||
# locally modified files (changed on disk since the last install) without ever
|
# locally modified files (changed on disk since the last install) without ever
|
||||||
@@ -146,7 +149,7 @@ run_managed_sync() {
|
|||||||
local entries entry entry_action entry_path entry_backup entry_hash entry_target
|
local entries entry entry_action entry_path entry_backup entry_hash entry_target
|
||||||
local -a journal_lines
|
local -a journal_lines
|
||||||
# One stamp line, then one unit-separated line per file (an empty field must survive read).
|
# One stamp line, then one unit-separated line per file (an empty field must survive read).
|
||||||
entries=$(python3 -c '
|
entries=$(run_python -c '
|
||||||
import json, sys
|
import json, sys
|
||||||
journal = json.load(open(sys.argv[1], encoding="utf-8-sig"))
|
journal = json.load(open(sys.argv[1], encoding="utf-8-sig"))
|
||||||
lines = [str(journal["stamp"])]
|
lines = [str(journal["stamp"])]
|
||||||
@@ -211,12 +214,12 @@ sys.stdout.buffer.write(("\n".join(lines) + "\n").encode("utf-8"))
|
|||||||
content=${content%$'\034'}
|
content=${content%$'\034'}
|
||||||
needs_sub=false
|
needs_sub=false
|
||||||
if { [ "$flashbang_enabled" = false ] || [ "$statusline_enabled" = false ] || [ "$semantic_retrieval_enabled" = false ]; } && [[ "$relative" = settings.json || "$relative" = config.toml ]]; then
|
if { [ "$flashbang_enabled" = false ] || [ "$statusline_enabled" = false ] || [ "$semantic_retrieval_enabled" = false ]; } && [[ "$relative" = settings.json || "$relative" = config.toml ]]; then
|
||||||
content=$(python3 "$(dirname -- "${BASH_SOURCE[0]}")/install-options.py" filter --path "$source_file" --flashbang "$flashbang_enabled" --statusline "$statusline_enabled" --semantic-retrieval "$semantic_retrieval_enabled" && printf '\034') || return
|
content=$(run_python "$(dirname -- "${BASH_SOURCE[0]}")/install-options.py" filter --path "$source_file" --flashbang "$flashbang_enabled" --statusline "$statusline_enabled" --semantic-retrieval "$semantic_retrieval_enabled" && printf '\034') || return
|
||||||
content=${content%$'\034'}
|
content=${content%$'\034'}
|
||||||
needs_sub=true
|
needs_sub=true
|
||||||
fi
|
fi
|
||||||
if [[ "$relative" = CLAUDE.md || "$relative" = AGENTS.md ]] || { [ "$semantic_retrieval_enabled" = false ] && [ "$relative" = rules/general.md ]; }; then
|
if [[ "$relative" = CLAUDE.md || "$relative" = AGENTS.md ]] || { [ "$semantic_retrieval_enabled" = false ] && [ "$relative" = rules/general.md ]; }; then
|
||||||
content=$(python3 "$(dirname -- "${BASH_SOURCE[0]}")/install-options.py" filter-instructions --path "$source_file" --destination "$destination" --semantic-retrieval "$semantic_retrieval_enabled" && printf '\034') || return
|
content=$(run_python "$(dirname -- "${BASH_SOURCE[0]}")/install-options.py" filter-instructions --path "$source_file" --destination "$destination" --semantic-retrieval "$semantic_retrieval_enabled" && printf '\034') || return
|
||||||
content=${content%$'\034'}
|
content=${content%$'\034'}
|
||||||
needs_sub=true
|
needs_sub=true
|
||||||
fi
|
fi
|
||||||
@@ -234,12 +237,12 @@ sys.stdout.buffer.write(("\n".join(lines) + "\n").encode("utf-8"))
|
|||||||
new_hash=$(sha256_of_file "$source_file")
|
new_hash=$(sha256_of_file "$source_file")
|
||||||
fi
|
fi
|
||||||
if [ "$relative" = config.toml ] && [ -f "$target" ]; then
|
if [ "$relative" = config.toml ] && [ -f "$target" ]; then
|
||||||
content=$(printf '%s' "$content" | python3 "$(dirname -- "${BASH_SOURCE[0]}")/install-options.py" merge-toml --current "$target" --statusline "$statusline_enabled") || return
|
content=$(printf '%s' "$content" | run_python "$(dirname -- "${BASH_SOURCE[0]}")/install-options.py" merge-toml --current "$target" --statusline "$statusline_enabled") || return
|
||||||
needs_sub=true
|
needs_sub=true
|
||||||
new_hash=$(sha256_of_string "$content")
|
new_hash=$(sha256_of_string "$content")
|
||||||
fi
|
fi
|
||||||
if [ "$relative" = settings.json ] && [ -f "$target" ]; then
|
if [ "$relative" = settings.json ] && [ -f "$target" ]; then
|
||||||
content=$(printf '%s' "$content" | python3 "$(dirname -- "${BASH_SOURCE[0]}")/install-options.py" merge-json --current "$target") || return
|
content=$(printf '%s' "$content" | run_python "$(dirname -- "${BASH_SOURCE[0]}")/install-options.py" merge-json --current "$target") || return
|
||||||
needs_sub=true
|
needs_sub=true
|
||||||
new_hash=$(sha256_of_string "$content")
|
new_hash=$(sha256_of_string "$content")
|
||||||
fi
|
fi
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
. (Join-Path $PSScriptRoot '../../shared/hooks/scripts/Resolve-Python.ps1')
|
||||||
function Invoke-PluginCommand {
|
function Invoke-PluginCommand {
|
||||||
param(
|
param(
|
||||||
[Parameter(Mandatory=$true)][string]$Command,
|
[Parameter(Mandatory=$true)][string]$Command,
|
||||||
@@ -161,7 +162,7 @@ function Invoke-ManagedExtensions {
|
|||||||
if ($Update) { $arguments += '--update' }
|
if ($Update) { $arguments += '--update' }
|
||||||
if ($Summary) { $arguments += '--summary' }
|
if ($Summary) { $arguments += '--summary' }
|
||||||
if ($PSBoundParameters.ContainsKey('Entries')) { $arguments += '--selected'; $arguments += @($Entries | ForEach-Object { $_.name }) }
|
if ($PSBoundParameters.ContainsKey('Entries')) { $arguments += '--selected'; $arguments += @($Entries | ForEach-Object { $_.name }) }
|
||||||
& python @arguments
|
Invoke-Python @arguments
|
||||||
if ($LASTEXITCODE -ne 0) { throw 'Managed extension reconciliation failed.' }
|
if ($LASTEXITCODE -ne 0) { throw 'Managed extension reconciliation failed.' }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
|
# shellcheck source=../../shared/hooks/scripts/resolve-python.sh
|
||||||
|
. "$(dirname -- "${BASH_SOURCE[0]}")/../../shared/hooks/scripts/resolve-python.sh"
|
||||||
|
resolve_python || true
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
plugin_installed() {
|
plugin_installed() {
|
||||||
@@ -6,7 +9,7 @@ plugin_installed() {
|
|||||||
local inventory
|
local inventory
|
||||||
command -v "$client" >/dev/null 2>&1 || return 1
|
command -v "$client" >/dev/null 2>&1 || return 1
|
||||||
inventory=$("$client" plugin list --json) || return 2
|
inventory=$("$client" plugin list --json) || return 2
|
||||||
printf '%s' "$inventory" | python3 -c '
|
printf '%s' "$inventory" | run_python -c '
|
||||||
import json, sys
|
import json, sys
|
||||||
try:
|
try:
|
||||||
client, plugin = sys.argv[1:]
|
client, plugin = sys.argv[1:]
|
||||||
@@ -70,7 +73,7 @@ mcporter_server_installed() {
|
|||||||
local path="$1/.mcporter/mcporter.json" server=$2 url=$3
|
local path="$1/.mcporter/mcporter.json" server=$2 url=$3
|
||||||
if [ -L "$1/.mcporter" ] || [ -L "$path" ]; then printf 'MCPorter configuration path contains a link.\n' >&2; return 2; fi
|
if [ -L "$1/.mcporter" ] || [ -L "$path" ]; then printf 'MCPorter configuration path contains a link.\n' >&2; return 2; fi
|
||||||
[ -f "$path" ] || return 1
|
[ -f "$path" ] || return 1
|
||||||
python3 -c '
|
run_python -c '
|
||||||
import json, sys
|
import json, sys
|
||||||
try:
|
try:
|
||||||
with open(sys.argv[1], encoding="utf-8-sig") as stream:
|
with open(sys.argv[1], encoding="utf-8-sig") as stream:
|
||||||
@@ -193,7 +196,7 @@ managed_extensions() {
|
|||||||
local -n extension_names_ref=$selected_name
|
local -n extension_names_ref=$selected_name
|
||||||
arguments+=(--selected "${extension_names_ref[@]}")
|
arguments+=(--selected "${extension_names_ref[@]}")
|
||||||
fi
|
fi
|
||||||
python3 "${arguments[@]}"
|
run_python "${arguments[@]}"
|
||||||
}
|
}
|
||||||
|
|
||||||
sync_configured_plugins() {
|
sync_configured_plugins() {
|
||||||
|
|||||||
+3
-2
@@ -1,9 +1,10 @@
|
|||||||
|
. (Join-Path $PSScriptRoot '../../shared/hooks/scripts/Resolve-Python.ps1')
|
||||||
function Sync-Qmd {
|
function Sync-Qmd {
|
||||||
param([Parameter(Mandatory=$true)][string]$RepositoryRoot,[Parameter(Mandatory=$true)][string]$HomePath,[ValidateSet('Codex','Claude','Both')][Parameter(Mandatory=$true)][string]$Client,[Parameter(Mandatory=$true)][bool]$Enabled,[switch]$DryRun,[switch]$Update,[switch]$Summary)
|
param([Parameter(Mandatory=$true)][string]$RepositoryRoot,[Parameter(Mandatory=$true)][string]$HomePath,[ValidateSet('Codex','Claude','Both')][Parameter(Mandatory=$true)][string]$Client,[Parameter(Mandatory=$true)][bool]$Enabled,[switch]$DryRun,[switch]$Update,[switch]$Summary)
|
||||||
$arguments = @((Join-Path $PSScriptRoot 'qmd.py'), 'sync', '--root', $RepositoryRoot, '--home', $HomePath, '--client', $Client.ToLowerInvariant(), '--enabled', $Enabled.ToString().ToLowerInvariant())
|
$arguments = @((Join-Path $PSScriptRoot 'qmd.py'), 'sync', '--root', $RepositoryRoot, '--home', $HomePath, '--client', $Client.ToLowerInvariant(), '--enabled', $Enabled.ToString().ToLowerInvariant())
|
||||||
if ($DryRun) { $arguments += '--dry-run' }; if ($Update) { $arguments += '--update' }
|
if ($DryRun) { $arguments += '--dry-run' }; if ($Update) { $arguments += '--update' }
|
||||||
if ($Summary) { $arguments += '--summary' }
|
if ($Summary) { $arguments += '--summary' }
|
||||||
& python @arguments
|
Invoke-Python @arguments
|
||||||
if ($LASTEXITCODE -ne 0) { throw 'QMD local search reconciliation failed.' }
|
if ($LASTEXITCODE -ne 0) { throw 'QMD local search reconciliation failed.' }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -11,7 +12,7 @@ function Test-QmdDevice {
|
|||||||
param([Parameter(Mandatory=$true)][string]$RepositoryRoot,[Parameter(Mandatory=$true)][string]$HomePath,[switch]$Summary)
|
param([Parameter(Mandatory=$true)][string]$RepositoryRoot,[Parameter(Mandatory=$true)][string]$HomePath,[switch]$Summary)
|
||||||
$arguments = @((Join-Path $PSScriptRoot 'qmd.py'), 'benchmark', '--root', $RepositoryRoot, '--home', $HomePath)
|
$arguments = @((Join-Path $PSScriptRoot 'qmd.py'), 'benchmark', '--root', $RepositoryRoot, '--home', $HomePath)
|
||||||
if ($Summary) { $arguments += '--summary' }
|
if ($Summary) { $arguments += '--summary' }
|
||||||
& python @arguments | Write-Host
|
Invoke-Python @arguments | Write-Host
|
||||||
if ($LASTEXITCODE -eq 0) { return $true }
|
if ($LASTEXITCODE -eq 0) { return $true }
|
||||||
if ($LASTEXITCODE -eq 2) { return $false }
|
if ($LASTEXITCODE -eq 2) { return $false }
|
||||||
throw 'QMD benchmark failed.'
|
throw 'QMD benchmark failed.'
|
||||||
|
|||||||
+5
-2
@@ -1,4 +1,7 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
|
# shellcheck source=../../shared/hooks/scripts/resolve-python.sh
|
||||||
|
. "$(dirname -- "${BASH_SOURCE[0]}")/../../shared/hooks/scripts/resolve-python.sh"
|
||||||
|
resolve_python || true
|
||||||
|
|
||||||
sync_qmd() {
|
sync_qmd() {
|
||||||
local root=$1 client=$2 home_path=$3 enabled=$4 dry_run=$5 update=$6 summary=${7:-false}
|
local root=$1 client=$2 home_path=$3 enabled=$4 dry_run=$5 update=$6 summary=${7:-false}
|
||||||
@@ -6,7 +9,7 @@ sync_qmd() {
|
|||||||
[ "$dry_run" != true ] || arguments+=(--dry-run)
|
[ "$dry_run" != true ] || arguments+=(--dry-run)
|
||||||
[ "$update" != true ] || arguments+=(--update)
|
[ "$update" != true ] || arguments+=(--update)
|
||||||
[ "$summary" != true ] || arguments+=(--summary)
|
[ "$summary" != true ] || arguments+=(--summary)
|
||||||
python3 "${arguments[@]}"
|
run_python "${arguments[@]}"
|
||||||
}
|
}
|
||||||
|
|
||||||
test_qmd_device() {
|
test_qmd_device() {
|
||||||
@@ -14,7 +17,7 @@ test_qmd_device() {
|
|||||||
local arguments=("$root/scripts/lib/qmd.py" benchmark --root "$root" --home "$home_path")
|
local arguments=("$root/scripts/lib/qmd.py" benchmark --root "$root" --home "$home_path")
|
||||||
[ "$summary" != true ] || arguments+=(--summary)
|
[ "$summary" != true ] || arguments+=(--summary)
|
||||||
local status
|
local status
|
||||||
if python3 "${arguments[@]}" >&2; then return 0; else status=$?; fi
|
if run_python "${arguments[@]}" >&2; then return 0; else status=$?; fi
|
||||||
[ "$status" -eq 2 ] && return 1
|
[ "$status" -eq 2 ] && return 1
|
||||||
return 2
|
return 2
|
||||||
}
|
}
|
||||||
@@ -1,8 +1,9 @@
|
|||||||
|
. (Join-Path $PSScriptRoot '../../shared/hooks/scripts/Resolve-Python.ps1')
|
||||||
function Read-UpdateSelection {
|
function Read-UpdateSelection {
|
||||||
param([string]$HomePath, [string]$RepositoryRoot, [switch]$AllowLegacy)
|
param([string]$HomePath, [string]$RepositoryRoot, [switch]$AllowLegacy)
|
||||||
$arguments = @((Join-Path $PSScriptRoot 'selection-state.py'), 'read', '--home', $HomePath, '--manifest', (Join-Path $RepositoryRoot 'adapters/plugins.tsv'))
|
$arguments = @((Join-Path $PSScriptRoot 'selection-state.py'), 'read', '--home', $HomePath, '--manifest', (Join-Path $RepositoryRoot 'adapters/plugins.tsv'))
|
||||||
if ($AllowLegacy) { $arguments += '--allow-legacy' }
|
if ($AllowLegacy) { $arguments += '--allow-legacy' }
|
||||||
$output = & python @arguments
|
$output = Invoke-Python @arguments
|
||||||
if ($LASTEXITCODE -ne 0) { throw 'Could not load the saved selection.' }
|
if ($LASTEXITCODE -ne 0) { throw 'Could not load the saved selection.' }
|
||||||
return ($output | Out-String | ConvertFrom-Json)
|
return ($output | Out-String | ConvertFrom-Json)
|
||||||
}
|
}
|
||||||
@@ -14,6 +15,6 @@ function Save-UpdateSelection {
|
|||||||
$arguments += @($Plugins.Selected | ForEach-Object { $_.name })
|
$arguments += @($Plugins.Selected | ForEach-Object { $_.name })
|
||||||
$arguments += '--deselected'
|
$arguments += '--deselected'
|
||||||
$arguments += @($Plugins.Deselected | ForEach-Object { $_.name })
|
$arguments += @($Plugins.Deselected | ForEach-Object { $_.name })
|
||||||
& python @arguments
|
Invoke-Python @arguments
|
||||||
if ($LASTEXITCODE -ne 0) { throw 'Could not save the selection.' }
|
if ($LASTEXITCODE -ne 0) { throw 'Could not save the selection.' }
|
||||||
}
|
}
|
||||||
@@ -1,9 +1,12 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
# shellcheck disable=SC2154
|
# shellcheck disable=SC2154
|
||||||
|
# shellcheck source=../../shared/hooks/scripts/resolve-python.sh
|
||||||
|
. "$(dirname -- "${BASH_SOURCE[0]}")/../../shared/hooks/scripts/resolve-python.sh"
|
||||||
|
resolve_python || true
|
||||||
|
|
||||||
read_update_selection() {
|
read_update_selection() {
|
||||||
local saved key value
|
local saved key value
|
||||||
saved=$(python3 "$root/scripts/lib/selection-state.py" read --home "$home_path" --manifest "$root/adapters/plugins.tsv" --format tsv) || return
|
saved=$(run_python "$root/scripts/lib/selection-state.py" read --home "$home_path" --manifest "$root/adapters/plugins.tsv" --format tsv) || return
|
||||||
selected_plugins=()
|
selected_plugins=()
|
||||||
deselected_plugins=()
|
deselected_plugins=()
|
||||||
while IFS=$'\t' read -r key value; do
|
while IFS=$'\t' read -r key value; do
|
||||||
@@ -21,7 +24,7 @@ read_update_selection() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
save_update_selection() {
|
save_update_selection() {
|
||||||
python3 "$root/scripts/lib/selection-state.py" write --home "$home_path" --manifest "$root/adapters/plugins.tsv" \
|
run_python "$root/scripts/lib/selection-state.py" write --home "$home_path" --manifest "$root/adapters/plugins.tsv" \
|
||||||
--shell "$shell" --client "$client" --flashbang "$flashbang" --statusline "${statusline:-true}" --semantic-retrieval "${semantic_retrieval:-false}" \
|
--shell "$shell" --client "$client" --flashbang "$flashbang" --statusline "${statusline:-true}" --semantic-retrieval "${semantic_retrieval:-false}" \
|
||||||
--selected "${selected_plugins[@]}" --deselected "${deselected_plugins[@]}"
|
--selected "${selected_plugins[@]}" --deselected "${deselected_plugins[@]}"
|
||||||
}
|
}
|
||||||
File renamed without changes.
@@ -7,7 +7,7 @@ shift 2
|
|||||||
[ $# -gt 0 ] || { printf 'Child command is required.\n' >&2; exit 1; }
|
[ $# -gt 0 ] || { printf 'Child command is required.\n' >&2; exit 1; }
|
||||||
|
|
||||||
case "$client" in codex|Codex) client=Codex ;; claude|Claude) client=Claude ;; *) printf 'Unknown client: %s\n' "$client" >&2; exit 1 ;; esac
|
case "$client" in codex|Codex) client=Codex ;; claude|Claude) client=Claude ;; *) printf 'Unknown client: %s\n' "$client" >&2; exit 1 ;; esac
|
||||||
case "$key" in [A-Za-z_][A-Za-z0-9_]* ) ;; *) printf 'Credential key must be an environment-variable-compatible name.\n' >&2; exit 1 ;; esac
|
[[ "$key" =~ ^[A-Za-z_][A-Za-z0-9_]{0,127}$ ]] || { printf 'Credential key must be an environment-variable-compatible name.\n' >&2; exit 1; }
|
||||||
|
|
||||||
powershell_command=$(command -v powershell.exe || command -v powershell || command -v pwsh || true)
|
powershell_command=$(command -v powershell.exe || command -v powershell || command -v pwsh || true)
|
||||||
[ -n "$powershell_command" ] || { printf 'PowerShell is required to read the Windows credential store.\n' >&2; exit 1; }
|
[ -n "$powershell_command" ] || { printf 'PowerShell is required to read the Windows credential store.\n' >&2; exit 1; }
|
||||||
|
|||||||
@@ -1,11 +1,34 @@
|
|||||||
[CmdletBinding()]
|
[CmdletBinding()]
|
||||||
param([switch]$Summary)
|
param([switch]$Summary)
|
||||||
|
# Checks that Python resolution skips a PATH entry that cannot run Python (such as the Windows
|
||||||
|
# Store app execution alias) and that check-capabilities reports the resolved interpreter.
|
||||||
$ErrorActionPreference = 'Stop'
|
$ErrorActionPreference = 'Stop'
|
||||||
$root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
|
$root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
|
||||||
$content = Get-Content (Join-Path $root 'scripts/commands/check-capabilities.ps1') -Raw
|
$stubs = Join-Path ([System.IO.Path]::GetTempPath()) ('capabilities-' + [Guid]::NewGuid().ToString('N'))
|
||||||
|
New-Item $stubs -ItemType Directory | Out-Null
|
||||||
|
$previousPath = $env:PATH
|
||||||
|
try {
|
||||||
|
$onWindows = [Environment]::OSVersion.Platform -eq [PlatformID]::Win32NT
|
||||||
|
# python imitates the Store alias: it is on PATH but only prints an install hint.
|
||||||
|
if ($onWindows) {
|
||||||
|
Set-Content (Join-Path $stubs 'python.cmd') "@echo Python was not found; run without arguments to install from the Microsoft Store 1>&2`r`n@exit /b 9009" -Encoding ASCII
|
||||||
|
Set-Content (Join-Path $stubs 'python3.cmd') "@if `"%~1`"==`"-c`" echo 3.12.0`r`n@exit /b 0" -Encoding ASCII
|
||||||
|
} else {
|
||||||
|
Set-Content (Join-Path $stubs 'python') "#!/bin/sh`necho 'Python was not found' >&2`nexit 9009`n" -NoNewline
|
||||||
|
Set-Content (Join-Path $stubs 'python3') "#!/bin/sh`nfor arg in `"`$@`"; do [ `"`$arg`" != -c ] || { echo 3.12.0; exit 0; }; done`nexit 0`n" -NoNewline
|
||||||
|
& chmod +x (Join-Path $stubs 'python') (Join-Path $stubs 'python3')
|
||||||
|
}
|
||||||
|
$env:PATH = $stubs + [System.IO.Path]::PathSeparator + $previousPath
|
||||||
|
$hostPath = (Get-Process -Id $PID).Path
|
||||||
|
|
||||||
if ($content -match '(?s)\(& \$python --version.*?Select-Object.*?\).*?\$LASTEXITCODE') {
|
$resolved = & $hostPath -NoProfile -ExecutionPolicy Bypass -Command ". '$root/shared/hooks/scripts/Resolve-Python.ps1'; (Get-PythonCommand).Display"
|
||||||
throw 'Python capability detection must not read $LASTEXITCODE after a pipeline.'
|
if ("$resolved".Trim() -ne 'python3') { throw "Resolver chose '$resolved' instead of skipping the broken python." }
|
||||||
|
|
||||||
|
$output = (& $hostPath -NoProfile -ExecutionPolicy Bypass -File (Join-Path $root 'scripts/commands/check-capabilities.ps1') 2>&1 | Out-String)
|
||||||
|
if ($output -notmatch 'PASS Python 3\.12\.0') { throw "check-capabilities did not use the resolved interpreter:`n$output" }
|
||||||
|
} finally {
|
||||||
|
$env:PATH = $previousPath
|
||||||
|
Remove-Item -LiteralPath $stubs -Recurse -Force -ErrorAction SilentlyContinue
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($Summary) { Write-Output 'Tests: PASS | capabilities' } else { Write-Output 'PASS capabilities: Python exit code is read without a pipeline' }
|
if ($Summary) { Write-Output 'Tests: PASS | capabilities' } else { Write-Output 'PASS capabilities: broken Python aliases are skipped' }
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Checks that Python resolution skips a PATH entry that cannot run Python (such as the Windows
|
||||||
|
# Store app execution alias) and that check-capabilities reports the resolved interpreter.
|
||||||
|
set -euo pipefail
|
||||||
|
summary=false
|
||||||
|
[ "${1:-}" != --summary ] || summary=true
|
||||||
|
root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)
|
||||||
|
stubs=$(mktemp -d)
|
||||||
|
trap 'rm -rf -- "$stubs"' EXIT
|
||||||
|
|
||||||
|
# python3 imitates the Store alias: it is on PATH but only prints an install hint.
|
||||||
|
printf '#!/bin/sh\necho "Python was not found; run without arguments to install from the Microsoft Store" >&2\nexit 9009\n' > "$stubs/python3"
|
||||||
|
printf '#!/bin/sh\nfor arg in "$@"; do [ "$arg" != -c ] || { echo 3.12.0; exit 0; }; done\nexit 0\n' > "$stubs/python"
|
||||||
|
chmod +x "$stubs/python3" "$stubs/python"
|
||||||
|
|
||||||
|
# shellcheck disable=SC2016 # Expanded by the child shell.
|
||||||
|
resolved=$(PATH="$stubs:$PATH" bash -c '. "$1/shared/hooks/scripts/resolve-python.sh"; resolve_python && printf "%s" "$(python_display)"' _ "$root")
|
||||||
|
[ "$resolved" = python ] || { printf 'FAIL resolver chose "%s" instead of skipping the broken python3\n' "$resolved" >&2; exit 1; }
|
||||||
|
|
||||||
|
output=$(PATH="$stubs:$PATH" bash "$root/scripts/commands/check-capabilities.sh" 2>&1) || true
|
||||||
|
grep -q 'PASS Python 3.12.0' <<<"$output" || { printf 'FAIL check-capabilities did not use the resolved interpreter:\n%s\n' "$output" >&2; exit 1; }
|
||||||
|
|
||||||
|
if [ "$summary" = true ]; then printf 'Tests: PASS | capabilities\n'; else printf 'PASS capabilities: broken Python aliases are skipped\n'; fi
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[2]
|
||||||
|
SCRIPTS = ROOT / 'shared/hooks/scripts'
|
||||||
|
SAFETY = SCRIPTS / 'command-safety.py'
|
||||||
|
|
||||||
|
|
||||||
|
def hook(command, tool='Bash'):
|
||||||
|
payload = json.dumps({'hook_event_name': 'PreToolUse', 'tool_name': tool, 'tool_input': {'command': command}})
|
||||||
|
return subprocess.run([sys.executable, str(SAFETY), '--hook'], input=payload, capture_output=True,
|
||||||
|
encoding='utf-8', timeout=20)
|
||||||
|
|
||||||
|
|
||||||
|
def check(command, workspace):
|
||||||
|
return subprocess.run([sys.executable, str(SAFETY), '--command', '-', '--workspace', str(workspace)], input=command,
|
||||||
|
capture_output=True, encoding='utf-8', timeout=20)
|
||||||
|
|
||||||
|
|
||||||
|
class HookTests(unittest.TestCase):
|
||||||
|
def assertBlocked(self, command, tool='Bash'):
|
||||||
|
result = hook(command, tool)
|
||||||
|
self.assertEqual(result.returncode, 2, f'{tool}: {command!r} was not blocked')
|
||||||
|
self.assertIn('Blocked by command-safety hook', result.stderr)
|
||||||
|
|
||||||
|
def assertAllowed(self, command, tool='Bash'):
|
||||||
|
result = hook(command, tool)
|
||||||
|
self.assertEqual(result.returncode, 0, f'{tool}: {command!r} was blocked: {result.stderr}')
|
||||||
|
|
||||||
|
def test_blocks_destructive_bash_variants(self):
|
||||||
|
for command in ('rm -rf build', 'rm -fr build', 'rm -r -f build', 'rm --recursive --force build', 'sudo rm -Rf /',
|
||||||
|
'cd x && rm -rf y', 'echo ok; rm -rf y', 'git reset --hard', 'git -C repo reset --hard HEAD~1',
|
||||||
|
'git clean -fdx', 'git clean --force', "bash -c 'rm -rf build'", 'bash -lc "git reset --hard"',
|
||||||
|
'eval "rm -rf build"', 'find . -name x | xargs rm -rf', 'FOO=1 /bin/rm -rf build'):
|
||||||
|
with self.subTest(command=command):
|
||||||
|
self.assertBlocked(command)
|
||||||
|
|
||||||
|
def test_blocks_destructive_powershell_variants(self):
|
||||||
|
for command in ('Remove-Item build -Recurse -Force', 'Remove-Item -Path build -Rec', 'rm -r build', 'ri build -recurse',
|
||||||
|
'Get-ChildItem x | Remove-Item -Recurse', 'git reset --hard', 'cmd /c "rd /s /q build"',
|
||||||
|
'pwsh -NoProfile -Command "Remove-Item build -Recurse"', 'format C:'):
|
||||||
|
with self.subTest(command=command):
|
||||||
|
self.assertBlocked(command, 'PowerShell')
|
||||||
|
|
||||||
|
def test_allows_ordinary_commands(self):
|
||||||
|
for command in ('rm build/file.txt', 'rm -r build', 'git reset HEAD file', 'git reset --soft HEAD~1', 'git clean -n',
|
||||||
|
'git status', 'echo "rm -rf is dangerous"', 'git commit -m "avoid rm -rf; use trash"', 'ls -rf'):
|
||||||
|
with self.subTest(command=command):
|
||||||
|
self.assertAllowed(command)
|
||||||
|
self.assertAllowed('Remove-Item build/file.txt', 'PowerShell')
|
||||||
|
self.assertAllowed('Remove-Item build -Recurse:$false', 'PowerShell')
|
||||||
|
|
||||||
|
def test_unknown_shell_checks_both_dialects(self):
|
||||||
|
self.assertBlocked('rm -r build', 'shell')
|
||||||
|
self.assertBlocked('rm -rf build', 'shell')
|
||||||
|
|
||||||
|
def test_fails_open_on_unusable_input(self):
|
||||||
|
for payload in ('', 'not json', '[]', '{"tool_input": "rm -rf /"}', '{"tool_input": {"command": 5}}'):
|
||||||
|
with self.subTest(payload=payload):
|
||||||
|
result = subprocess.run([sys.executable, str(SAFETY), '--hook'], input=payload, capture_output=True,
|
||||||
|
encoding='utf-8', timeout=20)
|
||||||
|
self.assertEqual(result.returncode, 0, result.stderr)
|
||||||
|
|
||||||
|
|
||||||
|
class CommandCheckTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
directory = tempfile.TemporaryDirectory()
|
||||||
|
self.addCleanup(directory.cleanup)
|
||||||
|
self.workspace = Path(directory.name).resolve()
|
||||||
|
|
||||||
|
def test_passes_safe_command_inside_workspace(self):
|
||||||
|
result = check(f'cat "{self.workspace / "file.txt"}"', self.workspace)
|
||||||
|
self.assertEqual(result.returncode, 0, result.stderr)
|
||||||
|
self.assertIn('PASS command safety', result.stdout)
|
||||||
|
|
||||||
|
def test_rejects_destructive_command(self):
|
||||||
|
result = check('git reset --hard', self.workspace)
|
||||||
|
self.assertEqual(result.returncode, 1)
|
||||||
|
self.assertIn('Blocked potentially destructive command', result.stderr)
|
||||||
|
|
||||||
|
def test_rejects_absolute_path_outside_workspace(self):
|
||||||
|
outside = self.workspace.parent / 'elsewhere.txt'
|
||||||
|
result = check(f'cat "{outside}"', self.workspace)
|
||||||
|
self.assertEqual(result.returncode, 1)
|
||||||
|
self.assertIn('outside the workspace', result.stderr)
|
||||||
|
|
||||||
|
def test_ignores_cmd_switches(self):
|
||||||
|
self.assertEqual(check('cmd /c dir', self.workspace).returncode, 0)
|
||||||
|
|
||||||
|
|
||||||
|
class WrapperTests(unittest.TestCase):
|
||||||
|
def run_wrapper(self, arguments, payload=None):
|
||||||
|
return subprocess.run(arguments, input=payload, capture_output=True, encoding='utf-8', timeout=60)
|
||||||
|
|
||||||
|
def test_wrappers_block_in_hook_mode_and_check_in_cli_mode(self):
|
||||||
|
event = json.dumps({'tool_name': 'Bash', 'tool_input': {'command': 'rm -rf build'}})
|
||||||
|
wrappers = []
|
||||||
|
bash = shutil.which('bash')
|
||||||
|
if os.name == 'nt':
|
||||||
|
# System32\bash.exe is WSL; use Git Bash like the other Windows tests.
|
||||||
|
candidate = Path(os.environ.get('ProgramFiles', 'C:/Program Files')) / 'Git/bin/bash.exe'
|
||||||
|
bash = str(candidate) if candidate.exists() else None
|
||||||
|
if bash:
|
||||||
|
wrappers.append(('bash', [bash, str(SCRIPTS / 'validate-command-safety.sh')]))
|
||||||
|
for name in ('pwsh', 'powershell'):
|
||||||
|
executable = shutil.which(name)
|
||||||
|
if executable:
|
||||||
|
wrappers.append((name, [executable, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File',
|
||||||
|
str(SCRIPTS / 'Validate-CommandSafety.ps1')]))
|
||||||
|
if not wrappers:
|
||||||
|
self.skipTest('No supported shell is available.')
|
||||||
|
for name, command in wrappers:
|
||||||
|
with self.subTest(shell=name):
|
||||||
|
blocked = self.run_wrapper(command, event)
|
||||||
|
self.assertEqual(blocked.returncode, 2, blocked.stderr)
|
||||||
|
allowed = self.run_wrapper(command, json.dumps({'tool_name': 'Bash', 'tool_input': {'command': 'git status'}}))
|
||||||
|
self.assertEqual(allowed.returncode, 0, allowed.stderr)
|
||||||
|
cli = command + (['-Command', 'git reset --hard'] if name != 'bash' else ['git reset --hard'])
|
||||||
|
self.assertEqual(self.run_wrapper(cli).returncode, 1)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
@@ -12,7 +12,6 @@ from pathlib import Path
|
|||||||
import queue
|
import queue
|
||||||
import shutil
|
import shutil
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
|
||||||
import tempfile
|
import tempfile
|
||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
|
|||||||
@@ -116,7 +116,7 @@ class InstallOptionsTests(unittest.TestCase):
|
|||||||
|
|
||||||
def test_qmd_warm_match_is_anchored(self):
|
def test_qmd_warm_match_is_anchored(self):
|
||||||
self.assertTrue(OPTIONS.is_qmd_warm({'command': 'bash "/c/hooks/scripts/qmd-warm.sh"'}))
|
self.assertTrue(OPTIONS.is_qmd_warm({'command': 'bash "/c/hooks/scripts/qmd-warm.sh"'}))
|
||||||
self.assertTrue(OPTIONS.is_qmd_warm({'command_windows': 'pwsh "C:\hooks\Start-QmdWarm.ps1"'}))
|
self.assertTrue(OPTIONS.is_qmd_warm({'command_windows': r'pwsh "C:\hooks\Start-QmdWarm.ps1"'}))
|
||||||
self.assertFalse(OPTIONS.is_qmd_warm({'command': 'bash "/c/hooks/scripts/my-qmd-warm.sh"'}))
|
self.assertFalse(OPTIONS.is_qmd_warm({'command': 'bash "/c/hooks/scripts/my-qmd-warm.sh"'}))
|
||||||
|
|
||||||
def test_merge_json_keeps_user_session_hook_and_drops_qmd_when_disabled(self):
|
def test_merge_json_keeps_user_session_hook_and_drops_qmd_when_disabled(self):
|
||||||
@@ -228,6 +228,9 @@ class InstallOptionsTests(unittest.TestCase):
|
|||||||
commands = scripts / 'commands'
|
commands = scripts / 'commands'
|
||||||
commands.mkdir(parents=True)
|
commands.mkdir(parents=True)
|
||||||
shutil.copytree(ROOT / 'scripts/lib', scripts / 'lib', ignore=shutil.ignore_patterns('__pycache__'))
|
shutil.copytree(ROOT / 'scripts/lib', scripts / 'lib', ignore=shutil.ignore_patterns('__pycache__'))
|
||||||
|
(root / 'shared/hooks/scripts').mkdir(parents=True)
|
||||||
|
for resolver in ('resolve-python.sh', 'Resolve-Python.ps1'):
|
||||||
|
shutil.copy(ROOT / 'shared/hooks/scripts' / resolver, root / 'shared/hooks/scripts' / resolver)
|
||||||
home = Path(directory) / 'home'
|
home = Path(directory) / 'home'
|
||||||
home.mkdir()
|
home.mkdir()
|
||||||
(root / 'adapters').mkdir()
|
(root / 'adapters').mkdir()
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import unittest
|
|||||||
|
|
||||||
ROOT = Path(__file__).resolve().parents[2]
|
ROOT = Path(__file__).resolve().parents[2]
|
||||||
sys.path.insert(0, str(ROOT / 'scripts/lib'))
|
sys.path.insert(0, str(ROOT / 'scripts/lib'))
|
||||||
from personal_instructions import CLIENT_FILES, START, refresh, render
|
from personal_instructions import CLIENT_FILES, START, refresh, render # noqa: E402 - needs the sys.path entry above
|
||||||
|
|
||||||
|
|
||||||
class PersonalInstructionTests(unittest.TestCase):
|
class PersonalInstructionTests(unittest.TestCase):
|
||||||
|
|||||||
@@ -67,7 +67,7 @@ try {
|
|||||||
if (@($selection.Deselected | Where-Object { $_.name -eq 'Context7' }).Count -ne 1) { throw 'A different MCPorter server must not select Context7.' }
|
if (@($selection.Deselected | Where-Object { $_.name -eq 'Context7' }).Count -ne 1) { throw 'A different MCPorter server must not select Context7.' }
|
||||||
} finally { Remove-Item -LiteralPath $mcporterHome -Recurse -Force -ErrorAction SilentlyContinue }
|
} finally { Remove-Item -LiteralPath $mcporterHome -Recurse -Force -ErrorAction SilentlyContinue }
|
||||||
$script:managedArguments = @()
|
$script:managedArguments = @()
|
||||||
function python { $script:managedArguments = @($args); $global:LASTEXITCODE = 0 }
|
function Invoke-Python { $script:managedArguments = @($args); $global:LASTEXITCODE = 0 }
|
||||||
$entry = [pscustomobject]@{ name = 'Test'; codex_method = 'plugin'; codex_marketplace = '-'; codex_plugin = 'test@market' }
|
$entry = [pscustomobject]@{ name = 'Test'; codex_method = 'plugin'; codex_marketplace = '-'; codex_plugin = 'test@market' }
|
||||||
Sync-ConfiguredPlugins -RepositoryRoot (Split-Path (Split-Path $PSScriptRoot -Parent) -Parent) -Client Codex -HomePath $testHome -Update -Summary -Entries @($entry)
|
Sync-ConfiguredPlugins -RepositoryRoot (Split-Path (Split-Path $PSScriptRoot -Parent) -Parent) -Client Codex -HomePath $testHome -Update -Summary -Entries @($entry)
|
||||||
if ($managedArguments -notcontains 'sync' -or $managedArguments -notcontains '--update' -or $managedArguments -notcontains 'Test' -or $managedArguments -notcontains $testHome) { throw 'Managed reconciliation must receive selection, home, and update mode.' }
|
if ($managedArguments -notcontains 'sync' -or $managedArguments -notcontains '--update' -or $managedArguments -notcontains 'Test' -or $managedArguments -notcontains $testHome) { throw 'Managed reconciliation must receive selection, home, and update mode.' }
|
||||||
|
|||||||
@@ -121,7 +121,7 @@ class RemoveCustomizationTests(unittest.TestCase):
|
|||||||
for name in ('remove-credentials.ps1', 'remove-credentials.sh'):
|
for name in ('remove-credentials.ps1', 'remove-credentials.sh'):
|
||||||
shutil.copy2(ROOT / 'scripts' / 'commands' / name, commands / name)
|
shutil.copy2(ROOT / 'scripts' / 'commands' / name, commands / name)
|
||||||
shutil.copy2(ROOT / 'scripts/lib/install-targets.ps1', library / 'install-targets.ps1')
|
shutil.copy2(ROOT / 'scripts/lib/install-targets.ps1', library / 'install-targets.ps1')
|
||||||
(library / 'credentials.ps1').write_text('''
|
(library / 'with-credential.ps1').write_text('''
|
||||||
function Assert-CredentialKey { param([string]$Value)
|
function Assert-CredentialKey { param([string]$Value)
|
||||||
if ($Value -notmatch '^[A-Za-z_][A-Za-z0-9_]{0,127}$') { throw 'Invalid credential key.' }
|
if ($Value -notmatch '^[A-Za-z_][A-Za-z0-9_]{0,127}$') { throw 'Invalid credential key.' }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
import importlib.util
|
||||||
|
from pathlib import Path
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[2]
|
||||||
|
SPEC = importlib.util.spec_from_file_location('validate_config', ROOT / 'scripts/checks/validate-config.py')
|
||||||
|
VALIDATE = importlib.util.module_from_spec(SPEC)
|
||||||
|
SPEC.loader.exec_module(VALIDATE)
|
||||||
|
|
||||||
|
|
||||||
|
class RuleStructureTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
directory = tempfile.TemporaryDirectory()
|
||||||
|
self.addCleanup(directory.cleanup)
|
||||||
|
self.package = Path(directory.name)
|
||||||
|
self.write('rules/lang/index.md', '# Lang Rules\n\n| Topic | `references/a.md` | `rules-lang-a` |\n')
|
||||||
|
self.write('rules/lang/references/a.md', '# Lang A\n\n* Rule.\n')
|
||||||
|
self.write('rules/git.md', '# Git Guidelines\n')
|
||||||
|
self.write('AGENTS.md', 'Load `rules/lang/index.md` and `rules/git.md`.\n')
|
||||||
|
|
||||||
|
def write(self, relative, text):
|
||||||
|
path = self.package / relative
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
path.write_text(text, encoding='utf-8')
|
||||||
|
|
||||||
|
def assertRejected(self, fragment):
|
||||||
|
with self.assertRaisesRegex(ValueError, fragment):
|
||||||
|
VALIDATE.validate_rule_tree(self.package)
|
||||||
|
|
||||||
|
def test_accepts_consistent_tree(self):
|
||||||
|
VALIDATE.validate_rule_tree(self.package)
|
||||||
|
|
||||||
|
def test_rejects_missing_level_one_heading(self):
|
||||||
|
self.write('rules/lang/references/a.md', '## Forms\n')
|
||||||
|
self.assertRejected('level-1 heading')
|
||||||
|
|
||||||
|
def test_rejects_duplicate_titles(self):
|
||||||
|
self.write('rules/other.md', '# Lang A\n')
|
||||||
|
self.assertRejected('must be unique')
|
||||||
|
|
||||||
|
def test_rejects_unlinked_reference(self):
|
||||||
|
self.write('rules/lang/references/b.md', '# Lang B\n')
|
||||||
|
self.assertRejected('not linked')
|
||||||
|
|
||||||
|
def test_rejects_dangling_index_link(self):
|
||||||
|
self.write('rules/lang/index.md', '# Lang Rules\n\n`references/a.md` `references/missing.md`\n')
|
||||||
|
self.assertRejected('links missing rule')
|
||||||
|
|
||||||
|
def test_rejects_route_to_missing_rule(self):
|
||||||
|
self.write('AGENTS.md', 'Load `rules/lang/gone.md`.\n')
|
||||||
|
self.assertRejected('routes to missing rule')
|
||||||
|
|
||||||
|
def test_rejects_claude_route_to_missing_skill(self):
|
||||||
|
self.write('CLAUDE.md', 'Invoke `rules-lang-a` and `rules-missing`.\n')
|
||||||
|
self.write('skills/rules-lang-a/SKILL.md', '---\nname: rules-lang-a\n---\n')
|
||||||
|
with self.assertRaisesRegex(ValueError, 'missing skill rules-missing'):
|
||||||
|
VALIDATE.validate_rule_routing(self.package)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
@@ -61,12 +61,12 @@ foreach ($shell in @('powershell','bash')) {
|
|||||||
if ($shell -eq 'powershell' -and $content -match 'WindowStyle\s+Hidden') { throw "PowerShell hook hides the terminal in $package" }
|
if ($shell -eq 'powershell' -and $content -match 'WindowStyle\s+Hidden') { throw "PowerShell hook hides the terminal in $package" }
|
||||||
if ($client -eq 'codex') {
|
if ($client -eq 'codex') {
|
||||||
$events = @([regex]::Matches($content, '(?m)^\[\[hooks\.([^.\]]+)\]\]\s*$') | ForEach-Object { $_.Groups[1].Value })
|
$events = @([regex]::Matches($content, '(?m)^\[\[hooks\.([^.\]]+)\]\]\s*$') | ForEach-Object { $_.Groups[1].Value })
|
||||||
if ((($events | Sort-Object) -join ',') -ne 'SessionStart,Stop,Stop,UserPromptSubmit' -or $content -match 'flashbang-if-input' -or $content -match '(?m)^async\s*=\s*true\s*$') { throw "Codex finish hook is incorrect in $package" }
|
if ((($events | Sort-Object) -join ',') -ne 'PreToolUse,SessionStart,Stop,Stop,UserPromptSubmit' -or $content -match 'flashbang-if-input' -or $content -match '(?m)^async\s*=\s*true\s*$') { throw "Codex finish hook is incorrect in $package" }
|
||||||
if ($content -notmatch 'approvals_reviewer\s*=\s*"auto_review"') { throw "Codex auto review is missing in $package" }
|
if ($content -notmatch 'approvals_reviewer\s*=\s*"auto_review"') { throw "Codex auto review is missing in $package" }
|
||||||
if ($content -notmatch '(?m)^sandbox_mode\s*=\s*"danger-full-access"\s*$') { throw "Codex full access is missing in $package" }
|
if ($content -notmatch '(?m)^sandbox_mode\s*=\s*"danger-full-access"\s*$') { throw "Codex full access is missing in $package" }
|
||||||
if ($content -notmatch '(?m)^max_depth\s*=\s*1\s*$') { throw "Codex agent depth limit is missing in $package" }
|
if ($content -notmatch '(?m)^max_depth\s*=\s*1\s*$') { throw "Codex agent depth limit is missing in $package" }
|
||||||
if ($content -notmatch 'status_line\s*=\s*\["model", "reasoning", "fast-mode", "approval-mode", "five-hour-limit", "weekly-limit", "project-name", "git-branch", "context-window-size", "context-used", "used-tokens"\]') { throw "Codex status line is incorrect in $package" }
|
if ($content -notmatch 'status_line\s*=\s*\["model", "reasoning", "fast-mode", "approval-mode", "five-hour-limit", "weekly-limit", "project-name", "git-branch", "context-window-size", "context-used", "used-tokens"\]') { throw "Codex status line is incorrect in $package" }
|
||||||
} elseif ((($settings.hooks.PSObject.Properties.Name | Sort-Object) -join ',') -ne 'PreCompact,SessionStart,Stop,UserPromptSubmit' -or $content -match 'flashbang-if-input' -or $settings.hooks.Stop[0].hooks[0].async) {
|
} elseif ((($settings.hooks.PSObject.Properties.Name | Sort-Object) -join ',') -ne 'PreCompact,PreToolUse,SessionStart,Stop,UserPromptSubmit' -or $content -match 'flashbang-if-input' -or $settings.hooks.Stop[0].hooks[0].async) {
|
||||||
throw "Claude finish hook is incorrect in $package"
|
throw "Claude finish hook is incorrect in $package"
|
||||||
} elseif ($content -notmatch '"defaultMode"\s*:\s*"auto"') {
|
} elseif ($content -notmatch '"defaultMode"\s*:\s*"auto"') {
|
||||||
throw "Claude auto permission mode is missing in $package"
|
throw "Claude auto permission mode is missing in $package"
|
||||||
|
|||||||
@@ -51,10 +51,11 @@ for shell in powershell bash; do
|
|||||||
test "$(find "$package/agents" -type f | wc -l)" -eq "$source_agent_count"
|
test "$(find "$package/agents" -type f | wc -l)" -eq "$source_agent_count"
|
||||||
expected_reviewer_shell_tool=Bash
|
expected_reviewer_shell_tool=Bash
|
||||||
[ "$shell" != powershell ] || expected_reviewer_shell_tool=PowerShell
|
[ "$shell" != powershell ] || expected_reviewer_shell_tool=PowerShell
|
||||||
if [ "$client" = claude ]; then grep -q "^tools: Read,Grep,Glob,$expected_reviewer_shell_tool\$" "$package/agents/reviewer.md"; fi
|
# Generated files may have CRLF endings when the PowerShell build produced them, so allow trailing whitespace.
|
||||||
|
if [ "$client" = claude ]; then grep -q "^tools: Read,Grep,Glob,${expected_reviewer_shell_tool}[[:space:]]*\$" "$package/agents/reviewer.md"; fi
|
||||||
if [ "$client" = claude ]; then
|
if [ "$client" = claude ]; then
|
||||||
for role in architect researcher; do
|
for role in architect researcher; do
|
||||||
grep -q "^tools: Read,Grep,Glob,WebFetch,WebSearch,$expected_reviewer_shell_tool\$" "$package/agents/$role.md" || { printf '%s research shell capability is missing in %s\n' "$role" "$package"; exit 1; }
|
grep -q "^tools: Read,Grep,Glob,WebFetch,WebSearch,${expected_reviewer_shell_tool}[[:space:]]*\$" "$package/agents/$role.md" || { printf '%s research shell capability is missing in %s\n' "$role" "$package"; exit 1; }
|
||||||
done
|
done
|
||||||
fi
|
fi
|
||||||
expected_skill_count=$source_skill_count
|
expected_skill_count=$source_skill_count
|
||||||
@@ -79,7 +80,7 @@ for shell in powershell bash; do
|
|||||||
grep -q 'bash .*flashbang.sh' "$package/$file"
|
grep -q 'bash .*flashbang.sh' "$package/$file"
|
||||||
fi
|
fi
|
||||||
if [ "$client" = codex ]; then
|
if [ "$client" = codex ]; then
|
||||||
[ "$(sed -n 's/^\[\[hooks\.\([^].]*\)\]\]$/\1/p' "$package/$file" | sort)" = $'SessionStart\nStop\nStop\nUserPromptSubmit' ]
|
[ "$(sed -n 's/^\[\[hooks\.\([^].]*\)\]\][[:space:]]*$/\1/p' "$package/$file" | sort)" = $'PreToolUse\nSessionStart\nStop\nStop\nUserPromptSubmit' ]
|
||||||
! grep -q 'flashbang-if-input' "$package/$file"
|
! grep -q 'flashbang-if-input' "$package/$file"
|
||||||
! grep -Eq '^async[[:space:]]*=[[:space:]]*true[[:space:]]*$' "$package/$file"
|
! grep -Eq '^async[[:space:]]*=[[:space:]]*true[[:space:]]*$' "$package/$file"
|
||||||
grep -q 'approvals_reviewer[[:space:]]*=[[:space:]]*"auto_review"' "$package/$file"
|
grep -q 'approvals_reviewer[[:space:]]*=[[:space:]]*"auto_review"' "$package/$file"
|
||||||
@@ -87,7 +88,7 @@ for shell in powershell bash; do
|
|||||||
grep -Eq '^max_depth[[:space:]]*=[[:space:]]*1[[:space:]]*$' "$package/$file"
|
grep -Eq '^max_depth[[:space:]]*=[[:space:]]*1[[:space:]]*$' "$package/$file"
|
||||||
grep -Fq 'status_line = ["model", "reasoning", "fast-mode", "approval-mode", "five-hour-limit", "weekly-limit", "project-name", "git-branch", "context-window-size", "context-used", "used-tokens"]' "$package/$file"
|
grep -Fq 'status_line = ["model", "reasoning", "fast-mode", "approval-mode", "five-hour-limit", "weekly-limit", "project-name", "git-branch", "context-window-size", "context-used", "used-tokens"]' "$package/$file"
|
||||||
else
|
else
|
||||||
python3 -c 'import json,sys; settings=json.load(open(sys.argv[1], encoding="utf-8-sig")); assert set(settings["hooks"]) == {"PreCompact", "SessionStart", "Stop", "UserPromptSubmit"}' "$package/$file"
|
python3 -c 'import json,sys; settings=json.load(open(sys.argv[1], encoding="utf-8-sig")); assert set(settings["hooks"]) == {"PreCompact", "PreToolUse", "SessionStart", "Stop", "UserPromptSubmit"}' "$package/$file"
|
||||||
! grep -q 'flashbang-if-input' "$package/$file"
|
! grep -q 'flashbang-if-input' "$package/$file"
|
||||||
! grep -q '"async"[[:space:]]*:[[:space:]]*true' "$package/$file"
|
! grep -q '"async"[[:space:]]*:[[:space:]]*true' "$package/$file"
|
||||||
grep -q '"defaultMode"[[:space:]]*:[[:space:]]*"auto"' "$package/$file"
|
grep -q '"defaultMode"[[:space:]]*:[[:space:]]*"auto"' "$package/$file"
|
||||||
|
|||||||
@@ -23,6 +23,8 @@ class TelemetryTests(unittest.TestCase):
|
|||||||
script = root / 'scripts/commands/telemetry.sh'
|
script = root / 'scripts/commands/telemetry.sh'
|
||||||
script.parent.mkdir(parents=True)
|
script.parent.mkdir(parents=True)
|
||||||
shutil.copy(ROOT / 'scripts/commands/telemetry.sh', script)
|
shutil.copy(ROOT / 'scripts/commands/telemetry.sh', script)
|
||||||
|
(root / 'shared/hooks/scripts').mkdir(parents=True)
|
||||||
|
shutil.copy(ROOT / 'shared/hooks/scripts/resolve-python.sh', root / 'shared/hooks/scripts/resolve-python.sh')
|
||||||
env = dict(os.environ, AI_CONFIG_TELEMETRY='1')
|
env = dict(os.environ, AI_CONFIG_TELEMETRY='1')
|
||||||
result = subprocess.run([bash, str(script), 'record', 'subagent-stop', '--role', 'reviewer', '--filesRead', '3', '--outcome', 'findings'], env=env, capture_output=True, text=True)
|
result = subprocess.run([bash, str(script), 'record', 'subagent-stop', '--role', 'reviewer', '--filesRead', '3', '--outcome', 'findings'], env=env, capture_output=True, text=True)
|
||||||
self.assertEqual(result.returncode, 0, result.stderr)
|
self.assertEqual(result.returncode, 0, result.stderr)
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import os
|
||||||
import shutil
|
import shutil
|
||||||
import subprocess
|
import subprocess
|
||||||
import tempfile
|
import tempfile
|
||||||
@@ -53,6 +54,8 @@ class UserCustomizationTests(unittest.TestCase):
|
|||||||
(home / '.my-ai-configuration/instructions/codex.md').read_text())
|
(home / '.my-ai-configuration/instructions/codex.md').read_text())
|
||||||
|
|
||||||
def test_add_credentials_installs_a_client_scoped_helper(self):
|
def test_add_credentials_installs_a_client_scoped_helper(self):
|
||||||
|
if os.name != 'nt':
|
||||||
|
self.skipTest('The OS credential store is supported on Windows only.')
|
||||||
powershell = shutil.which('powershell') or shutil.which('pwsh')
|
powershell = shutil.which('powershell') or shutil.which('pwsh')
|
||||||
if powershell is None:
|
if powershell is None:
|
||||||
self.skipTest('PowerShell is unavailable.')
|
self.skipTest('PowerShell is unavailable.')
|
||||||
@@ -82,7 +85,7 @@ class UserCustomizationTests(unittest.TestCase):
|
|||||||
finally:
|
finally:
|
||||||
cleanup = subprocess.run([
|
cleanup = subprocess.run([
|
||||||
powershell, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command',
|
powershell, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command',
|
||||||
f". '{ROOT / 'scripts/lib/credentials.ps1'}'; Remove-ManagedCredential -Client Codex -Key {key}",
|
f". '{ROOT / 'scripts/lib/with-credential.ps1'}'; Remove-ManagedCredential -Client Codex -Key {key}",
|
||||||
], capture_output=True, text=True, timeout=20)
|
], capture_output=True, text=True, timeout=20)
|
||||||
if stored:
|
if stored:
|
||||||
self.assertEqual(0, cleanup.returncode, cleanup.stderr)
|
self.assertEqual(0, cleanup.returncode, cleanup.stderr)
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Global Instructions
|
# Global Instructions
|
||||||
|
|
||||||
For credentials, run the child command through `~/.my-ai-configuration/bin/with-credential.__SHELL__` with the client and credential key. Never expose credentials in commands, output, logs, or files.
|
For credentials, run the child command through `~/.my-ai-configuration/bin/with-credential.__SCRIPT_EXTENSION__` with the client and credential key. Never expose credentials in commands, output, logs, or files.
|
||||||
|
|
||||||
## Loading rules
|
## Loading rules
|
||||||
|
|
||||||
@@ -10,7 +10,7 @@ For Codex, read the listed rule path directly. For Claude, invoke the matching `
|
|||||||
|
|
||||||
Changes to or reviews of code, scripts, hooks, tests, infrastructure, integrations, or executable configuration: `rules/security/index.md` / `rules-security`. Skip it for prose-only changes.
|
Changes to or reviews of code, scripts, hooks, tests, infrastructure, integrations, or executable configuration: `rules/security/index.md` / `rules-security`. Skip it for prose-only changes.
|
||||||
|
|
||||||
Focused security: authentication, authorization, sessions, tokens, permissions, tenants => `rules/security/references/auth.md` / `rules-security-auth`; HTTP, requests, serialization, endpoints => `api.md` / `rules-security-api`; browser, cookies, redirects, XSS, CSRF => `web.md` / `rules-security-web`; databases, queries, persistence, sensitive data => `data.md` / `rules-security-data`; files, uploads, archives, paths, processes, IPC, deserialization => `files.md` / `rules-security-files`; network, URLs, proxies, TLS, SSRF => `network.md` / `rules-security-network`; cryptography, secrets, keys, credentials => `crypto.md` / `rules-security-crypto`; dependencies, packages, plugins, builds, deployment, CI => `supply-chain.md` / `rules-security-supply-chain`; active security testing => `testing.md` / `rules-security-testing`.
|
Focused security (Codex paths under `rules/security/references/`): authentication, authorization, sessions, tokens, permissions, tenants => `auth.md` / `rules-security-auth`; inbound HTTP endpoints, request handling, API (de)serialization => `api.md` / `rules-security-api`; browser, cookies, redirects, XSS, CSRF => `web.md` / `rules-security-web`; databases, queries, persistence, sensitive data => `data.md` / `rules-security-data`; files, uploads, archives, paths, processes, IPC, XML parsing, deserialization => `files.md` / `rules-security-files`; outbound HTTP calls, webhooks, URL fetching, proxies, TLS, SSRF => `network.md` / `rules-security-network`; cryptography, secrets, keys, credentials => `crypto.md` / `rules-security-crypto`; dependencies, packages, plugins, builds, deployment, CI => `supply-chain.md` / `rules-security-supply-chain`; LLM calls, prompts, agents, tools, retrieval/RAG => `ai.md` / `rules-security-ai`; active security testing => `testing.md` / `rules-security-testing`.
|
||||||
|
|
||||||
Technology indexes: Angular => `rules/angular/index.md` / `rules-angular`; C#/.NET => `rules/csharp/index.md` / `rules-csharp`; Java/JVM => `rules/java/index.md` / `rules-java`; TypeScript/ECMAScript => `rules/typescript/index.md` / `rules-typescript`; UI/UX => `rules/ui-ux/index.md` / `rules-ui-ux`; WPF/XAML/MVVM => `rules/wpf/index.md` / `rules-wpf`.
|
Technology indexes: Angular => `rules/angular/index.md` / `rules-angular`; C#/.NET => `rules/csharp/index.md` / `rules-csharp`; Java/JVM => `rules/java/index.md` / `rules-java`; TypeScript/ECMAScript => `rules/typescript/index.md` / `rules-typescript`; UI/UX => `rules/ui-ux/index.md` / `rules-ui-ux`; WPF/XAML/MVVM => `rules/wpf/index.md` / `rules-wpf`.
|
||||||
|
|
||||||
|
|||||||
@@ -4,8 +4,8 @@ This directory contains registered hooks and optional utilities. They do not byp
|
|||||||
|
|
||||||
When Flashbang is enabled, both clients register `Stop` (`flashbang`) for finish notifications. Claude also registers `PreCompact` (`Record-Compact`/`record-compact.sh`) and `SessionStart` (`Show-SessionStatePointer`/`show-session-state-pointer.sh`). PreCompact records its timestamp under the installed configuration root. Both session hooks point to an existing workspace `.ai-session/state.json`, using event `cwd` or the process working directory. The main agent owns that state; hooks never write it or print its contents. Missing state is a successful no-op.
|
When Flashbang is enabled, both clients register `Stop` (`flashbang`) for finish notifications. Claude also registers `PreCompact` (`Record-Compact`/`record-compact.sh`) and `SessionStart` (`Show-SessionStatePointer`/`show-session-state-pointer.sh`). PreCompact records its timestamp under the installed configuration root. Both session hooks point to an existing workspace `.ai-session/state.json`, using event `cwd` or the process working directory. The main agent owns that state; hooks never write it or print its contents. Missing state is a successful no-op.
|
||||||
|
|
||||||
Both clients register `Stop` (`Check-CompletionEvidence`/`check-completion-evidence.sh`) and `UserPromptSubmit` (`Show-CorrectionPrompt`/`show-correction-prompt.sh`). Both call `agent-guards.py`, store nothing, and fail open. The first pushes back once on a completion claim without a named check while non-prose changes exist; the second asks the agent to propose a durable rule after a likely correction.
|
Both clients register `PreToolUse` (`Validate-CommandSafety`/`validate-command-safety.sh`), which blocks clearly destructive shell commands by exiting 2; it parses command text, so it is a guard rail rather than a security boundary, and it fails open. Both clients also register `Stop` (`Check-CompletionEvidence`/`check-completion-evidence.sh`) and `UserPromptSubmit` (`Show-CorrectionPrompt`/`show-correction-prompt.sh`). Both call `agent-guards.py`, store nothing, and fail open. The first pushes back once on a completion claim without a named check while non-prose changes exist; the second asks the agent to propose a durable rule after a likely correction.
|
||||||
|
|
||||||
`Validate-CommandSafety`/`validate-command-safety.sh` and `Invoke-PostChangeVerification`/`invoke-post-change-verification.sh` are not registered or invoked automatically. The safety utility checks selected command-text patterns; the verification utility runs the repository build only when explicitly invoked. `Test-SessionConfig`/`test-session-config.sh` checks repository inputs during a build.
|
`Invoke-PostChangeVerification`/`invoke-post-change-verification.sh` is not registered or invoked automatically; it runs the repository build only when explicitly invoked. Python-based hooks resolve their interpreter through `Resolve-Python.ps1`/`resolve-python.sh` and are silently skipped without Python 3.11+. `Test-SessionConfig`/`test-session-config.sh` checks repository inputs during a build.
|
||||||
|
|
||||||
When local QMD search is enabled, both clients also register a `SessionStart` warm-up hook (`Start-QmdWarm.ps1`/`qmd-warm.sh`). It starts the installed Node wrapper in the background from the process working directory, only inside a Git repository. Warm-up errors are recorded in `~/.my-ai-configuration/qmd/warm.log`; they do not fail the session. Disabling local search removes the hook registration.
|
When local QMD search is enabled, both clients also register a `SessionStart` warm-up hook (`Start-QmdWarm.ps1`/`start-qmd-warm.sh`). It starts the installed Node wrapper in the background from the process working directory, only inside a Git repository. Warm-up errors are recorded in `~/.my-ai-configuration/qmd/warm.log`; they do not fail the session. Disabling local search removes the hook registration.
|
||||||
@@ -5,12 +5,15 @@ set -uo pipefail
|
|||||||
# Python's standard tkinter module because Bash itself cannot create windows.
|
# Python's standard tkinter module because Bash itself cannot create windows.
|
||||||
# No third-party Python package is required.
|
# No third-party Python package is required.
|
||||||
|
|
||||||
if ! command -v python3 >/dev/null 2>&1; then
|
hook_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
|
||||||
|
# shellcheck source=scripts/resolve-python.sh
|
||||||
|
. "$hook_dir/scripts/resolve-python.sh" 2>/dev/null || resolve_python() { return 1; }
|
||||||
|
if ! resolve_python; then
|
||||||
command -v notify-send >/dev/null 2>&1 && notify-send 'AI assistant requires attention'
|
command -v notify-send >/dev/null 2>&1 && notify-send 'AI assistant requires attention'
|
||||||
exit 0
|
exit 0
|
||||||
fi
|
fi
|
||||||
|
|
||||||
python3 - "$@" 2>/dev/null <<'PY' || exit 0
|
run_python - "$@" 2>/dev/null <<'PY' || exit 0
|
||||||
import argparse
|
import argparse
|
||||||
import re
|
import re
|
||||||
import shutil
|
import shutil
|
||||||
|
|||||||
@@ -1,7 +1,10 @@
|
|||||||
[CmdletBinding()]
|
[CmdletBinding()]
|
||||||
param()
|
param()
|
||||||
|
# Best effort: without Python 3.11+ this hook is a silent no-op; doctor reports that case.
|
||||||
try {
|
try {
|
||||||
$ErrorActionPreference = 'Stop'
|
$ErrorActionPreference = 'Stop'
|
||||||
& python (Join-Path $PSScriptRoot 'agent-guards.py') stop 2>$null
|
. (Join-Path $PSScriptRoot 'Resolve-Python.ps1')
|
||||||
|
$python = Get-PythonCommand
|
||||||
|
if ($python) { & $python.Path @($python.Arguments) (Join-Path $PSScriptRoot 'agent-guards.py') stop 2>$null }
|
||||||
} catch {}
|
} catch {}
|
||||||
exit 0
|
exit 0
|
||||||
@@ -10,6 +10,8 @@ try {
|
|||||||
('{"event":"compact","timestamp":"' + (Get-Date).ToUniversalTime().ToString('o') + '"}') | Add-Content $path
|
('{"event":"compact","timestamp":"' + (Get-Date).ToUniversalTime().ToString('o') + '"}') | Add-Content $path
|
||||||
if ((Get-Item $path).Length -gt 1048576) { Move-Item $path ($path + '.1') -Force }
|
if ((Get-Item $path).Length -gt 1048576) { Move-Item $path ($path + '.1') -Force }
|
||||||
}
|
}
|
||||||
& python (Join-Path $PSScriptRoot 'session-state.py') --hook 2>$null
|
. (Join-Path $PSScriptRoot 'Resolve-Python.ps1')
|
||||||
|
$python = Get-PythonCommand
|
||||||
|
if ($python) { & $python.Path @($python.Arguments) (Join-Path $PSScriptRoot 'session-state.py') --hook 2>$null }
|
||||||
} catch {}
|
} catch {}
|
||||||
exit 0
|
exit 0
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
# Resolves a working Python 3.11+ interpreter for PowerShell scripts and hooks.
|
||||||
|
# Dot-source this file, then call Get-PythonCommand. Candidates are probed by running them,
|
||||||
|
# so the Windows Store "App execution alias" stub (which exists on PATH but only prints an
|
||||||
|
# install hint) is rejected instead of being mistaken for Python. The `py -3` launcher is
|
||||||
|
# tried last for Windows installations that do not put python.exe on PATH.
|
||||||
|
|
||||||
|
$script:ResolvedPythonCommand = $null
|
||||||
|
|
||||||
|
function Get-PythonCommand {
|
||||||
|
param([switch]$Required)
|
||||||
|
if ($null -ne $script:ResolvedPythonCommand) { return $script:ResolvedPythonCommand }
|
||||||
|
$previousErrorActionPreference = $ErrorActionPreference
|
||||||
|
$ErrorActionPreference = 'Continue'
|
||||||
|
try {
|
||||||
|
foreach ($candidate in @(@('python'), @('python3'), @('py', '-3'))) {
|
||||||
|
$application = Get-Command $candidate[0] -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
|
||||||
|
if (-not $application) { continue }
|
||||||
|
$prefix = @($candidate | Select-Object -Skip 1)
|
||||||
|
try {
|
||||||
|
& $application.Source @prefix -c 'import sys; sys.exit(0 if sys.version_info >= (3, 11) else 1)' *> $null
|
||||||
|
$probeExitCode = $LASTEXITCODE
|
||||||
|
} catch { $probeExitCode = 1 }
|
||||||
|
if ($probeExitCode -eq 0) {
|
||||||
|
$script:ResolvedPythonCommand = [pscustomobject]@{ Path = $application.Source; Arguments = $prefix; Display = ($candidate -join ' ') }
|
||||||
|
return $script:ResolvedPythonCommand
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
$ErrorActionPreference = $previousErrorActionPreference
|
||||||
|
}
|
||||||
|
if ($Required) { throw (Get-PythonMissingMessage) }
|
||||||
|
return $null
|
||||||
|
}
|
||||||
|
|
||||||
|
function Get-PythonMissingMessage {
|
||||||
|
return 'Python 3.11 or newer was not found (tried python, python3, py -3). A Windows Store app execution alias does not count; install Python, or disable the python/python3 aliases under Settings > Apps > Advanced app settings > App execution aliases.'
|
||||||
|
}
|
||||||
|
|
||||||
|
# Runs Python with the given arguments; stdin is inherited, so pipe input with Get-PythonCommand instead.
|
||||||
|
function Invoke-Python {
|
||||||
|
$python = Get-PythonCommand -Required
|
||||||
|
& $python.Path @($python.Arguments) @args
|
||||||
|
}
|
||||||
@@ -1,7 +1,10 @@
|
|||||||
[CmdletBinding()]
|
[CmdletBinding()]
|
||||||
param()
|
param()
|
||||||
|
# Best effort: without Python 3.11+ this hook is a silent no-op; doctor reports that case.
|
||||||
try {
|
try {
|
||||||
$ErrorActionPreference = 'Stop'
|
$ErrorActionPreference = 'Stop'
|
||||||
& python (Join-Path $PSScriptRoot 'agent-guards.py') prompt 2>$null
|
. (Join-Path $PSScriptRoot 'Resolve-Python.ps1')
|
||||||
|
$python = Get-PythonCommand
|
||||||
|
if ($python) { & $python.Path @($python.Arguments) (Join-Path $PSScriptRoot 'agent-guards.py') prompt 2>$null }
|
||||||
} catch {}
|
} catch {}
|
||||||
exit 0
|
exit 0
|
||||||
@@ -1,7 +1,10 @@
|
|||||||
[CmdletBinding()]
|
[CmdletBinding()]
|
||||||
param()
|
param()
|
||||||
|
# Best effort: without Python 3.11+ this hook is a silent no-op; doctor reports that case.
|
||||||
try {
|
try {
|
||||||
$ErrorActionPreference = 'Stop'
|
$ErrorActionPreference = 'Stop'
|
||||||
& python (Join-Path $PSScriptRoot 'session-state.py') --hook 2>$null
|
. (Join-Path $PSScriptRoot 'Resolve-Python.ps1')
|
||||||
|
$python = Get-PythonCommand
|
||||||
|
if ($python) { & $python.Path @($python.Arguments) (Join-Path $PSScriptRoot 'session-state.py') --hook 2>$null }
|
||||||
} catch {}
|
} catch {}
|
||||||
exit 0
|
exit 0
|
||||||
@@ -1,5 +1,17 @@
|
|||||||
param([Parameter(Mandatory=$true)][string]$Command, [string]$Workspace = (Get-Location).Path)
|
# Without -Command this runs as a PreToolUse hook: it reads the event from stdin and exits 2 to block.
|
||||||
$dangerous = @('git reset --hard','git clean -fd','git clean -fx','Remove-Item -Recurse','rm -rf','format c:','del /s /q')
|
# With -Command it checks one command and also rejects absolute paths outside -Workspace.
|
||||||
foreach ($pattern in $dangerous) { if ($Command.IndexOf($pattern, [StringComparison]::OrdinalIgnoreCase) -ge 0) { Write-Error "Blocked potentially destructive command: $pattern"; exit 1 } }
|
# Pattern checks are a guard rail against accidents, not a security boundary.
|
||||||
if ($Command -match '(?i)(^|\s)([A-Z]:\\|/)(?!.*' + [regex]::Escape($Workspace) + ')') { Write-Error 'Blocked command containing an absolute path outside the workspace.'; exit 1 }
|
param([string]$Command, [string]$Workspace = (Get-Location).Path)
|
||||||
Write-Output 'PASS command safety'
|
. (Join-Path $PSScriptRoot 'Resolve-Python.ps1')
|
||||||
|
$python = Get-PythonCommand
|
||||||
|
$script = Join-Path $PSScriptRoot 'command-safety.py'
|
||||||
|
if ($PSBoundParameters.ContainsKey('Command')) {
|
||||||
|
if (-not $python) { Write-Error (Get-PythonMissingMessage); exit 1 }
|
||||||
|
# Pass the command on stdin: Windows PowerShell 5.1 does not escape embedded quotes in native arguments.
|
||||||
|
$Command | & $python.Path @($python.Arguments) $script --command - --workspace $Workspace
|
||||||
|
exit $LASTEXITCODE
|
||||||
|
}
|
||||||
|
# Registered hooks fail open without Python; doctor reports that case.
|
||||||
|
if (-not $python) { exit 0 }
|
||||||
|
& $python.Path @($python.Arguments) $script --hook
|
||||||
|
exit $LASTEXITCODE
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
set -uo pipefail
|
set -uo pipefail
|
||||||
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
|
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
|
||||||
python3 "$script_dir/agent-guards.py" stop 2>/dev/null || true
|
# Best effort: without Python 3.11+ this hook is a silent no-op; doctor reports that case.
|
||||||
|
. "$script_dir/resolve-python.sh"
|
||||||
|
if resolve_python; then run_python "$script_dir/agent-guards.py" stop 2>/dev/null || true; fi
|
||||||
@@ -0,0 +1,222 @@
|
|||||||
|
"""Block clearly destructive shell commands.
|
||||||
|
|
||||||
|
Hook mode (--hook) reads a Claude or Codex PreToolUse event from stdin and exits 2 with a
|
||||||
|
reason on stderr to block the tool call; anything it cannot parse is allowed (fail open).
|
||||||
|
CLI mode (--command) checks one command and additionally rejects absolute paths outside the
|
||||||
|
workspace. Both modes are guard rails against accidents, not a security boundary: they parse
|
||||||
|
command text and cannot see what scripts, aliases, or variables expand to at run time.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import ntpath
|
||||||
|
import os
|
||||||
|
import posixpath
|
||||||
|
import re
|
||||||
|
import shlex
|
||||||
|
import sys
|
||||||
|
|
||||||
|
WRAPPERS = {'sudo', 'command', 'builtin', 'exec', 'nohup', 'time', 'env', 'xargs'}
|
||||||
|
POSIX_SHELLS = {'bash', 'sh', 'zsh', 'dash', 'ksh'}
|
||||||
|
POWERSHELL_HOSTS = {'pwsh', 'powershell'}
|
||||||
|
POWERSHELL_REMOVE = {'remove-item', 'ri'}
|
||||||
|
# In PowerShell these aliases mean Remove-Item; in Bash, rm follows the POSIX rules instead.
|
||||||
|
POWERSHELL_REMOVE_ALIASES = {'rm', 'del', 'erase', 'rd', 'rmdir'}
|
||||||
|
CMD_REMOVE = {'del', 'erase', 'rd', 'rmdir'}
|
||||||
|
RECURSE_PARAMETER = re.compile(r'-r(?:e(?:c(?:u(?:r(?:s(?:e)?)?)?)?)?)?(?::\$true)?')
|
||||||
|
MAX_DEPTH = 3
|
||||||
|
|
||||||
|
|
||||||
|
def split_segments(command):
|
||||||
|
"""Split on ;, &, |, &&, || and newlines that are outside quotes."""
|
||||||
|
segments, current, quote = [], [], None
|
||||||
|
for character in command:
|
||||||
|
if quote:
|
||||||
|
current.append(character)
|
||||||
|
if character == quote:
|
||||||
|
quote = None
|
||||||
|
elif character in '\'"':
|
||||||
|
quote = character
|
||||||
|
current.append(character)
|
||||||
|
elif character in ';&|\n':
|
||||||
|
segments.append(''.join(current))
|
||||||
|
current = []
|
||||||
|
else:
|
||||||
|
current.append(character)
|
||||||
|
segments.append(''.join(current))
|
||||||
|
return [segment.strip() for segment in segments if segment.strip()]
|
||||||
|
|
||||||
|
|
||||||
|
def tokenize(segment):
|
||||||
|
try:
|
||||||
|
return shlex.split(segment, posix=True)
|
||||||
|
except ValueError:
|
||||||
|
return segment.split()
|
||||||
|
|
||||||
|
|
||||||
|
def program_name(token):
|
||||||
|
name = re.split(r'[\\/]', token)[-1].lower()
|
||||||
|
return re.sub(r'\.(exe|cmd|bat)$', '', name)
|
||||||
|
|
||||||
|
|
||||||
|
def strip_wrappers(tokens):
|
||||||
|
index = 0
|
||||||
|
while index < len(tokens):
|
||||||
|
token = tokens[index]
|
||||||
|
if program_name(token) in WRAPPERS or re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*=.*', token):
|
||||||
|
index += 1
|
||||||
|
continue
|
||||||
|
break
|
||||||
|
return tokens[index:]
|
||||||
|
|
||||||
|
|
||||||
|
def short_flags(tokens):
|
||||||
|
flags = set()
|
||||||
|
for token in tokens:
|
||||||
|
if re.fullmatch(r'-[A-Za-z]+', token):
|
||||||
|
flags.update(token[1:])
|
||||||
|
return flags
|
||||||
|
|
||||||
|
|
||||||
|
def git_subcommand(arguments):
|
||||||
|
index = 0
|
||||||
|
while index < len(arguments):
|
||||||
|
token = arguments[index]
|
||||||
|
if token in ('-C', '-c', '--git-dir', '--work-tree', '--namespace'):
|
||||||
|
index += 2
|
||||||
|
elif token.startswith('-'):
|
||||||
|
index += 1
|
||||||
|
else:
|
||||||
|
return token.lower(), [item.lower() for item in arguments[index + 1:]]
|
||||||
|
return '', []
|
||||||
|
|
||||||
|
|
||||||
|
def check_tokens(tokens, shell=None):
|
||||||
|
"""Return why the command is blocked; shell is 'bash', 'powershell', or None when unknown."""
|
||||||
|
tokens = strip_wrappers(tokens)
|
||||||
|
if not tokens:
|
||||||
|
return None
|
||||||
|
program = program_name(tokens[0])
|
||||||
|
arguments = tokens[1:]
|
||||||
|
lowered = [argument.lower() for argument in arguments]
|
||||||
|
if program == 'rm' and shell != 'powershell':
|
||||||
|
flags = short_flags(arguments)
|
||||||
|
recursive = bool(flags & {'r', 'R'}) or '--recursive' in lowered
|
||||||
|
force = 'f' in flags or '--force' in lowered
|
||||||
|
if recursive and force:
|
||||||
|
return 'recursive forced deletion (rm -rf)'
|
||||||
|
if program == 'git':
|
||||||
|
subcommand, rest = git_subcommand(arguments)
|
||||||
|
if subcommand == 'reset' and '--hard' in rest:
|
||||||
|
return 'discarding work tree changes (git reset --hard)'
|
||||||
|
if subcommand == 'clean' and ('f' in short_flags(rest) or '--force' in rest):
|
||||||
|
return 'deleting untracked files (git clean -f)'
|
||||||
|
powershell_remove = program in POWERSHELL_REMOVE or (shell != 'bash' and program in POWERSHELL_REMOVE_ALIASES)
|
||||||
|
if powershell_remove and any(RECURSE_PARAMETER.fullmatch(item) for item in lowered):
|
||||||
|
return 'recursive deletion (Remove-Item -Recurse)'
|
||||||
|
if program in CMD_REMOVE and '/s' in lowered and '/q' in lowered:
|
||||||
|
return 'quiet recursive deletion (del /s /q)'
|
||||||
|
if program == 'format' and any(re.fullmatch(r'[a-z]:', item) for item in lowered):
|
||||||
|
return 'formatting a drive'
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def nested_command(tokens):
|
||||||
|
"""Return (command, shell) for bash -c, pwsh -Command, cmd /c, and eval; otherwise None."""
|
||||||
|
tokens = strip_wrappers(tokens)
|
||||||
|
if not tokens:
|
||||||
|
return None
|
||||||
|
program = program_name(tokens[0])
|
||||||
|
if program == 'eval':
|
||||||
|
return ' '.join(tokens[1:]), 'bash'
|
||||||
|
for index, token in enumerate(tokens[1:], start=1):
|
||||||
|
lowered = token.lower()
|
||||||
|
nested = ' '.join(tokens[index + 1:])
|
||||||
|
if program in POSIX_SHELLS and re.fullmatch(r'-[a-z]*c', lowered):
|
||||||
|
return nested, 'bash'
|
||||||
|
if program in POWERSHELL_HOSTS and lowered in ('-c', '-command'):
|
||||||
|
return nested, 'powershell'
|
||||||
|
if program == 'cmd' and lowered in ('/c', '/k'):
|
||||||
|
return nested, None
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def find_violation(command, shell=None, depth=0):
|
||||||
|
if depth > MAX_DEPTH:
|
||||||
|
return None
|
||||||
|
for segment in split_segments(command):
|
||||||
|
tokens = tokenize(segment)
|
||||||
|
reason = check_tokens(tokens, shell)
|
||||||
|
if reason:
|
||||||
|
return reason
|
||||||
|
nested = nested_command(tokens)
|
||||||
|
if nested:
|
||||||
|
reason = find_violation(nested[0], nested[1], depth + 1)
|
||||||
|
if reason:
|
||||||
|
return reason
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def outside_workspace(command, workspace):
|
||||||
|
workspace = os.path.normcase(os.path.realpath(workspace))
|
||||||
|
for token in tokenize(command):
|
||||||
|
candidate = token.split('=', 1)[-1] if token.startswith('-') else token
|
||||||
|
if re.fullmatch(r'/[A-Za-z?]', candidate):
|
||||||
|
continue # cmd.exe switches such as /c or /s are not paths.
|
||||||
|
if not (posixpath.isabs(candidate) or ntpath.isabs(candidate)):
|
||||||
|
continue
|
||||||
|
resolved = os.path.normcase(os.path.realpath(candidate))
|
||||||
|
try:
|
||||||
|
inside = os.path.commonpath([resolved, workspace]) == workspace
|
||||||
|
except ValueError:
|
||||||
|
inside = False
|
||||||
|
if not inside:
|
||||||
|
return candidate
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def run_hook(data):
|
||||||
|
try:
|
||||||
|
event = json.loads(data.decode('utf-8', errors='replace'))
|
||||||
|
command = event.get('tool_input', {}).get('command')
|
||||||
|
tool = str(event.get('tool_name', '')).lower()
|
||||||
|
except (ValueError, AttributeError):
|
||||||
|
return 0
|
||||||
|
if not isinstance(command, str):
|
||||||
|
return 0
|
||||||
|
shell = tool if tool in ('bash', 'powershell') else None
|
||||||
|
reason = find_violation(command, shell)
|
||||||
|
if reason:
|
||||||
|
print(f'Blocked by command-safety hook: {reason}. Ask the user to run this command themselves if it is intended.', file=sys.stderr)
|
||||||
|
return 2
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def run_check(command, workspace):
|
||||||
|
reason = find_violation(command)
|
||||||
|
if reason:
|
||||||
|
print(f'Blocked potentially destructive command: {reason}', file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
path = outside_workspace(command, workspace)
|
||||||
|
if path:
|
||||||
|
print(f'Blocked command containing an absolute path outside the workspace: {path}', file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
print('PASS command safety')
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||||
|
mode = parser.add_mutually_exclusive_group(required=True)
|
||||||
|
mode.add_argument('--hook', action='store_true', help='read a PreToolUse event from stdin')
|
||||||
|
mode.add_argument('--command', help="command text to check, or '-' to read it from stdin")
|
||||||
|
parser.add_argument('--workspace', default=os.getcwd())
|
||||||
|
args = parser.parse_args()
|
||||||
|
if args.hook:
|
||||||
|
return run_hook(sys.stdin.buffer.read())
|
||||||
|
command = sys.stdin.read() if args.command == '-' else args.command
|
||||||
|
return run_check(command, args.workspace)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
sys.exit(main())
|
||||||
@@ -2,4 +2,5 @@
|
|||||||
set -uo pipefail
|
set -uo pipefail
|
||||||
root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)
|
root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)
|
||||||
[ "${AI_CONFIG_TELEMETRY:-1}" = 0 ] || { mkdir -p "$root/.ai-session" && printf '{"event":"compact","timestamp":"%s"}\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" >> "$root/.ai-session/telemetry.jsonl"; [ "$(wc -c < "$root/.ai-session/telemetry.jsonl")" -le 1048576 ] || mv -f "$root/.ai-session/telemetry.jsonl" "$root/.ai-session/telemetry.jsonl.1"; }
|
[ "${AI_CONFIG_TELEMETRY:-1}" = 0 ] || { mkdir -p "$root/.ai-session" && printf '{"event":"compact","timestamp":"%s"}\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" >> "$root/.ai-session/telemetry.jsonl"; [ "$(wc -c < "$root/.ai-session/telemetry.jsonl")" -le 1048576 ] || mv -f "$root/.ai-session/telemetry.jsonl" "$root/.ai-session/telemetry.jsonl.1"; }
|
||||||
python3 "$root/hooks/scripts/session-state.py" --hook 2>/dev/null || true
|
. "$root/hooks/scripts/resolve-python.sh"
|
||||||
|
if resolve_python; then run_python "$root/hooks/scripts/session-state.py" --hook 2>/dev/null || true; fi
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Resolves a working Python 3.11+ interpreter for Bash scripts and hooks.
|
||||||
|
# Source this file, then call resolve_python (sets the ai_python array) or run_python.
|
||||||
|
# Candidates are probed by running them, so the Windows Store "App execution alias" stub
|
||||||
|
# that Git Bash finds on PATH is rejected instead of being mistaken for Python.
|
||||||
|
|
||||||
|
ai_python=()
|
||||||
|
|
||||||
|
resolve_python() {
|
||||||
|
[ "${#ai_python[@]}" -eq 0 ] || return 0
|
||||||
|
local candidate
|
||||||
|
for candidate in python3 python 'py -3'; do
|
||||||
|
# shellcheck disable=SC2086 # 'py -3' is intentionally split into command and argument.
|
||||||
|
command -v ${candidate%% *} >/dev/null 2>&1 || continue
|
||||||
|
# shellcheck disable=SC2086
|
||||||
|
if $candidate -c 'import sys; sys.exit(0 if sys.version_info >= (3, 11) else 1)' >/dev/null 2>&1 </dev/null; then
|
||||||
|
read -r -a ai_python <<<"$candidate"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
python_missing_message() {
|
||||||
|
printf '%s\n' 'Python 3.11 or newer was not found (tried python3, python, py -3). A Windows Store app execution alias does not count; install Python, or disable the python/python3 aliases under Settings > Apps > Advanced app settings > App execution aliases.'
|
||||||
|
}
|
||||||
|
|
||||||
|
python_display() {
|
||||||
|
printf '%s' "${ai_python[*]}"
|
||||||
|
}
|
||||||
|
|
||||||
|
run_python() {
|
||||||
|
resolve_python || { python_missing_message >&2; return 127; }
|
||||||
|
"${ai_python[@]}" "$@"
|
||||||
|
}
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
set -uo pipefail
|
set -uo pipefail
|
||||||
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
|
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
|
||||||
python3 "$script_dir/agent-guards.py" prompt 2>/dev/null || true
|
# Best effort: without Python 3.11+ this hook is a silent no-op; doctor reports that case.
|
||||||
|
. "$script_dir/resolve-python.sh"
|
||||||
|
if resolve_python; then run_python "$script_dir/agent-guards.py" prompt 2>/dev/null || true; fi
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
set -uo pipefail
|
set -uo pipefail
|
||||||
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
|
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
|
||||||
python3 "$script_dir/session-state.py" --hook 2>/dev/null || true
|
# Best effort: without Python 3.11+ this hook is a silent no-op; doctor reports that case.
|
||||||
|
. "$script_dir/resolve-python.sh"
|
||||||
|
if resolve_python; then run_python "$script_dir/session-state.py" --hook 2>/dev/null || true; fi
|
||||||
File renamed without changes.
@@ -1,8 +1,17 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
set -euo pipefail
|
# Without arguments this runs as a PreToolUse hook: it reads the event from stdin and exits 2 to block.
|
||||||
|
# With a command argument it checks that command and also rejects absolute paths outside the
|
||||||
command_text=${1:?Command is required}
|
# workspace (second argument, default: the working directory).
|
||||||
for pattern in 'git reset --hard' 'git clean -fd' 'git clean -fx' 'rm -rf' 'Remove-Item -Recurse' 'format c:' 'del /s /q'; do
|
# Pattern checks are a guard rail against accidents, not a security boundary.
|
||||||
[[ ${command_text,,} != *"${pattern,,}"* ]] || { printf 'Blocked potentially destructive command: %s\n' "$pattern" >&2; exit 1; }
|
set -uo pipefail
|
||||||
done
|
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
|
||||||
printf 'PASS command safety\n'
|
# shellcheck source=resolve-python.sh
|
||||||
|
. "$script_dir/resolve-python.sh"
|
||||||
|
if [ $# -gt 0 ]; then
|
||||||
|
resolve_python || { python_missing_message >&2; exit 1; }
|
||||||
|
printf '%s' "$1" | run_python "$script_dir/command-safety.py" --command - --workspace "${2:-$PWD}"
|
||||||
|
exit $?
|
||||||
|
fi
|
||||||
|
# Registered hooks fail open without Python; doctor reports that case.
|
||||||
|
resolve_python || exit 0
|
||||||
|
run_python "$script_dir/command-safety.py" --hook
|
||||||
@@ -1,14 +1,14 @@
|
|||||||
# Angular Rules
|
# Angular Rules
|
||||||
|
|
||||||
For Angular work, open the focused topic rule that matches the change. Apply the security and accessibility rule whenever browser-facing behavior is affected.
|
For Angular work, open the focused topic rule that matches the change. Angular code is TypeScript: load the matching TypeScript topic rules (`rules/typescript/index.md` / `rules-typescript`) as well. Load the security and accessibility rule when the change renders untrusted content, binds HTML or URLs, configures HTTP security or tokens, or builds interactive controls.
|
||||||
|
|
||||||
| Topic | Codex rule | Claude skill |
|
| Topic | Codex rule | Claude skill |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| Components and state | `references/components-and-state.md` | `rules-angular-components-and-state` |
|
| Components, change detection, signals, and DOM access | `references/components-and-state.md` | `rules-angular-components-and-state` |
|
||||||
| Templates and styling | `references/templates-and-styling.md` | `rules-angular-templates-and-styling` |
|
| Templates and styling | `references/templates-and-styling.md` | `rules-angular-templates-and-styling` |
|
||||||
| RxJS | `references/rxjs.md` | `rules-angular-rxjs` |
|
| RxJS | `references/rxjs.md` | `rules-angular-rxjs` |
|
||||||
| Services and HTTP | `references/services-and-http.md` | `rules-angular-services-and-http` |
|
| Dependency injection, services, and HTTP | `references/services-and-http.md` | `rules-angular-services-and-http` |
|
||||||
| Forms and routing | `references/forms-and-routing.md` | `rules-angular-forms-and-routing` |
|
| Forms and routing | `references/forms-and-routing.md` | `rules-angular-forms-and-routing` |
|
||||||
| Security and accessibility | `references/security-and-accessibility.md` | `rules-angular-security-and-accessibility` |
|
| Security and accessibility | `references/security-and-accessibility.md` | `rules-angular-security-and-accessibility` |
|
||||||
| Performance | `references/performance.md` | `rules-angular-performance` |
|
| Performance | `references/performance.md` | `rules-angular-performance` |
|
||||||
| Testing and architecture | `references/testing-and-architecture.md` | `rules-angular-testing-and-architecture` |
|
| Testing, architecture, and package versions | `references/testing-and-architecture.md` | `rules-angular-testing-and-architecture` |
|
||||||
@@ -1,13 +1,18 @@
|
|||||||
|
# Angular Components, Change Detection, and Signals
|
||||||
|
|
||||||
|
Apply these rules when creating or changing Angular components, directives, signal state, change detection, or DOM access.
|
||||||
|
|
||||||
## Components
|
## Components
|
||||||
|
|
||||||
* Prefer standalone components, directives, and pipes for new work. Avoid introducing `NgModule` unless the existing architecture requires it.
|
* Prefer standalone components, directives, and pipes for new work. Avoid introducing `NgModule` unless the existing architecture requires it.
|
||||||
* Keep components small; move substantial business logic to a focused service or domain layer.
|
* Keep components small; move substantial business logic to a focused service or domain layer.
|
||||||
* Keep dependencies explicit and follow the feature architecture. Avoid god components, god services, unnecessary wrappers, and abstractions without a concrete need.
|
* Keep dependencies explicit and follow the feature architecture. Avoid god components, god services, unnecessary wrappers, and abstractions without a concrete need.
|
||||||
* Use `ChangeDetectionStrategy.OnPush` unless there is a concrete reason not to.
|
* Use `ChangeDetectionStrategy.OnPush` unless there is a concrete reason not to, in both zone.js and zoneless applications.
|
||||||
* Keep component state minimal and prefer immutable state updates.
|
* Keep component state minimal and prefer immutable state updates.
|
||||||
* Avoid direct mutation of shared state.
|
* Avoid direct mutation of shared state.
|
||||||
* Keep inputs and outputs strongly typed.
|
* Keep inputs and outputs strongly typed.
|
||||||
* Prefer signal-based inputs and outputs when consistent with the project.
|
* In new code on Angular 19+, use `input()` and `input.required()`, `output()` (an `OutputEmitterRef`, not a signal), `model()` for intended two-way bindings, and signal queries (`viewChild`, `viewChildren`, `contentChild`, `contentChildren`). Keep `@Input`, `@Output`, and decorator queries only where the surrounding code uses them.
|
||||||
|
* Use the `host` object in component metadata instead of `@HostBinding` and `@HostListener` in new code.
|
||||||
* Avoid unnecessary two-way binding.
|
* Avoid unnecessary two-way binding.
|
||||||
* Avoid unnecessary component-to-component coupling.
|
* Avoid unnecessary component-to-component coupling.
|
||||||
* Prefer explicit data flow from parent to child and explicit events upward.
|
* Prefer explicit data flow from parent to child and explicit events upward.
|
||||||
@@ -15,6 +20,12 @@
|
|||||||
* Use lifecycle hooks only when required.
|
* Use lifecycle hooks only when required.
|
||||||
* Avoid complex initialization logic inside constructors.
|
* Avoid complex initialization logic inside constructors.
|
||||||
|
|
||||||
|
## Change Detection
|
||||||
|
|
||||||
|
* Check whether the application uses zone.js or is zoneless: new applications are zoneless by default since Angular 21 (`provideZonelessChangeDetection`, stable since 20.2). Do not migrate between the two as a side effect of another task.
|
||||||
|
* In zoneless applications, change template-bound state only through signals, `markForCheck`, the `async` pipe, or template event handlers. Mutating plain fields in `setTimeout` or promise callbacks does not update the view.
|
||||||
|
* Do not add `NgZone` APIs (`onStable`, `onMicrotaskEmpty`, `runOutsideAngular`) for rendering logic; use `afterNextRender` or `afterRenderEffect` for DOM work after rendering.
|
||||||
|
|
||||||
## Signals and State
|
## Signals and State
|
||||||
|
|
||||||
* Prefer signals for local and synchronous reactive state.
|
* Prefer signals for local and synchronous reactive state.
|
||||||
@@ -22,5 +33,16 @@
|
|||||||
* Keep signals private when external mutation is not intended, and expose readonly state where practical.
|
* Keep signals private when external mutation is not intended, and expose readonly state where practical.
|
||||||
* Avoid circular signal dependencies.
|
* Avoid circular signal dependencies.
|
||||||
* Use `effect` only for actual side effects, not as a replacement for normal data flow. Keep effects small and deterministic, and clean up resources they create.
|
* Use `effect` only for actual side effects, not as a replacement for normal data flow. Keep effects small and deterministic, and clean up resources they create.
|
||||||
|
* Use `linkedSignal` (Angular 20+) for writable state that resets when a source changes, instead of an `effect` that writes signals.
|
||||||
|
* For parameter-driven reads, use `httpResource`, `resource`, or `rxResource` (stable since Angular 22; experimental in 19 to 21, so use them there only if the project already does). Use RxJS for event streams, cancellation semantics, and multi-step flows; convert with `toSignal` at the component edge, in an injection context. Never perform writes or mutations through resources.
|
||||||
* Do not use global state unless multiple unrelated parts of the application genuinely need it.
|
* Do not use global state unless multiple unrelated parts of the application genuinely need it.
|
||||||
* Do not introduce a state-management library without a clear requirement.
|
* Do not introduce a state-management library without a clear requirement.
|
||||||
|
|
||||||
|
## DOM and Browser APIs
|
||||||
|
|
||||||
|
* Prefer Angular APIs and declarative templates over direct DOM manipulation.
|
||||||
|
* Use `Renderer2` only when direct rendering abstraction is actually needed.
|
||||||
|
* Avoid accessing globals directly when it harms testability or SSR compatibility.
|
||||||
|
* When the application uses SSR, guard `window`, `document`, `localStorage`, and similar browser-only APIs with `isPlatformBrowser`, or run DOM access in `afterNextRender` or `afterRenderEffect`, which run only in the browser.
|
||||||
|
* Clean up event listeners, observers and timers.
|
||||||
|
* Avoid layout thrashing in performance-sensitive code.
|
||||||
@@ -1,11 +1,13 @@
|
|||||||
|
# Angular Forms and Routing
|
||||||
|
|
||||||
|
Apply these rules when building Angular forms, validation, routes, guards, or resolvers.
|
||||||
|
|
||||||
## Forms
|
## Forms
|
||||||
|
|
||||||
* Prefer reactive forms for non-trivial forms.
|
* Follow the form approach the project uses. For non-trivial forms, use typed reactive forms (`FormGroup`, `FormControl`, `NonNullableFormBuilder`; `nonNullable` controls where reset should restore the initial value) and never `Untyped*` classes in new code.
|
||||||
* Keep forms strongly typed.
|
* Signal forms (`@angular/forms/signals`) are stable since Angular 22. Use them for new forms only when the project is on 22+ and has adopted them; do not migrate existing forms unasked.
|
||||||
* Avoid untyped forms.
|
|
||||||
* Keep validation rules centralized and reusable where practical.
|
* Keep validation rules centralized and reusable where practical.
|
||||||
* Validate on both client and server where required.
|
* Client-side validation is user experience; the server must validate every submission. Never treat client-side validation as a security boundary.
|
||||||
* Never treat client-side validation as a security boundary.
|
|
||||||
* Keep form state separate from domain state when useful.
|
* Keep form state separate from domain state when useful.
|
||||||
* Avoid large components that combine layout, validation, persistence and business logic.
|
* Avoid large components that combine layout, validation, persistence and business logic.
|
||||||
* Display validation errors consistently.
|
* Display validation errors consistently.
|
||||||
@@ -14,11 +16,13 @@
|
|||||||
## Routing
|
## Routing
|
||||||
|
|
||||||
* Keep route definitions explicit and predictable.
|
* Keep route definitions explicit and predictable.
|
||||||
* Prefer lazy loading for larger feature areas.
|
* Prefer lazy loading for larger feature areas with `loadComponent` or `loadChildren` pointing to standalone route arrays.
|
||||||
|
* Write new guards and resolvers as functions (`CanActivateFn`, `ResolveFn`); keep class-based guards where the project uses them, since they remain supported.
|
||||||
|
* Use `withComponentInputBinding()` to bind route parameters to component inputs where the project enables it.
|
||||||
* Avoid loading large feature bundles eagerly without need.
|
* Avoid loading large feature bundles eagerly without need.
|
||||||
* Use route guards only for navigation behavior, not as a security boundary.
|
* Use route guards only for navigation behavior, not as a security boundary.
|
||||||
* Authorization must still be enforced on the backend.
|
* Authorization must still be enforced on the backend.
|
||||||
* Keep resolvers focused.
|
* Keep resolvers focused.
|
||||||
* Avoid expensive work during navigation unless required.
|
* Avoid expensive work during navigation unless required.
|
||||||
* Keep route parameters strongly typed at application boundaries where practical.
|
* Route and query parameters arrive as `string | null`. Parse and validate them before use and treat them as untrusted input.
|
||||||
* Do not rely on client-side routing state for sensitive authorization decisions.
|
* Do not rely on client-side routing state for sensitive authorization decisions.
|
||||||
@@ -1,33 +1,15 @@
|
|||||||
|
# Angular Performance
|
||||||
|
|
||||||
|
Apply these rules when optimizing Angular rendering, loading, bundle size, or hydration.
|
||||||
|
|
||||||
## Performance
|
## Performance
|
||||||
|
|
||||||
* Use `OnPush`.
|
Apply the TypeScript performance rule for general measurement, allocation, and bundle guidance, and these Angular-specific levers on top. Measure before optimizing.
|
||||||
* Use stable tracking in loops.
|
|
||||||
* Avoid unnecessary change detection triggers.
|
|
||||||
* Avoid repeated expensive template calculations.
|
|
||||||
* Avoid unnecessary subscriptions.
|
|
||||||
* Avoid unnecessary DOM rendering.
|
|
||||||
* Lazy-load large features and heavy dependencies where appropriate.
|
|
||||||
* Avoid large initial bundles.
|
|
||||||
* Avoid importing full libraries when only a small part is required.
|
|
||||||
* Avoid unnecessary deep cloning.
|
|
||||||
* Avoid unnecessary object and array recreation in hot paths.
|
|
||||||
* Keep state updates targeted.
|
|
||||||
* Avoid unnecessary global state updates.
|
|
||||||
* Measure bundle size and runtime performance before micro-optimizing.
|
|
||||||
* Prefer architectural improvements over template-level micro-optimizations.
|
|
||||||
|
|
||||||
## Performance Priority
|
* Use `OnPush` and signals so change detection touches only what changed (see the components rule for zoneless applications).
|
||||||
|
* Defer heavy, below-the-fold, or rarely used template parts with `@defer` and an explicit trigger such as `on viewport` or `on interaction`, with a placeholder that reserves layout space.
|
||||||
Prioritize Angular performance work in this order:
|
* Use `NgOptimizedImage` (`ngSrc`) for images, with explicit dimensions and `priority` for the largest contentful image.
|
||||||
|
* Lazy-load routes and heavy dependencies, and keep the bundle budgets in `angular.json` enforced; do not raise a budget to make a build pass without approval.
|
||||||
* Application architecture
|
* For server-side rendering, use `provideClientHydration()`, which includes incremental hydration since Angular 22; do not add the deprecated `withIncrementalHydration()` there. Use event replay instead of re-rendering on hydration.
|
||||||
* Network and API behavior
|
* Use `runOutsideAngular` only in zone.js applications, for high-frequency events that must not trigger change detection.
|
||||||
* Bundle size and lazy loading
|
* Keep RxJS and signal updates targeted; avoid global state updates for local changes.
|
||||||
* State architecture
|
|
||||||
* Change detection
|
|
||||||
* Rendering and DOM complexity
|
|
||||||
* RxJS and subscription behavior
|
|
||||||
* Memory allocations
|
|
||||||
* CPU micro-optimizations
|
|
||||||
|
|
||||||
Never optimize based purely on assumptions.
|
|
||||||
@@ -1,3 +1,7 @@
|
|||||||
|
# Angular RxJS
|
||||||
|
|
||||||
|
Apply these rules when writing or changing RxJS streams, subscriptions, or signal and observable interop in Angular.
|
||||||
|
|
||||||
## RxJS
|
## RxJS
|
||||||
|
|
||||||
* Use RxJS for asynchronous streams, events and complex reactive flows.
|
* Use RxJS for asynchronous streams, events and complex reactive flows.
|
||||||
|
|||||||
@@ -1,37 +1,20 @@
|
|||||||
|
# Angular Security and Accessibility
|
||||||
|
|
||||||
|
Apply these rules when Angular code renders untrusted content, binds HTML or URLs, configures HTTP security, handles tokens, or builds interactive UI. Load `rules-security-web` for the general browser rules and `rules-ui-ux-visual-and-accessibility` for general accessibility; this file adds only Angular specifics.
|
||||||
|
|
||||||
## Security
|
## Security
|
||||||
|
|
||||||
* Treat all external data as untrusted.
|
* Use `bypassSecurityTrust*` only as the shared web security rule allows: compile-time constants, developer-controlled values, or output of a maintained sanitizer, with the reason in a comment.
|
||||||
* Never bypass Angular sanitization without a verified reason.
|
* `[innerHTML]` is sanitized, but `ElementRef.nativeElement.innerHTML` and `Renderer2.setProperty(el, 'innerHTML', ...)` bypass sanitization; never use them with untrusted content.
|
||||||
* Avoid direct DOM manipulation.
|
* Never build templates from user data or compile templates at runtime.
|
||||||
* Avoid `innerHTML` with untrusted content.
|
* Angular's `HttpClient` sends the XSRF token (configured with `withXsrfConfiguration`) only on mutating requests to relative or same-origin URLs. APIs on another origin that use cookie authentication need their own CSRF protection.
|
||||||
* Avoid `bypassSecurityTrust*` unless explicitly required and the input is fully controlled.
|
* Prefer `autoCsp` (build option, inline scripts only, not with SSR) or a nonce through `ngCspNonce` or `CSP_NONCE` over relaxing the Content Security Policy.
|
||||||
* Never expose secrets in frontend code.
|
* Never place server secrets in the Angular application. Handle session tokens as the shared web security rule defines: prefer `HttpOnly` cookies or a backend-for-frontend; tokens the app must hold stay in memory, and refresh tokens never go into `localStorage` or `sessionStorage`.
|
||||||
* Never store sensitive credentials in the Angular application.
|
* Route guards and hidden UI are navigation aids, not authorization; enforce authorization on the backend.
|
||||||
* Do not rely on frontend checks for authorization.
|
|
||||||
* Enforce authentication and authorization on the backend.
|
|
||||||
* Avoid leaking sensitive information through logs or error messages.
|
|
||||||
* Use secure cookie or token handling according to the application's authentication architecture.
|
|
||||||
* Avoid storing sensitive tokens in insecure browser storage without a deliberate security decision.
|
|
||||||
* Do not disable security controls for convenience.
|
|
||||||
|
|
||||||
## DOM and Browser APIs
|
|
||||||
|
|
||||||
* Prefer Angular APIs and declarative templates over direct DOM manipulation.
|
|
||||||
* Use `Renderer2` only when direct rendering abstraction is actually needed.
|
|
||||||
* Avoid accessing globals directly when it harms testability or SSR compatibility.
|
|
||||||
* Consider SSR and hydration compatibility for browser-specific code.
|
|
||||||
* Guard access to `window`, `document`, `localStorage` and similar browser-only APIs when SSR is supported.
|
|
||||||
* Clean up event listeners, observers and timers.
|
|
||||||
* Avoid layout thrashing in performance-sensitive code.
|
|
||||||
|
|
||||||
## Accessibility
|
## Accessibility
|
||||||
|
|
||||||
* Use semantic HTML.
|
* Bind ARIA attributes with `[attr.aria-*]`, and keep accessible names and states synchronized with signal or component state.
|
||||||
* Preserve keyboard navigation.
|
* Use Angular CDK accessibility utilities (`FocusTrap`, `LiveAnnouncer`, `FocusMonitor`) instead of hand-written focus management, or `@angular/aria` where the project uses it.
|
||||||
* Ensure interactive elements are actually interactive elements.
|
* After router navigation, move focus to the main content or heading and update the page title (`Title` service or route `title`).
|
||||||
* Do not replace buttons with clickable `div` elements.
|
* Do not replace buttons or links with clickable `div` elements.
|
||||||
* Provide labels for form controls.
|
|
||||||
* Maintain visible focus behavior.
|
|
||||||
* Use ARIA only when native HTML semantics are insufficient.
|
|
||||||
* Avoid unnecessary custom widgets.
|
|
||||||
* Keep accessible names and states synchronized with UI state.
|
|
||||||
@@ -1,9 +1,13 @@
|
|||||||
|
# Angular Dependency Injection, Services, and HTTP
|
||||||
|
|
||||||
|
Apply these rules when creating Angular services, configuring dependency injection, or calling HTTP APIs.
|
||||||
|
|
||||||
## Dependency Injection
|
## Dependency Injection
|
||||||
|
|
||||||
* Prefer Angular dependency injection for application services.
|
* Prefer Angular dependency injection for application services.
|
||||||
* Keep injected dependencies minimal.
|
* Keep injected dependencies minimal.
|
||||||
* Avoid service locator patterns.
|
* Avoid service locator patterns.
|
||||||
* Prefer `inject()` where it improves readability and is consistent with the project.
|
* Prefer the `inject()` function over constructor parameter injection, as the Angular style guide recommends since v20; keep constructor injection where the surrounding code consistently uses it.
|
||||||
* Do not inject services that are not used.
|
* Do not inject services that are not used.
|
||||||
* Scope services intentionally.
|
* Scope services intentionally.
|
||||||
* Prefer application-wide singletons only for truly shared stateless or coordinated state.
|
* Prefer application-wide singletons only for truly shared stateless or coordinated state.
|
||||||
@@ -27,13 +31,13 @@
|
|||||||
|
|
||||||
* Keep API access centralized and strongly typed.
|
* Keep API access centralized and strongly typed.
|
||||||
* Prefer dedicated API clients or data-access services.
|
* Prefer dedicated API clients or data-access services.
|
||||||
* Do not use `any` for API responses.
|
* Do not use `any` for API responses. The type parameter of `HttpClient.get<T>()` or `httpResource<T>()` is a compile-time assertion, not validation.
|
||||||
* Treat all server responses as untrusted at runtime.
|
* Treat all server responses as `unknown` until validated, as in the TypeScript runtime-safety rule. Validate them with a schema or parser at the data-access boundary before they drive authorization, persistence, navigation, or rendering.
|
||||||
* Validate external data when the contract is security- or correctness-critical.
|
|
||||||
* Keep DTOs separate from domain models when their responsibilities differ.
|
* Keep DTOs separate from domain models when their responsibilities differ.
|
||||||
* Avoid duplicate API calls.
|
* Avoid duplicate API calls.
|
||||||
* Cache only when the invalidation strategy is clear.
|
* Cache only when the invalidation strategy is clear.
|
||||||
* Avoid manual URL string construction when typed helpers or centralized endpoints are available.
|
* Avoid manual URL string construction when typed helpers or centralized endpoints are available.
|
||||||
|
* Configure HTTP with `provideHttpClient(withInterceptors([...]), withFetch())` and functional interceptors in new code, not `HttpClientModule` or `HTTP_INTERCEPTORS` classes.
|
||||||
* Use interceptors only for cross-cutting concerns.
|
* Use interceptors only for cross-cutting concerns.
|
||||||
* Do not put unrelated business logic into HTTP interceptors.
|
* Do not put unrelated business logic into HTTP interceptors.
|
||||||
* Handle cancellation where appropriate.
|
* Handle cancellation where appropriate.
|
||||||
|
|||||||
@@ -1,18 +1,19 @@
|
|||||||
|
# Angular Templates and Styling
|
||||||
|
|
||||||
|
Apply these rules when writing Angular templates, control flow, or component styles.
|
||||||
|
|
||||||
## Templates
|
## Templates
|
||||||
|
|
||||||
* Keep expressions short and readable.
|
* Keep expressions short and readable.
|
||||||
* Do not execute expensive methods from templates.
|
* Reading signals and `computed` values in templates is correct. Do not call other methods that compute or allocate from templates; use `computed` or a pure pipe instead.
|
||||||
* Avoid function calls in templates when their result can be derived or cached.
|
|
||||||
* Avoid complex conditions directly in markup.
|
* Avoid complex conditions directly in markup.
|
||||||
* Prefer derived state in TypeScript over repeated template expressions.
|
* Prefer derived state in TypeScript over repeated template expressions.
|
||||||
* Use Angular control flow syntax such as `@if`, `@for` and `@switch` for new code.
|
* Use Angular control flow syntax such as `@if`, `@for` and `@switch` for new code.
|
||||||
* Always provide stable tracking for repeated collections.
|
* In `@for`, track a stable unique key such as `track item.id`; use `$index` only for static lists that never reorder. For legacy `*ngFor`, supply `trackBy`.
|
||||||
* Avoid deeply nested template structures.
|
* Avoid deeply nested template structures.
|
||||||
* Split large templates into focused components when it improves maintainability.
|
* Split large templates into focused components when it improves maintainability.
|
||||||
* Avoid unnecessary DOM elements.
|
* Avoid unnecessary DOM elements.
|
||||||
* Use semantic HTML.
|
* Use semantic HTML and native elements before custom implementations; see the accessibility section of the Angular security and accessibility rule.
|
||||||
* Prefer native HTML behavior before custom implementations.
|
|
||||||
* Keep accessibility in mind when choosing elements and interactions.
|
|
||||||
|
|
||||||
## Styling
|
## Styling
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,14 @@
|
|||||||
|
# Angular Testing and Architecture
|
||||||
|
|
||||||
|
Apply these rules when writing Angular tests, organizing features, or changing Angular package versions.
|
||||||
|
|
||||||
## Testing
|
## Testing
|
||||||
|
|
||||||
|
Apply the TypeScript testing rule for general test design, and these Angular specifics.
|
||||||
|
|
||||||
|
* Use the project's test runner. New CLI projects use Vitest since Angular 21; Karma remains supported, so do not migrate runners as part of another task.
|
||||||
|
* In zoneless tests, configure `TestBed` with `provideZonelessChangeDetection()` and use `await fixture.whenStable()` instead of `fakeAsync` and `tick`, which require zone.js.
|
||||||
|
* Set signal inputs with `fixture.componentRef.setInput()`. Test HTTP with `provideHttpClient()` plus `provideHttpClientTesting()` and `HttpTestingController`. Prefer Angular CDK component harnesses for interacting with material or CDK components.
|
||||||
* Test behavior, not implementation details.
|
* Test behavior, not implementation details.
|
||||||
* Prefer focused component tests.
|
* Prefer focused component tests.
|
||||||
* Test critical user interactions.
|
* Test critical user interactions.
|
||||||
@@ -26,29 +35,10 @@
|
|||||||
* Avoid exposing internal implementation details across feature boundaries.
|
* Avoid exposing internal implementation details across feature boundaries.
|
||||||
* Prefer local ownership of state and logic.
|
* Prefer local ownership of state and logic.
|
||||||
|
|
||||||
## Code Quality
|
## Code Quality and Dependencies
|
||||||
|
|
||||||
* Use strict TypeScript settings.
|
Apply the TypeScript rules for types, style, and dependency review, plus these Angular specifics.
|
||||||
* Avoid `any`.
|
|
||||||
* Avoid unnecessary type assertions.
|
|
||||||
* Avoid non-null assertions unless safety is guaranteed.
|
|
||||||
* Prefer modern, readable syntax.
|
|
||||||
* Use descriptive names.
|
|
||||||
* Avoid vague names such as `data`, `item`, `value` or `temp` when better names exist.
|
|
||||||
* Remove dead code.
|
|
||||||
* Remove unused imports and dependencies.
|
|
||||||
* Add comments only for non-obvious decisions or public contracts.
|
|
||||||
* Treat Angular, TypeScript and lint warnings seriously.
|
|
||||||
* Do not suppress diagnostics without a concrete reason.
|
|
||||||
* Prefer correctness, security and maintainability over cleverness.
|
|
||||||
|
|
||||||
## Dependency Rules
|
|
||||||
|
|
||||||
|
* Treat Angular compiler, template type-checking, and lint warnings seriously; do not suppress them without a concrete reason.
|
||||||
|
* Keep all `@angular/*` packages on the same major and minor version, and upgrade them with `ng update` so migrations run.
|
||||||
* Prefer Angular and browser platform capabilities before adding third-party libraries.
|
* Prefer Angular and browser platform capabilities before adding third-party libraries.
|
||||||
* Do not add dependencies without a clear benefit.
|
|
||||||
* Avoid libraries that duplicate existing framework functionality.
|
|
||||||
* Avoid abandoned or poorly maintained packages.
|
|
||||||
* Keep Angular package versions aligned.
|
|
||||||
* Do not mix incompatible Angular package versions.
|
|
||||||
* Respect the existing lockfile and package manager.
|
|
||||||
* Avoid unrelated dependency upgrades.
|
|
||||||
@@ -2,10 +2,11 @@
|
|||||||
|
|
||||||
Apply these rules when designing public APIs, service boundaries, or application architecture.
|
Apply these rules when designing public APIs, service boundaries, or application architecture.
|
||||||
|
|
||||||
* Give APIs explicit, strongly typed contracts. Keep trusted internal paths free of checks already done at the boundary.
|
* Give APIs explicit, strongly typed contracts. On trusted internal paths, do not repeat format or argument validation the boundary already performed. Authorization, resource ownership, and tenant scoping are never "already done": enforce them at the operation that accesses the data.
|
||||||
* Separate request models from persistence and domain models. Bind only fields the caller may set, and project only fields the caller may read.
|
* Separate request models from persistence and domain models. Bind only fields the caller may set, and project only fields the caller may read.
|
||||||
* Authenticate and authorize before accessing protected resources. Keep the decision close to the protected operation, enforce resource ownership and tenant scope in the data access path, not only in the UI or route layer, and fail closed when identity, ownership, or policy evaluation is unavailable.
|
* Authenticate and authorize before accessing protected resources. Keep the decision close to the protected operation, enforce resource ownership and tenant scope in the data access path, not only in the UI or route layer, and fail closed when identity, ownership, or policy evaluation is unavailable.
|
||||||
* Use explicit, bounded pagination for potentially large collections.
|
* Use explicit, bounded pagination for potentially large collections.
|
||||||
|
* Treat EF Core `DbContext` as a short-lived, non-thread-safe unit of work: scoped per request in web apps, created through `IDbContextFactory<T>` per operation in desktop apps and background services, never shared across threads or held as a singleton. Use `AsNoTracking` for read-only queries, and use `FromSql` or `FromSqlInterpolated` instead of concatenating into `FromSqlRaw`.
|
||||||
* Keep application, domain, and infrastructure concerns separate. Avoid cross-layer coupling and service-locator patterns.
|
* Keep application, domain, and infrastructure concerns separate. Avoid cross-layer coupling and service-locator patterns.
|
||||||
* Use dependency injection when substitution or lifecycle management is needed. Keep dependencies explicit and avoid excessive constructor dependencies.
|
* Use dependency injection when substitution or lifecycle management is needed. Keep dependencies explicit and avoid excessive constructor dependencies.
|
||||||
* Preserve established project and public API conventions unless a concrete compatibility or correctness issue requires a change.
|
* Preserve established project and public API conventions unless a concrete compatibility or correctness issue requires a change.
|
||||||
@@ -5,9 +5,11 @@ Apply these rules when adding or changing asynchronous APIs, background work, or
|
|||||||
* Use asynchronous APIs for genuinely asynchronous I/O; do not wrap synchronous work in unnecessary tasks.
|
* Use asynchronous APIs for genuinely asynchronous I/O; do not wrap synchronous work in unnecessary tasks.
|
||||||
* Keep asynchronous operations async through the call chain. Avoid `.Result`, `.Wait()`, and other synchronous waits that can block threads or deadlock.
|
* Keep asynchronous operations async through the call chain. Avoid `.Result`, `.Wait()`, and other synchronous waits that can block threads or deadlock.
|
||||||
* Accept and propagate `CancellationToken` through work that can take meaningful time or be cancelled by its caller.
|
* Accept and propagate `CancellationToken` through work that can take meaningful time or be cancelled by its caller.
|
||||||
* Bound concurrency for large or unbounded workloads. Avoid creating a task per item or using uncontrolled `Task.WhenAll`; use an appropriate queue or concurrency limiter when work must be throttled.
|
* In library and service code, use `ConfigureAwait(false)` or follow the project's CA2007 setting. In UI code (WPF view models and event handlers) use plain `await` so the continuation resumes on the UI thread.
|
||||||
* Use `ValueTask` only when profiling supports it and its usage contract is clear; otherwise prefer `Task`.
|
* Bound concurrency for large or unbounded workloads. Avoid creating a task per item or using uncontrolled `Task.WhenAll`; use `Parallel.ForEachAsync` with `MaxDegreeOfParallelism` (.NET 6+) or `SemaphoreSlim.WaitAsync` with the release in `finally`.
|
||||||
|
* Use `ValueTask` only when profiling supports it. Await a `ValueTask` exactly once, never concurrently, and never read `.Result` before it completes; otherwise prefer `Task`.
|
||||||
* Keep shared state safe under concurrent access and preserve cancellation and exception behavior when coordinating tasks. Prefer immutable messages or synchronization primitives with clear ownership over unsynchronized shared mutation.
|
* Keep shared state safe under concurrent access and preserve cancellation and exception behavior when coordinating tasks. Prefer immutable messages or synchronization primitives with clear ownership over unsynchronized shared mutation.
|
||||||
* Avoid holding locks across `await`, blocking thread-pool threads, and starting background work whose lifetime is detached from its owner.
|
* For synchronous locks on .NET 9+, prefer `System.Threading.Lock` over locking on `object`. Use `SemaphoreSlim` when a critical section contains `await`. Avoid blocking thread-pool threads and starting background work whose lifetime is detached from its owner.
|
||||||
* For producer/consumer work, apply backpressure and bound buffered items so a fast producer cannot exhaust memory.
|
* For producer/consumer work, use `Channel.CreateBounded` so a fast producer gets backpressure and cannot exhaust memory.
|
||||||
* Retry only transient failures, with bounded attempts and delay. Preserve idempotency and cancellation, and avoid multiplying retries across nested layers.
|
* Retry only transient failures, with bounded attempts and delay, in one layer only. Prefer the project's resilience library (`Microsoft.Extensions.Http.Resilience` or Polly v8) over hand-written loops. Preserve idempotency and cancellation.
|
||||||
|
* Create `HttpClient` through `IHttpClientFactory` or reuse a long-lived instance with `SocketsHttpHandler.PooledConnectionLifetime`; never create one per request.
|
||||||
@@ -2,8 +2,8 @@
|
|||||||
|
|
||||||
Apply these rules when editing C# syntax, class structure, and everyday code organization.
|
Apply these rules when editing C# syntax, class structure, and everyday code organization.
|
||||||
|
|
||||||
* Follow current C# and .NET conventions and the style already used in the project.
|
* Follow the style already used in the project. Before using newer syntax, check `TargetFramework` and `LangVersion`, including `Directory.Build.props`: `net10.0` defaults to C# 14, while .NET Framework 4.x defaults to C# 7.3, where records, file-scoped namespaces, collection expressions, primary constructors, and the `field` keyword are unavailable. Do not raise `LangVersion` without approval.
|
||||||
* Prefer direct, readable code over clever control flow, hidden magic, or outdated verbosity.
|
* Within the available language version, prefer direct, readable code over clever control flow, hidden magic, or outdated verbosity.
|
||||||
* Keep classes, methods, and responsibilities focused. Use descriptive names and established domain terms; avoid unexplained abbreviations.
|
* Keep classes, methods, and responsibilities focused. Use descriptive names and established domain terms; avoid unexplained abbreviations.
|
||||||
* Prefer composition over inheritance. Use inheritance only for a real substitutable contract, and seal types when extension is not intended.
|
* Prefer composition over inheritance. Use inheritance only for a real substitutable contract, and seal types when extension is not intended.
|
||||||
* Avoid unnecessary wrappers, abstractions, reflection, runtime type checks, and global mutable state.
|
* Avoid unnecessary wrappers, abstractions, reflection, runtime type checks, and global mutable state.
|
||||||
|
|||||||
@@ -6,8 +6,8 @@ Apply these rules when handling external input, failures, logs, or sensitive inf
|
|||||||
* Validate size, range, format, and allowed values before expensive parsing or allocation. Keep validation consistent with downstream business and security constraints.
|
* Validate size, range, format, and allowed values before expensive parsing or allocation. Keep validation consistent with downstream business and security constraints.
|
||||||
* Fail fast for invalid arguments or impossible state. Do not use exceptions for routine control flow or swallow unexpected exceptions.
|
* Fail fast for invalid arguments or impossible state. Do not use exceptions for routine control flow or swallow unexpected exceptions.
|
||||||
* Preserve useful exception context without exposing secrets, personal data, or internal details in logs, APIs, or user-facing errors.
|
* Preserve useful exception context without exposing secrets, personal data, or internal details in logs, APIs, or user-facing errors.
|
||||||
* Use structured logging and avoid excessive logging, especially in hot paths. Never log credentials, tokens, or sensitive payloads.
|
* Use structured logging with message templates and named placeholders, not string interpolation (CA2254); use `[LoggerMessage]` source-generated methods in hot paths. Never log credentials, tokens, or sensitive payloads.
|
||||||
* Dispose owned resources correctly, including on failure paths.
|
* Dispose owned resources with `using` or `await using` (for `IAsyncDisposable`), including on failure paths. Do not dispose dependencies injected by the container.
|
||||||
* Use narrow exception handling around the operation that can fail. Do not catch broadly merely to retry, continue with partial state, or convert failures into success.
|
* Use narrow exception handling around the operation that can fail. Do not catch broadly merely to retry, continue with partial state, or convert failures into success.
|
||||||
* Avoid returning different error detail to unauthenticated callers when it would disclose whether protected accounts, records, or resources exist.
|
* Avoid returning different error detail to unauthenticated callers when it would disclose whether protected accounts, records, or resources exist.
|
||||||
* Treat resource limits as part of safe error handling: cap request bodies, page sizes, query complexity, decompressed data, collection sizes, parser depth, and other attacker-controlled work.
|
* Treat resource limits as part of safe error handling: cap request bodies, page sizes, query complexity, decompressed data, collection sizes, parser depth, and other attacker-controlled work.
|
||||||
@@ -1,13 +1,12 @@
|
|||||||
# C# Security
|
# C# Security
|
||||||
|
|
||||||
Apply these rules when implementing or reviewing security-sensitive .NET code. Load the matching shared security rule for the affected API, identity, data, file, network, cryptographic, or dependency boundary as well.
|
Apply these rules when implementing or reviewing security-sensitive .NET code. Load the shared security rule for each affected boundary (API, auth, web, data, files, network, crypto, supply chain, AI); this file adds only .NET specifics.
|
||||||
|
|
||||||
* Use parameterized database APIs. If a query identifier or sort expression cannot be parameterized, select it from a fixed allowlist; never concatenate untrusted input into SQL.
|
* Use parameters with ADO.NET (`SqlParameter`) and EF Core (`FromSql` or `FromSqlInterpolated`, never concatenation into `FromSqlRaw` or `ExecuteSqlRaw`). Select dynamic identifiers and sort expressions from a fixed allowlist.
|
||||||
* For file access, canonicalize the resolved path and verify it remains inside the authorized root. Account for reparse points and symlinks when the attacker can affect directory contents.
|
* Resolve file paths with `Path.GetFullPath(Path.Combine(root, input))` and require the result to start with the root plus a trailing directory separator, using `StringComparison.OrdinalIgnoreCase` on Windows. Account for reparse points and symlinks when the attacker can affect directory contents.
|
||||||
* For process execution, avoid a shell. Pass executable and arguments separately using APIs supported by the target framework, validate each argument, and restrict executable paths.
|
* For process execution, set `ProcessStartInfo.UseShellExecute = false` explicitly (its default is `true` on .NET Framework), start the executable by absolute path, and pass arguments through `ArgumentList` (.NET Core 2.1+). On .NET Framework, build `Arguments` with correct Windows argument escaping instead of ad-hoc quoting. Never pass untrusted arguments to `.bat` or `.cmd` targets, because `cmd.exe` re-parses them; validate each argument against an allowlist.
|
||||||
* Deserialize into explicit DTOs or allowlisted types. Avoid unsafe polymorphic type activation and unbounded object graphs for untrusted data.
|
* Deserialize into explicit DTOs or allowlisted types. Prefer `System.Text.Json` and allow polymorphism only through registered `[JsonDerivedType]` types. For untrusted data never use `BinaryFormatter` (it throws since .NET 9; do not restore it through the unsupported compatibility package), `NetDataContractSerializer`, `SoapFormatter`, `LosFormatter`, or Newtonsoft.Json `TypeNameHandling` other than `None`. Bound object-graph depth and size.
|
||||||
* Apply timeouts to regular expressions that evaluate untrusted input and prefer patterns with predictable complexity.
|
* For regular expressions on untrusted input on .NET 7+, use `RegexOptions.NonBacktracking` when the pattern needs no backreferences or lookarounds; otherwise pass an explicit match timeout, because there is none by default. Declare regexes with `[GeneratedRegex]` on .NET 7+.
|
||||||
* Keep secrets in an approved secret store or protected configuration source. Never embed them in assemblies, client bundles, or source.
|
* Use `RandomNumberGenerator` for security values and `CryptographicOperations.FixedTimeEquals` for comparing secrets. Never return `true` unconditionally from `ServerCertificateCustomValidationCallback` or `RemoteCertificateValidationCallback`.
|
||||||
* Use platform TLS and established cryptographic APIs. Do not create custom cryptography or disable certificate validation; use cryptographically secure randomness for security tokens.
|
* Keep secrets in user secrets during development and in a secret store such as Azure Key Vault in deployed environments; use ASP.NET Core Data Protection for application-level protection of payloads. Never embed secrets in assemblies or client bundles.
|
||||||
* Use framework output encoding and safe APIs for HTML, XML, and other interpreters. Do not build executable markup or queries from untrusted strings.
|
* Use Razor's automatic encoding and `System.Text.Encodings.Web` encoders; avoid `Html.Raw` and `MarkupString` with untrusted content.
|
||||||
* Review security-sensitive changes with tests for rejected, malformed, oversized, unauthenticated, and cross-tenant inputs, as applicable.
|
|
||||||
@@ -2,8 +2,9 @@
|
|||||||
|
|
||||||
Apply these rules when changing tests, package references, analyzers, or build diagnostics.
|
Apply these rules when changing tests, package references, analyzers, or build diagnostics.
|
||||||
|
|
||||||
* Write deterministic behavior-based tests. Avoid coupling assertions to private call order, implementation details, current time, or uncontrolled external services.
|
* Write deterministic behavior-based tests. Avoid coupling assertions to private call order, implementation details, or uncontrolled external services. Inject `TimeProvider` (.NET 8+) instead of reading `DateTime.Now`, and use `FakeTimeProvider` from `Microsoft.Extensions.TimeProvider.Testing` in tests.
|
||||||
* Make code testable through clear contracts and dependencies; do not add production hooks or abstractions solely for tests without a concrete need.
|
* Make code testable through clear contracts and dependencies; do not add production hooks or abstractions solely for tests without a concrete need.
|
||||||
* Prefer the .NET BCL and existing supported packages over new libraries when they solve the problem adequately.
|
* Prefer the .NET BCL and existing supported packages over new libraries when they solve the problem adequately.
|
||||||
* Treat compiler, analyzer, and nullable warnings seriously. Suppress a diagnostic only for a specific, documented reason and narrow the suppression to the affected code.
|
* Treat compiler, analyzer, and nullable warnings seriously. Suppress a diagnostic only for a specific, documented reason and narrow the suppression to the affected code.
|
||||||
* Include analyzers in the verification of the changed path.
|
* Build the changed projects with analyzers enabled and warnings visible. Where the project sets `TreatWarningsAsErrors`, `AnalysisLevel`, or `EnforceCodeStyleInBuild`, never lower them to get a green build, and respect `.editorconfig`.
|
||||||
|
* Add or update packages through Central Package Management (`Directory.Packages.props`) when the repository uses it. Keep NuGetAudit enabled; it audits transitive packages by default only for `net10.0`+ projects, so prefer `NuGetAuditMode` `all` for older targets when the project allows it.
|
||||||
@@ -5,7 +5,7 @@ Apply these rules when designing type contracts, choosing collection shapes, or
|
|||||||
* Prefer strongly typed models over `object`, `dynamic`, loosely typed dictionaries, or string-based contracts.
|
* Prefer strongly typed models over `object`, `dynamic`, loosely typed dictionaries, or string-based contracts.
|
||||||
* Write null-safe code: enable nullable reference types where supported, model nullability accurately, and check nullable values before dereferencing them. Avoid null-forgiving operators unless a nearby invariant proves the value cannot be null.
|
* Write null-safe code: enable nullable reference types where supported, model nullability accurately, and check nullable values before dereferencing them. Avoid null-forgiving operators unless a nearby invariant proves the value cannot be null.
|
||||||
* Prefer concrete collection types for internal parameters, properties, and local APIs when the contract does not need abstraction.
|
* Prefer concrete collection types for internal parameters, properties, and local APIs when the contract does not need abstraction.
|
||||||
* Expose collection interfaces such as `IReadOnlyList<T>`, `IEnumerable<T>`, `IDictionary<TKey, TValue>`, or `ICollection<T>` only when their capability is part of an intentional boundary or public contract.
|
* At public boundaries, return read-only shapes (`IReadOnlyList<T>`, `IReadOnlyDictionary<TKey, TValue>`, or `ReadOnlyCollection<T>`) and accept the least capable interface the method needs (`IEnumerable<T>` or `IReadOnlyCollection<T>`). Expose mutable interfaces such as `IList<T>` or `IDictionary<TKey, TValue>` only when callers must mutate. Consider `FrozenDictionary` or `FrozenSet` (.NET 8+) for read-mostly lookups.
|
||||||
* Choose collection types based on lookup, ordering, mutation, and iteration needs. Pre-size collections only when expected capacity is known and material.
|
* Choose collection types based on lookup, ordering, mutation, and iteration needs. Pre-size collections only when expected capacity is known and material.
|
||||||
* Avoid large mutable structs and direct exposure of mutable internal collections.
|
* Avoid large mutable structs and direct exposure of mutable internal collections.
|
||||||
* Prefer immutable data and readonly state where practical, while preserving established API and serialization contracts.
|
* Prefer immutable data and readonly state where practical, while preserving established API and serialization contracts.
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
## Decision Rule
|
# Decision Rule
|
||||||
|
|
||||||
* Gather evidence from the repository, available tooling, and current technical sources before making technical decisions.
|
* Gather evidence from the repository, available tooling, and current technical sources before making technical decisions.
|
||||||
* Make technical implementation and code-style decisions independently when existing code, reliable documentation, or established standards provide sufficient evidence and the decision is reversible.
|
* Make technical implementation and code-style decisions independently when existing code, reliable documentation, or established standards provide sufficient evidence and the decision is reversible.
|
||||||
|
|||||||
@@ -10,5 +10,6 @@ For Java or JVM work, open only the topic rules relevant to the task. Follow the
|
|||||||
| Async work and concurrency | `references/async-and-concurrency.md` | `rules-java-async-and-concurrency` |
|
| Async work and concurrency | `references/async-and-concurrency.md` | `rules-java-async-and-concurrency` |
|
||||||
| Performance | `references/performance.md` | `rules-java-performance` |
|
| Performance | `references/performance.md` | `rules-java-performance` |
|
||||||
| Security | `references/security.md` | `rules-java-security` |
|
| Security | `references/security.md` | `rules-java-security` |
|
||||||
|
| Spring Boot and Spring Security | `references/spring.md` | `rules-java-spring` |
|
||||||
| Validation, errors, and logging | `references/safety-and-errors.md` | `rules-java-safety-and-errors` |
|
| Validation, errors, and logging | `references/safety-and-errors.md` | `rules-java-safety-and-errors` |
|
||||||
| Tests, dependencies, and build diagnostics | `references/testing-and-dependencies.md` | `rules-java-testing-and-dependencies` |
|
| Tests, dependencies, and build diagnostics | `references/testing-and-dependencies.md` | `rules-java-testing-and-dependencies` |
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Apply these rules when designing public APIs, service boundaries, or application structure.
|
Apply these rules when designing public APIs, service boundaries, or application structure.
|
||||||
|
|
||||||
* Give APIs explicit request, response, and error contracts. Validate external input at the boundary without scattering redundant checks through trusted internal code.
|
* Give APIs explicit request, response, and error contracts. Validate external input at the boundary without scattering redundant format checks through trusted internal code; authorization, ownership, and tenant scoping are never such redundant checks.
|
||||||
* Separate transport models, domain models, and persistence entities. Accept only fields callers may set and return only fields they may read.
|
* Separate transport models, domain models, and persistence entities. Accept only fields callers may set and return only fields they may read.
|
||||||
* Authorize the specific resource and operation where data is accessed or changed. Preserve ownership and tenant scope across alternate paths and background work.
|
* Authorize the specific resource and operation where data is accessed or changed. Preserve ownership and tenant scope across alternate paths and background work.
|
||||||
* Bound payloads, page sizes, query complexity, and operation cost. Use pagination or streaming for potentially large results.
|
* Bound payloads, page sizes, query complexity, and operation cost. Use pagination or streaming for potentially large results.
|
||||||
|
|||||||
@@ -3,10 +3,13 @@
|
|||||||
Apply these rules when changing executors, threads, futures, background work, or shared state.
|
Apply these rules when changing executors, threads, futures, background work, or shared state.
|
||||||
|
|
||||||
* Choose synchronous, asynchronous, platform-thread, or virtual-thread execution for the actual workload and target Java release. Virtual threads suit many blocking I/O tasks; they do not accelerate CPU work.
|
* Choose synchronous, asynchronous, platform-thread, or virtual-thread execution for the actual workload and target Java release. Virtual threads suit many blocking I/O tasks; they do not accelerate CPU work.
|
||||||
|
* Create one virtual thread per task (`Executors.newVirtualThreadPerTaskExecutor()`); never pool virtual threads. Limit downstream concurrency with a `Semaphore`, not with a fixed pool size.
|
||||||
|
* On JDK 21 to 23, blocking inside `synchronized` pins the carrier thread; prefer `ReentrantLock` on hot blocking paths there. JDK 24+ (JEP 491) removes that pinning, but native frames and class initialization still pin.
|
||||||
|
* Do not cache expensive objects in `ThreadLocal` when running on virtual threads. On JDK 25+, prefer `ScopedValue` (final, JEP 506) for request-scoped context.
|
||||||
* Keep task lifetime owned by a request, service, or scoped executor. Close or shut down owned executors and handle completion, failure, timeout, and cancellation.
|
* Keep task lifetime owned by a request, service, or scoped executor. Close or shut down owned executors and handle completion, failure, timeout, and cancellation.
|
||||||
* Propagate interruption and cancellation. When catching `InterruptedException` without rethrowing it, restore the interrupt flag and stop work safely; do not turn cancellation into success.
|
* Propagate interruption and cancellation. When catching `InterruptedException` without rethrowing it, restore the interrupt flag and stop work safely; do not turn cancellation into success.
|
||||||
* Bound queues, fan-out, and downstream calls. Virtual threads reduce thread cost but do not remove database, network, memory, or rate limits.
|
* Bound queues, fan-out, and downstream calls. Virtual threads reduce thread cost but do not remove database, network, memory, or rate limits.
|
||||||
* Protect shared mutable state with clear ownership or suitable concurrency primitives. Do not assume `volatile` makes compound actions atomic.
|
* Protect shared mutable state with clear ownership or suitable concurrency primitives. Do not assume `volatile` makes compound actions atomic.
|
||||||
* Avoid blocking joins inside unrelated executor tasks when they can exhaust a bounded pool. Use `CompletableFuture` or parallel streams only when their execution context and failure behavior are understood.
|
* Avoid blocking joins inside unrelated executor tasks when they can exhaust a bounded pool. Use `CompletableFuture` or parallel streams only when their execution context and failure behavior are understood.
|
||||||
* Keep retries limited to transient failures, with bounded attempts and delay. Preserve idempotency and avoid retry multiplication across layers.
|
* Keep retries limited to transient failures, with bounded attempts and delay. Preserve idempotency and avoid retry multiplication across layers.
|
||||||
* Use preview concurrency APIs only when the project explicitly enables them for its target release.
|
* Use preview concurrency APIs only when the project explicitly enables them for its target release; `StructuredTaskScope` is still a preview API in JDK 25.
|
||||||
@@ -7,5 +7,5 @@ Apply these rules when handling external input, failures, resources, or logs.
|
|||||||
* Use try-with-resources for owned `AutoCloseable` resources. Keep ownership explicit and do not close resources supplied by a caller unless the contract says so.
|
* Use try-with-resources for owned `AutoCloseable` resources. Keep ownership explicit and do not close resources supplied by a caller unless the contract says so.
|
||||||
* Catch only failures the current layer can handle. Preserve exception causes and useful context; do not swallow failures, catch broadly to continue with partial state, or use exceptions for routine control flow.
|
* Catch only failures the current layer can handle. Preserve exception causes and useful context; do not swallow failures, catch broadly to continue with partial state, or use exceptions for routine control flow.
|
||||||
* Preserve interruption and cancellation during error handling. Timeouts and retries need bounds and must not silently turn failure into success.
|
* Preserve interruption and cancellation during error handling. Timeouts and retries need bounds and must not silently turn failure into success.
|
||||||
* Use structured logs where the project supports them. Never log credentials, tokens, personal data, or unbounded payloads; avoid excessive logging in hot paths.
|
* Use structured logs where the project supports them. Never log credentials, tokens, personal data, or unbounded payloads; avoid excessive logging in hot paths. Pass untrusted values as parameters, never as the log format string, and strip or encode CR/LF in them unless the log format is structured.
|
||||||
* Return safe, consistent error information. Do not disclose protected resource existence or internal details to unauthorized callers.
|
* Return safe, consistent error information. Do not disclose protected resource existence or internal details to unauthorized callers.
|
||||||
Loaded 100 of 148 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user