Skip to content
Back to search

sovereign-plugins

MarketplaceWorks with Claude CodeGitHub

Production-grade Claude Code skills for the full project lifecycle — setup, daily workflow, session management, and quality audits

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/AlexZio00/sovereign-skills with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/AlexZio00/sovereign-skills'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/alexzio00--sovereign-skills/badge.svg)](/listings/alexzio00--sovereign-skills)

HTML

<a href="/listings/alexzio00--sovereign-skills"><img src="/api/listings/alexzio00--sovereign-skills/badge.svg" alt="findsafeskills safety rating" /></a>

Install

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

**New project (15 min):**

/project-init       →  CLAUDE.md + ROADMAP + .gitignore + .env.example
/setup              →  rules/ + hooks + memory/ + agent routing + team
then daily:
  /session-start      at the start of every session
  /scope              before each feature (define IN/OUT/exit criteria)
  /freeze             before implementation (declare editable zone)
  /goal-lock          lock the goal, enforce PLAN→DO→VERIFY loop
  /stepback           anytime — zoom out, check direction, 10 lines
  /next-action        anytime — reads current state, proposes top-3 next actions
  /code-autopsy       12Q code review with severity scoring + verdict
  /pre-push           before each push (secrets scan + agent review)
  /session-checkpoint at the end of every session

**Existing project (5 min):**

/project-check      →  Score across 4 dimensions + gap list by severity
/collab-audit       →  14-section AI collaboration diagnostic from your work patterns

**Governance & audits (as needed):**

/integration-intake →  before adopting an external skill/agent/rule/plugin — 5-item screening gate
/full-audit         →  exhaustive area audit (codebase/docs/skills/memory/config) with a coverage map
/clean-room         →  when a task mixes safety-adjacent material with genuinely safe work
/eval-leakage-audit →  before trusting an eval/metric/holdout — check for circular self-confirmation
/doc-drift          →  audit loaded context (CLAUDE.md/MEMORY.md/skills) for outdated/contradictory wording
/ssot-audit         →  one fact in many files — find the source of truth, then consolidate

**If you write your own skills:**

/skill-trigger-auditor →  before changing a skill description — catch routing collisions and misfires
/skill-ops             →  snapshot/rollback a skill before editing, check which skills are actually used
/project-overview      →  one status map across several projects

---

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 164 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. {
  2. "name": "sovereign-plugins",
  3. "description": "Production-grade Claude Code skills for the full project lifecycle — setup, daily workflow, session management, and quality audits",
  4. "owner": {
  5. "name": "AlexZio00",
  6. "url": "https://github.com/AlexZio00"
  7. },
  8. "plugins": [
  9. {
  10. "name": "project-init",
  11. "description": "Interview-based project scaffolding — generates CLAUDE.md, ROADMAP, .gitignore, and .env.example from decisions, not templates",
  12. "source": "./project-init",
  13. "category": "development",
  14. "tags": ["scaffolding", "project-setup", "claude-md", "roadmap", "interview", "init"]
  15. },
  16. {
  17. "name": "setup",
  18. "description": "Claude Code infrastructure and agent team setup — rules, hooks, memory system, routing, and agent installation in one guided flow",
  19. "source": "./setup",
  20. "category": "development",
  21. "tags": ["infrastructure", "agent-team", "rules", "hooks", "memory", "routing", "setup"]
  22. },
  23. {
  24. "name": "scope",
  25. "description": "Define what is IN, what is OUT, and exit criteria before implementation. Quick mode (3 questions) or Full mode (layered spec)",
  26. "source": "./scope",
  27. "category": "productivity",
  28. "tags": ["scope", "requirements", "exit-criteria", "specification", "planning"]
  29. },
  30. {
  31. "name": "freeze",
  32. "description": "Declare the editable zone — everything outside is frozen. Prevents scope creep during implementation",
  33. "source": "./freeze",
  34. "category": "productivity",
  35. "tags": ["freeze", "scope-control", "editable-zone", "scope-creep", "protection"]
  36. },
  37. {
  38. "name": "goal-lock",
  39. "description": "Agent discipline engine — locks the goal, enforces PLAN-DO-VERIFY-FINALIZE-OUTPUT loop, detects 16 success masquerading patterns",
  40. "source": "./goal-lock",
  41. "category": "productivity",
  42. "tags": ["goal", "discipline", "verification", "masquerading", "agent-control", "quality"]
  43. },
  44. {
  45. "name": "pre-push",
  46. "description": "Mandatory pre-push pipeline — secrets scan (14 patterns), build/test gate, lint, parallel AI code review. Blocks push on Critical/High findings",
  47. "source": "./pre-push",
  48. "category": "development",
  49. "tags": ["pre-push", "secrets-scan", "code-review", "security", "lint", "ci", "pipeline"]
  50. },
  51. {
  52. "name": "session-start",
  53. "description": "Session opener — loads handoff from last session, reviews lessons learned, runs health check, outputs ready signal with priority action",
  54. "source": "./session-start",
  55. "category": "productivity",
  56. "tags": ["session", "handoff", "context-restore", "lessons", "health-check", "start"]
  57. },
  58. {
  59. "name": "session-checkpoint",
  60. "description": "Session closer — saves context before compact. Handoff file, memory updates, lesson extraction, reflexion",
  61. "source": "./session-checkpoint",
  62. "category": "productivity",
  63. "tags": ["session", "checkpoint", "handoff", "memory", "reflexion", "compact", "lessons"]
  64. },
  65. {
  66. "name": "project-check",
  67. "description": "Scan existing project across 4 dimensions: Infrastructure, Security, Quality, Harness. Returns scored gaps ordered by severity",
  68. "source": "./project-check",
  69. "category": "development",
  70. "tags": ["audit", "health-check", "infrastructure", "security", "quality", "diagnostic"]
  71. },
  72. {
  73. "name": "code-autopsy",
  74. "description": "12Q quantified code review — 4-axis scoring (Security/Stability/Robustness/Operability), severity anchors, deployment verdict, factuality gate. Works as standalone prompt in any LLM",
  75. "source": "./code-autopsy",
  76. "category": "development",
  77. "tags": ["code-review", "12q", "severity", "scoring", "deployment-verdict", "security", "testing", "observability"]
  78. },
  79. {
  80. "name": "collab-audit",
  81. "description": "14-section AI collaboration audit — analyzes actual work patterns to generate behavioral profile, blind spots, and growth direction",
  82. "source": "./collab-audit",
  83. "category": "productivity",
  84. "tags": ["collaboration", "audit", "behavioral", "patterns", "growth", "diagnostic"]
  85. },
  86. {
  87. "name": "stepback",
  88. "description": "One-shot perspective reset — 1 reframing question + 3 quick checks (scope drift, side effects, better approach) in under 10 lines. Use anytime during work",
  89. "source": "./stepback",
  90. "category": "productivity",
  91. "tags": ["perspective", "zoom-out", "scope-check", "direction", "meta", "one-shot"]
  92. },
  93. {
  94. "name": "skill-ops",
  95. "description": "Skill ops hub with 4 modes: snapshot/rollback, usage health, invocation frequency, and an operational quality score for Claude Code skills and agents",
  96. "source": "./skill-ops",
  97. "category": "development",
  98. "tags": ["skill-management", "snapshot", "rollback", "usage-health", "invocations"]
  99. },
  100. {
  101. "name": "next-action",
  102. "description": "Reads handoff/git/lessons/STATE and proposes top-3 next actions by impact. Proposes only, never executes",
  103. "source": "./next-action",
  104. "category": "productivity",
  105. "tags": ["next-action", "recommendation", "priority", "handoff", "state"]
  106. },
  107. {
  108. "name": "project-overview",
  109. "description": "Generates a deterministic cross-project status map from registered projects' session handoffs",
  110. "source": "./project-overview",
  111. "category": "productivity",
  112. "tags": ["cross-project", "overview", "status-map", "registry"]
  113. },
  114. {
  115. "name": "full-audit",
  116. "description": "Exhaustive area audit (codebase/docs/skills/memory/config) with a deterministic-sweep + content-review three-layer method and a persistent coverage map",
  117. "source": "./full-audit",
  118. "category": "development",
  119. "tags": ["audit", "exhaustive", "coverage-map", "deterministic", "false-positive-guard"]
  120. },
  121. {
  122. "name": "integration-intake",
  123. "description": "5-item screening gate for adopting external patterns (skills/agents/rules/plugins/MCP), with a provenance/injection check for imported executable content",
  124. "source": "./integration-intake",
  125. "category": "development",
  126. "tags": ["integration", "adoption-gate", "redundancy-check", "provenance", "supply-chain"]
  127. },
  128. {
  129. "name": "clean-room",
  130. "description": "Carves safety-adjacent requests into a safe scope, executed by a genuinely isolated fresh-context subagent, with an adversarial verify pass and a descope ledger",
  131. "source": "./clean-room",
  132. "category": "productivity",
  133. "tags": ["scope-isolation", "safety", "descope", "fresh-context", "ledger"]
  134. },
  135. {
  136. "name": "eval-leakage-audit",
  137. "description": "Audits whether an eval/metric/holdout secures independent external ground truth vs circular self-confirmation, using a 28-pattern taxonomy. Read-only",
  138. "source": "./eval-leakage-audit",
  139. "category": "development",
  140. "tags": ["eval", "leakage", "holdout", "circular-verification", "ground-truth"]
  141. },
  142. {
  143. "name": "doc-drift",
  144. "description": "Audits the memory/docs Claude Code loads into context (CLAUDE.md/MEMORY.md/skills/agents/commands) for outdated claims, contradictions, and risky wording; produces a prioritized fix list",
  145. "source": "./doc-drift",
  146. "category": "development",
  147. "tags": ["doc-drift", "memory-audit", "context", "outdated", "contradiction"]
  148. },
  149. {
  150. "name": "ssot-audit",
  151. "description": "Finds where one fact, value or decision is duplicated or contradicted across files, names the single source of truth (read-only), then consolidates copies after user approval",
  152. "source": "./ssot-audit",
  153. "category": "development",
  154. "tags": ["ssot", "source-of-truth", "dedupe", "consolidation", "audit"]
  155. },
  156. {
  157. "name": "skill-trigger-auditor",
  158. "description": "Audits whether skills, agents and slash commands route correctly: description clarity, collisions, built-in command conflicts, holdout precision/recall, plus an optional probe that measures real Skill tool calls",
  159. "source": "./skill-trigger-auditor",
  160. "category": "development",
  161. "tags": ["skill-routing", "trigger-audit", "collision", "regression", "holdout"]
  162. }
  163. ]
  164. }
README.md · README · 344 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. 🌐 **English** | [한국어](docs/README.ko.md) | [日本語](docs/README.ja.md) | [中文](docs/README.zh.md) | [Español](docs/README.es.md)
  2. # sovereign-skills v6.6.0
  3. 22 skills for the full Claude Code project lifecycle — from setup to daily workflow to code review to session management to governance. Each skill is useful standalone; the full sequence covers everything.
  4. > **What changed in v6.6.0:** 20 of the 22 skills updated. `eval-leakage-audit` grows from 28 to 31 patterns (trivial-cue baseline, per-condition grader error in A-vs-B comparisons, undisclosed fallback scoring). `skill-trigger-auditor` scores trigger tests per split (tuning / heldout / review / real). Two new helper scripts with tests: `doc-drift/scripts/stale_numbers.py` (counts and versions in docs that no longer match the files) and `pre-push/scripts/share_record.py` (per-class counts of e-mails, home paths and key-shaped strings in what a public push carries, recorded without values). `integration-intake` checks how to leave a connector or memory provider before you adopt it. Fixes: `pre-push` no longer reads font URLs such as `family=…:wght@400` as a password in a connection string; `project-check` detects GitHub fine-grained tokens and uses the larger size class when file count and LOC disagree; `session-start` runs its health check even when the rest is skipped. See [CHANGELOG.md](CHANGELOG.md).
  5. ---
  6. ## Quick Start
  7. **New project (15 min):**
  8. ```
  9. /project-init → CLAUDE.md + ROADMAP + .gitignore + .env.example
  10. /setup → rules/ + hooks + memory/ + agent routing + team
  11. then daily:
  12. /session-start at the start of every session
  13. /scope before each feature (define IN/OUT/exit criteria)
  14. /freeze before implementation (declare editable zone)
  15. /goal-lock lock the goal, enforce PLAN→DO→VERIFY loop
  16. /stepback anytime — zoom out, check direction, 10 lines
  17. /next-action anytime — reads current state, proposes top-3 next actions
  18. /code-autopsy 12Q code review with severity scoring + verdict
  19. /pre-push before each push (secrets scan + agent review)
  20. /session-checkpoint at the end of every session
  21. ```
  22. **Existing project (5 min):**
  23. ```
  24. /project-check → Score across 4 dimensions + gap list by severity
  25. /collab-audit → 14-section AI collaboration diagnostic from your work patterns
  26. ```
  27. **Governance & audits (as needed):**
  28. ```
  29. /integration-intake → before adopting an external skill/agent/rule/plugin — 5-item screening gate
  30. /full-audit → exhaustive area audit (codebase/docs/skills/memory/config) with a coverage map
  31. /clean-room → when a task mixes safety-adjacent material with genuinely safe work
  32. /eval-leakage-audit → before trusting an eval/metric/holdout — check for circular self-confirmation
  33. /doc-drift → audit loaded context (CLAUDE.md/MEMORY.md/skills) for outdated/contradictory wording
  34. /ssot-audit → one fact in many files — find the source of truth, then consolidate
  35. ```
  36. **If you write your own skills:**
  37. ```
  38. /skill-trigger-auditor → before changing a skill description — catch routing collisions and misfires
  39. /skill-ops → snapshot/rollback a skill before editing, check which skills are actually used
  40. /project-overview → one status map across several projects
  41. ```
  42. ---
  43. ## Skills
  44. ### Setup Phase
  45. | Skill | What it does |
  46. |-------|-------------|
  47. | [project-init](project-init/) | Interview-based project scaffolding — generates CLAUDE.md, ROADMAP, .gitignore, and .env.example from decisions, not templates |
  48. | [setup](setup/) | Claude Code infrastructure and agent team — rules, hooks, memory, routing, and agent installation in one guided flow |
  49. ### Daily Workflow
  50. | Skill | What it does |
  51. |-------|-------------|
  52. | [scope](scope/) | Define what's IN, what's OUT, and exit criteria before implementation. Quick mode (3 questions) or Full mode (layered spec). Full mode ships `coverage_check.py` (requirement ↔ task check) |
  53. | [freeze](freeze/) | Declare the editable zone — everything outside is frozen. Prevents scope creep during implementation |
  54. | [goal-lock](goal-lock/) | Agent discipline engine — locks the goal, enforces PLAN→DO→VERIFY→FINALIZE→OUTPUT loop, detects 16 success masquerading patterns |
  55. | [pre-push](pre-push/) | Mandatory pre-push pipeline — secrets scan (14 patterns), build/test, lint, parallel AI code review. Checks what the push actually carries (staged + outgoing commits). Blocks push on Critical/High findings. Pushes to a public mirror also get a value-free share record (`share_record.py`) |
  56. ### Perspective
  57. | Skill | What it does |
  58. |-------|-------------|
  59. | [stepback](stepback/) | One-shot perspective reset — 1 abstract reframing question + 3 quick checks (scope drift, side effects, better approach) and a continue/stop verdict, in under 10 lines. Use anytime during work |
  60. | [next-action](next-action/) | Reads handoff/git/lessons/STATE and proposes the top-3 next actions by impact. Proposes only, never executes. Use anytime |
  61. ### Session Management
  62. | Skill | What it does |
  63. |-------|-------------|
  64. | [session-start](session-start/) | Load handoff from last session, review lessons, health check, output "ready" signal with priority action. Flags handoff items whose date has already passed |
  65. | [session-checkpoint](session-checkpoint/) | Save session context before compact — handoff file, memory updates, lesson extraction, reflexion (what went wrong, what to do differently). Keeps future-dated items in a separate "Scheduled checks" list |
  66. ### Code Review
  67. | Skill | What it does |
  68. |-------|-------------|
  69. | [code-autopsy](code-autopsy/) | 12Q quantified code review (v7.3) — 4-axis scoring (Security/Stability/Robustness/Operability), severity anchors, deployment verdict (SHIP/FIX/RISKY/BLOCK), factuality gate. Each finding is marked NEW or PRE-EXISTING and carries an evidence tier. Backed by empirical evidence (Johnson 2019, Parnas 1972). Also works as a standalone prompt in any LLM |
  70. ### Quality
  71. | Skill | What it does |
  72. |-------|-------------|
  73. | [project-check](project-check/) | Scan existing project across 4 dimensions: Infrastructure, Security, Quality, Harness. Gaps ordered by severity |
  74. | [collab-audit](collab-audit/) | 14-section AI collaboration audit — analyzes your actual work patterns (not surveys) to generate behavioral profile, blind spots, and growth direction. `extract_session_meta.py` builds the session data it needs |
  75. ### Operations
  76. | Skill | What it does |
  77. |-------|-------------|
  78. | [skill-ops](skill-ops/) | Skill/agent ops hub — snapshot/rollback + usage health + invocation tracking + quality score, 4 modes. Ships `skill_snapshot.py` and `skill_health_bucket.py` |
  79. | [project-overview](project-overview/) | Generates a deterministic cross-project status map from registered projects' session handoffs, and reports snapshots older than 7 days |
  80. | [skill-trigger-auditor](skill-trigger-auditor/) | Audits skill, agent and slash-command routing for collisions and misfires, and gates description changes behind holdout trigger tests scored per split (tuning / heldout / review / real). Optional probe measures real Skill tool calls |
  81. ### Governance
  82. | Skill | What it does |
  83. |-------|-------------|
  84. | [full-audit](full-audit/) | Exhaustive audit of an entire area (codebase/docs/skills/memory/config) — deterministic sweep + content review two-layer method, anti-false-positive kill-test, seeded canaries, persistent coverage map |
  85. | [integration-intake](integration-intake/) | 5-item screening gate for adopting external patterns (skills/agents/rules/plugins/MCP) — redundancy check against your existing assets, a provenance/injection check for imported executable content, a license line, a ledger lookup of earlier verdicts, and an exit-path check for connectors and memory providers |
  86. | [clean-room](clean-room/) | Carves safety-adjacent requests into a safe scope, executed by a genuinely isolated fresh-context subagent — adversarial verify pass + descope ledger |
  87. | [eval-leakage-audit](eval-leakage-audit/) | Audits whether an eval/metric/holdout actually secures independent external ground truth vs circular self-confirmation — 31-pattern taxonomy, two golden cases. Read-only |
  88. | [doc-drift](doc-drift/) | Audits the memory/docs Claude Code loads into context (CLAUDE.md/MEMORY.md/skills/agents/commands) for outdated claims, mutual contradictions, and risky/ambiguous wording — produces a prioritized fix list. `stale_numbers.py` flags counts and versions that no longer match |
  89. | [ssot-audit](ssot-audit/) | Finds every copy of one fact, value or decision across a repo or notes folder, names the source of truth (read-only), and consolidates the duplicates only after you approve |
  90. ---
  91. ## Lifecycle Flow
  92. ```
  93. ┌─────────────────── Setup (once) ────────────────────┐
  94. │ /project-init → /setup │
  95. └─────────────────────────────────────────────────────┘
  96. ↓
  97. ┌──────────────────── Daily Loop ─────────────────────┐
  98. │ /session-start │
  99. │ ↓ │
  100. │ /scope → /freeze → /goal-lock → work │
  101. │ → /stepback (anytime) → /code-autopsy │
  102. │ → /pre-push │
  103. │ ↓ │
  104. │ /session-checkpoint │
  105. └─────────────────────────────────────────────────────┘
  106. ↓
  107. ┌───────────────────── On Demand ─────────────────────┐
  108. │ /stepback (perspective reset — anytime) │
  109. │ /next-action (top-3 next actions from state) │
  110. │ /project-check (health audit) │
  111. │ /code-autopsy (12Q code review — any LLM) │
  112. │ /collab-audit (behavioral diagnostic) │
  113. │ /integration-intake (before adopting external work)│
  114. │ /full-audit (exhaustive area audit) │
  115. │ /clean-room (safety-adjacent scope carve-out)│
  116. │ /eval-leakage-audit (eval circular-logic check) │
  117. │ /doc-drift (loaded-context drift audit) │
  118. │ /ssot-audit (one fact, many copies) │
  119. └─────────────────────────────────────────────────────┘
  120. ↓
  121. ┌─────────── Skill authors / multi-project ───────────┐
  122. │ /skill-ops (snapshot, rollback, usage) │
  123. │ /skill-trigger-auditor (routing collisions) │
  124. │ /project-overview (cross-project status map) │
  125. └─────────────────────────────────────────────────────┘
  126. ```
  127. ---
  128. ## Installation
  129. ### Option A: Copy skills (simplest)
  130. Each skill is a standalone directory with a `SKILL.md` file. Copy the ones you want:
  131. ```bash
  132. # Install all skills
  133. git clone https://github.com/AlexZio00/sovereign-skills.git
  134. cd sovereign-skills
  135. for d in */; do [ -f "$d/SKILL.md" ] && cp -r "$d" ~/.claude/skills/; done
  136. # Or install one skill
  137. cp -r goal-lock ~/.claude/skills/
  138. ```
  139. ### Option B: Marketplace (sovereign-plugins)
  140. This repo is a Claude Code plugin marketplace named `sovereign-plugins`. Add it once, then install the skills you want. Inside a Claude Code session:
  141. ```
  142. /plugin marketplace add AlexZio00/sovereign-skills
  143. /plugin install goal-lock@sovereign-plugins
  144. ```
  145. From a shell, the same two steps are:
  146. ```bash
  147. claude plugin marketplace add AlexZio00/sovereign-skills
  148. claude plugin install goal-lock@sovereign-plugins
  149. ```
  150. In the desktop app, add the marketplace with one of the commands above, then pick skills from the plugin browser (**+** next to the prompt box → **Add plugins**). Third-party marketplaces do not auto-update by default. See the [official plugin install guide](https://code.claude.com/docs/en/plugins/install.md).
  151. Each skill also includes standalone `.claude-plugin/plugin.json` metadata.
  152. Skills are invoked by typing the trigger command (e.g., `/goal-lock`) in Claude Code. Claude reads the SKILL.md and follows the instructions.
  153. ### Option C: Codex
  154. Codex discovers skills by scanning `.agents/skills/<skill-name>/SKILL.md` at the repository, user (`$HOME/.agents/skills`), admin, and system levels — no separate agent definition is required. Install a skill for Codex the same way you would for Claude Code, just under the `.agents/skills/` path:
  155. ```bash
  156. # User-level (available in every project)
  157. cp -r goal-lock ~/.agents/skills/goal-lock/
  158. # Repo-level (this project only)
  159. cp -r goal-lock .agents/skills/goal-lock/
  160. ```
  161. Each skill also ships an **optional** `agents/openai.yaml` — UI/policy metadata for the ChatGPT desktop app (display name, description, icon/branding color, and the `allow_implicit_invocation` flag, `true` by default). It is not needed for Codex to find or run the skill; copy it along with `SKILL.md` only if you want that metadata applied:
  162. ```bash
  163. cp -r goal-lock/agents .agents/skills/goal-lock/agents/
  164. ```
  165. See the [official Codex skills documentation](https://learn.chatgpt.com/docs/build-skills) for the full discovery and metadata spec.
  166. ### Option D: Cursor / Other Agents
  167. The SKILL.md content is universal markdown — it works with any LLM that reads markdown instructions. Copy `SKILL.md` into your agent's instruction path.
  168. ### Requirements
  169. - **Claude Code**: CLI, desktop app, or web app ([claude.ai/code](https://claude.ai/code))
  170. - **Codex**: OpenAI Codex — reads `SKILL.md` directly from `.agents/skills/`; `agents/openai.yaml` is optional UI metadata
  171. - **Cursor / Other**: Any agent that reads markdown instructions
  172. - Skills directory: `~/.claude/skills/` (Claude Code) or agent-specific path
  173. - Python 3.9+ for the bundled helper scripts (`scripts/*.py` inside several skills). Skills call them as `${CLAUDE_SKILL_DIR}/scripts/<name>.py`, which Claude Code fills in with the skill's own folder; in other agents, replace it with the folder where you installed the skill. When a script cannot run, each skill says whether it falls back to a manual step or stops
  174. - `pre-push` includes both `scan_secrets.py` (preferred) and `scan_secrets.pl` (Perl fallback). Optional: `ruff` (changed-line lint) and `gitleaks` (second secret-scan engine, warning only)
  175. ### Files the session skills read and write
  176. `session-start`, `session-checkpoint`, `next-action`, `project-overview`, `skill-ops` and `collab-audit` share a few plain-text files: a session handoff, `tasks/lessons.md`, `~/.claude/STATE.md`, `memory/MEMORY.md`, a context log and an invocation log. None of them is required — a skill skips the step when the file is missing. Formats: [docs/FILE-CONVENTIONS.md](docs/FILE-CONVENTIONS.md).
  177. ### Optional agents and skills not included here
  178. Some skills can hand work to agents or skills that this repo does **not** ship. Each mention in a SKILL.md is labeled optional and has a fallback, so nothing breaks without them:
  179. | Name | Used by | Without it |
  180. |------|---------|------------|
  181. | `code-reviewer`, `security-reviewer`, `database-reviewer`, `build-error-resolver` | pre-push | `/setup` can generate these agents; otherwise pre-push runs an inline review (code-autopsy FAST MODE) and marks agent steps SKIPPED |
  182. | `refactor-cleaner` | pre-push | step skipped |
  183. | `doubt-reviewer` | scope (Full mode), goal-lock | a general-purpose subagent with an adversarial prompt, or SKIPPED in the report |
  184. | `verification`, `brainstorming`, `check-harness`, `memory-dream`, `forge` | various see-also / routing notes | pointers only — the skill works without them |
  185. ---
  186. ## Agentic Design Patterns Coverage
  187. The skills map to 18 agentic design patterns from the published catalogs ([Gulli 2026](https://books.google.com/books/about/Agentic_Design_Patterns.html?id=QqR20QEACAAJ), [Sairahul 2026](https://x.com/sairahul1/status/2069045570556383464)):
  188. | Pattern | Implemented by | How |
  189. |---------|---------------|-----|
  190. | **Sequential Pipeline** | session-start → scope → goal-lock → pre-push → checkpoint | Full lifecycle chain |
  191. | **Parallel Execution** | pre-push | Parallel AI code review agents |
  192. | **Loop (Retry)** | goal-lock | VERIFY fail → PLAN re-entry, capped retries |
  193. | **Review & Critique** | pre-push, code-autopsy, full-audit, eval-leakage-audit | Independent reviewer subagents (optional — see above) or an inline review; 12Q structured review; full-audit's Phase 2 fan-out reviewer pass; eval-leakage-audit critiques whether an eval secures independent ground truth vs circular self-confirmation |
  194. | **Iterative Refinement** | goal-lock | PLAN→DO→VERIFY→FINALIZE until DONE EVIDENCE passes |
  195. | **Coordinator/Router** | setup | Agent routing rules generation |
  196. | **Plan-and-Execute** | goal-lock, scope | Plan reviewable before execution |
  197. | **ReAct** | project-check | Investigate → score → recommend path |
  198. | **Reflexion** | session-checkpoint | Phase 1.7: analyze failures → lessons for next session |
  199. | **Human-in-the-Loop** | goal-lock, pre-push, integration-intake | STOP RULES, Critical/High blocks push; integration-intake's 5-item screening gate before adoption |
  200. | **Custom Logic** | pre-push | Deterministic secrets scan (Python, Perl fallback) + AI review |
  201. | **Event-Driven** | session-start | Triggered on session open, loads prior state |
  202. | **Guardrails/Safety** | goal-lock, clean-room | 16 success masquerading patterns detected; clean-room isolates safety-adjacent scope into a carved-out subagent run |
  203. | **Memory Management** | session-checkpoint, doc-drift | Handoff file + memory updates + lesson extraction; doc-drift audits the memory/docs loaded into context for outdated claims, contradictions, and risky wording |
  204. | **Goal Setting** | goal-lock | GOAL + DONE EVIDENCE input sheet |
  205. | **Step-Back Abstraction** | stepback | DeepMind step-back: concrete → abstract principle |
  206. | **Prioritization** | next-action | Ranks candidate actions from handoff/git/lessons/STATE by impact |
  207. | **Evaluation & Monitoring** | skill-ops, skill-trigger-auditor, project-overview | Usage health per skill; routing precision/recall on holdout prompts; stale-snapshot report across projects |
  208. ---
  209. ## Design Principles
  210. 1. **Interview over template** — Skills ask questions and generate filled content, not empty skeletons
  211. 2. **Verification over trust** — DONE EVIDENCE must be executed, not assumed. "It should pass" is not verification
  212. 3. **Scope before code** — Define IN/OUT/exit criteria before touching files. Freeze what you're not changing
  213. 4. **Honest reporting** — WORKING / PARTIAL / BROKEN labels. No silent brokenness, no mock deception
  214. 5. **Session continuity** — Start with handoff, end with checkpoint. Context survives across sessions
  215. ---
  216. ## How Skills Connect
  217. Skills declare relationships via `see_also` (related) and `not_for`
  218. (misuse guardrails) in their frontmatter. Key relationships:
  219. | Skill | Connects to | Relationship |
  220. |-------|-------------|---------------|
  221. | `scope` | `goal-lock`, `freeze` | scope defines what to build; freeze locks the editable zone; goal-lock enforces the execution loop |
  222. | `freeze` | `scope`, `goal-lock` | freeze is the manual zone-lock companion to scope's planning and goal-lock's loop enforcement |
  223. | `goal-lock` | `scope`, `freeze` | goal-lock is the execution-time discipline layer that scope/freeze set boundaries for |
  224. | `stepback` | `next-action` | stepback checks direction ("am I solving the right problem"), next-action recommends what to do ("what's next by impact") |
  225. | `next-action` | `session-start`, `stepback` | next-action reads current state for recommendations; session-start restores prior-session state |
  226. | `session-start` | `session-checkpoint` | lifecycle pair — open and close a session |
  227. | `session-checkpoint` | `session-start`, `setup` | closes a session; setup opens a new project |
  228. | `code-autopsy` | `pre-push` | code-autopsy is a deep, on-demand 12Q review; pre-push runs a faster automated pipeline before every push |
  229. | `skill-ops` | `project-overview` | skill-ops manages skill/agent lifecycle (snapshot/rollback/usage); project-overview aggregates status across multiple projects |
  230. | `integration-intake` | `full-audit` | integration-intake gates a single external adoption decision; full-audit sweeps an entire area (including your existing skill/agent inventory) for drift or gaps |
  231. | `full-audit` | `code-autopsy`, `project-check` | full-audit is a broader, multi-area sweep with a persistent coverage map; code-autopsy stays per-file/12Q, project-check stays a 4-dimension score |
  232. | `clean-room` | `goal-lock` | clean-room fires when a task's scope mixes safety-adjacent material with safe work, mid-execution; goal-lock is the surrounding PLAN→DO→VERIFY loop it interrupts |
  233. | `doc-drift` | `full-audit` | doc-drift audits only the memory/docs loaded into context (CLAUDE.md/MEMORY.md/skills/agents) for drift and contradictions; full-audit sweeps an entire area with a coverage map |
  234. | `eval-leakage-audit` | `full-audit`, `code-autopsy` | eval-leakage-audit checks whether an eval/metric/holdout is circular (measurement integrity); full-audit and code-autopsy review code/areas, not the eval's independence |
  235. | `ssot-audit` | `doc-drift`, `full-audit` | ssot-audit follows one fact across files and picks the source of truth; doc-drift checks loaded context for drift; full-audit sweeps a whole area |
  236. | `skill-trigger-auditor` | `skill-ops`, `doc-drift` | skill-trigger-auditor checks whether skills fire on the right prompts; skill-ops tracks whether they are used and rolls them back; doc-drift checks their text for outdated claims |
  237. | `project-check` | `setup`, `collab-audit` | project-check scores a repo's setup and lists gaps (setup fills them); collab-audit looks at how you work with the AI, not at the repo |
  238. Diagram (arrows = "hands off to" / "informs"):
  239. ```
  240. setup ──> scope ──> freeze ──> goal-lock ──> pre-push
  241. │
  242. stepback (anytime, any stage)
  243. │
  244. session-start <──> session-checkpoint
  245. │
  246. next-action (reads state, recommends)
  247. │
  248. integration-intake / full-audit / clean-room / eval-leakage-audit / doc-drift / ssot-audit
  249. (on-demand governance & audits, any stage)
  250. │
  251. skill-ops / skill-trigger-auditor / project-overview
  252. (for skill authors and multi-project setups)
  253. ```
  254. ---
  255. ## Changelog
  256. See [CHANGELOG.md](CHANGELOG.md) for the full version history (v3.0 → latest).
  257. ## License
  258. MIT — see [LICENSE](LICENSE).
  259. ## Contributing
  260. Issues and PRs welcome. If you build a skill that fits the lifecycle, open a PR.
  261. ## Contact
  262. DM [@AlexZio00](https://x.com/AlexZio00) for custom skill development.
pre-push/scripts/scan_secrets.py · Bundled script · 286 lines
  1. #!/usr/bin/env python3
  2. """scan_secrets.py -- deterministic secrets scanner for git diffs.
  3. Usage: git diff --staged | python scan_secrets.py (run from the skill's scripts/ folder or by full path)
  4. Exit code: 0 = clean, 1 = issues found
  5. Design: scans ONLY added (+) lines to avoid blocking secret removal commits.
  6. Exception: merge conflict markers are checked on all lines (added + context).
  7. Ported from scan_secrets.pl (coinangel/claude-pre-push-skill, MIT). Regex patterns and
  8. anti-evasion defenses are preserved 1:1 from the Perl original; the regression suite
  9. (test_scan_secrets.py) re-verifies parity.
  10. Hardening notes (internal revision history, not a version table):
  11. - STDIN is decoded as UTF-8 and every line is normalized (zero-width characters, smart quotes,
  12. homoglyphs) before any rule runs.
  13. - A whole-line-reversed copy is re-scanned with the unanchored tight-form rules, and
  14. "A" + "B" quote concatenation is collapsed into one literal before matching.
  15. - Not fixed on purpose: cross-line credential splitting, and a looser f4b prefix-tolerant anchor
  16. (both need their own design and a calibration corpus).
  17. - Same-line allow marker: an added line that carries `scan-secrets: allow` or
  18. `gitleaks:allow` after a comment leader (`#`, `//`, `/*`, `--`, `;`) skips credential
  19. checks for that one line only (merge-conflict detection is never suppressible). Every skip is
  20. counted and printed to stderr as `[ALLOW] N added line(s) skipped ...`, so a marker cannot
  21. silently swallow a finding.
  22. """
  23. from __future__ import annotations
  24. import re
  25. import sys
  26. from collections.abc import Iterable
  27. # ── Normalization (defangs zero-width / smart-quote / homoglyph evasion) ──
  28. _ZERO_WIDTH_RE = re.compile("[​‌‍]")
  29. _CURLY_QUOTES = str.maketrans({
  30. "‘": "'", "’": "'", "“": '"', "”": '"',
  31. })
  32. _CYRILLIC_HOMOGLYPHS = str.maketrans({
  33. "а": "a", "е": "e", "о": "o", "р": "p",
  34. "с": "c", "у": "y", "х": "x", "і": "i",
  35. "ј": "j", "ѕ": "s",
  36. })
  37. # collapse "A" + "B" (+ "C" ...) quote+operator concatenation into one literal
  38. _CONCAT_RE = re.compile(r"""(["'])([^"']*)\1(\s*\+\s*)(["'])([^"']*)\4""")
  39. def _collapse_concat(line: str) -> str:
  40. while True:
  41. new_line, n = _CONCAT_RE.subn(r"\1\2\5\1", line)
  42. if n == 0:
  43. return line
  44. line = new_line
  45. def _normalize(line: str) -> str:
  46. line = _ZERO_WIDTH_RE.sub("", line)
  47. line = line.translate(_CURLY_QUOTES)
  48. line = line.translate(_CYRILLIC_HOMOGLYPHS)
  49. return _collapse_concat(line)
  50. # ── Merge conflict markers — checked on ALL lines (added + unchanged context) ──
  51. _MERGE_RE = re.compile(r"^[+ ](<{7} |={7}\s*$|>{7} )")
  52. # ── Same-line allow marker: skips credential checks for that one added line
  53. # only. Merge-conflict detection above still applies (never suppressible).
  54. # Skips are counted and reported by main() so a silent bypass isn't possible. ──
  55. _ALLOW_RE = re.compile(r"(?:#|//|/\*|--|;)\s*(?:scan-secrets:\s*allow|gitleaks:allow)\b")
  56. LAST_ALLOWED_COUNT = 0
  57. # ── f1: AWS Access Key ID (AKIA=long-term, ASIA=STS/temporary) ──
  58. _F1_RE = re.compile(r"(?:AKIA|ASIA)[0-9A-Z]{16}")
  59. # ── f2: Private key header — RSA/EC/DSA/OpenSSH/generic/PKCS8-ENCRYPTED, PGP
  60. # block, and the 4-dash SSH2/Tectia export variant ──
  61. _F2_RE = re.compile(
  62. r"-{4,5}\s?BEGIN\s+(?:[A-Z0-9]+\s+){0,3}PRIVATE\s+KEY(?:\s+BLOCK)?\s?-{4,5}"
  63. )
  64. # ── f3: Password embedded in connection/DSN string (skip ${VAR}/$(cmd)
  65. # templates — scoped to the matched credential substring only) ──
  66. # userinfo cannot hold / ? # (RFC 3986) - without this a URL path/query (e.g. a Google Fonts
  67. # "family=JetBrains+Mono:wght@400") reads as user:password@host. An empty user (redis://:pw@h) is allowed.
  68. _F3_RE = re.compile(r"""(://[^\s:@/?#]*:[^\s@]{4,}@)""")
  69. _F3_TEMPLATE_RE = re.compile(r"\$\{|\$\(")
  70. # ── f4a: Hardcoded credential assignment — quoted value (6+ chars) ──
  71. _F4A_RE = re.compile(
  72. r"""(password|passwd|pwd|secret|api_key|apikey|access_token|auth_token"""
  73. r"""|bearer_token|jwt_secret|github_token|gh_token)\s*[=:]\s*"""
  74. r"""['"][^'"]{6,}['"]""",
  75. re.IGNORECASE,
  76. )
  77. # ── f4b: Hardcoded credential assignment — unquoted YAML/ENV value
  78. # Anchored to start of added line to avoid matching inside string/comments ──
  79. _F4B_RE = re.compile(
  80. r"""^\+\s*(PASSWORD|PASSWD|PWD|SECRET|API_KEY|APIKEY|ACCESS_TOKEN"""
  81. r"""|AUTH_TOKEN|BEARER_TOKEN|JWT_SECRET|GITHUB_TOKEN|GH_TOKEN)[_A-Z0-9]*"""
  82. r"""\s*[=:]\s*[^\s'"#$\{]{6,}""",
  83. re.IGNORECASE,
  84. )
  85. # ── f5: Platform tokens — Slack / GitHub (5 types) / Stripe live ──
  86. _F5_RE = re.compile(
  87. r"xox[baprs]-[0-9A-Za-z\-]+|gh[poushr]_[0-9A-Za-z]{20,}"
  88. r"|github_pat_[A-Za-z0-9_]{50,}|sk_live_[0-9A-Za-z]+|pk_live_[0-9A-Za-z]+"
  89. )
  90. # ── f6: Secret in Dockerfile ENV/ARG directive — anchored so ENV/ARG must be
  91. # the leading instruction token, not a substring of ordinary prose ──
  92. _F6_RE = re.compile(
  93. r"^\+\s*(?:ENV|ARG)\s+\w*(?:PASSWORD|SECRET|KEY|TOKEN)\w*[\s=]",
  94. re.IGNORECASE,
  95. )
  96. # ── f7: Google / Gemini API Key (AIza + 35 alphanumeric chars) ──
  97. _F7_RE = re.compile(r"AIza[0-9A-Za-z\-_]{35}")
  98. # ── f8: npm registry auth token (.npmrc) — whitespace-around-'=' tolerant ──
  99. _F8_RE = re.compile(r"_authToken\s*=\s*[A-Za-z0-9\-_]{20,}")
  100. # ── f9: LLM provider API keys (Anthropic/OpenAI/HuggingFace/Replicate/Groq/xAI) ──
  101. _F9_RE = re.compile(
  102. r"sk-ant-[A-Za-z0-9_\-]{20,}|sk-proj-[A-Za-z0-9_\-]{20,}"
  103. r"|sk-svcacct-[A-Za-z0-9_\-]{20,}|sk-[A-Za-z0-9]{48}(?![a-z])"
  104. r"|hf_[A-Za-z0-9]{30,}|r8_[A-Za-z0-9]{30,}|gsk_[A-Za-z0-9]{40,}"
  105. r"|xai-[A-Za-z0-9]{20,}"
  106. )
  107. # ── f10: Azure credentials — Storage Account Key / SAS token sig / conn string ──
  108. _F10_RE = re.compile(
  109. r"AccountKey=[A-Za-z0-9+/]{86}==|(?:[?&]|&amp;)sig=[A-Za-z0-9%+/]{30,}"
  110. r"|DefaultEndpointsProtocol=https;AccountName=",
  111. re.IGNORECASE,
  112. )
  113. # ── f11: Prompt injection strings embedded in code (supply-chain prompt attack) ──
  114. _F11_RE = re.compile(
  115. r"""["'](?:[^"']*?)(?:ignore\s+(?:previous|all\s+previous)\s+instructions"""
  116. r"""|disregard\s+(?:your\s+)?(?:instructions|guidelines|system\s+prompt)"""
  117. r"""|you\s+are\s+now\s+(?:a|an)\s+\w+\s+without\s+(?:restrictions|limits)"""
  118. r"""|forget\s+(?:everything|your\s+previous|all\s+previous)"""
  119. r"""|system\s+prompt\s+override|jailbreak\s+mode\s+enabled)"""
  120. r"""(?:[^"']*?)["']""",
  121. re.IGNORECASE,
  122. )
  123. # ── f12: Supply-chain risk — non-standard package sources ──
  124. _F12_EXTRA_INDEX_RE = re.compile(
  125. r"--extra-index-url\s+(?!https?://(?:pypi\.org|files\.pythonhosted\.org))",
  126. re.IGNORECASE,
  127. )
  128. _F12_INDEX_RE = re.compile(
  129. r"--index-url\s+(?!https?://(?:pypi\.org|files\.pythonhosted\.org))",
  130. re.IGNORECASE,
  131. )
  132. _F12_GIT_HTTP_RE = re.compile(r"git\+http://", re.IGNORECASE)
  133. # ── f13: Slack Incoming Webhook URL ──
  134. _F13_RE = re.compile(r"hooks\.slack\.com/services/[A-Za-z0-9]+/[A-Za-z0-9]+/[A-Za-z0-9]+")
  135. # Reversed-line defense: applied only to unanchored/tight-form rules. Anchored
  136. # or keyword-proximity rules (f3/f4a/f4b/f6/f11/f12) are excluded — reversal
  137. # breaks their intended semantics and would just add false-positive surface.
  138. _REVERSED_PATTERNS = (_F1_RE, _F2_RE, _F5_RE, _F7_RE, _F8_RE, _F9_RE, _F10_RE, _F13_RE)
  139. _REVERSED_KEYS = ("f1", "f2", "f5", "f7", "f8", "f9", "f10", "f13")
  140. _MESSAGES = (
  141. ("f_merge", "CRITICAL", "Unresolved merge conflict markers detected"),
  142. ("f1", "CRITICAL", "AWS Access Key ID detected"),
  143. ("f2", "CRITICAL", "Private key detected"),
  144. ("f3", "CRITICAL", "Password in connection string detected"),
  145. ("f4a", "HIGH", "Hardcoded credential assignment (quoted value) detected"),
  146. ("f4b", "HIGH", "Hardcoded credential assignment (unquoted YAML/ENV) detected"),
  147. ("f5", "CRITICAL", "Platform token detected (Slack / GitHub / Stripe)"),
  148. ("f6", "CRITICAL", "Secret in Dockerfile ENV directive"),
  149. ("f7", "CRITICAL", "Google / Gemini API Key detected"),
  150. ("f8", "HIGH", "npm registry auth token detected"),
  151. ("f9", "CRITICAL", "LLM provider API key detected (Anthropic / OpenAI / HuggingFace / Replicate / Groq)"),
  152. ("f10", "CRITICAL", "Azure credential detected (Storage Key / SAS token / connection string)"),
  153. ("f11", "HIGH", "Prompt injection string detected in code (LLM supply-chain attack risk)"),
  154. ("f12", "HIGH", "Supply-chain risk detected (non-PyPI index URL or HTTP git install)"),
  155. ("f13", "HIGH", "Slack Incoming Webhook URL detected"),
  156. )
  157. assert len(_REVERSED_KEYS) == len(_REVERSED_PATTERNS) # zip() without strict= (Python 3.9)
  158. def scan_lines(lines: Iterable[str]) -> dict:
  159. """Pure decision function: scan an already-split sequence of diff lines and return the flag dict.
  160. No file or STDIN I/O, so tests can call it directly (no subprocess or perl needed)."""
  161. global LAST_ALLOWED_COUNT
  162. flags = {key: False for key, _, _ in _MESSAGES}
  163. allowed = 0
  164. for raw_line in lines:
  165. line = _normalize(raw_line)
  166. if _MERGE_RE.search(line):
  167. flags["f_merge"] = True
  168. if not line.startswith("+"):
  169. continue
  170. if line.startswith("+++"):
  171. continue
  172. if _ALLOW_RE.search(line):
  173. allowed += 1
  174. continue
  175. # Runtime-reversal defense: a value written backwards in source
  176. # contains the real secret as a contiguous substring once the WHOLE
  177. # LINE is reversed. Only unanchored, tight-form rules are re-checked.
  178. reversed_line = line[::-1]
  179. for key, pattern in zip(_REVERSED_KEYS, _REVERSED_PATTERNS):
  180. if pattern.search(reversed_line):
  181. flags[key] = True
  182. if _F1_RE.search(line):
  183. flags["f1"] = True
  184. if _F2_RE.search(line):
  185. flags["f2"] = True
  186. m3 = _F3_RE.search(line)
  187. if m3 and not _F3_TEMPLATE_RE.search(m3.group(1)):
  188. flags["f3"] = True
  189. if _F4A_RE.search(line):
  190. flags["f4a"] = True
  191. if _F4B_RE.search(line):
  192. flags["f4b"] = True
  193. if _F5_RE.search(line):
  194. flags["f5"] = True
  195. if _F6_RE.search(line):
  196. flags["f6"] = True
  197. if _F7_RE.search(line):
  198. flags["f7"] = True
  199. if _F8_RE.search(line):
  200. flags["f8"] = True
  201. if _F9_RE.search(line):
  202. flags["f9"] = True
  203. if _F10_RE.search(line):
  204. flags["f10"] = True
  205. if _F11_RE.search(line):
  206. flags["f11"] = True
  207. if (_F12_EXTRA_INDEX_RE.search(line) or _F12_INDEX_RE.search(line)
  208. or _F12_GIT_HTTP_RE.search(line)):
  209. flags["f12"] = True
  210. if _F13_RE.search(line):
  211. flags["f13"] = True
  212. LAST_ALLOWED_COUNT = allowed
  213. return flags
  214. def format_report(flags: dict) -> str:
  215. out = []
  216. for key, severity, text in _MESSAGES:
  217. if flags.get(key):
  218. out.append(f"\U0001f6a8 {severity}: {text}")
  219. return "\n".join(out)
  220. def main() -> int:
  221. # Diffs are UTF-8 and the report contains emoji; the console default (cp949, cp1252, ...) would
  222. # crash on either, so force UTF-8 and never fail on an undecodable byte.
  223. for stream in (sys.stdin, sys.stdout, sys.stderr):
  224. if hasattr(stream, "reconfigure"):
  225. stream.reconfigure(encoding="utf-8", errors="replace")
  226. lines = [line.rstrip("\r\n") for line in sys.stdin]
  227. flags = scan_lines(lines)
  228. if LAST_ALLOWED_COUNT:
  229. print(
  230. f"[ALLOW] {LAST_ALLOWED_COUNT} added line(s) skipped by an allow marker "
  231. "(scan-secrets: allow / gitleaks:allow) - review them in the diff",
  232. file=sys.stderr,
  233. )
  234. if any(flags.values()):
  235. print(format_report(flags))
  236. return 1
  237. return 0
  238. if __name__ == "__main__":
  239. sys.exit(main())
session-checkpoint/scripts/test_ct_promotion_queue.py · Bundled script · 449 lines · 1 finding marked
  1. """test_ct_promotion_queue.py — regression tests for ct_promotion_queue."""
  2. from __future__ import annotations
  3. import os
  4. import subprocess
  5. import sys
  6. import tempfile
  7. sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
  8. import ct_promotion_queue as ctq
  9. SCRIPT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "ct_promotion_queue.py")
  10. CASES = []
  11. def case(name, fn):
  12. CASES.append((name, fn))
  13. # 1. is_enabled: no marker -> False
  14. def _is_enabled_false():
  15. with tempfile.TemporaryDirectory() as td:
  16. marker = os.path.join(td, "memory-ct-autopatch.enabled")
  17. return ctq.is_enabled(marker) is False
  18. case("is_enabled: marker missing -> False", _is_enabled_false)
  19. # 2. is_enabled: marker present -> True
  20. def _is_enabled_true():
  21. with tempfile.TemporaryDirectory() as td:
  22. marker = os.path.join(td, "memory-ct-autopatch.enabled")
  23. with open(marker, "w", encoding="utf-8") as f:
  24. f.write("")
  25. return ctq.is_enabled(marker) is True
  26. case("is_enabled: marker present -> True", _is_enabled_true)
  27. # 3. extract_entries: only date-bracket lines, 1-indexed lineno, with/without leading dash
  28. case("extract_entries: only date-bracket lines, 1-index lineno, optional leading dash", lambda: ctq.extract_entries(
  29. "unrelated header\n[2026-08-01] [EVENT] [ttl:30d] [ref:0] content1\nunrelated line\n- [2026-08-02] [EVENT] [ttl:30d] [ref:0] content2"
  30. ) == [(2, "[2026-08-01] [EVENT] [ttl:30d] [ref:0] content1"), (4, "- [2026-08-02] [EVENT] [ttl:30d] [ref:0] content2")])
  31. # 4. extract_entries: empty text -> empty list
  32. case("extract_entries: empty text -> []", lambda: ctq.extract_entries("") == [])
  33. # 5. tokenize: extracts a file-path-shaped token
  34. case("tokenize: extracts file-path-like token", lambda: "ct_promotion_queue.py" in ctq.tokenize(
  35. "wrote a new script ct_promotion_queue.py"
  36. ))
  37. # 6. tokenize: extracts a quoted phrase
  38. case("tokenize: extracts quoted token", lambda: "core-idea" in ctq.tokenize(
  39. 'the core of this design is "core-idea", a three-stage split'
  40. ))
  41. # 7. tokenize: extracts a proper noun
  42. case("tokenize: extracts proper-noun token", lambda: "Stage" in ctq.tokenize(
  43. "Stage 1 is deterministic, Stage 2 is LLM-based"
  44. ))
  45. # 8. tokenize: excludes generic stopwords
  46. case("tokenize: excludes generic stopword tokens", lambda: "MEMORY" not in ctq.tokenize(
  47. "MEMORY promotion review"
  48. ))
  49. # 8b. tokenize: excludes context-log TYPE tags (EVENT, etc.) — guards against cross-cluster contamination via shared tags
  50. case("tokenize: excludes context-log TYPE tags (EVENT/MILESTONE/etc, cross-cluster contamination guard)", lambda: (
  51. "EVENT" not in ctq.tokenize("[2026-08-01] [EVENT] [ttl:30d] [ref:0] unrelated content")
  52. and "MILESTONE" not in ctq.tokenize("[2026-08-01] [MILESTONE] [ttl:90d] [ref:0] unrelated content")
  53. ))
  54. # 9. cluster_entries: 3 lines sharing a token -> 1 cluster, mention_count=3
  55. def _cluster_related():
  56. entries = [
  57. (1, "ct_promotion_queue.py design discussion"),
  58. (2, "ct_promotion_queue.py implementation start"),
  59. (3, "ct_promotion_queue.py test authoring"),
  60. ]
  61. clusters = ctq.cluster_entries(entries)
  62. return len(clusters) == 1 and clusters[0]["mention_count"] == 3
  63. case("cluster_entries: 3 lines sharing token -> 1 cluster, mention_count=3", _cluster_related)
  64. # 10. cluster_entries: 3 unrelated lines (no shared token) -> no cluster
  65. def _cluster_unrelated():
  66. entries = [
  67. (1, "alpha.py discussion"),
  68. (2, "beta.py discussion"),
  69. (3, "gamma.py discussion"),
  70. ]
  71. clusters = ctq.cluster_entries(entries)
  72. return clusters == []
  73. case("cluster_entries: unrelated lines (no shared token) -> no cluster", _cluster_unrelated)
  74. # 11. cluster_entries: only 2 lines share a token (below T2) -> no cluster
  75. def _cluster_below_threshold():
  76. entries = [
  77. (1, "delta.py discussion1"),
  78. (2, "delta.py discussion2"),
  79. (3, "unrelated content"),
  80. ]
  81. clusters = ctq.cluster_entries(entries)
  82. return clusters == []
  83. case("cluster_entries: only 2 shared-token lines (below T2) -> no cluster", _cluster_below_threshold)
  84. # 12. cluster_entries: realistic format (with TYPE tag) — two distinct topics must NOT merge just from sharing a tag (key regression)
  85. def _cluster_no_tag_contamination():
  86. entries = [
  87. (1, "[2026-08-01] [EVENT] [ttl:30d] [ref:0] newfeature.py design"),
  88. (2, "[2026-08-01] [EVENT] [ttl:30d] [ref:0] newfeature.py implementation"),
  89. (3, "[2026-08-01] [EVENT] [ttl:30d] [ref:0] newfeature.py test"),
  90. (4, "[2026-08-01] [EVENT] [ttl:30d] [ref:0] oldfeature.py design"),
  91. (5, "[2026-08-01] [EVENT] [ttl:30d] [ref:0] oldfeature.py implementation"),
  92. (6, "[2026-08-01] [EVENT] [ttl:30d] [ref:0] oldfeature.py test"),
  93. ]
  94. clusters = ctq.cluster_entries(entries)
  95. topics = sorted(ctq.summarize_topic(c) for c in clusters)
  96. return len(clusters) == 2 and topics == ["newfeature.py", "oldfeature.py"]
  97. case("cluster_entries: shared [EVENT] tag alone must NOT merge unrelated topics", _cluster_no_tag_contamination)
  98. # 13. summarize_topic: most frequent token, ties broken alphabetically
  99. def _summarize_topic_basic():
  100. cluster = {"lines": [
  101. (1, "ct_promotion_queue.py design"),
  102. (2, "ct_promotion_queue.py implementation"),
  103. (3, "ct_promotion_queue.py test"),
  104. ]}
  105. return ctq.summarize_topic(cluster) == "ct_promotion_queue.py"
  106. case("summarize_topic: most frequent token wins", _summarize_topic_basic)
  107. # 14. ct_topic_exists: present -> True
  108. case("ct_topic_exists: substring present -> True", lambda: ctq.ct_topic_exists(
  109. "## Section\n- adopted ct_promotion_queue.py", "ct_promotion_queue.py"
  110. ) is True)
  111. # 15. ct_topic_exists: absent -> False
  112. case("ct_topic_exists: substring absent -> False", lambda: ctq.ct_topic_exists(
  113. "## Section\n- unrelated content", "ct_promotion_queue.py"
  114. ) is False)
  115. # 16. load_queue_records: missing file -> []
  116. def _load_queue_missing():
  117. with tempfile.TemporaryDirectory() as td:
  118. return ctq.load_queue_records(os.path.join(td, "nope.jsonl")) == []
  119. case("load_queue_records: missing file -> []", _load_queue_missing)
  120. # 17. load_queue_records: parses valid JSONL, skips corrupted lines
  121. def _load_queue_parses_valid_skips_broken():
  122. with tempfile.TemporaryDirectory() as td:
  123. path = os.path.join(td, "q.jsonl")
  124. with open(path, "w", encoding="utf-8") as f:
  125. f.write('{"topic_summary":"a","status":"queued"}\n')
  126. f.write("not json\n")
  127. f.write('{"topic_summary":"b","status":"drafted"}\n')
  128. records = ctq.load_queue_records(path)
  129. return len(records) == 2 and records[0]["topic_summary"] == "a" and records[1]["topic_summary"] == "b"
  130. case("load_queue_records: parses valid lines, skips malformed", _load_queue_parses_valid_skips_broken)
  131. # 18. append_record: creates file+directory fresh, then appends
  132. def _append_record_creates_dir_and_file():
  133. with tempfile.TemporaryDirectory() as td:
  134. path = os.path.join(td, "sub", "q.jsonl")
  135. ctq.append_record({"topic_summary": "x", "status": "queued"}, path)
  136. records = ctq.load_queue_records(path)
  137. return len(records) == 1 and records[0]["topic_summary"] == "x"
  138. case("append_record: creates parent dir + appends JSONL", _append_record_creates_dir_and_file)
  139. # 19. is_duplicate_in_queue: matching topic_summary + queued status + scope -> True
  140. # (a real record always has "scope" filled by build_record(), so including scope in the fixture is
  141. # realistic — covers the added scope/project_path matching, fixed by code-reviewer 2026-08-02, HIGH)
  142. case("is_duplicate_in_queue: matches queued status + scope -> True", lambda: ctq.is_duplicate_in_queue(
  143. "topic-a", [{"topic_summary": "topic-a", "status": "queued", "scope": "global"}]
  144. ) is True)
  145. # 20. is_duplicate_in_queue: applied status is excluded from duplicate detection -> False
  146. case("is_duplicate_in_queue: applied status excluded -> False", lambda: ctq.is_duplicate_in_queue(
  147. "topic-a", [{"topic_summary": "topic-a", "status": "applied", "scope": "global"}]
  148. ) is False)
  149. # 21. check_resurfaced: no tombstones directory -> False
  150. def _check_resurfaced_no_dir():
  151. with tempfile.TemporaryDirectory() as td:
  152. return ctq.check_resurfaced({"foo"}, os.path.join(td, "nope")) is False
  153. case("check_resurfaced: tombstones dir missing -> False", _check_resurfaced_no_dir)
  154. # 22. check_resurfaced: 3+ tokens match -> True
  155. def _check_resurfaced_match():
  156. with tempfile.TemporaryDirectory() as td:
  157. tpath = os.path.join(td, "2026-07.jsonl")
  158. with open(tpath, "w", encoding="utf-8") as f:
  159. f.write('{"item_summary":"ct_promotion_queue.py stage1 clustering rejected design"}\n')
  160. tokens = {"ct_promotion_queue.py", "stage1", "clustering"}
  161. return ctq.check_resurfaced(tokens, td) is True
  162. case("check_resurfaced: 3+ token match -> True", _check_resurfaced_match)
  163. # 23. check_resurfaced: only 2 tokens match (below threshold) -> False
  164. def _check_resurfaced_below_threshold():
  165. with tempfile.TemporaryDirectory() as td:
  166. tpath = os.path.join(td, "2026-07.jsonl")
  167. with open(tpath, "w", encoding="utf-8") as f:
  168. f.write('{"item_summary":"ct_promotion_queue.py stage1 unrelated"}\n')
  169. tokens = {"ct_promotion_queue.py", "stage1", "unrelated-token"}
  170. return ctq.check_resurfaced(tokens, td) is False
  171. case("check_resurfaced: only 2 token match (below threshold) -> False", _check_resurfaced_below_threshold)
  172. # 24. build_record: project_path included only when scope=project
  173. def _build_record_project_path():
  174. cluster = {"lines": [(1, "a"), (2, "a"), (3, "a")], "mention_count": 3}
  175. rec_project = ctq.build_record(cluster, "context-log.md", "project", "D:\\ProjectA", "clean:internal", False)
  176. rec_global = ctq.build_record(cluster, "context-log.md", "global", None, "clean:internal", False)
  177. return "project_path" in rec_project and "project_path" not in rec_global
  178. case("build_record: project_path only when scope=project", _build_record_project_path)
  179. # 25. build_record: flag included only when resurfaced=True
  180. def _build_record_resurfaced_flag():
  181. cluster = {"lines": [(1, "a"), (2, "a"), (3, "a")], "mention_count": 3}
  182. rec_flagged = ctq.build_record(cluster, "context-log.md", "global", None, "clean:internal", True)
  183. rec_clean = ctq.build_record(cluster, "context-log.md", "global", None, "clean:internal", False)
  184. return rec_flagged.get("flag") == "resurfaced" and "flag" not in rec_clean
  185. case("build_record: flag=resurfaced only when resurfaced=True", _build_record_resurfaced_flag)
  186. # 26. run_scan: no opt-in marker -> doesn't even create the queue file (confirms the opt-in requirement is actually enforced)
  187. def _run_scan_disabled_no_write():
  188. with tempfile.TemporaryDirectory() as td:
  189. marker = os.path.join(td, "marker.enabled") # deliberately not created
  190. queue = os.path.join(td, "queue.jsonl")
  191. log_path = os.path.join(td, "context-log.md")
  192. with open(log_path, "w", encoding="utf-8") as f:
  193. f.write("[2026-08-01] [EVENT] [ttl:30d] [ref:0] x.py discussion\n")
  194. result = ctq.run_scan(log_path, os.path.join(td, "MEMORY.md"), os.path.join(td, "tomb"),
  195. queue, marker, "global", None, "clean:internal")
  196. return result == {"enabled": False} and not os.path.exists(queue)
  197. case("run_scan: opt-in disabled -> no queue file written", _run_scan_disabled_no_write)
  198. # 27. run_scan: end-to-end 3-line cluster -> 1 enqueue, a topic already in CT only increments the skip count
  199. def _run_scan_end_to_end():
  200. with tempfile.TemporaryDirectory() as td:
  201. marker = os.path.join(td, "marker.enabled")
  202. with open(marker, "w", encoding="utf-8") as f:
  203. f.write("")
  204. queue = os.path.join(td, "queue.jsonl")
  205. log_path = os.path.join(td, "context-log.md")
  206. with open(log_path, "w", encoding="utf-8") as f:
  207. f.write(
  208. "[2026-08-01] [EVENT] [ttl:30d] [ref:0] newfeature.py design\n"
  209. "[2026-08-01] [EVENT] [ttl:30d] [ref:0] newfeature.py implementation\n"
  210. "[2026-08-01] [EVENT] [ttl:30d] [ref:0] newfeature.py test\n"
  211. "[2026-08-01] [EVENT] [ttl:30d] [ref:0] oldfeature.py design\n"
  212. "[2026-08-01] [EVENT] [ttl:30d] [ref:0] oldfeature.py implementation\n"
  213. "[2026-08-01] [EVENT] [ttl:30d] [ref:0] oldfeature.py test\n"
  214. )
  215. memory_md = os.path.join(td, "MEMORY.md")
  216. with open(memory_md, "w", encoding="utf-8") as f:
  217. f.write("## Current Status\n- oldfeature.py already in CT\n")
  218. result = ctq.run_scan(log_path, memory_md, os.path.join(td, "tomb"), queue, marker,
  219. "global", None, "clean:internal")
  220. records = ctq.load_queue_records(queue)
  221. return (
  222. result["enqueued"] == 1
  223. and result["skipped_ct_exists"] == 1
  224. and len(records) == 1
  225. and records[0]["topic_summary"] == "newfeature.py"
  226. and records[0]["mention_count"] == 3
  227. )
  228. case("run_scan: end-to-end enqueues new topic, skips CT-existing topic", _run_scan_end_to_end)
  229. # 28. run_scan: a cluster matching a tombstone -> resurfaced count + record flag set ("resurfacing" requirement)
  230. def _run_scan_resurfaced_flag():
  231. with tempfile.TemporaryDirectory() as td:
  232. marker = os.path.join(td, "marker.enabled")
  233. with open(marker, "w", encoding="utf-8") as f:
  234. f.write("")
  235. tomb_dir = os.path.join(td, "tomb")
  236. os.makedirs(tomb_dir)
  237. with open(os.path.join(tomb_dir, "2026-07.jsonl"), "w", encoding="utf-8") as f:
  238. f.write('{"item_summary":"ghosttopic.py clusterx legacy rejected design"}\n')
  239. log_path = os.path.join(td, "context-log.md")
  240. with open(log_path, "w", encoding="utf-8") as f:
  241. f.write(
  242. "[2026-08-01] [EVENT] [ttl:30d] [ref:0] GhostTopic.py re-discussion 'ClusterX' Legacy\n"
  243. "[2026-08-01] [EVENT] [ttl:30d] [ref:0] GhostTopic.py re-review 'ClusterX' Legacy\n"
  244. "[2026-08-01] [EVENT] [ttl:30d] [ref:0] GhostTopic.py re-confirmation 'ClusterX' Legacy\n"
  245. )
  246. memory_md = os.path.join(td, "MEMORY.md")
  247. with open(memory_md, "w", encoding="utf-8") as f:
  248. f.write("")
  249. queue = os.path.join(td, "queue.jsonl")
  250. result = ctq.run_scan(log_path, memory_md, tomb_dir, queue, marker, "global", None, "clean:internal")
  251. records = ctq.load_queue_records(queue)
  252. return result["resurfaced"] == 1 and len(records) == 1 and records[0].get("flag") == "resurfaced"
  253. case("run_scan: tombstone-matching cluster sets resurfaced flag + count", _run_scan_resurfaced_flag)
  254. # 29. cmd_scan CLI: subprocess integration — prints enabled + summary line, exit 0
  255. def _cli_cmd_scan_smoke():
  256. with tempfile.TemporaryDirectory() as td:
  257. marker = os.path.join(td, "marker.enabled")
  258. with open(marker, "w", encoding="utf-8") as f:
  259. f.write("")
  260. log_path = os.path.join(td, "context-log.md")
  261. with open(log_path, "w", encoding="utf-8") as f:
  262. f.write(
  263. "[2026-08-01] [EVENT] [ttl:30d] [ref:0] clituple.py design\n"
  264. "[2026-08-01] [EVENT] [ttl:30d] [ref:0] clituple.py implementation\n"
  265. "[2026-08-01] [EVENT] [ttl:30d] [ref:0] clituple.py test\n"
  266. )
  267. memory_md = os.path.join(td, "MEMORY.md")
  268. queue = os.path.join(td, "queue.jsonl")
  269. proc = subprocess.run(
  270. [sys.executable, SCRIPT, "scan", "--context-log", log_path, "--memory-md", memory_md,
  271. "--queue", queue, "--marker", marker, "--tombstones-dir", os.path.join(td, "tomb")],
  272. capture_output=True, text=True,
  273. )
  274. return proc.returncode == 0 and "enqueued=1" in proc.stdout
  275. case("cmd_scan CLI: end-to-end subprocess -> exit 0, enqueued=1 in stdout", _cli_cmd_scan_smoke)
  276. # 30. static self-test: memory_md_path is never opened in write/append mode (no-leak oracle)
  277. def _no_memory_md_write_leak():
  278. with open(SCRIPT, encoding="utf-8") as f:
  279. source = f.read()
  280. forbidden = [
  281. 'open(memory_md_path, "w"', "open(memory_md_path, 'w'",
  282. 'open(memory_md_path, "a"', "open(memory_md_path, 'a'",
  283. ]
  284. return not any(p in source for p in forbidden)
  285. case("static: memory_md_path never opened write/append mode (no-leak oracle)", _no_memory_md_write_leak)
  286. # 31. is_duplicate_in_queue: when queued -> expired is appended in that order, the latest (expired) status allows re-queueing (HIGH regression, code-reviewer 2026-08-02)
  287. case("is_duplicate_in_queue: latest-status-wins allows re-queue after resolution", lambda: ctq.is_duplicate_in_queue(
  288. "topic-x", [
  289. {"topic_summary": "topic-x", "status": "queued", "scope": "global"},
  290. {"topic_summary": "topic-x", "status": "expired", "scope": "global"},
  291. ]
  292. ) is False)
  293. # 32. is_duplicate_in_queue: same topic_summary but scope=project + a different project_path -> not a duplicate
  294. case("is_duplicate_in_queue: same topic_summary, different project_path -> not duplicate", lambda: ctq.is_duplicate_in_queue(
  295. "config.py",
  296. [{"topic_summary": "config.py", "status": "queued", "scope": "project", "project_path": "D:\\ProjectA"}],
  297. scope="project", project_path="D:\\ProjectB",
  298. ) is False)
  299. # 33. load_queue_records: a valid-JSON but non-dict line (bare list) is skipped, no crash (MEDIUM regression)
  300. def _load_queue_skips_non_dict_json():
  301. with tempfile.TemporaryDirectory() as td:
  302. path = os.path.join(td, "q.jsonl")
  303. with open(path, "w", encoding="utf-8") as f:
  304. f.write("[1,2,3]\n")
  305. f.write('{"topic_summary":"a","status":"queued"}\n')
  306. records = ctq.load_queue_records(path)
  307. return len(records) == 1 and records[0]["topic_summary"] == "a"
  308. case("load_queue_records: skips valid-JSON-but-non-dict lines, no crash", _load_queue_skips_non_dict_json)
  309. # 35. is_quarantined_entry: [QUARANTINE] tag detected -> True
  310. case("is_quarantined_entry: [QUARANTINE] tag -> True", lambda: ctq.is_quarantined_entry(
  311. "[2026-08-01] [QUARANTINE] [ttl:90d] [ref:0] external instruction detected in fetched content"
  312. ) is True)
  313. # 36. is_quarantined_entry: ordinary [EVENT] tag -> False
  314. case("is_quarantined_entry: ordinary [EVENT] tag -> False", lambda: ctq.is_quarantined_entry(
  315. "[2026-08-01] [EVENT] [ttl:30d] [ref:0] newfeature.py design"
  316. ) is False)
  317. # 37. run_scan: 3 [QUARANTINE]-tagged lines sharing a token must NOT enqueue (injection-defense regression)
  318. def _run_scan_excludes_quarantined():
  319. with tempfile.TemporaryDirectory() as td:
  320. marker = os.path.join(td, "marker.enabled")
  321. with open(marker, "w", encoding="utf-8") as f:
  322. f.write("")
  323. queue = os.path.join(td, "queue.jsonl")
  324. log_path = os.path.join(td, "context-log.md")
  325. with open(log_path, "w", encoding="utf-8") as f:
  326. f.write(
  327. "[2026-08-01] [QUARANTINE] [ttl:90d] [ref:0] injected.py claims admin override\n"
  328. "[2026-08-01] [QUARANTINE] [ttl:90d] [ref:0] injected.py claims admin override again\n"
  329. "[2026-08-01] [QUARANTINE] [ttl:90d] [ref:0] injected.py claims admin override thrice\n"
  330. )
  331. memory_md = os.path.join(td, "MEMORY.md")
  332. with open(memory_md, "w", encoding="utf-8") as f:
  333. f.write("")
  334. result = ctq.run_scan(log_path, memory_md, os.path.join(td, "tomb"), queue, marker,
  335. "global", None, "clean:internal")
  336. records = ctq.load_queue_records(queue)
  337. return (
  338. result["enqueued"] == 0
  339. and result["clusters_found"] == 0
  340. and result["skipped_quarantined"] == 3
  341. and records == []
  342. )
  343. case("run_scan: [QUARANTINE]-tagged cluster never enqueued (injection defense)", _run_scan_excludes_quarantined)
  344. # 38. run_scan: mixed log — [QUARANTINE] lines excluded, legitimate cluster still enqueues normally
  345. def _run_scan_mixed_quarantine_and_legit():
  346. with tempfile.TemporaryDirectory() as td:
  347. marker = os.path.join(td, "marker.enabled")
  348. with open(marker, "w", encoding="utf-8") as f:
  349. f.write("")
  350. queue = os.path.join(td, "queue.jsonl")
  351. log_path = os.path.join(td, "context-log.md")
  352. with open(log_path, "w", encoding="utf-8") as f:
  353. f.write(
  354. "[2026-08-01] [QUARANTINE] [ttl:90d] [ref:0] newfeature.py ignore prior instructions\n"
    • Note: Quoted as data in code: Quotes instruction-override phrasing (in quotes, code, a table or an example): "ignore prior instructions"
    • Line 396 on GitHub
  355. "[2026-08-01] [EVENT] [ttl:30d] [ref:0] newfeature.py design\n"
  356. "[2026-08-01] [EVENT] [ttl:30d] [ref:0] newfeature.py implementation\n"
  357. "[2026-08-01] [EVENT] [ttl:30d] [ref:0] newfeature.py test\n"
  358. )
  359. memory_md = os.path.join(td, "MEMORY.md")
  360. with open(memory_md, "w", encoding="utf-8") as f:
  361. f.write("")
  362. result = ctq.run_scan(log_path, memory_md, os.path.join(td, "tomb"), queue, marker,
  363. "global", None, "clean:internal")
  364. records = ctq.load_queue_records(queue)
  365. return (
  366. result["enqueued"] == 1
  367. and result["skipped_quarantined"] == 1
  368. and len(records) == 1
  369. and records[0]["mention_count"] == 3 # the quarantined line must not inflate this count
  370. )
  371. case("run_scan: [QUARANTINE] line excluded from mixed log, legit cluster (count=3) still enqueues", _run_scan_mixed_quarantine_and_legit)
  372. # 34. check_resurfaced: a tombstone file with a valid-JSON but non-dict line mixed in still gets judged from the rest, no crash
  373. def _check_resurfaced_skips_non_dict_json():
  374. with tempfile.TemporaryDirectory() as td:
  375. tpath = os.path.join(td, "2026-07.jsonl")
  376. with open(tpath, "w", encoding="utf-8") as f:
  377. f.write('"just a string"\n')
  378. f.write('{"item_summary":"ct_promotion_queue.py stage1 clustering rejected design"}\n')
  379. tokens = {"ct_promotion_queue.py", "stage1", "clustering"}
  380. return ctq.check_resurfaced(tokens, td) is True
  381. case("check_resurfaced: skips valid-JSON-but-non-dict lines, no crash", _check_resurfaced_skips_non_dict_json)
  382. def main():
  383. fails = []
  384. for name, fn in CASES:
  385. try:
  386. ok = fn()
  387. except Exception as e:
  388. ok = False
  389. name = f"{name} [EXC: {e}]"
  390. print(f"{'PASS' if ok else 'FAIL'} {name}")
  391. if not ok:
  392. fails.append(name)
  393. print(f"\n{len(CASES) - len(fails)}/{len(CASES)} passed")
  394. return 1 if fails else 0
  395. def test_all_cases():
  396. """pytest entry point: this file uses its own runner, so without this wrapper `pytest` collects
  397. 0 tests and exits 0 (looks like a pass)."""
  398. assert main() == 0
  399. if __name__ == "__main__":
  400. raise SystemExit(main())

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.