8000 GitHub - yk0211/cpp-safety: Modern C++20/23 Safety Engineering Skill · GitHub
[go: up one dir, main page]

Skip to content

About

Modern C++20/23 Safety Engineering Skill

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

cpp-safety — Modern C++20/23 Safety Engineering Skill

English (default) · 简体中文文档

A portable agent skill that enforces modern C++20/C++23 safety practices when writing, reviewing, refactoring, debugging or testing C++ code. It uses the standard <name>/SKILL.md bundle layout and runs on WorkBuddy, DeepSeek Harness, Claude Code and Codex/Cursor-style agents (see §4.1). It focuses on eliminating undefined behavior, use-after-free, dangling pointers/references, iterator invalidation, data races, resource leaks, exception-safety violations, and asynchronous lifetime bugs. It also covers contract design, error-handling conventions, sanitizer tooling, cross-platform portability, worked case studies and safety test templates.

Maintenance procedures (authority model, de-duplication, guideline drift, release checklist) live in MAINTAINING.md.


1. What It Does

The skill instructs the assistant to:

  • Inspect ownership, object lifetime, shared state, container mutation, and async operations before changing code.
  • Prefer value semantics, RAII, and explicit ownership.
  • Reject or require justification for unsafe patterns (naked new/delete, returning references to locals, capturing short-lived references in async callbacks, holding locks across co_await, etc.).
  • Distinguish contract violations (programming errors → assert/terminate) from recoverable failures (→ std::expected / exceptions).
  • Run and report real verification: compiler warnings, Clang-Tidy, sanitizers (ASan/UBSan/TSan), and tests — never claim a check passed without running it.
  • Require a regression test that fails on the pre-fix code for every safety fix.
  • Classify findings by severity (CRITICAL / HIGH / MEDIUM / LOW) and follow the auto-fix policy (SKILL.md §15.1).

2. Supported Standards

  • C++20 and C++23.
  • Primary toolchain: Clang (GCC-compatible subset also covered); MSVC-specific guidance in references/portability.md.
  • Designed for high-concurrency services (game servers, networking, Asio, coroutines).

Note: standard contract attributes ([[pre:]], [[post:]], contract_assert) are C++26, not C++20/23. This skill uses GSL Expects/Ensures, project CHECK macros, and type-encoded constraints instead. See references/contracts.md.

Scope guards (std::scope_exit) are not reliably available in C++23 standard libraries; see references/modern-features.md §6 for a portable fallback.

3. Included References

Technical references live in references/; process documents live at the repository root.

File Coverage
SKILL.md Behaviour contract: AI workflow, severity, auto-fix policy, prohibited patterns, loading rules.
references/pointer-lifetime.md Ownership model, dangling pointers/references, string_view/span, lambda capture, stable identity.
references/iterator-invalidation.md Container/iterator/reference invalidation guarantees.
references/undefined-behavior.md UB, integer arithmetic, alignment, strict aliasing.
references/exception-safety.md RAII, exception guarantees, resource cleanup.
references/async-concurrency.md Callbacks, timers, concurrency, lifetime across threads.
references/asio-coroutine-safety.md Asio sockets/timers/co_spawn/awaitable, cancellation, shutdown.
references/static-analysis.md Warnings, Clang-Tidy, Cppcheck, sanitizer strategy, CI.
references/sanitizers.md Deep ASan/UBSan/LSan guide: flags, runtime options, suppressions, server pitfalls.
references/coding-standards.md Google Style safety subset + Core Guidelines R/I/ES/CP/F + project-style override & deviation policy + drift checklist.
references/contracts.md Preconditions, postconditions, invariants, assertion strategy, C++26 caveat.
references/error-handling.md std::expected, exceptions, status codes, error paths, async error propagation.
references/portability.md MSVC vs Clang/GCC, sanitizer availability, LLP64/LP64, Windows headers, dash/sh.
references/modern-features.md C++20/23 feature traps (ranges/views, modules, atomic_ref, start_lifetime_as) + toolchain matrix.
references/case-studies.md Six anonymized before/after fixes (allocator, timer, delay queue, parser, async session, service chain).
references/testing-safety.md Death tests, libFuzzer harness, regression patterns, sanitizer smoke test, CI tiers.
references/cheatsheet.md One-page Bad/Good lookup, severity, verification commands, reference routing.
MAINTAINING.md Authority map, de-duplication SOP, guideline drift tracking, new-reference SOP, release checklist.
scripts/validate_harness.py Static DeepSeek Harness / SKILL.md compatibility checker; see §4.2.

3.1 Source Materials (recommended for long-term inclusion)

  1. Google C++ Style Guide — engineering and style conventions. https://google.github.io/styleguide/cppguide.html
  2. C++ Core Guidelines — focus on R (Resource management), I (Interfaces), ES (Expressions and statements), CP (Concurrency), F (Functions). https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines
  3. Clang AddressSanitizer — memory error detection. https://clang.llvm.org/docs/AddressSanitizer.html
  4. Clang UndefinedBehaviorSanitizer — undefined behavior detection. https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html
  5. C++ Core Guidelines GitHub — canonical, continuously updated source. https://github.com/isocpp/CppCoreGuidelines

3.2 Documentation Languages

English is the default. The Chinese translation is kept in a separate file so neither document is diluted by inline duplication:

  • README.md — English (this file)
  • README.zh-CN.md — 简体中文
  • MAINTAINING.md — English process document (referenced from both)

3.3 Document Authority

Each rule has exactly one authoritative source (SKILL.md §0 and MAINTAINING.md §2):

  • SKILL.md is authoritative for behaviour (what the AI must do).
  • references/*.md are authoritative for technical rules.
  • SKILL.md §2–§12 are non-authoritative summaries; redundant Bad/Good blocks were removed in favour of pointers to the references.
  • READMEs and cheatsheet.md contain navigation only.

When updating a rule, change exactly one authoritative file and add links elsewhere.

4. How to Use

  1. Install/enable the cpp-safety skill in WorkBuddy.
  2. When you ask the assistant to write or review C++ code, it follows the Required AI Workflow (Inspect → Design → Implement → Review → Verify → Report) defined in SKILL.md, loading the relevant references/*.md files automatically.
  3. Start from references/cheatsheet.md for a quick defect lookup and reference routing, or references/case-studies.md to recognize a known pattern.
  4. For regression tests, use the templates in references/testing-safety.md.
  5. Review the assistant's severity-tagged report and the verification commands it actually executed.
  6. When extending the skill itself, read MAINTAINING.md first.

4.1 Using with DeepSeek Harness (DSH)

Yes — supported as-is, with no conversion. DSH reads the same directory-bundle SKILL.md format as Claude Code / Codex-style agents. Copy the whole directory so that references/ stays a sibling of SKILL.md:

Scope Destination
Project (rank 100, highest priority) <projectRoot>/.dsh/skills/cpp-safety/
Project, .agents convention (rank 200) <projectRoot>/.agents/skills/cpp-safety/
User / all projects (rank 400) ~/.dsh/skills/cpp-safety/
# POSIX sh / dash / Git Bash — no bash-only syntax
SKILL_SRC=/path/to/cpp-safety
mkdir -p .dsh/skills/cpp-safety
cp "$SKILL_SRC/SKILL.md" "$SKILL_SRC/README.md" "$SKILL_SRC/README.zh-CN.md" \
   "$SKILL_SRC/MAINTAINING.md" .dsh/skills/cpp-safety/
cp -R "$SKILL_SRC/references" .dsh/skills/cpp-safety/
# Windows PowerShell
New-Item -ItemType Directory -Force .dsh\skills | Out-Null
Copy-Item -Recurse -Force C:\path\to\cpp-safety .dsh\skills\cpp-safety

Then run npx @deepseek-ai/dsh web and confirm cpp-safety appears in the skill catalog.

DSH behaviour Implication for this skill
Skill name comes from the directory name; kebab-case ^[a-z0-9]+(?:-[a-z0-9]+)*$ Keep the folder named cpp-safety, matching frontmatter name.
Recursive **/SKILL.md discovery is not supported Put the folder directly under .dsh/skills/, not in a nested subfolder.
Only disable-model-invocation / user-invocable are recognised; omitting both allows model and user invocation The current name + description frontmatter works unchanged; the model can auto-invoke.
Session catalog injects only name + description, bounded by catalogDescriptionMaxLength (default 500) Description is kept short with trigger words first; check its length via MAINTAINING.md §7.
Body loads on skill({name}); <skill_resources> resolves explicitly referenced relative files and does not enumerate the skill directory SKILL.md §0.1 declares the base path, and every references/*.md is explicitly named in the loading rules.
Chat app chat.deepseek.com has no skills support Use DeepSeek Harness, not the web chat box.
This skill ships no scripts, hooks or network calls No sandbox or permission concerns.

Verification:

  1. npx @deepseek-ai/dsh web → open http://127.0.0.1:3080.
  2. Ask: "Review this C++20 function for dangling references" (Chinese trigger phrases are also embedded in the frontmatter description).
  3. Confirm the model calls skill({name: "cpp-safety"}) and actually reads references/cheatsheet.md.
  4. If it answers without reading any reference, resource-path resolution failed: give it the absolute skill-directory path once and retry. SKILL.md §0.1 already instructs this fallback.

4.2 Automated Compatibility Check

scripts/validate_harness.py (Python 3.7+, zero dependencies, cross-platform) runs the static checks above without starting Harness or touching the network:

Group What it checks
FM Frontmatter parses; kebab-case name; folded description length vs the 500 bound and the 450 headroom; trigger clause survives truncation; model auto-invocation is enabled.
LAY SKILL.md at root; references/ as a sibling; no nested SKILL.md; directory name matches name; pure-Markdown payload.
PATH SKILL.md §0.1 base-path declaration; loading-rule references exist; every relative link in every document resolves; no machine-specific absolute paths.
DOC EN/ZH README section alignment; authority map and loading rules cover all 16 references.
python scripts/validate_harness.py                                  # report + fallback prompt
python scripts/validate_harness.py --json                          # CI-friendly output
python scripts/validate_harness.py --prompt-only                   # fallback prompt only
python scripts/validate_harness.py --install .dsh/skills/cpp-safety  # copy + verify

--install copies only SKILL.md, both READMEs, MAINTAINING.md and references/. scripts/ and .workbuddy/ never enter the Harness skill directory, so the installed bundle stays pure Markdown. It never deletes existing files; add --force to overwrite into a non-empty target.

The generated fallback prompt embeds the absolute path of the installed skill root — exactly what §4.1 step 4 needs when <skill_resources> fails to resolve references/*.md.

Exit codes: 0 = compatible (WARN allowed), 1 = at least one FAIL, 2 = bad arguments.

5. Suggested Verification Workflow

  • Debug/test builds: -fsanitize=address,undefined + -fno-omit-frame-pointer -g.
  • Separate TSan build for data-race coverage; never combine TSan and ASan.
  • CI matrix: Linux Clang (ASan/UBSan/TSan) + GCC + Windows MSVC (/W4 /permissive- /analyze).
  • CI stages: warnings → Clang-Tidy → unit tests → contract death tests → ASan/UBSan → fuzz smoke test → TSan (nightly) → long fuzzing.
  • Every safety fix needs a regression test that fails before the fix (references/testing-safety.md §1).
  • See static-analysis.md §6 (CMake), sanitizers.md §11, portability.md §3/§8, and testing-safety.md §7 (CI tiers).

6. Auto-Fix Policy

SKILL.md §15.1 defines what the assistant may change without asking:

Severity Permitted action
CRITICAL Report with evidence + proposed minimal patch; ask before changing behaviour.
HIGH Propose minimal fix with lifetime justification; apply only if the contract is fully understood.
MEDIUM May fix directly if local and low-risk; document reasoning.
LOW May fix directly.

Prefer the simplest correct change; if a fix does not work, revert to the simpler approach instead of layering workarounds.

7. Optimization Roadmap

All backlog items are complete. This section is now an optimization log.

Completed — initial build

  • ✅ coding-standards.md and sanitizers.md (Google Style + Core Guidelines R/I/ES/CP/F; ASan/UBSan/LSan deep guide).
  • ✅ contracts.md — and corrected the earlier claim that [[pre]]/[[post]] are C++20 (they are C++26; C++20/23 use GSL Expects/Ensures + CHECK).
  • ✅ error-handling.md — std::expected / exception conventions and async error paths.
  • ✅ portability.md — MSVC vs Clang/GCC, sanitizer availability, LLP64/LP64, dash/sh.
  • ✅ cheatsheet.md — one-page quick reference.
  • ✅ Auto-fix policy tied to review severity (SKILL.md §15.1).
  • ✅ Split EN/ZH README into independent files.

Completed — final batch

  • ✅ Project-style override table + "when to deviate" policy (coding-standards.md §3): precedence hierarchy, non-overridable red lines, override table, deviation decision steps, and a Doxygen deviation-comment template.
  • ✅ Guideline drift tracking: MAINTAINING.md §4 (upstream sources, triggers, refresh procedure, Version Log, dash-safe helper) plus coding-standards.md §4.1 checklist.
  • ✅ Anonymized before/after case studies: references/case-studies.md with six generalized defects and regression tests.
  • ✅ Test templates: references/testing-safety.md — death tests, libFuzzer harness, regression patterns by defect class, sanitizer smoke test, shutdown checklist, CI tiers; wired into static-analysis.md §8 and SKILL.md §14 Step 5.
  • ✅ De-duplication / single source of truth: SKILL.md §0 authority map + MAINTAINING.md §2/§3 SOP; removed the three largest redundant Bad/Good blocks from the SKILL.md summary.
  • ✅ C++20/23 feature deep-dive: references/modern-features.md — ranges/views dangling, modules, atomic_ref, start_lifetime_as, scope-guard availability caveat, toolchain support matrix and feature-test-macro checklist.
  • ✅ Registered every new document in the loading rules, both README tables and the cheatsheet.md routing table.
  • ✅ Harness portability (SKILL.md §0.1 + §4.1 of both READMEs): compacted the frontmatter description below DSH's 500-character catalog bound, added Chinese/English trigger words, and declared the references/ path base for hosts that do not inject the skill root.
  • ✅ Automated Harness check (scripts/validate_harness.py, §4.2): 21 static checks, whitelist-based --install, JSON output, and absolute-path fallback-prompt generation.

Ongoing Maintenance (periodic, not backlog)

Activity Cadence Procedure
Guideline drift refresh Quarterly / toolchain upgrade MAINTAINING.md §4
Toolchain support matrix update Compiler/library upgrade modern-features.md §1, portability.md §2
Case study library growth As new patterns appear MAINTAINING.md §6
De-duplication review Every release MAINTAINING.md §3
Sanitizer flag verification CI config change testing-safety.md §5

8. External References

About

Modern C++20/23 Safety Engineering Skill

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

0