Compare commits
43
Commits
e19aa2e27c
...
main
No files matched your search
+34
-9
@@ -48,6 +48,10 @@ jobs:
|
||||
python-version: '3.12'
|
||||
- name: Compile Python sources
|
||||
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
|
||||
run: |
|
||||
set -euo pipefail
|
||||
@@ -71,10 +75,12 @@ jobs:
|
||||
if ! command -v pwsh >/dev/null 2>&1; then
|
||||
# Microsoft's signed apt repository; the job fails when PowerShell cannot be installed.
|
||||
. /etc/os-release
|
||||
wget -q -O "$RUNNER_TEMP/packages-microsoft-prod.deb" "https://packages.microsoft.com/config/$ID/$VERSION_ID/packages-microsoft-prod.deb"
|
||||
# Runner DNS fails intermittently (wget exit 4); retry transient network errors and keep them visible.
|
||||
wget -nv --tries=5 --waitretry=10 --retry-connrefused --retry-on-host-error \
|
||||
-O "$RUNNER_TEMP/packages-microsoft-prod.deb" "https://packages.microsoft.com/config/$ID/$VERSION_ID/packages-microsoft-prod.deb"
|
||||
sudo dpkg -i "$RUNNER_TEMP/packages-microsoft-prod.deb"
|
||||
sudo apt-get update
|
||||
sudo apt-get install --yes --no-install-recommends powershell
|
||||
sudo apt-get -o Acquire::Retries=5 update
|
||||
sudo apt-get -o Acquire::Retries=5 install --yes --no-install-recommends powershell
|
||||
fi
|
||||
pwsh -NoLogo -NoProfile -NonInteractive -Command '$PSVersionTable.PSVersion.ToString()'
|
||||
- name: Run PowerShell tests
|
||||
@@ -107,6 +113,16 @@ jobs:
|
||||
bash scripts/commands/build.sh --summary
|
||||
after=$(find generated -type f -print0 | sort -z | xargs -0 sha256sum)
|
||||
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:
|
||||
name: Bash integration and installation guards
|
||||
@@ -115,13 +131,15 @@ jobs:
|
||||
needs: [build]
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Build packages for integration checks
|
||||
env:
|
||||
REQUIRE_CODEX_SCHEMA: 'false'
|
||||
run: bash scripts/commands/build.sh --summary
|
||||
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||
with:
|
||||
name: generated-packages
|
||||
- name: Unpack generated packages
|
||||
run: tar -xzf generated.tar.gz && rm generated.tar.gz
|
||||
- name: Run integration tests
|
||||
run: |
|
||||
set -euo pipefail
|
||||
bash scripts/tests/test-capabilities.sh --summary
|
||||
bash scripts/tests/test-install-guards.sh --summary
|
||||
bash scripts/tests/test-plugin-selection.sh --summary
|
||||
bash scripts/tests/test-quick-update.sh --summary
|
||||
@@ -149,8 +167,11 @@ jobs:
|
||||
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
|
||||
with:
|
||||
python-version: '3.12'
|
||||
- name: Build packages
|
||||
run: bash scripts/commands/build.sh --summary
|
||||
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||
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
|
||||
with:
|
||||
node-version: '24'
|
||||
@@ -184,6 +205,8 @@ jobs:
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v22.16.0
|
||||
with:
|
||||
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.
|
||||
- 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
|
||||
@@ -206,6 +229,8 @@ jobs:
|
||||
! grep -RInE "$unsafe_patterns" .gitea/workflows
|
||||
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
|
||||
# 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
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
@@ -92,22 +92,29 @@ Install and update also rebuild internally; the explicit build above lets you ch
|
||||
- A managed-file manifest tracks unchanged and stale files. Replaced files are backed up; locally modified stale
|
||||
files are retained with a warning.
|
||||
- Dry-run support (no destination writes, backups, or plugin changes) and timestamped backup directories.
|
||||
- Finish notifications, Claude session-state hooks, optional safety utilities, and compact status displays.
|
||||
- Finish notifications, session-state and compaction hooks, a command-safety hook that blocks clearly destructive
|
||||
shell commands, and compact status displays for both clients.
|
||||
- Separate install, update, and uninstall scripts: install refuses to run against an already-installed destination,
|
||||
update refuses to run against one that is not installed yet, and uninstall refuses to run against one that was
|
||||
never installed.
|
||||
- User-level extension installation for Ponytail, i-have-adhd, Superpowers, Context7, Caveman, MCPorter,
|
||||
Humanizer, Impeccable, and Anthropic Frontend Design, with an interactive extension toggle during both install and update. Only extensions
|
||||
installed and recorded by this setup can be removed through deselection.
|
||||
- Optional local search for both clients through QMD with Qwen3-Embedding-0.6B, Qwen3-Reranker-0.6B, and QMD Query Expansion 1.7B (Yes/No/Auto; Auto benchmarks GPU, then CPU).
|
||||
Humanizer, Impeccable, Apple Design, REA, Modern Web Guidance, and Roast Room, with an interactive extension toggle
|
||||
during both install and update. Only extensions installed and recorded by this setup can be removed through deselection.
|
||||
- Roast Room, an advisory board of AI seats that roasts a business decision, with a live room in the browser. The setup
|
||||
keeps one Git clone in `~/.my-ai-configuration/roast-room` for both clients, and a launcher skill runs it from any
|
||||
folder (`/roast-room` in Claude Code, `$roast-room` in Codex). It runs only when invoked by name. See
|
||||
[Plugins](docs/plugins.md) for details.
|
||||
- Optional local search for both clients through QMD with Qwen3-Embedding-4B, Qwen3-Reranker-4B, and QMD Query Expansion 1.7B (Yes/No/Auto; Auto benchmarks GPU, then CPU).
|
||||
|
||||
## Requirements
|
||||
|
||||
- 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`.
|
||||
- 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.
|
||||
- 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. npm's global bin directory (`npm prefix --global`; on Windows usually `%APPDATA%\npm`) must be on `PATH` so agents can call `mcporter`; `doctor` warns when it is missing.
|
||||
- Git and Node.js 20 or newer for Roast Room: Git keeps the clone current, and Node.js serves the live room. Without
|
||||
Node.js the board still runs, just without the live room.
|
||||
|
||||
Core Bash setup scripts do not require PowerShell. The credential commands use Windows Credential Manager and require
|
||||
PowerShell, including when invoked through their Bash wrappers. The PowerShell scripts remain compatible with
|
||||
@@ -233,8 +240,7 @@ Dry runs still rebuild `generated/`, but do not modify installation destinations
|
||||
Selecting Codex also installs shared skills to `.agents/skills`. An interactive extension list includes plugins and
|
||||
Codex skills; unchecked extensions are skipped on installation. Normal install and update ask whether to enable
|
||||
Flashbang, apply the custom status line, and enable local QMD search. Choices are saved for Quickupdate.
|
||||
The shared skill catalog includes development skills and focused writing, image, site structure, psychology, and
|
||||
conversion skills. All retained skills are included in both generated clients; installation includes `semantic-search` only when local QMD search is enabled.
|
||||
The shared skill catalog includes development skills, a media skill, and the Roast Room launcher. All retained skills are included in both generated clients; installation includes `semantic-search` only when local QMD search is enabled.
|
||||
The status line defaults to enabled to preserve existing behavior. Disabling it removes the custom client setting and,
|
||||
for Claude, the setup-owned status line script. Disabling local QMD search removes its setup-owned package, models, and repository collections once no client still uses it. See [Local QMD search](docs/configuration.md#local-qmd-search) for storage and removal details.
|
||||
Dry runs preview changes without updating extensions or retrieval. See [Plugins](docs/plugins.md) for client-specific behavior.
|
||||
@@ -303,9 +309,9 @@ Codex and Claude Code receive the same shared rules, skills, agents, hooks, and
|
||||
|
||||
Codex defaults to full access under the account that launches it, with unrestricted command network access.
|
||||
Launch Codex as the repository owner; Codex does not switch to that owner automatically. Full access removes
|
||||
Codex's filesystem sandbox boundaries. Eligible approval requests still use automatic review. Claude uses
|
||||
automatic permissions and enables its sandbox where the platform supports it; explicit deny rules still apply where it
|
||||
does not. Both clients include the same logical agent roles and compact status displays. See
|
||||
Codex's filesystem sandbox boundaries. Eligible approval requests still use automatic review, and execpolicy rules
|
||||
forbid a few destructive Git and `rm` commands. Claude uses automatic permissions and enables its sandbox where the
|
||||
platform supports it; explicit deny rules still apply where it does not. Both clients include the same logical agent roles and compact status displays. See
|
||||
[Configuration](docs/configuration.md) for settings, permissions, and limitations.
|
||||
|
||||
## Support
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
role tools
|
||||
architect Read,Grep,Glob,WebFetch,WebSearch,__SHELL__
|
||||
researcher Read,Grep,Glob,WebFetch,WebSearch,__SHELL__
|
||||
reviewer Read,Grep,Glob,__SHELL__
|
||||
verifier Read,Grep,Glob,__SHELL__
|
||||
implementer Read,Grep,Glob,Edit,Write,__SHELL__
|
||||
role tools skills
|
||||
architect Read,Grep,Glob,WebFetch,WebSearch,__SHELL_TOOL__,Skill rules-orchestration
|
||||
researcher Read,Grep,Glob,WebFetch,WebSearch,__SHELL_TOOL__,Skill rules-orchestration,research
|
||||
reviewer Read,Grep,Glob,__SHELL_TOOL__,Skill rules-orchestration,review-pull-request
|
||||
verifier Read,Grep,Glob,__SHELL_TOOL__,Skill rules-orchestration
|
||||
implementer Read,Grep,Glob,Edit,Write,__SHELL_TOOL__,Skill rules-orchestration
|
||||
|
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"permissions": {
|
||||
"defaultMode": "auto",
|
||||
"allow": __CLAUDE_ALLOW_RULES__,
|
||||
"deny": __CLAUDE_DENY_RULES__
|
||||
"allow": ["Agent", "__SHELL_TOOL__(mcporter call context7.*)"],
|
||||
"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__,
|
||||
"env": {
|
||||
@@ -15,6 +15,10 @@
|
||||
"command": "__STATUSLINE_COMMAND__ \"__AI_CONFIG_ROOT__/statusline/__STATUSLINE_SCRIPT__\""
|
||||
},
|
||||
"hooks": {
|
||||
"PreToolUse": [
|
||||
{"matcher": "Bash|PowerShell", "hooks": [{"type": "command", "command": "__HOOK_COMMAND__ \"__AI_CONFIG_ROOT__/hooks/scripts/__COMMAND_SAFETY_SCRIPT__\"", "timeout": 6}]},
|
||||
{"matcher": "Grep|Glob", "hooks": [{"type": "command", "command": "__HOOK_COMMAND__ \"__AI_CONFIG_ROOT__/hooks/scripts/__SEARCH_REMINDER_SCRIPT__\"", "timeout": 4}]}
|
||||
],
|
||||
"PreCompact": [{"hooks": [{"type": "command", "command": "__HOOK_COMMAND__ \"__AI_CONFIG_ROOT__/hooks/scripts/__COMPACT_SCRIPT__\"", "timeout": 4}]}],
|
||||
"SessionStart": [
|
||||
{"hooks": [{"type": "command", "command": "__HOOK_COMMAND__ \"__AI_CONFIG_ROOT__/hooks/scripts/__SESSION_POINTER_SCRIPT__\"", "timeout": 4}]},
|
||||
|
||||
@@ -1 +1 @@
|
||||
Read skills/rules-orchestration/SKILL.md from your installed configuration before acting as a subagent.
|
||||
Follow the preloaded `rules-orchestration` skill as a subagent; if it is not in your context, read skills/rules-orchestration/SKILL.md from your installed configuration first.
|
||||
@@ -41,3 +41,51 @@ type = "command"
|
||||
command = '__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
|
||||
|
||||
[[hooks.SessionStart]]
|
||||
[[hooks.SessionStart.hooks]]
|
||||
type = "command"
|
||||
command = '__HOOK_COMMAND__ "__AI_CONFIG_ROOT__/hooks/scripts/__SESSION_POINTER_SCRIPT__"'
|
||||
command_windows = '__POWERSHELL_HOOK_COMMAND__ "__AI_CONFIG_ROOT__/hooks/scripts/__SESSION_POINTER_SCRIPT__"'
|
||||
timeout = 4
|
||||
|
||||
# Caveman's Codex skill has no hook of its own here; this prints it at every start, resume, clear, and compaction.
|
||||
[[hooks.SessionStart]]
|
||||
[[hooks.SessionStart.hooks]]
|
||||
type = "command"
|
||||
command = '__HOOK_COMMAND__ "__AI_CONFIG_ROOT__/hooks/scripts/__CAVEMAN_SCRIPT__"'
|
||||
command_windows = '__POWERSHELL_HOOK_COMMAND__ "__AI_CONFIG_ROOT__/hooks/scripts/__CAVEMAN_SCRIPT__"'
|
||||
timeout = 4
|
||||
|
||||
[[hooks.PreCompact]]
|
||||
[[hooks.PreCompact.hooks]]
|
||||
type = "command"
|
||||
command = '__HOOK_COMMAND__ "__AI_CONFIG_ROOT__/hooks/scripts/__COMPACT_SCRIPT__"'
|
||||
command_windows = '__POWERSHELL_HOOK_COMMAND__ "__AI_CONFIG_ROOT__/hooks/scripts/__COMPACT_SCRIPT__"'
|
||||
timeout = 4
|
||||
|
||||
# Codex reports every shell command as Bash; on Windows it is PowerShell text, so check both dialects there.
|
||||
# The same hook process also reminds to run semantic-search before open shell searches; a no-op without QMD.
|
||||
[[hooks.PreToolUse]]
|
||||
matcher = "Bash"
|
||||
[[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__" -Shell unknown'
|
||||
timeout = 6
|
||||
|
||||
# Impeccable's design detector; the wrapper is a no-op unless the Impeccable Codex skill is installed.
|
||||
[[hooks.PostToolUse]]
|
||||
matcher = "Edit|Write|apply_patch"
|
||||
[[hooks.PostToolUse.hooks]]
|
||||
type = "command"
|
||||
command = '__HOOK_COMMAND__ "__AI_CONFIG_ROOT__/hooks/scripts/__IMPECCABLE_HOOK_SCRIPT__"'
|
||||
command_windows = '__POWERSHELL_HOOK_COMMAND__ "__AI_CONFIG_ROOT__/hooks/scripts/__IMPECCABLE_HOOK_SCRIPT__"'
|
||||
timeout = 10
|
||||
|
||||
[[hooks.Stop]]
|
||||
[[hooks.Stop.hooks]]
|
||||
type = "command"
|
||||
command = '__HOOK_COMMAND__ "__AI_CONFIG_ROOT__/hooks/scripts/__IMPECCABLE_HOOK_SCRIPT__"'
|
||||
command_windows = '__POWERSHELL_HOOK_COMMAND__ "__AI_CONFIG_ROOT__/hooks/scripts/__IMPECCABLE_HOOK_SCRIPT__"'
|
||||
timeout = 30
|
||||
@@ -0,0 +1,45 @@
|
||||
# Managed by MyAiConfiguration. Codex execpolicy backstop that mirrors Claude's permissions.deny.
|
||||
# The command-safety hook also catches forms these prefix rules cannot express
|
||||
# (rm -r -f, Remove-Item -Recurse, commands inside if/for blocks or nested shells).
|
||||
|
||||
prefix_rule(
|
||||
pattern = ["git", "reset", "--hard"],
|
||||
decision = "forbidden",
|
||||
justification = "Discards work tree changes. Ask the user to run it if intended.",
|
||||
)
|
||||
|
||||
prefix_rule(
|
||||
pattern = ["git", "clean"],
|
||||
decision = "forbidden",
|
||||
justification = "Deletes untracked files. Ask the user to run it if intended.",
|
||||
)
|
||||
|
||||
prefix_rule(
|
||||
pattern = ["git", "checkout", "--"],
|
||||
decision = "forbidden",
|
||||
justification = "Discards file changes. Ask the user to run it if intended.",
|
||||
)
|
||||
|
||||
prefix_rule(
|
||||
pattern = ["git", "push", "--force"],
|
||||
decision = "forbidden",
|
||||
justification = "Overwrites remote history. Ask the user to run it if intended.",
|
||||
)
|
||||
|
||||
prefix_rule(
|
||||
pattern = ["git", "push", "-f"],
|
||||
decision = "forbidden",
|
||||
justification = "Overwrites remote history. Ask the user to run it if intended.",
|
||||
)
|
||||
|
||||
prefix_rule(
|
||||
pattern = ["rm", "-rf"],
|
||||
decision = "forbidden",
|
||||
justification = "Recursive forced deletion. Ask the user to run it if intended.",
|
||||
)
|
||||
|
||||
prefix_rule(
|
||||
pattern = ["rm", "-fr"],
|
||||
decision = "forbidden",
|
||||
justification = "Recursive forced deletion. Ask the user to run it if intended.",
|
||||
)
|
||||
@@ -0,0 +1,18 @@
|
||||
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
|
||||
__IMPECCABLE_HOOK_SCRIPT__ Invoke-ImpeccableHook.ps1 invoke-impeccable-hook.sh
|
||||
__SEARCH_REMINDER_SCRIPT__ Show-SearchReminder.ps1 show-search-reminder.sh
|
||||
__CAVEMAN_SCRIPT__ Show-CavemanMode.ps1 show-caveman-mode.sh
|
||||
__SHELL_TOOL__ PowerShell Bash
|
||||
__SCRIPT_EXTENSION__ ps1 sh
|
||||
|
@@ -3,8 +3,11 @@ Ponytail DietrichGebert/ponytail ponytail@ponytail DietrichGebert/ponytail ponyt
|
||||
i-have-adhd ayghri/i-have-adhd i-have-adhd@i-have-adhd ayghri/i-have-adhd i-have-adhd@i-have-adhd plugin - -
|
||||
Superpowers anthropics/claude-plugins-official superpowers@claude-plugins-official openai-curated-remote superpowers@openai-curated-remote plugin - -
|
||||
Context7 upstash/context7 context7@context7-marketplace upstash/context7 context7@context7-marketplace plugin - - context7 https://mcp.context7.com/mcp
|
||||
Caveman JuliusBrussee/caveman caveman@caveman thinkhome-org/caveman-codex caveman@thinkhome-caveman plugin - -
|
||||
Caveman JuliusBrussee/caveman caveman@caveman - - skill JuliusBrussee/caveman caveman
|
||||
MCPorter - mcporter - mcporter cli mcporter -
|
||||
Humanizer blader/humanizer humanizer@humanizer - - skill blader/humanizer humanizer
|
||||
Impeccable pbakaus/impeccable impeccable@impeccable pbakaus/impeccable impeccable skill pbakaus/impeccable impeccable
|
||||
Anthropic Frontend Design anthropics/claude-plugins-official frontend-design@claude-plugins-official - - skill anthropics/skills frontend-design
|
||||
REA morluto/rea rea@rea morluto/rea rea@rea plugin - -
|
||||
Modern Web Guidance GoogleChrome/modern-web-guidance modern-web-guidance@googlechrome GoogleChrome/modern-web-guidance modern-web-guidance@googlechrome plugin - -
|
||||
Apple Design - - - - skill dickwu/apple-design-skill apple-design
|
||||
Roast Room - - - - clone nateherkai/roast-room roast-room
|
||||
|
@@ -4,27 +4,27 @@
|
||||
"permanent_context_hard_limit_tokens": 15000,
|
||||
"metrics": {
|
||||
"permanent_context_tokens": {
|
||||
"claude": 5451,
|
||||
"codex": 3767
|
||||
"claude": 6808,
|
||||
"codex": 4115
|
||||
},
|
||||
"instruction_tokens": {
|
||||
"claude": 1485,
|
||||
"codex": 1485
|
||||
"claude": 1883,
|
||||
"codex": 1883
|
||||
},
|
||||
"skill_metadata_tokens": {
|
||||
"claude": 3163,
|
||||
"codex": 1554
|
||||
"claude": 3885,
|
||||
"codex": 1360
|
||||
},
|
||||
"auto_loaded_rule_tokens": {
|
||||
"claude": 678,
|
||||
"codex": 678
|
||||
"claude": 789,
|
||||
"codex": 788
|
||||
},
|
||||
"rule_catalog_tokens": {
|
||||
"claude": 28818,
|
||||
"codex": 8510
|
||||
"claude": 35779,
|
||||
"codex": 9518
|
||||
},
|
||||
"agent_metadata_tokens": {
|
||||
"claude": 204,
|
||||
"claude": 261,
|
||||
"codex": 124
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
metric client baseline_tokens
|
||||
permanent_context_tokens claude 5451
|
||||
permanent_context_tokens codex 3767
|
||||
instruction_tokens claude 1485
|
||||
instruction_tokens codex 1485
|
||||
skill_metadata_tokens claude 3163
|
||||
skill_metadata_tokens codex 1554
|
||||
auto_loaded_rule_tokens claude 678
|
||||
auto_loaded_rule_tokens codex 678
|
||||
rule_catalog_tokens claude 28818
|
||||
rule_catalog_tokens codex 8510
|
||||
agent_metadata_tokens claude 204
|
||||
permanent_context_tokens claude 6808
|
||||
permanent_context_tokens codex 4115
|
||||
instruction_tokens claude 1883
|
||||
instruction_tokens codex 1883
|
||||
skill_metadata_tokens claude 3885
|
||||
skill_metadata_tokens codex 1360
|
||||
auto_loaded_rule_tokens claude 789
|
||||
auto_loaded_rule_tokens codex 788
|
||||
rule_catalog_tokens claude 35779
|
||||
rule_catalog_tokens codex 9518
|
||||
agent_metadata_tokens claude 261
|
||||
agent_metadata_tokens codex 124
|
||||
|
+4
-2
@@ -12,7 +12,7 @@ Use only the roles that are likely to improve the outcome. Choose `researcher`,
|
||||
|
||||
## Research tools
|
||||
|
||||
Claude's [capability manifest](../adapters/claude/capabilities.tsv) gives `architect` and `researcher` file inspection, web research, and the package's shell tool (`PowerShell` or `Bash`). Shell access supports mandatory semantic search and Context7 research through MCPorter. Their role instructions scope shell use to inspection and research; this is an instruction-level boundary, not a read-only shell sandbox.
|
||||
Claude's [capability manifest](../adapters/claude/capabilities.tsv) gives `architect` and `researcher` file inspection, web research, and the package's shell tool (`PowerShell` or `Bash`). Every role also gets the `Skill` tool, so it can load `technical-research`, `semantic-search`, and the `rules-*` skills its instructions require. The manifest's optional `skills` column lists skills Claude preloads into the agent at startup: `rules-orchestration` for every role, plus `research` for `researcher` and `review-pull-request` for `reviewer`. The build fails if a preloaded skill is missing from the package. Subagents skip `plugin-workflow`; the parent passes the constraints that apply. Shell access supports mandatory semantic search and Context7 research through MCPorter. Their role instructions scope shell use to inspection and research; this is an instruction-level boundary, not a read-only shell sandbox.
|
||||
|
||||
The `reviewer` may inspect Git diffs and run required research commands through its shell tool. Tests, builds, and behavior reproduction belong to the `verifier` or parent. Missing execution evidence remains an explicit review gap. Codex receives the same role instructions; the Claude tool manifest is client-specific.
|
||||
|
||||
@@ -24,6 +24,8 @@ Assignments contain a concrete task, allowed scope and ownership, success criter
|
||||
|
||||
The shared [orchestration rule](../shared/rules/orchestration.md) defines the `RESULT`, `EVIDENCE`, `CHANGES`, `RISKS`, and optional `NEXT` handoff. Codex loads it as a rule file; Claude loads the generated `rules-orchestration` skill. Agent adapters add only the client-specific loading instruction. The protocol body is not copied into every role or permanent prompt.
|
||||
|
||||
The same rule bounds delegation that plugins suggest, such as Superpowers' subagent workflows. A plugin default alone never authorizes subagents, per-task reviews stay proportional, parallel writers get disjoint files, and plugin or built-in agents are used only for their own specialty. Their output goes inside the shared handoff sections. See [Plugin workflows and agents](../shared/rules/orchestration.md#plugin-workflows-and-agents).
|
||||
|
||||
## Task state
|
||||
|
||||
See the [canonical task-state policy](../shared/rules/orchestration.md#canonical-task-state) for when to use state and what it may contain. The optional `.ai-session/state.json` file is local handoff state for a long-running active goal, not persistent project memory.
|
||||
@@ -32,4 +34,4 @@ The optional `scripts/commands/session-state.ps1` and `scripts/commands/session-
|
||||
|
||||
Starting a different goal requires `-Reset -Goal ...` or `--reset --goal ...`, which clears the previous task's decisions and verification. Updates are atomic; legacy field names are migrated when reading existing state.
|
||||
|
||||
After compaction, verify that the state belongs to the current goal and workspace before using it. Claude's lifecycle hooks point to an existing workspace state without creating or summarizing it. Codex follows the same recovery instructions manually; no unsupported lifecycle events are registered.
|
||||
After compaction, verify that the state belongs to the current goal and workspace before using it. The `PreCompact` and `SessionStart` hooks of both clients point to an existing workspace state without creating or summarizing it.
|
||||
+18
-3
@@ -5,7 +5,8 @@ and [`adapters/claude/config/settings.json`](../adapters/claude/config/settings.
|
||||
Installation targets `~/.codex` and `~/.claude`; Codex skills go to `~/.agents/skills`.
|
||||
Choose the PowerShell or Bash package independently of the client.
|
||||
|
||||
Codex receives a generated global `AGENTS.md`, agent TOML files, skills, rule files, and a `config.toml` adapter.
|
||||
Codex receives a generated global `AGENTS.md`, agent TOML files, skills, rule files, a `config.toml` adapter, and
|
||||
execpolicy rules in `~/.codex/rules/my-ai-configuration.rules`.
|
||||
It sets full access for commands, automatic approval review, `agents.enabled = true`,
|
||||
`agents.max_concurrent_threads_per_session = 5`, and `agents.max_depth = 1`.
|
||||
|
||||
@@ -30,7 +31,8 @@ Codex sets `sandbox_mode = "danger-full-access"`, `approval_policy = "on-request
|
||||
restrictions, under the account that launches Codex. Launch Codex as the repository owner to use that identity;
|
||||
this configuration does not impersonate another user or change filesystem ownership. OS permissions, firewalls,
|
||||
and managed organization policies still apply. Eligible approval requests retain automatic review, which does
|
||||
not restore a filesystem boundary. See the [official OpenAI security documentation](https://learn.chatgpt.com/docs/agent-approvals-security).
|
||||
not restore a filesystem boundary. The execpolicy rules forbid a few destructive Git and `rm` prefixes, mirroring
|
||||
Claude's deny rules; see [Hooks](hooks.md) for the list and its limits. See the [official OpenAI security documentation](https://learn.chatgpt.com/docs/agent-approvals-security).
|
||||
|
||||
The adapter no longer selects the Windows sandbox or workspace writable roots. This avoids using the dedicated
|
||||
`CodexSandboxOnline` account, whose identity differs from the repository owner and can trigger Git's ownership
|
||||
@@ -79,8 +81,21 @@ Quickupdate reuses the saved choice and device; it does not rerun the benchmark.
|
||||
- **No:** omit the search skill and its instruction line, remove the warm-up hook registration,
|
||||
and disable search for the selected clients. Dry runs do not download, benchmark, or remove QMD resources.
|
||||
|
||||
The models are Qwen3-Embedding-0.6B, Qwen3-Reranker-0.6B, and QMD Query Expansion 1.7B.
|
||||
The models are Qwen3-Embedding-4B, Qwen3-Reranker-4B, and QMD Query Expansion 1.7B.
|
||||
Exact model URIs live in [`shared/qmd/qmd-lib.mjs`](../shared/qmd/qmd-lib.mjs).
|
||||
Install and update rewrite the setup-owned `models:` block, so changed models reach existing installations.
|
||||
When a new embedding model produces vectors of another size, the daemon clears all old vectors and
|
||||
re-embeds each repository on its next search; run `qmd embed` to re-embed your own QMD collections.
|
||||
Install and update also delete model files the setup downloaded that the current models no longer use.
|
||||
They stop a running QMD daemon first, so the next search uses the new scripts and models. A QMD package
|
||||
the setup installed is reinstalled at the tested version; a foreign installation of another version is kept
|
||||
and reported. `doctor` checks the runtime scripts, the QMD version, the model files, and the daemon.
|
||||
Repository indexes skip git-ignored files, npm and pnpm lockfiles, and minified `*.min.js` bundles.
|
||||
They cover source, web templates and styles, .NET and WPF markup and project files; the
|
||||
file mask lives in `MASK` in `shared/qmd/qmd-lib.mjs` and is reapplied to existing repository collections.
|
||||
Where the Claude sandbox is enabled (macOS, Linux, WSL2), the exact search command is listed in
|
||||
`sandbox.excludedCommands`, because the sandbox blocks the localhost daemon and the index under the home directory.
|
||||
Disabling local search removes that exclusion, including on update.
|
||||
Auto thresholds can be overridden with `QMD_BENCHMARK_MAX_QUERY_SECONDS` and
|
||||
`QMD_BENCHMARK_MIN_CHUNKS_PER_SECOND`. The benchmark uses a temporary database and a deterministic
|
||||
100-document fixture; its measurements are not an end-to-end estimate for a user's repository.
|
||||
|
||||
@@ -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.
|
||||
|
||||
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
|
||||
|
||||
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
|
||||
|
||||
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`).
|
||||
+15
-4
@@ -6,21 +6,32 @@ The adapters register these events:
|
||||
|
||||
| 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 matches `Bash` and on Windows checks both dialects (`-Shell unknown`), because Codex reports PowerShell script text as `Bash`. |
|
||||
| Codex and Claude | `PreToolUse` | Remind the agent to run `semantic-search` before the first open search and again after every 10 open searches without it; a no-op unless QMD's `qmd-search.mjs` is installed. Shell commands are checked inside the command-safety hook process, so each shell call starts one hook process. Claude adds a separate hook for `Grep` and `Glob` (`Show-SearchReminder`/`show-search-reminder.sh`). |
|
||||
| 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 | `UserPromptSubmit` | Ask the agent to propose a durable rule when a prompt looks like a correction (`Show-CorrectionPrompt`/`show-correction-prompt.sh`). |
|
||||
| Claude | `PreCompact` | Record the compaction timestamp under the installed configuration root and point to existing workspace task state. |
|
||||
| Claude | `SessionStart` | Print an absolute pointer if the workspace's `.ai-session/state.json` exists. |
|
||||
| Codex and Claude | `PreCompact` | Record the compaction timestamp under the installed configuration root and point to existing workspace task state. |
|
||||
| Codex and Claude | `SessionStart` | Print an absolute pointer if the workspace's `.ai-session/state.json` exists. |
|
||||
| Codex | `SessionStart` | Print the installed Caveman skill (`Show-CavemanMode`/`show-caveman-mode.sh`) so caveman style is always on, as the Claude plugin does; `CAVEMAN_DEFAULT_MODE=off` disables it, and it is a no-op without the skill. |
|
||||
| Codex and Claude | `SessionStart` | Warm the QMD index and search daemon in the background (only while local QMD search is enabled). |
|
||||
|
||||
The main agent alone maintains canonical task state. Hooks never write or summarize it, print its contents, or infer completed verification. The task-state hooks use the hook event's `cwd`, falling back to the process working directory when no workspace is supplied. Malformed event data does not fall back to another project. An absent state file is a successful no-op. Legacy state under the installed configuration root is not automatically adopted; confirm its task before migrating it. The scripts do not grant permissions, bypass approvals, or replace client permission systems.
|
||||
|
||||
The search reminder never blocks a tool call. It fires on `Grep`/`Glob` or on shell commands that look like searches (`rg`, `grep`, `find`, `fd`, `git grep`, `Select-String`, recursive `Get-ChildItem`). It repeats after every 10 open searches without `qmd-search.mjs`, which also covers context lost to compaction, and stays silent while the session keeps using `qmd-search.mjs`. It matches command text, so wrapped or aliased searches can slip through. Per-session markers are hashed session IDs under `~/.my-ai-configuration/state/search-reminder/`; markers older than seven days are pruned.
|
||||
|
||||
The QMD warm-up hook uses the process working directory and starts only inside a Git repository when Node.js and the installed wrapper are available. It runs detached; wrapper errors are recorded in `~/.my-ai-configuration/qmd/warm.log`. Disabling local search removes its hook registration. See [Local QMD search](configuration.md#local-qmd-search) for daemon behavior and storage.
|
||||
|
||||
When enabled during installation or update, Flashbang runs on `Stop`, after the main agent finishes responding. The default flash lasts about 500 milliseconds. The PowerShell command omits `-WindowStyle Hidden`, which can hide or minimize the shared terminal. The PowerShell hook creates a low-opacity click-through overlay without activating another window when its native GUI APIs are available; unsupported runtimes exit safely. Its native DLL cache is optional: a missing `LOCALAPPDATA` environment variable or an unusable cache falls back to in-process compilation instead of suppressing the notification. The Bash hook uses Python's `tkinter`, uses `xrandr` for multi-monitor bounds when available, and falls back to `notify-send` when the overlay is unavailable. Registered hooks are best effort: errors do not fail a Claude session.
|
||||
|
||||
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`, `git checkout -- <path>` or `git checkout .`, `git restore` of working-tree files, `git push --force` (including `-f` and `+refspec`), `git stash clear`, `find -delete`, `Remove-Item -Recurse` (including `ri` and, outside Bash, the `rm`/`del`/`rd` aliases), `del`/`rd /s /q`, and `format <drive>:`. Heredoc bodies count as text, not commands. 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.
|
||||
|
||||
`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.
|
||||
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. Codex gets the same backstop as execpolicy rules in `~/.codex/rules/my-ai-configuration.rules` (`prefix_rule` with `decision = "forbidden"` for `git reset --hard`, `git clean`, `git checkout --`, `git push --force`, `git push -f`, `rm -rf`, and `rm -fr`); prefix rules cannot express `Remove-Item ... -Recurse`. Neither layer catches `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. Codex cannot run a status-line script; its `[tui] status_line` in the managed `config.toml` shows the equivalent built-in items (model, reasoning, limits, project, branch, and context use).
|
||||
+11
-5
@@ -2,13 +2,19 @@
|
||||
|
||||
The user-level plugin manifest is `adapters/plugins.tsv`. It maps each logical extension to the client-specific plugin, skill, or MCP installation method.
|
||||
|
||||
The current baseline includes Ponytail, i-have-adhd, Superpowers, Context7, Caveman, MCPorter, Humanizer, Impeccable, and Anthropic Frontend Design. Install and update operate at user scope and show an extension selector unless running a dry run or Quickupdate. Selections are collected before configuration changes. Both rebuild generated packages before synchronizing client files and extensions. Choosing Auto for local search can prepare and benchmark QMD earlier, during option selection.
|
||||
The current baseline includes Ponytail, i-have-adhd, Superpowers, Context7, Caveman, MCPorter, Humanizer, Impeccable, Apple Design, REA, Modern Web Guidance, and Roast Room. Install and update operate at user scope and show an extension selector unless running a dry run or Quickupdate. Selections are collected before configuration changes. Both rebuild generated packages before synchronizing client files and extensions. Choosing Auto for local search can prepare and benchmark QMD earlier, during option selection.
|
||||
|
||||
### Automatic workflow integration
|
||||
|
||||
The always-loaded general rules route both clients to the shared `plugin-workflow` skill for development tasks, on resume, and at phase changes; questions and prose-only changes skip it, and the general rules carry the core response style. The policy requires Superpowers at development phase boundaries, Ponytail for implementation and review, Impeccable for UI planning through verification, and i-have-adhd response structure with Caveman's concise style when available. Superpowers owns process; Ponytail constrains implementation to the smallest complete, verified change; Impeccable owns UI decisions; Frontend Design supplements uncovered needs without starting another workflow. User authorization, research gates, and proportionate checks retain precedence.
|
||||
The always-loaded general rules require both clients to load the shared `plugin-workflow` skill at the start of every session, including questions and prose-only work, and again after resume and compaction. UI work additionally loads the shared `ui-workflow` skill, which runs Impeccable and Apple Design as one design loop. Each plugin layer inside it applies only at its own triggers, so development-only layers stay idle for questions and prose. The policy requires Superpowers at development phase boundaries, Ponytail for implementation and review, Impeccable for UI planning through verification, Modern Web Guidance before HTML, CSS, client-side script, or browser-extension changes, and i-have-adhd response structure with Caveman's concise style when available. Superpowers owns process; Ponytail constrains implementation to the smallest complete, verified change; Impeccable owns UI decisions; Modern Web Guidance picks web platform APIs and patterns. Modern Web Guidance fetches its guides through `npx`, so it needs npm registry access. The general rules themselves also require Humanizer when writing or substantially rewriting prose read outside the chat (documentation, comments, commit or PR bodies, UI copy, messages). Chat replies and small fixes such as typos skip it. User authorization, research gates, and proportionate checks retain precedence.
|
||||
|
||||
The installed i-have-adhd 0.4.1 skill declares `disable-model-invocation: true`. The shared policy therefore supplies automatic response guidance without forcing a manual-only skill invocation or relying on its optional hook. It does not diagnose the user. Style stop commands persist through task changes and resume; `normal mode` disables i-have-adhd, Caveman, and Ponytail for the session. Explicit mode levels override defaults. Missing plugins are reported once and do not trigger installation. These are instruction-level requirements, not runtime interception or a guarantee of model compliance. Existing installations receive them through the normal configuration update; builds do not modify local plugin caches or hook trust.
|
||||
The installed i-have-adhd 0.4.1 skill declares `disable-model-invocation: true`. The shared policy therefore supplies automatic response guidance without forcing a manual-only skill invocation. Install and update do not create the plugin's opt-in flag `.i-have-adhd-always` in the Claude configuration directory (`CLAUDE_CONFIG_DIR`, default `~/.claude`): its SessionStart hook would inject the full ruleset into every session and duplicate the shared guidance. A flag left by an older setup stays in place; delete it to turn always-on off. It does not diagnose the user. Style stop commands persist through task changes and resume; `normal mode` disables i-have-adhd, Caveman, and Ponytail for the session. Ponytail runs at `ultra` by default: when Ponytail is selected, install and update set `defaultMode` to `ultra` in Ponytail's config file (`%APPDATA%\ponytail\config.json` on Windows, `~/.config/ponytail/config.json` elsewhere, or under `$XDG_CONFIG_HOME`) and keep its other keys. `PONYTAIL_DEFAULT_MODE` still takes precedence. Besides `ponytail-review`, the workflow routes whole-repository quality audits to `ponytail-audit` and questions about deferred `shortcut:` comments to `ponytail-debt`; both also run on demand as `/ponytail-audit` and `/ponytail-debt` and change nothing. Caveman contributes only its response style: its process skills (such as `surgical-patch`, `safe-refactor`, `verify-and-stop`, and `caveman-explore`) overlap Superpowers, Ponytail, and the research skills, so the workflow does not route to them. Impeccable starts its own review and documentation agents. Explicit mode levels override defaults. Missing plugins are reported once and do not trigger installation. These are instruction-level requirements, not runtime interception or a guarantee of model compliance. Existing installations receive them through the normal configuration update; builds do not modify local plugin caches or hook trust.
|
||||
|
||||
### REA (Reverse Engineer Anything)
|
||||
|
||||
REA installs as the native `rea@rea` plugin from the `morluto/rea` marketplace for both clients. The plugin bundles the `reverse-engineer-anything` skill and its MCP server, pinned to one `rea-agents` npm version per release. The general rules and `plugin-workflow` require the skill for reverse-engineering work on artifacts without usable source, limited to targets the user is authorized to inspect.
|
||||
|
||||
The client needs a standalone `node` on its `PATH`. Analysis providers such as Ghidra (12.1 or later with a matching 64-bit JDK) are not installed by the plugin; set `GHIDRA_INSTALL_DIR` and `JAVA_HOME` in the environment the client starts from. Do not also run `npx rea-agents setup` for the same client: that registers a second `rea` server. `rea doctor` cannot see plugin-owned state, so check a plugin installation with `claude plugin list` or `codex plugin list` instead.
|
||||
|
||||
### Context7 routing
|
||||
|
||||
@@ -41,9 +47,9 @@ The check passes only if documentation retrieval returns relevant content with a
|
||||
|
||||
Codex's local `plugins` and `marketplaces` tables survive configuration synchronization, along with other root keys, extra fields in managed tables, other unmanaged tables, and unowned array tables; changed files are backed up. Cached plugin files alone are not treated as proof of installation: selection uses the client CLI's installed list. If an older update removed the registrations, inspect the backed-up `config.toml` under `~/.codex/backups/` and reselect the affected plugins on the next update.
|
||||
|
||||
Codex receives Caveman through its native plugin adapter. Humanizer, Impeccable, and Anthropic Frontend Design are downloaded as skill payloads from the GitHub sources in the manifest, without running upstream installers. All three appear in the extension selector for Codex. Ownership is recorded in `~/.my-ai-configuration/extensions.json`. Skill files are tracked by hash; modified or foreign files are retained with a warning. Existing installations from before ownership tracking are not automatically adopted.
|
||||
Roast Room uses the `clone` method: install keeps a shallow Git clone of the manifest's GitHub source in `~/.my-ai-configuration/<folder>` and update fast-forwards it unless tracked files changed locally. Both clients share the clone. The personal launcher skill `shared/skills/extensions/roast-room` makes `/roast-room` (Claude Code) and `$roast-room` (Codex) work from any folder; `disable-model-invocation: true` and Codex's `agents/openai.yaml` (`allow_implicit_invocation: false`) keep it manual-only. It starts the live room (`node app/server.mjs`, port 4730) when it is not running and writes sessions into the clone, where the room reads them. Outside the clone, seats run through the upstream fallback (a general subagent given the seat's agent file) because the `council-*` agents are registered only in a Claude Code session started there. As a personal skill it also shadows the clone's own `roast-room` skill, so the board never starts on its own. `/newroaster` still needs a Claude Code session started in the clone. Uninstall removes the clone only when it holds no saved sessions, `.env` files, or other local files.
|
||||
|
||||
On Windows, installation and update repair the known Caveman 1.0.0 hook launcher in setup-owned Codex installations so it resolves the plugin path under PowerShell as well as Command Prompt. Custom commands and foreign installations are preserved. Review the changed hook definitions in Codex `/hooks`; setup does not grant hook trust automatically.
|
||||
Caveman is a Claude plugin and a Codex skill payload (`skills/caveman` from the same repository); a registered Codex `SessionStart` hook prints it so caveman style is always on in Codex too. A `-` in the `codex_method` column marks a Claude-only extension, which the Codex selector omits and which install and update remove from Codex when this setup installed it there; no current entry uses it. Humanizer and Impeccable are downloaded to Codex as skill payloads from the GitHub sources in the manifest, without running upstream installers. Both appear in the extension selector for Codex. Apple Design has no plugin marketplace, so a `-` in `claude_plugin` together with `codex_method` `skill` installs the same payload for Claude into `~/.claude/skills/apple-design`. Each update downloads the latest upstream commit and records its revision. For Codex, a skill payload's `agents/*.toml` files are also written to `~/.codex/agents/`, where Codex loads custom agents, so Impeccable's finish, motion, asset, documenter, and edit-applier agents are registered as on Claude; they are tracked by hash and removed with the skill. Impeccable's design-detector hooks run in every project for both clients: Claude through the plugin's own hooks, Codex through the registered `Invoke-ImpeccableHook`/`invoke-impeccable-hook.sh` wrapper (see `shared/hooks/README.md`). No per-project `impeccable hooks on` is needed; `impeccable hooks off` still disables a project. Ownership is recorded in `~/.my-ai-configuration/extensions.json`. Skill files are tracked by hash; modified or foreign files are retained with a warning. Existing installations from before ownership tracking are not automatically adopted.
|
||||
|
||||
|
||||
### Setup options outside the extension selector
|
||||
|
||||
+12
-6
@@ -15,7 +15,7 @@ Run scripts from the repository root. PowerShell and Bash commands have equivale
|
||||
|
||||
| Script | Purpose |
|
||||
| --- | --- |
|
||||
| `commands/build.ps1`, `commands/build.sh` | Generate four client packages in `generated/` from the shared skill catalog. |
|
||||
| `commands/build.ps1`, `commands/build.sh` | Generate four client packages in `generated/` from the shared skill catalog. `-SkipCodexSchema` / `--skip-codex-schema` skips the Codex schema check; Claude-only installs and updates pass it. |
|
||||
| `commands/check-capabilities.ps1`, `commands/check-capabilities.sh` | Check required tools and versions. |
|
||||
| `commands/install.ps1`, `commands/install.sh` | Install a selected client configuration. |
|
||||
| `commands/update.ps1`, `commands/update.sh` | Update an existing installation; Quick reuses saved choices. |
|
||||
@@ -51,7 +51,7 @@ The A/B benchmark measures whole sessions. Auto selection of local QMD search us
|
||||
|
||||
## 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
|
||||
PowerShell 5.1 script; failed version or configuration checks contribute to the final failure summary.
|
||||
@@ -59,14 +59,18 @@ On Windows, an unavailable profile-folder lookup falls back to PowerShell's home
|
||||
|
||||
| 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-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-caveman-hook.py` | Validate the Codex Caveman session hook in both shells: it prints the installed skill without frontmatter, is silent without the skill, and honors `CAVEMAN_DEFAULT_MODE=off`. |
|
||||
| `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-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-install-options.py` | Validate interactive option handling and generated manifest changes. |
|
||||
| `tests/test-managed-extensions.py` | Validate plugin, skill, and CLI ownership handling. |
|
||||
| `tests/test-skill-contracts.py` | Validate the doctor check that installed Impeccable and Apple Design skills still name what `plugin-workflow` coordinates. |
|
||||
| `tests/test-managed-install.ps1`, `tests/test-managed-install.sh` | Validate managed-file synchronization and backups. |
|
||||
| `tests/test-plugin-selection.ps1`, `tests/test-plugin-selection.sh` | Validate plugin selection. |
|
||||
| `tests/test-prompt-budget.py` | Validate prompt budget threshold evaluation. |
|
||||
@@ -77,13 +81,14 @@ On Windows, an unavailable profile-folder lookup falls back to PowerShell's home
|
||||
| `tests/test-qmd-lib.mjs`, `test-qmd-daemon.mjs`, `test-qmd-search.mjs`, `test-qmd-warm.mjs`, `test-qmd-benchmark.mjs` | Model-free QMD unit tests; require the YAML dependency. |
|
||||
| `tests/test-qmd-integration.mjs` | Manual integration test using real QMD and downloaded models; excluded from CI. |
|
||||
| `tests/test-qmd-setup.py` | Validate QMD installation, migration, and removal. |
|
||||
| `tests/test-agent-guards.py` | Validate the completion-evidence and correction-prompt hooks. |
|
||||
| `tests/test-agent-guards.py` | Validate the completion-evidence, correction-prompt, and search-reminder hooks. |
|
||||
| `tests/test-session-state.py` | Validate session-state helpers. |
|
||||
| `tests/test-shell-packages.ps1`, `tests/test-shell-packages.sh` | Validate generated package contents and client settings. |
|
||||
| `tests/test-runtime-status.ps1`, `tests/test-runtime-status.sh` | Validate build summaries and status-line output. |
|
||||
| `tests/test-install-selections.ps1`, `tests/test-install-selections.sh` | Validate dry-run shell and client selections. |
|
||||
| `tests/test-command-summaries.ps1`, `tests/test-command-summaries.sh` | Validate doctor, install, and update summary output. |
|
||||
| `tests/test-telemetry.py` | Validate telemetry output. |
|
||||
| `tests/test-uninstall.py` | Validate in both shells that uninstall strips only setup-owned hooks and entries from `settings.json` and `config.toml`, keeps the saved selection while another client remains installed, and that Bash and PowerShell merges write identical files; update rejects an invalid Claude concurrency value. |
|
||||
| `tests/test-personal-instructions.py` | Validate startup instruction pointers and preservation of personal instruction files. |
|
||||
| `tests/test-user-customizations.py` | Validate user instruction overlays and credential helpers. |
|
||||
|
||||
@@ -138,7 +143,7 @@ Benchmark fixture READMEs describe the starting task state and are retained as t
|
||||
| Script | Purpose |
|
||||
| --- | --- |
|
||||
| `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-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. |
|
||||
@@ -150,4 +155,5 @@ Benchmark fixture READMEs describe the starting task state and are retained as t
|
||||
| `lib/selection-state.py` | Read and write Quickupdate state. |
|
||||
| `lib/qmd.sh`, `lib/qmd.ps1` | Invoke local QMD search from the installation flow. |
|
||||
| `lib/qmd.py` | Install, migrate, benchmark, and remove local QMD search. |
|
||||
| `lib/skill-contracts.py` | Doctor check: warn when an upstream Impeccable or Apple Design update no longer names the commands and sections `plugin-workflow` relies on. |
|
||||
| [`shared/qmd/`](../shared/qmd/) (repository root) | Installed QMD scripts: search CLI, daemon, warm-up, benchmark, and shared library. |
|
||||
+12
-14
@@ -4,24 +4,22 @@ Skills are reusable workflows. Rules are persistent constraints and agents are s
|
||||
|
||||
The current structure is organized by purpose:
|
||||
|
||||
- `planning/`: impact analysis and work-item definition
|
||||
- `research/`: `research` gate for open searches, with technical and repository specialists, plus `semantic-search`, which is installed only while local QMD search is enabled
|
||||
- `reviews/`: security, performance, WPF, UI/UX, business, API, and EF Core reviews
|
||||
- `implementation/`: SQL, unit-test, and integration-test writing
|
||||
- `verification/`: facts and work-item verification
|
||||
- `git/`: pull request reviews
|
||||
- `content-strategy/`, `copy-editing/`, `copywriting/`: planning, editing, and writing text
|
||||
- `image/`: image assets, screenshots, SEO and performance, social-preview metadata, practical marketing workflows, design tools, and common mistakes
|
||||
- `site-architecture/`: website structure
|
||||
- `marketing-psychology/`, `offers/`, `product-marketing/`, `cro/`: audience understanding, value framing, and conversion
|
||||
- `planning/`: change impact analysis
|
||||
- `research/`: `research` gate for open searches, with its repository route and the `technical-research` specialist, plus `semantic-search`, which is installed only while local QMD search is enabled
|
||||
- `reviews/`: `review-pull-request` as the single review entry point, plus security, performance, WPF, UI/UX, business, API, and EF Core reviews
|
||||
- `implementation/`: SQL, unit-test, integration-test, and end-to-end or UI test writing
|
||||
- `diagnostics/`: read-only incident investigation from Grafana, Azure DevOps, and SQL Server evidence, and before/after performance measurement
|
||||
- `work-items/`: work-item definition and verification, including Azure DevOps items (fact checking lives in `research`)
|
||||
- `extensions/`: launchers for managed extensions (currently `roast-room`, run only by name: `/roast-room` in Claude Code, `$roast-room` in Codex)
|
||||
- `media/`: images, screenshots, video, and audio: formats, delivery and performance, captions and transcripts, playback, social-preview metadata, practical marketing workflows, design tools, and common mistakes
|
||||
|
||||
General planning, debugging, code review, and completion verification workflows come from Superpowers, so the catalog does not duplicate their triggers. The remaining skills cover focused domains Superpowers does not.
|
||||
|
||||
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, the shared `ui-workflow` skill for UI (Impeccable leads direction and edits, Apple Design supplies cited platform and accessibility constraints and a merged review), REA for reverse engineering, and i-have-adhd with Caveman for responses. Global instructions require loading it at the start of every session, including questions and prose, and again after resume and compaction; each plugin layer inside it applies only at its own triggers. 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/` holds development skills, the `media` skill, the `plugin-workflow` and `ui-workflow` coordinators, and the Roast Room launcher. The `media` skill has a short core and seven focused references loaded only when relevant: image optimization, OG and social-preview images, video, audio, marketing workflows, design tools, and common mistakes. 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.
|
||||
|
||||
Claude discovers only `skills/<name>/SKILL.md`, so its generated package flattens the categorized catalog to one directory per skill name, together with the skill's `references/`; the build fails on duplicate names or a `name` that differs from its directory. Claude's package additionally has a `rules-*` skill for each focused rule file or directory in
|
||||
`shared/rules/`. The rule-to-skill loading conditions live in `shared/global-instructions.md`, so full rule text loads
|
||||
@@ -29,7 +27,7 @@ only when Claude invokes a matching skill instead of sitting permanently in cont
|
||||
files directly. Both clients embed the general rules in their global instructions.
|
||||
Language, framework, library, and security rules use directory indexes plus focused topic files. Their generated Claude skills expose each focused rule separately; the index skills also include the references for contextual lookup. See [Configuration](configuration.md).
|
||||
|
||||
Every search or lookup must use `research` and the applicable specialist, including direct reads, exact matches, familiar areas, and follow-up queries during implementation or verification. Loaded instructions can be reused; their checks apply to each search. Semantic retrieval runs first for unknown repository identifiers; known identifiers still use direct reads or `rg` within the research workflow. Disabling QMD does not disable the research requirement. These are agent instructions, not a runtime tool interceptor.
|
||||
Open searches (unknown locations or identifiers, behavior questions, discovery) must use `research` and the applicable specialist, including familiar areas and follow-up queries during implementation or verification. Direct reads of known paths and exact matches of known identifiers need no skill load. Loaded instructions can be reused; their checks apply to each search. Semantic retrieval runs first for unknown repository identifiers; known identifiers still use direct reads or `rg` within the research workflow. Disabling QMD does not disable the research requirement. These are agent instructions, not a runtime tool interceptor.
|
||||
|
||||
Context7 phase checkpoints are defined once in `research/technical-research/SKILL.md`. Focused planning, SQL and test-writing, and verification skills call them explicitly, as do the architect, implementer, and verifier roles. The global rule applies the same checkpoints inside Superpowers and other plugin workflows without modifying upstream plugin caches or duplicating general workflow skills. Planning verifies external assumptions before accepting a design; implementation checks them against actual versions before coding; verification requires both applicable source evidence and proportionate execution results. Evidence travels in the existing plan or handoff and is reused across phases when the behavior, version, and environment match. Queries contain only public, sanitized concepts, use bounded timeouts and refinement, and report source fallback or unresolved gaps explicitly. This enforces an instruction contract; it does not guarantee model compliance or add network calls to builds and tests.
|
||||
|
||||
|
||||
@@ -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)
|
||||
try:
|
||||
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()
|
||||
if arm == 'baseline':
|
||||
# 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 '?'
|
||||
groups.setdefault((category, result['client'], result['arm']), []).append(result)
|
||||
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%} | '
|
||||
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} | '
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import tomllib
|
||||
from pathlib import Path
|
||||
@@ -11,11 +12,13 @@ from pathlib import Path
|
||||
|
||||
CLAUDE_TOP_LEVEL = {"permissions", "sandbox", "env", "statusLine", "hooks"}
|
||||
CLAUDE_PERMISSION_KEYS = {"defaultMode", "allow", "deny"}
|
||||
CLAUDE_SANDBOX_KEYS = {"enabled", "allowUnsandboxedCommands", "failIfUnavailable", "network"}
|
||||
CLAUDE_SANDBOX_KEYS = {"enabled", "allowUnsandboxedCommands", "failIfUnavailable", "excludedCommands", "network"}
|
||||
# The only command allowed outside the sandbox: QMD search needs its localhost daemon and home-directory index.
|
||||
CLAUDE_SANDBOX_EXCLUDED = ['node "$HOME/.my-ai-configuration/qmd/qmd-search.mjs" *']
|
||||
CLAUDE_STATUS_LINE_KEYS = {"type", "command"}
|
||||
CLAUDE_HOOK_KEYS = {"type", "command", "timeout"}
|
||||
CLAUDE_PERMISSION_MODES = {"acceptEdits", "auto", "bypassPermissions", "default", "dontAsk", "plan"}
|
||||
CLAUDE_VALID_TOOLS = {"Read", "Grep", "Glob", "Edit", "Write", "Bash", "PowerShell", "WebFetch", "WebSearch"}
|
||||
CLAUDE_VALID_TOOLS = {"Read", "Grep", "Glob", "Edit", "Write", "Bash", "PowerShell", "WebFetch", "WebSearch", "Skill"}
|
||||
|
||||
|
||||
def fail(message: str) -> None:
|
||||
@@ -41,6 +44,7 @@ def validate_claude(path: Path) -> None:
|
||||
fail(f"permissions.{key} must be an array of strings")
|
||||
sandbox = require_keys(settings.get("sandbox"), CLAUDE_SANDBOX_KEYS, "sandbox")
|
||||
if sandbox != {"enabled": False} and sandbox != {"enabled": True, "allowUnsandboxedCommands": False, "failIfUnavailable": True,
|
||||
"excludedCommands": CLAUDE_SANDBOX_EXCLUDED,
|
||||
"network": {"allowedDomains": ["mcp.context7.com"]}}:
|
||||
fail("sandbox must be disabled or enabled with fail-closed settings")
|
||||
env = settings.get("env")
|
||||
@@ -87,6 +91,51 @@ def validate_agent_tools(package: Path) -> None:
|
||||
unknown = [tool for tool in tools if tool not in CLAUDE_VALID_TOOLS]
|
||||
if unknown:
|
||||
fail(f"{path}: unknown Claude tool name(s): {', '.join(unknown)}")
|
||||
# Claude skips a missing preloaded skill silently, so check the names against the package.
|
||||
if "skills:" in lines:
|
||||
for line in lines[lines.index("skills:") + 1:]:
|
||||
if not line.startswith(" - "):
|
||||
break
|
||||
skill = line.removeprefix(" - ").strip()
|
||||
if not (package / "skills" / skill / "SKILL.md").is_file():
|
||||
fail(f"{path}: preloads missing skill {skill}")
|
||||
|
||||
|
||||
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:
|
||||
@@ -97,6 +146,8 @@ def main() -> int:
|
||||
validate_claude(Path(sys.argv[2]))
|
||||
validate_rule_skills(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
|
||||
|
||||
|
||||
|
||||
@@ -8,11 +8,7 @@ param(
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
|
||||
. (Join-Path $root 'scripts/lib/install-targets.ps1')
|
||||
$selectedClient = $Client
|
||||
$selectedKey = $Key
|
||||
. (Join-Path $root 'scripts/lib/credentials.ps1')
|
||||
$Client = $selectedClient
|
||||
$Key = $selectedKey
|
||||
. (Join-Path $root 'scripts/lib/with-credential.ps1')
|
||||
|
||||
if (-not $Client) { $Client = Read-InstallClient -Client $Client }
|
||||
if (-not $Key) { $Key = Read-Host 'Credential key' }
|
||||
@@ -28,9 +24,9 @@ if ($ValueFromStdin) {
|
||||
|
||||
$bin = Join-Path $HomePath '.my-ai-configuration/bin'
|
||||
New-Item -ItemType Directory -Path $bin -Force | Out-Null
|
||||
foreach ($source in @('credentials.ps1', 'with-credential.sh')) {
|
||||
$destination = Join-Path $bin $(if ($source -eq 'credentials.ps1') { 'with-credential.ps1' } else { $source })
|
||||
if (-not (Test-Path -LiteralPath $destination)) { Copy-Item (Join-Path $root "scripts/lib/$source") $destination }
|
||||
foreach ($source in @('with-credential.ps1', 'with-credential.sh')) {
|
||||
# Always refresh so fixes to the helper reach machines that already have it.
|
||||
Copy-Item -LiteralPath (Join-Path $root "scripts/lib/$source") -Destination (Join-Path $bin $source) -Force
|
||||
}
|
||||
foreach ($target in $(if ($Client -eq 'Both') { @('Codex', 'Claude') } else { @($Client) })) {
|
||||
Set-ManagedCredential $target $Key $Value
|
||||
|
||||
@@ -6,6 +6,7 @@ param(
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$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')
|
||||
|
||||
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"
|
||||
$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))
|
||||
& 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.' }
|
||||
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"
|
||||
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
|
||||
python_command=$(command -v python || command -v python3 || true)
|
||||
[ -n "$python_command" ] || { printf 'Python is required to add instructions.\n' >&2; exit 1; }
|
||||
# shellcheck source=../../shared/hooks/scripts/resolve-python.sh
|
||||
. "$script_dir/../../shared/hooks/scripts/resolve-python.sh"
|
||||
resolve_python || { python_missing_message >&2; exit 1; }
|
||||
mkdir -p -- "$directory"
|
||||
for target in "${targets[@]}"; do
|
||||
path="$directory/$target.md"
|
||||
[ ! -s "$path" ] || [ "$(tail -c 1 -- "$path" | wc -l)" -eq 1 ] || printf '\n' >> "$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"
|
||||
done
|
||||
@@ -1,4 +1,5 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$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
|
||||
@@ -1,4 +1,7 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
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" "$@"
|
||||
+48
-34
@@ -1,21 +1,41 @@
|
||||
[CmdletBinding()]
|
||||
param([switch]$Summary)
|
||||
param([switch]$Summary, [switch]$SkipCodexSchema)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
|
||||
. (Join-Path $root 'shared/hooks/scripts/Resolve-Python.ps1')
|
||||
$shared = Join-Path $root 'shared'
|
||||
$final = Join-Path $root 'generated'
|
||||
# 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))
|
||||
# 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 }
|
||||
# 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
|
||||
if ($sandboxSupported) {
|
||||
$kernel = (& uname -r 2>$null | Out-String).Trim()
|
||||
if ($kernel -match '(?i)microsoft') { $sandboxSupported = $kernel -match '(?i)microsoft-standard-WSL2' }
|
||||
}
|
||||
$claudeSandbox = if ($sandboxSupported) { '{"enabled": true, "allowUnsandboxedCommands": false, "failIfUnavailable": true, "network": {"allowedDomains": ["mcp.context7.com"]}}' } else { '{"enabled": false}' }
|
||||
# QMD search must reach its localhost daemon and write its index under the home directory, which the sandbox blocks.
|
||||
# The exact skill command keeps the exclusion narrow; harmless when local search is disabled.
|
||||
$claudeSandbox = if ($sandboxSupported) { '{"enabled": true, "allowUnsandboxedCommands": false, "failIfUnavailable": true, "excludedCommands": ["node \"$HOME/.my-ai-configuration/qmd/qmd-search.mjs\" *"], "network": {"allowedDomains": ["mcp.context7.com"]}}' } else { '{"enabled": false}' }
|
||||
$pluginManifest = Join-Path $root 'adapters/plugins.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" }
|
||||
$pluginEntries = @(Import-Csv -LiteralPath $pluginManifest -Delimiter ([char]9))
|
||||
@@ -31,9 +51,12 @@ foreach ($pluginEntry in $pluginEntries) {
|
||||
|
||||
if (-not (Test-Path -LiteralPath $capabilityManifest)) { throw "Missing capability manifest: $capabilityManifest" }
|
||||
$agentTools = @{}
|
||||
$agentSkills = @{}
|
||||
foreach ($entry in @(Import-Csv -LiteralPath $capabilityManifest -Delimiter ([char]9))) {
|
||||
if ([string]::IsNullOrWhiteSpace($entry.role) -or [string]::IsNullOrWhiteSpace($entry.tools)) { throw 'Invalid capability manifest row.' }
|
||||
$agentTools[$entry.role] = $entry.tools
|
||||
# Optional: skills whose full content Claude preloads into the subagent at startup.
|
||||
$agentSkills[$entry.role] = @(([string]$entry.skills).Split(',') | ForEach-Object { $_.Trim() } | Where-Object { $_ })
|
||||
}
|
||||
|
||||
# Build into a private sibling directory and swap it into place only after validation, so a failed
|
||||
@@ -49,6 +72,7 @@ New-Item $output -ItemType Directory | Out-Null
|
||||
|
||||
function Copy-Directory($source, $destination) {
|
||||
New-Item $destination -ItemType Directory -Force | Out-Null
|
||||
$source = (Get-Item -LiteralPath $source).FullName # expand 8.3 short paths so the prefix cut lines up
|
||||
Get-ChildItem $source -File -Recurse | ForEach-Object {
|
||||
$relative = $_.FullName.Substring($source.Length).TrimStart([char[]]@('\','/'))
|
||||
$target = Join-Path $destination $relative
|
||||
@@ -150,7 +174,14 @@ foreach ($shell in @('powershell','bash')) {
|
||||
$ruleContent = Get-Content $ruleSkill.Body -Raw
|
||||
$ruleTitle = (Get-Content $ruleSkill.Body | Where-Object { $_ -match '^#+\s+' } | Select-Object -First 1) -replace '^#+\s+', ''
|
||||
if ([string]::IsNullOrWhiteSpace($ruleTitle)) { throw "Missing rule title in $($ruleSkill.Body)" }
|
||||
# The rule's opening "Apply ..."/"For ..." sentence states when it applies; it is a better trigger than the title.
|
||||
$ruleLead = Get-Content $ruleSkill.Body | Where-Object { $_.Trim() -and $_ -notmatch '^#' } | Select-Object -First 1
|
||||
if ($ruleLead -match '^(Apply|For)\s') {
|
||||
$sentenceEnd = $ruleLead.IndexOf('. ')
|
||||
$ruleDescription = if ($sentenceEnd -ge 0) { $ruleLead.Substring(0, $sentenceEnd + 1) } else { $ruleLead.TrimEnd() }
|
||||
} else {
|
||||
$ruleDescription = "Use when the task concerns $ruleTitle."
|
||||
}
|
||||
$skillBody = "---`r`nname: $($ruleSkill.Name)`r`ndescription: $(Quote-Toml $ruleDescription)`r`n---`r`n`r`n$ruleContent"
|
||||
Set-Content (Join-Path $skillDir 'SKILL.md') $skillBody -Encoding UTF8
|
||||
if ($ruleSkill.References -and (Test-Path -LiteralPath $ruleSkill.References)) {
|
||||
@@ -158,19 +189,15 @@ 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
|
||||
$credentialHelperExtension = if ($shell -eq 'powershell') { 'ps1' } else { 'sh' }
|
||||
|
||||
$agentsContent = $sharedTemplate.Replace('__CLIENT__', 'codex').Replace('__SHELL__', $credentialHelperExtension)
|
||||
$agentsContent = $agentsContent.TrimEnd() + "`r`n`r`n---`r`n`r`n$generalContent"
|
||||
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
|
||||
$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"
|
||||
Set-Content (Join-Path $output "codex-$shell/AGENTS.md") $instructionsContent -Encoding UTF8
|
||||
Set-Content (Join-Path $output "claude-$shell/CLAUDE.md") $instructionsContent -Encoding UTF8
|
||||
|
||||
Copy-Item (Join-Path $root 'adapters/codex/config/config.toml') (Join-Path $output "codex-$shell/config.toml") -Force
|
||||
# Codex loads every *.rules file under ~/.codex/rules as execpolicy rules; the Markdown rules there are ignored.
|
||||
Copy-Item (Join-Path $root 'adapters/codex/rules/my-ai-configuration.rules') (Join-Path $output "codex-$shell/rules/my-ai-configuration.rules") -Force
|
||||
Copy-Item (Join-Path $root 'adapters/claude/config/settings.json') (Join-Path $output "claude-$shell/settings.json") -Force
|
||||
|
||||
foreach ($client in @('codex','claude')) {
|
||||
@@ -185,42 +212,29 @@ foreach ($shell in @('powershell','bash')) {
|
||||
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
|
||||
} else {
|
||||
$shellTool = if ($shell -eq 'powershell') { 'PowerShell' } else { 'Bash' }
|
||||
$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"
|
||||
if ($tools) { $frontmatter += "tools: $tools`r`n" }
|
||||
if ($agentSkills[$name]) { $frontmatter += "skills:`r`n" + (($agentSkills[$name] | ForEach-Object { " - $_`r`n" }) -join '') }
|
||||
Set-Content (Join-Path $agentsOutput "$name.md") ($frontmatter + "---`r`n`r`n$instructions") -Encoding UTF8
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($client in @('codex','claude')) {
|
||||
$file = if ($client -eq 'codex') { 'config.toml' } else { 'settings.json' }
|
||||
$path = Join-Path $output "$client-$shell/$file"
|
||||
$command = if ($shell -eq 'powershell') { '__POWERSHELL_COMMAND__' } else { 'bash' }
|
||||
$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)
|
||||
foreach ($path in @((Join-Path $output "codex-$shell/config.toml"), (Join-Path $output "claude-$shell/settings.json"))) {
|
||||
$content = Expand-ShellPlaceholders (Get-Content -LiteralPath $path -Raw) $shell
|
||||
# The sandbox depends on the build platform, not the shell, so it is not part of the placeholder table.
|
||||
$content = $content.Replace('__CLAUDE_SANDBOX__', $claudeSandbox)
|
||||
Set-Content -LiteralPath $path -Value $content -Encoding UTF8
|
||||
}
|
||||
|
||||
$tomlPath = Join-Path $output "codex-$shell/config.toml"
|
||||
$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." }
|
||||
Test-CodexSchema $tomlPath
|
||||
# Claude-only installs and updates never use the Codex packages, so their schema check is skipped.
|
||||
if (-not $SkipCodexSchema) { Test-CodexSchema $tomlPath }
|
||||
}
|
||||
|
||||
$leftoverPlaceholders = @(Get-ChildItem $output -File -Recurse | ForEach-Object {
|
||||
|
||||
+79
-70
@@ -1,14 +1,20 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
summary=false
|
||||
skip_codex_schema=false
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--summary) summary=true; shift ;;
|
||||
--skip-codex-schema) skip_codex_schema=true; shift ;;
|
||||
*) printf 'Unknown argument: %s\n' "$1" >&2; exit 1 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
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"
|
||||
final="$root/generated"
|
||||
sandbox_supported=false
|
||||
@@ -24,18 +30,48 @@ case "$platform" in
|
||||
;;
|
||||
esac
|
||||
sandbox='{"enabled": false}'
|
||||
[ "$sandbox_supported" != true ] || sandbox='{"enabled": true, "allowUnsandboxedCommands": false, "failIfUnavailable": true, "network": {"allowedDomains": ["mcp.context7.com"]}}'
|
||||
# QMD search must reach its localhost daemon and write its index under the home directory, which the sandbox blocks.
|
||||
# The exact skill command keeps the exclusion narrow; harmless when local search is disabled.
|
||||
[ "$sandbox_supported" != true ] || sandbox='{"enabled": true, "allowUnsandboxedCommands": false, "failIfUnavailable": true, "excludedCommands": ["node \"$HOME/.my-ai-configuration/qmd/qmd-search.mjs\" *"], "network": {"allowedDomains": ["mcp.context7.com"]}}'
|
||||
plugin_manifest="$root/adapters/plugins.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; }
|
||||
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"
|
||||
[ -f "$capability_manifest" ] || { printf 'Missing capability manifest: %s\n' "$capability_manifest" >&2; exit 1; }
|
||||
declare -A agent_tools
|
||||
while IFS=$'\t' read -r role tools; do
|
||||
declare -A agent_tools agent_skills
|
||||
while IFS=$'\t' read -r role tools skills; do
|
||||
[ "$role" != role ] || continue
|
||||
[ -n "$role" ] && [ -n "$tools" ] || { printf 'Invalid capability manifest row.\n' >&2; exit 1; }
|
||||
agent_tools[$role]="$tools"
|
||||
# Optional: skills whose full content Claude preloads into the subagent at startup.
|
||||
agent_skills[$role]="${skills:-}"
|
||||
done < "$capability_manifest"
|
||||
|
||||
copy_directory() {
|
||||
@@ -46,7 +82,8 @@ copy_directory() {
|
||||
|
||||
read_field() {
|
||||
local path=$1 name=$2 value
|
||||
value=$(sed -n "s/^${name}:[[:space:]]*//p" "$path" | head -n 1)
|
||||
# Quit inside sed: piping into head can SIGPIPE the writer, which pipefail turns into exit 141.
|
||||
value=$(sed -n "/^${name}:/{s/^${name}:[[:space:]]*//p;q;}" "$path")
|
||||
[ -n "$value" ] || { printf 'Missing %s in %s\n' "$name" "$path" >&2; exit 1; }
|
||||
printf '%s' "$value"
|
||||
}
|
||||
@@ -107,7 +144,7 @@ declare -A claude_skill_names=()
|
||||
while IFS= read -r skill_file; do
|
||||
skill_source=$(dirname -- "$skill_file")
|
||||
skill_name=$(basename -- "$skill_source")
|
||||
head -n 6 "$skill_file" | grep -qx "name: $skill_name" || { printf 'Skill name must match its directory: %s\n' "$skill_file" >&2; exit 1; }
|
||||
sed -n 1,6p "$skill_file" | grep -x "name: $skill_name" >/dev/null || { printf 'Skill name must match its directory: %s\n' "$skill_file" >&2; exit 1; }
|
||||
[ -z "${claude_skill_names[$skill_name]+x}" ] || { printf 'Duplicate Claude skill name: %s\n' "$skill_name" >&2; exit 1; }
|
||||
claude_skill_names[$skill_name]=1
|
||||
copy_directory "$skill_source" "$claude_skills/$skill_name"
|
||||
@@ -142,29 +179,32 @@ while IFS= read -r rule_path; do
|
||||
rule_skill_names[$skill_name]=1
|
||||
skill_dir="$claude_skills/$skill_name"
|
||||
mkdir -p "$skill_dir"
|
||||
rule_title=$(sed -n 's/^#\{1,6\} *//p' "$rule_body" | head -n 1)
|
||||
rule_title=$(sed -n '/^#\{1,6\} */{s///p;q;}' "$rule_body")
|
||||
if [ -z "$rule_title" ]; then printf 'Missing rule title in %s\n' "$rule_body" >&2; exit 1; fi
|
||||
rule_description="Use when the task concerns $rule_title."
|
||||
# The rule's opening "Apply ..."/"For ..." sentence states when it applies; it is a better trigger than the title.
|
||||
rule_lead=$(awk '!/^#/ && !/^[[:space:]]*$/ { print; exit }' "$rule_body" | tr -d '\r')
|
||||
case "$rule_lead" in
|
||||
'Apply '*|'For '*)
|
||||
rule_description=${rule_lead%%. *}
|
||||
if [ "$rule_description" != "$rule_lead" ]; then rule_description="$rule_description."; fi
|
||||
rule_description=${rule_description%"${rule_description##*[![:space:]]}"}
|
||||
;;
|
||||
*) rule_description="Use when the task concerns $rule_title." ;;
|
||||
esac
|
||||
{ printf -- '---\nname: %s\ndescription: %s\n---\n\n' "$skill_name" "$(quote_toml "$rule_description")"; cat "$rule_body"; } > "$skill_dir/SKILL.md"
|
||||
if [ -n "$references_dir" ] && [ -d "$references_dir" ]; then
|
||||
copy_directory "$references_dir" "$skill_dir/references"
|
||||
fi
|
||||
done < <(find "$shared/rules" -mindepth 1 -type f -name '*.md' -printf '%P\n' | sort)
|
||||
done < <(cd "$shared/rules" && find . -mindepth 1 -type f -name '*.md' | sed 's|^\./||' | sort)
|
||||
|
||||
shared_template=$(<"$shared/global-instructions.md")
|
||||
instructions_content=$(expand_shell_placeholders "$(<"$shared/global-instructions.md")" "$shell")
|
||||
general_content=$(<"$shared/rules/general.md")
|
||||
credential_helper_extension='sh'
|
||||
[ "$shell" != powershell ] || credential_helper_extension='ps1'
|
||||
|
||||
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"
|
||||
printf '%s\n\n---\n\n%s\n' "${instructions_content%$'\n'}" "$general_content" > "$output/codex-$shell/AGENTS.md"
|
||||
printf '%s\n\n---\n\n%s\n' "${instructions_content%$'\n'}" "$general_content" > "$output/claude-$shell/CLAUDE.md"
|
||||
|
||||
cp "$root/adapters/codex/config/config.toml" "$output/codex-$shell/config.toml"
|
||||
# Codex loads every *.rules file under ~/.codex/rules as execpolicy rules; the Markdown rules there are ignored.
|
||||
cp "$root/adapters/codex/rules/my-ai-configuration.rules" "$output/codex-$shell/rules/my-ai-configuration.rules"
|
||||
cp "$root/adapters/claude/config/settings.json" "$output/claude-$shell/settings.json"
|
||||
|
||||
for client in codex claude; do
|
||||
@@ -178,66 +218,35 @@ for client in codex claude; do
|
||||
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"
|
||||
else
|
||||
tools=${agent_tools[$name]:-}
|
||||
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
|
||||
tools=$(expand_shell_placeholders "${agent_tools[$name]:-}" "$shell")
|
||||
{
|
||||
printf -- '---\nname: %s\ndescription: %s\n' "$name" "$description"
|
||||
if [ -n "$tools" ]; then printf 'tools: %s\n' "$tools"; fi
|
||||
if [ -n "${agent_skills[$name]:-}" ]; then
|
||||
printf 'skills:\n'
|
||||
IFS=',' read -r -a preload <<<"${agent_skills[$name]}"
|
||||
for skill in "${preload[@]}"; do skill=${skill//[[:space:]]/}; [ -z "$skill" ] || printf ' - %s\n' "$skill"; done
|
||||
fi
|
||||
printf -- '---\n\n%s\n' "$instructions"
|
||||
} > "$agents_output/$name.md"
|
||||
fi
|
||||
done
|
||||
done
|
||||
|
||||
for client in codex claude; do
|
||||
file=config.toml
|
||||
[ "$client" != claude ] || file=settings.json
|
||||
command=bash
|
||||
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}
|
||||
for path in "$output/codex-$shell/config.toml" "$output/claude-$shell/settings.json"; do
|
||||
content=$(expand_shell_placeholders "$(<"$path")" "$shell")
|
||||
# The sandbox depends on the build platform, not the shell, so it is not part of the placeholder table.
|
||||
content=${content//__CLAUDE_SANDBOX__/"$sandbox"}
|
||||
printf '%s\n' "$content" > "$path"
|
||||
done
|
||||
|
||||
toml_path="$output/codex-$shell/config.toml"
|
||||
settings_path="$output/claude-$shell/settings.json"
|
||||
python3 "$root/scripts/checks/validate-config.py" "$toml_path" "$settings_path"
|
||||
if command -v codex >/dev/null; then
|
||||
run_python "$root/scripts/checks/validate-config.py" "$toml_path" "$settings_path"
|
||||
# Claude-only installs and updates never use the Codex packages, so their schema check is skipped.
|
||||
if [ "$skip_codex_schema" = true ]; then
|
||||
:
|
||||
elif command -v codex >/dev/null; then
|
||||
schema_home=$(mktemp -d)
|
||||
cp "$toml_path" "$schema_home/config.toml"
|
||||
CODEX_HOME="$schema_home" codex --strict-config --help >/dev/null
|
||||
|
||||
@@ -11,14 +11,12 @@ function Check-Version([string]$name, [string]$version, [version]$minimum) { if
|
||||
Check-Version 'PowerShell' $PSVersionTable.PSVersion.ToString() ([version]'5.1')
|
||||
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' }
|
||||
$pythonVersion = $null
|
||||
foreach ($python in @('python', 'python3')) {
|
||||
if (-not (Get-Command $python -ErrorAction SilentlyContinue)) { continue }
|
||||
$candidate = & $python --version 2>$null
|
||||
$pythonExitCode = $LASTEXITCODE
|
||||
if ($pythonExitCode -eq 0) { $pythonVersion = $candidate -replace '^Python\s+', ''; break }
|
||||
}
|
||||
if ($null -ne $pythonVersion) { Check-Version 'Python' $pythonVersion ([version]'3.11') } else { Fail 'Python 3.11 or newer is required' }
|
||||
. (Join-Path (Split-Path (Split-Path $PSScriptRoot -Parent) -Parent) 'shared/hooks/scripts/Resolve-Python.ps1')
|
||||
$python = Get-PythonCommand
|
||||
if ($python) {
|
||||
$pythonVersion = (& $python.Path @($python.Arguments) -c 'import platform; print(platform.python_version())' 2>$null | Out-String).Trim()
|
||||
Check-Version 'Python' $pythonVersion ([version]'3.11')
|
||||
} else { Fail (Get-PythonMissingMessage) }
|
||||
|
||||
if ($failed) { Write-Error 'Capability check: FAIL'; exit 1 }
|
||||
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
|
||||
}
|
||||
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() {
|
||||
local name=$1 version=$2 required=$3
|
||||
@@ -18,11 +18,12 @@ check_version() {
|
||||
check_version Bash "${BASH_VERSINFO[0]}.${BASH_VERSINFO[1]}" 4.3
|
||||
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
|
||||
require_command python3
|
||||
if command -v python3 >/dev/null 2>&1 && python3 -c 'import sys; raise SystemExit(sys.version_info < (3, 11))' >/dev/null 2>&1; then
|
||||
pass "Python $(python3 --version 2>&1 | awk '{print $2}') (minimum 3.11)"
|
||||
# shellcheck source=../../shared/hooks/scripts/resolve-python.sh
|
||||
. "$(dirname -- "${BASH_SOURCE[0]}")/../../shared/hooks/scripts/resolve-python.sh"
|
||||
if resolve_python; then
|
||||
check_version Python "$(run_python -c 'import platform; print(platform.python_version())')" 3.11
|
||||
else
|
||||
fail 'Python 3.11 or newer is required'
|
||||
fail "$(python_missing_message)"
|
||||
fi
|
||||
|
||||
if [ "$failed" = true ]; then printf 'Capability check: FAIL\n' >&2; exit 1; fi
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$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
|
||||
@@ -1,4 +1,7 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
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'
|
||||
$root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
|
||||
. (Join-Path $root 'scripts/lib/manifest.ps1')
|
||||
. (Join-Path $root 'shared/hooks/scripts/Resolve-Python.ps1')
|
||||
$homePath = [Environment]::GetFolderPath('UserProfile')
|
||||
if ([string]::IsNullOrWhiteSpace($homePath)) { $homePath = $HOME }
|
||||
$script:fail = $false
|
||||
@@ -37,6 +38,29 @@ foreach ($tool in @('codex','claude')) {
|
||||
} 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' }
|
||||
# Globally installed npm CLIs (qmd, mcporter) must be callable by agents, so npm's global bin directory belongs on PATH.
|
||||
if (Get-Command npm -ErrorAction SilentlyContinue) {
|
||||
$npmPrefix = @((Invoke-DoctorCommand -Command 'npm' -Arguments @('prefix', '--global')).Output | ForEach-Object { "$_".Trim() } | Where-Object { $_ }) | Select-Object -Last 1
|
||||
if ($npmPrefix) {
|
||||
$npmBin = if ([Environment]::OSVersion.Platform -eq [PlatformID]::Win32NT) { $npmPrefix } else { Join-Path $npmPrefix 'bin' }
|
||||
$pathEntries = @($env:PATH -split [regex]::Escape([string][System.IO.Path]::PathSeparator) | ForEach-Object { $_.TrimEnd([char[]]@('\', '/')) })
|
||||
if ($pathEntries -contains $npmBin.TrimEnd([char[]]@('\', '/'))) { Result 'PASS' "npm global bin directory is on PATH ($npmBin)" }
|
||||
else { Result 'WARN' "npm global bin directory $npmBin is not on PATH; agents cannot call globally installed CLIs such as mcporter. Add it to your user PATH and restart the terminal." }
|
||||
}
|
||||
}
|
||||
$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." }
|
||||
# QMD local search: reports nothing when the setup did not enable it.
|
||||
if ($python) {
|
||||
$qmdChecks = Invoke-DoctorCommand -Command $python.Path -Arguments (@($python.Arguments) + @((Join-Path $root 'scripts/lib/qmd.py'), 'doctor', '--root', $root, '--home', $homePath))
|
||||
if ($qmdChecks.ExitCode -ne 0) { Result 'WARN' "QMD checks failed: $($qmdChecks.Output -join ' ')" }
|
||||
else { foreach ($line in $qmdChecks.Output) { if ("$line" -match '^(PASS|WARN|FAIL) (.+)$') { Result $Matches[1] $Matches[2] } } }
|
||||
# Upstream skill updates can rename what plugin-workflow coordinates; reports nothing when neither skill is installed.
|
||||
$contractChecks = Invoke-DoctorCommand -Command $python.Path -Arguments (@($python.Arguments) + @((Join-Path $root 'scripts/lib/skill-contracts.py'), '--home', $homePath))
|
||||
if ($contractChecks.ExitCode -ne 0) { Result 'WARN' "Skill contract checks failed: $($contractChecks.Output -join ' ')" }
|
||||
else { foreach ($line in $contractChecks.Output) { if ("$line" -match '^(PASS|WARN|FAIL) (.+)$') { Result $Matches[1] $Matches[2] } } }
|
||||
}
|
||||
|
||||
$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
|
||||
@@ -71,8 +95,11 @@ if (Test-Path -LiteralPath $settingsPath) {
|
||||
}
|
||||
$configTomlPath = Join-Path $homePath '.codex/config.toml'
|
||||
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 (Get-Command codex -ErrorAction SilentlyContinue) {
|
||||
$previousCodexHome = $env:CODEX_HOME
|
||||
try {
|
||||
|
||||
@@ -10,6 +10,9 @@ while [ $# -gt 0 ]; do
|
||||
done
|
||||
|
||||
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"
|
||||
home_path=${HOME:?HOME is required}
|
||||
failed=false
|
||||
@@ -33,6 +36,43 @@ for tool in codex claude; do
|
||||
else result WARN "$tool unavailable"; fi
|
||||
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'
|
||||
# Globally installed npm CLIs (qmd, mcporter) must be callable by agents, so npm's global bin directory belongs on PATH.
|
||||
if command -v npm >/dev/null 2>&1; then
|
||||
npm_prefix=$(npm prefix --global 2>/dev/null | tr -d '␍' | tail -n 1)
|
||||
if [ -n "$npm_prefix" ]; then
|
||||
case "$(uname -s 2>/dev/null)" in
|
||||
MINGW*|MSYS*|CYGWIN*) npm_bin=$(cygpath -u "$npm_prefix" 2>/dev/null || printf '%s' "$npm_prefix") ;;
|
||||
*) npm_bin="$npm_prefix/bin" ;;
|
||||
esac
|
||||
case ":$PATH:" in
|
||||
*":$npm_bin:"*|*":$npm_bin/:"*) result PASS "npm global bin directory is on PATH ($npm_bin)" ;;
|
||||
*) result WARN "npm global bin directory $npm_bin is not on PATH; agents cannot call globally installed CLIs such as mcporter. Add it to your user PATH and restart the terminal." ;;
|
||||
esac
|
||||
fi
|
||||
fi
|
||||
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
|
||||
# QMD local search: reports nothing when the setup did not enable it.
|
||||
if resolve_python; then
|
||||
if qmd_output=$(run_python "$root/scripts/lib/qmd.py" doctor --root "$root" --home "$home_path" 2>&1); then
|
||||
while IFS= read -r line; do
|
||||
case "$line" in PASS\ *|WARN\ *|FAIL\ *) result "${line%% *}" "${line#* }" ;; esac
|
||||
done <<< "$qmd_output"
|
||||
else
|
||||
result WARN "QMD checks failed: ${qmd_output//$'\n'/ }"
|
||||
fi
|
||||
# Upstream skill updates can rename what plugin-workflow coordinates; reports nothing when neither skill is installed.
|
||||
if contract_output=$(run_python "$root/scripts/lib/skill-contracts.py" --home "$home_path" 2>&1); then
|
||||
while IFS= read -r line; do
|
||||
case "$line" in PASS\ *|WARN\ *|FAIL\ *) result "${line%% *}" "${line#* }" ;; esac
|
||||
done <<< "$contract_output"
|
||||
else
|
||||
result WARN "Skill contract checks failed: ${contract_output//$'\n'/ }"
|
||||
fi
|
||||
fi
|
||||
|
||||
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)
|
||||
@@ -62,8 +102,8 @@ done
|
||||
if [ -f "$home_path/.claude/settings.json" ]; 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
|
||||
elif command -v python3 >/dev/null 2>&1 && python3 --version >/dev/null 2>&1; 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
|
||||
elif resolve_python; 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'
|
||||
else
|
||||
result FAIL 'installed .claude/settings.json is not valid JSON'
|
||||
@@ -71,7 +111,9 @@ if [ -f "$home_path/.claude/settings.json" ]; then
|
||||
fi
|
||||
fi
|
||||
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'
|
||||
else
|
||||
result FAIL 'installed .codex/config.toml is invalid TOML'
|
||||
|
||||
@@ -26,7 +26,7 @@ if (-not $DryRun -and (Test-AnyManifestPresent (Get-InstallDestinations -HomePat
|
||||
$options = Read-InstallOptions -HomePath $homePath -RepositoryRoot $root -Client $Client -DryRun:$DryRun
|
||||
|
||||
$buildScript = Join-Path $root 'scripts/commands/build.ps1'
|
||||
& $buildScript -Summary:$Summary
|
||||
& $buildScript -Summary:$Summary -SkipCodexSchema:($Client -eq 'Claude')
|
||||
if (-not $?) { throw 'Build failed. Installation was not started.' }
|
||||
$generated = Join-Path $root 'generated'
|
||||
if (-not (Test-Path $generated)) { throw 'Generated output is missing after a successful build.' }
|
||||
|
||||
@@ -39,6 +39,7 @@ read_install_options
|
||||
|
||||
build_args=()
|
||||
[ "$summary" = false ] || build_args+=(--summary)
|
||||
[ "$client" != claude ] || build_args+=(--skip-codex-schema)
|
||||
bash "$root/scripts/commands/build.sh" "${build_args[@]}"
|
||||
generated="$root/generated"
|
||||
[ -d "$generated" ] || { printf 'Generated output is missing after a successful build.\n' >&2; exit 1; }
|
||||
|
||||
@@ -2,11 +2,12 @@
|
||||
param([switch]$Summary)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$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'
|
||||
$budgetArgs = @()
|
||||
if ($Summary) { $budgetArgs += '--summary' }
|
||||
& python $budgetScript @budgetArgs
|
||||
Invoke-Python $budgetScript @budgetArgs
|
||||
$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.' }
|
||||
exit $budgetExit
|
||||
@@ -3,9 +3,12 @@ set -euo pipefail
|
||||
summary=false
|
||||
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)
|
||||
# shellcheck source=../../shared/hooks/scripts/resolve-python.sh
|
||||
. "$root/shared/hooks/scripts/resolve-python.sh"
|
||||
resolve_python || true
|
||||
budget_args=()
|
||||
[ "$summary" = false ] || budget_args+=(--summary)
|
||||
budget_status=0
|
||||
python3 "$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-budget.py" "${budget_args[@]}" || budget_status=$?
|
||||
run_python "$root/scripts/lib/prompt-inventory.py" --home "${HOME:?HOME is required}"
|
||||
exit "$budget_status"
|
||||
@@ -6,11 +6,7 @@ param(
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
|
||||
. (Join-Path $root 'scripts/lib/install-targets.ps1')
|
||||
$selectedClient = $Client
|
||||
$selectedKey = $Key
|
||||
. (Join-Path $root 'scripts/lib/credentials.ps1')
|
||||
$Client = $selectedClient
|
||||
$Key = $selectedKey
|
||||
. (Join-Path $root 'scripts/lib/with-credential.ps1')
|
||||
|
||||
if (-not $Client) { $Client = Read-InstallClient -Client $Client }
|
||||
if (-not $Key) { $Key = Read-Host 'Credential key to remove' }
|
||||
|
||||
@@ -6,10 +6,11 @@ param(
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$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')
|
||||
|
||||
if (-not $Client) { $Client = Read-InstallClient -Client $Client }
|
||||
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.' }
|
||||
& 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.' }
|
||||
@@ -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
|
||||
|
||||
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
|
||||
python_command=$(command -v python || command -v python3 || true)
|
||||
[ -n "$python_command" ] || { printf 'Python is required to remove instructions.\n' >&2; exit 1; }
|
||||
"$python_command" "$script_dir/../lib/remove-instruction.py" --client "${client,,}" --instruction "$instruction" --home "$home_path"
|
||||
# shellcheck source=../../shared/hooks/scripts/resolve-python.sh
|
||||
. "$script_dir/../../shared/hooks/scripts/resolve-python.sh"
|
||||
resolve_python || { python_missing_message >&2; exit 1; }
|
||||
run_python "$script_dir/../lib/remove-instruction.py" --client "${client,,}" --instruction "$instruction" --home "$home_path"
|
||||
@@ -8,6 +8,6 @@ while IFS= read -r file; do key_input+="\n$file:$(sha256sum "$file" | awk '{prin
|
||||
key=$(printf '%s' "$key_input" | sha256sum | awk '{print $1}')
|
||||
if [ "$force" = false ] && [ -f "$cache_path" ] && grep -Fq "\"invalidationKey\": \"$key\"" "$cache_path"; then [ "$summary" = true ] && printf 'Repository context: unchanged\n'; exit 0; fi
|
||||
mapfile -t languages < <(find "$root" -type f ! -path '*/generated/*' ! -path '*/.git/*' ! -path '*/node_modules/*' ! -path '*/.ai-session/*' | awk -F. 'NF>1 {print $NF}' | sort -u | awk 'BEGIN{a["cs"]="csharp";a["ts"]="typescript";a["tsx"]="typescript";a["py"]="python";a["ps1"]="powershell";a["sh"]="bash"} a[$1]!=""{print a[$1]}' | sort -u)
|
||||
solutions=$(find "$root" -type f -name '*.sln' ! -path '*/generated/*' -printf '"%f",' | sed 's/,$//'); tests=$(find "$root" -type f ! -path '*/generated/*' ! -path '*/.git/*' -iname '*test*' -printf '"%f",' | sed 's/,$//'); manager=null; [ -f "$root/pnpm-lock.yaml" ] && manager='"pnpm"'; [ -f "$root/package-lock.json" ] && manager='"npm"'; [ -f "$root/yarn.lock" ] && manager='"yarn"'
|
||||
solutions=$(find "$root" -type f -name '*.sln' ! -path '*/generated/*' | sed 's|.*/||; s/.*/"&",/' | tr -d '\n' | sed 's/,$//'); tests=$(find "$root" -type f ! -path '*/generated/*' ! -path '*/.git/*' -iname '*test*' | sed 's|.*/||; s/.*/"&",/' | tr -d '\n' | sed 's/,$//'); manager=null; [ -f "$root/pnpm-lock.yaml" ] && manager='"pnpm"'; [ -f "$root/package-lock.json" ] && manager='"npm"'; [ -f "$root/yarn.lock" ] && manager='"yarn"'
|
||||
mkdir -p "$cache_dir"; printf '{\n "invalidationKey": "%s",\n "head": "%s",\n "languages": [%s],\n "frameworks": [],\n "solutions": [%s],\n "testProjects": [%s],\n "packageManager": %s,\n "buildCommands": {}\n}\n' "$key" "$head" "$(printf '"%s",' "${languages[@]}" | sed 's/,$//')" "$solutions" "$tests" "$manager" > "$cache_path"
|
||||
if [ "$summary" = true ]; then printf 'Repository context: refreshed | %s languages | %s solutions\n' "${#languages[@]}" "$(find "$root" -type f -name '*.sln' ! -path '*/generated/*' | wc -l)"; else printf '%s\n' "$cache_path"; fi
|
||||
@@ -27,5 +27,7 @@ if ($Pointer) { $arguments += '--pointer' }
|
||||
if ($Reset) { $arguments += '--reset' }
|
||||
$payload = $values | ConvertTo-Json -Depth 4 -Compress
|
||||
$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
|
||||
@@ -1,6 +1,9 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
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=()
|
||||
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
|
||||
[ "${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"
|
||||
# shellcheck source=../../shared/hooks/scripts/resolve-python.sh
|
||||
. "$root/shared/hooks/scripts/resolve-python.sh"
|
||||
resolve_python || true
|
||||
action=${1:-record}; shift || true
|
||||
case "$action" in
|
||||
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
|
||||
rows=[]
|
||||
for line in open(sys.argv[1],encoding='utf-8',errors='replace'):
|
||||
@@ -20,7 +23,7 @@ PY
|
||||
exit 0;;
|
||||
record) event=${1:?event required}; shift;; *) printf 'Unknown action: %s\n' "$action" >&2; exit 1;;
|
||||
esac
|
||||
python3 - "$path" "$event" "$@" <<'PY' || exit 0
|
||||
run_python - "$path" "$event" "$@" <<'PY' || exit 0
|
||||
import json,sys,datetime
|
||||
path,event=sys.argv[1:3]; args=sys.argv[3:]
|
||||
record={'event':event,'timestamp':datetime.datetime.now(datetime.timezone.utc).isoformat()}
|
||||
|
||||
@@ -60,7 +60,8 @@ Sync-ConfiguredPlugins -RepositoryRoot $root -HomePath $homePath -Client $Client
|
||||
Sync-Qmd -RepositoryRoot $root -HomePath $homePath -Client $Client -Enabled $false -DryRun:$DryRun -Summary:$Summary
|
||||
|
||||
if (-not $DryRun) {
|
||||
$remaining = @($targets | Where-Object { Test-Path -LiteralPath (Get-ManagedManifestPath $_.Destination) })
|
||||
# Keep the shared selection while the other client is still installed.
|
||||
$remaining = @(Get-InstallTargets -Generated $generated -HomePath $homePath -Shell 'bash' -Client 'Both' | Where-Object { Test-Path -LiteralPath (Get-ManagedManifestPath $_.Destination) })
|
||||
if ($remaining.Count -eq 0) {
|
||||
$configRoot = Join-Path $homePath '.my-ai-configuration'
|
||||
$selectionPath = Join-Path $configRoot 'selection.json'
|
||||
|
||||
@@ -79,9 +79,10 @@ sync_qmd "$root" "$client" "$home_path" false "$dry_run" false "$summary"
|
||||
|
||||
if [ "$dry_run" = false ]; then
|
||||
remaining=0
|
||||
for target_pair in "${targets[@]}"; do
|
||||
# Keep the shared selection while the other client is still installed.
|
||||
while IFS= read -r target_pair; do
|
||||
[ -f "$(manifest_path "${target_pair#*|}")" ] && remaining=$((remaining + 1))
|
||||
done
|
||||
done < <(get_install_targets "$generated" "$home_path" bash both)
|
||||
if [ "$remaining" -eq 0 ]; then
|
||||
config_root="$home_path/.my-ai-configuration"
|
||||
rm -f -- "$config_root/selection.json"
|
||||
|
||||
@@ -15,6 +15,9 @@ $root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
|
||||
. (Join-Path $root 'scripts/lib/install-options.ps1')
|
||||
. (Join-Path $root 'scripts/lib/qmd.ps1')
|
||||
|
||||
$claudeConcurrency = if ($env:CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY) { $env:CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY } else { '5' }
|
||||
if ($claudeConcurrency -notmatch '^[1-9][0-9]?$' -or [int]$claudeConcurrency -gt 10) { throw 'CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY must be an integer from 1 to 10.' }
|
||||
|
||||
$homePath = [Environment]::GetFolderPath('UserProfile')
|
||||
if ($Quick) {
|
||||
$saved = Read-UpdateSelection -HomePath $homePath -RepositoryRoot $root
|
||||
@@ -33,7 +36,7 @@ if (-not $DryRun -and -not (Test-AllManifestsPresent (Get-InstallDestinations -H
|
||||
$options = if ($Quick) { $saved } else { Read-InstallOptions -HomePath $homePath -RepositoryRoot $root -Client $Client -DryRun:$DryRun }
|
||||
|
||||
$buildScript = Join-Path $root 'scripts/commands/build.ps1'
|
||||
& $buildScript -Summary:$Summary
|
||||
& $buildScript -Summary:$Summary -SkipCodexSchema:($Client -eq 'Claude')
|
||||
if (-not $?) { throw 'Build failed. Update was not started.' }
|
||||
$generated = Join-Path $root 'generated'
|
||||
if (-not (Test-Path $generated)) { throw 'Generated output is missing after a successful build.' }
|
||||
@@ -51,7 +54,7 @@ $plugins = if ($Quick) {
|
||||
|
||||
foreach ($item in (Get-InstallTargets -Generated $generated -HomePath $homePath -Shell $shell -Client $Client)) {
|
||||
Sync-ManagedDestination -Source $item.Source -Destination $item.Destination -Stamp $stamp `
|
||||
-AiConfigRoot $item.Destination.Replace('\','/') -ShellCommand $shellCommand -PowerShellCommand $powerShellCommand -FlashbangEnabled $options.flashbang -StatusLineEnabled $options.statusline -SemanticRetrievalEnabled $options.semantic_retrieval -DryRun:$DryRun -Summary:$Summary
|
||||
-AiConfigRoot $item.Destination.Replace('\','/') -ShellCommand $shellCommand -PowerShellCommand $powerShellCommand -ClaudeConcurrency $claudeConcurrency -FlashbangEnabled $options.flashbang -StatusLineEnabled $options.statusline -SemanticRetrievalEnabled $options.semantic_retrieval -DryRun:$DryRun -Summary:$Summary
|
||||
}
|
||||
|
||||
Sync-Qmd -RepositoryRoot $root -HomePath $homePath -Client $Client -Enabled $options.semantic_retrieval -DryRun:$DryRun -Update -Summary:$Summary
|
||||
|
||||
@@ -25,6 +25,9 @@ root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)
|
||||
. "$root/scripts/lib/install-options.sh"
|
||||
. "$root/scripts/lib/qmd.sh"
|
||||
|
||||
claude_concurrency=${CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY:-5}
|
||||
[[ "$claude_concurrency" =~ ^[1-9][0-9]?$ ]] && [ "$claude_concurrency" -le 10 ] || { printf 'CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY must be an integer from 1 to 10.\n' >&2; exit 1; }
|
||||
|
||||
home_path=${HOME:?HOME is required}
|
||||
selected_plugins=()
|
||||
deselected_plugins=()
|
||||
@@ -45,6 +48,7 @@ if [ "$quick" = false ]; then read_install_options; fi
|
||||
|
||||
build_args=()
|
||||
[ "$summary" = false ] || build_args+=(--summary)
|
||||
[ "$client" != claude ] || build_args+=(--skip-codex-schema)
|
||||
bash "$root/scripts/commands/build.sh" "${build_args[@]}"
|
||||
generated="$root/generated"
|
||||
[ -d "$generated" ] || { printf 'Generated output is missing after a successful build.\n' >&2; exit 1; }
|
||||
@@ -63,7 +67,7 @@ fi
|
||||
while IFS='|' read -r source destination; do
|
||||
ai_config_root=$destination
|
||||
command -v cygpath >/dev/null && ai_config_root=$(cygpath -m "$destination")
|
||||
sync_managed_destination "$source" "$destination" "$stamp" "$ai_config_root" "$shell_command" "$powershell_command" "$dry_run" "$summary" "$flashbang" 5 "$statusline" "$semantic_retrieval"
|
||||
sync_managed_destination "$source" "$destination" "$stamp" "$ai_config_root" "$shell_command" "$powershell_command" "$dry_run" "$summary" "$flashbang" "$claude_concurrency" "$statusline" "$semantic_retrieval"
|
||||
done < <(get_install_targets "$generated" "$home_path" "$shell" "$client")
|
||||
|
||||
sync_qmd "$root" "$client" "$home_path" "$semantic_retrieval" "$dry_run" true "$summary"
|
||||
|
||||
@@ -8,13 +8,17 @@ import tomllib
|
||||
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|caveman-?mode|qmd-warm|Start-QmdWarm|completion-?evidence|correction-?prompt|command-?safety|impeccable-?hook|search-?reminder)\.(?:ps1|sh)'
|
||||
|
||||
|
||||
def is_flashbang(hook):
|
||||
return any(re.search(r'(?:[/\\\s"\x27]|^)flashbang\.(?:ps1|sh)(?:[\s"\x27]|$)', str(hook.get(key, '')), re.I)
|
||||
for key in ('command', 'command_windows'))
|
||||
|
||||
|
||||
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'))
|
||||
|
||||
|
||||
@@ -54,6 +58,12 @@ def filter_options(path, flashbang_enabled=True, statusline_enabled=True, semant
|
||||
settings['hooks']['SessionStart'] = remaining
|
||||
else:
|
||||
settings.get('hooks', {}).pop('SessionStart', None)
|
||||
sandbox = settings.get('sandbox', {})
|
||||
excluded = [command for command in sandbox.get('excludedCommands', []) if 'qmd-search.mjs' not in command]
|
||||
if excluded:
|
||||
sandbox['excludedCommands'] = excluded
|
||||
else:
|
||||
sandbox.pop('excludedCommands', None)
|
||||
if not statusline_enabled:
|
||||
settings.pop('statusLine', None)
|
||||
return json.dumps(settings, indent=2, ensure_ascii=False) + '\n'
|
||||
@@ -99,29 +109,43 @@ def filter_flashbang(path):
|
||||
return filter_options(path, flashbang_enabled=False)
|
||||
|
||||
|
||||
def without_owned_hooks(groups):
|
||||
retained = []
|
||||
for group in groups:
|
||||
if not isinstance(group, dict) or not isinstance(group.get('hooks'), list):
|
||||
retained.append(group)
|
||||
continue
|
||||
foreign = [hook for hook in group['hooks'] if not (isinstance(hook, dict) and re.search(
|
||||
OWNED_HOOK_PATTERN,
|
||||
str(hook.get('command', '')) + str(hook.get('command_windows', '')), re.I))]
|
||||
if foreign:
|
||||
retained.append(dict(group, hooks=foreign))
|
||||
return retained
|
||||
|
||||
|
||||
def without_qmd_exclusion(settings):
|
||||
sandbox = settings.get('sandbox')
|
||||
if isinstance(sandbox, dict) and isinstance(sandbox.get('excludedCommands'), list):
|
||||
# The QMD exclusion is owned; managed settings re-add it only while semantic retrieval is enabled.
|
||||
excluded = [command for command in sandbox['excludedCommands'] if 'qmd-search.mjs' not in str(command)]
|
||||
settings['sandbox'] = dict(sandbox, excludedCommands=excluded) if excluded else {k: v for k, v in sandbox.items() if k != 'excludedCommands'}
|
||||
|
||||
|
||||
def merge_json(current, managed):
|
||||
if not isinstance(current, dict) or not isinstance(managed, dict):
|
||||
return managed
|
||||
result = dict(current)
|
||||
if 'statusLine' not in managed:
|
||||
result.pop('statusLine', None)
|
||||
without_qmd_exclusion(result)
|
||||
for key, value in managed.items():
|
||||
if key == 'hooks' and isinstance(value, dict) and isinstance(result.get(key), dict):
|
||||
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, [])
|
||||
old_groups = hooks.get(event, [])
|
||||
if isinstance(groups, list) and isinstance(old_groups, list):
|
||||
retained = []
|
||||
for group in old_groups:
|
||||
if not isinstance(group, dict) or not isinstance(group.get('hooks'), list):
|
||||
retained.append(group)
|
||||
continue
|
||||
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)',
|
||||
str(hook.get('command', '')) + str(hook.get('command_windows', '')), re.I))]
|
||||
if foreign:
|
||||
retained.append(dict(group, hooks=foreign))
|
||||
retained = without_owned_hooks(old_groups)
|
||||
merged = groups + [group for group in retained if group not in groups]
|
||||
if merged:
|
||||
hooks[event] = merged
|
||||
@@ -167,7 +191,7 @@ def merge_toml(current_text, managed_text, statusline_enabled=True):
|
||||
managed_headers = {header for header, _ in managed_sections}
|
||||
extras = []
|
||||
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):
|
||||
plugin_table = re.match(r'^\[(?:plugins|marketplaces)(?:\.|\])', header)
|
||||
array_table = header.startswith('[[')
|
||||
@@ -221,9 +245,46 @@ def merge_toml(current_text, managed_text, statusline_enabled=True):
|
||||
return result
|
||||
|
||||
|
||||
def strip_json(current):
|
||||
"""Remove only what this setup owns (hooks, status line, QMD exclusion); keep everything else."""
|
||||
if not isinstance(current, dict):
|
||||
return current
|
||||
result = dict(current)
|
||||
status = result.get('statusLine')
|
||||
if isinstance(status, dict) and re.search(OWNED_HOOK_PATTERN, str(status.get('command', '')), re.I):
|
||||
del result['statusLine']
|
||||
without_qmd_exclusion(result)
|
||||
if isinstance(result.get('hooks'), dict):
|
||||
hooks = {}
|
||||
for event, groups in result['hooks'].items():
|
||||
remaining = without_owned_hooks(groups) if isinstance(groups, list) else groups
|
||||
if remaining:
|
||||
hooks[event] = remaining
|
||||
if hooks:
|
||||
result['hooks'] = hooks
|
||||
else:
|
||||
del result['hooks']
|
||||
return result
|
||||
|
||||
|
||||
def strip_toml(current_text):
|
||||
# Merging with an empty managed file drops owned hook tables and keeps every other line.
|
||||
result = merge_toml(current_text, '').lstrip('\r\n')
|
||||
return result if result.strip() else ''
|
||||
|
||||
|
||||
def strip_file(path):
|
||||
"""Return path's content without owned entries, or '' when nothing else remains."""
|
||||
content = path.read_text(encoding='utf-8-sig')
|
||||
if path.name == 'config.toml':
|
||||
return strip_toml(content)
|
||||
result = strip_json(json.loads(content))
|
||||
return json.dumps(result, indent=2, ensure_ascii=False) + '\n' if result else ''
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('action', choices=('filter', 'filter-instructions', 'merge-json', 'merge-toml'))
|
||||
parser.add_argument('action', choices=('filter', 'filter-instructions', 'merge-json', 'merge-toml', 'strip'))
|
||||
parser.add_argument('--path', type=Path)
|
||||
parser.add_argument('--current', type=Path)
|
||||
parser.add_argument('--flashbang', choices=('true', 'false'))
|
||||
@@ -241,6 +302,8 @@ if __name__ == '__main__':
|
||||
if args.destination and args.path.name in CLIENT_FILES.values():
|
||||
client = next(client for client, name in CLIENT_FILES.items() if name == args.path.name)
|
||||
result = render(result, args.destination.parent, client)
|
||||
elif args.action == 'strip':
|
||||
result = strip_file(args.current)
|
||||
else:
|
||||
managed = args.managed.read_text(encoding='utf-8-sig') if args.managed else sys.stdin.buffer.read().decode('utf-8-sig')
|
||||
current = args.current.read_text(encoding='utf-8-sig')
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
#!/usr/bin/env bash
|
||||
# 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() {
|
||||
local prompt=$1 default=$2 hint=y/N answer
|
||||
@@ -22,7 +25,7 @@ read_install_options() {
|
||||
semantic_retrieval=false
|
||||
local saved key value
|
||||
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
|
||||
value=${value%$'\r'}
|
||||
case "$key" in flashbang) flashbang=$value ;; statusline) statusline=$value ;; semantic_retrieval) semantic_retrieval=$value ;; esac
|
||||
|
||||
@@ -11,10 +11,14 @@ import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.request
|
||||
import zipfile
|
||||
|
||||
|
||||
PONYTAIL_MODE = 'ultra'
|
||||
|
||||
|
||||
def linked(path):
|
||||
try:
|
||||
metadata = path.lstat()
|
||||
@@ -55,11 +59,33 @@ def atomic_write(path, data):
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def find_executable(name):
|
||||
found = shutil.which(name)
|
||||
if found or name == 'npm':
|
||||
return found
|
||||
# npm's global bin directory is often missing from PATH right after a Node.js setup on Windows,
|
||||
# so a CLI this setup just installed globally (such as mcporter) would not be found otherwise.
|
||||
npm = shutil.which('npm')
|
||||
if npm is None:
|
||||
return None
|
||||
try:
|
||||
prefix = subprocess.run([npm, 'prefix', '--global'], stdin=subprocess.DEVNULL, capture_output=True,
|
||||
text=True, timeout=60).stdout.strip()
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
return None
|
||||
if not prefix:
|
||||
return None
|
||||
return shutil.which(name, path=prefix if os.name == 'nt' else os.path.join(prefix, 'bin'))
|
||||
|
||||
|
||||
def run_command(arguments, summary=False, home=None):
|
||||
executable = shutil.which(arguments[0])
|
||||
executable = find_executable(arguments[0])
|
||||
if executable is None:
|
||||
raise ValueError(f'{arguments[0]} CLI is required to manage plugins.')
|
||||
environment = os.environ.copy()
|
||||
# npm 12 defaults allow-remote to none, so Claude's install of an npm plugin source (a registry tarball URL) fails
|
||||
# with EALLOWREMOTE. "root" is not enough there; "all" applies only to this child process, and a user value wins.
|
||||
environment.setdefault('npm_config_allow_remote', 'all')
|
||||
if home is not None:
|
||||
environment.update(HOME=str(home), USERPROFILE=str(home), CODEX_HOME=str(home / '.codex'), CLAUDE_CONFIG_DIR=str(home / '.claude'))
|
||||
result = subprocess.run([executable, *arguments[1:]], stdin=subprocess.DEVNULL,
|
||||
@@ -170,7 +196,7 @@ class Manager:
|
||||
raise ValueError('Invalid extension ownership ledger.')
|
||||
identities = set()
|
||||
for resource in self.state['resources']:
|
||||
if not isinstance(resource, dict) or resource.get('client') not in ('codex', 'claude', 'shared') or resource.get('kind') not in ('plugin', 'skill', 'qmd', 'cli', 'mcp'):
|
||||
if not isinstance(resource, dict) or resource.get('client') not in ('codex', 'claude', 'shared') or resource.get('kind') not in ('plugin', 'skill', 'qmd', 'cli', 'mcp', 'clone'):
|
||||
raise ValueError('Invalid extension ownership record.')
|
||||
if not isinstance(resource.get('name'), str) or not resource['name']:
|
||||
raise ValueError('Invalid extension ownership name.')
|
||||
@@ -185,7 +211,8 @@ class Manager:
|
||||
raise ValueError('Invalid owned plugin source.')
|
||||
elif resource['kind'] == 'skill':
|
||||
directory = resource.get('directory', '')
|
||||
if not re.fullmatch(r'\.agents/skills/[A-Za-z0-9_-]+', directory) or resource['client'] != 'codex':
|
||||
roots = {'codex': r'\.agents', 'claude': r'\.claude'}
|
||||
if resource['client'] not in roots or not re.fullmatch(roots[resource['client']] + r'/skills/[A-Za-z0-9_-]+', directory):
|
||||
raise ValueError('Invalid owned skill directory.')
|
||||
safe_path(self.home, directory)
|
||||
if not isinstance(resource.get('files'), dict):
|
||||
@@ -196,6 +223,13 @@ class Manager:
|
||||
if not relative.startswith(directory + '/') or not re.fullmatch(r'[a-f0-9]{64}', value):
|
||||
raise ValueError('Invalid owned skill file record.')
|
||||
safe_path(self.home, relative)
|
||||
for relative, value in resource.get('agents', {}).items():
|
||||
if resource['client'] != 'codex' or not re.fullmatch(r'\.codex/agents/[A-Za-z0-9_-]+\.toml', relative) or not re.fullmatch(r'[a-f0-9]{64}', value):
|
||||
raise ValueError('Invalid owned skill agent record.')
|
||||
elif resource['kind'] == 'clone':
|
||||
if resource['client'] != 'shared' or not re.fullmatch(r'\.my-ai-configuration/[A-Za-z0-9_-]+', resource.get('directory', '')):
|
||||
raise ValueError('Invalid owned clone record.')
|
||||
safe_path(self.home, resource['directory'])
|
||||
elif resource['kind'] == 'qmd' and (resource.get('package') != '@tobilu/qmd' or resource['client'] not in ('codex', 'shared')):
|
||||
raise ValueError('Invalid owned QMD record.')
|
||||
elif resource['kind'] == 'cli' and not re.fullmatch(r'[a-z0-9@/_.-]+', resource.get('package', '')):
|
||||
@@ -248,6 +282,16 @@ class Manager:
|
||||
else:
|
||||
run_command(arguments, self.summary, self.home)
|
||||
|
||||
def refresh_marketplace(self, client, name):
|
||||
# Windows briefly locks a fresh marketplace clone (antivirus, indexers, open sessions), so the CLI's rename fails with EPERM.
|
||||
for attempt in range(3):
|
||||
try:
|
||||
return self.command([client, 'plugin', 'marketplace', 'update', name])
|
||||
except ValueError as error:
|
||||
if attempt == 2 or not re.search(r'\b(EPERM|EBUSY|EACCES)\b|try again', str(error), re.I):
|
||||
raise
|
||||
time.sleep(5 * (attempt + 1))
|
||||
|
||||
def remove(self, record):
|
||||
if self.dry_run:
|
||||
if not self.summary:
|
||||
@@ -263,6 +307,14 @@ class Manager:
|
||||
self.command(arguments)
|
||||
self.cache[client].pop(selector, None)
|
||||
elif record['kind'] == 'skill':
|
||||
for relative, expected in list(record.get('agents', {}).items()):
|
||||
path = safe_path(self.home, relative)
|
||||
if path.exists() and (not path.is_file() or digest(path) != expected):
|
||||
print(f'WARN Preserving modified agent file: {relative}')
|
||||
continue
|
||||
path.unlink(missing_ok=True)
|
||||
del record['agents'][relative]
|
||||
self.save()
|
||||
empty_candidates = set()
|
||||
for relative, expected in list(record['files'].items()):
|
||||
path = safe_path(self.home, relative)
|
||||
@@ -292,6 +344,25 @@ class Manager:
|
||||
pass
|
||||
if record['files']:
|
||||
return
|
||||
elif record['kind'] == 'clone':
|
||||
directory = safe_path(self.home, record['directory'])
|
||||
if directory.exists():
|
||||
# Saved sessions, .env files, and local edits live in the clone; never delete them.
|
||||
try:
|
||||
status = run_command(['git', '-C', str(directory), 'status', '--porcelain', '--ignored', '--untracked-files=all'], True, self.home)
|
||||
except ValueError as error:
|
||||
print(f'WARN Preserving {record["directory"]}: cannot read its Git status ({str(error).splitlines()[0]}).')
|
||||
return
|
||||
local = [line for line in status.splitlines() if not line[3:].startswith('node_modules/')]
|
||||
if local:
|
||||
print(f'WARN Preserving {record["directory"]}: it holds local files ({len(local)}); delete it yourself if they are not needed.')
|
||||
return
|
||||
# Git marks pack files read-only, which Windows refuses to delete.
|
||||
def retry(_, path, __):
|
||||
os.chmod(path, stat.S_IWRITE)
|
||||
os.unlink(path)
|
||||
|
||||
shutil.rmtree(directory, **({'onexc': retry} if sys.version_info >= (3, 12) else {'onerror': retry}))
|
||||
elif record['kind'] == 'mcp':
|
||||
self.command(['mcporter', '--config', str(self.home / '.mcporter/mcporter.json'), 'config', 'remove', record['server']])
|
||||
else:
|
||||
@@ -304,7 +375,11 @@ class Manager:
|
||||
if entry['codex_method'] == 'cli':
|
||||
self.ensure_cli(client, entry)
|
||||
return
|
||||
skill = client == 'codex' and entry['codex_method'] != 'plugin'
|
||||
if entry['codex_method'] == 'clone':
|
||||
self.ensure_clone(client, entry)
|
||||
return
|
||||
# A Claude row without a plugin ('-') reuses the skill payload from codex_source.
|
||||
skill = entry['codex_method'] == 'skill' and (client == 'codex' or entry['claude_plugin'] == '-')
|
||||
kind = 'skill' if skill else 'plugin'
|
||||
record = next((r for r in self.state['resources'] if r['client'] == client and r['name'] == entry['name']), None)
|
||||
selector = entry[client + '_plugin']
|
||||
@@ -318,7 +393,7 @@ class Manager:
|
||||
print(f'DRYRUN ensure {client} {kind}: {entry["name"]}')
|
||||
return
|
||||
if skill:
|
||||
self.ensure_skill(entry, record)
|
||||
self.ensure_skill(client, entry, record)
|
||||
return
|
||||
if not re.fullmatch(r'[A-Za-z0-9_.-]+@[A-Za-z0-9_.-]+', selector):
|
||||
raise ValueError('Invalid plugin selector.')
|
||||
@@ -333,17 +408,20 @@ class Manager:
|
||||
if client == 'claude' and item.get('enabled') is False:
|
||||
self.command([client, 'plugin', 'enable', selector])
|
||||
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
|
||||
if item is not None and client == 'claude':
|
||||
self.command([client, 'plugin', 'marketplace', 'update', selector.rsplit('@', 1)[1]])
|
||||
self.refresh_marketplace(client, selector.rsplit('@', 1)[1])
|
||||
self.command([client, 'plugin', 'update', selector])
|
||||
if item.get('enabled') is False:
|
||||
self.command([client, 'plugin', 'enable', selector])
|
||||
if record is not None:
|
||||
self.cache.pop(client, None)
|
||||
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
|
||||
marketplace = entry[client + '_marketplace']
|
||||
if marketplace not in ('', '-', 'openai-curated-remote'):
|
||||
@@ -354,7 +432,7 @@ class Manager:
|
||||
else:
|
||||
self.command([client, 'plugin', 'marketplace', 'add', marketplace])
|
||||
if client == 'claude':
|
||||
self.command([client, 'plugin', 'marketplace', 'update', selector.rsplit('@', 1)[1]])
|
||||
self.refresh_marketplace(client, selector.rsplit('@', 1)[1])
|
||||
arguments = [client, 'plugin', 'install', selector, '--scope', 'user'] if client == 'claude' else [client, 'plugin', 'add', selector]
|
||||
self.command(arguments)
|
||||
resolved_version = None
|
||||
@@ -363,7 +441,8 @@ class Manager:
|
||||
resolved_version = self.installed(client).get(selector, {}).get('version')
|
||||
if record is None:
|
||||
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.save()
|
||||
self.cache[client][selector] = {'scope': 'user'}
|
||||
@@ -390,29 +469,68 @@ class Manager:
|
||||
self.state['resources'].append(dict(client='shared', name=entry['name'], kind='cli', package=package, clients=[client]))
|
||||
self.save()
|
||||
|
||||
def repair_caveman_windows_hooks(self):
|
||||
if self.dry_run or os.name != 'nt':
|
||||
def ensure_clone(self, client, entry):
|
||||
"""Keep a project repository (skills, agents, app) cloned under ~/.my-ai-configuration, shared by both clients."""
|
||||
source, folder = entry['codex_source'], entry['codex_skill']
|
||||
if not re.fullmatch(r'[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+', source) or not re.fullmatch(r'[A-Za-z0-9_-]+', folder):
|
||||
raise ValueError('Invalid clone source or folder.')
|
||||
directory = '.my-ai-configuration/' + folder
|
||||
target = safe_path(self.home, directory)
|
||||
record = next((r for r in self.state['resources'] if r['client'] == 'shared' and r['name'] == entry['name']), None)
|
||||
if record is None and target.exists():
|
||||
if not self.summary:
|
||||
print(f'PASS Preserving pre-existing folder: {directory}')
|
||||
return
|
||||
if not any(r['client'] == 'codex' and r['kind'] == 'plugin'
|
||||
and r['selector'] == 'caveman@thinkhome-caveman' for r in self.state['resources']):
|
||||
if self.dry_run:
|
||||
if not self.summary:
|
||||
print(f'DRYRUN ensure {client} clone: {entry["name"]}')
|
||||
return
|
||||
# ponytail: only the known 1.0.0 command; remove when upstream ships a portable launcher.
|
||||
path = safe_path(self.home, '.codex/plugins/cache/thinkhome-caveman/caveman/1.0.0/hooks/hooks.json')
|
||||
if not path.is_file():
|
||||
if record is not None and client not in record['clients']:
|
||||
record['clients'] = sorted(set(record['clients']) | {client})
|
||||
self.save()
|
||||
if not target.exists():
|
||||
self.command(['git', 'clone', '--depth', '1', f'https://github.com/{source}.git', str(target)])
|
||||
elif self.update and entry['name'] not in self.updated_packages:
|
||||
# Both clients share the folder; check and pull it once per run. A broken clone must not stop the other extensions.
|
||||
self.updated_packages.add(entry['name'])
|
||||
try:
|
||||
changed = run_command(['git', '-C', str(target), 'status', '--porcelain', '--untracked-files=no'], True, self.home)
|
||||
if changed.strip():
|
||||
print(f'WARN Not updating {directory}: tracked files were changed locally.')
|
||||
else:
|
||||
self.command(['git', '-C', str(target), 'pull', '--ff-only', '--quiet'])
|
||||
except ValueError as error:
|
||||
print(f'WARN Not updating {directory}: {str(error).splitlines()[0]}')
|
||||
if record is None:
|
||||
self.state['resources'].append(dict(client='shared', name=entry['name'], kind='clone', directory=directory, source=source, clients=[client]))
|
||||
self.save()
|
||||
|
||||
def ensure_ponytail_mode(self):
|
||||
# Same lookup as Ponytail's hooks/ponytail-config.js; PONYTAIL_DEFAULT_MODE still wins over this file.
|
||||
if os.environ.get('XDG_CONFIG_HOME'):
|
||||
directory = Path(os.environ['XDG_CONFIG_HOME'])
|
||||
elif os.name == 'nt':
|
||||
directory = Path(os.environ.get('APPDATA') or self.home / 'AppData/Roaming')
|
||||
else:
|
||||
directory = self.home / '.config'
|
||||
path = directory / 'ponytail/config.json'
|
||||
try:
|
||||
config = json.loads(path.read_text(encoding='utf-8-sig')) if path.is_file() else {}
|
||||
except ValueError:
|
||||
config = None
|
||||
if not isinstance(config, dict):
|
||||
print(f'WARN Preserving unreadable Ponytail configuration: {path}')
|
||||
return
|
||||
content = json.loads(path.read_text(encoding='utf-8'))
|
||||
changed = False
|
||||
for groups in content.get('hooks', {}).values():
|
||||
for group in groups:
|
||||
for hook in group.get('hooks', []):
|
||||
if hook.get('commandWindows') == 'node "%PLUGIN_ROOT%\\hooks\\caveman-hook.mjs"':
|
||||
hook['commandWindows'] = ('node -e "import(require(\'node:url\').pathToFileURL('
|
||||
'require(\'node:path\').join(process.env.PLUGIN_ROOT,'
|
||||
'\'hooks\',\'caveman-hook.mjs\')).href)"')
|
||||
changed = True
|
||||
if changed:
|
||||
atomic_write(path, (json.dumps(content, indent=2) + '\n').encode('utf-8'))
|
||||
print('Repaired Caveman Windows hook commands; review the changed hooks in Codex /hooks.')
|
||||
if config.get('defaultMode') == PONYTAIL_MODE:
|
||||
return
|
||||
if self.dry_run:
|
||||
if not self.summary:
|
||||
print(f'DRYRUN set Ponytail default mode to {PONYTAIL_MODE}')
|
||||
return
|
||||
if linked(path) or linked(path.parent):
|
||||
raise ValueError('Ponytail configuration path contains a link.')
|
||||
config['defaultMode'] = PONYTAIL_MODE
|
||||
atomic_write(path, (json.dumps(config, indent=2) + '\n').encode('utf-8'))
|
||||
|
||||
def ensure_mcporter(self, entry, clients):
|
||||
server, url = entry['mcporter_name'], entry['mcporter_url']
|
||||
@@ -446,16 +564,16 @@ class Manager:
|
||||
record.update(server=server, url=url)
|
||||
self.save()
|
||||
|
||||
def ensure_skill(self, entry, record):
|
||||
def ensure_skill(self, client, entry, record):
|
||||
skill = entry['codex_skill']
|
||||
if not re.fullmatch(r'[A-Za-z0-9_-]+', skill):
|
||||
raise ValueError('Invalid skill name.')
|
||||
directory = '.agents/skills/' + skill
|
||||
directory = ('.agents/skills/' if client == 'codex' else '.claude/skills/') + skill
|
||||
target = self.home / directory
|
||||
alternate = self.home / '.codex' / 'skills' / skill
|
||||
alternate = self.home / '.codex' / 'skills' / skill if client == 'codex' else target
|
||||
if record is None and (target.exists() or target.is_symlink() or alternate.exists() or alternate.is_symlink()):
|
||||
if not self.summary:
|
||||
print(f'PASS Preserving pre-existing Codex skill: {skill}')
|
||||
print(f'PASS Preserving pre-existing {client} skill: {skill}')
|
||||
return
|
||||
target = safe_path(self.home, directory)
|
||||
if record and record['directory'] != directory:
|
||||
@@ -469,7 +587,7 @@ class Manager:
|
||||
_, files = fetched[:2]
|
||||
revision = fetched[2] if len(fetched) > 2 else None
|
||||
if record is None:
|
||||
record = dict(client='codex', name=entry['name'], kind='skill', directory=directory, source=entry['codex_source'], files={}, complete=False)
|
||||
record = dict(client=client, name=entry['name'], kind='skill', directory=directory, source=entry['codex_source'], files={}, complete=False)
|
||||
self.state['resources'].append(record)
|
||||
self.save()
|
||||
record['complete'] = False
|
||||
@@ -497,20 +615,47 @@ class Manager:
|
||||
path.unlink(missing_ok=True)
|
||||
del record['files'][relative]
|
||||
self.save()
|
||||
if client == 'codex':
|
||||
self.sync_skill_agents(record, files)
|
||||
record['complete'] = True
|
||||
self.save()
|
||||
|
||||
def sync_skill_agents(self, record, files):
|
||||
"""Codex loads custom agents only from ~/.codex/agents, so register the skill's agents/*.toml there."""
|
||||
agents = {'.codex/agents/' + name.split('/', 1)[1]: content for name, (content, _) in files.items()
|
||||
if re.fullmatch(r'agents/[A-Za-z0-9_-]+\.toml', name)}
|
||||
owned = record.setdefault('agents', {})
|
||||
for relative, content in agents.items():
|
||||
path = safe_path(self.home, relative)
|
||||
if path.exists() and (relative not in owned or not path.is_file() or digest(path) != owned[relative]):
|
||||
print(f'WARN Preserving modified or foreign agent file: {relative}')
|
||||
continue
|
||||
atomic_write(path, content)
|
||||
owned[relative] = hashlib.sha256(content).hexdigest()
|
||||
self.save()
|
||||
for relative in [name for name in owned if name not in agents]:
|
||||
path = safe_path(self.home, relative)
|
||||
if path.exists() and (not path.is_file() or digest(path) != owned[relative]):
|
||||
print(f'WARN Preserving modified stale agent file: {relative}')
|
||||
continue
|
||||
path.unlink(missing_ok=True)
|
||||
del owned[relative]
|
||||
self.save()
|
||||
|
||||
def sync(self, entries, clients, selected, action='sync'):
|
||||
self.normalize_global_records()
|
||||
desired = {entry['name']: entry for entry in entries if entry['name'] in selected}
|
||||
use_mcporter = 'MCPorter' in desired
|
||||
mcporter_entries = {name: entry for name, entry in desired.items() if use_mcporter and entry.get('mcporter_name') and entry.get('mcporter_url') not in ('', '-')}
|
||||
direct_entries = {name: entry for name, entry in desired.items() if name not in mcporter_entries}
|
||||
# codex_method '-' marks a Claude-only extension; owned Codex installs of it are removed.
|
||||
claude_only = {name for name, entry in direct_entries.items() if entry['codex_method'] == '-'}
|
||||
for record in sorted(self.state['resources'], key=lambda record: record['kind'] != 'mcp'):
|
||||
if record['client'] != 'shared' and record['client'] not in clients:
|
||||
continue
|
||||
selected_entries = mcporter_entries if record['kind'] == 'mcp' else direct_entries
|
||||
if (action == 'sync' and record['name'] not in selected_entries) or (action == 'remove' and record['name'] in selected):
|
||||
if ((action == 'sync' and record['name'] not in selected_entries) or (action == 'remove' and record['name'] in selected)
|
||||
or (action != 'remove' and record['client'] == 'codex' and record['name'] in claude_only)):
|
||||
if record['client'] == 'shared':
|
||||
remaining = [client for client in record.get('clients', ['claude', 'codex']) if client not in clients]
|
||||
if remaining:
|
||||
@@ -521,14 +666,56 @@ class Manager:
|
||||
if action != 'remove':
|
||||
for client in clients:
|
||||
for entry in direct_entries.values():
|
||||
if client != 'codex' or entry['name'] not in claude_only:
|
||||
self.ensure(client, entry)
|
||||
if client == 'codex' and entry.get('codex_plugin') == 'caveman@thinkhome-caveman':
|
||||
self.repair_caveman_windows_hooks()
|
||||
if 'Ponytail' in direct_entries:
|
||||
self.ensure_ponytail_mode()
|
||||
for entry in mcporter_entries.values():
|
||||
self.ensure_mcporter(entry, clients)
|
||||
print('EXTENSIONS: reconciliation complete' + (' (dry run)' if self.dry_run else ''))
|
||||
|
||||
|
||||
def process_alive(pid):
|
||||
if os.name == 'nt':
|
||||
import ctypes
|
||||
kernel32 = ctypes.windll.kernel32
|
||||
handle = kernel32.OpenProcess(0x1000, False, pid) # PROCESS_QUERY_LIMITED_INFORMATION
|
||||
if not handle:
|
||||
return False
|
||||
code = ctypes.c_ulong()
|
||||
try:
|
||||
return bool(kernel32.GetExitCodeProcess(handle, ctypes.byref(code))) and code.value == 259 # STILL_ACTIVE
|
||||
finally:
|
||||
kernel32.CloseHandle(handle)
|
||||
try:
|
||||
os.kill(pid, 0)
|
||||
except ProcessLookupError:
|
||||
return False
|
||||
except PermissionError:
|
||||
return True
|
||||
return True
|
||||
|
||||
|
||||
def acquire_lock(lock):
|
||||
"""Create the lock with this PID; replace a lock whose process is gone (closed terminal, kill)."""
|
||||
for _ in range(2):
|
||||
try:
|
||||
descriptor = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
|
||||
except FileExistsError:
|
||||
try:
|
||||
pid = int(lock.read_text(encoding='utf-8').strip() or 0)
|
||||
except (OSError, ValueError):
|
||||
pid = 0
|
||||
if pid and process_alive(pid):
|
||||
raise ValueError(f'Another install or update is running (PID {pid}). If it is not, delete {lock}.')
|
||||
lock.unlink(missing_ok=True)
|
||||
continue
|
||||
with os.fdopen(descriptor, 'w', encoding='utf-8') as stream:
|
||||
stream.write(str(os.getpid()))
|
||||
return
|
||||
raise ValueError(f'Cannot acquire {lock}.')
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('action', choices=('sync', 'install', 'remove'))
|
||||
@@ -555,9 +742,8 @@ def main():
|
||||
return
|
||||
lock = safe_path(manager.home, '.my-ai-configuration/extensions.lock')
|
||||
lock.parent.mkdir(parents=True, exist_ok=True)
|
||||
descriptor = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
|
||||
acquire_lock(lock)
|
||||
try:
|
||||
os.close(descriptor)
|
||||
manager = Manager(args.home, args.dry_run, args.update, args.summary)
|
||||
manager.sync(entries, clients, selected, args.action)
|
||||
finally:
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
. (Join-Path $PSScriptRoot '../../shared/hooks/scripts/Resolve-Python.ps1')
|
||||
function Get-ManagedManifestPath {
|
||||
param([Parameter(Mandatory=$true)][string]$Destination)
|
||||
return (Join-Path $Destination '.ai-config-manifest.tsv')
|
||||
@@ -117,7 +118,7 @@ function Invoke-InstallOptions {
|
||||
[System.IO.File]::WriteAllBytes($managedPath, $Managed)
|
||||
$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 }
|
||||
return [System.IO.File]::ReadAllText($outputPath, (New-Object System.Text.UTF8Encoding($false)))
|
||||
} finally {
|
||||
@@ -220,6 +221,8 @@ function Invoke-ManagedSync {
|
||||
|
||||
# Plan every change before writing anything, so the journal can describe the whole run.
|
||||
$plan = New-Object System.Collections.ArrayList
|
||||
# Get-ChildItem returns long paths; expand an 8.3 short $Source (such as JULIAN~1) so the prefix cut below lines up.
|
||||
$Source = (Get-Item -LiteralPath $Source).FullName
|
||||
Get-ChildItem $Source -File -Recurse | ForEach-Object {
|
||||
$relative = $_.FullName.Substring($Source.Length).TrimStart([char[]]@('\','/')).Replace('\','/')
|
||||
if ((Split-Path $Destination -Leaf) -eq '.codex' -and $relative.StartsWith('skills/')) { return }
|
||||
@@ -265,14 +268,23 @@ function Invoke-ManagedSync {
|
||||
if (-not (Test-Path -LiteralPath $target)) { continue }
|
||||
# A stale file changed locally is backed up but kept; only an unmodified one is removed.
|
||||
$action = if ((Get-Sha256Hash $target) -eq $oldManifest[$relative]) { 'REMOVE' } else { 'KEEP' }
|
||||
$null = $plan.Add([pscustomobject]@{ Relative = $relative; Target = $target; Action = $action; Bytes = $null; Hash = $null })
|
||||
$bytes = $null
|
||||
$hash = $null
|
||||
if ($action -eq 'KEEP' -and $relative -in @('settings.json', 'config.toml')) {
|
||||
# Client plugin commands edit these after install; drop only the entries this setup owns.
|
||||
$stripped = Invoke-InstallOptions -Arguments @('strip', '--current', $target) -ErrorMessage "Could not remove managed entries from $relative."
|
||||
$action = if ($stripped) { 'STRIP' } else { 'REMOVE' }
|
||||
$bytes = (New-Object System.Text.UTF8Encoding($false)).GetBytes($stripped)
|
||||
$hash = Get-Sha256HashOfBytes $bytes
|
||||
}
|
||||
$null = $plan.Add([pscustomobject]@{ Relative = $relative; Target = $target; Action = $action; Bytes = $bytes; Hash = $hash })
|
||||
}
|
||||
|
||||
if (-not $DryRun) {
|
||||
$journalEntries = @(foreach ($item in $plan) {
|
||||
switch ($item.Action) {
|
||||
'CREATE' { [ordered]@{ path = $item.Relative; action = 'create'; sha256 = $item.Hash } }
|
||||
'UPDATE' { [ordered]@{ path = $item.Relative; action = 'update'; backup = "$Stamp/$($item.Relative)"; sha256 = $item.Hash } }
|
||||
{ $_ -in @('UPDATE', 'STRIP') } { [ordered]@{ path = $item.Relative; action = 'update'; backup = "$Stamp/$($item.Relative)"; sha256 = $item.Hash } }
|
||||
'REMOVE' { [ordered]@{ path = $item.Relative; action = 'remove'; backup = "$Stamp/$($item.Relative)" } }
|
||||
}
|
||||
})
|
||||
|
||||
+38
-14
@@ -1,4 +1,7 @@
|
||||
#!/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
|
||||
# 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
|
||||
@@ -116,6 +119,16 @@ acquire_managed_lock() {
|
||||
return 1
|
||||
}
|
||||
|
||||
# run_install_options <arguments...>: print install-options.py output byte-exact.
|
||||
# Python writes a file, because a captured stdout gets CRLF on Windows and differs from PowerShell's bytes.
|
||||
run_install_options() {
|
||||
local output status=0
|
||||
output=$(mktemp) || return 1
|
||||
{ run_python "$(dirname -- "${BASH_SOURCE[0]}")/install-options.py" "$@" --output "$output" && cat -- "$output"; } || status=$?
|
||||
rm -f -- "$output"
|
||||
return "$status"
|
||||
}
|
||||
|
||||
# sync_managed_destination: same arguments as run_managed_sync; holds the destination lock unless dry-running.
|
||||
sync_managed_destination() {
|
||||
[ "$7" != true ] || { run_managed_sync "$@"; return; }
|
||||
@@ -146,7 +159,7 @@ run_managed_sync() {
|
||||
local entries entry entry_action entry_path entry_backup entry_hash entry_target
|
||||
local -a journal_lines
|
||||
# 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
|
||||
journal = json.load(open(sys.argv[1], encoding="utf-8-sig"))
|
||||
lines = [str(journal["stamp"])]
|
||||
@@ -211,12 +224,12 @@ sys.stdout.buffer.write(("\n".join(lines) + "\n").encode("utf-8"))
|
||||
content=${content%$'\034'}
|
||||
needs_sub=false
|
||||
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_install_options filter --path "$source_file" --flashbang "$flashbang_enabled" --statusline "$statusline_enabled" --semantic-retrieval "$semantic_retrieval_enabled" && printf '\034') || return
|
||||
content=${content%$'\034'}
|
||||
needs_sub=true
|
||||
fi
|
||||
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_install_options filter-instructions --path "$source_file" --destination "$destination" --semantic-retrieval "$semantic_retrieval_enabled" && printf '\034') || return
|
||||
content=${content%$'\034'}
|
||||
needs_sub=true
|
||||
fi
|
||||
@@ -233,13 +246,14 @@ sys.stdout.buffer.write(("\n".join(lines) + "\n").encode("utf-8"))
|
||||
else
|
||||
new_hash=$(sha256_of_file "$source_file")
|
||||
fi
|
||||
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
|
||||
needs_sub=true
|
||||
new_hash=$(sha256_of_string "$content")
|
||||
fi
|
||||
if [ "$relative" = settings.json ] && [ -f "$target" ]; then
|
||||
content=$(printf '%s' "$content" | python3 "$(dirname -- "${BASH_SOURCE[0]}")/install-options.py" merge-json --current "$target") || return
|
||||
if [[ "$relative" = config.toml || "$relative" = settings.json ]] && [ -f "$target" ]; then
|
||||
local managed_file merge_action=merge-json
|
||||
[ "$relative" = settings.json ] || merge_action=merge-toml
|
||||
managed_file=$(mktemp) || return 1
|
||||
printf '%s' "$content" > "$managed_file" || { rm -f -- "$managed_file"; return 1; }
|
||||
content=$(run_install_options "$merge_action" --current "$target" --managed "$managed_file" --statusline "$statusline_enabled" && printf '\034') || { rm -f -- "$managed_file"; return 1; }
|
||||
rm -f -- "$managed_file"
|
||||
content=${content%$'\034'}
|
||||
needs_sub=true
|
||||
new_hash=$(sha256_of_string "$content")
|
||||
fi
|
||||
@@ -262,10 +276,20 @@ sys.stdout.buffer.write(("\n".join(lines) + "\n").encode("utf-8"))
|
||||
target=$(managed_target "$destination" "$relative") || return 1
|
||||
[ -f "$target" ] || continue
|
||||
# A stale file changed locally is backed up but kept; only an unmodified one is removed.
|
||||
local stripped='' stripped_hash=''
|
||||
action=KEEP
|
||||
[ "$(sha256_of_file "$target")" != "${old_manifest[$relative]}" ] || action=REMOVE
|
||||
plan_relative+=("$relative"); plan_target+=("$target"); plan_action+=("$action"); plan_hash+=('')
|
||||
plan_source+=(''); plan_sub+=(false); plan_content+=('')
|
||||
if [ "$(sha256_of_file "$target")" = "${old_manifest[$relative]}" ]; then
|
||||
action=REMOVE
|
||||
elif [[ "$relative" = settings.json || "$relative" = config.toml ]]; then
|
||||
# Client plugin commands edit these after install; drop only the entries this setup owns.
|
||||
stripped=$(run_install_options strip --current "$target" && printf '\034') || return 1
|
||||
stripped=${stripped%$'\034'}
|
||||
action=STRIP
|
||||
[ -n "$stripped" ] || action=REMOVE
|
||||
stripped_hash=$(sha256_of_string "$stripped")
|
||||
fi
|
||||
plan_relative+=("$relative"); plan_target+=("$target"); plan_action+=("$action"); plan_hash+=("$stripped_hash")
|
||||
plan_source+=(''); plan_sub+=(true); plan_content+=("$stripped")
|
||||
done
|
||||
|
||||
local index entry journal_content first_entry=true
|
||||
@@ -276,7 +300,7 @@ sys.stdout.buffer.write(("\n".join(lines) + "\n").encode("utf-8"))
|
||||
for index in "${!plan_action[@]}"; do
|
||||
case "${plan_action[$index]}" in
|
||||
CREATE) entry=$(printf '{"path": %s, "action": "create", "sha256": "%s"}' "$(json_string "${plan_relative[$index]}")" "${plan_hash[$index]}") ;;
|
||||
UPDATE) entry=$(printf '{"path": %s, "action": "update", "backup": %s, "sha256": "%s"}' "$(json_string "${plan_relative[$index]}")" "$(json_string "$stamp/${plan_relative[$index]}")" "${plan_hash[$index]}") ;;
|
||||
UPDATE|STRIP) entry=$(printf '{"path": %s, "action": "update", "backup": %s, "sha256": "%s"}' "$(json_string "${plan_relative[$index]}")" "$(json_string "$stamp/${plan_relative[$index]}")" "${plan_hash[$index]}") ;;
|
||||
REMOVE) entry=$(printf '{"path": %s, "action": "remove", "backup": %s}' "$(json_string "${plan_relative[$index]}")" "$(json_string "$stamp/${plan_relative[$index]}")") ;;
|
||||
*) continue ;;
|
||||
esac
|
||||
|
||||
+21
-2
@@ -1,3 +1,4 @@
|
||||
. (Join-Path $PSScriptRoot '../../shared/hooks/scripts/Resolve-Python.ps1')
|
||||
function Invoke-PluginCommand {
|
||||
param(
|
||||
[Parameter(Mandatory=$true)][string]$Command,
|
||||
@@ -65,6 +66,18 @@ function Get-InstalledPlugins {
|
||||
}
|
||||
}
|
||||
|
||||
function Test-CliCommand {
|
||||
param([Parameter(Mandatory=$true)][string]$Name)
|
||||
if (Get-Command $Name -ErrorAction SilentlyContinue) { return $true }
|
||||
# npm's global bin directory is often missing from PATH on Windows; match managed-extensions.py find_executable.
|
||||
if (-not (Get-Command npm -ErrorAction SilentlyContinue)) { return $false }
|
||||
$prefix = @(& npm prefix --global 2>$null | ForEach-Object { "$_".Trim() } | Where-Object { $_ }) | Select-Object -Last 1
|
||||
if (-not $prefix) { return $false }
|
||||
$directory = if ([Environment]::OSVersion.Platform -eq [PlatformID]::Win32NT) { $prefix } else { Join-Path $prefix 'bin' }
|
||||
# Count matches: the extensionless Unix match is '', which [bool] would treat as false.
|
||||
return @(@('', '.cmd', '.exe', '.ps1') | Where-Object { Test-Path -LiteralPath (Join-Path $directory ($Name + $_)) -PathType Leaf }).Count -gt 0
|
||||
}
|
||||
|
||||
function Test-InstalledMCPServer {
|
||||
param([string]$HomePath, [string]$Name, [string]$Url)
|
||||
$path = Join-Path $HomePath '.mcporter/mcporter.json'
|
||||
@@ -109,6 +122,8 @@ function Select-ConfiguredPlugins {
|
||||
[switch]$DryRun
|
||||
)
|
||||
$entries = @(Get-ConfiguredPluginEntries -RepositoryRoot $RepositoryRoot)
|
||||
# codex_method '-' marks a Claude-only extension.
|
||||
if ($Client -eq 'Codex') { $entries = @($entries | Where-Object { $_.codex_method -ne '-' }) }
|
||||
$toggleable = @($entries)
|
||||
$fixed = @($entries | Where-Object { $toggleable -notcontains $_ })
|
||||
if ($toggleable.Count -eq 0 -or ($DryRun -and $Mode -eq 'Install')) { return @{ Selected = $entries; Deselected = @() } }
|
||||
@@ -118,15 +133,19 @@ function Select-ConfiguredPlugins {
|
||||
if ($Mode -eq 'Update') { foreach ($referenceClient in $referenceClients) { $installed[$referenceClient] = @(Get-InstalledPlugins -Client $referenceClient -HomePath $HomePath) } }
|
||||
$checked = @($toggleable | ForEach-Object {
|
||||
if ($Mode -eq 'Install') { $true; return }
|
||||
if ($_.codex_method -eq 'cli') { return $null -ne (Get-Command $_.codex_source -ErrorAction SilentlyContinue) }
|
||||
if ($_.codex_method -eq 'cli') { return Test-CliCommand -Name $_.codex_source }
|
||||
if ($_.codex_method -eq 'clone') { return Test-Path -LiteralPath (Join-Path $HomePath ('.my-ai-configuration/' + $_.codex_skill)) }
|
||||
$entry = $_
|
||||
$found = if ($entry.mcporter_name -and $entry.mcporter_url) {
|
||||
Test-InstalledMCPServer -HomePath $HomePath -Name $entry.mcporter_name -Url $entry.mcporter_url
|
||||
} else { $false }
|
||||
foreach ($referenceClient in $referenceClients) {
|
||||
if ($referenceClient -eq 'Codex' -and $entry.codex_method -eq '-') { continue }
|
||||
$selector = if ($referenceClient -eq 'Claude') { $entry.claude_plugin } else { $entry.codex_plugin }
|
||||
if ($referenceClient -eq 'Codex' -and $entry.codex_method -ne 'plugin') {
|
||||
$found = $found -or (Test-Path -LiteralPath (Join-Path $HomePath ('.agents/skills/' + $entry.codex_skill))) -or (Test-Path -LiteralPath (Join-Path $HomePath ('.codex/skills/' + $entry.codex_skill)))
|
||||
} elseif ($referenceClient -eq 'Claude' -and $entry.claude_plugin -eq '-' -and $entry.codex_method -eq 'skill') {
|
||||
$found = $found -or (Test-Path -LiteralPath (Join-Path $HomePath ('.claude/skills/' + $entry.codex_skill)))
|
||||
} else {
|
||||
$idField = if ($referenceClient -eq 'Claude') { 'id' } else { 'pluginId' }
|
||||
$found = $found -or [bool](@($installed[$referenceClient] | Where-Object { $_.$idField -eq $selector }).Count)
|
||||
@@ -161,7 +180,7 @@ function Invoke-ManagedExtensions {
|
||||
if ($Update) { $arguments += '--update' }
|
||||
if ($Summary) { $arguments += '--summary' }
|
||||
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.' }
|
||||
}
|
||||
|
||||
|
||||
+31
-4
@@ -1,4 +1,7 @@
|
||||
#!/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
|
||||
|
||||
plugin_installed() {
|
||||
@@ -6,7 +9,7 @@ plugin_installed() {
|
||||
local inventory
|
||||
command -v "$client" >/dev/null 2>&1 || return 1
|
||||
inventory=$("$client" plugin list --json) || return 2
|
||||
printf '%s' "$inventory" | python3 -c '
|
||||
printf '%s' "$inventory" | run_python -c '
|
||||
import json, sys
|
||||
try:
|
||||
client, plugin = sys.argv[1:]
|
||||
@@ -22,6 +25,21 @@ except (ValueError, KeyError, TypeError) as error:
|
||||
' "$client" "$plugin"
|
||||
}
|
||||
|
||||
cli_installed() {
|
||||
local name=$1 prefix
|
||||
command -v "$name" >/dev/null 2>&1 && return 0
|
||||
# npm's global bin directory is often missing from PATH; match managed-extensions.py find_executable.
|
||||
command -v npm >/dev/null 2>&1 || return 1
|
||||
prefix=$(npm prefix --global 2>/dev/null | tr -d '\r' | tail -n 1)
|
||||
[ -n "$prefix" ] || return 1
|
||||
case "$(uname -s 2>/dev/null)" in
|
||||
MINGW*|MSYS*|CYGWIN*)
|
||||
prefix=$(cygpath -u "$prefix" 2>/dev/null || printf '%s' "$prefix")
|
||||
[ -f "$prefix/$name" ] || [ -f "$prefix/$name.cmd" ] || [ -f "$prefix/$name.exe" ] ;;
|
||||
*) [ -x "$prefix/bin/$name" ] ;;
|
||||
esac
|
||||
}
|
||||
|
||||
run_plugin_command() {
|
||||
local dry_run=$1
|
||||
shift
|
||||
@@ -70,7 +88,7 @@ mcporter_server_installed() {
|
||||
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
|
||||
[ -f "$path" ] || return 1
|
||||
python3 -c '
|
||||
run_python -c '
|
||||
import json, sys
|
||||
try:
|
||||
with open(sys.argv[1], encoding="utf-8-sig") as stream:
|
||||
@@ -128,6 +146,8 @@ select_configured_plugins() {
|
||||
|
||||
local name all_names=() toggle_names=() fixed_names=()
|
||||
while IFS= read -r name; do
|
||||
# codex_method '-' marks a Claude-only extension.
|
||||
if [ "$client" = codex ] && [ "$(plugin_field "$root" "$name" codex_method)" = - ]; then continue; fi
|
||||
all_names+=("$name")
|
||||
if plugin_toggleable "$root" "$name" "$client"; then toggle_names+=("$name"); else fixed_names+=("$name"); fi
|
||||
done < <(get_plugin_names "$root")
|
||||
@@ -148,7 +168,11 @@ select_configured_plugins() {
|
||||
continue
|
||||
fi
|
||||
if [ "$(plugin_field "$root" "$name" codex_method)" = cli ]; then
|
||||
if command -v "$(plugin_field "$root" "$name" codex_source)" >/dev/null 2>&1; then checked+=(true); else checked+=(false); fi
|
||||
if cli_installed "$(plugin_field "$root" "$name" codex_source)"; then checked+=(true); else checked+=(false); fi
|
||||
continue
|
||||
fi
|
||||
if [ "$(plugin_field "$root" "$name" codex_method)" = clone ]; then
|
||||
if [ -d "${home_path:-$HOME}/.my-ai-configuration/$(plugin_field "$root" "$name" codex_skill)" ]; then checked+=(true); else checked+=(false); fi
|
||||
continue
|
||||
fi
|
||||
found=false
|
||||
@@ -160,11 +184,14 @@ select_configured_plugins() {
|
||||
else status=$?; [ "$status" -eq 1 ] || return "$status"; fi
|
||||
fi
|
||||
for reference_client in "${reference_clients[@]}"; do
|
||||
if [ "$reference_client" = codex ] && [ "$(plugin_field "$root" "$name" codex_method)" = - ]; then continue; fi
|
||||
if [ "$reference_client" = claude ]; then selector=$(plugin_field "$root" "$name" claude_plugin); else selector=$(plugin_field "$root" "$name" codex_plugin); fi
|
||||
if [ "$reference_client" = codex ] && [ "$(plugin_field "$root" "$name" codex_method)" != plugin ]; then
|
||||
local skill_name
|
||||
skill_name=$(plugin_field "$root" "$name" codex_skill)
|
||||
{ [ -d "$HOME/.agents/skills/$skill_name" ] || [ -d "$HOME/.codex/skills/$skill_name" ]; } && found=true
|
||||
elif [ "$reference_client" = claude ] && [ "$selector" = - ] && [ "$(plugin_field "$root" "$name" codex_method)" = skill ]; then
|
||||
[ -d "$HOME/.claude/skills/$(plugin_field "$root" "$name" codex_skill)" ] && found=true
|
||||
elif plugin_installed "$reference_client" "$selector"; then found=true
|
||||
else
|
||||
status=$?
|
||||
@@ -193,7 +220,7 @@ managed_extensions() {
|
||||
local -n extension_names_ref=$selected_name
|
||||
arguments+=(--selected "${extension_names_ref[@]}")
|
||||
fi
|
||||
python3 "${arguments[@]}"
|
||||
run_python "${arguments[@]}"
|
||||
}
|
||||
|
||||
sync_configured_plugins() {
|
||||
|
||||
+3
-2
@@ -1,9 +1,10 @@
|
||||
. (Join-Path $PSScriptRoot '../../shared/hooks/scripts/Resolve-Python.ps1')
|
||||
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)
|
||||
$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 ($Summary) { $arguments += '--summary' }
|
||||
& python @arguments
|
||||
Invoke-Python @arguments
|
||||
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)
|
||||
$arguments = @((Join-Path $PSScriptRoot 'qmd.py'), 'benchmark', '--root', $RepositoryRoot, '--home', $HomePath)
|
||||
if ($Summary) { $arguments += '--summary' }
|
||||
& python @arguments | Write-Host
|
||||
Invoke-Python @arguments | Write-Host
|
||||
if ($LASTEXITCODE -eq 0) { return $true }
|
||||
if ($LASTEXITCODE -eq 2) { return $false }
|
||||
throw 'QMD benchmark failed.'
|
||||
|
||||
+129
-22
@@ -10,6 +10,7 @@ import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
PACKAGE = '@tobilu/qmd'
|
||||
VERSION = '2.8.3'
|
||||
@@ -20,7 +21,7 @@ WINDOWS = os.name == 'nt'
|
||||
|
||||
def run(arguments, env=None, timeout=1800, check=True):
|
||||
result = subprocess.run(arguments, env=env, capture_output=True, text=True, encoding='utf-8', errors='replace',
|
||||
timeout=timeout, shell=WINDOWS and arguments[0] in ('npm', 'qmd'))
|
||||
timeout=timeout, shell=WINDOWS and arguments[0] == 'npm')
|
||||
if check and result.returncode != 0:
|
||||
raise ValueError(f'{" ".join(arguments[:3])} failed: {(result.stderr or result.stdout).strip()[-300:]}')
|
||||
return result.stdout
|
||||
@@ -59,6 +60,14 @@ def node_version_ok(text):
|
||||
return bool(match) and int(match.group(1)) >= 22
|
||||
|
||||
|
||||
def model_files(text):
|
||||
"""Cache file names node-llama-cpp gives the hf: model URIs in qmd-lib.mjs: hf_<owner>_<file> plus <file>.etag."""
|
||||
names = set()
|
||||
for owner, file in re.findall(r"'hf:([^/']+)/[^/']+/([^/']+\.gguf)'", text):
|
||||
names |= {f'hf_{owner}_{file}', f'{file}.etag'}
|
||||
return names
|
||||
|
||||
|
||||
def digest(path):
|
||||
return hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
|
||||
@@ -94,16 +103,51 @@ class Setup:
|
||||
def node(self, script, *arguments, env=None, timeout=1800):
|
||||
return self.run(['node', str(self.scripts / script), *arguments], env=env, timeout=timeout)
|
||||
|
||||
def qmd_cli(self, *arguments, timeout=1800):
|
||||
# Run the CLI through node from the global package, as qmd-lib.mjs does, so it also works
|
||||
# when npm's global bin directory is not on PATH (common on Windows right after install).
|
||||
package = os.environ.get('QMD_PACKAGE_DIR') or str(Path(self.run(['npm', 'root', '--global']).strip()) / '@tobilu' / 'qmd')
|
||||
return self.run(['node', str(Path(package) / 'dist' / 'cli' / 'qmd.js'), *arguments], timeout=timeout)
|
||||
|
||||
def package_installed(self):
|
||||
return self.package_version() is not None
|
||||
|
||||
def package_version(self):
|
||||
"""Installed global QMD version, '' when npm lists it without one, or None when it is absent."""
|
||||
# npm list exits non-zero on tree problems (ELSPROBLEMS) but still prints valid JSON.
|
||||
output = self.run(['npm', 'list', '--global', '--depth=0', '--json'], check=False)
|
||||
try:
|
||||
listing = json.loads(output)
|
||||
except json.JSONDecodeError:
|
||||
raise ValueError('npm list did not return JSON.')
|
||||
# Before the first global install the global prefix directory does not exist; npm then
|
||||
# reports ENOENT without a dependency list, which means nothing is installed yet.
|
||||
error = listing.get('error') if isinstance(listing, dict) else None
|
||||
if isinstance(error, dict) and error.get('code') == 'ENOENT' and 'dependencies' not in listing:
|
||||
return None
|
||||
if not isinstance(listing, dict) or not isinstance(listing.get('dependencies'), dict):
|
||||
raise ValueError('npm list did not report the global packages.')
|
||||
return PACKAGE in listing['dependencies']
|
||||
entry = listing['dependencies'].get(PACKAGE)
|
||||
if entry is None:
|
||||
return None
|
||||
return str(entry.get('version') or '') if isinstance(entry, dict) else ''
|
||||
|
||||
def stop_daemon(self):
|
||||
"""Stop the setup's QMD daemon and wait until it releases the scripts, models, and package."""
|
||||
daemon = self.scripts / 'daemon.json'
|
||||
try:
|
||||
pid = json.loads(daemon.read_text(encoding='utf-8')).get('pid') if daemon.is_file() else None
|
||||
except (OSError, ValueError, AttributeError):
|
||||
pid = None
|
||||
try:
|
||||
if self.scripts.joinpath('qmd-search.mjs').exists():
|
||||
self.node('qmd-search.mjs', '--stop', timeout=60)
|
||||
except (ValueError, OSError, subprocess.SubprocessError):
|
||||
pass
|
||||
if isinstance(pid, int) and pid > 0:
|
||||
deadline = time.monotonic() + 10
|
||||
while process_alive(pid) and time.monotonic() < deadline:
|
||||
time.sleep(0.2)
|
||||
|
||||
def require_node(self):
|
||||
if not node_version_ok(self.run(['node', '--version'])):
|
||||
@@ -160,13 +204,21 @@ class Setup:
|
||||
"""Steps shared by Yes and Auto: package, scripts, models block, model download."""
|
||||
self.require_node()
|
||||
self.migrate(state)
|
||||
if not self.package_installed():
|
||||
# A running daemon keeps old code and models loaded and locks the model files on Windows.
|
||||
self.stop_daemon()
|
||||
version = self.package_version()
|
||||
if version is None or (state['owned_package'] and version != VERSION):
|
||||
self.run(['npm', 'install', '--global', f'{PACKAGE}@{VERSION}'])
|
||||
state['owned_package'] = True
|
||||
elif version != VERSION:
|
||||
# A foreign installation is never changed; the runtime scripts rely on internals of the tested version.
|
||||
print(f'QMD local search: the installed {PACKAGE} {version or "(unknown version)"} is not the tested {VERSION}; '
|
||||
f'search may fall back to the slower CLI. Run: npm install --global {PACKAGE}@{VERSION}', file=sys.stderr)
|
||||
self.install_scripts(state)
|
||||
atomic_json(self.state_path, state)
|
||||
if not state['models_block']:
|
||||
# Rewrite the setup-owned block on every run so changed default models reach existing installs.
|
||||
output = self.node('qmd-config.mjs', 'set-models')
|
||||
if not state['models_block']:
|
||||
try:
|
||||
previous = json.loads(output.strip().splitlines()[-1])['previous']
|
||||
except (IndexError, KeyError, TypeError, json.JSONDecodeError):
|
||||
@@ -175,10 +227,32 @@ class Setup:
|
||||
state['models_block'] = True
|
||||
atomic_json(self.state_path, state)
|
||||
before = {p.name for p in self.models.iterdir()} if self.models.is_dir() else set()
|
||||
self.run(['qmd', 'pull'], timeout=3600)
|
||||
self.qmd_cli('pull', timeout=3600)
|
||||
after = {p.name for p in self.models.iterdir()} if self.models.is_dir() else set()
|
||||
state['owned_models'] = sorted(set(state['owned_models']) | (after - before))
|
||||
atomic_json(self.state_path, state)
|
||||
self.prune_models(state)
|
||||
|
||||
def prune_models(self, state):
|
||||
"""Delete setup-downloaded model files the current models no longer use; foreign files stay."""
|
||||
current = model_files((self.root / 'shared' / 'qmd' / 'qmd-lib.mjs').read_text(encoding='utf-8'))
|
||||
if not current: # an unparsable model list must never delete every model
|
||||
return
|
||||
kept = []
|
||||
for name in state['owned_models']:
|
||||
if name in current:
|
||||
kept.append(name)
|
||||
continue
|
||||
path = self.models / name
|
||||
if name != Path(name).name or not path.is_file() or path.is_symlink():
|
||||
continue # already gone, or not a plain file the setup can safely delete
|
||||
try:
|
||||
path.unlink()
|
||||
except OSError as error: # a running daemon may still hold it; the next update retries
|
||||
print(f'QMD local search: could not delete unused model {name}: {error}', file=sys.stderr)
|
||||
kept.append(name)
|
||||
state['owned_models'] = sorted(kept)
|
||||
atomic_json(self.state_path, state)
|
||||
|
||||
def detect_gpu(self):
|
||||
try:
|
||||
@@ -194,7 +268,7 @@ class Setup:
|
||||
def enable(self, clients):
|
||||
state = self.load()
|
||||
if self.dry_run:
|
||||
self.say('DRYRUN enable QMD local search: Qwen3-Embedding-0.6B, Qwen3-Reranker-0.6B, QMD query expansion 1.7B')
|
||||
self.say('DRYRUN enable QMD local search: Qwen3-Embedding-4B, Qwen3-Reranker-4B, QMD query expansion 1.7B')
|
||||
return
|
||||
self.install(state)
|
||||
if state['device'] is None:
|
||||
@@ -204,26 +278,13 @@ class Setup:
|
||||
self.say(f'QMD local search enabled on {state["device"].upper()}.')
|
||||
|
||||
def remove_all(self, state):
|
||||
daemon = self.scripts / 'daemon.json'
|
||||
try:
|
||||
pid = json.loads(daemon.read_text(encoding='utf-8')).get('pid') if daemon.is_file() else None
|
||||
except (OSError, ValueError, AttributeError):
|
||||
pid = None
|
||||
try:
|
||||
if self.scripts.joinpath('qmd-search.mjs').exists():
|
||||
self.node('qmd-search.mjs', '--stop', timeout=60)
|
||||
except (ValueError, OSError, subprocess.SubprocessError):
|
||||
pass
|
||||
if isinstance(pid, int) and pid > 0:
|
||||
deadline = time.monotonic() + 10 # the daemon must release the model files and the package
|
||||
while process_alive(pid) and time.monotonic() < deadline:
|
||||
time.sleep(0.2)
|
||||
self.stop_daemon()
|
||||
collections = self.scripts / 'collections.json'
|
||||
names = json.loads(collections.read_text(encoding='utf-8')) if collections.exists() else []
|
||||
for name in names:
|
||||
if re.fullmatch(r'repo-[0-9a-f]{12}', name):
|
||||
try:
|
||||
self.run(['qmd', 'collection', 'remove', name])
|
||||
self.qmd_cli('collection', 'remove', name)
|
||||
except (ValueError, subprocess.SubprocessError):
|
||||
pass
|
||||
if state['models_block'] and self.scripts.joinpath('qmd-config.mjs').exists():
|
||||
@@ -314,9 +375,51 @@ class Setup:
|
||||
return True
|
||||
|
||||
|
||||
def doctor_checks(setup):
|
||||
"""Read-only QMD checks for the doctor command, as (PASS|WARN|FAIL, message) pairs; none when QMD is not set up."""
|
||||
if not setup.state_path.exists():
|
||||
return []
|
||||
state = setup.load()
|
||||
checks = []
|
||||
scripts = {name: setup.scripts / name for name in state['files']}
|
||||
missing = sorted(name for name, path in scripts.items() if not path.is_file())
|
||||
changed = sorted(name for name, path in scripts.items() if path.is_file() and digest(path) != state['files'][name])
|
||||
checks.append(('FAIL', f'QMD runtime scripts are missing: {", ".join(missing)}') if missing
|
||||
else ('WARN', f'QMD runtime scripts were modified: {", ".join(changed)}') if changed
|
||||
else ('PASS', 'QMD runtime scripts match the setup'))
|
||||
try:
|
||||
version = setup.package_version()
|
||||
checks.append(('FAIL', f'{PACKAGE} is not installed') if version is None
|
||||
else ('PASS', f'{PACKAGE} {version} installed') if version == VERSION
|
||||
else ('WARN', f'{PACKAGE} {version or "(unknown version)"} is not the tested {VERSION}; search may fall back to the slower CLI'))
|
||||
except (ValueError, OSError, subprocess.SubprocessError) as error:
|
||||
checks.append(('WARN', f'could not read the {PACKAGE} version: {error}'))
|
||||
library = setup.scripts / 'qmd-lib.mjs'
|
||||
wanted = sorted(n for n in model_files(library.read_text(encoding='utf-8') if library.is_file() else '') if n.endswith('.gguf'))
|
||||
absent = [n for n in wanted if not (setup.models / n).is_file()]
|
||||
checks.append(('WARN', f'QMD model files are not downloaded yet: {", ".join(absent)}') if absent
|
||||
else ('PASS', f'QMD model files present ({len(wanted)})'))
|
||||
info = None
|
||||
try:
|
||||
info = json.loads((setup.scripts / 'daemon.json').read_text(encoding='utf-8'))
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
if isinstance(info, dict) and info.get('port') and info.get('token'):
|
||||
request = urllib.request.Request(f'http://127.0.0.1:{int(info["port"])}/health', headers={'x-qmd-token': str(info['token'])})
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=2) as response:
|
||||
running = json.loads(response.read().decode('utf-8')).get('service') == 'ai-config-qmd'
|
||||
except (OSError, ValueError):
|
||||
running = False
|
||||
checks.append(('PASS', 'QMD daemon answers') if running else ('WARN', 'QMD daemon.json is stale; the next search starts a new daemon'))
|
||||
else:
|
||||
checks.append(('PASS', 'QMD daemon is not running; the next search starts it'))
|
||||
return checks
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('action', choices=('sync', 'benchmark'))
|
||||
parser.add_argument('action', choices=('sync', 'benchmark', 'doctor'))
|
||||
parser.add_argument('--root', required=True, type=Path)
|
||||
parser.add_argument('--home', required=True, type=Path)
|
||||
parser.add_argument('--client', choices=('codex', 'claude', 'both'))
|
||||
@@ -328,6 +431,10 @@ def main():
|
||||
setup = Setup(args.home.resolve(), args.root.resolve(), run, args.dry_run, args.summary)
|
||||
if args.action == 'benchmark':
|
||||
raise SystemExit(0 if setup.benchmark() else 2)
|
||||
if args.action == 'doctor':
|
||||
for status, message in doctor_checks(setup):
|
||||
print(f'{status} {message}')
|
||||
return
|
||||
if args.client is None or args.enabled is None:
|
||||
parser.error('sync requires --client and --enabled')
|
||||
clients = ['codex', 'claude'] if args.client == 'both' else [args.client]
|
||||
|
||||
+5
-2
@@ -1,4 +1,7 @@
|
||||
#!/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() {
|
||||
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)
|
||||
[ "$update" != true ] || arguments+=(--update)
|
||||
[ "$summary" != true ] || arguments+=(--summary)
|
||||
python3 "${arguments[@]}"
|
||||
run_python "${arguments[@]}"
|
||||
}
|
||||
|
||||
test_qmd_device() {
|
||||
@@ -14,7 +17,7 @@ test_qmd_device() {
|
||||
local arguments=("$root/scripts/lib/qmd.py" benchmark --root "$root" --home "$home_path")
|
||||
[ "$summary" != true ] || arguments+=(--summary)
|
||||
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
|
||||
return 2
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
. (Join-Path $PSScriptRoot '../../shared/hooks/scripts/Resolve-Python.ps1')
|
||||
function Read-UpdateSelection {
|
||||
param([string]$HomePath, [string]$RepositoryRoot, [switch]$AllowLegacy)
|
||||
$arguments = @((Join-Path $PSScriptRoot 'selection-state.py'), 'read', '--home', $HomePath, '--manifest', (Join-Path $RepositoryRoot 'adapters/plugins.tsv'))
|
||||
if ($AllowLegacy) { $arguments += '--allow-legacy' }
|
||||
$output = & python @arguments
|
||||
$output = Invoke-Python @arguments
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Could not load the saved selection.' }
|
||||
return ($output | Out-String | ConvertFrom-Json)
|
||||
}
|
||||
@@ -14,6 +15,6 @@ function Save-UpdateSelection {
|
||||
$arguments += @($Plugins.Selected | ForEach-Object { $_.name })
|
||||
$arguments += '--deselected'
|
||||
$arguments += @($Plugins.Deselected | ForEach-Object { $_.name })
|
||||
& python @arguments
|
||||
Invoke-Python @arguments
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Could not save the selection.' }
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
#!/usr/bin/env bash
|
||||
# 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() {
|
||||
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=()
|
||||
deselected_plugins=()
|
||||
while IFS=$'\t' read -r key value; do
|
||||
@@ -21,7 +24,7 @@ read_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}" \
|
||||
--selected "${selected_plugins[@]}" --deselected "${deselected_plugins[@]}"
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Doctor check: installed upstream skills still offer what plugin-workflow's UI section names."""
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
|
||||
# Keep in sync with the Impeccable and Apple Design section of shared/skills/plugin-workflow/SKILL.md.
|
||||
CONTRACTS = {
|
||||
'impeccable': ('Impeccable', ['critique', 'audit', 'harden', 'adapt', 'clarify', 'layout', 'typeset', 'polish',
|
||||
'shape', 'craft-floor', 'Operate', 'Persuade']),
|
||||
'apple-design': ('Apple Design', ['Always load', 'Lens 1', 'Lens 5', 'Critical', 'Design improvement mode',
|
||||
'cross-platform']),
|
||||
}
|
||||
|
||||
|
||||
def installed_skill_files(home, skill):
|
||||
candidates = [home / '.claude/skills' / skill / 'SKILL.md', home / '.agents/skills' / skill / 'SKILL.md',
|
||||
home / '.codex/skills' / skill / 'SKILL.md']
|
||||
cache = home / '.claude/plugins/cache' / skill / skill
|
||||
if cache.is_dir():
|
||||
versions = sorted((p for p in cache.iterdir() if (p / 'skills' / skill / 'SKILL.md').is_file()),
|
||||
key=lambda p: tuple(int(part) if part.isdigit() else 0 for part in p.name.split('.')))
|
||||
if versions:
|
||||
candidates.append(versions[-1] / 'skills' / skill / 'SKILL.md')
|
||||
return [path for path in candidates if path.is_file()]
|
||||
|
||||
|
||||
def check(home):
|
||||
results = []
|
||||
for skill, (name, tokens) in CONTRACTS.items():
|
||||
for path in installed_skill_files(home, skill):
|
||||
text = path.read_text(encoding='utf-8', errors='replace')
|
||||
missing = [token for token in tokens if token not in text]
|
||||
if missing:
|
||||
results.append(('WARN', f'{name} at {path.parent} no longer mentions {", ".join(missing)}; '
|
||||
'review the UI section of plugin-workflow'))
|
||||
else:
|
||||
results.append(('PASS', f'{name} at {path.parent} matches the plugin-workflow coordination'))
|
||||
return results
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--home', required=True)
|
||||
for status, message in check(Path(parser.parse_args().home)):
|
||||
print(f'{status} {message}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -1,10 +1,19 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[ValidateSet('Codex', 'Claude')][string]$Client,
|
||||
[string]$Key,
|
||||
[Parameter(Position = 2)][string]$FilePath,
|
||||
[Parameter(Position = 3, ValueFromRemainingArguments = $true)][string[]]$ArgumentList
|
||||
)
|
||||
# Usage: with-credential.ps1 -Client <Codex|Claude> -Key <NAME> -FilePath <command> [child arguments...]
|
||||
# No param() block: PowerShell would bind abbreviated child flags such as -k or -d to -Key or -Debug.
|
||||
# Only the exact names below are read; everything after the command goes to the child unchanged.
|
||||
# Own variable names: scripts that dot-source this file keep their own $Client and $Key.
|
||||
$credentialClient = $null
|
||||
$credentialKey = $null
|
||||
$childPath = $null
|
||||
$childArguments = @()
|
||||
for ($index = 0; $index -lt $args.Count; $index++) {
|
||||
$token = [string]$args[$index]
|
||||
if ($null -ne $childPath) { $childArguments = @($args[$index..($args.Count - 1)] | ForEach-Object { [string]$_ }); break }
|
||||
if ($token -eq '-Client' -and $index + 1 -lt $args.Count) { $credentialClient = [string]$args[++$index] }
|
||||
elseif ($token -eq '-Key' -and $index + 1 -lt $args.Count) { $credentialKey = [string]$args[++$index] }
|
||||
elseif ($token -eq '-FilePath' -and $index + 1 -lt $args.Count) { $childPath = [string]$args[++$index] }
|
||||
else { $childPath = $token }
|
||||
}
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
@@ -106,20 +115,24 @@ function Remove-ManagedCredential {
|
||||
function Invoke-WithManagedCredential {
|
||||
param([ValidateSet('Codex', 'Claude')][string]$Client, [string]$Key, [string]$FilePath, [string[]]$ArgumentList)
|
||||
Assert-CredentialKey $Key
|
||||
if (-not (Test-Path -LiteralPath $FilePath -PathType Leaf)) { throw 'Child command was not found.' }
|
||||
# Accept a full path or a command name on PATH (gh, curl.exe).
|
||||
$command = Get-Command -Name $FilePath -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
|
||||
if (-not $command) { throw 'Child command was not found.' }
|
||||
$FilePath = $command.Source
|
||||
$prior = [Environment]::GetEnvironmentVariable($Key, 'Process')
|
||||
$value = Get-ManagedCredential $Client $Key
|
||||
try {
|
||||
[Environment]::SetEnvironmentVariable($Key, $value, 'Process')
|
||||
# Output goes straight to the caller; returning a value here would capture the child's stdout.
|
||||
& $FilePath @ArgumentList
|
||||
return $LASTEXITCODE
|
||||
} finally {
|
||||
[Environment]::SetEnvironmentVariable($Key, $prior, 'Process')
|
||||
$value = $null
|
||||
}
|
||||
}
|
||||
|
||||
if ($FilePath) {
|
||||
if (-not $Client -or -not $Key) { throw 'Client and key are required.' }
|
||||
exit (Invoke-WithManagedCredential $Client $Key $FilePath $ArgumentList)
|
||||
if ($childPath) {
|
||||
if (-not $credentialClient -or -not $credentialKey) { throw 'Client and key are required.' }
|
||||
Invoke-WithManagedCredential $credentialClient $credentialKey $childPath $childArguments
|
||||
exit $LASTEXITCODE
|
||||
}
|
||||
@@ -7,7 +7,7 @@ shift 2
|
||||
[ $# -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 "$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)
|
||||
[ -n "$powershell_command" ] || { printf 'PowerShell is required to read the Windows credential store.\n' >&2; exit 1; }
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
@@ -11,10 +12,10 @@ SCRIPTS = ROOT / 'shared/hooks/scripts'
|
||||
GUARDS = SCRIPTS / 'agent-guards.py'
|
||||
|
||||
|
||||
def guard(mode, event, cwd=None):
|
||||
def guard(mode, event, cwd=None, env=None):
|
||||
payload = event if isinstance(event, str) else json.dumps(event)
|
||||
result = subprocess.run([sys.executable, str(GUARDS), mode], cwd=cwd, input=payload, capture_output=True,
|
||||
encoding='utf-8', timeout=20)
|
||||
encoding='utf-8', timeout=20, env=env)
|
||||
assert result.returncode == 0, result.stderr
|
||||
return result.stdout
|
||||
|
||||
@@ -86,11 +87,80 @@ class CorrectionPromptTests(unittest.TestCase):
|
||||
self.assertEqual(guard('prompt', event), '')
|
||||
|
||||
|
||||
def fake_home(directory, qmd=True):
|
||||
home = Path(directory)
|
||||
if qmd:
|
||||
script = home / '.my-ai-configuration/qmd/qmd-search.mjs'
|
||||
script.parent.mkdir(parents=True)
|
||||
script.write_text('')
|
||||
return dict(os.environ, HOME=str(home), USERPROFILE=str(home))
|
||||
|
||||
|
||||
class SearchReminderTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
directory = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(directory.cleanup)
|
||||
self.home = Path(directory.name)
|
||||
self.env = fake_home(directory.name)
|
||||
|
||||
def search(self, session='s1', tool='Grep', command=None, env=None):
|
||||
tool_input = {'command': command} if command is not None else {'pattern': 'x'}
|
||||
return guard('search', {'session_id': session, 'tool_name': tool, 'tool_input': tool_input}, env=env or self.env)
|
||||
|
||||
def test_reminds_once_per_session(self):
|
||||
output = json.loads(self.search())['hookSpecificOutput']
|
||||
self.assertEqual(output['hookEventName'], 'PreToolUse')
|
||||
self.assertIn('semantic-search', output['additionalContext'])
|
||||
self.assertEqual(self.search(tool='Glob'), '')
|
||||
self.assertIn('additionalContext', self.search(session='s2', tool='Bash', command='rg Tile'))
|
||||
self.assertNotIn('s1', ' '.join(p.name for p in (self.home / '.my-ai-configuration/state/search-reminder').iterdir()))
|
||||
|
||||
def test_reminds_again_after_repeated_searches_without_qmd(self):
|
||||
self.assertIn('additionalContext', self.search())
|
||||
outputs = [self.search(tool='Grep') for _ in range(10)]
|
||||
self.assertEqual([''] * (10 - 1), outputs[:-1])
|
||||
self.assertIn('additionalContext', outputs[-1])
|
||||
|
||||
def test_qmd_use_resets_the_repeat_counter(self):
|
||||
self.assertIn('additionalContext', self.search())
|
||||
for _ in range(10 - 1):
|
||||
self.search(tool='Grep')
|
||||
query = 'node "$HOME/.my-ai-configuration/qmd/qmd-search.mjs" --query "Where are tests?" --top-k 5'
|
||||
self.assertEqual(self.search(tool='Bash', command=query), '')
|
||||
self.assertEqual(self.search(tool='Grep'), '')
|
||||
|
||||
def test_detects_shell_searches(self):
|
||||
searches = ('rg Tile', 'git grep -n x', 'find . -name "*.csproj"', 'grep -r xunit src',
|
||||
'Get-ChildItem -Recurse -Filter *.csproj', 'Get-Content a.cs | Select-String Test', 'cd src && fd test')
|
||||
for index, command in enumerate(searches):
|
||||
with self.subTest(command=command):
|
||||
self.assertIn('additionalContext', self.search(f'shell{index}', 'PowerShell', command))
|
||||
for index, command in enumerate(('git status', 'npm run find-tests', 'dotnet test', 'ls src')):
|
||||
with self.subTest(command=command):
|
||||
self.assertEqual(self.search(f'other{index}', 'Bash', command), '')
|
||||
|
||||
def test_qmd_use_suppresses_reminder(self):
|
||||
query = 'node "$HOME/.my-ai-configuration/qmd/qmd-search.mjs" --query "Where are tests?" --top-k 5'
|
||||
self.assertEqual(self.search(tool='Bash', command=query), '')
|
||||
self.assertEqual(self.search(tool='Grep'), '')
|
||||
|
||||
def test_silent_without_qmd(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
self.assertEqual(self.search(env=fake_home(directory, qmd=False)), '')
|
||||
|
||||
def test_fails_open_on_malformed_events(self):
|
||||
for event in ('', 'not json', '[]', {'session_id': 3, 'tool_name': 'Grep', 'tool_input': {}},
|
||||
{'session_id': 's', 'tool_name': 'Grep'}, {'session_id': 's', 'tool_name': 'Bash', 'tool_input': {'command': 7}}):
|
||||
self.assertEqual(guard('search', event, env=self.env), '')
|
||||
|
||||
|
||||
class EntryPointTests(unittest.TestCase):
|
||||
def test_shell_entry_points(self):
|
||||
shells = (('powershell', shutil.which('pwsh') or shutil.which('powershell'), 0), ('bash', shutil.which('bash'), 1))
|
||||
names = ((('Show-CorrectionPrompt.ps1', 'show-correction-prompt.sh'), {'prompt': 'Nein, anders'}, 'additionalContext'),
|
||||
(('Check-CompletionEvidence.ps1', 'check-completion-evidence.sh'), None, 'decision'))
|
||||
(('Check-CompletionEvidence.ps1', 'check-completion-evidence.sh'), None, 'decision'),
|
||||
(('Show-SearchReminder.ps1', 'show-search-reminder.sh'),
|
||||
{'session_id': 'entry', 'tool_name': 'Grep', 'tool_input': {'pattern': 'x'}}, 'additionalContext'))
|
||||
for shell, executable, index in shells:
|
||||
if not executable or (shell == 'bash' and sys.platform == 'win32'):
|
||||
continue
|
||||
@@ -98,12 +168,14 @@ class EntryPointTests(unittest.TestCase):
|
||||
workspace = Path(directory)
|
||||
git(workspace, 'init', '--quiet')
|
||||
(workspace / 'app.py').write_text('x = 1\n')
|
||||
env = fake_home(directory)
|
||||
for scripts, event, expected in names:
|
||||
event = event or {'cwd': str(workspace), 'last_assistant_message': 'All done.'}
|
||||
script = str(SCRIPTS / scripts[index])
|
||||
command = ([executable, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', script]
|
||||
if shell == 'powershell' else [executable, script])
|
||||
result = subprocess.run(command, input=json.dumps(event), capture_output=True, encoding='utf-8', timeout=30)
|
||||
result = subprocess.run(command, input=json.dumps(event), capture_output=True, encoding='utf-8', timeout=30,
|
||||
env=env)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(result.stderr, '')
|
||||
self.assertIn(expected, json.loads(result.stdout) | json.loads(result.stdout).get('hookSpecificOutput', {}))
|
||||
|
||||
@@ -43,6 +43,15 @@ $actualFiles = @(Get-ChildItem $baselineGenerated -File -Recurse | ForEach-Objec
|
||||
if (Compare-Object $expectedFiles $actualFiles) { throw 'generated/ is incomplete after two parallel builds.' }
|
||||
if (@(Get-ChildItem $baseline -Force | Where-Object Name -like 'generated.*').Count) { throw 'Parallel builds left a build directory, retired tree, or lock behind.' }
|
||||
|
||||
# A Codex CLI that rejects every config proves the schema check runs by default and is skipped on request.
|
||||
function codex { $global:LASTEXITCODE = 1; 'unsupported setting' }
|
||||
try {
|
||||
& (Join-Path $baseline 'scripts/commands/build.ps1') -Summary -SkipCodexSchema 3>&1 | Out-Null
|
||||
$schemaChecked = $false
|
||||
try { & (Join-Path $baseline 'scripts/commands/build.ps1') -Summary 2>&1 | Out-Null } catch { $schemaChecked = $_.Exception.Message -match 'Codex schema validation failed' }
|
||||
if (-not $schemaChecked) { throw 'The build must run the Codex schema check unless it is skipped.' }
|
||||
} finally { Remove-Item function:codex -ErrorAction SilentlyContinue }
|
||||
|
||||
Test-BuildFails 'invalid Claude settings.json' {
|
||||
param($copy)
|
||||
Add-Content (Join-Path $copy 'adapters/claude/config/settings.json') '} this is not json {'
|
||||
@@ -61,6 +70,13 @@ Test-BuildFails 'unknown Claude tool name in capability manifest' {
|
||||
Set-Content $manifest $lines
|
||||
}
|
||||
|
||||
Test-BuildFails 'missing preloaded skill in capability manifest' {
|
||||
param($copy)
|
||||
$manifest = Join-Path $copy 'adapters/claude/capabilities.tsv'
|
||||
$lines = Get-Content $manifest | ForEach-Object { if ($_ -match '^architect\t') { $_ + ',no-such-skill' } else { $_ } }
|
||||
Set-Content $manifest $lines
|
||||
}
|
||||
|
||||
Test-BuildFails 'duplicate plugin name' {
|
||||
param($copy)
|
||||
$manifest = Join-Path $copy 'adapters/plugins.tsv'
|
||||
|
||||
@@ -45,6 +45,17 @@ wait "$second_build" || { printf 'Parallel build 2 failed:\n%s\n' "$(cat "$work/
|
||||
[ "$(cd "$baseline/generated" && find . -type f | sort)" = "$expected_files" ] || { printf 'generated/ is incomplete after two parallel builds.\n' >&2; exit 1; }
|
||||
[ -z "$(find "$baseline" -maxdepth 1 -name 'generated.*' -print -quit)" ] || { printf 'Parallel builds left a build directory, retired tree, or lock behind.\n' >&2; exit 1; }
|
||||
|
||||
# A Codex CLI that rejects every config proves the schema check runs by default and is skipped on request.
|
||||
mkdir -p "$work/fake-codex"
|
||||
printf '#!/usr/bin/env bash\nexit 1\n' > "$work/fake-codex/codex"
|
||||
chmod +x "$work/fake-codex/codex"
|
||||
PATH="$work/fake-codex:$PATH" bash "$baseline/scripts/commands/build.sh" --summary --skip-codex-schema >/dev/null 2>&1 \
|
||||
|| { printf 'The build must skip the Codex schema check on request.\n' >&2; exit 1; }
|
||||
if PATH="$work/fake-codex:$PATH" bash "$baseline/scripts/commands/build.sh" --summary >/dev/null 2>&1; then
|
||||
printf 'The build must run the Codex schema check unless it is skipped.\n' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
mutate_invalid_json() {
|
||||
printf '} this is not json {' >> "$1/adapters/claude/config/settings.json"
|
||||
}
|
||||
@@ -60,6 +71,11 @@ mutate_invalid_tool_name() {
|
||||
}
|
||||
test_build_fails 'unknown Claude tool name in capability manifest' mutate_invalid_tool_name
|
||||
|
||||
mutate_missing_preloaded_skill() {
|
||||
sed -i 's/^\(architect\t.*\)$/\1,no-such-skill/' "$1/adapters/claude/capabilities.tsv"
|
||||
}
|
||||
test_build_fails 'missing preloaded skill in capability manifest' mutate_missing_preloaded_skill
|
||||
|
||||
mutate_duplicate_plugin() {
|
||||
local manifest="$1/adapters/plugins.tsv"
|
||||
sed -n '2p' "$manifest" >> "$manifest"
|
||||
|
||||
@@ -1,11 +1,34 @@
|
||||
[CmdletBinding()]
|
||||
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'
|
||||
$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') {
|
||||
throw 'Python capability detection must not read $LASTEXITCODE after a pipeline.'
|
||||
$resolved = & $hostPath -NoProfile -ExecutionPolicy Bypass -Command ". '$root/shared/hooks/scripts/Resolve-Python.ps1'; (Get-PythonCommand).Display"
|
||||
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,63 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SCRIPTS = ROOT / 'shared/hooks/scripts'
|
||||
SKILL = '---\nname: caveman\ndescription: Terse style.\n---\n\n# caveman\n\nRespond terse like smart caveman.\n'
|
||||
|
||||
|
||||
def wrappers():
|
||||
found = []
|
||||
for name in ('pwsh', 'powershell'):
|
||||
executable = shutil.which(name)
|
||||
if executable:
|
||||
found.append((name, [executable, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', str(SCRIPTS / 'Show-CavemanMode.ps1')]))
|
||||
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:
|
||||
found.append(('bash', [bash, str(SCRIPTS / 'show-caveman-mode.sh')]))
|
||||
return found
|
||||
|
||||
|
||||
class CavemanHookTests(unittest.TestCase):
|
||||
def run_hook(self, command, home, mode=None):
|
||||
environment = dict(os.environ, HOME=str(home), USERPROFILE=str(home))
|
||||
environment.pop('CAVEMAN_DEFAULT_MODE', None)
|
||||
if mode:
|
||||
environment['CAVEMAN_DEFAULT_MODE'] = mode
|
||||
return subprocess.run(command, capture_output=True, encoding='utf-8', timeout=60, env=environment)
|
||||
|
||||
def test_prints_installed_skill_without_frontmatter_and_respects_off(self):
|
||||
available = wrappers()
|
||||
if not available:
|
||||
self.skipTest('No supported shell is available.')
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
home = Path(directory)
|
||||
for name, command in available:
|
||||
with self.subTest(shell=name, case='missing skill'):
|
||||
result = self.run_hook(command, home)
|
||||
self.assertEqual((0, ''), (result.returncode, result.stdout))
|
||||
skill = home / '.agents/skills/caveman/SKILL.md'
|
||||
skill.parent.mkdir(parents=True)
|
||||
skill.write_text(SKILL, encoding='utf-8')
|
||||
for name, command in available:
|
||||
with self.subTest(shell=name, case='installed'):
|
||||
result = self.run_hook(command, home)
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
self.assertIn('CAVEMAN MODE ACTIVE (mode: caveman)', result.stdout)
|
||||
self.assertIn('Respond terse like smart caveman.', result.stdout)
|
||||
self.assertNotIn('description: Terse style.', result.stdout)
|
||||
with self.subTest(shell=name, case='off'):
|
||||
result = self.run_hook(command, home, 'off')
|
||||
self.assertEqual((0, ''), (result.returncode, result.stdout))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,205 @@
|
||||
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', shell=None):
|
||||
payload = json.dumps({'hook_event_name': 'PreToolUse', 'tool_name': tool, 'tool_input': {'command': command}})
|
||||
extra = ['--shell', shell] if shell else []
|
||||
return subprocess.run([sys.executable, str(SAFETY), '--hook', *extra], 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_commands_hidden_in_control_flow_and_wrapper_options(self):
|
||||
for command in ('if [ -d build ]; then rm -rf build; fi', 'for d in a b; do rm -rf "$d"; done',
|
||||
'while true; do git reset --hard; done', '(rm -rf x)', '{ git reset --hard; }', '! rm -rf x',
|
||||
'find . -print0 | xargs -0 rm -rf', 'sudo -E rm -rf /x', 'env -i git reset --hard',
|
||||
'timeout 30 rm -rf x', 'nice -n 5 rm -rf x', 'rm -rf ${dir}', 'echo ${#arr[@]}; rm -rf x',
|
||||
"sudo -u bob bash -c 'rm -rf x'"):
|
||||
with self.subTest(command=command):
|
||||
self.assertBlocked(command)
|
||||
for command in ('Get-ChildItem bin -Recurse | ForEach-Object { Remove-Item $_ -Recurse -Force }',
|
||||
'gci bin | % { ri $_ -Recurse }', 'foreach ($d in $dirs) { Remove-Item $d -Recurse }'):
|
||||
with self.subTest(command=command):
|
||||
self.assertBlocked(command, 'PowerShell')
|
||||
|
||||
def test_blocks_commands_after_comments_escapes_and_line_continuations(self):
|
||||
for command in ("echo hi # don't touch\nrm -rf build", 'echo "\\""; git reset --hard', "echo 'a\\'; rm -rf x",
|
||||
'rm \\\n -rf build', 'git reset \\\n --hard'):
|
||||
with self.subTest(command=command):
|
||||
self.assertBlocked(command)
|
||||
self.assertBlocked('Remove-Item build `\n -Recurse -Force', 'PowerShell')
|
||||
|
||||
def test_blocks_git_and_find_forms_that_discard_work(self):
|
||||
for command in ('git checkout -- .', 'git checkout -- src/app.ts', 'git checkout HEAD -- a.txt', 'git checkout .',
|
||||
'git restore .', 'git restore --worktree src', 'git push --force', 'git push -f origin main',
|
||||
'git push --force-with-lease', 'git push origin +main', 'git stash clear',
|
||||
'find . -name "*.tmp" -delete'):
|
||||
with self.subTest(command=command):
|
||||
self.assertBlocked(command)
|
||||
for command in ('git checkout main', 'git checkout -b feat/x', 'git restore --staged file.txt', 'git push',
|
||||
'git push origin main', 'git stash list', 'find . -name "*.tmp"'):
|
||||
with self.subTest(command=command):
|
||||
self.assertAllowed(command)
|
||||
|
||||
def test_heredoc_bodies_are_text_not_commands(self):
|
||||
for command in ("cat > c.sh <<'EOF'\nrm -rf \"$tmp\"\nEOF", 'git commit -F - <<EOF\nfix: avoid git reset --hard\nEOF',
|
||||
'cat <<-END\n\trm -rf x\n\tEND'):
|
||||
with self.subTest(command=command):
|
||||
self.assertAllowed(command)
|
||||
self.assertBlocked('cat > a.txt <<EOF\nhello\nEOF\nrm -rf build')
|
||||
self.assertBlocked('cat <<EOF; rm -rf build\nbody\nEOF')
|
||||
|
||||
def test_allows_comments_and_hashes_that_are_not_commands(self):
|
||||
for command in ('ls # rm -rf x', 'git commit -m "fix #12; rm -rf is bad"', 'echo a#b', 'echo "\\"rm -rf x\\""'):
|
||||
with self.subTest(command=command):
|
||||
self.assertAllowed(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_shell_override_checks_codex_windows_powershell_text_reported_as_bash(self):
|
||||
for command in ('rm -r build', 'Remove-Item build -Recurse', 'ri build -recurse', 'rm -rf build'):
|
||||
with self.subTest(command=command):
|
||||
self.assertEqual(2, hook(command, 'Bash', 'unknown').returncode)
|
||||
self.assertEqual(0, hook('rm -r build', 'Bash').returncode, 'Claude Git Bash keeps the POSIX meaning of rm -r')
|
||||
self.assertEqual(0, hook('Get-ChildItem build', 'Bash', 'unknown').returncode)
|
||||
|
||||
def test_unknown_shell_checks_both_dialects(self):
|
||||
self.assertBlocked('rm -r build', 'shell')
|
||||
self.assertBlocked('rm -rf build', 'shell')
|
||||
|
||||
def test_allowed_shell_search_gets_the_search_reminder_in_the_same_process(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
home = Path(directory)
|
||||
(home / '.my-ai-configuration/qmd').mkdir(parents=True)
|
||||
(home / '.my-ai-configuration/qmd/qmd-search.mjs').write_text('')
|
||||
env = dict(os.environ, HOME=str(home), USERPROFILE=str(home))
|
||||
|
||||
def run(command, session='s1'):
|
||||
payload = json.dumps({'session_id': session, 'tool_name': 'Bash', 'tool_input': {'command': command}})
|
||||
return subprocess.run([sys.executable, str(SAFETY), '--hook'], input=payload, capture_output=True,
|
||||
encoding='utf-8', timeout=20, env=env)
|
||||
|
||||
result = run('rg Tile')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn('additionalContext', result.stdout)
|
||||
self.assertEqual('', run('git status', 's2').stdout)
|
||||
blocked = run('rm -rf build && rg x', 's3')
|
||||
self.assertEqual(blocked.returncode, 2)
|
||||
self.assertEqual('', blocked.stdout)
|
||||
|
||||
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)
|
||||
# Codex hook commands pass -Shell; the wrapper must stay in hook mode and read the event.
|
||||
codex = json.dumps({'tool_name': 'Bash', 'tool_input': {'command': 'rm -r build'}})
|
||||
self.assertEqual(2, self.run_wrapper(command + ['-Shell', 'unknown'], codex).returncode, name)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -12,7 +12,6 @@ from pathlib import Path
|
||||
import queue
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
|
||||
@@ -99,6 +99,29 @@ class InstallOptionsTests(unittest.TestCase):
|
||||
commands = [hook['command'] for group in result['hooks']['SessionStart'] for hook in group['hooks']]
|
||||
self.assertEqual(commands, ['bash "/c/hooks/scripts/show-session-state-pointer.sh"'])
|
||||
|
||||
def test_managed_powershell_session_hooks_are_replaced_not_duplicated(self):
|
||||
pointer = {'hooks': [{'type': 'command', 'command': 'pwsh -File "C:/c/hooks/scripts/Show-SessionStatePointer.ps1"'}]}
|
||||
caveman = {'hooks': [{'type': 'command', 'command': 'pwsh -File "C:/c/hooks/scripts/Show-CavemanMode.ps1"'}]}
|
||||
managed = {'hooks': {'SessionStart': [pointer, caveman]}}
|
||||
merged = OPTIONS.merge_json(OPTIONS.merge_json({}, managed), managed)
|
||||
self.assertEqual([pointer, caveman], merged['hooks']['SessionStart'])
|
||||
toml = ('[[hooks.SessionStart]]\n[[hooks.SessionStart.hooks]]\ntype = "command"\n'
|
||||
"command = 'bash \"/c/hooks/scripts/show-caveman-mode.sh\"'\n")
|
||||
self.assertEqual(1, OPTIONS.merge_toml(toml, toml).count('show-caveman-mode.sh'))
|
||||
|
||||
def test_semantic_retrieval_disabled_removes_qmd_sandbox_exclusion(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
settings = Path(directory) / 'settings.json'
|
||||
qmd = 'node "$HOME/.my-ai-configuration/qmd/qmd-search.mjs" *'
|
||||
settings.write_text(json.dumps({'sandbox': {'enabled': True, 'excludedCommands': [qmd, 'docker *']}}), encoding='utf-8')
|
||||
self.assertEqual(json.loads(OPTIONS.filter_options(settings, semantic_retrieval_enabled=False))['sandbox']['excludedCommands'], ['docker *'])
|
||||
settings.write_text(json.dumps({'sandbox': {'enabled': True, 'excludedCommands': [qmd]}}), encoding='utf-8')
|
||||
self.assertEqual(json.loads(OPTIONS.filter_options(settings, semantic_retrieval_enabled=False))['sandbox'], {'enabled': True})
|
||||
self.assertEqual(json.loads(OPTIONS.filter_options(settings, semantic_retrieval_enabled=True))['sandbox']['excludedCommands'], [qmd])
|
||||
current = {'sandbox': {'enabled': True, 'excludedCommands': [qmd, 'docker *']}}
|
||||
self.assertEqual(OPTIONS.merge_json(current, {'sandbox': {'enabled': True}})['sandbox']['excludedCommands'], ['docker *'])
|
||||
self.assertEqual(OPTIONS.merge_json(current, {'sandbox': {'excludedCommands': [qmd]}})['sandbox']['excludedCommands'], [qmd, 'docker *'])
|
||||
|
||||
def test_semantic_retrieval_disabled_removes_codex_session_hook(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
config = Path(directory) / 'config.toml'
|
||||
@@ -109,6 +132,41 @@ class InstallOptionsTests(unittest.TestCase):
|
||||
self.assertNotIn('qmd-warm', result)
|
||||
self.assertNotIn('hooks.SessionStart', result)
|
||||
|
||||
def test_codex_merge_registers_impeccable_hooks_once(self):
|
||||
managed = (ROOT / 'adapters/codex/config/config.toml').read_text(encoding='utf-8')
|
||||
managed = managed.replace('__IMPECCABLE_HOOK_SCRIPT__', 'invoke-impeccable-hook.sh')
|
||||
merged = OPTIONS.merge_toml(OPTIONS.merge_toml('', managed), managed)
|
||||
hooks = tomllib.loads(merged)['hooks']
|
||||
def impeccable(groups):
|
||||
return [group for group in groups if 'impeccable-hook' in group['hooks'][0]['command']]
|
||||
self.assertEqual(1, len(impeccable(hooks['PostToolUse'])))
|
||||
self.assertEqual('Edit|Write|apply_patch', impeccable(hooks['PostToolUse'])[0]['matcher'])
|
||||
self.assertEqual(1, len(impeccable(hooks['Stop'])))
|
||||
|
||||
def test_impeccable_hook_wrappers_forward_event_or_are_noops(self):
|
||||
scripts = ROOT / 'shared/hooks/scripts'
|
||||
shells = [(shutil.which('bash'), [], 'invoke-impeccable-hook.sh', 'impeccable', 'printf "%s:" "$1"; cat\n')]
|
||||
if os.name == 'nt':
|
||||
shells.append((shutil.which('powershell'), ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File'],
|
||||
'Invoke-ImpeccableHook.ps1', 'impeccable.cmd', '@echo off\r\n<nul set /p=%1:\r\nmore\r\n'))
|
||||
for executable, arguments, name, launcher_name, launcher_body in shells:
|
||||
if not executable:
|
||||
continue
|
||||
with self.subTest(shell=name), tempfile.TemporaryDirectory() as directory:
|
||||
home = Path(directory)
|
||||
env = dict(os.environ, HOME=str(home), USERPROFILE=str(home), CODEX_HOME=str(home / '.codex'))
|
||||
def run():
|
||||
return subprocess.run([executable, *arguments, str(scripts / name)], input='{"event":1}',
|
||||
env=env, capture_output=True, text=True, timeout=60)
|
||||
result = run()
|
||||
self.assertEqual((0, ''), (result.returncode, result.stdout), result.stderr)
|
||||
launcher = home / '.agents/skills/impeccable/scripts' / launcher_name
|
||||
launcher.parent.mkdir(parents=True)
|
||||
launcher.write_text(launcher_body, newline='')
|
||||
result = run()
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
self.assertEqual('hook:{"event":1}', result.stdout.strip())
|
||||
|
||||
def test_instruction_line_only_with_semantic_search(self):
|
||||
text = 'Line one.\nWhen `semantic-search` is installed, run it first.\nLine three.\n'
|
||||
self.assertEqual(OPTIONS.filter_instructions(text, False), 'Line one.\nLine three.\n')
|
||||
@@ -116,7 +174,7 @@ class InstallOptionsTests(unittest.TestCase):
|
||||
|
||||
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_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"'}))
|
||||
|
||||
def test_merge_json_keeps_user_session_hook_and_drops_qmd_when_disabled(self):
|
||||
@@ -195,7 +253,7 @@ class InstallOptionsTests(unittest.TestCase):
|
||||
environment = dict(os.environ, OPTION_SOURCE=str(source), OPTION_DESTINATION=str(destination))
|
||||
for enabled in (False, True):
|
||||
if kind == 'powershell':
|
||||
command = [executable, '-NoProfile', '-Command',
|
||||
command = [executable, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command',
|
||||
"$ErrorActionPreference='Stop'; . ./scripts/lib/manifest.ps1; "
|
||||
"Sync-ManagedDestination -Source $env:OPTION_SOURCE -Destination $env:OPTION_DESTINATION "
|
||||
"-Stamp test -AiConfigRoot root -ShellCommand bash -PowerShellCommand pwsh "
|
||||
@@ -206,7 +264,7 @@ class InstallOptionsTests(unittest.TestCase):
|
||||
'sync_managed_destination "$OPTION_SOURCE" "$OPTION_DESTINATION" test root bash pwsh false true '
|
||||
+ str(enabled).lower()]
|
||||
environment.update(OPTION_SOURCE=source.as_posix(), OPTION_DESTINATION=destination.as_posix())
|
||||
result = subprocess.run(command, cwd=ROOT, env=environment, capture_output=True, text=True, timeout=20)
|
||||
result = subprocess.run(command, cwd=ROOT, env=environment, capture_output=True, text=True, errors='replace', timeout=20)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
installed = json.loads((destination / 'settings.json').read_text(encoding='utf-8-sig'))
|
||||
self.assertEqual('Stop' in installed['hooks'], enabled)
|
||||
@@ -228,6 +286,9 @@ class InstallOptionsTests(unittest.TestCase):
|
||||
commands = scripts / 'commands'
|
||||
commands.mkdir(parents=True)
|
||||
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.mkdir()
|
||||
(root / 'adapters').mkdir()
|
||||
@@ -264,11 +325,11 @@ class InstallOptionsTests(unittest.TestCase):
|
||||
environment = dict(os.environ, HOME=home.as_posix(), TEST_INSTALL_HOME=str(home))
|
||||
for name, quick, answers in [('install', False, 'n\nn\nn\n'), ('update', True, '')]:
|
||||
entry = str(commands / (name + '.' + suffix))
|
||||
command = ([executable, '-NoProfile', '-File', entry, '-Shell', 'Bash', '-Client', 'Both', '-Summary']
|
||||
command = ([executable, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', entry, '-Shell', 'Bash', '-Client', 'Both', '-Summary']
|
||||
if kind == 'powershell' else [executable, entry, '--shell', 'bash', '--client', 'both', '--summary'])
|
||||
if quick:
|
||||
command.append('-Quick' if kind == 'powershell' else '--quick')
|
||||
result = subprocess.run(command, env=environment, input=answers, capture_output=True, text=True, timeout=25)
|
||||
result = subprocess.run(command, env=environment, input=answers, capture_output=True, text=True, errors='replace', timeout=25)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
self.assertNotIn('CLI-MOCK', result.stdout)
|
||||
if quick:
|
||||
|
||||
@@ -6,7 +6,9 @@ import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
@@ -37,7 +39,14 @@ def mcp():
|
||||
mcporter_url='https://mcp.context7.com/mcp')
|
||||
|
||||
|
||||
def clone():
|
||||
return dict(name='Roast Room', codex_method='clone', codex_source='nateherkai/roast-room', codex_skill='roast-room',
|
||||
codex_plugin='-', codex_marketplace='-', claude_plugin='-', claude_marketplace='-')
|
||||
|
||||
|
||||
class ManagedExtensionTests(unittest.TestCase):
|
||||
git_status = ''
|
||||
|
||||
def setUp(self):
|
||||
self.temporary = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temporary.cleanup)
|
||||
@@ -56,6 +65,8 @@ class ManagedExtensionTests(unittest.TestCase):
|
||||
if args[:2] == ['npm', 'list']:
|
||||
return '{"dependencies":{}}'
|
||||
self.commands.append(args)
|
||||
if args[0] == 'git' and 'status' in args:
|
||||
return self.git_status
|
||||
if len(args) > 3 and args[2] in ('add', 'install') and args[1] == 'plugin':
|
||||
self.installed[args[0]][args[3]] = {'scope': 'user'}
|
||||
if args[2] in ('remove', 'uninstall'):
|
||||
@@ -105,6 +116,16 @@ class ManagedExtensionTests(unittest.TestCase):
|
||||
self.assertEqual('foreign', target.read_text())
|
||||
self.assertEqual([], self.manager().state['resources'])
|
||||
|
||||
def test_skill_without_claude_plugin_installs_skill_payload_for_both_clients(self):
|
||||
entry = dict(skill(), claude_plugin='-', claude_marketplace='-')
|
||||
self.manager().sync([entry], ['claude', 'codex'], {'Humanizer'})
|
||||
self.assertEqual('original', (self.home / '.claude/skills/humanizer/SKILL.md').read_text())
|
||||
self.assertEqual('original', (self.home / '.agents/skills/humanizer/SKILL.md').read_text())
|
||||
self.assertEqual([], self.commands)
|
||||
self.manager().sync([], ['claude'], set())
|
||||
self.assertFalse((self.home / '.claude/skills/humanizer').exists())
|
||||
self.assertEqual(['codex'], [r['client'] for r in self.manager().state['resources']])
|
||||
|
||||
def test_skill_removal_preserves_modified_and_foreign_files(self):
|
||||
self.manager().sync([skill()], ['codex'], {'Humanizer'})
|
||||
directory = self.home / '.agents/skills/humanizer'
|
||||
@@ -203,57 +224,154 @@ class ManagedExtensionTests(unittest.TestCase):
|
||||
with self.assertRaisesRegex(ValueError, 'refresh failed'):
|
||||
self.manager().sync([plugin()], ['claude'], {'Example'})
|
||||
self.assertEqual(['claude', 'plugin', 'marketplace', 'update', 'test'], command.call_args.args[0])
|
||||
self.assertEqual(1, command.call_count)
|
||||
self.assertEqual([], self.manager().state['resources'])
|
||||
|
||||
@unittest.skipUnless(os.name == 'nt', 'Windows hook compatibility')
|
||||
def test_owned_caveman_hook_repair_runs_in_powershell_and_is_idempotent(self):
|
||||
entry = dict(plugin('Caveman'), codex_plugin='caveman@thinkhome-caveman')
|
||||
root = self.home / '.codex/plugins/cache/thinkhome-caveman/caveman/1.0.0'
|
||||
path = root / 'hooks/hooks.json'
|
||||
path.parent.mkdir(parents=True)
|
||||
hook = {'type': 'command', 'command': 'unchanged',
|
||||
'commandWindows': 'node "%PLUGIN_ROOT%\\hooks\\caveman-hook.mjs"'}
|
||||
path.write_text(json.dumps({'hooks': {event: [{'hooks': [dict(hook)]}]
|
||||
for event in ['SessionStart', 'UserPromptSubmit', 'SubagentStart']}}))
|
||||
upstream = path.read_bytes()
|
||||
self.manager().sync([entry], ['codex'], {'Caveman'})
|
||||
repaired = path.read_bytes()
|
||||
for groups in json.loads(repaired)['hooks'].values():
|
||||
self.assertNotIn('%PLUGIN_ROOT%', groups[0]['hooks'][0]['commandWindows'])
|
||||
self.assertEqual('unchanged', groups[0]['hooks'][0]['command'])
|
||||
self.manager().sync([entry], ['codex'], {'Caveman'})
|
||||
self.assertEqual(repaired, path.read_bytes())
|
||||
path.write_bytes(upstream)
|
||||
self.manager(update=True).sync([entry], ['codex'], {'Caveman'})
|
||||
self.assertEqual(repaired, path.read_bytes())
|
||||
if not shutil.which('node'):
|
||||
self.skipTest('Node is unavailable for launcher execution')
|
||||
(root / 'hooks/caveman-hook.mjs').write_text("process.stdout.write('hook-ok');")
|
||||
command = json.loads(repaired)['hooks']['SessionStart'][0]['hooks'][0]['commandWindows']
|
||||
result = subprocess.run(['powershell', '-NoProfile', '-Command', command],
|
||||
env=dict(os.environ, PLUGIN_ROOT=str(root)), capture_output=True, text=True, timeout=10)
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
self.assertEqual('hook-ok', result.stdout)
|
||||
def test_claude_marketplace_refresh_retries_transient_lock(self):
|
||||
failures = [ValueError("EPERM: operation not permitted, rename 'caveman..clone'")] * 2
|
||||
def command(args, summary, home=None):
|
||||
if args[2:4] == ['marketplace', 'update'] and failures:
|
||||
raise failures.pop()
|
||||
return self.command(args, summary, home)
|
||||
with patch.object(extensions, 'run_command', side_effect=command), patch.object(extensions.time, 'sleep') as sleep:
|
||||
self.manager().sync([plugin()], ['claude'], {'Example'})
|
||||
self.assertEqual(2, sleep.call_count)
|
||||
self.assertEqual(['claude', 'plugin', 'install', 'example@test', '--scope', 'user'], self.commands[-1])
|
||||
self.assertEqual(['Example'], [r['name'] for r in self.manager().state['resources']])
|
||||
|
||||
@unittest.skipUnless(os.name == 'nt', 'Windows hook compatibility')
|
||||
def test_caveman_repair_preserves_foreign_and_custom_hooks_and_dry_runs(self):
|
||||
entry = dict(plugin('Caveman'), codex_plugin='caveman@thinkhome-caveman')
|
||||
path = self.home / '.codex/plugins/cache/thinkhome-caveman/caveman/1.0.0/hooks/hooks.json'
|
||||
path.parent.mkdir(parents=True)
|
||||
original = json.dumps({'hooks': {'SessionStart': [{'hooks': [{'commandWindows':
|
||||
'node "%PLUGIN_ROOT%\\hooks\\caveman-hook.mjs"'}]}]}}).encode()
|
||||
path.write_bytes(original)
|
||||
self.installed['codex'][entry['codex_plugin']] = {}
|
||||
self.manager().sync([entry], ['codex'], {'Caveman'})
|
||||
def test_claude_marketplace_refresh_gives_up_after_three_transient_failures(self):
|
||||
with patch.object(extensions, 'run_command', side_effect=ValueError('EBUSY')) as command, patch.object(extensions.time, 'sleep'):
|
||||
with self.assertRaisesRegex(ValueError, 'EBUSY'):
|
||||
self.manager().sync([plugin()], ['claude'], {'Example'})
|
||||
self.assertEqual(3, command.call_count)
|
||||
|
||||
def test_claude_only_entry_removes_owned_codex_install_and_keeps_claude(self):
|
||||
self.manager().sync([plugin('Caveman')], ['claude', 'codex'], {'Caveman'})
|
||||
installed = len(self.commands)
|
||||
claude_only = dict(plugin('Caveman'), codex_method='-', codex_plugin='-')
|
||||
for action in ('install', 'sync'):
|
||||
self.manager().sync([claude_only], ['claude', 'codex'], {'Caveman'}, action)
|
||||
self.assertEqual([['codex', 'plugin', 'remove', 'caveman@test']], [c for c in self.commands[installed:] if c[0] == 'codex'])
|
||||
self.assertEqual(['claude'], [r['client'] for r in self.manager().state['resources']])
|
||||
|
||||
def test_codex_skill_agents_are_registered_and_removed_with_the_skill(self):
|
||||
payload = {'SKILL.md': (b'skill', False), 'agents/impeccable_finish_reviewer.toml': (b'name = "x"\n', False),
|
||||
'agents/openai.yaml': (b'policy: {}\n', False)}
|
||||
agent = self.home / '.codex/agents/impeccable_finish_reviewer.toml'
|
||||
entry = dict(skill(), name='Impeccable', codex_skill='impeccable', claude_plugin='-', claude_marketplace='-')
|
||||
with patch.object(extensions, 'fetch_skill', return_value=('impeccable', payload)):
|
||||
self.manager().sync([entry], ['claude', 'codex'], {'Impeccable'})
|
||||
self.assertEqual(b'name = "x"\n', agent.read_bytes())
|
||||
self.assertFalse((self.home / '.codex/agents/openai.yaml').exists())
|
||||
self.assertFalse((self.home / '.claude/agents').exists(), 'Claude gets its agents from the plugin')
|
||||
self.manager().sync([], ['codex'], set())
|
||||
self.assertFalse(agent.exists())
|
||||
|
||||
def test_foreign_codex_agent_file_is_preserved(self):
|
||||
payload = {'SKILL.md': (b'skill', False), 'agents/impeccable_finish_reviewer.toml': (b'upstream', False)}
|
||||
agent = self.home / '.codex/agents/impeccable_finish_reviewer.toml'
|
||||
agent.parent.mkdir(parents=True)
|
||||
agent.write_bytes(b'mine')
|
||||
with patch.object(extensions, 'fetch_skill', return_value=('impeccable', payload)):
|
||||
self.manager().sync([dict(skill(), name='Impeccable', codex_skill='impeccable')], ['codex'], {'Impeccable'})
|
||||
self.manager().sync([], ['codex'], set())
|
||||
self.assertEqual(b'mine', agent.read_bytes())
|
||||
|
||||
def test_clone_is_shared_by_both_clients_and_cloned_once(self):
|
||||
target = self.home / '.my-ai-configuration/roast-room'
|
||||
original = self.command
|
||||
|
||||
def clone_creates_folder(args, summary, home=None):
|
||||
if args[:2] == ['git', 'clone']:
|
||||
target.mkdir(parents=True)
|
||||
return original(args, summary, home)
|
||||
with patch.object(extensions, 'run_command', side_effect=clone_creates_folder):
|
||||
self.manager().sync([clone()], ['claude', 'codex'], {'Roast Room'})
|
||||
self.assertEqual([['git', 'clone', '--depth', '1', 'https://github.com/nateherkai/roast-room.git', str(target)]], self.commands)
|
||||
records = self.manager().state['resources']
|
||||
self.assertEqual([('shared', 'clone', ['claude', 'codex'])], [(r['client'], r['kind'], r['clients']) for r in records])
|
||||
self.manager(update=True).sync([clone()], ['claude', 'codex'], {'Roast Room'})
|
||||
self.assertEqual(1, sum(1 for command in self.commands if 'pull' in command))
|
||||
self.manager().sync([], ['claude'], set())
|
||||
self.assertTrue(target.is_dir(), 'the clone stays while Codex still uses it')
|
||||
self.assertEqual(['codex'], self.manager().state['resources'][0]['clients'])
|
||||
|
||||
def test_pre_existing_clone_folder_is_not_claimed(self):
|
||||
(self.home / '.my-ai-configuration/roast-room').mkdir(parents=True)
|
||||
self.manager(update=True).sync([clone()], ['claude'], {'Roast Room'})
|
||||
self.assertEqual([], self.commands)
|
||||
self.assertEqual([], self.manager().state['resources'])
|
||||
self.assertEqual(original, path.read_bytes())
|
||||
self.installed['codex'].clear()
|
||||
self.manager(dry_run=True).sync([entry], ['codex'], {'Caveman'})
|
||||
self.assertEqual(original, path.read_bytes())
|
||||
original = b'{"hooks":{"SessionStart":[{"hooks":[{"commandWindows":"custom"}]}]}}'
|
||||
path.write_bytes(original)
|
||||
self.manager().sync([entry], ['codex'], {'Caveman'})
|
||||
self.assertEqual(original, path.read_bytes())
|
||||
|
||||
def test_clone_update_pulls_only_when_tracked_files_are_unchanged(self):
|
||||
self.manager().sync([clone()], ['claude'], {'Roast Room'})
|
||||
(self.home / '.my-ai-configuration/roast-room').mkdir(parents=True)
|
||||
self.git_status = ' M .claude/skills/roast-room/SKILL.md\n'
|
||||
self.manager(update=True).sync([clone()], ['claude'], {'Roast Room'})
|
||||
self.assertNotIn('pull', [part for command in self.commands for part in command])
|
||||
self.git_status = ''
|
||||
self.manager(update=True).sync([clone()], ['claude'], {'Roast Room'})
|
||||
self.assertEqual('pull', self.commands[-1][3])
|
||||
|
||||
def test_clone_removal_keeps_local_sessions_and_removes_clean_clone(self):
|
||||
target = self.home / '.my-ai-configuration/roast-room'
|
||||
self.manager().sync([clone()], ['claude'], {'Roast Room'})
|
||||
target.mkdir(parents=True)
|
||||
self.git_status = '?? sessions/2026-11-19-pricing/brief.md\n!! node_modules/x/index.js\n'
|
||||
self.manager().sync([], ['claude'], set())
|
||||
self.assertTrue(target.is_dir())
|
||||
self.assertEqual(1, len(self.manager().state['resources']))
|
||||
self.git_status = '!! node_modules/x/index.js\n'
|
||||
self.manager().sync([], ['claude'], set())
|
||||
self.assertFalse(target.exists())
|
||||
self.assertEqual([], self.manager().state['resources'])
|
||||
|
||||
def test_clean_clone_with_read_only_git_objects_is_removed(self):
|
||||
target = self.home / '.my-ai-configuration/roast-room'
|
||||
self.manager().sync([clone()], ['claude'], {'Roast Room'})
|
||||
pack = target / '.git/objects/pack/pack-1.idx'
|
||||
pack.parent.mkdir(parents=True)
|
||||
pack.write_text('x')
|
||||
os.chmod(pack, stat.S_IREAD)
|
||||
self.manager().sync([], ['claude'], set())
|
||||
self.assertFalse(target.exists())
|
||||
self.assertEqual([], self.manager().state['resources'])
|
||||
|
||||
def test_clone_git_failure_warns_and_does_not_stop_other_extensions(self):
|
||||
target = self.home / '.my-ai-configuration/roast-room'
|
||||
self.manager().sync([clone()], ['claude'], {'Roast Room'})
|
||||
target.mkdir(parents=True)
|
||||
original = self.command
|
||||
|
||||
def git_fails(args, summary, home=None):
|
||||
if args[0] == 'git':
|
||||
raise ValueError('fatal: not a git repository')
|
||||
return original(args, summary, home)
|
||||
with patch.object(extensions, 'run_command', side_effect=git_fails):
|
||||
self.manager(update=True).sync([clone(), plugin()], ['claude'], {'Roast Room', 'Example'})
|
||||
self.assertIn(['claude', 'plugin', 'install', 'example@test', '--scope', 'user'], self.commands)
|
||||
self.manager().sync([], ['claude'], set())
|
||||
self.assertTrue(target.is_dir(), 'an unreadable clone is never deleted')
|
||||
self.assertEqual(['Roast Room'], [r['name'] for r in self.manager().state['resources']])
|
||||
|
||||
def test_stale_lock_from_a_dead_process_is_replaced(self):
|
||||
lock = self.home / '.my-ai-configuration/extensions.lock'
|
||||
lock.parent.mkdir(parents=True)
|
||||
dead = subprocess.Popen([sys.executable, '-c', 'pass'])
|
||||
dead.wait()
|
||||
lock.write_text(str(dead.pid))
|
||||
extensions.acquire_lock(lock)
|
||||
self.assertEqual(str(os.getpid()), lock.read_text())
|
||||
lock.write_text(str(os.getpid()))
|
||||
with self.assertRaisesRegex(ValueError, 'Another install or update is running'):
|
||||
extensions.acquire_lock(lock)
|
||||
|
||||
def test_selected_adhd_does_not_enable_always_on_flag(self):
|
||||
# plugin-workflow carries the response structure; the full always-on ruleset would duplicate it.
|
||||
config = self.home / '.claude'
|
||||
flag = config / '.i-have-adhd-always'
|
||||
with patch.dict(os.environ, {'CLAUDE_CONFIG_DIR': str(config)}):
|
||||
self.manager().sync([plugin('i-have-adhd')], ['claude'], {'i-have-adhd'})
|
||||
self.assertFalse(flag.exists())
|
||||
|
||||
def test_dry_run_summary_has_one_line(self):
|
||||
with contextlib.redirect_stdout(io.StringIO()) as output:
|
||||
@@ -336,6 +454,31 @@ class CommandTests(unittest.TestCase):
|
||||
result = extensions.run_command([str(executable), 'plugin', 'list', '--json'], True, home)
|
||||
self.assertEqual([str(home / '.codex'), str(home / '.claude')], result.splitlines())
|
||||
|
||||
def test_global_npm_cli_is_found_when_its_directory_is_not_on_path(self):
|
||||
with tempfile.TemporaryDirectory() as temporary:
|
||||
prefix = Path(temporary)
|
||||
bin_dir = prefix if os.name == 'nt' else prefix / 'bin'
|
||||
bin_dir.mkdir(exist_ok=True)
|
||||
tool = bin_dir / ('mcporter.cmd' if os.name == 'nt' else 'mcporter')
|
||||
tool.write_text('@echo off\n' if os.name == 'nt' else '#!/bin/sh\n')
|
||||
tool.chmod(0o700)
|
||||
real_which = shutil.which
|
||||
|
||||
def which(name, mode=os.F_OK | os.X_OK, path=None):
|
||||
if path is None:
|
||||
return '/usr/bin/npm' if name == 'npm' else None
|
||||
return real_which(name, mode, path)
|
||||
|
||||
prefix_result = subprocess.CompletedProcess(['npm'], 0, stdout=f'{prefix}\n', stderr='')
|
||||
with patch.object(extensions.shutil, 'which', side_effect=which), \
|
||||
patch.object(extensions.subprocess, 'run', return_value=prefix_result):
|
||||
found = extensions.find_executable('mcporter')
|
||||
self.assertEqual(Path(found).resolve(), tool.resolve())
|
||||
|
||||
def test_missing_cli_stays_missing_without_npm(self):
|
||||
with patch.object(extensions.shutil, 'which', return_value=None):
|
||||
self.assertIsNone(extensions.find_executable('mcporter'))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -10,7 +10,7 @@ import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
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):
|
||||
@@ -118,7 +118,7 @@ class PersonalInstructionTests(unittest.TestCase):
|
||||
def sync(client, dry=False):
|
||||
self.environment['TEST_CLIENT'] = client
|
||||
if shell == 'powershell':
|
||||
return self.run_command(str(executable), '-NoProfile', '-Command',
|
||||
return self.run_command(str(executable), '-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command',
|
||||
". ./scripts/lib/manifest.ps1; Sync-ManagedDestination -Source $env:TEST_SOURCE "
|
||||
"-Destination (Join-Path $env:TEST_HOME ('.' + $env:TEST_CLIENT)) -Stamp test -Summary "
|
||||
+ ('-DryRun' if dry else ''))
|
||||
@@ -129,7 +129,7 @@ class PersonalInstructionTests(unittest.TestCase):
|
||||
|
||||
def change(action):
|
||||
if shell == 'powershell':
|
||||
self.run_command(str(executable), '-NoProfile', '-File', str(ROOT / f'scripts/commands/{action}-instruction.ps1'),
|
||||
self.run_command(str(executable), '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', str(ROOT / f'scripts/commands/{action}-instruction.ps1'),
|
||||
'-Client', 'Both', '-Instruction', 'Use English.', '-HomePath', str(self.home))
|
||||
else:
|
||||
self.run_command(str(executable), '-c',
|
||||
|
||||
@@ -37,7 +37,7 @@ catch { $failed = $true }
|
||||
$env:AI_CONFIG_VERBOSE = $null
|
||||
if (-not $failed -or $diagnostics -notcontains 'download progress' -or $diagnostics -notcontains 'WARN test warning') { throw 'Plugin failure must retain full diagnostics and fail.' }
|
||||
$global:LASTEXITCODE = 0
|
||||
$script:codexInventory = '{"installed":[{"pluginId":"ponytail@ponytail"},{"pluginId":"i-have-adhd@i-have-adhd"},{"pluginId":"superpowers@openai-curated-remote"},{"pluginId":"context7@context7-marketplace"},{"pluginId":"caveman@thinkhome-caveman"}],"available":[]}'
|
||||
$script:codexInventory = '{"installed":[{"pluginId":"ponytail@ponytail"},{"pluginId":"i-have-adhd@i-have-adhd"},{"pluginId":"superpowers@openai-curated-remote"},{"pluginId":"context7@context7-marketplace"}],"available":[]}'
|
||||
function codex { $script:observedCodexHome = $env:CODEX_HOME; $script:observedProfile = $env:USERPROFILE; $script:codexInventory }
|
||||
$testHome = Join-Path ([System.IO.Path]::GetTempPath()) 'ai-config-plugin-test-home'
|
||||
$previousCodexHome = [Environment]::GetEnvironmentVariable('CODEX_HOME', 'Process')
|
||||
@@ -47,7 +47,8 @@ if ($observedCodexHome -ne (Join-Path $testHome '.codex') -or $observedProfile -
|
||||
if ([Environment]::GetEnvironmentVariable('CODEX_HOME', 'Process') -ne $previousCodexHome -or [Environment]::GetEnvironmentVariable('USERPROFILE', 'Process') -ne $previousProfile) { throw 'Plugin inspection must restore the process environment.' }
|
||||
$script:answers.Enqueue('done')
|
||||
$selection = Select-ConfiguredPlugins -RepositoryRoot (Split-Path (Split-Path $PSScriptRoot -Parent) -Parent) -Client Codex -Mode Update
|
||||
if (@($selection.Selected | Where-Object { $_.codex_method -eq 'plugin' }).Count -ne 5) { throw 'All installed Codex plugins must start checked when updating.' }
|
||||
if (@($selection.Selected | Where-Object { $_.codex_method -eq 'plugin' }).Count -ne 4) { throw 'All installed Codex plugins must start checked when updating.' }
|
||||
if (@($selection.Selected + $selection.Deselected | Where-Object { $_.name -in @('Caveman', 'Roast Room') }).Count -ne 2) { throw 'Caveman and Roast Room must be offered for Codex too.' }
|
||||
$script:answers.Enqueue('4')
|
||||
$script:answers.Enqueue('done')
|
||||
$selection = Select-ConfiguredPlugins -RepositoryRoot (Split-Path (Split-Path $PSScriptRoot -Parent) -Parent) -Client Codex -Mode Update
|
||||
@@ -66,8 +67,21 @@ try {
|
||||
$selection = Select-ConfiguredPlugins -RepositoryRoot $root -Client Codex -Mode Update -HomePath $mcporterHome
|
||||
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 }
|
||||
$npmPrefix = Join-Path $root ('.npm-test-' + [Guid]::NewGuid())
|
||||
$cliName = 'ai-config-test-cli-' + [Guid]::NewGuid().ToString('N')
|
||||
try {
|
||||
New-Item (Join-Path $npmPrefix 'bin') -ItemType Directory -Force | Out-Null
|
||||
function npm { $npmPrefix }
|
||||
if (Test-CliCommand -Name $cliName) { throw 'A missing CLI must not be detected.' }
|
||||
New-Item (Join-Path $npmPrefix "$cliName.cmd") -ItemType File | Out-Null
|
||||
New-Item (Join-Path $npmPrefix "bin/$cliName") -ItemType File | Out-Null
|
||||
if (-not (Test-CliCommand -Name $cliName)) { throw 'A CLI in the npm global prefix must be detected when it is not on PATH.' }
|
||||
} finally {
|
||||
Remove-Item function:npm -ErrorAction SilentlyContinue
|
||||
Remove-Item -LiteralPath $npmPrefix -Recurse -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
$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' }
|
||||
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.' }
|
||||
|
||||
@@ -48,6 +48,19 @@ select_configured_plugins "$root" codex Update true selected deselected
|
||||
printf '%s\n' '{"mcpServers":{"context7":{"baseUrl":"https://example.invalid/mcp"}}}' > "$test_home/.mcporter/mcporter.json"
|
||||
select_configured_plugins "$root" codex Update true selected deselected
|
||||
[[ " ${deselected[*]} " == *' Context7 '* ]] || { printf 'A different MCPorter server must not select Context7.\n' >&2; exit 1; }
|
||||
for name in Caveman 'Roast Room'; do
|
||||
[[ " ${selected[*]} ${deselected[*]} " == *" $name "* ]] || { printf '%s must be offered for Codex too.\n' "$name" >&2; exit 1; }
|
||||
done
|
||||
npm_prefix=$(mktemp -d "$root/.npm-test.XXXXXX")
|
||||
cli_name="ai-config-test-cli-${npm_prefix##*.}"
|
||||
npm() { printf '%s\n' "$npm_prefix"; }
|
||||
if cli_installed "$cli_name"; then rm -rf -- "$npm_prefix"; printf 'A missing CLI must not be detected.\n' >&2; exit 1; fi
|
||||
mkdir -p "$npm_prefix/bin"
|
||||
touch "$npm_prefix/$cli_name.cmd" "$npm_prefix/bin/$cli_name"
|
||||
chmod +x "$npm_prefix/bin/$cli_name"
|
||||
if ! cli_installed "$cli_name"; then rm -rf -- "$npm_prefix"; printf 'A CLI in the npm global prefix must be detected when it is not on PATH.\n' >&2; exit 1; fi
|
||||
rm -rf -- "$npm_prefix"
|
||||
unset -f npm
|
||||
# shellcheck disable=SC2034
|
||||
selected=()
|
||||
plugin_installed() { printf 'Empty selection must not query installed plugins.\n' >&2; exit 1; }
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { existsSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs';
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync, utimesSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join, resolve } from 'node:path';
|
||||
import { acquireStartLock, createServer, gitFingerprint, ignoreGlobs, keepModelsLoaded } from '../../shared/qmd/qmd-daemon.mjs';
|
||||
import { INDEX_EXCLUDES, acquireStartLock, createServer, gitFingerprint, ignoreGlobs, indexIgnores, keepModelsLoaded, pruneCollections } from '../../shared/qmd/qmd-daemon.mjs';
|
||||
import { collectionName } from '../../shared/qmd/qmd-lib.mjs';
|
||||
|
||||
const defaultHits = () => [{ displayPath: `${collectionName('/r')}/src/a.ts`, body: 'x\nretry here', bestChunkPos: 2, bestChunk: 'retry here', score: 0.91 }];
|
||||
@@ -72,6 +72,19 @@ test('search adds the repo collection once, refreshes on change, and filters oth
|
||||
assert.equal(s.store.calls.filter((c) => c[0] === 'update').length, 1, 'unchanged fingerprint skips update');
|
||||
});
|
||||
|
||||
test('a changed embedding size clears old vectors and embeds again', async (t) => {
|
||||
const s = await start(t);
|
||||
let failures = 1;
|
||||
const embed = s.store.embed;
|
||||
s.store.embed = async (opts) => {
|
||||
if (failures-- > 0) throw new Error('Embedding dimension mismatch: existing vectors are 1024d but the current model produces 2560d.');
|
||||
return embed(opts);
|
||||
};
|
||||
s.store.internal = { clearAllEmbeddings: () => s.store.calls.push(['clear']) };
|
||||
assert.equal((await s.call('/search', { repo: '/r', query: 'q', limit: 1 })).status, 200);
|
||||
assert.deepEqual(s.store.calls.filter((c) => c[0] === 'clear' || c[0] === 'embed').map((c) => c[0]), ['clear', 'embed']);
|
||||
});
|
||||
|
||||
test('rejects a missing query', async (t) => {
|
||||
const s = await start(t);
|
||||
assert.equal((await s.call('/search', { repo: '/r' })).status, 400);
|
||||
@@ -182,6 +195,13 @@ test('ignoreGlobs turns git ignored paths into escaped QMD ignore globs', () =>
|
||||
assert.deepEqual(ignoreGlobs('', escape), []);
|
||||
});
|
||||
|
||||
test('index ignores add lockfiles and minified bundles to the git ignored paths', () => {
|
||||
const ignores = indexIgnores('/r', (path) => path, () => ['dist/**']);
|
||||
assert.deepEqual(ignores, [...INDEX_EXCLUDES, 'dist/**']);
|
||||
for (const pattern of ['**/package-lock.json', '**/pnpm-lock.yaml', '**/*.min.js']) assert.ok(ignores.includes(pattern));
|
||||
assert.deepEqual(indexIgnores('/r', (path) => path, () => []), INDEX_EXCLUDES, 'fixed excludes apply when git lists nothing');
|
||||
});
|
||||
|
||||
test('git ignored paths reach addCollection and are persisted only when they change', async (t) => {
|
||||
let ignore = ['dist/**'];
|
||||
let fingerprint = 'one';
|
||||
@@ -202,6 +222,27 @@ test('git ignored paths reach addCollection and are persisted only when they cha
|
||||
assert.equal(s.store.calls.filter((c) => c[0] === 'update').length, 3);
|
||||
});
|
||||
|
||||
test('daemon start prunes recorded repo collections whose path is gone and keeps the rest', async (t) => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'qmd-prune-'));
|
||||
t.after(() => rmSync(dir, { recursive: true, force: true }));
|
||||
const collectionsFile = join(dir, 'collections.json');
|
||||
const gone = join(dir, 'deleted-worktree');
|
||||
const recorded = ['repo-aaaaaaaaaaaa', 'repo-bbbbbbbbbbbb', 'repo-cccccccccccc', 'repo-dddddddddddd'];
|
||||
writeFileSync(collectionsFile, JSON.stringify(recorded));
|
||||
const store = { listCollections: async () => [
|
||||
{ name: 'notes', pwd: gone }, { name: 'repo-aaaaaaaaaaaa', pwd: gone }, { name: 'repo-bbbbbbbbbbbb', pwd: dir }, { name: 'repo-cccccccccccc', pwd: gone },
|
||||
] };
|
||||
const removed = [];
|
||||
const logged = [];
|
||||
await pruneCollections({ store, collectionsFile, log: (line) => logged.push(line), remove: (name) => {
|
||||
if (name === 'repo-cccccccccccc') throw new Error('locked');
|
||||
removed.push(name);
|
||||
} });
|
||||
assert.deepEqual(removed, ['repo-aaaaaaaaaaaa'], 'only a missing path is removed; foreign collections are never touched');
|
||||
assert.deepEqual(JSON.parse(readFileSync(collectionsFile, 'utf8')), ['repo-bbbbbbbbbbbb', 'repo-cccccccccccc', 'repo-dddddddddddd']);
|
||||
assert.equal(logged.length, 1, 'a failed removal is logged and kept for the next start');
|
||||
});
|
||||
|
||||
test('the start lock admits one launcher and is taken over after 2 minutes', (t) => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'qmd-lock-'));
|
||||
t.after(() => rmSync(dir, { recursive: true, force: true }));
|
||||
|
||||
@@ -7,7 +7,7 @@ import { tmpdir } from 'node:os';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import * as YAML from './fixtures/yaml-shim.mjs';
|
||||
import { collectionName, deviceEnv, idleMinutes, qmdConfigPath, qmdPackageDir, writePrivateJson, writeTextAtomic, readJson, runQmdCli, MODELS } from '../../shared/qmd/qmd-lib.mjs';
|
||||
import { collectionName, deviceEnv, idleMinutes, qmdConfigPath, qmdPackageDir, writePrivateJson, writeTextAtomic, readJson, runQmdCli, MASK, MODELS } from '../../shared/qmd/qmd-lib.mjs';
|
||||
import { setModels, unsetModels, previousModels, restoreModels, setCollectionIgnore } from '../../shared/qmd/qmd-config.mjs';
|
||||
|
||||
for (const layout of ['nested', 'hoisted']) {
|
||||
@@ -134,4 +134,7 @@ test('setCollectionIgnore writes the ignore list of one collection and keeps the
|
||||
const cleared = setCollectionIgnore(withIgnore, YAML, 'repo-aaaaaaaaaaaa', []);
|
||||
assert.deepEqual(YAML.default.parse(cleared).collections['repo-aaaaaaaaaaaa'], { path: '/r', includeByDefault: false });
|
||||
assert.equal(setCollectionIgnore(original, YAML, 'repo-bbbbbbbbbbbb', ['x']), null, 'an unknown collection is not created');
|
||||
const remasked = setCollectionIgnore(cleared, YAML, 'repo-aaaaaaaaaaaa', [], MASK);
|
||||
assert.equal(YAML.default.parse(remasked).collections['repo-aaaaaaaaaaaa'].pattern, MASK, 'an older file mask is replaced');
|
||||
assert.match(MASK, /html,css,scss,xaml/);
|
||||
});
|
||||
@@ -4,11 +4,18 @@ import { EventEmitter } from 'node:events';
|
||||
import { mkdtempSync, rmSync, writeFileSync, existsSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { callDaemon, runSearch, startDaemon, toCliResults } from '../../shared/qmd/qmd-search.mjs';
|
||||
import { callDaemon, getDocument, runSearch, startDaemon, toCliResults } from '../../shared/qmd/qmd-search.mjs';
|
||||
import { collectionName } from '../../shared/qmd/qmd-lib.mjs';
|
||||
|
||||
const hit = [{ path: 'src/a.ts', line: 3, score: 0.9, snippet: 's' }];
|
||||
|
||||
test('getDocument reads qmd URIs through the QMD CLI and rejects other input', () => {
|
||||
const calls = [];
|
||||
assert.equal(getDocument('qmd://notes/a b.md:10', (args) => { calls.push(args); return 'body'; }), 'body');
|
||||
assert.deepEqual(calls, [['get', 'qmd://notes/a b.md:10']]);
|
||||
for (const bad of ['notes/a.md', 'qmd://notes', '--help', 'qmd:///a.md']) assert.throws(() => getDocument(bad, () => 'x'), /qmd:\/\//);
|
||||
});
|
||||
|
||||
test('uses the daemon when it answers', async () => {
|
||||
const results = await runSearch({ root: '/My Repo/ü', query: 'q', topK: 5,
|
||||
daemon: async (path, body) => { assert.equal(path, '/search'); assert.equal(body.repo, '/My Repo/ü'); return { results: hit }; },
|
||||
@@ -88,13 +95,32 @@ function tempDaemonFile(t, value) {
|
||||
return file;
|
||||
}
|
||||
|
||||
test('startDaemon resolves when its child loses the start race to a running daemon', async (t) => {
|
||||
const file = tempDaemonFile(t, { port: 4000, token: 'other', pid: 999 });
|
||||
await startDaemon({ file, spawnChild: () => {
|
||||
const losingChild = () => {
|
||||
const child = new EventEmitter(); child.unref = () => {}; child.pid = 1;
|
||||
setImmediate(() => child.emit('exit', 0));
|
||||
return child;
|
||||
} });
|
||||
};
|
||||
|
||||
test('startDaemon resolves when its child loses the start race to a running daemon', async (t) => {
|
||||
const file = tempDaemonFile(t, { port: 4000, token: 'other', pid: 999 });
|
||||
const fetchImpl = async (url, options) => {
|
||||
assert.equal(url, 'http://127.0.0.1:4000/health');
|
||||
assert.equal(options.headers['x-qmd-token'], 'other');
|
||||
return { ok: true, json: async () => ({ service: 'ai-config-qmd' }) };
|
||||
};
|
||||
await startDaemon({ file, fetchImpl, spawnChild: losingChild });
|
||||
});
|
||||
|
||||
test('after a lost race a stale daemon.json from a crashed daemon is not used until a new token appears', async (t) => {
|
||||
const file = tempDaemonFile(t, { port: 4000, token: 'crashed', pid: 999 });
|
||||
let checks = 0;
|
||||
const fetchImpl = async () => { checks += 1; throw new TypeError('fetch failed'); };
|
||||
let rewritten = false;
|
||||
const timer = setTimeout(() => { rewritten = true; writeFileSync(file, JSON.stringify({ port: 4001, token: 'fresh', pid: 998 })); }, 1200);
|
||||
t.after(() => clearTimeout(timer));
|
||||
await startDaemon({ file, fetchImpl, spawnChild: losingChild });
|
||||
assert.ok(rewritten, 'resolved on the stale daemon.json');
|
||||
assert.ok(checks >= 1, 'the stale token was health-checked');
|
||||
});
|
||||
|
||||
test('a 403 means a stale token: daemon.json is deleted and one new daemon is started', async (t) => {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
@@ -17,8 +18,8 @@ spec.loader.exec_module(qmd)
|
||||
|
||||
class FakeRunner:
|
||||
def __init__(self, installed=False, gpu='cuda', gpu_result=None, cpu_result=None, previous=None, fail_pull=False, list_output=None,
|
||||
node='v22.4.0', fail=(), on_call=None):
|
||||
self.calls, self.installed, self.gpu = [], installed, gpu
|
||||
node='v22.4.0', fail=(), on_call=None, version='2.8.3'):
|
||||
self.calls, self.installed, self.gpu, self.version = [], installed, gpu, version
|
||||
self.previous, self.fail_pull, self.list_output = previous, fail_pull, list_output
|
||||
self.node, self.fail, self.on_call = node, fail, on_call
|
||||
self.results = {'gpu': gpu_result, 'cpu': cpu_result}
|
||||
@@ -34,14 +35,14 @@ class FakeRunner:
|
||||
return self.node
|
||||
if arguments[-1:] == ['set-models']:
|
||||
return json.dumps({'previous': self.previous}) + chr(10)
|
||||
if self.fail_pull and arguments[:2] == ['qmd', 'pull']:
|
||||
if self.fail_pull and arguments[0] == 'node' and arguments[-1:] == ['pull']:
|
||||
raise ValueError('pull failed')
|
||||
if 'npm list' in joined and self.list_output is not None:
|
||||
return self.list_output
|
||||
if 'npm list' in joined:
|
||||
return json.dumps({'dependencies': {'@tobilu/qmd': {}} if self.installed else {}})
|
||||
return json.dumps({'dependencies': {'@tobilu/qmd': {'version': self.version}} if self.installed else {}})
|
||||
if 'npm install' in joined:
|
||||
self.installed = True
|
||||
self.installed, self.version = True, arguments[-1].rsplit('@', 1)[-1]
|
||||
if 'npm uninstall' in joined:
|
||||
self.installed = False
|
||||
if '--detect' in joined:
|
||||
@@ -103,6 +104,66 @@ class SetupTest(unittest.TestCase):
|
||||
self.assertFalse(any('npm uninstall' in ' '.join(c) for c in runner.calls))
|
||||
self.assertFalse((self.home / '.my-ai-configuration/qmd.json').exists())
|
||||
|
||||
def test_update_stops_the_running_daemon_before_replacing_scripts(self):
|
||||
runner = FakeRunner()
|
||||
self.setup(runner).enable(['claude'])
|
||||
runner.calls.clear()
|
||||
self.setup(runner).enable(['claude'])
|
||||
stop = next(i for i, c in enumerate(runner.calls) if c[-1:] == ['--stop'])
|
||||
set_models = next(i for i, c in enumerate(runner.calls) if c[-1:] == ['set-models'])
|
||||
self.assertLess(stop, set_models)
|
||||
|
||||
def test_owned_package_with_another_version_is_reinstalled(self):
|
||||
runner = FakeRunner()
|
||||
self.setup(runner).enable(['claude'])
|
||||
runner.version = '2.7.0'
|
||||
runner.calls.clear()
|
||||
self.setup(runner).enable(['claude'])
|
||||
self.assertIn(['npm', 'install', '--global', '@tobilu/qmd@2.8.3'], runner.calls)
|
||||
|
||||
def test_foreign_package_with_another_version_only_warns(self):
|
||||
runner = FakeRunner(installed=True, version='2.9.0')
|
||||
with mock.patch('sys.stderr', new_callable=io.StringIO) as stderr:
|
||||
self.setup(runner).enable(['claude'])
|
||||
self.assertFalse(any('npm install' in ' '.join(c) for c in runner.calls))
|
||||
self.assertIn('2.9.0 is not the tested 2.8.3', stderr.getvalue())
|
||||
|
||||
def test_doctor_checks_report_scripts_package_models_and_daemon(self):
|
||||
setup = self.setup(FakeRunner())
|
||||
self.assertEqual([], qmd.doctor_checks(setup))
|
||||
setup.enable(['claude'])
|
||||
checks = qmd.doctor_checks(setup)
|
||||
# Scripts match, package matches, models not downloaded in the fake runner, daemon not running.
|
||||
self.assertEqual(['PASS', 'PASS', 'WARN', 'PASS'], [status for status, _ in checks], checks)
|
||||
(self.home / '.my-ai-configuration/qmd/qmd-search.mjs').write_text('changed')
|
||||
self.assertEqual(('WARN', 'QMD runtime scripts were modified: qmd-search.mjs'), qmd.doctor_checks(setup)[0])
|
||||
|
||||
def test_model_files_follow_node_llama_cpp_cache_names(self):
|
||||
names = qmd.model_files((ROOT / 'shared/qmd/qmd-lib.mjs').read_text(encoding='utf-8'))
|
||||
self.assertIn('hf_Qwen_Qwen3-Embedding-4B-Q4_K_M.gguf', names)
|
||||
self.assertIn('Qwen3-Embedding-4B-Q4_K_M.gguf.etag', names)
|
||||
self.assertEqual(6, len(names))
|
||||
|
||||
def test_update_deletes_only_owned_models_no_longer_used(self):
|
||||
models = self.home / '.cache/qmd/models'
|
||||
current = qmd.model_files((ROOT / 'shared/qmd/qmd-lib.mjs').read_text(encoding='utf-8'))
|
||||
def create(arguments):
|
||||
if arguments[-1:] == ['pull']:
|
||||
for name in current:
|
||||
(models / name).write_text('x')
|
||||
runner = FakeRunner(on_call=create)
|
||||
self.setup(runner).enable(['claude'])
|
||||
for name in ('hf_Qwen_Qwen3-Embedding-0.6B-Q8_0.gguf', 'foreign.gguf'):
|
||||
(models / name).write_text('x')
|
||||
state = self.state()
|
||||
state['owned_models'].append('hf_Qwen_Qwen3-Embedding-0.6B-Q8_0.gguf')
|
||||
(self.home / '.my-ai-configuration/qmd.json').write_text(json.dumps(state))
|
||||
self.setup(runner).enable(['claude'])
|
||||
self.assertFalse((models / 'hf_Qwen_Qwen3-Embedding-0.6B-Q8_0.gguf').exists())
|
||||
self.assertTrue((models / 'foreign.gguf').exists())
|
||||
self.assertTrue(all((models / n).exists() for n in current))
|
||||
self.assertEqual(sorted(current), self.state()['owned_models'])
|
||||
|
||||
def test_disable_removes_owned_models_and_collections(self):
|
||||
runner = FakeRunner()
|
||||
setup = self.setup(runner)
|
||||
@@ -115,7 +176,8 @@ class SetupTest(unittest.TestCase):
|
||||
(self.home / '.my-ai-configuration/qmd/collections.json').write_text(json.dumps(['repo-abcdefabcdef']))
|
||||
setup.disable(['claude'])
|
||||
self.assertFalse(model.exists())
|
||||
self.assertIn(['qmd', 'collection', 'remove', 'repo-abcdefabcdef'], runner.calls)
|
||||
self.assertTrue(any(call[0] == 'node' and call[1].endswith('qmd.js') and call[2:] == ['collection', 'remove', 'repo-abcdefabcdef']
|
||||
for call in runner.calls), runner.calls)
|
||||
self.assertIn(['npm', 'uninstall', '--global', '@tobilu/qmd'], runner.calls)
|
||||
|
||||
def test_benchmark_unsuitable_cleans_up(self):
|
||||
@@ -155,6 +217,15 @@ class SetupTest(unittest.TestCase):
|
||||
self.assertIn(['node', str(self.home / '.my-ai-configuration/qmd/qmd-config.mjs'), 'restore-models', '{"embed": "mine"}'], runner.calls)
|
||||
self.assertFalse(any(c[-1:] == ['unset-models'] for c in runner.calls))
|
||||
|
||||
def test_update_rewrites_owned_models_block_and_keeps_user_original(self):
|
||||
runner = FakeRunner(previous={'embed': 'mine'})
|
||||
self.setup(runner).enable(['claude'])
|
||||
# The second run sees the setup's own older block; it must refresh it without recording it as the user's.
|
||||
runner.previous = {'rerank': 'older setup default'}
|
||||
self.setup(runner).enable(['claude'])
|
||||
self.assertEqual(2, sum(c[-1:] == ['set-models'] for c in runner.calls))
|
||||
self.assertEqual(self.state()['previous_models'], {'embed': 'mine'})
|
||||
|
||||
def test_models_block_removed_when_none_existed(self):
|
||||
runner = FakeRunner()
|
||||
setup = self.setup(runner)
|
||||
@@ -220,6 +291,29 @@ class SetupTest(unittest.TestCase):
|
||||
self.assertTrue(self.setup(FakeRunner(list_output='{"dependencies": {"@tobilu/qmd": {}}, "error": {}}')).package_installed())
|
||||
self.assertFalse(self.setup(FakeRunner(list_output='{"dependencies": {}}')).package_installed())
|
||||
|
||||
def test_qmd_cli_runs_through_node_without_relying_on_path(self):
|
||||
# npm's global bin directory is often missing from PATH on Windows right after install.
|
||||
runner = FakeRunner()
|
||||
runner_root = str(self.home / 'npm-root')
|
||||
original = runner.__call__
|
||||
|
||||
def call(arguments, env=None, timeout=None, check=True):
|
||||
if arguments == ['npm', 'root', '--global']:
|
||||
runner.calls.append(list(arguments))
|
||||
return runner_root + '\n'
|
||||
return original(arguments, env=env, timeout=timeout, check=check)
|
||||
|
||||
setup = self.setup(call)
|
||||
setup.qmd_cli('pull')
|
||||
expected = str(Path(runner_root) / '@tobilu' / 'qmd' / 'dist' / 'cli' / 'qmd.js')
|
||||
self.assertIn(['node', expected, 'pull'], runner.calls)
|
||||
self.assertFalse(any(call[0] == 'qmd' for call in runner.calls))
|
||||
|
||||
def test_package_installed_treats_missing_global_prefix_as_not_installed(self):
|
||||
# npm reports ENOENT for the global prefix before anything was ever installed globally.
|
||||
output = '{"error": {"code": "ENOENT", "summary": "ENOENT: no such file or directory, lstat \'C:\\\\Users\\\\me\\\\AppData\\\\Roaming\\\\npm\'"}}'
|
||||
self.assertFalse(self.setup(FakeRunner(list_output=output)).package_installed())
|
||||
|
||||
def test_non_mapping_previous_models_are_restored_verbatim(self):
|
||||
runner = FakeRunner(previous='custom.gguf')
|
||||
setup = self.setup(runner)
|
||||
|
||||
@@ -35,15 +35,15 @@ class SelectionTests(unittest.TestCase):
|
||||
self.assertFalse(self.path.exists())
|
||||
|
||||
def test_selection_round_trip_and_last_successful_write(self):
|
||||
self.save('--selected', 'Superpowers', 'Anthropic Frontend Design', '--deselected', 'Context7')
|
||||
self.save('--selected', 'Superpowers', 'Humanizer', '--deselected', 'Context7')
|
||||
original = self.path.read_bytes()
|
||||
state = json.loads(self.run_state('read').stdout)
|
||||
self.assertEqual(state['shell'], 'powershell')
|
||||
self.assertEqual(state['client'], 'both')
|
||||
self.assertEqual(state['selected'], ['Superpowers', 'Anthropic Frontend Design'])
|
||||
self.assertEqual(state['selected'], ['Superpowers', 'Humanizer'])
|
||||
self.assertEqual(state['deselected'], ['Context7'])
|
||||
self.assertEqual(self.path.read_bytes(), original)
|
||||
self.assertIn('selected\tAnthropic Frontend Design', self.run_state('read', '--format', 'tsv').stdout)
|
||||
self.assertIn('selected\tHumanizer', self.run_state('read', '--format', 'tsv').stdout)
|
||||
self.save('--selected', 'Context7')
|
||||
self.assertEqual(json.loads(self.run_state('read').stdout)['selected'], ['Context7'])
|
||||
|
||||
@@ -114,7 +114,7 @@ class SelectionTests(unittest.TestCase):
|
||||
if not shell:
|
||||
self.skipTest('PowerShell unavailable')
|
||||
environment = dict(os.environ, TEST_SELECTION_HOME=str(self.home), TEST_REPOSITORY_ROOT=str(ROOT))
|
||||
save = subprocess.run([shell, '-NoProfile', '-Command',
|
||||
save = subprocess.run([shell, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command',
|
||||
"$ErrorActionPreference = 'Stop'; . (Join-Path $env:TEST_REPOSITORY_ROOT 'scripts/lib/selection-state.ps1'); "
|
||||
"Save-UpdateSelection -HomePath $env:TEST_SELECTION_HOME -RepositoryRoot $env:TEST_REPOSITORY_ROOT "
|
||||
"-Shell PowerShell -Client Both -Flashbang $false -StatusLine $false -Plugins @{ Selected = @([pscustomobject]@{name='Superpowers'}); Deselected = @() }"],
|
||||
@@ -128,15 +128,15 @@ class SelectionTests(unittest.TestCase):
|
||||
stream.write(source)
|
||||
entry = Path(stream.name)
|
||||
self.addCleanup(entry.unlink)
|
||||
result = subprocess.run([shell, '-NoProfile', '-File', str(entry), '-Quick', '-DryRun'],
|
||||
env=environment, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=90)
|
||||
result = subprocess.run([shell, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', str(entry), '-Quick', '-DryRun'],
|
||||
env=environment, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=300) # Git Bash on Windows needs ~3 min
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
self.assertNotIn('Select plugins', result.stdout)
|
||||
self.assertIn('DRYRUN ensure codex plugin: Superpowers', result.stdout)
|
||||
self.assertNotIn('DRYRUN ensure codex plugin: Context7', result.stdout)
|
||||
self.assertEqual(self.path.read_bytes(), original)
|
||||
self.assertFalse((self.home / '.codex').exists())
|
||||
failed = subprocess.run([shell, '-NoProfile', '-File', str(entry), '-Quick'], env=environment,
|
||||
failed = subprocess.run([shell, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', str(entry), '-Quick'], env=environment,
|
||||
stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=10)
|
||||
self.assertNotEqual(failed.returncode, 0)
|
||||
self.assertEqual(self.path.read_bytes(), original)
|
||||
@@ -158,7 +158,7 @@ class SelectionTests(unittest.TestCase):
|
||||
original = self.path.read_bytes()
|
||||
environment = dict(os.environ, HOME=self.home.as_posix())
|
||||
result = subprocess.run([shell, str(ROOT / 'scripts/commands/update.sh'), '--quick', '--dry-run'],
|
||||
env=environment, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=90)
|
||||
env=environment, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=300) # Git Bash on Windows needs ~3 min
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
self.assertNotIn('Select plugins', result.stdout)
|
||||
self.assertIn('DRYRUN ensure codex plugin: Superpowers', result.stdout)
|
||||
|
||||
@@ -121,7 +121,7 @@ class RemoveCustomizationTests(unittest.TestCase):
|
||||
for name in ('remove-credentials.ps1', 'remove-credentials.sh'):
|
||||
shutil.copy2(ROOT / 'scripts' / 'commands' / name, commands / name)
|
||||
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)
|
||||
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()
|
||||
@@ -45,34 +45,39 @@ foreach ($shell in @('powershell','bash')) {
|
||||
if ($client -eq 'claude') { $settings = $content | ConvertFrom-Json }
|
||||
if (@(Get-ChildItem "$package/agents" -File).Count -ne $sourceAgentCount) { throw "Missing agents in $package" }
|
||||
$expectedReviewerShellTool = if ($shell -eq 'powershell') { 'PowerShell' } else { 'Bash' }
|
||||
if ($client -eq 'claude' -and (Get-Content (Join-Path $package 'agents/reviewer.md') -Raw) -notmatch "(?m)^tools: Read,Grep,Glob,$expectedReviewerShellTool\r?`$") { throw "Reviewer capability profile is missing in $package" }
|
||||
if ($client -eq 'claude' -and (Get-Content (Join-Path $package 'agents/reviewer.md') -Raw) -notmatch "(?m)^tools: Read,Grep,Glob,$expectedReviewerShellTool,Skill\r?`$") { throw "Reviewer capability profile is missing in $package" }
|
||||
if ($client -eq 'claude') {
|
||||
foreach ($role in @('architect','researcher')) {
|
||||
if ((Get-Content (Join-Path $package "agents/$role.md") -Raw) -notmatch "(?m)^tools: Read,Grep,Glob,WebFetch,WebSearch,$expectedReviewerShellTool\r?`$") { throw "$role research shell capability is missing in $package" }
|
||||
if ((Get-Content (Join-Path $package "agents/$role.md") -Raw) -notmatch "(?m)^tools: Read,Grep,Glob,WebFetch,WebSearch,$expectedReviewerShellTool,Skill\r?`$") { throw "$role research shell capability is missing in $package" }
|
||||
}
|
||||
}
|
||||
$expectedSkillCount = if ($client -eq 'claude') { $sourceSkillCount + $ruleSkillCount } else { $sourceSkillCount }
|
||||
$launcher = if ($client -eq 'claude') { 'skills/roast-room' } else { 'skills/extensions/roast-room' }
|
||||
if (-not (Test-Path "$package/$launcher/SKILL.md") -or -not (Test-Path "$package/$launcher/agents/openai.yaml")) { throw "Missing roast-room launcher in $package" }
|
||||
if ($client -eq 'codex' -and -not (Test-Path "$package/rules/my-ai-configuration.rules")) { throw "Missing Codex execpolicy rules in $package" }
|
||||
if (@(Get-ChildItem "$package/skills" -Filter SKILL.md -Recurse).Count -ne $expectedSkillCount) { throw "Missing skills in $package" }
|
||||
$securityReview = if ($client -eq 'claude') { 'skills/security-review/SKILL.md' } else { 'skills/reviews/security-review/SKILL.md' }
|
||||
if ($client -eq 'claude' -and @(Get-ChildItem "$package/skills" -Filter SKILL.md -Recurse | Where-Object { $_.Directory.Parent.FullName -ne (Resolve-Path "$package/skills").Path }).Count) { throw "Nested Claude skills in $package" }
|
||||
if ((Test-Path "$package/skills/debugging/SKILL.md") -or -not (Test-Path "$package/$securityReview") -or -not (Test-Path "$package/skills/copywriting/SKILL.md") -or -not (Test-Path "$package/skills/marketing-psychology/SKILL.md") -or -not (Test-Path "$package/skills/image/SKILL.md") -or (Test-Path "$package/skills/marketing-plan/SKILL.md") -or (Test-Path "$package/skills/social/SKILL.md")) { throw "Incorrect skill catalog in $package" }
|
||||
if ((Test-Path "$package/skills/debugging/SKILL.md") -or -not (Test-Path "$package/$securityReview") -or (Test-Path "$package/skills/copywriting/SKILL.md") -or (Test-Path "$package/skills/cro/SKILL.md") -or -not (Test-Path "$package/skills/media/SKILL.md") -or (Test-Path "$package/skills/marketing-plan/SKILL.md") -or (Test-Path "$package/skills/social/SKILL.md")) { throw "Incorrect skill catalog in $package" }
|
||||
$diagnostics = if ($client -eq 'claude') { 'skills' } else { 'skills/diagnostics' }
|
||||
foreach ($skill in @('incident-investigation','performance-measure')) { if (-not (Test-Path "$package/$diagnostics/$skill/SKILL.md")) { throw "Missing $skill in $package" } }
|
||||
$expected = if ($shell -eq 'powershell') { '__POWERSHELL_COMMAND__ .*flashbang.ps1' } else { 'bash .*flashbang.sh' }
|
||||
if ($content -notmatch $expected -or $content -match '__HOOK_|__POWERSHELL_HOOK_') { throw "Incorrect shell command in $package" }
|
||||
if ($shell -eq 'powershell' -and $content -match 'WindowStyle\s+Hidden') { throw "PowerShell hook hides the terminal in $package" }
|
||||
if ($client -eq 'codex') {
|
||||
$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 'PostToolUse,PreCompact,PreToolUse,SessionStart,SessionStart,SessionStart,Stop,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 '(?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 '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"
|
||||
} elseif ($content -notmatch '"defaultMode"\s*:\s*"auto"') {
|
||||
throw "Claude auto permission mode is missing in $package"
|
||||
} elseif ($settings.env.CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS -ne '5' -or $settings.env.CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH -ne '1') {
|
||||
throw "Claude subagent limits are missing in $package"
|
||||
} elseif ($sandboxSupported -and ($settings.sandbox.enabled -ne $true -or $settings.sandbox.allowUnsandboxedCommands -ne $false -or $settings.sandbox.failIfUnavailable -ne $true -or (@($settings.sandbox.network.allowedDomains) -join ',') -ne 'mcp.context7.com' -or @($settings.sandbox.PSObject.Properties).Count -ne 4)) {
|
||||
} elseif ($sandboxSupported -and ($settings.sandbox.enabled -ne $true -or $settings.sandbox.allowUnsandboxedCommands -ne $false -or $settings.sandbox.failIfUnavailable -ne $true -or (@($settings.sandbox.network.allowedDomains) -join ',') -ne 'mcp.context7.com' -or (@($settings.sandbox.excludedCommands) -join ',') -ne 'node "$HOME/.my-ai-configuration/qmd/qmd-search.mjs" *' -or @($settings.sandbox.PSObject.Properties).Count -ne 5)) {
|
||||
throw "Claude strict sandbox is missing in $package"
|
||||
} elseif (-not $sandboxSupported -and ($settings.sandbox.enabled -ne $false -or @($settings.sandbox.PSObject.Properties).Count -ne 1)) {
|
||||
throw "Claude sandbox must be disabled in $package"
|
||||
|
||||
@@ -21,7 +21,7 @@ case "$(uname -s 2>/dev/null || true)" in
|
||||
esac
|
||||
source_agent_count=$(find "$root/shared/agents" -mindepth 1 -maxdepth 1 -type d | wc -l)
|
||||
source_skill_count=$(find "$root/shared/skills" -name SKILL.md | wc -l)
|
||||
mapfile -t rule_paths < <(find "$root/shared/rules" -mindepth 1 -type f -name '*.md' ! -name general.md -printf '%P\n' | sort)
|
||||
mapfile -t rule_paths < <(cd "$root/shared/rules" && find . -mindepth 1 -type f -name '*.md' ! -name general.md | sed 's|^\./||' | sort)
|
||||
rule_skill_count=${#rule_paths[@]}
|
||||
global_instructions=$(<"$root/shared/global-instructions.md")
|
||||
rule_skill_name() {
|
||||
@@ -51,10 +51,11 @@ for shell in powershell bash; do
|
||||
test "$(find "$package/agents" -type f | wc -l)" -eq "$source_agent_count"
|
||||
expected_reviewer_shell_tool=Bash
|
||||
[ "$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},Skill[[:space:]]*\$" "$package/agents/reviewer.md"; fi
|
||||
if [ "$client" = claude ]; then
|
||||
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},Skill[[:space:]]*\$" "$package/agents/$role.md" || { printf '%s research shell capability is missing in %s\n' "$role" "$package"; exit 1; }
|
||||
done
|
||||
fi
|
||||
expected_skill_count=$source_skill_count
|
||||
@@ -67,9 +68,18 @@ for shell in powershell bash; do
|
||||
else
|
||||
test -f "$package/skills/reviews/security-review/SKILL.md"
|
||||
fi
|
||||
test -f "$package/skills/copywriting/SKILL.md"
|
||||
test -f "$package/skills/marketing-psychology/SKILL.md"
|
||||
test -f "$package/skills/image/SKILL.md"
|
||||
test ! -e "$package/skills/copywriting/SKILL.md"
|
||||
test ! -e "$package/skills/cro/SKILL.md"
|
||||
test -f "$package/skills/media/SKILL.md"
|
||||
diagnostics="$package/skills/diagnostics"
|
||||
[ "$client" != claude ] || diagnostics="$package/skills"
|
||||
test -f "$diagnostics/incident-investigation/SKILL.md"
|
||||
test -f "$diagnostics/performance-measure/SKILL.md"
|
||||
launcher="$package/skills/extensions/roast-room"
|
||||
[ "$client" != claude ] || launcher="$package/skills/roast-room"
|
||||
test -f "$launcher/SKILL.md"
|
||||
test -f "$launcher/agents/openai.yaml"
|
||||
[ "$client" = claude ] || test -f "$package/rules/my-ai-configuration.rules"
|
||||
test ! -e "$package/skills/marketing-plan/SKILL.md"
|
||||
test ! -e "$package/skills/social/SKILL.md"
|
||||
if [ "$shell" = powershell ]; then
|
||||
@@ -79,7 +89,7 @@ for shell in powershell bash; do
|
||||
grep -q 'bash .*flashbang.sh' "$package/$file"
|
||||
fi
|
||||
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)" = $'PostToolUse\nPreCompact\nPreToolUse\nSessionStart\nSessionStart\nSessionStart\nStop\nStop\nStop\nUserPromptSubmit' ]
|
||||
! grep -q 'flashbang-if-input' "$package/$file"
|
||||
! grep -Eq '^async[[:space:]]*=[[:space:]]*true[[:space:]]*$' "$package/$file"
|
||||
grep -q 'approvals_reviewer[[:space:]]*=[[:space:]]*"auto_review"' "$package/$file"
|
||||
@@ -87,13 +97,13 @@ for shell in powershell bash; do
|
||||
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"
|
||||
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 '"async"[[:space:]]*:[[:space:]]*true' "$package/$file"
|
||||
grep -q '"defaultMode"[[:space:]]*:[[:space:]]*"auto"' "$package/$file"
|
||||
grep -q '"CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS"[[:space:]]*:[[:space:]]*"5"' "$package/$file"
|
||||
grep -q '"CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH"[[:space:]]*:[[:space:]]*"1"' "$package/$file"
|
||||
python3 -c 'import json,sys; settings=json.load(open(sys.argv[1], encoding="utf-8-sig")); expected={"enabled": True, "allowUnsandboxedCommands": False, "failIfUnavailable": True, "network": {"allowedDomains": ["mcp.context7.com"]}} if sys.argv[2] == "true" else {"enabled": False}; assert settings["sandbox"] == expected' "$package/$file" "$sandbox_supported"
|
||||
python3 -c 'import json,sys; settings=json.load(open(sys.argv[1], encoding="utf-8-sig")); expected={"enabled": True, "allowUnsandboxedCommands": False, "failIfUnavailable": True, "excludedCommands": ["node \"$HOME/.my-ai-configuration/qmd/qmd-search.mjs\" *"], "network": {"allowedDomains": ["mcp.context7.com"]}} if sys.argv[2] == "true" else {"enabled": False}; assert settings["sandbox"] == expected' "$package/$file" "$sandbox_supported"
|
||||
statusline_extension='sh'
|
||||
[ "$shell" != powershell ] || statusline_extension=ps1
|
||||
test -f "$package/statusline/statusline.$statusline_extension"
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SPEC = importlib.util.spec_from_file_location('contracts', ROOT / 'scripts/lib/skill-contracts.py')
|
||||
CONTRACTS = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(CONTRACTS)
|
||||
|
||||
|
||||
class SkillContractTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
directory = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(directory.cleanup)
|
||||
self.home = Path(directory.name)
|
||||
|
||||
def write(self, relative, text):
|
||||
path = self.home / relative
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(text, encoding='utf-8')
|
||||
|
||||
def test_reports_nothing_when_skills_are_absent(self):
|
||||
self.assertEqual([], CONTRACTS.check(self.home))
|
||||
|
||||
def test_passes_complete_skill_and_warns_on_missing_names(self):
|
||||
self.write('.claude/skills/apple-design/SKILL.md', ' '.join(CONTRACTS.CONTRACTS['apple-design'][1]))
|
||||
self.write('.agents/skills/impeccable/SKILL.md', 'critique audit')
|
||||
results = dict((message.split(' at ')[0], status) for status, message in CONTRACTS.check(self.home))
|
||||
self.assertEqual({'Apple Design': 'PASS', 'Impeccable': 'WARN'}, results)
|
||||
|
||||
def test_uses_highest_cached_plugin_version(self):
|
||||
tokens = ' '.join(CONTRACTS.CONTRACTS['impeccable'][1])
|
||||
self.write('.claude/plugins/cache/impeccable/impeccable/4.10.0/skills/impeccable/SKILL.md', tokens)
|
||||
self.write('.claude/plugins/cache/impeccable/impeccable/4.9.2/skills/impeccable/SKILL.md', 'old')
|
||||
[(status, message)] = CONTRACTS.check(self.home)
|
||||
self.assertEqual('PASS', status)
|
||||
self.assertIn('4.10.0', message)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -23,6 +23,8 @@ class TelemetryTests(unittest.TestCase):
|
||||
script = root / 'scripts/commands/telemetry.sh'
|
||||
script.parent.mkdir(parents=True)
|
||||
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')
|
||||
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)
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import tomllib
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
TEST_ROOT = ROOT / '.ai-session' / 'test-uninstall'
|
||||
sys.path.insert(0, str(ROOT / 'scripts/lib'))
|
||||
SPEC = importlib.util.spec_from_file_location('install_options', ROOT / 'scripts/lib/install-options.py')
|
||||
OPTIONS = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(OPTIONS)
|
||||
|
||||
OWNED_SETTINGS = {
|
||||
'permissions': {'allow': ['Agent']},
|
||||
'statusLine': {'type': 'command', 'command': 'bash "/home/.claude/statusline/statusline.sh"'},
|
||||
'sandbox': {'enabled': True, 'excludedCommands': ['node */qmd-search.mjs *']},
|
||||
'hooks': {
|
||||
'Stop': [{'hooks': [{'type': 'command', 'command': 'bash "/home/.claude/hooks/flashbang.sh"'}]}],
|
||||
'PreCompact': [{'hooks': [{'type': 'command', 'command': 'bash "/home/.claude/hooks/scripts/record-compact.sh"'}]}],
|
||||
},
|
||||
}
|
||||
OWNED_TOML = ('approval_policy = "on-request"\n\n[features]\nhooks = true\n\n'
|
||||
'[[hooks.Stop]]\n[[hooks.Stop.hooks]]\ntype = "command"\n'
|
||||
"command = 'bash \"/home/.codex/hooks/flashbang.sh\"'\ntimeout = 8\n")
|
||||
|
||||
|
||||
def find_bash():
|
||||
if os.name == 'nt':
|
||||
candidate = Path(os.environ.get('ProgramFiles', 'C:/Program Files')) / 'Git/bin/bash.exe'
|
||||
return str(candidate) if candidate.exists() else None
|
||||
return shutil.which('bash')
|
||||
|
||||
|
||||
def find_powershell():
|
||||
return shutil.which('powershell') or shutil.which('pwsh')
|
||||
|
||||
|
||||
class UninstallTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
TEST_ROOT.mkdir(parents=True, exist_ok=True)
|
||||
self.temporary = tempfile.TemporaryDirectory(dir=TEST_ROOT)
|
||||
self.addCleanup(self.temporary.cleanup)
|
||||
self.work = Path(self.temporary.name)
|
||||
self.environment = dict(os.environ, AI_CONFIG_NO_INTERACTIVE='1')
|
||||
for name in ('TEMP', 'TMP', 'TMPDIR'):
|
||||
self.environment[name] = str(self.work)
|
||||
|
||||
def run_process(self, arguments, environment=None, timeout=120):
|
||||
return subprocess.run(arguments, env=environment or self.environment, stdin=subprocess.DEVNULL,
|
||||
capture_output=True, text=True, timeout=timeout)
|
||||
|
||||
def bash_sync(self, source, destination):
|
||||
shell = find_bash() or self.skipTest('Bash unavailable')
|
||||
result = self.run_process([shell, '-c', 'set -euo pipefail; . "$1/scripts/lib/manifest.sh"; '
|
||||
'run_managed_sync "$2" "$3" stamp /root "" "" false true',
|
||||
'test', ROOT.as_posix(), source.as_posix(), destination.as_posix()])
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
return result.stdout
|
||||
|
||||
def powershell_sync(self, source, destination):
|
||||
shell = find_powershell() or self.skipTest('PowerShell unavailable')
|
||||
environment = dict(self.environment, TEST_ROOT=str(ROOT), TEST_SOURCE=str(source), TEST_DESTINATION=str(destination))
|
||||
if Path(shell).stem.lower() == 'powershell':
|
||||
environment = {key: value for key, value in environment.items() if key.upper() != 'PSMODULEPATH'} # Windows PowerShell 5.1 cannot load pwsh 7 module paths
|
||||
result = self.run_process([shell, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command',
|
||||
"$ErrorActionPreference = 'Stop'; . (Join-Path $env:TEST_ROOT 'scripts/lib/manifest.ps1'); "
|
||||
"Invoke-ManagedSync -Source $env:TEST_SOURCE -Destination $env:TEST_DESTINATION -Stamp stamp "
|
||||
"-AiConfigRoot /root -ShellCommand '' -PowerShellCommand '' -Summary"], environment)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
return result.stdout
|
||||
|
||||
def make_source(self, files):
|
||||
source = self.work / 'source'
|
||||
shutil.rmtree(source, ignore_errors=True)
|
||||
source.mkdir()
|
||||
for name, content in files.items():
|
||||
(source / name).write_bytes(content.encode('utf-8'))
|
||||
return source
|
||||
|
||||
# Bug 1: plugin installs change settings.json after install; uninstall must still remove owned hooks.
|
||||
def check_uninstall_strips_owned_entries(self, sync):
|
||||
destination = self.work / 'home/.claude'
|
||||
sync(self.make_source({'settings.json': json.dumps(OWNED_SETTINGS, indent=2) + '\n', 'config.toml': OWNED_TOML}), destination)
|
||||
settings = json.loads((destination / 'settings.json').read_text(encoding='utf-8'))
|
||||
settings['enabledPlugins'] = {'demo@market': True}
|
||||
settings['hooks']['Stop'].append({'hooks': [{'type': 'command', 'command': 'foreign-hook'}]})
|
||||
(destination / 'settings.json').write_text(json.dumps(settings, indent=2) + '\n', encoding='utf-8')
|
||||
|
||||
sync(self.make_source({}), destination)
|
||||
|
||||
self.assertFalse((destination / 'config.toml').exists(), 'an unmodified managed file is removed')
|
||||
remaining = json.loads((destination / 'settings.json').read_text(encoding='utf-8'))
|
||||
self.assertEqual(remaining['enabledPlugins'], {'demo@market': True})
|
||||
self.assertEqual(remaining['permissions'], {'allow': ['Agent']})
|
||||
self.assertNotIn('statusLine', remaining)
|
||||
self.assertEqual(remaining['sandbox'], {'enabled': True})
|
||||
self.assertEqual(remaining['hooks'], {'Stop': [{'hooks': [{'type': 'command', 'command': 'foreign-hook'}]}]})
|
||||
self.assertTrue((destination / 'backups/stamp/settings.json').exists())
|
||||
|
||||
def test_bash_uninstall_strips_owned_entries_from_changed_settings(self):
|
||||
self.check_uninstall_strips_owned_entries(self.bash_sync)
|
||||
|
||||
def test_powershell_uninstall_strips_owned_entries_from_changed_settings(self):
|
||||
self.check_uninstall_strips_owned_entries(self.powershell_sync)
|
||||
|
||||
def test_strip_removes_owned_toml_hooks_and_keeps_user_tables(self):
|
||||
current = OWNED_TOML + '\n[plugins."demo@market"]\nenabled = true\n'
|
||||
result = OPTIONS.strip_toml(current)
|
||||
parsed = tomllib.loads(result)
|
||||
self.assertNotIn('hooks', parsed)
|
||||
self.assertEqual(parsed['plugins'], {'demo@market': {'enabled': True}})
|
||||
self.assertEqual(parsed['approval_policy'], 'on-request')
|
||||
self.assertEqual(OPTIONS.strip_toml(OWNED_TOML[OWNED_TOML.index('[[hooks'):]), '')
|
||||
|
||||
def test_strip_json_returns_empty_when_only_owned_entries_remain(self):
|
||||
owned = {key: OWNED_SETTINGS[key] for key in ('statusLine', 'hooks')}
|
||||
self.assertEqual(OPTIONS.strip_json(owned), {})
|
||||
|
||||
# Bug 4: Bash must write the same merged bytes as PowerShell.
|
||||
def test_bash_and_powershell_write_identical_merged_files(self):
|
||||
files = {'settings.json': json.dumps(OWNED_SETTINGS, indent=2) + '\n', 'config.toml': OWNED_TOML, 'CLAUDE.md': '# Title\n\nBody\n'}
|
||||
current = {'settings.json': '{"model": "x"}\n', 'config.toml': 'model = "x"\n', 'CLAUDE.md': 'old\n'}
|
||||
written = {}
|
||||
for name, sync in (('bash', self.bash_sync), ('powershell', self.powershell_sync)):
|
||||
destination = self.work / name / '.claude'
|
||||
destination.mkdir(parents=True)
|
||||
for file, content in current.items():
|
||||
(destination / file).write_bytes(content.encode('utf-8'))
|
||||
sync(self.make_source(files), destination)
|
||||
written[name] = {file: (destination / file).read_bytes() for file in files}
|
||||
for file, content in written[name].items():
|
||||
self.assertNotIn(b'\r', content, f'{name} {file}')
|
||||
self.assertTrue(content.endswith(b'\n'), f'{name} {file}')
|
||||
self.assertEqual(written['bash'], written['powershell'])
|
||||
|
||||
# Bug 2: uninstalling one client must keep the selection while the other client is installed.
|
||||
def uninstall_copy(self, suffix, replacements):
|
||||
source = (ROOT / f'scripts/commands/uninstall{suffix}').read_text(encoding='utf-8-sig')
|
||||
for old, new in replacements:
|
||||
self.assertIn(old, source)
|
||||
source = source.replace(old, new)
|
||||
with tempfile.NamedTemporaryFile(mode='w', suffix=f'.tmp{suffix}', dir=ROOT / 'scripts/commands',
|
||||
encoding='utf-8', newline='\n', delete=False) as stream:
|
||||
stream.write(source)
|
||||
entry = Path(stream.name)
|
||||
self.addCleanup(entry.unlink)
|
||||
return entry
|
||||
|
||||
def make_installed_home(self):
|
||||
home = self.work / 'home'
|
||||
for destination in ('.claude', '.codex', '.agents/skills'):
|
||||
(home / destination).mkdir(parents=True)
|
||||
(home / destination / '.ai-config-manifest.tsv').write_text('path\tsha256\n', encoding='utf-8')
|
||||
selection = home / '.my-ai-configuration/selection.json'
|
||||
selection.parent.mkdir()
|
||||
selection.write_text('{}', encoding='utf-8')
|
||||
return home, selection
|
||||
|
||||
def test_bash_uninstall_one_client_keeps_selection(self):
|
||||
shell = find_bash() or self.skipTest('Bash unavailable')
|
||||
home, selection = self.make_installed_home()
|
||||
entry = self.uninstall_copy('.sh', [('sync_configured_plugins "$root"', ': '), ('sync_qmd "$root"', ': ')])
|
||||
result = self.run_process([shell, str(entry), '--client', 'claude', '--force', '--summary'],
|
||||
dict(self.environment, HOME=home.as_posix()))
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
self.assertFalse((home / '.claude/.ai-config-manifest.tsv').exists())
|
||||
self.assertTrue(selection.exists())
|
||||
|
||||
def test_powershell_uninstall_one_client_keeps_selection(self):
|
||||
shell = find_powershell() or self.skipTest('PowerShell unavailable')
|
||||
home, selection = self.make_installed_home()
|
||||
entry = self.uninstall_copy('.ps1', [("[Environment]::GetFolderPath('UserProfile')", '$env:TEST_HOME'),
|
||||
('Sync-ConfiguredPlugins -RepositoryRoot', '# '), ('Sync-Qmd -RepositoryRoot', '# ')])
|
||||
environment = dict(self.environment, TEST_HOME=str(home))
|
||||
if Path(shell).stem.lower() == 'powershell':
|
||||
environment = {key: value for key, value in environment.items() if key.upper() != 'PSMODULEPATH'}
|
||||
result = self.run_process([shell, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', str(entry),
|
||||
'-Client', 'Claude', '-Force', '-Summary'], environment)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
self.assertFalse((home / '.claude/.ai-config-manifest.tsv').exists())
|
||||
self.assertTrue(selection.exists())
|
||||
|
||||
# Bug 3: update must validate CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY like install does.
|
||||
def test_bash_update_rejects_invalid_claude_concurrency(self):
|
||||
shell = find_bash() or self.skipTest('Bash unavailable')
|
||||
result = self.run_process([shell, str(ROOT / 'scripts/commands/update.sh'), '--dry-run', '--client', 'claude', '--shell', 'bash'],
|
||||
dict(self.environment, HOME=self.work.as_posix(), CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY='11'))
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn('CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY must be an integer from 1 to 10.', result.stderr)
|
||||
|
||||
def test_powershell_update_rejects_invalid_claude_concurrency(self):
|
||||
shell = find_powershell() or self.skipTest('PowerShell unavailable')
|
||||
environment = dict(self.environment, CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY='0')
|
||||
if Path(shell).stem.lower() == 'powershell':
|
||||
environment = {key: value for key, value in environment.items() if key.upper() != 'PSMODULEPATH'}
|
||||
result = self.run_process([shell, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', str(ROOT / 'scripts/commands/update.ps1'),
|
||||
'-DryRun', '-Client', 'Claude', '-Shell', 'Bash'], environment)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn('CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY must be an integer from 1 to 10.', result.stdout + result.stderr)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main(argv=[sys.argv[0]], verbosity=2)
|
||||
@@ -1,5 +1,7 @@
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import uuid
|
||||
@@ -53,6 +55,8 @@ class UserCustomizationTests(unittest.TestCase):
|
||||
(home / '.my-ai-configuration/instructions/codex.md').read_text())
|
||||
|
||||
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')
|
||||
if powershell is None:
|
||||
self.skipTest('PowerShell is unavailable.')
|
||||
@@ -60,6 +64,9 @@ class UserCustomizationTests(unittest.TestCase):
|
||||
home = Path(directory)
|
||||
key = f'MY_TEST_TOKEN_{uuid.uuid4().hex}'
|
||||
stored = False
|
||||
stale = home / '.my-ai-configuration/bin/with-credential.ps1'
|
||||
stale.parent.mkdir(parents=True)
|
||||
stale.write_text('# outdated helper\n', encoding='utf-8')
|
||||
try:
|
||||
result = subprocess.run([
|
||||
powershell, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File',
|
||||
@@ -70,19 +77,31 @@ class UserCustomizationTests(unittest.TestCase):
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
stored = True
|
||||
helper = home / '.my-ai-configuration/bin/with-credential.ps1'
|
||||
self.assertTrue(helper.is_file())
|
||||
self.assertEqual((ROOT / 'scripts/lib/with-credential.ps1').read_bytes(), helper.read_bytes(),
|
||||
'add-credentials must replace an outdated helper')
|
||||
self.assertTrue((home / '.my-ai-configuration/bin/with-credential.sh').is_file())
|
||||
child = f"if ([Environment]::GetEnvironmentVariable('{key}', 'Process')) {{ exit 0 }}; exit 1"
|
||||
child = (f"if ([Environment]::GetEnvironmentVariable('{key}', 'Process')) "
|
||||
"{ Write-Output 'child-output'; exit 3 }; exit 1")
|
||||
injected = subprocess.run([
|
||||
powershell, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', str(helper),
|
||||
'-Client', 'Codex', '-Key', key, '-FilePath', powershell,
|
||||
'-NoProfile', '-Command', child,
|
||||
], capture_output=True, text=True, timeout=20)
|
||||
self.assertEqual(0, injected.returncode, injected.stderr)
|
||||
self.assertEqual(3, injected.returncode, injected.stderr)
|
||||
self.assertIn('child-output', injected.stdout)
|
||||
helper_call = [powershell, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', str(helper), '-Client', 'Codex', '-Key', key]
|
||||
# Child flags that abbreviate helper or common parameters (-k, -d, -v, -c) must reach the child unchanged.
|
||||
echoed = subprocess.run(helper_call + ['-FilePath', sys.executable, '-c', 'import sys; print(chr(124).join(sys.argv[1:]))',
|
||||
'-k', '-d', '-v', '-Key', 'x'], capture_output=True, text=True, timeout=20)
|
||||
self.assertEqual(0, echoed.returncode, echoed.stderr)
|
||||
self.assertEqual('-k|-d|-v|-Key|x', echoed.stdout.strip())
|
||||
# A command name found on PATH works without a full path.
|
||||
on_path = subprocess.run(helper_call + ['-FilePath', 'cmd.exe', '/c', 'exit', '4'], capture_output=True, text=True, timeout=20)
|
||||
self.assertEqual(4, on_path.returncode, on_path.stderr)
|
||||
finally:
|
||||
cleanup = subprocess.run([
|
||||
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)
|
||||
if stored:
|
||||
self.assertEqual(0, cleanup.returncode, cleanup.stderr)
|
||||
|
||||
@@ -4,4 +4,4 @@ Start from the parent's requirements and references. Identify relevant boundarie
|
||||
|
||||
Before accepting a design that relies on external technology behavior, MUST apply the planning checkpoint in `technical-research`. Carry supporting evidence or unresolved assumptions into the handoff.
|
||||
|
||||
Use shell commands for inspection and required research tools, including semantic search and MCPorter. Do not modify implementation code unless assigned.
|
||||
Use shell commands for inspection and required research tools, including semantic search (when installed) and MCPorter. Do not modify implementation code unless assigned.
|
||||
@@ -2,4 +2,4 @@
|
||||
|
||||
Start with the parent's question and references. Inspect only code, patterns, documentation, and constraints needed to answer it; expand when evidence requires it. Return conclusions, concrete references, and unknowns using the shared orchestration handoff protocol. Avoid modifying implementation code by default.
|
||||
|
||||
Use shell commands for inspection and required research tools, including semantic search and MCPorter.
|
||||
Use shell commands for inspection and required research tools, including semantic search (when installed) and MCPorter.
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
Provide static and semantic correctness review using the acceptance criteria and actual git diff. Inspect changed symbols first, then direct callers, dependencies, tests, and contracts needed to judge correctness. Expand for shared state, configuration, persistence, security, generated code, or public API effects; avoid broad repository exploration by default.
|
||||
|
||||
Use shell commands to inspect diffs and run required research tools, including semantic search and MCPorter. Do not run tests, builds, or runtime checks; reuse supplied execution evidence and report gaps to the parent or verifier.
|
||||
Use shell commands to inspect diffs and run required research tools, including semantic search (when installed) and MCPorter. Do not run tests, builds, or runtime checks; reuse supplied execution evidence and report gaps to the parent or verifier.
|
||||
|
||||
For each finding, report SEVERITY (blocking, important, or minor), LOCATION, IMPACT, EVIDENCE, and SCOPE (introduced, pre-existing, or uncertain). Do not report stylistic preferences or pre-existing issues unless they materially affect the requested change. Prioritize actionable correctness defects, keep unrelated cleanup out of scope, and use blocking only for security, data-loss, broken contracts, or deterministic failures.
|
||||
Run the review through `review-pull-request`: it owns the specialist list, severity scale, finding schema, and dedup rules. Do not report stylistic preferences, and keep unrelated cleanup out of scope.
|
||||
|
||||
Check logic, regressions, architecture, maintainability, security, and contract consistency. Follow the shared orchestration handoff protocol. Do not modify implementation code unless assigned.
|
||||
@@ -1,20 +1,20 @@
|
||||
# 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
|
||||
|
||||
Load rules just in time. First identify the changed area, languages, frameworks, tools, and security or workflow concerns from the task and nearby files. Then load only rules whose triggers match; never preload or recursively read the complete rules tree.
|
||||
|
||||
For Codex, read the listed rule path directly. For Claude, invoke the matching `rules-*` skill by its exact name. When a technology directory applies, load its index skill/file first, then load only the topic skills/files that match the work. An index is a small routing map, not a request to load every linked topic. Load cross-cutting rules independently when their stated trigger applies. If a needed rule is not listed or installed, continue with applicable rules and repository conventions.
|
||||
For Codex, read the listed rule path directly. For Claude, invoke the matching `rules-*` skill by its exact name. When a technology directory applies, load its index skill/file first, then load only the topic skills/files that match the work. Load cross-cutting rules independently when their stated trigger applies. If a needed rule is not listed or installed, continue with applicable rules and repository conventions.
|
||||
|
||||
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, webhooks, 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, URL fetching, proxies, TLS, SSRF => `network.md` / `rules-security-network`; cryptography, secrets, keys, credentials => `crypto.md` / `rules-security-crypto`; dependencies, packages, plugins, builds, containers, IaC, deployment, CI => `supply-chain.md` / `rules-security-supply-chain`; LLM calls, prompts, agents, tools, retrieval/RAG => `ai.md` / `rules-security-ai`; logging, audit, monitoring => `logging.md` / `rules-security-logging`; desktop or mobile client apps => `clients.md` / `rules-security-clients`; 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, Blazor, MAUI => `rules/csharp/index.md` / `rules-csharp`; 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`.
|
||||
|
||||
Cross-cutting: unclear requirements or significant choices => `rules/decision-rule.md` / `rules-decision-rule`; completion or review readiness => `rules/definition-of-done.md` / `rules-definition-of-done`; Git operations => `rules/git.md` / `rules-git`; Microsoft 365, Azure DevOps, Teams => `rules/microsoft.md` / `rules-microsoft`; delegation or long-running work => `rules/orchestration.md` / `rules-orchestration`; behavior-preserving refactors => `rules/refactoring.md` / `rules-refactoring`.
|
||||
Cross-cutting: unclear requirements or significant choices => `rules/decision-rule.md` / `rules-decision-rule`; completion or review readiness => `rules/definition-of-done.md` / `rules-definition-of-done`; Git operations => `rules/git.md` / `rules-git`; Azure DevOps, Teams, Microsoft 365, SharePoint, SQL Server, Confluence, Grafana, or other connected remote systems => `rules/microsoft.md` / `rules-microsoft`; delegation or long-running work => `rules/orchestration.md` / `rules-orchestration`; behavior-preserving refactors => `rules/refactoring.md` / `rules-refactoring`.
|
||||
|
||||
## Tools and delegation
|
||||
|
||||
|
||||
@@ -2,10 +2,12 @@
|
||||
|
||||
This directory contains registered hooks and optional utilities. They do not bypass client permission prompts or grant access.
|
||||
|
||||
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. Both clients also register `PreCompact` (`Record-Compact`/`record-compact.sh`) and `SessionStart` (`Show-SessionStatePointer`/`show-session-state-pointer.sh`). Codex additionally registers `SessionStart` (`Show-CavemanMode`/`show-caveman-mode.sh`), which prints the installed Caveman skill so caveman style is always on, as the Claude plugin's own hook does. 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. The command-safety hook also runs the search reminder from `agent-guards.py` in the same process for shell commands, and Claude registers a second `PreToolUse` hook (`Show-SearchReminder`/`show-search-reminder.sh`) for `Grep` and `Glob`. The reminder asks the agent to run `semantic-search` before the first open search and again after every 10 open searches without `qmd-search.mjs`, which also covers context lost to compaction; it never blocks, stays silent while the session keeps using `qmd-search.mjs`, does nothing unless QMD is installed, and keeps only hashed per-session markers under `~/.my-ai-configuration/state/search-reminder/`.
|
||||
|
||||
`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.
|
||||
|
||||
Codex also registers `PostToolUse` (matcher `Edit|Write|apply_patch`) and `Stop` hooks for Impeccable's design detector (`Invoke-ImpeccableHook.ps1`/`invoke-impeccable-hook.sh`). The wrapper runs the installed Impeccable Codex skill's `impeccable hook` and is a no-op when that skill is missing. Claude receives the same hooks from the Impeccable plugin. The detector is on by default in every project; a project opts out with `impeccable hooks off`.
|
||||
@@ -5,12 +5,15 @@ set -uo pipefail
|
||||
# Python's standard tkinter module because Bash itself cannot create windows.
|
||||
# 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'
|
||||
exit 0
|
||||
fi
|
||||
|
||||
python3 - "$@" 2>/dev/null <<'PY' || exit 0
|
||||
run_python - "$@" 2>/dev/null <<'PY' || exit 0
|
||||
import argparse
|
||||
import re
|
||||
import shutil
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
[CmdletBinding()]
|
||||
param()
|
||||
# Best effort: without Python 3.11+ this hook is a silent no-op; doctor reports that case.
|
||||
try {
|
||||
$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 {}
|
||||
exit 0
|
||||
@@ -0,0 +1,13 @@
|
||||
# Codex PostToolUse/Stop: run the Impeccable design detector when its Codex skill is installed; otherwise a no-op.
|
||||
# Claude receives the same hooks from the Impeccable plugin. Projects can still opt out with `impeccable hooks off`.
|
||||
$codexHome = if ($env:CODEX_HOME) { $env:CODEX_HOME } else { Join-Path $HOME '.codex' }
|
||||
$windows = $env:OS -eq 'Windows_NT'
|
||||
foreach ($skill in @((Join-Path $HOME '.agents/skills/impeccable'), (Join-Path $codexHome 'skills/impeccable'))) {
|
||||
$launcher = Join-Path $skill $(if ($windows) { 'scripts/impeccable.cmd' } else { 'scripts/impeccable' })
|
||||
if (-not (Test-Path -LiteralPath $launcher -PathType Leaf)) { continue }
|
||||
# The hook reply carries non-ASCII text; Windows PowerShell would otherwise decode it with the OEM code page.
|
||||
[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)
|
||||
if ($windows) { & $launcher hook } else { & sh $launcher hook }
|
||||
exit $LASTEXITCODE
|
||||
}
|
||||
exit 0
|
||||
@@ -10,6 +10,8 @@ try {
|
||||
('{"event":"compact","timestamp":"' + (Get-Date).ToUniversalTime().ToString('o') + '"}') | Add-Content $path
|
||||
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 {}
|
||||
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
|
||||
}
|
||||
Loaded 100 of 306 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user