From 696fd86fd4d0bf002d2fc0bd6f2eb315e2a9f90a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A5=94=E8=B7=91=E7=9A=84=E9=91=AB?= <3089729486@qq.com> Date: Wed, 2 Sep 2026 21:05:25 +0800 Subject: [PATCH 1/4] feat: add defensive cleanup mode and harness guidance --- README.en.md | 34 ++++++- README.md | 34 ++++++- SKILL.md | 22 ++++- agents/openai.yaml | 4 +- docs/harness-compatibility.md | 47 ++++++++++ references/defensive-categories.md | 33 +++++++ references/defensive-proof-and-delivery.md | 49 ++++++++++ scripts/verify_harness_contract.py | 102 +++++++++++++++++++++ 8 files changed, 310 insertions(+), 15 deletions(-) create mode 100644 docs/harness-compatibility.md create mode 100644 references/defensive-categories.md create mode 100644 references/defensive-proof-and-delivery.md create mode 100644 scripts/verify_harness_contract.py diff --git a/README.en.md b/README.en.md index 356014c..aca7268 100644 --- a/README.en.md +++ b/README.en.md @@ -13,10 +13,16 @@ -`simplify-codebase` is an Agent Skill for finding and safely removing accidental complexity from an existing codebase while protecting behavior, boundaries, and compatibility that still matter. +`simplify-codebase` is an Agent Skill with two separate objectives: safely remove accidental complexity from an existing codebase, or clean maintenance-only defensive layers left by AI-generated changes. Both objectives protect behavior, boundaries, and compatibility that still matter. It does not optimize for deletion volume. It asks whether a change reduces the number of concepts and obligations a team must keep coherent over time. +## AI defensive-layer cleanup + +AI-generated changes can leave tests, build/CI guards, static scans, and inventories that protect only one implementation shape. After this objective is selected, the Skill asks for a cleanup category and traces real consumers and boundaries. A category authorizes investigation, not deletion of a live business, API, security, data-integrity, or deployment contract. + +When both objectives are requested, the Skill keeps their candidates, cut boundaries, and validation results separate instead of mixing the risks in one change batch. + ## Why it exists Codebase entropy is rarely just an unused function. It can be duplicated state, an ownerless abstraction, an interface consumed only by tests, an obsolete compatibility path, or half of a retired feature still embedded in a shared artifact. @@ -69,7 +75,7 @@ git clone https://github.com/tt-a1i/simplify-codebase.git \ ~/.codex/skills/simplify-codebase ``` -Start a new task after installation so the Skill catalog refreshes. For other Agent environments that support `SKILL.md`, place the repository in that environment's Skill directory. +Start a new task after installation so the Skill catalog refreshes. For other Agent environments that support `SKILL.md`, place the repository in that environment's Skill directory. See [Harness compatibility](./docs/harness-compatibility.md) for Codex, Claude Code, Cursor, GitHub Copilot, Cline, Gemini CLI, and OpenCode locations and verification. ## Use @@ -97,12 +103,26 @@ Use $simplify-codebase to remove one high-confidence source of accidental comple Use $simplify-codebase to verify and integrate the simplification findings from this PR. Preserve evidence, not finding counts. ``` +### Clean AI defensive layers + +```text +Use $simplify-codebase for this repository. First ask me to choose ordinary simplification or AI defensive-layer cleanup; do not edit files yet. +``` + +```text +Choose AI defensive-layer cleanup. Remove test guardrails, build/deployment/CI guardrails, and static-check scripts and inventories. Preserve business behavior, APIs, security, data integrity, and real deployment behavior. +``` + +Runtime retries, fallbacks, repairs, and recovery paths are high risk. Handle them only with explicit authorization and evidence that they protect no real boundary. + ## What it returns A read-only survey returns coverage, ranked proof records, important counterexamples, unresolved questions, and the next fact needed for each uncertainty. A change task also returns the implemented cut, validation results by layer, remaining risk, an operation receipt, and an executable undo path. A narrow green check is never presented as complete runtime or user acceptance. +When a Handoff is authorized for defensive cleanup, it must list every deleted file, symbol, or section with its original role, defensive obligation, consumer evidence, removal rationale, retained behavior, reintroduction trigger, and verification result. + ## Repository layout ```text @@ -114,16 +134,20 @@ A change task also returns the implemented cut, validation results by layer, rem │ ├── boundaries-and-lifecycle.md │ ├── execution-and-recovery.md │ ├── decision-records.md -│ └── integrating-findings.md +│ ├── integrating-findings.md +│ ├── defensive-categories.md +│ └── defensive-proof-and-delivery.md ├── docs/validation.md # Behavioral validation evidence +├── docs/harness-compatibility.md # Cross-harness installation and validation +├── scripts/verify_harness_contract.py # Portable contract check └── assets/hero.png # Original hero artwork ``` ## Quality and boundaries -This version has been exercised in Change, Broad, Integration, and Decision-record scenarios, including a full survey of a 973-file Python + TypeScript project. See [docs/validation.md](./docs/validation.md) for the method and known limits. +This version has been exercised in Change, Broad, Integration, and Decision-record scenarios, including a full survey of a 973-file Python + TypeScript project. See [docs/validation.md](./docs/validation.md) for the method and known limits, and [docs/harness-compatibility.md](./docs/harness-compatibility.md) for the cross-harness directory and metadata contract. -The Skill does not replace product judgment. Removing a reachable capability, supported interface, persisted representation, or compatibility path still requires explicit user authority. +The Skill does not replace product judgment. Removing a reachable capability, supported interface, persisted representation, or compatibility path still requires explicit user authority. The AI defensive-layer mode must not misclassify security checks, credential handling, data integrity, access isolation, or durable recovery as routine guardrails. ## Contributing diff --git a/README.md b/README.md index e3761e6..074de9c 100644 --- a/README.md +++ b/README.md @@ -13,10 +13,16 @@ -`simplify-codebase` 是一个面向现有代码库的 Agent Skill。它帮助编码智能体识别并安全移除偶然复杂度,同时保护仍然有效的行为、边界与兼容性。 +`simplify-codebase` 是一个面向现有代码库的 Agent Skill。它有两个互不混用的处理目标:识别并安全移除偶然复杂度,或清理 AI 修改后留下的维护性防回退层;两者都保护仍然有效的行为、边界与兼容性。 它不追求“删得多”。它关心的是:一次改动能否减少团队今后必须持续保持一致的概念和义务。 +## AI 防回退层清理 + +AI 修改可能留下只保护某次实现形态的测试、构建/CI 守卫、静态扫描或清单。选择此目标后,Skill 会先要求选择类别,再追踪真实消费者与边界;类别只授权调查,不授权删除仍在保护业务、API、安全、数据完整性或真实部署行为的代码。 + +当用户同时要求普通简化和防回退层清理时,Skill 会分别维护候选、删除边界与验证结果,避免把两种风险混在同一批修改中。 + ## 为什么需要它 代码库里的冗余很少只是“某个函数没人调用”。它也可能是重复状态、失去所有者的抽象、只剩测试消费的接口、早已无效的兼容路径,或者被保留在共享文件中的半截功能。 @@ -67,7 +73,7 @@ git clone https://github.com/tt-a1i/simplify-codebase.git \ ~/.codex/skills/simplify-codebase ``` -安装后请新建一个任务,让 Skill 目录重新加载。其他支持 `SKILL.md` 的 Agent 环境可将本仓库放入各自的 Skill 目录。 +安装后请新建一个任务,让 Skill 目录重新加载。其他支持 `SKILL.md` 的 Agent 环境可将本仓库放入各自的 Skill 目录。Codex、Claude Code、Cursor、GitHub Copilot、Cline、Gemini CLI 与 OpenCode 的目录、优先级和验证方式见 [跨 Harness 兼容性](./docs/harness-compatibility.md)。 ## 使用 @@ -95,12 +101,26 @@ git clone https://github.com/tt-a1i/simplify-codebase.git \ 使用 $simplify-codebase 复核并整合这个 PR 中的简化建议。保留证据,不保留候选数量。 ``` +### 清理 AI 修改防回退层 + +```text +使用 $simplify-codebase 处理这个仓库。先让我选择:普通代码简化,还是 AI 修改防回退层清理;不要修改文件。 +``` + +```text +选择 AI 防回退层清理。清理测试防回退层、构建部署与 CI 防回退层、静态检查脚本与清单。保留业务、API、安全、数据完整性和真实部署行为。 +``` + +运行时重试、回退、修复和恢复路径风险较高,只有在用户明确授权且证据证明不再保护真实边界时才处理。 + ## 输出是什么样的 只读审计会交付覆盖范围、排序后的证明记录、重要反例、未决问题和下一条所需证据。 修改任务会额外交付实际变更、分层验证结果、剩余风险、操作回执与可执行的撤销路径。一次小范围测试通过,不会被包装成完整的运行时或用户验收。 +如果用户授权生成 Handoff,防回退清理必须逐项记录每个删除文件、删除符号或删除区段:原本作用、防回退职责、消费者证据、为何安全删除、保留的行为、重新引入条件和验证结果。 + ## 仓库结构 ```text @@ -112,16 +132,20 @@ git clone https://github.com/tt-a1i/simplify-codebase.git \ │ ├── boundaries-and-lifecycle.md │ ├── execution-and-recovery.md │ ├── decision-records.md -│ └── integrating-findings.md +│ ├── integrating-findings.md +│ ├── defensive-categories.md +│ └── defensive-proof-and-delivery.md ├── docs/validation.md # 行为验证与质量证据 +├── docs/harness-compatibility.md # 跨平台安装与验证 +├── scripts/verify_harness_contract.py # 可移植契约校验 └── assets/hero.png # 原创 Hero 视觉 ``` ## 质量与边界 -这个版本经过 Change、Broad、Integration 和 Decision-record 场景验证,也在一个 973 文件的 Python + TypeScript 项目上完成过全库审计。测试方法与已知边界记录在 [docs/validation.md](./docs/validation.md)。 +这个版本经过 Change、Broad、Integration 和 Decision-record 场景验证,也在一个 973 文件的 Python + TypeScript 项目上完成过全库审计。测试方法与已知边界记录在 [docs/validation.md](./docs/validation.md)。跨 harness 的目录与元数据契约见 [docs/harness-compatibility.md](./docs/harness-compatibility.md)。 -Skill 不能替代产品决策。删除仍然可达的能力、已支持接口、持久化表示或兼容路径时,仍需由使用者明确授权。 +Skill 不能替代产品决策。删除仍然可达的能力、已支持接口、持久化表示或兼容路径时,仍需由使用者明确授权。AI 防回退模式也不能把安全校验、凭据处理、数据完整性、访问隔离或持久化恢复误判为普通防回退代码。 ## 贡献 diff --git a/SKILL.md b/SKILL.md index 5e3139a..b1ec601 100644 --- a/SKILL.md +++ b/SKILL.md @@ -1,13 +1,25 @@ --- name: simplify-codebase -description: Simplification audit or authorized codebase simplification whose stated objective is to remove accidental complexity. Use for evidence-backed deletion or consolidation of dead code, duplicate state, redundant APIs or layers, ownerless abstractions, obsolete compatibility or design records, and over-engineering in any language; also use for 代码简化 or 熵回收. Do not use for general code review, onboarding, style-only refactoring, or performance tuning. +description: Audit or change an existing codebase through either ordinary simplification or cleanup of AI-generated defensive and anti-regression layers. First route the request to one objective, then use evidence-backed deletion while preserving live behavior, safety boundaries, and compatibility. Use for 代码简化、熵回收或 AI 修改防回退层清理; do not use for general code review, onboarding, style-only refactoring, or performance tuning. --- # Simplify Codebase -Reduce the number of concepts and obligations a codebase must keep coherent. Line-count reduction is supporting evidence, not the objective. A successful run may conclude that the inspected surface is already justified. +Reduce the number of concepts and obligations a codebase must keep coherent. This Skill has two independent objectives: ordinary simplification and AI defensive-layer cleanup. Line-count reduction is supporting evidence, not the objective. A successful run may conclude that the inspected surface is already justified. -## Select mode and scope +## Select the objective, mode, and scope + +First identify the objective. If the user has not made it clear, ask them to choose one before inspecting or modifying files: + +1. **Ordinary simplification** — remove accidental complexity such as dead code, duplicate state, ownerless abstractions, redundant APIs or layers, obsolete compatibility paths, and over-engineering. +2. **AI defensive-layer cleanup** — remove maintenance-only tests, build/deployment/CI guards, static source scans and inventories, or explicitly selected runtime defensive paths that were added to protect an AI-generated change from regression. + +Do not mix the objectives in one unreviewed cut. Both use the shared proof, boundary, authorization, and validation workflow below, but read only the references for the selected objective: + +- For ordinary simplification, use [investigation](references/investigation.md), [boundaries and lifecycle](references/boundaries-and-lifecycle.md), [execution and recovery](references/execution-and-recovery.md), and other references as their routing rules require. +- For AI defensive-layer cleanup, after the user selects one or more defensive categories, read [defensive categories](references/defensive-categories.md) and, for Change mode, [defensive proof and delivery](references/defensive-proof-and-delivery.md). + +If the user selects both objectives, maintain separate candidate records, cut boundaries, and validation results. First choose the authority mode: @@ -70,6 +82,8 @@ In Survey mode, stop after reporting the ranked evidence. Include important reje In Change mode, read [execution-and-recovery.md](references/execution-and-recovery.md) and select the strongest authorized cut. One ownership boundary is the default batch size, not a run limit: for an explicitly requested set of cuts, finish and validate each boundary before starting the next. +For AI defensive-layer cleanup, a selected category authorizes investigation, not deletion of a live contract. Do not remove security, credential, validation, persistence, lifecycle, or real deployment behavior merely because it is defensive. + If the user requests a simplification proposal, local cleanup annotation, or design-record consolidation, or if a selected change invalidates an ADR, RFC, design note, or architectural inventory, read [decision-records.md](references/decision-records.md). Do not turn an ordinary code audit into a repository-wide documentation purge. If the user asks to combine findings from another branch, pull request, task, or agent run, read [integrating-findings.md](references/integrating-findings.md). Preserve evidence, not finding counts. @@ -79,3 +93,5 @@ If the user asks to combine findings from another branch, pull request, task, or For a survey, report coverage, ranked proof records, rejected or unresolved high-value leads, and the next fact needed for each uncertainty. For a change, complete the validation and operation receipt defined in [execution-and-recovery.md](references/execution-and-recovery.md). Report each validation layer separately; a narrow green check does not establish broader runtime, deployment, or user acceptance. + +For AI defensive-layer cleanup, if the user authorizes a Handoff note, enumerate every deleted file and every materially deleted symbol or section in a retained file. For each entry state its original role, defensive obligation, consumer evidence, reason it was safe to remove, retained behavior, reintroduction trigger, and verification. Follow [defensive proof and delivery](references/defensive-proof-and-delivery.md). diff --git a/agents/openai.yaml b/agents/openai.yaml index 48833ad..e7eb445 100644 --- a/agents/openai.yaml +++ b/agents/openai.yaml @@ -1,7 +1,7 @@ interface: display_name: "Simplify Codebase" - short_description: "Prove and remove accidental codebase complexity" - default_prompt: "Use $simplify-codebase to audit this repository and rank the safest high-impact simplifications without editing files." + short_description: "Simplify code or clean AI defensive layers" + default_prompt: "Use $simplify-codebase. First ask whether to simplify accidental complexity or clean AI-generated defensive layers, then audit without editing files." policy: allow_implicit_invocation: true diff --git a/docs/harness-compatibility.md b/docs/harness-compatibility.md new file mode 100644 index 0000000..fb0ad14 --- /dev/null +++ b/docs/harness-compatibility.md @@ -0,0 +1,47 @@ +# Harness Compatibility / Harness 兼容性 + +`simplify-codebase` is one portable Agent Skills package. Its installation directory, `SKILL.md` frontmatter `name`, and invocation name are all `simplify-codebase`. This alignment is required by some harnesses and avoids platform-specific aliases. + +`simplify-codebase` 是一个可移植的单一 Agent Skills 包。安装目录、`SKILL.md` 的 `name` 与调用名称统一为 `simplify-codebase`;部分 harness 要求三者一致,这一约定可避免平台专属别名。 + +## Portable contract / 可移植契约 + +- `SKILL.md` begins with only the portable `name` and `description` frontmatter fields. +- Detailed guidance is loaded through repository-relative Markdown links. +- Codex display metadata lives in `agents/openai.yaml`; other harnesses may ignore that optional file safely. +- Do not add vendor-only fields to `SKILL.md`. Put vendor-specific behavior in a separate adapter only when it is necessary and does not change the shared workflow. + +Run this release check from the repository root: + +```bash +python scripts/verify_harness_contract.py +``` + +After installation, add `--verify-directory-name` to confirm that the installed directory also matches `simplify-codebase`. + +安装后可添加 `--verify-directory-name`,确认实际安装目录同样命名为 `simplify-codebase`。 + +## Supported discovery locations / 支持的发现目录 + +| Harness | User scope | Project scope | Verify | +| --- | --- | --- | --- | +| Codex | `~/.codex/skills/simplify-codebase/` | repository-specific Codex skill directory when configured | Start a new task and invoke `$simplify-codebase`. | +| Claude Code | `~/.claude/skills/simplify-codebase/` | `.claude/skills/simplify-codebase/` | Invoke `/simplify-codebase` or ask a matching request. | +| Cursor | `~/.agents/skills/simplify-codebase/` or `~/.cursor/skills/simplify-codebase/` | `.agents/skills/simplify-codebase/` or `.cursor/skills/simplify-codebase/` | Use `/simplify-codebase` or verify it appears in Customize → Skills. | +| GitHub Copilot | `~/.copilot/skills/simplify-codebase/` or `~/.agents/skills/simplify-codebase/` | `.github/skills/simplify-codebase/`, `.claude/skills/simplify-codebase/`, or `.agents/skills/simplify-codebase/` | Invoke `/simplify-codebase` or confirm it is listed by the Copilot client. | +| Cline | `~/.cline/skills/simplify-codebase/` | `.cline/skills/simplify-codebase/`, `.clinerules/skills/simplify-codebase/`, or `.claude/skills/simplify-codebase/` | Enable Skills, then invoke a matching request or confirm it appears in the Skills panel. | +| Gemini CLI | `~/.gemini/skills/simplify-codebase/` | `.gemini/skills/simplify-codebase/` | Run `/skills list`, then invoke or approve activation. | +| OpenCode | `~/.agents/skills/simplify-codebase/` or `~/.config/opencode/skills/simplify-codebase/` | `.agents/skills/simplify-codebase/` or `.opencode/skills/simplify-codebase/` | Confirm the `skill` tool advertises `simplify-codebase` in a new session. | + +Use one location at the intended precedence level. Do not install a second copy with the same name unless an override is intentional. + +选择目标优先级中的一个目录安装即可。除非明确需要覆盖,不要安装同名的第二份副本。 + +## Sources / 依据 + +- [Claude Code Skills](https://code.claude.com/docs/en/skills) +- [Cursor Agent Skills](https://prod.cursor.com/docs/skills) +- [GitHub Copilot Agent Skills](https://docs.github.com/en/copilot/concepts/agents/about-agent-skills) +- [Cline Skills](https://docs.cline.bot/customization/skills) +- [Gemini CLI Agent Skills](https://geminicli.com/docs/cli/tutorials/skills-getting-started/) +- [OpenCode Agent Skills](https://opencode.ai/docs/skills) diff --git a/references/defensive-categories.md b/references/defensive-categories.md new file mode 100644 index 0000000..f5c5935 --- /dev/null +++ b/references/defensive-categories.md @@ -0,0 +1,33 @@ +# AI Defensive-Layer Categories + +Read this reference only after the user selects the AI defensive-layer cleanup objective. A category identifies where to investigate; it never proves that removal is safe. + +## 1. Test guardrails + +Look for tests that assert directory trees, import bans, fixed file inventories, historical migration names, exact agent/component counts, implementation-private defaults, or literal source text. Prefer removing a test only when it has no distinct user-visible, API, persistence, or operational behavior to protect. + +Keep tests for business outcomes, public APIs, error handling, security, persistence, concurrency, deployment acceptance, and integration behavior even when they use mocks. + +## 2. Build, deployment, and CI guardrails + +Look for duplicate builders, abandoned conversion paths, temporary packaging adapters, dead image-export helpers, and CI jobs that only enforce a retired implementation. Trace every script from documented commands, manifests, containers, CI configuration, release instructions, and external deployment entrypoints. + +Do not remove credential filtering, image/runtime startup behavior, health checks, reproducible artifact requirements, or active release commands without an explicit operational decision. + +## 3. Static-check guardrails + +Look for source scanners, regex allowlists/denylists, layout checks, generated manifest comparisons, dependency bans, and documentation inventories created solely as AI-change tripwires. Determine whether the same requirement is already covered by a meaningful behavior check or a current CI policy. + +Keep security scanning, license/compliance checks, accessibility requirements, and gates owned by an active engineering policy. + +## 4. Compatibility and relay layers + +Look for one-line re-exports, deprecated module paths, old environment keys, former file locations, old response envelopes, UI state migration, and adapters with no current consumer. Check external callers, persisted data, deployment environment variables, release notes, and historical inputs before deletion. + +Removing a reachable public or persisted compatibility path is a product decision. Stop and request direction if its support window is unknown. + +## 5. Runtime defensive paths + +Look for fallback providers, retries, error normalization, output repair, mock-only bootstrapping, rollback routes, and recovery branches. First name the user-visible failure mode and the boundary protected. Many of these are live business reliability requirements, not AI-edit protection. + +Only remove a runtime defensive path when evidence shows it protects no real boundary and the user has authorized surrendering the behavior. Never fold security, authorization, secret handling, validation, data-integrity, or durable-data recovery into a routine cleanup batch. diff --git a/references/defensive-proof-and-delivery.md b/references/defensive-proof-and-delivery.md new file mode 100644 index 0000000..e0f6785 --- /dev/null +++ b/references/defensive-proof-and-delivery.md @@ -0,0 +1,49 @@ +# Defensive Cleanup Proof and Delivery + +## Candidate record + +For each deletion candidate, record: + +```text +Candidate: exact test, script, layer, symbol, or path +Category: selected cleanup category +Purpose: defensive/anti-regression behavior it was intended to enforce +Consumers: runtime, support-only, dynamic/external, persisted, unknown +Cut boundary: code, tests, configuration, docs, and build entries to change +Consequence: observable behavior or compatibility no longer offered +Confidence and risk: evidence strength, blast radius, reversibility +Verification: smallest decisive check plus affected local gates +``` + +Do not treat an unreferenced file as proven dead until dynamic imports, package exports, scripts, environment keys, persisted formats, and external consumers are accounted for. + +## Change sequence + +1. Capture the relevant baseline and known failures when feasible. +2. Complete one ownership boundary at a time. +3. Search for removed symbols, paths, configuration keys, and documentation residue. +4. Run the targeted behavior check, then affected build/type/lint/test/smoke checks. +5. Inspect the diff and working-tree status. Do not stage generated runtime data or unrelated user changes. +6. If a Handoff note is authorized, use an itemized deletion ledger. Do not collapse multiple files into a category summary. + +## Handoff deletion ledger + +The Handoff note must contain one entry for every deleted file and every materially deleted symbol or section in a retained file. A table is preferred: + +```text +Deleted path or retained file + removed symbol/section: exact repository-relative path and name +Original role: what the file, symbol, or section did before cleanup +Category: selected cleanup category +Defensive obligation: the AI-change rollback/anti-regression/static obligation it enforced +Consumer evidence: runtime/support/dynamic/persisted/external search and boundary findings +Why safe to remove: why it is not a live business, API, security, persistence, lifecycle, or deployment contract +Retained behavior: active code, test, build path, or safety boundary that remains +Reintroduction trigger: the concrete future requirement that would justify restoring it +Verification: targeted check and affected local gates, including baseline failures if relevant +``` + +For a deleted file, explain its original responsibility even if it had no runtime consumer. For a partially edited file, identify the removed implementation-shape guard separately from the file's retained business/API responsibility. Include generated runtime data and unrelated working-tree changes in a separate exclusion note; they are not deletion entries. + +## Stop conditions + +Stop and report rather than delete when a candidate has unresolved dynamic/external consumers, supports stored data or a public contract, is tied to security or data safety, has a failing baseline that masks the result, or needs a product decision about backwards compatibility. diff --git a/scripts/verify_harness_contract.py b/scripts/verify_harness_contract.py new file mode 100644 index 0000000..e5283e2 --- /dev/null +++ b/scripts/verify_harness_contract.py @@ -0,0 +1,102 @@ +#!/usr/bin/env python3 +"""Check the portable Agent Skills contract used by supported harnesses.""" + +from __future__ import annotations + +import argparse +import re +import sys +from pathlib import Path + + +EXPECTED_NAME = "simplify-codebase" +FRONTMATTER_FIELDS = {"name", "description"} +NAME_PATTERN = re.compile(r"^[a-z0-9-]+$") +MAX_DESCRIPTION_LENGTH = 1024 + + +def fail(message: str) -> None: + print(f"ERROR: {message}", file=sys.stderr) + raise SystemExit(1) + + +def parse_frontmatter(skill_path: Path) -> dict[str, str]: + lines = skill_path.read_text(encoding="utf-8").splitlines() + if not lines or lines[0] != "---": + fail("SKILL.md must begin with YAML frontmatter.") + + try: + end = lines.index("---", 1) + except ValueError: + fail("SKILL.md frontmatter is not closed.") + + fields: dict[str, str] = {} + for line in lines[1:end]: + if not line.strip() or line.lstrip().startswith("#"): + continue + if ":" not in line: + fail(f"Unsupported frontmatter syntax: {line!r}") + key, value = line.split(":", 1) + fields[key.strip()] = value.strip().strip('"') + return fields + + +def verify_relative_links(root: Path, skill_path: Path) -> None: + content = skill_path.read_text(encoding="utf-8") + for destination in re.findall(r"\]\(([^)]+)\)", content): + if "://" in destination or destination.startswith("#"): + continue + target = root / destination.split("#", 1)[0] + if not target.exists(): + fail(f"SKILL.md links to missing local resource: {destination}") + + +def main() -> None: + parser = argparse.ArgumentParser( + description="Check the portable Agent Skills package contract." + ) + parser.add_argument( + "--verify-directory-name", + action="store_true", + help="also require the current directory to match the skill name", + ) + args = parser.parse_args() + + root = Path(__file__).resolve().parents[1] + skill_path = root / "SKILL.md" + if args.verify_directory_name and root.name != EXPECTED_NAME: + fail( + f"Skill directory must be named {EXPECTED_NAME!r}; found {root.name!r}." + ) + if not skill_path.is_file(): + fail("Missing SKILL.md.") + + fields = parse_frontmatter(skill_path) + if set(fields) != FRONTMATTER_FIELDS: + fail( + "Portable SKILL.md frontmatter must contain only name and description; " + f"found {sorted(fields)}." + ) + if fields["name"] != EXPECTED_NAME: + fail( + f"Frontmatter name must be {EXPECTED_NAME!r}; found {fields['name']!r}." + ) + if not NAME_PATTERN.fullmatch(fields["name"]): + fail("Frontmatter name must use lowercase letters, digits, and hyphens only.") + if not fields["description"]: + fail("Frontmatter description must not be empty.") + if len(fields["description"]) > MAX_DESCRIPTION_LENGTH: + fail( + "Frontmatter description must be at most " + f"{MAX_DESCRIPTION_LENGTH} characters." + ) + + verify_relative_links(root, skill_path) + if not (root / "agents" / "openai.yaml").is_file(): + fail("Missing optional Codex metadata at agents/openai.yaml.") + + print("Portable harness contract: valid") + + +if __name__ == "__main__": + main() From 8e45841283ead0f2de9d53fa85012da38229be03 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A5=94=E8=B7=91=E7=9A=84=E9=91=AB?= <3089729486@qq.com> Date: Wed, 2 Sep 2026 22:03:12 +0800 Subject: [PATCH 2/4] Revert "feat: add defensive cleanup mode and harness guidance" This reverts commit 696fd86fd4d0bf002d2fc0bd6f2eb315e2a9f90a. --- README.en.md | 34 +------ README.md | 34 +------ SKILL.md | 22 +---- agents/openai.yaml | 4 +- docs/harness-compatibility.md | 47 ---------- references/defensive-categories.md | 33 ------- references/defensive-proof-and-delivery.md | 49 ---------- scripts/verify_harness_contract.py | 102 --------------------- 8 files changed, 15 insertions(+), 310 deletions(-) delete mode 100644 docs/harness-compatibility.md delete mode 100644 references/defensive-categories.md delete mode 100644 references/defensive-proof-and-delivery.md delete mode 100644 scripts/verify_harness_contract.py diff --git a/README.en.md b/README.en.md index aca7268..356014c 100644 --- a/README.en.md +++ b/README.en.md @@ -13,16 +13,10 @@ -`simplify-codebase` is an Agent Skill with two separate objectives: safely remove accidental complexity from an existing codebase, or clean maintenance-only defensive layers left by AI-generated changes. Both objectives protect behavior, boundaries, and compatibility that still matter. +`simplify-codebase` is an Agent Skill for finding and safely removing accidental complexity from an existing codebase while protecting behavior, boundaries, and compatibility that still matter. It does not optimize for deletion volume. It asks whether a change reduces the number of concepts and obligations a team must keep coherent over time. -## AI defensive-layer cleanup - -AI-generated changes can leave tests, build/CI guards, static scans, and inventories that protect only one implementation shape. After this objective is selected, the Skill asks for a cleanup category and traces real consumers and boundaries. A category authorizes investigation, not deletion of a live business, API, security, data-integrity, or deployment contract. - -When both objectives are requested, the Skill keeps their candidates, cut boundaries, and validation results separate instead of mixing the risks in one change batch. - ## Why it exists Codebase entropy is rarely just an unused function. It can be duplicated state, an ownerless abstraction, an interface consumed only by tests, an obsolete compatibility path, or half of a retired feature still embedded in a shared artifact. @@ -75,7 +69,7 @@ git clone https://github.com/tt-a1i/simplify-codebase.git \ ~/.codex/skills/simplify-codebase ``` -Start a new task after installation so the Skill catalog refreshes. For other Agent environments that support `SKILL.md`, place the repository in that environment's Skill directory. See [Harness compatibility](./docs/harness-compatibility.md) for Codex, Claude Code, Cursor, GitHub Copilot, Cline, Gemini CLI, and OpenCode locations and verification. +Start a new task after installation so the Skill catalog refreshes. For other Agent environments that support `SKILL.md`, place the repository in that environment's Skill directory. ## Use @@ -103,26 +97,12 @@ Use $simplify-codebase to remove one high-confidence source of accidental comple Use $simplify-codebase to verify and integrate the simplification findings from this PR. Preserve evidence, not finding counts. ``` -### Clean AI defensive layers - -```text -Use $simplify-codebase for this repository. First ask me to choose ordinary simplification or AI defensive-layer cleanup; do not edit files yet. -``` - -```text -Choose AI defensive-layer cleanup. Remove test guardrails, build/deployment/CI guardrails, and static-check scripts and inventories. Preserve business behavior, APIs, security, data integrity, and real deployment behavior. -``` - -Runtime retries, fallbacks, repairs, and recovery paths are high risk. Handle them only with explicit authorization and evidence that they protect no real boundary. - ## What it returns A read-only survey returns coverage, ranked proof records, important counterexamples, unresolved questions, and the next fact needed for each uncertainty. A change task also returns the implemented cut, validation results by layer, remaining risk, an operation receipt, and an executable undo path. A narrow green check is never presented as complete runtime or user acceptance. -When a Handoff is authorized for defensive cleanup, it must list every deleted file, symbol, or section with its original role, defensive obligation, consumer evidence, removal rationale, retained behavior, reintroduction trigger, and verification result. - ## Repository layout ```text @@ -134,20 +114,16 @@ When a Handoff is authorized for defensive cleanup, it must list every deleted f │ ├── boundaries-and-lifecycle.md │ ├── execution-and-recovery.md │ ├── decision-records.md -│ ├── integrating-findings.md -│ ├── defensive-categories.md -│ └── defensive-proof-and-delivery.md +│ └── integrating-findings.md ├── docs/validation.md # Behavioral validation evidence -├── docs/harness-compatibility.md # Cross-harness installation and validation -├── scripts/verify_harness_contract.py # Portable contract check └── assets/hero.png # Original hero artwork ``` ## Quality and boundaries -This version has been exercised in Change, Broad, Integration, and Decision-record scenarios, including a full survey of a 973-file Python + TypeScript project. See [docs/validation.md](./docs/validation.md) for the method and known limits, and [docs/harness-compatibility.md](./docs/harness-compatibility.md) for the cross-harness directory and metadata contract. +This version has been exercised in Change, Broad, Integration, and Decision-record scenarios, including a full survey of a 973-file Python + TypeScript project. See [docs/validation.md](./docs/validation.md) for the method and known limits. -The Skill does not replace product judgment. Removing a reachable capability, supported interface, persisted representation, or compatibility path still requires explicit user authority. The AI defensive-layer mode must not misclassify security checks, credential handling, data integrity, access isolation, or durable recovery as routine guardrails. +The Skill does not replace product judgment. Removing a reachable capability, supported interface, persisted representation, or compatibility path still requires explicit user authority. ## Contributing diff --git a/README.md b/README.md index 074de9c..e3761e6 100644 --- a/README.md +++ b/README.md @@ -13,16 +13,10 @@ -`simplify-codebase` 是一个面向现有代码库的 Agent Skill。它有两个互不混用的处理目标:识别并安全移除偶然复杂度,或清理 AI 修改后留下的维护性防回退层;两者都保护仍然有效的行为、边界与兼容性。 +`simplify-codebase` 是一个面向现有代码库的 Agent Skill。它帮助编码智能体识别并安全移除偶然复杂度,同时保护仍然有效的行为、边界与兼容性。 它不追求“删得多”。它关心的是:一次改动能否减少团队今后必须持续保持一致的概念和义务。 -## AI 防回退层清理 - -AI 修改可能留下只保护某次实现形态的测试、构建/CI 守卫、静态扫描或清单。选择此目标后,Skill 会先要求选择类别,再追踪真实消费者与边界;类别只授权调查,不授权删除仍在保护业务、API、安全、数据完整性或真实部署行为的代码。 - -当用户同时要求普通简化和防回退层清理时,Skill 会分别维护候选、删除边界与验证结果,避免把两种风险混在同一批修改中。 - ## 为什么需要它 代码库里的冗余很少只是“某个函数没人调用”。它也可能是重复状态、失去所有者的抽象、只剩测试消费的接口、早已无效的兼容路径,或者被保留在共享文件中的半截功能。 @@ -73,7 +67,7 @@ git clone https://github.com/tt-a1i/simplify-codebase.git \ ~/.codex/skills/simplify-codebase ``` -安装后请新建一个任务,让 Skill 目录重新加载。其他支持 `SKILL.md` 的 Agent 环境可将本仓库放入各自的 Skill 目录。Codex、Claude Code、Cursor、GitHub Copilot、Cline、Gemini CLI 与 OpenCode 的目录、优先级和验证方式见 [跨 Harness 兼容性](./docs/harness-compatibility.md)。 +安装后请新建一个任务,让 Skill 目录重新加载。其他支持 `SKILL.md` 的 Agent 环境可将本仓库放入各自的 Skill 目录。 ## 使用 @@ -101,26 +95,12 @@ git clone https://github.com/tt-a1i/simplify-codebase.git \ 使用 $simplify-codebase 复核并整合这个 PR 中的简化建议。保留证据,不保留候选数量。 ``` -### 清理 AI 修改防回退层 - -```text -使用 $simplify-codebase 处理这个仓库。先让我选择:普通代码简化,还是 AI 修改防回退层清理;不要修改文件。 -``` - -```text -选择 AI 防回退层清理。清理测试防回退层、构建部署与 CI 防回退层、静态检查脚本与清单。保留业务、API、安全、数据完整性和真实部署行为。 -``` - -运行时重试、回退、修复和恢复路径风险较高,只有在用户明确授权且证据证明不再保护真实边界时才处理。 - ## 输出是什么样的 只读审计会交付覆盖范围、排序后的证明记录、重要反例、未决问题和下一条所需证据。 修改任务会额外交付实际变更、分层验证结果、剩余风险、操作回执与可执行的撤销路径。一次小范围测试通过,不会被包装成完整的运行时或用户验收。 -如果用户授权生成 Handoff,防回退清理必须逐项记录每个删除文件、删除符号或删除区段:原本作用、防回退职责、消费者证据、为何安全删除、保留的行为、重新引入条件和验证结果。 - ## 仓库结构 ```text @@ -132,20 +112,16 @@ git clone https://github.com/tt-a1i/simplify-codebase.git \ │ ├── boundaries-and-lifecycle.md │ ├── execution-and-recovery.md │ ├── decision-records.md -│ ├── integrating-findings.md -│ ├── defensive-categories.md -│ └── defensive-proof-and-delivery.md +│ └── integrating-findings.md ├── docs/validation.md # 行为验证与质量证据 -├── docs/harness-compatibility.md # 跨平台安装与验证 -├── scripts/verify_harness_contract.py # 可移植契约校验 └── assets/hero.png # 原创 Hero 视觉 ``` ## 质量与边界 -这个版本经过 Change、Broad、Integration 和 Decision-record 场景验证,也在一个 973 文件的 Python + TypeScript 项目上完成过全库审计。测试方法与已知边界记录在 [docs/validation.md](./docs/validation.md)。跨 harness 的目录与元数据契约见 [docs/harness-compatibility.md](./docs/harness-compatibility.md)。 +这个版本经过 Change、Broad、Integration 和 Decision-record 场景验证,也在一个 973 文件的 Python + TypeScript 项目上完成过全库审计。测试方法与已知边界记录在 [docs/validation.md](./docs/validation.md)。 -Skill 不能替代产品决策。删除仍然可达的能力、已支持接口、持久化表示或兼容路径时,仍需由使用者明确授权。AI 防回退模式也不能把安全校验、凭据处理、数据完整性、访问隔离或持久化恢复误判为普通防回退代码。 +Skill 不能替代产品决策。删除仍然可达的能力、已支持接口、持久化表示或兼容路径时,仍需由使用者明确授权。 ## 贡献 diff --git a/SKILL.md b/SKILL.md index b1ec601..5e3139a 100644 --- a/SKILL.md +++ b/SKILL.md @@ -1,25 +1,13 @@ --- name: simplify-codebase -description: Audit or change an existing codebase through either ordinary simplification or cleanup of AI-generated defensive and anti-regression layers. First route the request to one objective, then use evidence-backed deletion while preserving live behavior, safety boundaries, and compatibility. Use for 代码简化、熵回收或 AI 修改防回退层清理; do not use for general code review, onboarding, style-only refactoring, or performance tuning. +description: Simplification audit or authorized codebase simplification whose stated objective is to remove accidental complexity. Use for evidence-backed deletion or consolidation of dead code, duplicate state, redundant APIs or layers, ownerless abstractions, obsolete compatibility or design records, and over-engineering in any language; also use for 代码简化 or 熵回收. Do not use for general code review, onboarding, style-only refactoring, or performance tuning. --- # Simplify Codebase -Reduce the number of concepts and obligations a codebase must keep coherent. This Skill has two independent objectives: ordinary simplification and AI defensive-layer cleanup. Line-count reduction is supporting evidence, not the objective. A successful run may conclude that the inspected surface is already justified. +Reduce the number of concepts and obligations a codebase must keep coherent. Line-count reduction is supporting evidence, not the objective. A successful run may conclude that the inspected surface is already justified. -## Select the objective, mode, and scope - -First identify the objective. If the user has not made it clear, ask them to choose one before inspecting or modifying files: - -1. **Ordinary simplification** — remove accidental complexity such as dead code, duplicate state, ownerless abstractions, redundant APIs or layers, obsolete compatibility paths, and over-engineering. -2. **AI defensive-layer cleanup** — remove maintenance-only tests, build/deployment/CI guards, static source scans and inventories, or explicitly selected runtime defensive paths that were added to protect an AI-generated change from regression. - -Do not mix the objectives in one unreviewed cut. Both use the shared proof, boundary, authorization, and validation workflow below, but read only the references for the selected objective: - -- For ordinary simplification, use [investigation](references/investigation.md), [boundaries and lifecycle](references/boundaries-and-lifecycle.md), [execution and recovery](references/execution-and-recovery.md), and other references as their routing rules require. -- For AI defensive-layer cleanup, after the user selects one or more defensive categories, read [defensive categories](references/defensive-categories.md) and, for Change mode, [defensive proof and delivery](references/defensive-proof-and-delivery.md). - -If the user selects both objectives, maintain separate candidate records, cut boundaries, and validation results. +## Select mode and scope First choose the authority mode: @@ -82,8 +70,6 @@ In Survey mode, stop after reporting the ranked evidence. Include important reje In Change mode, read [execution-and-recovery.md](references/execution-and-recovery.md) and select the strongest authorized cut. One ownership boundary is the default batch size, not a run limit: for an explicitly requested set of cuts, finish and validate each boundary before starting the next. -For AI defensive-layer cleanup, a selected category authorizes investigation, not deletion of a live contract. Do not remove security, credential, validation, persistence, lifecycle, or real deployment behavior merely because it is defensive. - If the user requests a simplification proposal, local cleanup annotation, or design-record consolidation, or if a selected change invalidates an ADR, RFC, design note, or architectural inventory, read [decision-records.md](references/decision-records.md). Do not turn an ordinary code audit into a repository-wide documentation purge. If the user asks to combine findings from another branch, pull request, task, or agent run, read [integrating-findings.md](references/integrating-findings.md). Preserve evidence, not finding counts. @@ -93,5 +79,3 @@ If the user asks to combine findings from another branch, pull request, task, or For a survey, report coverage, ranked proof records, rejected or unresolved high-value leads, and the next fact needed for each uncertainty. For a change, complete the validation and operation receipt defined in [execution-and-recovery.md](references/execution-and-recovery.md). Report each validation layer separately; a narrow green check does not establish broader runtime, deployment, or user acceptance. - -For AI defensive-layer cleanup, if the user authorizes a Handoff note, enumerate every deleted file and every materially deleted symbol or section in a retained file. For each entry state its original role, defensive obligation, consumer evidence, reason it was safe to remove, retained behavior, reintroduction trigger, and verification. Follow [defensive proof and delivery](references/defensive-proof-and-delivery.md). diff --git a/agents/openai.yaml b/agents/openai.yaml index e7eb445..48833ad 100644 --- a/agents/openai.yaml +++ b/agents/openai.yaml @@ -1,7 +1,7 @@ interface: display_name: "Simplify Codebase" - short_description: "Simplify code or clean AI defensive layers" - default_prompt: "Use $simplify-codebase. First ask whether to simplify accidental complexity or clean AI-generated defensive layers, then audit without editing files." + short_description: "Prove and remove accidental codebase complexity" + default_prompt: "Use $simplify-codebase to audit this repository and rank the safest high-impact simplifications without editing files." policy: allow_implicit_invocation: true diff --git a/docs/harness-compatibility.md b/docs/harness-compatibility.md deleted file mode 100644 index fb0ad14..0000000 --- a/docs/harness-compatibility.md +++ /dev/null @@ -1,47 +0,0 @@ -# Harness Compatibility / Harness 兼容性 - -`simplify-codebase` is one portable Agent Skills package. Its installation directory, `SKILL.md` frontmatter `name`, and invocation name are all `simplify-codebase`. This alignment is required by some harnesses and avoids platform-specific aliases. - -`simplify-codebase` 是一个可移植的单一 Agent Skills 包。安装目录、`SKILL.md` 的 `name` 与调用名称统一为 `simplify-codebase`;部分 harness 要求三者一致,这一约定可避免平台专属别名。 - -## Portable contract / 可移植契约 - -- `SKILL.md` begins with only the portable `name` and `description` frontmatter fields. -- Detailed guidance is loaded through repository-relative Markdown links. -- Codex display metadata lives in `agents/openai.yaml`; other harnesses may ignore that optional file safely. -- Do not add vendor-only fields to `SKILL.md`. Put vendor-specific behavior in a separate adapter only when it is necessary and does not change the shared workflow. - -Run this release check from the repository root: - -```bash -python scripts/verify_harness_contract.py -``` - -After installation, add `--verify-directory-name` to confirm that the installed directory also matches `simplify-codebase`. - -安装后可添加 `--verify-directory-name`,确认实际安装目录同样命名为 `simplify-codebase`。 - -## Supported discovery locations / 支持的发现目录 - -| Harness | User scope | Project scope | Verify | -| --- | --- | --- | --- | -| Codex | `~/.codex/skills/simplify-codebase/` | repository-specific Codex skill directory when configured | Start a new task and invoke `$simplify-codebase`. | -| Claude Code | `~/.claude/skills/simplify-codebase/` | `.claude/skills/simplify-codebase/` | Invoke `/simplify-codebase` or ask a matching request. | -| Cursor | `~/.agents/skills/simplify-codebase/` or `~/.cursor/skills/simplify-codebase/` | `.agents/skills/simplify-codebase/` or `.cursor/skills/simplify-codebase/` | Use `/simplify-codebase` or verify it appears in Customize → Skills. | -| GitHub Copilot | `~/.copilot/skills/simplify-codebase/` or `~/.agents/skills/simplify-codebase/` | `.github/skills/simplify-codebase/`, `.claude/skills/simplify-codebase/`, or `.agents/skills/simplify-codebase/` | Invoke `/simplify-codebase` or confirm it is listed by the Copilot client. | -| Cline | `~/.cline/skills/simplify-codebase/` | `.cline/skills/simplify-codebase/`, `.clinerules/skills/simplify-codebase/`, or `.claude/skills/simplify-codebase/` | Enable Skills, then invoke a matching request or confirm it appears in the Skills panel. | -| Gemini CLI | `~/.gemini/skills/simplify-codebase/` | `.gemini/skills/simplify-codebase/` | Run `/skills list`, then invoke or approve activation. | -| OpenCode | `~/.agents/skills/simplify-codebase/` or `~/.config/opencode/skills/simplify-codebase/` | `.agents/skills/simplify-codebase/` or `.opencode/skills/simplify-codebase/` | Confirm the `skill` tool advertises `simplify-codebase` in a new session. | - -Use one location at the intended precedence level. Do not install a second copy with the same name unless an override is intentional. - -选择目标优先级中的一个目录安装即可。除非明确需要覆盖,不要安装同名的第二份副本。 - -## Sources / 依据 - -- [Claude Code Skills](https://code.claude.com/docs/en/skills) -- [Cursor Agent Skills](https://prod.cursor.com/docs/skills) -- [GitHub Copilot Agent Skills](https://docs.github.com/en/copilot/concepts/agents/about-agent-skills) -- [Cline Skills](https://docs.cline.bot/customization/skills) -- [Gemini CLI Agent Skills](https://geminicli.com/docs/cli/tutorials/skills-getting-started/) -- [OpenCode Agent Skills](https://opencode.ai/docs/skills) diff --git a/references/defensive-categories.md b/references/defensive-categories.md deleted file mode 100644 index f5c5935..0000000 --- a/references/defensive-categories.md +++ /dev/null @@ -1,33 +0,0 @@ -# AI Defensive-Layer Categories - -Read this reference only after the user selects the AI defensive-layer cleanup objective. A category identifies where to investigate; it never proves that removal is safe. - -## 1. Test guardrails - -Look for tests that assert directory trees, import bans, fixed file inventories, historical migration names, exact agent/component counts, implementation-private defaults, or literal source text. Prefer removing a test only when it has no distinct user-visible, API, persistence, or operational behavior to protect. - -Keep tests for business outcomes, public APIs, error handling, security, persistence, concurrency, deployment acceptance, and integration behavior even when they use mocks. - -## 2. Build, deployment, and CI guardrails - -Look for duplicate builders, abandoned conversion paths, temporary packaging adapters, dead image-export helpers, and CI jobs that only enforce a retired implementation. Trace every script from documented commands, manifests, containers, CI configuration, release instructions, and external deployment entrypoints. - -Do not remove credential filtering, image/runtime startup behavior, health checks, reproducible artifact requirements, or active release commands without an explicit operational decision. - -## 3. Static-check guardrails - -Look for source scanners, regex allowlists/denylists, layout checks, generated manifest comparisons, dependency bans, and documentation inventories created solely as AI-change tripwires. Determine whether the same requirement is already covered by a meaningful behavior check or a current CI policy. - -Keep security scanning, license/compliance checks, accessibility requirements, and gates owned by an active engineering policy. - -## 4. Compatibility and relay layers - -Look for one-line re-exports, deprecated module paths, old environment keys, former file locations, old response envelopes, UI state migration, and adapters with no current consumer. Check external callers, persisted data, deployment environment variables, release notes, and historical inputs before deletion. - -Removing a reachable public or persisted compatibility path is a product decision. Stop and request direction if its support window is unknown. - -## 5. Runtime defensive paths - -Look for fallback providers, retries, error normalization, output repair, mock-only bootstrapping, rollback routes, and recovery branches. First name the user-visible failure mode and the boundary protected. Many of these are live business reliability requirements, not AI-edit protection. - -Only remove a runtime defensive path when evidence shows it protects no real boundary and the user has authorized surrendering the behavior. Never fold security, authorization, secret handling, validation, data-integrity, or durable-data recovery into a routine cleanup batch. diff --git a/references/defensive-proof-and-delivery.md b/references/defensive-proof-and-delivery.md deleted file mode 100644 index e0f6785..0000000 --- a/references/defensive-proof-and-delivery.md +++ /dev/null @@ -1,49 +0,0 @@ -# Defensive Cleanup Proof and Delivery - -## Candidate record - -For each deletion candidate, record: - -```text -Candidate: exact test, script, layer, symbol, or path -Category: selected cleanup category -Purpose: defensive/anti-regression behavior it was intended to enforce -Consumers: runtime, support-only, dynamic/external, persisted, unknown -Cut boundary: code, tests, configuration, docs, and build entries to change -Consequence: observable behavior or compatibility no longer offered -Confidence and risk: evidence strength, blast radius, reversibility -Verification: smallest decisive check plus affected local gates -``` - -Do not treat an unreferenced file as proven dead until dynamic imports, package exports, scripts, environment keys, persisted formats, and external consumers are accounted for. - -## Change sequence - -1. Capture the relevant baseline and known failures when feasible. -2. Complete one ownership boundary at a time. -3. Search for removed symbols, paths, configuration keys, and documentation residue. -4. Run the targeted behavior check, then affected build/type/lint/test/smoke checks. -5. Inspect the diff and working-tree status. Do not stage generated runtime data or unrelated user changes. -6. If a Handoff note is authorized, use an itemized deletion ledger. Do not collapse multiple files into a category summary. - -## Handoff deletion ledger - -The Handoff note must contain one entry for every deleted file and every materially deleted symbol or section in a retained file. A table is preferred: - -```text -Deleted path or retained file + removed symbol/section: exact repository-relative path and name -Original role: what the file, symbol, or section did before cleanup -Category: selected cleanup category -Defensive obligation: the AI-change rollback/anti-regression/static obligation it enforced -Consumer evidence: runtime/support/dynamic/persisted/external search and boundary findings -Why safe to remove: why it is not a live business, API, security, persistence, lifecycle, or deployment contract -Retained behavior: active code, test, build path, or safety boundary that remains -Reintroduction trigger: the concrete future requirement that would justify restoring it -Verification: targeted check and affected local gates, including baseline failures if relevant -``` - -For a deleted file, explain its original responsibility even if it had no runtime consumer. For a partially edited file, identify the removed implementation-shape guard separately from the file's retained business/API responsibility. Include generated runtime data and unrelated working-tree changes in a separate exclusion note; they are not deletion entries. - -## Stop conditions - -Stop and report rather than delete when a candidate has unresolved dynamic/external consumers, supports stored data or a public contract, is tied to security or data safety, has a failing baseline that masks the result, or needs a product decision about backwards compatibility. diff --git a/scripts/verify_harness_contract.py b/scripts/verify_harness_contract.py deleted file mode 100644 index e5283e2..0000000 --- a/scripts/verify_harness_contract.py +++ /dev/null @@ -1,102 +0,0 @@ -#!/usr/bin/env python3 -"""Check the portable Agent Skills contract used by supported harnesses.""" - -from __future__ import annotations - -import argparse -import re -import sys -from pathlib import Path - - -EXPECTED_NAME = "simplify-codebase" -FRONTMATTER_FIELDS = {"name", "description"} -NAME_PATTERN = re.compile(r"^[a-z0-9-]+$") -MAX_DESCRIPTION_LENGTH = 1024 - - -def fail(message: str) -> None: - print(f"ERROR: {message}", file=sys.stderr) - raise SystemExit(1) - - -def parse_frontmatter(skill_path: Path) -> dict[str, str]: - lines = skill_path.read_text(encoding="utf-8").splitlines() - if not lines or lines[0] != "---": - fail("SKILL.md must begin with YAML frontmatter.") - - try: - end = lines.index("---", 1) - except ValueError: - fail("SKILL.md frontmatter is not closed.") - - fields: dict[str, str] = {} - for line in lines[1:end]: - if not line.strip() or line.lstrip().startswith("#"): - continue - if ":" not in line: - fail(f"Unsupported frontmatter syntax: {line!r}") - key, value = line.split(":", 1) - fields[key.strip()] = value.strip().strip('"') - return fields - - -def verify_relative_links(root: Path, skill_path: Path) -> None: - content = skill_path.read_text(encoding="utf-8") - for destination in re.findall(r"\]\(([^)]+)\)", content): - if "://" in destination or destination.startswith("#"): - continue - target = root / destination.split("#", 1)[0] - if not target.exists(): - fail(f"SKILL.md links to missing local resource: {destination}") - - -def main() -> None: - parser = argparse.ArgumentParser( - description="Check the portable Agent Skills package contract." - ) - parser.add_argument( - "--verify-directory-name", - action="store_true", - help="also require the current directory to match the skill name", - ) - args = parser.parse_args() - - root = Path(__file__).resolve().parents[1] - skill_path = root / "SKILL.md" - if args.verify_directory_name and root.name != EXPECTED_NAME: - fail( - f"Skill directory must be named {EXPECTED_NAME!r}; found {root.name!r}." - ) - if not skill_path.is_file(): - fail("Missing SKILL.md.") - - fields = parse_frontmatter(skill_path) - if set(fields) != FRONTMATTER_FIELDS: - fail( - "Portable SKILL.md frontmatter must contain only name and description; " - f"found {sorted(fields)}." - ) - if fields["name"] != EXPECTED_NAME: - fail( - f"Frontmatter name must be {EXPECTED_NAME!r}; found {fields['name']!r}." - ) - if not NAME_PATTERN.fullmatch(fields["name"]): - fail("Frontmatter name must use lowercase letters, digits, and hyphens only.") - if not fields["description"]: - fail("Frontmatter description must not be empty.") - if len(fields["description"]) > MAX_DESCRIPTION_LENGTH: - fail( - "Frontmatter description must be at most " - f"{MAX_DESCRIPTION_LENGTH} characters." - ) - - verify_relative_links(root, skill_path) - if not (root / "agents" / "openai.yaml").is_file(): - fail("Missing optional Codex metadata at agents/openai.yaml.") - - print("Portable harness contract: valid") - - -if __name__ == "__main__": - main() From ec9eee29d9d6e9c74df7c7257881981ee7606369 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A5=94=E8=B7=91=E7=9A=84=E9=91=AB?= <3089729486@qq.com> Date: Wed, 2 Sep 2026 22:07:39 +0800 Subject: [PATCH 3/4] fix: narrow guardrail cleanup to simplification lens --- README.en.md | 8 ++++++++ README.md | 8 ++++++++ SKILL.md | 6 +++++- references/execution-and-recovery.md | 4 ++++ references/investigation.md | 3 +++ 5 files changed, 28 insertions(+), 1 deletion(-) diff --git a/README.en.md b/README.en.md index 356014c..c98c5ce 100644 --- a/README.en.md +++ b/README.en.md @@ -23,6 +23,8 @@ Codebase entropy is rarely just an unused function. It can be duplicated state, Static analysis can surface leads, but it cannot prove a deletion safe by itself. This Skill follows runtime consumers, dynamic registration, persisted formats, public interfaces, design history, and verification boundaries before classifying a candidate as remove, merge, retain, or unresolved. +It also recognizes implementation-shape guardrails: tests, static scans, inventories, and build/CI checks that constrain directory layout, literal source text, private defaults, exact component counts, or a historical implementation identity without protecting observable behavior. AI authorship is not removal evidence; business, API, security, persistence, concurrency, and real deployment guards remain ordinary live contracts. + > **Core principle:** deleted lines are an outcome. The durable gain is deleting a fact, state, contract, or concept that no longer needs maintenance. ## How it works @@ -97,6 +99,12 @@ Use $simplify-codebase to remove one high-confidence source of accidental comple Use $simplify-codebase to verify and integrate the simplification findings from this PR. Preserve evidence, not finding counts. ``` +### Investigate implementation-shape guardrails + +```text +Use $simplify-codebase to audit tests, build/CI, and static checks that only preserve an obsolete implementation shape. Do not modify files, and retain checks that still protect business, security, or deployment behavior. +``` + ## What it returns A read-only survey returns coverage, ranked proof records, important counterexamples, unresolved questions, and the next fact needed for each uncertainty. diff --git a/README.md b/README.md index e3761e6..5ec68b2 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,8 @@ 静态检查可以提供线索,但不能单独证明一项删除是安全的。这个 Skill 会继续追踪运行时消费者、动态注册、持久化格式、公共接口、历史决策与验证边界,再决定应该删除、合并、保留,还是标记为暂时无法判断。 +它也会识别“实现形态守卫”:只约束目录结构、源文本、私有默认值、固定组件数量或历史实现身份,却不再保护可观察行为的测试、静态扫描、清单和构建/CI 检查。AI 是否生成过这些代码不是删除证据;业务、API、安全、持久化、并发和真实部署守卫仍按普通契约保留。 + > **核心原则:** 删除代码行只是结果。真正的收益是删除一个需要长期维护的事实、状态、契约或概念。 ## 工作方式 @@ -95,6 +97,12 @@ git clone https://github.com/tt-a1i/simplify-codebase.git \ 使用 $simplify-codebase 复核并整合这个 PR 中的简化建议。保留证据,不保留候选数量。 ``` +### 调查实现形态守卫 + +```text +使用 $simplify-codebase 审计测试、构建/CI 和静态检查里只保护旧实现形态的守卫。不要修改文件,并保留仍然保护业务、安全和部署行为的检查。 +``` + ## 输出是什么样的 只读审计会交付覆盖范围、排序后的证明记录、重要反例、未决问题和下一条所需证据。 diff --git a/SKILL.md b/SKILL.md index 5e3139a..0fc02ca 100644 --- a/SKILL.md +++ b/SKILL.md @@ -1,6 +1,6 @@ --- name: simplify-codebase -description: Simplification audit or authorized codebase simplification whose stated objective is to remove accidental complexity. Use for evidence-backed deletion or consolidation of dead code, duplicate state, redundant APIs or layers, ownerless abstractions, obsolete compatibility or design records, and over-engineering in any language; also use for 代码简化 or 熵回收. Do not use for general code review, onboarding, style-only refactoring, or performance tuning. +description: Simplification audit or authorized codebase simplification whose stated objective is to remove accidental complexity. Use for evidence-backed deletion or consolidation of dead code, duplicate state, redundant APIs or layers, ownerless abstractions, obsolete compatibility or design records, over-engineering, and tests or checks that preserve an obsolete implementation shape; also use for 代码简化、熵回收或 AI 防回退清理. Do not use for general code review, onboarding, style-only refactoring, or performance tuning. --- # Simplify Codebase @@ -14,6 +14,8 @@ First choose the authority mode: - **Survey** for simplification audit, investigation, or candidate-finding requests. Remain read-only and return ranked evidence. - **Change** for explicit simplify, remove, consolidate, refactor, or repository-documentation edit requests. Prove each cut, implement it within the authorized scope, and validate the surviving contract. +A request that only says to inspect or clean defensive, anti-regression, or AI-generated guardrails without clearly authorizing edits remains Survey. AI provenance is not deletion evidence and does not lower the proof burden. When a request combines an implementation-shape guardrail with another simplification, keep separate proof records and cut boundaries even when they are validated in the same run. + Then choose the coverage scope: - **Focused** when the user names a subsystem, symbol, state machine, dependency, or suspected duplication. Cover that boundary thoroughly before expanding outward. @@ -36,6 +38,8 @@ The contract map is complete when all in-scope entrypoints and authority boundar For every Broad engagement, and for Focused work involving dynamic architecture or dependency substitution, read [investigation.md](references/investigation.md). Build a coverage map before ranking findings; the first plausible deletion must not end the survey. +Also read [investigation.md](references/investigation.md) when tests, source scans, inventories, import bans, or build/CI checks may preserve an implementation shape rather than observable behavior. Apply its implementation-shape guardrail lens within the ordinary proof workflow. + For concurrency, cancellation, readiness, cleanup, defensive copies, validation, authorization, security isolation, accessibility, data-loss prevention, or cross-process data, also read [boundaries-and-lifecycle.md](references/boundaries-and-lifecycle.md). Use repository-native search, compiler and linter output, dependency metadata, and history as discovery instruments. Treat their findings as leads until runtime consumers and contracts have been examined. diff --git a/references/execution-and-recovery.md b/references/execution-and-recovery.md index 2974d99..127f03d 100644 --- a/references/execution-and-recovery.md +++ b/references/execution-and-recovery.md @@ -6,6 +6,8 @@ Purpose: retire each proved obligation completely, validate the surviving system Prefer one high-confidence ownership boundary over a mixed cleanup batch. The selected change should retire a complete obligation and have a decisive check. If investigation reveals a larger product choice or broader migration than the user authorized, present the ranked plan and obtain one scope confirmation before applying it. +When one request includes an implementation-shape guardrail and another simplification, preserve separate proof records and cut boundaries. Removing the guardrail must not become authority to remove the implementation it once described, or vice versa. + Pause application when dynamic or external consumers remain unknown, stored data lacks a migration story, baseline failures erase the intended signal, the cut crosses unrelated ownership boundaries, or rollback would be impractical. Convert the result into an evidence report with the exact missing decision or fact. ## Remove the obligation vertically @@ -61,4 +63,6 @@ Undo: files or commit range to reverse and any data/config restoration required The undo path must match the side effects. Source-only changes may be reversible from the diff; migrations, published packages, deployments, and durable data require explicit restoration steps and separate authorization. +For a removed implementation-shape guardrail, the existing `Artifacts` entry must identify each deleted file or materially deleted section and state its original check, decisive removal evidence, surviving behavior, reintroduction condition, and verification. Use the same receipt rather than creating a parallel delivery schema. + The batch is complete only when the structural cut criterion, every applicable verification ring, the complete diff audit, and the operation receipt are all satisfied or reported as unavailable with the resulting evidence limitation. diff --git a/references/investigation.md b/references/investigation.md index 68e4367..c1ec119 100644 --- a/references/investigation.md +++ b/references/investigation.md @@ -31,9 +31,12 @@ Use these lenses to generate leads: - **Local infrastructure**: custom parsing, retry, framing, matching, diffing, scheduling, or collection code duplicates a suitable platform feature or dependency. - **Support drag**: tests, examples, snapshots, generated expectations, or documentation are the only reason an otherwise unused surface remains. - **Feature fossil**: implementation was abandoned or removed while schema, configuration, tests, compatibility logic, or design records still preserve its outline. +- **Implementation-shape guardrail**: a test, source scan, inventory, import ban, or build/CI check enforces file layout, literal source text, private defaults, exact component counts, or a historical implementation identity without owning observable behavior. Do not equate visual similarity with duplication. Independent implementations may test an interface, isolate failure domains, protect different owners, or support distinct compatibility contracts. +Do not use AI authorship or a label such as "defensive" as evidence that a guardrail is removable. Treat it as a candidate only when the consumer map shows that its remaining obligation is an obsolete implementation shape. Keep guards that protect business outcomes, public APIs, trust boundaries, security, persistence, concurrency, deployment acceptance, integration behavior, or an active engineering policy. + ## Climb the evidence ladder Classify each lead by the strongest evidence reached: From 6e4fdb9a24a4f0880d67c4c983633b19d10e2ebe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A5=94=E8=B7=91=E7=9A=84=E9=91=AB?= <3089729486@qq.com> Date: Wed, 2 Sep 2026 22:22:15 +0800 Subject: [PATCH 4/4] test: validate implementation-shape guardrail behavior --- SKILL.md | 2 +- docs/validation.md | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/SKILL.md b/SKILL.md index 0fc02ca..e1b03d4 100644 --- a/SKILL.md +++ b/SKILL.md @@ -14,7 +14,7 @@ First choose the authority mode: - **Survey** for simplification audit, investigation, or candidate-finding requests. Remain read-only and return ranked evidence. - **Change** for explicit simplify, remove, consolidate, refactor, or repository-documentation edit requests. Prove each cut, implement it within the authorized scope, and validate the surviving contract. -A request that only says to inspect or clean defensive, anti-regression, or AI-generated guardrails without clearly authorizing edits remains Survey. AI provenance is not deletion evidence and does not lower the proof burden. When a request combines an implementation-shape guardrail with another simplification, keep separate proof records and cut boundaries even when they are validated in the same run. +A request that only mentions defensive, anti-regression, or AI-generated guardrails without an explicit edit verb or other change authority remains Survey. AI provenance is not deletion evidence and does not lower the proof burden. When a request combines an implementation-shape guardrail with another simplification, keep separate proof records and cut boundaries even when they are validated in the same run. Then choose the coverage scope: diff --git a/docs/validation.md b/docs/validation.md index 79aba05..aedc111 100644 --- a/docs/validation.md +++ b/docs/validation.md @@ -30,6 +30,14 @@ This document records the behavioral validation completed before the initial ope - Expected behavior: prove the cut below file granularity. - Result: the focused audit found 14 candidate-exclusive CSS classes, identified removable members inside mixed selectors, retained the shared stylesheet and surviving component, and found two stale documentation references. +### Implementation-shape guardrail + +- Fixture: a small Node.js package with pricing and authorization behavior, an unexported dead helper, a deployment check, and a test plus script that asserted an exact source filename and function spelling. +- Ambiguous request: an independent Skill run was told only that defensive or AI-generated guardrails might exist. It selected Survey mode, made no edits, ranked the implementation-shape guard separately from the dead helper, and retained the quantity validation, authorization boundary, business tests, and deployment check. +- Focused change: an explicitly authorized run removed only `tests/layout.guard.test.js`, `scripts/check-layout.js`, and the `check:layout` package entry. The baseline passed 4 tests plus the layout and deployment checks; afterward all 3 surviving behavior tests and the deployment check passed. The operation receipt named every deleted artifact, its original check, the removal evidence, surviving behavior, reintroduction condition, verification, and undo path. +- Mixed objectives: an explicitly authorized run handled the shape guard and dead helper as separate proof records and cut boundaries. It removed 22 lines across 4 files with no replacement machinery, found no residue, passed syntax and diff checks, passed all 3 surviving behavior tests, and preserved the deployment check. The final receipt kept both cuts separate. +- Environment note: the Windows fixture runner used `npm.cmd` because the bare `npm` shim was unavailable; this did not change the fixture or expected behavior. + ## Mechanical checks / 机械检查 - Skill structure and frontmatter validation;