{"id":"dde34b0f-6fd3-4a2a-aac9-8e25d377cf69","entityType":"agent","slug":"clawhub-staok-spec-kit-coding","name":"Spec-kit Coding","canonicalUrl":"https://www.xpersona.co/agent/clawhub-staok-spec-kit-coding","canonicalPath":"/agent/clawhub-staok-spec-kit-coding","generatedAt":"2026-10-11T16:00:08.981Z","source":"CLAWHUB","claimStatus":"UNCLAIMED","verificationTier":"NONE","summary":{"evidence":{"source":"editorial-content","verified":true,"confidence":"high","updatedAt":"2026-10-11T13:06:47.274Z","emptyReason":null},"description":"Orchestrator for GitHub Spec-Kit SDD workflow in OpenClaw. Use when starting a new project with spec-driven development, setting up spec-kit toolchain, or ru... Skill: Spec-kit Coding Owner: staok Summary: Orchestrator for GitHub Spec-Kit SDD workflow in OpenClaw. Use when starting a new project with spec-driven development, setting up spec-kit toolchain, or ru... Tags: latest:1.0.5 Version history: v1.0.5 | 2026-06-16T07:40:35.431Z | user spec-kit-coding v1.0.5 - Removed unnecessary files: TODO.txt and skill-card.md - Updated SKILL.md with a new instruction: now asks users","descriptionLabel":"Technical summary","evidenceSummary":"Capability contract not published. No trust telemetry is available yet. 1.1K downloads reported by the source. Last updated 10/11/2026.","installCommand":"clawhub skill install s17b6q0zz08bewcdk63scg1x6h85g46x:spec-kit-coding","sourceUrl":"https://clawhub.ai/staok/spec-kit-coding","homepage":"https://clawhub.ai/staok/skills/spec-kit-coding","primaryLinks":[{"label":"View on ClawHub","url":"https://clawhub.ai/staok/spec-kit-coding","kind":"source"},{"label":"Homepage","url":"https://clawhub.ai/staok/skills/spec-kit-coding","kind":"homepage"}],"safetyScore":84,"overallRank":62,"popularityScore":61,"trustScore":null,"claimedByName":null,"isOwner":false,"seoDescription":"Orchestrator for GitHub Spec-Kit SDD workflow in OpenClaw. Use when starting a new project with spec-driven development, setting up spec-kit toolchain, or ru..."},"coverage":{"evidence":{"source":"public-profile","verified":false,"confidence":"medium","updatedAt":"2026-10-11T13:06:47.274Z","emptyReason":null},"protocols":[{"protocol":"OPENCLEW","label":"OpenClaw","status":"self-declared","notes":"Declared in the public agent profile."}],"capabilities":[],"verifiedCount":0,"selfDeclaredCount":1,"capabilityMatrix":{"rows":[{"key":"OPENCLEW","type":"protocol","support":"unknown","confidenceSource":"profile","notes":"Listed on profile"}],"flattenedTokens":"protocol:OPENCLEW|unknown|profile"}},"adoption":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-11T13:06:47.274Z","emptyReason":null},"stars":null,"forks":null,"downloads":1060,"packageName":null,"latestVersion":"1.0.5","tractionLabel":"1.1K downloads"},"release":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-11T13:06:47.213Z","emptyReason":null},"lastUpdatedAt":"2026-10-11T13:06:47.274Z","lastCrawledAt":"2026-10-11T13:06:47.213Z","lastIndexedAt":null,"nextCrawlAt":"2026-10-12T13:06:47.213Z","lastVerifiedAt":null,"highlights":[{"version":"1.0.5","createdAt":"2026-06-16T07:40:35.431Z","changelog":"spec-kit-coding v1.0.5 - Removed unnecessary files: TODO.txt and skill-card.md - Updated SKILL.md with a new instruction: now asks users at project creation whether to auto-run the workflow or confirm at each step - No functional workflow changes; documentation and cleanup only","fileCount":24,"zipByteSize":65238},{"version":"1.0.4","createdAt":"2026-06-01T04:00:02.988Z","changelog":"# Changelog for spec-kit-coding v1.0.4 - Removed the file: `skill-card.md`. - Updated security constraints to emphasize that agents should be disabled in critical-path, legacy, and security-sensitive code; only use in low-risk scenarios. - Minor clarifications to workflow: Grill Alignment now runs once per project, and domain docs (CONTEXT.md, ADRs) are reused for new features. - Fixed typo in Feature Management section (\"modify an existing feature\"). - No functional changes to implementation steps or primary workflow.","fileCount":25,"zipByteSize":65677},{"version":"1.0.3","createdAt":"2026-05-30T09:23:54.687Z","changelog":"spec-kit-coding v1.0.3 - Added TODO.txt file as a placeholder or for pending items. - No changes to code or behavior; only documentation and hard constraints content updated.","fileCount":25,"zipByteSize":65002},{"version":"1.0.2","createdAt":"2026-05-29T12:49:28.998Z","changelog":"spec-kit-coding 1.0.2 - Removed TODO.txt and skill-card.md. - SKILL.md significantly condensed and streamlined: repetitive quick reference, workflow details, and internal section links replaced by an organized, simplified set of hard constraints and workflow steps. - Documentation now places more emphasis on core constraints, essential workflow, and clear gating for user interaction. - No changes to core functional scope or underlying implementation.","fileCount":24,"zipByteSize":63695},{"version":"1.0.1","createdAt":"2026-05-24T07:02:49.864Z","changelog":"spec-kit-coding 1.0.1 - Initial release with setup instructions, usage workflow, and safety/communication rules. - Adds documentation covering toolchain checks, project initialization, git management, and documentation practices. - Provides quick reference guide, scope definitions, and hard constraints for safe and structured spec-driven development workflows. - No functional code changes; this version introduces skill documentation to guide usage and best practices.","fileCount":25,"zipByteSize":71812},{"version":"1.0.0","createdAt":"2026-05-24T06:40:39.351Z","changelog":"Spec-Kit Coding Skill 1.0.0 — Initial Release - First public version providing orchestration for GitHub Spec-Kit SDD workflows in OpenClaw. - Handles setup: toolchain checks, skill installation, and project initialization. - Enforces hard constraints on feature-splitting, documentation, git policy, and secure tool usage. - Guides users through project bootstrapping, including git management and project docs (README.md, DEVLOG.md). - Scoped to forward coding and quality gates; does not cover requirements discovery or deployment.","fileCount":23,"zipByteSize":70075}]},"execution":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No published capability contract is available yet."},"installCommand":"clawhub skill install s17b6q0zz08bewcdk63scg1x6h85g46x:spec-kit-coding","setupComplexity":"low","setupSteps":["Setup complexity is classified as HIGH. You must provision dedicated cloud infrastructure or an isolated VM. Do not run this directly on your local workstation.","Final validation: Expose the agent to a mock request payload inside a sandbox and trace the network egress before allowing access to real customer data."],"contract":{"contractStatus":"missing","authModes":[],"requires":[],"forbidden":[],"supportsMcp":false,"supportsA2a":false,"supportsStreaming":false,"inputSchemaRef":null,"outputSchemaRef":null,"dataRegion":null,"contractUpdatedAt":null,"sourceUpdatedAt":null,"freshnessSeconds":null},"invocationGuide":{"preferredApi":{"snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-staok-spec-kit-coding/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-staok-spec-kit-coding/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-staok-spec-kit-coding/trust"},"curlExamples":["curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-staok-spec-kit-coding/snapshot\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-staok-spec-kit-coding/contract\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-staok-spec-kit-coding/trust\""],"jsonRequestTemplate":{"query":"summarize this repo","constraints":{"maxLatencyMs":2000,"protocolPreference":["OPENCLEW"]}},"jsonResponseTemplate":{"ok":true,"result":{"summary":"...","confidence":0.9},"meta":{"source":"CLAWHUB","generatedAt":"2026-10-11T16:00:08.977Z"}},"retryPolicy":{"maxAttempts":3,"backoffMs":[500,1500,3500],"retryableConditions":["HTTP_429","HTTP_503","NETWORK_TIMEOUT"]}},"endpoints":{"dossierUrl":"https://www.xpersona.co/api/v1/agents/clawhub-staok-spec-kit-coding/dossier","snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-staok-spec-kit-coding/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-staok-spec-kit-coding/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-staok-spec-kit-coding/trust"}},"reliability":{"evidence":{"source":"runtime-metrics","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No trust, reliability, or runtime telemetry is available."},"trust":{"status":"unavailable","handshakeStatus":"UNKNOWN","verificationFreshnessHours":null,"reputationScore":null,"p95LatencyMs":null,"successRate30d":null,"fallbackRate":null,"attempts30d":null,"trustUpdatedAt":null,"trustConfidence":"unknown","sourceUpdatedAt":null,"freshnessSeconds":null},"decisionGuardrails":{"doNotUseIf":["Contract metadata is missing or unavailable for deterministic execution."],"safeUseWhen":[],"riskFlags":["missing_or_unavailable_contract","trust_data_unavailable","schema_references_missing"],"operationalConfidence":"low"},"executionMetrics":{"observedLatencyMsP50":null,"observedLatencyMsP95":null,"estimatedCostUsd":null,"uptime30d":null,"rateLimitRpm":null,"rateLimitBurst":null,"lastVerifiedAt":null,"verificationSource":null},"runtimeMetrics":{"successRate":null,"avgLatencyMs":null,"avgCostUsd":null,"hallucinationRate":null,"retryRate":null,"disputeRate":null,"p50Latency":null,"p95Latency":null,"lastUpdated":null}},"benchmarks":{"evidence":{"source":"no-benchmark-data","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No benchmark suites or observed failure patterns are available."},"suites":[],"failurePatterns":[]},"artifacts":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"high","updatedAt":"2026-10-11T13:06:47.274Z","emptyReason":null},"readme":"Skill: Spec-kit Coding\n\nOwner: staok\n\nSummary: Orchestrator for GitHub Spec-Kit SDD workflow in OpenClaw. Use when starting a new project with spec-driven development, setting up spec-kit toolchain, or ru...\n\nTags: latest:1.0.5\n\nVersion history:\n\nv1.0.5 | 2026-06-16T07:40:35.431Z | user\n\nspec-kit-coding v1.0.5\n\n- Removed unnecessary files: TODO.txt and skill-card.md\n- Updated SKILL.md with a new instruction: now asks users at project creation whether to auto-run the workflow or confirm at each step\n- No functional workflow changes; documentation and cleanup only\n\nv1.0.4 | 2026-06-01T04:00:02.988Z | user\n\n# Changelog for spec-kit-coding v1.0.4\n\n- Removed the file: `skill-card.md`.\n- Updated security constraints to emphasize that agents should be disabled in critical-path, legacy, and security-sensitive code; only use in low-risk scenarios.\n- Minor clarifications to workflow: Grill Alignment now runs once per project, and domain docs (CONTEXT.md, ADRs) are reused for new features.\n- Fixed typo in Feature Management section (\"modify an existing feature\").\n- No functional changes to implementation steps or primary workflow.\n\nv1.0.3 | 2026-05-30T09:23:54.687Z | user\n\nspec-kit-coding v1.0.3\n\n- Added TODO.txt file as a placeholder or for pending items.\n- No changes to code or behavior; only documentation and hard constraints content updated.\n\nv1.0.2 | 2026-05-29T12:49:28.998Z | user\n\nspec-kit-coding 1.0.2\n\n- Removed TODO.txt and skill-card.md.\n- SKILL.md significantly condensed and streamlined: repetitive quick reference, workflow details, and internal section links replaced by an organized, simplified set of hard constraints and workflow steps.\n- Documentation now places more emphasis on core constraints, essential workflow, and clear gating for user interaction.\n- No changes to core functional scope or underlying implementation.\n\nv1.0.1 | 2026-05-24T07:02:49.864Z | user\n\nspec-kit-coding 1.0.1\n\n- Initial release with setup instructions, usage workflow, and safety/communication rules.\n- Adds documentation covering toolchain checks, project initialization, git management, and documentation practices.\n- Provides quick reference guide, scope definitions, and hard constraints for safe and structured spec-driven development workflows.\n- No functional code changes; this version introduces skill documentation to guide usage and best practices.\n\nv1.0.0 | 2026-05-24T06:40:39.351Z | user\n\nSpec-Kit Coding Skill 1.0.0 — Initial Release\n\n- First public version providing orchestration for GitHub Spec-Kit SDD workflows in OpenClaw.\n- Handles setup: toolchain checks, skill installation, and project initialization.\n- Enforces hard constraints on feature-splitting, documentation, git policy, and secure tool usage.\n- Guides users through project bootstrapping, including git management and project docs (README.md, DEVLOG.md).\n- Scoped to forward coding and quality gates; does not cover requirements discovery or deployment.\n\nArchive index:\n\nArchive v1.0.5: 24 files, 65238 bytes\n\nFiles: CodingGuidance/CppCodingStyle.md (28612b), CodingGuidance/CppEngineeringFrameworkReference/AppContext.cpp (11115b), CodingGuidance/CppEngineeringFrameworkReference/AppContext.h (2950b), CodingGuidance/CppEngineeringFrameworkReference/CppModuleInitCaseExample.cpp (8754b), CodingGuidance/CppEngineeringFrameworkReference/CppModuleRunCaseExample.cpp (9280b), CodingGuidance/DesignPattern/Builder/ProductBuilder.h (9979b), CodingGuidance/DesignPattern/DesignPattern.md (10012b), CodingGuidance/DesignPattern/Pimpl/MyInterface.h (1369b), CodingGuidance/DesignPattern/Pimpl/MyInterfaceImpl.cpp (844b), CodingGuidance/DesignPattern/PImpl2/inc_private/GenericModuleImpl.h (1715b), CodingGuidance/DesignPattern/PImpl2/include/GenericModule.h (532b), CodingGuidance/DesignPattern/PImpl2/src/GenericModule.cpp (161b), CodingGuidance/DesignPattern/PImpl2/src/GenericModuleImpl.cpp (3060b), CodingGuidance/DesignPattern/RAII/RAII.cpp (6617b), CodingGuidance/DesignPattern/RAII/RAII.h (3568b), CodingGuidance/DesignPattern/Singleton/ClassFactory_Example.cpp (3797b), CodingGuidance/DesignPattern/Singleton/ClassFactory.hpp (7029b), CodingGuidance/DesignPattern/Singleton/Singleton.cpp (420b), CodingGuidance/DesignPattern/Singleton/Singleton.h (1307b), CodingGuidance/TopLevelCodingGuidance.md (5334b), setup.sh (26266b), skill-card.md (2531b), SKILL.md (32363b), _meta.json (134b)\n\nFile v1.0.5:SKILL.md\n\n---\nname: spec-kit-coding\ndescription: \"Orchestrator for GitHub Spec-Kit SDD workflow in OpenClaw. Use when starting a new project with spec-driven development, setting up spec-kit toolchain, or running through the full SDD pipeline.\"\n---\n# Spec-Kit Coding -- OpenClaw Orchestrator\n\n> **Repo:** [Staok/spec-kit-coding-skill](https://github.com/Staok/spec-kit-coding-skill)\n\nOrchestrates the complete Spec-Driven Development workflow via [github/spec-kit](https://github.com/github/spec-kit).\n\nCovers: Engineering Implementation. Does not cover\nrequirements discovery, operations/deployment, or cross-domain (SRE, security, etc.).\n\n---\n\n## HARD CONSTRAINTS\n\nREAD FIRST, APPLY ALWAYS.\n\nThese constraints are non-negotiable. Do NOT require the user to repeat them.\n\n### Security\n\n- Never transmit sensitive information to the network.\n- Before any external action (API calls, sending data outside local machine),\n  explain and ask for approval.\n- Do not install third-party libraries or modify system config without\n  asking first. If a new dependency is needed, explain why and get approval.\n- Prefer reusing existing, proven, popular third-party solutions. Avoid\n  reinventing the wheel. Keep tool usage simple and lean. Minimize dependency footprint.\n- **WARNING:** As a principle, agents should be disabled in critical-path code,\n  legacy system maintenance, and security-sensitive modules. Permitted only in\n  low-risk scenarios such as prototyping, search, and documentation.\n\n### Feature Management / Quick Reference\n\n- Starting a project, follow section: WORKFLOW, from STEP 1 to STEP 7.\n- On first project creation, ask the user: auto-run the WORKFLOW (pause only for required confirmations), or confirm at each step.\n- Add a new feature or modify an existing feature:\n  - \"add\" / \"new\" / behavior no spec covers -> new feature -> section: STEP 5: Spec-Kit Phases / New Feature.\n  - \"change\" / \"modify\" / changing existing behavior -> modify existing -> section: Feature Modification Entry Point.\n- Each `/speckit-specify` invocation creates exactly ONE feature. If the user\n  describes a messy, multi-concern requirement, split it first:\n  - List each proposed feature with a short name and one-line summary.\n  - Note dependencies between features.\n  - Ask user to confirm the split before proceeding.\n- When uncertain whether the user wants a new feature or a modification to an\n  existing one, ASK. Do not guess. Present your organized analysis. Show several or both options concisely.\n- For projects that have already been delivered or already exist, if a bug is reported, refer to section: Bug Fix Entry Point.\n\n### Communication\n\n- Collect all unclear points first, then ask once. Avoid back-and-forth.\n- Be efficient and concise. Output only necessary information.\n- Remind the user how to think about the problem better; help improve prompt\n  quality over time.\n\n### Documentation-First\n\n- For spec/plan/tasks .etc phase docs (spec.md, plan.md, tasks.md): these are created via the speckit-* phases prior to implementation.\n- For DEVLOG.md: update per implementation batch, and after every phase\n  completion. DEVLOG must always reflect the latest state.\n- For README.md Architecture: seed during plan phase. Update as a final step\n  after all implementation completes (Step 5 and Step 6.3).\n- Never reverse the order: docs first, code second.\n\n### Git Management\n\n- During project init (Step 1), ASK whether to enable git. Record the answer.\n- If enabled: `git init`, `.gitignore`, initial commit. Then commit after\n  each phase completion and each implementation batch.\n- If disabled: do not create or manage a git repository.\n- The user may enable git at any later point. Once enabled, keep it on.\n\n### Context Isolation\n\n- \"Implement\" (The whole Step 6 and Step 6.X) MUST run in fresh isolated sub-agent sessions.\n  Never run implement in a session that has accumulated multiple prior phases.\n- If tasks.md has more than ~15 items, split implementation into batches.\n  Each batch = fresh sub-agent session.\n- Better to over-split than to produce garbage from context saturation.\n\n### Session Interrupt\n\n- If a session is interrupted mid-phase, do NOT assume which phase to restart\n  from. Ask the user: \"Restart from [interrupted-phase] or from\n  [previous-completed-phase]?\" If user is unsure, default to re-running the\n  interrupted phase from the start.\n\n---\n\n## WORKFLOW\n\n### STEP 0: Prerequisites (one-time per machine)\n\nRun: `bash ~/.openclaw/workspace/skills/spec-kit-coding/setup.sh`\n\nAsk user for confirmation before first run. This installs `specify` CLI,\nspeckit-* skills, and auxiliary skills. Do NOT proceed until it reports\nall dependencies ready.\n\nOptions: `--check-only` (check without install), `--force` (force reinstall).\n\n### STEP 1: Project Init\n\n1. Ask user for project path (default: current directory).\n2. Ask: \"Enable git management?\"\n\nIn project directory from now on:\n\n1. Run: `specify init --here --integration claude --force --ignore-agent-tools --script sh --no-git`\n2. Clean up: `rm -rf .claude CLAUDE.md` (keep `.specify/`).\n3. Verify: `.specify/` exists by run  `test -d .specify && echo \"OK: .specify/ exists\"`, and skills .etc are present by run `bash ~/.openclaw/workspace/skills/spec-kit-coding/setup.sh --check-only`.\n4. Follow the Git management section to do.\n\n### STEP 2: Create Project Docs\n\nCreate `README.md` and `DEVLOG.md`. Templates in Appendix A.\n\nKey rules:\n\n- README.md Architecture section: seed during plan phase (Step 5).\n  Update as final (Step 6.3).\n- DEVLOG.md: per-feature tracking. Each feature has its own phase history\n  block. The Summary table is regenerated from Feature Detail blocks after\n  every update -- do NOT manually edit the Summary section.\n\nGATE: Confirm with user that docs look correct.\n\n### STEP 3: Coding Standards and UI Skill Check\n\n#### Coding Standards (Checkpoint A -- before constitution)\n\nCollect BOTH architecture principles AND coding style conventions in ONE prompt:\n\n1. If user already provided documents/URLs/inline text earlier in the\n   conversation, use them directly. Do NOT re-ask.\n2. If not provided: detect languages from README.md SPEC Overview, then ask:\n\n> Use built-in coding standards as constitution reference?\n>\n> Architecture & Design:\n> `spec-kit-coding/CodingGuidance/TopLevelCodingGuidance.md`\n>\n> [Per-language coding style skills listed here based on detected languages]\n>\n> Coding Style (C++): `spec-kit-coding/CodingGuidance/CppCodingStyle.md`,\n> `spec-kit-coding/CodingGuidance/CppEngineeringFrameworkReference/`,\n> `spec-kit-coding/CodingGuidance/DesignPattern/`,\n> `external-skills/ecc-cpp-coding-standards`\n> [Similar for other languages, `spec-kit-coding/external-skills/ecc-*`]\n>\n> Language-agnostic: `spec-kit-coding/external-skills/ecc-coding-standards`\n\n- \"Yes\": include reference paths in constitution prompt, just ask to directly write the reference paths in constitution.md but Do NOT copy or re-write  the reference files content.\n- \"No\": generate concise generic guidance inline.\n- \"Partial\": respect the user's selection.\n\nRules:\n\n- Once confirmed, standards persist across all features in the project.\n- Do NOT modify `CodingGuidance/`. Read-only except during skill updates.\n\n#### UI Skill Check (Checkpoint B -- before plan, after constitution)\n\nIf the project involves UI, ask ONCE:\n\n> This project involves UI. Available frontend skills:\n> `spec-kit-coding/external-skills/ui-ux-pro-max-skill` (design system), or `spec-kit-coding/external-skills/ecc-*`. Load relevant ones for plan/implement?\n\n- \"yes\": sub-agents read chosen UI skills during plan and implement.\n- \"no\": skip.\n\n### STEP 4: Grill Alignment\n\nBefore writing specs, align the agent's understanding with the project's domain.\nUse `spec-kit-coding/external-skills/mattpocock-grill-with-docs`.\n\nOutputs:\n\n- CONTEXT.md at project root: Domain glossary. Devoid of implementation\n  details — it is a glossary, not a spec or scratch pad.\n- docs/adr/: Architecture Decision Records (sparingly).\n\nRuns once per project. Subsequent features reuse CONTEXT.md and ADRs.\n\nGATE: Confirm with user that CONTEXT.md accurately captures the domain\nlanguage and any created ADRs are correct.\n\n### STEP 5: Spec-Kit Phases / New Feature\n\nTwo paths available. Choose per-feature based on requirement clarity.\n\n**Production path (8 Phases -- for complex/ambiguous features):**\n\n```\nconstitution -> specify -> clarify -> checklist -> plan -> tasks -> analyze -> implement\n```\n\n**Lean path (6 Phases -- for simple/well-understood features):**\n\n```\nconstitution -> specify -> clarify -> plan -> tasks -> implement\n```\n\nEach phase apply the corresponding skill `spec-kit-coding/external-skills/speckit-*`.\n\nRules:\n\n- `constitution` runs once at project start. Subsequent features reuse it.\n- Use `CONTEXT.md` terminology in `specify`, `plan`, `tasks`.\n- `clarify` is ALWAYS run after `specify` (both paths). It catches ambiguities.\n- Skip `checklist` and `analyze` on lean path.\n- `speckit-specify` may generate an internal validation checklist as part of\n  its own flow. This is NOT the standalone `speckit-checklist` step.\n\nWhen to re-run constitution, only for:\n\n- Adding a new programming language not previously covered\n- Architecture-level changes that override existing principles\n\nIf git enabled: commit after every spec-Kit phases.\n\n### STEP 6: Implementation\n\nMUST run in fresh isolated sessions. Use the spawn template below.\n\n1. If tasks.md <= ~15 items and estimated code-gen calls <= ~12:\n   single sub-agent.\n2. Otherwise: split into batches. Each batch = fresh sub-agent session.\n3. After each batch: sub-agent updates DEVLOG.md. If git enabled: commit.\n4. Orchestrator tracks remaining tasks, spawns next batch.\n\n#### Spawn Template\n\nCopy this verbatim, filling in placeholders from the table:\n\n```\nYou are <ROLE> for feature <NNN>-<name> in project at <project-dir>.\n\nCONTEXT BOUNDARY: You are a fresh isolated session. Focus EXCLUSIVELY on\nfeature <NNN>-<name>. The documents below are your sole source of truth.\nDo NOT mix in details from other features, projects, or earlier batches.\n\nBefore <ACTION>, read these documents in order:\n1. <project-dir>/CONTEXT.md (Domain glossary — if it exists)\n2. <project-dir>/.specify/memory/constitution.md\n3. <project-dir>/specs/<NNN>-<name>/* (All documents related to this feature)\n4. <project-dir>/docs/adr/ (Architecture Decision Records — if any exist)\n5. <project-dir>/README.md (Architecture section)\n\n<ROLE_SPECIFIC_INSTRUCTIONS>\n\nAfter completing your work:\n- Update <project-dir>/DEVLOG.md\n- If git management is enabled: git commit all changes\n- Report back using the structured format below\n```\n\n| Placeholder                | Implement                                                                                                                                                          | Code Review (Step 6.1)                                                                                                                                                                                                                                                                                                                                                                                                                                                             | Test (Step 6.2)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |\n| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| ROLE                       | implementing                                                                                                                                                       | performing a CODE REVIEW for                                                                                                                                                                                                                                                                                                                                                                                                                                                       | performing TEST DEVELOPMENT for                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |\n| ACTION                     | writing any code                                                                                                                                                   | reviewing                                                                                                                                                                                                                                                                                                                                                                                                                                                                          | writing any test code                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |\n| ROLE_SPECIFIC_INSTRUCTIONS | Implement tasks M-N from tasks.md per speckit-implement skill. If plan is infeasible or conflicts with spec.md, STOP and report to orchestrator -- do NOT proceed. | Apply `spec-kit-coding/external-skills/superpowers-requesting-code-review`. **Checklist: (1) Practicality & Generality (2) Risk (memory, threads, deadlock, exception, errors, UB, security) (3) Optimization (algorithmic, allocations, copies, deps) (4) Architecture Alignment (5) Coding Standards per constitution.md.** Output: severity (Critical/Important/Minor/Suggestion) with file:line, description, recommendation. Overall: Ready/Needs Fixes/Major Rework. | Test environment:`/tmp/<project-name>-test/`. Framework by language (gtest/C++, pytest/Python, cargo/Rust, Jest/JS-TS, go test/Go .etc). **Ask the user for testing strategy: Module-level (cover all public APIs, normal/boundary/error inputs and thread safety(if applicable, concurrent construction/destruction and API calls from multiple threads), key API call sequences); Integration (Module-to-module interaction tests, Full application functional flow tests), that validate that all business logic behaves as expected; Coverage (optional): language-appropriate tools(gcov+lcov (C++), pytest-cov(python), cargo-tarpaulin (Rust), Jest --coverage (JS/TS), or language-equivalent).** When tests fail: apply BOTH skills — `spec-kit-coding/external-skills/mattpocock-diagnose` (build feedback loop first → 3-5 falsifiable hypotheses → instrument → fix → regression-test) AND `spec-kit-coding/external-skills/superpowers-systematic-debugging` (7-layer diagnostic model: L1 symptom → L2 logic → L3 system → L4 architecture → L5 cross-system → L6 platform → L7 spec gap). If 3+ fix attempts fail: question architecture, report to orchestrator. If ALL pass: proceed to STEP 6.3: Final Review. |\n\n#### Sub-Agent Report Format\n\nEvery sub-agent MUST end with:\n\n```\n## SUB-AGENT REPORT\n- Role: <implement | code-review | test>\n- Feature: <NNN>-<name>\n- Status: <SUCCESS | PARTIAL | BLOCKED | FAILED>\n- Tasks Completed: <list or \"all\">\n- Tasks Remaining: <list or \"none\">\n- Issues Found: <count, severity breakdown if review/test>\n- Blockers: <description or \"none\">\n- Files Modified: <list>\n- Summary: <1-2 sentences>\n```\n\nOrchestrator uses Status:\n\n- SUCCESS -> proceed to next gate\n- PARTIAL -> spawn continuation batch\n- BLOCKED -> escalate to user\n- FAILED -> diagnose; retry, rollback, or escalate\n\nGATE: After all batches report SUCCESS, confirm with user before proceeding\nto Code Review.\n\n#### STEP 6.1: Code Review\n\nAfter code implementation.\n\nCode review and fix. Ready the project for Testing.\n\nSpawn a fresh isolated session using the spawn template (Step 6) with the\n\"Code Review (Step 6.1)\" column values.\n\nAfter review:\n\n1. Present findings to user.\n2. Ask: \"Which review findings should be addressed?\"\n3. Apply ONLY user-approved fixes.\n4. Re-run review on changed files AND related files.\n5. If new issues: repeat from step 1. Limit: 3 review-fix cycles total.\n6. If issues persist after 3 cycles: stop. Report outstanding issues to the\n   user; user may decide to record them in README.md Known Limitations / Issues and proceed.\n\n#### STEP 6.2: Testing\n\nCode testing and debugging and fix. Ready the project for Final Review.\n\nSpawn a fresh isolated session using the spawn template (Step 6) with the\n\"Test (Step 6.2)\" column values.\n\n#### STEP 6.3: Final Review\n\nAfter STEP 6.2: Testing.\n\nOptimization & Doc Sync + Complexity Audit. Ready the project for STEP 7:\nDelivery Check.\n\nPerform these actions in order. Do NOT skip any.\n\n1. Re-read all modified source files for the feature.\n2. Check for:\n\n   1. Algorithmic improvements (better complexity).\n   2. Redundant allocations or copies.\n   3. Unnecessary dependencies.\n   4. Dead code or unreachable branches.\n   5. .etc\n3. Complexity Delta. Inspect the actual diff and report:\n\n   ```text\n   Complexity Delta:\n   - Files over 1200 lines:\n   - Files newly crossing 1200 lines:\n   - Largest touched file delta:\n   - Largest touched function/block:\n   - New branches/fallbacks/adapters:\n   - Retired branches/fallbacks/adapters:\n   - Net entropy: decreased | stable | increased-with-justification\n   - Required follow-up:\n   \n   Complexity Governance Suggestion:\n   - Recommendation: none | monitor | schedule-refactor | extract helper | split owner | open follow-up\n   - Why:\n   - Suggested scope:\n   - Timing:\n   ```\n\n   Skip for trivial changes (tests-only, generated, formatting, etc.).\n4. Record findings in README.md -> Features Plan / TODOs (NOT as TODO\n   comments in source). Format:\n   `- [ ] [category] description (file: path:line-range)`\n   Categories: optimization, robustness, clarity, security, perf.\n5. Present candidates to user:\n\n   > Optimization candidates found:\n   > **Implement now (low risk, high impact):**\n   >\n   > - [item]\n   >\n   > **Defer (tracked in README):**\n   >\n   > - [item]\n   >   Which \"implement now\" items should I apply?\n   >\n6. If user approves code changes:\n   a. Apply changes.\n   b. Full clean rebuild.\n   c. Run ALL tests.\n   d. If any test fails -> return to STEP 6.2: Testing.\n   e. If all pass -> continue.\n   f. If 3 cycles of regression->test->debug fail to converge: escalate to user.\n7. Update README.md Architecture section to reflect what was actually built.\n8. Update DEVLOG.md -- verify all phases and dates are current.\n9. If git enabled: commit.\n\n### STEP 7: Delivery Check\n\nRun through this checklist. Every item must be checked:\n\n- [ ] All required speckit-* phases completed or skipped (lean skips\n  checklist, analyze -- this is expected).\n- [ ] STEP 4 Grill Alignment completed (CONTEXT.md + any ADRs created).\n- [ ] Code review(If asked) completed and approved fixes applied.\n- [ ] All tests pass.\n- [ ] Source tree is clean (no temp files, no build artifacts in source dirs).\n- [ ] Complexity Delta checked (Step 6.3 item 3). Net entropy not increased\n  without justification.\n- [ ] Whole README.md is up-to-date.\n\n  Especially: README.md Architecture section is up-to-date. Optimization findings tracked in README.md Features Plan / TODOs section.\n- [ ] DEVLOG.md reflects all completed phases.\n- [ ] All hard constraints from section HARD CONSTRAINTS respected.\n- [ ] If git enabled: all changes committed.\n- [ ] Evidence Card. Fill out ONE evidence card covering all verification:\n\n  ```text\n  Evidence Card:\n  - Command / Check: <exact verification command(s) run>\n  - Exit Status: <exit code(s)>\n  - Covered: <what was verified>\n  - Not Covered: <what was NOT verified>\n  - Residual Risk: <remaining risk>\n  - Confidence: A | B | C\n  ```\n\n  Confidence grades:\n\n  - A: Direct verification + regression, no unknowns\n  - B: Direct verification, bounded residual risk\n  - C: Partial verification only, not closed — do NOT claim done\n\n  A claim of completion without evidence is NOT acceptable. Words like\n  \"should\", \"probably\", \"seems to\" are Red Flags — STOP and verify.\n\nGATE: Present delivery summary to user, including the filled Evidence Card.\n\n### Feature Modification Entry Point\n\nWhen the user wants to modify an existing feature, route by change type:\n\n| Tier | Type               | Examples                                        | Route                                                                                                                                   |\n| ---- | ------------------ | ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |\n| 1    | Parameter/Constant | timeout 30s->60s, max retries 3->5              | You can directly edit spec.md, then continue spec-Kit phases: clarify -> plan -> tasks -> implement -> then go section: STEP 6.2 to 6.3 |\n| 2    | Ambiguity/Gap      | \"handle errors\" unspecified, missing edge cases | clarify -> plan -> tasks -> implement -> then go section: STEP 6.1 to 6.3                                                               |\n| 3    | Substantive        | new OAuth login, REST->WebSocket, new roles     | Re-run specify -> full pipeline -> then go section: STEP 6.1 to 6.3                                                                     |\n\nDEVLOG records a new phase cycle regardless of tier.\n\nAll path above at end must go section: STEP 7: Delivery Check.\n\n### Bug Fix Entry Point\n\nWhen user reports a bug:\n\n1. Read the feature's spec.md, plan.md, and relevant source files.\n2. Determine if the bug is:\n   - Spec gap (behavior not defined) -> clarify -> plan -> implement.\n   - Implementation error (code disagrees with spec) -> fix directly.\n3. Then go section: STEP 6.2: Testing\n4. Then go section: STEP 6.3: Final Review\n5. Go section: STEP 7: Delivery Check.\n\n---\n\n## TROUBLESHOOTING\n\n| Problem                          | Fix                                     |\n| -------------------------------- | --------------------------------------- |\n| `specify: command not found`   | Install via uv or pipx (Step 0)         |\n| Skills not in workspace          | Run `bash setup.sh` (Step 0)          |\n| `.specify/` missing in project | Re-run Step 1                           |\n| Scripts not executable           | `chmod +x .specify/scripts/bash/*.sh` |\n| Task references stale spec       | Re-run the relevant speckit-* phase     |\n\n---\n\n## APPENDIX A: README.md and DEVLOG.md Templates\n\n### README.md Template\n\nCreate `<project-dir>/README.md`:\n\n````markdown\n# <Project Name>\n\n## Project Introduction\n\n<One-paragraph overview.>\n\n## Key Features\n\n<!-- Completed features (use `- ` list, NOT checkboxes).\n     This section describes what the project DOES today. -->\n- <Feature 1>\n- <Feature 2>\n\n## SPEC Overview\n\n- Type: <CLI tool / TUI / GUI / library / web service / ...>\n- Language(s) / Version(s): <e.g. C++20, Python 3.11; for mixed projects e.g. C++20 (backend) + Python 3.11 (tooling)>\n- Build: <CMake, cargo, pip, ...>\n- Dependencies: <key deps>\n- License: <MIT, Apache-2.0, ...>\n\n## Local Build\n\n### Prerequisites\n- <...>\n\n### Build Commands\n```bash\n# Debug\n<...>\n# Release\n<...>\n```\n\n## Usage Examples\n\n```bash\n# Basic usage\n<...>\n# With options\n<...>\n```\n\n## Architecture\n\n**Living document.** Seeded during plan phase (Step 5). Updated after all\nimplementation completes (Step 6.3).\n\n<Architecture diagram (ASCII art preferred) and description.\nInclude: high-level component layout, platform abstraction (if cross-platform),\ndata model summary, and key design decisions.>\n\n### Platform / Component Details\n\n<Break down key subsystems with enough detail that a new developer\ncan understand the layout without reading all source code.>\n\n## Known Limitations / Issues\n\n- <Limitation 1: what it is and why>\n- <Limitation 2>\n\n## Features Plan / TODOs\n\n<!-- Planned/upcoming features (use `- [ ]` checkboxes).\n     This section describes what the project WILL DO in the future.\n     Move items to Key Features (as `- ` bullets) when implemented. -->\n- [ ] <Planned feature or pending task>\n- [ ] ...\n\n## Spec-Driven Development Workflow And More\n\nThis project uses [github/spec-kit](https://github.com/github/spec-kit)\norchestrated via the spec-kit-coding OpenClaw skill. Progress tracked in\nDEVLOG.md.\n````\n\n### DEVLOG.md Template\n\nCreate `<project-dir>/DEVLOG.md` with **per-feature progress tracking**.\n\nAll dates in DEVLOG.md MUST use `YYYY-MM-DD HH:MM` format.\n\nFeature name is `<NNN>-<feature-name>` that the dir name from `<project-dir>/specs` dir.\n\n````markdown\n# Development Log -- <Project Name>\n\n## Feature Progress Summary\n\n| Feature | Specify | Clarify | Checklist | Plan | Tasks | Analyze | Implement | Updated |\n|---------|---------|---------|-----------|------|-------|---------|-----------|---------|\n| -- | -- | -- | -- | -- | -- | -- | -- | -- |\n\nLegend: [ ] pending | [~] in-progress | [√] complete | [>] skipped | [!] blocked\n\n## Feature Details\n\n<!-- FEATURE BLOCK START -->\n### <NNN>-<feature-name>\n\n- Description: <one-line summary>\n- Current Phase: <phase>\n- Last Updated: <date>\n\n**Phase History**:\n\n| Phase | Date | Status | Notes |\n|-------|------|--------|-------|\n| speckit-specify | | [ ] | |\n| speckit-clarify | | [ ] | |\n| speckit-checklist | | [ ] | |\n| speckit-plan | | [ ] | |\n| speckit-tasks | | [ ] | |\n| speckit-analyze | | [ ] | |\n| speckit-implement | | [ ] | |\n<!-- FEATURE BLOCK END -->\n\n## Global Notes\n\n- Constitution: <date or pending>\n- Project init: <date>\n- <Cross-feature decisions>\n````\n\nRules:\n\n- After each phase completes: update the Feature Detail block (Phase History\n  table + Current Phase + Last Updated).\n- After updating any Feature Detail: regenerate the Summary table from all\n  Feature Detail blocks. Never manually edit the Summary section.\n- When re-entering a feature (modification): add a new row to its Phase History.\n- If starting a new feature before finishing a previous one: per-feature\n  tracking keeps them independent.\n\n---\n\n## APPENDIX B: Speckit Skills Reference\n\nThese are installed to `external-skills/` by `setup.sh` (Step 0):\n\n| Skill                | Purpose                                | When                           |\n| -------------------- | -------------------------------------- | ------------------------------ |\n| speckit-constitution | Project principles & governance        | Once per project               |\n| speckit-specify      | Feature specification (what & why)     | Every new feature              |\n| speckit-clarify      | Quality gate -- catch spec ambiguities | After specify, always          |\n| speckit-checklist    | Requirement quality checklist          | Production path, after clarify |\n| speckit-plan         | Technical implementation plan          | After clarify/checklist        |\n| speckit-tasks        | Actionable, dependency-ordered tasks   | After plan                     |\n| speckit-analyze      | Cross-artifact consistency analysis    | Production path, after tasks   |\n| speckit-implement    | Execute tasks (batched)                | After analyze (or tasks, lean) |\n\n## APPENDIX C: Auxiliary Skills Reference\n\nAll under `external-skills/`. Invoked as needed in review/test/ui .etc.\nSee `external-skills/MANIFEST.md` for complete listing.\n\nFile v1.0.5:_meta.json\n\n{\n  \"ownerId\": \"kn7200kmgerbhf59xrmr2sbm9585gczq\",\n  \"slug\": \"spec-kit-coding\",\n  \"version\": \"1.0.5\",\n  \"publishedAt\": 1781595635431\n}\n\nFile v1.0.5:CodingGuidance/CppCodingStyle.md\n\n## 良好实践经验 / 易错注意 / 开发套路 / 惯例写法\r\n\r\n（引自 [Cpp-Learning/编程经验-规范, 调试、性能和内存检查工具集合.md at main · Staok/Cpp-Learning](https://github.com/Staok/Cpp-Learning/blob/main/编程经验-规范%2C 调试、性能和内存检查工具集合.md)）\r\n\r\n\r\n\r\n### 模块 和 类\r\n\r\n一个类的所有 对外 API，尽量都做到 线程安全的，除非需要特殊考虑或者特殊说明。锁的范围尽量小，注意内部带锁的多个函数的嵌套调用的情况。\r\n\r\n\r\n\r\n对于启动 app process 的 各个模块 初始化、反初始化、信号 与 未catch异常管理 等等，参考这个的做法：`CppEngineeringFrameworkReference/AppContext.h`。\r\n\r\n\r\n\r\n对于每个具体干活的、拆分好的执行业务功能的模块用一个类。每个类的具体的统一做法如下：\r\n\r\n- 视需求，有的可以是可以创建多个，有的是单例模式。\r\n\r\n- 对于完成业务/任务的类，不需要多例，就可以写为单例，对于单例类，写上不可拷贝或移动的构造，以及不可赋值操作的拷贝和移动构造。\r\n\r\n- 如果是模块作用的类：\r\n\r\n  对于类在启动其作用的时候，如果没有一直循环运行的任务（比如在一个线程里面或者 启动函数里面的 `while(true){...}`）则使用 init 的情况；相反，则使用 run 的情况。下面给出参考。\r\n\r\n  对于 init 的情况，具体参考这个例子来写类的框架：`CppEngineeringFrameworkReference/CppModuleInitCaseExample.cpp`。\r\n\r\n  对于 run 的情况，具体参考这个例子来写类的框架：`CppEngineeringFrameworkReference/CppModuleRunCaseExample.cpp`。\r\n\r\n  关于框架参考代码的 log 和 线程池 相关依赖为示例参考，不是要求。\r\n\r\n- 如果是工具作用的类，尽量做到 RAII。\r\n- 在除了启停的 API 以外的其它对外 API 中都应该先判断 是否已经运行或者初始化完毕。\r\n- 按照需要，对外 API 都做到 线程安全（结合具体业务考虑选择使用什么类型的锁，比如读写锁、循环锁等）；锁范围尽量小。如果内部使用线程或线程池的，则需由外部传入；如果线程内异步执行类内资源，在此之前，使用 `std::weak_ptr<XXX> selfWeakPtr = shared_from_this();` 并线程函数 lambda 按值捕获 `selfWeakPtr`（注意不要捕获 this，异步执行的线程可能捕获已经资源释放掉了的 类实例 this，因此使用这里说的 捕获 selfWeakPtr 的方法！），在里面 `.lock()` 然后判断是否为空和判断是否已经在运行或初始化完毕，再使用。\r\n- 关于类变量初始化：\r\n  - 类变量在声明的地方进行赋值默认值。\r\n  - 使用 nullptr 对 指针变量（尽量使用智能指针）声明的时候 进行 初始化；指针资源释放掉后，需要再赋值为 nullptr 。\r\n  - 对于 const 变量，则在 类构造函数 的 初始化列表 处 进行赋值。尽量使用 const。\r\n\r\n\r\n\r\n对于程序中用到多个实例的类，比如 屏幕上的多个 object 或者 多个实体的数据 等的 建模：\r\n\r\n- 关于类抽象、继承和多态的对数据进行建模的设计，应符合直觉、有意义、方便使用。\r\n- 基类/抽象类、派生类 的结构设计尽量按照实际情况，尽量分层次处理，基类/抽象类中列好公共 变量 和 接口/虚函数/纯虚函数 等。\r\n\r\n- 每个类都做到 RAII。\r\n\r\n- 对于一类的事物，每个事物用类封装，它们最好有个共同的抽象基类（继承其），并且每个具体事物的类里面 override 所有抽象基类的虚函数（形成多态）；若这些事物要随时创建，搞一个它们的工厂类（抽象工厂模式）来用 比较通用的接口 通过 不同的入参 来创建不同的一类事物 并返回他们的基类类型指针（用 如 std::make_shared 来创建）；参考自己的 `C-C++-设计模式综合\\DesignPattern\\Builder`。\r\n\r\n- 在具体的地方用 vector、map 等方式存储它们的智能指针（如 std::shared_ptr）来存着他们，或专门写个创建并管理它们的类（增删改查，判（判空）排（排序）复（复位））且用 LRU 的方式存储他们以实现 有序排列的同时 实现 增加、查询 均为O(1) 复杂度。参考自己写的 `GeneralContainer` 作为 对象池 进行管理，也避免频繁申请和释放 示例，改善程序性能，即缓存，空间换时间。\r\n\r\n\r\n\r\n- 如果是写库，则使用 impl 模式。在对外接口的 头文件中 尽量减少和避免 include 三方库的头文件。\r\n\r\n\r\n\r\n\r\n### 函数\r\n\r\n- 函数的 命名 和 使用方式 （以及注释说明）要 符合直觉、易于理解，不要搞谜语考试别人。\r\n\r\n- 可复用的部分拆分出单独的函数。函数保持短小精悍。\r\n\r\n  > **\"Give someone state and they'll have a bug one day, but teach them how to represent state in two separate locations that have to be kept in sync and they'll have bugs for a lifetime.\"** [ocornut/imgui: Dear ImGui: Bloat-free Graphical User interface for C++ with minimal dependencies (github.com)](https://github.com/ocornut/imgui)。\r\n  >\r\n  > DeepSeek 翻译为：单一状态顶多偶尔出错，双份状态终身调试不休。\r\n\r\n- 如需用锁，优化为无锁，或 减少锁的范围，只针对必要部分。\r\n\r\n- 函数实现尽量降低 圈复杂度。\r\n\r\n- 不允许使用递归（即不允许函数自己调用自己），如有必要，使用栈结构和循环替代实现。循环必须有退出条件。\r\n\r\n- 处理可能抛异常的三方函数，自己写的，尽量不主动抛异常。\r\n\r\n- 同一个函数内，局部变量所占用的空间应小于16KB。\r\n\r\n- 不对内容进行修改的指针型参数，使用 const 修饰。\r\n\r\n- 函数的返回值，一般为有符号整数表示执行结果，0 表示执行成功，负值表示出错（使用 -errno，比如 -EIO），正值表示带条件的执行成功（个人习惯，使用返回的正数区分是什么警告级别的问题）。\r\n\r\n  对外接口性质的函数：\r\n\r\n  - 根据 GSL（C++ Core Guidelines） 的契约检查，入参检查分为：前置检查，后置检查。\r\n\r\n    - 前置检查：在执行操作之前进行的检查，确保所有的先决条件都已经满足，如果条件不满足，则操作不会执行，程序可以立即返回错误或抛出异常。\r\n\r\n      即 检查外部给我的是否是好的。\r\n\r\n    - 后置检查：在操作执行之后进行的检查，验证操作的结果是否符合预期。如果结果不符合预期，则可能需要进行错误处理或修正。\r\n\r\n      即 检查我给外部的是否是好的。\r\n\r\n  - 考虑入参检查的策略，是检查少数错误的情况并返回错误值，还是检查少数正确的情况才执行，从检查的复杂度上选择复杂度小的。函数的入参，也不必总是执行复杂的检查，从整体设计上出发入手，首先考虑是否有必要检查（对外接口性函数需要，因为外面传入什么不确定，而模块、类的内部使用的很多函数从设计上入手，不需要总是检查入参，会增加运行负担）。\r\n\r\n  - 很多函数其实也可以不需要返回值或者外部判断返回值，需要从整体结构设计上入手，因为实际调用时候并不会总是检查返回值，无意义的、根本就不会出错的返回值检查也会增加运行负担。\r\n\r\n  - 关于函数入参的使用：\r\n\r\n    - 函数函数入参较多则考虑使用结构体打包，考虑可扩展性。\r\n\r\n      函数形参超过三个的，考虑 使用 struct 打包（后续补充形参也可直接修改这个结构体，比较方便维护），传递参数尽量不用 std::array, std::pair, std::tuple 等这种 破坏可读性 的东西。较多参数、可能变化的参数群 可以 封装为 struct。\r\n\r\n    - 视情况尽量使用 引用 来传入（注意传入变量的声明周期）。如果外面资源在对函数传入后就不用了，考虑用右值引用。\r\n\r\n      即视情况，尽量做到 零拷贝，或者减少拷贝，减少数据处理流程和时间。\r\n\r\n    - 涉及到外部传入变量的引用在内部对其处理，函数的 Doxygen 注释中提醒要保持传入变量的声明周期在函数内部使用的期间有效。\r\n\r\n      指针作为函数参数时，请检查参数是否为 nullptr。应尽量避免直接使用裸指针或者 c 风格 的数组，如果必要数组作为函数参数时，必须同时将其长度作为函数的参数。\r\n\r\n    - 类的多个方法中带锁，如果其中某个函数涉及到外部传入回调函数并使用，小心和考虑回调函数内部是否可以调用其它带锁的类方法，如有使用上的限制请注释说明。\r\n\r\n  - 返回内部参数，可直接写成拷贝返回即可（编译器 的 返回值优化（RVO）），不要返回指针、引用等容易增加 不确定性 问题，如 资源生命周期同步问题等。\r\n\r\n- 执行体中，可常用 大括号 `{ ... }` 包裹较独立的多段语句，控制其内部临时变量的生命周期，能提前结束的就可以提前结束。\r\n\r\n- 可以更多的使用模板元编程。\r\n\r\n- 控制内存占用。开发时要发觉和警惕 数量较大的 类实例数量或者内存申请，以及过于频繁的内存申请和释放。\r\n\r\n  在 内存已经碎片化 或 小内存频繁申请和释放 时候，malloc 时间显著延长。考虑使用 内存池 或 对象池。即缓存，空间换时间。\r\n\r\n  还比如，对于前者比如平面射击游戏中的满屏幕的子弹等要素，要发觉，子弹的颜色和图案都是一样的，所以至少这两个变量没必要在子弹类里面作为普通变量，而是用static修饰的方法；并且这个情况是子弹实例的创建和释放频繁，可以用提前申请的有多个对象的对象池进行管理。诸如此类。\r\n\r\n- 复杂函数放在 .c 或 .cpp 源文件 中定义；行数较少的、被高频调用的函数，公用函数性质的、短平快的，可在 .h 或 .hpp 中 写为内联函数，提高性能。\r\n\r\n\r\n\r\n### 变量\r\n\r\n- 变量类型约束为有限的、惯用的 以下几种即可。尽量不要用过多类型的数据类型，或自定义类型名称，复杂数据类型增加阅读难度。\r\n\r\n  - 基本变量就基本类型：std::string，各种 int（使用 int32_t 等），double（对于 64位 机器，少用 float） 等。\r\n  - 常用容器，按需使用，vector, list, map, unordered_map, set, stack 等。\r\n  - 多选一的、有限种类表示的，用枚举或枚举类，不要用字符串。\r\n  - 传递多种参数，使用结构体（不要用 std::tuple 等）。二元的数据（比如表示是否成功的整数 和 结果产物） 或者 key-value 类型的 可以用 std::pair。\r\n  - 多种类型合一个变量，使用 std::variant。\r\n- 对于类型写起来很长的类型，可以用 typedef（C 编程用）或 using（C++ 编程用）取个名字。\r\n- 类、结构体等的数据机构设计，考虑：缓存行对齐(考虑添加alignas(64))，SIMD友好的数据结构。\r\n- 多用 编译期 的 检查 和 计算。static_assert，以及 一些表达式使用 constexpr 替代 宏。\r\n- 尽量少用 std::string 等比较重的变量作为 index，而尽量都用 枚举类（在需要枚举的情况下使用） 或 整数（比如 map 中 key 可以用 uint64_t 作为 句柄 / token）。\r\n- 通过逻辑设计 或者 条件检查，以及后续测试：\r\n  - 整数之间运算时，确保不出现溢出、符号反转或除以0。\r\n  - 防止数组、指针越界访问。\r\n- 循环次数如果受外部数据控制，需要校验其合法性。\r\n- 标准库容器视情况可多用 emplace 等 右值引用来传递值，减少拷贝。\r\n- 禁止对有符号整数进行位操作运算。禁止对指针进行逻辑或位运算。禁止整数与指针间互相转化，在64位系统下可能导致高位截断，需使用intptr_t等类型安全转换。\r\n- 整型表达式比较或赋值为一种更大类型，必须先用这种更大类型对它进行求值。\r\n- 内存申请前，必须对申请内存大小进行合法性校验。\r\n- 内存分配后必须判断是否成功。内存释放之后立即赋予 nullptr。\r\n- 32 位机器尽量使用 32 位整型，少用 8、16 位整型。64 位机器则整数还是 32位，而浮点数尽量用 double。\r\n- 小数类型有精度问题，如果精度满足则可用，否则使用整数来表达。\r\n\r\n\r\n\r\n### 打印 Log\r\n\r\n打印 log 的一些规范，有用的 log 优化常用方法：\r\n\r\n- 可用于追踪程序流程的、关键系统级别的模块的启停和状态改变 等 需要打log。\r\n- 日志 log 中 隐私（企业、个人（用户））相关信息不要打印到 log 中。\r\n- 降频；比较前后数据，有变化时再打印；只打印 error 错误信息，以及关键 info 信息。\r\n- 比较稳定且不重要的模块尽可能精简，出了问题再加 log 也来的及。\r\n- log 描述尽量简化，单词用缩写，函数名不用打全。\r\n\r\n\r\n\r\nlog 持久化 和 分析 一系列 基础设施：可以选择 spdlog 库进行功能封装\r\n\r\n需要功能：\r\n\r\n- 分级别log，设置级别，\r\n- 单线程顺序异步log（不阻塞，不耗时），\r\n- log到文件并按大小滚动增加文件（并设置最大文件数量如10）、\r\n- 打包和加密保存、传输、\r\n- log打标签和设置回调（就可以直接作为埋点用）\r\n\r\n\r\n\r\n### 注释\r\n\r\n- 主旨是：方便自己日后回忆心路历程；方便他人熟悉 程序流程 和 究竟这段想要干什么 以及 为什么，帮助理解怎么使用和维护。\r\n\r\n  代码本身已经描述了怎么写的，注释里面就要重点描述写的过程中自己的心路历程这些后人看不到的东西，谁说代码不需要注释或者文档都没用，多些同理心和换位思考，世界更美好。\r\n\r\n  即 写注释重点放在：是什么 / 做什么、为什么、怎么做。\r\n\r\n- 均使用 Doxygen 格式。英文注释。\r\n\r\n- 注释包括：文件、类、函数、变量、函数内部关键点。\r\n\r\n  函数内部实现的注释，不管多行还是单行，都优先使用 `// xxx`。\r\n\r\n- 对外接口的头文件的前面给出几个这个模块的使用例子，说明基本用法（可选，但推荐）。\r\n\r\n- （对 AI 生成 来说）可直接生成 API 文档的水准。\r\n\r\n\r\n\r\n### 易错注意 / 开发套路\r\n\r\n\r\n\r\np.s 这些地方易错有些无法静态检查出，是运行起来碰到，目前还没有好的静态工具来检出，所以靠人来保证程序的健壮性，是良好的 程序框架设计 和 一些规则、规范 的 教育、培训、落实 来。\r\n\r\n\r\n\r\n- 多线程访问公用资源的竞争。\r\n\r\n  表现：程序 crash，变量不正常。\r\n\r\n  如何避免：\r\n\r\n  一个资源 的 创建、修改、删除 等：\r\n\r\n  - 要么 确保 一个模块的 所有 API 调用 都在一个线程（如 UI 线程 等）；\r\n  - 要么 确保多个线程公用一把锁（锁类型：单纯的互斥量，或者读写锁 等，选择适当的锁类型，或者使用 std::atomic 类型变量），且确保用 RAII （如 std::lock_guard、std::unique_lock 等）的方式用锁，保证可能被多个线程访问的同一块资源被锁保护起来。\r\n  - 注意：\r\n    - 防止同一个锁多次上锁，对于同一个类里面的API，可以用 std::recursive_mutex。\r\n    - 防止两个锁相互锁住，形成死锁，程序设计上尽量保持调用的单向流动，避免相互复杂的调用。\r\n    - 减少锁的范围，只用锁保护必要的部分，提升程序性能。\r\n\r\n- 死锁。\r\n\r\n  表现：程序卡住，但不 crash。使用锁且调用形成环，或者对 非循环锁 进行多次加锁，形成死锁，卡死。\r\n\r\n  如何避免：\r\n\r\n  确保调用不形成环，调用栈单向流动，或者使用循环锁。一般一个类的所有对外 API 做成多线程调用安全的，就使用锁，并且只保护关键的部分。\r\n\r\n  检出死锁：使用线程看门狗。起一个线程当作需要被喂的看门狗（若一段时间（比如10秒）没有得到喂狗，则主动抛异常，使得程序 产生 coredump 或者 crash exit，或者 使用 其它动态检查工具帮助打印信息，分析即可），主任务线程（关键作用的，它死锁了或者挂了就是大问题）周期性（比如100Hz、10Hz）喂狗。\r\n\r\n- 访问 非法 / 失效指针。\r\n\r\n  表现：运行到使用指针的点就 crash。\r\n\r\n  如何避免：\r\n\r\n  1. 动态创建的资源，避免使用裸指针，尽量使用 智能指针 替代使用 new/delete。释放指针后 置为 nullptr / null。\r\n\r\n     对于一些情况使用了 new / delete，要加锁互斥，new 前先判断 指针是否不为空，delete 前先判断 指针是否为空，delete 后 给指针 置 nullptr（防止多个线程 重复 delete），而且这种 crash 和 coredump 比较难定位问题所在，std::shared_ptr 等智能指针管理对象创建和销毁是线程安全的。[C++ : shared_ptr是线程安全的吗？ - 知乎 (zhihu.com)](https://zhuanlan.zhihu.com/p/664993437)。所以尽早就定好原则、列清过往经验和风险点、沟通到位、大家一块写尽量健壮的代码。\r\n\r\n  2. 使用 智能指针 std::shared_ptr 或者 std::unique_ptr。如果需要跨线程传递，就声明为 std::shared_ptr，并且 传递给 std::weak_ptr 后复制进另外线程里面，先 使用 `.lock()` 获取 后 再判空（判断是否已经失效），有效则可继续正常用。\r\n\r\n  3. lambda 注意捕获变量的生命周期，只捕获必要的部分，尽量不使用 捕获 `this` 或者 `&`（如果需要 this，则使用 shared_from_this 获取 后传递给 std::weak_ptr 后 再传递）。一个被捕获或传入的指针变量已经超出生命周期（比如释放掉了）再调用 lambda 并在里面使用这个指针变量，必 crash。\r\n\r\n- 抛异常。\r\n\r\n  表现：执行到回抛异常的函数 crash，程序结束也许会有打印。\r\n\r\n  如何避免：\r\n\r\n  使用系统调用、库函数等，查看文档确定其是否会抛异常，会抛异常的 API 若有必要 尽量 加 try cache 异常捕获。比如 如 std::stoi()，容器的 .at()、json 库 的一些 API 等等。接住异常要打印 log，并当即处理现场（视情况严重性，是直接终止程序（后面依靠比较完备的测试来逐渐收敛程序 bug 来提高程序健壮性），还是及时在当下来处理错误（如给个默认值等））。\r\n\r\n  自己写的程序不要抛异常，只接不抛，否则代码规模一大不好控制。\r\n\r\n- 数组、容器访问越界。\r\n\r\n  表现：运行到访问 数组、容器 crash。\r\n\r\n  避免：\r\n\r\n  1. 确保 判断 和 处理 各种外部传入 的 index 值。\r\n\r\n  2. 程序设计良好，在内部确保各个地方对 数组 或 容器 使用 index 不会发生越界等问题。如 使用 std 容器的 .at() 之前通过 检查 或 设计 保证不越界，或者调用容器的 .at() 等 的时候 使用 try catch 等。\r\n\r\n     对于 c++ STL 容器，使用方括号 [] 访问 如果越界不会抛异常，应该只使用 .at() 这一类的 API 并用 try catch，还有 对于 申请的内存 的 越界访问，要小心。\r\n\r\n\r\n\r\n## 细节写法格式规范\r\n\r\n（引自 [Cpp-Learning/编程经验-规范, 调试、性能和内存检查工具集合.md at main · Staok/Cpp-Learning](https://github.com/Staok/Cpp-Learning/blob/main/编程经验-规范%2C 调试、性能和内存检查工具集合.md)）\r\n\r\n注意这里应该只放格式相关的内容。\r\n\r\n\r\n\r\n注意，有个个人早期总结的一些 编程 经验 和 写法规范，主要针对 mcu c 的（自己的一些经验、网搜很多良好的经验、写法等 的 集合）：[Staok/coding-style-and-more: C 编写规范和其他 (github.com)](https://github.com/Staok/coding-style-and-more)，[gitee 地址](https://gitee.com/staok/coding-style-and-more)，这里面的规范我已经融合到下面了。coding-style-and-more 这个文章基本不再动了，里面的编码格式部分在开新项目时也不必参考了，参考如下这里的就好。这个文章里面关于 mcu 的各种经验还是值得在开发 mcu 等产品的时候借鉴的。\r\n\r\n\r\n\r\n- 文件中，引用头文件顺序：.c/.cpp 源文件 对应的 .h 头文件，标准库头文件，其它三方库的 头文件，本项目的其它头文件。应该尽量减少 对外接口 头文件 中 引用的 头文件。\r\n\r\n- 基本格式：\r\n\r\n  - 单文件最多尽量控制在 1200 行以内 或 左右。\r\n\r\n    函数最多尽量控制在 100 行以内。一个函数执行功能保持单一。\r\n\r\n    每一行最好不要超过100个字符在，超过部分选择在合适位置换行。\r\n\r\n    这样，倒逼在前期设计、模块结构、编码实现上多思考。\r\n\r\n  - 默认缩进 4 个空格，不要使用 tab。多行宏也用缩进。预处理相关代码如 `#if` `#ifdef` 等，看情况也要缩进。\r\n\r\n  - 使用 utf-8 编码。\r\n\r\n  - 不要有无意义的空格，行尾不要有空格。文件结尾保留一个空行。（这些可使用 VsCode 的 trim 相关设置参数）\r\n\r\n  - 函数等之间留有一个空行。\r\n\r\n    两个空行用于大段分割。不要有多于两个空行。\r\n\r\n  - 普通函数、类方法成员的花括号，在源文件里面，左括号另起一行，右括号与之竖向对齐；在头文件里面，左括号不必另起一行。如果两个以上参数，或者有参数写起来过长的，则每个参数新开一行，并且最后一个原括号前面留一个空格，格式如下：\r\n\r\n    ```c++\r\n    int32_t AAA::aaa(const std::string& a)\r\n    {\r\n        ...\r\n    }\r\n    \r\n    int32_t AAA::bbb(\r\n        const std::string& a,\r\n        const TimerCallback_t& b,\r\n        uint32_t c,\r\n        int32_t d,\r\n        bool e )\r\n    {\r\n        ...\r\n    }\r\n    ```\r\n\r\n    函数内用于分部分/分范围的花括号（在左括号上面一行注释说明下面这一段主要在做什么），左括号另起一行，右括号与之竖向对齐。\r\n\r\n    其它语句的左花括号如 if、for、while 等不必另起一行，其中的关键字和圆括号、花括号等之间空一格。 else 和 catch 等不必另起一行。对于判断语句含有多个判断条件的，每个判断条件新起一行并用括号括住，逻辑判断符号放在判断条件前面，判断语句最后的圆括号前空一格，左花括号另起一行，格式如下：\r\n\r\n    ```c++\r\n    if (ZZZ) {\r\n        ....\r\n    }\r\n    \r\n    if (    (AAA)\r\n         || (!BBB)\r\n         || (CCC < -1)\r\n         || (DDD == 0) )\r\n    {\r\n        return;\r\n    } else {\r\n        ...\r\n        // brief explain the braced code below\r\n        {\r\n            ....\r\n        }\r\n    }\r\n    ```\r\n\r\n    if 判断 true 或 false，判断 \"true\" 用这个写法：`if (check_func()) { ... }`，而不是 `if (check_func() == 1 或 true)`；判断是否为 \"false\" 用写法：`if (!check_func()) { ... }`。\r\n\r\n    switch-case 语句中，case 与 switch 对齐，case 内部 执行多于一个执行语句时，就使用 大花括号 括起来；必须带 default 分支。\r\n\r\n    结构体 和 类 的 声明 的左花括号不必另起一行。类的 public、private 等关键字 与 class 对齐。继承另起一行写，构造函数的初始化列表另起一行写，逗号都写到后面，类内的关键变量和const变量要写到初始化列表里面，类内的数字、布尔和指针等变量在声明时候都要写初始值，析构函数要用 virtual 修饰，等等，具体格式如下：\r\n\r\n    ```c++\r\n    class BBB {\r\n        ...\r\n    };\r\n    \r\n    class AAA\r\n      : BBB {\r\n    public:\r\n        AAA()\r\n          : BBB(),\r\n            mIsrunning(false) {\r\n            ...\r\n        }\r\n        virtual ~AAA() = default;\r\n    \r\n        bool isRunning() const {\r\n            return mIsrunning.load();\r\n        }\r\n    \r\n    private:\r\n        std::atomic<bool> mIsrunning{false};\r\n        std::mutex mMutex;\r\n    \r\n        std::shared_ptr<BBB> mBPtr = nullptr;\r\n        uint32_t mVal{0};\r\n        uint32_t mVal2{0};\r\n    };\r\n    ```\r\n\r\n  - namespace 所包裹的内容不用增加缩进层次。\r\n\r\n    预编译执行所包裹的内容不用增加缩进层次。\r\n\r\n- 命名相关：\r\n\r\n  - （尽量）全部用驼峰命名法，紧凑易读。\r\n\r\n  - 文件名、类的类型名、结构体的类型名、枚举或枚举类的类型名、枚举值名、宏名：首字母大写的驼峰命名法（帕斯卡命名法），其中枚举值名、宏名可加下划线来分割。\r\n\r\n    函数、局部变量，首字母小写的驼峰命名法。\r\n\r\n  - 普通函数、类的方法成员：\r\n\r\n    类内私有变量成员，使用 m 开头。bool 类型的类内私有变量，前缀为 mIs。\r\n\r\n    非类内的 bool 类型变量，前缀为 is。\r\n\r\n    指针类型变量用 ptr 结尾。\r\n\r\n    写 和 读 的方法函数命名惯例使用 set / get 作为前缀（set 函数里面 首先判断设置值是否与当前相同，不同才设，这个酌情加）；\r\n\r\n    返回 bool 类型的 set 或者 get 的函数， 前缀为 setIs 和 getIs。\r\n\r\n    回调函数命名结尾使用 CbFun（即 Callback Function ）。\r\n\r\n    设置、绑定回调函数、槽函数的函数使用 on 作为前缀，比如 onXXXChange 等。\r\n\r\n  - 具有互斥意义的变量或者动作相反的函数应该是用互斥词组命名，例子如下：\r\n\r\n    > add/remove      begin/end             create/destroy               insert/delete\r\n    > first/last            get/release            increment/decrement    put/get add/delete\r\n    > lock/unlock      open/close             min/max                        old/new\r\n    > start/stop         next/previous         source/target                 show/hide\r\n    > send/receive   source/destination  copy/paste                    up/down\r\n\r\n  - 对于写起来不长的数据类型，比如结构体和类，以及 枚举类、枚举 等，一般不要用 typedef 或者 using 来对类型进行重命名，即定义变量时候带着 struct 或 class 等关键字，标出变量的类型有利于阅读；但是对于写起来比较长的数据类型，比如 std::function<...> 等，可以使用 using 来对类型进行重命名。\r\n\r\n  - 源文件 内部用 的公共函数 使用 下划线开头，一般使用 `static <return type> _xxx(...) { ... }` 格式来。\r\n\r\n    头文件的公共函数，额外使用 inline 修饰，不必下划线开头，都放到与文件名同名的、首字母大写的 namespace 里面。\r\n\r\n- 函数 / 变量：\r\n\r\n  - 函数 入参 / 形参 不必下划线前缀。\r\n\r\n  - 宏函数 的 函数部分 推荐用 `do { ... } while(0)` 包起来，使用的时候以加分号结尾。\r\n\r\n  - 使用 枚举类 替代 传统枚举。如果要用枚举，里面变量命名首位加枚举类型名，用于每个枚举变量全局唯一。例子如下：\r\n\r\n    ```c++\r\n      enum TempEnum {\r\n          TempEnum_NumA = 0,\r\n          TempEnum_NumB,\r\n          // ...\r\n          TempEnum_MAX,\r\n      };\r\n      \r\n      // ↓\r\n      \r\n      enum class TempEnumClass {\r\n          NumA = 0,\r\n          NumB,\r\n          // ...\r\n          MAX,\r\n      };\r\n      \r\n      enum class TempEnumClass1 {\r\n          NumA = 0,\r\n          NumB,\r\n          // ...\r\n          MAX,\r\n      };\r\n    ```\r\n\r\n  - 长运算语句尽量多的用括号（每一步运算都用括号括起来），并做好空格增加可读性，例子如下：\r\n\r\n    ```c\r\n    temp = ( 0x7F << ((xByte - 1) * 8) );\r\n    #define MAX( x, y ) ( ((x) > (y)) ? (x) : (y) )\r\n    ```\r\n\r\n  - 定义指针的三种写法 `int* i_ptr;` 、`unsigned int * i_ptr;` 、 `int *i_ptr, *l_ptr, *a_ptr;`，分清这三种场合，第一个 单独定义一个指针（把 * 靠近类型名），第二个 指针类型名 超过一个单词（则把 * 写在中间），第三个 多个指针定义（把 * 靠近变量名）。\r\n\r\n    根据经验规范，C++ 编程应尽量避免裸指针而是用智能指针。\r\n\r\n\r\n\r\n\r\n- 在头文件可以写上这个：\r\n\r\n  年份根据实际修改，Name 根据所属实体修改。\r\n\r\n  ```c++\r\n  /*\r\n   * Copyright © 2025 [Name] All Rights Reserved.\r\n   */\r\n  ```\r\n\r\n  copyright 声明过来，有利于知道代码是谁写的，是三方还是原创，写于什么时候，SDK常规做法，也有利于用脚本过源码文件时候排查版权。\n\nFile v1.0.5:CodingGuidance/DesignPattern/DesignPattern.md\n\n# 程序设计的一些通用结构\r\n\r\n参考并总结 [设计模式目录：22种设计模式](https://refactoringguru.cn/design-patterns/catalog)。\r\n\r\n更多参考 [设计模式 | 菜鸟教程](https://www.runoob.com/python-design-pattern/python-design-pattern-tutorial.html)。\r\n\r\n\r\n\r\n------\r\n\r\n## RAII\r\n\r\n使用 RAII（Resource Acquisition Is Initialization）模式可以确保资源在对象的生命周期内正确初始化和释放。\r\n\r\n应尽量把程序结构定为多个类的多模块拆分和接力协作，并且，每个类写为 RAII 模式，确保类实例的所有内部资源的初始化和释放与其对象的生命周期一致，达到多次 启停的目的，方便外部使用和管理。\r\n\r\n参考 同文件夹 的 `RAII` 目录。内有详细注释说明。\r\n\r\n\r\n\r\n---\r\n\r\n## 创建型模式\r\n\r\n参考 同文件夹 的 `Pimpl` 和 `Pimpl2`、`Builder` 和 `Singleton` 目录。内有详细注释说明。\r\n\r\n\r\n\r\n---\r\n\r\n## 结构型模式\r\n\r\n\r\n\r\n### 适配器(adapter) & 桥接(bridge) & 组合(composite)\r\n\r\n适配器(adapter) 可以写为 多种信息类型之间的转换 的组件：选定一个内部的统一的格式，做例如 setIn() 和 setOut() 的方法。\r\n\r\n如选定 jsonObj (比如 `nlohmann::json`) 作为内部的中间统一格式，就可以有 `jsonObj.setIn( jsonStr | jsonObj | xmlStr | xmlObj | yamlStr | yamlObj ... )`，以及 `jsonObj.setOut( ... )`。还可以参考 pcl 库的 各种滤波器 的使用，其中就有 `setInput()` 方法 并 重载了多种输入。\r\n\r\n\r\n\r\n上下二者类似 ↑ ↓\r\n\r\n\r\n\r\n桥接(bridge) 可以作为 多对多的控制或调用 的模块（模块为比组件高一个级别的层级，包括多个组件构成） 的结构：上层有多种对外接口功能，下层也有多种平台或者其它情况的各种适配，那种就可以设计一个中间层，只保留少量的、通用的接口。\r\n\r\n\r\n\r\n类似于 ↓\r\n\r\n\r\n\r\n组合(composite) 可以用于 信息结构呈现为树状或网状的 信息存储：将每个信息节点，用 多叉树 或者 网 的数据结构，组合到一起，再添加各种处理操作。\r\n\r\n\r\n\r\n\r\n### 装饰器(decorator) & 外观(facade) & 代理(proxy)\r\n\r\n这几个类似 wrap 封装一层 的结构 或 方法：比如现在有 三种 三方组件库 A、B 和 C，他们具体接口不一样但是功能行为类似，比如多种社交媒体平台接口，均有发帖和获取贴等，现在要写个上层使用统一的结构对其操作，就可以加一个 wrap 包装/封装一层，先来个比如 WrapBasic 的抽象类定义通用的必要的接口，再写 AWrap 类继承 WrapBasic 并实现 特定接口 来操作 A 库的接口，其它 B 和 C 同理。现在就有了 AWrap、BWrap 和 CWrap 三种 接口统一的 类 可供操作 三种库。\r\n\r\n\r\n\r\n---\r\n\r\n## 行为模式\r\n\r\n\r\n\r\n### 行为链条(chain) & 迭代器(iterator)\r\n\r\n行为链条(chain)：用于链式的处理逻辑，比如要进行一系列有先后的检查步骤，并要方便的可以在中间增减检查步骤：使用链表结构存储检查函数或者检查抽象类智能指针等，核心就是使用链表的数据结构，如 `std::list`。\r\n\r\n对于链条数据结构的遍历，就需要迭代器如下。\r\n\r\n\r\n\r\n迭代器(iterator)：搞一个对某个数据结构的指定迭代/遍历方法的迭代器类：如对于 二叉树 或 网 的数据结构有 深度优先 和 广度优先 等遍历方法。\r\n\r\n自己实现的数据结构，需要实现基本的方法：增删改查；我再加四个：判排复遍——判空、排序（对于哈希表结构则没有）、复位（清空）和遍历。\r\n\r\n对于遍历，可以两种：\r\n\r\n1. 提供遍历的方法比如 `traverse(const TraverseFunction& traverse_func)`，传入一个遍历的回调函数，如下。还可以增加遍历方法指定的形参。\r\n\r\n   ```c++\r\n   template <typename Key, typename Value>\r\n   void GeneralContainer<Key, Value>::traverse(const TraverseFunction& traverse_func) const\r\n   {\r\n       if(!traverse_func) {\r\n           return;\r\n       }\r\n       std::shared_lock<std::shared_mutex> lock(mMutex);\r\n       for (const auto& it : mList) { // 正序遍历\r\n           traverse_func(it);\r\n       }\r\n   }\r\n   ```\r\n\r\n2. 提供这里所说的迭代器类，不同的迭代器类代表对这个数据结构的不同的遍历方法。比如 std 标准库 容器的:\r\n\r\n   ```c++\r\n   std::vector<int> myVector = {1, 2, 3, 4, 5};\r\n   auto forwardIter = myVector.begin();    // forwardIter 指向 第一个 元素，forwardIter++ 则移动到第二个元素。\r\n   auto backwardIter = myVector.rbegin();  // backwardIter 指向 最后一个 元素，backwardIter++ 则移动到倒数第二个元素。\r\n   ```\r\n\r\n\r\n\r\n### 中介/中央调度(mediator) & 命令(command)\r\n\r\n中介/中央调度(mediator)：多个地方的组件请求执行动作，如果其之间有冲突，比如多个 app 要往 状态栏 弹带优先级的信息，不要各自都直接弹出，因为需要优先级高的始终在最上，因此需要一个中介或者中央调度的组件或模块，多个地方的 app 统一往这个 中介 请求弹信息，由 中介 选择 往信息栏 插入 的位置并插入、或者检查黑名单并忽略等等。\r\n\r\n还有 GUI 程序中的弹窗场景，有的界面可以弹窗，有的界面不允许弹窗，等等还有其它设计情况，因此需要一个中介去统一接受弹窗请求并处理。\r\n\r\n\r\n\r\n命令(command)：思想是，打包一个执行动作以及其传入参数：一个执行动作，如 GUI 程序中 用户点击一个按键，索要执行的一系列程序，封装为一个函数（多种按键有枚举等关系，或者按键为登录等需要传入参数的），需要执行动作时候，打包函数和函数实参 如用 `std::bind()`，放到一个队列中去执行。可以参考 线程池 [progschj/ThreadPool: A simple C++11 Thread Pool implementation](https://github.com/progschj/ThreadPool) 的使用方法。\r\n\r\n如上面的中介就需要类似 命令 的方式，设置接口，处理来自其它组件的 \"命令\"。\r\n\r\n\r\n\r\n### 备忘录(memento) & 访问者(visitor)\r\n\r\n备忘录(memento)：针对需要给组件当前状态整一个快照、用于存留到历史记录中用于后面可能的再现/回放等场景，则给每个组件添加一个 比如 save() 或者 snapshot() 的方法，方法返回 保存了这个组件所有当前信息的（足够回放的）通用 Memento 类或者这个组件的一份克隆，有一个 history 类进行保存并在每次进行快照的时候增长。\r\n\r\n参考 [C++ 备忘录模式讲解和代码示例](https://refactoringguru.cn/design-patterns/memento/cpp/example)。\r\n\r\n\r\n\r\n访问者(visitor)：给需要被访问的类添加一个类似于 Accept(Visitor* visitor) 的函数，传入 visitor 后调用其 visitor->VisitConcreteComponentA(this);，在 VisitConcreteComponentA() 内部访问 当前类实例。\r\n\r\n参考 [C++ 访问者模式讲解和代码示例](https://refactoringguru.cn/design-patterns/visitor/cpp/example)。\r\n\r\n\r\n\r\n### 观察者(observer) / 发布-订阅(publisher-subscribers)\r\n\r\n观察者订阅发布者，发布者执行发布操作（可带参数），即所有订阅这个发布者的观察者的订阅回调函数都会被执行。\r\n\r\n发布-订阅 模式的 C++ 库，如：libsigcplusplus、KDBindings、等 信号槽 类型库，以及 dds 进程间通讯库等。\r\n\r\n\r\n\r\n### 状态设计(state) / 有限状态机(FSM)\r\n\r\n将组件或模块或设备的功能执行划分为一些状态以及状态之间的转移条件，画出状态转移图，即设计为 有限状态机 FSM，进行业务的编程建模。\r\n\r\n简单的可以为 switch-case 语句进行，复杂的、功能多的可以上库，如以下库等：\r\n\r\n- StateMachine [endurodave/StateMachine: State Machine Design in C++](https://github.com/endurodave/StateMachine)，C++，编程风格为 定义 事件 event 下 所有 状态 的 行为，以及状态进入和退出的行为等。\r\n- UML State Machine in C [kiishor/UML-State-Machine-in-C: A minimalist UML State machine framework for finite state machine and hierarchical state machine in C](https://github.com/kiishor/UML-State-Machine-in-C)，C 语言，轻量级（可用于 mcu），表格化构建状态机，支持层级状态机。\r\n- stateMachine [misje/stateMachine: A feature-rich, yet simple finite state machine (FSM) implementation in C](https://github.com/misje/stateMachine)，C 语言，简易简陋超轻量状态机，可用于 mcu。\r\n\r\n\r\n\r\nFPGA 的 IP核 设计中常用 FSM 概念进行建模，有几种不同的写法，Verilog 编码 的例子可见 [HDL-FPGA-study-and-norms/FPGA学习和规范 的参考源码/具体模块/fsm 一段和三段状态机例子 at main · Staok/HDL-FPGA-study-and-norms](https://github.com/Staok/HDL-FPGA-study-and-norms/tree/main/FPGA学习和规范 的参考源码/具体模块/fsm 一段和三段状态机例子)。\r\n\r\n\r\n\r\n### 策略(strategy) & 模板方法(template-method) / 类多态\r\n\r\n策略(strategy)：针对需要对于一定的数据集，使用不同的策略来获取不同的结果。策略可以使用基类和衍生类的多态来实现，这样，创建不同种类的策略类实例并给到执行，就是使用了不同的策略。\r\n\r\n参考 [C++ 策略模式讲解和代码示例](https://refactoringguru.cn/design-patterns/strategy/cpp/example)。\r\n\r\n\r\n\r\n模板方法(template-method)：基类定义执行操作（里面包含多种子操作以及特定顺序）的一个（纯）虚函数，并定义一些子操作（（纯）虚）函数，继承这个基类的多个衍生类中，使用不同的实现重写这些执行操作的函数（不同的子操作、顺序等，以及不同的操作实现），使用类多态，做到创建不同的类实例，用于对数据执行不同的策略操作。\r\n\r\n参考 [C++ 模板方法模式讲解和代码示例](https://refactoringguru.cn/design-patterns/template-method/cpp/example)。\n\nFile v1.0.5:CodingGuidance/TopLevelCodingGuidance.md\n\n## 编码顶层指导\r\n\r\n（引自 [Cpp-Learning/编程经验-规范, 调试、性能和内存检查工具集合.md at main · Staok/Cpp-Learning](https://github.com/Staok/Cpp-Learning/blob/main/编程经验-规范%2C 调试、性能和内存检查工具集合.md)）\r\n\r\n- **层次化，即分清晰的多层**。程序结构分为多个层次，文件夹也按照如此划分，不同模块处于不同功能层。具体问题具体分析。\r\n- **高内聚、低耦合。不宜常修改，应易扩展**。\r\n\r\n  写东西时候先多思考架构。不必一上来就写 等 情况的出现，减少后面 debug 和 重构的时间。\r\n\r\n  - 各部分选择合适的最佳实践和设计模式。\r\n  - 多看一些 **最佳实践的文章和软件工程** 来对自己进行提高。\r\n  - **设计模式**相关综合 [Staok/C-Cpp-design-patterns](https://github.com/Staok/C-Cpp-design-patterns)，具体参考其里面的 `DesignPattern` 文件夹下的文档和代码例子。检查 `CppCodingGuidance/DesignPattern` 若存在则直接用。\r\n\r\n  模块化。模块独立，各端分离，接口分明。每个模块可独立的、动态的、运行时的创建、启、停和释放，程序由多个模块搭建、协作来构成。\r\n\r\n  多写可复用代码。代码具有良好的实用性、通用性，以及安全性（风险规避）。\r\n\r\n  易于扩展和维护。\r\n- **参数化**。\r\n\r\n  几个维度：\r\n\r\n  - 对于模块的编写维度：考虑可通过修改参数来增强模块的适用范围和灵活性。模块编写考虑高复用性和多用性。敏锐的发现和合并公共的处理逻辑为一个通用的中间层，靠传入不同参数进行处理。\r\n  - 对于设备管理维度：数据驱动法，就像 Linux 中的 设备树 作为可方便修改的数据表格，可以冷更新或者热更新到系统、程序中去并生效，不必有改动的时候每次都改代码并重新编译打包和部署。可用 json 等格式 写入 外部配置文件，程序读取并应用。\r\n  - 对于软件整体运行层面：会有很多 settings，用户的或者系统内部的。可用 json 等格式 作为 设置存储文件，程序读写用。\r\n  - 对于不同机型或者运行工况，需要不同套参数，将其 表格化，数据驱动，初始化时候按照机型选取对应的一套参数装填并使用。\r\n- **可读性**。\r\n\r\n  注释：基本要求：英文 Doxygen 注释格式，头文件写几个用例（帮助快速熟悉使用），可直接生成 API 文档的水准。\r\n- 代码格式，以具有良好的可读性为好。整个工程整齐划一，**风格和编程模式具有连贯性**。\r\n\r\n  参考 具体的另外提供的 细节写法格式和规范。\r\n\r\n  （可选，默认不必用）每个项目有统一的 .clang_format 文件，时常 format 下。\r\n- （按需）**跨平台化**。\r\n\r\n  考虑软件的通用性和可移植性，考虑应用层的硬件无关性、跨平台性 / 跨操作系统性（主要是 Win 和 Linux），屏蔽日后换平台的工作量和痛苦。\r\n\r\n  除非特殊要求，否则不假定编写的代码用于特定场景（比如只用于 ROS2 环境 等），要按照实用、通用的准则去写。\r\n\r\n  三方库：尽量选用 Win 和 Linux 都兼容的，流行的、社区活跃的。\r\n- **依赖合理**。\r\n\r\n  按照当前需求和未来规划，合理分配哪些选择使用三方库，哪些选择自己实现。对于当前和未来需求而且功能复杂的，选择三方库（合理选择依赖的三方库，能覆盖需求，功能较丰富，尽量选择支持 Win 和 Linux 跨平台的，拒绝多用、滥用），对于代码量小的可以合理的自己实现。\r\n\r\n  对于 C/C++ 工程，为了不复杂化部署：均使用 cmake，依赖的三方库下载并放到工程目录的 third_party 文件夹里面 来直接通过 cmake 引入来使用。对于 C 除非指定版本 否则至少 C99。对于 C++ 除非约束版本 否则至少 C++17。\r\n\r\n  对于 Python，在工程目录建立 venv 虚拟环境来做，如果依赖特别多而且库有比较大的，则先询问用户是否还要使用 venv 虚拟环境 还是直接全局安装三方库。\r\n- **高性能**。\r\n\r\n  选择运行高效的、高性能的实现方式。若项目是刚开始搭建，而且高性能方案有一定难度，则可以先记录文档，先按照容易实现的（同时也有一定高性能保证的）方案来做，后面有需要则再优化性能。\r\n\r\n  具体内部的算法实现应降低圈复杂度、降低时间复杂度，但如果代价是显著增加空间复杂度则也不必，做好权衡。代码保持简洁易读。\r\n\r\n  也要注意避免头文件的过多嵌套导致编译时长显著增加。\r\n- **健壮性，稳定运行**。\r\n\r\n  风险点提前规避和检查，参考后面 `良好实践经验 / 易错注意 / 开发套路 / 惯例写法` 一节。\r\n- **可测试性**、**易于测试**。\r\n\r\n  保持程序的能控能观性。程序受外部控制接口统一且清晰，程序状态和对外影响、产物等明确。方便测试。\r\n\r\n  代码必须通过测试。具体测试要求参考另外提供的。\r\n\r\n  编码中尽量去掉 编译 warning。\r\n\r\n  Evidence over claims — 验证之后（代码审查、修复、测试 都通过）再声称完成。\n\nFile v1.0.5:skill-card.md\n\n## Description:\n\nSpec-kit Coding orchestrates the GitHub Spec-Kit spec-driven development workflow in OpenClaw for project setup, toolchain setup, and SDD pipeline execution.\n\nThis skill is ready for commercial/non-commercial use.\n\n## Publisher:\n\n[staok](https://clawhub.ai/user/staok)\n\n### License/Terms of Use:\n\nMIT-0\n\n## Use Case:\n\nDevelopers and engineers use this skill to initialize OpenClaw projects around GitHub Spec-Kit, establish project documentation and coding standards, and move features through specification, planning, tasking, implementation, review, and testing phases.\n\n### Deployment Geography for Use:\n\nGlobal\n\n## Known Risks and Mitigations:\n\nRisk: The setup workflow fetches executable tooling and third-party skills from GitHub into the OpenClaw workspace.\n\nMitigation: Run `setup.sh --check-only` first, review the listed downloads, and proceed with installation only after accepting those remote dependencies.\n\nRisk: The project initialization workflow can remove existing `.claude` and `CLAUDE.md` agent configuration.\n\nMitigation: Use a new or backed-up project directory before initialization, and avoid running the cleanup step in projects with important existing agent configuration.\n\nRisk: `--force` can reinstall tools and overwrite downloaded skill directories.\n\nMitigation: Avoid `--force` unless repair or refresh is necessary, and review generated `SOURCE.md` and manifest entries after reinstalling.\n\n## Reference(s):\n\n- [ClawHub Skill Page](https://clawhub.ai/staok/skills/spec-kit-coding)\n- [GitHub Spec-Kit](https://github.com/github/spec-kit)\n- [C++ Coding Style Guidance](CodingGuidance/CppCodingStyle.md)\n- [Top-Level Coding Guidance](CodingGuidance/TopLevelCodingGuidance.md)\n- [Design Pattern Guidance](CodingGuidance/DesignPattern/DesignPattern.md)\n\n## Skill Output:\n\n**Output Type(s):** [text, markdown, code, shell commands, configuration, guidance]\n\n**Output Format:** [Markdown guidance with inline shell commands, file templates, and task handoff prompts]\n\n**Output Parameters:** [1D]\n\n**Other Properties Related to Output:** [May create or update project files, documentation, specs, tasks, and agent handoff instructions when the workflow is followed.]\n\n## Skill Version(s):\n\n1.0.5 (source: release evidence)\n\n## Ethical Considerations:\n\nUsers should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment.\n\nArchive v1.0.4: 25 files, 65677 bytes\n\nFiles: CodingGuidance/CppCodingStyle.md (28612b), CodingGuidance/CppEngineeringFrameworkReference/AppContext.cpp (11115b), CodingGuidance/CppEngineeringFrameworkReference/AppContext.h (2950b), CodingGuidance/CppEngineeringFrameworkReference/CppModuleInitCaseExample.cpp (8754b), CodingGuidance/CppEngineeringFrameworkReference/CppModuleRunCaseExample.cpp (9280b), CodingGuidance/DesignPattern/Builder/ProductBuilder.h (9979b), CodingGuidance/DesignPattern/DesignPattern.md (10012b), CodingGuidance/DesignPattern/Pimpl/MyInterface.h (1369b), CodingGuidance/DesignPattern/Pimpl/MyInterfaceImpl.cpp (844b), CodingGuidance/DesignPattern/PImpl2/inc_private/GenericModuleImpl.h (1715b), CodingGuidance/DesignPattern/PImpl2/include/GenericModule.h (532b), CodingGuidance/DesignPattern/PImpl2/src/GenericModule.cpp (161b), CodingGuidance/DesignPattern/PImpl2/src/GenericModuleImpl.cpp (3060b), CodingGuidance/DesignPattern/RAII/RAII.cpp (6617b), CodingGuidance/DesignPattern/RAII/RAII.h (3568b), CodingGuidance/DesignPattern/Singleton/ClassFactory_Example.cpp (3797b), CodingGuidance/DesignPattern/Singleton/ClassFactory.hpp (7029b), CodingGuidance/DesignPattern/Singleton/Singleton.cpp (420b), CodingGuidance/DesignPattern/Singleton/Singleton.h (1307b), CodingGuidance/TopLevelCodingGuidance.md (5334b), setup.sh (26266b), skill-card.md (2996b), SKILL.md (32229b), TODO.txt (274b), _meta.json (134b)\n\nFile v1.0.4:SKILL.md\n\n---\nname: spec-kit-coding\ndescription: \"Orchestrator for GitHub Spec-Kit SDD workflow in OpenClaw. Use when starting a new project with spec-driven development, setting up spec-kit toolchain, or running through the full SDD pipeline.\"\n---\n# Spec-Kit Coding -- OpenClaw Orchestrator\n\n> **Repo:** [Staok/spec-kit-coding-skill](https://github.com/Staok/spec-kit-coding-skill)\n\nOrchestrates the complete Spec-Driven Development workflow via [github/spec-kit](https://github.com/github/spec-kit).\n\nCovers: Engineering Implementation. Does not cover\nrequirements discovery, operations/deployment, or cross-domain (SRE, security, etc.).\n\n---\n\n## HARD CONSTRAINTS\n\nREAD FIRST, APPLY ALWAYS.\n\nThese constraints are non-negotiable. Do NOT require the user to repeat them.\n\n### Security\n\n- Never transmit sensitive information to the network.\n- Before any external action (API calls, sending data outside local machine),\n  explain and ask for approval.\n- Do not install third-party libraries or modify system config without\n  asking first. If a new dependency is needed, explain why and get approval.\n- Prefer reusing existing, proven, popular third-party solutions. Avoid\n  reinventing the wheel. Keep tool usage simple and lean. Minimize dependency footprint.\n- **WARNING:** As a principle, agents should be disabled in critical-path code,\n  legacy system maintenance, and security-sensitive modules. Permitted only in\n  low-risk scenarios such as prototyping, search, and documentation.\n\n### Feature Management / Quick Reference\n\n- Starting a project, follow section: WORKFLOW, from STEP 1 to STEP 7.\n- Add a new feature or modify an existing feature:\n  - \"add\" / \"new\" / behavior no spec covers -> new feature -> section: STEP 5: Spec-Kit Phases / New Feature.\n  - \"change\" / \"modify\" / changing existing behavior -> modify existing -> section: Feature Modification Entry Point.\n- Each `/speckit-specify` invocation creates exactly ONE feature. If the user\n  describes a messy, multi-concern requirement, split it first:\n  - List each proposed feature with a short name and one-line summary.\n  - Note dependencies between features.\n  - Ask user to confirm the split before proceeding.\n- When uncertain whether the user wants a new feature or a modification to an\n  existing one, ASK. Do not guess. Present your organized analysis. Show several or both options concisely.\n- For projects that have already been delivered or already exist, if a bug is reported, refer to section: Bug Fix Entry Point.\n\n### Communication\n\n- Collect all unclear points first, then ask once. Avoid back-and-forth.\n- Be efficient and concise. Output only necessary information.\n- Remind the user how to think about the problem better; help improve prompt\n  quality over time.\n\n### Documentation-First\n\n- For spec/plan/tasks .etc phase docs (spec.md, plan.md, tasks.md): these are created via the speckit-* phases prior to implementation.\n- For DEVLOG.md: update per implementation batch, and after every phase\n  completion. DEVLOG must always reflect the latest state.\n- For README.md Architecture: seed during plan phase. Update as a final step\n  after all implementation completes (Step 5 and Step 6.3).\n- Never reverse the order: docs first, code second.\n\n### Git Management\n\n- During project init (Step 1), ASK whether to enable git. Record the answer.\n- If enabled: `git init`, `.gitignore`, initial commit. Then commit after\n  each phase completion and each implementation batch.\n- If disabled: do not create or manage a git repository.\n- The user may enable git at any later point. Once enabled, keep it on.\n\n### Context Isolation\n\n- \"Implement\" (The whole Step 6 and Step 6.X) MUST run in fresh isolated sub-agent sessions.\n  Never run implement in a session that has accumulated multiple prior phases.\n- If tasks.md has more than ~15 items, split implementation into batches.\n  Each batch = fresh sub-agent session.\n- Better to over-split than to produce garbage from context saturation.\n\n### Session Interrupt\n\n- If a session is interrupted mid-phase, do NOT assume which phase to restart\n  from. Ask the user: \"Restart from [interrupted-phase] or from\n  [previous-completed-phase]?\" If user is unsure, default to re-running the\n  interrupted phase from the start.\n\n---\n\n## WORKFLOW\n\n### STEP 0: Prerequisites (one-time per machine)\n\nRun: `bash ~/.openclaw/workspace/skills/spec-kit-coding/setup.sh`\n\nAsk user for confirmation before first run. This installs `specify` CLI,\nspeckit-* skills, and auxiliary skills. Do NOT proceed until it reports\nall dependencies ready.\n\nOptions: `--check-only` (check without install), `--force` (force reinstall).\n\n### STEP 1: Project Init\n\n1. Ask user for project path (default: current directory).\n2. Ask: \"Enable git management?\"\n\nIn project directory from now on:\n\n1. Run: `specify init --here --integration claude --force --ignore-agent-tools --script sh --no-git`\n2. Clean up: `rm -rf .claude CLAUDE.md` (keep `.specify/`).\n3. Verify: `.specify/` exists by run  `test -d .specify && echo \"OK: .specify/ exists\"`, and skills .etc are present by run `bash ~/.openclaw/workspace/skills/spec-kit-coding/setup.sh --check-only`.\n4. Follow the Git management section to do.\n\n### STEP 2: Create Project Docs\n\nCreate `README.md` and `DEVLOG.md`. Templates in Appendix A.\n\nKey rules:\n\n- README.md Architecture section: seed during plan phase (Step 5).\n  Update as final (Step 6.3).\n- DEVLOG.md: per-feature tracking. Each feature has its own phase history\n  block. The Summary table is regenerated from Feature Detail blocks after\n  every update -- do NOT manually edit the Summary section.\n\nGATE: Confirm with user that docs look correct.\n\n### STEP 3: Coding Standards and UI Skill Check\n\n#### Coding Standards (Checkpoint A -- before constitution)\n\nCollect BOTH architecture principles AND coding style conventions in ONE prompt:\n\n1. If user already provided documents/URLs/inline text earlier in the\n   conversation, use them directly. Do NOT re-ask.\n2. If not provided: detect languages from README.md SPEC Overview, then ask:\n\n> Use built-in coding standards as constitution reference?\n>\n> Architecture & Design:\n> `spec-kit-coding/CodingGuidance/TopLevelCodingGuidance.md`\n>\n> [Per-language coding style skills listed here based on detected languages]\n>\n> Coding Style (C++): `spec-kit-coding/CodingGuidance/CppCodingStyle.md`,\n> `spec-kit-coding/CodingGuidance/CppEngineeringFrameworkReference/`,\n> `spec-kit-coding/CodingGuidance/DesignPattern/`,\n> `external-skills/ecc-cpp-coding-standards`\n> [Similar for other languages, `spec-kit-coding/external-skills/ecc-*`]\n>\n> Language-agnostic: `spec-kit-coding/external-skills/ecc-coding-standards`\n\n- \"Yes\": include reference paths in constitution prompt, just ask to directly write the reference paths in constitution.md but Do NOT copy or re-write  the reference files content.\n- \"No\": generate concise generic guidance inline.\n- \"Partial\": respect the user's selection.\n\nRules:\n\n- Once confirmed, standards persist across all features in the project.\n- Do NOT modify `CodingGuidance/`. Read-only except during skill updates.\n\n#### UI Skill Check (Checkpoint B -- before plan, after constitution)\n\nIf the project involves UI, ask ONCE:\n\n> This project involves UI. Available frontend skills:\n> `spec-kit-coding/external-skills/ui-ux-pro-max-skill` (design system), or `spec-kit-coding/external-skills/ecc-*`. Load relevant ones for plan/implement?\n\n- \"yes\": sub-agents read chosen UI skills during plan and implement.\n- \"no\": skip.\n\n### STEP 4: Grill Alignment\n\nBefore writing specs, align the agent's understanding with the project's domain.\nUse `spec-kit-coding/external-skills/mattpocock-grill-with-docs`.\n\nOutputs:\n\n- CONTEXT.md at project root: Domain glossary. Devoid of implementation\n  details — it is a glossary, not a spec or scratch pad.\n- docs/adr/: Architecture Decision Records (sparingly).\n\nRuns once per project. Subsequent features reuse CONTEXT.md and ADRs.\n\nGATE: Confirm with user that CONTEXT.md accurately captures the domain\nlanguage and any created ADRs are correct.\n\n### STEP 5: Spec-Kit Phases / New Feature\n\nTwo paths available. Choose per-feature based on requirement clarity.\n\n**Production path (8 Phases -- for complex/ambiguous features):**\n\n```\nconstitution -> specify -> clarify -> checklist -> plan -> tasks -> analyze -> implement\n```\n\n**Lean path (6 Phases -- for simple/well-understood features):**\n\n```\nconstitution -> specify -> clarify -> plan -> tasks -> implement\n```\n\nEach phase apply the corresponding skill `spec-kit-coding/external-skills/speckit-*`.\n\nRules:\n\n- `constitution` runs once at project start. Subsequent features reuse it.\n- Use `CONTEXT.md` terminology in `specify`, `plan`, `tasks`.\n- `clarify` is ALWAYS run after `specify` (both paths). It catches ambiguities.\n- Skip `checklist` and `analyze` on lean path.\n- `speckit-specify` may generate an internal validation checklist as part of\n  its own flow. This is NOT the standalone `speckit-checklist` step.\n\nWhen to re-run constitution, only for:\n\n- Adding a new programming language not previously covered\n- Architecture-level changes that override existing principles\n\nIf git enabled: commit after every spec-Kit phases.\n\n### STEP 6: Implementation\n\nMUST run in fresh isolated sessions. Use the spawn template below.\n\n1. If tasks.md <= ~15 items and estimated code-gen calls <= ~12:\n   single sub-agent.\n2. Otherwise: split into batches. Each batch = fresh sub-agent session.\n3. After each batch: sub-agent updates DEVLOG.md. If git enabled: commit.\n4. Orchestrator tracks remaining tasks, spawns next batch.\n\n#### Spawn Template\n\nCopy this verbatim, filling in placeholders from the table:\n\n```\nYou are <ROLE> for feature <NNN>-<name> in project at <project-dir>.\n\nCONTEXT BOUNDARY: You are a fresh isolated session. Focus EXCLUSIVELY on\nfeature <NNN>-<name>. The documents below are your sole source of truth.\nDo NOT mix in details from other features, projects, or earlier batches.\n\nBefore <ACTION>, read these documents in order:\n1. <project-dir>/CONTEXT.md (Domain glossary — if it exists)\n2. <project-dir>/.specify/memory/constitution.md\n3. <project-dir>/specs/<NNN>-<name>/* (All documents related to this feature)\n4. <project-dir>/docs/adr/ (Architecture Decision Records — if any exist)\n5. <project-dir>/README.md (Architecture section)\n\n<ROLE_SPECIFIC_INSTRUCTIONS>\n\nAfter completing your work:\n- Update <project-dir>/DEVLOG.md\n- If git management is enabled: git commit all changes\n- Report back using the structured format below\n```\n\n| Placeholder                | Implement                                                                                                                                                          | Code Review (Step 6.1)                                                                                                                                                                                                                                                                                                                                                                                                                                                             | Test (Step 6.2)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |\n| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| ROLE                       | implementing                                                                                                                                                       | performing a CODE REVIEW for                                                                                                                                                                                                                                                                                                                                                                                                                                                       | performing TEST DEVELOPMENT for                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |\n| ACTION                     | writing any code                                                                                                                                                   | reviewing                                                                                                                                                                                                                                                                                                                                                                                                                                                                          | writing any test code                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |\n| ROLE_SPECIFIC_INSTRUCTIONS | Implement tasks M-N from tasks.md per speckit-implement skill. If plan is infeasible or conflicts with spec.md, STOP and report to orchestrator -- do NOT proceed. | Apply `spec-kit-coding/external-skills/superpowers-requesting-code-review`. **Checklist: (1) Practicality & Generality (2) Risk (memory, threads, deadlock, exception, errors, UB, security) (3) Optimization (algorithmic, allocations, copies, deps) (4) Architecture Alignment (5) Coding Standards per constitution.md.** Output: severity (Critical/Important/Minor/Suggestion) with file:line, description, recommendation. Overall: Ready/Needs Fixes/Major Rework. | Test environment:`/tmp/<project-name>-test/`. Framework by language (gtest/C++, pytest/Python, cargo/Rust, Jest/JS-TS, go test/Go .etc). **Ask the user for testing strategy: Module-level (cover all public APIs, normal/boundary/error inputs and thread safety(if applicable, concurrent construction/destruction and API calls from multiple threads), key API call sequences); Integration (Module-to-module interaction tests, Full application functional flow tests), that validate that all business logic behaves as expected; Coverage (optional): language-appropriate tools(gcov+lcov (C++), pytest-cov(python), cargo-tarpaulin (Rust), Jest --coverage (JS/TS), or language-equivalent).** When tests fail: apply BOTH skills — `spec-kit-coding/external-skills/mattpocock-diagnose` (build feedback loop first → 3-5 falsifiable hypotheses → instrument → fix → regression-test) AND `spec-kit-coding/external-skills/superpowers-systematic-debugging` (7-layer diagnostic model: L1 symptom → L2 logic → L3 system → L4 architecture → L5 cross-system → L6 platform → L7 spec gap). If 3+ fix attempts fail: question architecture, report to orchestrator. If ALL pass: proceed to STEP 6.3: Final Review. |\n\n#### Sub-Agent Report Format\n\nEvery sub-agent MUST end with:\n\n```\n## SUB-AGENT REPORT\n- Role: <implement | code-review | test>\n- Feature: <NNN>-<name>\n- Status: <SUCCESS | PARTIAL | BLOCKED | FAILED>\n- Tasks Completed: <list or \"all\">\n- Tasks Remaining: <list or \"none\">\n- Issues Found: <count, severity breakdown if review/test>\n- Blockers: <description or \"none\">\n- Files Modified: <list>\n- Summary: <1-2 sentences>\n```\n\nOrchestrator uses Status:\n\n- SUCCESS -> proceed to next gate\n- PARTIAL -> spawn continuation batch\n- BLOCKED -> escalate to user\n- FAILED -> diagnose; retry, rollback, or escalate\n\nGATE: After all batches report SUCCESS, confirm with user before proceeding\nto Code Review.\n\n#### STEP 6.1: Code Review\n\nAfter code implementation.\n\nCode review and fix. Ready the project for Testing.\n\nSpawn a fresh isolated session using the spawn template (Step 6) with the\n\"Code Review (Step 6.1)\" column values.\n\nAfter review:\n\n1. Present findings to user.\n2. Ask: \"Which review findings should be addressed?\"\n3. Apply ONLY user-approved fixes.\n4. Re-run review on changed files AND related files.\n5. If new issues: repeat from step 1. Limit: 3 review-fix cycles total.\n6. If issues persist after 3 cycles: stop. Report outstanding issues to the\n   user; user may decide to record them in README.md Known Limitations / Issues and proceed.\n\n#### STEP 6.2: Testing\n\nCode testing and debugging and fix. Ready the project for Final Review.\n\nSpawn a fresh isolated session using the spawn template (Step 6) with the\n\"Test (Step 6.2)\" column values.\n\n#### STEP 6.3: Final Review\n\nAfter STEP 6.2: Testing.\n\nOptimization & Doc Sync + Complexity Audit. Ready the project for STEP 7:\nDelivery Check.\n\nPerform these actions in order. Do NOT skip any.\n\n1. Re-read all modified source files for the feature.\n2. Check for:\n\n   1. Algorithmic improvements (better complexity).\n   2. Redundant allocations or copies.\n   3. Unnecessary dependencies.\n   4. Dead code or unreachable branches.\n   5. .etc\n3. Complexity Delta. Inspect the actual diff and report:\n\n   ```text\n   Complexity Delta:\n   - Files over 1200 lines:\n   - Files newly crossing 1200 lines:\n   - Largest touched file delta:\n   - Largest touched function/block:\n   - New branches/fallbacks/adapters:\n   - Retired branches/fallbacks/adapters:\n   - Net entropy: decreased | stable | increased-with-justification\n   - Required follow-up:\n\n   Complexity Governance Suggestion:\n   - Recommendation: none | monitor | schedule-refactor | extract helper | split owner | open follow-up\n   - Why:\n   - Suggested scope:\n   - Timing:\n   ```\n\n   Skip for trivial changes (tests-only, generated, formatting, etc.).\n4. Record findings in README.md -> Features Plan / TODOs (NOT as TODO\n   comments in source). Format:\n   `- [ ] [category] description (file: path:line-range)`\n   Categories: optimization, robustness, clarity, security, perf.\n5. Present candidates to user:\n\n   > Optimization candidates found:\n   > **Implement now (low risk, high impact):**\n   >\n   > - [item]\n   >\n   > **Defer (tracked in README):**\n   >\n   > - [item]\n   >   Which \"implement now\" items should I apply?\n   >\n6. If user approves code changes:\n   a. Apply changes.\n   b. Full clean rebuild.\n   c. Run ALL tests.\n   d. If any test fails -> return to STEP 6.2: Testing.\n   e. If all pass -> continue.\n   f. If 3 cycles of regression->test->debug fail to converge: escalate to user.\n7. Update README.md Architecture section to reflect what was actually built.\n8. Update DEVLOG.md -- verify all phases and dates are current.\n9. If git enabled: commit.\n\n### STEP 7: Delivery Check\n\nRun through this checklist. Every item must be checked:\n\n- [ ] All required speckit-* phases completed or skipped (lean skips\n  checklist, analyze -- this is expected).\n- [ ] STEP 4 Grill Alignment completed (CONTEXT.md + any ADRs created).\n- [ ] Code review(If asked) completed and approved fixes applied.\n- [ ] All tests pass.\n- [ ] Source tree is clean (no temp files, no build artifacts in source dirs).\n- [ ] Complexity Delta checked (Step 6.3 item 3). Net entropy not increased\n  without justification.\n- [ ] Whole README.md is up-to-date.\n\n  Especially: README.md Architecture section is up-to-date. Optimization findings tracked in README.md Features Plan / TODOs section.\n- [ ] DEVLOG.md reflects all completed phases.\n- [ ] All hard constraints from section HARD CONSTRAINTS respected.\n- [ ] If git enabled: all changes committed.\n- [ ] Evidence Card. Fill out ONE evidence card covering all verification:\n\n  ```text\n  Evidence Card:\n  - Command / Check: <exact verification command(s) run>\n  - Exit Status: <exit code(s)>\n  - Covered: <what was verified>\n  - Not Covered: <what was NOT verified>\n  - Residual Risk: <remaining risk>\n  - Confidence: A | B | C\n  ```\n\n  Confidence grades:\n\n  - A: Direct verification + regression, no unknowns\n  - B: Direct verification, bounded residual risk\n  - C: Partial verification only, not closed — do NOT claim done\n\n  A claim of completion without evidence is NOT acceptable. Words like\n  \"should\", \"probably\", \"seems to\" are Red Flags — STOP and verify.\n\nGATE: Present delivery summary to user, including the filled Evidence Card.\n\n### Feature Modification Entry Point\n\nWhen the user wants to modify an existing feature, route by change type:\n\n| Tier | Type               | Examples                                        | Route                                                                                                                                   |\n| ---- | ------------------ | ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |\n| 1    | Parameter/Constant | timeout 30s->60s, max retries 3->5              | You can directly edit spec.md, then continue spec-Kit phases: clarify -> plan -> tasks -> implement -> then go section: STEP 6.2 to 6.3 |\n| 2    | Ambiguity/Gap      | \"handle errors\" unspecified, missing edge cases | clarify -> plan -> tasks -> implement -> then go section: STEP 6.1 to 6.3                                                               |\n| 3    | Substantive        | new OAuth login, REST->WebSocket, new roles     | Re-run specify -> full pipeline -> then go section: STEP 6.1 to 6.3                                                                     |\n\nDEVLOG records a new phase cycle regardless of tier.\n\nAll path above at end must go section: STEP 7: Delivery Check.\n\n### Bug Fix Entry Point\n\nWhen user reports a bug:\n\n1. Read the feature's spec.md, plan.md, and relevant source files.\n2. Determine if the bug is:\n   - Spec gap (behavior not defined) -> clarify -> plan -> implement.\n   - Implementation error (code disagrees with spec) -> fix directly.\n3. Then go section: STEP 6.2: Testing\n4. Then go section: STEP 6.3: Final Review\n5. Go section: STEP 7: Delivery Check.\n\n---\n\n## TROUBLESHOOTING\n\n| Problem                          | Fix                                     |\n| -------------------------------- | --------------------------------------- |\n| `specify: command not found`   | Install via uv or pipx (Step 0)         |\n| Skills not in workspace          | Run `bash setup.sh` (Step 0)          |\n| `.specify/` missing in project | Re-run Step 1                           |\n| Scripts not executable           | `chmod +x .specify/scripts/bash/*.sh` |\n| Task references stale spec       | Re-run the relevant speckit-* phase     |\n\n---\n\n## APPENDIX A: README.md and DEVLOG.md Templates\n\n### README.md Template\n\nCreate `<project-dir>/README.md`:\n\n````markdown\n# <Project Name>\n\n## Project Introduction\n\n<One-paragraph overview.>\n\n## Key Features\n\n<!-- Completed features (use `- ` list, NOT checkboxes).\n     This section describes what the project DOES today. -->\n- <Feature 1>\n- <Feature 2>\n\n## SPEC Overview\n\n- Type: <CLI tool / TUI / GUI / library / web service / ...>\n- Language(s) / Version(s): <e.g. C++20, Python 3.11; for mixed projects e.g. C++20 (backend) + Python 3.11 (tooling)>\n- Build: <CMake, cargo, pip, ...>\n- Dependencies: <key deps>\n- License: <MIT, Apache-2.0, ...>\n\n## Local Build\n\n### Prerequisites\n- <...>\n\n### Build Commands\n```bash\n# Debug\n<...>\n# Release\n<...>\n```\n\n## Usage Examples\n\n```bash\n# Basic usage\n<...>\n# With options\n<...>\n```\n\n## Architecture\n\n**Living document.** Seeded during plan phase (Step 5). Updated after all\nimplementation completes (Step 6.3).\n\n<Architecture diagram (ASCII art preferred) and description.\nInclude: high-level component layout, platform abstraction (if cross-platform),\ndata model summary, and key design decisions.>\n\n### Platform / Component Details\n\n<Break down key subsystems with enough detail that a new developer\ncan understand the layout without reading all source code.>\n\n## Known Limitations / Issues\n\n- <Limitation 1: what it is and why>\n- <Limitation 2>\n\n## Features Plan / TODOs\n\n<!-- Planned/upcoming features (use `- [ ]` checkboxes).\n     This section describes what the project WILL DO in the future.\n     Move items to Key Features (as `- ` bullets) when implemented. -->\n- [ ] <Planned feature or pending task>\n- [ ] ...\n\n## Spec-Driven Development Workflow And More\n\nThis project uses [github/spec-kit](https://github.com/github/spec-kit)\norchestrated via the spec-kit-coding OpenClaw skill. Progress tracked in\nDEVLOG.md.\n````\n\n### DEVLOG.md Template\n\nCreate `<project-dir>/DEVLOG.md` with **per-feature progress tracking**.\n\nAll dates in DEVLOG.md MUST use `YYYY-MM-DD HH:MM` format.\n\nFeature name is `<NNN>-<feature-name>` that the dir name from `<project-dir>/specs` dir.\n\n````markdown\n# Development Log -- <Project Name>\n\n## Feature Progress Summary\n\n| Feature | Specify | Clarify | Checklist | Plan | Tasks | Analyze | Implement | Updated |\n|---------|---------|---------|-----------|------|-------|---------|-----------|---------|\n| -- | -- | -- | -- | -- | -- | -- | -- | -- |\n\nLegend: [ ] pending | [~] in-progress | [√] complete | [>] skipped | [!] blocked\n\n## Feature Details\n\n<!-- FEATURE BLOCK START -->\n### <NNN>-<feature-name>\n\n- Description: <one-line summary>\n- Current Phase: <phase>\n- Last Updated: <date>\n\n**Phase History**:\n\n| Phase | Date | Status | Notes |\n|-------|------|--------|-------|\n| speckit-specify | | [ ] | |\n| speckit-clarify | | [ ] | |\n| speckit-checklist | | [ ] | |\n| speckit-plan | | [ ] | |\n| speckit-tasks | | [ ] | |\n| speckit-analyze | | [ ] | |\n| speckit-implement | | [ ] | |\n<!-- FEATURE BLOCK END -->\n\n## Global Notes\n\n- Constitution: <date or pending>\n- Project init: <date>\n- <Cross-feature decisions>\n````\n\nRules:\n\n- After each phase completes: update the Feature Detail block (Phase History\n  table + Current Phase + Last Updated).\n- After updating any Feature Detail: regenerate the Summary table from all\n  Feature Detail blocks. Never manually edit the Summary section.\n- When re-entering a feature (modification): add a new row to its Phase History.\n- If starting a new feature before finishing a previous one: per-feature\n  tracking keeps them independent.\n\n---\n\n## APPENDIX B: Speckit Skills Reference\n\nThese are installed to `external-skills/` by `setup.sh` (Step 0):\n\n| Skill                | Purpose                                | When                           |\n| -------------------- | -------------------------------------- | ------------------------------ |\n| speckit-constitution | Project principles & governance        | Once per project               |\n| speckit-specify      | Feature specification (what & why)     | Every new feature              |\n| speckit-clarify      | Quality gate -- catch spec ambiguities | After specify, always          |\n| speckit-checklist    | Requirement quality checklist          | Production path, after clarify |\n| speckit-plan         | Technical implementation plan          | After clarify/checklist        |\n| speckit-tasks        | Actionable, dependency-ordered tasks   | After plan                     |\n| speckit-analyze      | Cross-artifact consistency analysis    | Production path, after tasks   |\n| speckit-implement    | Execute tasks (batched)                | After analyze (or tasks, lean) |\n\n## APPENDIX C: Auxiliary Skills Reference\n\nAll under `external-skills/`. Invoked as needed in review/test/ui .etc.\nSee `external-skills/MANIFEST.md` for complete listing.\n\nFile v1.0.4:_meta.json\n\n{\n  \"ownerId\": \"kn7200kmgerbhf59xrmr2sbm9585gczq\",\n  \"slug\": \"spec-kit-coding\",\n  \"version\": \"1.0.4\",\n  \"publishedAt\": 1780286402988\n}\n\nFile v1.0.4:CodingGuidance/CppCodingStyle.md\n\n## 良好实践经验 / 易错注意 / 开发套路 / 惯例写法\r\n\r\n（引自 [Cpp-Learning/编程经验-规范, 调试、性能和内存检查工具集合.md at main · Staok/Cpp-Learning](https://github.com/Staok/Cpp-Learning/blob/main/编程经验-规范%2C 调试、性能和内存检查工具集合.md)）\r\n\r\n\r\n\r\n### 模块 和 类\r\n\r\n一个类的所有 对外 API，尽量都做到 线程安全的，除非需要特殊考虑或者特殊说明。锁的范围尽量小，注意内部带锁的多个函数的嵌套调用的情况。\r\n\r\n\r\n\r\n对于启动 app process 的 各个模块 初始化、反初始化、信号 与 未catch异常管理 等等，参考这个的做法：`CppEngineeringFrameworkReference/AppContext.h`。\r\n\r\n\r\n\r\n对于每个具体干活的、拆分好的执行业务功能的模块用一个类。每个类的具体的统一做法如下：\r\n\r\n- 视需求，有的可以是可以创建多个，有的是单例模式。\r\n\r\n- 对于完成业务/任务的类，不需要多例，就可以写为单例，对于单例类，写上不可拷贝或移动的构造，以及不可赋值操作的拷贝和移动构造。\r\n\r\n- 如果是模块作用的类：\r\n\r\n  对于类在启动其作用的时候，如果没有一直循环运行的任务（比如在一个线程里面或者 启动函数里面的 `while(true){...}`）则使用 init 的情况；相反，则使用 run 的情况。下面给出参考。\r\n\r\n  对于 init 的情况，具体参考这个例子来写类的框架：`CppEngineeringFrameworkReference/CppModuleInitCaseExample.cpp`。\r\n\r\n  对于 run 的情况，具体参考这个例子来写类的框架：`CppEngineeringFrameworkReference/CppModuleRunCaseExample.cpp`。\r\n\r\n  关于框架参考代码的 log 和 线程池 相关依赖为示例参考，不是要求。\r\n\r\n- 如果是工具作用的类，尽量做到 RAII。\r\n- 在除了启停的 API 以外的其它对外 API 中都应该先判断 是否已经运行或者初始化完毕。\r\n- 按照需要，对外 API 都做到 线程安全（结合具体业务考虑选择使用什么类型的锁，比如读写锁、循环锁等）；锁范围尽量小。如果内部使用线程或线程池的，则需由外部传入；如果线程内异步执行类内资源，在此之前，使用 `std::weak_ptr<XXX> selfWeakPtr = shared_from_this();` 并线程函数 lambda 按值捕获 `selfWeakPtr`（注意不要捕获 this，异步执行的线程可能捕获已经资源释放掉了的 类实例 this，因此使用这里说的 捕获 selfWeakPtr 的方法！），在里面 `.lock()` 然后判断是否为空和判断是否已经在运行或初始化完毕，再使用。\r\n- 关于类变量初始化：\r\n  - 类变量在声明的地方进行赋值默认值。\r\n  - 使用 nullptr 对 指针变量（尽量使用智能指针）声明的时候 进行 初始化；指针资源释放掉后，需要再赋值为 nullptr 。\r\n  - 对于 const 变量，则在 类构造函数 的 初始化列表 处 进行赋值。尽量使用 const。\r\n\r\n\r\n\r\n对于程序中用到多个实例的类，比如 屏幕上的多个 object 或者 多个实体的数据 等的 建模：\r\n\r\n- 关于类抽象、继承和多态的对数据进行建模的设计，应符合直觉、有意义、方便使用。\r\n- 基类/抽象类、派生类 的结构设计尽量按照实际情况，尽量分层次处理，基类/抽象类中列好公共 变量 和 接口/虚函数/纯虚函数 等。\r\n\r\n- 每个类都做到 RAII。\r\n\r\n- 对于一类的事物，每个事物用类封装，它们最好有个共同的抽象基类（继承其），并且每个具体事物的类里面 override 所有抽象基类的虚函数（形成多态）；若这些事物要随时创建，搞一个它们的工厂类（抽象工厂模式）来用 比较通用的接口 通过 不同的入参 来创建不同的一类事物 并返回他们的基类类型指针（用 如 std::make_shared 来创建）；参考自己的 `C-C++-设计模式综合\\DesignPattern\\Builder`。\r\n\r\n- 在具体的地方用 vector、map 等方式存储它们的智能指针（如 std::shared_ptr）来存着他们，或专门写个创建并管理它们的类（增删改查，判（判空）排（排序）复（复位））且用 LRU 的方式存储他们以实现 有序排列的同时 实现 增加、查询 均为O(1) 复杂度。参考自己写的 `GeneralContainer` 作为 对象池 进行管理，也避免频繁申请和释放 示例，改善程序性能，即缓存，空间换时间。\r\n\r\n\r\n\r\n- 如果是写库，则使用 impl 模式。在对外接口的 头文件中 尽量减少和避免 include 三方库的头文件。\r\n\r\n\r\n\r\n\r\n### 函数\r\n\r\n- 函数的 命名 和 使用方式 （以及注释说明）要 符合直觉、易于理解，不要搞谜语考试别人。\r\n\r\n- 可复用的部分拆分出单独的函数。函数保持短小精悍。\r\n\r\n  > **\"Give someone state and they'll have a bug one day, but teach them how to represent state in two separate locations that have to be kept in sync and they'll have bugs for a lifetime.\"** [ocornut/imgui: Dear ImGui: Bloat-free Graphical User interface for C++ with minimal dependencies (github.com)](https://github.com/ocornut/imgui)。\r\n  >\r\n  > DeepSeek 翻译为：单一状态顶多偶尔出错，双份状态终身调试不休。\r\n\r\n- 如需用锁，优化为无锁，或 减少锁的范围，只针对必要部分。\r\n\r\n- 函数实现尽量降低 圈复杂度。\r\n\r\n- 不允许使用递归（即不允许函数自己调用自己），如有必要，使用栈结构和循环替代实现。循环必须有退出条件。\r\n\r\n- 处理可能抛异常的三方函数，自己写的，尽量不主动抛异常。\r\n\r\n- 同一个函数内，局部变量所占用的空间应小于16KB。\r\n\r\n- 不对内容进行修改的指针型参数，使用 const 修饰。\r\n\r\n- 函数的返回值，一般为有符号整数表示执行结果，0 表示执行成功，负值表示出错（使用 -errno，比如 -EIO），正值表示带条件的执行成功（个人习惯，使用返回的正数区分是什么警告级别的问题）。\r\n\r\n  对外接口性质的函数：\r\n\r\n  - 根据 GSL（C++ Core Guidelines） 的契约检查，入参检查分为：前置检查，后置检查。\r\n\r\n    - 前置检查：在执行操作之前进行的检查，确保所有的先决条件都已经满足，如果条件不满足，则操作不会执行，程序可以立即返回错误或抛出异常。\r\n\r\n      即 检查外部给我的是否是好的。\r\n\r\n    - 后置检查：在操作执行之后进行的检查，验证操作的结果是否符合预期。如果结果不符合预期，则可能需要进行错误处理或修正。\r\n\r\n      即 检查我给外部的是否是好的。\r\n\r\n  - 考虑入参检查的策略，是检查少数错误的情况并返回错误值，还是检查少数正确的情况才执行，从检查的复杂度上选择复杂度小的。函数的入参，也不必总是执行复杂的检查，从整体设计上出发入手，首先考虑是否有必要检查（对外接口性函数需要，因为外面传入什么不确定，而模块、类的内部使用的很多函数从设计上入手，不需要总是检查入参，会增加运行负担）。\r\n\r\n  - 很多函数其实也可以不需要返回值或者外部判断返回值，需要从整体结构设计上入手，因为实际调用时候并不会总是检查返回值，无意义的、根本就不会出错的返回值检查也会增加运行负担。\r\n\r\n  - 关于函数入参的使用：\r\n\r\n    - 函数函数入参较多则考虑使用结构体打包，考虑可扩展性。\r\n\r\n      函数形参超过三个的，考虑 使用 struct 打包（后续补充形参也可直接修改这个结构体，比较方便维护），传递参数尽量不用 std::array, std::pair, std::tuple 等这种 破坏可读性 的东西。较多参数、可能变化的参数群 可以 封装为 struct。\r\n\r\n    - 视情况尽量使用 引用 来传入（注意传入变量的声明周期）。如果外面资源在对函数传入后就不用了，考虑用右值引用。\r\n\r\n      即视情况，尽量做到 零拷贝，或者减少拷贝，减少数据处理流程和时间。\r\n\r\n    - 涉及到外部传入变量的引用在内部对其处理，函数的 Doxygen 注释中提醒要保持传入变量的声明周期在函数内部使用的期间有效。\r\n\r\n      指针作为函数参数时，请检查参数是否为 nullptr。应尽量避免直接使用裸指针或者 c 风格 的数组，如果必要数组作为函数参数时，必须同时将其长度作为函数的参数。\r\n\r\n    - 类的多个方法中带锁，如果其中某个函数涉及到外部传入回调函数并使用，小心和考虑回调函数内部是否可以调用其它带锁的类方法，如有使用上的限制请注释说明。\r\n\r\n  - 返回内部参数，可直接写成拷贝返回即可（编译器 的 返回值优化（RVO）），不要返回指针、引用等容易增加 不确定性 问题，如 资源生命周期同步问题等。\r\n\r\n- 执行体中，可常用 大括号 `{ ... }` 包裹较独立的多段语句，控制其内部临时变量的生命周期，能提前结束的就可以提前结束。\r\n\r\n- 可以更多的使用模板元编程。\r\n\r\n- 控制内存占用。开发时要发觉和警惕 数量较大的 类实例数量或者内存申请，以及过于频繁的内存申请和释放。\r\n\r\n  在 内存已经碎片化 或 小内存频繁申请和释放 时候，malloc 时间显著延长。考虑使用 内存池 或 对象池。即缓存，空间换时间。\r\n\r\n  还比如，对于前者比如平面射击游戏中的满屏幕的子弹等要素，要发觉，子弹的颜色和图案都是一样的，所以至少这两个变量没必要在子弹类里面作为普通变量，而是用static修饰的方法；并且这个情况是子弹实例的创建和释放频繁，可以用提前申请的有多个对象的对象池进行管理。诸如此类。\r\n\r\n- 复杂函数放在 .c 或 .cpp 源文件 中定义；行数较少的、被高频调用的函数，公用函数性质的、短平快的，可在 .h 或 .hpp 中 写为内联函数，提高性能。\r\n\r\n\r\n\r\n### 变量\r\n\r\n- 变量类型约束为有限的、惯用的 以下几种即可。尽量不要用过多类型的数据类型，或自定义类型名称，复杂数据类型增加阅读难度。\r\n\r\n  - 基本变量就基本类型：std::string，各种 int（使用 int32_t 等），double（对于 64位 机器，少用 float） 等。\r\n  - 常用容器，按需使用，vector, list, map, unordered_map, set, stack 等。\r\n  - 多选一的、有限种类表示的，用枚举或枚举类，不要用字符串。\r\n  - 传递多种参数，使用结构体（不要用 std::tuple 等）。二元的数据（比如表示是否成功的整数 和 结果产物） 或者 key-value 类型的 可以用 std::pair。\r\n  - 多种类型合一个变量，使用 std::variant。\r\n- 对于类型写起来很长的类型，可以用 typedef（C 编程用）或 using（C++ 编程用）取个名字。\r\n- 类、结构体等的数据机构设计，考虑：缓存行对齐(考虑添加alignas(64))，SIMD友好的数据结构。\r\n- 多用 编译期 的 检查 和 计算。static_assert，以及 一些表达式使用 constexpr 替代 宏。\r\n- 尽量少用 std::string 等比较重的变量作为 index，而尽量都用 枚举类（在需要枚举的情况下使用） 或 整数（比如 map 中 key 可以用 uint64_t 作为 句柄 / token）。\r\n- 通过逻辑设计 或者 条件检查，以及后续测试：\r\n  - 整数之间运算时，确保不出现溢出、符号反转或除以0。\r\n  - 防止数组、指针越界访问。\r\n- 循环次数如果受外部数据控制，需要校验其合法性。\r\n- 标准库容器视情况可多用 emplace 等 右值引用来传递值，减少拷贝。\r\n- 禁止对有符号整数进行位操作运算。禁止对指针进行逻辑或位运算。禁止整数与指针间互相转化，在64位系统下可能导致高位截断，需使用intptr_t等类型安全转换。\r\n- 整型表达式比较或赋值为一种更大类型，必须先用这种更大类型对它进行求值。\r\n- 内存申请前，必须对申请内存大小进行合法性校验。\r\n- 内存分配后必须判断是否成功。内存释放之后立即赋予 nullptr。\r\n- 32 位机器尽量使用 32 位整型，少用 8、16 位整型。64 位机器则整数还是 32位，而浮点数尽量用 double。\r\n- 小数类型有精度问题，如果精度满足则可用，否则使用整数来表达。\r\n\r\n\r\n\r\n### 打印 Log\r\n\r\n打印 log 的一些规范，有用的 log 优化常用方法：\r\n\r\n- 可用于追踪程序流程的、关键系统级别的模块的启停和状态改变 等 需要打log。\r\n- 日志 log 中 隐私（企业、个人（用户））相关信息不要打印到 log 中。\r\n- 降频；比较前后数据，有变化时再打印；只打印 error 错误信息，以及关键 info 信息。\r\n- 比较稳定且不重要的模块尽可能精简，出了问题再加 log 也来的及。\r\n- log 描述尽量简化，单词用缩写，函数名不用打全。\r\n\r\n\r\n\r\nlog 持久化 和 分析 一系列 基础设施：可以选择 spdlog 库进行功能封装\r\n\r\n需要功能：\r\n\r\n- 分级别log，设置级别，\r\n- 单线程顺序异步log（不阻塞，不耗时），\r\n- log到文件并按大小滚动增加文件（并设置最大文件数量如10）、\r\n- 打包和加密保存、传输、\r\n- log打标签和设置回调（就可以直接作为埋点用）\r\n\r\n\r\n\r\n### 注释\r\n\r\n- 主旨是：方便自己日后回忆心路历程；方便他人熟悉 程序流程 和 究竟这段想要干什么 以及 为什么，帮助理解怎么使用和维护。\r\n\r\n  代码本身已经描述了怎么写的，注释里面就要重点描述写的过程中自己的心路历程这些后人看不到的东西，谁说代码不需要注释或者文档都没用，多些同理心和换位思考，世界更美好。\r\n\r\n  即 写注释重点放在：是什么 / 做什么、为什么、怎么做。\r\n\r\n- 均使用 Doxygen 格式。英文注释。\r\n\r\n- 注释包括：文件、类、函数、变量、函数内部关键点。\r\n\r\n  函数内部实现的注释，不管多行还是单行，都优先使用 `// xxx`。\r\n\r\n- 对外接口的头文件的前面给出几个这个模块的使用例子，说明基本用法（可选，但推荐）。\r\n\r\n- （对 AI 生成 来说）可直接生成 API 文档的水准。\r\n\r\n\r\n\r\n### 易错注意 / 开发套路\r\n\r\n\r\n\r\np.s 这些地方易错有些无法静态检查出，是运行起来碰到，目前还没有好的静态工具来检出，所以靠人来保证程序的健壮性，是良好的 程序框架设计 和 一些规则、规范 的 教育、培训、落实 来。\r\n\r\n\r\n\r\n- 多线程访问公用资源的竞争。\r\n\r\n  表现：程序 crash，变量不正常。\r\n\r\n  如何避免：\r\n\r\n  一个资源 的 创建、修改、删除 等：\r\n\r\n  - 要么 确保 一个模块的 所有 API 调用 都在一个线程（如 UI 线程 等）；\r\n  - 要么 确保多个线程公用一把锁（锁类型：单纯的互斥量，或者读写锁 等，选择适当的锁类型，或者使用 std::atomic 类型变量），且确保用 RAII （如 std::lock_guard、std::unique_lock 等）的方式用锁，保证可能被多个线程访问的同一块资源被锁保护起来。\r\n  - 注意：\r\n    - 防止同一个锁多次上锁，对于同一个类里面的API，可以用 std::recursive_mutex。\r\n    - 防止两个锁相互锁住，形成死锁，程序设计上尽量保持调用的单向流动，避免相互复杂的调用。\r\n    - 减少锁的范围，只用锁保护必要的部分，提升程序性能。\r\n\r\n- 死锁。\r\n\r\n  表现：程序卡住，但不 crash。使用锁且调用形成环，或者对 非循环锁 进行多次加锁，形成死锁，卡死。\r\n\r\n  如何避免：\r\n\r\n  确保调用不形成环，调用栈单向流动，或者使用循环锁。一般一个类的所有对外 API 做成多线程调用安全的，就使用锁，并且只保护关键的部分。\r\n\r\n  检出死锁：使用线程看门狗。起一个线程当作需要被喂的看门狗（若一段时间（比如10秒）没有得到喂狗，则主动抛异常，使得程序 产生 coredump 或者 crash exit，或者 使用 其它动态检查工具帮助打印信息，分析即可），主任务线程（关键作用的，它死锁了或者挂了就是大问题）周期性（比如100Hz、10Hz）喂狗。\r\n\r\n- 访问 非法 / 失效指针。\r\n\r\n  表现：运行到使用指针的点就 crash。\r\n\r\n  如何避免：\r\n\r\n  1. 动态创建的资源，避免使用裸指针，尽量使用 智能指针 替代使用 new/delete。释放指针后 置为 nullptr / null。\r\n\r\n     对于一些情况使用了 new / delete，要加锁互斥，new 前先判断 指针是否不为空，delete 前先判断 指针是否为空，delete 后 给指针 置 nullptr（防止多个线程 重复 delete），而且这种 crash 和 coredump 比较难定位问题所在，std::shared_ptr 等智能指针管理对象创建和销毁是线程安全的。[C++ : shared_ptr是线程安全的吗？ - 知乎 (zhihu.com)](https://zhuanlan.zhihu.com/p/664993437)。所以尽早就定好原则、列清过往经验和风险点、沟通到位、大家一块写尽量健壮的代码。\r\n\r\n  2. 使用 智能指针 std::shared_ptr 或者 std::unique_ptr。如果需要跨线程传递，就声明为 std::shared_ptr，并且 传递给 std::weak_ptr 后复制进另外线程里面，先 使用 `.lock()` 获取 后 再判空（判断是否已经失效），有效则可继续正常用。\r\n\r\n  3. lambda 注意捕获变量的生命周期，只捕获必要的部分，尽量不使用 捕获 `this` 或者 `&`（如果需要 this，则使用 shared_from_this 获取 后传递给 std::weak_ptr 后 再传递）。一个被捕获或传入的指针变量已经超出生命周期（比如释放掉了）再调用 lambda 并在里面使用这个指针变量，必 crash。\r\n\r\n- 抛异常。\r\n\r\n  表现：执行到回抛异常的函数 crash，程序结束也许会有打印。\r\n\r\n  如何避免：\r\n\r\n  使用系统调用、库函数等，查看文档确定其是否会抛异常，会抛异常的 API 若有必要 尽量 加 try cache 异常捕获。比如 如 std::stoi()，容器的 .at()、json 库 的一些 API 等等。接住异常要打印 log，并当即处理现场（视情况严重性，是直接终止程序（后面依靠比较完备的测试来逐渐收敛程序 bug 来提高程序健壮性），还是及时在当下来处理错误（如给个默认值等））。\r\n\r\n  自己写的程序不要抛异常，只接不抛，否则代码规模一大不好控制。\r\n\r\n- 数组、容器访问越界。\r\n\r\n  表现：运行到访问 数组、容器 crash。\r\n\r\n  避免：\r\n\r\n  1. 确保 判断 和 处理 各种外部传入 的 index 值。\r\n\r\n  2. 程序设计良好，在内部确保各个地方对 数组 或 容器 使用 index 不会发生越界等问题。如 使用 std 容器的 .at() 之前通过 检查 或 设计 保证不越界，或者调用容器的 .at() 等 的时候 使用 try catch 等。\r\n\r\n     对于 c++ STL 容器，使用方括号 [] 访问 如果越界不会抛异常，应该只使用 .at() 这一类的 API 并用 try catch，还有 对于 申请的内存 的 越界访问，要小心。\r\n\r\n\r\n\r\n## 细节写法格式规范\r\n\r\n（引自 [Cpp-Learning/编程经验-规范, 调试、性能和内存检查工具集合.md at main · Staok/Cpp-Learning](https://github.com/Staok/Cpp-Learning/blob/main/编程经验-规范%2C 调试、性能和内存检查工具集合.md)）\r\n\r\n注意这里应该只放格式相关的内容。\r\n\r\n\r\n\r\n注意，有个个人早期总结的一些 编程 经验 和 写法规范，主要针对 mcu c 的（自己的一些经验、网搜很多良好的经验、写法等 的 集合）：[Staok/coding-style-and-more: C 编写规范和其他 (github.com)](https://github.com/Staok/coding-style-and-more)，[gitee 地址](https://gitee.com/staok/coding-style-and-more)，这里面的规范我已经融合到下面了。coding-style-and-more 这个文章基本不再动了，里面的编码格式部分在开新项目时也不必参考了，参考如下这里的就好。这个文章里面关于 mcu 的各种经验还是值得在开发 mcu 等产品的时候借鉴的。\r\n\r\n\r\n\r\n- 文件中，引用头文件顺序：.c/.cpp 源文件 对应的 .h 头文件，标准库头文件，其它三方库的 头文件，本项目的其它头文件。应该尽量减少 对外接口 头文件 中 引用的 头文件。\r\n\r\n- 基本格式：\r\n\r\n  - 单文件最多尽量控制在 1200 行以内 或 左右。\r\n\r\n    函数最多尽量控制在 100 行以内。一个函数执行功能保持单一。\r\n\r\n    每一行最好不要超过100个字符在，超过部分选择在合适位置换行。\r\n\r\n    这样，倒逼在前期设计、模块结构、编码实现上多思考。\r\n\r\n  - 默认缩进 4 个空格，不要使用 tab。多行宏也用缩进。预处理相关代码如 `#if` `#ifdef` 等，看情况也要缩进。\r\n\r\n  - 使用 utf-8 编码。\r\n\r\n  - 不要有无意义的空格，行尾不要有空格。文件结尾保留一个空行。（这些可使用 VsCode 的 trim 相关设置参数）\r\n\r\n  - 函数等之间留有一个空行。\r\n\r\n    两个空行用于大段分割。不要有多于两个空行。\r\n\r\n  - 普通函数、类方法成员的花括号，在源文件里面，左括号另起一行，右括号与之竖向对齐；在头文件里面，左括号不必另起一行。如果两个以上参数，或者有参数写起来过长的，则每个参数新开一行，并且最后一个原括号前面留一个空格，格式如下：\r\n\r\n    ```c++\r\n    int32_t AAA::aaa(const std::string& a)\r\n    {\r\n        ...\r\n    }\r\n    \r\n    int32_t AAA::bbb(\r\n        const std::string& a,\r\n        const TimerCallback_t& b,\r\n        uint32_t c,\r\n        int32_t d,\r\n        bool e )\r\n    {\r\n        ...\r\n    }\r\n    ```\r\n\r\n    函数内用于分部分/分范围的花括号（在左括号上面一行注释说明下面这一段主要在做什么），左括号另起一行，右括号与之竖向对齐。\r\n\r\n    其它语句的左花括号如 if、for、while 等不必另起一行，其中的关键字和圆括号、花括号等之间空一格。 else 和 catch 等不必另起一行。对于判断语句含有多个判断条件的，每个判断条件新起一行并用括号括住，逻辑判断符号放在判断条件前面，判断语句最后的圆括号前空一格，左花括号另起一行，格式如下：\r\n\r\n    ```c++\r\n    if (ZZZ) {\r\n        ....\r\n    }\r\n    \r\n    if (    (AAA)\r\n         || (!BBB)\r\n         || (CCC < -1)\r\n         || (DDD == 0) )\r\n    {\r\n        return;\r\n    } else {\r\n        ...\r\n        // brief explain the braced code below\r\n        {\r\n            ....\r\n        }\r\n    }\r\n    ```\r\n\r\n    if 判断 true 或 false，判断 \"true\" 用这个写法：`if (check_func()) { ... }`，而不是 `if (check_func() == 1 或 true)`；判断是否为 \"false\" 用写法：`if (!check_func()) { ... }`。\r\n\r\n    switch-case 语句中，case 与 switch 对齐，case 内部 执行多于一个执行语句时，就使用 大花括号 括起来；必须带 default 分支。\r\n\r\n    结构体 和 类 的 声明 的左花括号不必另起一行。类的 public、private 等关键字 与 class 对齐。继承另起一行写，构造函数的初始化列表另起一行写，逗号都写到后面，类内的关键变量和const变量要写到初始化列表里面，类内的数字、布尔和指针等变量在声明时候都要写初始值，析构函数要用 virtual 修饰，等等，具体格式如下：\r\n\r\n    ```c++\r\n    class BBB {\r\n        ...\r\n    };\r\n    \r\n    class AAA\r\n      : BBB {\r\n    public:\r\n        AAA()\r\n          : BBB(),\r\n            mIsrunning(false) {\r\n            ...\r\n        }\r\n        virtual ~AAA() = default;\r\n    \r\n        bool isRunning() const {\r\n            return mIsrunning.load();\r\n        }\r\n    \r\n    private:\r\n        std::atomic<bool> mIsrunning{false};\r\n        std::mutex mMutex;\r\n    \r\n        std::shared_ptr<BBB> mBPtr = nullptr;\r\n        uint32_t mVal{0};\r\n        uint32_t mVal2{0};\r\n    };\r\n    ```\r\n\r\n  - namespace 所包裹的内容不用增加缩进层次。\r\n\r\n    预编译执行所包裹的内容不用增加缩进层次。\r\n\r\n- 命名相关：\r\n\r\n  - （尽量）全部用驼峰命名法，紧凑易读。\r\n\r\n  - 文件名、类的类型名、结构体的类型名、枚举或枚举类的类型名、枚举值名、宏名：首字母大写的驼峰命名法（帕斯卡命名法），其中枚举值名、宏名可加下划线来分割。\r\n\r\n    函数、局部变量，首字母小写的驼峰命名法。\r\n\r\n  - 普通函数、类的方法成员：\r\n\r\n    类内私有变量成员，使用 m 开头。bool 类型的类内私有变量，前缀为 mIs。\r\n\r\n    非类内的 bool 类型变量，前缀为 is。\r\n\r\n    指针类型变量用 ptr 结尾。\r\n\r\n    写 和 读 的方法函数命名惯例使用 set / get 作为前缀（set 函数里面 首先判断设置值是否与当前相同，不同才设，这个酌情加）；\r\n\r\n    返回 bool 类型的 set 或者 get 的函数， 前缀为 setIs 和 getIs。\r\n\r\n    回调函数命名结尾使用 CbFun（即 Callback Function ）。\r\n\r\n    设置、绑定回调函数、槽函数的函数使用 on 作为前缀，比如 onXXXChange 等。\r\n\r\n  - 具有互斥意义的变量或者动作相反的函数应该是用互斥词组命名，例子如下：\r\n\r\n    > add/remove      begin/end             create/destroy               insert/delete\r\n    > first/last            get/release            increment/decrement    put/get add/delete\r\n    > lock/unlock      open/close             min/max                        old/new\r\n    > start/stop         next/previous         source/target                 show/hide\r\n    > send/receive   source/destination  copy/paste                    up/down\r\n\r\n  - 对于写起来不长的数据类型，比如结构体和类，以及 枚举类、枚举 等，一般不要用 typedef 或者 using 来对类型进行重命名，即定义变量时候带着 struct 或 class 等关键字，标出变量的类型有利于阅读；但是对于写起来比较长的数据类型，比如 std::function<...> 等，可以使用 using 来对类型进行重命名。\r\n\r\n  - 源文件 内部用 的公共函数 使用 下划线开头，一般使用 `static <return type> _xxx(...) { ... }` 格式来。\r\n\r\n    头文件的公共函数，额外使用 inline 修饰，不必下划线开头，都放到与文件名同名的、首字母大写的 namespace 里面。\r\n\r\n- 函数 / 变量：\r\n\r\n  - 函数 入参 / 形参 不必下划线前缀。\r\n\r\n  - 宏函数 的 函数部分 推荐用 `do { ... } while(0)` 包起来，使用的时候以加分号结尾。\r\n\r\n  - 使用 枚举类 替代 传统枚举。如果要用枚举，里面变量命名首位加枚举类型名，用于每个枚举变量全局唯一。例子如下：\r\n\r\n    ```c++\r\n      enum TempEnum {\r\n          TempEnum_NumA = 0,\r\n          TempEnum_NumB,\r\n          // ...\r\n          TempEnum_MAX,\r\n      };\r\n      \r\n      // ↓\r\n      \r\n      enum class TempEnumClass {\r\n          NumA = 0,\r\n          NumB,\r\n          // ...\r\n          MAX,\r\n      };\r\n      \r\n      enum class TempEnumClass1 {\r\n          NumA = 0,\r\n          NumB,\r\n          // ...\r\n          MAX,\r\n      };\r\n    ```\r\n\r\n  - 长运算语句尽量多的用括号（每一步运算都用括号括起来），并做好空格增加可读性，例子如下：\r\n\r\n    ```c\r\n    temp = ( 0x7F << ((xByte - 1) * 8) );\r\n    #define MAX( x, y ) ( ((x) > (y)) ? (x) : (y) )\r\n    ```\r\n\r\n  - 定义指针的三种写法 `int* i_ptr;` 、`unsigned int * i_ptr;` 、 `int *i_ptr, *l_ptr, *a_ptr;`，分清这三种场合，第一个 单独定义一个指针（把 * 靠近类型名），第二个 指针类型名 超过一个单词（则把 * 写在中间），第三个 多个指针定义（把 * 靠近变量名）。\r\n\r\n    根据经验规范，C++ 编程应尽量避免裸指针而是用智能指针。\r\n\r\n\r\n\r\n\r\n- 在头文件可以写上这个：\r\n\r\n  年份根据实际修改，Name 根据所属实体修改。\r\n\r\n  ```c++\r\n  /*\r\n   * Copyright © 2025 [Name] All Rights Reserved.\r\n   */\r\n  ```\r\n\r\n  copyright 声明过来，有利于知道代码是谁写的，是三方还是原创，写于什么时候，SDK常规做法，也有利于用脚本过源码文件时候排查版权。\n\nFile v1.0.4:CodingGuidance/DesignPattern/DesignPattern.md\n\n# 程序设计的一些通用结构\r\n\r\n参考并总结 [设计模式目录：22种设计模式](https://refactoringguru.cn/design-patterns/catalog)。\r\n\r\n更多参考 [设计模式 | 菜鸟教程](https://www.runoob.com/python-design-pattern/python-design-pattern-tutorial.html)。\r\n\r\n\r\n\r\n------\r\n\r\n## RAII\r\n\r\n使用 RAII（Resource Acquisition Is Initialization）模式可以确保资源在对象的生命周期内正确初始化和释放。\r\n\r\n应尽量把程序结构定为多个类的多模块拆分和接力协作，并且，每个类写为 RAII 模式，确保类实例的所有内部资源的初始化和释放与其对象的生命周期一致，达到多次 启停的目的，方便外部使用和管理。\r\n\r\n参考 同文件夹 的 `RAII` 目录。内有详细注释说明。\r\n\r\n\r\n\r\n---\r\n\r\n## 创建型模式\r\n\r\n参考 同文件夹 的 `Pimpl` 和 `Pimpl2`、`Builder` 和 `Singleton` 目录。内有详细注释说明。\r\n\r\n\r\n\r\n---\r\n\r\n## 结构型模式\r\n\r\n\r\n\r\n### 适配器(adapter) & 桥接(bridge) & 组合(composite)\r\n\r\n适配器(adapter) 可以写为 多种信息类型之间的转换 的组件：选定一个内部的统一的格式，做例如 setIn() 和 setOut() 的方法。\r\n\r\n如选定 jsonObj (比如 `nlohmann::json`) 作为内部的中间统一格式，就可以有 `jsonObj.setIn( jsonStr | jsonObj | xmlStr | xmlObj | yamlStr | yamlObj ... )`，以及 `jsonObj.setOut( ... )`。还可以参考 pcl 库的 各种滤波器 的使用，其中就有 `setInput()` 方法 并 重载了多种输入。\r\n\r\n\r\n\r\n上下二者类似 ↑ ↓\r\n\r\n\r\n\r\n桥接(bridge) 可以作为 多对多的控制或调用 的模块（模块为比组件高一个级别的层级，包括多个组件构成） 的结构：上层有多种对外接口功能，下层也有多种平台或者其它情况的各种适配，那种就可以设计一个中间层，只保留少量的、通用的接口。\r\n\r\n\r\n\r\n类似于 ↓\r\n\r\n\r\n\r\n组合(composite) 可以用于 信息结构呈现为树状或网状的 信息存储：将每个信息节点，用 多叉树 或者 网 的数据结构，组合到一起，再添加各种处理操作。\r\n\r\n\r\n\r\n\r\n### 装饰器(decorator) & 外观(facade) & 代理(proxy)\r\n\r\n这几个类似 wrap 封装一层 的结构 或 方法：比如现在有 三种 三方组件库 A、B 和 C，他们具体接口不一样但是功能行为类似，比如多种社交媒体平台接口，均有发帖和获取贴等，现在要写个上层使用统一的结构对其操作，就可以加一个 wrap 包装/封装一层，先来个比如 WrapBasic 的抽象类定义通用的必要的接口，再写 AWrap 类继承 WrapBasic 并实现 特定接口 来操作 A 库的接口，其它 B 和 C 同理。现在就有了 AWrap、BWrap 和 CWrap 三种 接口统一的 类 可供操作 三种库。\r\n\r\n\r\n\r\n---\r\n\r\n## 行为模式\r\n\r\n\r\n\r\n### 行为链条(chain) & 迭代器(iterator)\r\n\r\n行为链条(chain)：用于链式的处理逻辑，比如要进行一系列有先后的检查步骤，并要方便的可以在中间增减检查步骤：使用链表结构存储检查函数或者检查抽象类智能指针等，核心就是使用链表的数据结构，如 `std::list`。\r\n\r\n对于链条数据结构的遍历，就需要迭代器如下。\r\n\r\n\r\n\r\n迭代器(iterator)：搞一个对某个数据结构的指定迭代/遍历方法的迭代器类：如对于 二叉树 或 网 的数据结构有 深度优先 和 广度优先 等遍历方法。\r\n\r\n自己实现的数据结构，需要实现基本的方法：增删改查；我再加四个：判排复遍——判空、排序（对于哈希表结构则没有）、复位（清空）和遍历。\r\n\r\n对于遍历，可以两种：\r\n\r\n1. 提供遍历的方法比如 `traverse(const TraverseFunction& traverse_func)`，传入一个遍历的回调函数，如下。还可以增加遍历方法指定的形参。\r\n\r\n   ```c++\r\n   template <typename Key, typename Value>\r\n   void GeneralContainer<Key, Value>::traverse(const TraverseFunction& traverse_func) const\r\n   {\r\n       if(!traverse_func) {\r\n           return;\r\n       }\r\n       std::shared_lock<std::shared_mutex> lock(mMutex);\r\n       for (const auto& it : mList) { // 正序遍历\r\n           traverse_func(it);\r\n       }\r\n   }\r\n   ```\r\n\r\n2. 提供这里所说的迭代器类，不同的迭代器类代表对这个数据结构的不同的遍历方法。比如 std 标准库 容器的:\r\n\r\n   ```c++\r\n   std::vector<int> myVector = {1, 2, 3, 4, 5};\r\n   auto forwardIter = myVector.begin();    // forwardIter 指向 第一个 元素，forwardIter++ 则移动到第二个元素。\r\n   auto backwardIter = myVector.rbegin();  // backwardIter 指向 最后一个 元素，backwardIter++ 则移动到倒数第二个元素。\r\n   ```\r\n\r\n\r\n\r\n### 中介/中央调度(mediator) & 命令(command)\r\n\r\n中介/中央调度(mediator)：多个地方的组件请求执行动作，如果其之间有冲突，比如多个 app 要往 状态栏 弹带优先级的信息，不要各自都直接弹出，因为需要优先级高的始终在最上，因此需要一个中介或者中央调度的组件或模块，多个地方的 app 统一往这个 中介 请求弹信息，由 中介 选择 往信息栏 插入 的位置并插入、或者检查黑名单并忽略等等。\r\n\r\n还有 GUI 程序中的弹窗场景，有的界面可以弹窗，有的界面不允许弹窗，等等还有其它设计情况，因此需要一个中介去统一接受弹窗请求并处理。\r\n\r\n\r\n\r\n命令(command)：思想是，打包一个执行动作以及其传入参数：一个执行动作，如 GUI 程序中 用户点击一个按键，索要执行的一系列程序，封装为一个函数（多种按键有枚举等关系，或者按键为登录等需要传入参数的），需要执行动作时候，打包函数和函数实参 如用 `std::bind()`，放到一个队列中去执行。可以参考 线程池 [progschj/ThreadPool: A simple C++11 Thread Pool implementation](https://github.com/progschj/ThreadPool) 的使用方法。\r\n\r\n如上面的中介就需要类似 命令 的方式，设置接口，处理来自其它组件的 \"命令\"。\r\n\r\n\r\n\r\n### 备忘录(memento) & 访问者(visitor)\r\n\r\n备忘录(memento)：针对需要给组件当前状态整一个快照、用于存留到历史记录中用于后面可能的再现/回放等场景，则给每个组件添加一个 比如 save() 或者 snapshot() 的方法，方法返回 保存了这个组件所有当前信息的（足够回放的）通用 Memento 类或者这个组件的一份克隆，有一个 history 类进行保存并在每次进行快照的时候增长。\r\n\r\n参考 [C++ 备忘录模式讲解和代码示例](https://refactoringguru.cn/design-patterns/memento/cpp/example)。\r\n\r\n\r\n\r\n访问者(visitor)：给需要被访问的类添加一个类似于 Accept(Visitor* visitor) 的函数，传入 visitor 后调用其 visitor->VisitConcreteComponentA(this);，在 VisitConcreteComponentA() 内部访问 当前类实例。\r\n\r\n参考 [C++ 访问者模式讲解和代码示例](https://refactoringguru.cn/design-patterns/visitor/cpp/example)。\r\n\r\n\r\n\r\n### 观察者(observer) / 发布-订阅(publisher-subscribers)\r\n\r\n观察者订阅发布者，发布者执行发布操作（可带参数），即所有订阅这个发布者的观察者的订阅回调函数都会被执行。\r\n\r\n发布-订阅 模式的 C++ 库，如：libsigcplusplus、KDBindings、等 信号槽 类型库，以及 dds 进程间通讯库等。\r\n\r\n\r\n\r\n### 状态设计(state) / 有限状态机(FSM)\r\n\r\n将组件或模块或设备的功能执行划分为一些状态以及状态之间的转移条件，画出状态转移图，即设计为 有限状态机 FSM，进行业务的编程建模。\r\n\r\n简单的可以为 switch-case 语句进行，复杂的、功能多的可以上库，如以下库等：\r\n\r\n- StateMachine [endurodave/StateMachine: State Machine Design in C++](https://github.com/endurodave/StateMachine)，C++，编程风格为 定义 事件 event 下 所有 状态 的 行为，以及状态进入和退出的行为等。\r\n- UML State Machine in C [kiishor/UML-State-Machine-in-C: A minimalist UML State machine framework for finite state machine and hierarchical state machine in C](https://github.com/kiishor/UML-State-Machine-in-C)，C 语言，轻量级（可用于 mcu），表格化构建状态机，支持层级状态机。\r\n- stateMachine [misje/stateMachine: A feature-rich, yet simple finite state machine (FSM) implementation in C](https://github.com/misje/stateMachine)，C 语言，简易简陋超轻量状态机，可用于 mcu。\r\n\r\n\r\n\r\nFPGA 的 IP核 设计中常用 FSM 概念进行建模，有几种不同的写法，Verilog 编码 的例子可见 [HDL-FPGA-study-and-norms/FPGA学习和规范 的参考源码/具体模块/fsm 一段和三段状态机例子 at main · Staok/HDL-FPGA-study-and-norms](https://github.com/Staok/HDL-FPGA-study-and-norms/tree/main/FPGA学习和规范 的参考源码/具体模块/fsm 一段和三段状态机例子)。\r\n\r\n\r\n\r\n### 策略(strategy) & 模板方法(template-method) / 类多态\r\n\r\n策略(strategy)：针对需要对于一定的数据集，使用不同的策略来获取不同的结果。策略可以使用基类和衍生类的多态来实现，这样，创建不同种类的策略类实例并给到执行，就是使用了不同的策略。\r\n\r\n参考 [C++ 策略模式讲解和代码示例](https://refactoringguru.cn/design-patterns/strategy/cpp/example)。\r\n\r\n\r\n\r\n模板方法(template-method)：基类定义执行操作（里面包含多种子操作以及特定顺序）的一个（纯）虚函数，并定义一些子操作（（纯）虚）函数，继承这个基类的多个衍生类中，使用不同的实现重写这些执行操作的函数（不同的子操作、顺序等，以及不同的操作实现），使用类多态，做到创建不同的类实例，用于对数据执行不同的策略操作。\r\n\r\n参考 [C++ 模板方法模式讲解和代码示例](https://refactoringguru.cn/design-patterns/template-method/cpp/example)。\n\nFile v1.0.4:CodingGuidance/TopLevelCodingGuidance.md\n\n## 编码顶层指导\r\n\r\n（引自 [Cpp-Learning/编程经验-规范, 调试、性能和内存检查工具集合.md at main · Staok/Cpp-Learning](https://github.com/Staok/Cpp-Learning/blob/main/编程经验-规范%2C 调试、性能和内存检查工具集合.md)）\r\n\r\n- **层次化，即分清晰的多层**。程序结构分为多个层次，文件夹也按照如此划分，不同模块处于不同功能层。具体问题具体分析。\r\n- **高内聚、低耦合。不宜常修改，应易扩展**。\r\n\r\n  写东西时候先多思考架构。不必一上来就写 等 情况的出现，减少后面 debug 和 重构的时间。\r\n\r\n  - 各部分选择合适的最佳实践和设计模式。\r\n  - 多看一些 **最佳实践的文章和软件工程** 来对自己进行提高。\r\n  - **设计模式**相关综合 [Staok/C-Cpp-design-patterns](https://github.com/Staok/C-Cpp-design-patterns)，具体参考其里面的 `DesignPattern` 文件夹下的文档和代码例子。检查 `CppCodingGuidance/DesignPattern` 若存在则直接用。\r\n\r\n  模块化。模块独立，各端分离，接口分明。每个模块可独立的、动态的、运行时的创建、启、停和释放，程序由多个模块搭建、协作来构成。\r\n\r\n  多写可复用代码。代码具有良好的实用性、通用性，以及安全性（风险规避）。\r\n\r\n  易于扩展和维护。\r\n- **参数化**。\r\n\r\n  几个维度：\r\n\r\n  - 对于模块的编写维度：考虑可通过修改参数来增强模块的适用范围和灵活性。模块编写考虑高复用性和多用性。敏锐的发现和合并公共的处理逻辑为一个通用的中间层，靠传入不同参数进行处理。\r\n  - 对于设备管理维度：数据驱动法，就像 Linux 中的 设备树 作为可方便修改的数据表格，可以冷更新或者热更新到系统、程序中去并生效，不必有改动的时候每次都改代码并重新编译打包和部署。可用 json 等格式 写入 外部配置文件，程序读取并应用。\r\n  - 对于软件整体运行层面：会有很多 settings，用户的或者系统内部的。可用 json 等格式 作为 设置存储文件，程序读写用。\r\n  - 对于不同机型或者运行工况，需要不同套参数，将其 表格化，数据驱动，初始化时候按照机型选取对应的一套参数装填并使用。\r\n- **可读性**。\r\n\r\n  注释：基本要求：英文 Doxygen 注释格式，头文件写几个用例（帮助快速熟悉使用），可直接生成 API 文档的水准。\r\n- 代码格式，以具有良好的可读性为好。整个工程整齐划一，**风格和编程模式具有连贯性**。\r\n\r\n  参考 具体的另外提供的 细节写法格式和规范。\r\n\r\n  （可选，默认不必用）每个项目有统一的 .clang_format 文件，时常 format 下。\r\n- （按需）**跨平台化**。\r\n\r\n  考虑软件的通用性和可移植性，考虑应用层的硬件无关性、跨平台性 / 跨操作系统性（主要是 Win 和 Linux），屏蔽日后换平台的工作量和痛苦。\r\n\r\n  除非特殊要求，否则不假定编写的代码用于特定场景（比如只用于 ROS2 环境 等），要按照实用、通用的准则去写。\r\n\r\n  三方库：尽量选用 Win 和 Linux 都兼容的，流行的、社区活跃的。\r\n- **依赖合理**。\r\n\r\n  按照当前需求和未来规划，合理分配哪些选择使用三方库，哪些选择自己实现。对于当前和未来需求而且功能复杂的，选择三方库（合理选择依赖的三方库，能覆盖需求，功能较丰富，尽量选择支持 Win 和 Linux 跨平台的，拒绝多用、滥用），对于代码量小的可以合理的自己实现。\r\n\r\n  对于 C/C++ 工程，为了不复杂化部署：均使用 cmake，依赖的三方库下载并放到工程目录的 third_party 文件夹里面 来直接通过 cmake 引入来使用。对于 C 除非指定版本 否则至少 C99。对于 C++ 除非约束版本 否则至少 C++17。\r\n\r\n  对于 Python，在工程目录建立 venv 虚拟环境来做，如果依赖特别多而且库有比较大的，则先询问用户是否还要使用 venv 虚拟环境 还是直接全局安装三方库。\r\n- **高性能**。\r\n\r\n  选择运行高效的、高性能的实现方式。若项目是刚开始搭建，而且高性能方案有一定难度，则可以先记录文档，先按照容易实现的（同时也有一定高性能保证的）方案来做，后面有需要则再优化性能。\r\n\r\n  具体内部的算法实现应降低圈复杂度、降低时间复杂度，但如果代价是显著增加空间复杂度则也不必，做好权衡。代码保持简洁易读。\r\n\r\n  也要注意避免头文件的过多嵌套导致编译时长显著增加。\r\n- **健壮性，稳定运行**。\r\n\r\n  风险点提前规避和检查，参考后面 `良好实践经验 / 易错注意 / 开发套路 / 惯例写法` 一节。\r\n- **可测试性**、**易于测试**。\r\n\r\n  保持程序的能控能观性。程序受外部控制接口统一且清晰，程序状态和对外影响、产物等明确。方便测试。\r\n\r\n  代码必须通过测试。具体测试要求参考另外提供的。\r\n\r\n  编码中尽量去掉 编译 warning。\r\n\r\n  Evidence over claims — 验证之后（代码审查、修复、测试 都通过）再声称完成。\n\nFile v1.0.4:skill-card.md\n\n## Description: <br>\nOrchestrator for GitHub Spec-Kit SDD workflow in OpenClaw. Use when starting a new project with spec-driven development, setting up spec-kit toolchain, or running through the full SDD pipeline. <br>\n\nThis skill is ready for commercial/non-commercial use. <br>\n\n## Publisher: <br>\n[staok](https://clawhub.ai/user/staok) <br>\n\n### License/Terms of Use: <br>\nMIT-0 <br>\n\n\n## Use Case: <br>\nDevelopers and engineering teams use this skill to initialize and run a Spec-Kit spec-driven development workflow, including project documentation, feature specification, planning, task breakdown, implementation orchestration, review, testing, and delivery checks. <br>\n\n### Deployment Geography for Use: <br>\nGlobal <br>\n\n## Known Risks and Mitigations: <br>\nRisk: The setup workflow can install Spec-Kit tooling and download auxiliary skills from GitHub, which may be unsuitable for strict offline or reproducible environments. <br>\nMitigation: Review setup.sh before use, prefer --check-only for assessment, and approve network downloads or dependency installation only in environments where current upstream content is acceptable. <br>\nRisk: The workflow can create or edit project documentation, specification files, source code, tests, and git commits. <br>\nMitigation: Use the skill in low-risk development scenarios, keep user approval gates for setup and git management, and review generated plans, code, tests, and commits before relying on them. <br>\nRisk: The artifact warns against using agents in critical-path, legacy, or security-sensitive code. <br>\nMitigation: Limit use to prototyping, search, documentation, and other low-risk workflows unless a human reviewer explicitly approves a broader scope. <br>\n\n\n## Reference(s): <br>\n- [ClawHub release page](https://clawhub.ai/staok/spec-kit-coding) <br>\n- [Source repository declared by artifact](https://github.com/Staok/spec-kit-coding-skill) <br>\n- [GitHub Spec-Kit](https://github.com/github/spec-kit) <br>\n- [Top-level coding guidance](CodingGuidance/TopLevelCodingGuidance.md) <br>\n- [C++ coding style guidance](CodingGuidance/CppCodingStyle.md) <br>\n\n\n## Skill Output: <br>\n**Output Type(s):** [guidance, markdown, code, shell commands, configuration] <br>\n**Output Format:** [Markdown with inline shell commands, generated or edited project files, and structured status summaries] <br>\n**Output Parameters:** [1D] <br>\n**Other Properties Related to Output:** [May produce project specifications, plans, task lists, README and DEVLOG updates, review findings, test guidance, commits when git management is enabled, and setup commands that require user approval.] <br>\n\n## Skill Version(s): <br>\n1.0.4 (source: server release evidence) <br>\n\n## Ethical Considerations: <br>\nUsers should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment. <br>\n\nFile v1.0.4:TODO.txt\n\nECC的AgentShield适合放在什么阶段进行？也下载，相应的更新脚本和skill原文。\r\n新加一个 程序性能优化 流程，看看怎么弄好。\r\nmattpocock-improve-codebase-architecture 在什么阶段进行比较好？在 程序性能优化 流程？\n\nArchive v1.0.3: 25 files, 65002 bytes\n\nFiles: CodingGuidance/CppCodingStyle.md (28612b), CodingGuidance/CppEngineeringFrameworkReference/AppContext.cpp (11115b), CodingGuidance/CppEngineeringFrameworkReference/AppContext.h (2950b), CodingGuidance/CppEngineeringFrameworkReference/CppModuleInitCaseExample.cpp (8754b), CodingGuidance/CppEngineeringFrameworkReference/CppModuleRunCaseExample.cpp (9280b), CodingGuidance/DesignPattern/Builder/ProductBuilder.h (9979b), CodingGuidance/DesignPattern/DesignPattern.md (10012b), CodingGuidance/DesignPattern/Pimpl/MyInterface.h (1369b), CodingGuidance/DesignPattern/Pimpl/MyInterfaceImpl.cpp (844b), CodingGuidance/DesignPattern/PImpl2/inc_private/GenericModuleImpl.h (1715b), CodingGuidance/DesignPattern/PImpl2/include/GenericModule.h (532b), CodingGuidance/DesignPattern/PImpl2/src/GenericModule.cpp (161b), CodingGuidance/DesignPattern/PImpl2/src/GenericModuleImpl.cpp (3060b), CodingGuidance/DesignPattern/RAII/RAII.cpp (6617b), CodingGuidance/DesignPattern/RAII/RAII.h (3568b), CodingGuidance/DesignPattern/Singleton/ClassFactory_Example.cpp (3797b), CodingGuidance/DesignPattern/Singleton/ClassFactory.hpp (7029b), CodingGuidance/DesignPattern/Singleton/Singleton.cpp (420b), CodingGuidance/DesignPattern/Singleton/Singleton.h (1307b), CodingGuidance/TopLevelCodingGuidance.md (5334b), setup.sh (26266b), skill-card.md (2228b), SKILL.md (24913b), TODO.txt (274b), _meta.json (134b)\n\nFile v1.0.3:SKILL.md\n\n---\nname: spec-kit-coding\ndescription: \"Orchestrator for GitHub Spec-Kit SDD workflow in OpenClaw. Use when starting a new project with spec-driven development, setting up spec-kit toolchain, or running through the full SDD pipeline.\"\n---\n# Spec-Kit Coding -- OpenClaw Orchestrator\n\nOrchestrates the complete Spec-Driven Development workflow via\n[github/spec-kit](https://github.com/github/spec-kit).\n\nCovers: Engineering Implementation. Does not cover\nrequirements discovery, operations/deployment, or cross-domain (SRE, security, etc.).\n\n---\n\n## HARD CONSTRAINTS\n\nREAD FIRST, APPLY ALWAYS.\n\nThese constraints are non-negotiable. Do NOT require the user to repeat them.\n\n### Security\n\n- Never transmit sensitive information to the network.\n- Before any external action (API calls, sending data outside local machine),\n   explain and ask for approval.\n- Do not install third-party libraries or modify system config without\n   asking first. If a new dependency is needed, explain why and get approval.\n- Prefer reusing existing, proven, popular third-party solutions. Avoid\n   reinventing the wheel. Keep tool usage simple and lean. Minimize dependency footprint.\n\n### Feature Management / Quick Reference\n\n- Starting a project, follow section: WORKFLOW, from STEP 1 to STEP 7.\n- Add a new feature or modify a existing feature:\n   - \"add\" / \"new\" / behavior no spec covers -> new feature -> section: STEP 5: Spec-Kit Phases / New Feature.\n   - \"change\" / \"modify\" / changing existing behavior -> modify existing -> section: Feature Modification Entry Point.\n- Each `/speckit-specify` invocation creates exactly ONE feature. If the user\n   describes a messy, multi-concern requirement, split it first:\n   - List each proposed feature with a short name and one-line summary.\n   - Note dependencies between features.\n   - Ask user to confirm the split before proceeding.\n- When uncertain whether the user wants a new feature or a modification to an\n   existing one, ASK. Do not guess. Present your organized analysis. Show several or both options concisely.\n- For projects that have already been delivered or already exist, if a bug is reported, refer to section: Bug Fix Entry Point.\n\n### Communication\n\n- Collect all unclear points first, then ask once. Avoid back-and-forth.\n- Be efficient and concise. Output only necessary information.\n- Remind the user how to think about the problem better; help improve prompt\n  quality over time.\n\n### Documentation-First\n\n- For spec/plan/tasks .etc phase docs (spec.md, plan.md, tasks.md): these are created via the speckit-* phases prior to implementation.\n- For DEVLOG.md: update per implementation batch, and after every phase\n  completion. DEVLOG must always reflect the latest state.\n- For README.md Architecture: seed during plan phase. Update as a final step\n  after all implementation completes (Step 5 and Step 6.3).\n- Never reverse the order: docs first, code second.\n\n### Git Management\n\n- During project init (Step 1), ASK whether to enable git. Record the answer.\n- If enabled: `git init`, `.gitignore`, initial commit. Then commit after\n  each phase completion and each implementation batch.\n- If disabled: do not create or manage a git repository.\n- The user may enable git at any later point. Once enabled, keep it on.\n\n### Context Isolation\n\n- \"Implement\" (The whole Step 6 and Step 6.X) MUST run in fresh isolated sub-agent sessions.\n  Never run implement in a session that has accumulated multiple prior phases.\n- If tasks.md has more than ~15 items, split implementation into batches.\n  Each batch = fresh sub-agent session.\n- Better to over-split than to produce garbage from context saturation.\n\n### Session Interrupt\n\n- If a session is interrupted mid-phase, do NOT assume which phase to restart\n  from. Ask the user: \"Restart from [interrupted-phase] or from\n  [previous-completed-phase]?\" If user is unsure, default to re-running the\n  interrupted phase from the start.\n\n---\n\n## WORKFLOW\n\n### STEP 0: Prerequisites (one-time per machine)\n\nRun: `bash ~/.openclaw/workspace/skills/spec-kit-coding/setup.sh`\n\nAsk user for confirmation before first run. This installs `specify` CLI,\nspeckit-* skills, and auxiliary skills. Do NOT proceed until it reports\nall dependencies ready.\n\nOptions: `--check-only` (check without install), `--force` (force reinstall).\n\n### STEP 1: Project Init\n\n1. Ask user for project path (default: current directory).\n2. Ask: \"Enable git management?\"\n\nIn project directory from now on:\n\n1. Run: `specify init --here --integration claude --force --ignore-agent-tools --script sh --no-git`\n2. Clean up: `rm -rf .claude CLAUDE.md` (keep `.specify/`).\n3. Verify: `.specify/` exists by run  `test -d .specify && echo \"OK: .specify/ exists\"`, and skills .etc are present by run `bash ~/.openclaw/workspace/skills/spec-kit-coding/setup.sh --check-only`.\n4. Follow the Git management section to do.\n\n### STEP 2: Create Project Docs\n\nCreate `README.md` and `DEVLOG.md`. Templates in Appendix A.\n\nKey rules:\n\n- README.md Architecture section: seed during plan phase (Step 5).\n  Update as final (Step 6.3).\n- DEVLOG.md: per-feature tracking. Each feature has its own phase history\n  block. The Summary table is regenerated from Feature Detail blocks after\n  every update -- do NOT manually edit the Summary section.\n\nGATE: Confirm with user that docs look correct.\n\n### STEP 3: Coding Standards and UI Skill Check\n\n#### Coding Standards (Checkpoint A -- before constitution)\n\nCollect BOTH architecture principles AND coding style conventions in ONE prompt:\n\n1. If user already provided documents/URLs/inline text earlier in the\n   conversation, use them directly. Do NOT re-ask.\n2. If not provided: detect languages from README.md SPEC Overview, then ask:\n\n> Use built-in coding standards as constitution reference?\n>\n> Architecture & Design:\n> `spec-kit-coding/CodingGuidance/TopLevelCodingGuidance.md`\n>\n> [Per-language coding style skills listed here based on detected languages]\n>\n> Coding Style (C++): `spec-kit-coding/CodingGuidance/CppCodingStyle.md`,\n> `spec-kit-coding/CodingGuidance/CppEngineeringFrameworkReference/`,\n> `spec-kit-coding/CodingGuidance/DesignPattern/`,\n> `external-skills/ecc-cpp-coding-standards`\n> [Similar for other languages, `spec-kit-coding/external-skills/ecc-*`]\n>\n> Language-agnostic: `spec-kit-coding/external-skills/ecc-coding-standards`\n\n- \"Yes\": include reference paths in constitution prompt, just ask to directly write the reference paths in constitution.md but Do NOT copy or re-write  the reference files content.\n- \"No\": generate concise generic guidance inline.\n- \"Partial\": respect the user's selection.\n\nRules:\n\n- Once confirmed, standards persist across all features in the project.\n- Do NOT modify `CodingGuidance/`. Read-only except during skill updates.\n\n#### UI Skill Check (Checkpoint B -- before plan, after constitution)\n\nIf the project involves UI, ask ONCE:\n\n> This project involves UI. Available frontend skills:\n> `spec-kit-coding/external-skills/ui-ux-pro-max-skill` (design system), or `spec-kit-coding/external-skills/ecc-*`. Load relevant ones for plan/implement?\n\n- \"yes\": sub-agents read chosen UI skills during plan and implement.\n- \"no\": skip.\n\n### STEP 4: Grill Alignment\n\nBefore writing specs, align the agent's understanding with the project's domain.\nUse `spec-kit-coding/external-skills/mattpocock-grill-with-docs`.\n\nOutputs:\n\n- CONTEXT.md at project root: Domain glossary. Devoid of implementation\n  details — it is a glossary, not a spec or scratch pad.\n- docs/adr/: Architecture Decision Records (sparingly).\n\nGATE: Confirm with user that CONTEXT.md accurately captures the domain\nlanguage and any created ADRs are correct.\n\n### STEP 5: Spec-Kit Phases / New Feature\n\nTwo paths available. Choose per-feature based on requirement clarity.\n\n**Production path (8 Phases -- for complex/ambiguous features):**\n\n```\nconstitution -> specify -> clarify -> checklist -> plan -> tasks -> analyze -> implement\n```\n\n**Lean path (6 Phases -- for simple/well-understood features):**\n\n```\nconstitution -> specify -> clarify -> plan -> tasks -> implement\n```\n\nEach phase apply the corresponding skill `spec-kit-coding/external-skills/speckit-*`.\n\nRules:\n\n- `constitution` runs once at project start. Subsequent features reuse it.\n- Use `CONTEXT.md` terminology in `specify`, `plan`, `tasks`.\n- `clarify` is ALWAYS run after `specify` (both paths). It catches ambiguities.\n- Skip `checklist` and `analyze` on lean path.\n- `speckit-specify` may generate an internal validation checklist as part of\n  its own flow. This is NOT the standalone `speckit-checklist` step.\n\nWhen to re-run constitution, only for:\n\n- Adding a new programming language not previously covered\n- Architecture-level changes that override existing principles\n\nIf git enabled: commit after every spec-Kit phases.\n\n### STEP 6: Implementation\n\nMUST run in fresh isolated sessions. Use the spawn template below.\n\n1. If tasks.md <= ~15 items and estimated code-gen calls <= ~12:\n   single sub-agent.\n2. Otherwise: split into batches. Each batch = fresh sub-agent session.\n3. After each batch: sub-agent updates DEVLOG.md. If git enabled: commit.\n4. Orchestrator tracks remaining tasks, spawns next batch.\n\n#### Spawn Template\n\nCopy this verbatim, filling in placeholders from the table:\n\n```\nYou are <ROLE> for feature <NNN>-<name> in project at <project-dir>.\n\nCONTEXT BOUNDARY: You are a fresh isolated session. Focus EXCLUSIVELY on\nfeature <NNN>-<name>. The documents below are your sole source of truth.\nDo NOT mix in details from other features, projects, or earlier batches.\n\nBefore <ACTION>, read these documents in order:\n1. <project-dir>/CONTEXT.md (Domain glossary — if it exists)\n2. <project-dir>/.specify/memory/constitution.md\n3. <project-dir>/specs/<NNN>-<name>/* (All documents related to this feature)\n4. <project-dir>/docs/adr/ (Architecture Decision Records — if any exist)\n5. <project-dir>/README.md (Architecture section)\n\n<ROLE_SPECIFIC_INSTRUCTIONS>\n\nAfter completing your work:\n- Update <project-dir>/DEVLOG.md\n- If git management is enabled: git commit all changes\n- Report back using the structured format below\n```\n\n| Placeholder                | Implement                                                    | Code Review (Step 6.1)                                       | Test (Step 6.2)                                              |\n| -------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ |\n| ROLE                       | implementing                                                 | performing a CODE REVIEW for                                 | performing TEST DEVELOPMENT for                              |\n| ACTION                     | writing any code                                             | reviewing                                                    | writing any test code                                        |\n| ROLE_SPECIFIC_INSTRUCTIONS | Implement tasks M-N from tasks.md per speckit-implement skill. If plan is infeasible or conflicts with spec.md, STOP and report to orchestrator -- do NOT proceed. | Apply `spec-kit-coding/external-skills/superpowers-requesting-code-review`. **Checklist: (1) Practicality & Generality (2) Risk (memory, threads, deadlock, exception , errors, UB, security) (3) Optimization (algorithmic, allocations, copies, deps) (4) Architecture Alignment (5) Coding Standards per constitution.md.** Output: severity (Critical/Important/Minor/Suggestion) with file:line, description, recommendation. Overall: Ready/Needs Fixes/Major Rework. | Test environment:`/tmp/<project-name>-test/`. Framework by language (gtest/C++, pytest/Python, cargo/Rust, Jest/JS-TS, go test/Go .etc). **Ask the user for testing strategy: Module-level (cover all public APIs, normal/boundary/error inputs and thread safety(if applicable, concurrent construction/destruction and API calls from multiple threads), key API call sequences); Integration (Module-to-module interaction tests, Full application functional flow tests), that validate that all business logic behaves as expected; Coverage (optional): language-appropriate tools(gcov+lcov (C++), pytest-cov(python), cargo-tarpaulin (Rust), Jest --coverage (JS/TS), or language-equivalent).** When tests fail: apply BOTH skills — `spec-kit-coding/external-skills/mattpocock-diagnose` (build feedback loop first → 3-5 falsifiable hypotheses → instrument → fix → regression-test) AND `spec-kit-coding/external-skills/superpowers-systematic-debugging` (7-layer diagnostic model: L1 symptom → L2 logic → L3 system → L4 architecture → L5 cross-system → L6 platform → L7 spec gap). If 3+ fix attempts fail: question architecture, report to orchestrator. If ALL pass: proceed to STEP 6.3: Final Review. |\n\n#### Sub-Agent Report Format\n\nEvery sub-agent MUST end with:\n\n```\n## SUB-AGENT REPORT\n- Role: <implement | code-review | test>\n- Feature: <NNN>-<name>\n- Status: <SUCCESS | PARTIAL | BLOCKED | FAILED>\n- Tasks Completed: <list or \"all\">\n- Tasks Remaining: <list or \"none\">\n- Issues Found: <count, severity breakdown if review/test>\n- Blockers: <description or \"none\">\n- Files Modified: <list>\n- Summary: <1-2 sentences>\n```\n\nOrchestrator uses Status:\n\n- SUCCESS -> proceed to next gate\n- PARTIAL -> spawn continuation batch\n- BLOCKED -> escalate to user\n- FAILED -> diagnose; retry, rollback, or escalate\n\nGATE: After all batches report SUCCESS, confirm with user before proceeding\nto Code Review.\n\n#### STEP 6.1: Code Review\n\nAfter code implementation.\n\nCode review and fix. Ready the project for Testing.\n\nSpawn a fresh isolated session using the spawn template (Step 6) with the\n\"Code Review (Step 6.1)\" column values.\n\nAfter review:\n\n1. Present findings to user.\n\n2. Ask: \"Which review findings should be addressed?\"\n\n3. Apply ONLY user-approved fixes.\n\n4. Re-run review on changed files AND related files.\n\n5. If new issues: repeat from step 1. Limit: 3 review-fix cycles total.\n\n6. If issues persist after 3 cycles: question architecture, report to orchestrator,\n\n   may ask user to record them to README.md Known Limitations / Issues section.\n\n#### STEP 6.2: Testing\n\nCode testing and debugging and fix. Ready the project for Final Review.\n\nSpawn a fresh isolated session using the spawn template (Step 6) with the\n\"Test (Step 6.2)\" column values.\n\n#### STEP 6.3: Final Review\n\nAfter STEP 6.2: Testing.\n\nOptimization & Doc Sync + Complexity Audit. Ready the project for STEP 7:\nDelivery Check.\n\nPerform these actions in order. Do NOT skip any.\n\n1. Re-read all modified source files for the feature.\n2. Check for:\n\n   1. Algorithmic improvements (better complexity).\n   2. Redundant allocations or copies.\n   3. Unnecessary dependencies.\n   4. Dead code or unreachable branches.\n   5. .etc\n3. Complexity Delta. Inspect the actual diff and report:\n\n   ```text\n   Complexity Delta:\n   - Files over 1200 lines:\n   - Files newly crossing 1200 lines:\n   - Largest touched file delta:\n   - Largest touched function/block:\n   - New branches/fallbacks/adapters:\n   - Retired branches/fallbacks/adapters:\n   - Net entropy: decreased | stable | increased-with-justification\n   - Required follow-up:\n\n   Complexity Governance Suggestion:\n   - Recommendation: none | monitor | schedule-refactor | extract helper | split owner | open follow-up\n   - Why:\n   - Suggested scope:\n   - Timing:\n   ```\n\n   Skip for trivial changes (tests-only, generated, formatting, etc.).\n\n4. Record findings in README.md -> Features Plan / TODOs (NOT as TODO\n   comments in source). Format:\n   `- [ ] [category] description (file: path:line-range)`\n   Categories: optimization, robustness, clarity, security, perf.\n5. Present candidates to user:\n\n   > Optimization candidates found:\n   > **Implement now (low risk, high impact):**\n   >\n   > - [item]\n   >   **Defer (tracked in README):**\n   > - [item]\n   >   Which \"implement now\" items should I apply?\n   >\n6. If user approves code changes:\n   a. Apply changes.\n   b. Full clean rebuild.\n   c. Run ALL tests.\n   d. If any test fails -> return to STEP 6.2: Testing.\n   e. If all pass -> continue.\n   f. If 3 cycles of regression->test->debug fail to converge: escalate to user.\n7. Update README.md Architecture section to reflect what was actually built.\n8. Update DEVLOG.md -- verify all phases and dates are current.\n9. If git enabled: commit.\n\n### STEP 7: Delivery Check\n\nRun through this checklist. Every item must be checked:\n\n- [ ] All required speckit-* phases completed or skipped (lean skips\n  checklist, analyze -- this is expected).\n\n- [ ] STEP 4 Grill Alignment completed (CONTEXT.md + any ADRs created).\n  \n- [ ] Code review(If asked) completed and approved fixes applied.\n\n- [ ] All tests pass.\n\n- [ ] Source tree is clean (no temp files, no build artifacts in source dirs).\n\n- [ ] Complexity Delta checked (Step 6.3 item 3). Net entropy not increased\n  without justification.\n\n- [ ] Whole README.md is up-to-date.\n\n  Especially: README.md Architecture section is up-to-date. Optimization findings tracked in README.md Features Plan / TODOs section.\n\n- [ ] DEVLOG.md reflects all completed phases.\n\n- [ ] All hard constraints from section HARD CONSTRAINTS respected.\n\n- [ ] If git enabled: all changes committed.\n\n- [ ] Evidence Card. Fill out ONE evidence card covering all verification:\n\n  ```text\n  Evidence Card:\n  - Command / Check: <exact verification command(s) run>\n  - Exit Status: <exit code(s)>\n  - Covered: <what was verified>\n  - Not Covered: <what was NOT verified>\n  - Residual Risk: <remaining risk>\n  - Confidence: A | B | C\n  ```\n\n  Confidence grades:\n  - A: Direct verification + regression, no unknowns\n  - B: Direct verification, bounded residual risk\n  - C: Partial verification only, not closed — do NOT claim done\n\n  A claim of completion without evidence is NOT acceptable. Words like\n  \"should\", \"probably\", \"seems to\" are Red Flags — STOP and verify.\n\nGATE: Present delivery summary to user, including the filled Evidence Card.\n\n### Feature Modification Entry Point\n\nWhen the user wants to modify an existing feature, route by change type:\n\n| Tier | Type               | Examples                                        | Route                                                        |\n| ---- | ------------------ | ----------------------------------------------- | ------------------------------------------------------------ |\n| 1    | Parameter/Constant | timeout 30s->60s, max retries 3->5              | You can directly edit spec.md, then continue spec-Kit phases: clarify -> plan -> tasks -> implement -> then go section: STEP 6.2: Testing |\n| 2    | Ambiguity/Gap      | \"handle errors\" unspecified, missing edge cases | clarify -> plan -> tasks -> implement -> then go section: STEP 6.1 to 6.3 |\n| 3    | Substantive        | new OAuth login, REST->WebSocket, new roles     | Re-run specify -> full pipeline -> then go section: STEP 6.1 to 6.3 |\n\nDEVLOG records a new phase cycle regardless of tier.\n\nAll path above at end must go section: STEP 7: Delivery Check.\n\n### Bug Fix Entry Point\n\nWhen user reports a bug:\n\n1. Read the feature's spec.md, plan.md, and relevant source files.\n2. Determine if the bug is:\n   - Spec gap (behavior not defined) -> clarify -> plan -> implement.\n   - Implementation error (code disagrees with spec) -> fix directly.\n3. Then go section: STEP 6.2: Testing\n4. Go section: STEP 7: Delivery Check.\n\n---\n\n## TROUBLESHOOTING\n\n| Problem                          | Fix                                     |\n| -------------------------------- | --------------------------------------- |\n| `specify: command not found`   | Install via uv or pipx (Step 0)         |\n| Skills not in workspace          | Run `bash setup.sh` (Step 0)          |\n| `.specify/` missing in project | Re-run Step 1                           |\n| Scripts not executable           | `chmod +x .specify/scripts/bash/*.sh` |\n| Task references stale spec       | Re-run the relevant speckit-* phase     |\n\n---\n\n## APPENDIX A: README.md and DEVLOG.md Templates\n\n### README.md Template\n\nCreate `<project-dir>/README.md`:\n\n````markdown\n# <Project Name>\n\n## Project Introduction\n\n<One-paragraph overview.>\n\n## Key Features\n\n<!-- Completed features (use `- ` list, NOT checkboxes).\n     This section describes what the project DOES today. -->\n- <Feature 1>\n- <Feature 2>\n\n## SPEC Overview\n\n- Type: <CLI tool / TUI / GUI / library / web service / ...>\n- Language(s) / Version(s): <e.g. C++20, Python 3.11; for mixed projects e.g. C++20 (backend) + Python 3.11 (tooling)>\n- Build: <CMake, cargo, pip, ...>\n- Dependencies: <key deps>\n- License: <MIT, Apache-2.0, ...>\n\n## Local Build\n\n### Prerequisites\n- <...>\n\n### Build Commands\n```bash\n# Debug\n<...>\n# Release\n<...>\n```\n\n## Usage Examples\n\n```bash\n# Basic usage\n<...>\n# With options\n<...>\n```\n\n## Architecture\n\n**Living document.** Seeded during plan phase (Step 5). Updated after all\nimplementation completes (Step 6.3).\n\n<Architecture diagram (ASCII art preferred) and description.\nInclude: high-level component layout, platform abstraction (if cross-platform),\ndata model summary, and key design decisions.>\n\n### Platform / Component Details\n\n<Break down key subsystems with enough detail that a new developer\ncan understand the layout without reading all source code.>\n\n## Known Limitations / Issues\n\n- <Limitation 1: what it is and why>\n- <Limitation 2>\n\n## Features Plan / TODOs\n\n<!-- Planned/upcoming features (use `- [ ]` checkboxes).\n     This section describes what the project WILL DO in the future.\n     Move items to Key Features (as `- ` bullets) when implemented. -->\n- [ ] <Planned feature or pending task>\n- [ ] ...\n\n## Spec-Driven Development Workflow And More\n\nThis project uses [github/spec-kit](https://github.com/github/spec-kit)\norchestrated via the spec-kit-coding OpenClaw skill. Progress tracked in\nDEVLOG.md.\n````\n\n### DEVLOG.md Template\n\nCreate `<project-dir>/DEVLOG.md` with **per-feature progress tracking**.\n\nAll dates in DEVLOG.md MUST use `YYYY-MM-DD HH:MM` format.\n\nFeature name is `<NNN>-<feature-name>` that the dir name from `<project-dir>/specs` dir.\n\n````markdown\n# Development Log -- <Project Name>\n\n## Feature Progress Summary\n\n| Feature | Specify | Clarify | Checklist | Plan | Tasks | Analyze | Implement | Updated |\n|---------|---------|---------|-----------|------|-------|---------|-----------|---------|\n| -- | -- | -- | -- | -- | -- | -- | -- | -- |\n\nLegend: [ ] pending | [~] in-progress | [√] complete | [>] skipped | [!] blocked\n\n## Feature Details\n\n<!-- FEATURE BLOCK START -->\n### <NNN>-<feature-name>\n\n- Description: <one-line summary>\n- Current Phase: <phase>\n- Last Updated: <date>\n\n**Phase History**:\n\n| Phase | Date | Status | Notes |\n|-------|------|--------|-------|\n| speckit-specify | | [ ] | |\n| speckit-clarify | | [ ] | |\n| speckit-checklist | | [ ] | |\n| speckit-plan | | [ ] | |\n| speckit-tasks | | [ ] | |\n| speckit-analyze | | [ ] | |\n| speckit-implement | | [ ] | |\n<!-- FEATURE BLOCK END -->\n\n## Global Notes\n\n- Constitution: <date or pending>\n- Project init: <date>\n- <Cross-feature decisions>\n````\n\nRules:\n\n- After each phase completes: update the Feature Detail block (Phase History\n  table + Current Phase + Last Updated).\n- After updating any Feature Detail: regenerate the Summary table from all\n  Feature Detail blocks. Never manually edit the Summary section.\n- When re-entering a feature (modification): add a new row to its Phase History.\n- If starting a new feature before finishing a previous one: per-feature\n  tracking keeps them independent.\n\n---\n\n## APPENDIX B: Speckit Skills Reference\n\nThese are installed to `external-skills/` by `setup.sh` (Step 0):\n\n| Skill                | Purpose                                | When                           |\n| -------------------- | -------------------------------------- | ------------------------------ |\n| speckit-constitution | Project principles & governance        | Once per project               |\n| speckit-specify      | Feature specification (what & why)     | Every new feature              |\n| speckit-clarify      | Quality gate -- catch spec ambiguities | After specify, always          |\n| speckit-checklist    | Requirement quality checklist          | Production path, after clarify |\n| speckit-plan         | Technical implementation plan          | After clarify/checklist        |\n| speckit-tasks        | Actionable, dependency-ordered tasks   | After plan                     |\n| speckit-analyze      | Cross-artifact consistency analysis    | Production path, after tasks   |\n| speckit-implement    | Execute tasks (batched)                | After analyze (or tasks, lean) |\n\n## APPENDIX C: Auxiliary Skills Reference\n\nAll under `external-skills/`. Invoked as needed in review/test/ui .etc.\nSee `external-skills/MANIFEST.md` for complete listing.\n\nFile v1.0.3:_meta.json\n\n{\n  \"ownerId\": \"kn7200kmgerbhf59xrmr2sbm9585gczq\",\n  \"slug\": \"spec-kit-coding\",\n  \"version\": \"1.0.3\",\n  \"publishedAt\": 1780133034687\n}\n\nFile v1.0.3:CodingGuidance/CppCodingStyle.md\n\n## 良好实践经验 / 易错注意 / 开发套路 / 惯例写法\r\n\r\n（引自 [Cpp-Learning/编程经验-规范, 调试、性能和内存检查工具集合.md at main · Staok/Cpp-Learning](https://github.com/Staok/Cpp-Learning/blob/main/编程经验-规范%2C 调试、性能和内存检查工具集合.md)）\r\n\r\n\r\n\r\n### 模块 和 类\r\n\r\n一个类的所有 对外 API，尽量都做到 线程安全的，除非需要特殊考虑或者特殊说明。锁的范围尽量小，注意内部带锁的多个函数的嵌套调用的情况。\r\n\r\n\r\n\r\n对于启动 app process 的 各个模块 初始化、反初始化、信号 与 未catch异常管理 等等，参考这个的做法：`CppEngineeringFrameworkReference/AppContext.h`。\r\n\r\n\r\n\r\n对于每个具体干活的、拆分好的执行业务功能的模块用一个类。每个类的具体的统一做法如下：\r\n\r\n- 视需求，有的可以是可以创建多个，有的是单例模式。\r\n\r\n- 对于完成业务/任务的类，不需要多例，就可以写为单例，对于单例类，写上不可拷贝或移动的构造，以及不可赋值操作的拷贝和移动构造。\r\n\r\n- 如果是模块作用的类：\r\n\r\n  对于类在启动其作用的时候，如果没有一直循环运行的任务（比如在一个线程里面或者 启动函数里面的 `while(true){...}`）则使用 init 的情况；相反，则使用 run 的情况。下面给出参考。\r\n\r\n  对于 init 的情况，具体参考这个例子来写类的框架：`CppEngineeringFrameworkReference/CppModu\n\nArchive v1.0.2: 24 files, 63695 bytes\n\nFiles: CodingGuidance/CppCodingStyle.md (28612b), CodingGuidance/CppEngineeringFrameworkReference/AppContext.cpp (11115b), CodingGuidance/CppEngineeringFrameworkReference/AppContext.h (2950b), CodingGuidance/CppEngineeringFrameworkReference/CppModuleInitCaseExample.cpp (8754b), CodingGuidance/CppEngineeringFrameworkReference/CppModuleRunCaseExample.cpp (9280b), CodingGuidance/DesignPattern/Builder/ProductBuilder.h (9979b), CodingGuidance/DesignPattern/DesignPattern.md (10012b), CodingGuidance/DesignPattern/Pimpl/MyInterface.h (1369b), CodingGuidance/DesignPattern/Pimpl/MyInterfaceImpl.cpp (844b), CodingGuidance/DesignPattern/PImpl2/inc_private/GenericModuleImpl.h (1715b), CodingGuidance/DesignPattern/PImpl2/include/GenericModule.h (532b), CodingGuidance/DesignPattern/PImpl2/src/GenericModule.cpp (161b), CodingGuidance/DesignPattern/PImpl2/src/GenericModuleImpl.cpp (3060b), CodingGuidance/DesignPattern/RAII/RAII.cpp (6617b), CodingGuidance/DesignPattern/RAII/RAII.h (3568b), CodingGuidance/DesignPattern/Singleton/ClassFactory_Example.cpp (3797b), CodingGuidance/DesignPattern/Singleton/ClassFactory.hpp (7029b), CodingGuidance/DesignPattern/Singleton/Singleton.cpp (420b), CodingGuidance/DesignPattern/Singleton/Singleton.h (1307b), CodingGuidance/TopLevelCodingGuidance.md (5334b), setup.sh (23339b), skill-card.md (2842b), SKILL.md (28198b), _meta.json (134b)\n\nArchive v1.0.1: 25 files, 71812 bytes\n\nFiles: CodingGuidance/CppCodingStyle.md (29012b), CodingGuidance/CppEngineeringFrameworkReference/AppContext.cpp (11115b), CodingGuidance/CppEngineeringFrameworkReference/AppContext.h (2950b), CodingGuidance/CppEngineeringFrameworkReference/CppModuleInitCaseExample.cpp (8754b), CodingGuidance/CppEngineeringFrameworkReference/CppModuleRunCaseExample.cpp (9280b), CodingGuidance/DesignPattern/Builder/ProductBuilder.h (9979b), CodingGuidance/DesignPattern/DesignPattern.md (10012b), CodingGuidance/DesignPattern/Pimpl/MyInterface.h (1369b), CodingGuidance/DesignPattern/Pimpl/MyInterfaceImpl.cpp (844b), CodingGuidance/DesignPattern/PImpl2/inc_private/GenericModuleImpl.h (1715b), CodingGuidance/DesignPattern/PImpl2/include/GenericModule.h (532b), CodingGuidance/DesignPattern/PImpl2/src/GenericModule.cpp (161b), CodingGuidance/DesignPattern/PImpl2/src/GenericModuleImpl.cpp (3060b), CodingGuidance/DesignPattern/RAII/RAII.cpp (6617b), CodingGuidance/DesignPattern/RAII/RAII.h (3568b), CodingGuidance/DesignPattern/Singleton/ClassFactory_Example.cpp (3797b), CodingGuidance/DesignPattern/Singleton/ClassFactory.hpp (7029b), CodingGuidance/DesignPattern/Singleton/Singleton.cpp (420b), CodingGuidance/DesignPattern/Singleton/Singleton.h (1307b), CodingGuidance/TopLevelCodingGuidance.md (5334b), setup.sh (23074b), skill-card.md (2748b), SKILL.md (48443b), TODO.txt (304b), _meta.json (134b)\n\nArchive v1.0.0: 23 files, 70075 bytes\n\nFiles: CodingGuidance/CppCodingStyle.md (29012b), CodingGuidance/CppEngineeringFrameworkReference/AppContext.cpp (11115b), CodingGuidance/CppEngineeringFrameworkReference/AppContext.h (2950b), CodingGuidance/CppEngineeringFrameworkReference/CppModuleInitCaseExample.cpp (8754b), CodingGuidance/CppEngineeringFrameworkReference/CppModuleRunCaseExample.cpp (9280b), CodingGuidance/DesignPattern/Builder/ProductBuilder.h (9979b), CodingGuidance/DesignPattern/DesignPattern.md (10012b), CodingGuidance/DesignPattern/Pimpl/MyInterface.h (1369b), CodingGuidance/DesignPattern/Pimpl/MyInterfaceImpl.cpp (844b), CodingGuidance/DesignPattern/PImpl2/inc_private/GenericModuleImpl.h (1715b), CodingGuidance/DesignPattern/PImpl2/include/GenericModule.h (532b), CodingGuidance/DesignPattern/PImpl2/src/GenericModule.cpp (161b), CodingGuidance/DesignPattern/PImpl2/src/GenericModuleImpl.cpp (3060b), CodingGuidance/DesignPattern/RAII/RAII.cpp (6617b), CodingGuidance/DesignPattern/RAII/RAII.h (3568b), CodingGuidance/DesignPattern/Singleton/ClassFactory_Example.cpp (3797b), CodingGuidance/DesignPattern/Singleton/ClassFactory.hpp (7029b), CodingGuidance/DesignPattern/Singleton/Singleton.cpp (420b), CodingGuidance/DesignPattern/Singleton/Singleton.h (1307b), CodingGuidance/TopLevelCodingGuidance.md (5334b), setup.sh (23074b), SKILL.md (48443b), _meta.json (134b)","readmeExcerpt":"Skill: Spec-kit Coding Owner: staok Summary: Orchestrator for GitHub Spec-Kit SDD workflow in OpenClaw. Use when starting a new project with spec-driven development, setting up spec-kit toolchain, or ru... Tags: latest:1.0.5 Version history: v1.0.5 | 2026-06-16T07:40:35.431Z | user spec-kit-coding v1.0.5 - Removed unnecessary files: TODO.txt and skill-card.md - Updated SKILL.md with a new instruction: now asks users ","codeSnippets":[],"executableExamples":[{"language":"text","snippet":"constitution -> specify -> clarify -> checklist -> plan -> tasks -> analyze -> implement"},{"language":"text","snippet":"constitution -> specify -> clarify -> plan -> tasks -> implement"},{"language":"text","snippet":"You are <ROLE> for feature <NNN>-<name> in project at <project-dir>.\n\nCONTEXT BOUNDARY: You are a fresh isolated session. Focus EXCLUSIVELY on\nfeature <NNN>-<name>. The documents below are your sole source of truth.\nDo NOT mix in details from other features, projects, or earlier batches.\n\nBefore <ACTION>, read these documents in order:\n1. <project-dir>/CONTEXT.md (Domain glossary — if it exists)\n2. <project-dir>/.specify/memory/constitution.md\n3. <project-dir>/specs/<NNN>-<name>/* (All documents related to this feature)\n4. <project-dir>/docs/adr/ (Architecture Decision Records — if any exist)\n5. <project-dir>/README.md (Architecture section)\n\n<ROLE_SPECIFIC_INSTRUCTIONS>\n\nAfter completing your work:\n- Update <project-dir>/DEVLOG.md\n- If git management is enabled: git commit all changes\n- Report back using the structured format below"},{"language":"text","snippet":"## SUB-AGENT REPORT\n- Role: <implement | code-review | test>\n- Feature: <NNN>-<name>\n- Status: <SUCCESS | PARTIAL | BLOCKED | FAILED>\n- Tasks Completed: <list or \"all\">\n- Tasks Remaining: <list or \"none\">\n- Issues Found: <count, severity breakdown if review/test>\n- Blockers: <description or \"none\">\n- Files Modified: <list>\n- Summary: <1-2 sentences>"},{"language":"text","snippet":"Complexity Delta:\n   - Files over 1200 lines:\n   - Files newly crossing 1200 lines:\n   - Largest touched file delta:\n   - Largest touched function/block:\n   - New branches/fallbacks/adapters:\n   - Retired branches/fallbacks/adapters:\n   - Net entropy: decreased | stable | increased-with-justification\n   - Required follow-up:\n   \n   Complexity Governance Suggestion:\n   - Recommendation: none | monitor | schedule-refactor | extract helper | split owner | open follow-up\n   - Why:\n   - Suggested scope:\n   - Timing:"},{"language":"text","snippet":"Evidence Card:\n  - Command / Check: <exact verification command(s) run>\n  - Exit Status: <exit code(s)>\n  - Covered: <what was verified>\n  - Not Covered: <what was NOT verified>\n  - Residual Risk: <remaining risk>\n  - Confidence: A | B | C"}],"parameters":null,"dependencies":[],"permissions":[],"extractedFiles":[{"path":"SKILL.md","content":"---\nname: spec-kit-coding\ndescription: \"Orchestrator for GitHub Spec-Kit SDD workflow in OpenClaw. Use when starting a new project with spec-driven development, setting up spec-kit toolchain, or running through the full SDD pipeline.\"\n---\n# Spec-Kit Coding -- OpenClaw Orchestrator\n\n> **Repo:** [Staok/spec-kit-coding-skill](https://github.com/Staok/spec-kit-coding-skill)\n\nOrchestrates the complete Spec-Driven Development workflow via [github/spec-kit](https://github.com/github/spec-kit).\n\nCovers: Engineering Implementation. Does not cover\nrequirements discovery, operations/deployment, or cross-domain (SRE, security, etc.).\n\n---\n\n## HARD CONSTRAINTS\n\nREAD FIRST, APPLY ALWAYS.\n\nThese constraints are non-negotiable. Do NOT require the user to repeat them.\n\n### Security\n\n- Never transmit sensitive information to the network.\n- Before any external action (API calls, sending data outside local machine),\n  explain and ask for approval.\n- Do not install third-party libraries or modify system config without\n  asking first. If a new dependency is needed, explain why and get approval.\n- Prefer reusing existing, proven, popular third-party solutions. Avoid\n  reinventing the wheel. Keep tool usage simple and lean. Minimize dependency footprint.\n- **WARNING:** As a principle, agents should be disabled in critical-path code,\n  legacy system maintenance, and security-sensitive modules. Permitted only in\n  low-risk scenarios such as prototyping, search, and documentation.\n\n### Feature Management / Quick Reference\n\n- Starting a project, follow section: WORKFLOW, from STEP 1 to STEP 7.\n- On first project creation, ask the user: auto-run the WORKFLOW (pause only for required confirmations), or confirm at each step.\n- Add a new feature or modify an existing feature:\n  - \"add\" / \"new\" / behavior no spec covers -> new feature -> section: STEP 5: Spec-Kit Phases / New Feature.\n  - \"change\" / \"modify\" / changing existing behavior -> modify existing -> section: Feature Modification Entry Point.\n- Each `/speckit-specify` invocation creates exactly ONE feature. If the user\n  describes a messy, multi-concern requirement, split it first:\n  - List each proposed feature with a short name and one-line summary.\n  - Note dependencies between features.\n  - Ask user to confirm the split before proceeding.\n- When uncertain whether the user wants a new feature or a modification to an\n  existing one, ASK. Do not guess. Present your organized analysis. Show several or both options concisely.\n- For projects that have already been delivered or already exist, if a bug is reported, refer to section: Bug Fix Entry Point.\n\n### Communication\n\n- Collect all unclear points first, then ask once. Avoid back-and-forth.\n- Be efficient and concise. Output only necessary information.\n- Remind the user how to think about the problem better; help improve prompt\n  quality over time.\n\n### Documentation-First\n\n- For spec/plan/tasks .etc phase docs (spec.md, plan.md, tasks.md): these are created via the spec"},{"path":"_meta.json","content":"{\n  \"ownerId\": \"kn7200kmgerbhf59xrmr2sbm9585gczq\",\n  \"slug\": \"spec-kit-coding\",\n  \"version\": \"1.0.5\",\n  \"publishedAt\": 1781595635431\n}"},{"path":"CodingGuidance/CppCodingStyle.md","content":"## 良好实践经验 / 易错注意 / 开发套路 / 惯例写法\r\n\r\n（引自 [Cpp-Learning/编程经验-规范, 调试、性能和内存检查工具集合.md at main · Staok/Cpp-Learning](https://github.com/Staok/Cpp-Learning/blob/main/编程经验-规范%2C 调试、性能和内存检查工具集合.md)）\r\n\r\n\r\n\r\n### 模块 和 类\r\n\r\n一个类的所有 对外 API，尽量都做到 线程安全的，除非需要特殊考虑或者特殊说明。锁的范围尽量小，注意内部带锁的多个函数的嵌套调用的情况。\r\n\r\n\r\n\r\n对于启动 app process 的 各个模块 初始化、反初始化、信号 与 未catch异常管理 等等，参考这个的做法：`CppEngineeringFrameworkReference/AppContext.h`。\r\n\r\n\r\n\r\n对于每个具体干活的、拆分好的执行业务功能的模块用一个类。每个类的具体的统一做法如下：\r\n\r\n- 视需求，有的可以是可以创建多个，有的是单例模式。\r\n\r\n- 对于完成业务/任务的类，不需要多例，就可以写为单例，对于单例类，写上不可拷贝或移动的构造，以及不可赋值操作的拷贝和移动构造。\r\n\r\n- 如果是模块作用的类：\r\n\r\n  对于类在启动其作用的时候，如果没有一直循环运行的任务（比如在一个线程里面或者 启动函数里面的 `while(true){...}`）则使用 init 的情况；相反，则使用 run 的情况。下面给出参考。\r\n\r\n  对于 init 的情况，具体参考这个例子来写类的框架：`CppEngineeringFrameworkReference/CppModuleInitCaseExample.cpp`。\r\n\r\n  对于 run 的情况，具体参考这个例子来写类的框架：`CppEngineeringFrameworkReference/CppModuleRunCaseExample.cpp`。\r\n\r\n  关于框架参考代码的 log 和 线程池 相关依赖为示例参考，不是要求。\r\n\r\n- 如果是工具作用的类，尽量做到 RAII。\r\n- 在除了启停的 API 以外的其它对外 API 中都应该先判断 是否已经运行或者初始化完毕。\r\n- 按照需要，对外 API 都做到 线程安全（结合具体业务考虑选择使用什么类型的锁，比如读写锁、循环锁等）；锁范围尽量小。如果内部使用线程或线程池的，则需由外部传入；如果线程内异步执行类内资源，在此之前，使用 `std::weak_ptr<XXX> selfWeakPtr = shared_from_this();` 并线程函数 lambda 按值捕获 `selfWeakPtr`（注意不要捕获 this，异步执行的线程可能捕获已经资源释放掉了的 类实例 this，因此使用这里说的 捕获 selfWeakPtr 的方法！），在里面 `.lock()` 然后判断是否为空和判断是否已经在运行或初始化完毕，再使用。\r\n- 关于类变量初始化：\r\n  - 类变量在声明的地方进行赋值默认值。\r\n  - 使用 nullptr 对 指针变量（尽量使用智能指针）声明的时候 进行 初始化；指针资源释放掉后，需要再赋值为 nullptr 。\r\n  - 对于 const 变量，则在 类构造函数 的 初始化列表 处 进行赋值。尽量使用 const。\r\n\r\n\r\n\r\n对于程序中用到多个实例的类，比如 屏幕上的多个 object 或者 多个实体的数据 等的 建模：\r\n\r\n- 关于类抽象、继承和多态的对数据进行建模的设计，应符合直觉、有意义、方便使用。\r\n- 基类/抽象类、派生类 的结构设计尽量按照实际情况，尽量分层次处理，基类/抽象类中列好公共 变量 和 接口/虚函数/纯虚函数 等。\r\n\r\n- 每个类都做到 RAII。\r\n\r\n- 对于一类的事物，每个事物用类封装，它们最好有个共同的抽象基类（继承其），并且每个具体事物的类里面 override 所有抽象基类的虚函数（形成多态）；若这些事物要随时创建，搞一个它们的工厂类（抽象工厂模式）来用 比较通用的接口 通过 不同的入参 来创建不同的一类事物 并返回他们的基类类型指针（用 如 std::make_shared 来创建）；参考自己的 `C-C++-设计模式综合\\DesignPattern\\Builder`。\r\n\r\n- 在具体的地方用 vector、map 等方式存储它们的智能指针（如 std::shared_ptr）来存着他们，或专门写个创建并管理它们的类（增删改查，判（判空）排（排序）复（复位））且用 LRU 的方式存储他们以实现 有序排列的同时 实现 增加、查询 均为O(1) 复杂度。参考自己写的 `GeneralContainer` 作为 对象池 进行管理，也避免频繁申请和释放 示例，改善程序性能，即缓存，空间换时间。\r\n\r\n\r\n\r\n- 如果是写库，则使用 impl 模式。在对外接口的 头文件中 尽量减少和避免 include 三方库的头文件。\r\n\r\n\r\n\r\n\r\n### 函数\r\n\r\n- 函数的 命名 和 使用方式 （以及注释说明）要 符合直觉、易于理解，不要搞谜语考试别人。\r\n\r\n- 可复用的部分拆分出单独的函数。函数保持短小精悍。\r\n\r\n  > **\"Give someone state and they'll have a bug one day, but teach them how to represent state in two separate locations that have to be kept in sync and they'll have bugs for a lifetime.\"** [ocornut/imgui: Dear ImGui: Bloat-free Graphical User interface for C++ with minimal dependencies (github.com)](https://github.com/ocornut/imgui)。\r\n  >\r\n  > DeepSeek 翻译为：单一状态顶多偶尔出错，双份状态终身调试不休。\r\n\r\n- 如需用锁，优化为无锁，或 减少锁的范围，只针对必要部分。\r\n\r\n- 函数实现尽量降低 圈复杂度。\r\n\r\n- 不允许使用递归（即不允许函数自己调用自己），如有必要，使用栈结构和循环替代实现。循环必须有退出条件。\r\n\r\n- 处理可能抛异常的三方函数，自己写的，尽量不主动抛异常。\r\n\r\n- 同一个函数内，局部变量所占用的空间应小于16KB。\r\n\r\n- 不对内容进行修改的指针型参数，使用 const 修饰。\r\n\r\n- 函数的返回值，一般为有符号整数表示执行结果，0 表示执行成功，负值表示出错（使用 -errno，比如 -EIO），正值表示带条件的执行成功（个人习惯，使用返回的正数区分是什么警告级别的问题）。\r\n\r\n  对外接口性质的函数：\r\n\r\n  - 根据 GSL（C++ Core Guidelines） 的契约检查，入参检查分为：前置检查，后置检查。\r\n\r\n "},{"path":"CodingGuidance/DesignPattern/DesignPattern.md","content":"# 程序设计的一些通用结构\r\n\r\n参考并总结 [设计模式目录：22种设计模式](https://refactoringguru.cn/design-patterns/catalog)。\r\n\r\n更多参考 [设计模式 | 菜鸟教程](https://www.runoob.com/python-design-pattern/python-design-pattern-tutorial.html)。\r\n\r\n\r\n\r\n------\r\n\r\n## RAII\r\n\r\n使用 RAII（Resource Acquisition Is Initialization）模式可以确保资源在对象的生命周期内正确初始化和释放。\r\n\r\n应尽量把程序结构定为多个类的多模块拆分和接力协作，并且，每个类写为 RAII 模式，确保类实例的所有内部资源的初始化和释放与其对象的生命周期一致，达到多次 启停的目的，方便外部使用和管理。\r\n\r\n参考 同文件夹 的 `RAII` 目录。内有详细注释说明。\r\n\r\n\r\n\r\n---\r\n\r\n## 创建型模式\r\n\r\n参考 同文件夹 的 `Pimpl` 和 `Pimpl2`、`Builder` 和 `Singleton` 目录。内有详细注释说明。\r\n\r\n\r\n\r\n---\r\n\r\n## 结构型模式\r\n\r\n\r\n\r\n### 适配器(adapter) & 桥接(bridge) & 组合(composite)\r\n\r\n适配器(adapter) 可以写为 多种信息类型之间的转换 的组件：选定一个内部的统一的格式，做例如 setIn() 和 setOut() 的方法。\r\n\r\n如选定 jsonObj (比如 `nlohmann::json`) 作为内部的中间统一格式，就可以有 `jsonObj.setIn( jsonStr | jsonObj | xmlStr | xmlObj | yamlStr | yamlObj ... )`，以及 `jsonObj.setOut( ... )`。还可以参考 pcl 库的 各种滤波器 的使用，其中就有 `setInput()` 方法 并 重载了多种输入。\r\n\r\n\r\n\r\n上下二者类似 ↑ ↓\r\n\r\n\r\n\r\n桥接(bridge) 可以作为 多对多的控制或调用 的模块（模块为比组件高一个级别的层级，包括多个组件构成） 的结构：上层有多种对外接口功能，下层也有多种平台或者其它情况的各种适配，那种就可以设计一个中间层，只保留少量的、通用的接口。\r\n\r\n\r\n\r\n类似于 ↓\r\n\r\n\r\n\r\n组合(composite) 可以用于 信息结构呈现为树状或网状的 信息存储：将每个信息节点，用 多叉树 或者 网 的数据结构，组合到一起，再添加各种处理操作。\r\n\r\n\r\n\r\n\r\n### 装饰器(decorator) & 外观(facade) & 代理(proxy)\r\n\r\n这几个类似 wrap 封装一层 的结构 或 方法：比如现在有 三种 三方组件库 A、B 和 C，他们具体接口不一样但是功能行为类似，比如多种社交媒体平台接口，均有发帖和获取贴等，现在要写个上层使用统一的结构对其操作，就可以加一个 wrap 包装/封装一层，先来个比如 WrapBasic 的抽象类定义通用的必要的接口，再写 AWrap 类继承 WrapBasic 并实现 特定接口 来操作 A 库的接口，其它 B 和 C 同理。现在就有了 AWrap、BWrap 和 CWrap 三种 接口统一的 类 可供操作 三种库。\r\n\r\n\r\n\r\n---\r\n\r\n## 行为模式\r\n\r\n\r\n\r\n### 行为链条(chain) & 迭代器(iterator)\r\n\r\n行为链条(chain)：用于链式的处理逻辑，比如要进行一系列有先后的检查步骤，并要方便的可以在中间增减检查步骤：使用链表结构存储检查函数或者检查抽象类智能指针等，核心就是使用链表的数据结构，如 `std::list`。\r\n\r\n对于链条数据结构的遍历，就需要迭代器如下。\r\n\r\n\r\n\r\n迭代器(iterator)：搞一个对某个数据结构的指定迭代/遍历方法的迭代器类：如对于 二叉树 或 网 的数据结构有 深度优先 和 广度优先 等遍历方法。\r\n\r\n自己实现的数据结构，需要实现基本的方法：增删改查；我再加四个：判排复遍——判空、排序（对于哈希表结构则没有）、复位（清空）和遍历。\r\n\r\n对于遍历，可以两种：\r\n\r\n1. 提供遍历的方法比如 `traverse(const TraverseFunction& traverse_func)`，传入一个遍历的回调函数，如下。还可以增加遍历方法指定的形参。\r\n\r\n   ```c++\r\n   template <typename Key, typename Value>\r\n   void GeneralContainer<Key, Value>::traverse(const TraverseFunction& traverse_func) const\r\n   {\r\n       if(!traverse_func) {\r\n           return;\r\n       }\r\n       std::shared_lock<std::shared_mutex> lock(mMutex);\r\n       for (const auto& it : mList) { // 正序遍历\r\n           traverse_func(it);\r\n       }\r\n   }\r\n   ```\r\n\r\n2. 提供这里所说的迭代器类，不同的迭代器类代表对这个数据结构的不同的遍历方法。比如 std 标准库 容器的:\r\n\r\n   ```c++\r\n   std::vector<int> myVector = {1, 2, 3, 4, 5};\r\n   auto forwardIter = myVector.begin();    // forwardIter 指向 第一个 元素，forwardIter++ 则移动到第二个元素。\r\n   auto backwardIter = myVector.rbegin();  // backwardIter 指向 最后一个 元素，backwardIter++ 则移动到倒数第二个元素。\r\n   ```\r\n\r\n\r\n\r\n### 中介/中央调度(mediator) & 命令(command)\r\n\r\n中介/中央调度(mediator)：多个地方的组件请求执行动作，如果其之间有冲突，比如多个 app 要往 状态栏 弹带优先级的信息，不要各自都直接弹出，因为需要优先级高的始终在最上，因此需要一个中介或者中央调度的组件或模块，多个地方的 app 统一往这个 中介 请求弹信息，由 中介 选择 往信息栏 插入 的位置并插入、或者检查黑名单并忽略等等。\r\n\r\n还有 GUI 程序中的弹窗场景，有的界面可以弹窗，有的界面不允许弹窗，等等还有其它设计情况，因此需要一个中介去统一接受弹窗请求并处理。\r\n\r\n\r\n\r\n命令(command)：思想是，打包一个执行动作以及其传入参数：一个执行动作，如 GUI 程序中 用户点击一个按键，索要执行的一系列程序，封装为一个函数（多种按键有枚举等关系，或"},{"path":"CodingGuidance/TopLevelCodingGuidance.md","content":"## 编码顶层指导\r\n\r\n（引自 [Cpp-Learning/编程经验-规范, 调试、性能和内存检查工具集合.md at main · Staok/Cpp-Learning](https://github.com/Staok/Cpp-Learning/blob/main/编程经验-规范%2C 调试、性能和内存检查工具集合.md)）\r\n\r\n- **层次化，即分清晰的多层**。程序结构分为多个层次，文件夹也按照如此划分，不同模块处于不同功能层。具体问题具体分析。\r\n- **高内聚、低耦合。不宜常修改，应易扩展**。\r\n\r\n  写东西时候先多思考架构。不必一上来就写 等 情况的出现，减少后面 debug 和 重构的时间。\r\n\r\n  - 各部分选择合适的最佳实践和设计模式。\r\n  - 多看一些 **最佳实践的文章和软件工程** 来对自己进行提高。\r\n  - **设计模式**相关综合 [Staok/C-Cpp-design-patterns](https://github.com/Staok/C-Cpp-design-patterns)，具体参考其里面的 `DesignPattern` 文件夹下的文档和代码例子。检查 `CppCodingGuidance/DesignPattern` 若存在则直接用。\r\n\r\n  模块化。模块独立，各端分离，接口分明。每个模块可独立的、动态的、运行时的创建、启、停和释放，程序由多个模块搭建、协作来构成。\r\n\r\n  多写可复用代码。代码具有良好的实用性、通用性，以及安全性（风险规避）。\r\n\r\n  易于扩展和维护。\r\n- **参数化**。\r\n\r\n  几个维度：\r\n\r\n  - 对于模块的编写维度：考虑可通过修改参数来增强模块的适用范围和灵活性。模块编写考虑高复用性和多用性。敏锐的发现和合并公共的处理逻辑为一个通用的中间层，靠传入不同参数进行处理。\r\n  - 对于设备管理维度：数据驱动法，就像 Linux 中的 设备树 作为可方便修改的数据表格，可以冷更新或者热更新到系统、程序中去并生效，不必有改动的时候每次都改代码并重新编译打包和部署。可用 json 等格式 写入 外部配置文件，程序读取并应用。\r\n  - 对于软件整体运行层面：会有很多 settings，用户的或者系统内部的。可用 json 等格式 作为 设置存储文件，程序读写用。\r\n  - 对于不同机型或者运行工况，需要不同套参数，将其 表格化，数据驱动，初始化时候按照机型选取对应的一套参数装填并使用。\r\n- **可读性**。\r\n\r\n  注释：基本要求：英文 Doxygen 注释格式，头文件写几个用例（帮助快速熟悉使用），可直接生成 API 文档的水准。\r\n- 代码格式，以具有良好的可读性为好。整个工程整齐划一，**风格和编程模式具有连贯性**。\r\n\r\n  参考 具体的另外提供的 细节写法格式和规范。\r\n\r\n  （可选，默认不必用）每个项目有统一的 .clang_format 文件，时常 format 下。\r\n- （按需）**跨平台化**。\r\n\r\n  考虑软件的通用性和可移植性，考虑应用层的硬件无关性、跨平台性 / 跨操作系统性（主要是 Win 和 Linux），屏蔽日后换平台的工作量和痛苦。\r\n\r\n  除非特殊要求，否则不假定编写的代码用于特定场景（比如只用于 ROS2 环境 等），要按照实用、通用的准则去写。\r\n\r\n  三方库：尽量选用 Win 和 Linux 都兼容的，流行的、社区活跃的。\r\n- **依赖合理**。\r\n\r\n  按照当前需求和未来规划，合理分配哪些选择使用三方库，哪些选择自己实现。对于当前和未来需求而且功能复杂的，选择三方库（合理选择依赖的三方库，能覆盖需求，功能较丰富，尽量选择支持 Win 和 Linux 跨平台的，拒绝多用、滥用），对于代码量小的可以合理的自己实现。\r\n\r\n  对于 C/C++ 工程，为了不复杂化部署：均使用 cmake，依赖的三方库下载并放到工程目录的 third_party 文件夹里面 来直接通过 cmake 引入来使用。对于 C 除非指定版本 否则至少 C99。对于 C++ 除非约束版本 否则至少 C++17。\r\n\r\n  对于 Python，在工程目录建立 venv 虚拟环境来做，如果依赖特别多而且库有比较大的，则先询问用户是否还要使用 venv 虚拟环境 还是直接全局安装三方库。\r\n- **高性能**。\r\n\r\n  选择运行高效的、高性能的实现方式。若项目是刚开始搭建，而且高性能方案有一定难度，则可以先记录文档，先按照容易实现的（同时也有一定高性能保证的）方案来做，后面有需要则再优化性能。\r\n\r\n  具体内部的算法实现应降低圈复杂度、降低时间复杂度，但如果代价是显著增加空间复杂度则也不必，做好权衡。代码保持简洁易读。\r\n\r\n  也要注意避免头文件的过多嵌套导致编译时长显著增加。\r\n- **健壮性，稳定运行**。\r\n\r\n  风险点提前规避和检查，参考后面 `良好实践经验 / 易错注意 / 开发套路 / 惯例写法` 一节。\r\n- **可测试性**、**易于测试**。\r\n\r\n  保持程序的能控能观性。程序受外部控制接口统一且清晰，程序状态和对外影响、产物等明确。方便测试。\r\n\r\n  代码必须通过测试。具体测试要求参考另外提供的。\r\n\r\n  编码中尽量去掉 编译 warning。\r\n\r\n  Evidence over claims — 验证之后（代码审查、修复、测试 都通过）再声称完成。"}],"languages":[],"docsSourceLabel":"CLAWHUB","editorialOverview":"Orchestrator for GitHub Spec-Kit SDD workflow in OpenClaw. Use when starting a new project with spec-driven development, setting up spec-kit toolchain, or ru... Skill: Spec-kit Coding Owner: staok Summary: Orchestrator for GitHub Spec-Kit SDD workflow in OpenClaw. Use when starting a new project with spec-driven development, setting up spec-kit toolchain, or ru... Tags: latest:1.0.5 Version history: v1.0.5 | 2026-06-16T07:40:35.431Z | user spec-kit-coding v1.0.5 - Removed unnecessary files: TODO.txt and skill-card.md - Updated SKILL.md with a new instruction: now asks users","editorialQuality":{"score":100,"threshold":65,"status":"ready","wordCount":1405,"uniquenessScore":51,"reasons":[]}},"media":{"evidence":{"source":"no-media","verified":false,"confidence":"low","updatedAt":"2026-10-11T13:06:47.274Z","emptyReason":"No screenshots, media assets, or demo links are available."},"primaryImageUrl":null,"mediaAssetCount":0,"assets":[],"demoUrl":null},"ownerResources":{"evidence":{"source":"unclaimed","verified":false,"confidence":"low","updatedAt":"2026-10-11T13:06:47.274Z","emptyReason":"This page has not been claimed by the agent owner."},"hasCustomPage":false,"customPageUpdatedAt":null,"customLinks":[],"structuredLinks":{"docsUrl":null,"demoUrl":null,"supportUrl":null,"pricingUrl":null,"statusUrl":null},"customPage":null},"relatedAgents":{"evidence":{"source":"protocol-neighbors","verified":false,"confidence":"medium","updatedAt":"2026-10-11T16:00:08.981Z","emptyReason":null},"items":[{"id":"8ebccd8e-3863-4187-8355-c3f14e1f9edf","entityType":"agent","canonicalPath":"/agent/iofficeai-aionui","slug":"iofficeai-aionui","name":"AionUi","description":"Free, local, open-source 24/7 Cowork app and OpenClaw for Gemini CLI, Claude Code, Codex, OpenCode, Qwen Code, Goose CLI, Auggie, and more | 🌟 Star if you like it!","url":"https://github.com/iOfficeAI/AionUi","homepage":"https://www.aionui.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-10-09T19:11:12.944Z","createdAt":"2026-02-25T03:38:16.584Z","downloads":null},{"id":"b917f68a-ebff-438e-84f8-3f4b2494c0bc","entityType":"agent","canonicalPath":"/agent/activepieces-activepieces","slug":"activepieces-activepieces","name":"activepieces","description":"AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents","url":"https://github.com/activepieces/activepieces","homepage":"https://www.activepieces.com","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-15T02:22:12.426Z","createdAt":"2026-02-25T03:38:12.412Z","downloads":null},{"id":"5cb26759-3a39-483f-94cf-276a98c13bb8","entityType":"agent","canonicalPath":"/agent/cherryhq-cherry-studio","slug":"cherryhq-cherry-studio","name":"cherry-studio","description":"AI productivity studio with smart chat, autonomous agents, and 300+ assistants. Unified access to frontier LLMs","url":"https://github.com/CherryHQ/cherry-studio","homepage":"https://cherry-ai.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-11T14:38:40.986Z","createdAt":"2026-02-25T03:38:19.379Z","downloads":null},{"id":"6f6582d0-5d76-4f0f-b81d-86520247950b","entityType":"agent","canonicalPath":"/agent/copilotkit-copilotkit","slug":"copilotkit-copilotkit","name":"CopilotKit","description":"The Frontend for Agents & Generative UI. React + Angular","url":"https://github.com/CopilotKit/CopilotKit","homepage":"https://docs.copilotkit.ai","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-03-25T09:50:57.846Z","createdAt":"2026-02-25T03:39:14.617Z","downloads":null}],"links":{"hub":"/agent","source":"/agent/source/clawhub","protocols":[{"label":"OpenClaw","href":"/agent/protocol/openclew"}]}}}