Compare commits

...
24 Commits
Author SHA1 Message Date
fraujulianandClaude Opus 5.5 d4f76fb132 fix(credentials): prompt for client when -Client is omitted
CI / CI configuration security checks (push) Successful in 4s
CI / Capabilities and shell quality (push) Successful in 12s
CI / Python tests and compilation (push) Successful in 31s
CI / QMD unit tests (push) Successful in 7s
CI / Build and inspect generated packages (push) Successful in 25s
CI / PowerShell tests on Ubuntu (push) Successful in 1m41s
CI / Installed client configuration smoke tests (push) Successful in 1m8s
CI / Bash integration and installation guards (push) Successful in 1m39s
add-credentials.ps1 and remove-credentials.ps1 saved $Client and $Key
before dot-sourcing with-credential.ps1 and assigned them back
afterwards. Without -Client, that assignment put an empty string into
a ValidateSet variable, and the script stopped with ValidateSetFailure
before it could ask which client to use. with-credential.ps1 now uses
its own variable names, so the save-and-restore is no longer needed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 09:15:17 +01:00
fraujulianandClaude Opus 5.5 3725fe31ee fix(plugins): allow npm tarball fetches for plugin installs
npm 12 changed the default of allow-remote to none. Claude installs
npm plugin sources such as rea-agents from a registry tarball URL, so
`claude plugin install rea@rea` failed with EALLOWREMOTE. The client
commands now run with npm_config_allow_remote=all. root does not
cover this case. The setting applies only to these child processes,
and a value the user sets still takes precedence.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 09:05:24 +01:00
Julian LechnerandClaude Opus 5.5 2b2403e1de docs: add Roast Room to README and bring docs up to date
CI / CI configuration security checks (push) Successful in 3s
CI / Capabilities and shell quality (push) Successful in 11s
CI / Python tests and compilation (push) Successful in 31s
CI / QMD unit tests (push) Successful in 7s
CI / Build and inspect generated packages (push) Successful in 25s
CI / PowerShell tests on Ubuntu (push) Successful in 2m13s
CI / Installed client configuration smoke tests (push) Successful in 1m15s
CI / Bash integration and installation guards (push) Successful in 1m43s
The README now lists Roast Room as a feature and an extension, with its
Git and Node.js requirements. It also fixes the broken %APPDATA%\npm path
and describes the current skill catalog and Codex execpolicy rules.

The docs now match the code: Codex registers PreCompact and SessionStart
hooks, the command-safety hook and execpolicy lists include the new
blocked commands, the media skill has seven references, direct reads need
no research skill, and test-uninstall.py is listed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 10:02:46 +01:00
Julian LechnerandClaude Opus 5.5 a493658f41 chore(budget): raise Claude prompt budget baselines
CI / CI configuration security checks (push) Successful in 3s
CI / Capabilities and shell quality (push) Successful in 13s
CI / Python tests and compilation (push) Successful in 34s
CI / QMD unit tests (push) Successful in 8s
CI / Build and inspect generated packages (push) Successful in 24s
CI / PowerShell tests on Ubuntu (push) Successful in 1m5s
CI / Installed client configuration smoke tests (push) Successful in 40s
CI / Bash integration and installation guards (push) Successful in 1m34s
Rule skills now use their opening "Apply ..." sentence as description
and agents list preloaded skills, which grows Claude metadata on
purpose. Total permanent context stays well under the 10000 soft target.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 09:52:28 +01:00
Julian LechnerandClaude Opus 5.5 2917ad08ec test(packages): match single Codex PreToolUse hook and Skill agent tool
CI / CI configuration security checks (push) Successful in 2s
CI / Capabilities and shell quality (push) Successful in 14s
CI / Python tests and compilation (push) Successful in 34s
CI / QMD unit tests (push) Successful in 6s
CI / Build and inspect generated packages (push) Successful in 25s
CI / PowerShell tests on Ubuntu (push) Successful in 1m14s
CI / Installed client configuration smoke tests (push) Successful in 40s
CI / Bash integration and installation guards (push) Failing after 1m19s
The search reminder now runs inside the command-safety hook, and agent
capability profiles include Skill. Update the generated-package checks
to expect both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 08:04:24 +01:00
Julian LechnerandClaude Opus 5.5 bdf32bb6bd fix(build): avoid SIGPIPE exits and ruff E731 failure
CI / CI configuration security checks (push) Successful in 2s
CI / Capabilities and shell quality (push) Successful in 14s
CI / Python tests and compilation (push) Successful in 31s
CI / QMD unit tests (push) Successful in 7s
CI / Build and inspect generated packages (push) Successful in 19s
CI / PowerShell tests on Ubuntu (push) Failing after 1m7s
CI / Bash integration and installation guards (push) Failing after 17s
CI / Installed client configuration smoke tests (push) Successful in 33s
Piping sed/grep into `head -n 1` under `set -o pipefail` could kill the
writer with SIGPIPE and abort build.sh with exit 141. Quit inside
sed/awk instead. Rewrite the rmtree retry lambda as a def for ruff E731.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 14:36:59 +01:00
Julian Lechner c3e22eb902 corrections
CI / CI configuration security checks (push) Successful in 6s
CI / Python tests and compilation (push) Failing after 12s
CI / QMD unit tests (push) Skipped
CI / Capabilities and shell quality (push) Successful in 1m50s
CI / Build and inspect generated packages (push) Skipped
CI / Bash integration and installation guards (push) Skipped
CI / Installed client configuration smoke tests (push) Skipped
CI / PowerShell tests on Ubuntu (push) Failing after 7m24s
2026-11-19 10:30:43 +01:00
Julian LechnerandClaude Opus 5.5 b35e2254b3 feat(extensions): add Roast Room, bring Codex to parity, fix audit findings
Roast Room is installed as a managed Git clone under
~/.my-ai-configuration/roast-room, shared by Claude and Codex. A personal
launcher skill runs it from any folder, starts its live room when needed,
and only runs when invoked by name (/roast-room, $roast-room).

Codex now gets what was Claude-only before: the Caveman skill with a
SessionStart hook that keeps it on, PreCompact and session-pointer hooks,
execpolicy deny rules mirroring Claude's permissions.deny, and Impeccable's
custom agents registered in ~/.codex/agents. The command-safety hook checks
both shell dialects for Codex on Windows, where PowerShell text arrives as
Bash, in both the PowerShell and Bash packages.

Audit fixes:
- command-safety blocks git checkout -- / restore / push --force /
  stash clear and find -delete, and treats heredoc bodies as text
- removing a clone clears read-only Git files, git errors no longer abort
  the extension sync, and a lock left by a dead process is replaced
- with-credential passes child flags such as -k or -d through unchanged
  and resolves commands from PATH
- uninstall strips only owned hooks from settings.json and config.toml and
  keeps the selection while another client is installed; update keeps
  CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY; Bash merges write the same bytes as
  PowerShell
- qmd no longer trusts a stale daemon.json after a lost start race and
  prunes collections of deleted repositories
- Bash scripts avoid GNU-only find -printf

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 09:02:47 +01:00
Julian LechnerandClaude Opus 5.5 63a36d90e0 fix(hooks): close command-safety bypasses and credential helper output loss
The command-safety hook only checked the first word of each segment, so
destructive commands inside if/for/while blocks, subshells, braces,
PowerShell script blocks, or behind wrapper options (xargs -0, sudo -E,
timeout 30) ran unchecked. A comment with an apostrophe, an escaped quote,
or a line continuation also hid the following command. Skip shell
keywords, split on braces, drop comments, honor backslash escapes, join
continued lines, and check every suffix after a wrapper. CLI mode also
strips the byte order mark that Windows PowerShell 5.1 adds to piped
stdin, which let every command pass there.

with-credential.ps1 returned the child's exit code from a function, so
the child's stdout was captured and the exit code became 0. Run the child
as a statement and exit with its code. add-credentials now refreshes the
installed helper on every run so fixes reach existing machines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 08:00:18 +01:00
Julian Lechner f5d8f6f11b feat(skills): reworked skills and rules
CI / CI configuration security checks (push) Successful in 3s
CI / Capabilities and shell quality (push) Successful in 14s
CI / Python tests and compilation (push) Successful in 26s
CI / QMD unit tests (push) Successful in 5s
CI / Build and inspect generated packages (push) Successful in 14s
CI / PowerShell tests on Ubuntu (push) Successful in 1m4s
CI / Installed client configuration smoke tests (push) Successful in 33s
CI / Bash integration and installation guards (push) Successful in 1m1s
2026-11-18 14:17:49 +01:00
Julian LechnerandClaude Opus 5.5 29632ff0ce chore(rules): remove Java rules
Delete the Java and Spring rule set under shared/rules/java and its
routing entry in the global instructions. No other rule or skill
referenced it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 10:17:20 +01:00
Julian LechnerandClaude Opus 5.5 df09ddeaa9 docs(rules): add WPF accessibility and theming, trim WPF rules
A new WPF topic rule covers accessibility (AutomationProperties names
and help text, keyboard access, visible focus, high contrast through
SystemColors, automation peers for custom controls), DPI scaling in
device-independent units with tests across scale factors and monitors,
and the Fluent theme through ThemeMode on .NET 9 and later.

The existing WPF rules lose about a quarter of their size by merging
one-line generic bullets that the C# and shared rules already cover,
while keeping the WPF-specific pitfalls. Duplicate async void and
binding error guidance is merged, client secret handling defers to the
client app security rule, the architecture rule asks to check .NET
Framework versus .NET before using newer APIs, and the CommunityToolkit
note states that partial properties require C# 14.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 10:14:24 +01:00
Julian LechnerandClaude Opus 5.5 b6c33780c3 docs(rules): update TypeScript and Angular rules for TS 7 and trim duplicates
TypeScript 7.0 ships the native compiler as tsc and drops options
deprecated in 6.0. Angular 22 still requires TypeScript >=6.0.0 <6.1.0,
so both rule sets now warn against moving Angular projects to TS 7, and
the Angular index asks to check the Angular version first.

TypeScript runtime safety adds error handling (Error objects only,
cause chaining, unknown in catch, one error model per layer, no
swallowed errors) plus exact decimals for money, ISO 8601 UTC dates, and
Intl formatting. Angular adds per-route SSR render modes, a global
ErrorHandler with provideBrowserGlobalErrorListeners, and translatable
text with locale-aware formatting.

Generic guidance that the TypeScript, refactoring, and UI/UX rules
already cover is removed from the Angular rules, which shrink by about
7.5 percent despite the additions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 10:08:25 +01:00
Julian LechnerandClaude Opus 5.5 368cf5ee4a docs(security): add logging and client app rules, close coverage gaps
New focused rules: security logging and audit (events to log, log
injection, what never to log, tamper-evident audit trails) and desktop
and mobile client apps (shipped code is public, platform secret stores,
pinning with rotation, signed updates, WebView limits).

Existing rules gain inbound webhook verification in api, GDPR handling
of personal data in data, container and infrastructure-as-code
hardening in supply-chain, and post-quantum key establishment with
ML-KEM (FIPS 203) in a hybrid construction in crypto. Security testing
of a third-party or public target now needs one confirmation of
ownership or permission. Duplicate authorization bullets in auth and
api are merged, and webhook routing distinguishes inbound from outbound.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 10:03:44 +01:00
Julian LechnerandClaude Opus 5.5 ff33ea1327 docs(rules): add MAUI and Blazor rules, close C# gaps
New C# topic rules for .NET MAUI and Blazor, both centered on
performance and cross-platform reuse. MAUI covers compilation strategy
per platform (ReadyToRun, NativeAOT), trim and AOT safety, lean startup,
CollectionView and flat layouts, and per-platform conventions. Blazor
covers render mode cost, WebAssembly payload size and AOT trade-offs,
prerender state, rendering cost, and Razor class libraries shared across
web, WebAssembly, and Hybrid hosts. The C# index and global routing now
name both.

The existing C# rules gain the net11.0 default of C# 15, async void only
for event handlers, explicit StringComparison, invariant culture for
machine data, UTC or DateTimeOffset for stored times, ProblemDetails,
and ValidateOnStart. Duplicate authorization and raw SQL guidance in the
architecture rule is merged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 09:57:17 +01:00
Julian LechnerandClaude Opus 5.5 b74357b586 docs(rules): unify remote write approval and sharpen cross-cutting rules
The microsoft rule now covers every connected remote system: Azure
DevOps, Teams, SharePoint and Microsoft 365, SQL Server, Confluence,
Grafana, and other connectors. A direct request that names the action,
target, and content counts as confirmation. Deletions, irreversible and
bulk changes, and access changes always need confirmation. Database
writes show the statement and expected row count first. Definition of
Done now defers to this rule instead of contradicting it.

The decision rule adds how to ask, what to do when no one can answer,
and naming a concrete risk once before following a user decision.

Refactoring guidance is language neutral, Definition of Done accepts
documented shortcut: comments, and both point to the proportional
verification rule that actually exists.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 09:41:35 +01:00
Julian LechnerandClaude Opus 5.5 b8b4438275 fix(install): handle 8.3 source paths, bound plugin delegation, check skill contracts
Sync-ManagedDestination and Copy-Directory cut relative paths by the
length of $Source. With an 8.3 short path such as JULIAN~1, Get-ChildItem
returned long paths, so files landed under a truncated directory name.
Both now expand $Source with Get-Item first.

PowerShell tests now pass -ExecutionPolicy Bypass, tolerate non-UTF-8
console output, and give the Git Bash quick update 300 seconds.

The orchestration rule now covers plugin workflows. A plugin default
alone never authorizes subagents, per-task reviews stay proportional,
parallel writers get disjoint files, and plugin agents keep to their
specialty inside the shared handoff format.

doctor warns when an installed Impeccable or Apple Design skill no
longer names the commands and sections plugin-workflow relies on.
Prompt budget baselines are refreshed to the current values.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 09:31:00 +01:00
Julian LechnerandClaude Opus 5.5 abc9ae8e1b feat(plugins): add Apple Design and coordinate it with Impeccable
Install dickwu/apple-design-skill as a managed extension for Claude and
Codex. It has no Claude marketplace, so a manifest row with claude_plugin
"-" and codex_method "skill" now installs the skill payload into
~/.claude/skills as well. Updates fetch the latest upstream commit.

plugin-workflow runs Impeccable and Apple Design as one UI loop:
Impeccable leads direction and edits, Apple Design supplies cited
platform and accessibility constraints, and both feed one merged review.
A precedence list puts user instructions and project rules first.
Apple platform conventions apply only to Apple targets.

The UI/UX rules and the copy, marketing, image and WPF review skills now
point to the same roles. Topic rules allow bolder marketing surfaces,
prefer undo for reversible destructive actions, and prefer skeletons
inside content.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 08:56:04 +01:00
Julian LechnerandClaude Opus 5.5 53511937b0 fix(install): drop semantic-search leftovers when local search is off
CI / CI configuration security checks (push) Successful in 2s
CI / Capabilities and shell quality (push) Successful in 17s
CI / Python tests and compilation (push) Successful in 30s
CI / QMD unit tests (push) Successful in 5s
CI / Build and inspect generated packages (push) Successful in 17s
CI / PowerShell tests on Ubuntu (push) Successful in 1m25s
CI / Installed client configuration smoke tests (push) Successful in 48s
CI / Bash integration and installation guards (push) Successful in 1m10s
Disabling local QMD search now removes the qmd-search sandbox exclusion,
also from existing settings on update. Agent instructions mention semantic
search only as available when installed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 13:55:27 +01:00
Julian LechnerandClaude Opus 5.5 477e792f97 fix(rules): reply in the user's language, keep repository content English
CI / CI configuration security checks (push) Successful in 3s
CI / Capabilities and shell quality (push) Successful in 22s
CI / Python tests and compilation (push) Successful in 34s
CI / QMD unit tests (push) Successful in 7s
CI / Build and inspect generated packages (push) Successful in 17s
CI / PowerShell tests on Ubuntu (push) Successful in 1m8s
CI / Installed client configuration smoke tests (push) Successful in 34s
CI / Bash integration and installation guards (push) Successful in 1m10s
The general rule required all user-facing output in English, so agents
answered German prompts in English. Keep repository content in English
and write user-facing output in the user's language.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 13:13:13 +01:00
Julian LechnerandClaude Opus 5.5 305bcdeb54 feat(hooks): remind agents to use semantic search before open searches
CI / CI configuration security checks (push) Successful in 2s
CI / Capabilities and shell quality (push) Successful in 16s
CI / Python tests and compilation (push) Successful in 29s
CI / QMD unit tests (push) Successful in 5s
CI / Build and inspect generated packages (push) Successful in 17s
CI / PowerShell tests on Ubuntu (push) Successful in 1m10s
CI / Installed client configuration smoke tests (push) Successful in 34s
CI / Bash integration and installation guards (push) Successful in 1m9s
Add a PreToolUse hook (Show-SearchReminder/show-search-reminder.sh via
agent-guards.py) that, once per session, reminds the agent to run
semantic-search before the first open search. It fires on Grep/Glob and
on shell search commands, never blocks, stays silent once the session
ran qmd-search.mjs, and does nothing unless QMD is installed. Per-session
markers are hashed and pruned after seven days.

Claude matches Grep|Glob|Bash|PowerShell; Codex matches Bash.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 12:56:49 +01:00
Julian LechnerandClaude Opus 5.5 cb22d56539 fix(rules): trim always-loaded instructions under prompt budget
CI / CI configuration security checks (push) Successful in 4s
CI / Capabilities and shell quality (push) Successful in 11s
CI / Python tests and compilation (push) Successful in 25s
CI / QMD unit tests (push) Successful in 5s
CI / Build and inspect generated packages (push) Successful in 16s
CI / PowerShell tests on Ubuntu (push) Successful in 1m13s
CI / Installed client configuration smoke tests (push) Successful in 38s
CI / Bash integration and installation guards (push) Successful in 1m14s
Instruction tokens rose to 1883 against the 1837 limit (baseline 1670
+10%). Condense the Humanizer and plugin-workflow lines in the general
rules and drop a redundant index sentence from the global instructions;
the generated instruction files now measure 1828 tokens.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 12:24:11 +01:00
Julian LechnerandClaude Opus 5.5 20fcb9ea5b fix(plugins): detect extensionless npm global CLIs on Unix
CI / CI configuration security checks (push) Successful in 3s
CI / Capabilities and shell quality (push) Successful in 13s
CI / Python tests and compilation (push) Successful in 25s
CI / QMD unit tests (push) Successful in 5s
CI / Build and inspect generated packages (push) Successful in 18s
CI / PowerShell tests on Ubuntu (push) Successful in 1m11s
CI / Installed client configuration smoke tests (push) Successful in 39s
CI / Bash integration and installation guards (push) Failing after 59s
Test-CliCommand cast the matching suffix to bool. On Unix the only match
is the empty suffix '', which [bool] treats as false, so CLIs such as
MCPorter in the npm global prefix were never detected. Count matches
instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 12:20:07 +01:00
Julian LechnerandClaude Opus 5.5 49636323f0 fix(ci): accept QMD sandbox exclusion and satisfy ruff E731
CI / CI configuration security checks (push) Successful in 3s
CI / Capabilities and shell quality (push) Successful in 13s
CI / Python tests and compilation (push) Successful in 26s
CI / QMD unit tests (push) Successful in 5s
CI / Build and inspect generated packages (push) Successful in 18s
CI / PowerShell tests on Ubuntu (push) Failing after 51s
CI / Installed client configuration smoke tests (push) Canceled after 54s
CI / Bash integration and installation guards (push) Canceled after 55s
- validate-config: allow sandbox.excludedCommands only with the exact
  QMD search command, keeping the sandbox fail-closed
- shell package tests: expect the excludedCommands entry
- tests: replace assigned lambdas with functions (ruff E731)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 12:16:42 +01:00
247 changed files with 3231 additions and 8911 deletions

No files matched your search

+16 -11
View File
@@ -92,13 +92,18 @@ 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 - A managed-file manifest tracks unchanged and stale files. Replaced files are backed up; locally modified stale
files are retained with a warning. files are retained with a warning.
- Dry-run support (no destination writes, backups, or plugin changes) and timestamped backup directories. - 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, - 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 update refuses to run against one that is not installed yet, and uninstall refuses to run against one that was
never installed. never installed.
- User-level extension installation for Ponytail, i-have-adhd, Superpowers, Context7, Caveman (Claude only), MCPorter, - User-level extension installation for Ponytail, i-have-adhd, Superpowers, Context7, Caveman, MCPorter,
Humanizer, Impeccable, REA, and Modern Web Guidance, with an interactive extension toggle during both install and update. Only extensions Humanizer, Impeccable, Apple Design, REA, Modern Web Guidance, and Roast Room, with an interactive extension toggle
installed and recorded by this setup can be removed through deselection. 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). - 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 ## Requirements
@@ -107,8 +112,9 @@ Install and update also rebuild internally; the explicit build above lets you ch
- Bash 4.3 or newer, with standard utilities such as `awk`, `sed`, and `sha256sum`. - Bash 4.3 or newer, with standard utilities such as `awk`, `sed`, and `sha256sum`.
- Python 3.11 or newer for configuration validation and 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. - Python 3.11 or newer for configuration validation and the Python-based hooks and helpers. Scripts and hooks try `python`, `python3`, and the `py -3` launcher (Bash: `python3` first) and use the first one that actually runs Python 3.11+, so the Windows Store app execution alias is ignored. Without Python, build and capability checks stop with an actionable message, doctor reports a failure, and the registered Python-based hooks are skipped.
- `jq` for Claude's Bash status line; without it, that status line produces no output. - `jq` for Claude's Bash status line; without it, that status line produces no output.
- Node.js 22 or newer and `npm` when local QMD search or MCPorter is selected. npm's global bin directory (`npm prefix --global`; on Windows usually `%APPDATA% - 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.
pm`) 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 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 PowerShell, including when invoked through their Bash wrappers. The PowerShell scripts remain compatible with
@@ -234,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 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 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. 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 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.
conversion skills. 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, 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. 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. Dry runs preview changes without updating extensions or retrieval. See [Plugins](docs/plugins.md) for client-specific behavior.
@@ -304,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. 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 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 Codex's filesystem sandbox boundaries. Eligible approval requests still use automatic review, and execpolicy rules
automatic permissions and enables its sandbox where the platform supports it; explicit deny rules still apply where it forbid a few destructive Git and `rm` commands. Claude uses automatic permissions and enables its sandbox where the
does not. Both clients include the same logical agent roles and compact status displays. See 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. [Configuration](docs/configuration.md) for settings, permissions, and limitations.
## Support ## Support
+6 -6
View File
@@ -1,6 +1,6 @@
role tools role tools skills
architect Read,Grep,Glob,WebFetch,WebSearch,__SHELL_TOOL__ architect Read,Grep,Glob,WebFetch,WebSearch,__SHELL_TOOL__,Skill rules-orchestration
researcher Read,Grep,Glob,WebFetch,WebSearch,__SHELL_TOOL__ researcher Read,Grep,Glob,WebFetch,WebSearch,__SHELL_TOOL__,Skill rules-orchestration,research
reviewer Read,Grep,Glob,__SHELL_TOOL__ reviewer Read,Grep,Glob,__SHELL_TOOL__,Skill rules-orchestration,review-pull-request
verifier Read,Grep,Glob,__SHELL_TOOL__ verifier Read,Grep,Glob,__SHELL_TOOL__,Skill rules-orchestration
implementer Read,Grep,Glob,Edit,Write,__SHELL_TOOL__ implementer Read,Grep,Glob,Edit,Write,__SHELL_TOOL__,Skill rules-orchestration
1 role tools skills
2 architect Read,Grep,Glob,WebFetch,WebSearch,__SHELL_TOOL__ Read,Grep,Glob,WebFetch,WebSearch,__SHELL_TOOL__,Skill rules-orchestration
3 researcher Read,Grep,Glob,WebFetch,WebSearch,__SHELL_TOOL__ Read,Grep,Glob,WebFetch,WebSearch,__SHELL_TOOL__,Skill rules-orchestration,research
4 reviewer Read,Grep,Glob,__SHELL_TOOL__ Read,Grep,Glob,__SHELL_TOOL__,Skill rules-orchestration,review-pull-request
5 verifier Read,Grep,Glob,__SHELL_TOOL__ Read,Grep,Glob,__SHELL_TOOL__,Skill rules-orchestration
6 implementer Read,Grep,Glob,Edit,Write,__SHELL_TOOL__ Read,Grep,Glob,Edit,Write,__SHELL_TOOL__,Skill rules-orchestration
+4 -1
View File
@@ -15,7 +15,10 @@
"command": "__STATUSLINE_COMMAND__ \"__AI_CONFIG_ROOT__/statusline/__STATUSLINE_SCRIPT__\"" "command": "__STATUSLINE_COMMAND__ \"__AI_CONFIG_ROOT__/statusline/__STATUSLINE_SCRIPT__\""
}, },
"hooks": { "hooks": {
"PreToolUse": [{"matcher": "Bash|PowerShell", "hooks": [{"type": "command", "command": "__HOOK_COMMAND__ \"__AI_CONFIG_ROOT__/hooks/scripts/__COMMAND_SAFETY_SCRIPT__\"", "timeout": 6}]}], "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}]}], "PreCompact": [{"hooks": [{"type": "command", "command": "__HOOK_COMMAND__ \"__AI_CONFIG_ROOT__/hooks/scripts/__COMPACT_SCRIPT__\"", "timeout": 4}]}],
"SessionStart": [ "SessionStart": [
{"hooks": [{"type": "command", "command": "__HOOK_COMMAND__ \"__AI_CONFIG_ROOT__/hooks/scripts/__SESSION_POINTER_SCRIPT__\"", "timeout": 4}]}, {"hooks": [{"type": "command", "command": "__HOOK_COMMAND__ \"__AI_CONFIG_ROOT__/hooks/scripts/__SESSION_POINTER_SCRIPT__\"", "timeout": 4}]},
+1 -1
View File
@@ -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.
+26 -1
View File
@@ -42,11 +42,36 @@ command = '__HOOK_COMMAND__ "__AI_CONFIG_ROOT__/hooks/scripts/__QMD_WARM_SCRIPT_
command_windows = '__POWERSHELL_HOOK_COMMAND__ "__AI_CONFIG_ROOT__/hooks/scripts/__QMD_WARM_SCRIPT__"' command_windows = '__POWERSHELL_HOOK_COMMAND__ "__AI_CONFIG_ROOT__/hooks/scripts/__QMD_WARM_SCRIPT__"'
timeout = 4 timeout = 4
[[hooks.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]] [[hooks.PreToolUse]]
matcher = "Bash"
[[hooks.PreToolUse.hooks]] [[hooks.PreToolUse.hooks]]
type = "command" type = "command"
command = '__HOOK_COMMAND__ "__AI_CONFIG_ROOT__/hooks/scripts/__COMMAND_SAFETY_SCRIPT__"' command = '__HOOK_COMMAND__ "__AI_CONFIG_ROOT__/hooks/scripts/__COMMAND_SAFETY_SCRIPT__"'
command_windows = '__POWERSHELL_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 timeout = 6
# Impeccable's design detector; the wrapper is a no-op unless the Impeccable Codex skill is installed. # Impeccable's design detector; the wrapper is a no-op unless the Impeccable Codex skill is installed.
@@ -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.",
)
+2
View File
@@ -12,5 +12,7 @@ __CORRECTION_PROMPT_SCRIPT__ Show-CorrectionPrompt.ps1 show-correction-prompt.sh
__COMPLETION_EVIDENCE_SCRIPT__ Check-CompletionEvidence.ps1 check-completion-evidence.sh __COMPLETION_EVIDENCE_SCRIPT__ Check-CompletionEvidence.ps1 check-completion-evidence.sh
__COMMAND_SAFETY_SCRIPT__ Validate-CommandSafety.ps1 validate-command-safety.sh __COMMAND_SAFETY_SCRIPT__ Validate-CommandSafety.ps1 validate-command-safety.sh
__IMPECCABLE_HOOK_SCRIPT__ Invoke-ImpeccableHook.ps1 invoke-impeccable-hook.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 __SHELL_TOOL__ PowerShell Bash
__SCRIPT_EXTENSION__ ps1 sh __SCRIPT_EXTENSION__ ps1 sh
1 placeholder powershell bash
12 __COMPLETION_EVIDENCE_SCRIPT__ Check-CompletionEvidence.ps1 check-completion-evidence.sh
13 __COMMAND_SAFETY_SCRIPT__ Validate-CommandSafety.ps1 validate-command-safety.sh
14 __IMPECCABLE_HOOK_SCRIPT__ Invoke-ImpeccableHook.ps1 invoke-impeccable-hook.sh
15 __SEARCH_REMINDER_SCRIPT__ Show-SearchReminder.ps1 show-search-reminder.sh
16 __CAVEMAN_SCRIPT__ Show-CavemanMode.ps1 show-caveman-mode.sh
17 __SHELL_TOOL__ PowerShell Bash
18 __SCRIPT_EXTENSION__ ps1 sh
+3 -1
View File
@@ -3,9 +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 - - 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 - - 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 Context7 upstash/context7 context7@context7-marketplace upstash/context7 context7@context7-marketplace plugin - - context7 https://mcp.context7.com/mcp
Caveman JuliusBrussee/caveman caveman@caveman - - - - - Caveman JuliusBrussee/caveman caveman@caveman - - skill JuliusBrussee/caveman caveman
MCPorter - mcporter - mcporter cli mcporter - MCPorter - mcporter - mcporter cli mcporter -
Humanizer blader/humanizer humanizer@humanizer - - skill blader/humanizer humanizer Humanizer blader/humanizer humanizer@humanizer - - skill blader/humanizer humanizer
Impeccable pbakaus/impeccable impeccable@impeccable pbakaus/impeccable impeccable skill pbakaus/impeccable impeccable Impeccable pbakaus/impeccable impeccable@impeccable pbakaus/impeccable impeccable skill pbakaus/impeccable impeccable
REA morluto/rea rea@rea morluto/rea rea@rea plugin - - 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 - - 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
1 name claude_marketplace claude_plugin codex_marketplace codex_plugin codex_method codex_source codex_skill mcporter_name mcporter_url
3 i-have-adhd ayghri/i-have-adhd i-have-adhd@i-have-adhd ayghri/i-have-adhd i-have-adhd@i-have-adhd plugin - -
4 Superpowers anthropics/claude-plugins-official superpowers@claude-plugins-official openai-curated-remote superpowers@openai-curated-remote plugin - -
5 Context7 upstash/context7 context7@context7-marketplace upstash/context7 context7@context7-marketplace plugin - - context7 https://mcp.context7.com/mcp
6 Caveman JuliusBrussee/caveman caveman@caveman - - - skill - JuliusBrussee/caveman - caveman
7 MCPorter - mcporter - mcporter cli mcporter -
8 Humanizer blader/humanizer humanizer@humanizer - - skill blader/humanizer humanizer
9 Impeccable pbakaus/impeccable impeccable@impeccable pbakaus/impeccable impeccable skill pbakaus/impeccable impeccable
10 REA morluto/rea rea@rea morluto/rea rea@rea plugin - -
11 Modern Web Guidance GoogleChrome/modern-web-guidance modern-web-guidance@googlechrome GoogleChrome/modern-web-guidance modern-web-guidance@googlechrome plugin - -
12 Apple Design - - - - skill dickwu/apple-design-skill apple-design
13 Roast Room - - - - clone nateherkai/roast-room roast-room
+11 -11
View File
@@ -4,27 +4,27 @@
"permanent_context_hard_limit_tokens": 15000, "permanent_context_hard_limit_tokens": 15000,
"metrics": { "metrics": {
"permanent_context_tokens": { "permanent_context_tokens": {
"claude": 5959, "claude": 6808,
"codex": 4100 "codex": 4115
}, },
"instruction_tokens": { "instruction_tokens": {
"claude": 1670, "claude": 1883,
"codex": 1670 "codex": 1883
}, },
"skill_metadata_tokens": { "skill_metadata_tokens": {
"claude": 3354, "claude": 3885,
"codex": 1575 "codex": 1360
}, },
"auto_loaded_rule_tokens": { "auto_loaded_rule_tokens": {
"claude": 732, "claude": 789,
"codex": 731 "codex": 788
}, },
"rule_catalog_tokens": { "rule_catalog_tokens": {
"claude": 36519, "claude": 35779,
"codex": 8944 "codex": 9518
}, },
"agent_metadata_tokens": { "agent_metadata_tokens": {
"claude": 204, "claude": 261,
"codex": 124 "codex": 124
} }
} }
+11 -11
View File
@@ -1,13 +1,13 @@
metric client baseline_tokens metric client baseline_tokens
permanent_context_tokens claude 5959 permanent_context_tokens claude 6808
permanent_context_tokens codex 4100 permanent_context_tokens codex 4115
instruction_tokens claude 1670 instruction_tokens claude 1883
instruction_tokens codex 1670 instruction_tokens codex 1883
skill_metadata_tokens claude 3354 skill_metadata_tokens claude 3885
skill_metadata_tokens codex 1575 skill_metadata_tokens codex 1360
auto_loaded_rule_tokens claude 732 auto_loaded_rule_tokens claude 789
auto_loaded_rule_tokens codex 731 auto_loaded_rule_tokens codex 788
rule_catalog_tokens claude 36519 rule_catalog_tokens claude 35779
rule_catalog_tokens codex 8944 rule_catalog_tokens codex 9518
agent_metadata_tokens claude 204 agent_metadata_tokens claude 261
agent_metadata_tokens codex 124 agent_metadata_tokens codex 124
1 metric client baseline_tokens
2 permanent_context_tokens claude 5959 6808
3 permanent_context_tokens codex 4100 4115
4 instruction_tokens claude 1670 1883
5 instruction_tokens codex 1670 1883
6 skill_metadata_tokens claude 3354 3885
7 skill_metadata_tokens codex 1575 1360
8 auto_loaded_rule_tokens claude 732 789
9 auto_loaded_rule_tokens codex 731 788
10 rule_catalog_tokens claude 36519 35779
11 rule_catalog_tokens codex 8944 9518
12 agent_metadata_tokens claude 204 261
13 agent_metadata_tokens codex 124
+4 -2
View File
@@ -12,7 +12,7 @@ Use only the roles that are likely to improve the outcome. Choose `researcher`,
## Research tools ## 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. 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 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 ## 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. 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. 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.
+6 -3
View File
@@ -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`. Installation targets `~/.codex` and `~/.claude`; Codex skills go to `~/.agents/skills`.
Choose the PowerShell or Bash package independently of the client. 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`, It sets full access for commands, automatic approval review, `agents.enabled = true`,
`agents.max_concurrent_threads_per_session = 5`, and `agents.max_depth = 1`. `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; 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, 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 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 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 `CodexSandboxOnline` account, whose identity differs from the repository owner and can trigger Git's ownership
@@ -89,10 +91,11 @@ They stop a running QMD daemon first, so the next search uses the new scripts an
the setup installed is reinstalled at the tested version; a foreign installation of another version is kept 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. 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. 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, and JVM build files; the 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. 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 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. `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 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 `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. 100-document fixture; its measurements are not an end-to-end estimate for a user's repository.
+10 -6
View File
@@ -6,28 +6,32 @@ The adapters register these events:
| Client | Event | Action | | Client | Event | Action |
| --- | --- | --- | | --- | --- | --- |
| Codex and Claude | `PreToolUse` | Block clearly destructive shell commands (`Validate-CommandSafety`/`validate-command-safety.sh`); Claude matches the `Bash` and `PowerShell` tools. | | Codex and Claude | `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` | Run the finish notification (`flashbang`). |
| Codex and Claude | `Stop` | Push back once on an unbacked completion claim (`Check-CompletionEvidence`/`check-completion-evidence.sh`). | | Codex and Claude | `Stop` | Push back once on an unbacked completion claim (`Check-CompletionEvidence`/`check-completion-evidence.sh`). |
| Codex and Claude | `UserPromptSubmit` | Ask the agent to propose a durable rule when a prompt looks like a correction (`Show-CorrectionPrompt`/`show-correction-prompt.sh`). | | Codex and Claude | `UserPromptSubmit` | Ask the agent to propose a durable rule when a prompt looks like a correction (`Show-CorrectionPrompt`/`show-correction-prompt.sh`). |
| Claude | `PreCompact` | Record the compaction timestamp under the installed configuration root and point to existing workspace task state. | | Codex and 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 | `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). | | 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 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. 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. 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`. The completion hook blocks a stop only when the last message claims completion, names no check, and the Git working tree has non-prose changes. It uses the message wording, not command output, so it is a nudge rather than proof, and it never blocks twice in a row. The correction hook matches German and English phrases, adds a fixed instruction, and stores nothing; it skips slash commands and prompts over 2,000 characters. Rules change only after user approval. Both hooks need Python and fail open. Codex skips new or changed hooks until they are trusted through `/hooks`.
The command-safety hook parses the command (quote-aware splitting on `;`, `&&`, `||`, `|`, and newlines; nested `bash -c`, `pwsh -Command`, `cmd /c`, and `eval`) and exits 2 with a reason for `rm` with recursive and force flags in any order, `git reset --hard`, `git clean -f`, `Remove-Item -Recurse` (including `ri` and, outside Bash, the `rm`/`del`/`rd` aliases), `del`/`rd /s /q`, and `format <drive>:`. The logic lives once in `command-safety.py`; the shell wrappers only resolve Python. Called with a command argument (`-Command`/first argument), the wrappers check that command and also reject absolute paths outside the workspace. Like the client deny rules, the hook is a guard rail against accidents, not a security boundary: it sees only command text, not what scripts, aliases, or variables expand to, and it fails open on unparsable input or missing Python. The 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.
The Claude `permissions.deny` patterns (`Bash(rm -rf*)`, `PowerShell(Remove-Item *-Recurse*)`, and the `git reset --hard`/`git clean` patterns) match only the literal command prefix. They do not catch `rm -fr`, `rm -r -f`, or a destructive command after `cd x &&`; the PreToolUse hook covers those variants. Treat both layers as hurdles, and rely on the sandbox, approvals, and version control for real protection. 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. `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. All Python-based hooks find their interpreter through `Resolve-Python.ps1`/`resolve-python.sh`, which skip PATH entries that cannot run Python 3.11+ (such as the Windows Store alias). Without Python these hooks are skipped silently; `doctor` reports that case as a failure.
`Test-SessionConfig`/`test-session-config.sh` checks required repository inputs and is called by the build. Build and doctor do not execute the registered notification or session-state hooks. Claude's status line is a separate `statusLine` command, not a hook event. `Test-SessionConfig`/`test-session-config.sh` checks required repository inputs and is called by the build. Build and doctor do not execute the registered notification or session-state hooks. Claude's status line is a separate `statusLine` command, not a hook event. 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).
+6 -4
View File
@@ -2,13 +2,13 @@
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 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 (Claude only), MCPorter, Humanizer, Impeccable, REA, and Modern Web Guidance. 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 ### 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, 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. Because prose-only tasks skip `plugin-workflow`, the general rules themselves 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 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. In addition, when i-have-adhd is selected, install and update create its opt-in flag `.i-have-adhd-always` in the Claude configuration directory (`CLAUDE_CONFIG_DIR`, default `~/.claude`), so the plugin's SessionStart hook injects the full ruleset into every session. Deselecting the plugin leaves the flag in place; it has no effect without the plugin, and deleting it turns 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. 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 (Reverse Engineer Anything)
@@ -47,7 +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'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.
Caveman is installed for Claude only: 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. 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. 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. 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.
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 ### Setup options outside the extension selector
+5 -1
View File
@@ -63,12 +63,14 @@ On Windows, an unavailable profile-folder lookup falls back to PowerShell's home
| `tests/test-build-validation.ps1`, `tests/test-build-validation.sh` | Validate build failures and generated output. | | `tests/test-build-validation.ps1`, `tests/test-build-validation.sh` | Validate build failures and generated output. |
| `tests/test-capabilities.ps1`, `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-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-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-command-safety.py` | Validate the command-safety hook: destructive Bash, PowerShell, and cmd variants are blocked, ordinary commands pass, unusable input fails open, and both shell wrappers pass stdin and exit codes through. |
| `tests/test-install-guards.ps1`, `tests/test-install-guards.sh` | Validate install and update guard conditions. | | `tests/test-install-guards.ps1`, `tests/test-install-guards.sh` | Validate install and update guard conditions. |
| `tests/test-config-effects.py` | Check that generated limits and permissions take effect: Codex keeps the V1 multi-agent implementation that honors `agents.max_depth`; with `AI_CONFIG_LIVE_TESTS=1`, short Haiku sessions confirm that Claude withholds the Agent tool from subagents, refuses subagents above the concurrency limit, and blocks `git reset --hard` in every shell tool. | | `tests/test-config-effects.py` | Check that generated limits and permissions take effect: Codex keeps the V1 multi-agent implementation that honors `agents.max_depth`; with `AI_CONFIG_LIVE_TESTS=1`, short Haiku sessions confirm that Claude withholds the Agent tool from subagents, refuses subagents above the concurrency limit, and blocks `git reset --hard` in every shell tool. |
| `tests/test-client-smoke.py` | Install a package into a temporary home with foreign settings and ask the installed Claude and Codex CLIs which skills, agents, and hooks they discover, without completing a model request. Skips a client whose CLI is unavailable unless `AI_CONFIG_REQUIRE_CLIENTS=1`, which the CI `client-smoke` job sets. | | `tests/test-client-smoke.py` | Install a package into a temporary home with foreign settings and ask the installed Claude and Codex CLIs which skills, agents, and hooks they discover, without completing a model request. Skips a client whose CLI is unavailable unless `AI_CONFIG_REQUIRE_CLIENTS=1`, which the CI `client-smoke` job sets. |
| `tests/test-install-options.py` | Validate interactive option handling and generated manifest changes. | | `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-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-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-plugin-selection.ps1`, `tests/test-plugin-selection.sh` | Validate plugin selection. |
| `tests/test-prompt-budget.py` | Validate prompt budget threshold evaluation. | | `tests/test-prompt-budget.py` | Validate prompt budget threshold evaluation. |
@@ -79,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-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-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-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-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-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-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-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-command-summaries.ps1`, `tests/test-command-summaries.sh` | Validate doctor, install, and update summary output. |
| `tests/test-telemetry.py` | Validate telemetry 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-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. | | `tests/test-user-customizations.py` | Validate user instruction overlays and credential helpers. |
@@ -152,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/selection-state.py` | Read and write Quickupdate state. |
| `lib/qmd.sh`, `lib/qmd.ps1` | Invoke local QMD search from the installation flow. | | `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/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. | | [`shared/qmd/`](../shared/qmd/) (repository root) | Installed QMD scripts: search CLI, daemon, warm-up, benchmark, and shared library. |
+10 -12
View File
@@ -4,24 +4,22 @@ Skills are reusable workflows. Rules are persistent constraints and agents are s
The current structure is organized by purpose: The current structure is organized by purpose:
- `planning/`: impact analysis and work-item definition - `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 - `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/`: security, performance, WPF, UI/UX, business, API, and EF Core reviews - `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, and integration-test writing - `implementation/`: SQL, unit-test, integration-test, and end-to-end or UI test writing
- `verification/`: facts and work-item verification - `diagnostics/`: read-only incident investigation from Grafana, Azure DevOps, and SQL Server evidence, and before/after performance measurement
- `git/`: pull request reviews - `work-items/`: work-item definition and verification, including Azure DevOps items (fact checking lives in `research`)
- `content-strategy/`, `copy-editing/`, `copywriting/`: planning, editing, and writing text - `extensions/`: launchers for managed extensions (currently `roast-room`, run only by name: `/roast-room` in Claude Code, `$roast-room` in Codex)
- `image/`: image assets, screenshots, SEO and performance, social-preview metadata, practical marketing workflows, design tools, and common mistakes - `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
- `site-architecture/`: website structure
- `marketing-psychology/`, `offers/`, `product-marketing/`, `cro/`: audience understanding, value framing, and conversion
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. 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, REA for reverse engineering, 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. 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. 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 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 `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. 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). 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. 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.
+13 -2
View File
@@ -12,11 +12,13 @@ from pathlib import Path
CLAUDE_TOP_LEVEL = {"permissions", "sandbox", "env", "statusLine", "hooks"} CLAUDE_TOP_LEVEL = {"permissions", "sandbox", "env", "statusLine", "hooks"}
CLAUDE_PERMISSION_KEYS = {"defaultMode", "allow", "deny"} 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_STATUS_LINE_KEYS = {"type", "command"}
CLAUDE_HOOK_KEYS = {"type", "command", "timeout"} CLAUDE_HOOK_KEYS = {"type", "command", "timeout"}
CLAUDE_PERMISSION_MODES = {"acceptEdits", "auto", "bypassPermissions", "default", "dontAsk", "plan"} 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: def fail(message: str) -> None:
@@ -42,6 +44,7 @@ def validate_claude(path: Path) -> None:
fail(f"permissions.{key} must be an array of strings") fail(f"permissions.{key} must be an array of strings")
sandbox = require_keys(settings.get("sandbox"), CLAUDE_SANDBOX_KEYS, "sandbox") sandbox = require_keys(settings.get("sandbox"), CLAUDE_SANDBOX_KEYS, "sandbox")
if sandbox != {"enabled": False} and sandbox != {"enabled": True, "allowUnsandboxedCommands": False, "failIfUnavailable": True, if sandbox != {"enabled": False} and sandbox != {"enabled": True, "allowUnsandboxedCommands": False, "failIfUnavailable": True,
"excludedCommands": CLAUDE_SANDBOX_EXCLUDED,
"network": {"allowedDomains": ["mcp.context7.com"]}}: "network": {"allowedDomains": ["mcp.context7.com"]}}:
fail("sandbox must be disabled or enabled with fail-closed settings") fail("sandbox must be disabled or enabled with fail-closed settings")
env = settings.get("env") env = settings.get("env")
@@ -88,6 +91,14 @@ def validate_agent_tools(package: Path) -> None:
unknown = [tool for tool in tools if tool not in CLAUDE_VALID_TOOLS] unknown = [tool for tool in tools if tool not in CLAUDE_VALID_TOOLS]
if unknown: if unknown:
fail(f"{path}: unknown Claude tool name(s): {', '.join(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_PATH = re.compile(r"`(rules/[A-Za-z0-9_./-]+\.md)`")
+2 -6
View File
@@ -8,11 +8,7 @@ param(
$ErrorActionPreference = 'Stop' $ErrorActionPreference = 'Stop'
$root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent $root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
. (Join-Path $root 'scripts/lib/install-targets.ps1') . (Join-Path $root 'scripts/lib/install-targets.ps1')
$selectedClient = $Client
$selectedKey = $Key
. (Join-Path $root 'scripts/lib/with-credential.ps1') . (Join-Path $root 'scripts/lib/with-credential.ps1')
$Client = $selectedClient
$Key = $selectedKey
if (-not $Client) { $Client = Read-InstallClient -Client $Client } if (-not $Client) { $Client = Read-InstallClient -Client $Client }
if (-not $Key) { $Key = Read-Host 'Credential key' } if (-not $Key) { $Key = Read-Host 'Credential key' }
@@ -29,8 +25,8 @@ if ($ValueFromStdin) {
$bin = Join-Path $HomePath '.my-ai-configuration/bin' $bin = Join-Path $HomePath '.my-ai-configuration/bin'
New-Item -ItemType Directory -Path $bin -Force | Out-Null New-Item -ItemType Directory -Path $bin -Force | Out-Null
foreach ($source in @('with-credential.ps1', 'with-credential.sh')) { foreach ($source in @('with-credential.ps1', 'with-credential.sh')) {
$destination = Join-Path $bin $source # Always refresh so fixes to the helper reach machines that already have it.
if (-not (Test-Path -LiteralPath $destination)) { Copy-Item (Join-Path $root "scripts/lib/$source") $destination } 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) })) { foreach ($target in $(if ($Client -eq 'Both') { @('Codex', 'Claude') } else { @($Client) })) {
Set-ManagedCredential $target $Key $Value Set-ManagedCredential $target $Key $Value
+14
View File
@@ -51,9 +51,12 @@ foreach ($pluginEntry in $pluginEntries) {
if (-not (Test-Path -LiteralPath $capabilityManifest)) { throw "Missing capability manifest: $capabilityManifest" } if (-not (Test-Path -LiteralPath $capabilityManifest)) { throw "Missing capability manifest: $capabilityManifest" }
$agentTools = @{} $agentTools = @{}
$agentSkills = @{}
foreach ($entry in @(Import-Csv -LiteralPath $capabilityManifest -Delimiter ([char]9))) { 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.' } if ([string]::IsNullOrWhiteSpace($entry.role) -or [string]::IsNullOrWhiteSpace($entry.tools)) { throw 'Invalid capability manifest row.' }
$agentTools[$entry.role] = $entry.tools $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 # Build into a private sibling directory and swap it into place only after validation, so a failed
@@ -69,6 +72,7 @@ New-Item $output -ItemType Directory | Out-Null
function Copy-Directory($source, $destination) { function Copy-Directory($source, $destination) {
New-Item $destination -ItemType Directory -Force | Out-Null 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 { Get-ChildItem $source -File -Recurse | ForEach-Object {
$relative = $_.FullName.Substring($source.Length).TrimStart([char[]]@('\','/')) $relative = $_.FullName.Substring($source.Length).TrimStart([char[]]@('\','/'))
$target = Join-Path $destination $relative $target = Join-Path $destination $relative
@@ -170,7 +174,14 @@ foreach ($shell in @('powershell','bash')) {
$ruleContent = Get-Content $ruleSkill.Body -Raw $ruleContent = Get-Content $ruleSkill.Body -Raw
$ruleTitle = (Get-Content $ruleSkill.Body | Where-Object { $_ -match '^#+\s+' } | Select-Object -First 1) -replace '^#+\s+', '' $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)" } 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." $ruleDescription = "Use when the task concerns $ruleTitle."
}
$skillBody = "---`r`nname: $($ruleSkill.Name)`r`ndescription: $(Quote-Toml $ruleDescription)`r`n---`r`n`r`n$ruleContent" $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 Set-Content (Join-Path $skillDir 'SKILL.md') $skillBody -Encoding UTF8
if ($ruleSkill.References -and (Test-Path -LiteralPath $ruleSkill.References)) { if ($ruleSkill.References -and (Test-Path -LiteralPath $ruleSkill.References)) {
@@ -185,6 +196,8 @@ foreach ($shell in @('powershell','bash')) {
Set-Content (Join-Path $output "claude-$shell/CLAUDE.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 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 Copy-Item (Join-Path $root 'adapters/claude/config/settings.json') (Join-Path $output "claude-$shell/settings.json") -Force
foreach ($client in @('codex','claude')) { foreach ($client in @('codex','claude')) {
@@ -203,6 +216,7 @@ foreach ($shell in @('powershell','bash')) {
if ($tools) { $tools = Expand-ShellPlaceholders $tools $shell } if ($tools) { $tools = Expand-ShellPlaceholders $tools $shell }
$frontmatter = "---`r`nname: $name`r`ndescription: $description`r`n" $frontmatter = "---`r`nname: $name`r`ndescription: $description`r`n"
if ($tools) { $frontmatter += "tools: $tools`r`n" } if ($tools) { $frontmatter += "tools: $tools`r`n" }
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 Set-Content (Join-Path $agentsOutput "$name.md") ($frontmatter + "---`r`n`r`n$instructions") -Encoding UTF8
} }
} }
+31 -8
View File
@@ -65,11 +65,13 @@ expand_shell_placeholders() {
[ -f "$plugin_manifest" ] || { printf 'Missing plugin manifest: %s\n' "$plugin_manifest" >&2; exit 1; } [ -f "$plugin_manifest" ] || { printf 'Missing plugin manifest: %s\n' "$plugin_manifest" >&2; exit 1; }
awk -F '\t' 'NR == 1 { next } NF == 0 { next } $1 == "" || $3 == "" || $6 == "" { print "Invalid plugin manifest row." > "/dev/stderr"; exit 1 } seen[$1]++ { print "Duplicate plugin name in manifest: " $1 > "/dev/stderr"; exit 1 }' "$plugin_manifest" awk -F '\t' 'NR == 1 { next } NF == 0 { next } $1 == "" || $3 == "" || $6 == "" { print "Invalid plugin manifest row." > "/dev/stderr"; exit 1 } seen[$1]++ { print "Duplicate plugin name in manifest: " $1 > "/dev/stderr"; exit 1 }' "$plugin_manifest"
[ -f "$capability_manifest" ] || { printf 'Missing capability manifest: %s\n' "$capability_manifest" >&2; exit 1; } [ -f "$capability_manifest" ] || { printf 'Missing capability manifest: %s\n' "$capability_manifest" >&2; exit 1; }
declare -A agent_tools declare -A agent_tools agent_skills
while IFS=$'\t' read -r role tools; do while IFS=$'\t' read -r role tools skills; do
[ "$role" != role ] || continue [ "$role" != role ] || continue
[ -n "$role" ] && [ -n "$tools" ] || { printf 'Invalid capability manifest row.\n' >&2; exit 1; } [ -n "$role" ] && [ -n "$tools" ] || { printf 'Invalid capability manifest row.\n' >&2; exit 1; }
agent_tools[$role]="$tools" agent_tools[$role]="$tools"
# Optional: skills whose full content Claude preloads into the subagent at startup.
agent_skills[$role]="${skills:-}"
done < "$capability_manifest" done < "$capability_manifest"
copy_directory() { copy_directory() {
@@ -80,7 +82,8 @@ copy_directory() {
read_field() { read_field() {
local path=$1 name=$2 value 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; } [ -n "$value" ] || { printf 'Missing %s in %s\n' "$name" "$path" >&2; exit 1; }
printf '%s' "$value" printf '%s' "$value"
} }
@@ -141,7 +144,7 @@ declare -A claude_skill_names=()
while IFS= read -r skill_file; do while IFS= read -r skill_file; do
skill_source=$(dirname -- "$skill_file") skill_source=$(dirname -- "$skill_file")
skill_name=$(basename -- "$skill_source") 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; } [ -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 claude_skill_names[$skill_name]=1
copy_directory "$skill_source" "$claude_skills/$skill_name" copy_directory "$skill_source" "$claude_skills/$skill_name"
@@ -176,14 +179,23 @@ while IFS= read -r rule_path; do
rule_skill_names[$skill_name]=1 rule_skill_names[$skill_name]=1
skill_dir="$claude_skills/$skill_name" skill_dir="$claude_skills/$skill_name"
mkdir -p "$skill_dir" 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 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" { 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 if [ -n "$references_dir" ] && [ -d "$references_dir" ]; then
copy_directory "$references_dir" "$skill_dir/references" copy_directory "$references_dir" "$skill_dir/references"
fi 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)
instructions_content=$(expand_shell_placeholders "$(<"$shared/global-instructions.md")" "$shell") instructions_content=$(expand_shell_placeholders "$(<"$shared/global-instructions.md")" "$shell")
general_content=$(<"$shared/rules/general.md") general_content=$(<"$shared/rules/general.md")
@@ -191,6 +203,8 @@ printf '%s\n\n---\n\n%s\n' "${instructions_content%$'\n'}" "$general_content" >
printf '%s\n\n---\n\n%s\n' "${instructions_content%$'\n'}" "$general_content" > "$output/claude-$shell/CLAUDE.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" 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" cp "$root/adapters/claude/config/settings.json" "$output/claude-$shell/settings.json"
for client in codex claude; do for client in codex claude; do
@@ -205,7 +219,16 @@ for client in codex claude; do
printf 'name = %s\ndescription = %s\ndeveloper_instructions = %s\n' "$(quote_toml "$name")" "$(quote_toml "$description")" "$(quote_toml "$instructions")" > "$agents_output/$name.toml" printf 'name = %s\ndescription = %s\ndeveloper_instructions = %s\n' "$(quote_toml "$name")" "$(quote_toml "$description")" "$(quote_toml "$instructions")" > "$agents_output/$name.toml"
else else
tools=$(expand_shell_placeholders "${agent_tools[$name]:-}" "$shell") tools=$(expand_shell_placeholders "${agent_tools[$name]:-}" "$shell")
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 {
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 fi
done done
done done
+4
View File
@@ -56,6 +56,10 @@ if ($python) {
$qmdChecks = Invoke-DoctorCommand -Command $python.Path -Arguments (@($python.Arguments) + @((Join-Path $root 'scripts/lib/qmd.py'), 'doctor', '--root', $root, '--home', $homePath)) $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 ' ')" } 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] } } } 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 $sourceAgentCount = @(Get-ChildItem (Join-Path $root 'shared/agents') -Directory -ErrorAction SilentlyContinue).Count
+8
View File
@@ -64,6 +64,14 @@ if resolve_python; then
else else
result WARN "QMD checks failed: ${qmd_output//$'\n'/ }" result WARN "QMD checks failed: ${qmd_output//$'\n'/ }"
fi 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 fi
source_agent_count=$(find "$root/shared/agents" -mindepth 1 -maxdepth 1 -type d 2>/dev/null | wc -l) source_agent_count=$(find "$root/shared/agents" -mindepth 1 -maxdepth 1 -type d 2>/dev/null | wc -l)
-4
View File
@@ -6,11 +6,7 @@ param(
$ErrorActionPreference = 'Stop' $ErrorActionPreference = 'Stop'
$root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent $root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
. (Join-Path $root 'scripts/lib/install-targets.ps1') . (Join-Path $root 'scripts/lib/install-targets.ps1')
$selectedClient = $Client
$selectedKey = $Key
. (Join-Path $root 'scripts/lib/with-credential.ps1') . (Join-Path $root 'scripts/lib/with-credential.ps1')
$Client = $selectedClient
$Key = $selectedKey
if (-not $Client) { $Client = Read-InstallClient -Client $Client } if (-not $Client) { $Client = Read-InstallClient -Client $Client }
if (-not $Key) { $Key = Read-Host 'Credential key to remove' } if (-not $Key) { $Key = Read-Host 'Credential key to remove' }
+1 -1
View File
@@ -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}') 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 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) 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" 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 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
+2 -1
View File
@@ -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 Sync-Qmd -RepositoryRoot $root -HomePath $homePath -Client $Client -Enabled $false -DryRun:$DryRun -Summary:$Summary
if (-not $DryRun) { 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) { if ($remaining.Count -eq 0) {
$configRoot = Join-Path $homePath '.my-ai-configuration' $configRoot = Join-Path $homePath '.my-ai-configuration'
$selectionPath = Join-Path $configRoot 'selection.json' $selectionPath = Join-Path $configRoot 'selection.json'
+3 -2
View File
@@ -79,9 +79,10 @@ sync_qmd "$root" "$client" "$home_path" false "$dry_run" false "$summary"
if [ "$dry_run" = false ]; then if [ "$dry_run" = false ]; then
remaining=0 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)) [ -f "$(manifest_path "${target_pair#*|}")" ] && remaining=$((remaining + 1))
done done < <(get_install_targets "$generated" "$home_path" bash both)
if [ "$remaining" -eq 0 ]; then if [ "$remaining" -eq 0 ]; then
config_root="$home_path/.my-ai-configuration" config_root="$home_path/.my-ai-configuration"
rm -f -- "$config_root/selection.json" rm -f -- "$config_root/selection.json"
+4 -1
View File
@@ -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/install-options.ps1')
. (Join-Path $root 'scripts/lib/qmd.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') $homePath = [Environment]::GetFolderPath('UserProfile')
if ($Quick) { if ($Quick) {
$saved = Read-UpdateSelection -HomePath $homePath -RepositoryRoot $root $saved = Read-UpdateSelection -HomePath $homePath -RepositoryRoot $root
@@ -51,7 +54,7 @@ $plugins = if ($Quick) {
foreach ($item in (Get-InstallTargets -Generated $generated -HomePath $homePath -Shell $shell -Client $Client)) { foreach ($item in (Get-InstallTargets -Generated $generated -HomePath $homePath -Shell $shell -Client $Client)) {
Sync-ManagedDestination -Source $item.Source -Destination $item.Destination -Stamp $stamp ` 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 Sync-Qmd -RepositoryRoot $root -HomePath $homePath -Client $Client -Enabled $options.semantic_retrieval -DryRun:$DryRun -Update -Summary:$Summary
+4 -1
View File
@@ -25,6 +25,9 @@ root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)
. "$root/scripts/lib/install-options.sh" . "$root/scripts/lib/install-options.sh"
. "$root/scripts/lib/qmd.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} home_path=${HOME:?HOME is required}
selected_plugins=() selected_plugins=()
deselected_plugins=() deselected_plugins=()
@@ -64,7 +67,7 @@ fi
while IFS='|' read -r source destination; do while IFS='|' read -r source destination; do
ai_config_root=$destination ai_config_root=$destination
command -v cygpath >/dev/null && ai_config_root=$(cygpath -m "$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") done < <(get_install_targets "$generated" "$home_path" "$shell" "$client")
sync_qmd "$root" "$client" "$home_path" "$semantic_retrieval" "$dry_run" true "$summary" sync_qmd "$root" "$client" "$home_path" "$semantic_retrieval" "$dry_run" true "$summary"
+75 -16
View File
@@ -9,7 +9,7 @@ from personal_instructions import CLIENT_FILES, render
# Hook scripts this configuration installs; merges replace these and keep any foreign hooks. # Hook scripts this configuration installs; merges replace these and keep any foreign hooks.
OWNED_HOOK_PATTERN = r'(?:flashbang|statusline|record-compact|session-state-pointer|qmd-warm|Start-QmdWarm|completion-?evidence|correction-?prompt|command-?safety|impeccable-?hook)\.(?:ps1|sh)' 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): def is_flashbang(hook):
@@ -58,6 +58,12 @@ def filter_options(path, flashbang_enabled=True, statusline_enabled=True, semant
settings['hooks']['SessionStart'] = remaining settings['hooks']['SessionStart'] = remaining
else: else:
settings.get('hooks', {}).pop('SessionStart', None) 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: if not statusline_enabled:
settings.pop('statusLine', None) settings.pop('statusLine', None)
return json.dumps(settings, indent=2, ensure_ascii=False) + '\n' return json.dumps(settings, indent=2, ensure_ascii=False) + '\n'
@@ -103,21 +109,9 @@ def filter_flashbang(path):
return filter_options(path, flashbang_enabled=False) return filter_options(path, flashbang_enabled=False)
def merge_json(current, managed): def without_owned_hooks(groups):
if not isinstance(current, dict) or not isinstance(managed, dict):
return managed
result = dict(current)
if 'statusLine' not in managed:
result.pop('statusLine', None)
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', 'PreToolUse'}:
groups = value.get(event, [])
old_groups = hooks.get(event, [])
if isinstance(groups, list) and isinstance(old_groups, list):
retained = [] retained = []
for group in old_groups: for group in groups:
if not isinstance(group, dict) or not isinstance(group.get('hooks'), list): if not isinstance(group, dict) or not isinstance(group.get('hooks'), list):
retained.append(group) retained.append(group)
continue continue
@@ -126,6 +120,32 @@ def merge_json(current, managed):
str(hook.get('command', '')) + str(hook.get('command_windows', '')), re.I))] str(hook.get('command', '')) + str(hook.get('command_windows', '')), re.I))]
if foreign: if foreign:
retained.append(dict(group, hooks=foreign)) retained.append(dict(group, hooks=foreign))
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', 'PreToolUse'}:
groups = value.get(event, [])
old_groups = hooks.get(event, [])
if isinstance(groups, list) and isinstance(old_groups, list):
retained = without_owned_hooks(old_groups)
merged = groups + [group for group in retained if group not in groups] merged = groups + [group for group in retained if group not in groups]
if merged: if merged:
hooks[event] = merged hooks[event] = merged
@@ -225,9 +245,46 @@ def merge_toml(current_text, managed_text, statusline_enabled=True):
return result 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__': if __name__ == '__main__':
parser = argparse.ArgumentParser() 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('--path', type=Path)
parser.add_argument('--current', type=Path) parser.add_argument('--current', type=Path)
parser.add_argument('--flashbang', choices=('true', 'false')) parser.add_argument('--flashbang', choices=('true', 'false'))
@@ -245,6 +302,8 @@ if __name__ == '__main__':
if args.destination and args.path.name in CLIENT_FILES.values(): 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) client = next(client for client, name in CLIENT_FILES.items() if name == args.path.name)
result = render(result, args.destination.parent, client) result = render(result, args.destination.parent, client)
elif args.action == 'strip':
result = strip_file(args.current)
else: else:
managed = args.managed.read_text(encoding='utf-8-sig') if args.managed else sys.stdin.buffer.read().decode('utf-8-sig') 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') current = args.current.read_text(encoding='utf-8-sig')
+153 -26
View File
@@ -83,6 +83,9 @@ def run_command(arguments, summary=False, home=None):
if executable is None: if executable is None:
raise ValueError(f'{arguments[0]} CLI is required to manage plugins.') raise ValueError(f'{arguments[0]} CLI is required to manage plugins.')
environment = os.environ.copy() 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: if home is not None:
environment.update(HOME=str(home), USERPROFILE=str(home), CODEX_HOME=str(home / '.codex'), CLAUDE_CONFIG_DIR=str(home / '.claude')) 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, result = subprocess.run([executable, *arguments[1:]], stdin=subprocess.DEVNULL,
@@ -193,7 +196,7 @@ class Manager:
raise ValueError('Invalid extension ownership ledger.') raise ValueError('Invalid extension ownership ledger.')
identities = set() identities = set()
for resource in self.state['resources']: 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.') raise ValueError('Invalid extension ownership record.')
if not isinstance(resource.get('name'), str) or not resource['name']: if not isinstance(resource.get('name'), str) or not resource['name']:
raise ValueError('Invalid extension ownership name.') raise ValueError('Invalid extension ownership name.')
@@ -208,7 +211,8 @@ class Manager:
raise ValueError('Invalid owned plugin source.') raise ValueError('Invalid owned plugin source.')
elif resource['kind'] == 'skill': elif resource['kind'] == 'skill':
directory = resource.get('directory', '') 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.') raise ValueError('Invalid owned skill directory.')
safe_path(self.home, directory) safe_path(self.home, directory)
if not isinstance(resource.get('files'), dict): if not isinstance(resource.get('files'), dict):
@@ -219,6 +223,13 @@ class Manager:
if not relative.startswith(directory + '/') or not re.fullmatch(r'[a-f0-9]{64}', value): if not relative.startswith(directory + '/') or not re.fullmatch(r'[a-f0-9]{64}', value):
raise ValueError('Invalid owned skill file record.') raise ValueError('Invalid owned skill file record.')
safe_path(self.home, relative) 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')): elif resource['kind'] == 'qmd' and (resource.get('package') != '@tobilu/qmd' or resource['client'] not in ('codex', 'shared')):
raise ValueError('Invalid owned QMD record.') raise ValueError('Invalid owned QMD record.')
elif resource['kind'] == 'cli' and not re.fullmatch(r'[a-z0-9@/_.-]+', resource.get('package', '')): elif resource['kind'] == 'cli' and not re.fullmatch(r'[a-z0-9@/_.-]+', resource.get('package', '')):
@@ -296,6 +307,14 @@ class Manager:
self.command(arguments) self.command(arguments)
self.cache[client].pop(selector, None) self.cache[client].pop(selector, None)
elif record['kind'] == 'skill': 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() empty_candidates = set()
for relative, expected in list(record['files'].items()): for relative, expected in list(record['files'].items()):
path = safe_path(self.home, relative) path = safe_path(self.home, relative)
@@ -325,6 +344,25 @@ class Manager:
pass pass
if record['files']: if record['files']:
return 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': elif record['kind'] == 'mcp':
self.command(['mcporter', '--config', str(self.home / '.mcporter/mcporter.json'), 'config', 'remove', record['server']]) self.command(['mcporter', '--config', str(self.home / '.mcporter/mcporter.json'), 'config', 'remove', record['server']])
else: else:
@@ -337,7 +375,11 @@ class Manager:
if entry['codex_method'] == 'cli': if entry['codex_method'] == 'cli':
self.ensure_cli(client, entry) self.ensure_cli(client, entry)
return 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' 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) record = next((r for r in self.state['resources'] if r['client'] == client and r['name'] == entry['name']), None)
selector = entry[client + '_plugin'] selector = entry[client + '_plugin']
@@ -351,7 +393,7 @@ class Manager:
print(f'DRYRUN ensure {client} {kind}: {entry["name"]}') print(f'DRYRUN ensure {client} {kind}: {entry["name"]}')
return return
if skill: if skill:
self.ensure_skill(entry, record) self.ensure_skill(client, entry, record)
return return
if not re.fullmatch(r'[A-Za-z0-9_.-]+@[A-Za-z0-9_.-]+', selector): if not re.fullmatch(r'[A-Za-z0-9_.-]+@[A-Za-z0-9_.-]+', selector):
raise ValueError('Invalid plugin selector.') raise ValueError('Invalid plugin selector.')
@@ -427,6 +469,42 @@ class Manager:
self.state['resources'].append(dict(client='shared', name=entry['name'], kind='cli', package=package, clients=[client])) self.state['resources'].append(dict(client='shared', name=entry['name'], kind='cli', package=package, clients=[client]))
self.save() self.save()
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 self.dry_run:
if not self.summary:
print(f'DRYRUN ensure {client} clone: {entry["name"]}')
return
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): def ensure_ponytail_mode(self):
# Same lookup as Ponytail's hooks/ponytail-config.js; PONYTAIL_DEFAULT_MODE still wins over this file. # Same lookup as Ponytail's hooks/ponytail-config.js; PONYTAIL_DEFAULT_MODE still wins over this file.
if os.environ.get('XDG_CONFIG_HOME'): if os.environ.get('XDG_CONFIG_HOME'):
@@ -454,19 +532,6 @@ class Manager:
config['defaultMode'] = PONYTAIL_MODE config['defaultMode'] = PONYTAIL_MODE
atomic_write(path, (json.dumps(config, indent=2) + '\n').encode('utf-8')) atomic_write(path, (json.dumps(config, indent=2) + '\n').encode('utf-8'))
def ensure_adhd_always_on(self):
# i-have-adhd's SessionStart hook injects its full ruleset only while this opt-in flag exists.
path = Path(os.environ.get('CLAUDE_CONFIG_DIR') or self.home / '.claude') / '.i-have-adhd-always'
if path.is_file() and not linked(path):
return
if self.dry_run:
if not self.summary:
print('DRYRUN enable i-have-adhd always-on mode')
return
if linked(path) or path.exists():
raise ValueError('i-have-adhd always-on flag path is a link or not a file.')
atomic_write(path, b'')
def ensure_mcporter(self, entry, clients): def ensure_mcporter(self, entry, clients):
server, url = entry['mcporter_name'], entry['mcporter_url'] server, url = entry['mcporter_name'], entry['mcporter_url']
if not re.fullmatch(r'[a-z0-9-]+', server) or not re.fullmatch(r'https://[^\s]+', url): if not re.fullmatch(r'[a-z0-9-]+', server) or not re.fullmatch(r'https://[^\s]+', url):
@@ -499,16 +564,16 @@ class Manager:
record.update(server=server, url=url) record.update(server=server, url=url)
self.save() self.save()
def ensure_skill(self, entry, record): def ensure_skill(self, client, entry, record):
skill = entry['codex_skill'] skill = entry['codex_skill']
if not re.fullmatch(r'[A-Za-z0-9_-]+', skill): if not re.fullmatch(r'[A-Za-z0-9_-]+', skill):
raise ValueError('Invalid skill name.') raise ValueError('Invalid skill name.')
directory = '.agents/skills/' + skill directory = ('.agents/skills/' if client == 'codex' else '.claude/skills/') + skill
target = self.home / directory 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 record is None and (target.exists() or target.is_symlink() or alternate.exists() or alternate.is_symlink()):
if not self.summary: if not self.summary:
print(f'PASS Preserving pre-existing Codex skill: {skill}') print(f'PASS Preserving pre-existing {client} skill: {skill}')
return return
target = safe_path(self.home, directory) target = safe_path(self.home, directory)
if record and record['directory'] != directory: if record and record['directory'] != directory:
@@ -522,7 +587,7 @@ class Manager:
_, files = fetched[:2] _, files = fetched[:2]
revision = fetched[2] if len(fetched) > 2 else None revision = fetched[2] if len(fetched) > 2 else None
if record is 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.state['resources'].append(record)
self.save() self.save()
record['complete'] = False record['complete'] = False
@@ -550,9 +615,33 @@ class Manager:
path.unlink(missing_ok=True) path.unlink(missing_ok=True)
del record['files'][relative] del record['files'][relative]
self.save() self.save()
if client == 'codex':
self.sync_skill_agents(record, files)
record['complete'] = True record['complete'] = True
self.save() 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'): def sync(self, entries, clients, selected, action='sync'):
self.normalize_global_records() self.normalize_global_records()
desired = {entry['name']: entry for entry in entries if entry['name'] in selected} desired = {entry['name']: entry for entry in entries if entry['name'] in selected}
@@ -581,13 +670,52 @@ class Manager:
self.ensure(client, entry) self.ensure(client, entry)
if 'Ponytail' in direct_entries: if 'Ponytail' in direct_entries:
self.ensure_ponytail_mode() self.ensure_ponytail_mode()
if 'i-have-adhd' in direct_entries:
self.ensure_adhd_always_on()
for entry in mcporter_entries.values(): for entry in mcporter_entries.values():
self.ensure_mcporter(entry, clients) self.ensure_mcporter(entry, clients)
print('EXTENSIONS: reconciliation complete' + (' (dry run)' if self.dry_run else '')) 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(): def main():
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument('action', choices=('sync', 'install', 'remove')) parser.add_argument('action', choices=('sync', 'install', 'remove'))
@@ -614,9 +742,8 @@ def main():
return return
lock = safe_path(manager.home, '.my-ai-configuration/extensions.lock') lock = safe_path(manager.home, '.my-ai-configuration/extensions.lock')
lock.parent.mkdir(parents=True, exist_ok=True) 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: try:
os.close(descriptor)
manager = Manager(args.home, args.dry_run, args.update, args.summary) manager = Manager(args.home, args.dry_run, args.update, args.summary)
manager.sync(entries, clients, selected, args.action) manager.sync(entries, clients, selected, args.action)
finally: finally:
+13 -2
View File
@@ -221,6 +221,8 @@ function Invoke-ManagedSync {
# Plan every change before writing anything, so the journal can describe the whole run. # Plan every change before writing anything, so the journal can describe the whole run.
$plan = New-Object System.Collections.ArrayList $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 { Get-ChildItem $Source -File -Recurse | ForEach-Object {
$relative = $_.FullName.Substring($Source.Length).TrimStart([char[]]@('\','/')).Replace('\','/') $relative = $_.FullName.Substring($Source.Length).TrimStart([char[]]@('\','/')).Replace('\','/')
if ((Split-Path $Destination -Leaf) -eq '.codex' -and $relative.StartsWith('skills/')) { return } if ((Split-Path $Destination -Leaf) -eq '.codex' -and $relative.StartsWith('skills/')) { return }
@@ -266,14 +268,23 @@ function Invoke-ManagedSync {
if (-not (Test-Path -LiteralPath $target)) { continue } if (-not (Test-Path -LiteralPath $target)) { continue }
# A stale file changed locally is backed up but kept; only an unmodified one is removed. # 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' } $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) { if (-not $DryRun) {
$journalEntries = @(foreach ($item in $plan) { $journalEntries = @(foreach ($item in $plan) {
switch ($item.Action) { switch ($item.Action) {
'CREATE' { [ordered]@{ path = $item.Relative; action = 'create'; sha256 = $item.Hash } } '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)" } } 'REMOVE' { [ordered]@{ path = $item.Relative; action = 'remove'; backup = "$Stamp/$($item.Relative)" } }
} }
}) })
+34 -13
View File
@@ -119,6 +119,16 @@ acquire_managed_lock() {
return 1 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: same arguments as run_managed_sync; holds the destination lock unless dry-running.
sync_managed_destination() { sync_managed_destination() {
[ "$7" != true ] || { run_managed_sync "$@"; return; } [ "$7" != true ] || { run_managed_sync "$@"; return; }
@@ -214,12 +224,12 @@ sys.stdout.buffer.write(("\n".join(lines) + "\n").encode("utf-8"))
content=${content%$'\034'} content=${content%$'\034'}
needs_sub=false needs_sub=false
if { [ "$flashbang_enabled" = false ] || [ "$statusline_enabled" = false ] || [ "$semantic_retrieval_enabled" = false ]; } && [[ "$relative" = settings.json || "$relative" = config.toml ]]; then if { [ "$flashbang_enabled" = false ] || [ "$statusline_enabled" = false ] || [ "$semantic_retrieval_enabled" = false ]; } && [[ "$relative" = settings.json || "$relative" = config.toml ]]; then
content=$(run_python "$(dirname -- "${BASH_SOURCE[0]}")/install-options.py" filter --path "$source_file" --flashbang "$flashbang_enabled" --statusline "$statusline_enabled" --semantic-retrieval "$semantic_retrieval_enabled" && printf '\034') || return content=$(run_install_options filter --path "$source_file" --flashbang "$flashbang_enabled" --statusline "$statusline_enabled" --semantic-retrieval "$semantic_retrieval_enabled" && printf '\034') || return
content=${content%$'\034'} content=${content%$'\034'}
needs_sub=true needs_sub=true
fi fi
if [[ "$relative" = CLAUDE.md || "$relative" = AGENTS.md ]] || { [ "$semantic_retrieval_enabled" = false ] && [ "$relative" = rules/general.md ]; }; then if [[ "$relative" = CLAUDE.md || "$relative" = AGENTS.md ]] || { [ "$semantic_retrieval_enabled" = false ] && [ "$relative" = rules/general.md ]; }; then
content=$(run_python "$(dirname -- "${BASH_SOURCE[0]}")/install-options.py" filter-instructions --path "$source_file" --destination "$destination" --semantic-retrieval "$semantic_retrieval_enabled" && printf '\034') || return content=$(run_install_options filter-instructions --path "$source_file" --destination "$destination" --semantic-retrieval "$semantic_retrieval_enabled" && printf '\034') || return
content=${content%$'\034'} content=${content%$'\034'}
needs_sub=true needs_sub=true
fi fi
@@ -236,13 +246,14 @@ sys.stdout.buffer.write(("\n".join(lines) + "\n").encode("utf-8"))
else else
new_hash=$(sha256_of_file "$source_file") new_hash=$(sha256_of_file "$source_file")
fi fi
if [ "$relative" = config.toml ] && [ -f "$target" ]; then if [[ "$relative" = config.toml || "$relative" = settings.json ]] && [ -f "$target" ]; then
content=$(printf '%s' "$content" | run_python "$(dirname -- "${BASH_SOURCE[0]}")/install-options.py" merge-toml --current "$target" --statusline "$statusline_enabled") || return local managed_file merge_action=merge-json
needs_sub=true [ "$relative" = settings.json ] || merge_action=merge-toml
new_hash=$(sha256_of_string "$content") managed_file=$(mktemp) || return 1
fi printf '%s' "$content" > "$managed_file" || { rm -f -- "$managed_file"; return 1; }
if [ "$relative" = settings.json ] && [ -f "$target" ]; then content=$(run_install_options "$merge_action" --current "$target" --managed "$managed_file" --statusline "$statusline_enabled" && printf '\034') || { rm -f -- "$managed_file"; return 1; }
content=$(printf '%s' "$content" | run_python "$(dirname -- "${BASH_SOURCE[0]}")/install-options.py" merge-json --current "$target") || return rm -f -- "$managed_file"
content=${content%$'\034'}
needs_sub=true needs_sub=true
new_hash=$(sha256_of_string "$content") new_hash=$(sha256_of_string "$content")
fi fi
@@ -265,10 +276,20 @@ sys.stdout.buffer.write(("\n".join(lines) + "\n").encode("utf-8"))
target=$(managed_target "$destination" "$relative") || return 1 target=$(managed_target "$destination" "$relative") || return 1
[ -f "$target" ] || continue [ -f "$target" ] || continue
# A stale file changed locally is backed up but kept; only an unmodified one is removed. # A stale file changed locally is backed up but kept; only an unmodified one is removed.
local stripped='' stripped_hash=''
action=KEEP action=KEEP
[ "$(sha256_of_file "$target")" != "${old_manifest[$relative]}" ] || action=REMOVE if [ "$(sha256_of_file "$target")" = "${old_manifest[$relative]}" ]; then
plan_relative+=("$relative"); plan_target+=("$target"); plan_action+=("$action"); plan_hash+=('') action=REMOVE
plan_source+=(''); plan_sub+=(false); plan_content+=('') 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 done
local index entry journal_content first_entry=true local index entry journal_content first_entry=true
@@ -279,7 +300,7 @@ sys.stdout.buffer.write(("\n".join(lines) + "\n").encode("utf-8"))
for index in "${!plan_action[@]}"; do for index in "${!plan_action[@]}"; do
case "${plan_action[$index]}" in case "${plan_action[$index]}" in
CREATE) entry=$(printf '{"path": %s, "action": "create", "sha256": "%s"}' "$(json_string "${plan_relative[$index]}")" "${plan_hash[$index]}") ;; 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]}")") ;; REMOVE) entry=$(printf '{"path": %s, "action": "remove", "backup": %s}' "$(json_string "${plan_relative[$index]}")" "$(json_string "$stamp/${plan_relative[$index]}")") ;;
*) continue ;; *) continue ;;
esac esac
+5 -1
View File
@@ -74,7 +74,8 @@ function Test-CliCommand {
$prefix = @(& npm prefix --global 2>$null | ForEach-Object { "$_".Trim() } | Where-Object { $_ }) | Select-Object -Last 1 $prefix = @(& npm prefix --global 2>$null | ForEach-Object { "$_".Trim() } | Where-Object { $_ }) | Select-Object -Last 1
if (-not $prefix) { return $false } if (-not $prefix) { return $false }
$directory = if ([Environment]::OSVersion.Platform -eq [PlatformID]::Win32NT) { $prefix } else { Join-Path $prefix 'bin' } $directory = if ([Environment]::OSVersion.Platform -eq [PlatformID]::Win32NT) { $prefix } else { Join-Path $prefix 'bin' }
return [bool](@('', '.cmd', '.exe', '.ps1') | Where-Object { Test-Path -LiteralPath (Join-Path $directory ($Name + $_)) -PathType Leaf }) # 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 { function Test-InstalledMCPServer {
@@ -133,6 +134,7 @@ function Select-ConfiguredPlugins {
$checked = @($toggleable | ForEach-Object { $checked = @($toggleable | ForEach-Object {
if ($Mode -eq 'Install') { $true; return } if ($Mode -eq 'Install') { $true; return }
if ($_.codex_method -eq 'cli') { return Test-CliCommand -Name $_.codex_source } 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 = $_ $entry = $_
$found = if ($entry.mcporter_name -and $entry.mcporter_url) { $found = if ($entry.mcporter_name -and $entry.mcporter_url) {
Test-InstalledMCPServer -HomePath $HomePath -Name $entry.mcporter_name -Url $entry.mcporter_url Test-InstalledMCPServer -HomePath $HomePath -Name $entry.mcporter_name -Url $entry.mcporter_url
@@ -142,6 +144,8 @@ function Select-ConfiguredPlugins {
$selector = if ($referenceClient -eq 'Claude') { $entry.claude_plugin } else { $entry.codex_plugin } $selector = if ($referenceClient -eq 'Claude') { $entry.claude_plugin } else { $entry.codex_plugin }
if ($referenceClient -eq 'Codex' -and $entry.codex_method -ne '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))) $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 { } else {
$idField = if ($referenceClient -eq 'Claude') { 'id' } else { 'pluginId' } $idField = if ($referenceClient -eq 'Claude') { 'id' } else { 'pluginId' }
$found = $found -or [bool](@($installed[$referenceClient] | Where-Object { $_.$idField -eq $selector }).Count) $found = $found -or [bool](@($installed[$referenceClient] | Where-Object { $_.$idField -eq $selector }).Count)
+6
View File
@@ -171,6 +171,10 @@ select_configured_plugins() {
if cli_installed "$(plugin_field "$root" "$name" codex_source)"; then checked+=(true); else checked+=(false); fi if cli_installed "$(plugin_field "$root" "$name" codex_source)"; then checked+=(true); else checked+=(false); fi
continue continue
fi 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 found=false
local mcporter_name mcporter_url status local mcporter_name mcporter_url status
mcporter_name=$(plugin_field "$root" "$name" mcporter_name) mcporter_name=$(plugin_field "$root" "$name" mcporter_name)
@@ -186,6 +190,8 @@ select_configured_plugins() {
local skill_name local skill_name
skill_name=$(plugin_field "$root" "$name" codex_skill) skill_name=$(plugin_field "$root" "$name" codex_skill)
{ [ -d "$HOME/.agents/skills/$skill_name" ] || [ -d "$HOME/.codex/skills/$skill_name" ]; } && found=true { [ -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 elif plugin_installed "$reference_client" "$selector"; then found=true
else else
status=$? status=$?
+48
View File
@@ -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()
+25 -12
View File
@@ -1,10 +1,19 @@
[CmdletBinding()] # Usage: with-credential.ps1 -Client <Codex|Claude> -Key <NAME> -FilePath <command> [child arguments...]
param( # No param() block: PowerShell would bind abbreviated child flags such as -k or -d to -Key or -Debug.
[ValidateSet('Codex', 'Claude')][string]$Client, # Only the exact names below are read; everything after the command goes to the child unchanged.
[string]$Key, # Own variable names: scripts that dot-source this file keep their own $Client and $Key.
[Parameter(Position = 2)][string]$FilePath, $credentialClient = $null
[Parameter(Position = 3, ValueFromRemainingArguments = $true)][string[]]$ArgumentList $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' $ErrorActionPreference = 'Stop'
@@ -106,20 +115,24 @@ function Remove-ManagedCredential {
function Invoke-WithManagedCredential { function Invoke-WithManagedCredential {
param([ValidateSet('Codex', 'Claude')][string]$Client, [string]$Key, [string]$FilePath, [string[]]$ArgumentList) param([ValidateSet('Codex', 'Claude')][string]$Client, [string]$Key, [string]$FilePath, [string[]]$ArgumentList)
Assert-CredentialKey $Key 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') $prior = [Environment]::GetEnvironmentVariable($Key, 'Process')
$value = Get-ManagedCredential $Client $Key $value = Get-ManagedCredential $Client $Key
try { try {
[Environment]::SetEnvironmentVariable($Key, $value, 'Process') [Environment]::SetEnvironmentVariable($Key, $value, 'Process')
# Output goes straight to the caller; returning a value here would capture the child's stdout.
& $FilePath @ArgumentList & $FilePath @ArgumentList
return $LASTEXITCODE
} finally { } finally {
[Environment]::SetEnvironmentVariable($Key, $prior, 'Process') [Environment]::SetEnvironmentVariable($Key, $prior, 'Process')
$value = $null $value = $null
} }
} }
if ($FilePath) { if ($childPath) {
if (-not $Client -or -not $Key) { throw 'Client and key are required.' } if (-not $credentialClient -or -not $credentialKey) { throw 'Client and key are required.' }
exit (Invoke-WithManagedCredential $Client $Key $FilePath $ArgumentList) Invoke-WithManagedCredential $credentialClient $credentialKey $childPath $childArguments
exit $LASTEXITCODE
} }
+76 -4
View File
@@ -1,4 +1,5 @@
import json import json
import os
from pathlib import Path from pathlib import Path
import shutil import shutil
import subprocess import subprocess
@@ -11,10 +12,10 @@ SCRIPTS = ROOT / 'shared/hooks/scripts'
GUARDS = SCRIPTS / 'agent-guards.py' 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) 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, 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 assert result.returncode == 0, result.stderr
return result.stdout return result.stdout
@@ -86,11 +87,80 @@ class CorrectionPromptTests(unittest.TestCase):
self.assertEqual(guard('prompt', event), '') 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): class EntryPointTests(unittest.TestCase):
def test_shell_entry_points(self): def test_shell_entry_points(self):
shells = (('powershell', shutil.which('pwsh') or shutil.which('powershell'), 0), ('bash', shutil.which('bash'), 1)) 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'), 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: for shell, executable, index in shells:
if not executable or (shell == 'bash' and sys.platform == 'win32'): if not executable or (shell == 'bash' and sys.platform == 'win32'):
continue continue
@@ -98,12 +168,14 @@ class EntryPointTests(unittest.TestCase):
workspace = Path(directory) workspace = Path(directory)
git(workspace, 'init', '--quiet') git(workspace, 'init', '--quiet')
(workspace / 'app.py').write_text('x = 1\n') (workspace / 'app.py').write_text('x = 1\n')
env = fake_home(directory)
for scripts, event, expected in names: for scripts, event, expected in names:
event = event or {'cwd': str(workspace), 'last_assistant_message': 'All done.'} event = event or {'cwd': str(workspace), 'last_assistant_message': 'All done.'}
script = str(SCRIPTS / scripts[index]) script = str(SCRIPTS / scripts[index])
command = ([executable, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', script] command = ([executable, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', script]
if shell == 'powershell' else [executable, 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.returncode, 0, result.stderr)
self.assertEqual(result.stderr, '') self.assertEqual(result.stderr, '')
self.assertIn(expected, json.loads(result.stdout) | json.loads(result.stdout).get('hookSpecificOutput', {})) self.assertIn(expected, json.loads(result.stdout) | json.loads(result.stdout).get('hookSpecificOutput', {}))
+7
View File
@@ -70,6 +70,13 @@ Test-BuildFails 'unknown Claude tool name in capability manifest' {
Set-Content $manifest $lines 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' { Test-BuildFails 'duplicate plugin name' {
param($copy) param($copy)
$manifest = Join-Path $copy 'adapters/plugins.tsv' $manifest = Join-Path $copy 'adapters/plugins.tsv'
+5
View File
@@ -71,6 +71,11 @@ mutate_invalid_tool_name() {
} }
test_build_fails 'unknown Claude tool name in capability manifest' 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() { mutate_duplicate_plugin() {
local manifest="$1/adapters/plugins.tsv" local manifest="$1/adapters/plugins.tsv"
sed -n '2p' "$manifest" >> "$manifest" sed -n '2p' "$manifest" >> "$manifest"
+63
View File
@@ -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()
+78 -2
View File
@@ -12,9 +12,10 @@ SCRIPTS = ROOT / 'shared/hooks/scripts'
SAFETY = SCRIPTS / 'command-safety.py' SAFETY = SCRIPTS / 'command-safety.py'
def hook(command, tool='Bash'): def hook(command, tool='Bash', shell=None):
payload = json.dumps({'hook_event_name': 'PreToolUse', 'tool_name': tool, 'tool_input': {'command': command}}) payload = json.dumps({'hook_event_name': 'PreToolUse', 'tool_name': tool, 'tool_input': {'command': command}})
return subprocess.run([sys.executable, str(SAFETY), '--hook'], input=payload, capture_output=True, 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) encoding='utf-8', timeout=20)
@@ -41,6 +42,51 @@ class HookTests(unittest.TestCase):
with self.subTest(command=command): with self.subTest(command=command):
self.assertBlocked(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): 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', 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"', 'Get-ChildItem x | Remove-Item -Recurse', 'git reset --hard', 'cmd /c "rd /s /q build"',
@@ -56,10 +102,37 @@ class HookTests(unittest.TestCase):
self.assertAllowed('Remove-Item build/file.txt', 'PowerShell') self.assertAllowed('Remove-Item build/file.txt', 'PowerShell')
self.assertAllowed('Remove-Item build -Recurse:$false', '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): def test_unknown_shell_checks_both_dialects(self):
self.assertBlocked('rm -r build', 'shell') self.assertBlocked('rm -r build', 'shell')
self.assertBlocked('rm -rf 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): def test_fails_open_on_unusable_input(self):
for payload in ('', 'not json', '[]', '{"tool_input": "rm -rf /"}', '{"tool_input": {"command": 5}}'): for payload in ('', 'not json', '[]', '{"tool_input": "rm -rf /"}', '{"tool_input": {"command": 5}}'):
with self.subTest(payload=payload): with self.subTest(payload=payload):
@@ -123,6 +196,9 @@ class WrapperTests(unittest.TestCase):
self.assertEqual(allowed.returncode, 0, allowed.stderr) self.assertEqual(allowed.returncode, 0, allowed.stderr)
cli = command + (['-Command', 'git reset --hard'] if name != 'bash' else ['git reset --hard']) cli = command + (['-Command', 'git reset --hard'] if name != 'bash' else ['git reset --hard'])
self.assertEqual(self.run_wrapper(cli).returncode, 1) 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__': if __name__ == '__main__':
+31 -6
View File
@@ -99,6 +99,29 @@ class InstallOptionsTests(unittest.TestCase):
commands = [hook['command'] for group in result['hooks']['SessionStart'] for hook in group['hooks']] 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"']) 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): def test_semantic_retrieval_disabled_removes_codex_session_hook(self):
with tempfile.TemporaryDirectory() as directory: with tempfile.TemporaryDirectory() as directory:
config = Path(directory) / 'config.toml' config = Path(directory) / 'config.toml'
@@ -114,7 +137,8 @@ class InstallOptionsTests(unittest.TestCase):
managed = managed.replace('__IMPECCABLE_HOOK_SCRIPT__', 'invoke-impeccable-hook.sh') managed = managed.replace('__IMPECCABLE_HOOK_SCRIPT__', 'invoke-impeccable-hook.sh')
merged = OPTIONS.merge_toml(OPTIONS.merge_toml('', managed), managed) merged = OPTIONS.merge_toml(OPTIONS.merge_toml('', managed), managed)
hooks = tomllib.loads(merged)['hooks'] hooks = tomllib.loads(merged)['hooks']
impeccable = lambda groups: [group for group in groups if 'impeccable-hook' in group['hooks'][0]['command']] 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(1, len(impeccable(hooks['PostToolUse'])))
self.assertEqual('Edit|Write|apply_patch', impeccable(hooks['PostToolUse'])[0]['matcher']) self.assertEqual('Edit|Write|apply_patch', impeccable(hooks['PostToolUse'])[0]['matcher'])
self.assertEqual(1, len(impeccable(hooks['Stop']))) self.assertEqual(1, len(impeccable(hooks['Stop'])))
@@ -131,7 +155,8 @@ class InstallOptionsTests(unittest.TestCase):
with self.subTest(shell=name), tempfile.TemporaryDirectory() as directory: with self.subTest(shell=name), tempfile.TemporaryDirectory() as directory:
home = Path(directory) home = Path(directory)
env = dict(os.environ, HOME=str(home), USERPROFILE=str(home), CODEX_HOME=str(home / '.codex')) env = dict(os.environ, HOME=str(home), USERPROFILE=str(home), CODEX_HOME=str(home / '.codex'))
run = lambda: subprocess.run([executable, *arguments, str(scripts / name)], input='{"event":1}', def run():
return subprocess.run([executable, *arguments, str(scripts / name)], input='{"event":1}',
env=env, capture_output=True, text=True, timeout=60) env=env, capture_output=True, text=True, timeout=60)
result = run() result = run()
self.assertEqual((0, ''), (result.returncode, result.stdout), result.stderr) self.assertEqual((0, ''), (result.returncode, result.stdout), result.stderr)
@@ -228,7 +253,7 @@ class InstallOptionsTests(unittest.TestCase):
environment = dict(os.environ, OPTION_SOURCE=str(source), OPTION_DESTINATION=str(destination)) environment = dict(os.environ, OPTION_SOURCE=str(source), OPTION_DESTINATION=str(destination))
for enabled in (False, True): for enabled in (False, True):
if kind == 'powershell': if kind == 'powershell':
command = [executable, '-NoProfile', '-Command', command = [executable, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command',
"$ErrorActionPreference='Stop'; . ./scripts/lib/manifest.ps1; " "$ErrorActionPreference='Stop'; . ./scripts/lib/manifest.ps1; "
"Sync-ManagedDestination -Source $env:OPTION_SOURCE -Destination $env:OPTION_DESTINATION " "Sync-ManagedDestination -Source $env:OPTION_SOURCE -Destination $env:OPTION_DESTINATION "
"-Stamp test -AiConfigRoot root -ShellCommand bash -PowerShellCommand pwsh " "-Stamp test -AiConfigRoot root -ShellCommand bash -PowerShellCommand pwsh "
@@ -239,7 +264,7 @@ class InstallOptionsTests(unittest.TestCase):
'sync_managed_destination "$OPTION_SOURCE" "$OPTION_DESTINATION" test root bash pwsh false true ' 'sync_managed_destination "$OPTION_SOURCE" "$OPTION_DESTINATION" test root bash pwsh false true '
+ str(enabled).lower()] + str(enabled).lower()]
environment.update(OPTION_SOURCE=source.as_posix(), OPTION_DESTINATION=destination.as_posix()) 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) self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
installed = json.loads((destination / 'settings.json').read_text(encoding='utf-8-sig')) installed = json.loads((destination / 'settings.json').read_text(encoding='utf-8-sig'))
self.assertEqual('Stop' in installed['hooks'], enabled) self.assertEqual('Stop' in installed['hooks'], enabled)
@@ -300,11 +325,11 @@ class InstallOptionsTests(unittest.TestCase):
environment = dict(os.environ, HOME=home.as_posix(), TEST_INSTALL_HOME=str(home)) 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, '')]: for name, quick, answers in [('install', False, 'n\nn\nn\n'), ('update', True, '')]:
entry = str(commands / (name + '.' + suffix)) 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 kind == 'powershell' else [executable, entry, '--shell', 'bash', '--client', 'both', '--summary'])
if quick: if quick:
command.append('-Quick' if kind == 'powershell' else '--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.assertEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertNotIn('CLI-MOCK', result.stdout) self.assertNotIn('CLI-MOCK', result.stdout)
if quick: if quick:
+134 -7
View File
@@ -6,7 +6,9 @@ import json
import os import os
from pathlib import Path from pathlib import Path
import shutil import shutil
import stat
import subprocess import subprocess
import sys
import tempfile import tempfile
import unittest import unittest
from unittest.mock import patch from unittest.mock import patch
@@ -37,7 +39,14 @@ def mcp():
mcporter_url='https://mcp.context7.com/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): class ManagedExtensionTests(unittest.TestCase):
git_status = ''
def setUp(self): def setUp(self):
self.temporary = tempfile.TemporaryDirectory() self.temporary = tempfile.TemporaryDirectory()
self.addCleanup(self.temporary.cleanup) self.addCleanup(self.temporary.cleanup)
@@ -56,6 +65,8 @@ class ManagedExtensionTests(unittest.TestCase):
if args[:2] == ['npm', 'list']: if args[:2] == ['npm', 'list']:
return '{"dependencies":{}}' return '{"dependencies":{}}'
self.commands.append(args) 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': if len(args) > 3 and args[2] in ('add', 'install') and args[1] == 'plugin':
self.installed[args[0]][args[3]] = {'scope': 'user'} self.installed[args[0]][args[3]] = {'scope': 'user'}
if args[2] in ('remove', 'uninstall'): if args[2] in ('remove', 'uninstall'):
@@ -105,6 +116,16 @@ class ManagedExtensionTests(unittest.TestCase):
self.assertEqual('foreign', target.read_text()) self.assertEqual('foreign', target.read_text())
self.assertEqual([], self.manager().state['resources']) 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): def test_skill_removal_preserves_modified_and_foreign_files(self):
self.manager().sync([skill()], ['codex'], {'Humanizer'}) self.manager().sync([skill()], ['codex'], {'Humanizer'})
directory = self.home / '.agents/skills/humanizer' directory = self.home / '.agents/skills/humanizer'
@@ -233,17 +254,123 @@ class ManagedExtensionTests(unittest.TestCase):
self.assertEqual([['codex', 'plugin', 'remove', 'caveman@test']], [c for c in self.commands[installed:] if c[0] == 'codex']) 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']]) self.assertEqual(['claude'], [r['client'] for r in self.manager().state['resources']])
def test_selected_adhd_enables_always_on_flag_once(self): 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'])
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' config = self.home / '.claude'
flag = config / '.i-have-adhd-always' flag = config / '.i-have-adhd-always'
with patch.dict(os.environ, {'CLAUDE_CONFIG_DIR': str(config)}): with patch.dict(os.environ, {'CLAUDE_CONFIG_DIR': str(config)}):
self.manager(dry_run=True).sync([plugin('i-have-adhd')], ['claude'], {'i-have-adhd'})
self.assertFalse(flag.exists())
for _ in range(2):
self.manager().sync([plugin('i-have-adhd')], ['claude'], {'i-have-adhd'}) self.manager().sync([plugin('i-have-adhd')], ['claude'], {'i-have-adhd'})
self.assertTrue(flag.is_file())
flag.unlink()
self.manager().sync([plugin('Example')], ['claude'], {'Example'})
self.assertFalse(flag.exists()) self.assertFalse(flag.exists())
def test_dry_run_summary_has_one_line(self): def test_dry_run_summary_has_one_line(self):
+2 -2
View File
@@ -118,7 +118,7 @@ class PersonalInstructionTests(unittest.TestCase):
def sync(client, dry=False): def sync(client, dry=False):
self.environment['TEST_CLIENT'] = client self.environment['TEST_CLIENT'] = client
if shell == 'powershell': 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 " ". ./scripts/lib/manifest.ps1; Sync-ManagedDestination -Source $env:TEST_SOURCE "
"-Destination (Join-Path $env:TEST_HOME ('.' + $env:TEST_CLIENT)) -Stamp test -Summary " "-Destination (Join-Path $env:TEST_HOME ('.' + $env:TEST_CLIENT)) -Stamp test -Summary "
+ ('-DryRun' if dry else '')) + ('-DryRun' if dry else ''))
@@ -129,7 +129,7 @@ class PersonalInstructionTests(unittest.TestCase):
def change(action): def change(action):
if shell == 'powershell': 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)) '-Client', 'Both', '-Instruction', 'Use English.', '-HomePath', str(self.home))
else: else:
self.run_command(str(executable), '-c', self.run_command(str(executable), '-c',
+1 -1
View File
@@ -48,7 +48,7 @@ if ([Environment]::GetEnvironmentVariable('CODEX_HOME', 'Process') -ne $previous
$script:answers.Enqueue('done') $script:answers.Enqueue('done')
$selection = Select-ConfiguredPlugins -RepositoryRoot (Split-Path (Split-Path $PSScriptRoot -Parent) -Parent) -Client Codex -Mode Update $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 4) { 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 -eq 'Caveman' }).Count) { throw 'Claude-only extensions must not be offered for Codex.' } 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('4')
$script:answers.Enqueue('done') $script:answers.Enqueue('done')
$selection = Select-ConfiguredPlugins -RepositoryRoot (Split-Path (Split-Path $PSScriptRoot -Parent) -Parent) -Client Codex -Mode Update $selection = Select-ConfiguredPlugins -RepositoryRoot (Split-Path (Split-Path $PSScriptRoot -Parent) -Parent) -Client Codex -Mode Update
+3 -1
View File
@@ -48,7 +48,9 @@ select_configured_plugins "$root" codex Update true selected deselected
printf '%s\n' '{"mcpServers":{"context7":{"baseUrl":"https://example.invalid/mcp"}}}' > "$test_home/.mcporter/mcporter.json" printf '%s\n' '{"mcpServers":{"context7":{"baseUrl":"https://example.invalid/mcp"}}}' > "$test_home/.mcporter/mcporter.json"
select_configured_plugins "$root" codex Update true selected deselected select_configured_plugins "$root" codex Update true selected deselected
[[ " ${deselected[*]} " == *' Context7 '* ]] || { printf 'A different MCPorter server must not select Context7.\n' >&2; exit 1; } [[ " ${deselected[*]} " == *' Context7 '* ]] || { printf 'A different MCPorter server must not select Context7.\n' >&2; exit 1; }
[[ " ${selected[*]} ${deselected[*]} " != *' Caveman '* ]] || { printf 'Claude-only extensions must not be offered for Codex.\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") npm_prefix=$(mktemp -d "$root/.npm-test.XXXXXX")
cli_name="ai-config-test-cli-${npm_prefix##*.}" cli_name="ai-config-test-cli-${npm_prefix##*.}"
npm() { printf '%s\n' "$npm_prefix"; } npm() { printf '%s\n' "$npm_prefix"; }
+23 -2
View File
@@ -2,10 +2,10 @@
import { test } from 'node:test'; import { test } from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process'; 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 { tmpdir } from 'node:os';
import { join, resolve } from 'node:path'; import { join, resolve } from 'node:path';
import { INDEX_EXCLUDES, acquireStartLock, createServer, gitFingerprint, ignoreGlobs, indexIgnores, 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'; 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 }]; const defaultHits = () => [{ displayPath: `${collectionName('/r')}/src/a.ts`, body: 'x\nretry here', bestChunkPos: 2, bestChunk: 'retry here', score: 0.91 }];
@@ -222,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); 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) => { test('the start lock admits one launcher and is taken over after 2 minutes', (t) => {
const dir = mkdtempSync(join(tmpdir(), 'qmd-lock-')); const dir = mkdtempSync(join(tmpdir(), 'qmd-lock-'));
t.after(() => rmSync(dir, { recursive: true, force: true })); t.after(() => rmSync(dir, { recursive: true, force: true }));
+23 -4
View File
@@ -95,13 +95,32 @@ function tempDaemonFile(t, value) {
return file; return file;
} }
test('startDaemon resolves when its child loses the start race to a running daemon', async (t) => { const losingChild = () => {
const file = tempDaemonFile(t, { port: 4000, token: 'other', pid: 999 });
await startDaemon({ file, spawnChild: () => {
const child = new EventEmitter(); child.unref = () => {}; child.pid = 1; const child = new EventEmitter(); child.unref = () => {}; child.pid = 1;
setImmediate(() => child.emit('exit', 0)); setImmediate(() => child.emit('exit', 0));
return child; 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) => { test('a 403 means a stale token: daemon.json is deleted and one new daemon is started', async (t) => {
+4 -1
View File
@@ -147,7 +147,10 @@ class SetupTest(unittest.TestCase):
def test_update_deletes_only_owned_models_no_longer_used(self): def test_update_deletes_only_owned_models_no_longer_used(self):
models = self.home / '.cache/qmd/models' models = self.home / '.cache/qmd/models'
current = qmd.model_files((ROOT / 'shared/qmd/qmd-lib.mjs').read_text(encoding='utf-8')) current = qmd.model_files((ROOT / 'shared/qmd/qmd-lib.mjs').read_text(encoding='utf-8'))
create = lambda arguments: [(models / n).write_text('x') for n in current] if arguments[-1:] == ['pull'] else None def create(arguments):
if arguments[-1:] == ['pull']:
for name in current:
(models / name).write_text('x')
runner = FakeRunner(on_call=create) runner = FakeRunner(on_call=create)
self.setup(runner).enable(['claude']) self.setup(runner).enable(['claude'])
for name in ('hf_Qwen_Qwen3-Embedding-0.6B-Q8_0.gguf', 'foreign.gguf'): for name in ('hf_Qwen_Qwen3-Embedding-0.6B-Q8_0.gguf', 'foreign.gguf'):
+5 -5
View File
@@ -114,7 +114,7 @@ class SelectionTests(unittest.TestCase):
if not shell: if not shell:
self.skipTest('PowerShell unavailable') self.skipTest('PowerShell unavailable')
environment = dict(os.environ, TEST_SELECTION_HOME=str(self.home), TEST_REPOSITORY_ROOT=str(ROOT)) 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'); " "$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 " "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 = @() }"], "-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) stream.write(source)
entry = Path(stream.name) entry = Path(stream.name)
self.addCleanup(entry.unlink) self.addCleanup(entry.unlink)
result = subprocess.run([shell, '-NoProfile', '-File', str(entry), '-Quick', '-DryRun'], result = subprocess.run([shell, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', str(entry), '-Quick', '-DryRun'],
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.assertEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertNotIn('Select plugins', result.stdout) self.assertNotIn('Select plugins', result.stdout)
self.assertIn('DRYRUN ensure codex plugin: Superpowers', result.stdout) self.assertIn('DRYRUN ensure codex plugin: Superpowers', result.stdout)
self.assertNotIn('DRYRUN ensure codex plugin: Context7', result.stdout) self.assertNotIn('DRYRUN ensure codex plugin: Context7', result.stdout)
self.assertEqual(self.path.read_bytes(), original) self.assertEqual(self.path.read_bytes(), original)
self.assertFalse((self.home / '.codex').exists()) 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) stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=10)
self.assertNotEqual(failed.returncode, 0) self.assertNotEqual(failed.returncode, 0)
self.assertEqual(self.path.read_bytes(), original) self.assertEqual(self.path.read_bytes(), original)
@@ -158,7 +158,7 @@ class SelectionTests(unittest.TestCase):
original = self.path.read_bytes() original = self.path.read_bytes()
environment = dict(os.environ, HOME=self.home.as_posix()) environment = dict(os.environ, HOME=self.home.as_posix())
result = subprocess.run([shell, str(ROOT / 'scripts/commands/update.sh'), '--quick', '--dry-run'], 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.assertEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertNotIn('Select plugins', result.stdout) self.assertNotIn('Select plugins', result.stdout)
self.assertIn('DRYRUN ensure codex plugin: Superpowers', result.stdout) self.assertIn('DRYRUN ensure codex plugin: Superpowers', result.stdout)
+10 -5
View File
@@ -45,23 +45,28 @@ foreach ($shell in @('powershell','bash')) {
if ($client -eq 'claude') { $settings = $content | ConvertFrom-Json } if ($client -eq 'claude') { $settings = $content | ConvertFrom-Json }
if (@(Get-ChildItem "$package/agents" -File).Count -ne $sourceAgentCount) { throw "Missing agents in $package" } if (@(Get-ChildItem "$package/agents" -File).Count -ne $sourceAgentCount) { throw "Missing agents in $package" }
$expectedReviewerShellTool = if ($shell -eq 'powershell') { 'PowerShell' } else { 'Bash' } $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') { if ($client -eq 'claude') {
foreach ($role in @('architect','researcher')) { 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 } $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" } 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' } $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 ($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' } $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 ($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 ($shell -eq 'powershell' -and $content -match 'WindowStyle\s+Hidden') { throw "PowerShell hook hides the terminal in $package" }
if ($client -eq 'codex') { if ($client -eq 'codex') {
$events = @([regex]::Matches($content, '(?m)^\[\[hooks\.([^.\]]+)\]\]\s*$') | ForEach-Object { $_.Groups[1].Value }) $events = @([regex]::Matches($content, '(?m)^\[\[hooks\.([^.\]]+)\]\]\s*$') | ForEach-Object { $_.Groups[1].Value })
if ((($events | Sort-Object) -join ',') -ne 'PostToolUse,PreToolUse,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 ((($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 'approvals_reviewer\s*=\s*"auto_review"') { throw "Codex auto review is missing in $package" }
if ($content -notmatch '(?m)^sandbox_mode\s*=\s*"danger-full-access"\s*$') { throw "Codex full access is missing in $package" } if ($content -notmatch '(?m)^sandbox_mode\s*=\s*"danger-full-access"\s*$') { throw "Codex full access is missing in $package" }
if ($content -notmatch '(?m)^max_depth\s*=\s*1\s*$') { throw "Codex agent depth limit is missing in $package" } if ($content -notmatch '(?m)^max_depth\s*=\s*1\s*$') { throw "Codex agent depth limit is missing in $package" }
@@ -72,7 +77,7 @@ foreach ($shell in @('powershell','bash')) {
throw "Claude auto permission mode is missing in $package" 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') { } 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" 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" 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)) { } 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" throw "Claude sandbox must be disabled in $package"
+17 -8
View File
@@ -21,7 +21,7 @@ case "$(uname -s 2>/dev/null || true)" in
esac esac
source_agent_count=$(find "$root/shared/agents" -mindepth 1 -maxdepth 1 -type d | wc -l) 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) 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[@]} rule_skill_count=${#rule_paths[@]}
global_instructions=$(<"$root/shared/global-instructions.md") global_instructions=$(<"$root/shared/global-instructions.md")
rule_skill_name() { rule_skill_name() {
@@ -52,10 +52,10 @@ for shell in powershell bash; do
expected_reviewer_shell_tool=Bash expected_reviewer_shell_tool=Bash
[ "$shell" != powershell ] || expected_reviewer_shell_tool=PowerShell [ "$shell" != powershell ] || expected_reviewer_shell_tool=PowerShell
# Generated files may have CRLF endings when the PowerShell build produced them, so allow trailing whitespace. # Generated files may have CRLF endings when the PowerShell build produced them, so allow trailing whitespace.
if [ "$client" = claude ]; then grep -q "^tools: Read,Grep,Glob,${expected_reviewer_shell_tool}[[:space:]]*\$" "$package/agents/reviewer.md"; fi if [ "$client" = claude ]; then grep -q "^tools: Read,Grep,Glob,${expected_reviewer_shell_tool},Skill[[:space:]]*\$" "$package/agents/reviewer.md"; fi
if [ "$client" = claude ]; then if [ "$client" = claude ]; then
for role in architect researcher; do for role in architect researcher; do
grep -q "^tools: Read,Grep,Glob,WebFetch,WebSearch,${expected_reviewer_shell_tool}[[:space:]]*\$" "$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 done
fi fi
expected_skill_count=$source_skill_count expected_skill_count=$source_skill_count
@@ -68,9 +68,18 @@ for shell in powershell bash; do
else else
test -f "$package/skills/reviews/security-review/SKILL.md" test -f "$package/skills/reviews/security-review/SKILL.md"
fi fi
test -f "$package/skills/copywriting/SKILL.md" test ! -e "$package/skills/copywriting/SKILL.md"
test -f "$package/skills/marketing-psychology/SKILL.md" test ! -e "$package/skills/cro/SKILL.md"
test -f "$package/skills/image/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/marketing-plan/SKILL.md"
test ! -e "$package/skills/social/SKILL.md" test ! -e "$package/skills/social/SKILL.md"
if [ "$shell" = powershell ]; then if [ "$shell" = powershell ]; then
@@ -80,7 +89,7 @@ for shell in powershell bash; do
grep -q 'bash .*flashbang.sh' "$package/$file" grep -q 'bash .*flashbang.sh' "$package/$file"
fi fi
if [ "$client" = codex ]; then if [ "$client" = codex ]; then
[ "$(sed -n 's/^\[\[hooks\.\([^].]*\)\]\][[:space:]]*$/\1/p' "$package/$file" | sort)" = $'PostToolUse\nPreToolUse\nSessionStart\nStop\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 -q 'flashbang-if-input' "$package/$file"
! grep -Eq '^async[[:space:]]*=[[:space:]]*true[[:space:]]*$' "$package/$file" ! grep -Eq '^async[[:space:]]*=[[:space:]]*true[[:space:]]*$' "$package/$file"
grep -q 'approvals_reviewer[[:space:]]*=[[:space:]]*"auto_review"' "$package/$file" grep -q 'approvals_reviewer[[:space:]]*=[[:space:]]*"auto_review"' "$package/$file"
@@ -94,7 +103,7 @@ for shell in powershell bash; do
grep -q '"defaultMode"[[:space:]]*:[[:space:]]*"auto"' "$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_CONCURRENT_SUBAGENTS"[[:space:]]*:[[:space:]]*"5"' "$package/$file"
grep -q '"CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH"[[:space:]]*:[[:space:]]*"1"' "$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' statusline_extension='sh'
[ "$shell" != powershell ] || statusline_extension=ps1 [ "$shell" != powershell ] || statusline_extension=ps1
test -f "$package/statusline/statusline.$statusline_extension" test -f "$package/statusline/statusline.$statusline_extension"
+42
View File
@@ -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()
+210
View File
@@ -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)
+19 -3
View File
@@ -1,6 +1,7 @@
import os import os
import shutil import shutil
import subprocess import subprocess
import sys
import tempfile import tempfile
import unittest import unittest
import uuid import uuid
@@ -63,6 +64,9 @@ class UserCustomizationTests(unittest.TestCase):
home = Path(directory) home = Path(directory)
key = f'MY_TEST_TOKEN_{uuid.uuid4().hex}' key = f'MY_TEST_TOKEN_{uuid.uuid4().hex}'
stored = False 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: try:
result = subprocess.run([ result = subprocess.run([
powershell, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', powershell, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File',
@@ -73,15 +77,27 @@ class UserCustomizationTests(unittest.TestCase):
self.assertEqual(0, result.returncode, result.stderr) self.assertEqual(0, result.returncode, result.stderr)
stored = True stored = True
helper = home / '.my-ai-configuration/bin/with-credential.ps1' 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()) 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([ injected = subprocess.run([
powershell, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', str(helper), powershell, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', str(helper),
'-Client', 'Codex', '-Key', key, '-FilePath', powershell, '-Client', 'Codex', '-Key', key, '-FilePath', powershell,
'-NoProfile', '-Command', child, '-NoProfile', '-Command', child,
], capture_output=True, text=True, timeout=20) ], 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: finally:
cleanup = subprocess.run([ cleanup = subprocess.run([
powershell, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', powershell, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command',
+1 -1
View File
@@ -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. 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.
+1 -1
View File
@@ -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. 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 -2
View File
@@ -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. 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. Check logic, regressions, architecture, maintainability, security, and contract consistency. Follow the shared orchestration handoff protocol. Do not modify implementation code unless assigned.
+4 -4
View File
@@ -6,15 +6,15 @@ For credentials, run the child command through `~/.my-ai-configuration/bin/with-
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. 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. 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 (Codex paths under `rules/security/references/`): authentication, authorization, sessions, tokens, permissions, tenants => `auth.md` / `rules-security-auth`; inbound HTTP endpoints, request handling, API (de)serialization => `api.md` / `rules-security-api`; browser, cookies, redirects, XSS, CSRF => `web.md` / `rules-security-web`; databases, queries, persistence, sensitive data => `data.md` / `rules-security-data`; files, uploads, archives, paths, processes, IPC, XML parsing, deserialization => `files.md` / `rules-security-files`; outbound HTTP calls, webhooks, URL fetching, proxies, TLS, SSRF => `network.md` / `rules-security-network`; cryptography, secrets, keys, credentials => `crypto.md` / `rules-security-crypto`; dependencies, packages, plugins, builds, deployment, CI => `supply-chain.md` / `rules-security-supply-chain`; LLM calls, prompts, agents, tools, retrieval/RAG => `ai.md` / `rules-security-ai`; active security testing => `testing.md` / `rules-security-testing`. 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 ## Tools and delegation
+2 -2
View File
@@ -2,9 +2,9 @@
This directory contains registered hooks and optional utilities. They do not bypass client permission prompts or grant access. 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 `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. 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/`.
`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. `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.
+16
View File
@@ -0,0 +1,16 @@
[CmdletBinding()]
param()
# Codex SessionStart hook: Codex adds plain stdout to the session context, so printing the installed
# Caveman skill makes caveman style always-on like the Claude plugin. CAVEMAN_DEFAULT_MODE=off disables it.
try {
$ErrorActionPreference = 'Stop'
$mode = if ($env:CAVEMAN_DEFAULT_MODE) { $env:CAVEMAN_DEFAULT_MODE.ToLowerInvariant() } else { 'caveman' }
if ($mode -in @('off', 'manual')) { exit 0 }
$userHome = if ($env:USERPROFILE) { $env:USERPROFILE } elseif ($env:HOME) { $env:HOME } else { [Environment]::GetFolderPath('UserProfile') }
$skill = Join-Path $userHome '.agents/skills/caveman/SKILL.md'
if (-not (Test-Path -LiteralPath $skill -PathType Leaf)) { exit 0 }
$text = [IO.File]::ReadAllText($skill)
$body = [regex]::Replace($text, '\A---\r?\n.*?\r?\n---\r?\n', '', 'Singleline')
[Console]::Out.Write("CAVEMAN MODE ACTIVE (mode: $mode). Follow these rules for every response until the user says ""stop caveman"" or ""normal mode"".`n`n$body")
} catch {}
exit 0
@@ -0,0 +1,10 @@
[CmdletBinding()]
param()
# Best effort: without Python 3.11+ this hook is a silent no-op; doctor reports that case.
try {
$ErrorActionPreference = 'Stop'
. (Join-Path $PSScriptRoot 'Resolve-Python.ps1')
$python = Get-PythonCommand
if ($python) { & $python.Path @($python.Arguments) (Join-Path $PSScriptRoot 'agent-guards.py') search 2>$null }
} catch {}
exit 0
@@ -1,7 +1,8 @@
# Without -Command this runs as a PreToolUse hook: it reads the event from stdin and exits 2 to block. # Without -Command this runs as a PreToolUse hook: it reads the event from stdin and exits 2 to block.
# With -Command it checks one command and also rejects absolute paths outside -Workspace. # With -Command it checks one command and also rejects absolute paths outside -Workspace.
# Pattern checks are a guard rail against accidents, not a security boundary. # Pattern checks are a guard rail against accidents, not a security boundary.
param([string]$Command, [string]$Workspace = (Get-Location).Path) # -Shell (bash, powershell, unknown) overrides the dialect taken from the hook's tool name.
param([string]$Command, [string]$Workspace = (Get-Location).Path, [ValidateSet('', 'bash', 'powershell', 'unknown')][string]$Shell = '')
. (Join-Path $PSScriptRoot 'Resolve-Python.ps1') . (Join-Path $PSScriptRoot 'Resolve-Python.ps1')
$python = Get-PythonCommand $python = Get-PythonCommand
$script = Join-Path $PSScriptRoot 'command-safety.py' $script = Join-Path $PSScriptRoot 'command-safety.py'
@@ -13,5 +14,6 @@ if ($PSBoundParameters.ContainsKey('Command')) {
} }
# Registered hooks fail open without Python; doctor reports that case. # Registered hooks fail open without Python; doctor reports that case.
if (-not $python) { exit 0 } if (-not $python) { exit 0 }
& $python.Path @($python.Arguments) $script --hook $shellArguments = if ($Shell) { @('--shell', $Shell) } else { @() }
& $python.Path @($python.Arguments) $script --hook @shellArguments
exit $LASTEXITCODE exit $LASTEXITCODE
+56 -1
View File
@@ -1,9 +1,11 @@
import hashlib
import json import json
import os import os
from pathlib import Path from pathlib import Path
import re import re
import subprocess import subprocess
import sys import sys
import time
MAX_EVENT_BYTES = 1048576 MAX_EVENT_BYTES = 1048576
MAX_PROMPT_CHARS = 2000 MAX_PROMPT_CHARS = 2000
@@ -28,6 +30,18 @@ CORRECTION_CONTEXT = ('This prompt may correct you. If it reveals a durable rule
'in one line and ask for approval. After approval, store it in the user\'s configuration repository: ' 'in one line and ask for approval. After approval, store it in the user\'s configuration repository: '
'`shared/` for all clients, or `scripts/commands/add-instruction` for one client. Ask for the ' '`shared/` for all clients, or `scripts/commands/add-instruction` for one client. Ask for the '
'repository path if unknown. Never change instructions without approval.') 'repository path if unknown. Never change instructions without approval.')
QMD_SEARCH = '.my-ai-configuration/qmd/qmd-search.mjs'
SEARCH_TOOLS = ('Grep', 'Glob')
# shortcut: matches command text, not parsed shells; a wrapped or aliased search slips through, which only skips a reminder.
SEARCH_COMMAND = re.compile(r'(?:^|[\s;&|(])(?:rg|grep|egrep|fgrep|findstr|find|fd|ag|ack|select-string|sls|git\s+grep|'
r'(?:get-childitem|gci|ls|dir)\b[^|;&]*\s-(?:recurse|r)\b)(?=\s|$)', re.I)
# Searches without qmd-search before the reminder repeats; covers long sessions and context lost to compaction.
REMIND_EVERY = 10
SEARCH_CONTEXT = ('Search reminder: for open searches - unknown locations or identifiers, behavior '
'questions, discovery, or claims that something is absent - run `semantic-search` first: '
'node "$HOME/' + QMD_SEARCH + '" --query "<full question>" --top-k 5. Known paths, symbols, and exact '
'strings may use rg/Grep directly. An empty pattern search does not prove absence.')
MARKER_MAX_AGE = 7 * 24 * 3600
def read_event(): def read_event():
@@ -65,8 +79,49 @@ def show_correction(event):
print(json.dumps({'hookSpecificOutput': {'hookEventName': 'UserPromptSubmit', 'additionalContext': CORRECTION_CONTEXT}})) print(json.dumps({'hookSpecificOutput': {'hookEventName': 'UserPromptSubmit', 'additionalContext': CORRECTION_CONTEXT}}))
def search_marker(session):
directory = Path.home() / '.my-ai-configuration/state/search-reminder'
if any(part.is_symlink() for part in (directory.parent, directory)):
raise OSError('Search reminder state path contains a link.')
directory.mkdir(parents=True, exist_ok=True)
return directory / hashlib.sha256(session.encode('utf-8')).hexdigest()[:32]
def prune_markers(directory, now):
for path in directory.iterdir():
if path.is_file() and not path.is_symlink() and now - path.stat().st_mtime > MARKER_MAX_AGE:
path.unlink()
def remind_search(event):
session, tool, tool_input = event.get('session_id'), event.get('tool_name'), event.get('tool_input')
if not isinstance(session, str) or not session or not isinstance(tool_input, dict) or not (Path.home() / QMD_SEARCH).is_file():
return
command = tool_input.get('command') if tool in ('Bash', 'PowerShell') else None
if not isinstance(command, str):
command = ''
used_qmd = 'qmd-search.mjs' in command
if not used_qmd and tool not in SEARCH_TOOLS and not SEARCH_COMMAND.search(command):
return
marker = search_marker(session)
if marker.is_symlink():
return
if marker.exists():
try:
count = int(marker.read_text(encoding='utf-8') or '0') + 1
except ValueError:
count = 1
else:
prune_markers(marker.parent, time.time())
count = REMIND_EVERY
remind = not used_qmd and count >= REMIND_EVERY
marker.write_text('0' if used_qmd or remind else str(count), encoding='utf-8')
if remind:
print(json.dumps({'hookSpecificOutput': {'hookEventName': 'PreToolUse', 'additionalContext': SEARCH_CONTEXT}}))
def main(): def main():
handlers = {'stop': check_completion, 'prompt': show_correction} handlers = {'stop': check_completion, 'prompt': show_correction, 'search': remind_search}
try: try:
handlers[sys.argv[1]](read_event()) handlers[sys.argv[1]](read_event())
except (IndexError, KeyError, ValueError, OSError, RecursionError, subprocess.SubprocessError): except (IndexError, KeyError, ValueError, OSError, RecursionError, subprocess.SubprocessError):
+91 -14
View File
@@ -8,6 +8,7 @@ command text and cannot see what scripts, aliases, or variables expand to at run
""" """
import argparse import argparse
import importlib.util
import json import json
import ntpath import ntpath
import os import os
@@ -16,7 +17,11 @@ import re
import shlex import shlex
import sys import sys
WRAPPERS = {'sudo', 'command', 'builtin', 'exec', 'nohup', 'time', 'env', 'xargs'} WRAPPERS = {'sudo', 'doas', 'command', 'builtin', 'exec', 'nohup', 'time', 'env', 'xargs', 'timeout', 'nice'}
# Shell keywords that can precede a command in the same segment.
KEYWORDS = {'if', 'then', 'else', 'elif', 'do', 'while', 'until', '!'}
LINE_CONTINUATION = re.compile(r'[\\`]\r?\n')
HEREDOC = re.compile(r'<<(-?)\s*([\'"]?)([A-Za-z_][A-Za-z0-9_]*)\2')
POSIX_SHELLS = {'bash', 'sh', 'zsh', 'dash', 'ksh'} POSIX_SHELLS = {'bash', 'sh', 'zsh', 'dash', 'ksh'}
POWERSHELL_HOSTS = {'pwsh', 'powershell'} POWERSHELL_HOSTS = {'pwsh', 'powershell'}
POWERSHELL_REMOVE = {'remove-item', 'ri'} POWERSHELL_REMOVE = {'remove-item', 'ri'}
@@ -28,9 +33,37 @@ MAX_DEPTH = 3
def split_segments(command): def split_segments(command):
"""Split on ;, &, |, &&, || and newlines that are outside quotes.""" """Split on ;, &, |, &&, ||, newlines, and braces outside quotes; drop # comments and heredoc bodies; join continued lines."""
segments, current, quote = [], [], None command = LINE_CONTINUATION.sub(' ', command)
for character in command: segments, current, quote, index, heredocs = [], [], None, 0, []
while index < len(command):
character = command[index]
if not quote and command.startswith('<<', index) and not command.startswith('<<<', index):
match = HEREDOC.match(command, index)
if match:
heredocs.append((match.group(1) == '-', match.group(3)))
current.append(match.group(0))
index = match.end()
continue
if not quote and character == '\n' and heredocs:
# The body is text for the command, not commands: skip to each delimiter line.
segments.append(''.join(current))
current = []
lines = command[index + 1:].split('\n')
consumed = 0
for strip_tabs, word in heredocs:
while consumed < len(lines):
line = lines[consumed].rstrip('\r')
consumed += 1
if (line.lstrip('\t') if strip_tabs else line) == word:
break
heredocs = []
index += 1 + sum(len(line) + 1 for line in lines[:consumed])
continue
if character == '\\' and quote != "'" and index + 1 < len(command):
current.append(command[index:index + 2])
index += 2
continue
if quote: if quote:
current.append(character) current.append(character)
if character == quote: if character == quote:
@@ -38,11 +71,16 @@ def split_segments(command):
elif character in '\'"': elif character in '\'"':
quote = character quote = character
current.append(character) current.append(character)
elif character in ';&|\n': elif character == '#' and (index == 0 or command[index - 1].isspace()):
newline = command.find('\n', index)
index = len(command) if newline < 0 else newline
continue
elif character in ';&|\n{}':
segments.append(''.join(current)) segments.append(''.join(current))
current = [] current = []
else: else:
current.append(character) current.append(character)
index += 1
segments.append(''.join(current)) segments.append(''.join(current))
return [segment.strip() for segment in segments if segment.strip()] return [segment.strip() for segment in segments if segment.strip()]
@@ -60,14 +98,16 @@ def program_name(token):
def strip_wrappers(tokens): def strip_wrappers(tokens):
index = 0 """Drop leading keywords, subshell parentheses, and variable assignments; stop at the first program or wrapper."""
while index < len(tokens): tokens = list(tokens)
token = tokens[index] while tokens:
if program_name(token) in WRAPPERS or re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*=.*', token): first = tokens[0].lstrip('(')
index += 1 if not first or first in KEYWORDS or re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*=.*', first):
tokens.pop(0)
continue continue
tokens[0] = first
break break
return tokens[index:] return tokens
def short_flags(tokens): def short_flags(tokens):
@@ -97,6 +137,13 @@ def check_tokens(tokens, shell=None):
if not tokens: if not tokens:
return None return None
program = program_name(tokens[0]) program = program_name(tokens[0])
if program in WRAPPERS:
# Wrapper options and values (xargs -0, sudo -u bob, timeout 30) come before the wrapped command.
for start in range(1, len(tokens)):
reason = check_tokens(tokens[start:], shell)
if reason:
return reason
return None
arguments = tokens[1:] arguments = tokens[1:]
lowered = [argument.lower() for argument in arguments] lowered = [argument.lower() for argument in arguments]
if program == 'rm' and shell != 'powershell': if program == 'rm' and shell != 'powershell':
@@ -111,6 +158,16 @@ def check_tokens(tokens, shell=None):
return 'discarding work tree changes (git reset --hard)' return 'discarding work tree changes (git reset --hard)'
if subcommand == 'clean' and ('f' in short_flags(rest) or '--force' in rest): if subcommand == 'clean' and ('f' in short_flags(rest) or '--force' in rest):
return 'deleting untracked files (git clean -f)' return 'deleting untracked files (git clean -f)'
if subcommand == 'checkout' and ('--' in rest or '.' in rest):
return 'discarding file changes (git checkout -- <path>)'
if subcommand == 'restore' and rest and ('--staged' not in rest or '--worktree' in rest):
return 'discarding file changes (git restore)'
if subcommand == 'push' and ('f' in short_flags(rest) or any(item.startswith(('--force', '+')) for item in rest)):
return 'overwriting remote history (git push --force)'
if subcommand == 'stash' and rest[:1] == ['clear']:
return 'deleting all stashes (git stash clear)'
if program == 'find' and '-delete' in lowered:
return 'deleting found files (find -delete)'
powershell_remove = program in POWERSHELL_REMOVE or (shell != 'bash' and program in POWERSHELL_REMOVE_ALIASES) powershell_remove = program in POWERSHELL_REMOVE or (shell != 'bash' and program in POWERSHELL_REMOVE_ALIASES)
if powershell_remove and any(RECURSE_PARAMETER.fullmatch(item) for item in lowered): if powershell_remove and any(RECURSE_PARAMETER.fullmatch(item) for item in lowered):
return 'recursive deletion (Remove-Item -Recurse)' return 'recursive deletion (Remove-Item -Recurse)'
@@ -127,6 +184,8 @@ def nested_command(tokens):
if not tokens: if not tokens:
return None return None
program = program_name(tokens[0]) program = program_name(tokens[0])
if program in WRAPPERS:
return next((found for start in range(1, len(tokens)) if (found := nested_command(tokens[start:]))), None)
if program == 'eval': if program == 'eval':
return ' '.join(tokens[1:]), 'bash' return ' '.join(tokens[1:]), 'bash'
for index, token in enumerate(tokens[1:], start=1): for index, token in enumerate(tokens[1:], start=1):
@@ -175,7 +234,7 @@ def outside_workspace(command, workspace):
return None return None
def run_hook(data): def run_hook(data, shell_override=None):
try: try:
event = json.loads(data.decode('utf-8', errors='replace')) event = json.loads(data.decode('utf-8', errors='replace'))
command = event.get('tool_input', {}).get('command') command = event.get('tool_input', {}).get('command')
@@ -185,13 +244,29 @@ def run_hook(data):
if not isinstance(command, str): if not isinstance(command, str):
return 0 return 0
shell = tool if tool in ('bash', 'powershell') else None shell = tool if tool in ('bash', 'powershell') else None
if shell_override:
# Codex reports every shell command as Bash, even PowerShell script text on Windows.
shell = None if shell_override == 'unknown' else shell_override
reason = find_violation(command, shell) reason = find_violation(command, shell)
if reason: if reason:
print(f'Blocked by command-safety hook: {reason}. Ask the user to run this command themselves if it is intended.', file=sys.stderr) print(f'Blocked by command-safety hook: {reason}. Ask the user to run this command themselves if it is intended.', file=sys.stderr)
return 2 return 2
remind_search(event)
return 0 return 0
def remind_search(event):
# Runs the search reminder in this process so shell calls start one hook process, not two.
# Best effort like agent-guards.py itself: a reminder failure never blocks or fails the command.
try:
spec = importlib.util.spec_from_file_location('agent_guards', os.path.join(os.path.dirname(os.path.abspath(__file__)), 'agent-guards.py'))
guards = importlib.util.module_from_spec(spec)
spec.loader.exec_module(guards)
guards.remind_search(event)
except Exception:
pass
def run_check(command, workspace): def run_check(command, workspace):
reason = find_violation(command) reason = find_violation(command)
if reason: if reason:
@@ -211,10 +286,12 @@ def main():
mode.add_argument('--hook', action='store_true', help='read a PreToolUse event from stdin') mode.add_argument('--hook', action='store_true', help='read a PreToolUse event from stdin')
mode.add_argument('--command', help="command text to check, or '-' to read it from stdin") mode.add_argument('--command', help="command text to check, or '-' to read it from stdin")
parser.add_argument('--workspace', default=os.getcwd()) parser.add_argument('--workspace', default=os.getcwd())
parser.add_argument('--shell', choices=('bash', 'powershell', 'unknown'), help='hook mode: dialect to assume instead of the tool name')
args = parser.parse_args() args = parser.parse_args()
if args.hook: if args.hook:
return run_hook(sys.stdin.buffer.read()) return run_hook(sys.stdin.buffer.read(), args.shell)
command = sys.stdin.read() if args.command == '-' else args.command # Windows PowerShell 5.1 prefixes piped stdin with a UTF-8 byte order mark.
command = sys.stdin.buffer.read().decode('utf-8-sig', errors='replace') if args.command == '-' else args.command
return run_check(command, args.workspace) return run_check(command, args.workspace)
+10
View File
@@ -0,0 +1,10 @@
#!/usr/bin/env bash
# Codex SessionStart hook: Codex adds plain stdout to the session context, so printing the installed
# Caveman skill makes caveman style always-on like the Claude plugin. CAVEMAN_DEFAULT_MODE=off disables it.
mode=$(printf '%s' "${CAVEMAN_DEFAULT_MODE:-caveman}" | tr '[:upper:]' '[:lower:]')
case "$mode" in off|manual) exit 0 ;; esac
skill="${HOME:-}/.agents/skills/caveman/SKILL.md"
[ -f "$skill" ] || exit 0
printf 'CAVEMAN MODE ACTIVE (mode: %s). Follow these rules for every response until the user says "stop caveman" or "normal mode".\n\n' "$mode"
awk 'NR == 1 && /^---/ { front = 1; next } front && /^---/ { front = 0; next } !front' "$skill" 2>/dev/null
exit 0
@@ -0,0 +1,6 @@
#!/usr/bin/env bash
set -uo pipefail
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
# Best effort: without Python 3.11+ this hook is a silent no-op; doctor reports that case.
. "$script_dir/resolve-python.sh"
if resolve_python; then run_python "$script_dir/agent-guards.py" search 2>/dev/null || true; fi
@@ -7,6 +7,12 @@ set -uo pipefail
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
# shellcheck source=resolve-python.sh # shellcheck source=resolve-python.sh
. "$script_dir/resolve-python.sh" . "$script_dir/resolve-python.sh"
hook_arguments=()
# Codex hook commands pass -Shell <bash|powershell|unknown>; that is still hook mode.
if [ "${1:-}" = -Shell ] && [ $# -eq 2 ]; then
hook_arguments=(--shell "$2")
shift 2
fi
if [ $# -gt 0 ]; then if [ $# -gt 0 ]; then
resolve_python || { python_missing_message >&2; exit 1; } resolve_python || { python_missing_message >&2; exit 1; }
printf '%s' "$1" | run_python "$script_dir/command-safety.py" --command - --workspace "${2:-$PWD}" printf '%s' "$1" | run_python "$script_dir/command-safety.py" --command - --workspace "${2:-$PWD}"
@@ -14,4 +20,4 @@ if [ $# -gt 0 ]; then
fi fi
# Registered hooks fail open without Python; doctor reports that case. # Registered hooks fail open without Python; doctor reports that case.
resolve_python || exit 0 resolve_python || exit 0
run_python "$script_dir/command-safety.py" --hook run_python "$script_dir/command-safety.py" --hook ${hook_arguments[@]+"${hook_arguments[@]}"}
+21
View File
@@ -82,6 +82,25 @@ export function keepModelsLoaded(store) {
const REPO_COLLECTION = /^repo-[0-9a-f]{12}$/; const REPO_COLLECTION = /^repo-[0-9a-f]{12}$/;
// Deleted worktrees and temp clones leave recorded repo collections behind; drop those whose path is gone.
export async function pruneCollections({ store, collectionsFile, remove, exists = existsSync, log = console.error }) {
const recorded = readJson(collectionsFile, []);
if (!Array.isArray(recorded) || recorded.length === 0) return;
const paths = new Map((await store.listCollections()).map((c) => [c.name, c.pwd]));
const kept = recorded.filter((name) => {
const path = paths.get(name);
if (!REPO_COLLECTION.test(name) || !path || exists(path)) return true;
try {
remove(name);
return false;
} catch (error) {
log(`qmd-daemon: could not remove stale collection ${name}: ${error.message}`);
return true;
}
});
if (kept.length !== recorded.length) writePrivateJson(collectionsFile, kept);
}
function tokenMatches(given, expected) { function tokenMatches(given, expected) {
const a = Buffer.from(String(given ?? '')); const a = Buffer.from(String(given ?? ''));
const b = Buffer.from(expected); const b = Buffer.from(expected);
@@ -224,6 +243,8 @@ async function main() {
const { loadConfig } = await importQmd(join('dist', 'collections.js')); const { loadConfig } = await importQmd(join('dist', 'collections.js'));
const { syncConfigToDb } = await importQmd(join('dist', 'store.js')); const { syncConfigToDb } = await importQmd(join('dist', 'store.js'));
const collectionsFile = join(dir, 'collections.json'); const collectionsFile = join(dir, 'collections.json');
await pruneCollections({ store, collectionsFile, remove: (name) => runQmdCli(['collection', 'remove', name], { windowsHide: true, stdio: 'ignore' }) })
.catch((error) => console.error(`qmd-daemon: could not prune stale collections: ${error.message}`));
const token = randomBytes(32).toString('hex'); const token = randomBytes(32).toString('hex');
let stopping = false; let stopping = false;
const stop = async () => { const stop = async () => {
+3 -3
View File
@@ -12,9 +12,9 @@ export const MODELS = {
rerank: 'hf:giladgd/Qwen3-Reranker-4B-GGUF/Qwen3-Reranker-4B.Q4_K_M.gguf', rerank: 'hf:giladgd/Qwen3-Reranker-4B-GGUF/Qwen3-Reranker-4B.Q4_K_M.gguf',
generate: 'hf:tobil/qmd-query-expansion-1.7B-gguf/qmd-query-expansion-1.7B-q4_k_m.gguf', generate: 'hf:tobil/qmd-query-expansion-1.7B-gguf/qmd-query-expansion-1.7B-q4_k_m.gguf',
}; };
// Covers the stacks with rules in this configuration: web templates and styles, .NET and WPF markup and projects, and JVM builds. // Covers the stacks with rules in this configuration: web templates and styles, .NET and WPF markup and projects.
export const MASK = '**/*.{md,py,cs,ts,tsx,mts,cts,js,jsx,mjs,cjs,go,rs,java,kt,kts,ps1,sh,json,yml,yaml,toml,xml,sql,' export const MASK = '**/*.{md,py,cs,ts,tsx,mts,cts,js,jsx,mjs,cjs,go,rs,ps1,sh,json,yml,yaml,toml,xml,sql,'
+ 'html,css,scss,xaml,razor,cshtml,csproj,props,targets,gradle,properties}'; + 'html,css,scss,xaml,razor,cshtml,csproj,props,targets}';
export function collectionName(repoPath) { export function collectionName(repoPath) {
return 'repo-' + createHash('sha256').update(resolve(repoPath), 'utf8').digest('hex').slice(0, 12); return 'repo-' + createHash('sha256').update(resolve(repoPath), 'utf8').digest('hex').slice(0, 12);
+15 -2
View File
@@ -41,7 +41,18 @@ export async function callDaemon(path, body, { file = daemonFile(), fetchImpl =
return response.json(); return response.json();
} }
export async function startDaemon({ spawnChild = spawn, file = daemonFile() } = {}) { async function healthy(info, fetchImpl) {
try {
const response = await fetchImpl(`http://127.0.0.1:${info.port}/health`, { headers: { 'x-qmd-token': info.token }, signal: AbortSignal.timeout(2000) });
return response.ok && (await response.json()).service === 'ai-config-qmd';
} catch {
return false;
}
}
export async function startDaemon({ spawnChild = spawn, file = daemonFile(), fetchImpl = fetch } = {}) {
// After a crash daemon.json keeps the dead daemon's port and token, so a lost race must not trust that token unchecked.
const staleToken = readJson(file, null)?.token;
const device = readJson(setupStatePath(), {}).device || 'cpu'; const device = readJson(setupStatePath(), {}).device || 'cpu';
const child = spawnChild(process.execPath, [join(here, 'qmd-daemon.mjs')], { detached: true, stdio: 'ignore', windowsHide: true, env: deviceEnv(device) }); const child = spawnChild(process.execPath, [join(here, 'qmd-daemon.mjs')], { detached: true, stdio: 'ignore', windowsHide: true, env: deviceEnv(device) });
let failure = null; let failure = null;
@@ -57,7 +68,9 @@ export async function startDaemon({ spawnChild = spawn, file = daemonFile() } =
await new Promise((done) => setTimeout(done, 500)); await new Promise((done) => setTimeout(done, 500));
if (failure) throw failure; if (failure) throw failure;
const info = readJson(file, null); const info = readJson(file, null);
if (info?.port && info?.token && (lostRace || info.pid === child.pid)) return; if (!info?.port || !info?.token) continue;
if (info.pid === child.pid) return;
if (lostRace && (info.token !== staleToken || await healthy(info, fetchImpl))) return;
} }
throw new Error('daemon did not start within 120 s'); throw new Error('daemon did not start within 120 s');
} }
+1 -1
View File
@@ -1,6 +1,6 @@
# Angular Rules # Angular Rules
For Angular work, open the focused topic rule that matches the change. Angular code is TypeScript: load the matching TypeScript topic rules (`rules/typescript/index.md` / `rules-typescript`) as well. Load the security and accessibility rule when the change renders untrusted content, binds HTML or URLs, configures HTTP security or tokens, or builds interactive controls. For Angular work, check the Angular version in `package.json` first, then open the focused topic rule that matches the change. Angular code is TypeScript: load the matching TypeScript topic rules (`rules/typescript/index.md` / `rules-typescript`) as well. Load the security and accessibility rule when the change renders untrusted content, binds HTML or URLs, configures HTTP security or tokens, or builds interactive controls.
| Topic | Codex rule | Claude skill | | Topic | Codex rule | Claude skill |
| --- | --- | --- | | --- | --- | --- |
@@ -6,19 +6,12 @@ Apply these rules when creating or changing Angular components, directives, sign
* Prefer standalone components, directives, and pipes for new work. Avoid introducing `NgModule` unless the existing architecture requires it. * Prefer standalone components, directives, and pipes for new work. Avoid introducing `NgModule` unless the existing architecture requires it.
* Keep components small; move substantial business logic to a focused service or domain layer. * Keep components small; move substantial business logic to a focused service or domain layer.
* Keep dependencies explicit and follow the feature architecture. Avoid god components, god services, unnecessary wrappers, and abstractions without a concrete need.
* Use `ChangeDetectionStrategy.OnPush` unless there is a concrete reason not to, in both zone.js and zoneless applications. * Use `ChangeDetectionStrategy.OnPush` unless there is a concrete reason not to, in both zone.js and zoneless applications.
* Keep component state minimal and prefer immutable state updates. * Keep component state minimal, update it immutably, and never mutate shared state directly.
* Avoid direct mutation of shared state.
* Keep inputs and outputs strongly typed.
* In new code on Angular 19+, use `input()` and `input.required()`, `output()` (an `OutputEmitterRef`, not a signal), `model()` for intended two-way bindings, and signal queries (`viewChild`, `viewChildren`, `contentChild`, `contentChildren`). Keep `@Input`, `@Output`, and decorator queries only where the surrounding code uses them. * In new code on Angular 19+, use `input()` and `input.required()`, `output()` (an `OutputEmitterRef`, not a signal), `model()` for intended two-way bindings, and signal queries (`viewChild`, `viewChildren`, `contentChild`, `contentChildren`). Keep `@Input`, `@Output`, and decorator queries only where the surrounding code uses them.
* Use the `host` object in component metadata instead of `@HostBinding` and `@HostListener` in new code. * Use the `host` object in component metadata instead of `@HostBinding` and `@HostListener` in new code.
* Avoid unnecessary two-way binding. * Prefer explicit data flow: inputs down, events up. Avoid unnecessary two-way binding, component coupling, and exposed internal state.
* Avoid unnecessary component-to-component coupling. * Use lifecycle hooks only when required, and keep constructors free of complex initialization.
* Prefer explicit data flow from parent to child and explicit events upward.
* Do not expose internal component state unnecessarily.
* Use lifecycle hooks only when required.
* Avoid complex initialization logic inside constructors.
## Change Detection ## Change Detection
@@ -40,9 +33,6 @@ Apply these rules when creating or changing Angular components, directives, sign
## DOM and Browser APIs ## DOM and Browser APIs
* Prefer Angular APIs and declarative templates over direct DOM manipulation. * Prefer Angular APIs and declarative templates over direct DOM manipulation; use `Renderer2` only when a rendering abstraction is actually needed.
* Use `Renderer2` only when direct rendering abstraction is actually needed.
* Avoid accessing globals directly when it harms testability or SSR compatibility.
* When the application uses SSR, guard `window`, `document`, `localStorage`, and similar browser-only APIs with `isPlatformBrowser`, or run DOM access in `afterNextRender` or `afterRenderEffect`, which run only in the browser. * When the application uses SSR, guard `window`, `document`, `localStorage`, and similar browser-only APIs with `isPlatformBrowser`, or run DOM access in `afterNextRender` or `afterRenderEffect`, which run only in the browser.
* Clean up event listeners, observers and timers. * Clean up event listeners, observers, and timers, and avoid layout thrashing in performance-sensitive code.
* Avoid layout thrashing in performance-sensitive code.
@@ -6,23 +6,14 @@ Apply these rules when building Angular forms, validation, routes, guards, or re
* Follow the form approach the project uses. For non-trivial forms, use typed reactive forms (`FormGroup`, `FormControl`, `NonNullableFormBuilder`; `nonNullable` controls where reset should restore the initial value) and never `Untyped*` classes in new code. * Follow the form approach the project uses. For non-trivial forms, use typed reactive forms (`FormGroup`, `FormControl`, `NonNullableFormBuilder`; `nonNullable` controls where reset should restore the initial value) and never `Untyped*` classes in new code.
* Signal forms (`@angular/forms/signals`) are stable since Angular 22. Use them for new forms only when the project is on 22+ and has adopted them; do not migrate existing forms unasked. * Signal forms (`@angular/forms/signals`) are stable since Angular 22. Use them for new forms only when the project is on 22+ and has adopted them; do not migrate existing forms unasked.
* Keep validation rules centralized and reusable where practical. * Keep validation rules centralized and reusable, and keep form state separate from domain state when useful. The UI/UX forms rule covers error display and input preservation.
* Client-side validation is user experience; the server must validate every submission. Never treat client-side validation as a security boundary. * Client-side validation is user experience; the server must validate every submission. Never treat client-side validation as a security boundary.
* Keep form state separate from domain state when useful.
* Avoid large components that combine layout, validation, persistence and business logic.
* Display validation errors consistently.
* Preserve user input when recoverable errors occur.
## Routing ## Routing
* Keep route definitions explicit and predictable. * Keep route definitions explicit, and lazy load larger feature areas with `loadComponent` or `loadChildren` pointing to standalone route arrays.
* Prefer lazy loading for larger feature areas with `loadComponent` or `loadChildren` pointing to standalone route arrays.
* Write new guards and resolvers as functions (`CanActivateFn`, `ResolveFn`); keep class-based guards where the project uses them, since they remain supported. * Write new guards and resolvers as functions (`CanActivateFn`, `ResolveFn`); keep class-based guards where the project uses them, since they remain supported.
* Use `withComponentInputBinding()` to bind route parameters to component inputs where the project enables it. * Use `withComponentInputBinding()` to bind route parameters to component inputs where the project enables it.
* Avoid loading large feature bundles eagerly without need. * Use route guards only for navigation behavior, not as a security boundary; enforce authorization on the backend. Keep resolvers focused and navigation free of expensive work.
* Use route guards only for navigation behavior, not as a security boundary.
* Authorization must still be enforced on the backend.
* Keep resolvers focused.
* Avoid expensive work during navigation unless required.
* Route and query parameters arrive as `string | null`. Parse and validate them before use and treat them as untrusted input. * Route and query parameters arrive as `string | null`. Parse and validate them before use and treat them as untrusted input.
* Do not rely on client-side routing state for sensitive authorization decisions. * With SSR, set the render mode per route in `app.routes.server.ts` (`ServerRoute` with `RenderMode.Prerender` for static pages, `RenderMode.Server` for per-request content, `RenderMode.Client` for client-only pages), registered through `provideServerRendering(withRoutes(...))`.
+1 -2
View File
@@ -10,8 +10,7 @@ Apply these rules when writing or changing RxJS streams, subscriptions, or signa
* Avoid nested `subscribe`. * Avoid nested `subscribe`.
* Avoid manual subscriptions where `async`, signals or framework helpers are sufficient. * Avoid manual subscriptions where `async`, signals or framework helpers are sufficient.
* Bind every manual subscription's lifetime with `takeUntilDestroyed` or equivalent Angular lifecycle integration to avoid leaks. * Bind every manual subscription's lifetime with `takeUntilDestroyed` or equivalent Angular lifecycle integration to avoid leaks.
* Use the correct flattening operator for the required semantics. * Choose the flattening operator for its semantics; `switchMap`, `mergeMap`, `concatMap`, and `exhaustMap` are not interchangeable.
* Do not use `switchMap`, `mergeMap`, `concatMap` or `exhaustMap` interchangeably.
* Avoid unnecessary `Subject` usage. * Avoid unnecessary `Subject` usage.
* Prefer exposing observables instead of exposing mutable subjects. * Prefer exposing observables instead of exposing mutable subjects.
* Prefer `BehaviorSubject` only when a current value is actually required. * Prefer `BehaviorSubject` only when a current value is actually required.
@@ -1,44 +1,22 @@
# Angular Dependency Injection, Services, and HTTP # Angular Dependency Injection, Services, and HTTP
Apply these rules when creating Angular services, configuring dependency injection, or calling HTTP APIs. Apply these rules when creating Angular services, configuring dependency injection, or calling HTTP APIs. The TypeScript modeling and runtime-safety rules cover contracts and validation; this file adds Angular specifics.
## Dependency Injection ## Dependency injection and services
* Prefer Angular dependency injection for application services.
* Keep injected dependencies minimal.
* Avoid service locator patterns.
* Prefer the `inject()` function over constructor parameter injection, as the Angular style guide recommends since v20; keep constructor injection where the surrounding code consistently uses it. * Prefer the `inject()` function over constructor parameter injection, as the Angular style guide recommends since v20; keep constructor injection where the surrounding code consistently uses it.
* Do not inject services that are not used. * Scope services intentionally. Use root singletons only for truly shared, stateless, or coordinated state, and never store request- or component-specific mutable state in them.
* Scope services intentionally. * Use injection tokens for configuration or real abstractions; do not add interfaces only to satisfy dependency injection.
* Prefer application-wide singletons only for truly shared stateless or coordinated state. * Keep services focused, expose readonly state to consumers, and separate API access, domain logic, and UI state where practical. Do not use services merely to move poorly structured component code elsewhere.
* Avoid storing request-specific or component-specific mutable state in root services.
* Use injection tokens for configuration or abstractions where appropriate.
* Do not create interfaces only to satisfy dependency injection when no abstraction is needed.
## Services
* Keep services focused on a clear responsibility.
* Avoid large catch-all services.
* Separate API access, domain logic and UI state where practical.
* Avoid leaking transport models throughout the application.
* Do not expose mutable internal state directly.
* Prefer readonly APIs for state consumers.
* Avoid hidden side effects.
* Keep service methods predictable.
* Do not use services merely to move poorly structured component code elsewhere.
## HTTP and APIs ## HTTP and APIs
* Keep API access centralized and strongly typed. * Keep API access centralized in typed data-access services, and keep DTOs separate from domain models when their responsibilities differ.
* Prefer dedicated API clients or data-access services. * The type parameter of `HttpClient.get<T>()` or `httpResource<T>()` is a compile-time assertion, not validation. Treat responses as `unknown` and validate them at the data-access boundary before they drive authorization, persistence, navigation, or rendering.
* Do not use `any` for API responses. The type parameter of `HttpClient.get<T>()` or `httpResource<T>()` is a compile-time assertion, not validation. * Configure HTTP with `provideHttpClient(withInterceptors([...]), withFetch())` and functional interceptors in new code, not `HttpClientModule` or `HTTP_INTERCEPTORS` classes. Use interceptors only for cross-cutting concerns.
* Treat all server responses as `unknown` until validated, as in the TypeScript runtime-safety rule. Validate them with a schema or parser at the data-access boundary before they drive authorization, persistence, navigation, or rendering. * Avoid duplicate requests, cache only with a clear invalidation strategy, cancel requests the user no longer needs, and handle expected error states explicitly.
* Keep DTOs separate from domain models when their responsibilities differ.
* Avoid duplicate API calls.
* Cache only when the invalidation strategy is clear.
* Avoid manual URL string construction when typed helpers or centralized endpoints are available. * Avoid manual URL string construction when typed helpers or centralized endpoints are available.
* Configure HTTP with `provideHttpClient(withInterceptors([...]), withFetch())` and functional interceptors in new code, not `HttpClientModule` or `HTTP_INTERCEPTORS` classes.
* Use interceptors only for cross-cutting concerns. ## Errors
* Do not put unrelated business logic into HTTP interceptors.
* Handle cancellation where appropriate. * Route unhandled errors to one `ErrorHandler`; `provideBrowserGlobalErrorListeners()` forwards uncaught errors and unhandled promise rejections to it. Report them without secrets or personal data, and show users a recoverable state instead of a broken view.
* Handle expected error states explicitly.
@@ -1,28 +1,17 @@
# Angular Templates and Styling # Angular Templates and Styling
Apply these rules when writing Angular templates, control flow, or component styles. Apply these rules when writing Angular templates, control flow, or component styles. Load the UI/UX rules for visual design.
## Templates ## Templates
* Keep expressions short and readable. * Keep template expressions short. Reading signals and `computed` values is correct; do not call other methods that compute or allocate from templates, and move complex conditions into `computed` state or a pure pipe.
* Reading signals and `computed` values in templates is correct. Do not call other methods that compute or allocate from templates; use `computed` or a pure pipe instead. * Use built-in control flow (`@if`, `@for`, `@switch`) in new code.
* Avoid complex conditions directly in markup.
* Prefer derived state in TypeScript over repeated template expressions.
* Use Angular control flow syntax such as `@if`, `@for` and `@switch` for new code.
* In `@for`, track a stable unique key such as `track item.id`; use `$index` only for static lists that never reorder. For legacy `*ngFor`, supply `trackBy`. * In `@for`, track a stable unique key such as `track item.id`; use `$index` only for static lists that never reorder. For legacy `*ngFor`, supply `trackBy`.
* Avoid deeply nested template structures. * Split large or deeply nested templates into focused components, and avoid unnecessary DOM elements.
* Split large templates into focused components when it improves maintainability.
* Avoid unnecessary DOM elements.
* Use semantic HTML and native elements before custom implementations; see the accessibility section of the Angular security and accessibility rule. * Use semantic HTML and native elements before custom implementations; see the accessibility section of the Angular security and accessibility rule.
* Keep user-facing text translatable with the project's i18n approach, such as `i18n` attributes and `$localize`, and format dates, numbers, and currencies with locale-aware pipes instead of hand-built strings.
## Styling ## Styling
* Keep styles scoped and predictable. * Keep styles scoped to the component and follow the project's styling strategy; avoid unnecessary global CSS and mixing styling approaches.
* Avoid unnecessary global CSS. * Prefer design tokens and shared styles over magic values. Avoid excessive specificity, `!important`, and selectors that depend on fragile DOM structure.
* Follow the project's styling strategy consistently.
* Avoid excessive specificity.
* Avoid `!important` unless there is a concrete reason.
* Prefer reusable design tokens and shared styles over duplicated magic values.
* Keep component styles focused on component concerns.
* Avoid styling based on fragile DOM structure.
* Do not mix multiple styling approaches without need.
@@ -1,44 +1,24 @@
# Angular Testing and Architecture # Angular Testing and Architecture
Apply these rules when writing Angular tests, organizing features, or changing Angular package versions. Apply these rules when writing Angular tests, organizing features, or changing Angular package versions. The TypeScript testing, coding-style, and dependency rules and the shared refactoring rule cover general test design, structure, and dependency review; this file adds Angular specifics.
## Testing ## Testing
Apply the TypeScript testing rule for general test design, and these Angular specifics.
* Use the project's test runner. New CLI projects use Vitest since Angular 21; Karma remains supported, so do not migrate runners as part of another task. * Use the project's test runner. New CLI projects use Vitest since Angular 21; Karma remains supported, so do not migrate runners as part of another task.
* In zoneless tests, configure `TestBed` with `provideZonelessChangeDetection()` and use `await fixture.whenStable()` instead of `fakeAsync` and `tick`, which require zone.js. * In zoneless tests, configure `TestBed` with `provideZonelessChangeDetection()` and use `await fixture.whenStable()` instead of `fakeAsync` and `tick`, which require zone.js.
* Set signal inputs with `fixture.componentRef.setInput()`. Test HTTP with `provideHttpClient()` plus `provideHttpClientTesting()` and `HttpTestingController`. Prefer Angular CDK component harnesses for interacting with material or CDK components. * Set signal inputs with `fixture.componentRef.setInput()`. Test HTTP with `provideHttpClient()` plus `provideHttpClientTesting()` and `HttpTestingController`. Prefer Angular CDK component harnesses for Material and CDK components.
* Test behavior, not implementation details. * Test critical user interactions through the rendered component rather than its internals.
* Prefer focused component tests.
* Test critical user interactions.
* Test services and domain logic independently where useful.
* Avoid brittle tests coupled to internal structure.
* Avoid excessive mocking.
* Mock external boundaries rather than internal implementation details.
* Keep tests deterministic.
* Avoid time-dependent tests without controlled clocks.
* Avoid network-dependent tests without proper isolation.
* Keep test setup minimal and readable.
* Update tests when refactoring changes structure but not behavior.
## Architecture ## Architecture
* Keep UI, application, domain and data-access concerns separated where practical. * Organize code by feature, and keep UI, application, domain, and data-access concerns separate where practical.
* Organize code by feature rather than by technical file type when it improves cohesion. * Keep feature public APIs small; avoid cross-feature imports without a clear contract, and keep shared code genuinely shared.
* Avoid circular dependencies.
* Avoid cross-feature imports without a clear contract.
* Keep shared code genuinely shared.
* Do not move feature-specific logic into generic shared modules.
* Avoid dumping unrelated helpers into global utility files.
* Keep public APIs of feature areas small.
* Avoid exposing internal implementation details across feature boundaries.
* Prefer local ownership of state and logic. * Prefer local ownership of state and logic.
## Code Quality and Dependencies ## Versions and dependencies
Apply the TypeScript rules for types, style, and dependency review, plus these Angular specifics. * Check the Angular version in `package.json` before using version-specific APIs.
* Treat Angular compiler, template type-checking, and lint warnings seriously; do not suppress them without a concrete reason.
* Keep all `@angular/*` packages on the same major and minor version, and upgrade them with `ng update` so migrations run. * Keep all `@angular/*` packages on the same major and minor version, and upgrade them with `ng update` so migrations run.
* Keep TypeScript inside the range the Angular version supports (angular.dev/reference/versions); Angular 22 requires TypeScript `>=6.0.0 <6.1.0`, so do not move an Angular project to TypeScript 7 before Angular supports it.
* Treat Angular compiler, template type-checking, and lint warnings seriously; do not suppress them without a concrete reason.
* Prefer Angular and browser platform capabilities before adding third-party libraries. * Prefer Angular and browser platform capabilities before adding third-party libraries.
+3 -1
View File
@@ -1,6 +1,6 @@
# C# Rules # C# Rules
For C# or .NET work, open only the topic rules relevant to the task. Follow repository conventions and load applicable shared security rules as well. For C# or .NET work, including ASP.NET Core, Blazor, and .NET MAUI, open only the topic rules relevant to the task. Follow repository conventions and load applicable shared security rules as well.
| Topic | Codex rule | Claude skill | | Topic | Codex rule | Claude skill |
| --- | --- | --- | | --- | --- | --- |
@@ -12,3 +12,5 @@ For C# or .NET work, open only the topic rules relevant to the task. Follow repo
| Security | `references/security.md` | `rules-csharp-security` | | Security | `references/security.md` | `rules-csharp-security` |
| Validation, errors, and logging | `references/safety-and-errors.md` | `rules-csharp-safety-and-errors` | | Validation, errors, and logging | `references/safety-and-errors.md` | `rules-csharp-safety-and-errors` |
| Tests, dependencies, and analyzers | `references/testing-and-dependencies.md` | `rules-csharp-testing-and-dependencies` | | Tests, dependencies, and analyzers | `references/testing-and-dependencies.md` | `rules-csharp-testing-and-dependencies` |
| .NET MAUI apps | `references/maui.md` | `rules-csharp-maui` |
| Blazor components and apps | `references/blazor.md` | `rules-csharp-blazor` |
@@ -2,11 +2,11 @@
Apply these rules when designing public APIs, service boundaries, or application architecture. Apply these rules when designing public APIs, service boundaries, or application architecture.
* Give APIs explicit, strongly typed contracts. On trusted internal paths, do not repeat format or argument validation the boundary already performed. Authorization, resource ownership, and tenant scoping are never "already done": enforce them at the operation that accesses the data. * Give APIs explicit, strongly typed contracts. On trusted internal paths, do not repeat format or argument validation the boundary already performed.
* Separate request models from persistence and domain models. Bind only fields the caller may set, and project only fields the caller may read. * Separate request models from persistence and domain models. Bind only fields the caller may set, and project only fields the caller may read.
* Authenticate and authorize before accessing protected resources. Keep the decision close to the protected operation, enforce resource ownership and tenant scope in the data access path, not only in the UI or route layer, and fail closed when identity, ownership, or policy evaluation is unavailable. * Authenticate and authorize before accessing protected resources. Authorization, resource ownership, and tenant scoping are never "already done": keep the decision close to the protected operation, enforce ownership and tenant scope in the data access path, not only in the UI or route layer, and fail closed when identity, ownership, or policy evaluation is unavailable.
* Use explicit, bounded pagination for potentially large collections. * Use explicit, bounded pagination for potentially large collections.
* Treat EF Core `DbContext` as a short-lived, non-thread-safe unit of work: scoped per request in web apps, created through `IDbContextFactory<T>` per operation in desktop apps and background services, never shared across threads or held as a singleton. Use `AsNoTracking` for read-only queries, and use `FromSql` or `FromSqlInterpolated` instead of concatenating into `FromSqlRaw`. * Treat EF Core `DbContext` as a short-lived, non-thread-safe unit of work: scoped per request in web apps, created through `IDbContextFactory<T>` per operation in desktop apps and background services, never shared across threads or held as a singleton. Use `AsNoTracking` for read-only queries; raw SQL follows the C# security rules.
* Keep application, domain, and infrastructure concerns separate. Avoid cross-layer coupling and service-locator patterns. * Keep application, domain, and infrastructure concerns separate. Avoid cross-layer coupling and service-locator patterns.
* Use dependency injection when substitution or lifecycle management is needed. Keep dependencies explicit and avoid excessive constructor dependencies. * Use dependency injection when substitution or lifecycle management is needed. Keep dependencies explicit and avoid excessive constructor dependencies.
* Preserve established project and public API conventions unless a concrete compatibility or correctness issue requires a change. * Preserve established project and public API conventions unless a concrete compatibility or correctness issue requires a change.
@@ -4,6 +4,7 @@ Apply these rules when adding or changing asynchronous APIs, background work, or
* Use asynchronous APIs for genuinely asynchronous I/O; do not wrap synchronous work in unnecessary tasks. * Use asynchronous APIs for genuinely asynchronous I/O; do not wrap synchronous work in unnecessary tasks.
* Keep asynchronous operations async through the call chain. Avoid `.Result`, `.Wait()`, and other synchronous waits that can block threads or deadlock. * Keep asynchronous operations async through the call chain. Avoid `.Result`, `.Wait()`, and other synchronous waits that can block threads or deadlock.
* Return `Task` or `ValueTask` from async methods. Use `async void` only for event handlers, because callers cannot await it and its exceptions escape to the synchronization context; catch and handle failures inside such handlers.
* Accept and propagate `CancellationToken` through work that can take meaningful time or be cancelled by its caller. * Accept and propagate `CancellationToken` through work that can take meaningful time or be cancelled by its caller.
* In library and service code, use `ConfigureAwait(false)` or follow the project's CA2007 setting. In UI code (WPF view models and event handlers) use plain `await` so the continuation resumes on the UI thread. * In library and service code, use `ConfigureAwait(false)` or follow the project's CA2007 setting. In UI code (WPF view models and event handlers) use plain `await` so the continuation resumes on the UI thread.
* Bound concurrency for large or unbounded workloads. Avoid creating a task per item or using uncontrolled `Task.WhenAll`; use `Parallel.ForEachAsync` with `MaxDegreeOfParallelism` (.NET 6+) or `SemaphoreSlim.WaitAsync` with the release in `finally`. * Bound concurrency for large or unbounded workloads. Avoid creating a task per item or using uncontrolled `Task.WhenAll`; use `Parallel.ForEachAsync` with `MaxDegreeOfParallelism` (.NET 6+) or `SemaphoreSlim.WaitAsync` with the release in `finally`.
+26
View File
@@ -0,0 +1,26 @@
# C# Blazor
Apply these rules when building or changing Blazor components and apps. Performance and cross-platform reuse are the primary design goals. Check the target framework first: render modes, state persistence, and antiforgery behavior differ between .NET 8, 9, 10, and 11. Load the UI/UX rules for interface design and the shared web security rule for browser concerns.
## Performance
* Measure before optimizing: profile rendering, download size, and server memory in `Release` builds against a baseline.
* Choose the render mode for its cost: static server rendering for content, interactive server where latency is low and connections are few, WebAssembly where offline use or server load matters, and Auto to combine fast first load with client execution. Each mode moves cost between download size, server memory, and network latency.
* Keep WebAssembly payloads small: trim, lazy load rarely used assemblies with `BlazorWebAssemblyLazyLoad`, and serve compressed, fingerprinted assets. Enable AOT (`RunAOTCompilation`, with `WasmStripILAfterAOT`) only for CPU-heavy apps, because it speeds execution but enlarges the download.
* Expect prerendered components to initialize twice. Persist prerendered state with `PersistentComponentState`, or `[PersistentState]` on .NET 10+, instead of repeating service and database calls.
* Use streaming rendering (`[StreamRendering]`) to show content while slow data loads on static server rendering.
* Render less: virtualize large lists with `Virtualize`, give list items a stable `@key`, avoid unnecessary `StateHasChanged` calls, override `ShouldRender` for components with costly subtrees, and avoid creating thousands of small component instances in a loop when plain markup would do.
* Batch JavaScript interop. Avoid many fine-grained calls in loops, and pass small, serializable data.
* On interactive server rendering, keep circuit state small, release large objects promptly, and avoid per-user caches that grow without bounds.
## Cross-platform
* Put shared UI in a Razor class library that works in every host: Blazor Web App, WebAssembly, and Blazor Hybrid in .NET MAUI (`BlazorWebView`). Keep host-specific code out of it.
* Access platform features (device info, storage, files, notifications) through interfaces in the shared library, implemented per host and registered with dependency injection.
* Write components that work in every render mode they may run in: no browser-only APIs before the first render, no assumption of an HTTP context, and JavaScript interop only in `OnAfterRenderAsync(firstRender)`.
* Treat all WebAssembly and Hybrid client code and data as public. Never ship secrets or rely on client-side authorization; `AuthorizeView` and `[Authorize]` only hide UI. Enforce authorization in the server APIs and data access the client calls.
* Keep per-user state out of singleton services. On interactive server rendering, state lives in the user's circuit and is lost on disconnect; persist what must survive a reconnect or reload.
* Keep `app.UseAntiforgery()` in the pipeline. `EditForm` adds the token automatically; add `<AntiforgeryToken />` to plain HTML forms. Validate forms with a validator component and again on the server.
* Dispose `IJSObjectReference` and `DotNetObjectReference` instances in `DisposeAsync`, catch `JSDisconnectedException` there for server circuits, and implement `IDisposable` or `IAsyncDisposable` to unsubscribe events and stop timers.
* Never render untrusted content with `MarkupString`; let Razor encode it. Wrap risky regions in `ErrorBoundary` and keep detailed errors out of production.
* Test every host and render mode you ship, including Hybrid on each MAUI target platform.
@@ -2,7 +2,7 @@
Apply these rules when editing C# syntax, class structure, and everyday code organization. Apply these rules when editing C# syntax, class structure, and everyday code organization.
* Follow the style already used in the project. Before using newer syntax, check `TargetFramework` and `LangVersion`, including `Directory.Build.props`: `net10.0` defaults to C# 14, while .NET Framework 4.x defaults to C# 7.3, where records, file-scoped namespaces, collection expressions, primary constructors, and the `field` keyword are unavailable. Do not raise `LangVersion` without approval. * Follow the style already used in the project. Before using newer syntax, check `TargetFramework` and `LangVersion`, including `Directory.Build.props`: `net11.0` defaults to C# 15 and `net10.0` to C# 14, while .NET Framework 4.x defaults to C# 7.3, where records, file-scoped namespaces, collection expressions, primary constructors, and the `field` keyword are unavailable. Do not raise `LangVersion` without approval.
* Within the available language version, prefer direct, readable code over clever control flow, hidden magic, or outdated verbosity. * Within the available language version, prefer direct, readable code over clever control flow, hidden magic, or outdated verbosity.
* Keep classes, methods, and responsibilities focused. Use descriptive names and established domain terms; avoid unexplained abbreviations. * Keep classes, methods, and responsibilities focused. Use descriptive names and established domain terms; avoid unexplained abbreviations.
* Prefer composition over inheritance. Use inheritance only for a real substitutable contract, and seal types when extension is not intended. * Prefer composition over inheritance. Use inheritance only for a real substitutable contract, and seal types when extension is not intended.
+28
View File
@@ -0,0 +1,28 @@
# C# .NET MAUI
Apply these rules when building or changing .NET MAUI apps. Performance and cross-platform behavior are the primary design goals. Check the project's `TargetFrameworks` first: runtimes, compilation defaults, and controls differ between MAUI 8, 9, 10, and 11. Load the UI/UX rules for interface design and the C# performance rule for measurement.
## Performance
* Measure before optimizing, on real devices in `Release` builds: profile startup and hot paths with `dotnet-trace` or the MAUI profiling tooling, and compare against a baseline. Emulators and `Debug` builds do not show shipping performance.
* Choose the compilation strategy per platform and record why: ReadyToRun (the `Release` default, with `MauiEnableFullReadyToRun` for faster startup at a larger package), or NativeAOT for the smallest size and fastest startup where the app and its libraries are trim and AOT compatible. On Android, ReadyToRun requires `PublishTrimmed=true`.
* Keep the app trim and AOT safe: compiled bindings with `x:DataType` everywhere, no reflection-based serialization or DI scanning, and no trim warnings left unexplained.
* Keep startup lean: register services in `MauiProgram` without doing work there, defer non-essential initialization until after the first page renders, and load data asynchronously.
* Use `CollectionView` (not the deprecated `ListView`) with simple, flat item templates, and virtualize long lists. Avoid nested scroll views and per-item heavy converters or bindings.
* Prefer flat `Grid` layouts over deeply nested `StackLayout` trees, use `Border` instead of the obsolete `Frame`, and avoid fixed sizes that force re-measuring.
* Size images for their display size, use platform-appropriate formats, and cache remote images. Never decode full-resolution images for thumbnails.
* Keep the main thread free: run I/O and CPU work off it, and marshal only UI updates back with `MainThread.BeginInvokeOnMainThread` or the dispatcher.
* Unsubscribe events and dispose resources when pages disappear, so navigation does not leak pages, view models, or native views.
## Cross-platform
* Share UI, view models, and services by default. Put platform code in the `Platforms` folders or partial classes behind interfaces, and choose `OnPlatform`, `OnIdiom`, or conditional compilation only for real platform differences.
* Follow each target platform's conventions where people notice them: navigation, back behavior, tab placement, dialogs, and system fonts. Apply Apple's conventions to iOS and Mac Catalyst targets, Material to Android, and Windows conventions to Windows.
* Design for every supported size class and input: phone, tablet, and desktop windows, touch, mouse, and keyboard, safe areas, and text scaling.
* Customize controls through handlers and their mappers. Treat Xamarin custom renderers and compatibility renderers as temporary migration steps.
* Use MVVM with view models free of view types; prefer the project's MVVM library, such as CommunityToolkit.Mvvm source generators. Register pages and view models through dependency injection and navigate with Shell routes and typed parameters where the app uses Shell.
* Store tokens and other secrets with `SecureStorage`, never `Preferences`. Wrap `SecureStorage` calls in error handling and exclude its file from Android Auto Backup, because restored values cannot be decrypted on a new device.
* Request runtime permissions through `Permissions` at the point of use, and keep the feature usable or explained when a permission is denied.
* Expect suspension and termination: persist essential state in lifecycle events and restore it on resume.
* Set `SemanticProperties.Description` and `SemanticProperties.Hint` on meaningful images and controls without a visible label.
* Build and test `Release` builds with trimming on every platform you ship. Trimming, AOT, and platform differences surface only there.
@@ -8,6 +8,7 @@ Apply these rules when handling external input, failures, logs, or sensitive inf
* Preserve useful exception context without exposing secrets, personal data, or internal details in logs, APIs, or user-facing errors. * Preserve useful exception context without exposing secrets, personal data, or internal details in logs, APIs, or user-facing errors.
* Use structured logging with message templates and named placeholders, not string interpolation (CA2254); use `[LoggerMessage]` source-generated methods in hot paths. Never log credentials, tokens, or sensitive payloads. * Use structured logging with message templates and named placeholders, not string interpolation (CA2254); use `[LoggerMessage]` source-generated methods in hot paths. Never log credentials, tokens, or sensitive payloads.
* Dispose owned resources with `using` or `await using` (for `IAsyncDisposable`), including on failure paths. Do not dispose dependencies injected by the container. * Dispose owned resources with `using` or `await using` (for `IAsyncDisposable`), including on failure paths. Do not dispose dependencies injected by the container.
* In ASP.NET Core, return errors as `ProblemDetails` (`AddProblemDetails`) without internal details, and validate options at startup with `ValidateDataAnnotations` or a validator plus `ValidateOnStart()` so invalid configuration fails before the first request.
* Use narrow exception handling around the operation that can fail. Do not catch broadly merely to retry, continue with partial state, or convert failures into success. * Use narrow exception handling around the operation that can fail. Do not catch broadly merely to retry, continue with partial state, or convert failures into success.
* Avoid returning different error detail to unauthenticated callers when it would disclose whether protected accounts, records, or resources exist. * Avoid returning different error detail to unauthenticated callers when it would disclose whether protected accounts, records, or resources exist.
* Treat resource limits as part of safe error handling: cap request bodies, page sizes, query complexity, decompressed data, collection sizes, parser depth, and other attacker-controlled work. * Treat resource limits as part of safe error handling: cap request bodies, page sizes, query complexity, decompressed data, collection sizes, parser depth, and other attacker-controlled work.
@@ -9,3 +9,6 @@ Apply these rules when designing type contracts, choosing collection shapes, or
* Choose collection types based on lookup, ordering, mutation, and iteration needs. Pre-size collections only when expected capacity is known and material. * Choose collection types based on lookup, ordering, mutation, and iteration needs. Pre-size collections only when expected capacity is known and material.
* Avoid large mutable structs and direct exposure of mutable internal collections. * Avoid large mutable structs and direct exposure of mutable internal collections.
* Prefer immutable data and readonly state where practical, while preserving established API and serialization contracts. * Prefer immutable data and readonly state where practical, while preserving established API and serialization contracts.
* Pass `StringComparison` explicitly (CA1307, CA1309): `Ordinal` or `OrdinalIgnoreCase` for identifiers, keys, paths, and protocol values; culture-aware comparison only for text shown to users.
* Parse and format machine-readable numbers and dates with `CultureInfo.InvariantCulture`, and user-facing values with the user's culture. Never rely on the thread's current culture for data exchanged with files, APIs, or databases.
* Store and compute times in UTC or as `DateTimeOffset`, and convert to local time only for display. Read the clock through `TimeProvider` where tests need control.
+24 -7
View File
@@ -1,10 +1,27 @@
# Decision Rule # Decision Rule
* Gather evidence from the repository, available tooling, and current technical sources before making technical decisions. Apply these rules when requirements are unclear or a significant technical, product, or workflow choice must be made.
* Make technical implementation and code-style decisions independently when existing code, reliable documentation, or established standards provide sufficient evidence and the decision is reversible.
* Ask the user when technical uncertainty remains material, multiple meaningful options remain, or the decision has a high-impact or difficult-to-reverse effect. ## Decide or ask
* Ask the user before deciding business behavior, domain rules, validation rules, status transitions, permissions, database rules, error behavior, UI, UX, or other user-visible behavior when the requested behavior is missing or contradictory and the choice materially affects users, safety, or compatibility. Make minor reversible UI choices independently.
* Implement explicitly specified behavior without asking again. * Gather evidence from the repository, available tooling, and current technical sources before deciding, in proportion to the decision's impact.
* Ask the user when changing or choosing an API, database model, configuration format, external contract, or compatibility behavior remains ambiguous or has multiple meaningful interpretations. * Decide technical implementation and code-style questions yourself when existing code, reliable documentation, or established standards give sufficient evidence and the choice is reversible. Make minor reversible UI choices yourself.
* Do not invent business requirements or silently resolve contradictions. * Ask the user when a choice is missing, contradictory, or has several meaningful options and it materially affects any of these: business behavior, domain, validation or permission rules, status transitions, error behavior, user-visible UI or UX, APIs, database models, configuration formats, external contracts, compatibility, or anything high impact or hard to reverse.
* Implement explicitly specified behavior without asking again. Do not invent business requirements or silently resolve contradictions.
## How to ask
* Ask only what changes the work, and batch open questions into one message.
* Give each question two to four concrete options with their trade-offs, and put your recommendation first.
* Continue with work the question does not block while you wait.
## When no one can answer
* In background runs, scheduled tasks, or delegated work without user access, finish the unblocked work first.
* For a remaining reversible choice, take the safest option, record the assumption where the result is reported, and name it in the final report.
* Never make an irreversible, destructive, or business-rule decision on the user's behalf; stop at that point and report what is needed.
## User decisions
* Treat direct user input as the final decision for behavior and requirements. * Treat direct user input as the final decision for behavior and requirements.
* If a decision carries a concrete defect, security, or data-loss risk, name the risk once with evidence, then follow the decision.
+4 -4
View File
@@ -1,6 +1,6 @@
# Definition of Done # Definition of Done
A task is only considered done when all applicable requirements below are fulfilled. Apply these rules before claiming completion or review readiness. A task is only considered done when all applicable requirements below are fulfilled.
## Requirements ## Requirements
@@ -11,7 +11,7 @@ A task is only considered done when all applicable requirements below are fulfil
## Verification ## Verification
* Verification is sufficient for the change's risk and scope, following `general.md`'s Verification rules. A build, test run, new test, or independent review is not required for every change. * Verification is sufficient for the change's risk and scope, following the proportional verification rule in the general rules. A build, test run, new test, or independent review is not required for every change.
* Checks selected on that basis, and checks explicitly required by the user or project, have passed. Material gaps and pre-existing failures are reported without claiming unverified success. * Checks selected on that basis, and checks explicitly required by the user or project, have passed. Material gaps and pre-existing failures are reported without claiming unverified success.
* Any delegated research, review, or verification is complete and its relevant findings are resolved or reported. * Any delegated research, review, or verification is complete and its relevant findings are resolved or reported.
* External technology claims MUST pass the verification checkpoint in `technical-research`. Required unsupported assumptions or missing execution evidence leave affected criteria unverified; a Context7 call alone does not establish completion. * External technology claims MUST pass the verification checkpoint in `technical-research`. Required unsupported assumptions or missing execution evidence leave affected criteria unverified; a Context7 call alone does not establish completion.
@@ -20,11 +20,11 @@ A task is only considered done when all applicable requirements below are fulfil
* The implementation follows the project's coding, architecture, security, and performance guidelines and handles errors and edge cases appropriately. * The implementation follows the project's coding, architecture, security, and performance guidelines and handles errors and edge cases appropriately.
* No unrelated changes are included. * No unrelated changes are included.
* No temporary code, debug output, commented-out code, placeholders, or TODOs remain unless explicitly intended. * No temporary code, debug output, commented-out code, placeholders, or TODOs remain unless explicitly intended. A `shortcut:` comment that documents a known limit and when to upgrade counts as intended.
* Directly affected documentation and comments are updated; other documentation or comments are added only for a concrete need. * Directly affected documentation and comments are updated; other documentation or comments are added only for a concrete need.
## Work item state ## Work item state
* Do not mark, close, resolve, or otherwise change the state of a work item automatically. A task may be technically complete without changing its remote work item state. * Do not mark, close, resolve, or otherwise change the state of a work item automatically. A task may be technically complete without changing its remote work item state.
* Perform an Azure DevOps write only when the user explicitly requests or approves that specific action. A direct request in the current task is sufficient; do not ask for the same approval again. * Perform Azure DevOps and other remote writes only under the remote-system rules (`rules/microsoft.md` / `rules-microsoft`).
* If completion is unclear, requirements conflict, or something is missing, ask the user instead of deciding autonomously. * If completion is unclear, requirements conflict, or something is missing, ask the user instead of deciding autonomously.
+5 -6
View File
@@ -8,15 +8,14 @@ Use one applicable workflow per task, with the research gates below for searches
Never create or switch branches or worktrees unless the user explicitly requests it; stay on the current branch and do not ask about it. Commit and push requests always target the current branch unless the user names another branch. Never create or switch branches or worktrees unless the user explicitly requests it; stay on the current branch and do not ask about it. Commit and push requests always target the current branch unless the user names another branch.
For development tasks (code, script, hook, configuration, or UI changes; debugging; code review), MUST apply `plugin-workflow` before the first action, on resume, and at phase changes. Skip it for questions and prose-only changes. It coordinates Superpowers, Ponytail, Impeccable, Modern Web Guidance, i-have-adhd, and Caveman; reuse loaded instructions and preserve user opt-outs. MUST load `plugin-workflow` at the start of every session, including questions and prose-only work, and again after resume and compaction. Within a session, reuse the loaded copy for later tasks and phase changes. Subagents skip it; the parent passes the constraints that apply to the assignment. It coordinates the installed workflow, UI, web, and style plugins; each plugin layer applies only at its own triggers. Reuse loaded instructions and preserve opt-outs.
When writing or substantially rewriting prose read outside the chat (documentation, READMEs, comments, commit or PR bodies, UI copy, messages), MUST apply `humanizer` when installed before finishing; keep facts, terms, code, and required structure. Skip chat replies, quoted or generated text, and small fixes such as typos. For new or substantially rewritten prose outside the chat (docs, comments, commit/PR bodies, UI copy, messages), MUST apply installed `humanizer`; keep facts, terms, and code. Skip chat replies and small fixes.
For reverse engineering (binaries, app packages, minified bundles, undocumented formats or protocols, closed-source behavior), MUST load REA's `reverse-engineer-anything` skill when installed and prefer its tools over manual analysis. Analyze only targets the user is authorized to inspect. For reverse engineering (binaries, app packages, minified bundles, undocumented formats or protocols, closed-source behavior), MUST load REA's `reverse-engineer-anything` skill when installed and prefer its tools over manual analysis. Analyze only targets the user is authorized to inspect.
Every response: lead with the answer or required user action, number user steps, use Caveman `full` style when available; opt-outs apply. Every response: lead with the answer or required user action, number user steps, use Caveman style at the plugin's default level when available; opt-outs apply.
Before open searches (unknown locations or identifiers, behavior questions, discovery), MUST load and apply `research`, including for repository sources; before every external technology lookup, MUST load `technical-research`. Direct reads of known paths and exact matches of known identifiers need no skill load. Every lookup: define the question, inspect authoritative results, and disclose gaps. If a required skill is unavailable, report it and apply these checks. Before open searches (unknown locations or identifiers, behavior questions, discovery), MUST load and apply `research`, including for repository sources. Before relying on external technology behavior in any answer, plan, code, review, debugging, configuration, test, or upgrade, MUST apply `technical-research` and its gate and phase checkpoints, including inside plugin workflows. Direct reads of known paths and exact matches of known identifiers need no skill load. Every lookup: define the question, inspect authoritative results, and disclose gaps. If a required skill is unavailable, report it and apply these checks.
Known paths, symbols, strings, or errors use direct reads/`rg`. For unknown identifiers, apply installed `semantic-search`: semantic retrieval first, with its documented failure/rephrasing fallback. Known paths, symbols, strings, or errors use direct reads/`rg`. For unknown identifiers, apply installed `semantic-search`: semantic retrieval first, with its documented failure/rephrasing fallback.
Before relying on external technology behavior in any answer, plan, code, review, debugging, configuration, test, or upgrade, MUST automatically apply `technical-research`'s Context7-first gate and phase checkpoints, including inside plugin workflows. Follow its version checks, evidence reuse, query limits, and explicit source fallback.
Verify proportionally: run the cheapest check that detects likely failure; broaden for security, data loss, integration, or cross-component risk. Never claim unrun checks passed. Report failures and material gaps. Verify proportionally: run the cheapest check that detects likely failure; broaden for security, data loss, integration, or cross-component risk. Never claim unrun checks passed. Report failures and material gaps.
Update documentation and comments directly affected by an API, configuration, or behavior change so they stay accurate. Add other documentation or explanatory comments only for a concrete need, such as a non-obvious decision or public contract. Write repository content and user-facing output in English. Update documentation and comments directly affected by an API, configuration, or behavior change so they stay accurate. Add other documentation or explanatory comments only for a concrete need, such as a non-obvious decision or public contract. Write repository content in English; write user-facing output in the user's language.
+28 -157
View File
@@ -1,175 +1,46 @@
# Git Guidelines # Git Guidelines
## General Rules Apply these rules to Git operations: staging, commits, branches, history changes, merges, and pushes.
* Never commit changes unless explicitly instructed to do so. ## Authorization
* Never push changes unless explicitly instructed to do so.
* Never create a pull request unless explicitly instructed to do so.
* Never merge branches unless explicitly instructed to do so.
* Never rebase branches unless explicitly instructed to do so.
* Never amend an existing commit unless explicitly instructed to do so.
* Never create or delete Git tags unless explicitly instructed to do so.
* Never modify remote branches unless explicitly instructed to do so.
* Do not interpret general requests such as "finish this", "implement this", or "fix this" as permission to commit or push.
* Permission to commit does not imply permission to push.
* Permission to push does not imply permission to create or merge a pull request.
* Only perform Git write operations that the user explicitly requested.
* Read-only Git commands may be used when needed to inspect repository state.
* Create commits only with `git commit` and push commits only with `git push`. Never create commits or publish repository code through REST APIs, hosting-provider APIs, or other non-Git interfaces.
## Repository Safety The agent may edit files and run read-only Git commands (status, diff, log, show, fetch for inspection) whenever useful. Every Git write needs an explicit user request for that action, each time:
* Always inspect the current Git status before performing Git write operations. * commit, push, pull with merge or rebase, merge, rebase, amend, revert, or cherry-pick
* Never discard uncommitted user changes. * create, switch, rename, or delete a branch or worktree
* Never overwrite unrelated changes. * create or delete a tag, or change a remote branch
* Never reset, clean, checkout, restore, or revert user changes unless explicitly requested. * create, comment on, approve, complete, or merge a pull request
* Never use destructive Git operations without explicit instruction. * discard, reset, clean, restore, or stash working-tree changes
* Never use `git reset --hard` unless explicitly requested.
* Never use `git clean` unless explicitly requested.
* Never force-push unless explicitly requested.
* Never use `--force` or `--force-with-lease` unless explicitly requested.
* Never rewrite shared history without explicit instruction.
* Never modify `.gitignore` unless required by the task.
* Never commit secrets, credentials, tokens, API keys, private keys, environment files, or other sensitive data.
* Never bypass Git hooks unless explicitly requested.
* Never use `--no-verify` unless explicitly requested.
## Scope Permission does not carry over: a commit request does not allow a push, and a push does not allow a pull request. General requests such as "finish this", "fix this", or "implement this" never authorize a Git write. When in doubt, leave changes uncommitted.
* Only stage files related to the requested task. Create commits only with `git commit` and push only with `git push`; never publish code through REST or hosting-provider APIs. Pull requests and their comments, votes, and merges on Azure DevOps, Gitea, or other hosts are remote writes under the remote-system rules (`rules/microsoft.md` / `rules-microsoft`).
* Never stage unrelated modified files.
* Prefer staging specific files instead of using broad commands such as `git add .`.
* Do not include generated files unless they are intentionally tracked by the repository.
* Do not include formatting-only changes unrelated to the task.
* Do not modify unrelated files merely to create a cleaner commit.
* Keep commits focused on one logical change.
* Split unrelated changes into separate commits when multiple commits were explicitly requested.
## Commit Messages
Use Conventional Commits.
Format:
`<type>(<optional-scope>): <description>`
Allowed common types:
* `feat`: new functionality
* `fix`: bug fix
* `refactor`: code change without changing external behavior
* `perf`: performance improvement
* `test`: test changes
* `docs`: documentation changes
* `style`: formatting or style-only changes
* `build`: build system or dependency changes
* `ci`: CI/CD changes
* `chore`: maintenance work
* `revert`: revert of an earlier change
Commit message rules:
* Use lowercase commit types.
* Keep the subject concise and specific.
* Use imperative wording.
* Do not end the subject with a period.
* Describe what changed, not how hard the work was.
* Avoid vague messages such as `fix stuff`, `update`, `changes`, or `cleanup`.
* Use a scope when it improves clarity.
* Keep each commit limited to one logical purpose.
* Use `!` or a `BREAKING CHANGE:` footer for breaking changes.
* Reference issue or ticket identifiers only when relevant and known.
* Never invent issue numbers, ticket IDs, or references.
Examples of valid commit messages:
* `feat(auth): add refresh token rotation`
* `fix(api): handle missing user id`
* `refactor(storage): simplify cache abstraction`
* `perf(database): reduce duplicate queries`
* `test(users): add validation coverage`
* `docs(readme): document local setup`
* `build: update dotnet dependencies`
## Branches ## Branches
* Apply all work and Git operations to the current branch in the current checkout unless the user explicitly names another branch or worktree. * Work on the current branch and checkout. Do not ask about branches or worktrees, and ignore skill, plugin, or tool defaults that suggest new ones.
* Do not ask whether to create a branch, switch branches, or use a worktree. Stay on the current branch instead. * Commit to the current branch and push it to its upstream unless the user names another target. Never assume the target of a merge or rebase.
* Never create or switch branches unless explicitly requested. * When the user asks for a branch, follow the repository's naming convention, or `feat/`, `fix/`, `refactor/`, or `chore/` prefixes without one.
* Never create worktrees unless explicitly requested.
* Ignore skill, plugin, or tool defaults that suggest a new branch or worktree.
* Never delete branches unless explicitly requested.
* Never rename branches unless explicitly requested.
* Commit on the current branch unless the user names another branch.
* Push the current branch to its upstream unless the user names another target.
* Never assume the target branch for a merge or rebase.
* Preserve the repository's existing branch naming convention.
* If no branch naming convention exists and a branch was explicitly requested, prefer concise names such as:
* `feat/<name>` ## Safety
* `fix/<name>`
* `refactor/<name>`
* `chore/<name>`
## Pulling and Fetching * Never discard, overwrite, reset, clean, restore, or revert user changes, and never rewrite shared history, without an explicit request.
* Never use `git reset --hard`, `git clean`, `--force`, `--force-with-lease`, or `--no-verify`, and never bypass hooks or signing, unless the user explicitly asks.
* Do not pull, merge, or rebase automatically. Stop before a destructive conflict resolution; resolve a conflict only when the correct result is clear, keep both sides' work where possible, and never drop unrelated changes.
* Preserve each file's existing line endings and encoding. Do not commit whole-file line-ending or formatting changes unrelated to the task.
* Never commit secrets, credentials, tokens, keys, environment files, or other sensitive data. Change `.gitignore` only when the task requires it.
* Fetching remote state is allowed when required for inspection. ## Commits
* Do not pull automatically unless explicitly requested or required for an explicitly requested Git operation.
* Never resolve pull or merge conflicts by discarding user changes.
* Do not automatically rebase after pulling.
* Do not automatically merge remote changes into the current branch.
## Conflicts Before a requested commit:
* Stop before making destructive conflict-resolution decisions. 1. Inspect `git status`, stage only task-related files by name instead of `git add .`, and review the staged diff.
* Preserve both user work and repository history whenever possible. 2. Check the diff for secrets, unrelated changes, and untracked generated files.
* Resolve conflicts only when the correct resolution is clear from the task and surrounding code. 3. Run relevant checks when practical, and report any that were not run.
* Do not silently choose one side of a conflict when intent is ambiguous. 4. If the working tree holds several unrelated changes, propose one commit per logical change; split them only when the user agrees or asked for multiple commits.
* Never use conflict resolution as an excuse to remove unrelated changes.
## Before an Explicitly Requested Commit Write messages as Conventional Commits in English: `<type>(<optional-scope>): <description>`, with a lowercase type (`feat`, `fix`, `refactor`, `perf`, `test`, `docs`, `style`, `build`, `ci`, `chore`, `revert`), an imperative subject without a trailing period, and `!` or a `BREAKING CHANGE:` footer for breaking changes. Describe what changed and why, never effort; avoid vague subjects such as `update` or `fix stuff`. Apply `humanizer` to new or rewritten commit bodies. Reference issue or ticket IDs only when they are known; never invent them.
Before creating a commit: ## Before a requested push
* Inspect `git status`. Confirm the push was requested, push the current branch unless another was named, confirm the remote when several exist, and check that only the expected commits will be pushed.
* Inspect the staged diff.
* Confirm only task-related files are staged.
* Check for accidental secrets or sensitive files.
* Ensure the changes are consistent with the requested task.
* Run relevant tests, checks, or builds when practical.
* Do not include unrelated modifications.
* Use a Conventional Commit message.
## Before an Explicitly Requested Push
Before pushing:
* Confirm that pushing was explicitly requested.
* Push the current branch unless the user named another branch.
* Confirm the intended remote when multiple remotes exist.
* Ensure the commits being pushed are expected.
* Do not force-push unless explicitly requested.
* Do not push unrelated local commits unintentionally.
## Autonomous Agent Rule
The agent may edit files and implement requested changes autonomously.
The agent must not autonomously:
* commit
* push
* merge
* rebase
* amend commits
* create pull requests
* create or delete tags
* create or switch branches
* create worktrees
* delete branches
* rewrite Git history
* discard working-tree changes
These actions require explicit user instruction each time.
When in doubt, leave the repository changes uncommitted.
-15
View File
@@ -1,15 +0,0 @@
# Java Rules
For Java or JVM work, open only the topic rules relevant to the task. Follow the project's target Java release, compiler settings, and conventions. Load applicable shared security rules as well. Avoid preview APIs unless the project explicitly enables them.
| Topic | Codex rule | Claude skill |
| --- | --- | --- |
| Language style and code organization | `references/modern-java.md` | `rules-java-modern-java` |
| Types, collections, and null-safe contracts | `references/types-and-collections.md` | `rules-java-types-and-collections` |
| Architecture and API boundaries | `references/architecture-and-apis.md` | `rules-java-architecture-and-apis` |
| Async work and concurrency | `references/async-and-concurrency.md` | `rules-java-async-and-concurrency` |
| Performance | `references/performance.md` | `rules-java-performance` |
| Security | `references/security.md` | `rules-java-security` |
| Spring Boot and Spring Security | `references/spring.md` | `rules-java-spring` |
| Validation, errors, and logging | `references/safety-and-errors.md` | `rules-java-safety-and-errors` |
| Tests, dependencies, and build diagnostics | `references/testing-and-dependencies.md` | `rules-java-testing-and-dependencies` |
@@ -1,11 +0,0 @@
# Java Architecture and APIs
Apply these rules when designing public APIs, service boundaries, or application structure.
* Give APIs explicit request, response, and error contracts. Validate external input at the boundary without scattering redundant format checks through trusted internal code; authorization, ownership, and tenant scoping are never such redundant checks.
* Separate transport models, domain models, and persistence entities. Accept only fields callers may set and return only fields they may read.
* Authorize the specific resource and operation where data is accessed or changed. Preserve ownership and tenant scope across alternate paths and background work.
* Bound payloads, page sizes, query complexity, and operation cost. Use pagination or streaming for potentially large results.
* Keep domain decisions separate from transport, persistence, and framework wiring. Make dependencies explicit; use dependency injection for real lifecycle or substitution needs.
* Use small contracts at real boundaries. Avoid service locators.
* Preserve existing API and serialization behavior unless the task requires a change. Treat changes to nullability, ordering, exception types, and collection mutability as compatibility changes.
@@ -1,15 +0,0 @@
# Java Async and Concurrency
Apply these rules when changing executors, threads, futures, background work, or shared state.
* Choose synchronous, asynchronous, platform-thread, or virtual-thread execution for the actual workload and target Java release. Virtual threads suit many blocking I/O tasks; they do not accelerate CPU work.
* Create one virtual thread per task (`Executors.newVirtualThreadPerTaskExecutor()`); never pool virtual threads. Limit downstream concurrency with a `Semaphore`, not with a fixed pool size.
* On JDK 21 to 23, blocking inside `synchronized` pins the carrier thread; prefer `ReentrantLock` on hot blocking paths there. JDK 24+ (JEP 491) removes that pinning, but native frames and class initialization still pin.
* Do not cache expensive objects in `ThreadLocal` when running on virtual threads. On JDK 25+, prefer `ScopedValue` (final, JEP 506) for request-scoped context.
* Keep task lifetime owned by a request, service, or scoped executor. Close or shut down owned executors and handle completion, failure, timeout, and cancellation.
* Propagate interruption and cancellation. When catching `InterruptedException` without rethrowing it, restore the interrupt flag and stop work safely; do not turn cancellation into success.
* Bound queues, fan-out, and downstream calls. Virtual threads reduce thread cost but do not remove database, network, memory, or rate limits.
* Protect shared mutable state with clear ownership or suitable concurrency primitives. Do not assume `volatile` makes compound actions atomic.
* Avoid blocking joins inside unrelated executor tasks when they can exhaust a bounded pool. Use `CompletableFuture` or parallel streams only when their execution context and failure behavior are understood.
* Keep retries limited to transient failures, with bounded attempts and delay. Preserve idempotency and avoid retry multiplication across layers.
* Use preview concurrency APIs only when the project explicitly enables them for its target release; `StructuredTaskScope` is still a preview API in JDK 25.
@@ -1,12 +0,0 @@
# Java Coding Style
Apply these rules when editing Java syntax, class structure, and everyday code organization.
* Match the project's Java release, style, and framework conventions. Use newer syntax only when supported and clearer.
* Prefer direct control flow and descriptive domain names. Use streams when they clarify a transformation; loops are often clearer for stateful work or error handling.
* Use local `var` only when the initializer makes the type obvious. Keep public contracts explicitly typed.
* Use records for transparent immutable carriers and sealed types for genuinely closed variants when the target release supports them. Do not force them onto mutable entities or framework-managed types.
* Prefer composition and focused classes over inheritance, broad base classes, reflection, wrappers, global mutable state, or speculative interfaces.
* Make ownership, mutation, and side effects visible. Use `final` where it clarifies invariants; do not add it mechanically to every local variable.
* Prefer supported `java.time` APIs and standard library facilities over obsolete APIs or custom helpers when they fit the contract.
* Remove dead code. Add comments only for non-obvious decisions or public contracts that code cannot express clearly.
@@ -1,14 +0,0 @@
# Java Performance
Apply these rules when optimizing Java runtime, memory, or throughput.
* Measure a representative workload on the target JDK and deployment configuration before optimizing. Profile first; distinguish startup, steady-state latency, tail latency, throughput, allocation, GC, and memory costs.
* Prioritize algorithmic complexity, database and network round trips, I/O, contention, allocation and GC, then instruction-level work. Fix the dominant cost rather than tuning by intuition.
* Choose collections and algorithms for actual access patterns and data growth. Avoid repeated scans, needless sorting or copying, unbounded results, and N+1 data access.
* Filter and project in the data source when appropriate; avoid materializing rows or fields that the caller does not use. Bound page sizes and query work.
* Stream or process data in bounded chunks when whole-input buffering can exhaust memory. Bound queues, caches, thread pools, and parallel work to the capacity of downstream systems.
* Reduce allocation and boxing in profiled hot paths. Avoid premature object pooling, custom caches, and low-level tricks; pooling can retain memory or leak mutable state.
* Cache only when repeated work is measured and key, lifetime, invalidation, size limit, and sensitive-data handling are explicit.
* Use concurrency only when it improves measured end-to-end throughput or latency. Account for ordering, cancellation, backpressure, contention, and failure handling; virtual threads do not make CPU work faster.
* Use JMH for JVM microbenchmarks when isolating small operations; prevent dead-code elimination and account for warmup, forks, and measurement variance. Use production-like profiling for system behavior.
* Re-run the same workload after a change and compare correctness, CPU, allocation, GC, memory, latency, and throughput. Keep the simplest implementation that meets the measured goal.
@@ -1,11 +0,0 @@
# Java Safety and Error Handling
Apply these rules when handling external input, failures, resources, or logs.
* Validate size, range, format, and allowed values before expensive parsing, allocation, or side effects. Keep validation consistent with business and security constraints.
* Reject null where a value is required, with clear argument or boundary validation. Do not hide invalid state behind default values that change behavior.
* Use try-with-resources for owned `AutoCloseable` resources. Keep ownership explicit and do not close resources supplied by a caller unless the contract says so.
* Catch only failures the current layer can handle. Preserve exception causes and useful context; do not swallow failures, catch broadly to continue with partial state, or use exceptions for routine control flow.
* Preserve interruption and cancellation during error handling. Timeouts and retries need bounds and must not silently turn failure into success.
* Use structured logs where the project supports them. Never log credentials, tokens, personal data, or unbounded payloads; avoid excessive logging in hot paths. Pass untrusted values as parameters, never as the log format string, and strip or encode CR/LF in them unless the log format is structured.
* Return safe, consistent error information. Do not disclose protected resource existence or internal details to unauthorized callers.
-13
View File
@@ -1,13 +0,0 @@
# Java Security
Apply these rules to security-sensitive Java code. Load the shared security rule for each affected boundary (API, auth, web, data, files, network, crypto, supply chain, AI); this file adds only Java specifics, and the Spring rule covers Spring Boot and Spring Security.
* Use parameterized database APIs such as `PreparedStatement`. Select dynamic identifiers or sort expressions from a fixed allowlist; never concatenate untrusted data into SQL.
* Resolve file paths with `root.resolve(input).normalize()` and check containment with `Path.startsWith(root)`, never `String.startsWith`, which accepts `/data/app2` for `/data/app`. `normalize()` does not resolve symlinks; use `toRealPath()` when links matter and the file exists, and account for replacement races. Check every `ZipEntry` name the same way. Limit file size and processing work.
* Use `ProcessBuilder` with an absolute executable path and separate arguments; avoid shell interpretation. On Windows, the argument list is flattened into one command line that the target re-parses, and `.bat` or `.cmd` targets run through `cmd.exe`; never pass untrusted arguments to them, and validate attacker-controlled arguments against an allowlist.
* Parse untrusted XML with DTDs disabled (`http://apache.org/xml/features/disallow-doctype-decl` set to `true`), or, where DTDs are required, with external entities and external DTD and schema access disabled (`XMLConstants.ACCESS_EXTERNAL_DTD` and `ACCESS_EXTERNAL_SCHEMA` set to `""`, `XMLConstants.FEATURE_SECURE_PROCESSING` enabled). Apply this to every factory that reads untrusted XML: `DocumentBuilderFactory`, `SAXParserFactory`, `XMLInputFactory`, `TransformerFactory`, `SchemaFactory`, and JAXB unmarshallers.
* Deserialize into explicit allowed types and bound input size and nesting. Avoid native Java serialization for untrusted data; where it is unavoidable, install an `ObjectInputFilter` allowlist. With Jackson, never enable default typing (`activateDefaultTyping`) or `@JsonTypeInfo(use = Id.CLASS)` for untrusted input; use `Id.NAME` with registered subtypes or a strict `PolymorphicTypeValidator`. Spring Boot 4 uses Jackson 3 (`tools.jackson.*` packages; annotations stay in `com.fasterxml.jackson.annotation`). Load YAML with SnakeYAML 2.x or a `SafeConstructor`. Never evaluate untrusted SpEL, OGNL, or JNDI names.
* Use the platform's maintained TLS, cryptographic, and secure-random APIs with the parameters in the shared cryptography rule. Always specify the full `Cipher` transformation, for example `AES/GCM/NoPadding`, because `Cipher.getInstance("AES")` means ECB. Use `SecureRandom`, never `java.util.Random`, for security values, and `MessageDigest.isEqual` for constant-time comparison. Never install trust-all `X509TrustManager` or `HostnameVerifier` implementations. Do not rely on the Security Manager; JDK 24+ disables it permanently.
* For outbound URLs, parse with `java.net.URI` (the `URL` constructors are deprecated since JDK 20) and check every resolved `InetAddress` (`isLoopbackAddress`, `isLinkLocalAddress`, `isSiteLocalAddress`, `isAnyLocalAddress`, `isMulticastAddress`); these miss IPv6 unique-local `fc00::/7`, carrier-grade NAT `100.64.0.0/10`, and IPv4-mapped IPv6, so check those explicitly. Keep `java.net.http.HttpClient` on its default `Redirect.NEVER` or revalidate every hop.
* For regular expressions on untrusted input, bound the input length first and avoid nested or overlapping quantifiers, because `java.util.regex` has no timeout; use RE2/J for untrusted patterns.
* Encode output with the template engine's automatic escaping or the OWASP Java Encoder for the exact context; never build HTML, XML, LDAP, or JPQL from untrusted strings.
-12
View File
@@ -1,12 +0,0 @@
# Java Spring Boot and Spring Security
Apply these rules when changing Spring Boot configuration, Spring Security, Spring MVC or WebFlux endpoints, Spring Data repositories, or Actuator exposure. Follow the project's Spring Boot and Spring Security versions; Spring Boot 4 and Spring Framework 7 are current.
* Deny by default: end the `authorizeHttpRequests` chain with `.anyRequest().authenticated()` (or `denyAll()`) and list public routes explicitly with `permitAll`.
* Keep CSRF protection enabled for browser clients that authenticate with cookies or sessions. Disable it only for stateless token-authenticated APIs, and say why in the configuration.
* Expose only `health` and `info` Actuator endpoints publicly. Never expose `env`, `heapdump`, `threaddump`, `configprops`, `loggers`, `mappings`, or `beans` without authentication; `heapdump` and `env` leak secrets. Prefer a separate management port.
* Enforce method security (`@PreAuthorize` with `@EnableMethodSecurity`) on service methods reachable from non-HTTP entry points such as messaging, schedulers, or batch jobs.
* Bind requests to dedicated DTOs, never directly to JPA entities with `@RequestBody` or `@ModelAttribute`, to prevent mass assignment. Validate DTOs with Bean Validation (`@Valid`).
* Use parameter binding in JPQL, HQL, and `@Query` native SQL; never concatenate untrusted input into query strings. Select dynamic sort properties from an allowlist before building `Sort` objects.
* Store passwords through a `DelegatingPasswordEncoder` with an encoder that meets the shared cryptography rule, for example `Argon2PasswordEncoder.defaultsForSpringSecurity_v5_8()`, and upgrade legacy hashes on login.
* Keep secrets out of `application.yml` and profiles in the repository; bind them from environment variables or a secret store.
@@ -1,11 +0,0 @@
# Java Testing and Dependencies
Apply these rules when changing tests, build files, dependencies, or diagnostics.
* Write deterministic behavior-based tests for public contracts and failure paths. Avoid assertions tied to private call order, wall-clock timing, or uncontrolled external services.
* Test null and empty cases, malformed input, resource cleanup, interruption, and concurrency behavior when those risks are affected. Use integration tests for actual persistence, framework, or serialization boundaries.
* Keep production code testable through clear contracts and ownership. Do not add abstraction layers or production hooks solely for tests without a concrete need.
* Prefer the JDK and existing supported libraries when they solve the problem. Keep dependencies minimal, maintained, and compatible with the configured Java release.
* Respect the repository's Maven or Gradle dependency and plugin management. Review transitive changes, build plugins, and lockfiles; do not hand-edit generated dependency state.
* Treat compiler warnings and configured static-analysis findings as actionable. Suppress a diagnostic only with a specific reason and narrow scope.
* Run the focused tests and checks for the changed path; broaden verification when shared behavior, compatibility, or security is affected.
@@ -1,11 +0,0 @@
# Java Types and Collections
Apply these rules when defining type contracts, choosing collections, or handling nullable values.
* Write null-safe code. State whether each boundary value may be absent, validate required values before dereferencing, and use the project's nullability annotations and analysis tools when available. Do not assume an annotation enforces runtime validation.
* Prefer non-null return values and empty collections for valid empty results. Use `Optional<T>` mainly for a return value that may have no result; do not return a null `Optional` or use it for fields and parameters by default.
* Distinguish a missing map key from a key mapped to null when the contract permits both. Do not use `get()` alone when that distinction matters.
* Keep public contracts strongly typed. Avoid raw types, unchecked casts, and stringly typed maps; document and narrowly suppress unavoidable generic warnings.
* Choose `List`, `Set`, `Map`, or a more specific type according to ordering, uniqueness, lookup, and mutation needs. Expose only the capabilities callers need; do not leak mutable internal collections.
* Distinguish an unmodifiable view from an independent copy. Make defensive copies at ownership boundaries when later mutation would violate the contract.
* Prefer immutable data for values with stable identity and ownership, while respecting framework and serialization requirements. Avoid unnecessary boxing and copies in measured hot paths.
Loaded 100 of 247 files, more files were not shown because too many files have changed in this diff. Show more