Refuses tool calls that break Verdant's AGENTS.md fences: force-push, pushes to verdant-grow-diary/main, rebase, --no-verify, dependency/lockfile changes…

These workflows include the Client secret boundary guard. The badge reflects overall workflow status, not the guard alone — see Client Secret Boundary Guard for how to verify the guard specifically.
Quick links: Workflow · Latest run · Artifacts are attached to each completed run under quicklog-smoke-artifacts (open the run page → Artifacts).
Verdant is a standalone Grow Room Operating System. It turns grow logs, plant photos, sensor readings, alerts, and AI-assisted analysis into safer grow decisions and better harvest outcomes.
The current product priority is the V0 operating loop:
Grow → Tent → Plant → Diary/Logs → Photo → Sensor Snapshot → AI Doctor → Alert/Recommendation → Approval-Required Action Queue
/tools/grow-help-toolkit is a client-side nutrient, grow-light, and expense planner. It requires no account or Toolkit backend, sends no calculator inputs to analytics, and uses no device control or live sensor data. The last inputs are stored only in browser localStorage; CSV and print exports are also generated in the browser.
Core formulas:
PPM500 = EC × 500, PPM640 = EC × 640, PPM700 = EC × 700EC = PPM ÷ selected scale; CF = EC × 10amount = dose per L/gal × working reservoir L/galmL/L = (target EC − source-water EC) ÷ EC-per-mL/Lbase mL/L = EC rise ÷ Σ(part EC-per-mL/L × part ratio); part mL/L = base mL/L × part ratioV1 = (C2 × V2) ÷ C1grams = g/gal × working gallonsDLI (mol/m²/day) = PPFD × hours × 3600 ÷ 1,000,000PPF (µmol/s) = actual watts × efficacy (µmol/J)(fixture PPF × fixture count × canopy efficiency) ÷ area m²PPFDnew = PPFDchart × (hchart ÷ hnew)²(target PPFD × area m²) ÷ (fixture PPF × efficiency)kWh = (actual watts ÷ 1,000) × hours/day × days; cost = kWh × ratecost/mol = cycle electricity cost ÷ (PPF × fixture count × total light-hours × 3,600 ÷ 1,000,000)cost/g = selected cycle cost ÷ dried saleable harvest gramsoperating ROI % = (user comparison value − operating cost) ÷ operating cost × 100; setup payback cycles = setup cost ÷ positive operating-cycle savingsAll light outputs are planning estimates. Verify canopy PPFD with a PAR meter; inverse-square behavior and the optional 3×3 interpolation are approximations, not measured PAR maps. Nutrient EC/PPM ranges are typical starting references, not guarantees. Cost-per-weight accepts dried saleable weight only and never prefills a yield or market price. Optional N/P/K ppm entries are grower-entered planning notes only; they do not infer a dose without product elemental analysis.
The in-app About panel keeps the reviewed capability sources beside a short note explaining what each reference informed. It also links bidirectionally with the public VPD calculator (/tools/vpd-calculator), grow-stage target bands (/tools/blueprint-targets), and grow guides (/guides). Those pages are separate references: calculator inputs are never placed in a URL or transferred between tools.
bun install
bun run dev
The dev server runs Vite on http://localhost:8080. bun is the package manager (bun.lock is authoritative) — do not use npm or yarn. On Windows, run bun install from a checkout outside OneDrive; OneDrive reparse points break it.
Lovable Cloud auto-manages the .env file. Do not edit it by hand. Variables provided:
VITE_SUPABASE_URLVITE_SUPABASE_PUBLISHABLE_KEYVITE_SUPABASE_PROJECT_IDAdditional secrets (API keys for edge functions, third-party services) are configured via Lovable Cloud secrets — never commit secrets to the repo.
Production domain: https://verdantgrowdiary.com (also served on https://www.verdantgrowdiary.com).
docs/specs/release-topology-specification.md §4; do not assume a platform. Both the apex and www hostnames must serve a valid certificate before announcing a release.A record, www A record) can interrupt SSL issuance — re-verify the certificate after any DNS update.docs/launch-checklist.md for the full pre-launch verification steps.Public crawler surfaces:
public/robots.txt — allows crawling and points at the production sitemap.public/sitemap.xml — lists the indexable public surfaces. Private authenticated and noindex routes are intentionally excluded.Run all of the following before requesting review:
bunx vitest run
bunx eslint <changed files>
npm run build
All existing tests must pass. New behavior must ship with new tests.
Scanner guardrail changes must also run the CI-equivalent sentinel:
bun run test:scanner-guardrails:ci
See docs/testing/scanner-guardrails.md for scannerIt, installScannerGuardrail, cached scanner walks, and slow-test telemetry rules.
Watch-mode tests:
npx vitest
The scanner guardrail suite walks the filesystem and is the most likely source of environmental timeout flakes. A 5000ms slow-test sentinel appends offenders to test-results/scanner-guardrail-slow-tests.jsonl.
bun run test:scanner-guardrails # raw scanner sentinel (vitest)
bun run test:scanner-guardrails:ci # CI-equivalent wrapper:
# - deletes the stale report
# - runs the scanner suite
# - validates JSONL row contract
# - fails the build if any slow
# row was emitted
bun run test:scanner-guardrails:ci -- --verbose
# also prints report path, threshold,
# stale-report removal state,
# post-run report presence, row count,
# validation stats (valid/invalid/slow),
# and the value-preview truncation limit
bun run test:scanner-guardrails:clean # remove the default report
bun run test:scanner-guardrails:clean -- <path> # remove a specific report file
Report path: test-results/scanner-guardrail-slow-tests.jsonl.
Diagnostics behavior:
GITHUB_ACTIONS=true, the CI wrapper emits one ::error annotation per invalid or slow telemetry row (not just the first). Annotations include report path, JSONL line number, suite/test/file, durationMs/thresholdMs, and the failed-fields list.::error lines are added under GitHub Actions.See docs/testing/scanner-guardrails.md for the full contract.
Every PR that touches data access, auth, AI, the Action Queue, sensors, device control, or migrations must satisfy the Verdant safety checklist.
docs/security-checklist.md — required per-PR security review.docs/security-exceptions.md — the registry of intentionally accepted security warnings. Any deviation from the checklist must be recorded here..github/pull_request_template.md — PR template that links the checklist and the validation commands above.The AI Coach is read-only and suggest-only. It must never trigger writes, device commands, or unattended Action Queue changes. Safety regressions are caught by:
Action Queue items remain approval-required. No code path may auto-approve, auto-complete, or auto-cancel queue items, and no executable device payload may ship through the queue. Safety and audit guarantees are covered by:
Sensor readings must never be faked as live. Every reading is labeled as one of demo, manual, live, stale, or invalid. Stale, missing, or suspicious telemetry must be surfaced as such — never silently substituted and never relabeled as healthy. See docs/sensor-truth-rules.md and docs/data-labeling-spec.md.
RLS is the ownership boundary for every user-owned table. Policies are written against auth.uid() and evaluated server-side. Never trust client-provided user_id — the frontend must not send it as a trusted field, and any client-supplied value must be re-checked server-side. No service_role key may appear in client code.
After deploying the pi-ingest-readings edge function, run the deployed pi-ingest smoke verification described in docs/pi-ingest-smoke-runbook.md. It covers signed-bridge happy-path, replay/idempotency, tampered signature, and unknown-bridge cases. The contract that runbook verifies lives in docs/pi-ingest-write-transaction-contract.md.
Windows EcoWitt local testbench: see docs/ecowitt-windows-testbench.md.
Verdant follows a read-only, no-write, no-control architecture for advisory surfaces:
demo, manual, live, stale, or invalid.user_id.service_role keys in client code.See docs/buildops-kit/README.md for the full BuildOps Kit covering product context, data-labeling, fixture contracts, AI Doctor output rules, Action Queue safety, prompt scaffolds, and the QA regression checklist.
The /one-tent-loop-proof route is a read-only diagnostic. Its rules are enforced by unit + fuzz + golden + Playwright tests. Any change to the proof surface must uphold the following:
present.healthy, verified, success, all good, no issues detected, confirmed safe, validated live.weak, unknown, stale, invalid, demo_only, missing, and blocked states. Do not hide or collapse a weak state into a neutral badge.sanitizeShortLabel before rendering.bun run test:one-tent-loop-proof-never-healthybunx vitest run src/test/one-tent-loop-top-gap-report-golden.test.tsstorageState): bun run test:e2e:one-tent-loop-proof-never-healthy:devbun run check:one-tent-loop-proof-never-healthyVerdant exposes three read-only MCP tools (list_grows, list_recent_diary_entries, get_latest_sensor_snapshot). The test src/test/mcp-local-rls-integration.test.ts proves that these tools enforce Supabase Row-Level Security through the signed-in grower's OAuth/session token, including under limit and includeArchived options, and that responses never leak another user's rows, raw_payload, service_role, JWTs, or bridge/OAuth secrets.
Beyond the explicit regression cases, the suite derives extra pagination/filter isolation cases from .lovable/mcp/manifest.json: every advertised limit/boolean-filter param automatically generates cross-user cases for both users, foreign-scope-id probes, and unauthenticated checks. Params are never invented — a tool that advertises no pagination/filter params (like get_latest_sensor_snapshot) is recorded as N/A instead of failing.
The suite is local-only and skips cleanly in CI/PRs where the harness is not configured. It never contacts hosted Supabase and never requires production secrets.
Required env vars
MCP_LOCAL_RLS_HARNESS=1LOCAL_SUPABASE_URL (e.g. http://127.0.0.1:54321)LOCAL_SUPABASE_ANON_KEYLOCAL_SUPABASE_SERVICE_ROLE_KEY — local only, used exclusively for seeding/cleanup; MCP tool execution itself always routes through supabaseForUser(ctx) with an anon-scoped user token. Never paste a hosted/production service role key here, and never commit any service role key — local keys are ephemeral CLI-generated values.Required local services
supabase start) with this repo's migrations applied (supabase db reset or supabase migration up).42501 permission denied until you mirror hosted reality (local database only): GRANT USAGE ON SCHEMA public TO anon, authenticated, service_role;
GRANT ALL ON TABLE public.grows, public.tents, public.diary_entries,
public.sensor_readings TO service_role;
GRANT SELECT ON TABLE public.grows, public.tents, public.diary_entries,
public.sensor_readings TO authenticated;
The CI workflow runs this automatically after supabase db reset --local.
Run it
MCP_LOCAL_RLS_HARNESS=1 \
LOCAL_SUPABASE_URL=http://127.0.0.1:54321 \
LOCAL_SUPABASE_ANON_KEY=<local-anon-key> \
LOCAL_SUPABASE_SERVICE_ROLE_KEY=<local-service-role-key> \
bun run test:mcp:rls:local
The test:mcp:rls:local package script is a thin wrapper around bunx vitest run src/test/mcp-local-rls-integration.test.ts — it contains no keys; you always supply local env values yourself.
CI behavior
The mcp-local-rls-integration workflow (.github/workflows/mcp-local-rls-integration.yml) runs the harness against a fresh local Supabase on the runner:
supabase link, no remote db push, no hosted refs, no repo secrets),supabase db reset --local,artifacts/mcp-local-rls/ (harness log, response snapshots, vitest output). Artifacts are sanitized twice — at write time by the harness and again by scripts/sanitize-mcp-rls-artifacts.mjs — so JWTs, bearer tokens, service_role material, refresh/bridge/access tokens, client secrets, raw headers, raw_payload, and live env values are always redacted.scripts/assert-required-money-migrations-applied.mjs verifies that every migration listed in scripts/required-money-migrations.mjs is actually present in the target database's supabase_migrations.schema_migrations tracker. It is read-only (single SELECT) and blocks deploys when a required migration exists on disk but has not been applied to the target environment.
The .github/workflows/required-money-migrations.yml workflow runs this check against live only, by manual dispatch from the deploy branch with a typed LIVE confirmation. Verdant has no sandbox database lane. It reads the DB connection string from its protected GitHub environment:
verdant-production → SUPABASE_DB_URLpostgresql://postgres.<ref>:REDACTED@aws-0-<region>.pooler.supabase.com:5432/postgres. The password is the database password, not the anon or service-role key.SUPABASE_DB_URL with the live project's URL.required-money-migrations workflow with target_env=live and confirm_live=LIVE to confirm the job goes green. If it errors with exit code 2, the URL is wrong or the pooler is unreachable; exit code 1 means a required migration is missing from production and must be applied before deploying.Rotate these secrets whenever the database password is rotated.
Requires psql on PATH (brew install libpq on macOS, sudo apt-get install postgresql-client on Debian/Ubuntu).
# Live (Verdant has no sandbox database)
SUPABASE_DB_URL='postgresql://postgres.<live-ref>:REDACTED@aws-0-<region>.pooler.supabase.com:5432/postgres' \
TARGET_ENV=live \
node scripts/assert-required-money-migrations-applied.mjs
Exit codes: 0 = all required migrations applied, 1 = one or more missing (do not deploy), 2 = malformed required-file name (extractor could not derive a 14-digit prefix), 3 = no DB connection string, 4 = psql not on PATH, 5 = tracker query failed. Treat 2-5 as blocking. The script writes a machine-readable audit to audit/money-migrations/applied-audit.json and an expected-vs-actual diff to audit/money-migrations/applied-audit.diff.txt on every exit branch — the same files CI uploads as artifacts. Override the diff path with DIFF_PATH=/tmp/foo.diff.txt.
Pair it with the file-presence guard when auditing locally:
node scripts/assert-required-money-migrations.mjs
migrationVersion() and applied-check logicsrc/test/required-money-migrations-version.test.ts covers the 14-digit prefix extractor (migrationVersion() in scripts/required-money-migrations.mjs) and the applied-vs-required comparison used by assert-required-money-migrations-applied.mjs.
Run just this file (fast, no DB needed):
# Focused run — recommended
bunx vitest run src/test/required-money-migrations-version.test.ts
# Verbose reporter (shows every case name)
bunx vitest run src/test/required-money-migrations-version.test.ts --reporter=verbose
# Filter to a single case
bunx vitest run src/test/required-money-migrations-version.test.ts -t "migrationVersion"
bunx vitest run src/test/required-money-migrations-version.test.ts -t "applied-check"
To inspect the exact prefixes the extractor produces for the current required list (useful when a filename rename shows up as one missing + one unknown):
node -e "
import('./scripts/required-money-migrations.mjs').then(m => {
for (const f of m.REQUIRED_MONEY_MIGRATIONS) {
console.log(m.migrationVersion(f).padEnd(16), f);
}
});
"
To compare expected (required) vs actual (applied in a target DB) prefixes without running the guard, use the same pooled URL as the applied-check:
# Expected prefixes (from the source-of-truth list)
node -e "
import('./scripts/required-money-migrations.mjs').then(m => {
console.log(m.REQUIRED_MONEY_MIGRATIONS.map(m.migrationVersion).sort().join('\n'));
});
" > /tmp/expected-versions.txt
# Actual prefixes (from the target DB's migration tracker)
psql "$SUPABASE_DB_URL" -Atc \
"SELECT version FROM supabase_migrations.schema_migrations ORDER BY version" \
> /tmp/applied-versions.txt
# Required but NOT applied (what the guard would flag)
comm -23 <(sort -u /tmp/expected-versions.txt) <(sort -u /tmp/applied-versions.txt)
# Applied but NOT required (informational — expected to be non-empty)
comm -13 <(sort -u /tmp/expected-versions.txt) <(sort -u /tmp/applied-versions.txt)
The guard itself uses the same SELECT and comparison; these commands just let you eyeball the two sides independently.
diff-money-migration-prefixes.mjs)scripts/diff-money-migration-prefixes.mjs is a lightweight companion to the applied-check. It dumps the extractor's expected 14-digit prefixes from the required-money-migrations manifest and (optionally) diffs them against `supabase_migrations.sche
hooks/register.ts 94 lines1import type { ProcessRunResult, Register } from "claude-code";
2
3import {
4 MIGRATION_PATH,
5 PUBLISHED_MIGRATION_MSG,
6 checkBash,
7 checkFileEdit,
8 checkInWarning,
9 checkMcp,
10 repoRelative,
11} from "./rules";
12
13type Git = (argv: readonly string[]) => Promise<ProcessRunResult | null>;
14
15const BASE_REFS = ["origin/verdant-grow-diary", "origin/main"];
16
17/** A migration is published when the base branch (or, with no base ref, HEAD) already holds it. */
18async function isPublished(git: Git, rel: string): Promise<boolean> {
19 for (const ref of BASE_REFS) {
20 const r = await git(["git", "cat-file", "-e", `${ref}:${rel}`]);
21 if (r && r.exitCode === 0) return true;
22 }
23 const base = await git(["git", "rev-parse", "--verify", "-q", "origin/verdant-grow-diary"]);
24 if (base && base.exitCode === 0) return false;
25 const r = await git(["git", "cat-file", "-e", `HEAD:${rel}`]);
26 return r !== null && r.exitCode === 0;
27}
28
29/** The checkout root, so paths anchor exactly even when the checkout sits under ~/src or ~/docs. */
30async function repoRoot(git: Git): Promise<string | null> {
31 const r = await git(["git", "rev-parse", "--show-toplevel"]);
32 return r && r.exitCode === 0 ? r.stdout.trim() || null : null;
33}
34
35/** The refusal reason for writing `filePath`, or null. */
36async function fileReason(git: Git, filePath: unknown): Promise<string | null> {
37 if (typeof filePath !== "string") return null;
38 const root = await repoRoot(git);
39 const reason = checkFileEdit(filePath, root);
40 if (reason) return reason;
41 const rel = repoRelative(filePath, root);
42 if (MIGRATION_PATH.test(rel) && (await isPublished(git, rel)))
43 return PUBLISHED_MIGRATION_MSG(rel);
44 return null;
45}
46
47export const register: Register = (on) => {
48 on("tool.call", { tool: "Bash" }, ($, e, next) => {
49 const reason = checkBash(e.command);
50 if (!reason) return next(e);
51 $.ui.toast("verdant-guard blocked a command");
52 return { deny: `verdant-guard: ${reason}` };
53 });
54
55 on("tool.call", { tool: "Edit" }, async ($, e, next) => {
56 const reason = await fileReason((argv) => $.process.run(argv).catch(() => null), e.file_path);
57 if (!reason) return next(e);
58 $.ui.toast("verdant-guard blocked an edit");
59 return { deny: `verdant-guard: ${reason}` };
60 });
61
62 on("tool.call", { tool: "Write" }, async ($, e, next) => {
63 const reason = await fileReason((argv) => $.process.run(argv).catch(() => null), e.file_path);
64 if (!reason) return next(e);
65 $.ui.toast("verdant-guard blocked a write");
66 return { deny: `verdant-guard: ${reason}` };
67 });
68
69 on("tool.call", { tool: "NotebookEdit" }, async ($, e, next) => {
70 const reason = await fileReason(
71 (argv) => $.process.run(argv).catch(() => null),
72 e.notebook_path,
73 );
74 if (!reason) return next(e);
75 $.ui.toast("verdant-guard blocked a notebook edit");
76 return { deny: `verdant-guard: ${reason}` };
77 });
78
79 on("tool.call", async ($, e, next) => {
80 if (!e.tool.startsWith("mcp__")) return next(e);
81 const input = e as unknown as Record<string, unknown>;
82 const reason = checkMcp(e.tool, input);
83 if (reason) {
84 $.ui.toast("verdant-guard blocked an MCP call");
85 return { deny: `verdant-guard: ${reason}` };
86 }
87 const warning = checkInWarning(e.tool, input);
88 if (!warning) return next(e);
89 const ran = await next(e);
90 if (ran.deny !== undefined) return ran;
91 return { ...ran, context: [...(ran.context ?? []), warning] };
92 });
93};
94hooks/rules.ts 941 lines1// Pure rules for verdant-guard: no engine, no I/O, deterministic.
2// Each check returns a refusal reason, or null when the call may run.
3// Source of every rule: AGENTS.md / CLAUDE.md on the verdant-grow-diary deploy branch.
4
5export const PROTECTED_BRANCHES = ["verdant-grow-diary", "main"] as const;
6
7// The production Supabase project ref (CURRENT_STATE.md, standing directive 2026-08-25).
8export const PRODUCTION_PROJECT_REF = "knkwiiywfkbqznbxwqfh";
9
10const HEREDOC_START = /(?<!<)<<(?!<)-?\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\1/;
11const SHELL_READS_STDIN = /(^|[\s|;&(])(bash|sh|zsh|dash)(\s+-[a-z]+)*\s*(<<|$)/;
12
13/**
14 * Drops heredoc bodies: they are data (a file being written, a script for python or node),
15 * not shell commands. A body fed to a shell (`bash <<EOF`) is kept, since the shell runs it.
16 */
17export function stripHeredocs(command: string): string {
18 const out: string[] = [];
19 let end: string | null = null;
20 let keep = false;
21 for (const line of command.split("\n")) {
22 if (end !== null) {
23 if (line.trim() === end) end = null;
24 else if (keep) out.push(line);
25 continue;
26 }
27 out.push(line);
28 const m = HEREDOC_START.exec(line);
29 if (m && m[2]) {
30 end = m[2];
31 keep = SHELL_READS_STDIN.test(line.slice(0, m.index).trimEnd() + " <<");
32 }
33 }
34 return out.join("\n");
35}
36
37/**
38 * Splits a shell command into simple-command segments and tokens. Quote-aware: `&&`, `||`,
39 * `;`, `|` and newlines split only outside quotes, so `grep "a|git push --force"` stays one
40 * command. Quotes are removed from tokens; a backslash escapes the next character outside
41 * single quotes. It does not expand `$(…)`, backticks or `bash -c` strings (see README).
42 * Unquoted redirections (`2>&1`, `> log`, `<in`) and their targets are dropped, since they are
43 * not arguments; pass `redirections: false` for text no shell parses, such as an `env -S` string.
44 */
45/** Index of the `)` closing the `(` at `open`, respecting nested parens and quotes; -1 if none. */
46function matchingParen(text: string, open: number): number {
47 let depth = 0;
48 let quote: "'" | '"' | null = null;
49 for (let i = open; i < text.length; i += 1) {
50 const c = text[i];
51 if (quote !== null) {
52 if (c === "\\" && quote === '"') i += 1;
53 else if (c === quote) quote = null;
54 continue;
55 }
56 if (c === "\\") i += 1;
57 else if (c === "'" || c === '"') quote = c;
58 else if (c === "(") depth += 1;
59 else if (c === ")" && --depth === 0) return i;
60 }
61 return -1;
62}
63
64export function segments(command: string, redirections = true): string[][] {
65 const text = stripHeredocs(command);
66 const out: string[][] = [];
67 let tokens: string[] = [];
68 let token = "";
69 let inToken = false;
70 let quoted = false;
71 let quote: "'" | '"' | null = null;
72 // `redirect`: the current word is a redirection; `dropNext`: the next word is its target.
73 let redirect = false;
74 let dropNext = false;
75 const endToken = () => {
76 if (inToken) {
77 if (redirect) dropNext = token === "";
78 else if (dropNext) dropNext = false;
79 else tokens.push(token);
80 }
81 token = "";
82 inToken = false;
83 quoted = false;
84 redirect = false;
85 };
86 const endSegment = () => {
87 endToken();
88 dropNext = false;
89 if (tokens.length > 0) out.push(tokens);
90 tokens = [];
91 };
92 for (let i = 0; i < text.length; i += 1) {
93 const c = text[i]!;
94 if (quote !== null) {
95 if (quote === '"' && c === "$" && text[i + 1] === "(") {
96 // A command substitution still runs inside double quotes: check its body as commands.
97 const end = matchingParen(text, i + 1);
98 if (end > i + 1) {
99 out.push(...segments(text.slice(i + 2, end)));
100 token += text.slice(i, end + 1);
101 i = end;
102 continue;
103 }
104 }
105 if (c === quote) quote = null;
106 else if (c === "\\" && quote === '"' && i + 1 < text.length) {
107 // As in bash: inside double quotes a backslash escapes only $ ` " \ and newline;
108 // before anything else it stays, so `"git\_push"` keeps its backslash for env -S.
109 const next = text[i + 1]!;
110 if (next === "\n") i += 1;
111 else if ('$`"\\'.includes(next)) token += text[++i];
112 else token += c;
113 } else token += c;
114 continue;
115 }
116 if (c === "'" || c === '"') {
117 quote = c;
118 inToken = true;
119 quoted = true;
120 } else if (redirections && c === "#" && !inToken) {
121 // An unquoted `#` that starts a word begins a comment: Bash ignores the rest of the line,
122 // so `gh pr ready 1 # --undo` runs `gh pr ready 1`. Inside a word (`a#b`) it is a character.
123 while (i + 1 < text.length && text[i + 1] !== "\n") i += 1;
124 } else if (
125 redirections &&
126 !redirect &&
127 (c === ">" || c === "<" || (c === "&" && text[i + 1] === ">"))
128 ) {
129 // An unquoted `>`, `<` or `&>` opens a redirection: read the whole operator, then any
130 // attached target. A descriptor right before it (`2>`, `{fd}>`) belongs to it; any
131 // other word before it (`main>log`, `-f>log`) is a word of its own and stays.
132 if (inToken && (quoted || !/^(\d+|\{[A-Za-z_][A-Za-z0-9_]*\})$/.test(token))) endToken();
133 while (i + 1 < text.length && "<>&|".includes(text[i + 1]!)) i += 1;
134 redirect = true;
135 inToken = true;
136 token = "";
137 } else if (c === "\\" && i + 1 < text.length) {
138 // A backslash-newline is a line continuation, not a character.
139 if (text[i + 1] !== "\n") {
140 token += text[i + 1];
141 inToken = true;
142 }
143 i += 1;
144 } else if (c === "\n" || c === ";" || c === "|" || c === "(" || c === ")") {
145 if (c === "|" && text[i + 1] === "|") i += 1;
146 endSegment();
147 } else if (c === "&" && text[i - 1] !== ">" && text[i + 1] !== ">") {
148 // `&&` and a lone background `&` both end a command; `2>&1` and `&>` are redirections.
149 if (text[i + 1] === "&") i += 1;
150 endSegment();
151 } else if (/\s/.test(c)) {
152 endToken();
153 } else {
154 token += c;
155 inToken = true;
156 }
157 }
158 endSegment();
159 // An unclosed quote would hide everything after it, so fall back to the conservative
160 // split that treats every operator as a separator.
161 if (quote !== null) return [...out, ...naiveSegments(text)];
162 return out;
163}
164
165function naiveSegments(text: string): string[][] {
166 return text
167 .split(/&&|\|\||;|\||\n|\(|\)|(?<![>])&(?![>])/)
168 .map((s) =>
169 s
170 .trim()
171 .split(/\s+/)
172 .filter(Boolean)
173 .map((t) => t.replace(/^['"]|['"]$/g, "")),
174 )
175 .filter((t) => t.length > 0);
176}
177
178// Wrapper commands, the options they are known to read a value for, and the options they are
179// known to read as flags. An option on neither list is read both ways and every reading is
180// checked, so an option this guard has not heard of cannot hide the command. `--` ends the
181// wrapper's options.
182const WRAPPER_VALUE_OPTIONS = new Map<string, ReadonlySet<string>>([
183 ["env", new Set(["-u", "--unset", "-C", "--chdir"])],
184 [
185 "sudo",
186 new Set([
187 "-u",
188 "--user",
189 "-g",
190 "--group",
191 "-C",
192 "--close-from",
193 "-D",
194 "--chdir",
195 "--host",
196 "-p",
197 "--prompt",
198 "-R",
199 "--chroot",
200 "-r",
201 "--role",
202 "-t",
203 "--type",
204 "-T",
205 "--command-timeout",
206 "-U",
207 "--other-user",
208 ]),
209 ],
210 ["exec", new Set(["-a"])],
211 ["time", new Set(["-f", "--format", "-o", "--output"])],
212]);
213
214const WRAPPER_FLAGS = new Map<string, ReadonlySet<string>>([
215 ["env", new Set(["-i", "-0", "-v", "--ignore-environment", "--null", "--debug"])],
216 [
217 "sudo",
218 new Set([
219 "-A",
220 "--askpass",
221 "-B",
222 "--bell",
223 "-b",
224 "--background",
225 "-E",
226 "--preserve-env",
227 "-e",
228 "--edit",
229 "-H",
230 "--set-home",
231 "-i",
232 "--login",
233 "-K",
234 "--remove-timestamp",
235 "-k",
236 "--reset-timestamp",
237 "-l",
238 "--list",
239 "-N",
240 "--no-update",
241 "-n",
242 "--non-interactive",
243 "-P",
244 "--preserve-groups",
245 "-S",
246 "--stdin",
247 "-s",
248 "--shell",
249 "-V",
250 "-v",
251 "--validate",
252 ]),
253 ],
254 ["exec", new Set(["-c", "-l"])],
255 ["time", new Set(["-p", "--portability", "-v", "--verbose", "-q", "--quiet", "-a", "--append"])],
256]);
257
258/** Splits a string into words the way a shell would, removing quotes (`env -S`). */
259function shellWords(text: string): string[] {
260 return segments(text, false).flat();
261}
262
263/**
264 * A shell assignment word: `VAR=value`, `VAR+=value`, and the subscripted `a[i]=` / `a[i]+=`
265 * forms (Bash rejects a subscript in a command prefix but still runs the command after it).
266 */
267const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*(\[[^\]]*\])?\+?=/;
268
269/**
270 * True when `word` is an assignment the wrapper `head` consumes itself, so it does not end the
271 * wrapper: sudo takes `VAR=value` among its options (`sudo VAR=x -u root cmd`), and GNU env reads
272 * any operand holding `=` as NAME=VALUE (`env 1=x cmd`), not only a shell identifier.
273 */
274function isWrapperAssignment(head: string, word: string): boolean {
275 if (head === "sudo") return ASSIGNMENT.test(word);
276 return head === "env" && !word.startsWith("-") && word.includes("=");
277}
278
279/** More wrapper readings or parse steps than this make the command uncheckable. */
280const MAX_PREFIX_STEPS = 512;
281
282/** True when long option `option` abbreviates a `--name` in `set` (getopt_long prefixes). */
283function longIn(option: string, set: ReadonlySet<string>): boolean {
284 return [...set].some((v) => v.startsWith("--") && longOpt(option, v.slice(2)));
285}
286
287/**
288 * Every reading of a command once leading `VAR=value` assignments and `sudo`/`env`/`exec`/`time`
289 * wrappers with their own options are dropped, so `env -i git push --force` is checked as
290 * `git push --force`. `env -S "<cmd>"` (`--split-string`) runs its argument as the command, so
291 * that argument is split and read again. A short-option cluster (`sudo -Eu runner`) is read
292 * letter by letter: a value-taking letter takes the rest of the cluster as its value, or the
293 * next word when it is last. An option the guard does not classify yields two readings, one
294 * where it is a flag and one where it takes a value. Returns null when there are too many
295 * readings to check.
296 */
297function prefixReadings(tokens: string[], onSplit?: (split: string) => void): string[][] | null {
298 const out: string[][] = [];
299 const seen = new Set<string>();
300 let steps = 0;
301
302 const visit = (words: string[]): void => {
303 if ((steps += 1) > MAX_PREFIX_STEPS) return;
304 let rest = words;
305 while (rest[0] !== undefined && ASSIGNMENT.test(rest[0])) rest = rest.slice(1);
306 const key = rest.join("\u0000");
307 if (seen.has(key)) return;
308 seen.add(key);
309 const head = rest[0];
310 const values = head === undefined ? undefined : WRAPPER_VALUE_OPTIONS.get(head);
311 if (head === undefined || values === undefined) {
312 out.push(rest);
313 return;
314 }
315 const flags = WRAPPER_FLAGS.get(head) ?? new Set<string>();
316 const split = (text: string, next: number): void => {
317 onSplit?.(text);
318 // GNU env puts the split words back in place of `-S` and keeps parsing them as its own
319 // options, so `env -S '-- git push -f'` runs the push: parse them as env options again.
320 visit([head, ...shellWords(text), ...rest.slice(next)]);
321 };
322
323 // Each option position is read once, so the two readings of every unknown option keep the
324 // walk linear in the number of words instead of doubling with each one.
325 const walked = new Set<string>();
326 const options = (i: number): void => {
327 if (walked.has(`${i}`) || (steps += 1) > MAX_PREFIX_STEPS) return;
328 walked.add(`${i}`);
329 const option = rest[i];
330 if (option === undefined) return visit(rest.slice(i));
331 if (isWrapperAssignment(head, option)) return options(i + 1);
332 if (!option.startsWith("-") || option === "-") {
333 // GNU env reads a lone `-` as `-i`; for the others it is the command.
334 if (option === "-" && head === "env") return options(i + 1);
335 return visit(rest.slice(i));
336 }
337 if (option === "--") {
338 // `--` ends the wrapper's options, not its assignments: `env -- 1=x cmd` still sets `1=x`.
339 let j = i + 1;
340 while (j < rest.length && isWrapperAssignment(head, rest[j]!)) j += 1;
341 return visit(rest.slice(j));
342 }
343 if (option.startsWith("--")) {
344 // Long options match by unambiguous prefix, as getopt_long does (`--spli`, `--us`).
345 const eq = option.indexOf("=");
346 if (head === "env" && longOpt(option, "split-string")) {
347 return eq >= 0 ? split(option.slice(eq + 1), i + 1) : split(rest[i + 1] ?? "", i + 2);
348 }
349 if (eq >= 0) return options(i + 1);
350 const value = longIn(option, values);
351 const flag = longIn(option, flags);
352 if (!value || flag) options(i + 1);
353 if (value || !flag) options(i + 2);
354 return;
355 }
356 letters(i, 1);
357 };
358
359 // A single-dash option is read letter by letter, whatever follows the first letter: an
360 // attached value can hold any character (`env -S'git push -f'`, `sudo -urunner`).
361 const letters = (i: number, k: number): void => {
362 if (walked.has(`${i}:${k}`) || (steps += 1) > MAX_PREFIX_STEPS) return;
363 walked.add(`${i}:${k}`);
364 const option = rest[i]!;
365 if (k >= option.length) return options(i + 1);
366 const letter = `-${option[k]}`;
367 const attached = option.slice(k + 1);
368 if (head === "env" && letter === "-S") {
369 return attached !== "" ? split(attached, i + 1) : split(rest[i + 1] ?? "", i + 2);
370 }
371 const value = values.has(letter);
372 const flag = flags.has(letter);
373 if (!value || flag) letters(i, k + 1);
374 if (value || !flag) options(attached === "" ? i + 2 : i + 1);
375 };
376
377 options(1);
378 };
379
380 visit(tokens);
381 return steps > MAX_PREFIX_STEPS ? null : out;
382}
383
384/** True when a short-option cluster such as `-uf` sets `flag` before any value-taking letter. */
385function clusterHas(token: string, flag: string, valueLetters: string): boolean {
386 if (!/^-[A-Za-z0-9]{2,}$/.test(token)) return false;
387 for (const c of token.slice(1)) {
388 if (c === flag) return true;
389 if (valueLetters.includes(c)) return false;
390 }
391 return false;
392}
393
394/** For `git -C dir push ...` returns ["push", ...]. */
395function gitArgs(tokens: string[]): string[] | null {
396 if (tokens[0] !== "git") return null;
397 let i = 1;
398 for (let t = tokens[i]; t !== undefined && t.startsWith("-"); t = tokens[i]) {
399 // -C <dir> and -c <k=v> consume a value
400 i += t === "-C" || t === "-c" ? 2 : 1;
401 }
402 return tokens.slice(i);
403}
404
405/**
406 * True when `token` is `--<full>` or an abbreviation of it, with or without `=value`. Git's
407 * option parser accepts any unambiguous prefix (`--al` is `--all`, `--force-w` is
408 * `--force-with-lease`); an ambiguous one is an error, so matching every prefix fails closed.
409 */
410function longOpt(token: string, full: string): boolean {
411 const m = /^--([A-Za-z0-9-]+)(=.*)?$/.exec(token);
412 return m !== null && m[1] !== undefined && full.startsWith(m[1]);
413}
414
415const FORCE_LONG = ["force", "force-with-lease", "force-if-includes"] as const;
416
417function checkGit(args: string[]): string | null {
418 const [sub, ...rest] = args;
419 if (sub === "push") {
420 if (
421 rest.some(
422 (t) =>
423 t === "-f" ||
424 FORCE_LONG.some((f) => longOpt(t, f)) ||
425 clusterHas(t, "f", "o") ||
426 (/^\+/.test(t) && !t.startsWith("+-")),
427 )
428 ) {
429 return "Force-push is forbidden (AGENTS.md › Git and merges: never force-push or rewrite history). Update the branch by merging from base.";
430 }
431 if (rest.some((t) => longOpt(t, "no-verify"))) {
432 return "`--no-verify` skips the repo's pre-commit/pre-push safety gates. Run the hooks and fix what they report.";
433 }
434 if (rest.some((t) => longOpt(t, "all") || longOpt(t, "mirror") || longOpt(t, "branches"))) {
435 return "Bulk pushes (`--all`, `--mirror`, `--branches`) include `main` and `verdant-grow-diary` when they exist locally (AGENTS.md: never push directly to them). Push your own task branch by name.";
436 }
437 const positional = rest.filter((t) => !t.startsWith("-"));
438 if (positional.slice(1).some((ref) => ref === ":" || ref === "+:")) {
439 return "The `:` refspec pushes every matching branch, including protected ones (AGENTS.md: never push directly to verdant-grow-diary or main). Push your own task branch by name.";
440 }
441 for (const ref of positional.slice(1)) {
442 const target = ref.includes(":") ? ref.split(":").pop()! : ref;
443 const branch = target.replace(/^refs\/heads\//, "");
444 if (target.includes("*")) {
445 // A wildcard refspec pushes every local branch it matches (`refs/heads/*:refs/heads/*`).
446 const glob = new RegExp(
447 `^${target
448 .split("*")
449 .map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&"))
450 .join(".*")}$`,
451 );
452 const hit = PROTECTED_BRANCHES.find((b) => glob.test(b) || glob.test(`refs/heads/${b}`));
453 if (hit) {
454 return `The wildcard refspec \`${ref}\` can push \`${hit}\` (AGENTS.md: never push directly to verdant-grow-diary or main). Push your own task branch by name.`;
455 }
456 continue;
457 }
458 if ((PROTECTED_BRANCHES as readonly string[]).includes(branch)) {
459 return `Pushing to \`${branch}\` is forbidden (AGENTS.md: never push directly to verdant-grow-diary or main). Push your own task branch and open a draft PR.`;
460 }
461 }
462 return null;
463 }
464 if (sub === "rebase" && !rest.some((t) => t === "--abort" || t === "--quit")) {
465 return "`git rebase` rewrites history (AGENTS.md: update branches by merging from base). Use `git merge origin/<base>`.";
466 }
467 // `git pull` short options cluster (`-qr`); -s, -X, -o, -S and -j take the rest as a value.
468 if (
469 sub === "pull" &&
470 rest.some((t) => t === "-r" || longOpt(t, "rebase") || clusterHas(t, "r", "sXoSj"))
471 ) {
472 return "`git pull --rebase` rewrites history. Use `git pull --no-rebase` or `git merge`.";
473 }
474 if (
475 sub === "commit" &&
476 rest.some((t) => longOpt(t, "no-verify") || t === "-n" || clusterHas(t, "n", "mFcCtSu"))
477 ) {
478 return "`git commit --no-verify` skips lint-staged, the full-project tsc and the docs-safety asserts. Commit without it and fix what fails.";
479 }
480 if (sub === "filter-branch" || sub === "filter-repo") {
481 return "History rewriting is forbidden (AGENTS.md › Git and merges).";
482 }
483 return null;
484}
485
486const LOCK_MSG =
487 "Dependency and lockfile changes are off-limits without Matthew's approval (AGENTS.md › Off-limits). Bun is canonical; never add/change deps with npm/yarn/pnpm.";
488
489function checkPackageManager(tokens: string[]): string | null {
490 const [pm, sub, ...rest] = tokens;
491 const positional = rest.filter((t) => !t.startsWith("-"));
492 if (pm === "npm") {
493 if (["add", "uninstall", "remove", "rm", "un", "update", "up", "upgrade"].includes(sub ?? ""))
494 return LOCK_MSG;
495 // A bare install (no package named) is the run skill's public-registry bootstrap; naming a package is a dependency change.
496 if ((sub === "install" || sub === "i") && positional.length > 0) return LOCK_MSG;
497 return null;
498 }
499 if (pm === "yarn" || pm === "pnpm") {
500 if (["add", "remove", "install", "i", "up", "upgrade", "update"].includes(sub ?? ""))
501 return LOCK_MSG;
502 return null;
503 }
504 if (pm === "bun") {
505 if (["add", "a", "remove", "rm", "update"].includes(sub ?? "")) return LOCK_MSG;
506 if (sub === "install" || sub === "i") {
507 if (positional.length > 0) return LOCK_MSG;
508 return "Don't run `bun install` here: bun.lock pins ~137 tarballs on a Lovable registry that 403s outside its sandbox. If node_modules exists, use it; otherwise follow the verified bootstrap in .claude/skills/run-verdant-grow-diary/SKILL.md.";
509 }
510 }
511 return null;
512}
513
514// Playwright options that take no value. Every other option written without `=` is assumed to
515// consume the next token, so an unlisted value (`--global-timeout 60000`, `--only-changed main`)
516// is never mistaken for a spec filter. Unknown flags fail closed: pass `--flag=value` instead.
517const PW_BOOLEAN_FLAGS = new Set([
518 "--debug",
519 "--fail-on-flaky-tests",
520 "--forbid-only",
521 "--fully-parallel",
522 "--headed",
523 "--help",
524 "-h",
525 "--ignore-snapshots",
526 "--last-failed",
527 "--list",
528 "--no-deps",
529 "--pass-with-no-tests",
530 "--quiet",
531 "--ui",
532 "-x",
533]);
534
535/** A spec filter the shell passes through unchanged: no expansion can make it disappear. */
536const PW_LITERAL_FILTER = /^[A-Za-z0-9._/:@+=-]+$/;
537
538const PW_DEBUG_MODES = new Set(["inspector", "cli"]);
539
540// pnpm and yarn global options that take the next word as their value when written without `=`
541// (`pnpm -C dir exec …`, `yarn --cwd dir exec …`). Any other leading option is read as a flag.
542const PM_GLOBAL_VALUE_OPTIONS = new Set([
543 "-C",
544 "--dir",
545 "-F",
546 "--filter",
547 "--filter-prod",
548 "--cwd",
549 "--reporter",
550 "--loglevel",
551 "--workspace-concurrency",
552]);
553
554/**
555 * Every way `pnpm|yarn [global options] exec|dlx …` can be read: the words after `exec`/`dlx`
556 * for each reading. An option this guard does not know may take a value or not (`--test-pattern x`
557 * does), so both readings are kept and each is checked: unclassified options fail closed.
558 */
559function pmRunnerStarts(tokens: string[]): string[][] {
560 const starts: string[][] = [];
561 const seen = new Set<number>();
562 const walk = (i: number): void => {
563 if (seen.has(i)) return;
564 seen.add(i);
565 const t = tokens[i];
566 if (t === undefined) return;
567 if (t === "dlx" || t === "exec") {
568 starts.push(tokens.slice(i + 1));
569 return;
570 }
571 if (!t.startsWith("-")) return;
572 if (t.includes("=")) walk(i + 1);
573 else if (PM_GLOBAL_VALUE_OPTIONS.has(t)) walk(i + 2);
574 else {
575 walk(i + 1);
576 walk(i + 2);
577 }
578 };
579 walk(1);
580 return starts;
581}
582
583// Package-runner options (npx, bunx, `pnpm exec`) known to take no value, and known to take one.
584// Any other option written without `=` is read both ways, so neither reading can hide a command.
585const RUNNER_FLAGS = new Set([
586 "-y",
587 "--yes",
588 "--no",
589 "--bun",
590 "--silent",
591 "-s",
592 "-q",
593 "--quiet",
594 "--ignore-existing",
595 "--include-workspace-root",
596 "--workspaces",
597 "-ws",
598]);
599const RUNNER_VALUE_OPTIONS = new Set(["-p", "--package", "-w", "--workspace"]);
600
601/** One reading of a package-runner prefix: the command words it runs, or a shell call string. */
602type RunnerView = { tokens: string[] } | { call: string };
603
604/**
605 * Every reading of a package-runner prefix (`bunx`, `npx`, `bun x`, `pnpm dlx|exec`,
606 * `yarn dlx|exec`), or null when `tokens` is not one. `-c`/`--call` (and `-c=…`) give the
607 * command as one shell string, which may hold several commands (`a; git push -f`), so it is
608 * returned whole for checkBash to split and check like any other command line.
609 */
610function runnerViews(tokens: string[]): RunnerView[] | null {
611 const [a, b] = tokens;
612 let starts: string[][];
613 if (a === "bunx" || a === "npx") starts = [tokens.slice(1)];
614 else if (a === "bun" && b === "x") starts = [tokens.slice(2)];
615 else if (a === "pnpm" || a === "yarn") starts = pmRunnerStarts(tokens);
616 else return null;
617 if (starts.length === 0) return null;
618 const views: RunnerView[] = [];
619 for (const rest of starts) {
620 const seen = new Set<number>();
621 const walk = (i: number): void => {
622 if (seen.has(i)) return;
623 seen.add(i);
624 const t = rest[i];
625 if (t === undefined) return;
626 if (!t.startsWith("-")) {
627 views.push({ tokens: rest.slice(i) });
628 return;
629 }
630 if (t === "--") {
631 views.push({ tokens: rest.slice(i + 1) });
632 return;
633 }
634 if (t.startsWith("-c=") || t.startsWith("--call=")) {
635 views.push({ call: t.slice(t.indexOf("=") + 1) });
636 return;
637 }
638 if (t === "-c" || t === "--call") {
639 if (rest[i + 1] !== undefined) views.push({ call: rest[i + 1]! });
640 return;
641 }
642 if (t.includes("=") || RUNNER_FLAGS.has(t)) walk(i + 1);
643 else if (RUNNER_VALUE_OPTIONS.has(t)) walk(i + 2);
644 else {
645 walk(i + 1);
646 walk(i + 2);
647 }
648 };
649 walk(0);
650 }
651 return views;
652}
653
654/** The credential-free projects in `playwright.config.ts`, which install no global route mocks. */
655const PW_MOCKED_PROJECTS = ["chromium-mocked", "webkit-mocked"] as const;
656
657/** A `--project` value with nothing left for the shell to expand. */
658const PW_PROJECT_LITERAL = /^[A-Za-z0-9._/:@+=*-]+$/;
659
660/**
661 * True when a `--project` selector picks a mocked project, or cannot be read here (a word the
662 * shell can still expand), so an uncheckable selector is treated as mocked and fails closed. Playwright 1.62 compares names
663 * case-insensitively and reads `*` as a wildcard (`filterProjects` in `lib/runner/index.js`).
664 */
665function selectsMockedProject(selector: string): boolean {
666 // A selector the shell can still expand (`$P`, a substitution, `{a,b}`, `?`/`[…]` globs) is
667 // unknown here, so it fails closed. `*` stays: Playwright reads it as its own wildcard.
668 if (!PW_PROJECT_LITERAL.test(selector)) return true;
669 const lower = selector.toLowerCase();
670 if (!lower.includes("*")) return lower.includes("mocked");
671 const escaped = lower.split("*").map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
672 const pattern = new RegExp(`^${escaped.join(".*")}$`);
673 return PW_MOCKED_PROJECTS.some((name) => pattern.test(name));
674}
675
676function checkPlaywright(t: string[]): string | null {
677 if (t[0] !== "playwright" || t[1] !== "test") return null;
678 const args = t.slice(2);
679 const projects: string[] = [];
680 let specs = 0;
681 for (let i = 0; i < args.length; i += 1) {
682 const a = args[i] ?? "";
683 // Words after `--` do not narrow the run (Playwright 1.62.1 `--list -- --project=x` lists every
684 // project's tests), so neither they nor anything later counts as a project or a spec.
685 if (a === "--") break;
686 if (a.startsWith("--project=")) {
687 projects.push(a.slice("--project=".length));
688 continue;
689 }
690 if (a === "--project") {
691 // `--project <project-name...>` is variadic: every word up to the next option is a project
692 // name, a spec path included (Playwright then reports that "project" as not found).
693 while (i + 1 < args.length && !(args[i + 1] ?? "-").startsWith("-"))
694 projects.push(args[++i]!);
695 continue;
696 }
697 if (a.startsWith("-")) {
698 // `--debug [mode]` takes an optional mode (Playwright 1.62: `inspector` or `cli`).
699 if (a === "--debug" && PW_DEBUG_MODES.has(args[i + 1] ?? "")) {
700 i += 1;
701 continue;
702 }
703 if (!a.includes("=") && !PW_BOOLEAN_FLAGS.has(a) && !(args[i + 1] ?? "-").startsWith("-")) {
704 i += 1;
705 }
706 continue;
707 }
708 // An empty filter matches every test, and the shell can expand a word to nothing (`$VAR`,
709 // a substitution, `{,}`, a glob under nullglob), so only a plain literal word counts.
710 if (PW_LITERAL_FILTER.test(a)) specs += 1;
711 }
712 if (specs > 0) return null;
713 if (projects.length === 0) {
714 return "`playwright test` with no `--project` runs every project, `chromium-mocked` included, and without a spec filter that can reach real Supabase (the mocked projects install no global route mocks). Pass an explicit spec path.";
715 }
716 const project = projects.find(selectsMockedProject);
717 if (project !== undefined) {
718 return `\`--project=${project}\` without a spec filter can reach real Supabase (the mocked projects install no global route mocks). Pass an explicit spec path.`;
719 }
720 return null;
721}
722
723const PFLAG_TRUE = /^(1|t|T|TRUE|true|True)$/;
724
725/** The effective value of a GitHub CLI `--undo` boolean flag across all its occurrences. */
726function undoIsSet(tokens: string[]): boolean {
727 let undo = false;
728 for (const t of tokens) {
729 // After `--` every word is positional: `gh pr ready -- --undo` selects a branch named `--undo`.
730 if (t === "--") break;
731 if (t === "--undo") undo = true;
732 else if (t.startsWith("--undo=")) undo = PFLAG_TRUE.test(t.slice("--undo=".length));
733 }
734 return undo;
735}
736
737const PROD_MSG =
738 "Production database changes, deploys, promotion and rollback are Matthew's decisions (AGENTS.md › Release and Environment Rules). Prepare a release packet or escalation instead.";
739
740function checkProductionOps(tokens: string[], whole: string): string | null {
741 const [cmd, a, b] = tokens;
742 if (cmd === "supabase") {
743 if (a === "db" && (b === "push" || (b === "reset" && tokens.includes("--linked"))))
744 return PROD_MSG;
745 if (a === "migration" && (b === "up" || b === "repair")) return PROD_MSG;
746 if (a === "functions" && b === "deploy") return PROD_MSG;
747 if (a === "secrets" && (b === "set" || b === "unset")) return PROD_MSG;
748 }
749 if (cmd === "vercel") {
750 if (tokens.includes("--prod") || ["promote", "rollback", "alias"].includes(a ?? ""))
751 return PROD_MSG;
752 }
753 // `gh pr ready --undo` converts a PR back to draft, which the drafts-remain-draft rule wants.
754 // `--undo` is a pflag boolean: the last occurrence wins and `--undo=false` turns it off.
755 if (cmd === "gh" && a === "pr" && (b === "merge" || (b === "ready" && !undoIsSet(tokens)))) {
756 return "Merging and marking PRs ready belong to Chemdawg after 35/35 required checks plus an independent exact-head PASS (AGENTS.md). Drafts remain draft.";
757 }
758 if (
759 (cmd === "psql" || cmd === "pg_dump" || cmd === "pg_restore") &&
760 whole.includes(PRODUCTION_PROJECT_REF)
761 ) {
762 return PROD_MSG;
763 }
764 return null;
765}
766
767/** Runner nesting deeper than this is not unwrapped further; the command is refused instead. */
768const MAX_RUNNER_DEPTH = 8;
769
770const RUNNER_DEPTH_MSG = `Package runners nested more than ${MAX_RUNNER_DEPTH} deep cannot be checked here. Run the inner command directly.`;
771
772const PREFIX_STEPS_MSG =
773 "This command's wrapper options (env, sudo, exec, time) have too many possible readings to check here. Write the command out without the wrapper options.";
774
775/** The whole Bash rule set. `depth` counts package runners already unwrapped. */
776export function checkBash(command: string, depth = 0): string | null {
777 for (const raw of segments(command)) {
778 const reason = checkCommand(raw, command, depth);
779 if (reason) return reason;
780 }
781 return null;
782}
783
784/** Checks one simple command, then every command a package runner prefix can run. */
785function checkCommand(raw: string[], whole: string, depth: number): string | null {
786 if (depth > MAX_RUNNER_DEPTH) return RUNNER_DEPTH_MSG;
787 let expands = false;
788 const readings = prefixReadings(raw, (split) => {
789 // GNU `env -S` has its own grammar beyond quotes: `${NAME}` expansion, backslash
790 // escapes (`\_` separates arguments, `\c` ends the string) and `#` comments. And the
791 // operand reaches this point with its quotes already removed, so a brace, glob,
792 // backtick or `~` here may be one Bash expands before env sees it
793 // (`env -S {git,push,-f}`). This guard models neither, so any of those makes the
794 // wrapped command uncheckable.
795 if (/[\\$#{}*?[\]`~]/.test(split)) expands = true;
796 });
797 if (expands) {
798 return "`env -S` with `$`, `\\`, `#`, braces, globs, backticks or `~` uses expansion, escapes or comments this guard cannot follow, so the command it runs cannot be checked here. Write the command out without `env -S`.";
799 }
800 if (readings === null) return PREFIX_STEPS_MSG;
801 for (const tokens of readings) {
802 const reason = checkTokens(tokens, whole, depth);
803 if (reason) return reason;
804 }
805 return null;
806}
807
808/** Checks one reading of a simple command, then every command a package runner can run. */
809function checkTokens(tokens: string[], whole: string, depth: number): string | null {
810 if (tokens.length === 0) return null;
811 const git = gitArgs(tokens);
812 const reason =
813 (git ? checkGit(git) : null) ??
814 checkPackageManager(tokens) ??
815 checkPlaywright(tokens) ??
816 checkProductionOps(tokens, whole);
817 if (reason) return reason;
818 // A package runner can carry any command, another runner included (`pnpm exec npx -c '…'`,
819 // `npx -c 'a; git push -f'`): check every reading of it with the whole rule set.
820 for (const view of runnerViews(tokens) ?? []) {
821 const inner =
822 "call" in view
823 ? checkBash(view.call, depth + 1)
824 : checkCommand(view.tokens, whole, depth + 1);
825 if (inner) return inner;
826 }
827 return null;
828}
829
830/** Normalises a path to its repo-relative form by anchoring on known roots. */
831export function repoRelative(filePath: string, repoRoot?: string | null): string {
832 const p = filePath.replace(/\\/g, "/");
833 // With the repository root known, strip it exactly: the heuristic below would anchor on the
834 // first `/src/` or `/docs/` anywhere, which is wrong for a checkout under ~/src/ or ~/docs/.
835 const root = repoRoot ? repoRoot.replace(/\\/g, "/").replace(/\/+$/, "") : "";
836 if (root && p.startsWith(`${root}/`)) return p.slice(root.length + 1);
837 for (const root of ["src/", "supabase/", "scripts/", "docs/", "e2e/", "config/", ".github/"]) {
838 const i = p.indexOf(`/${root}`);
839 if (i >= 0) return p.slice(i + 1);
840 if (p.startsWith(root)) return p;
841 }
842 return p.replace(/^.*\//, "");
843}
844
845const GENERATED = [
846 /^src\/routeTree\.gen\.ts$/,
847 /^src\/integrations\/supabase\/types\.ts$/,
848 /^supabase\/functions\/mcp\/index\.ts$/,
849 /^supabase\/functions\/_shared\/lib\//,
850];
851
852const LOCKFILES = new Set([
853 "bun.lock",
854 "bun.lockb",
855 "package-lock.json",
856 "yarn.lock",
857 "pnpm-lock.yaml",
858]);
859
860export const MIGRATION_PATH = /^supabase\/migrations\/[^/]+\.sql$/;
861
862/**
863 * Static file-edit rules. Published-migration immutability needs a git lookup,
864 * so it is decided in register.ts with `isPublished`.
865 */
866export function checkFileEdit(filePath: string, repoRoot?: string | null): string | null {
867 const rel = repoRelative(filePath, repoRoot);
868 if (GENERATED.some((re) => re.test(rel))) {
869 return `\`${rel}\` is generated — never hand-edit it (CLAUDE.md › Conventions). Regenerate it with the repo's tooling.`;
870 }
871 if (LOCKFILES.has(rel)) return LOCK_MSG;
872 return null;
873}
874
875export const PUBLISHED_MIGRATION_MSG = (rel: string) =>
876 `\`${rel}\` is a published migration and is permanent history (AGENTS.md › Migration Immutability). Ship a new additive migration, or check config/local-supabase-replay-compatibility.json.`;
877
878/**
879 * MCP tools that publish, merge, promote or write production, keyed by service and tool name.
880 * The server segment of `mcp__<server>__<tool>` varies by how a connector is installed
881 * (`Supabase`, `supabase`, `claude_ai_Supabase`), so it is matched by service, not exactly.
882 */
883const MCP_DENY: Record<string, string> = {
884 github__merge_pull_request: "merge",
885 github__enable_pr_auto_merge: "merge",
886 supabase__apply_migration: "prod",
887 supabase__execute_sql: "prod",
888 supabase__deploy_edge_function: "prod",
889 supabase__merge_branch: "prod",
890 supabase__reset_branch: "prod",
891 supabase__delete_branch: "prod",
892 supabase__pause_project: "prod",
893 supabase__restore_project: "prod",
894 vercel__request_promote: "prod",
895 vercel__request_rollback: "prod",
896 vercel__create_deployment: "prod",
897 vercel__start_rolling_release: "prod",
898 vercel__complete_rolling_release: "prod",
899 vercel__approve_rolling_release_stage: "prod",
900 lovable__deploy_project: "prod",
901};
902
903const MCP_SERVICES = ["github", "supabase", "vercel", "lovable"] as const;
904
905/** `mcp__claude_ai_Supabase__execute_sql` → `supabase__execute_sql`; null for other servers. */
906function mcpServiceTool(tool: string): string | null {
907 const m = /^mcp__(.+?)__([^_].*)$/.exec(tool);
908 if (!m || !m[1] || !m[2]) return null;
909 const server = m[1].toLowerCase();
910 // The service must be a whole `_`- or `-`-separated part of the server name, so
911 // `claude-ai-supabase` and `supabase_prod` match while `notsupabase` does not.
912 const parts = server.split(/[_-]/);
913 const service = MCP_SERVICES.find((s) => parts.includes(s));
914 return service ? `${service}__${m[2]}` : null;
915}
916
917export function checkMcp(tool: string, input: Record<string, unknown>): string | null {
918 const key = mcpServiceTool(tool);
919 const kind = key ? MCP_DENY[key] : undefined;
920 if (kind === "merge") {
921 return "Merging belongs to Chemdawg after 35/35 required checks plus an independent exact-head PASS (AGENTS.md).";
922 }
923 if (kind === "prod") return PROD_MSG;
924 if (key === "github__update_pull_request" && input.draft === false) {
925 return "Drafts remain draft (AGENTS.md › Git and merges). Readiness is decided by the merge owner.";
926 }
927 return null;
928}
929
930/** CLAUDE.md › Check-in cadence: the prompt cache lives 60 min; arm at <= 55. */
931export const CHECK_IN_MAX_MINUTES = 55;
932
933export function checkInWarning(tool: string, input: Record<string, unknown>): string | null {
934 if (!/send_later$/.test(tool)) return null;
935 const minutes = typeof input.delay_minutes === "number" ? input.delay_minutes : null;
936 if (minutes !== null && minutes > CHECK_IN_MAX_MINUTES && minutes <= 75) {
937 return `verdant-guard: this check-in is armed at ${minutes} min. CLAUDE.md asks for <= ${CHECK_IN_MAX_MINUTES} min so the wake lands inside the 60-minute prompt cache; a 56–75 min gap is usually an accidental near-miss.`;
938 }
939 return null;
940}
941