diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 6a9eb98..240d0c2 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -1,7 +1,7 @@ { "$schema": "https://anthropic.com/claude-code/marketplace.schema.json", "name": "coding-discipline", - "description": "Lean, firm guardrails for coding agents: spec sync plus risk-triggered design alignment, TDD, root-cause debugging, prioritized review, evidence-based verification, disciplined git, and context hygiene.", + "description": "Root-cause debugging and spec sync, with on-demand design discussion and TDD.", "owner": { "name": "chipfighter" }, @@ -9,7 +9,7 @@ { "name": "coding-discipline", "source": "./plugins/coding-discipline", - "description": "Eight lean but firm skills, including spec-sync for durable intent and context-hygiene against stale documentation. They trigger only when their conditions match and stay strict once active. Includes a SessionStart discipline primer, passive local usage counting, and first-entry guide-doc seeding for CLAUDE.md / AGENTS.md." + "description": "Two automatically selected skills for root-cause debugging and spec sync, plus on-demand brainstorming and TDD." } ] } diff --git a/.gitattributes b/.gitattributes index 94017be..6f81f8a 100644 --- a/.gitattributes +++ b/.gitattributes @@ -2,24 +2,12 @@ .gitattributes text eol=lf .gitignore text eol=lf -# Hook scripts require LF. CRLF makes Git Bash report $'\r' errors and breaks -# the polyglot .cmd wrapper. -# Match extensionless scripts by filename: no slash applies repository-wide, -# while a slash would incorrectly anchor the pattern at the repository root. -*.sh text eol=lf -session-start-skills text eol=lf -log-usage text eol=lf - -# The polyglot wrapper is parsed by both cmd and bash; modern cmd.exe handles LF. -*.cmd text eol=lf - # Other text *.md text eol=lf *.json text eol=lf *.yml text eol=lf *.yaml text eol=lf *.py text eol=lf -*.ps1 text eol=lf # Binary *.png binary diff --git a/.github/ISSUE_TEMPLATE/routing-feedback.md b/.github/ISSUE_TEMPLATE/routing-feedback.md index 81b5ce8..a173781 100644 --- a/.github/ISSUE_TEMPLATE/routing-feedback.md +++ b/.github/ISSUE_TEMPLATE/routing-feedback.md @@ -1,21 +1,17 @@ --- -name: Routing feedback (false trigger / missed trigger) -about: A skill triggered when it should not have, or failed to trigger when it should +name: Skill invocation feedback +about: Report an unexpected skill invocation or an invocation that was missed or failed labels: routing --- -**Type** (keep one): false trigger / missed trigger +**Type** (keep one) · false trigger / missed trigger / explicit invocation failed -**Skill involved**: +**Skill and explicit command, if any** -**Original task prompt** (paste it as closely as possible): +**Original task prompt** -**Expected behavior**: +**Expected behavior** -**Actual behavior**: +**Actual behavior** -**Model**: - -**Harness**: Claude Code / Codex / other - -**Was the skill invoked explicitly?**: yes / no +**Plugin version, model, and host version** diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 31af56d..6e16fe8 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -26,10 +26,3 @@ jobs: run: python tests/test-plugin-metadata.py - name: Scan the shipped skill surface run: python tests/test-skill-safety.py - - name: Test hooks on Linux - if: runner.os == 'Linux' - run: bash tests/test-hooks.sh - - name: Test hooks on Windows - if: runner.os == 'Windows' - shell: pwsh - run: powershell -NoProfile -ExecutionPolicy Bypass -File tests/test-windows-hook.ps1 diff --git a/README.md b/README.md index c6d4462..e3a524e 100644 --- a/README.md +++ b/README.md @@ -1,75 +1,24 @@ # coding-discipline -**Chinese** → [README.zh-CN.md](README.zh-CN.md) +**Chinese** · [README.zh-CN.md](README.zh-CN.md) -**Guardrails, not a workflow.** Quiet on routine work; firm when a named -failure mode is at risk. - -AI coding agents tend to fail in two expensive ways: - -1. **They drift off-goal.** A decision is confirmed in chat, but the next - session reads a stale spec and builds the old target. -2. **They skip steps.** They code before requirements are aligned, patch - symptoms before finding the root cause, or claim success without current - evidence. - -`coding-discipline` is a lightweight, workflow-agnostic plugin that addresses -both: - -- **Spec sync** writes confirmed goals, non-goals, constraints, and acceptance - criteria back to the current source of truth when later sessions would - otherwise act on stale intent. -- **Risk-triggered discipline** invokes firm engineering guardrails only when - their conditions match: design alignment, TDD, systematic debugging, - prioritized review, evidence-before-done, disciplined git flow, and context - hygiene. - -It does **not** replace Plan mode, launch subagents, orchestrate worktrees, -choose models, or force every task through a spec workflow. Small changes stay -small. When a risk trigger matches, the corresponding skill stays firm. - -8 skills + 2 hooks. Install once, apply globally. Supports Claude Code and -Codex. - -## Why this exists - -[Superpowers](https://github.com/obra/superpowers) proved that engineering -discipline can live in agent skills — this plugin even reuses its -cross-platform hook pattern (see Credits). But Superpowers is a complete -workflow: its bootstrap asks the agent to route every response, even a -clarifying question, through the skill system first. - -coding-discipline starts from the opposite default. Skills stay dormant until -a named failure mode is at risk; routine work runs untouched. The fixed -context injected per session is ~1.2k tokens and cannot silently grow — a CI -test fails the build when it does. The cost that actually differs between -plugins is how often one inserts itself, and what it spawns when it does. - -On top of the guardrails, this project adds a piece of its own: the spec -layer. spec-sync writes confirmed goals, non-goals, hard constraints, and -acceptance criteria back into the docs the project already has — no -proposal → approve → archive lifecycle, no new artifacts — so the next -session does not rebuild a target you already rejected. - -Use it when you want more discipline than a bare coding agent, but do not -want another orchestration layer. +A small plugin for Claude Code and Codex. It helps trace bugs with an unclear +cause and keeps confirmed project decisions available across sessions. +Brainstorming and test-driven development are available when you ask for them. ## Install ### Codex -```bash +```text codex plugin marketplace add chipfighter/coding-discipline codex plugin add coding-discipline@coding-discipline ``` -Open a new task after installation. The first time a hook is enabled, and -whenever it changes, Codex asks you to review it. Use `/hooks` to inspect and -trust it. - -To test a local checkout, replace the first command with: +Open a new chat after installation. To test a local checkout, run the following +from the repository root in place of the first command. -```bash +```text codex plugin marketplace add . ``` @@ -80,197 +29,93 @@ codex plugin marketplace add . /plugin install coding-discipline@coding-discipline ``` -The first command adds this repository as a self-hosted plugin source; the -second installs the plugin. Open a new session after installation. To test a -local checkout, replace the repository name in the first command with a local -path. - -### Skills only, without hooks (Codex and other hosts) +Open a new session after installation. To test a local checkout, replace +`chipfighter/coding-discipline` in the first command with the local path. -The eight skills are plain `SKILL.md` files that conform to the -[agentskills.io](https://agentskills.io) spec — conformant `name`, a -description within the 1024-character limit, and a `license` on every file so a -copied skill still carries its terms. A CI test enforces those limits, because -Claude Code is lenient about all three and a violation would fail silently -wherever else the directory is copied. +### Copy individual Codex skills -Codex supports `SKILL.md` directly: +From the repository root, copy the directories for the skills you want to +`~/.agents/skills/`. Keep each directory intact so that Codex can read its +invocation settings. ```bash mkdir -p ~/.agents/skills cp -r plugins/coding-discipline/skills/* ~/.agents/skills/ ``` -Windows PowerShell: +Windows PowerShell ```powershell -Copy-Item -Recurse "plugins\coding-discipline\skills\*" "$HOME\.agents\skills\" -``` - -This route omits SessionStart injection, usage counting, and guide-doc seeding. -If you want the global discipline primer, review -`plugins/coding-discipline/hooks/skill-discipline.md` and merge it into -`~/.codex/AGENTS.md` once. - -## The eight skills - -Each skill description defines both its trigger and its exclusions. The full -instructions load only when the skill is selected. - -| skill | when it triggers | -|---|---| -| `spec-sync` | confirmed goals, non-goals, constraints, or acceptance criteria must survive across sessions, but the current source of truth is stale or missing | -| `brainstorming` | requirements have multiple reasonable interpretations, design tradeoffs matter, or a wrong change would be expensive | -| `tdd` | new or changed behavior can be verified with an automated regression test | -| `systematic-debugging` | a bug, failure, or unexpected behavior has no established root cause | -| `code-review` | changes affect coordination across modules, cross a high-risk boundary, or the user requests a review | -| `verify-before-done` | before any claim that work is complete, fixed, tested, or ready | -| `git-flow` | branching, worktrees, commits, tags, or branch wrap-up | -| `context-hygiene` | entering a project, reading project history, or resolving conflicting documentation | - -The skills are intentionally short. They keep only the hard judgment rules that -models routinely skip; the harness remains responsible for ordinary planning -and execution. - -## The two hooks - -- **SessionStart discipline:** injects a compact, host-neutral primer that - requires matched skills to be formally invoked, preserves instruction - precedence, and tells the agent to answer in the user's language while - matching the repository language for files and comments. The hook emits the - envelope each host documents — `hookSpecificOutput.additionalContext` for - Claude Code and Codex, `additional_context` for Cursor, top-level - `additionalContext` for Copilot — and appends only the host's own invocation - note. Tests cover all four envelope shapes; Claude Code and Codex are the two - used daily, so treat Cursor and Copilot as conformant-but-unproven until you - have run them yourself. -- **Passive local usage counting:** appends session activations to - `~/.coding-discipline/usage.jsonl`. Claude Code also exposes per-skill - invocations, each tagged with its session id. Every record keeps the - directory it ran in, spelled the same way on every host, so usage stays - attributable to a project after that project is deleted. Nothing is sent over - the network. - -View the local summary by host, skill, and project; pass a keyword such as a -project name to narrow it: - -```bash -bash plugins/coding-discipline/hooks/skills-count.sh -``` - -Disable counting: - -```bash -CD_USAGE_ENABLED=0 +$skillDirectory = Join-Path $HOME ".agents/skills" +New-Item -ItemType Directory -Force -Path $skillDirectory | Out-Null +Copy-Item -Recurse "plugins/coding-discipline/skills/*" $skillDirectory ``` -Disable the primer by itself, leaving counting and guide seeding in place: - -```bash -CD_PRIMER=0 -``` - -The primer is fixed cost paid on every session, and whether it earns that cost -is a question about your workload rather than a claim this project can settle -for you. This switch is what makes it answerable: run the same tasks with it on -and off, and compare. - -## Project guide seeding - -On the first session inside a Git repository, the plugin creates an empty guide -skeleton when the target file does not already exist: - -- Claude Code → `CLAUDE.md` -- Codex → `AGENTS.md` - -The guide is seeded only at the repository root, including when the session -starts in a nested directory or worktree. It never overwrites an existing file. -Set `CD_SEED_AGENT_DOC=0` to disable it. +The plugin has no hooks, usage logging, or shell dependencies. -The English skeleton is intentionally sparse. Add only confirmed project facts -that cannot be inferred from the code. Agents still answer in the user's -language. The guide is shared project context, not a machine-local cache: -commit confirmed rules when the team and future sessions need them, and never -store secrets, tokens, or personal data in it. +## Skills -## Honest limits +| Skill | Invocation | When to use it | +|---|---|---| +| `systematic-debugging` | Automatic or explicit | The cause is unclear, the failure crosses component boundaries, or a previous fix failed. Gather evidence, trace the cause, and verify the fix. | +| `spec-sync` | Automatic or explicit | A confirmed outcome, non-goal, constraint, or acceptance criterion changes what future sessions should do. Find the current source of truth and update the affected text. | +| `brainstorming` | Explicit | Discuss a decision whose tradeoffs affect the result or could cause significant rework. | +| `tdd` | Explicit | Use red, green, and refactor for behavior that benefits from a focused automated test. | -Skills are prompt-level discipline, not a deterministic policy engine. They -reduce failure probability; they cannot guarantee perfect routing or -compliance. +In Codex, type `$` and select the skill. In Claude Code, use the plugin +command, for example `/coding-discipline:brainstorming` or +`/coding-discipline:tdd`. -For stronger enforcement: +Use the host's review and worktree features for routine operations. Put +project-specific review criteria, Git conventions, and acceptance commands in +the repository's own instructions. After the last relevant edit, run the +checks that support your completion claim and report any gaps. Use CI and +branch protection for checks that must pass before merge. -- invoke a skill explicitly when routing must not be left to the model; -- put repository-specific hard rules in that project's `CLAUDE.md` or - `AGENTS.md`; -- put mechanical requirements in CI, lint, tests, branch protection, and - required review. +## Project instructions -Report false triggers and missed triggers with the repository's routing -feedback issue template. Regression cases grow from real failures rather than a -synthetic release suite. +Keep existing `AGENTS.md` and `CLAUDE.md` files. The plugin no longer creates +them at startup. Use the host's `/init` command when a project needs a guide. +Good entries include the current spec, the test command, and conventions the +agent cannot reliably infer from the code. -## Security +Codex and current Claude Code can share `AGENTS.md`. When a repository +needs a separate `CLAUDE.md`, add `@AGENTS.md` to it and put any Claude-specific +instructions below the import. [Claude Code project instructions](https://code.claude.com/docs/en/memory#share-one-file-with-other-coding-tools) -A skill is executable context: whatever it says enters an agent that already -holds your credentials and your file system. Public skill catalogues scanned in -2026 turned out to carry prompt injection and credential exfiltration in a -large minority of entries, so this plugin treats "our skills are clean" as a -claim that has to be checked rather than promised. +## Feedback and security -`tests/test-skill-safety.py` scans every shipped file for the known attack -classes — network egress, credential and private-key paths, piping into a -shell, decoded or indirect execution, and invisible or bidirectional Unicode -that hides instructions from a human reading the diff. Each rule carries a -sample it must still match, so a pattern that quietly stops working fails the -build instead of reporting success forever. CI runs it on Ubuntu and Windows. +Skills guide the model, and automatic invocation can miss or overmatch. Use the +[routing feedback template](.github/ISSUE_TEMPLATE/routing-feedback.md) to +report a misfire or an explicit invocation that failed. -The plugin makes no network calls and sends no telemetry. Its only write -outside your repository is the local usage log at -`~/.coding-discipline/usage.jsonl`, and the test fails if that sink ever moves -without this claim being re-checked. - -```bash -python tests/test-skill-safety.py -``` - -## Dependencies - -- **bash** — included on macOS and Linux. On Windows, install - [Git for Windows](https://git-scm.com/download/win); `run-hook.cmd` locates - Git Bash without selecting WSL's `bash.exe`. -- No `jq` — JSON escaping and local usage records use pure bash. +`tests/test-skill-safety.py` scans the shipped files for known attack patterns, +including references to credentials, network exfiltration, shell pipelines, +decoded execution, and hidden or bidirectional Unicode. A known-bad sample +checks that each rule still matches. ## Development and verification -```bash +```text python tests/test-plugin-metadata.py python tests/test-skill-safety.py -bash tests/test-hooks.sh ``` -On Windows: +GitHub Actions runs both checks on Ubuntu and Windows. If Claude Code is +installed, its validator can also check the marketplace, plugin, and skills. -```powershell -powershell -NoProfile -ExecutionPolicy Bypass -File tests/test-windows-hook.ps1 +```text +claude plugin validate --strict . +claude plugin validate --strict plugins/coding-discipline +claude plugin validate --strict plugins/coding-discipline/skills ``` -The metadata test freezes the English fixed-context baseline at 4580 -characters (4944 at v0.8.0, re-frozen after a dedup trim): the SessionStart -primer plus all eight skill descriptions may not grow unless text is removed -elsewhere. GitHub Actions runs the same validation -on Ubuntu and Windows. - ## Credits -The discipline philosophy and cross-platform hook foundation — including the -polyglot `run-hook.cmd`, SessionStart injection, and pure-bash JSON escaping — -come from [Superpowers](https://github.com/obra/superpowers) by Jesse Vincent -(MIT). This project narrows that foundation into a workflow-agnostic guardrail -layer and adds spec synchronization, risk-triggered routing, and -Windows/Git-Bash support. +The original engineering discipline and cross-platform hook patterns were +inspired by Jesse Vincent's [Superpowers](https://github.com/obra/superpowers) +(MIT). ## License -MIT — see [LICENSE](LICENSE). +MIT · [LICENSE](LICENSE) diff --git a/README.zh-CN.md b/README.zh-CN.md index 498f964..8824f11 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -1,65 +1,21 @@ # coding-discipline -**English** → [README.md](README.md) +**English** · [README.md](README.md) -**只加护栏,不接管工作流。** 日常改动零打扰;具名失败模式临近才介入, -介入就不松。 - -AI 编程助手经常以两种代价很高的方式失败: - -1. **目标漂移。** 对话里已经拍板,但下一轮 session 读到过期 spec, - 继续实现旧目标。 -2. **跳过步骤。** 需求还没对齐就写代码、根因没找到就修症状,或者没有 - 最新证据就宣称完成。 - -`coding-discipline` 是一个轻量、与工作流无关的插件,同时处理这两类问题: - -- **Spec 同步**:当后续 session 可能按过期意图继续工作时,把已经确认的 - 目标、非目标、约束和验收标准写回当前真源。 -- **风险触发纪律**:只有条件命中时才启用硬护栏,包括设计对齐、TDD、 - 系统化调试、优先级评审、证据式验收、规范的 Git 流程和上下文卫生。 - -它**不会**替代 Plan 模式、启动子 agent、编排 worktree、选择模型,也不会 -强迫每个任务都走 spec 流程。小改动保持轻量;风险条件一旦命中,对应 -skill 就保持严格。 - -8 个 skill + 2 个 hook,安装一次,全局生效。支持 Claude Code 和 Codex。 - -## 为什么做这个项目 - -[Superpowers](https://github.com/obra/superpowers) 证明了工程纪律可以以 -skill 的形式存在——本插件的跨平台 hook 底座也来自它(见致谢)。但 -Superpowers 是一整套工作流:它的引导词要求 agent 在给出任何回复(包括 -澄清问题)之前,都先走一遍 skill 系统。 - -coding-discipline 的默认值反过来:skill 平时休眠,只在具名失败模式临近 -时才介入,日常改动零打扰。每个 session 的固定注入约 1.2k tokens,而且 -不会悄悄变大——一旦增长,CI 测试直接失败。插件之间真正不同的开销是 -介入频率,以及介入时会带出什么。 - -在护栏之上,这个项目加了一块自己的东西:spec 层。spec-sync 把已确认的 -目标、非目标、硬约束和验收标准写回项目已有的文档——不需要 -proposal → approve → archive 生命周期,也不新增任何制品——下一个 -session 就不会把你已经否掉的方案重新做一遍。 - -如果你觉得裸用 coding agent 不够稳,但又不想再加一层编排系统,这个项目 -就是为这种需求设计的。 +一个适用于 Claude Code 和 Codex 的轻量插件。它帮助你查清复杂故障的根因,并把已经确认、后续会话还要用的项目决定写回现行规格。方案讨论和测试驱动开发可以按需调用。 ## 安装 ### Codex -```bash +```text codex plugin marketplace add chipfighter/coding-discipline codex plugin add coding-discipline@coding-discipline ``` -安装后新开一个 task。首次启用 hook 或 hook 内容变化时,Codex 会要求审核; -用 `/hooks` 查看并信任。 - -测试本地 checkout 时,把第一条命令换成: +安装后新开一个对话。测试本地副本时,在仓库根目录执行以下命令,替换第一条命令。 -```bash +```text codex plugin marketplace add . ``` @@ -70,175 +26,71 @@ codex plugin marketplace add . /plugin install coding-discipline@coding-discipline ``` -第一条命令把本仓库添加为自托管插件源,第二条安装插件。安装后新开一个 -session。本地测试时,把第一条中的仓库名换成本地路径。 - -### 只安装 skills,不安装 hooks(Codex 及其他宿主) +安装后新开一个会话。测试本地副本时,把第一条命令中的 `chipfighter/coding-discipline` 换成本地路径。 -8 个 skill 都是符合 [agentskills.io](https://agentskills.io) 规范的普通 -`SKILL.md`:合规的 `name`、不超过 1024 字符的 description,以及每个文件 -自带的 `license`——这样单独拷走的 skill 仍然带着授权条款。CI 会强制这三 -条限制,因为 Claude Code 对它们都很宽松,一旦违反,在这里照常工作,拷到 -别的宿主却会静默失败。 +### 单独安装 Codex 技能 -Codex 原生支持 `SKILL.md`: +在仓库根目录把需要的技能目录复制到 `~/.agents/skills/`。保留完整目录,Codex 才能读取其中的调用设置。 ```bash mkdir -p ~/.agents/skills cp -r plugins/coding-discipline/skills/* ~/.agents/skills/ ``` -Windows PowerShell: +Windows PowerShell ```powershell -Copy-Item -Recurse "plugins\coding-discipline\skills\*" "$HOME\.agents\skills\" -``` - -这种方式没有 SessionStart 注入、用量计数和项目引导文档骨架。如果需要 -全局纪律总纲,请先审核 -`plugins/coding-discipline/hooks/skill-discipline.md`,再把它合并到 -`~/.codex/AGENTS.md`,不要重复追加。 - -## 8 个 skills - -每个 skill 的 description 同时定义触发条件和排除条件。只有 skill 被选中 -后才加载完整正文。 - -| skill | 什么时候触发 | -|---|---| -| `spec-sync` | 已确认的目标、非目标、约束或验收需要跨 session 保留,但当前真源过期或缺失 | -| `brainstorming` | 需求有多种合理理解、设计需要取舍,或改错代价高 | -| `tdd` | 新增或修改的行为可以用自动化回归测试验证 | -| `systematic-debugging` | bug、失败或非预期行为的根因尚未确定 | -| `code-review` | 改动影响多个模块的配合、跨越高风险边界,或用户明确要求评审 | -| `verify-before-done` | 宣称完成、修复、测试通过或可以交付之前 | -| `git-flow` | 分支、worktree、提交、tag 或分支收尾 | -| `context-hygiene` | 进入项目、读取项目历史或处理互相冲突的文档 | - -这些 skill 故意保持很短,只保留模型经常跳过的硬判断规则;普通的规划和 -执行仍由 harness 负责。 - -## 2 个 hooks - -- **SessionStart 纪律总纲**:注入一段精简、平台中立的纪律,要求正式调用 - 命中的 skill,维护指令优先级,并要求 agent 用用户的语言回答、用仓库 - 已有语言编写文件和注释。Hook 会按各宿主自己的文档输出对应信封—— - Claude Code 和 Codex 用 `hookSpecificOutput.additionalContext`,Cursor 用 - `additional_context`,Copilot 用顶层 `additionalContext`——并只追加该宿主 - 自己的调用说明。四种信封形状都有测试覆盖;日常在用的是 Claude Code 和 - Codex,所以在你自己跑通之前,请把 Cursor 和 Copilot 当作"符合规范但未 - 实测"。 -- **被动本地用量计数**:把 session 激活记录追加到 - `~/.coding-discipline/usage.jsonl`。Claude Code 还可以记录每个 skill - 的调用,并附上所属 session 的 id。每条记录都保留运行时所在的目录,而且在 - 各个宿主上写法一致,所以项目删除之后,用量仍能对应到具体项目。数据不会上传。 - -按宿主、skill 和项目查看本地汇总;传入项目名之类的关键词可以只看相关记录: - -```bash -bash plugins/coding-discipline/hooks/skills-count.sh -``` - -关闭计数: - -```bash -CD_USAGE_ENABLED=0 +$skillDirectory = Join-Path $HOME ".agents/skills" +New-Item -ItemType Directory -Force -Path $skillDirectory | Out-Null +Copy-Item -Recurse "plugins/coding-discipline/skills/*" $skillDirectory ``` -只关闭纪律总纲,保留计数和引导文档生成: - -```bash -CD_PRIMER=0 -``` - -总纲是每个 session 都要付的固定开销。它值不值这个开销,取决于你自己的工作 -负载,不是本项目单方面能替你下结论的事。这个开关的意义就在于让它可被回答: -同样一批任务,开和关各跑一遍,比较结果。 - -## 自动生成项目引导文档 - -第一次在 Git 仓库中开启 session 时,如果目标文件不存在,插件会创建一份 -空骨架: - -- Claude Code → `CLAUDE.md` -- Codex → `AGENTS.md` - -即使从子目录或 worktree 启动,文件也只会生成在仓库根目录。已有文件永不 -覆盖。设置 `CD_SEED_AGENT_DOC=0` 可以关闭。 +插件无需安装 Bash,也没有启动钩子和用量记录。 -英文骨架故意保持精简,只应记录已经确认、且无法从代码推断的项目事实。 -Agent 仍然会用用户的语言回答。引导文档是共享的项目上下文,不是本机缓存: -团队和后续 session 需要的已确认规则通常应该提交到仓库,但绝不能在里面写 -密钥、令牌或个人隐私。 +## 技能 -## 能力边界 +| 技能 | 调用方式 | 适用场景 | +|---|---|---| +| `systematic-debugging` | 自动或手动 | 根因不明、故障跨组件,或上次修复没奏效。先收集证据、追查根因,再验证修复。 | +| `spec-sync` | 自动或手动 | 已确认的目标、非目标、约束或验收标准会改变后续会话的工作。找到现行规格,只更新相关原文。 | +| `brainstorming` | 手动 | 一个设计决策会实质影响结果,或选错代价很高,需要先讨论取舍。 | +| `tdd` | 手动 | 某个行为值得用针对性的自动化测试覆盖时,采用先写失败测试、再实现、最后重构的流程。 | -Skill 是提示词层面的纪律,不是确定性规则引擎。它能降低失败概率,但不能 -保证路由和执行永远正确。 +在 Codex 中输入 `$` 并选中对应技能。在 Claude Code 中使用插件命令,例如 `/coding-discipline:brainstorming` 或 `/coding-discipline:tdd`。 -需要更强约束时: +日常审查和 worktree 管理由宿主提供。项目专用的审查要求、Git 约定和验收命令写在仓库指令里。最后一次相关修改后,执行足以支撑结论的检查,说明实测结果和未验证项。合并前必须通过的检查交给 CI 和分支保护。 -- 不想让模型判断路由,就显式调用 skill; -- 把仓库专属硬规则写进该项目的 `CLAUDE.md` 或 `AGENTS.md`; -- 把机械性要求交给 CI、lint、测试、分支保护和 required review。 +## 项目指令 -误触发和漏触发请通过仓库的 routing feedback issue 模板反馈。回归案例只 -从真实失败中生长,不维护人工场景发版套件。 +保留已有的 `AGENTS.md` 和 `CLAUDE.md`。插件已取消启动时自动创建这两个文件的行为。项目确实需要指令时,用对应工具的 `/init` 初始化。适合写进去的是现行规格的入口、测试命令,以及仅凭代码难以推断的约定。 -## 安全 +Codex 和新版 Claude Code 可以共用 `AGENTS.md`。如果仓库需要独立的 `CLAUDE.md`,在里面用 `@AGENTS.md` 引入共享规则,再补充 Claude 专用指令。 [Claude Code 项目指令](https://code.claude.com/docs/en/memory#share-one-file-with-other-coding-tools) -Skill 本身就是可执行的上下文:它写什么,都会进入一个已经握着你的凭据和 -文件系统的 agent。2026 年对公开 skill 目录的扫描发现,其中相当一部分带有 -提示词注入和凭据外传,所以本插件把"我们的 skill 是干净的"当成一个需要被 -检验的声明,而不是一句承诺。 +## 反馈与安全 -`tests/test-skill-safety.py` 会扫描所有随插件分发的文件,检查已知的攻击 -类型——网络外传、凭据与私钥路径、管道进 shell、解码或间接执行,以及会对 -人眼隐藏指令的不可见/双向控制字符。每条规则都带一个必须命中的样本,所以 -一条悄悄失效的规则会让构建失败,而不是永远报告通过。CI 在 Ubuntu 和 -Windows 上都会执行。 +自动调用可能误触发或漏触发。遇到这两种情况,或者手动调用失败,可以使用[路由反馈模板](.github/ISSUE_TEMPLATE/routing-feedback.md)。 -本插件不发起任何网络请求,也不上报任何遥测。它在你的仓库之外唯一的写入 -是本地用量日志 `~/.coding-discipline/usage.jsonl`;如果这个位置发生变化, -测试会失败,提醒重新核对上面这条声明。 - -```bash -python tests/test-skill-safety.py -``` - -## 依赖 - -- **bash**:macOS 和 Linux 自带;Windows 安装 - [Git for Windows](https://git-scm.com/download/win),`run-hook.cmd` - 会找到 Git Bash,并避免误用 WSL 的 `bash.exe`。 -- 不需要 `jq`:JSON 转义和本地记录全部使用纯 bash。 +`tests/test-skill-safety.py` 扫描插件分发的文件,检查凭据路径、网络外传、进入 shell 的管道、解码执行和隐藏或双向 Unicode 字符等已知模式。每条规则都用一个应命中的样本验证。 ## 开发与验证 -```bash +```text python tests/test-plugin-metadata.py python tests/test-skill-safety.py -bash tests/test-hooks.sh ``` -Windows: +GitHub Actions 会在 Ubuntu 和 Windows 上执行这两项检查。安装了 Claude Code 的话,还可以使用它的校验命令检查插件源、插件和技能。 -```powershell -powershell -NoProfile -ExecutionPolicy Bypass -File tests/test-windows-hook.ps1 +```text +claude plugin validate --strict . +claude plugin validate --strict plugins/coding-discipline +claude plugin validate --strict plugins/coding-discipline/skills ``` -元数据测试把英文固定上下文基线冻结为 4580 个字符(v0.8.0 时为 4944, -去重删减后重新冻结):SessionStart 总纲与 8 条 skill description 的总长度 -不能增长,除非从其他位置删掉等量内容。GitHub Actions 会在 Ubuntu 和 Windows 上执行相同验证。 - ## 致谢 -纪律理念与跨平台 hook 基础——包括 polyglot `run-hook.cmd`、SessionStart -注入和纯 bash JSON 转义——来自 Jesse Vincent 的 -[Superpowers](https://github.com/obra/superpowers)(MIT)。本项目把这套 -基础收敛为不接管工作流的护栏层,并加入 spec 同步、风险触发路由和 -Windows / Git-Bash 支持。 +本项目早期的工程纪律和跨平台钩子设计受到 Jesse Vincent 的 [Superpowers](https://github.com/obra/superpowers)(MIT)启发。 -## License +## 许可证 -MIT — 见 [LICENSE](LICENSE)。 +MIT · [LICENSE](LICENSE) diff --git a/plugins/coding-discipline/.claude-plugin/plugin.json b/plugins/coding-discipline/.claude-plugin/plugin.json index a57c324..811551c 100644 --- a/plugins/coding-discipline/.claude-plugin/plugin.json +++ b/plugins/coding-discipline/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "coding-discipline", - "description": "Workflow-agnostic guardrails for AI coding agents: spec-sync preserves confirmed intent across sessions; brainstorming, TDD, root-cause debugging, prioritized review, evidence-before-done, disciplined git, and context hygiene trigger only when their risk conditions match. Includes a SessionStart discipline primer, optional guide-doc seeding, and passive local usage counting.", - "version": "0.10.0", + "description": "Focused skills for investigating hard-to-explain failures and keeping confirmed project decisions current, with optional design discussion and TDD.", + "version": "0.11.0", "author": { "name": "chipfighter" }, @@ -14,8 +14,6 @@ "spec", "tdd", "debugging", - "code-review", - "git", "workflow", "brainstorming", "guardrails", diff --git a/plugins/coding-discipline/.codex-plugin/plugin.json b/plugins/coding-discipline/.codex-plugin/plugin.json index 30779f8..c1d76c7 100644 --- a/plugins/coding-discipline/.codex-plugin/plugin.json +++ b/plugins/coding-discipline/.codex-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "coding-discipline", - "version": "0.10.0", - "description": "Workflow-agnostic guardrails for AI coding agents: spec sync preserves confirmed intent across sessions, while risk-triggered skills enforce design alignment, TDD, root-cause debugging, prioritized review, evidence-before-done, disciplined git, and context hygiene.", + "version": "0.11.0", + "description": "Focused skills for investigating hard-to-explain failures and keeping confirmed project decisions current, with optional design discussion and TDD.", "author": { "name": "chipfighter" }, @@ -14,8 +14,6 @@ "spec", "tdd", "debugging", - "code-review", - "git", "workflow", "brainstorming", "guardrails", @@ -25,11 +23,10 @@ "agent-skills" ], "skills": "./skills/", - "hooks": "./hooks/hooks-codex.json", "interface": { "displayName": "Coding Discipline", - "shortDescription": "Spec sync + risk-triggered discipline for coding agents", - "longDescription": "Keep confirmed goals, boundaries, and acceptance criteria synchronized with the current spec, then apply firm engineering discipline only when the risk justifies it: align ambiguous requirements, test testable behavior first, find root causes, review by priority, verify before claiming done, use disciplined git flow, and avoid stale-context drift. It adds guardrails without taking over planning, subagents, worktrees, or the development workflow.", + "shortDescription": "Root-cause debugging and durable project decisions", + "longDescription": "Investigate failures with unclear causes and keep the current project spec aligned with confirmed decisions. Design discussion and test-driven development are available on demand.", "developerName": "chipfighter", "category": "Coding", "capabilities": [ @@ -38,9 +35,8 @@ "Write" ], "defaultPrompt": [ - "Use coding-discipline to align the design before implementing this feature.", "Use systematic-debugging to find the root cause of this problem.", - "Use code-review and verify-before-done to inspect this change." + "Use spec-sync to update the current specification with the decisions we just confirmed." ], "websiteURL": "https://github.com/chipfighter/coding-discipline" } diff --git a/plugins/coding-discipline/hooks/hooks-codex.json b/plugins/coding-discipline/hooks/hooks-codex.json deleted file mode 100644 index ad7b4f1..0000000 --- a/plugins/coding-discipline/hooks/hooks-codex.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "hooks": { - "SessionStart": [ - { - "matcher": "startup|resume|clear|compact", - "hooks": [ - { - "type": "command", - "command": "\"${PLUGIN_ROOT}/hooks/run-hook.cmd\" session-start-skills codex", - "commandWindows": "cmd.exe /d /s /c \"\"%PLUGIN_ROOT%\\hooks\\run-hook.cmd\" session-start-skills codex\"", - "async": false - } - ] - } - ] - } -} diff --git a/plugins/coding-discipline/hooks/hooks.json b/plugins/coding-discipline/hooks/hooks.json deleted file mode 100644 index 6aec031..0000000 --- a/plugins/coding-discipline/hooks/hooks.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "hooks": { - "SessionStart": [ - { - "matcher": "startup|clear|compact", - "hooks": [ - { - "type": "command", - "command": "\"${CLAUDE_PLUGIN_ROOT}/hooks/run-hook.cmd\" session-start-skills claude-code", - "async": false - } - ] - } - ], - "PostToolUse": [ - { - "matcher": "Skill", - "hooks": [ - { - "type": "command", - "command": "\"${CLAUDE_PLUGIN_ROOT}/hooks/run-hook.cmd\" log-usage" - } - ] - } - ] - } -} diff --git a/plugins/coding-discipline/hooks/log-usage b/plugins/coding-discipline/hooks/log-usage deleted file mode 100755 index f389ba9..0000000 --- a/plugins/coding-discipline/hooks/log-usage +++ /dev/null @@ -1,31 +0,0 @@ -#!/usr/bin/env bash -# Claude Code PostToolUse(Skill) hook: Tier 2 counting records one -# {event:"skill"} entry per invocation. -# The JSON payload arrives on stdin. Extract the skill name with grep/sed -# (no jq), then hand it to the shared writer. -# Always exit 0; usage logging must never interrupt the main workflow. -# Codex loads skills internally through progressive disclosure rather than a -# tool call, so it exposes no per-skill event for this hook. -PATH="/usr/bin:/mingw64/bin:${PATH:-}" -export PATH -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" -. "${SCRIPT_DIR}/usage-lib.sh" - -payload="$(cat 2>/dev/null || true)" - -# Values arrive JSON-escaped, so a Windows path reads C:\\Users. Undo that -# before the writer turns each separator into a forward slash. -extract() { - local value - value="$(printf '%s' "$payload" \ - | grep -o "\"$1\"[[:space:]]*:[[:space:]]*\"[^\"]*\"" \ - | head -1 | sed -E "s/.*:[[:space:]]*\"([^\"]*)\"\$/\1/")" - printf '%s' "${value//\\\\/\\}" -} - -skill="$(extract skill)"; [ -n "$skill" ] || skill="?" -cwd="$(extract cwd)" -session_id="$(extract session_id)" - -cd_write_record skill "$skill" "$cwd" "$session_id" -exit 0 diff --git a/plugins/coding-discipline/hooks/run-hook.cmd b/plugins/coding-discipline/hooks/run-hook.cmd deleted file mode 100755 index 7b869f9..0000000 --- a/plugins/coding-discipline/hooks/run-hook.cmd +++ /dev/null @@ -1,68 +0,0 @@ -: << 'CMDBLOCK' -@echo off -setlocal EnableExtensions -REM Cross-platform polyglot wrapper: hand the hook script to the right bash. -REM Windows: cmd.exe runs this batch block, finds Git-for-Windows bash in -REM standard locations and calls it (deliberately AVOIDING the WSL -REM launcher at C:\Windows\System32\bash.exe). -REM Unix: the shell reads the whole file as a script -- ":" is a no-op and -REM the heredoc swallows this batch block, then the Unix tail runs. -REM -REM NOTE: keep this file ASCII-only. cmd.exe parses .cmd under the OEM code page -REM and chokes on UTF-8 multibyte bytes even inside REM comments. -REM -REM Hook scripts use extensionless names (e.g. "session-start-skills") so Claude -REM Code's Windows auto-detection -- which prepends "bash" to any command -REM containing ".sh" -- does not interfere. -REM -REM Usage: run-hook.cmd [args...] - -if "%~1"=="" ( - echo run-hook.cmd: missing script name >&2 - exit /b 1 -) - -set "HOOK_DIR=%~dp0" - -if exist "C:\Program Files\Git\bin\bash.exe" goto git64 -if exist "C:\Program Files (x86)\Git\bin\bash.exe" goto git32 -if exist "%LOCALAPPDATA%\Programs\Git\bin\bash.exe" goto gitlocal - -REM Fallback: bash on PATH (user-installed Git Bash / MSYS2 / Cygwin). -where bash >nul 2>nul -if errorlevel 1 goto nobash -goto bashpath - -REM No bash found: fail clearly so the host can surface the missing dependency. -:nobash -echo run-hook.cmd: Git Bash was not found. Install Git for Windows or put bash on PATH. >&2 -exit /b 127 - -:bashpath -REM MSYS2 login shells cd to HOME unless CHERE_INVOKING is set; the hook -REM scripts depend on the caller's working directory. -set "CHERE_INVOKING=1" -bash --login "%HOOK_DIR%%~1" %2 %3 %4 %5 %6 %7 %8 %9 -exit /b %ERRORLEVEL% - -:git64 -set "PATH=C:\Program Files\Git\usr\bin;C:\Program Files\Git\mingw64\bin;%PATH%" -"C:\Program Files\Git\bin\bash.exe" --noprofile --norc "%HOOK_DIR%%~1" %2 %3 %4 %5 %6 %7 %8 %9 -exit /b %ERRORLEVEL% - -:git32 -set "PATH=C:\Program Files (x86)\Git\usr\bin;C:\Program Files (x86)\Git\mingw32\bin;%PATH%" -"C:\Program Files (x86)\Git\bin\bash.exe" --noprofile --norc "%HOOK_DIR%%~1" %2 %3 %4 %5 %6 %7 %8 %9 -exit /b %ERRORLEVEL% - -:gitlocal -set "PATH=%LOCALAPPDATA%\Programs\Git\usr\bin;%LOCALAPPDATA%\Programs\Git\mingw64\bin;%PATH%" -"%LOCALAPPDATA%\Programs\Git\bin\bash.exe" --noprofile --norc "%HOOK_DIR%%~1" %2 %3 %4 %5 %6 %7 %8 %9 -exit /b %ERRORLEVEL% -CMDBLOCK - -# ---- Unix (bash/zsh): run the named script directly ---- -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" -SCRIPT_NAME="$1" -shift -exec bash "${SCRIPT_DIR}/${SCRIPT_NAME}" "$@" diff --git a/plugins/coding-discipline/hooks/session-start-skills b/plugins/coding-discipline/hooks/session-start-skills deleted file mode 100755 index fe09384..0000000 --- a/plugins/coding-discipline/hooks/session-start-skills +++ /dev/null @@ -1,88 +0,0 @@ -#!/usr/bin/env bash -# Cross-platform SessionStart hook: -# 1. Inject the skill-discipline primer. -# 2. Record one Tier 1 session activation. -# Reads skill-discipline.md beside this file, escapes it as JSON with pure bash -# (no jq), and selects the host-specific output field. -PATH="/usr/bin:/mingw64/bin:${PATH:-}" -export PATH -set -euo pipefail - -case "${1:-}" in - codex|claude-code|cursor|copilot) export CD_PLATFORM="$1" ;; - "") ;; - *) printf 'session-start-skills: unsupported platform: %s\n' "$1" >&2; exit 2 ;; -esac - -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" -. "${SCRIPT_DIR}/usage-lib.sh" - -body="$(cat "${SCRIPT_DIR}/skill-discipline.md" 2>/dev/null \ - || echo '(Skill discipline file missing: hooks/skill-discipline.md)')" - -# Keep the primer host-neutral; append only the host-specific invocation note. -platform="$(cd_detect_platform)" -case "$platform" in - claude-code) mech='> On this host, invoke the skill with the **Skill tool**. Reading `SKILL.md` as an ordinary file does not count as invoking it.' ;; - codex) mech='> On this host, Codex can load a skill automatically from its description or explicitly through `$skill-name`. Do not load it by printing the file yourself.' ;; - *) mech='> Load skills through the skill mechanism of this host. Reading `SKILL.md` as an ordinary file does not count as invoking it.' ;; -esac - -# Escape a JSON string with bash parameter expansion only. -escape_for_json() { - local s="$1" - s="${s//\\/\\\\}"; s="${s//\"/\\\"}" - s="${s//$'\n'/\\n}"; s="${s//$'\r'/\\r}"; s="${s//$'\t'/\\t}" - printf '%s' "$s" -} - -wrapped=" -${body} -${mech} -" -esc="$(escape_for_json "$wrapped")" - -# Tier 1 counting writes to a file and does not affect the injection JSON. -cd_write_record session "" "$PWD" - -# Seed an empty project guide at the Git root on first entry. Create only, -# never overwrite, and never interrupt the main workflow. The skeleton stays -# deliberately empty and grows one confirmed line at a time under -# context-hygiene; this hook must not hard-code project facts. -seed_agent_doc() { - case "${CD_SEED_AGENT_DOC:-1}" in - 0|false|False|FALSE|no|No|NO|off|Off|OFF) return 0 ;; - esac - local repo_root target - repo_root="$(git -C "$PWD" rev-parse --show-toplevel 2>/dev/null)" || return 0 - local seed="${SCRIPT_DIR}/../templates/agent-doc.seed.md" - [ -f "$seed" ] || return 0 - case "$platform" in - codex) target="${repo_root}/AGENTS.md" ;; - claude-code) target="${repo_root}/CLAUDE.md" ;; - *) return 0 ;; - esac - [ -e "$target" ] || cp -n "$seed" "$target" 2>/dev/null || true -} -seed_agent_doc || true - -# The primer is the one piece worth isolating: it is fixed cost paid on every -# session, and whether it earns that cost can only be measured by turning it off -# on its own. Counting and seeding already ran above, so this changes nothing but -# the injected text. -case "${CD_PRIMER:-1}" in - 0|false|False|FALSE|no|No|NO|off|Off|OFF) exit 0 ;; -esac - -# Cursor uses additional_context; Copilot/SDK uses top-level additionalContext; -# Claude Code, Codex, and the default path use -# hookSpecificOutput.additionalContext. -if [ -n "${CURSOR_PLUGIN_ROOT:-}" ]; then - printf '{"additional_context":"%s"}\n' "$esc" -elif [ -n "${COPILOT_CLI:-}" ]; then - printf '{"additionalContext":"%s"}\n' "$esc" -else - printf '{"hookSpecificOutput":{"hookEventName":"SessionStart","additionalContext":"%s"}}\n' "$esc" -fi - -exit 0 diff --git a/plugins/coding-discipline/hooks/skill-discipline.md b/plugins/coding-discipline/hooks/skill-discipline.md deleted file mode 100644 index 7fc8421..0000000 --- a/plugins/coding-discipline/hooks/skill-discipline.md +++ /dev/null @@ -1,24 +0,0 @@ -# Skill discipline - -Each skill's description is the sole trigger source: **when the task clearly -matches, formally invoke the skill; when it is clearly excluded, do not invoke -it.** If information is missing, check only the fact needed to decide; once it -is known, stop without writing a report. Do not inflate a small task into a -full process, and do not ignore a satisfied trigger. - -Four baseline rules always apply: -1. **Align before changing** — if the requirement or direction is uncertain, - align first instead of implementing a stale interpretation. -2. **Say when the direction is wrong** — surface a better path or a conflict - with the goal before continuing; blind agreement is a failure. -3. **Do not overbuild or expand scope** — omit unused features and untouched - modules; leave only the extension points that are actually needed. -4. **Do not guess libraries or APIs** — when usage is uncertain, check the - documentation or source before writing code. - -Respond in the user's language unless they request otherwise. Match the -repository's established language for files, documentation, and comments. - -**The user's latest explicit instruction wins. Without a newer instruction, -follow the current project's `CLAUDE.md` / `AGENTS.md`; both override this -discipline and every skill.** diff --git a/plugins/coding-discipline/hooks/skills-count.sh b/plugins/coding-discipline/hooks/skills-count.sh deleted file mode 100755 index ac11867..0000000 --- a/plugins/coding-discipline/hooks/skills-count.sh +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env bash -# Summarize usage written by SessionStart (session activations on every host) -# and PostToolUse(Skill) (per-skill activity on Claude Code). No jq required. -# Usage: -# bash skills-count.sh # all records -# bash skills-count.sh # records whose full line contains keyword, -# # e.g. a project name to see its skills -PATH="/usr/bin:/mingw64/bin:${PATH:-}" -export PATH -set -euo pipefail - -LOG="${CD_USAGE_LOG:-$HOME/.coding-discipline/usage.jsonl}" -[ -f "$LOG" ] || { echo "No usage records yet ($LOG does not exist)."; exit 0; } - -filter="${1:-}" -if [ -n "$filter" ]; then - data="$(grep -F "$filter" "$LOG" || true)" - echo "== Usage (records containing '$filter') ==" -else - data="$(cat "$LOG")" - echo "== Usage (all records) ==" -fi -[ -n "$data" ] || { echo "(No matching records.)"; exit 0; } - -field() { grep -o "\"$1\":\"[^\"]*\"" | sed -E 's/.*:"([^"]*)"/\1/'; } - -echo "" -echo "-- Session activations by host --" -sess="$(printf '%s\n' "$data" | grep '"event":"session"' || true)" -if [ -n "$sess" ]; then printf '%s\n' "$sess" | field platform | sort | uniq -c | sort -rn -else echo "(None yet.)"; fi - -echo "" -echo "-- Skill invocations by skill (Claude Code only) --" -sk="$(printf '%s\n' "$data" | grep '"event":"skill"' || true)" -if [ -n "$sk" ]; then printf '%s\n' "$sk" | field skill | sort | uniq -c | sort -rn -else echo "(None yet; only Claude Code exposes per-skill activity.)"; fi - -echo "" -echo "-- Skill invocations by project (Claude Code only) --" -# Records written before paths were canonicalized doubled every separator -# (D://work//x); fold them onto the current spelling so a project counts once. -if [ -n "$sk" ]; then printf '%s\n' "$sk" | field cwd | sed -E 's#(.)/{2,}#\1/#g' | sort | uniq -c | sort -rn -else echo "(None yet; only Claude Code exposes per-skill activity.)"; fi - -echo "" -total="$(printf '%s\n' "$data" | grep -c '' || true)" -first="$(printf '%s\n' "$data" | head -1 | field ts)" -last="$(printf '%s\n' "$data" | tail -1 | field ts)" -echo "${total} total records; first ${first}; latest ${last}" diff --git a/plugins/coding-discipline/hooks/usage-lib.sh b/plugins/coding-discipline/hooks/usage-lib.sh deleted file mode 100644 index 3d7e243..0000000 --- a/plugins/coding-discipline/hooks/usage-lib.sh +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env bash -# Shared cross-platform usage library sourced by session-start-skills and -# log-usage. Pure bash, no jq. -# Every host appends to the same JSONL sink; environment variables identify the -# host. Record shape: -# {"ts","platform","event":"session"|"skill","skill","cwd","session_id"} - -PATH="/usr/bin:/mingw64/bin:${PATH:-}" -export PATH - -CD_USAGE_LOG="${CD_USAGE_LOG:-$HOME/.coding-discipline/usage.jsonl}" -CD_USAGE_ENABLED="${CD_USAGE_ENABLED:-1}" - -# Detect the host from runtime environment variables, most specific first. -cd_detect_platform() { - if [ -n "${CD_PLATFORM:-}" ]; then echo "$CD_PLATFORM" - elif [ -n "${CURSOR_PLUGIN_ROOT:-}" ]; then echo cursor - elif [ -n "${PLUGIN_ROOT:-}" ]; then echo codex - elif [ -n "${CODEX_HOME:-}" ]; then echo codex - elif [ -n "${COPILOT_CLI:-}" ]; then echo copilot - elif [ -n "${CLAUDE_PLUGIN_ROOT:-}" ] || [ -n "${CLAUDE_PROJECT_DIR:-}" ]; then echo claude-code - else echo unknown - fi -} - -# cd_canonical_path -# One directory must reach the log under one spelling, or per-project counts -# split. On Windows a hook payload carries the native C:\x while Git Bash's $PWD -# reads /c/x or a mount such as /tmp/x; all of them become C:/x. Only cygpath -# knows where MSYS mounts point, so rewriting the string alone is not enough. -cd_canonical_path() { - local p="${1:-}" - case "$p" in - /*) - case "${OSTYPE:-}" in - msys*|cygwin*) p="$(cygpath -m "$p" 2>/dev/null || printf '%s' "$p")" ;; - esac - ;; - esac - printf '%s' "${p//\\//}" -} - -# cd_write_record [session_id] -# skill and session_id may be empty; every failure stays silent and never -# interrupts work. -cd_write_record() { - local event="${1:-}" skill="${2:-}" cwd="${3:-}" session_id="${4:-}" - local platform ts - case "$CD_USAGE_ENABLED" in - 0|false|False|FALSE|no|No|NO|off|Off|OFF) return 0 ;; - esac - platform="$(cd_detect_platform)" - ts="$(date -u +%FT%TZ 2>/dev/null || echo '?')" - # JSON safety: escape backslashes before quotes. The canonical path has no - # backslashes left, but skill and session_id arrive as decoded host values. - cwd="$(cd_canonical_path "$cwd")"; cwd="${cwd//\"/\\\"}" - skill="${skill//\\/\\\\}"; skill="${skill//\"/\\\"}" - session_id="${session_id//\\/\\\\}"; session_id="${session_id//\"/\\\"}" - mkdir -p "$(dirname "$CD_USAGE_LOG")" 2>/dev/null || true - printf '{"ts":"%s","platform":"%s","event":"%s","skill":"%s","cwd":"%s","session_id":"%s"}\n' \ - "$ts" "$platform" "$event" "$skill" "$cwd" "$session_id" >> "$CD_USAGE_LOG" 2>/dev/null || true -} diff --git a/plugins/coding-discipline/skills/brainstorming/SKILL.md b/plugins/coding-discipline/skills/brainstorming/SKILL.md index e22f239..0753285 100644 --- a/plugins/coding-discipline/skills/brainstorming/SKILL.md +++ b/plugins/coding-discipline/skills/brainstorming/SKILL.md @@ -1,26 +1,10 @@ --- name: brainstorming -description: Use before coding when requirements have multiple reasonable interpretations, approaches require tradeoffs, or mistakes would be costly (permissions/payments/data migration/public APIs/data structures/hard-to-revert changes). Clarify requirements and design one question at a time, then get approval before implementation. Do not trigger for a focused small change with a clear goal and approach, or for mechanical edits (copy/constants/config values). +description: Discuss implementation choices when the user explicitly requests design help or wants to decide a tradeoff before coding. +disable-model-invocation: true license: MIT --- -**Hard rule: write no code until the design is approved.** Once this skill triggers, follow it through—the design may be only a few sentences, but it must be explained and approved first. Deciding midway that it is "actually simple" is not a reason to exit: "simple" often means unstated assumptions. +Check the relevant project context and summarize the intended outcome, constraints, and what would count as success. -## Excuses that surface when you want to skip design -| What you tell yourself | Reality | -|---|---| -| "This is too simple to need design." | "Simple" means unstated assumptions, which are the most dangerous. A simple design may take only a few sentences, but it still needs to be explained and approved. | -| "It will be faster to think while building." | Starting from a misaligned understanding makes rework slower. Align on the direction before acting. | -| "The user probably wants X." | Do not decide for the user. Clarify one question at a time, and offer choices when possible. | - -## Process -1. **Inspect the context first**: relevant files, documentation, and recent commits. Do not design in a vacuum. -2. **Ask one question at a time** to clarify the goal, constraints, and success criteria. Offer choices when possible; they are easier to answer than open-ended questions. Put only one question in each message. -3. **Split up work that is too large**: if it is really several independent subsystems, stop and help divide it into subprojects and prioritize them before detailing a large task that should be broken apart. -4. **Present 2–3 approaches with tradeoffs**: put your **recommended** option first and explain why, then list the alternatives and their costs. -5. **Present the design in sections and confirm each one**: make each section as long or short as its complexity warrants. After each section, ask "Does this look right?" before continuing. -6. **Remove features that are not needed yet (YAGNI)**: if it is not needed now, do not design it. - -## After approval -Begin implementation only after the design is approved. If any part stops making sense along the way, return and clarify it. -If the design establishes a durable project decision that cannot be inferred from the code (a technology choice / hard boundary / definition of done), ask whether to record it in the project guide (`AGENTS.md` for Codex, `CLAUDE.md` for Claude Code; see context-hygiene for how). If an approved outcome or acceptance criterion from this session must persist across sessions, also ask whether to create or update the current spec, then hand that work to spec-sync. +Compare the practical options that would change the outcome, recommend one, and explain its main tradeoff. Use existing project conventions for reversible details. Ask about unresolved choices only when they would materially change the result or create substantial rework. If the user asked to approve a design before implementation, present the proposed design for that decision. diff --git a/plugins/coding-discipline/skills/brainstorming/agents/openai.yaml b/plugins/coding-discipline/skills/brainstorming/agents/openai.yaml new file mode 100644 index 0000000..5b1f887 --- /dev/null +++ b/plugins/coding-discipline/skills/brainstorming/agents/openai.yaml @@ -0,0 +1,2 @@ +policy: + allow_implicit_invocation: false diff --git a/plugins/coding-discipline/skills/code-review/SKILL.md b/plugins/coding-discipline/skills/code-review/SKILL.md deleted file mode 100644 index 24b9899..0000000 --- a/plugins/coding-discipline/skills/code-review/SKILL.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -name: code-review -description: Use when changes affect interactions across multiple modules, involve high-risk areas (authorization/authentication, payments/funds, data deletion/migration, public APIs/cross-service interfaces/security boundaries), or the user requests a review. Review in this order—correctness → requirements → security → simplicity → style. Verify feedback before acting; do not comply blindly or agree performatively. Unless the user asks, documentation-only changes, explicit config values, and mechanical renames do not trigger merely because of a PR or merge. -license: MIT ---- - -## Performing a review (review it yourself; delegate when worthwhile and supported) -When an independent perspective is needed and the current client supports subagents, you may delegate a review. Give the reviewer **carefully scoped context** (what changed, which requirements it should meet, and the base..head diff range), not the entire session history. Review small changes yourself; do not add agent overhead for appearances. - -Review in this **priority order**. Do not dwell on a lower priority while a higher one is unresolved: -1. **Correctness**: is the logic sound; are edge cases, errors, or concurrency missing; can it crash? -2. **Requirements**: check each requirement and design point. Does the change do what was requested, and is anything missing? -3. **Security**: injection, unauthorized access, secret leakage, unvalidated input. -4. **Simplicity**: overengineering, duplication, removable dead code, features that are not needed yet. -5. **Style**: naming, consistency, readability—review these last, not first. - -Use severity: fix blockers (crashes/security) immediately, fix important issues before proceeding, and note minor issues for later. - -## Receiving review feedback -- **Verify before changing anything**: does this feedback apply to **this** codebase? Could it break existing behavior? Is there a reason the code is written this way? If uncertain, say, "I cannot verify X. Should I investigate, ask, or leave it for now?" -- **Do not comply blindly**: if a suggestion is wrong, lacks context, asks for something not needed yet, or conflicts with an established architecture decision, push back with **technical reasons** rather than changing it because a reviewer said so. Stop and consult someone when the conflict concerns architecture. -- **No performative agreement**: do not say "You're right!", "Good suggestion!", or "Thanks for catching that!" If you make the change, state what changed and where. If your pushback was wrong, say only, "I checked and I was wrong because X; I changed it." Do not write a long apology. -- If anything is unclear, **clarify every item before making changes**. Do not act only on the items you understand; review items are often related, and partial understanding leads to wrong changes. -- Address one item at a time, test each change, and confirm that it introduced no regressions (see verify-before-done). diff --git a/plugins/coding-discipline/skills/context-hygiene/SKILL.md b/plugins/coding-discipline/skills/context-hygiene/SKILL.md deleted file mode 100644 index eb9f42c..0000000 --- a/plugins/coding-discipline/skills/context-hygiene/SKILL.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -name: context-hygiene -description: Use when starting a project, reading project documentation or history, or resolving conflicts between documents. For current state, read only the latest documents designated by the project; do not proactively read archives; do not duplicate the spec; use long-term memory only for environment, people, and preferences not recorded in the repository. -license: MIT ---- - -Old documents can trace history, but they are not current facts. Models easily follow the most extensively documented old account instead of finding the latest, correct one. If the project guide document (Codex's `AGENTS.md` / Claude Code's `CLAUDE.md`) designates a current-state document and archive location, follow it. - -## What to read—and what not to read -1. **For current state, read only the latest document designated by the project** (such as the top of `CHANGELOG.md` or a STATUS document). Do not treat an old version snapshot as current. -2. **Do not proactively read archives or documents marked `superseded` / deprecated.** When history is genuinely needed, search for and read the relevant passage rather than reading the entire archive. -3. When documents conflict, first follow the project's designated latest state document; if it is still unclear, ask the user. Do not choose one yourself, and never treat an archive as current. - -## Do not copy another set of instructions -4. Point design work to the existing project guide document / architecture decision record (ADR) / current-state document instead of copying another spec—the copy will eventually go stale. -5. **When the reason for a direction changes, rewrite it; do not append:** retaining the old rationale invites it to be repeated and pull the work in the wrong direction. -6. **Use memory only for facts unavailable in the repository** (environment / people / preferences / lessons from past pitfalls). Read project progress from the current-state document, and record design rationale in an architecture decision record (ADR). Delete stale memory; do not archive another copy. - -## Project guide documents grow over time; they are not filled in up front -When the project root has no `AGENTS.md` (Codex) or `CLAUDE.md` (Claude Code), the plugin places the corresponding empty skeleton there the first time it enters the repository. It grows by **confirming one thing and recording one line**: -- Record only things already agreed with the user and not apparent from the code (technology choices / hard boundaries / definition of done). Do not record matters still under discussion or unsettled—filling the guide up front makes later sessions treat guesses as facts. -- Whenever such a decision is finalized, proactively ask, “Should I record this in the project guide document?” Write it only after approval, one line at a time. -- If a recorded decision later changes, edit that line; do not add a conflicting line below it (the same “rewrite, do not append” rule above). - -## When a document becomes obsolete -Mark it `status: superseded by XX`, move it to the archive, and use an architecture decision record (ADR) to explain why it was abandoned—so a later session does not revive and rebuild a discarded idea. diff --git a/plugins/coding-discipline/skills/git-flow/SKILL.md b/plugins/coding-discipline/skills/git-flow/SKILL.md deleted file mode 100644 index 66a8b34..0000000 --- a/plugins/coding-discipline/skills/git-flow/SKILL.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -name: git-flow -description: Use when creating a branch, using worktrees for parallel work, committing, or wrapping up. Covers branch naming, conventional commits, short-lived branches, worktree isolation, and final merge/cleanup. -license: MIT ---- - -> Branch naming rules, protected branches, whether to merge directly or through a PR / MR, whether merging triggers CI, and **how to choose versions / who creates tags** are project-specific rules governed by this repository's `AGENTS.md` / `CLAUDE.md`. This skill provides only general discipline. - -## Version / tag closeout (only for projects that manage versions with tags + CHANGELOG; **a tag is a version bookmark—whether it also means release / deployment is defined by the project guide document**) -- **Choose the version before creating the branch:** first confirm the intended tag with the owner—state the previous tag, what remains in the backlog, and whether this work is a feature or a fix, then recommend a version. **Wait for the owner's confirmation before creating the branch**; do not finish the work only to discover there is no agreed release target. -- **Follow SemVer:** major = breaking change, minor = backward-compatible feature, patch = backward-compatible fix. For 0.x, use the looser convention (minor = capability, patch = fix), and when uncertain prefer the larger bump. The project guide document defines what counts as a minor change. -- **Freeze once decided:** after the target version is confirmed, freeze its scope. New requirements arising midway **go to the backlog / next version by default**. Including one in the current version requires explicit owner approval and a clear statement of what it displaces or defers. -- **Use a component, not a version number, as the commit scope** (`feat(auth):`, not `feat(v1.2):`). Branches are deleted; commit history is not. The history remains accurate if the version changes. -- **Version closeout sequence:** complete the scope → merge the branch into the baseline → get CI green → move the CHANGELOG entry from pending into the new version → create the tag (who creates it and how are project-specific). - -## Branches and commits -- Create a new branch for each development effort. **Never** edit directly on a protected main branch or someone else's branch. If the user or client has explicitly provided a working branch, keep using it instead of creating a pointless one. Keep branches short-lived: integrate them quickly rather than letting them drift. -- Use a type + short description in branch names (for example, `feat/search-pagination` or `fix/login-timeout`); follow the project's naming convention when it has one. -- Use conventional commits: `type(scope): description` (feat/fix/refactor/docs/chore…). Commit in small steps, each independently reversible. - -## Parallel worktrees (when running several workstreams at once or isolating work from the current workspace) -- First check **whether you are already in an isolated workspace**. If so, do not nest another one. -- Prefer built-in worktree management in clients such as Claude Code / Codex. Do not manually run `git worktree add` and create a workspace the client cannot see; fall back to Git only when the client lacks this capability. -- Before creating a project-local worktree under `.worktrees/`, confirm that the directory is gitignored; otherwise its contents may be committed accidentally. -- After creating it, install dependencies and run the baseline tests. Report existing failures before starting work. - -## Wrap-up -- **Verify that all tests pass before wrapping up** (see verify-before-done). A failing branch must not proceed to merge / PR. -- Offer **explicit choices** instead of asking an open-ended “What next?”: ① merge into the baseline branch ② push and open a PR/MR ③ keep as-is ④ discard. -- Always in this order: **merge and verify success → remove the worktree → delete the branch**. A branch still referenced by a worktree cannot be deleted; before running `git worktree remove`, `cd` back to the main repository. -- Clean up only worktrees **you created**; do not touch client-created ones. Discarding requires typed confirmation. Do not force-push unless explicitly asked. diff --git a/plugins/coding-discipline/skills/spec-sync/SKILL.md b/plugins/coding-discipline/skills/spec-sync/SKILL.md index 3021c3c..fe0ed78 100644 --- a/plugins/coding-discipline/skills/spec-sync/SKILL.md +++ b/plugins/coding-discipline/skills/spec-sync/SKILL.md @@ -1,37 +1,11 @@ --- name: spec-sync -description: Use in cross-session work when user-confirmed outcomes, non-goals, hard constraints, or acceptance criteria have not been written back to the current source of truth (spec), or reality conflicts with it enough that following it would be wrong; also use during wrap-up or handoff when a source of truth should exist but does not. Edit only the affected original wording; do not keep separate old and new versions. Do not trigger for work that can be completed within one session, local implementation details, verification against existing acceptance criteria, locating the source of truth, or ordinary documentation edits. +description: Use when a user-confirmed decision changes a goal, non-goal, hard constraint, or acceptance criterion that future sessions or collaborators will rely on. license: MIT --- -Hard rule: **A change confirmed in conversation must not remain only in the conversation.** If user-confirmed intent that affects future collaboration or acceptance is not written back to the source of truth in this session, the next session cannot even see that the user changed their mind—intent that was never persisted cannot be recovered. +Would a new session following the current project document pursue a goal the user has rejected, violate a newly confirmed constraint, or use outdated acceptance criteria? If so, update that document. -## The decision test (the only test for whether to sync) -> If the next session or another agent read only the current source of truth, would it continue toward an outcome the user has rejected, violate a new constraint, or judge completion against stale criteria? If so, the change must be synced. - -- Only changes the user has **already confirmed** belong in the spec; your own inferences and ideas still under discussion do not. -- Before deciding, read the current source of truth at most once to compare. Do not turn this into research. - -## Write-back rules -1. Use the current source of truth already designated by the project—the document named by the project guide. -2. If none is designated, designate an existing Issue / PRD / ADR / status document as the current spec; **do not copy it into a second document**. If there are multiple candidates or none is obvious, ask the user to choose. -3. If nothing exists and the work genuinely spans sessions, is shared by multiple people, or would be costly to get wrong, ask whether the user wants a minimal spec (below). The user decides whether to create one; do not create one for work that can be completed within a single session. -4. After designating or creating one, put a pointer to the source of truth in the project guide document (the “where to find the current state” entry in `CLAUDE.md` / `AGENTS.md`)—**write only the pointer, not a copy of the content**—so the next session can find it. -5. **Edit only the affected original wording**: do not append separate “old decision / new decision” versions, reorder the document, or polish the whole document along the way. Replace the affected text as a whole only when the direction changes substantially; leave history to Git. -6. Do not record execution progress, next steps, or verification evidence. Those belong to the harness / Git / CI, not the spec. -7. In multi-person / multi-agent work, workers are read-only by default; the primary agent or owner maintains the spec. - -## Minimal spec (five items—add no more than needed) -The current desired outcome; explicit non-goals; hard constraints; acceptance criteria for this work; confirmed unresolved questions that would block safe execution (include only questions the user has confirmed—do not promote your guesses into settled facts). - -## Exceptions (do not force either case) -- **No write access to the source of truth** (for example, a PRD owned by someone else): do not overstep. State clearly what is stale and who should update it. -- **The user explicitly refuses write-back**: explain that the next session may read the old target, then comply. An old spec must never be used to block the user's latest instruction. - -## Hard rules -- Do not write changes to outcomes / non-goals / hard constraints / acceptance criteria into the source of truth until the user has confirmed them. -- If the implementation is verified but the source of truth is not synced, report those as two separate facts. Do not claim “the source of truth is synced” or “handoff will preserve everything.” -- Complete the sync **within this session**. Do not expect a later session to recover intent that was never persisted. - -## Boundary -Which document is the current source of truth and how to read it belong to context-hygiene. Verifying completion against existing acceptance criteria belongs to verify-before-done. This skill governs one thing only: **whether the source of truth reflects the user's latest confirmed decisions.** +- Find the current issue, spec, or decision record from the project instructions. Consult archived documents only when the task needs their history. +- Update the affected wording in place using only the confirmed decision. Keep the project guide as a pointer, and leave implementation progress and test results in their usual channels. +- If the current document is unclear, use repository evidence to identify it. Ask which document should govern only if the choice matters and remains unresolved. If the document cannot be edited within the task's scope, report what needs to be updated. diff --git a/plugins/coding-discipline/skills/systematic-debugging/SKILL.md b/plugins/coding-discipline/skills/systematic-debugging/SKILL.md index 3cf279b..d7a3a0c 100644 --- a/plugins/coding-discipline/skills/systematic-debugging/SKILL.md +++ b/plugins/coding-discipline/skills/systematic-debugging/SKILL.md @@ -1,40 +1,11 @@ --- name: systematic-debugging -description: Use before proposing a permanent fix for bugs, test failures, or unexpected behavior with an unknown root cause—mandatory when symptoms are far from the cause, a prior fix failed, or the issue crosses components. Reproduce, trace backward to the root cause, fix once at the source, and add a regression test. Do not trigger for obvious errors whose message identifies the cause (syntax/typo/missing import); fix those directly. +description: Use to investigate a failure whose cause is unclear, crosses component boundaries, or persists after a previous fix. Straightforward errors with an established cause can be fixed directly. license: MIT --- -Hard rule: **do not package a guess as a permanent fix before locating the root cause.** If the user explicitly needs emergency containment, you may apply a reversible temporary mitigation first, but you must state its risks and that the root cause is not fixed, then continue investigating. +1. Capture the failing behavior with a small reproduction. If it is intermittent or unavailable, use logs, traces, or a comparison with a known-good run, and state the limits of that evidence. +2. Trace the failure back to the component that introduces it. Check inputs and outputs at boundaries and use the smallest check that can distinguish plausible causes. Revisit the hypothesis when a fix fails. +3. Fix the cause and verify the original failure against the final change. Add a focused regression test if existing coverage would miss the failure and the test can reproduce it reliably. -## 1. Reproduce -- Read the error message and full stack trace carefully—the answer is often there. Do not skip them. Note the line number, file, and error code. -- Establish a reliable reproduction first: which steps trigger it every time? If you cannot reproduce it reliably, gather data before proceeding. **Do not guess.** -- Inspect recent changes: git diff, recent commits, new dependencies, and configuration or environment differences. - -## 2. Trace backward to the root cause -- Follow the bad value backward: where did it come from → who called something with it → continue to the source. **Fix it at the source, not at the symptom.** -- In a multi-component system (CI→build→signing, API→service→library), record what enters and leaves each boundary. Run it once to see **which layer** fails, then investigate that layer. Do not guess based on intuition. -- Find a similar working example and list every difference from the broken one. Do not assume that "this difference cannot matter." -- Example: an amount on a page has two extra decimal places. Trace it backward: the display layer receives the wrong value → it came from the API → the value read from the database is correct → the API returned cents as dollars. **Fix the API layer; do not compensate with display formatting.** - -## 3. One hypothesis at a time -- Write it down: "I believe the root cause is X because Y." -- Test it with the **smallest** change, varying only one thing at a time. Do not stack new fixes on an unverified one. -- If you do not understand X, say so. Do not pretend and guess. - -## 4. Fix the root + add a regression test -- Write a failing test that reproduces the bug before fixing it (see tdd). -- Make **one** fix in one place. Do not opportunistically refactor or change anything else. -- Verify that the test passes, nothing else broke, and the problem is actually gone (see verify-before-done). - -## Three failed fixes = stop and question the architecture -If every fix creates a new problem elsewhere or requires a "large refactor," the problem is not the hypothesis but the architecture. **Do not attempt a fourth fix.** Stop and discuss whether the design itself is fundamentally wrong. - -## No random attempts: when these thoughts appear, stop and return to Step 1 -| Thought | What to do | -|---|---| -| "Apply a quick fix now and investigate the root cause later." | There is no later—once the symptom changes, you will stop investigating. Trace it to the root cause before changing anything. | -| "Change this and see whether it works." | That is guessing. First write, "I believe the root cause is X because Y," then test it with the smallest change. | -| "It is probably X; just fix it." | Reaching a conclusion before tracing the data flow is a gamble. Follow the bad value to its source first. | -| "Put several changes in and run it." | Change only one variable at a time, or a passing result will not tell you which change mattered. | -| "Two attempts failed; maybe one more will work." | Stop. A third attempt probably means the direction is wrong. Return to Step 1 or ask someone else. | +For urgent containment, use a reversible mitigation within the authorized scope. State what it contains and which cause remains unconfirmed. diff --git a/plugins/coding-discipline/skills/tdd/SKILL.md b/plugins/coding-discipline/skills/tdd/SKILL.md index 29b2f7f..ebbe247 100644 --- a/plugins/coding-discipline/skills/tdd/SKILL.md +++ b/plugins/coding-discipline/skills/tdd/SKILL.md @@ -1,39 +1,12 @@ --- name: tdd -description: Use before implementation when behavior can be verified by automated tests and regression coverage has clear value. For bugs with an unknown root cause, use systematic-debugging first, then return for red-green. Follow red-green-refactor—write a failing test first, add only enough code to pass it, then refactor. Do not trigger for documentation, configuration, copy-only, or styling changes with no testable behavior. +description: Use red-green-refactor when the user explicitly asks for test-driven development or the project specifies it for the current change. +disable-model-invocation: true license: MIT --- -Hard rule: **write no implementation code without a test that failed first.** -Did you just write the implementation in this turn without delivering it? Remove it and restart from the test—do not keep it as a "reference" or look at it while adding tests. -**But never delete the user's existing code or someone else's workspace changes**: when working with an existing implementation, add tests that record and protect its current behavior before making the smallest change. +1. Add or adapt the smallest test that expresses the expected behavior. Run it against the baseline and establish that it fails for the intended reason. For a regression, use the actual failing scenario when practical. +2. Make the smallest implementation change that satisfies the behavior. Rerun the test and the relevant existing checks. +3. Refactor if it improves the result, then rerun the relevant checks on the final change. -## Excuses to stop as soon as they appear -| What you tell yourself | Reality | -|---|---| -| "Write the implementation first and add tests later." | Tests written afterward to match the implementation only prove that "the code does what it does," not that it is correct. | -| "Keep this as a reference; do not really remove it." | The time is already spent; it is a sunk cost. If you keep it, you will shape the tests around it. Remove it (only if you wrote it this turn; never delete the user's existing code). | -| "It is too simple to be worth testing." | "Simple" means an assumption you have not stated, which is exactly where failures happen. | - -## Red → Green → Refactor -1. **Red**: write the smallest failing test for one behavior. Give it a name that says what it tests, and test real code rather than mocks (use mocks only when unavoidable). -2. **Verify red (you must run it)**: watch it **fail**, specifically **because the behavior is not implemented yet**—not because of a typo, bad import, or syntax error. - - It passes immediately = you are testing behavior that already exists. The test has no value; rewrite it. - - The program errors instead of failing an assertion = fix the error and rerun until it "fails correctly." -3. **Green**: write the **minimum code needed to make it pass**. Do not slip in features that are not needed yet or change anything else. -4. **Verify green (you must run it)**: the test passes, every other test still passes, and the output is clean (no errors or warnings). If it fails, change the code, not the test. -5. **Refactor**: only after everything is green—remove duplication, improve names, extract functions. Keep the suite green throughout and add no new behavior. -6. For the next behavior, return to red. - -## Bugs also follow red-green -Write a failing test that **reproduces the bug** before fixing it. This test proves the fix and guards against recurrence. (See systematic-debugging for finding the root cause.) - -## A small example (adding email format validation) -1. **Red**: first assert that `is_valid_email("a@b.com")` is true and `is_valid_email("nope")` is false. The function does not exist yet; run the test and see it fail because the function is undefined, not because of a typo. -2. **Green**: write the smallest implementation (one regular expression) that makes both assertions pass. Do not add support for a pile of edge cases. -3. **Refactor**: extract constants or rename things only after everything is green; keep it green throughout. - -## These are design warnings, not testing difficulties -- A test is hard to write = the interface is hard to use. Simplify the interface. -- Everything requires a mock = coupling is too tight. Decouple it (dependency injection). -- Setup is huge = extract helpers; if it remains complex, simplify the design. +If implementation already exists, preserve it and use a safe baseline or an isolated comparison to check that the test distinguishes the behavior. When the baseline cannot be run, report what was verified. diff --git a/plugins/coding-discipline/skills/tdd/agents/openai.yaml b/plugins/coding-discipline/skills/tdd/agents/openai.yaml new file mode 100644 index 0000000..5b1f887 --- /dev/null +++ b/plugins/coding-discipline/skills/tdd/agents/openai.yaml @@ -0,0 +1,2 @@ +policy: + allow_implicit_invocation: false diff --git a/plugins/coding-discipline/skills/verify-before-done/SKILL.md b/plugins/coding-discipline/skills/verify-before-done/SKILL.md deleted file mode 100644 index c3767b9..0000000 --- a/plugins/coding-discipline/skills/verify-before-done/SKILL.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -name: verify-before-done -description: Use before claiming "done", "fixed", "tested", or "it runs", and before committing or opening a PR or MR—no task is exempt. Accept only evidence gathered after the last relevant change and just sufficient to prove the claim; do not over-verify small changes. -license: MIT ---- - -Hard rule: **Only evidence gathered after the last relevant change to the code, files, or environment, and directly sufficient to prove the claim, counts.** -- Claiming completion without sufficient evidence = lying; running the full test suite for a typo = waste. -- You may reuse evidence just gathered, but state when it was gathered and confirm that no code was changed, nothing was pulled, and the environment was not modified afterward. If you cannot say for sure, check again. - -## Required checks (before any claim of success or completion) -1. What claim must be proven? What check is just sufficient (command output / diff / artifact inspection…)? -2. Was the evidence gathered after the last relevant change? Yes—state when. No / uncertain—**check again**. -3. If you ran a command, read all output, inspect the exit code, and count failures. If you inspected a diff or artifact, state what you checked and the result. -4. Does the evidence actually prove the claim? Yes—state the conclusion together with the evidence. No—report the true status. - -Skipping any step = lying, not verification. - -## Could not run ≠ skipped -If a command cannot run (missing environment, broken dependencies, timeout), **verification failed**. Report that verification could not be completed and what blocked it. Do not quietly mark the step green as “skipped,” and do not misreport an environment problem as a product failure. - -## None of these counts as "verified" -| Claimed evidence | Why it does not count | -|---|---| -| lint / type checks passed | This proves only that the checks pass, not that the project builds, runs, or behaves correctly. | -| A subagent reported "success" | That is its claim. Inspect the diff / actual artifact yourself. | -| The regression test passed once | This does not prove it catches the problem. In a safe, isolated way, temporarily disable this round's fix → the test must fail → restore the fix → the test must pass. Do not do this by reverting or overwriting user files. | -| "Tests are green = requirements are met" | Check each requirement explicitly; green tests alone are not enough. | -| Only part of the suite ran | This does not mean the whole suite passed. | - -## Hard rules -- Do not substitute "should", "probably", or "looks right" for evidence. -- Do not celebrate ("Done!" / "Fixed!" / "Perfect!") before obtaining evidence. -- Before committing, pushing, or opening a PR or MR after an important change, pass the checks above. -- If this work includes a confirmed change that makes the current source of truth inaccurate, or the work spans sessions but still lacks a source of truth, use spec-sync before claiming it is ready for handoff. If the user explicitly refuses persistence, explain the consequence and follow their latest instruction. diff --git a/plugins/coding-discipline/templates/agent-doc.seed.md b/plugins/coding-discipline/templates/agent-doc.seed.md deleted file mode 100644 index 037d926..0000000 --- a/plugins/coding-discipline/templates/agent-doc.seed.md +++ /dev/null @@ -1,37 +0,0 @@ -# Project guide - -> The coding-discipline plugin created this file the first time it entered this -> repository. It starts nearly empty on purpose: it is not a specification -> written before the work begins. It grows one confirmed line at a time as the -> project evolves. -> -> Rules for maintaining it (aligned with `context-hygiene`): -> - Record only decisions confirmed with the user that cannot be inferred from -> the code. -> - Leave unresolved topics explicitly unresolved. -> - When a decision changes, replace the old line instead of appending a -> conflicting history. -> - Remove this introductory block once the sections below are established. - -## Current source of truth - -(Not decided — for example, the top of `CHANGELOG.md` or `docs/STATUS.md`. -Every session should trust only the document named here, not old snapshots.) - -## What this project is - -(Not decided — whose problem it solves, what the problem is, and why this -direction was chosen.) - -## Hard boundaries - -(Not decided.) - -## Stack and directory conventions - -(Not decided.) - -## Definition of done - -(Not decided — verifiable completion criteria for each feature, to prevent -overbuilding.) diff --git a/tests/test-hooks.sh b/tests/test-hooks.sh deleted file mode 100755 index 791733c..0000000 --- a/tests/test-hooks.sh +++ /dev/null @@ -1,266 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -ROOT="$(cd "$(dirname "$0")/.." && pwd)" -PLUGIN_ROOT="${ROOT}/plugins/coding-discipline" -HOOK="${PLUGIN_ROOT}/hooks/session-start-skills" -LOG_USAGE="${PLUGIN_ROOT}/hooks/log-usage" -SKILLS_COUNT="${PLUGIN_ROOT}/hooks/skills-count.sh" -TMP_ROOT="$(mktemp -d "${TMPDIR:-/tmp}/coding-discipline-tests.XXXXXX")" - -# A candidate interpreter must actually run. On Windows, the Microsoft Store -# python3.exe stub passes command -v but exits 49 when invoked; `py` is the -# launcher a real Windows install provides, so it has to be a candidate too or -# this suite is unrunnable on the Git Bash setup the README tells people to use. -PYTHON= -for cand in python3 python py; do - if "$cand" -c '' >/dev/null 2>&1; then PYTHON="$cand"; break; fi -done -if [ -z "$PYTHON" ]; then - printf 'FAIL: Python is required for JSON validation\n' >&2 - exit 1 -fi - -cleanup() { - case "$TMP_ROOT" in - "${TMPDIR:-/tmp}"/coding-discipline-tests.*) rm -rf -- "$TMP_ROOT" ;; - *) printf 'refusing to remove unexpected test path: %s\n' "$TMP_ROOT" >&2 ;; - esac -} -trap cleanup EXIT - -fail() { - printf 'FAIL: %s\n' "$*" >&2 - exit 1 -} - -make_repo() { - local path="$1" - git init -q "$path" - git -C "$path" -c user.name=tests -c user.email=tests@example.com \ - commit --allow-empty -qm initial -} - -assert_json_output() { - "$PYTHON" -c 'import json,sys; payload=json.load(sys.stdin); assert payload["hookSpecificOutput"]["hookEventName"] == "SessionStart"' -} - -# Codex's documented PLUGIN_ROOT wins even when CODEX_HOME is unset and the -# compatibility CLAUDE_PLUGIN_ROOT is also present. -repo_codex="${TMP_ROOT}/repo-codex" -make_repo "$repo_codex" -output="$({ - cd "$repo_codex" - env -u CODEX_HOME \ - PLUGIN_ROOT="$PLUGIN_ROOT" \ - CLAUDE_PLUGIN_ROOT="$PLUGIN_ROOT" \ - CD_USAGE_LOG="${TMP_ROOT}/usage-codex.jsonl" \ - "$HOOK" -})" -printf '%s\n' "$output" | assert_json_output -[ -f "${repo_codex}/AGENTS.md" ] || fail 'Codex did not create AGENTS.md' -[ ! -e "${repo_codex}/CLAUDE.md" ] || fail 'Codex created CLAUDE.md' -grep -q '^# Project guide$' "${repo_codex}/AGENTS.md" \ - || fail 'Codex did not seed the English project guide' -grep -q '"platform":"codex"' "${TMP_ROOT}/usage-codex.jsonl" \ - || fail 'Codex usage record has the wrong platform' - -# A Claude guide must not prevent Codex from creating its own guide. -printf '# Claude guide\n' > "${repo_codex}/CLAUDE.md" -rm "${repo_codex}/AGENTS.md" -( - cd "$repo_codex" - CD_USAGE_ENABLED=0 "$HOOK" codex >/dev/null -) -[ -f "${repo_codex}/AGENTS.md" ] || fail 'CLAUDE.md blocked AGENTS.md creation' - -# Existing target guides are never overwritten. -printf '# Keep me\n' > "${repo_codex}/AGENTS.md" -( - cd "$repo_codex" - CD_USAGE_ENABLED=0 "$HOOK" codex >/dev/null -) -[ "$(cat "${repo_codex}/AGENTS.md")" = '# Keep me' ] || fail 'existing AGENTS.md was overwritten' - -# Starting in a nested directory still seeds the repository root. -repo_nested="${TMP_ROOT}/repo-nested" -make_repo "$repo_nested" -mkdir -p "${repo_nested}/src/nested" -( - cd "${repo_nested}/src/nested" - CD_USAGE_ENABLED=0 "$HOOK" codex >/dev/null -) -[ -f "${repo_nested}/AGENTS.md" ] || fail 'nested start did not seed the repository root' -[ ! -e "${repo_nested}/src/nested/AGENTS.md" ] || fail 'guide was written into a nested directory' - -# Git worktrees use a .git pointer file and must still be recognized. -repo_main="${TMP_ROOT}/repo-main" -repo_worktree="${TMP_ROOT}/repo-worktree" -make_repo "$repo_main" -git -C "$repo_main" worktree add -qb test-worktree "$repo_worktree" -( - cd "$repo_worktree" - CD_USAGE_ENABLED=0 "$HOOK" codex >/dev/null -) -[ -f "${repo_worktree}/AGENTS.md" ] || fail 'worktree did not receive AGENTS.md' - -# Claude Code still receives CLAUDE.md. -repo_claude="${TMP_ROOT}/repo-claude" -make_repo "$repo_claude" -( - cd "$repo_claude" - CD_USAGE_ENABLED=0 "$HOOK" claude-code >/dev/null -) -[ -f "${repo_claude}/CLAUDE.md" ] || fail 'Claude Code did not create CLAUDE.md' -[ ! -e "${repo_claude}/AGENTS.md" ] || fail 'Claude Code created AGENTS.md' -grep -q '^# Project guide$' "${repo_claude}/CLAUDE.md" \ - || fail 'Claude Code did not seed the English project guide' - -# Both optional side effects can be disabled. -repo_opt_out="${TMP_ROOT}/repo-opt-out" -make_repo "$repo_opt_out" -( - cd "$repo_opt_out" - CD_SEED_AGENT_DOC=0 CD_USAGE_ENABLED=0 CD_USAGE_LOG="${TMP_ROOT}/disabled.jsonl" \ - "$HOOK" codex >/dev/null -) -[ ! -e "${repo_opt_out}/AGENTS.md" ] || fail 'guide opt-out was ignored' -[ ! -e "${TMP_ROOT}/disabled.jsonl" ] || fail 'usage opt-out was ignored' - -# Cursor and Copilot read the primer from different envelope fields than Claude -# Code and Codex. The hook already handles all four; these cases keep a refactor -# from silently dropping the two that no maintainer runs day to day. -assert_no_guide() { - local repo="$1" host="$2" - [ ! -e "${repo}/AGENTS.md" ] || fail "${host} seeded AGENTS.md" - [ ! -e "${repo}/CLAUDE.md" ] || fail "${host} seeded CLAUDE.md" -} - -repo_cursor="${TMP_ROOT}/repo-cursor" -make_repo "$repo_cursor" -output="$({ - cd "$repo_cursor" - env -u CODEX_HOME -u PLUGIN_ROOT -u COPILOT_CLI \ - CURSOR_PLUGIN_ROOT="$PLUGIN_ROOT" \ - CD_USAGE_LOG="${TMP_ROOT}/usage-cursor.jsonl" \ - "$HOOK" cursor -})" -printf '%s\n' "$output" | "$PYTHON" -c 'import json,sys; p=json.load(sys.stdin); assert set(p) == {"additional_context"}, p; assert p["additional_context"].strip()' \ - || fail 'Cursor did not receive additional_context' -grep -q '"platform":"cursor"' "${TMP_ROOT}/usage-cursor.jsonl" \ - || fail 'Cursor usage record has the wrong platform' -assert_no_guide "$repo_cursor" Cursor - -repo_copilot="${TMP_ROOT}/repo-copilot" -make_repo "$repo_copilot" -output="$({ - cd "$repo_copilot" - env -u CODEX_HOME -u PLUGIN_ROOT -u CURSOR_PLUGIN_ROOT \ - COPILOT_CLI=1 \ - CD_USAGE_LOG="${TMP_ROOT}/usage-copilot.jsonl" \ - "$HOOK" copilot -})" -printf '%s\n' "$output" | "$PYTHON" -c 'import json,sys; p=json.load(sys.stdin); assert set(p) == {"additionalContext"}, p; assert p["additionalContext"].strip()' \ - || fail 'Copilot did not receive additionalContext' -grep -q '"platform":"copilot"' "${TMP_ROOT}/usage-copilot.jsonl" \ - || fail 'Copilot usage record has the wrong platform' -assert_no_guide "$repo_copilot" Copilot - -# Hosts outside the two first-class ones must get the neutral invocation note -# rather than Claude Code's Skill-tool wording. -case "$output" in - *'Load skills through the skill mechanism of this host'*) ;; - *) fail 'a non-primary host did not receive the neutral invocation note' ;; -esac -case "$output" in - *'Skill tool'*) fail 'a non-primary host received Claude Code wording' ;; -esac - -# The primer can be switched off on its own. Measuring what those characters buy -# means changing that one variable and nothing else, so usage counting and guide -# seeding have to survive the opt-out. -repo_primer_off="${TMP_ROOT}/repo-primer-off" -make_repo "$repo_primer_off" -output="$({ - cd "$repo_primer_off" - CD_PRIMER=0 CD_USAGE_LOG="${TMP_ROOT}/usage-primer-off.jsonl" "$HOOK" claude-code -})" -[ -z "$output" ] || fail 'CD_PRIMER=0 still emitted a primer payload' -[ -f "${repo_primer_off}/CLAUDE.md" ] || fail 'CD_PRIMER=0 also suppressed guide seeding' -grep -q '"platform":"claude-code"' "${TMP_ROOT}/usage-primer-off.jsonl" \ - || fail 'CD_PRIMER=0 also suppressed usage counting' - -# Leaving it unset keeps the current behavior. -repo_primer_on="${TMP_ROOT}/repo-primer-on" -make_repo "$repo_primer_on" -output="$({ - cd "$repo_primer_on" - CD_USAGE_ENABLED=0 "$HOOK" claude-code -})" -printf '%s\n' "$output" | assert_json_output -case "$output" in - *'Skill discipline'*) ;; - *) fail 'the default path stopped injecting the primer' ;; -esac - -# A Windows host sends its native path with JSON-escaped backslashes. Each -# separator has to come out as one forward slash; doubling them logs the project -# under a spelling no other record uses. -printf '%s' '{"session_id":"sess-win","cwd":"C:\\Users\\dev\\proj","tool_name":"Skill","tool_input":{"skill":"coding-discipline:tdd"}}' \ - | CD_USAGE_LOG="${TMP_ROOT}/usage-skill-win.jsonl" bash "$LOG_USAGE" -grep -q '"cwd":"C:/Users/dev/proj"' "${TMP_ROOT}/usage-skill-win.jsonl" \ - || fail "skill record mangled a Windows cwd: $(cat "${TMP_ROOT}/usage-skill-win.jsonl")" - -# The session id is what leads from a suspicious trigger back to the transcript -# that produced it, which is where false-trigger reports come from. -grep -q '"session_id":"sess-win"' "${TMP_ROOT}/usage-skill-win.jsonl" \ - || fail "skill record dropped the session id: $(cat "${TMP_ROOT}/usage-skill-win.jsonl")" - -# Decoding the payload leaves real backslashes in a value, so the writer has to -# escape them again. Otherwise odd\name is logged as a newline, and a trailing -# backslash swallows the closing quote of its field. -printf '%s' '{"session_id":"sess\\bs","cwd":"/work/proj","tool_name":"Skill","tool_input":{"skill":"odd\\name\\"}}' \ - | CD_USAGE_LOG="${TMP_ROOT}/usage-backslash.jsonl" bash "$LOG_USAGE" -"$PYTHON" -c 'import json,sys; r=json.loads(sys.stdin.readline()); assert r["skill"] == "odd\\name\\" and r["session_id"] == "sess\\bs", r' \ - < "${TMP_ROOT}/usage-backslash.jsonl" \ - || fail "a backslash in a logged value broke the record: $(cat "${TMP_ROOT}/usage-backslash.jsonl")" - -# Session records take the directory from $PWD, skill records from the host -# payload. On Windows those spell one directory as "/tmp/x" or "/c/x" versus -# "C:\x", so both writers must settle on one spelling or per-project counts split. -repo_same="${TMP_ROOT}/repo-same-dir" -make_repo "$repo_same" -expected_dir="$(cd "$repo_same" && pwd)" -payload_dir="$expected_dir" -if command -v cygpath >/dev/null 2>&1; then - expected_dir="$(cygpath -m "$expected_dir")" - payload_dir="$(cygpath -w "$payload_dir")" -fi -( - cd "$repo_same" - CD_PRIMER=0 CD_SEED_AGENT_DOC=0 CD_USAGE_LOG="${TMP_ROOT}/usage-same-dir.jsonl" \ - "$HOOK" claude-code - printf '{"session_id":"sess-same","cwd":"%s","tool_name":"Skill","tool_input":{"skill":"coding-discipline:tdd"}}' \ - "${payload_dir//\\/\\\\}" \ - | CD_USAGE_LOG="${TMP_ROOT}/usage-same-dir.jsonl" bash "$LOG_USAGE" -) -spellings="$(grep -o '"cwd":"[^"]*"' "${TMP_ROOT}/usage-same-dir.jsonl" | sort -u)" -[ "$spellings" = "\"cwd\":\"${expected_dir}\"" ] \ - || fail "expected every record for one directory to read ${expected_dir}, got: ${spellings}" - -# The report breaks skill invocations down by project. Records written before -# paths were canonicalized doubled every separator; they have to fold into the -# same project as newer records instead of showing up as a second project. -cat > "${TMP_ROOT}/usage-report.jsonl" <<'JSONL' -{"ts":"2026-07-01T00:00:00Z","platform":"claude-code","event":"skill","skill":"coding-discipline:tdd","cwd":"D://work//alpha"} -{"ts":"2026-07-02T00:00:00Z","platform":"claude-code","event":"skill","skill":"coding-discipline:git-flow","cwd":"D:/work/alpha","session_id":"s1"} -{"ts":"2026-07-03T00:00:00Z","platform":"claude-code","event":"skill","skill":"coding-discipline:tdd","cwd":"/home/dev/beta","session_id":"s2"} -{"ts":"2026-07-03T00:00:01Z","platform":"claude-code","event":"session","skill":"","cwd":"/home/dev/beta","session_id":""} -JSONL -report="$(CD_USAGE_LOG="${TMP_ROOT}/usage-report.jsonl" bash "$SKILLS_COUNT")" -printf '%s\n' "$report" | grep -Eq '^ *2 D:/work/alpha$' \ - || fail "report did not count old and new spellings as one project: ${report}" -printf '%s\n' "$report" | grep -Eq '^ *1 /home/dev/beta$' \ - || fail "report miscounted a project: ${report}" - -printf 'hook behavior tests passed\n' diff --git a/tests/test-plugin-metadata.py b/tests/test-plugin-metadata.py index 8434ba1..bfd37e6 100644 --- a/tests/test-plugin-metadata.py +++ b/tests/test-plugin-metadata.py @@ -17,9 +17,17 @@ SKILL_NAME = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*") SKILL_NAME_MAX = 64 SKILL_DESCRIPTION_MAX = 1024 -# Re-frozen after the 2026-07 dedup trim (4944 at v0.8.0). Any new primer or -# description text must be offset elsewhere (zero-sum). +# Retain the existing context ceiling. With no session primer, only the +# skill descriptions contribute to this check. FIXED_CONTEXT_BUDGET = 4580 +AUTOMATIC_SKILLS = {"spec-sync", "systematic-debugging"} +MANUAL_SKILLS = {"brainstorming", "tdd"} +CLAUDE_MANUAL = re.compile(r"^disable-model-invocation:[ \t]+true[ \t]*$", re.MULTILINE) +CODEX_MANUAL = re.compile( + r"^policy:[ \t]*\n(?:[ \t]+[^\n]*\n)*?" + r"[ \t]+allow_implicit_invocation:[ \t]+false[ \t]*$", + re.MULTILINE, +) def load_json(path: Path) -> dict: @@ -36,16 +44,11 @@ def load_json(path: Path) -> dict: claude_manifest = load_json(PLUGIN / ".claude-plugin" / "plugin.json") assert claude_manifest["name"] == manifest["name"], "manifest names diverged" assert claude_manifest["version"] == manifest["version"], "manifest versions diverged" -assert (PLUGIN / manifest["skills"]).is_dir() -assert (PLUGIN / manifest["hooks"]).is_file() - -wrapper_path = "plugins/coding-discipline/hooks/run-hook.cmd" -wrapper_stage = subprocess.check_output( - ["git", "ls-files", "--stage", "--", wrapper_path], - cwd=ROOT, - text=True, -).split() -assert wrapper_stage and wrapper_stage[0] == "100755", "run-hook.cmd must be executable on Unix" +assert (PLUGIN / manifest["skills"]).resolve() == PLUGIN / "skills" +assert "hooks" not in manifest, "Codex must not register hooks" +assert "hooks" not in claude_manifest, "Claude Code must not register hooks" +assert not list(PLUGIN.glob("hooks/*")), "no hooks may ship with the plugin" +assert not (PLUGIN / "templates" / "agent-doc.seed.md").exists() interface = manifest["interface"] for field in ( @@ -61,14 +64,6 @@ def load_json(path: Path) -> dict: assert len(interface["defaultPrompt"]) <= 3 assert all(len(prompt) <= 128 for prompt in interface["defaultPrompt"]) -hooks = load_json(PLUGIN / "hooks" / "hooks-codex.json") -session = hooks["hooks"]["SessionStart"][0] -assert session["matcher"] == "startup|resume|clear|compact" -handler = session["hooks"][0] -assert handler["type"] == "command" -assert handler["command"].endswith("session-start-skills codex") -assert handler["commandWindows"].startswith("cmd.exe ") - marketplace = load_json(ROOT / ".agents" / "plugins" / "marketplace.json") entry = next(item for item in marketplace["plugins"] if item["name"] == manifest["name"]) assert entry["source"] == { @@ -81,8 +76,12 @@ def load_json(path: Path) -> dict: } assert entry["category"] +claude_marketplace = load_json(ROOT / ".claude-plugin" / "marketplace.json") +claude_entry = next(item for item in claude_marketplace["plugins"] if item["name"] == manifest["name"]) +assert claude_entry["source"] == entry["source"]["path"] + skills = sorted((PLUGIN / "skills").glob("*/SKILL.md")) -assert len(skills) == 8 +assert {path.parent.name for path in skills} == AUTOMATIC_SKILLS | MANUAL_SKILLS description_chars = 0 for path in skills: text = path.read_text(encoding="utf-8") @@ -101,14 +100,16 @@ def load_json(path: Path) -> dict: # has to carry its own licence rather than rely on the repository root. licence = re.search(r"(?m)^license:\s*(.+?)\s*$", frontmatter) assert licence and licence.group(1) == "MIT", f"{path} has no license: MIT" + + manual = path.parent.name in MANUAL_SKILLS + assert bool(CLAUDE_MANUAL.search(frontmatter)) == manual, f"{path} has the wrong Claude routing" + codex_policy = path.parent / "agents" / "openai.yaml" + metadata = codex_policy.read_text(encoding="utf-8") if codex_policy.is_file() else "" + assert bool(CODEX_MANUAL.search(metadata)) == manual, f"{path} has the wrong Codex routing" description_chars += len(description.group(1)) -primer_text = (PLUGIN / "hooks" / "skill-discipline.md").read_text(encoding="utf-8") -assert "Respond in the user's language unless they request otherwise." in primer_text -primer_chars = len(primer_text) -fixed_context_chars = description_chars + primer_chars -assert fixed_context_chars <= FIXED_CONTEXT_BUDGET, ( - f"fixed context grew to {fixed_context_chars} chars " +assert description_chars <= FIXED_CONTEXT_BUDGET, ( + f"fixed context grew to {description_chars} chars " f"(budget {FIXED_CONTEXT_BUDGET} = frozen v0.8.0 English baseline)" ) @@ -118,8 +119,6 @@ def load_json(path: Path) -> dict: extensionless_text = { ".gitattributes", ".gitignore", - "log-usage", - "session-start-skills", } tracked_files = subprocess.check_output( ["git", "ls-files"], diff --git a/tests/test-skill-safety.py b/tests/test-skill-safety.py index 09a6e45..1308d55 100644 --- a/tests/test-skill-safety.py +++ b/tests/test-skill-safety.py @@ -71,16 +71,16 @@ assert pattern.search(sample), f"rule went inert and matches nothing: {label}" -tracked = subprocess.check_output( - ["git", "ls-files", "--", SHIPPED], +shipped_files = subprocess.check_output( + ["git", "ls-files", "--cached", "--others", "--exclude-standard", "--", SHIPPED], cwd=ROOT, text=True, ).splitlines() -assert tracked, f"no tracked files under {SHIPPED}" +assert shipped_files, f"no files under {SHIPPED}" findings: list[str] = [] scanned = 0 -for relative in tracked: +for relative in shipped_files: path = ROOT / relative if not path.is_file(): continue @@ -97,12 +97,4 @@ assert not findings, "shipped plugin surface failed the safety scan:\n" + "\n".join(findings) -# The plugin's only persistence is the local usage log. If that sink ever moves, -# the "nothing is sent over the network" claim in README.md needs re-checking -# rather than inheriting the trust this test grants it today. -usage_lib = (ROOT / SHIPPED / "hooks" / "usage-lib.sh").read_text(encoding="utf-8") -assert 'CD_USAGE_LOG="${CD_USAGE_LOG:-$HOME/.coding-discipline/usage.jsonl}"' in usage_lib, ( - "the local usage sink moved; re-confirm the no-network privacy claim in README.md" -) - print(f"skill safety tests passed ({scanned} shipped files scanned)") diff --git a/tests/test-windows-hook.ps1 b/tests/test-windows-hook.ps1 deleted file mode 100644 index 4456200..0000000 --- a/tests/test-windows-hook.ps1 +++ /dev/null @@ -1,99 +0,0 @@ -$ErrorActionPreference = 'Stop' - -$Root = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path -$PluginRoot = Join-Path $Root 'plugins\coding-discipline' -$Hooks = Get-Content -Raw (Join-Path $PluginRoot 'hooks\hooks-codex.json') | ConvertFrom-Json -$CommandWindows = $Hooks.hooks.SessionStart[0].hooks[0].commandWindows -$TempBase = [IO.Path]::GetFullPath([IO.Path]::GetTempPath()) -$TempRoot = Join-Path $TempBase ('coding-discipline-tests-' + [guid]::NewGuid().ToString('N')) -$Repo = Join-Path $TempRoot 'repo' - -try { - New-Item -ItemType Directory -Path $Repo | Out-Null - & git -C $Repo init --quiet - if ($LASTEXITCODE -ne 0) { throw 'git init failed' } - & git -C $Repo -c user.name=tests -c user.email=tests@example.com commit --allow-empty -m initial --quiet - if ($LASTEXITCODE -ne 0) { throw 'git commit failed' } - - $env:PLUGIN_ROOT = $PluginRoot - $env:CLAUDE_PLUGIN_ROOT = $PluginRoot - $env:PLUGIN_DATA = Join-Path $TempRoot 'plugin-data' - $env:CD_USAGE_LOG = Join-Path $TempRoot 'usage.jsonl' - Remove-Item Env:CODEX_HOME -ErrorAction SilentlyContinue - - Push-Location $Repo - try { - $Output = Invoke-Expression $CommandWindows 2>&1 - if ($LASTEXITCODE -ne 0) { throw "Windows hook exited with $LASTEXITCODE`: $Output" } - } - finally { - Pop-Location - } - - $Payload = ($Output -join "`n") | ConvertFrom-Json - if ($Payload.hookSpecificOutput.hookEventName -ne 'SessionStart') { - throw 'Windows hook did not emit SessionStart JSON' - } - if (-not (Test-Path (Join-Path $Repo 'AGENTS.md'))) { throw 'Windows hook did not create AGENTS.md' } - if (Test-Path (Join-Path $Repo 'CLAUDE.md')) { throw 'Windows hook created CLAUDE.md' } - if ((Get-Content (Join-Path $Repo 'AGENTS.md') -TotalCount 1) -ne '# Project guide') { - throw 'Windows hook did not seed the English project guide' - } - if ((Get-Content -Raw $env:CD_USAGE_LOG) -notmatch '"platform":"codex"') { - throw 'Windows hook logged the wrong platform' - } - - # One directory must reach the log under one spelling whichever writer - # recorded it: the session record above came from Git Bash's $PWD, while a - # skill record carries the native path the host sends. - $SkillPayload = @{ - session_id = 'windows-session' - cwd = $Repo - tool_name = 'Skill' - tool_input = @{ skill = 'coding-discipline:tdd' } - } | ConvertTo-Json -Compress - Push-Location $Repo - try { - $SkillPayload | & (Join-Path $PluginRoot 'hooks\run-hook.cmd') log-usage - if ($LASTEXITCODE -ne 0) { throw "log-usage exited with $LASTEXITCODE" } - } - finally { - Pop-Location - } - # Select-Object -Unique compares case-sensitively; Sort-Object -Unique would - # hide a drive-letter case split. - $Spellings = @(Get-Content $env:CD_USAGE_LOG | ForEach-Object { ($_ | ConvertFrom-Json).cwd } | Select-Object -Unique) - $ExpectedDir = $Repo.Replace('\', '/') - if ($Spellings.Count -ne 1 -or $Spellings[0] -cne $ExpectedDir) { - throw "expected every record to read $ExpectedDir, got: $($Spellings -join ' | ')" - } - - Push-Location $Repo - try { - $PreviousPreference = $ErrorActionPreference - $ErrorActionPreference = 'Continue' - & (Join-Path $PluginRoot 'hooks\run-hook.cmd') session-start-skills invalid-platform 2>$null - $WrapperExit = $LASTEXITCODE - $ErrorActionPreference = $PreviousPreference - if ($WrapperExit -ne 2) { throw "wrapper did not preserve exit code 2 (got $WrapperExit)" } - } - finally { - Pop-Location - } - - Write-Output 'Windows hook tests passed' -} -finally { - $ResolvedTemp = [IO.Path]::GetFullPath($TempRoot) - if ($ResolvedTemp.StartsWith($TempBase, [StringComparison]::OrdinalIgnoreCase) -and - (Split-Path $ResolvedTemp -Leaf).StartsWith('coding-discipline-tests-')) { - Remove-Item -LiteralPath $ResolvedTemp -Recurse -Force -ErrorAction SilentlyContinue - } - else { - throw "refusing to remove unexpected test path: $ResolvedTemp" - } -} - -# Do not let the final native command's $LASTEXITCODE (2 from the -# invalid-platform case) leak into the script exit code. -exit 0