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
@@ -0,0 +1,106 @@
1
+ ---
2
+ model: sonnet
3
+ description: Run the app between review and ship (migrations, dev server, smoke/e2e, screenshots) and tick only the runtime DoD items it has evidence for.
4
+ argument-hint: <feature_id>
5
+ ---
6
+
7
+ You are the **lead**. Verify feature **$ARGUMENTS** at runtime, which is the step that actually
8
+ runs the app. Rules: `<core>/pipeline/schema/verify.md`. Read it before §2's call if it is not in
9
+ your context already.
10
+
11
+ > **No kanban move.** The board has no verify column and the card stays in Review. This command
12
+ > calls no `kanban-move.sh` on purpose.
13
+ >
14
+ > **The script does the process work.** Everything below goes through
15
+ > `<core>/pipeline/scripts/verify-run.sh`:
16
+ > - Never start, probe or kill a server yourself, and never run a migration outside it.
17
+ > - Never touch git (no checkout, commit, push or merge).
18
+ > - Never point an `.env` at another database.
19
+ > - A server left behind is stopped with `verify-run.sh stop $ARGUMENTS`, not with `kill`.
20
+
21
+ ## 0. Configured?
22
+
23
+ Read `<state>/profile.json` (fall back to `PIPELINE.md`'s `yaml pipeline-profile` block). Verify
24
+ applies only when both hold:
25
+ - `verify.enabled` is not `false`;
26
+ - the profile has `commands.smoke`, `commands.e2e`, or `commands.dev` **with** `commands.dev_ready`,
27
+ or the spec has `migrations: true` and the profile has a `commands.migrate`.
28
+
29
+ Otherwise say "no runtime commands in the profile, so there is nothing to verify (and `/cohorte-ship`
30
+ will not ask)" and stop.
31
+
32
+ ## 1. Inputs
33
+
34
+ - `specs/$ARGUMENTS.md` must exist. `status: merged` or `abandoned` ⇒ stop (a merged feature is
35
+ undone with `/cohorte-revert`, not re-verified). Any other status is fine. Verify normally follows
36
+ a `SHIP` verdict, but nothing forbids an earlier run.
37
+ - From the front-matter, take `migrations` (absent means `false`) and `reviewed_base`.
38
+ - `reviewed_base` present ⇒ pass it as `--digest-base`; `/cohorte-ship` compares that digest
39
+ with `reviewed_digest`.
40
+ - Absent ⇒ omit `--digest-base`, and say that ship will treat this run as unanchored.
41
+ - Touched surfaces: `<core>/pipeline/scripts/feature-diff.sh --default <default_branch> --name-only`,
42
+ grouped by `surfaces[].path`. Only their `verify.surfaces.<key>` hints are used.
43
+ - **In a feature worktree** (`git rev-parse --git-dir` ≠ `--git-common-dir`) with
44
+ `isolation.enabled`, substitute the slot's ports into every URL, as described in
45
+ `<core>/pipeline/schema/verify.md` §Ports.
46
+
47
+ ## 2. One call
48
+
49
+ Build it from the profile and leave out each bracketed part whose input is `""` or absent. Run it
50
+ in one Bash call with the **timeout at 600000 ms**:
51
+
52
+ ```
53
+ <core>/pipeline/scripts/verify-run.sh run $ARGUMENTS --digest-base <reviewed_base> \
54
+ [--migrate "<commands.migrate>" [--migrate-down "<commands.migrate_down, else commands.rollback>"] \
55
+ --db <verify.db, default local> --db-per-worktree <isolation.db_per_worktree, default false> \
56
+ --slots <isolation.registry, default .worktrees/slots.tsv>] \
57
+ [--dev "<commands.dev>" --ready "<commands.dev_ready>"] \
58
+ [--check "smoke=<commands.smoke>"] [--check "smoke:<key>=<verify.surfaces.<key>.smoke>"]… \
59
+ [--check "e2e=<commands.e2e>"] \
60
+ [--screenshot "<key><path>=<base_url><path>"]… \
61
+ [--skip "rollback=no commands.migrate_down in the profile"] \
62
+ --ready-timeout <verify.ready_timeout_seconds, 90> --check-timeout <verify.check_timeout_seconds, 600>
63
+ ```
64
+
65
+ - The `--migrate…` group goes in **only** when the spec says `migrations: true`. Add `--skip
66
+ "rollback=…"` when it does but the profile has no down command.
67
+ - `--screenshot` is left out when `verify.screenshots: off`. Use one per `verify.surfaces.<key>.paths`
68
+ entry of a touched surface. The `base_url` defaults to `dev_ready`'s origin.
69
+ - `--dev` without `--ready` is a usage error by design.
70
+
71
+ Route on the exit code:
72
+ - **4**: the gate would ask. The script printed the commands and started nothing. Show the human
73
+ that list and ask once. On yes, re-run the identical call plus `--confirmed`. On no, stop.
74
+ - **2**: usage. Fix the call. Never improvise the steps by hand.
75
+ - **0 / 1 / 3** (PASS / FAIL / SKIPPED): read `specs/reports/$ARGUMENTS.verify.json`. Keep only
76
+ `verdict`, `reason` and each check's `name · status · note` in context. On a FAIL, `tail -40` the
77
+ failing check's `log` and nothing else.
78
+
79
+ ## 3. Tick the runtime DoD items it proved
80
+
81
+ Go through the spec's `## 9. Acceptance criteria / DoD`, handling only the `- [ ]` lines that carry
82
+ `· runtime`:
83
+ - A line with `· runtime: <check>` ⇒ tick it (`- [x]`) **only** if verify.json has at least one
84
+ check named `<check>` or `<check>:…`, and all of them are `PASS`. Leave everything else alone. A
85
+ `SKIPPED` check proves nothing.
86
+ - A bare `· runtime` is never ticked. It needs a human eye.
87
+ - Never tick an untagged line, never untick a line, and edit nothing else in the spec.
88
+
89
+ Append to `specs/reports/$ARGUMENTS.verify.md`, under `## DoD`, one line per runtime item:
90
+ - a ticked item: `- [x] <item> — evidence: <log path>`;
91
+ - an open item: `- [ ] <item> — needs a human eye (evidence: <screenshot paths, or none>)`.
92
+
93
+ ## 4. Report
94
+
95
+ One line for the verdict and one per check (`<name> · <status> · <note>`), then the items you
96
+ ticked. Then route:
97
+ - **PASS** ⇒ `/cohorte-ship $ARGUMENTS`. Name any bare `· runtime` items the human should look at
98
+ first, with their screenshot paths.
99
+ - **FAIL** ⇒ a runtime finding. Have the human run `/cohorte-fix $ARGUMENTS` with the failing
100
+ check's line and log path pasted. After the fix, `/cohorte-review` and then `/cohorte-verify`
101
+ again (the code changed, so both verdicts are stale). `/cohorte-ship` blocks until a newer run
102
+ passes.
103
+ - **SKIPPED** ⇒ say why (the `reason`, or the gate-denied checks). `/cohorte-ship` will ask the
104
+ human whether to ship unverified.
105
+
106
+ **Recommend a `/clear`.** The verdict, logs and ticks are all on disk.
@@ -5,6 +5,7 @@ Installed per project as `.claude/hooks/cohorte-gate.py` and registered in the p
5
5
  `.claude/settings.json` as a PreToolUse hook:
6
6
 
7
7
  python3 "$CLAUDE_PROJECT_DIR/.claude/hooks/cohorte-gate.py" matcher: Bash|Task|Agent
8
+ and: Write|Edit|MultiEdit
8
9
 
9
10
  It reads the PreToolUse payload on stdin and either stays silent (allow, exit 0) or prints
10
11
  one `hookSpecificOutput.permissionDecision` of "ask" or "deny" (exit 0). Stdlib only,
@@ -30,6 +31,14 @@ What it does, in order of authority:
30
31
  These are matched as tokens, not substrings (see "Matching").
31
32
  5. Preflight phase gate: a Task/Agent dispatch of a listed subagent needs a fresh
32
33
  `.claude/preflight.ok` stamp whose content digest equals the dispatch checkout's.
34
+ 6. Surface ownership: a subagent (payload `agent_id`) whose `agent_type` is a surface agent
35
+ of `.claude/profile.json` is denied a Write/Edit/MultiEdit/NotebookEdit outside its
36
+ `surfaces[].path` (+ its `owns_also`, + `ownership.shared_writable`) and any write to the
37
+ contract (`contract.path`/`contract.index`). Its Bash writes get the same check, best
38
+ effort, through the self-protection target analysis (redirections, cp/mv/rm, tee, sed -i,
39
+ …). The lead, the fixed cohorte-* agents and unknown agent types are not restricted; no
40
+ profile.json or `ownership.enforce: false` ⇒ inert. Only targets inside a project
41
+ checkout are judged.
33
42
 
34
43
  Matching. The command is lexed like a shell does it: quotes, escapes, `\\`-newline
35
44
  continuations, comments, heredocs (bodies are data unless fed to a shell), `$(…)`,
@@ -1174,6 +1183,192 @@ def resolve_roots(cwd):
1174
1183
  return roots, top
1175
1184
 
1176
1185
 
1186
+ # ── surface ownership ────────────────────────────────────────────────────────
1187
+ # A surface implementer (a subagent whose `agent_type` is a `surfaces[].agent` of the
1188
+ # project's `.claude/profile.json`) may only write under its own `surfaces[].path`, plus
1189
+ # its `owns_also` and the global `ownership.shared_writable` entries; the frozen contract
1190
+ # (`contract.path`, `contract.index`) is read-only to it. The lead (no `agent_id` in the
1191
+ # payload), the fixed cohorte-* agents and unknown agent types are never restricted.
1192
+ # Inert when profile.json is absent or unreadable, or `ownership.enforce` is false. Only
1193
+ # targets inside one of the project's checkouts are judged — /dev/null, $TMPDIR, a file
1194
+ # under ~ are not another surface's tree. Nothing here may raise for a malformed profile:
1195
+ # hook() turns an exception on a Bash payload into a deny for everyone, the lead included.
1196
+ OWNERSHIP_OFF = {"false", "no", "off", "0"}
1197
+ GLOB_CHARS = set("*?[")
1198
+
1199
+
1200
+ def _profile_str(v):
1201
+ """A usable profile string: not empty, not a `<placeholder>` left by the template."""
1202
+ if not isinstance(v, str):
1203
+ return None
1204
+ v = v.strip()
1205
+ return v if v and not v.startswith("<") else None
1206
+
1207
+
1208
+ def _profile_paths(v):
1209
+ if isinstance(v, str):
1210
+ v = [v]
1211
+ if not isinstance(v, list):
1212
+ return []
1213
+ out = []
1214
+ for e in v:
1215
+ e = _profile_str(e)
1216
+ if e:
1217
+ out.append(e)
1218
+ return out
1219
+
1220
+
1221
+ def _nearest_dir(p):
1222
+ d = os.path.dirname(p) if not os.path.isdir(p) else p
1223
+ while d and not os.path.isdir(d):
1224
+ parent = os.path.dirname(d)
1225
+ if parent == d:
1226
+ return None
1227
+ d = parent
1228
+ return d or None
1229
+
1230
+
1231
+ class Ownership(object):
1232
+ def __init__(self, ctx, agent, mine, surfaces, shared, contract):
1233
+ self.ctx = ctx
1234
+ self.agent = agent
1235
+ self.mine = mine # [(key, path, owns_also)]
1236
+ self.surfaces = surfaces # [(key, agent, path)] — every surface, for the message
1237
+ self.shared = shared
1238
+ self.contract = contract
1239
+ self._tops = {}
1240
+
1241
+ @classmethod
1242
+ def load(cls, ctx, payload):
1243
+ """The ownership rules for this payload's agent, or None (not a surface agent, no
1244
+ profile, enforcement off). Never raises."""
1245
+ try:
1246
+ aid, agent = payload.get("agent_id"), payload.get("agent_type")
1247
+ if not (isinstance(aid, str) and aid.strip() and isinstance(agent, str) and agent.strip()):
1248
+ return None
1249
+ prof = None
1250
+ for r in ctx.roots:
1251
+ p = os.path.join(r, ".claude", "profile.json")
1252
+ if os.path.isfile(p):
1253
+ try:
1254
+ with open(p, "r", encoding="utf-8") as fh:
1255
+ prof = json.load(fh)
1256
+ except Exception as e:
1257
+ warn("%s is unreadable (%s) — surface ownership is not enforced until "
1258
+ "`cohorte sync` rewrites it" % (p, e))
1259
+ return None
1260
+ break
1261
+ if not isinstance(prof, dict):
1262
+ return None
1263
+ own = prof.get("ownership")
1264
+ own = own if isinstance(own, dict) else {}
1265
+ enforce = own.get("enforce", True)
1266
+ if enforce is False or (isinstance(enforce, str) and enforce.strip().lower() in OWNERSHIP_OFF):
1267
+ return None
1268
+ surfaces, mine = [], []
1269
+ for s in prof.get("surfaces") if isinstance(prof.get("surfaces"), list) else []:
1270
+ if not isinstance(s, dict):
1271
+ continue
1272
+ key = _profile_str(s.get("key")) or "?"
1273
+ sagent = _profile_str(s.get("agent")) or _profile_str(s.get("key"))
1274
+ path = _profile_str(s.get("path"))
1275
+ if path:
1276
+ surfaces.append((key, sagent, path))
1277
+ if sagent == agent.strip():
1278
+ if not path:
1279
+ warn("surface `%s` has no usable `path` — its agent is not restricted" % key)
1280
+ return None
1281
+ mine.append((key, path, _profile_paths(s.get("owns_also"))))
1282
+ if not mine:
1283
+ return None
1284
+ contract = []
1285
+ c = prof.get("contract")
1286
+ if isinstance(c, dict) and c.get("enabled") is not False:
1287
+ contract = [x for x in (_profile_str(c.get("path")), _profile_str(c.get("index"))) if x]
1288
+ return cls(ctx, agent.strip(), mine, surfaces,
1289
+ _profile_paths(own.get("shared_writable")), contract)
1290
+ except Exception as e:
1291
+ warn("surface ownership skipped: %s: %s" % (type(e).__name__, e))
1292
+ return None
1293
+
1294
+ def _top_of(self, path):
1295
+ d = _nearest_dir(path)
1296
+ if not d:
1297
+ return None
1298
+ if d not in self._tops:
1299
+ top, main = git_top_and_common(d)
1300
+ roots = self.ctx.roots
1301
+ ok = top and (top in roots or (main and os.path.realpath(main) in roots))
1302
+ self._tops[d] = top if ok else None
1303
+ return self._tops[d]
1304
+
1305
+ def base_of(self, real):
1306
+ """The project checkout `real` lives in (its own linked worktree wins over a main
1307
+ checkout that contains it), or None when it is outside every one of them."""
1308
+ cands = list(self.ctx.roots)
1309
+ top = self._top_of(real)
1310
+ if top and top not in cands:
1311
+ cands.append(top)
1312
+ best = None
1313
+ for c in cands:
1314
+ if real == c or real.startswith(c.rstrip(os.sep) + os.sep):
1315
+ if best is None or len(c) > len(best):
1316
+ best = c
1317
+ return best
1318
+
1319
+ @staticmethod
1320
+ def within(rel, real, base, entry):
1321
+ if os.path.isabs(entry):
1322
+ e = os.path.realpath(entry)
1323
+ return real == e or real.startswith(e.rstrip(os.sep) + os.sep)
1324
+ e = entry.replace("\\", "/").strip()
1325
+ while e.startswith("./"):
1326
+ e = e[2:]
1327
+ e = e.rstrip("/") or "."
1328
+ if e == ".":
1329
+ return True
1330
+ if GLOB_CHARS & set(e):
1331
+ parts = rel.split("/")
1332
+ return any(fnmatch.fnmatchcase("/".join(parts[:k]), e) for k in range(1, len(parts) + 1))
1333
+ e = "/".join(x for x in e.split("/") if x not in ("", "."))
1334
+ if rel == e or rel.startswith(e + "/"):
1335
+ return True
1336
+ target = os.path.realpath(os.path.join(base, e)) # the entry is itself a symlink
1337
+ return real == target or real.startswith(target.rstrip(os.sep) + os.sep)
1338
+
1339
+ def judge(self, path):
1340
+ """None when the agent may write `path` (absolute), else the reason it may not."""
1341
+ real = os.path.realpath(os.path.normpath(path))
1342
+ base = self.base_of(real)
1343
+ if base is None:
1344
+ return None
1345
+ rel = os.path.relpath(real, base).replace(os.sep, "/")
1346
+ if rel == "." or rel.startswith("../"):
1347
+ return None
1348
+ for c in self.contract:
1349
+ if self.within(rel, real, base, c):
1350
+ return ("`%s` is the frozen contract (`contract.path` in PIPELINE.md), read-only for "
1351
+ "surface agents — the lead authors it. If the contract is wrong, stop and say "
1352
+ "so in your handoff instead of changing it" % rel)
1353
+ mine = []
1354
+ for key, spath, also in self.mine:
1355
+ mine.append(spath)
1356
+ if self.within(rel, real, base, spath) or any(self.within(rel, real, base, e) for e in also):
1357
+ return None
1358
+ if any(self.within(rel, real, base, e) for e in self.shared):
1359
+ return None
1360
+ owner = None
1361
+ for key, sagent, spath in self.surfaces:
1362
+ if self.within(rel, real, base, spath) and (owner is None or len(spath) > len(owner[2])):
1363
+ owner = (key, sagent, spath)
1364
+ whose = ("it belongs to surface `%s` (agent `%s`)" % (owner[0], owner[1])
1365
+ if owner else "no surface owns it (it is the lead's)")
1366
+ return ("surface ownership — agent `%s` may only write under `%s` (plus its `owns_also` and "
1367
+ "`ownership.shared_writable`), and `%s` is outside: %s. Don't edit another surface's "
1368
+ "tree — report what you need from it in your handoff and the lead routes it"
1369
+ % (self.agent, "`, `".join(mine), rel, whose))
1370
+
1371
+
1177
1372
  class Ctx(object):
1178
1373
  def __init__(self, cwd, mode):
1179
1374
  self.cwd0 = os.path.realpath(cwd) if cwd and os.path.isdir(cwd) else None
@@ -1225,6 +1420,7 @@ class Ctx(object):
1225
1420
  self._defaults = None
1226
1421
  self._branches = {}
1227
1422
  self._aliases = {}
1423
+ self.owner = None # Ownership, set by evaluate() for a surface agent
1228
1424
  self._build_protected()
1229
1425
 
1230
1426
  def _build_protected(self):
@@ -1237,7 +1433,9 @@ class Ctx(object):
1237
1433
  for r in self.roots:
1238
1434
  for rel in ((".claude", "gate-config.json"), (".claude", "preflight.ok"),
1239
1435
  (".claude", "settings.json"), (".claude", "settings.local.json"),
1240
- (".claude", "hooks", "cohorte-gate.py"), (".cohorte", "gate-config.json")):
1436
+ (".claude", "hooks", "cohorte-gate.py"), (".cohorte", "gate-config.json"),
1437
+ # profile.json drives ownership enforcement: as protected as the config.
1438
+ (".claude", "profile.json")):
1241
1439
  add(write, os.path.join(r, *rel))
1242
1440
  add(delete, os.path.join(r, ".claude", "pipeline.json"))
1243
1441
  home = os.path.expanduser("~")
@@ -1570,7 +1768,7 @@ PROTECTED_HINT_RE = re.compile(r"(^|/)\.claude(/|$)|gate-config\.json|preflight\
1570
1768
  r"settings(\.local)?\.json|cohorte-gate\.py|pipeline\.json|"
1571
1769
  r"(^|/)\.cohorte(/|$)")
1572
1770
  PROTECTED_NAME_RE = re.compile(r"gate-config\.json|preflight\.ok|\.claude/settings(\.local)?\.json|"
1573
- r"cohorte-gate\.py")
1771
+ r"cohorte-gate\.py|\.claude/profile\.json")
1574
1772
  SPAWN_RE = {
1575
1773
  "py": re.compile(r"\bos\.(system|popen|exec\w*|spawn\w*)|\bsubprocess\b|\bpty\.spawn|"
1576
1774
  r"\bcommands\.getoutput|\bpexpect\b|\bsh\.\w+\("),
@@ -1580,7 +1778,7 @@ SPAWN_RE = {
1580
1778
  r"\bshell_exec\b|\bpassthru\b|\bproc_open\b"),
1581
1779
  }
1582
1780
  STRING_LIT_RE = re.compile(r"'((?:[^'\\]|\\.)*)'|\"((?:[^\"\\]|\\.)*)\"")
1583
- PROTECTED_BASENAMES = {"gate-config.json", "preflight.ok", "settings.json", "settings.local.json",
1781
+ PROTECTED_BASENAMES = {"gate-config.json", "preflight.ok", "settings.json", "settings.local.json", "profile.json",
1584
1782
  "cohorte-gate.py", "pipeline.json", ".claude", ".cohorte", "hooks", "~", "",
1585
1783
  ".", ".."}
1586
1784
 
@@ -2038,6 +2236,9 @@ class Analyzer(object):
2038
2236
  if name == "preflight.sh":
2039
2237
  self.preflight_args(args, state, depth)
2040
2238
  return
2239
+ if name == "verify-run.sh":
2240
+ self.verify_args(args, state, depth)
2241
+ return
2041
2242
  if name == "eval":
2042
2243
  text = " ".join(a.value for a in args)
2043
2244
  if any(a.dynamic for a in args):
@@ -2187,6 +2388,8 @@ class Analyzer(object):
2187
2388
  return
2188
2389
  if cmd_name(script.value) == "preflight.sh":
2189
2390
  self.preflight_args(sargs, state, depth)
2391
+ elif cmd_name(script.value) == "verify-run.sh":
2392
+ self.verify_args(sargs, state, depth)
2190
2393
 
2191
2394
  def preflight_args(self, args, state, depth):
2192
2395
  """preflight.sh <report> "<cmd>"…: it truncates <report>, and runs each cmd via sh -c."""
@@ -2199,6 +2402,31 @@ class Analyzer(object):
2199
2402
  else:
2200
2403
  self.analyze_text(a.value, state.copy(), depth + 1)
2201
2404
 
2405
+ # verify-run.sh run <id> --dev "<cmd>" --check "<name>=<cmd>" --migrate "<cmd>" …: every
2406
+ # command it is handed runs through a shell, so judge each one here — the script also asks
2407
+ # the gate itself, but its `--confirmed` flag is the lead's word, and a DENIED command must
2408
+ # stay denied whatever the flag says.
2409
+ VERIFY_CMD_FLAGS = {"--dev": False, "--ready": False, "--migrate": False,
2410
+ "--migrate-down": False, "--check": True}
2411
+
2412
+ def verify_args(self, args, state, depth):
2413
+ k = 0
2414
+ while k < len(args):
2415
+ flag = args[k].value
2416
+ if flag in self.VERIFY_CMD_FLAGS and k + 1 < len(args):
2417
+ a = args[k + 1]
2418
+ if a.dynamic:
2419
+ self.opaque("verify-run.sh runs a command built at run time", a.raw)
2420
+ else:
2421
+ cmd = a.value
2422
+ if self.VERIFY_CMD_FLAGS[flag] and "=" in cmd:
2423
+ cmd = cmd.split("=", 1)[1] # --check "<name>=<cmd>"
2424
+ if not (flag == "--ready" and re.match(r"^https?://", cmd.strip())):
2425
+ self.analyze_text(cmd, state.copy(), depth + 1)
2426
+ k += 2
2427
+ continue
2428
+ k += 1
2429
+
2202
2430
  def interp_code(self, name, args):
2203
2431
  lang = lang_of(name)
2204
2432
  k = 0
@@ -2313,21 +2541,29 @@ class Analyzer(object):
2313
2541
  if not w.dynamic:
2314
2542
  state.written.add(self.path_key(w, state))
2315
2543
 
2544
+ def known_text(self, w, state):
2545
+ """A run-time word with only the variables the gate can resolve itself
2546
+ ($CLAUDE_PROJECT_DIR, $HOME, $PWD) substituted, or None if anything else is left."""
2547
+ t = w.raw
2548
+ if len(t) >= 2 and t[0] == t[-1] == '"':
2549
+ t = t[1:-1]
2550
+ for var, val in (("CLAUDE_PROJECT_DIR", os.environ.get("CLAUDE_PROJECT_DIR")),
2551
+ ("HOME", os.path.expanduser("~")),
2552
+ ("PWD", state.cwd if state.cwd_known else None)):
2553
+ if val:
2554
+ # Forward slashes: a Windows value (C:\\Users\\…) would otherwise read as
2555
+ # shell escapes below and every expanded path would look suspect.
2556
+ val = val.replace("\\", "/")
2557
+ t = t.replace("${%s}" % var, val).replace("$" + var, val)
2558
+ if "$" in t or "`" in t or "'" in t or '"' in t or "\\" in t:
2559
+ return None
2560
+ return t
2561
+
2316
2562
  def classify_path(self, w, state, mode, relocated=False):
2317
2563
  ctx = self.ctx
2318
2564
  if w.dynamic:
2319
- t = w.raw
2320
- if len(t) >= 2 and t[0] == t[-1] == '"':
2321
- t = t[1:-1]
2322
- for var, val in (("CLAUDE_PROJECT_DIR", os.environ.get("CLAUDE_PROJECT_DIR")),
2323
- ("HOME", os.path.expanduser("~")),
2324
- ("PWD", state.cwd if state.cwd_known else None)):
2325
- if val:
2326
- # Forward slashes: a Windows value (C:\\Users\\…) would otherwise read as
2327
- # shell escapes below and every expanded path would look suspect.
2328
- val = val.replace("\\", "/")
2329
- t = t.replace("${%s}" % var, val).replace("$" + var, val)
2330
- if "$" in t or "`" in t or "'" in t or '"' in t or "\\" in t:
2565
+ t = self.known_text(w, state)
2566
+ if t is None:
2331
2567
  return "suspect" if suspicious(w.value.split(DYN)[-1], w.raw) else None
2332
2568
  w = static_word(t)
2333
2569
  v = os.path.expanduser(w.value)
@@ -2357,7 +2593,33 @@ class Analyzer(object):
2357
2593
  return "protected" if mode == "delete" else "suspect"
2358
2594
  return None
2359
2595
 
2360
- def check_path(self, w, state, mode, via, relocated=False):
2596
+ def check_owner(self, w, state, mode, via, relocated=False, existing=False):
2597
+ """Surface ownership for a Bash write — best effort: a target the gate can't resolve
2598
+ statically (a run-time word, a relative path after an unresolvable `cd`) is let
2599
+ through, never asked about (an ask is a deny in unattended runs)."""
2600
+ try:
2601
+ t = self.known_text(w, state) if w.dynamic else w.value
2602
+ if not t:
2603
+ return
2604
+ v = os.path.expanduser(t)
2605
+ if not os.path.isabs(v):
2606
+ if relocated or not state.cwd_known:
2607
+ return
2608
+ v = os.path.join(state.cwd, v)
2609
+ if existing and not os.path.exists(v):
2610
+ return
2611
+ why = self.ctx.owner.judge(v)
2612
+ except Exception as e:
2613
+ warn("surface ownership could not judge `%s`: %s: %s" % (w.raw, type(e).__name__, e))
2614
+ return
2615
+ if why:
2616
+ verb = {"write": "write", "delete": "delete or move", "recursive": "write into",
2617
+ "chmod": "change the permissions of"}.get(mode, "write")
2618
+ self.deny("%s would %s `%s`: %s" % (via, verb, w.raw, why))
2619
+
2620
+ def check_path(self, w, state, mode, via, relocated=False, existing=False):
2621
+ if self.ctx.owner is not None:
2622
+ self.check_owner(w, state, mode, via, relocated, existing)
2361
2623
  kind = self.classify_path(w, state, mode, relocated)
2362
2624
  if kind is None:
2363
2625
  return
@@ -2440,8 +2702,11 @@ class Analyzer(object):
2440
2702
  and "i" in w.value[1:].split(".")[0]))
2441
2703
  for w in args)
2442
2704
  if inplace:
2705
+ # Only existing files can be edited in place, so for ownership a positional
2706
+ # that names nothing on disk is the sed script (`sed -i 's/a/b/' f`) or a BSD
2707
+ # backup suffix (`sed -i .bak …`), not a target.
2443
2708
  for p in positionals(args, ("-e", "-f")):
2444
- self.check_path(p, state, "write", "`%s -i`" % name, relocated)
2709
+ self.check_path(p, state, "write", "`%s -i`" % name, relocated, existing=True)
2445
2710
  elif name == "dd":
2446
2711
  for w in args:
2447
2712
  if w.value.startswith("of="):
@@ -2725,6 +2990,43 @@ def default_cwd():
2725
2990
  return None
2726
2991
 
2727
2992
 
2993
+ def edit_targets(ti):
2994
+ """Every path a Write/Edit/MultiEdit/NotebookEdit call names. Only Write and Edit have a
2995
+ documented schema (`file_path`); `notebook_path` and per-edit `file_path`s are read
2996
+ defensively."""
2997
+ out = []
2998
+ for k in ("file_path", "notebook_path"):
2999
+ v = ti.get(k)
3000
+ if isinstance(v, str) and v and v not in out:
3001
+ out.append(v)
3002
+ edits = ti.get("edits")
3003
+ if isinstance(edits, list):
3004
+ for e in edits:
3005
+ v = e.get("file_path") if isinstance(e, dict) else None
3006
+ if isinstance(v, str) and v and v not in out:
3007
+ out.append(v)
3008
+ return out
3009
+
3010
+
3011
+ def edit_ownership(ctx, tool, targets):
3012
+ """Surface ownership for an edit tool: a deny, or None. Fails closed — the caller is a
3013
+ known surface agent, so a target the gate can't find or judge is refused."""
3014
+ if not targets:
3015
+ return ("deny", "`%s` by surface agent `%s` names no file path the gate can check "
3016
+ "(surface ownership) — refused" % (tool, ctx.owner.agent))
3017
+ for fp in targets:
3018
+ try:
3019
+ p = os.path.expanduser(fp)
3020
+ if not os.path.isabs(p):
3021
+ p = os.path.join(ctx.cwd0 or os.getcwd(), p)
3022
+ why = ctx.owner.judge(p)
3023
+ except Exception as e:
3024
+ why = "surface ownership could not be checked (%s: %s) — refused" % (type(e).__name__, e)
3025
+ if why:
3026
+ return ("deny", "`%s` of `%s` refused: %s" % (tool, fp, why))
3027
+ return None
3028
+
3029
+
2728
3030
  def evaluate(payload):
2729
3031
  """The decision for one PreToolUse payload: None (allow) or (decision, reason)."""
2730
3032
  tool = payload.get("tool_name")
@@ -2745,6 +3047,8 @@ def evaluate(payload):
2745
3047
  if not isinstance(ti, dict):
2746
3048
  raise PayloadError("tool_input is not an object")
2747
3049
  decision = None
3050
+ if tool == "Bash" or tool in EDIT_TOOLS:
3051
+ ctx.owner = Ownership.load(ctx, payload)
2748
3052
  if tool == "Bash":
2749
3053
  cmd = ti.get("command")
2750
3054
  if not isinstance(cmd, str):
@@ -2759,15 +3063,16 @@ def evaluate(payload):
2759
3063
  elif tool in DISPATCH_TOOLS:
2760
3064
  decision = Dispatch(ctx).evaluate(ti, ctx.cwd0)
2761
3065
  else:
2762
- fp = ti.get("file_path")
2763
- if fp is None:
2764
- fp = ti.get("notebook_path")
2765
- if isinstance(fp, str) and fp:
3066
+ targets = edit_targets(ti)
3067
+ if ctx.owner is not None:
3068
+ decision = edit_ownership(ctx, tool, targets)
3069
+ for fp in targets if decision is None else ():
2766
3070
  p = fp if os.path.isabs(fp) else os.path.join(ctx.cwd0 or ".", fp)
2767
3071
  p = os.path.expanduser(p)
2768
3072
  if os.path.normpath(p) in ctx.protected or os.path.realpath(p) in ctx.protected:
2769
3073
  decision = ("ask", "`%s` edits `%s`, a file the Cohorte gate depends on "
2770
3074
  "(self-protection) — confirm this change is intended" % (tool, fp))
3075
+ break
2771
3076
  if decision is None:
2772
3077
  return None
2773
3078
  level, reason = decision
@@ -2,10 +2,11 @@
2
2
  feature_id: patch-<slug>
3
3
  kind: patch # a bug fix, not a feature — /cohorte-build skips contract authoring, /cohorte-ship commits `fix(…)`
4
4
  title: <one line: the bug, from the user's side>
5
- status: draft # draft → frozen → in-progress → in-review → shipped → merged · blocked · abandoned (see SCHEMA.md §Spec status)
5
+ status: draft # draft → frozen → in-progress → in-review → shipped → merged · blocked · abandoned (see `<core>/pipeline/schema/spec-status.md`)
6
6
  severity: <critical | major | minor> # drives nothing mechanical; it is what the human triages on
7
7
  branch: <patch_branch_prefix><feature_id>
8
8
  created: <YYYY-MM-DD>
9
+ migrations: false # true only if the fix ships a migration — then ## Rollback is mandatory
9
10
  reviewed_base: # merge-base sha at the last SHIP verdict — freshness-gate anchor (written by /cohorte-review)
10
11
  reviewed_digest: # sha256 (16 hex) of the reviewed source diff vs reviewed_base, specs excluded — /cohorte-ship re-checks
11
12
  design_files: [] # omit unless the fix is itself visual
@@ -77,9 +78,17 @@ design_files: [] # omit unless the fix is itself visual
77
78
  - [ ] The §4 regression test exists, and failed before the fix
78
79
  - [ ] Each touched surface's tests (TDD) green
79
80
  - [ ] `PIPELINE.md` commands.lint · typecheck · test green
80
- - [ ] The repro in §1 no longer reproduces
81
+ - [ ] The repro in §1 no longer reproduces · runtime
81
82
  - [ ] Nothing outside §6's surfaces changed
82
83
 
84
+ ## Rollback
85
+
86
+ > Only if `migrations: true` (then mandatory — `/cohorte-ship` refuses stubs); delete otherwise.
87
+
88
+ - **Revert:** …
89
+ - **Data:** …
90
+ - **Migration down:** …
91
+
83
92
  ## Remediation
84
93
 
85
94
  > Filled by `/cohorte-fix` from a REVIEW REPORT; empty otherwise. Each item:
@@ -1,9 +1,10 @@
1
1
  ---
2
2
  feature_id: <slug>
3
3
  title: <Feature title>
4
- status: draft # draft → frozen → in-progress → in-review → shipped → merged · blocked · abandoned (see SCHEMA.md §Spec status)
4
+ status: draft # draft → frozen → in-progress → in-review → shipped → merged · blocked · abandoned (see `<core>/pipeline/schema/spec-status.md`)
5
5
  branch: <feature_branch_prefix><slug>
6
6
  created: <YYYY-MM-DD>
7
+ migrations: false # true when §4 adds/changes a migration — ## Rollback becomes mandatory, /cohorte-verify runs it on the dev DB (`<core>/pipeline/schema/verify.md`)
7
8
  reviewed_base: # merge-base sha at the last SHIP verdict — freshness-gate anchor (written by /cohorte-review)
8
9
  reviewed_digest: # sha256 (16 hex) of the reviewed source diff vs reviewed_base, specs excluded — /cohorte-ship re-checks
9
10
  design_files: [] # design page links — full URLs of the form https://claude.ai/design/p/<projectId>?file=<file> (each carries its own project + page); blank until designed; omit if no UI
@@ -72,16 +73,36 @@ design_files: [] # design page links — full URLs of the form https://claude.ai
72
73
 
73
74
  ## 9. Acceptance criteria / DoD
74
75
 
76
+ > Defaults follow `PIPELINE.md` `project.kind` (absent ⇒ `web`). `web` ⇒ keep the five lines below
77
+ > as they are. Any other kind ⇒ read only its `## <kind>` section of
78
+ > `<core>/pipeline/schema/project-kinds.md` and apply its **DoD** line: add the lines it lists, drop
79
+ > the ones it drops (mobile-first outside `web`/`mobile`). Then add this feature's own criteria.
80
+
75
81
  - [ ] Every contract endpoint/interface implemented exactly
76
82
  - [ ] Each surface's tests (TDD) green
77
83
  - [ ] `PIPELINE.md` commands.lint · typecheck · test green
78
- - [ ] Mobile-first / responsive verified (if UI)
84
+ - [ ] The app starts and the feature's main flow works · runtime: e2e
85
+ - [ ] Migrations apply and roll back on the dev DB (if `migrations: true`) · runtime: rollback
86
+ - [ ] Mobile-first / responsive verified (if UI) · runtime
79
87
  - [ ] User-facing copy in `ui_language`
80
88
 
89
+ > `· runtime: <check>` marks an item only a running app can prove: `/cohorte-verify` ticks it when its
90
+ > check (`smoke`, `e2e`, `rollback`, `smoke:<surface>`…) passed. A bare `· runtime` needs a human eye.
91
+
81
92
  ## 10. Assumptions & open questions
82
93
 
83
94
  - …
84
95
 
96
+ ## Rollback
97
+
98
+ > Mandatory when `migrations: true` (`/cohorte-ship` refuses the spec while this holds only stubs);
99
+ > otherwise optional. `/cohorte-revert` follows it, and its PR body carries it to whoever rolls back
100
+ > production. Each line concrete — a command, a table, a flag.
101
+
102
+ - **Revert:** … <!-- what goes back: the merge commit, a feature flag to flip first, a config to restore -->
103
+ - **Data:** … <!-- what is lost or irreversible: rows written since, a dropped column's values, backfills -->
104
+ - **Migration down:** … <!-- the exact step on the dev DB, e.g. `commands.migrate_down`; order vs. the code revert -->
105
+
85
106
  ## Remediation
86
107
 
87
108
  > Filled by `/cohorte-fix` (or `/cohorte-spec` Mode B) from a REVIEW REPORT; empty otherwise. Each item: