Skip to content

Practical patterns, starters & CLI tools for loop engineering with AI coding agents. Design systems that prompt and orchestrate agents (inspired by Addy Osmani and Boris Cherny). Includes loop-audit, loop-init, loop-cost.

feat(loop-gate): mechanical enforcement of the path denylist + auto-merge allowlist (#291)

JonyT Agenticc3b1363f4667
diff --git a/LOOP.md b/LOOP.md
index b84a086..bc7170e 100644
--- a/LOOP.md
+++ b/LOOP.md
@@ -63,6 +63,7 @@ See [docs/multi-loop.md](docs/multi-loop.md). Priority: CI Sweeper → PR Babysi
- No auto-merge on main except trivial dependency patches (allowlist + verifier)
- Denylist: showcase HTML/CSS, core primitives docs, audit scoring logic without human review
- Live loop state: `STATE.md` at repo root
+- `loop-gate check` mechanically enforces the denylist + auto-merge allowlist above from `gate.yaml`; see `tools/loop-gate`
## How to run locally
diff --git a/README.md b/README.md
index e28e517..00f3619 100644
--- a/README.md
+++ b/README.md
@@ -94,6 +94,7 @@ For developers using Grok, Claude Code, Codex, Cursor, and other AI coding agent
| [loop-context](tools/loop-context/) | Stateful memory manager + circuit breaker for long runs — `npx @cobusgreyling/loop-context --check --ledger run.json` |
| [loop-mcp-server](tools/mcp-server/) | MCP runtime lookup for patterns, skills, state — `npx @cobusgreyling/loop-mcp-server` |
| [loop-worktree](tools/loop-worktree/) | Manage isolated git worktrees per fix attempt — `npx @cobusgreyling/loop-worktree create --run-id <id> --pattern <p>` |
+| [loop-gate](tools/loop-gate/) | Mechanical enforcement of the path denylist + auto-merge allowlist from `gate.yaml` — `npx @cobusgreyling/loop-gate check --action auto-merge --paths <f1,f2,...>` |
| [Goal Engineering](https://github.com/cobusgreyling/goal-engineering) | **Companion:** loops discover, goals finish — `/goal` + [stack cookbook](https://github.com/cobusgreyling/goal-engineering/blob/main/docs/stack-cookbook.md) (`npx @cobusgreyling/goal doctor .`) |
| [Stories](stories/) | Real wins and honest failures |
| [Contributor quickstart](https://github.com/cobusgreyling/loop-engineering/discussions/123) | **Help wanted:** 21 scoped `good first issues` — comment *I'll take this* to get assigned |
diff --git a/docs/safety.md b/docs/safety.md
index ea1b3dc..06353dd 100644
--- a/docs/safety.md
+++ b/docs/safety.md
@@ -25,6 +25,12 @@ Encode in `minimal-fix` and implementer skills:
> Do not modify files matching the denylist. Escalate to human with context.
+[`loop-gate`](../tools/loop-gate) enforces this denylist (and the auto-merge
+allowlist below) mechanically from `gate.yaml` instead of relying on the
+loop to have read this file: `loop-gate check --action <type> --paths <changed files>`
+exits `2` to escalate, `0` to proceed — same convention `loop-context --check`
+already uses, so control scripts chain both.
+
## Auto-Merge Policy
**Default: no auto-merge.**
diff --git a/gate.yaml b/gate.yaml
new file mode 100644
index 0000000..60da165
--- /dev/null
+++ b/gate.yaml
@@ -0,0 +1,25 @@
+# Machine-readable twin of docs/safety.md's Path Denylist and Auto-Merge
+# Policy sections. Used by tools/loop-gate. Keep in sync with docs/safety.md
+# when either changes.
+version: 1
+
+denylist:
+ - ".env"
+ - ".env.*"
+ - "**/secrets/**"
+ - "**/credentials/**"
+ - "**/*_key*"
+ - "**/*_secret*"
+ - ".terraform/**"
+ - "k8s/production/**"
+ - "**/migrations/**"
+ - "auth/**"
+ - "payments/**"
+ - "billing/**"
+
+maxFiles: 10
+
+autoMergeAllowlist:
+ - "docs/**"
+ - "**/*.md"
+ - "**/*.test.mjs"
diff --git a/templates/gate.yaml.template b/templates/gate.yaml.template
new file mode 100644
index 0000000..0eb433f
--- /dev/null
+++ b/templates/gate.yaml.template
@@ -0,0 +1,27 @@
+# Machine-readable twin of your project's safety policy (see docs/safety.md
+# in loop-engineering for the prose this is meant to mirror). Copy to your
+# repo root as gate.yaml and adjust denylist/autoMergeAllowlist for your
+# project's own sensitive paths.
+version: 1
+
+denylist:
+ - ".env"
+ - ".env.*"
+ - "**/secrets/**"
+ - "**/credentials/**"
+ - "**/*_key*"
+ - "**/*_secret*"
+ - ".terraform/**"
+ - "k8s/production/**"
+ - "**/migrations/**"
+ - "auth/**"
+ - "payments/**"
+ - "billing/**"
+
+# Escalate instead of auto-merging when a change touches more than this many files.
+maxFiles: 10
+
+# --action auto-merge only proceeds if every changed path matches one of these.
+autoMergeAllowlist:
+ - "docs/**"
+ - "**/*.md"
diff --git a/tools/loop-gate/README.md b/tools/loop-gate/README.md
new file mode 100644
index 0000000..821d68d
--- /dev/null
+++ b/tools/loop-gate/README.md
@@ -0,0 +1,72 @@
+# loop-gate
+
+Mechanical enforcement of static safety policy — the code behind `docs/safety.md`'s Path Denylist and Auto-Merge Policy, and `LOOP.md`'s *"No auto-merge on main except trivial dependency patches"* / *"Denylist... without human review"* rules. Nothing evaluated a proposed change against that prose before; `loop-gate` does.
+
+Deliberately has **no knowledge of run history**. Stagnation, repeated failures, and token/daily budgets already belong to [`loop-context`](../loop-context)'s circuit breaker — `loop-gate` only looks at *what* is being proposed (which paths, what action type), not *how the run has behaved so far*. Chain the two:
+
+```bash
+loop-context --check --ledger run.json ... || exit 2 # run-history based
+loop-gate check --action auto-merge --paths a.ts,b.ts || exit 2 # policy based
+do-the-merge
+```
+
+## Install & Run
+
+```bash
+npx @cobusgreyling/loop-gate check --action auto-merge --paths docs/guide.md
+```
+
+**From this repo:**
+
+```bash
+cd tools/loop-gate
+npm install
+npm test
+```
+
+## Usage
+
+```bash
+loop-gate check --action <commit|merge|auto-merge> --paths <f1,f2,...> [--gate-file gate.yaml] [--json]
+```
+
+| Flag | Default | Meaning |
+|------|---------|---------|
+| `--action <commit\|merge\|auto-merge>` | required | What the loop is about to do |
+| `--paths <f1,f2,...>` | required | Comma-separated changed file paths |
+| `--gate-file <path>` | `gate.yaml` (cwd) | Policy file to evaluate against |
+| `--json` | off | Machine-readable decision output |
+
+Exit codes: `0` allowed · `2` escalate · `1` error (bad flags, missing/invalid config).
+
+## Policy file
+
+`gate.yaml` is the machine-readable twin of `docs/safety.md` — see [`templates/gate.yaml.template`](../../templates/gate.yaml.template) to scaffold your own, or this repo's own dogfood [`gate.yaml`](../../gate.yaml):
+
+```yaml
+version: 1
+denylist:
+ - ".env"
+ - "**/secrets/**"
+ - "auth/**"
+maxFiles: 10
+autoMergeAllowlist:
+ - "docs/**"
+ - "**/*.md"
+```
+
+Checked in order (first match wins, same "most specific trigger first" convention `loop-context`'s circuit breaker uses):
+
+1. **`denylist`** — any changed path matching a glob here escalates, regardless of `--action`.
+2. **`maxFiles`** — more changed paths than this escalates (matches `docs/safety.md`'s "Changes touching >N files" human gate).
+3. **`autoMergeAllowlist`** — only checked when `--action auto-merge`; every changed path must match one of these globs, or it escalates.
+
+Glob matching is via [`minimatch`](https://www.npmjs.com/package/minimatch) (the same semantics `.gitignore`-style globs use — `**` matches across path segments).
+
+## What this does not do
+
+- Does not read a run ledger, and never will — that keeps it decoupled from `loop-context` at the source level, the same way `loop-worktree` and `loop-context` stay independent while still being paired by convention in a control script.
+- Does not produce its own escalation summary format — fold its JSON decision into whatever your control script already assembles from `loop-context --inject` when escalating to a human.
+- Does not enforce anything by itself — like `loop-worktree`'s locks, this is advisory: a control script that skips calling `loop-gate` is not physically blocked. The mechanism is only as good as the scripts that call it.
+
+See [docs/safety.md](../../docs/safety.md) for the policy this codifies, and [docs/primitives.md](../../docs/primitives.md) for where safety gates fit in the Five Building Blocks + Memory model.
diff --git a/tools/loop-gate/dist/cli.d.ts b/tools/loop-gate/dist/cli.d.ts
new file mode 100644
index 0000000..b798801
--- /dev/null
+++ b/tools/loop-gate/dist/cli.d.ts
@@ -0,0 +1,2 @@
+#!/usr/bin/env node
+export {};
diff --git a/tools/loop-gate/dist/cli.js b/tools/loop-gate/dist/cli.js
new file mode 100644
index 0000000..d2c71f3
--- /dev/null
+++ b/tools/loop-gate/dist/cli.js
@@ -0,0 +1,80 @@
+#!/usr/bin/env node
+import { checkGate, loadGateConfig, assertValidAction, } from './gate.js';
+function parseFlags(argv) {
+ const flags = { help: false, gateFile: 'gate.yaml', json: false };
+ for (let i = 0; i < argv.length; i++) {
+ const a = argv[i];
+ if (a === '--help' || a === '-h')
+ flags.help = true;
+ else if (a === '--action')
+ flags.action = argv[++i];
+ else if (a === '--paths')
+ flags.paths = argv[++i];
+ else if (a === '--gate-file')
+ flags.gateFile = argv[++i];
+ else if (a === '--json')
+ flags.json = true;
+ }
+ return flags;
+}
+const HELP = `loop-gate — mechanical enforcement of static safety policy
+
+Evaluates a proposed change (action type + changed paths) against
+gate.yaml's denylist, max-files, and auto-merge allowlist. No knowledge of
+run history — pair with loop-context --check for stagnation/budget triggers.
+
+Usage:
+ loop-gate check --action <commit|merge|auto-merge> --paths <f1,f2,...> [options]
+
+Options:
+ --action <commit|merge|auto-merge> What the loop is about to do
+ --paths <f1,f2,...> Comma-separated changed file paths
+ --gate-file <path> Policy file (default: gate.yaml)
+ --json Machine-readable output
+ -h, --help This help
+
+Exit codes: 0 allowed · 2 escalate · 1 error
+
+Example:
+ loop-gate check --action auto-merge --paths $(git diff --name-only | tr '\\n' ',')
+`;
+async function main() {
+ const argv = process.argv.slice(2);
+ const command = argv[0];
+ if (!command || command === '--help' || command === '-h') {
+ console.log(HELP);
+ return command ? 0 : 1;
+ }
+ if (command !== 'check') {
+ console.error(`Unknown command "${command}".\n\n${HELP}`);
+ return 1;
+ }
+ const flags = parseFlags(argv.slice(1));
+ if (flags.help) {
+ console.log(HELP);
+ return 0;
+ }
+ if (!flags.action || !flags.paths) {
+ throw new Error('check requires --action and --paths.');
+ }
+ assertValidAction(flags.action);
+ const config = await loadGateConfig(flags.gateFile);
+ const paths = flags.paths.split(',').map((p) => p.trim()).filter(Boolean);
+ if (paths.length === 0) {
+ throw new Error('--paths must contain at least one non-empty path.');
+ }
+ const decision = checkGate({ config, action: flags.action, paths });
+ if (flags.json) {
+ console.log(JSON.stringify(decision, null, 2));
+ }
+ else {
+ console.log(`${decision.allowed ? 'ALLOWED' : 'ESCALATE'} [${decision.trigger}] — ${decision.reason}`);
+ }
+ return decision.allowed ? 0 : 2;
+}
+main()
+ .then((code) => process.exit(code))
+ .catch((err) => {
+ console.error(err instanceof Error ? err.message : String(err));
+ process.exit(1);
+});
diff --git a/tools/loop-gate/dist/gate.d.ts b/tools/loop-gate/dist/gate.d.ts
new file mode 100644
index 0000000..0ee0306
--- /dev/null
+++ b/tools/loop-gate/dist/gate.d.ts
@@ -0,0 +1,45 @@
+/**
+ * Mechanical enforcement of static policy (path denylist, auto-merge
+ * allowlist, max changed files) — the machine-readable twin of
+ * docs/safety.md's prose. Deliberately has no knowledge of run history
+ * (stagnation, repeat failures): that already belongs to loop-context's
+ * circuit breaker and must not be duplicated here.
+ */
+export type Action = 'commit' | 'merge' | 'auto-merge';
+export declare const VALID_ACTIONS: Action[];
+export declare function assertValidAction(action: string): asserts action is Action;
+export interface GateConfig {
+ version: 1;
+ /** Glob patterns that must never be touched without human approval. */
+ denylist: string[];
+ /** Escalate when more than this many paths are in the proposed change. */
+ maxFiles?: number;
+ /** For --action auto-merge: every path must match one of these globs. */
+ autoMergeAllowlist?: string[];
+}
+export declare function loadGateConfig(file: string): Promise<GateConfig>;
+export type GateTrigger = 'ok' | 'denylist' | 'file-count' | 'not-allowlisted';
+export interface GateDecision {
+ allowed: boolean;
+ trigger: GateTrigger;
+ reason: string;
+ /** Paths responsible for the trigger (empty when trigger is 'ok'). */
+ matchedPaths: string[];
+}
+export interface CheckInput {
+ config: GateConfig;
+ action: Action;
+ paths: string[];
+}
+/**
+ * Evaluate a proposed change against static policy. Checks the cheapest and
+ * most severe condition first (denylist), then file-count, then the
+ * auto-merge allowlist — mirroring loop-context's checkCircuitBreaker
+ * "most specific trigger first" ordering.
+ *
+ * All glob matching uses minimatch's `dot: true` — without it, `*` never
+ * matches a path segment starting with `.`, so denylist entries like
+ * `**\/secrets/**` or `**\/*_key*` would silently miss `.secrets/prod.json`
+ * or `.aws_key`, exactly the paths a denylist most needs to catch.
+ */
+export declare function checkGate(input: CheckInput): GateDecision;
diff --git a/tools/loop-gate/dist/gate.js b/tools/loop-gate/dist/gate.js
new file mode 100644
index 0000000..e427547
--- /dev/null
+++ b/tools/loop-gate/dist/gate.js
@@ -0,0 +1,99 @@
+/**
+ * Mechanical enforcement of static policy (path denylist, auto-merge
+ * allowlist, max changed files) — the machine-readable twin of
+ * docs/safety.md's prose. Deliberately has no knowledge of run history
+ * (stagnation, repeat failures): that already belongs to loop-context's
+ * circuit breaker and must not be duplicated here.
+ */
+import { readFile } from 'node:fs/promises';
+import { parse } from 'yaml';
+import { minimatch } from 'minimatch';
+export const VALID_ACTIONS = ['commit', 'merge', 'auto-merge'];
+export function assertValidAction(action) {
+ if (!VALID_ACTIONS.includes(action)) {
+ throw new Error(`Invalid --action: ${action}. Use one of: ${VALID_ACTIONS.join(', ')}.`);
+ }
+}
+function isStringArray(value) {
+ return Array.isArray(value) && value.every((v) => typeof v === 'string');
+}
+export async function loadGateConfig(file) {
+ let raw;
+ try {
+ raw = await readFile(file, 'utf8');
+ }
+ catch {
+ throw new Error(`Gate config not found: ${file}. Create one (see templates/gate.yaml.template) or pass --gate-file <path>.`);
+ }
+ let parsed;
+ try {
+ parsed = parse(raw);
+ }
+ catch (err) {
+ throw new Error(`Invalid YAML in ${file}: ${err.message}`);
+ }
+ const config = parsed;
+ const invalid = (detail) => new Error(`Invalid gate config at ${file}: ${detail}`);
+ if (!config || config.version !== 1) {
+ throw invalid('expected { version: 1, denylist: string[], ... }.');
+ }
+ if (!isStringArray(config.denylist)) {
+ throw invalid('"denylist" must be an array of strings.');
+ }
+ if (config.maxFiles !== undefined && (typeof config.maxFiles !== 'number' || !Number.isFinite(config.maxFiles))) {
+ throw invalid('"maxFiles" must be a number.');
+ }
+ if (config.autoMergeAllowlist !== undefined && !isStringArray(config.autoMergeAllowlist)) {
+ throw invalid('"autoMergeAllowlist" must be an array of strings.');
+ }
+ return config;
+}
+/**
+ * Evaluate a proposed change against static policy. Checks the cheapest and
+ * most severe condition first (denylist), then file-count, then the
+ * auto-merge allowlist — mirroring loop-context's checkCircuitBreaker
+ * "most specific trigger first" ordering.
+ *
+ * All glob matching uses minimatch's `dot: true` — without it, `*` never
+ * matches a path segment starting with `.`, so denylist entries like
+ * `**\/secrets/**` or `**\/*_key*` would silently miss `.secrets/prod.json`
+ * or `.aws_key`, exactly the paths a denylist most needs to catch.
+ */
+export function checkGate(input) {
+ const { config, action, paths } = input;
+ const denylistHits = paths.filter((p) => config.denylist.some((glob) => minimatch(p, glob, { dot: true })));
+ if (denylistHits.length > 0) {
+ return {
+ allowed: false,
+ trigger: 'denylist',
+ reason: `${denylistHits.length} path(s) match the denylist: ${denylistHits.join(', ')}. Escalating for human review.`,
+ matchedPaths: denylistHits,
+ };
+ }
+ if (config.maxFiles !== undefined && paths.length > config.maxFiles) {
+ return {
+ allowed: false,
+ trigger: 'file-count',
+ reason: `${paths.length} changed file(s) exceeds the max-files threshold (${config.maxFiles}). Escalating for human review.`,
+ matchedPaths: paths,
+ };
+ }
+ if (action === 'auto-merge') {
+ const allowlist = config.autoMergeAllowlist ?? [];
+ const notAllowlisted = paths.filter((p) => !allowlist.some((glob) => minimatch(p, glob, { dot: true })));
+ if (notAllowlisted.length > 0) {
+ return {
+ allowed: false,
+ trigger: 'not-allowlisted',
+ reason: `${notAllowlisted.length} path(s) are not on the auto-merge allowlist: ${notAllowlisted.join(', ')}. Escalating for human review.`,
+ matchedPaths: notAllowlisted,
+ };
+ }
+ }
+ return {
+ allowed: true,
+ trigger: 'ok',
+ reason: 'Within policy — cleared to proceed.',
+ matchedPaths: [],
+ };
+}
diff --git a/tools/loop-gate/package-lock.json b/tools/loop-gate/package-lock.json
new file mode 100644
index 0000000..c0608cb
--- /dev/null
+++ b/tools/loop-gate/package-lock.json
@@ -0,0 +1,109 @@
+{
+ "name": "@cobusgreyling/loop-gate",
+ "version": "1.0.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "@cobusgreyling/loop-gate",
+ "version": "1.0.0",
+ "license": "MIT",
+ "dependencies": {
+ "minimatch": "^10.0.0",
+ "yaml": "^2.8.0"
+ },
+ "bin": {
+ "loop-gate": "dist/cli.js"
+ },
+ "devDependencies": {
+ "@types/node": "^20.0.0",
+ "typescript": "^5.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@types/node": {
+ "version": "20.19.43",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.43.tgz",
+ "integrity": "sha512-6oYBAi5ikg4Pl+kGsoYtawUMBT2zZMCvPNF7pVLnHZfd1zf38DRiWn/gT01RYCdUqkv7Fhr+C9ot4/tb+2sVvA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "undici-types": "~6.21.0"
+ }
+ },
+ "node_modules/balanced-match": {
+ "version": "4.0.4",
+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz",
+ "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==",
+ "license": "MIT",
+ "engines": {
+ "node": "18 || 20 || >=22"
+ }
+ },
+ "node_modules/brace-expansion": {
+ "version": "5.0.7",
+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.7.tgz",
+ "integrity": "sha512-7oFy703dxfY3/NLxC1fh2SUCQ0H9rmAY+5EpDVfXjUTTs+HEwR2nYaqLv+GWcTsumwxPfiz6CzCNkwXwBUwqCA==",
+ "license": "MIT",
+ "dependencies": {
+ "balanced-match": "^4.0.2"
+ },
+ "engines": {
+ "node": "18 || 20 || >=22"
+ }
+ },
+ "node_modules/minimatch": {
+ "version": "10.2.5",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz",
+ "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==",
+ "license": "BlueOak-1.0.0",
+ "dependencies": {
+ "brace-expansion": "^5.0.5"
+ },
+ "engines": {
+ "node": "18 || 20 || >=22"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
+ "node_modules/typescript": {
+ "version": "5.9.3",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "tsc": "bin/tsc",
+ "tsserver": "bin/tsserver"
+ },
+ "engines": {
+ "node": ">=14.17"
+ }
+ },
+ "node_modules/undici-types": {
+ "version": "6.21.0",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
+ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/yaml": {
+ "version": "2.9.0",
+ "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz",
+ "integrity": "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==",
+ "license": "ISC",
+ "bin": {
+ "yaml": "bin.mjs"
+ },
+ "engines": {
+ "node": ">= 14.6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/eemeli"
+ }
+ }
+ }
+}
diff --git a/tools/loop-gate/package.json b/tools/loop-gate/package.json
new file mode 100644
index 0000000..f13d72c
--- /dev/null
+++ b/tools/loop-gate/package.json
@@ -0,0 +1,59 @@
+{
+ "name": "@cobusgreyling/loop-gate",
+ "version": "1.0.0",
+ "description": "Mechanical enforcement of LOOP.md/docs/safety.md's path denylist and auto-merge allowlist — evaluate a proposed change against static policy and block or allow it.",
+ "type": "module",
+ "main": "dist/gate.js",
+ "exports": {
+ ".": "./dist/gate.js"
+ },
+ "bin": {
+ "loop-gate": "dist/cli.js"
+ },
+ "files": [
+ "dist",
+ "README.md"
+ ],
+ "scripts": {
+ "build": "tsc",
+ "test": "npm run build && node --test test/*.test.mjs",
+ "prepublishOnly": "npm test",
+ "start": "node dist/cli.js"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "keywords": [
+ "loop-engineering",
+ "ai-agents",
+ "coding-agents",
+ "safety",
+ "policy",
+ "auto-merge",
+ "claude-code",
+ "grok",
+ "devtools"
+ ],
+ "author": "Cobus Greyling",
+ "license": "MIT",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/cobusgreyling/loop-engineering.git",
+ "directory": "tools/loop-gate"
+ },
+ "homepage": "https://cobusgreyling.github.io/loop-engineering/",
+ "bugs": {
+ "url": "https://github.com/cobusgreyling/loop-engineering/issues"
+ },
+ "publishConfig": {
+ "access": "public"
+ },
+ "dependencies": {
+ "minimatch": "^10.0.0",
+ "yaml": "^2.8.0"
+ },
+ "devDependencies": {
+ "@types/node": "^20.0.0",
+ "typescript": "^5.0.0"
+ }
+}
diff --git a/tools/loop-gate/src/cli.ts b/tools/loop-gate/src/cli.ts
new file mode 100644
index 0000000..0ad250b
--- /dev/null
+++ b/tools/loop-gate/src/cli.ts
@@ -0,0 +1,95 @@
+#!/usr/bin/env node
+import {
+ checkGate,
+ loadGateConfig,
+ assertValidAction,
+ type Action,
+} from './gate.js';
+
+interface Flags {
+ help: boolean;
+ gateFile: string;
+ action?: string;
+ paths?: string;
+ json: boolean;
+}
+
+function parseFlags(argv: string[]): Flags {
+ const flags: Flags = { help: false, gateFile: 'gate.yaml', json: false };
+ for (let i = 0; i < argv.length; i++) {
+ const a = argv[i];
+ if (a === '--help' || a === '-h') flags.help = true;
+ else if (a === '--action') flags.action = argv[++i];
+ else if (a === '--paths') flags.paths = argv[++i];
+ else if (a === '--gate-file') flags.gateFile = argv[++i];
+ else if (a === '--json') flags.json = true;
+ }
+ return flags;
+}
+
+const HELP = `loop-gate — mechanical enforcement of static safety policy
+
+Evaluates a proposed change (action type + changed paths) against
+gate.yaml's denylist, max-files, and auto-merge allowlist. No knowledge of
+run history — pair with loop-context --check for stagnation/budget triggers.
+
+Usage:
+ loop-gate check --action <commit|merge|auto-merge> --paths <f1,f2,...> [options]
+
+Options:
+ --action <commit|merge|auto-merge> What the loop is about to do
+ --paths <f1,f2,...> Comma-separated changed file paths
+ --gate-file <path> Policy file (default: gate.yaml)
+ --json Machine-readable output
+ -h, --help This help
+
+Exit codes: 0 allowed · 2 escalate · 1 error
+
+Example:
+ loop-gate check --action auto-merge --paths $(git diff --name-only | tr '\\n' ',')
+`;
+
+async function main(): Promise<number> {
+ const argv = process.argv.slice(2);
+ const command = argv[0];
+
+ if (!command || command === '--help' || command === '-h') {
+ console.log(HELP);
+ return command ? 0 : 1;
+ }
+ if (command !== 'check') {
+ console.error(`Unknown command "${command}".\n\n${HELP}`);
+ return 1;
+ }
+
+ const flags = parseFlags(argv.slice(1));
+ if (flags.help) {
+ console.log(HELP);
+ return 0;
+ }
+ if (!flags.action || !flags.paths) {
+ throw new Error('check requires --action and --paths.');
+ }
+ assertValidAction(flags.action);
+
+ const config = await loadGateConfig(flags.gateFile);
+ const paths = flags.paths.split(',').map((p) => p.trim()).filter(Boolean);
+ if (paths.length === 0) {
+ throw new Error('--paths must contain at least one non-empty path.');
+ }
+ const decision = checkGate({ config, action: flags.action as Action, paths });
+
+ if (flags.json) {
+ console.log(JSON.stringify(decision, null, 2));
+ } else {
+ console.log(`${decision.allowed ? 'ALLOWED' : 'ESCALATE'} [${decision.trigger}] — ${decision.reason}`);
+ }
+ return decision.allowed ? 0 : 2;
+}
+
+main()
+ .then((code) => process.exit(code))
+ .catch((err) => {
+ console.error(err instanceof Error ? err.message : String(err));
+ process.exit(1);
+ });
diff --git a/tools/loop-gate/src/gate.ts b/tools/loop-gate/src/gate.ts
new file mode 100644
index 0000000..4268e7f
--- /dev/null
+++ b/tools/loop-gate/src/gate.ts
@@ -0,0 +1,140 @@
+/**
+ * Mechanical enforcement of static policy (path denylist, auto-merge
+ * allowlist, max changed files) — the machine-readable twin of
+ * docs/safety.md's prose. Deliberately has no knowledge of run history
+ * (stagnation, repeat failures): that already belongs to loop-context's
+ * circuit breaker and must not be duplicated here.
+ */
+
+import { readFile } from 'node:fs/promises';
+import { parse } from 'yaml';
+import { minimatch } from 'minimatch';
+
+export type Action = 'commit' | 'merge' | 'auto-merge';
+
+export const VALID_ACTIONS: Action[] = ['commit', 'merge', 'auto-merge'];
+
+export function assertValidAction(action: string): asserts action is Action {
+ if (!VALID_ACTIONS.includes(action as Action)) {
+ throw new Error(`Invalid --action: ${action}. Use one of: ${VALID_ACTIONS.join(', ')}.`);
+ }
+}
+
+export interface GateConfig {
+ version: 1;
+ /** Glob patterns that must never be touched without human approval. */
+ denylist: string[];
+ /** Escalate when more than this many paths are in the proposed change. */
+ maxFiles?: number;
+ /** For --action auto-merge: every path must match one of these globs. */
+ autoMergeAllowlist?: string[];
+}
+
+function isStringArray(value: unknown): value is string[] {
+ return Array.isArray(value) && value.every((v) => typeof v === 'string');
+}
+
+export async function loadGateConfig(file: string): Promise<GateConfig> {
+ let raw: string;
+ try {
+ raw = await readFile(file, 'utf8');
+ } catch {
+ throw new Error(
+ `Gate config not found: ${file}. Create one (see templates/gate.yaml.template) or pass --gate-file <path>.`,
+ );
+ }
+
+ let parsed: unknown;
+ try {
+ parsed = parse(raw);
+ } catch (err) {
+ throw new Error(`Invalid YAML in ${file}: ${(err as Error).message}`);
+ }
+
+ const config = parsed as Partial<GateConfig> | null;
+ const invalid = (detail: string) => new Error(`Invalid gate config at ${file}: ${detail}`);
+
+ if (!config || config.version !== 1) {
+ throw invalid('expected { version: 1, denylist: string[], ... }.');
+ }
+ if (!isStringArray(config.denylist)) {
+ throw invalid('"denylist" must be an array of strings.');
+ }
+ if (config.maxFiles !== undefined && (typeof config.maxFiles !== 'number' || !Number.isFinite(config.maxFiles))) {
+ throw invalid('"maxFiles" must be a number.');
+ }
+ if (config.autoMergeAllowlist !== undefined && !isStringArray(config.autoMergeAllowlist)) {
+ throw invalid('"autoMergeAllowlist" must be an array of strings.');
+ }
+ return config as GateConfig;
+}
+
+export type GateTrigger = 'ok' | 'denylist' | 'file-count' | 'not-allowlisted';
+
+export interface GateDecision {
+ allowed: boolean;
+ trigger: GateTrigger;
+ reason: string;
+ /** Paths responsible for the trigger (empty when trigger is 'ok'). */
+ matchedPaths: string[];
+}
+
+export interface CheckInput {
+ config: GateConfig;
+ action: Action;
+ paths: string[];
+}
+
+/**
+ * Evaluate a proposed change against static policy. Checks the cheapest and
+ * most severe condition first (denylist), then file-count, then the
+ * auto-merge allowlist — mirroring loop-context's checkCircuitBreaker
+ * "most specific trigger first" ordering.
+ *
+ * All glob matching uses minimatch's `dot: true` — without it, `*` never
+ * matches a path segment starting with `.`, so denylist entries like
+ * `**\/secrets/**` or `**\/*_key*` would silently miss `.secrets/prod.json`
+ * or `.aws_key`, exactly the paths a denylist most needs to catch.
+ */
+export function checkGate(input: CheckInput): GateDecision {
+ const { config, action, paths } = input;
+
+ const denylistHits = paths.filter((p) => config.denylist.some((glob) => minimatch(p, glob, { dot: true })));
+ if (denylistHits.length > 0) {
+ return {
+ allowed: false,
+ trigger: 'denylist',
+ reason: `${denylistHits.length} path(s) match the denylist: ${denylistHits.join(', ')}. Escalating for human review.`,
+ matchedPaths: denylistHits,
+ };
+ }
+
+ if (config.maxFiles !== undefined && paths.length > config.maxFiles) {
+ return {
+ allowed: false,
+ trigger: 'file-count',
+ reason: `${paths.length} changed file(s) exceeds the max-files threshold (${config.maxFiles}). Escalating for human review.`,
+ matchedPaths: paths,
+ };
+ }
+
+ if (action === 'auto-merge') {
+ const allowlist = config.autoMergeAllowlist ?? [];
+ const notAllowlisted = paths.filter((p) => !allowlist.some((glob) => minimatch(p, glob, { dot: true })));
+ if (notAllowlisted.length > 0) {
+ return {
+ allowed: false,
+ trigger: 'not-allowlisted',
+ reason: `${notAllowlisted.length} path(s) are not on the auto-merge allowlist: ${notAllowlisted.join(', ')}. Escalating for human review.`,
+ matchedPaths: notAllowlisted,
+ };
+ }
+ }
+
+ return {
+ allowed: true,
+ trigger: 'ok',
+ reason: 'Within policy — cleared to proceed.',
+ matchedPaths: [],
+ };
+}
diff --git a/tools/loop-gate/test/cli.test.mjs b/tools/loop-gate/test/cli.test.mjs
new file mode 100644
index 0000000..c010c64
--- /dev/null
+++ b/tools/loop-gate/test/cli.test.mjs
@@ -0,0 +1,105 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { spawnSync } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+import { mkdtemp, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+const cli = path.join(path.dirname(fileURLToPath(import.meta.url)), '../dist/cli.js');
+
+async function freshGateDir() {
+ const dir = await mkdtemp(path.join(tmpdir(), 'loop-gate-cli-'));
+ await writeFile(
+ path.join(dir, 'gate.yaml'),
+ 'version: 1\ndenylist:\n - ".env"\n - "auth/**"\nmaxFiles: 3\nautoMergeAllowlist:\n - "docs/**"\n',
+ );
+ return dir;
+}
+
+function runCli(args, cwd) {
+ return spawnSync(process.execPath, [cli, ...args], { cwd, encoding: 'utf8' });
+}
+
+test('cli check allows an in-policy commit', async () => {
+ const dir = await freshGateDir();
+ const r = runCli(['check', '--action', 'commit', '--paths', 'src/index.ts', '--json'], dir);
+ assert.equal(r.status, 0);
+ const decision = JSON.parse(r.stdout);
+ assert.equal(decision.allowed, true);
+});
+
+test('cli check escalates on a denylist hit', async () => {
+ const dir = await freshGateDir();
+ const r = runCli(['check', '--action', 'commit', '--paths', 'auth/login.ts', '--json'], dir);
+ assert.equal(r.status, 2);
+ const decision = JSON.parse(r.stdout);
+ assert.equal(decision.trigger, 'denylist');
+});
+
+test('cli check escalates auto-merge on a non-allowlisted path', async () => {
+ const dir = await freshGateDir();
+ const r = runCli(['check', '--action', 'auto-merge', '--paths', 'src/index.ts'], dir);
+ assert.equal(r.status, 2);
+ assert.match(r.stdout, /not-allowlisted/);
+});
+
+test('cli check allows auto-merge on an allowlisted path', async () => {
+ const dir = await freshGateDir();
+ const r = runCli(['check', '--action', 'auto-merge', '--paths', 'docs/readme.md'], dir);
+ assert.equal(r.status, 0);
+});
+
+test('cli check rejects an invalid action', async () => {
+ const dir = await freshGateDir();
+ const r = runCli(['check', '--action', 'deploy', '--paths', 'x.ts'], dir);
+ assert.equal(r.status, 1);
+ assert.match(r.stderr, /Invalid --action: deploy/);
+});
+
+test('cli check rejects --paths that is whitespace/commas only, not silently allowed', async () => {
+ const dir = await freshGateDir();
+ const whitespaceOnly = runCli(['check', '--action', 'commit', '--paths', ' '], dir);
+ assert.equal(whitespaceOnly.status, 1);
+ assert.match(whitespaceOnly.stderr, /--paths must contain at least one non-empty path/);
+
+ const commasOnly = runCli(['check', '--action', 'commit', '--paths', ',,,'], dir);
+ assert.equal(commasOnly.status, 1);
+ assert.match(commasOnly.stderr, /--paths must contain at least one non-empty path/);
+});
+
+test('cli check requires --action and --paths', async () => {
+ const dir = await freshGateDir();
+ const r = runCli(['check', '--action', 'commit'], dir);
+ assert.equal(r.status, 1);
+ assert.match(r.stderr, /check requires --action and --paths/);
+});
+
+test('cli check surfaces a missing gate file clearly', async () => {
+ const dir = await mkdtemp(path.join(tmpdir(), 'loop-gate-cli-empty-'));
+ const r = runCli(['check', '--action', 'commit', '--paths', 'x.ts'], dir);
+ assert.equal(r.status, 1);
+ assert.match(r.stderr, /Gate config not found/);
+});
+
+test('cli check honors --gate-file', async () => {
+ const dir = await freshGateDir();
+ const customPath = path.join(dir, 'custom-gate.yaml');
+ await writeFile(customPath, 'version: 1\ndenylist:\n - "custom/**"\n');
+ const r = runCli(['check', '--action', 'commit', '--paths', 'custom/x.ts', '--gate-file', customPath, '--json'], dir);
+ assert.equal(r.status, 2);
+ const decision = JSON.parse(r.stdout);
+ assert.equal(decision.trigger, 'denylist');
+});
+
+test('cli --help prints usage and exits 0', () => {
+ const r = runCli(['--help']);
+ assert.equal(r.status, 0);
+ assert.match(r.stdout, /loop-gate/);
+});
+
+test('cli unknown command exits 1', () => {
+ const r = runCli(['bogus']);
+ assert.equal(r.status, 1);
+ assert.match(r.stderr, /Unknown command/);
+});
diff --git a/tools/loop-gate/test/gate.test.mjs b/tools/loop-gate/test/gate.test.mjs
new file mode 100644
index 0000000..abb1103
--- /dev/null
+++ b/tools/loop-gate/test/gate.test.mjs
@@ -0,0 +1,145 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdtemp, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { checkGate, loadGateConfig, assertValidAction } from '../dist/gate.js';
+
+const baseConfig = {
+ version: 1,
+ denylist: ['.env', '**/secrets/**', 'auth/**'],
+ maxFiles: 3,
+ autoMergeAllowlist: ['docs/**', '**/*.md'],
+};
+
+async function freshGateFile(contents) {
+ const dir = await mkdtemp(path.join(tmpdir(), 'loop-gate-'));
+ const file = path.join(dir, 'gate.yaml');
+ await writeFile(file, contents);
+ return file;
+}
+
+test('assertValidAction accepts the three known actions', () => {
+ for (const a of ['commit', 'merge', 'auto-merge']) {
+ assert.doesNotThrow(() => assertValidAction(a));
+ }
+});
+
+test('assertValidAction rejects an unknown action', () => {
+ assert.throws(() => assertValidAction('deploy'), /Invalid --action: deploy/);
+});
+
+test('checkGate allows a clean, in-policy change', () => {
+ const decision = checkGate({ config: baseConfig, action: 'commit', paths: ['src/index.ts'] });
+ assert.equal(decision.allowed, true);
+ assert.equal(decision.trigger, 'ok');
+});
+
+test('checkGate escalates on a denylist hit', () => {
+ const decision = checkGate({ config: baseConfig, action: 'commit', paths: ['auth/login.ts'] });
+ assert.equal(decision.allowed, false);
+ assert.equal(decision.trigger, 'denylist');
+ assert.deepEqual(decision.matchedPaths, ['auth/login.ts']);
+});
+
+test('checkGate escalates on a nested secrets path via **', () => {
+ const decision = checkGate({ config: baseConfig, action: 'commit', paths: ['config/secrets/prod.json'] });
+ assert.equal(decision.trigger, 'denylist');
+});
+
+test('checkGate escalates when file count exceeds maxFiles', () => {
+ const decision = checkGate({
+ config: baseConfig,
+ action: 'commit',
+ paths: ['a.ts', 'b.ts', 'c.ts', 'd.ts'],
+ });
+ assert.equal(decision.allowed, false);
+ assert.equal(decision.trigger, 'file-count');
+});
+
+test('checkGate denylist takes priority over file-count', () => {
+ const decision = checkGate({
+ config: baseConfig,
+ action: 'commit',
+ paths: ['.env', 'a.ts', 'b.ts', 'c.ts', 'd.ts'],
+ });
+ assert.equal(decision.trigger, 'denylist');
+});
+
+test('checkGate auto-merge allows only allowlisted paths', () => {
+ const ok = checkGate({ config: baseConfig, action: 'auto-merge', paths: ['docs/guide.md'] });
+ assert.equal(ok.allowed, true);
+
+ const blocked = checkGate({ config: baseConfig, action: 'auto-merge', paths: ['src/index.ts'] });
+ assert.equal(blocked.allowed, false);
+ assert.equal(blocked.trigger, 'not-allowlisted');
+ assert.deepEqual(blocked.matchedPaths, ['src/index.ts']);
+});
+
+test('checkGate auto-merge allowlist is not enforced for commit/merge actions', () => {
+ const decision = checkGate({ config: baseConfig, action: 'commit', paths: ['src/index.ts'] });
+ assert.equal(decision.allowed, true);
+});
+
+test('checkGate with no maxFiles configured never trips file-count', () => {
+ const config = { version: 1, denylist: [] };
+ const decision = checkGate({ config, action: 'commit', paths: Array.from({ length: 50 }, (_, i) => `f${i}.ts`) });
+ assert.equal(decision.allowed, true);
+});
+
+test('checkGate denylist globs match dotfile leaves (dot: true)', () => {
+ const config = { version: 1, denylist: ['**/*_key*', '**/*_secret*'] };
+ for (const p of ['.aws_key', 'config/.ssh_secret_token']) {
+ const decision = checkGate({ config, action: 'commit', paths: [p] });
+ assert.equal(decision.trigger, 'denylist', `expected "${p}" to hit the denylist`);
+ }
+});
+
+test('checkGate denylist ** traverses into a hidden (dot) directory (dot: true)', () => {
+ const config = { version: 1, denylist: ['**/secrets/**'] };
+ const decision = checkGate({ config, action: 'commit', paths: ['.config/secrets/prod.json'] });
+ assert.equal(decision.trigger, 'denylist');
+});
+
+test('loadGateConfig rejects a non-string denylist element', async () => {
+ const file = await freshGateFile('version: 1\ndenylist:\n - 42\n');
+ await assert.rejects(() => loadGateConfig(file), /"denylist" must be an array of strings/);
+});
+
+test('loadGateConfig rejects a non-numeric maxFiles instead of silently disabling the check', async () => {
+ const file = await freshGateFile('version: 1\ndenylist: []\nmaxFiles: "ten"\n');
+ await assert.rejects(() => loadGateConfig(file), /"maxFiles" must be a number/);
+});
+
+test('loadGateConfig rejects a malformed (non-array) autoMergeAllowlist', async () => {
+ const file = await freshGateFile('version: 1\ndenylist: []\nautoMergeAllowlist: "docs/**"\n');
+ await assert.rejects(() => loadGateConfig(file), /"autoMergeAllowlist" must be an array of strings/);
+});
+
+test('loadGateConfig parses a valid file', async () => {
+ const file = await freshGateFile('version: 1\ndenylist:\n - ".env"\nmaxFiles: 5\n');
+ const config = await loadGateConfig(file);
+ assert.equal(config.version, 1);
+ assert.deepEqual(config.denylist, ['.env']);
+ assert.equal(config.maxFiles, 5);
+});
+
+test('loadGateConfig rejects a missing file with a clear message', async () => {
+ await assert.rejects(() => loadGateConfig('/no/such/gate.yaml'), /Gate config not found/);
+});
+
+test('loadGateConfig rejects invalid YAML', async () => {
+ const file = await freshGateFile('version: 1\ndenylist: [\n');
+ await assert.rejects(() => loadGateConfig(file), /Invalid YAML/);
+});
+
+test('loadGateConfig rejects a config missing required fields', async () => {
+ const file = await freshGateFile('version: 1\n');
+ await assert.rejects(() => loadGateConfig(file), /Invalid gate config/);
+});
+
+test('loadGateConfig rejects the wrong version', async () => {
+ const file = await freshGateFile('version: 2\ndenylist: []\n');
+ await assert.rejects(() => loadGateConfig(file), /Invalid gate config/);
+});
diff --git a/tools/loop-gate/tsconfig.json b/tools/loop-gate/tsconfig.json
new file mode 100644
index 0000000..ef0f184
--- /dev/null
+++ b/tools/loop-gate/tsconfig.json
@@ -0,0 +1,13 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "NodeNext",
+ "moduleResolution": "NodeNext",
+ "outDir": "dist",
+ "rootDir": "src",
+ "strict": true,
+ "skipLibCheck": true,
+ "declaration": true
+ },
+ "include": ["src/**/*"]
+}