Skip to content

armgit / ECC

Public Imported from GitHub
0

The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.

feat(skills): integrate collision-safe story lifecycle from PR 2311

haelyra54925308d7f1
diff --cc .claude-plugin/marketplace.json
index 363cba605,266ad2574..9d2478a07
--- a/.claude-plugin/marketplace.json
+++ b/.claude-plugin/marketplace.json
@@@ -11,7 -11,7 +11,7 @@@
{
"name": "ecc",
"source": "./",
- "description": "Harness-native ECC operator layer - 71 agents, 306 skills, 97 legacy command shims, reusable hooks, rules, selective install profiles, and production-ready workflows for Claude Code, Codex, OpenCode, Cursor, and related agent harnesses",
- "description": "Harness-native ECC operator layer - 68 agents, 294 skills, 94 legacy command shims, reusable hooks, rules, selective install profiles, and production-ready workflows for Claude Code, Codex, OpenCode, Cursor, and related agent harnesses",
++ "description": "Harness-native ECC operator layer - 71 agents, 307 skills, 97 legacy command shims, reusable hooks, rules, selective install profiles, and production-ready workflows for Claude Code, Codex, OpenCode, Cursor, and related agent harnesses",
"version": "2.2.3",
"author": {
"name": "Affaan Mustafa",
diff --cc .claude-plugin/plugin.json
index 810d71650,d1eb21374..cefda529d
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@@ -1,7 -1,7 +1,7 @@@
{
"name": "ecc",
"version": "2.2.3",
- "description": "Harness-native ECC plugin for engineering teams - 71 agents, 306 skills, 97 legacy command shims, reusable hooks, rules, MCP conventions, and operator workflows for Claude Code plus adjacent agent harnesses",
- "description": "Harness-native ECC plugin for engineering teams - 68 agents, 294 skills, 94 legacy command shims, reusable hooks, rules, MCP conventions, and operator workflows for Claude Code plus adjacent agent harnesses",
++ "description": "Harness-native ECC plugin for engineering teams - 71 agents, 307 skills, 97 legacy command shims, reusable hooks, rules, MCP conventions, and operator workflows for Claude Code plus adjacent agent harnesses",
"author": {
"name": "Affaan Mustafa",
"url": "https://x.com/affaanmustafa"
diff --cc .gemini/GEMINI.md
index b5fef6a07,544993ad6..8eb00d916
--- a/.gemini/GEMINI.md
+++ b/.gemini/GEMINI.md
@@@ -4,7 -4,7 +4,7 @@@ This file provides Gemini CLI with the
## Overview
- ECC is a cross-harness coding system with 71 specialized agents, 306 skills, and 97 commands.
-ECC is a cross-harness coding system with 68 specialized agents, 294 skills, and 94 commands.
++ECC is a cross-harness coding system with 71 specialized agents, 307 skills, and 97 commands.
Gemini support is currently focused on a strong project-local instruction layer via `.gemini/GEMINI.md`, plus the shared MCP catalog and package-manager setup assets shipped by the installer.
diff --cc AGENTS.md
index 114555bf9,f4a0f616d..54c810619
--- a/AGENTS.md
+++ b/AGENTS.md
@@@ -1,6 -1,6 +1,6 @@@
# ECC — Agent Instructions
- This is a **production-ready AI coding plugin** providing 71 specialized agents, 306 skills, 97 commands, and automated hook workflows for software development.
-This is a **production-ready AI coding plugin** providing 68 specialized agents, 294 skills, 94 commands, and automated hook workflows for software development.
++This is a **production-ready AI coding plugin** providing 71 specialized agents, 307 skills, 97 commands, and automated hook workflows for software development.
**Version:** 2.2.3
@@@ -201,9 -200,9 +201,9 @@@ Troubleshoot failures: check test isola
## Project Structure
```
-agents/ — 68 specialized subagents
-skills/ — 294 workflow skills and domain knowledge
-commands/ — 94 slash commands
+agents/ — 71 specialized subagents
- skills/ — 306 workflow skills and domain knowledge
++skills/ — 307 workflow skills and domain knowledge
+commands/ — 97 slash commands
hooks/ — Trigger-based automations
rules/ — Always-follow guidelines (common + per-language)
scripts/ — Cross-platform Node.js utilities
diff --cc README.md
index b8074ef4f,403910d82..847734de8
--- a/README.md
+++ b/README.md
@@@ -139,15 -137,15 +139,15 @@@ Instead of rebuilding that process in e
> Optimize the context window. Persist everything else.
-ECC is MIT-licensed open source. It works best with Claude Code today, has a supported Codex sync path, and provides capability-limited adapters for Cursor, OpenCode, Gemini, Zed, GitHub Copilot, Antigravity, Qwen, and other harnesses. See the [support status matrix](#platform-support) before assuming feature parity.
+ECC is MIT-licensed open source. It works best with Claude Code today, has native Codex and Qoder plugin paths, and provides capability-limited adapters for Cursor, OpenCode, Gemini, Zed, GitHub Copilot, Antigravity, Qwen, and other harnesses. See the [support status matrix](#platform-support) before assuming feature parity.
- Access to 71 agents, 306 skills, and 97 legacy command shims, plus hooks, rules, memory, continuous learning, and AgentShield security scanning. The agents are specialized for planning, review, build repair, security, architecture, and domain work.
-Access to 68 agents, 294 skills, and 94 legacy command shims, plus hooks, rules, memory, continuous learning, and AgentShield security scanning. The agents are specialized for planning, review, build repair, security, architecture, and domain work.
++Access to 71 agents, 307 skills, and 97 legacy command shims, plus hooks, rules, memory, continuous learning, and AgentShield security scanning. The agents are specialized for planning, review, build repair, security, architecture, and domain work.
| Included | Count | What it gives you |
| ---------------- | ----------: | ------------------------------------------------------------------------------------ |
-| Agents | 68 agents | Planning, review, build repair, security, architecture, and domain work |
-| Skills | 294 skills | TDD, research, security, docs, frontend, data, ML, operations, and more |
-| Commands | 94 commands | Convenient entry points while ECC moves to a skills-first surface |
+| Agents | 71 agents | Planning, review, build repair, security, architecture, and domain work |
- | Skills | 306 skills | TDD, research, security, docs, frontend, data, ML, operations, and more |
++| Skills | 307 skills | TDD, research, security, docs, frontend, data, ML, operations, and more |
+| Commands | 97 commands | Convenient entry points while ECC moves to a skills-first surface |
| Hooks and memory | Runtime | Enforcement, session summaries, continuous learning, instincts, and context controls |
| Rules | Selective | Always-loaded standards you choose by language or project |
| AgentShield | Included | Scanning for prompts, hooks, MCP config, permissions, secrets, and agent files |
@@@ -858,9 -824,9 +858,9 @@@ Stable graduation of the 2.0 line: cont
```text
ECC/
-|-- agents/ # 68 specialized subagents for delegation
-|-- skills/ # 293 reusable workflows loaded on demand
-|-- commands/ # 94 maintained slash-command shims
+|-- agents/ # 71 specialized subagents for delegation
- |-- skills/ # 306 reusable workflows loaded on demand
++|-- skills/ # 307 reusable workflows loaded on demand
+|-- commands/ # 97 maintained slash-command shims
|-- rules/ # opt-in common and language standards
|-- hooks/ # runtime automation and enforcement
|-- scripts/ # install, repair, sync, orchestration, and checks
diff --cc README.zh-CN.md
index 8e719b5c8,a896430b3..f323c6194
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@@ -200,7 -200,7 +200,7 @@@ Copy-Item -Recurse rules/typescript "$H
/plugin list ecc@ecc
```
- **完成!** 你现在可以使用 71 个代理、306 个技能和 97 个命令。
-**完成!** 你现在可以使用 68 个代理、294 个技能和 94 个命令。
++**完成!** 你现在可以使用 71 个代理、307 个技能和 97 个命令。
### multi-* 命令需要额外配置
diff --cc SOUL.md
index d7bd7922f,92688e1b1..84262efce
--- a/SOUL.md
+++ b/SOUL.md
@@@ -1,7 -1,7 +1,7 @@@
# Soul
## Core Identity
- ECC is a production-ready AI coding plugin with 71 specialized agents, 306 skills, 97 commands, and automated hook workflows for software development.
-ECC is a production-ready AI coding plugin with 68 specialized agents, 294 skills, 94 commands, and automated hook workflows for software development.
++ECC is a production-ready AI coding plugin with 71 specialized agents, 307 skills, 97 commands, and automated hook workflows for software development.
## Core Principles
1. **Agent-First** — route work to the right specialist as early as possible.
diff --cc docs/zh-CN/AGENTS.md
index f8379e35a,8bcad7767..82ee7a6ca
--- a/docs/zh-CN/AGENTS.md
+++ b/docs/zh-CN/AGENTS.md
@@@ -1,6 -1,6 +1,6 @@@
# ECC — 智能体指令
- 这是一个**生产就绪的 AI 编码插件**,提供 71 个专业代理、306 项技能、97 条命令以及自动化钩子工作流,用于软件开发。
-这是一个**生产就绪的 AI 编码插件**,提供 68 个专业代理、294 项技能、94 条命令以及自动化钩子工作流,用于软件开发。
++这是一个**生产就绪的 AI 编码插件**,提供 71 个专业代理、307 项技能、97 条命令以及自动化钩子工作流,用于软件开发。
**版本:** 2.2.3
@@@ -146,9 -146,9 +146,9 @@@
## 项目结构
```
-agents/ — 68 个专业子代理
-skills/ — 294 个工作流技能和领域知识
-commands/ — 94 个斜杠命令
+agents/ — 71 个专业子代理
- skills/ — 306 个工作流技能和领域知识
++skills/ — 307 个工作流技能和领域知识
+commands/ — 97 个斜杠命令
hooks/ — 基于触发的自动化
rules/ — 始终遵循的指导方针(通用 + 每种语言)
scripts/ — 跨平台 Node.js 实用工具
diff --cc docs/zh-CN/README.md
index 95031fa11,d9c221e57..e9d56134e
--- a/docs/zh-CN/README.md
+++ b/docs/zh-CN/README.md
@@@ -264,7 -264,7 +264,7 @@@ Copy-Item -Recurse rules/typescript "$H
/plugin list ecc@ecc
```
- **搞定!** 你现在可以使用 71 个智能体、306 项技能和 97 个命令了。
-**搞定!** 你现在可以使用 68 个智能体、294 项技能和 94 个命令了。
++**搞定!** 你现在可以使用 71 个智能体、307 项技能和 97 个命令了。
***
@@@ -1176,9 -1176,9 +1176,9 @@@ opencod
| 功能特性 | Claude Code | OpenCode | 状态 |
|---------|---------------|----------|--------|
-| 智能体 | PASS: 68 个 | PASS: 12 个 | **Claude Code 领先** |
-| 命令 | PASS: 94 个 | PASS: 35 个 | **Claude Code 领先** |
-| 技能 | PASS: 294 项 | PASS: 37 项 | **Claude Code 领先** |
+| 智能体 | PASS: 71 个 | PASS: 12 个 | **Claude Code 领先** |
+| 命令 | PASS: 97 个 | PASS: 35 个 | **Claude Code 领先** |
- | 技能 | PASS: 306 项 | PASS: 37 项 | **Claude Code 领先** |
++| 技能 | PASS: 307 项 | PASS: 37 项 | **Claude Code 领先** |
| 钩子 | PASS: 8 种事件类型 | PASS: 11 种事件 | **OpenCode 更多!** |
| 规则 | PASS: 29 条 | PASS: 13 条指令 | **Claude Code 领先** |
| MCP 服务器 | PASS: 14 个 | PASS: 完整 | **完全对等** |
@@@ -1284,9 -1284,9 +1284,9 @@@ ECC 是**第一个最大化利用每个
| 功能特性 | Claude Code | Cursor IDE | Codex CLI | OpenCode |
|---------|-----------------------|------------|-----------|----------|
-| **智能体** | 68 | 共享 (AGENTS.md) | 共享 (AGENTS.md) | 12 |
-| **命令** | 94 | 共享 | 基于指令 | 35 |
-| **技能** | 294 | 共享 | 10 (原生格式) | 37 |
+| **智能体** | 71 | 共享 (AGENTS.md) | 共享 (AGENTS.md) | 12 |
+| **命令** | 97 | 共享 | 基于指令 | 35 |
- | **技能** | 306 | 共享 | 10 (原生格式) | 37 |
++| **技能** | 307 | 共享 | 10 (原生格式) | 37 |
| **钩子事件** | 8 种类型 | 15 种类型 | SessionStart(1 种类型) | 11 种类型 |
| **钩子脚本** | 20+ 个脚本 | 16 个脚本 (DRY 适配器) | 1 个 SessionStart 引导脚本 | 插件钩子 |
| **规则** | 34 (通用 + 语言) | 34 (YAML 前页) | 基于指令 | 13 条指令 |
diff --cc manifests/context-packs/[email protected]
index ed3be0d40,0984547a0..153529f03
--- a/manifests/context-packs/[email protected]
+++ b/manifests/context-packs/[email protected]
@@@ -1,295 -1,1 +1,295 @@@
-{"coverage":{"skills":294,"withTriggers":32},"generatedAt":"2026-09-24T23:51:22.784Z","id":"skill-triggers@1","model":{"effort":null,"id":"hand-seeded","source":"manual-curation-pending-regeneration"},"registryDigest":"66789fc92de15f0cb1bca221da72ebb747b742f2b7dc325e696c12964da190a9","schemaVersion":1,"triggers":{"skill:api-connector-builder":["add api integration","new provider connector","match existing integration pattern"],"skill:api-design":["rest endpoint design","pagination api","status codes","api versioning","rate limiting api","resource naming","filtering api","api error responses","offset pagination","limit query parameter","pagination defaults"],"skill:backend-patterns":["express api","node backend architecture","nextjs api routes","server side patterns","data access layer","static file server","url path handling","file server"],"skill:browser-qa":["deployed feature test","visual regression screenshots","core web vitals check","axe accessibility audit","ship do not ship","staging verification"],"skill:canary-watch":["post deploy monitoring","smoke test url","production url check","console errors production","sse stream check","after deploy verification"],"skill:code-tour":["onboarding walkthrough","explain subsystem","architecture tour","pr walkthrough","rca tour"],"skill:coding-standards":["code review standards","naming conventions","readability review","immutability conventions","fix naming typo","export naming","consistent exports"],"skill:content-hash-cache-pattern":["cache file processing","content addressed cache","sha256 hash cache"],"skill:database-migrations":["zero downtime migration","schema change production","add column large table","backfill data","expand contract","concurrent index","migration rollback","prisma migration","django migration"],"skill:deployment-patterns":["ci cd setup","dockerize app","health checks","rollback strategy","production readiness","deploy pipeline","containerize application"],"skill:design-system":["design tokens","visual consistency audit","css custom properties","ui audit","design system bootstrap"],"skill:django-patterns":["django orm","drf api","django rest framework","django caching","django signals","django middleware"],"skill:django-security":["django authentication","csrf protection","sql injection prevention","xss prevention","django deployment security","role based access control","authorization middleware","permissions checks"],"skill:docker-patterns":["dockerfile review","docker compose setup","container security","multi service orchestration"],"skill:error-handling":["error types","retry logic","circuit breaker","user facing errors","exception handling patterns","typed errors","error boundaries","go error handling","custom error class","error codes","config validation"],"skill:evm-token-decimals":["token decimals","wei conversion","erc20 balance off","bridge token precision"],"skill:frontend-a11y":["aria attributes","screen reader support","focus management","semantic html","form labeling","keyboard navigation react","a11y lint errors"],"skill:git-workflow":["merge vs rebase","commit conventions","resolve merge conflict","branching strategy","clean up commits","pull request cleanup","git history tidy"],"skill:hexagonal-architecture":["ports and adapters","dependency injection boundaries","decouple domain from io"],"skill:kubernetes-patterns":["kubernetes manifests","kubectl debugging","pod probes","k8s rbac","autoscaling config","configmap secrets"],"skill:orch-fix-defect":["fix a bug","broken behavior","regression fix","reproduce bug","defect repair"],"skill:postgres-patterns":["slow postgres query","query optimization","index design","rls policies","supabase schema","postgres indexing","database performance","schema design postgres","postgres driver","node postgres","query planner"],"skill:python-patterns":["pythonic code","pep 8","type hints python","python code review","idiomatic python"],"skill:python-testing":["pytest fixtures","mocking python","parametrized tests","coverage python","tdd python"],"skill:redis-patterns":["cache aside pattern","distributed lock","redis rate limiting","cache invalidation"],"skill:regex-vs-llm-structured-text":["parse invoice","extract receipt data","text extraction pipeline","parse form fields","cheap document parser","extract table data","parse log lines","parse access logs","common log format","log line parsing"],"skill:rust-patterns":["rust ownership","borrow checker","rust error handling","traits rust","rust concurrency","idiomatic rust"],"skill:search-first":["find existing library","npm package research","before writing custom code","evaluate existing tools","add dependency research"],"skill:security-review":["security audit","authentication review","sanitize user input","secrets handling","payment security checklist","prevent injection attacks","secure api endpoints","authn authz review","vulnerability checklist","input validation security","parameterized queries","sql injection"],"skill:security-scan":["audit claude config","claudemd security","mcp server audit","agentshield scan","hook configuration audit","settings json security"],"skill:tdd-workflow":["write test first","failing test","red green refactor","test driven development","regression test first","write a regression test"],"skill:verification-loop":["pre pr checks","verification report","quality gates","build lint test coverage","before creating a pr"]},"triggersDigest":"25b97a9e06fc336c7cf95ab854ed1a41033a54bcd6e1fb1cf69dc906332462aa"}
+{
+ "coverage": {
- "skills": 306,
++ "skills": 307,
+ "withTriggers": 33
+ },
+ "generatedAt": "2026-09-24T23:51:22.784Z",
+ "id": "skill-triggers@1",
+ "model": {
+ "effort": null,
+ "id": "hand-seeded",
+ "source": "manual-curation-pending-regeneration"
+ },
- "registryDigest": "16549b53055bf5c106e51ca7fb2fe68f8a705b5f6bad40d388349320caedfa63",
++ "registryDigest": "89c0fbf05b8a7e811dbf788cf9a141199e13c961b69812c80b4cbdb019500c07",
+ "schemaVersion": 1,
+ "triggers": {
+ "skill:agent-runtime-gateway-smoke-test": [
+ "test local agent gateway",
+ "remote sandbox callback smoke test",
+ "agent task stuck after dispatch",
+ "verify gateway tunnel",
+ "restore web api after agent test"
+ ],
+ "skill:api-connector-builder": [
+ "add api integration",
+ "new provider connector",
+ "match existing integration pattern"
+ ],
+ "skill:api-design": [
+ "rest endpoint design",
+ "pagination api",
+ "status codes",
+ "api versioning",
+ "rate limiting api",
+ "resource naming",
+ "filtering api",
+ "api error responses",
+ "offset pagination",
+ "limit query parameter",
+ "pagination defaults"
+ ],
+ "skill:backend-patterns": [
+ "express api",
+ "node backend architecture",
+ "nextjs api routes",
+ "server side patterns",
+ "data access layer",
+ "static file server",
+ "url path handling",
+ "file server"
+ ],
+ "skill:browser-qa": [
+ "deployed feature test",
+ "visual regression screenshots",
+ "core web vitals check",
+ "axe accessibility audit",
+ "ship do not ship",
+ "staging verification"
+ ],
+ "skill:canary-watch": [
+ "post deploy monitoring",
+ "smoke test url",
+ "production url check",
+ "console errors production",
+ "sse stream check",
+ "after deploy verification"
+ ],
+ "skill:code-tour": [
+ "onboarding walkthrough",
+ "explain subsystem",
+ "architecture tour",
+ "pr walkthrough",
+ "rca tour"
+ ],
+ "skill:coding-standards": [
+ "code review standards",
+ "naming conventions",
+ "readability review",
+ "immutability conventions",
+ "fix naming typo",
+ "export naming",
+ "consistent exports"
+ ],
+ "skill:content-hash-cache-pattern": [
+ "cache file processing",
+ "content addressed cache",
+ "sha256 hash cache"
+ ],
+ "skill:database-migrations": [
+ "zero downtime migration",
+ "schema change production",
+ "add column large table",
+ "backfill data",
+ "expand contract",
+ "concurrent index",
+ "migration rollback",
+ "prisma migration",
+ "django migration"
+ ],
+ "skill:deployment-patterns": [
+ "ci cd setup",
+ "dockerize app",
+ "health checks",
+ "rollback strategy",
+ "production readiness",
+ "deploy pipeline",
+ "containerize application"
+ ],
+ "skill:design-system": [
+ "design tokens",
+ "visual consistency audit",
+ "css custom properties",
+ "ui audit",
+ "design system bootstrap"
+ ],
+ "skill:django-patterns": [
+ "django orm",
+ "drf api",
+ "django rest framework",
+ "django caching",
+ "django signals",
+ "django middleware"
+ ],
+ "skill:django-security": [
+ "django authentication",
+ "csrf protection",
+ "sql injection prevention",
+ "xss prevention",
+ "django deployment security",
+ "role based access control",
+ "authorization middleware",
+ "permissions checks"
+ ],
+ "skill:docker-patterns": [
+ "dockerfile review",
+ "docker compose setup",
+ "container security",
+ "multi service orchestration"
+ ],
+ "skill:error-handling": [
+ "error types",
+ "retry logic",
+ "circuit breaker",
+ "user facing errors",
+ "exception handling patterns",
+ "typed errors",
+ "error boundaries",
+ "go error handling",
+ "custom error class",
+ "error codes",
+ "config validation"
+ ],
+ "skill:evm-token-decimals": [
+ "token decimals",
+ "wei conversion",
+ "erc20 balance off",
+ "bridge token precision"
+ ],
+ "skill:frontend-a11y": [
+ "aria attributes",
+ "screen reader support",
+ "focus management",
+ "semantic html",
+ "form labeling",
+ "keyboard navigation react",
+ "a11y lint errors"
+ ],
+ "skill:git-workflow": [
+ "merge vs rebase",
+ "commit conventions",
+ "resolve merge conflict",
+ "branching strategy",
+ "clean up commits",
+ "pull request cleanup",
+ "git history tidy"
+ ],
+ "skill:hexagonal-architecture": [
+ "ports and adapters",
+ "dependency injection boundaries",
+ "decouple domain from io"
+ ],
+ "skill:kubernetes-patterns": [
+ "kubernetes manifests",
+ "kubectl debugging",
+ "pod probes",
+ "k8s rbac",
+ "autoscaling config",
+ "configmap secrets"
+ ],
+ "skill:orch-fix-defect": [
+ "fix a bug",
+ "broken behavior",
+ "regression fix",
+ "reproduce bug",
+ "defect repair"
+ ],
+ "skill:postgres-patterns": [
+ "slow postgres query",
+ "query optimization",
+ "index design",
+ "rls policies",
+ "supabase schema",
+ "postgres indexing",
+ "database performance",
+ "schema design postgres",
+ "postgres driver",
+ "node postgres",
+ "query planner"
+ ],
+ "skill:python-patterns": [
+ "pythonic code",
+ "pep 8",
+ "type hints python",
+ "python code review",
+ "idiomatic python"
+ ],
+ "skill:python-testing": [
+ "pytest fixtures",
+ "mocking python",
+ "parametrized tests",
+ "coverage python",
+ "tdd python"
+ ],
+ "skill:redis-patterns": [
+ "cache aside pattern",
+ "distributed lock",
+ "redis rate limiting",
+ "cache invalidation"
+ ],
+ "skill:regex-vs-llm-structured-text": [
+ "parse invoice",
+ "extract receipt data",
+ "text extraction pipeline",
+ "parse form fields",
+ "cheap document parser",
+ "extract table data",
+ "parse log lines",
+ "parse access logs",
+ "common log format",
+ "log line parsing"
+ ],
+ "skill:rust-patterns": [
+ "rust ownership",
+ "borrow checker",
+ "rust error handling",
+ "traits rust",
+ "rust concurrency",
+ "idiomatic rust"
+ ],
+ "skill:search-first": [
+ "find existing library",
+ "npm package research",
+ "before writing custom code",
+ "evaluate existing tools",
+ "add dependency research"
+ ],
+ "skill:security-review": [
+ "security audit",
+ "authentication review",
+ "sanitize user input",
+ "secrets handling",
+ "payment security checklist",
+ "prevent injection attacks",
+ "secure api endpoints",
+ "authn authz review",
+ "vulnerability checklist",
+ "input validation security",
+ "parameterized queries",
+ "sql injection"
+ ],
+ "skill:security-scan": [
+ "audit claude config",
+ "claudemd security",
+ "mcp server audit",
+ "agentshield scan",
+ "hook configuration audit",
+ "settings json security"
+ ],
+ "skill:tdd-workflow": [
+ "write test first",
+ "failing test",
+ "red green refactor",
+ "test driven development",
+ "regression test first",
+ "write a regression test"
+ ],
+ "skill:verification-loop": [
+ "pre pr checks",
+ "verification report",
+ "quality gates",
+ "build lint test coverage",
+ "before creating a pr"
+ ]
+ },
+ "triggersDigest": "054898acb769893c46e5bd7037141f7be83fb775515ea1dbb52fb1c18aca19e6"
+}
diff --cc manifests/install-modules.json
index ad73d6471,b6d7e36da..a28092e7d
--- a/manifests/install-modules.json
+++ b/manifests/install-modules.json
@@@ -374,9 -334,9 +374,10 @@@
"skills/plankton-code-quality",
"skills/production-audit",
"skills/skill-comply",
+ "skills/skill-host-compat",
"skills/skill-scout",
"skills/skill-stocktake",
+ "skills/story-lifecycle",
"skills/strategic-compact",
"skills/tdd-workflow",
"skills/verification-loop",
diff --cc skills/story-lifecycle/scripts/ledger.js
index 000000000,4787fa007..969cf9675
mode 000000,100644..100644
--- a/skills/story-lifecycle/scripts/ledger.js
+++ b/skills/story-lifecycle/scripts/ledger.js
@@@ -1,0 -1,327 +1,339 @@@
+ #!/usr/bin/env node
+ 'use strict';
+ // Collision-safe, all-or-nothing writer for the .stories/ planning ledger.
+ // Usage: node ledger.js <init|allocate|apply|status|reconcile|recover> --root <repo> [options]
+
+ const fs = require('fs');
+ const os = require('os');
+ const path = require('path');
+ const { execFileSync } = require('child_process');
+
+ const SLUG = /^[a-z0-9]+(-[a-z0-9]+)*$/;
+ const STORY_FILE = /^([a-z0-9]+(?:-[a-z0-9]+)*)-([1-9][0-9]*)\.md$/;
+ const EPIC_FILE = /^epics\/([a-z0-9]+(?:-[a-z0-9]+)*)\.md$/;
+ const SPRINT_FILE = /^sprints\/sprint-([1-9][0-9]*)\.md$/;
+ const STATUSES = ['todo', 'in-progress', 'review', 'done'];
+ const SPRINT_VALUE = /^(unassigned|[1-9][0-9]*)$/;
+ const POINTS = ['1', '2', '3', '5', '8'];
+ const BACKUP = /^backup-[0-9]+$/;
+ const DERIVED = '<!-- Derived from story files';
+
+ class LedgerError extends Error {
+ constructor(message, code = 2) { super(message); this.exitCode = code; }
+ }
+
+ function parseArgs(argv) {
+ const opts = { _: [] };
+ for (let i = 0; i < argv.length; i++) {
+ if (argv[i].startsWith('--')) opts[argv[i].slice(2)] = argv[++i];
+ else opts._.push(argv[i]);
+ }
+ return opts;
+ }
+
+ function sleep(ms) { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); }
+
+ function pidAlive(pid) {
+ try { process.kill(pid, 0); return true; } catch (err) { return err.code === 'EPERM'; }
+ }
+
+ // Confine a ledger-relative path to the allowed file shapes under .stories/; refuse symlinks.
+ function resolveLedgerPath(dir, rel) {
+ const norm = String(rel).replace(/\\/g, '/');
+ const valid = EPIC_FILE.test(norm) || SPRINT_FILE.test(norm) || STORY_FILE.test(norm);
+ const abs = path.resolve(dir, norm);
+ const back = path.relative(dir, abs);
+ if (!valid || back.startsWith('..') || path.isAbsolute(back)) throw new LedgerError(`invalid ledger path: ${rel}`);
+ let isLink = false;
+ try { isLink = fs.lstatSync(abs).isSymbolicLink(); } catch (err) { if (err.code !== 'ENOENT') throw err; }
+ if (isLink) throw new LedgerError(`refusing symlinked ledger file: ${rel}`);
+ return abs;
+ }
+
+ // A symlinked ledger directory would redirect reads or writes outside .stories/.
+ function assertNoSymlinkDirs(dir) {
+ for (const p of [dir, ...['epics', 'sprints', '.txn', '.ids'].map((sub) => path.join(dir, sub))]) {
+ let st;
+ try { st = fs.lstatSync(p); } catch (err) { if (err.code === 'ENOENT') continue; throw err; }
+ if (st.isSymbolicLink()) throw new LedgerError(`refusing symlinked ledger directory: ${p}`);
+ }
+ }
+
+ // Allocation markers live in the git common dir so every worktree of a clone shares them.
+ function registryDir(root, dir) {
+ try {
+ const common = execFileSync('git', ['-C', root, 'rev-parse', '--git-common-dir'],
+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
- return path.join(path.resolve(root, common), 'story-lifecycle', 'ids');
- } catch {
++ const base = path.resolve(root, common);
++ for (const sub of ['story-lifecycle', 'story-lifecycle/ids']) {
++ const candidate = path.join(base, sub);
++ if (fs.existsSync(candidate) && fs.lstatSync(candidate).isSymbolicLink()) {
++ throw new LedgerError(`refusing symlinked allocation registry: ${candidate}`);
++ }
++ }
++ return path.join(base, 'story-lifecycle', 'ids');
++ } catch (error) {
++ if (error instanceof LedgerError) throw error;
+ return path.join(dir, '.ids');
+ }
+ }
+
+ function readLock(dir) {
+ try { return JSON.parse(fs.readFileSync(path.join(dir, '.lock'), 'utf8')); } catch { return null; }
+ }
+
+ function isStale(holder) { return holder.host === os.hostname() && !pidAlive(holder.pid); }
+
+ // Remove a stale lock only while holding .lock.break, after re-reading it, so a
+ // waiter that saw the old stale lock can never delete a newer live one.
+ // Returns false if another waiter (or a crashed one) holds .lock.break.
+ function breakStaleLock(dir) {
+ const brk = path.join(dir, '.lock.break');
+ try {
+ fs.writeFileSync(brk, String(process.pid), { flag: 'wx' });
+ } catch (err) {
+ if (err.code === 'EEXIST') return false;
+ throw err;
+ }
+ try {
+ const holder = readLock(dir);
+ if (holder && isStale(holder)) fs.rmSync(path.join(dir, '.lock'), { force: true });
+ return true;
+ } finally {
+ fs.rmSync(brk, { force: true });
+ }
+ }
+
+ function acquireLock(dir, waitMs) {
+ const lock = path.join(dir, '.lock');
+ const deadline = Date.now() + waitMs;
+ for (;;) {
+ try {
+ fs.writeFileSync(lock, JSON.stringify({ pid: process.pid, host: os.hostname(), at: new Date().toISOString() }), { flag: 'wx' });
+ return () => fs.rmSync(lock, { force: true });
+ } catch (err) {
+ if (err.code !== 'EEXIST') throw err;
+ }
+ const holder = readLock(dir); // null: lock vanished or half-written; retry
+ if (holder && isStale(holder) && breakStaleLock(dir)) continue;
+ if (Date.now() > deadline) {
+ const brk = fs.existsSync(path.join(dir, '.lock.break')) ? '; .lock.break is held (delete it only if no ledger command is running)' : '';
+ throw new LedgerError(`ledger locked by pid ${holder && holder.pid} since ${holder && holder.at}${brk}`, 3);
+ }
+ sleep(25 + Math.floor(Math.random() * 50));
+ }
+ }
+
+ // Roll back an interrupted transaction: restore backups, delete created files.
+ function recover(dir) {
+ const txn = path.join(dir, '.txn');
+ const journalPath = path.join(txn, 'journal.json');
+ let rolledBack = 0;
+ if (fs.existsSync(journalPath)) {
+ const { entries } = JSON.parse(fs.readFileSync(journalPath, 'utf8'));
+ for (const entry of entries) {
+ resolveLedgerPath(dir, entry.path);
+ if (entry.backup && !(BACKUP.test(entry.backup) && fs.lstatSync(path.join(txn, entry.backup)).isFile())) {
+ throw new LedgerError(`invalid journal backup: ${entry.backup}`);
+ }
+ }
+ for (const entry of entries) {
+ const target = resolveLedgerPath(dir, entry.path);
+ if (entry.backup) {
+ // Fresh temp file, then rename: neither step writes through a planted symlink.
+ const tmp = path.join(txn, 'restore.tmp');
+ fs.rmSync(tmp, { force: true });
+ fs.copyFileSync(path.join(txn, entry.backup), tmp, fs.constants.COPYFILE_EXCL);
+ fs.renameSync(tmp, target);
+ } else {
+ fs.rmSync(target, { force: true });
+ }
+ rolledBack++;
+ }
+ }
+ fs.rmSync(txn, { recursive: true, force: true });
+ return rolledBack;
+ }
+
+ function field(md, name) {
+ const m = md.match(new RegExp(`^\\*\\*${name}:\\*\\*[ \\t]*(.+)$`, 'm'));
+ return m ? m[1].trim() : null;
+ }
+
+ function parseStory(rel, md) {
+ const [, epic, n] = rel.match(STORY_FILE);
+ const id = `${epic}-${n}`;
+ const story = {
+ id, n: Number(n), epic, title: (md.match(/^# Story:[ \t]*(.+)$/m) || [])[1],
+ status: field(md, 'Status'), sprint: field(md, 'Sprint'), points: field(md, 'Points'),
+ };
+ if (field(md, 'ID') !== id || field(md, 'Epic') !== epic) throw new LedgerError(`${rel}: ID/Epic fields must match file name`);
+ if (!story.title || !STATUSES.includes(story.status)) throw new LedgerError(`${rel}: missing title or invalid status`);
+ if (!SPRINT_VALUE.test(story.sprint || '')) throw new LedgerError(`${rel}: Sprint must be unassigned or a sprint number`);
+ if (!POINTS.includes(story.points)) throw new LedgerError(`${rel}: Points must be one of ${POINTS.join(', ')}`);
+ return story;
+ }
+
+ function replaceTable(md, rel, header, rows) {
+ const i = md.indexOf(DERIVED);
+ if (i < 0) throw new LedgerError(`${rel}: missing derived-table marker`);
+ const start = md.indexOf('\n', i) + 1;
+ let end = start;
+ while (md[end] === '|') { const nl = md.indexOf('\n', end); end = nl < 0 ? md.length : nl + 1; }
+ return md.slice(0, start) + [header, ...rows].join('\n') + '\n' + md.slice(end);
+ }
+
+ // Read the ledger with pending changes overlaid; return regenerated epic/sprint files that differ.
+ function project(dir, pending = {}) {
+ const read = (rel) => (rel in pending ? pending[rel] : fs.readFileSync(resolveLedgerPath(dir, rel), 'utf8'));
+ const list = (sub, re) => {
+ const abs = path.join(dir, sub);
+ const onDisk = fs.existsSync(abs) ? fs.readdirSync(abs).map((f) => (sub ? `${sub}/${f}` : f)) : [];
+ return [...new Set([...onDisk, ...Object.keys(pending)])].filter((rel) => re.test(rel)).sort();
+ };
+ const stories = list('', STORY_FILE).map((rel) => parseStory(rel, read(rel)))
+ .sort((a, b) => a.epic.localeCompare(b.epic) || a.n - b.n);
+ const sprints = list('sprints', SPRINT_FILE);
+ for (const s of stories) {
+ if (s.sprint !== 'unassigned' && !sprints.includes(`sprints/sprint-${s.sprint}.md`)) {
+ throw new LedgerError(`${s.id}.md: sprint ${s.sprint} does not exist`);
+ }
+ }
+ const derived = {};
+ for (const rel of list('epics', EPIC_FILE)) {
+ const slug = rel.match(EPIC_FILE)[1];
+ const rows = stories.filter((s) => s.epic === slug).map((s) => `| ${s.id} | ${s.title} | ${s.status} |`);
+ const next = replaceTable(read(rel), rel, '| ID | Title | Status |\n| --- | --- | --- |', rows);
+ if (next !== read(rel)) derived[rel] = next;
+ }
+ for (const rel of sprints) {
+ const inSprint = stories.filter((s) => s.sprint === rel.match(SPRINT_FILE)[1]);
+ const rows = inSprint.map((s) => `| ${s.id} | ${s.title} | ${s.points} | ${s.status} |`);
+ const total = inSprint.reduce((sum, s) => sum + Number(s.points), 0);
+ const next = replaceTable(read(rel), rel, '| ID | Title | Points | Status |\n| --- | --- | --- | --- |', rows)
+ .replace(/^## Total Points:.*$/m, `## Total Points: ${total}`);
+ if (next !== read(rel)) derived[rel] = next;
+ }
+ return { stories, derived };
+ }
+
+ function init(dir) {
+ for (const sub of ['epics', 'sprints']) fs.mkdirSync(path.join(dir, sub), { recursive: true });
+ const ignore = path.join(dir, '.gitignore');
+ if (!fs.existsSync(ignore)) fs.writeFileSync(ignore, '.lock\n.lock.break\n.txn/\n.ids/\n');
+ return { ok: true, dir };
+ }
+
+ function allocate(root, dir, epic, count) {
+ if (!SLUG.test(epic || '') || epic.length > 64) throw new LedgerError(`invalid epic slug: ${epic}`);
+ if (!fs.existsSync(path.join(dir, 'epics', `${epic}.md`))) throw new LedgerError(`unknown epic: ${epic}`);
- if (!(count >= 1 && count <= 50)) throw new LedgerError('--count must be 1..50');
++ if (!(Number.isSafeInteger(count) && count >= 1 && count <= 50)) throw new LedgerError('--count must be 1..50');
+ const reg = registryDir(root, dir);
+ fs.mkdirSync(reg, { recursive: true });
+ const taken = [...fs.readdirSync(dir), ...fs.readdirSync(reg).map((f) => `${f}.md`)]
+ .map((f) => f.match(STORY_FILE)).filter((m) => m && m[1] === epic).map((m) => Number(m[2]));
+ let n = Math.max(0, ...taken);
+ const ids = [];
+ while (ids.length < count) {
+ const id = `${epic}-${++n}`;
+ try {
+ fs.writeFileSync(path.join(reg, id), '', { flag: 'wx' });
+ ids.push(id);
+ } catch (err) {
+ if (err.code !== 'EEXIST') throw err;
+ }
+ }
+ return { ids };
+ }
+
+ // changes: { create: { rel: content }, update: { rel: content } }
+ function apply(root, dir, changes) {
+ const keys = new Set();
+ const normalize = (obj = {}) => Object.fromEntries(Object.entries(obj).map(([rel, content]) => {
+ const key = rel.replace(/\\/g, '/');
+ if (keys.has(key)) throw new LedgerError(`duplicate path in batch: ${key}`);
+ keys.add(key);
+ return [key, content];
+ }));
+ const create = normalize(changes.create);
+ const update = normalize(changes.update);
+ const reg = registryDir(root, dir);
+ for (const rel of Object.keys(create)) {
+ if (fs.existsSync(resolveLedgerPath(dir, rel))) throw new LedgerError(`refusing to overwrite existing ${rel}`, 4);
+ const m = rel.match(STORY_FILE);
+ if (m && !fs.existsSync(path.join(reg, `${m[1]}-${m[2]}`))) throw new LedgerError(`${rel}: story ID was not allocated`);
+ if (m && parseStory(rel, create[rel]).status !== 'todo') throw new LedgerError(`${rel}: new stories start as todo`);
+ }
+ for (const rel of Object.keys(update)) {
+ const abs = resolveLedgerPath(dir, rel);
+ if (!fs.existsSync(abs)) throw new LedgerError(`cannot update missing ${rel}`);
+ if (!STORY_FILE.test(rel)) continue;
+ const from = parseStory(rel, fs.readFileSync(abs, 'utf8')).status;
+ const to = parseStory(rel, update[rel]).status;
+ if (to !== from && STATUSES.indexOf(to) !== STATUSES.indexOf(from) + 1) {
+ throw new LedgerError(`${rel}: status ${from} -> ${to} is not allowed; status moves forward one step at a time`);
+ }
+ }
+ const pending = { ...create, ...update };
+ const all = { ...pending, ...project(dir, pending).derived };
+ const txn = path.join(dir, '.txn');
+ fs.mkdirSync(txn);
+ const entries = Object.keys(all).map((rel, i) => {
+ const existed = fs.existsSync(resolveLedgerPath(dir, rel));
+ if (existed) fs.copyFileSync(resolveLedgerPath(dir, rel), path.join(txn, `backup-${i}`));
+ fs.writeFileSync(path.join(txn, `new-${i}`), all[rel]);
+ return { path: rel, backup: existed ? `backup-${i}` : null, staged: `new-${i}` };
+ });
+ fs.writeFileSync(path.join(txn, 'journal.tmp'), JSON.stringify({ entries }));
+ fs.renameSync(path.join(txn, 'journal.tmp'), path.join(txn, 'journal.json'));
+ const crashAfter = Number(process.env.STORY_LEDGER_CRASH_AFTER || -1);
+ entries.forEach((entry, i) => {
+ if (i === crashAfter) process.exit(70); // test-only fault injection
+ fs.renameSync(path.join(txn, entry.staged), resolveLedgerPath(dir, entry.path));
+ });
+ fs.rmSync(path.join(txn, 'journal.json')); // commit point
+ fs.rmSync(txn, { recursive: true, force: true });
+ return { ok: true, written: entries.map((e) => e.path) };
+ }
+
+ function main() {
+ const opts = parseArgs(process.argv.slice(2));
+ const cmd = opts._[0];
+ const root = path.resolve(opts.root || '.');
+ const dir = path.join(root, '.stories');
+ assertNoSymlinkDirs(dir);
+ if (cmd === 'init') return init(dir);
+ if (!fs.existsSync(path.join(dir, 'epics'))) throw new LedgerError('no .stories/ ledger; run `init` first');
+ if (cmd === 'status') {
+ const { stories, derived } = project(dir);
+ const holder = readLock(dir);
+ const recoveryPending = fs.existsSync(path.join(dir, '.txn')) && (!holder || isStale(holder));
+ return { stories, drift: Object.keys(derived), recoveryPending };
+ }
- const release = acquireLock(dir, Number(opts['wait-ms'] || 5000));
++ const waitMs = Number(opts['wait-ms'] ?? 5000);
++ if (!Number.isSafeInteger(waitMs) || waitMs < 0 || waitMs > 60000) {
++ throw new LedgerError('--wait-ms must be an integer in 0..60000');
++ }
++ const release = acquireLock(dir, waitMs);
+ try {
+ const rolledBack = recover(dir);
+ if (cmd === 'recover') return { ok: true, rolledBack };
+ if (cmd === 'allocate') return allocate(root, dir, opts.epic, Number(opts.count || 1));
+ if (cmd === 'reconcile') return apply(root, dir, {});
+ if (cmd === 'apply') return apply(root, dir, JSON.parse(fs.readFileSync(opts.input, 'utf8')));
+ throw new LedgerError(`unknown command: ${cmd}`);
+ } finally {
+ release();
+ }
+ }
+
+ if (require.main === module) {
+ try {
+ process.stdout.write(`${JSON.stringify(main(), null, 2)}\n`);
+ } catch (err) {
+ process.stderr.write(`[story-ledger] ${err.message}\n`);
+ process.exit(err.exitCode || 1);
+ }
+ }
+
+ module.exports = { resolveLedgerPath, project };
diff --cc tests/docs/story-lifecycle-ledger.test.js
index 000000000,6d9b8d4bd..20443a87a
mode 000000,100644..100644
--- a/tests/docs/story-lifecycle-ledger.test.js
+++ b/tests/docs/story-lifecycle-ledger.test.js
@@@ -1,0 -1,394 +1,413 @@@
+ const assert = require('assert');
+ const fs = require('fs');
+ const os = require('os');
+ const path = require('path');
+ const { execFileSync, spawn, spawnSync } = require('child_process');
+
+ const LEDGER = path.join(__dirname, '..', '..', 'skills', 'story-lifecycle', 'scripts', 'ledger.js');
+ const { resolveLedgerPath } = require(LEDGER);
+
+ const EPIC = `# Epic: Auth flow
+
+ **Slug:** auth-flow
+ **Status:** ready
+
+ ## Stories
+
+ <!-- Derived from story files — regenerated by status and on every transition -->
+ | ID | Title | Status |
+ | --- | --- | --- |
+ `;
+
+ function story(id, title, { sprint = 'unassigned', status = 'todo', points = 3 } = {}) {
+ return `# Story: ${title}\n\n**ID:** ${id}\n**Epic:** auth-flow\n**Sprint:** ${sprint}\n**Status:** ${status}\n**Points:** ${points}\n`;
+ }
+
+ function run(root, args, env = {}) {
+ const r = spawnSync(process.execPath, [LEDGER, ...args, '--root', root], { encoding: 'utf8', env: { ...process.env, ...env } });
+ return { code: r.status, out: r.stdout ? JSON.parse(r.stdout) : null, err: r.stderr };
+ }
+
+ function runAsync(root, args) {
+ return new Promise((resolve) => {
+ const child = spawn(process.execPath, [LEDGER, ...args, '--root', root]);
+ let out = '';
+ child.stdout.on('data', (d) => { out += d; });
+ child.on('close', (code) => resolve({ code, out }));
+ });
+ }
+
+ function writeJson(root, name, value) {
+ const file = path.join(root, name);
+ fs.writeFileSync(file, JSON.stringify(value));
+ return file;
+ }
+
+ function newRepo() {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'story-ledger-'));
+ execFileSync('git', ['init', '-q', root]);
+ assert.strictEqual(run(root, ['init']).code, 0);
+ const input = writeJson(root, 'epic.json', { create: { 'epics/auth-flow.md': EPIC } });
+ assert.strictEqual(run(root, ['apply', '--input', input]).code, 0);
+ return root;
+ }
+
+ function createStories(root, titles, tag = 'batch') {
+ const { ids } = run(root, ['allocate', '--epic', 'auth-flow', '--count', String(titles.length)]).out;
+ const create = Object.fromEntries(ids.map((id, i) => [`${id}.md`, story(id, titles[i])]));
+ return { ids, input: writeJson(root, `${tag}.json`, { create }) };
+ }
+
+ // Windows allows symlinks only with admin rights or Developer Mode; skip rather than fail there.
+ class Skip extends Error {}
+ function symlink(target, file, type) {
+ try {
+ fs.symlinkSync(target, file, type);
+ } catch (err) {
+ if (err.code === 'EPERM' && process.platform === 'win32') throw new Skip('symlinks not permitted');
+ throw err;
+ }
+ }
+
+ const read = (root, rel) => fs.readFileSync(path.join(root, '.stories', rel), 'utf8');
+ const storyFiles = (root) => fs.readdirSync(path.join(root, '.stories')).filter((f) => /-\d+\.md$/.test(f)).sort();
+
+ // One full create-stories run (allocate + apply) in a separate process.
+ const WRITER = `
+ const { execFileSync } = require('child_process');
+ const fs = require('fs');
+ const [ledger, root, tag] = process.argv.slice(1);
+ const run = (...a) => JSON.parse(execFileSync(process.execPath, [ledger, ...a, '--root', root]));
+ const { ids } = run('allocate', '--epic', 'auth-flow', '--count', '3');
+ const create = Object.fromEntries(ids.map((id) => [id + '.md',
+ '# Story: ' + tag + ' ' + id + '\\n\\n**ID:** ' + id + '\\n**Epic:** auth-flow\\n**Sprint:** unassigned\\n**Status:** todo\\n**Points:** 1\\n']));
+ fs.writeFileSync(root + '/' + tag + '.json', JSON.stringify({ create }));
+ run('apply', '--input', root + '/' + tag + '.json');
+ `;
+
+ const tests = [
+ ['create-stories writes story files and regenerates the epic table', () => {
+ const root = newRepo();
+ const { ids, input } = createStories(root, ['Login', 'Logout']);
+ assert.deepStrictEqual(ids, ['auth-flow-1', 'auth-flow-2']);
+ assert.strictEqual(run(root, ['apply', '--input', input]).code, 0);
+ assert.ok(read(root, 'epics/auth-flow.md').includes('| auth-flow-2 | Logout | todo |'));
+ assert.ok(fs.existsSync(path.join(root, '.stories', '.gitignore')));
+ }],
+
+ ['two concurrent writers get distinct IDs and neither overwrites the other', async () => {
+ const root = newRepo();
+ const codes = await Promise.all(['a', 'b'].map((tag) => new Promise((resolve) => {
+ spawn(process.execPath, ['-e', WRITER, LEDGER, root, tag], { stdio: 'inherit' }).on('close', resolve);
+ })));
+ assert.deepStrictEqual(codes, [0, 0]);
+ const files = storyFiles(root);
+ assert.strictEqual(files.length, 6, `expected 6 distinct story files, got ${files}`);
+ const epic = read(root, 'epics/auth-flow.md');
+ for (const f of files) assert.ok(epic.includes(`| ${f.slice(0, -3)} |`), `epic table missing ${f}`);
+ assert.deepStrictEqual(run(root, ['status']).out.drift, []);
+ }],
+
+ ['a held lock makes the second writer wait, fail cleanly, then succeed on retry', async () => {
+ const root = newRepo();
+ const { input } = createStories(root, ['Login']);
+ const lock = path.join(root, '.stories', '.lock');
+ fs.writeFileSync(lock, JSON.stringify({ pid: process.pid, host: os.hostname(), at: 'now' }));
+ fs.mkdirSync(path.join(root, '.stories', '.txn'));
+ assert.strictEqual(run(root, ['status']).out.recoveryPending, false, 'in-flight batch of a live writer is not interrupted');
+ const blocked = await runAsync(root, ['apply', '--input', input, '--wait-ms', '200']);
+ assert.strictEqual(blocked.code, 3, 'expected lock-timeout exit code');
+ assert.deepStrictEqual(storyFiles(root), []);
+ fs.rmSync(lock);
+ assert.strictEqual(run(root, ['apply', '--input', input]).code, 0);
+ assert.deepStrictEqual(storyFiles(root), ['auth-flow-1.md']);
+ }],
+
+ ['creating an existing story ID is refused without overwrite', () => {
+ const root = newRepo();
+ const { ids, input } = createStories(root, ['Login']);
+ assert.strictEqual(run(root, ['apply', '--input', input]).code, 0);
+ const again = writeJson(root, 'again.json', { create: { [`${ids[0]}.md`]: story(ids[0], 'Clobber') } });
+ assert.strictEqual(run(root, ['apply', '--input', again]).code, 4);
+ assert.ok(read(root, `${ids[0]}.md`).includes('Login'));
+ }],
+
+ ['unallocated story IDs are refused', () => {
+ const root = newRepo();
+ const input = writeJson(root, 'raw.json', { create: { 'auth-flow-9.md': story('auth-flow-9', 'Raw') } });
+ assert.notStrictEqual(run(root, ['apply', '--input', input]).code, 0);
+ assert.deepStrictEqual(storyFiles(root), []);
+ }],
+
+ ['an interrupted batch is rolled back completely by the next writer', () => {
+ const root = newRepo();
+ const before = read(root, 'epics/auth-flow.md');
+ const { input } = createStories(root, ['A', 'B', 'C']);
+ const crashed = run(root, ['apply', '--input', input], { STORY_LEDGER_CRASH_AFTER: '2' });
+ assert.strictEqual(crashed.code, 70);
+ assert.strictEqual(storyFiles(root).length, 2, 'fixture must leave a partial batch on disk');
+ assert.strictEqual(run(root, ['status']).out.recoveryPending, true);
+ assert.strictEqual(run(root, ['recover']).out.rolledBack, 4);
+ assert.deepStrictEqual(storyFiles(root), []);
+ assert.strictEqual(read(root, 'epics/auth-flow.md'), before);
+ assert.ok(!fs.existsSync(path.join(root, '.stories', '.lock')));
+ }],
+
+ ['plan-sprint assigns stories and derives the sprint table and total', () => {
+ const root = newRepo();
+ const { ids, input } = createStories(root, ['Login', 'Logout']);
+ run(root, ['apply', '--input', input]);
+ const sprint = '# Sprint 1\n\n## Stories\n\n<!-- Derived from story files — regenerated by status and on every transition -->\n| ID | Title | Points | Status |\n| --- | --- | --- | --- |\n\n## Total Points: 0\n';
+ const plan = writeJson(root, 'plan.json', {
+ create: { 'sprints/sprint-1.md': sprint },
+ update: Object.fromEntries(ids.map((id, i) => [`${id}.md`, story(id, ['Login', 'Logout'][i], { sprint: '1', points: 5 })])),
+ });
+ assert.strictEqual(run(root, ['apply', '--input', plan]).code, 0);
+ const s = read(root, 'sprints/sprint-1.md');
+ assert.ok(s.includes('| auth-flow-1 | Login | 5 | todo |'));
+ assert.ok(s.includes('## Total Points: 10'));
+ }],
+
+ ['status reports drift read-only; reconcile repairs the derived tables', () => {
+ const root = newRepo();
+ const { ids, input } = createStories(root, ['Login']);
+ run(root, ['apply', '--input', input]);
+ fs.writeFileSync(path.join(root, '.stories', `${ids[0]}.md`), story(ids[0], 'Login', { status: 'in-progress' }));
+ const epicBefore = read(root, 'epics/auth-flow.md');
+ assert.deepStrictEqual(run(root, ['status']).out.drift, ['epics/auth-flow.md']);
+ assert.strictEqual(read(root, 'epics/auth-flow.md'), epicBefore, 'status must not write');
+ assert.strictEqual(run(root, ['reconcile']).code, 0);
+ assert.ok(read(root, 'epics/auth-flow.md').includes('| auth-flow-1 | Login | in-progress |'));
+ }],
+
+ ['git worktrees of one clone share ID allocation', () => {
+ const root = newRepo();
+ execFileSync('git', ['-C', root, '-c', 'user.email=t@t', '-c', 'user.name=t', 'commit', '-q', '--allow-empty', '-m', 'init']);
+ const wt = `${root}-wt`;
+ execFileSync('git', ['-C', root, 'worktree', 'add', '-q', wt]);
+ run(wt, ['init']);
+ run(wt, ['apply', '--input', writeJson(wt, 'epic.json', { create: { 'epics/auth-flow.md': EPIC } })]);
+ const a = run(root, ['allocate', '--epic', 'auth-flow', '--count', '2']).out.ids;
+ const b = run(wt, ['allocate', '--epic', 'auth-flow', '--count', '2']).out.ids;
+ assert.deepStrictEqual([...a, ...b], ['auth-flow-1', 'auth-flow-2', 'auth-flow-3', 'auth-flow-4']);
+ }],
+
+ ['concurrent allocation from two worktrees never hands out the same ID', async () => {
+ const root = newRepo();
+ execFileSync('git', ['-C', root, '-c', 'user.email=t@t', '-c', 'user.name=t', 'commit', '-q', '--allow-empty', '-m', 'init']);
+ const wt = `${root}-wt`;
+ execFileSync('git', ['-C', root, 'worktree', 'add', '-q', wt]);
+ run(wt, ['init']);
+ run(wt, ['apply', '--input', writeJson(wt, 'epic.json', { create: { 'epics/auth-flow.md': EPIC } })]);
+ // Each worktree has its own lock, so only the shared exclusive-create markers prevent duplicates.
+ const results = await Promise.all(Array.from({ length: 32 }, (_, i) => runAsync(i % 2 ? wt : root, ['allocate', '--epic', 'auth-flow', '--count', '5'])));
+ const ids = results.flatMap((r) => JSON.parse(r.out).ids);
+ assert.strictEqual(ids.length, 160);
+ assert.strictEqual(new Set(ids).size, 160, 'duplicate story IDs allocated across worktrees');
+ }],
+
+ ['symlinked ledger directories are refused before any write', () => {
+ const root = newRepo();
+ const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'story-outside-'));
+ fs.rmSync(path.join(root, '.stories', 'sprints'), { recursive: true });
+ symlink(outside, path.join(root, '.stories', 'sprints'), 'dir');
+ const input = writeJson(root, 's.json', { create: { 'sprints/sprint-1.md': '# Sprint 1\n' } });
+ const r = run(root, ['apply', '--input', input]);
+ assert.strictEqual(r.code, 2);
+ assert.match(r.err, /symlinked ledger directory/);
+ assert.deepStrictEqual(fs.readdirSync(outside), []);
+ }],
+
+ ['recover rejects journal backups outside .txn/', () => {
+ const root = newRepo();
+ const txn = path.join(root, '.stories', '.txn');
+ fs.writeFileSync(path.join(root, 'private.txt'), 'SECRET');
+ fs.mkdirSync(txn);
+ fs.writeFileSync(path.join(txn, 'journal.json'), JSON.stringify({ entries: [{ path: 'epics/auth-flow.md', backup: '../../private.txt' }] }));
+ assert.strictEqual(run(root, ['recover']).code, 2);
+ assert.ok(!read(root, 'epics/auth-flow.md').includes('SECRET'));
+ }],
+
+ ['recover never writes through a symlinked ledger target', () => {
+ const root = newRepo();
+ const txn = path.join(root, '.stories', '.txn');
+ const victim = path.join(root, 'victim.txt');
+ fs.writeFileSync(victim, 'ORIGINAL');
+ symlink(victim, path.join(root, '.stories', 'auth-flow-1.md'));
+ fs.mkdirSync(txn);
+ fs.writeFileSync(path.join(txn, 'backup-0'), 'PLANTED');
+ fs.writeFileSync(path.join(txn, 'journal.json'), JSON.stringify({ entries: [{ path: 'auth-flow-1.md', backup: 'backup-0' }] }));
+ assert.strictEqual(run(root, ['recover']).code, 2);
+ assert.strictEqual(fs.readFileSync(victim, 'utf8'), 'ORIGINAL');
+ }],
+
+ ['symlinked ledger files are never read into or written through the ledger', () => {
+ const root = newRepo();
+ const { ids, input } = createStories(root, ['Login', 'Logout']);
+ run(root, ['apply', '--input', input]);
+ const outside = path.join(root, 'other-repo-story.md');
+ fs.writeFileSync(outside, story(ids[1], 'PRIVATE-TITLE'));
+ fs.rmSync(path.join(root, '.stories', `${ids[1]}.md`));
+ symlink(outside, path.join(root, '.stories', `${ids[1]}.md`));
+ const status = run(root, ['status']);
+ assert.strictEqual(status.code, 2);
+ assert.match(status.err, /symlinked ledger file/);
+ assert.strictEqual(run(root, ['reconcile']).code, 2);
+ const update = writeJson(root, 'u.json', { update: { [`${ids[1]}.md`]: story(ids[1], 'Logout', { status: 'in-progress' }) } });
+ assert.strictEqual(run(root, ['apply', '--input', update]).code, 2);
+ assert.ok(!read(root, 'epics/auth-flow.md').includes('PRIVATE-TITLE'));
+ assert.strictEqual(fs.readFileSync(outside, 'utf8'), story(ids[1], 'PRIVATE-TITLE'));
+ }],
+
+ ['recover never follows symlinks planted in .txn/', () => {
+ const root = newRepo();
+ const txn = path.join(root, '.stories', '.txn');
+ const outside = path.join(root, 'outside.txt');
+ fs.writeFileSync(outside, 'ORIGINAL');
+ fs.mkdirSync(txn);
+ fs.writeFileSync(path.join(txn, 'journal.json'), JSON.stringify({ entries: [{ path: 'auth-flow-1.md', backup: 'backup-0' }] }));
+ symlink(outside, path.join(txn, 'backup-0'));
+ assert.strictEqual(run(root, ['recover']).code, 2, 'symlinked backup must be refused');
+ assert.ok(!fs.existsSync(path.join(root, '.stories', 'auth-flow-1.md')));
+
+ fs.rmSync(path.join(txn, 'backup-0'));
+ fs.writeFileSync(path.join(txn, 'backup-0'), 'GOOD');
+ symlink(outside, path.join(txn, 'restore.tmp'));
+ assert.strictEqual(run(root, ['recover']).code, 0);
+ assert.strictEqual(fs.readFileSync(outside, 'utf8'), 'ORIGINAL');
+ assert.ok(fs.lstatSync(path.join(root, '.stories', 'auth-flow-1.md')).isFile());
+ }],
+
+ ['a leftover .lock.break makes writers time out instead of spinning', () => {
+ const root = newRepo();
+ fs.writeFileSync(path.join(root, '.stories', '.lock'), JSON.stringify({ pid: 2 ** 22 + 1, host: os.hostname(), at: 'stale' }));
+ fs.writeFileSync(path.join(root, '.stories', '.lock.break'), '1');
+ const r = spawnSync(process.execPath, [LEDGER, 'reconcile', '--root', root, '--wait-ms', '200'], { encoding: 'utf8', timeout: 5000 });
+ assert.strictEqual(r.status, 3, `expected lock timeout, got ${r.status} ${r.signal}`);
+ assert.match(r.stderr, /\.lock\.break is held/);
+ }],
+
+ ['symlinked .ids registry is refused outside git', () => {
+ const root = newRepo();
+ fs.rmSync(path.join(root, '.git'), { recursive: true });
+ const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'story-ids-'));
+ symlink(outside, path.join(root, '.stories', '.ids'), 'dir');
+ assert.strictEqual(run(root, ['allocate', '--epic', 'auth-flow']).code, 2);
+ assert.deepStrictEqual(fs.readdirSync(outside), []);
+ }],
+
+ ['a batch naming the same file twice is refused', () => {
+ const root = newRepo();
+ const input = writeJson(root, 'dup.json', { create: { 'sprints\\sprint-1.md': '# A\n', 'sprints/sprint-1.md': '# B\n' } });
+ const r = run(root, ['apply', '--input', input]);
+ assert.strictEqual(r.code, 2);
+ assert.match(r.err, /duplicate path/);
+ assert.ok(!fs.existsSync(path.join(root, '.stories', 'sprints', 'sprint-1.md')));
+ }],
+
+ ['a waiter that saw a stale lock never deletes the live lock that replaced it', () => {
+ const root = newRepo();
+ const lock = path.join(root, '.stories', '.lock');
+ fs.writeFileSync(lock, JSON.stringify({ pid: 2 ** 22 + 1, host: os.hostname(), at: 'stale' }));
+ // Preload: right after the waiter reads the stale lock, another writer wins and holds a live lock.
+ const preload = path.join(root, 'race.js');
+ fs.writeFileSync(preload, `const fs = require('fs'); const orig = fs.readFileSync; let raced = false;
+ fs.readFileSync = function (p, ...a) { const r = orig.call(fs, p, ...a);
+ if (!raced && String(p).endsWith('.lock')) { raced = true; fs.unlinkSync(p);
+ fs.writeFileSync(p, JSON.stringify({ pid: ${process.pid}, host: require('os').hostname(), at: 'live' }), { flag: 'wx' }); }
+ return r; };`);
+ const r = spawnSync(process.execPath, ['-r', preload, LEDGER, 'allocate', '--epic', 'auth-flow', '--root', root, '--wait-ms', '200'], { encoding: 'utf8' });
+ assert.strictEqual(r.status, 3, `expected lock timeout, got ${r.status}: ${r.stderr}`);
+ assert.ok(fs.readFileSync(lock, 'utf8').includes('live'), 'live lock was deleted');
+ }],
+
+ ['story status moves forward one step at a time and new stories start as todo', () => {
+ const root = newRepo();
+ const [id] = run(root, ['allocate', '--epic', 'auth-flow']).out.ids;
+ const put = (kind, status) => run(root, ['apply', '--input', writeJson(root, 't.json', { [kind]: { [`${id}.md`]: story(id, 'Login', { status }) } })]).code;
+ assert.strictEqual(put('create', 'done'), 2);
+ assert.strictEqual(put('create', 'todo'), 0);
+ assert.strictEqual(put('update', 'done'), 2, 'todo -> done skips steps');
+ for (const status of ['in-progress', 'in-progress', 'review', 'done']) assert.strictEqual(put('update', status), 0, status);
+ assert.strictEqual(put('update', 'todo'), 2, 'done -> todo moves backward');
+ assert.ok(read(root, 'epics/auth-flow.md').includes(`| ${id} | Login | done |`));
+ }],
+
+ ['stories can only be assigned to an existing sprint', () => {
+ const root = newRepo();
+ const { ids, input } = createStories(root, ['Login']);
+ run(root, ['apply', '--input', input]);
+ for (const sprint of ['2', 'bogus']) {
+ const plan = writeJson(root, 'p.json', { update: { [`${ids[0]}.md`]: story(ids[0], 'Login', { sprint }) } });
+ assert.strictEqual(run(root, ['apply', '--input', plan]).code, 2, sprint);
+ }
+ fs.writeFileSync(path.join(root, '.stories', `${ids[0]}.md`), story(ids[0], 'Login', { sprint: '7' }));
+ const status = run(root, ['status']);
+ assert.strictEqual(status.code, 2);
+ assert.match(status.err, /sprint 7 does not exist/);
+ }],
+
+ ['story points must be one of 1, 2, 3, 5, 8 so sprint totals stay exact', () => {
+ const root = newRepo();
+ const [id] = run(root, ['allocate', '--epic', 'auth-flow']).out.ids;
+ for (const points of ['bogus', '4', '-3', '1e3', '0', '']) {
+ const input = writeJson(root, 'pts.json', { create: { [`${id}.md`]: story(id, 'Login', { points }) } });
+ assert.strictEqual(run(root, ['apply', '--input', input]).code, 2, `Points=${points}`);
+ }
+ assert.deepStrictEqual(storyFiles(root), []);
+ fs.writeFileSync(path.join(root, '.stories', `${id}.md`), story(id, 'Login', { points: 'bogus' }));
+ const status = run(root, ['status']);
+ assert.strictEqual(status.code, 2);
+ assert.match(status.err, /Points must be one of/);
+ }],
+
++ ['git-common allocation registry refuses a symlinked parent', () => {
++ const root = newRepo();
++ const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'story-outside-'));
++ symlink(outside, path.join(root, '.git', 'story-lifecycle'), 'dir');
++ const result = run(root, ['allocate', '--epic', 'auth-flow']);
++ assert.strictEqual(result.code, 2, result.err);
++ assert.deepStrictEqual(fs.readdirSync(outside), []);
++ }],
++
++ ['allocation count and lock wait must be bounded integers', () => {
++ const root = newRepo();
++ for (const count of ['1.5', 'NaN', 'Infinity']) {
++ assert.strictEqual(run(root, ['allocate', '--epic', 'auth-flow', '--count', count]).code, 2);
++ }
++ for (const value of ['NaN', 'Infinity', '-1', '1.5', '60001']) {
++ assert.strictEqual(run(root, ['allocate', '--epic', 'auth-flow', '--wait-ms', value]).code, 2);
++ }
++ }],
++
+ ['ledger paths are confined to .stories/ file shapes', () => {
+ const dir = path.join(os.tmpdir(), '.stories');
+ for (const bad of ['../x-1.md', 'epics/../../x.md', 'Auth-1.md', 'a/b-1.md', 'epics/a.txt', 'sprints/sprint-0.md', '/abs-1.md']) {
+ assert.throws(() => resolveLedgerPath(dir, bad), /invalid ledger path/, bad);
+ }
+ assert.ok(resolveLedgerPath(dir, 'epics\\auth-flow.md').endsWith(path.join('epics', 'auth-flow.md')));
+ }],
+ ];
+
+ (async () => {
+ console.log('\n=== Testing story-lifecycle ledger behaviour ===\n');
+ let passed = 0;
+ let failed = 0;
+ for (const [name, fn] of tests) {
+ try {
+ await fn();
+ console.log(` ✓ ${name}`);
+ passed++;
+ } catch (error) {
+ if (error instanceof Skip) {
+ console.log(` - ${name} (skipped: ${error.message})`);
+ continue;
+ }
+ console.log(` ✗ ${name}`);
+ console.log(` Error: ${error.message}`);
+ failed++;
+ }
+ }
+ console.log(`\nResults: Passed: ${passed}, Failed: ${failed}`);
+ process.exit(failed > 0 ? 1 : 0);
+ })();