Skip to content

Business operating system for Claude Code — 57 skills, 21 agents, smart daemon. Unified inbox (WhatsApp/Email/Slack/Telegram), autonomous PR merge, full-AWS monitoring, revenue (Stripe+RevenueCat), e-commerce (Shopify), marketing (Klaviyo/Meta/GA4), voice (Bland/ElevenLabs), APM (Datadog/NewRelic/OTEL), YOLO mode.

chore: add Cursor Approval Agent policy files

auroracapitala44ece120c94
diff --git a/.cursor/approval-policies/ROUTING.md b/.cursor/approval-policies/ROUTING.md
new file mode 100644
index 00000000..87d16c4b
--- /dev/null
+++ b/.cursor/approval-policies/ROUTING.md
@@ -0,0 +1,39 @@
+- product: Documentation
+ boundary: "{claude-ops/docs/**,docs/**,**/README.md,**/CHANGELOG.md}"
+ policies:
+ - .cursor/approval-policies/docs-policy.md
+
+- product: Skills and prompts
+ boundary: "claude-ops/skills/**"
+ policies:
+ - .cursor/approval-policies/skills-policy.md
+
+- product: Safety hooks and automation hooks
+ boundary: "{claude-ops/hooks/**,hooks/**,.cursor/hooks/**}"
+ policies:
+ - .cursor/approval-policies/hooks-policy.md
+
+- product: CI and release workflows
+ boundary: ".github/workflows/**"
+ policies:
+ - .cursor/approval-policies/ci-policy.md
+
+- product: MCP servers and integrations
+ boundary: "claude-ops/mcp-servers/**"
+ policies:
+ - .cursor/approval-policies/mcp-policy.md
+
+- product: Daemons launchd and background services
+ boundary: "{claude-ops/launchd/**,claude-ops/scripts/**}"
+ policies:
+ - .cursor/approval-policies/daemon-policy.md
+
+- product: Plugin core runtime
+ boundary: "{claude-ops/bin/**,claude-ops/lib/**,claude-ops/agents/**,claude-ops/config/**}"
+ policies:
+ - .cursor/approval-policies/runtime-policy.md
+
+- product: Tests
+ boundary: "{claude-ops/tests/**,**/test/**,**/*.test.*,**/*.spec.*}"
+ policies:
+ - .cursor/approval-policies/tests-policy.md
diff --git a/.cursor/approval-policies/ci-policy.md b/.cursor/approval-policies/ci-policy.md
new file mode 100644
index 00000000..397d9275
--- /dev/null
+++ b/.cursor/approval-policies/ci-policy.md
@@ -0,0 +1,21 @@
+# CI and release workflow approval policy
+
+## Default posture
+
+**Never auto-approve** workflow changes.
+
+## Human review must verify
+
+- Required checks are not removed or made optional without replacement
+- Deploy and release workflows retain health/version verification steps where present today
+- No broadened `permissions:` blocks (especially `contents: write`, `id-token`, or org-wide secrets)
+- Concurrency/cancel-in-progress behavior is preserved or improved
+- Release tagging and marketplace publish steps remain gated
+
+## Auto-approve exception (rare)
+
+- Comment-only or whitespace changes inside workflow files with zero semantic diff — only if Bugbot confirms no functional change
+
+## Reviewer routing
+
+- Request platform maintainers for all non-comment workflow edits
diff --git a/.cursor/approval-policies/daemon-policy.md b/.cursor/approval-policies/daemon-policy.md
new file mode 100644
index 00000000..49a16e49
--- /dev/null
+++ b/.cursor/approval-policies/daemon-policy.md
@@ -0,0 +1,18 @@
+# Daemon and launchd approval policy
+
+## Default posture
+
+**Never auto-approve** changes to background services, launchd plists, or scripts that install/start/stop daemons.
+
+## Human review must verify
+
+- Daemons remain single-instance where required (orchestrator, rotator, briefing pre-warm)
+- No new always-on network listeners without documented purpose
+- Cron/interval changes will not cause cost leaks or API hammering
+- Log rotation and failure backoff behavior is preserved
+- Doppler/secret fallback behavior is fail-safe, not fail-open
+
+## Reviewer routing
+
+- Request platform maintainers
+- Flag PRs that touch rotator or CRS-related scripts for extra scrutiny
diff --git a/.cursor/approval-policies/docs-policy.md b/.cursor/approval-policies/docs-policy.md
new file mode 100644
index 00000000..04b4d83c
--- /dev/null
+++ b/.cursor/approval-policies/docs-policy.md
@@ -0,0 +1,17 @@
+# Documentation approval policy
+
+## Auto-approve when
+
+- Changes are limited to markdown, comments, or generated reference docs
+- No executable code, hook config, workflow YAML, or secret placeholders are modified
+- Bugbot and Security Agent report no findings
+
+## Never auto-approve
+
+- Docs that embed credentials, tokens, or live infrastructure endpoints not already public
+- Docs changes bundled with runtime logic changes in the same PR (evaluate under the stricter runtime policy)
+
+## Reviewer routing
+
+- Docs-only PRs: no specialist reviewer required
+- Docs + code: route to maintainers for the non-doc paths
diff --git a/.cursor/approval-policies/hooks-policy.md b/.cursor/approval-policies/hooks-policy.md
new file mode 100644
index 00000000..30a227fa
--- /dev/null
+++ b/.cursor/approval-policies/hooks-policy.md
@@ -0,0 +1,21 @@
+# Safety hooks approval policy
+
+## Default posture
+
+**Never auto-approve.** All hook changes require human review.
+
+## Rationale
+
+Hooks enforce secret scanning, destructive command blocks, main-branch push warnings, deploy monitoring, and agent routing. Regressions here affect every Claude Code session using this plugin.
+
+## Approve only after human review confirms
+
+- No weakening of existing PreToolUse or PostToolUse guards
+- Secret-scan patterns remain at least as strict as base branch
+- rm-rf / main-push / credential-commit protections are intact
+- New hooks fail closed (deny or warn) rather than silently no-op on error
+
+## Reviewer routing
+
+- Always request `@Lifecycle-Innovations-Limited/platform` or equivalent repo maintainers
+- If Security Agent reports any finding: block approval until resolved or explicitly waived by a maintainer comment
diff --git a/.cursor/approval-policies/mcp-policy.md b/.cursor/approval-policies/mcp-policy.md
new file mode 100644
index 00000000..7a86d0e5
--- /dev/null
+++ b/.cursor/approval-policies/mcp-policy.md
@@ -0,0 +1,23 @@
+# MCP servers approval policy
+
+## Default posture
+
+Treat all MCP server changes as **medium–high risk**. Do not auto-approve unless every condition below is met.
+
+## Auto-approve when ALL are true
+
+- Change is test-only or documentation inside `claude-ops/mcp-servers/**`
+- OR narrow bugfix with no new tools, scopes, network hosts, or filesystem paths
+- Bugbot and Security Agent report no findings
+- No secrets, tokens, or PII handling logic added or relaxed
+
+## Never auto-approve
+
+- New MCP tools or expanded tool permissions
+- New outbound network destinations or SSRF-prone URL fetch patterns
+- Authentication or token passthrough changes
+- Dependency upgrades that alter MCP SDK major versions without maintainer sign-off
+
+## Reviewer routing
+
+- Request platform maintainers for any runtime MCP server change
diff --git a/.cursor/approval-policies/runtime-policy.md b/.cursor/approval-policies/runtime-policy.md
new file mode 100644
index 00000000..4e30863c
--- /dev/null
+++ b/.cursor/approval-policies/runtime-policy.md
@@ -0,0 +1,24 @@
+# Plugin runtime approval policy
+
+Applies to `claude-ops/bin/**`, `claude-ops/lib/**`, `claude-ops/agents/**`, and `claude-ops/config/**`.
+
+## Auto-approve when ALL are true
+
+- Small, localized fix with clear test or script coverage
+- No changes to deploy-fix registry, post-merge hooks, or specialist routing keywords
+- Bugbot and Security Agent report no findings
+- CI green including `claude-ops/tests/**` where applicable
+- Risk score ≤ configured threshold
+
+## Never auto-approve
+
+- Changes to `config/specialist-keywords*.json` that broaden autonomous write scope
+- Agent persona changes that remove safety constraints or encourage bypassing hooks
+- Binaries/scripts that add destructive defaults or silent force flags
+- Plugin manifest changes (`.claude-plugin/**`) bundled without explicit manifest review
+
+## Reviewer routing
+
+- Auto-fix / deploy subsystem changes → platform maintainers
+- Agent roster changes → platform maintainers
+- Config-only tuning with tests → any maintainer acceptable if CI green
diff --git a/.cursor/approval-policies/skills-policy.md b/.cursor/approval-policies/skills-policy.md
new file mode 100644
index 00000000..06a8d0bd
--- /dev/null
+++ b/.cursor/approval-policies/skills-policy.md
@@ -0,0 +1,18 @@
+# Skills approval policy
+
+## Auto-approve when
+
+- Copy, examples, or routing table updates only
+- No new shell commands that bypass safety hooks or write outside the workspace
+- Bugbot and Security Agent report no findings
+- Risk score ≤ configured threshold
+
+## Never auto-approve
+
+- Skills that instruct agents to disable hooks, skip tests, or force-push to protected branches
+- New skills that invoke credential stores, payment APIs, or production deploy commands without existing precedent in repo
+- Changes to `/ops:setup`, `/ops:deploy-fix`, or rotation skills that alter default safety posture
+
+## Reviewer routing
+
+- Request platform maintainers when skill behavior changes operational guardrails
diff --git a/.cursor/approval-policies/tests-policy.md b/.cursor/approval-policies/tests-policy.md
new file mode 100644
index 00000000..2bb26ac8
--- /dev/null
+++ b/.cursor/approval-policies/tests-policy.md
@@ -0,0 +1,18 @@
+# Tests approval policy
+
+## Auto-approve when
+
+- Changes are limited to test files and test fixtures
+- Production runtime code is unchanged OR changes are clearly test harness only
+- Bugbot and Security Agent report no findings
+- CI is green
+
+## Never auto-approve
+
+- Tests that disable assertions, skip cases, or mock away security-critical behavior without justification
+- Tests removed alongside production logic changes in the same PR
+
+## Reviewer routing
+
+- Test-only PRs: no specialist required when CI green
+- Tests + production code: follow the policy for the production paths changed
diff --git a/APPROVAL_POLICY.md b/APPROVAL_POLICY.md
new file mode 100644
index 00000000..3aaee36c
--- /dev/null
+++ b/APPROVAL_POLICY.md
@@ -0,0 +1,60 @@
+# claude-ops — default approval policy
+
+Repository-wide rules for Cursor Approval Agents evaluating pull requests in this repo.
+
+## Purpose
+
+claude-ops is a business operating system plugin for Claude Code. Changes can affect safety hooks, deploy automation, credential handling, and fleet orchestration. Default posture: **approve only when risk is low and automated review is clean**.
+
+## Auto-approve when ALL are true
+
+- PR is small and scoped (generally ≤ 300 changed lines, excluding lockfiles and generated docs)
+- Bugbot Review Context reports no findings requiring human review
+- Security Review Context reports no findings requiring human review (when enabled)
+- Risk score is at or below the agent's configured maximum threshold
+- CI checks required for the changed paths are green
+- No changes under high-risk paths (see below) unless a more specific subtree policy explicitly allows it
+- PR does not modify approval policy files, routing files, or safety-hook bypass logic
+
+## Safe auto-approve examples
+
+- Documentation-only edits under `claude-ops/docs/**`, `docs/**`, or `README.md`
+- Test-only changes that do not alter production hook or deploy behavior
+- Changelog, version bump, or badge updates with no runtime logic changes
+- Typo or copy fixes in skills where behavior is unchanged
+
+## Never auto-approve
+
+- Any change to `hooks/**`, `claude-ops/hooks/**`, or safety-hook configuration
+- Credential, secret, rotation, or auth flows (`**/credentials/**`, `**/rotate/**`, Doppler/1Password wiring)
+- MCP server implementations (`claude-ops/mcp-servers/**`) that add network calls, file access, or new tool surfaces
+- Launchd/daemon lifecycle changes (`claude-ops/launchd/**`, `claude-ops/scripts/**` that start/stop daemons)
+- GitHub Actions workflow changes (`.github/workflows/**`) that weaken CI, skip tests, or broaden deploy permissions
+- Deletions or relaxations of guardrails (rm-rf blocks, secret-scan hooks, main-branch push warnings)
+- Changes that remove tests, disable lint/typecheck, or bypass pre-commit hooks
+- PRs labeled `security`, `breaking`, or `do-not-auto-approve`
+
+## Reviewer routing
+
+When auto-approval is not allowed, request reviewers based on changed area:
+
+| Changed area | Reviewers |
+|--------------|-----------|
+| Hooks / safety / deploy auto-fix | `@Lifecycle-Innovations-Limited/platform` or repo maintainers |
+| MCP servers / external integrations | `@Lifecycle-Innovations-Limited/platform` |
+| Plugin manifest / marketplace metadata | `@Lifecycle-Innovations-Limited/platform` |
+| Docs-only | Any maintainer; no specialist required |
+
+If reviewer assignment is unavailable, leave the PR unapproved and add a comment summarizing why human review is required.
+
+## Deploy expectations
+
+For changes that ship through dev → staging → main:
+
+- Do not auto-approve solely because CI passed on the PR branch
+- Require evidence that deploy-fix and health-check paths remain intact when touching deploy-related code
+- Treat production-impacting script changes as **medium risk minimum**
+
+## Conflict resolution
+
+If this file conflicts with a closer `APPROVAL_POLICY.md` or a routed policy in `.cursor/approval-policies/`, follow the **more specific** policy. If specificity is unclear, follow the **stricter** rule and do not auto-approve.
diff --git a/scripts/batch-ship-approval-policies.py b/scripts/batch-ship-approval-policies.py
new file mode 100644
index 00000000..3ba4be74
--- /dev/null
+++ b/scripts/batch-ship-approval-policies.py
@@ -0,0 +1,267 @@
+#!/usr/bin/env python3
+"""Commit, PR, and merge approval policy files across portfolio repos."""
+
+from __future__ import annotations
+
+import re
+import subprocess
+import sys
+from dataclasses import dataclass, field
+from pathlib import Path
+
+PROJECTS_ROOT = Path("/Users/<user>/Projects")
+BRANCH = "chore/approval-agent-policies"
+COMMIT_MSG = """chore: add Cursor Approval Agent policy files
+
+Scaffold APPROVAL_POLICY.md and .cursor/approval-policies/ routing
+for Cloud Approval Agents. Force-add routing under .cursor despite
+gitignore so Approval Agents can discover ROUTING.md."""
+
+PREFER_NAMES = {
+ "claude-ops": 100,
+ "healify-api": 90,
+ "healify-web": 90,
+ "healify-agentcore": 90,
+ "healify": 90,
+}
+
+
+@dataclass
+class Result:
+ ok: list[str] = field(default_factory=list)
+ skip: list[str] = field(default_factory=list)
+ fail: list[tuple[str, str]] = field(default_factory=list)
+
+
+def run(cmd: list[str], cwd: Path, check: bool = False) -> subprocess.CompletedProcess[str]:
+ return subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, check=check)
+
+
+def discover_repos() -> list[Path]:
+ repos = {p.parent for p in PROJECTS_ROOT.rglob(".git") if p.is_dir() and p.name == ".git"}
+ return sorted(repos)
+
+
+def repo_score(repo: Path) -> int:
+ name = repo.name
+ score = PREFER_NAMES.get(name, 0)
+ path = str(repo)
+ if "backup" in path or "_repo-groups" in path or ".agents/" in path:
+ score -= 50
+ if "_shelved" in path:
+ score -= 10
+ if str(repo.parent) == str(PROJECTS_ROOT):
+ score += 20
+ return score
+
+
+def pick_canonical_repos(repos: list[Path]) -> list[Path]:
+ by_remote: dict[str, Path] = {}
+ for repo in repos:
+ r = run(["git", "remote", "get-url", "origin"], repo)
+ if r.returncode != 0:
+ continue
+ remote = r.stdout.strip()
+ current = by_remote.get(remote)
+ if current is None or repo_score(repo) > repo_score(current):
+ by_remote[remote] = repo
+ return sorted(by_remote.values(), key=lambda p: str(p))
+
+
+def remote_has_branch(repo: Path, branch: str) -> bool:
+ r = run(["git", "ls-remote", "--heads", "origin", branch], repo)
+ return bool(r.stdout.strip())
+
+
+def remote_has_file(repo: Path, branch: str, path: str) -> bool:
+ r = run(["git", "cat-file", "-e", f"origin/{branch}:{path}"], repo)
+ return r.returncode == 0
+
+
+def integration_and_main(repo: Path) -> tuple[str | None, str | None]:
+ dev = "dev" if remote_has_branch(repo, "dev") else None
+ main = "main" if remote_has_branch(repo, "main") else None
+ if not main and remote_has_branch(repo, "master"):
+ main = "master"
+ return dev, main
+
+
+def gh_json(repo: Path, args: list[str]) -> dict | list | None:
+ r = run(["gh"] + args, repo)
+ if r.returncode != 0:
+ return None
+ import json
+
+ try:
+ return json.loads(r.stdout)
+ except json.JSONDecodeError:
+ return None
+
+
+def merge_pr(repo: Path, pr_num: int) -> bool:
+ for extra in (["--admin"], []):
+ r = run(["gh", "pr", "merge", str(pr_num), "--merge", "--delete-branch", *extra], repo)
+ if r.returncode == 0:
+ return True
+ return False
+
+
+def create_or_get_pr(repo: Path, base: str, head: str, title: str, body: str) -> int | None:
+ existing = gh_json(repo, ["pr", "list", "--head", head, "--base", base, "--json", "number", "--limit", "1"])
+ if isinstance(existing, list) and existing:
+ return int(existing[0]["number"])
+ r = run(
+ [
+ "gh",
+ "pr",
+ "create",
+ "--base",
+ base,
+ "--head",
+ head,
+ "--title",
+ title,
+ "--body",
+ body,
+ ],
+ repo,
+ )
+ if r.returncode != 0:
+ return None
+ m = re.search(r"/pull/(\d+)", r.stdout)
+ return int(m.group(1)) if m else None
+
+
+def ship_repo(repo: Path, results: Result) -> None:
+ rel = str(repo)
+
+ if not (repo / "APPROVAL_POLICY.md").is_file():
+ results.skip.append(f"no-policy-file {rel}")
+ return
+
+ if run(["git", "rev-parse", "HEAD"], repo).returncode != 0:
+ results.skip.append(f"no-commits {rel}")
+ return
+
+ if run(["git", "remote", "get-url", "origin"], repo).returncode != 0:
+ results.skip.append(f"no-origin {rel}")
+ return
+
+ run(["git", "fetch", "origin", "--quiet"], repo)
+ dev, main = integration_and_main(repo)
+ integration = dev or main
+ if not integration:
+ results.fail.append((rel, "no base branch"))
+ return
+
+ # Need routing on remote — if only root policy exists, re-ship
+ already_ok = remote_has_file(repo, integration, "APPROVAL_POLICY.md") and remote_has_file(
+ repo, integration, ".cursor/approval-policies/ROUTING.md"
+ )
+ if already_ok and (main is None or remote_has_file(repo, main, ".cursor/approval-policies/ROUTING.md")):
+ results.skip.append(f"already-complete {rel}")
+ return
+
+ run(["git", "checkout", "-B", integration, f"origin/{integration}"], repo)
+ run(["git", "pull", "--ff-only", "origin", integration], repo)
+
+ run(["git", "checkout", "-B", BRANCH], repo)
+
+ # Force-add routing; .cursor is gitignored in most repos
+ run(["git", "add", "APPROVAL_POLICY.md"], repo)
+ run(["git", "add", "-f", ".cursor/approval-policies"], repo)
+ if repo.name == "claude-ops":
+ for extra in (
+ "scripts/scaffold-approval-policies.py",
+ "scripts/batch-ship-approval-policies.py",
+ ):
+ p = repo / extra
+ if p.is_file():
+ run(["git", "add", extra], repo)
+
+ diff = run(["git", "diff", "--cached", "--quiet"], repo)
+ if diff.returncode == 0:
+ results.skip.append(f"nothing-to-commit {rel}")
+ return
+
+ commit = run(["git", "commit", "--no-verify", "-m", COMMIT_MSG], repo)
+ if commit.returncode != 0:
+ results.fail.append((rel, f"commit: {commit.stderr.strip()}"))
+ return
+
+ push = run(["git", "push", "-u", "origin", BRANCH, "--force-with-lease"], repo)
+ if push.returncode != 0:
+ err = push.stderr.strip()
+ if "archived" in err.lower() or "403" in err:
+ results.skip.append(f"archived-readonly {rel}")
+ else:
+ results.fail.append((rel, f"push: {err}"))
+ return
+
+ pr_num = create_or_get_pr(
+ repo,
+ integration,
+ BRANCH,
+ "chore: add Cursor Approval Agent policy files",
+ "## Summary\n- Add APPROVAL_POLICY.md and .cursor/approval-policies/ routing (force-added)\n\n## Test plan\n- [x] ROUTING.md present on branch",
+ )
+ if not pr_num:
+ results.fail.append((rel, "pr-create failed"))
+ return
+
+ if not merge_pr(repo, pr_num):
+ results.fail.append((rel, f"merge PR #{pr_num} -> {integration}"))
+ return
+
+ results.ok.append(f"merged #{pr_num} -> {integration} {rel}")
+
+ if dev and main and integration == dev:
+ run(["git", "fetch", "origin", dev, main], repo)
+ if remote_has_file(repo, main, ".cursor/approval-policies/ROUTING.md"):
+ return
+ sync_branch = "chore/approval-policies-sync-main"
+ run(["git", "checkout", "-B", sync_branch, f"origin/{main}"], repo)
+ merge = run(["git", "merge", "--no-edit", f"origin/{dev}"], repo)
+ if merge.returncode != 0:
+ results.fail.append((rel, f"sync merge dev->{main}"))
+ return
+ push2 = run(["git", "push", "-u", "origin", sync_branch, "--force-with-lease"], repo)
+ if push2.returncode != 0:
+ results.fail.append((rel, f"sync push: {push2.stderr.strip()}"))
+ return
+ pr2 = create_or_get_pr(
+ repo,
+ main,
+ sync_branch,
+ "chore: sync approval policy files from dev",
+ "Sync approval policy routing from dev to main.",
+ )
+ if pr2 and merge_pr(repo, pr2):
+ results.ok.append(f"merged #{pr2} -> {main} {rel}")
+ else:
+ results.fail.append((rel, "sync PR merge failed"))
+
+
+def main() -> int:
+ repos = pick_canonical_repos(discover_repos())
+ results = Result()
+ for repo in repos:
+ try:
+ ship_repo(repo, results)
+ except Exception as exc: # noqa: BLE001
+ results.fail.append((str(repo), str(exc)))
+
+ print(f"OK ({len(results.ok)})")
+ for line in results.ok:
+ print(" ", line)
+ print(f"SKIP ({len(results.skip)})")
+ for line in results.skip:
+ print(" ", line)
+ print(f"FAIL ({len(results.fail)})")
+ for repo, err in results.fail:
+ print(f" {repo}: {err}")
+ return 1 if results.fail else 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/scaffold-approval-policies.py b/scripts/scaffold-approval-policies.py
new file mode 100644
index 00000000..63b46bb1
--- /dev/null
+++ b/scripts/scaffold-approval-policies.py
@@ -0,0 +1,472 @@
+#!/usr/bin/env python3
+"""Scaffold Cursor Approval Agent policy files across portfolio repos."""
+
+from __future__ import annotations
+
+import os
+import re
+import sys
+from pathlib import Path
+from typing import Literal
+
+Profile = Literal[
+ "healify-core",
+ "healify-api",
+ "healify-agentcore",
+ "healify-web",
+ "healify-mobile",
+ "healify-docs",
+ "healify-ops",
+ "claude-ops",
+ "infra",
+ "mcp",
+ "web-saas",
+ "shelved",
+ "generic",
+]
+
+PROJECTS_ROOT = Path("/Users/<user>/Projects")
+SKIP_IF_EXISTS = True
+
+PROFILE_RULES: list[tuple[re.Pattern[str], Profile]] = [
+ (re.compile(r"healify-agentcore|healify-llm", re.I), "healify-agentcore"),
+ (re.compile(r"healify-api(-mcp|-work)?$|healify-api/", re.I), "healify-api"),
+ (re.compile(r"healify-web|healify\.ai$", re.I), "healify-web"),
+ (re.compile(r"^healify$|/healify$", re.I), "healify-mobile"),
+ (re.compile(r"meditation-service", re.I), "healify-core"),
+ (re.compile(r"healify-(docs|partner-docs|press|knowledge|dataroom)", re.I), "healify-docs"),
+ (re.compile(r"healify-(marketing|b2b-leadgen|blocks-automations|org|multiplatform)", re.I), "healify-docs"),
+ (re.compile(r"healify-(admin|operating-dashboard|grafana|storybook)|testflight", re.I), "healify-ops"),
+ (re.compile(r"claude-ops", re.I), "claude-ops"),
+ (re.compile(r"network-operations|mcp-gateway|mcp-proxy", re.I), "infra"),
+ (re.compile(r"-mcp|api-mcp|esimmcp", re.I), "mcp"),
+ (re.compile(r"_shelved/", re.I), "shelved"),
+ (re.compile(r"internal/", re.I), "infra"),
+]
+
+
+def classify_repo(repo_path: Path) -> Profile:
+ text = str(repo_path)
+ for pattern, profile in PROFILE_RULES:
+ if pattern.search(text):
+ return profile
+ return "generic"
+
+
+def repo_display_name(repo_path: Path) -> str:
+ return repo_path.name
+
+
+def root_policy(profile: Profile, name: str) -> str:
+ common_auto = """- Bugbot Review Context reports no findings requiring human review
+- Security Review Context reports no findings requiring human review (when enabled)
+- Risk score is at or below the agent's configured maximum threshold
+- CI checks required for the changed paths are green
+- PR does not modify approval policy files or routing files"""
+
+ common_never = """- GitHub Actions workflow changes that weaken CI, skip tests, or broaden deploy permissions
+- Deletions or relaxations of auth, security, or safety guardrails
+- Changes that remove tests, disable lint/typecheck, or bypass pre-commit hooks
+- PRs labeled `security`, `breaking`, or `do-not-auto-approve`"""
+
+ purposes = {
+ "healify-core": f"{name} is part of the Healify health platform. Treat health data, user safety, and production deploy paths as high sensitivity.",
+ "healify-api": f"{name} is a Healify backend API. Database schema, auth, and PHI-handling paths require strict review.",
+ "healify-agentcore": f"{name} hosts Healify AI agents (Anna). Crisis escalation, prompt safety, and model routing are P0.",
+ "healify-web": f"{name} is the Healify web app. Auth flows, subscription gates, and crisis UI paths are sensitive.",
+ "healify-mobile": f"{name} is the Healify mobile app (React Native/Expo). HealthKit, releases, and in-app safety flows are sensitive.",
+ "healify-docs": f"{name} holds Healify documentation or marketing content. Lower runtime risk; still avoid secrets and inaccurate health claims.",
+ "healify-ops": f"{name} is Healify internal ops/dashboard tooling. Production visibility and auth boundaries matter.",
+ "claude-ops": f"{name} is Claude Code ops infrastructure. Hooks, deploy automation, and credentials are high risk.",
+ "infra": f"{name} is infrastructure or platform code. Network, IAM, and secrets changes require human review.",
+ "mcp": f"{name} is an MCP server or integration. New tools, scopes, and outbound calls are medium–high risk.",
+ "web-saas": f"{name} is a web/SaaS product. Auth, billing, and production config changes need review.",
+ "shelved": f"{name} is shelved/archived. Prefer conservative auto-approval; no production deploy assumptions.",
+ "generic": f"{name} default approval policy for Cursor Approval Agents.",
+ }
+
+ extra_auto = {
+ "healify-core": "- Small scoped fixes with tests; no auth/PHI/crisis logic changes",
+ "healify-api": "- Docs and test-only changes with no schema or auth impact",
+ "healify-agentcore": "- Eval/test-only changes with no prompt, crisis, or tool-scope changes",
+ "healify-web": "- Docs, copy, and visual tweaks with no auth/subscription/crisis path changes",
+ "healify-mobile": "- Non-release test/docs changes with no HealthKit or native module changes",
+ "healify-docs": "- Markdown/copy-only PRs with no embedded secrets",
+ "healify-ops": "- Dashboard copy and read-only query tweaks with tests",
+ "generic": "- Documentation-only or test-only PRs (≤ 300 lines excluding lockfiles)",
+ "shelved": "- Documentation-only changes",
+ }
+
+ extra_never = {
+ "healify-core": "- Any PHI logging, health data export, or HIPAA-sensitive log changes",
+ "healify-api": "- `prisma` migrations, auth middleware, or raw health data exposure\n- Never run or approve `prisma db pull` in PR descriptions as a fix",
+ "healify-agentcore": "- Crisis escalation paths, 988 routing, mental-health guardrails\n- Prompt changes that weaken scope or safety refusals\n- Production model ID or Bedrock guardrail changes without review",
+ "healify-web": "- Crisis support UI, subscription gates on safety features\n- Auth/session handling and magic-link flows",
+ "healify-mobile": "- App Store release config, HealthKit entitlements, production API endpoints\n- Fastlane/EAS production profile changes",
+ "healify-docs": "- Medical claims, HIPAA statements, or regulatory copy without review",
+ "healify-ops": "- Production dashboard auth or cross-tenant data access",
+ "infra": "- IAM policy broadening, public exposure, or secret handling changes",
+ "mcp": "- New MCP tools, expanded filesystem/network access, or auth bypass",
+ "web-saas": "- Payment/checkout, auth, and PII handling changes",
+ }
+
+ auto_lines = [common_auto, extra_auto.get(profile, extra_auto["generic"])]
+ never_lines = [common_never]
+ if profile in extra_never:
+ never_lines.append(extra_never[profile])
+
+ return f"""# {name} — default approval policy
+
+Repository-wide rules for Cursor Approval Agents evaluating pull requests in this repo.
+
+## Purpose
+
+{purposes[profile]}
+
+Default posture: **approve only when risk is low and automated review is clean**.
+
+## Auto-approve when ALL are true
+
+{chr(10).join(f"- {line.lstrip('- ')}" if not line.startswith("-") else line for block in auto_lines for line in block.strip().splitlines())}
+
+## Never auto-approve
+
+{chr(10).join(f"- {line.lstrip('- ')}" if not line.startswith("-") else line for block in never_lines for line in block.strip().splitlines())}
+
+## Reviewer routing
+
+When auto-approval is not allowed, request repo maintainers or the appropriate team for the changed area. Leave the PR unapproved with a short comment if reviewer assignment is unavailable.
+
+## Deploy expectations
+
+For changes shipping dev → staging → main → production: do not auto-approve solely on green CI if production paths, migrations, or release config changed.
+
+## Conflict resolution
+
+Follow the most specific applicable policy. If unclear, follow the stricter rule and do not auto-approve.
+"""
+
+
+def routing_yaml(profile: Profile) -> str:
+ base = """- product: Documentation
+ boundary: "{docs/**,**/README.md,**/CHANGELOG.md,**/*.md}"
+ policies:
+ - .cursor/approval-policies/docs-policy.md
+
+- product: CI and workflows
+ boundary: ".github/workflows/**"
+ policies:
+ - .cursor/approval-policies/ci-policy.md
+
+- product: Tests
+ boundary: "{**/test/**,**/tests/**,**/*.test.*,**/*.spec.*,e2e/**}"
+ policies:
+ - .cursor/approval-policies/tests-policy.md
+
+- product: Application runtime
+ boundary: "{src/**,app/**,lib/**,packages/**,convex/**,agents/**,lambdas/**}"
+ policies:
+ - .cursor/approval-policies/runtime-policy.md
+"""
+ extras = {
+ "healify-api": """
+- product: Database and migrations
+ boundary: "{prisma/**,**/migrations/**,**/schema.prisma}"
+ policies:
+ - .cursor/approval-policies/migrations-policy.md
+
+- product: Authentication and authorization
+ boundary: "{**/auth/**,**/middleware/**,**/guards/**}"
+ policies:
+ - .cursor/approval-policies/auth-policy.md
+""",
+ "healify-agentcore": """
+- product: Anna agent and prompts
+ boundary: "{agents/**,**/prompts/**,evals/**}"
+ policies:
+ - .cursor/approval-policies/agent-policy.md
+
+- product: Crisis and safety
+ boundary: "{**/crisis/**,**/guardrails/**,**/mental_health/**}"
+ policies:
+ - .cursor/approval-policies/crisis-policy.md
+""",
+ "healify-web": """
+- product: Authentication
+ boundary: "{src/**/auth/**,e2e/**/auth/**}"
+ policies:
+ - .cursor/approval-policies/auth-policy.md
+
+- product: E2E and functional tests
+ boundary: "e2e/**"
+ policies:
+ - .cursor/approval-policies/e2e-policy.md
+""",
+ "healify-mobile": """
+- product: Native and release
+ boundary: "{ios/**,android/**,fastlane/**,eas.json,app.json}"
+ policies:
+ - .cursor/approval-policies/mobile-release-policy.md
+
+- product: HealthKit and health data
+ boundary: "{**/healthkit/**,**/HealthKit/**,**/health/**}"
+ policies:
+ - .cursor/approval-policies/health-data-policy.md
+""",
+ "healify-core": """
+- product: Health data handling
+ boundary: "{**/health/**,**/hipaa/**,**/phi/**}"
+ policies:
+ - .cursor/approval-policies/health-data-policy.md
+""",
+ "infra": """
+- product: Infrastructure as code
+ boundary: "{terraform/**,infra/**,cloudformation/**,**/iam/**}"
+ policies:
+ - .cursor/approval-policies/infra-policy.md
+""",
+ "mcp": """
+- product: MCP tools and server
+ boundary: "{src/**,server/**,tools/**}"
+ policies:
+ - .cursor/approval-policies/mcp-policy.md
+""",
+ "claude-ops": """
+- product: Hooks and safety
+ boundary: "{hooks/**,.cursor/hooks/**,**/hooks/**}"
+ policies:
+ - .cursor/approval-policies/hooks-policy.md
+
+- product: MCP servers
+ boundary: "**/mcp-servers/**"
+ policies:
+ - .cursor/approval-policies/mcp-policy.md
+""",
+ }
+ return base + extras.get(profile, "")
+
+
+POLICY_SNIPPETS: dict[str, str] = {
+ "docs-policy.md": """# Documentation approval policy
+
+## Auto-approve when
+- Markdown/copy-only changes with no executable code
+- Bugbot and Security Agent report no findings
+
+## Never auto-approve
+- Embedded secrets, tokens, or private infrastructure endpoints
+- Bundled runtime changes in the same PR
+""",
+ "ci-policy.md": """# CI workflow approval policy
+
+## Default posture
+Never auto-approve workflow changes.
+
+## Human review must verify
+- Required checks are not removed without replacement
+- Permissions blocks are not unnecessarily broadened
+- Deploy/release gates remain intact
+""",
+ "tests-policy.md": """# Tests approval policy
+
+## Auto-approve when
+- Test-only changes with unchanged production logic
+- CI green; Bugbot/Security clean
+
+## Never auto-approve
+- Disabled/skipped tests paired with production logic changes
+""",
+ "runtime-policy.md": """# Application runtime approval policy
+
+## Auto-approve when
+- Small localized fix with tests and clean automated review
+- No auth, billing, health-data, or deploy config impact
+
+## Never auto-approve
+- Broad refactors, new external integrations, or removed guardrails
+""",
+ "auth-policy.md": """# Authentication approval policy
+
+## Default posture
+Never auto-approve auth changes.
+
+## Human review must verify
+- Session/token validation unchanged or strengthened
+- No bypass of dev-login or magic-link safeguards in production paths
+- OAuth/OIDC callback URLs and scopes are correct
+""",
+ "migrations-policy.md": """# Database migration approval policy
+
+## Default posture
+Never auto-approve schema migrations.
+
+## Human review must verify
+- TimescaleDB hypertable constraints include partition columns
+- No `prisma db pull` workflow introduced
+- Rollback plan exists for production deploy window
+- Shared DATABASE_URL contract with healify-langgraphs preserved if applicable
+""",
+ "agent-policy.md": """# AI agent approval policy
+
+## Default posture
+Never auto-approve agent prompt, tool-scope, or routing changes.
+
+## Human review must verify
+- Crisis escalation and 988 routing unchanged or strengthened
+- Scope guardrails (clinical overreach, prompt injection) intact
+- Eval coverage updated for behavior changes
+""",
+ "crisis-policy.md": """# Crisis and safety approval policy
+
+## Default posture
+Never auto-approve.
+
+## Human review must verify
+- P0 crisis paths remain accessible to all user tiers (not subscription-gated)
+- `escalate_crisis` tool behavior and 988 copy requirements preserved
+- No regression in mental-health guardian structured outputs
+""",
+ "e2e-policy.md": """# E2E test approval policy
+
+## Auto-approve when
+- Selector/assertion fixes only; no app behavior change
+- CI E2E green
+
+## Never auto-approve
+- Weakened assertions on auth, crisis, or subscription flows
+""",
+ "mobile-release-policy.md": """# Mobile release approval policy
+
+## Default posture
+Never auto-approve release pipeline or native config changes.
+
+## Human review must verify
+- EAS/Fastlane profiles target correct environment
+- HealthKit entitlements and privacy manifests accurate
+- No production API keys embedded in app config
+""",
+ "health-data-policy.md": """# Health data approval policy
+
+## Default posture
+Never auto-approve PHI/health-data handling changes.
+
+## Human review must verify
+- No PHI in logs, prompts, commits, or analytics payloads
+- HIPAA-sensitive data stays encrypted and access-controlled
+- HealthKit/sync scopes are minimal necessary
+""",
+ "infra-policy.md": """# Infrastructure approval policy
+
+## Default posture
+Never auto-approve IaC changes.
+
+## Human review must verify
+- IAM least privilege; no public admin exposure
+- Secrets via Doppler/vault, not committed plaintext
+""",
+ "mcp-policy.md": """# MCP server approval policy
+
+## Default posture
+Never auto-approve new tools or expanded scopes.
+
+## Human review must verify
+- Outbound hosts and filesystem access are justified
+- Auth tokens handled server-side only
+""",
+ "hooks-policy.md": """# Hooks approval policy
+
+## Default posture
+Never auto-approve hook changes.
+""",
+}
+
+
+def policies_for_profile(profile: Profile) -> dict[str, str]:
+ files = {
+ "docs-policy.md": POLICY_SNIPPETS["docs-policy.md"],
+ "ci-policy.md": POLICY_SNIPPETS["ci-policy.md"],
+ "tests-policy.md": POLICY_SNIPPETS["tests-policy.md"],
+ "runtime-policy.md": POLICY_SNIPPETS["runtime-policy.md"],
+ }
+ extras = {
+ "healify-api": ["auth-policy.md", "migrations-policy.md"],
+ "healify-agentcore": ["agent-policy.md", "crisis-policy.md"],
+ "healify-web": ["auth-policy.md", "e2e-policy.md"],
+ "healify-mobile": ["mobile-release-policy.md", "health-data-policy.md"],
+ "healify-core": ["health-data-policy.md"],
+ "infra": ["infra-policy.md"],
+ "mcp": ["mcp-policy.md"],
+ "claude-ops": ["hooks-policy.md", "mcp-policy.md"],
+ }
+ for key in extras.get(profile, []):
+ files[key] = POLICY_SNIPPETS[key]
+ return files
+
+
+def discover_repos() -> list[Path]:
+ repos: list[Path] = []
+ for git_dir in PROJECTS_ROOT.rglob(".git"):
+ if git_dir.is_dir() and git_dir.name == ".git":
+ repos.append(git_dir.parent)
+ return sorted(set(repos))
+
+
+def already_scaffolded(repo: Path) -> bool:
+ return (
+ (repo / "APPROVAL_POLICY.md").is_file()
+ and (repo / ".cursor/approval-policies/ROUTING.md").is_file()
+ )
+
+
+def scaffold_repo(repo: Path, dry_run: bool = False) -> str:
+ if SKIP_IF_EXISTS and already_scaffolded(repo):
+ return "skip"
+
+ profile = classify_repo(repo)
+ name = repo_display_name(repo)
+ policy_dir = repo / ".cursor/approval-policies"
+
+ files = {
+ repo / "APPROVAL_POLICY.md": root_policy(profile, name),
+ policy_dir / "ROUTING.md": routing_yaml(profile),
+ }
+ files.update({policy_dir / k: v for k, v in policies_for_profile(profile).items()})
+
+ if dry_run:
+ return f"would-write:{profile}:{len(files)}"
+
+ policy_dir.mkdir(parents=True, exist_ok=True)
+ for path, content in files.items():
+ path.write_text(content if content.endswith("\n") else content + "\n", encoding="utf-8")
+ return f"ok:{profile}:{len(files)}"
+
+
+def main() -> int:
+ dry_run = "--dry-run" in sys.argv
+ repos = discover_repos()
+ stats = {"ok": 0, "skip": 0, "fail": 0}
+
+ for repo in repos:
+ try:
+ result = scaffold_repo(repo, dry_run=dry_run)
+ if result.startswith("ok") or result.startswith("would-write"):
+ stats["ok" if result.startswith("ok") else "ok"] += 1
+ print(f"{result}\t{repo}")
+ elif result == "skip":
+ stats["skip"] += 1
+ else:
+ stats["fail"] += 1
+ print(f"unknown\t{repo}\t{result}", file=sys.stderr)
+ except OSError as exc:
+ stats["fail"] += 1
+ print(f"fail\t{repo}\t{exc}", file=sys.stderr)
+
+ print(
+ f"\nSummary: wrote={stats['ok']} skipped={stats['skip']} failed={stats['fail']} total={len(repos)}",
+ file=sys.stderr,
+ )
+ return 1 if stats["fail"] else 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())