cohorte 3.0.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG.md +105 -0
  2. package/README.md +16 -10
  3. package/bin/cli.js +2 -1
  4. package/core/agents/cohorte-profile-reader.md +21 -31
  5. package/core/agents/cohorte-release.md +6 -3
  6. package/core/agents/cohorte-review.md +31 -5
  7. package/core/agents/implementer.template.md +13 -5
  8. package/core/commands/cohorte-audit.md +10 -3
  9. package/core/commands/cohorte-brainstorm.md +2 -2
  10. package/core/commands/cohorte-build.md +17 -10
  11. package/core/commands/cohorte-doctor.md +11 -9
  12. package/core/commands/cohorte-fix.md +2 -2
  13. package/core/commands/cohorte-fleet.md +1 -1
  14. package/core/commands/cohorte-init-pipeline.md +2 -2
  15. package/core/commands/cohorte-intake.md +3 -3
  16. package/core/commands/cohorte-patch.md +1 -1
  17. package/core/commands/cohorte-refactor.md +73 -8
  18. package/core/commands/cohorte-retro.md +2 -2
  19. package/core/commands/cohorte-revert.md +104 -0
  20. package/core/commands/cohorte-review.md +29 -14
  21. package/core/commands/cohorte-ship.md +17 -5
  22. package/core/commands/cohorte-spec.md +11 -2
  23. package/core/commands/cohorte-update-pipeline.md +12 -8
  24. package/core/commands/cohorte-verify.md +106 -0
  25. package/core/hooks/gate.py +326 -21
  26. package/core/templates/patch.template.md +11 -2
  27. package/core/templates/spec.template.md +23 -2
  28. package/core/templates/steps/init-pipeline/01-detect-stack.md +14 -5
  29. package/core/templates/steps/init-pipeline/02-interview-gaps.md +26 -3
  30. package/core/templates/steps/init-pipeline/03-draft-profile.md +2 -1
  31. package/core/templates/steps/init-pipeline/04-write-render.md +16 -12
  32. package/core/templates/steps/init-pipeline/05-report.md +1 -1
  33. package/core/workflows/audit.js +9 -4
  34. package/core/workflows/loop.js +15 -10
  35. package/core/workflows/refactor.js +116 -9
  36. package/core/workflows/review.js +24 -10
  37. package/lib/doctor.js +37 -3
  38. package/lib/install.js +11 -2
  39. package/lib/project.js +45 -8
  40. package/lib/render.js +3 -3
  41. package/lib/yaml.js +10 -1
  42. package/package.json +2 -2
  43. package/profile/PIPELINE.template.md +39 -1
  44. package/profile/SCHEMA.md +27 -746
  45. package/profile/cohorte.config.template.yaml +1 -1
  46. package/profile/schema/dead-agents.md +29 -0
  47. package/profile/schema/decisions.md +23 -0
  48. package/profile/schema/deferred.md +22 -0
  49. package/profile/schema/feature-diff.md +20 -0
  50. package/profile/schema/kanban.md +95 -0
  51. package/profile/schema/metrics.md +23 -0
  52. package/profile/schema/output-discipline.md +21 -0
  53. package/profile/schema/preflight.md +81 -0
  54. package/profile/schema/profile-block.md +103 -0
  55. package/profile/schema/project-kinds.md +89 -0
  56. package/profile/schema/readiness.md +17 -0
  57. package/profile/schema/reconcile.md +64 -0
  58. package/profile/schema/release-notes.md +29 -0
  59. package/profile/schema/rendering.md +48 -0
  60. package/profile/schema/retrieval.md +58 -0
  61. package/profile/schema/spec-status.md +79 -0
  62. package/profile/schema/specialization.md +41 -0
  63. package/profile/schema/verify.md +115 -0
  64. package/profile/schema/workflows.md +78 -0
  65. package/scripts/kanban-move.sh +45 -3
  66. package/scripts/verify-run.sh +509 -0
@@ -17,28 +17,37 @@ Gather evidence, then summarize what you found. Look for:
17
17
  - **Split candidates (sub-surface boundaries):** inside each surface, look for a clean internal partition
18
18
  — feature modules (`src/features/*`, `src/modules/*`, `app/(group)/*`), or independent services
19
19
  (`services/*`, domain folders). Note the surface's rough size (module/file count) so a *large* surface
20
- with a *clean* boundary can be proposed as several specialized surfaces in Phase 2. See SCHEMA.md
21
- §"Specialization — when to split one surface into more agents" for the heuristic. Don't split yet — just
20
+ with a *clean* boundary can be proposed as several specialized surfaces in Phase 2. See `<core>/pipeline/schema/specialization.md` for the heuristic. Don't split yet — just
22
21
  flag candidates + their would-be shared-code tree.
23
22
  - **Per-surface commands:** derive `test`/`lint`/`format`/`typecheck`/`build` from each surface's
24
23
  `package.json` scripts + the workspace filter syntax (e.g. `pnpm --filter <pkg> test`).
24
+ - **Project kind (`project.kind`):** match the evidence against the detection table of
25
+ `<core>/pipeline/schema/project-kinds.md` (read only its `### Detection` table) — first matching row
26
+ wins: react-native/expo/Swift/Kotlin app ⇒ `mobile`; browser UI deps ⇒ `web`; dbt/Airflow/notebooks ⇒
27
+ `data`; `bin` entries and no UI deps ⇒ `cli`; a published package with exports and no app ⇒
28
+ `library`; server-only ⇒ `api`; else `other`. Note the signal that decided it.
25
29
  - **Contract mechanism:** a shared types/schema package (`packages/shared-types`, Zod/`z.`),
26
30
  an `openapi.*`/`swagger.*` file, `.proto` files, or none.
27
31
  - **Release notes / versioning:** a `.changeset/` directory (+ `config.json`, and whether it declares a
28
32
  `fixed`/lockstep group — that names the anchor package), `changesets` in devDependencies, or a CI job
29
33
  that fails a PR lacking a note (grep `.github/workflows/*` for `changeset`). Also note the root
30
34
  `version`: a `0.y.z` product usually forbids `major`. None of these ⇒ `release_notes.enabled: false`.
35
+ - **Security scanners:** which dependency auditor fits each lockfile or manifest (`npm`/`pnpm`/`yarn`
36
+ audit, `pip-audit`, `govulncheck`, `cargo audit`), and whether each is installed (`command -v`).
37
+ Also check for a secret scanner on PATH (`gitleaks`, `trufflehog`). Match them against the
38
+ detected-defaults table in `<core>/pipeline/schema/preflight.md` §Security scans. They feed
39
+ `commands.security`.
31
40
  - **DB / migrations:** migration tooling (`node ace make:migration`, `knex`, `prisma`, `alembic`,
32
41
  `golang-migrate`), a `docker-compose.yml`, DB service.
33
42
  - **Design system:** an existing `design-reference/` snapshot, `components/ui`, a DesignSync MCP
34
43
  connection, Figma links, or none.
35
44
  - **Code retrieval:** is the `serena` CLI resolvable (`command -v serena`)? If not, does
36
- `~/.local/bin/serena` exist anyway — installed but PATH-broken (see SCHEMA.md §Code retrieval)?
45
+ `~/.local/bin/serena` exist anyway — installed but PATH-broken (see `<core>/pipeline/schema/retrieval.md`)?
37
46
  `graphify`? Is either already registered in this repo's `.mcp.json` or `claude mcp list`? (Feeds
38
47
  the retrieval question + Phase 4 wiring — default provider is `serena`.)
39
48
  - **VCS:** `git remote -v` → host + `owner/repo`; the default branch (`git symbolic-ref refs/remotes/origin/HEAD` or `git branch`).
40
49
  - **Existing `<memory>`** — read it; it may already state stack/conventions to fold in. **Existing
41
50
  `PIPELINE.md`** — if present, this is a re-run: load it as the starting draft and only reconcile deltas.
42
51
 
43
- Print a compact **Detection Report**: layout, surfaces (with framework + commands), contract, release
44
- notes, DB, design, vcs. Mark each field `detected` / `guessed` / `unknown`.
52
+ Print a compact **Detection Report**: layout, project kind, surfaces (with framework + commands),
53
+ contract, release notes, security scanners, DB, design, vcs. Mark each field `detected` / `guessed` / `unknown`.
@@ -4,15 +4,26 @@
4
4
 
5
5
  Ask ONLY what you couldn't confidently detect. Batch related questions. Cover:
6
6
 
7
+ - **Project kind** — always confirm, the detected `project.kind` as the Recommended option with the
8
+ signal that decided it (`web` · `api` · `cli` · `library` · `mobile` · `data` · `other`). It
9
+ selects the spec DoD defaults and the review's checks. Where `<core>/pipeline/schema/project-kinds.md`
10
+ says the kind has no design step, skip the **Design system** question below (`design.enabled: false`,
11
+ every `uses_design: false`); where it has no RBAC check, default **RBAC** to `enabled: false`.
7
12
  - **Surfaces & ownership** — confirm the surface list and each one's path + owning agent name. (If a
8
13
  single-app repo, one surface.) Confirm the `tools` each agent needs (add `DesignSync` only to a
9
14
  surface with `uses_design: true`), and each surface's `model` tier: `sonnet` (Recommended default —
10
15
  implementers mostly apply a frozen contract, which Sonnet handles at a fraction of the Opus-lead
11
16
  cost), `haiku` for purely mechanical surfaces (scaffolding), `inherit` only for surfaces with real
12
17
  design decisions worth running on the lead's model.
18
+ **Ownership is enforced** (the gate denies a surface agent's Write/Edit outside its `path`), so
19
+ check what each surface legitimately writes elsewhere: tests or fixtures in a root folder (`tests/`,
20
+ `e2e/`, `__tests__/` outside the surface path), a generated client, a shared i18n file. Propose them
21
+ as that surface's `owns_also: [...]`, and files every surface may touch (root lockfile, root
22
+ `package.json` workspaces list) as `ownership.shared_writable: [...]`. Unsure ⇒ propose, never skip:
23
+ a missing entry shows up as a denied write in the first build.
13
24
  - **Specialization (only if Phase 1 flagged a large + cleanly-separable surface)** — offer to split it
14
25
  into specialized sub-surfaces (e.g. `web-checkout`, `web-billing`) so `/cohorte-build` runs them in parallel,
15
- per SCHEMA.md §Specialization. If the human accepts, apply the rules: **shared code (routing, global
26
+ per `<core>/pipeline/schema/specialization.md`. If the human accepts, apply the rules: **shared code (routing, global
16
27
  state, DS kit/tokens) becomes its own single-owner surface**, and cross-slice shapes go through the
17
28
  contract. Default to NOT splitting when boundaries are tangled or slices are tiny — coarse is fine.
18
29
  - **Quiet commands** (never store a bare `pnpm test` as what agents execute) — for each noisy command
@@ -20,8 +31,20 @@ Ask ONLY what you couldn't confidently detect. Batch related questions. Cover:
20
31
  Recommended option: dot/failures-only reporter (`--reporter=dot` vitest/playwright, `--silent`
21
32
  jest, `-q` pytest, `--quiet` eslint/ruff — whatever the detected runner supports). These land in
22
33
  `test_quiet_cmd`/`lint_quiet_cmd` + `commands.test_quiet`/`lint_quiet` and are what agents and the
23
- `/cohorte-review` pre-flight actually run (SCHEMA.md §Output discipline). If the human declines or
34
+ `/cohorte-review` pre-flight actually run (`<core>/pipeline/schema/output-discipline.md`). If the human declines or
24
35
  the runner has no such flag, leave `""` — consumers then fall back to `<cmd> 2>&1 | tail -40`.
36
+ - **Security scans** (only if Phase 1 found an auditor or a secret scanner). Propose the detected
37
+ commands from `<core>/pipeline/schema/preflight.md` §Security scans as one multi-select. Fill
38
+ in `--default <default_branch>`. If `CLAUDE_CONFIG_DIR` is set, use its literal value in place
39
+ of `~/.claude`. Note that a scan red at its threshold blocks every review, so the default branch
40
+ must pass it today. If it doesn't, offer a higher threshold. The accepted commands go in
41
+ `commands.security`. None accepted ⇒ `security: []`.
42
+ - **Runtime verification** (`/cohorte-verify`, `<core>/pipeline/schema/verify.md`) — only if Phase 1
43
+ found a dev server, an e2e runner or migrations. Propose `commands.dev` + `commands.dev_ready` (a URL
44
+ such as `http://localhost:5173` or a probe command), `commands.smoke` / `commands.e2e` when they
45
+ exist, and `commands.migrate_down` when migrations do; ask `verify.db`: `local` (the dev DB is the
46
+ human's own) or `shared` (others use it — migrations are then refused unless isolation gives each
47
+ worktree its own DB). Declined ⇒ leave `dev_ready` empty: verify stays off and ship never asks.
25
48
  - **Contract** — mechanism (`shared-types-zod` / `openapi` / `protobuf` / `json-schema` / `none`) and
26
49
  where feature contracts are authored. If `none`, surfaces sync by the spec prose alone.
27
50
  - **Release notes (only if Phase 1 found a versioning tool or a note-enforcing CI job)** — confirm the
@@ -33,7 +56,7 @@ Ask ONLY what you couldn't confidently detect. Batch related questions. Cover:
33
56
  - **UI language** — language of all user-facing copy.
34
57
  - **RBAC** — is there a role hierarchy? If yes, list it highest→lowest.
35
58
  - **Design system** — enabled? provider (Claude Design / Figma / none) + project ids + kit/token paths.
36
- - **Code retrieval** — confirm the provider (see SCHEMA.md §Code retrieval): `serena` (Recommended
59
+ - **Code retrieval** — confirm the provider (see `<core>/pipeline/schema/retrieval.md`): `serena` (Recommended
37
60
  default — live LSP symbol navigation, no index to maintain), `graphify` (persistent knowledge graph
38
61
  over code + docs — better on very large or mixed code+docs repos, but needs an index step + rescans),
39
62
  or `none`. Only demote from `serena` if the human objects or the provider CLI can't be installed.
@@ -3,7 +3,8 @@
3
3
  ### Phase 3 — Draft the profile (show, don't write yet)
4
4
 
5
5
  Assemble the full `PIPELINE.md` from `<core>/pipeline/PIPELINE.template.md`, filling the `yaml pipeline-profile`
6
- block and every prose section from Phases 1–2. **Keep it lean**: every stateless agent re-reads this
6
+ block and every prose section from Phases 1–2 — including `project.kind` as confirmed in Phase 2
7
+ (and the `design`/`rbac` defaults it implied). **Keep it lean**: every stateless agent re-reads this
7
8
  file on every dispatch, so its length is a per-dispatch token+latency tax — terse rule-shaped
8
9
  conventions, no narration, no facts derivable from the code. **Show the human the drafted
9
10
  `PIPELINE.md` in a fenced block and get a go-ahead** before writing.
@@ -6,8 +6,7 @@
6
6
  2. **Wire it into `<memory>`:** if `<memory>` exists, ensure it references the profile (add a line
7
7
  near the top: `> Project profile & pipeline facts: **@PIPELINE.md**`). If not, create a minimal
8
8
  `<memory>` with that reference + a one-paragraph project intro.
9
- 3. **Render one agent per surface** — for each surface, follow SCHEMA.md §"Rendering / reconciling a
10
- surface agent" (steps 2–3): render `<agents>/<agent>.md` from the installer's
9
+ 3. **Render one agent per surface** — for each surface, follow `<core>/pipeline/schema/rendering.md` (steps 2–3): render `<agents>/<agent>.md` from the installer's
11
10
  `pipeline/implementer.template.md`, substituting `<SURFACE_AGENT>`, `<SURFACE_LABEL>`, `<SURFACE_PATH>`,
12
11
  `<SURFACE_TOOLS>`, `<SURFACE_MODEL>`, `<PROJECT_NAME>`, `<SURFACE_CONVENTIONS>` (the surface's
13
12
  baked convention slice — §Shared + its `### Surface:` stanza + its §Testing lines from the
@@ -26,14 +25,15 @@
26
25
  permission prompts — including mid-workflow, where nobody is watching a prompt: the detected
27
26
  per-surface `test_cmd`/`lint_cmd`/`typecheck_cmd`/`build_cmd` **and their `*_quiet_cmd`
28
27
  variants** and repo-wide `commands.*` equivalents as `Bash(<cmd>:*)` rules, plus read-only git —
29
- `Bash(git status:*)`, `Bash(git diff:*)`, `Bash(git log:*)`, `Bash(git rev-parse:*)` — plus the
28
+ `Bash(git status:*)`, `Bash(git diff:*)`, `Bash(git log:*)`, `Bash(git rev-parse:*)`, plus
29
+ `Bash(git switch:*)` and `Bash(date:*)` (the refactor workflow cuts its branch and dates its spec) — plus the
30
30
  shipped pipeline scripts (`Bash(<core>/pipeline/scripts/:*)` — preflight, kanban-move;
31
31
  a prefix rule matches a command *starting* with that path, so a `bash <path>`
32
32
  invocation would need its own entry), and the
33
33
  retrieval provider's MCP tools when wired (e.g. `mcp__serena`). Never allowlist anything matching
34
34
  a `gate.ask`/`gate.deny` pattern. Mention the human can widen it later with
35
35
  `/fewer-permission-prompts`) + the PostToolUse formatter hook (detected formatter). Do **not**
36
- write the gate hook here — step 9 (`<sync>`) registers it.
36
+ write the gate hook here — step 8 (`<sync>`) registers it.
37
37
  Preserve any existing custom keys.
38
38
  6. **Wire the retrieval provider** (skip if `retrieval.provider: none`):
39
39
  - **serena:** if the `serena` CLI is missing, have the human install it (`uv tool install -p 3.13
@@ -42,35 +42,39 @@
42
42
  recommend the PATH fix (`uv tool update-shell`, or add `~/.local/bin` to the shell profile) for
43
43
  CLI use. Then register at **project scope** (committed `.mcp.json`, portable —
44
44
  `--project-from-cwd` resolves the project at server start) using the **PATH-proof launcher**
45
- from SCHEMA.md §Code retrieval (`sh -c 'exec "$(command -v serena || echo
45
+ from `<core>/pipeline/schema/retrieval.md` (`sh -c 'exec "$(command -v serena || echo
46
46
  "$HOME/.local/bin/serena")" start-mcp-server …'` — a bare `serena` entry dies with ENOENT when
47
47
  Claude Code was launched from an environment without `~/.local/bin` on PATH; Windows-native
48
48
  teams use the bare form + PATH instead). If `.mcp.json` already has a bare `serena` entry,
49
49
  upgrade it to the launcher form rather than skipping. Add `.serena/` to the repo's `.gitignore`
50
50
  (per-machine cache/config Serena creates on first launch). On a large repo, offer the one-off
51
- `serena project index`. Finish with the **health check** from SCHEMA.md §Code retrieval and
51
+ `serena project index`. Finish with the **health check** from `<core>/pipeline/schema/retrieval.md` and
52
52
  report each result — if the static checks pass but the server isn't connected in this session,
53
53
  say a session restart is needed; never report Serena wired on registration alone.
54
54
  - **graphify:** have the human install it (`uv tool install graphify` then `graphify install`),
55
55
  build the initial graph (`/graphify .`), and note it needs incremental rescans (`--update`) after
56
56
  big changes.
57
57
  - Either way the rendered agents already carry the provider's MCP tools in their `tools:` list
58
- (step 3 / SCHEMA §Rendering); remind the human the new MCP server appears after a session restart.
58
+ (step 3 / `<core>/pipeline/schema/rendering.md`); remind the human the new MCP server appears after a session restart.
59
59
  7. **Render the isolation scripts** (if `isolation.enabled`) from the installer's
60
60
  `pipeline/scripts/*.template` to this repo's `scripts/new-feature.sh` and `scripts/remove-feature.sh`,
61
61
  substituting the `__TOKENS__` (project
62
62
  slug, DB pattern, port bases, compose file, branch prefix, install/dev/migrate commands, per-surface
63
63
  env stanzas). `chmod +x` them. If isolation is disabled, skip and note features build in the main checkout.
64
- 8. **Wire the project: run `<sync>`** from the repo root (one Bash call) and show its output. It is
64
+ 8. **Wire the project: run `<sync>`** from the repo root (one Bash call) and show its output — always
65
+ AFTER step 1 wrote `PIPELINE.md`, never before: it parses the machine block into
66
+ `<state>/profile.json`, the file the agents read instead of `PIPELINE.md`. It is
65
67
  deterministic and idempotent: it copies the gate to `.claude/hooks/cohorte-gate.py`, registers it
66
- in `.claude/settings.json` (matchers `Bash|Task|Agent` and `Write|Edit|MultiEdit`, exactly once,
68
+ in `.claude/settings.json` (matchers `Bash|Task|Agent` and `Write|Edit|MultiEdit|NotebookEdit`, exactly once,
67
69
  every other hook kept), writes the `<state>/pipeline.json` pointer, adds
68
70
  `<state>/preflight.ok`, `<state>/pipeline-metrics.jsonl` and `specs/reports/` to `.gitignore`, and
69
- seeds `specs/_template.md`. If it exits non-zero (e.g. `.claude/settings.json` is not valid JSON),
71
+ seeds `specs/_template.md`, and writes `<state>/profile.json` (it says so if the block does not
72
+ parse — fix `PIPELINE.md` and re-run). If it exits non-zero (e.g. `.claude/settings.json` is not valid JSON),
70
73
  stop and show the error — never hand-write those files instead. If `<state>/preflight.ok` is
71
74
  already tracked: `git rm --cached <state>/preflight.ok`.
72
75
  9. **Tell the human what to commit:** `PIPELINE.md`, `<agents>/`, `<state>/gate-config.json`,
73
- `<state>/settings.json`, `.claude/hooks/cohorte-gate.py`, `<state>/pipeline.json`, `.gitignore`,
76
+ `<state>/settings.json`, `.claude/hooks/cohorte-gate.py`, `<state>/pipeline.json`,
77
+ `<state>/profile.json` (regenerated by every `<sync>` — commit it with each `PIPELINE.md` change), `.gitignore`,
74
78
  `<memory>`. A teammate who clones gets the gate immediately; they need `npm i -g cohorte &&
75
79
  cohorte install` only for the commands.
76
80
  10. **CI workflow** (if `vcs.host: github` and no existing workflow already runs the profile's
@@ -81,7 +85,7 @@
81
85
  sibling workflow does if one exists. `/cohorte-ship` watches these checks before the merge.
82
86
  11. **Design system:** if `design.enabled` with a snapshot dir, note that `/cohorte-align-ds` is active; else the
83
87
  `/cohorte-align-ds` command will no-op with a clear message.
84
- 12. **Kanban** (only if the human opted in at Phase 2): wire it per SCHEMA.md §Kanban, writing into the
88
+ 12. **Kanban** (only if the human opted in at Phase 2): wire it per `<core>/pipeline/schema/kanban.md`, writing into the
85
89
  **global** `<config>` (never into this repo — the board points at a
86
90
  personal vault). Create the file from `pipeline/cohorte.config.template.yaml` if absent; set
87
91
  `kanban.enabled: true` and `obsidian.vault_path` if it was empty. Add a `kanban.boards[<PIPELINE
@@ -7,5 +7,5 @@ tailored workflow line, e.g.
7
7
  `/cohorte-brainstorm → /cohorte-spec → (design) → /cohorte-build <id> → test → /cohorte-review → /cohorte-ship`. Tell the human to sanity-check
8
8
  `PIPELINE.md`, commit it, and run `/cohorte-brainstorm` to start a feature. Note that this was the one-time
9
9
  setup: from now on `/cohorte-update-pipeline` both refreshes the core AND reconciles the generated files
10
- (SCHEMA.md §Reconcile), and `/cohorte-build` auto-grows surfaces — re-running `/cohorte-init-pipeline` is only for deep
10
+ (`<core>/pipeline/schema/reconcile.md`), and `/cohorte-build` auto-grows surfaces — re-running `/cohorte-init-pipeline` is only for deep
11
11
  stack changes (package manager, contract mechanism, surface overhaul).
@@ -3,7 +3,7 @@
3
3
  //
4
4
  // Invoke with args = {target: "<path or domain>"} (optional — default whole repo).
5
5
  //
6
- // Shape (SCHEMA.md §Workflows): profile via profile-reader (phase 0), the
6
+ // Shape (profile/schema/workflows.md): profile via profile-reader (phase 0), the
7
7
  // mechanical gates staged to disk by one haiku agent, then ONE auditor per
8
8
  // domain (each surface + `shared`) running concurrently — the runtime caps
9
9
  // concurrency at 20 (CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS since 2026-08), extra
@@ -144,7 +144,7 @@ const BACKLOG = {
144
144
  // ── Phase 0 — profile ────────────────────────────────────────────────────────
145
145
  phase('Profile')
146
146
  const profile = unwrapProfile(await agent(
147
- 'Return this project\'s PIPELINE.md `yaml pipeline-profile` block as JSON, per your instructions.',
147
+ 'Return this project\'s profile (the `yaml pipeline-profile` block — `.claude/profile.json`, else PIPELINE.md) as JSON, per your instructions.',
148
148
  { agentType: 'cohorte-profile-reader', label: 'profile', schema: PROFILE, effort: 'low' },
149
149
  ))
150
150
  if (!profile || profile.error) {
@@ -180,7 +180,7 @@ const gates = await agent(
180
180
  { model: 'haiku', label: 'gates', schema: GATES, effort: 'low' },
181
181
  )
182
182
  // A dead gates agent is NOT "zero mechanical failures" — silence would read as the
183
- // cleanest possible inventory from a phase that never ran (SCHEMA.md §Dead agents).
183
+ // cleanest possible inventory from a phase that never ran (profile/schema/dead-agents.md).
184
184
  // The domain auditors still run (they read the staged gates file, which then simply
185
185
  // isn't there), but the run must say the mechanical sweep is uncovered.
186
186
  const gatesCovered = gates != null
@@ -238,6 +238,11 @@ const oldDomains = (existing && Array.isArray(existing.domains) ? existing.domai
238
238
  .filter(d => d && d.key).map(d => ({ key: String(d.key).trim(), lines: Array.isArray(d.lines) ? d.lines : [] }))
239
239
  const oldByKey = Object.fromEntries(oldDomains.map(d => [d.key, d.lines]))
240
240
  const isOpenDeferred = l => /^- \[ \]/.test(l) && /deferred:\S/.test(l)
241
+ // A ticked item cleared by a refactor round that has not shipped yet: its `refactor:<id>` spec is
242
+ // the review → PR route, and dropping the line would orphan it. Workflow scripts cannot read the
243
+ // spec's status, so the workflow keeps every such line; /cohorte-audit (conversational) prunes the
244
+ // ones whose spec is merged or gone.
245
+ const isRefactorTick = l => /^- \[x\]/.test(l) && /refactor:\S/.test(l)
241
246
  let total = 0
242
247
  let carried = 0
243
248
  const sections = []
@@ -250,7 +255,7 @@ for (const key of order) {
250
255
  total += items.length
251
256
  const lines = items.map(it => `- [ ] ${it.severity} · ${it.file}:${it.line} · ${it.kind} · ${it.fix}`)
252
257
  if (d.overflow) lines.push(`- [ ] (+${d.overflow} more beyond the cap — re-audit ${d.key} after this pass)`)
253
- const keep = (oldByKey[key] || []).filter(isOpenDeferred).filter(l => !lines.includes(l))
258
+ const keep = (oldByKey[key] || []).filter(l => isOpenDeferred(l) || isRefactorTick(l)).filter(l => !lines.includes(l))
254
259
  carried += keep.length
255
260
  sections.push({ key, lines: lines.concat(keep) })
256
261
  } else if (oldByKey[key] && oldByKey[key].length) {
@@ -33,8 +33,8 @@
33
33
  // review. scripts/test-workflows.mjs stubs workflow() to pin both paths.
34
34
  //
35
35
  // NOTE for unattended runs: workflow subagents run in acceptEdits whatever the session
36
- // mode, so hooks/gate.py is the only brake on file edits for the whole run (SCHEMA.md
37
- // §Preflight) — and in bypassPermissions its asks escalate to hard denies.
36
+ // mode, so hooks/gate.py is the only brake on file edits for the whole run
37
+ // (profile/schema/preflight.md) — and in bypassPermissions its asks escalate to hard denies.
38
38
 
39
39
  export const meta = {
40
40
  name: 'cohorte-loop',
@@ -88,7 +88,7 @@ const TERMINAL = new Set(['treading-water', 'max-rounds', 'contract-change'])
88
88
  // ── The reducer — the whole design, as one pure function ─────────────────────
89
89
  // Evaluated in this order; the first match wins, and the order is load-bearing:
90
90
  // 1. A child abort (preflight red, dead stager) carries no coverage claim — relay it.
91
- // 2. `unreviewed` BEFORE `blocking`: SCHEMA.md §Dead agents — a dead reviewer makes
91
+ // 2. `unreviewed` BEFORE `blocking`: profile/schema/dead-agents.md — a dead reviewer makes
92
92
  // blocking == 0 a statement about code nobody read. Checked the other way round,
93
93
  // the loop ships a feature whose reviewer crashed, silently and "successfully".
94
94
  // 3. blocking == 0 ⇒ ship. HIGH/MEDIUM/LOW never block (they route to the backlog)
@@ -247,7 +247,7 @@ const spent = () => {
247
247
  }
248
248
 
249
249
  // kanban-move.sh is optional infrastructure — every prompt that runs it defines <core>
250
- // and tolerates its absence, per SCHEMA.md §Kanban.
250
+ // and tolerates its absence, per profile/schema/kanban.md.
251
251
  const CORE_DEF = '(<core> = "${CLAUDE_CONFIG_DIR:-$HOME/.claude}/cohorte" — ' +
252
252
  'script absent ⇒ skip the kanban step, the board is optional.)'
253
253
  const METRICS_PATH = '$(dirname "$(git rev-parse --git-common-dir)")/.claude/pipeline-metrics.jsonl'
@@ -255,7 +255,7 @@ const METRICS_PATH = '$(dirname "$(git rev-parse --git-common-dir)")/.claude/pip
255
255
  // ── Phase 0 — profile ────────────────────────────────────────────────────────
256
256
  phase('Profile')
257
257
  const profile = unwrapProfile(await agent(
258
- 'Return this project\'s PIPELINE.md `yaml pipeline-profile` block as JSON, per your instructions.',
258
+ 'Return this project\'s profile (the `yaml pipeline-profile` block — `.claude/profile.json`, else PIPELINE.md) as JSON, per your instructions.',
259
259
  { agentType: 'cohorte-profile-reader', label: 'profile', schema: PROFILE, effort: 'low' },
260
260
  ))
261
261
  if (!profile || profile.error) {
@@ -340,7 +340,12 @@ if (!['frozen', 'in-review', 'in-progress'].includes(status) && !blockedOk) {
340
340
  ? `spec is blocked by a finished loop run (reason: ${prevStop || 'unknown'}) — that stop needs a human: ` +
341
341
  `/cohorte-fix ${feature} for open Remediation items, or /cohorte-build ${feature} [--readiness-only] to re-enter; then re-run the loop`
342
342
  : `spec status is '${status || '(none)'}' — the loop needs frozen | in-review | in-progress ` +
343
- `(SCHEMA.md §Spec status). draft ⇒ /cohorte-spec; shipped/merged ⇒ done already`)
343
+ `(profile/schema/spec-status.md). draft ⇒ /cohorte-spec; shipped/merged ⇒ done already`)
344
+ }
345
+ // 1b. A `kind: refactor` spec (frozen by /cohorte-refactor §4) has no contract and enters at
346
+ // review — building it would dispatch implementers against a contract that does not exist.
347
+ if (facts.spec.kind === 'refactor') {
348
+ return abortPre(`specs/${feature}.md is a kind: refactor spec — it was built by /cohorte-refactor; run /cohorte-review ${feature} then /cohorte-ship ${feature}, never the loop`)
344
349
  }
345
350
  // 2. A fresh readiness verdict — the gate /cohorte-build §1.6 wrote. NOT-READY is the one
346
351
  // outcome more passes cannot fix; stale-or-absent means nobody has judged THIS spec.
@@ -410,7 +415,7 @@ const dispatchPrompt = j =>
410
415
  'Readiness gaps for YOUR surface (§1.6 RESERVATIONS — the spec is silent here: implement the stated ' +
411
416
  `assumption and flag what you assumed in your handoff): ${j.gaps}.`
412
417
 
413
- // Dispatch + roll call, SCHEMA.md §Dead agents: parallel fan-out, then each silent
418
+ // Dispatch + roll call, profile/schema/dead-agents.md: parallel fan-out, then each silent
414
419
  // surface retried ONCE, alone, byte-identical. Never a surface that answered.
415
420
  const dispatchSurfaces = async (jobs, phaseTitle) => {
416
421
  const tag = phaseTitle === 'Build' ? 'build' : 'fix'
@@ -470,7 +475,7 @@ const writeState = async ({ label, phaseName, outcome, reason, status: st, kanba
470
475
  }
471
476
 
472
477
  // Close the run: final loop.json + status + kanban, then the return object. Status
473
- // doctrine (SCHEMA.md §Spec status): `blocked` = a round gave up, reason named in
478
+ // doctrine (profile/schema/spec-status.md): `blocked` = a round gave up, reason named in
474
479
  // loop.json; `in-review` = zero blocking, awaiting /cohorte-ship; precondition aborts
475
480
  // never stamped anything, so they change nothing here either. A RESUMABLE abort leaves
476
481
  // loop.json without `outcome` (phase kept, reason set), so the next invocation resumes at
@@ -519,7 +524,7 @@ if (fresh(facts.build) && !(facts.build.dead || []).length) {
519
524
  const built = await dispatchSurfaces(jobs, 'Build')
520
525
  const dead = built.filter(b => b.handoff == null).map(b => b.key)
521
526
  // Write build.json + the metrics line EVEN WHEN a surface died — an incomplete batch
522
- // is exactly the batch worth recording (SCHEMA.md §Dead agents).
527
+ // is exactly the batch worth recording (profile/schema/dead-agents.md).
523
528
  await writeState({
524
529
  label: 'state:built', phaseName: dead.length ? 'build' : 'review',
525
530
  metrics: {
@@ -653,7 +658,7 @@ while (true) {
653
658
  const fixed = await dispatchSurfaces(fixJobs, 'Fix')
654
659
  const fixDead = fixed.filter(f => f.handoff == null).map(f => f.key)
655
660
  // The metrics line is written EVEN WHEN a surface died — an incomplete batch is
656
- // exactly the batch worth recording (SCHEMA.md §Dead agents), so it lands before
661
+ // exactly the batch worth recording (profile/schema/dead-agents.md), so it lands before
657
662
  // the dead-implementers abort, with the dead surfaces named.
658
663
  await writeState({ label: `state:fixed-${round}`, phaseName: 'review', metrics: {
659
664
  phase: 'fix', tokens: Math.max(0, spent() - mark),
@@ -5,11 +5,13 @@
5
5
  // cheaper through the conversational /cohorte-refactor — this script skips it and says
6
6
  // so. Invoke with args = {domains: ["backend", …]} or {domains: "all"}.
7
7
  //
8
- // Shape (SCHEMA.md §Workflows): profile via profile-reader (phase 0), the open
8
+ // Shape (profile/schema/workflows.md): profile via profile-reader (phase 0), the open
9
9
  // backlog read once, the `shared` domain (contract package — every slice
10
10
  // imports it) refactored FIRST and alone, then the other domains' surface
11
11
  // implementers in parallel (their trees are disjoint by construction), each
12
- // verified per-domain with one bounded retry round, and the backlog ticked.
12
+ // verified per-domain with one bounded retry round, then — gates green and ≥ 1 item
13
+ // cleared — the round frozen as ONE `kind: refactor` spec (the route to /cohorte-review →
14
+ // /cohorte-ship, which ships specs, not backlogs) and the backlog ticked with its id.
13
15
 
14
16
  export const meta = {
15
17
  name: 'cohorte-refactor',
@@ -21,7 +23,8 @@ export const meta = {
21
23
  { title: 'Shared', detail: 'refactor the contract package first, alone' },
22
24
  { title: 'Refactor', detail: 'one surface implementer per domain, parallel' },
23
25
  { title: 'Verify', detail: 'per-domain gates + item check, one retry round', model: 'haiku' },
24
- { title: 'Tick', detail: 'check cleared items off specs/refactor-backlog.md', model: 'haiku' },
26
+ { title: 'Spec', detail: 'freeze the round as a kind: refactor spec for review → ship', model: 'haiku' },
27
+ { title: 'Tick', detail: 'check cleared items off specs/refactor-backlog.md (· refactor:<id>)', model: 'haiku' },
25
28
  ],
26
29
  }
27
30
 
@@ -113,6 +116,18 @@ const OPEN = {
113
116
  },
114
117
  }
115
118
 
119
+ // The spec writer settles the id (the script has no clock — Date is unavailable in a
120
+ // workflow) and returns it; anything not shaped like a refactor id counts as a dead writer.
121
+ const SPEC = {
122
+ type: 'object', required: ['id', 'branch'], additionalProperties: false,
123
+ properties: {
124
+ id: { type: 'string', description: 'refactor-<domains>-<YYYY-MM-DD>[-n], the spec file name without .md' },
125
+ branch: { type: 'string', description: 'the branch checked out after step 3' },
126
+ kanban: { type: 'string', description: 'the line kanban-move.sh printed' },
127
+ },
128
+ }
129
+ const SPEC_ID = /^refactor-[a-z0-9][a-z0-9-]*$/
130
+
116
131
  const VERIFY = {
117
132
  type: 'object', required: ['cleared', 'remaining', 'gatesGreen'], additionalProperties: false,
118
133
  properties: {
@@ -126,7 +141,7 @@ const VERIFY = {
126
141
  // ── Phase 0 — profile ────────────────────────────────────────────────────────
127
142
  phase('Profile')
128
143
  const profile = unwrapProfile(await agent(
129
- 'Return this project\'s PIPELINE.md `yaml pipeline-profile` block as JSON, per your instructions.',
144
+ 'Return this project\'s profile (the `yaml pipeline-profile` block — `.claude/profile.json`, else PIPELINE.md) as JSON, per your instructions.',
130
145
  { agentType: 'cohorte-profile-reader', label: 'profile', schema: PROFILE, effort: 'low' },
131
146
  ))
132
147
  if (!profile || profile.error) {
@@ -228,6 +243,9 @@ const verifyDomain = async (d, implHandoff) => {
228
243
  v = v2
229
244
  ? { ...v2, cleared: [...new Set(cleared1.concat(v2.cleared || []))] }
230
245
  : { cleared: cleared1, remaining: retryItems, gatesGreen: false, failures: 'verifier died on the retry round' }
246
+ // The retry's verifier is asked the same question with no gates either — its
247
+ // gatesGreen is no more evidence than round 1's was.
248
+ if (noGates) v = { ...v, gatesGreen: false, failures: 'no gate commands declared for this domain — gates unverified' }
231
249
  }
232
250
  return { key: d.key, ...(v || { cleared: [], remaining: d.items, gatesGreen: false, failures: 'verifier died' }) }
233
251
  }
@@ -260,13 +278,94 @@ const restResults = await pipeline(
260
278
  )
261
279
  results.push(...restResults.filter(Boolean))
262
280
 
263
- // ── Phase 5 — tick the cleared items ─────────────────────────────────────────
264
- phase('Tick')
281
+ // ── Phase 5 — freeze the round as a `kind: refactor` spec ────────────────────
282
+ // Without it the round is code in the working tree with no route to a PR. ONE spec for the
283
+ // whole round: review's diff, the freshness digest and the release commit all cover the
284
+ // whole tree, so a spec per domain would each claim the others' code. Red gates ⇒ no spec
285
+ // (review's preflight would abort it anyway) — finish the round first.
265
286
  const clearedAll = results.flatMap(r => r.cleared)
287
+ const remainingAll = results.flatMap(r => r.remaining)
288
+ const gatesAllGreen = results.length > 0 && results.every(r => r.gatesGreen)
289
+ const clearedDomains = results.filter(r => r.cleared.length)
290
+ // Surface keys are free text (`web_checkout`, `API`); an id is a file name and a branch,
291
+ // and SPEC_ID below rejects anything else — so normalize here, not in the writer.
292
+ const idPart = k => String(k).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || 'domain'
293
+ const slug = clearedDomains.length > 3 ? 'all' : clearedDomains.map(r => idPart(r.key)).join('-')
294
+ const prefix = (profile.vcs && profile.vcs.feature_branch_prefix) || 'feature/'
295
+ const bare = l => String(l).replace(/^- \[[ x]\] /, '- ')
296
+ const specTitle = `Refactor ${slug} — ${clearedAll.length} backlog item(s)`
297
+ const specText = [
298
+ '---',
299
+ 'feature_id: <ID>',
300
+ 'kind: refactor # behaviour-preserving backlog pass — no contract; commit as refactor(<scope>)',
301
+ `title: ${specTitle}`,
302
+ 'status: frozen',
303
+ `branch: ${prefix}<ID>`,
304
+ 'created: <DATE>',
305
+ 'reviewed_base:',
306
+ 'reviewed_digest:',
307
+ '---',
308
+ '',
309
+ `# ${specTitle}`,
310
+ '',
311
+ '## 1. Goal',
312
+ '',
313
+ `Clear ${clearedAll.length} \`specs/refactor-backlog.md\` item(s) on ${clearedDomains.map(r => r.key).join(', ')} with no change of public behaviour.`,
314
+ '',
315
+ '## 2. Scope',
316
+ '',
317
+ '**In:** the §6 items, verbatim. **Out:** any behaviour change; the items §7 lists.',
318
+ '',
319
+ '## 6. Surface tasks',
320
+ ...clearedDomains.flatMap(r => ['', `### ${r.key}`, '', ...r.cleared.map(bare)]),
321
+ '',
322
+ '## 7. Out of scope',
323
+ '',
324
+ ...(remainingAll.length ? remainingAll.map(l => `${bare(l)} (still open in the backlog)`) : ['none']),
325
+ '',
326
+ '## 9. Acceptance criteria / DoD',
327
+ '',
328
+ '- [ ] Public behaviour preserved — no exported signature, route, response shape, CLI flag or persisted format changed (unless an item marks it a bug)',
329
+ '- [ ] Each §6 item cleared at its file:line',
330
+ '- [ ] All tests green — behaviour pinned by tests added first; no existing test loosened',
331
+ '- [ ] `PIPELINE.md` commands.lint · typecheck · test green',
332
+ "- [ ] Nothing outside §6's surfaces changed",
333
+ '',
334
+ '## Remediation',
335
+ '',
336
+ ].join('\n')
337
+
338
+ let spec = null
339
+ const wantSpec = clearedAll.length > 0 && gatesAllGreen
340
+ if (wantSpec) {
341
+ phase('Spec')
342
+ const w = await agent(
343
+ 'Freeze this cohorte refactor round as a spec (mechanical — no judgment). ' +
344
+ `0. ONE open refactor spec per branch: if \`git rev-parse --abbrev-ref HEAD\` is ${prefix}refactor-<x> and ` +
345
+ 'specs/refactor-<x>.md exists with `status:` frozen or in-review, then ID = refactor-<x>: append the §6 item ' +
346
+ "lines below under their `### <domain>` headings there (add a heading if missing), skip to step 4. " +
347
+ `1. Run \`date +%F\` ⇒ DATE; ID = refactor-${slug}-DATE. If specs/ID.md exists and its \`status:\` is ` +
348
+ 'shipped/merged/abandoned, suffix -2, -3… until the name is free. If it exists UNSHIPPED (frozen/in-review), ' +
349
+ "do not overwrite it: append this round's §6 item lines under their `### <domain>` headings there and skip step 2. " +
350
+ '2. Write specs/ID.md with EXACTLY the content below, every <ID> and <DATE> substituted. ' +
351
+ `3. \`git rev-parse --abbrev-ref HEAD\`: on ${base} ⇒ \`git switch -c ${prefix}ID\` (uncommitted work carries over); ` +
352
+ `already on ${prefix}ID ⇒ keep it; any other branch ⇒ leave it and report it. ` +
353
+ `4. \`<core>/pipeline/scripts/kanban-move.sh auto ID ready --title "[refactor] ${slug}"\` ` +
354
+ '(<core> = "${CLAUDE_CONFIG_DIR:-$HOME/.claude}/cohorte"). ' +
355
+ 'Return id (ID), branch (checked out now) and kanban (the line the script printed).\n' +
356
+ `<<<SPEC\n${specText}SPEC`,
357
+ { model: 'haiku', label: 'write-spec', schema: SPEC, effort: 'low' },
358
+ )
359
+ spec = w && typeof w === 'object' && SPEC_ID.test(String(w.id || '')) ? w : null
360
+ }
361
+
362
+ // ── Phase 6 — tick the cleared items ─────────────────────────────────────────
363
+ phase('Tick')
266
364
  let tickedOk = true
267
365
  if (clearedAll.length) {
268
366
  const ticked = await agent(
269
367
  'In specs/refactor-backlog.md flip EXACTLY these open `- [ ]` item lines to `- [x]` (match verbatim, ' +
368
+ (spec ? `append \` · refactor:${spec.id}\` to each flipped line, ` : '') +
270
369
  'leave every other line untouched), then return the single word done:\n' + clearedAll.join('\n'),
271
370
  { model: 'haiku', label: 'tick-backlog', effort: 'low' },
272
371
  )
@@ -275,6 +374,7 @@ if (clearedAll.length) {
275
374
  tickedOk = ticked != null && /done/i.test(String(ticked))
276
375
  }
277
376
 
377
+ const branchOk = spec && spec.branch === `${prefix}${spec.id}`
278
378
  return {
279
379
  domains: Object.fromEntries(results.map(r => [r.key, {
280
380
  cleared: r.cleared.length, remaining: r.remaining.length, gatesGreen: r.gatesGreen,
@@ -282,10 +382,17 @@ return {
282
382
  skippedSmall: Object.fromEntries(small.map(d => [d.key, d.items.length])),
283
383
  stillOpen: results.flatMap(r => r.remaining.map(line => `[${r.key}] ${line}`)).slice(0, 15),
284
384
  backlogTicked: tickedOk,
385
+ // Only a writer that came back with a well-formed id has its spec claimed.
386
+ refactorSpec: spec ? `specs/${spec.id}.md` : null,
285
387
  next: !tickedOk
286
388
  ? `${clearedAll.length} item(s) were cleared in code but NOT ticked off specs/refactor-backlog.md ` +
287
389
  '(the ticking agent died) — tick them by hand, or the next /cohorte-refactor re-dispatches finished work'
288
- : results.some(r => r.remaining.length || !r.gatesGreen)
289
- ? 'items remain — finish them with the conversational /cohorte-refactor <domain>'
290
- : 'all dispatched domains clean — optionally close with one final /cohorte-audit',
390
+ : wantSpec && !spec
391
+ ? `the refactor spec was NOT written (the spec writer died) — the ${clearedAll.length} cleared item(s) have no ` +
392
+ 'route to a PR: write it per /cohorte-refactor §4, then /cohorte-review <id> → /cohorte-ship <id>'
393
+ : spec
394
+ ? `/cohorte-review ${spec.id} → /cohorte-ship ${spec.id}` +
395
+ (branchOk ? '' : ` — but the checked-out branch is ${spec.branch || 'unknown'}, not ${prefix}${spec.id}: /cohorte-ship refuses it, switch first`) +
396
+ (remainingAll.length ? ` (${remainingAll.length} item(s) still open, listed in its §7 — /cohorte-refactor <domain> appends them to this spec first, or ship without them)` : '')
397
+ : 'items remain — finish them with the conversational /cohorte-refactor <domain> (gates must be green before the round gets a spec)',
291
398
  }