pattern-mcp 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -15,6 +15,11 @@ design reference.
15
15
 
16
16
  [Website](https://usepattern.sh) · [npm](https://www.npmjs.com/package/pattern-mcp) · [Report an issue](https://github.com/donaldrichard19-LVD/pattern-mcp/issues/new/choose)
17
17
 
18
+ **Current release: v0.10.0** — adds an opt-in enforcement boundary (a
19
+ `PreToolUse` hook plus a paired CI check) so a new component decision can
20
+ be required, not just logged. See [Enforcement boundary: hook + CI
21
+ gate](#enforcement-boundary-hook--ci-gate).
22
+
18
23
  <details>
19
24
  <summary><strong>Contents</strong> (click to expand)</summary>
20
25
 
@@ -22,6 +27,7 @@ design reference.
22
27
  - **Make the judgment call:** [`recommend_component`](#tool-recommend_component) · [`extract_requirements`](#tool-extract_requirements)
23
28
  - **Track cost and outcome:** [`record_component_decision`](#tool-record_component_decision) · [`read_ledger`](#tool-read_ledger) · [`report_build_cost`](#tool-report_build_cost) · [`report_outcome_proxy`](#tool-report_outcome_proxy) · [Feature cost attribution](#feature-cost-attribution) · [Outcome proxies](#outcome-proxies) · [Per-project judgment ledger](#per-project-judgment-ledger)
24
29
  - **Verify and export old decisions:** [`check_ledger_liveness`](#tool-check_ledger_liveness) · [`sweep_ledger_liveness`](#tool-sweep_ledger_liveness) · [`export_ledger_provenance`](#tool-export_ledger_provenance) · [`backfill_ledger_snapshot_ref`](#tool-backfill_ledger_snapshot_ref) · [`post_ledger_provenance_to_github`](#tool-post_ledger_provenance_to_github) · [Ledger integrity and decision provenance](#ledger-integrity-and-decision-provenance) (design overview — start here for how the five fit together)
30
+ - [Enforcement boundary: hook + CI gate](#enforcement-boundary-hook--ci-gate) (new in v0.10.0 — require the call, don't just log it)
25
31
  - [Per-project decision memory](#per-project-decision-memory) · [Security and privacy](#security-and-privacy) · [Telemetry](#telemetry)
26
32
  - **Cost:** [The `_meta` field](#the-_meta-field) · [Prompt caching](#prompt-caching) · [Measured cache and fetch behavior](#measured-cache-and-fetch-behavior) · [Search limits](#search-limits) · [Ensemble cost](#ensemble-cost-boundary-risk-cases-only) · [Session call cap](#session-call-cap)
27
33
  - [Local call log](#local-call-log) · [Known limitations](#known-limitations)
@@ -1477,14 +1483,21 @@ Two gaps in the ledger, surfaced from user feedback: it tracks that a
1477
1483
  decision was made, but not whether the thing it decided about is still
1478
1484
  live in your codebase, and it stores the checklist/verdict but not a
1479
1485
  version pin or an exportable artifact you can attach to a PR or issue.
1480
- Both are now fully addressed, across five tools:
1481
- [`check_ledger_liveness`](#tool-check_ledger_liveness) and
1482
- [`sweep_ledger_liveness`](#tool-sweep_ledger_liveness) close the first gap;
1483
- [`export_ledger_provenance`](#tool-export_ledger_provenance),
1484
- [`backfill_ledger_snapshot_ref`](#tool-backfill_ledger_snapshot_ref), and
1486
+ Both are now fully addressed, across five tools -- **old decisions can be
1487
+ checked, not just logged**: [`check_ledger_liveness`](#tool-check_ledger_liveness)
1488
+ verifies that the file where a decision was implemented still exists and
1489
+ still uses the recommended component, marking it an orphaned entry if it
1490
+ doesn't ([`sweep_ledger_liveness`](#tool-sweep_ledger_liveness) is the
1491
+ batch/scheduled version of the same check); **decisions can become
1492
+ shareable records**: [`export_ledger_provenance`](#tool-export_ledger_provenance)
1493
+ turns a decision into a self-contained Markdown record, and
1485
1494
  [`post_ledger_provenance_to_github`](#tool-post_ledger_provenance_to_github)
1486
- close the second. See `pattern-ledger-integrity-and-provenance-spec.md`
1487
- for the original phased plan this was built against.
1495
+ can attach it directly to the relevant PR or issue; and **older decisions
1496
+ aren't left behind**: [`backfill_ledger_snapshot_ref`](#tool-backfill_ledger_snapshot_ref)
1497
+ adds a `snapshot_ref` to decisions created before this feature existed, so
1498
+ the liveness check above works retroactively. See
1499
+ `pattern-ledger-integrity-and-provenance-spec.md` for the original phased
1500
+ plan this was built against.
1488
1501
 
1489
1502
  **This required the one deliberate exception** to Pattern otherwise having
1490
1503
  [no filesystem/git access to your repo](#per-project-judgment-ledger) at
@@ -1578,6 +1591,11 @@ itself is never rewritten.
1578
1591
 
1579
1592
  ## Enforcement boundary: hook + CI gate
1580
1593
 
1594
+ **Decisions can be enforced, not just tracked.** An opt-in `PreToolUse`
1595
+ hook can block a new component from being written until a matching
1596
+ ledger entry exists; a paired GitHub Action can also fail the PR if that
1597
+ decision record isn't committed alongside the code.
1598
+
1581
1599
  **The gap this closes:** SKILL.md instructs the calling agent to call
1582
1600
  `recommend_component` before scaffolding a new, non-trivial UI component,
1583
1601
  but nothing before this feature *enforced* that -- an agent could simply
@@ -1586,19 +1604,54 @@ Claude-Code-specific for the hook half; a consuming repo that never wires
1586
1604
  either piece up gets Pattern exactly as it worked before, and any other
1587
1605
  MCP host (Cursor, Codex, etc.) is entirely unaffected either way.
1588
1606
 
1589
- Two pieces, both templates under `templates/` -- pattern-mcp never
1590
- installs either into your repo on its own:
1591
-
1592
- - **`templates/hooks/check-gate-hook.mjs`** + **`templates/claude-settings/settings.json`**
1593
- -- a Claude Code `PreToolUse` hook that runs on `Write`/`Edit` calls. For
1594
- a genuinely new `.tsx`/`.jsx` file that exports a non-trivial component,
1595
- it looks up a ledger entry (via `~/.pattern/ledger.jsonl`, same as
1596
- everywhere else in Pattern) whose `file_path` matches the file being
1597
- written. A match writes a receipt and allows the write; no match blocks
1598
- it with a reason fed back to the model as retryable guidance, not a hard
1599
- failure. **This is the one new exception where Pattern writes into your
1600
- repo** (`.pattern/receipts/<feature_id>.json`) -- everything else
1601
- described in this README is read-only.
1607
+ **Set it up with one command:**
1608
+
1609
+ ```bash
1610
+ npx pattern-check-gate init
1611
+ ```
1612
+
1613
+ Confirms each step independently rather than one blanket "proceed?", and
1614
+ never auto-commits -- review with `git status`/`git diff` and commit
1615
+ yourself when ready:
1616
+
1617
+ 1. Confirms a project id (pre-filled from `package.json`'s `name`, or
1618
+ your git remote/directory name -- accept it or type your own).
1619
+ 2. Writes or merges `.claude/settings.json` -- if one already exists, it
1620
+ parses it, leaves any unrelated hooks untouched, and only appends the
1621
+ `PreToolUse` entry if it isn't already there (safe to rerun).
1622
+ 3. Writes `.github/workflows/pattern-gate.yml`, if a GitHub remote is
1623
+ detected and the file doesn't already exist with different content
1624
+ (never silently overwritten).
1625
+ 4. Asks, as its own explicit yes/no: **mark the check required in branch
1626
+ protection?** Needs `gh` installed and authenticated with admin rights
1627
+ on the repo; skips with clear next steps otherwise. Deliberately only
1628
+ offered when no branch protection exists yet on the default branch --
1629
+ GitHub's branch-protection API replaces the *entire* configuration on
1630
+ write, not just the required-checks list, so this refuses to guess at
1631
+ merging into whatever you already have rather than risk silently
1632
+ dropping an unrelated setting (e.g. required PR reviews). If
1633
+ protection already exists, add `pattern-gate` to it by hand instead.
1634
+
1635
+ Run non-interactively with `--yes` (accepts every safe default; branch
1636
+ protection is never auto-confirmed even then -- it's the one step that
1637
+ reaches outside your local filesystem into real, shared GitHub config).
1638
+
1639
+ **Or set it up by hand**, two pieces, neither installed automatically:
1640
+
1641
+ - **`.claude/settings.json`** wired to run `npx --yes
1642
+ pattern-check-gate-hook` on `PreToolUse` (see
1643
+ `templates/claude-settings/settings.json` for the exact shape) -- a
1644
+ Claude Code hook that runs on `Write`/`Edit` calls. For a genuinely new
1645
+ `.tsx`/`.jsx` file that exports a non-trivial component, it looks up a
1646
+ ledger entry (via `~/.pattern/ledger.jsonl`, same as everywhere else in
1647
+ Pattern) whose `file_path` matches the file being written. A match
1648
+ writes a receipt and allows the write; no match blocks it with a reason
1649
+ fed back to the model as retryable guidance, not a hard failure.
1650
+ **This is the one new exception where Pattern writes into your repo**
1651
+ (`.pattern/receipts/<feature_id>.json`) -- everything else described in
1652
+ this README is read-only. `project_id` no longer needs to be set by
1653
+ hand either -- it's derived the same way `init` pre-fills it (see
1654
+ `src/project-id.ts`); set `PATTERN_PROJECT_ID` only to override that.
1602
1655
  - **`templates/github-workflows/pattern-gate.yml`** -- a required PR
1603
1656
  check that reads the same receipt files back out of the diff. It never
1604
1657
  touches `~/.pattern/` (not reachable from a CI runner) and needs no
@@ -1615,11 +1668,11 @@ An escape hatch exists for both a whole-hook kill switch
1615
1668
  check) and a per-file override (a `// pattern-mcp:override reason="..."`
1616
1669
  comment) -- the override still writes a receipt recording
1617
1670
  `manual_override: true` and the reason, so it stays visible rather than
1618
- silent. See `src/component-gate.ts`, `src/gate-receipt.ts`, and
1619
- `src/check-gate.ts` (the new `pattern-check-gate` CLI, this project's
1620
- first entry point separate from the stdio MCP server) for the
1621
- implementation, and BACKLOG.md's "Enforcement boundary: hook + CI gate"
1622
- entry for the fuller design writeup.
1671
+ silent. See `src/component-gate.ts`, `src/gate-receipt.ts`,
1672
+ `src/check-gate.ts` (the `pattern-check-gate` CLI, this project's first
1673
+ entry point separate from the stdio MCP server), `src/check-gate-hook.ts`,
1674
+ and `src/init-enforcement.ts` for the implementation, and BACKLOG.md's
1675
+ "Enforcement boundary" entries for the fuller design writeup.
1623
1676
 
1624
1677
  ## Per-project decision memory
1625
1678
 
@@ -0,0 +1,81 @@
1
+ #!/usr/bin/env node
2
+ // pattern-check-gate-hook -- the Claude-Code-specific PreToolUse adapter.
3
+ // Wired up via .claude/settings.json (see templates/claude-settings/settings.json,
4
+ // or generated automatically by `pattern-check-gate init`). Not installed
5
+ // automatically by pattern-mcp itself -- opt-in, per BACKLOG.md's
6
+ // "Enforcement boundary: hook + CI gate" entry.
7
+ //
8
+ // A real bin entry (not a template file to hand-copy) so it resolves the
9
+ // same way whether pattern-mcp is a real devDependency in the consuming
10
+ // repo's node_modules or only ever fetched ad hoc via npx -- both cases
11
+ // invoke it as `npx --yes pattern-check-gate-hook`, npx's own caching
12
+ // handles the rest. This also makes it testable the same way as
13
+ // check-gate.ts itself (spawned as a real subprocess in
14
+ // scripts/verify-check-gate.mjs), rather than living outside the build.
15
+ //
16
+ // Reads the PreToolUse stdin JSON, shells out to `pattern-check-gate
17
+ // write`, and translates the result into the hook's blocking contract: a
18
+ // JSON object on stdout with permissionDecision "deny" blocks the tool
19
+ // call and feeds the reason back to Claude as retryable guidance (not a
20
+ // hard turn failure); exiting 0 with no output allows it.
21
+ //
22
+ // --project-id is intentionally omitted unless PATTERN_PROJECT_ID is set
23
+ // -- pattern-check-gate derives one itself (package.json name, then git
24
+ // remote, then directory name) when it's not passed. See project-id.ts.
25
+ import { existsSync, readFileSync } from "node:fs";
26
+ import { spawnSync } from "node:child_process";
27
+ async function main() {
28
+ if (process.env.PATTERN_NO_ENFORCEMENT_HOOK) {
29
+ process.exit(0);
30
+ }
31
+ const input = JSON.parse(readFileSync(0, "utf8"));
32
+ const toolName = input.tool_name;
33
+ if (toolName !== "Write" && toolName !== "Edit") {
34
+ process.exit(0);
35
+ }
36
+ const filePath = input.tool_input?.file_path;
37
+ if (!filePath)
38
+ process.exit(0);
39
+ // isNewFile is determined here, at hook time, before the write happens
40
+ // -- the one piece of Claude-Code-specific state pattern-check-gate
41
+ // itself doesn't have access to. Edit calls always target an existing
42
+ // file, so isNewFile is always false for them -- the initial Write
43
+ // that creates the file is the highest-signal moment.
44
+ const isNewFile = !existsSync(filePath);
45
+ const content = toolName === "Write" ? (input.tool_input?.content ?? "") : "";
46
+ const root = input.cwd ?? process.cwd();
47
+ const args = ["write", "--file", filePath, "--project-root", root];
48
+ if (process.env.PATTERN_PROJECT_ID) {
49
+ args.push("--project-id", process.env.PATTERN_PROJECT_ID);
50
+ }
51
+ if (isNewFile)
52
+ args.push("--is-new");
53
+ const result = spawnSync("npx", ["--yes", "pattern-check-gate", ...args], {
54
+ input: content,
55
+ encoding: "utf8",
56
+ timeout: 30000,
57
+ });
58
+ let parsed;
59
+ try {
60
+ parsed = JSON.parse((result.stdout || "").trim());
61
+ }
62
+ catch {
63
+ // If pattern-check-gate itself crashed or produced no parseable
64
+ // output, fail open (allow) rather than blocking on a plumbing bug --
65
+ // stderr still carries the detail for debugging.
66
+ if (result.stderr)
67
+ process.stderr.write(result.stderr);
68
+ process.exit(0);
69
+ }
70
+ if (parsed.ok === false) {
71
+ process.stdout.write(JSON.stringify({
72
+ hookSpecificOutput: {
73
+ hookEventName: "PreToolUse",
74
+ permissionDecision: "deny",
75
+ permissionDecisionReason: parsed.reason ?? "pattern-check-gate blocked this file.",
76
+ },
77
+ }));
78
+ }
79
+ process.exit(0);
80
+ }
81
+ main();
@@ -2,21 +2,28 @@
2
2
  // pattern-check-gate -- the enforcement-boundary CLI (see
3
3
  // BACKLOG.md's "Enforcement boundary: hook + CI gate" entry).
4
4
  //
5
- // Two modes, one shared classifier (component-gate.ts) so the local hook
6
- // and the CI check can never silently drift on what counts as "gated":
5
+ // Three modes. write/verify share one classifier (component-gate.ts) so
6
+ // the local hook and the CI check can never silently drift on what
7
+ // counts as "gated":
7
8
  //
8
- // write -- run locally (by the PreToolUse hook template) where
9
+ // write -- run locally (by check-gate-hook.ts) where
9
10
  // ~/.pattern/ledger.jsonl is reachable. Looks up a ledger
10
11
  // entry whose file_path matches the file being written; on a
11
12
  // match (or a manual override), writes a receipt into the
12
13
  // CONSUMING repo at .pattern/receipts/<feature_id>.json and
13
14
  // exits 0. No match, no override -> exits 1 and blocks.
15
+ // --project-id is optional -- see project-id.ts (Option A).
14
16
  //
15
17
  // verify -- run in CI, where ~/.pattern/ is never reachable. Trusts the
16
18
  // committed receipt as the artifact of record instead of
17
19
  // re-deriving anything from the ledger -- fails if a gated
18
20
  // file in the diff has no matching receipt.
19
21
  //
22
+ // init -- Option C: a guided setup that writes/merges
23
+ // .claude/settings.json and the workflow file, and can
24
+ // optionally configure branch protection via `gh`. See
25
+ // init-enforcement.ts; this file only dispatches to it.
26
+ //
20
27
  // No CLI-parsing or git-wrapper dependency, matching this project's
21
28
  // existing minimal-dependency posture (index.ts shells out to fixed git
22
29
  // subcommands rather than a library) -- argv is parsed by hand below.
@@ -30,6 +37,8 @@ import { existsSync, readFileSync } from "node:fs";
30
37
  import { isAbsolute, relative, resolve as resolvePath } from "node:path";
31
38
  import { isGatedComponentFile, parseManualOverride } from "./component-gate.js";
32
39
  import { deriveOverrideFeatureId, readAllGateReceipts, writeGateReceipt } from "./gate-receipt.js";
40
+ import { deriveProjectId } from "./project-id.js";
41
+ import { runInit } from "./init-enforcement.js";
33
42
  function normalize(p) {
34
43
  return p.replace(/\\/g, "/").replace(/^\.\//, "");
35
44
  }
@@ -86,10 +95,14 @@ function emit(result, ok) {
86
95
  }
87
96
  async function runWrite(root, flags) {
88
97
  const fileArg = flags.file;
89
- const projectId = flags["project-id"];
90
- if (typeof fileArg !== "string" || typeof projectId !== "string") {
91
- emit({ ok: false, reason: "write mode requires --file <path> and --project-id <id>" }, false);
98
+ if (typeof fileArg !== "string") {
99
+ emit({ ok: false, reason: "write mode requires --file <path>" }, false);
92
100
  }
101
+ // Option A: --project-id is now optional -- derive it (package.json
102
+ // name, then git remote, then the directory name) rather than require
103
+ // every caller to know and pass it. An explicit --project-id always
104
+ // wins over the derivation.
105
+ const projectId = typeof flags["project-id"] === "string" ? flags["project-id"] : deriveProjectId(root);
93
106
  const relPath = toRepoRelative(root, fileArg);
94
107
  if (relPath === null) {
95
108
  emit({ ok: false, reason: `--file resolves outside project root: ${fileArg}` }, false);
@@ -190,9 +203,13 @@ async function main() {
190
203
  else if (mode === "verify") {
191
204
  await runVerify(root, files);
192
205
  }
206
+ else if (mode === "init") {
207
+ await runInit(root, { yes: flags.yes === true });
208
+ }
193
209
  else {
194
- process.stderr.write("Usage: pattern-check-gate write --file <path> [--is-new] --project-id <id> [--project-root <root>] (content on stdin)\n");
210
+ process.stderr.write("Usage: pattern-check-gate write --file <path> [--is-new] [--project-id <id>] [--project-root <root>] (content on stdin)\n");
195
211
  process.stderr.write(" pattern-check-gate verify --files <path...> [--project-root <root>]\n");
212
+ process.stderr.write(" pattern-check-gate init [--project-root <root>] [--yes]\n");
196
213
  process.exit(2);
197
214
  }
198
215
  }
@@ -0,0 +1,316 @@
1
+ // Option C from BACKLOG.md's "Enforcement boundary setup" entry: a
2
+ // guided `pattern-check-gate init` that does the mechanical parts of
3
+ // setting up the hook + CI gate (see check-gate-hook.ts,
4
+ // templates/github-workflows/pattern-gate.yml) instead of requiring a
5
+ // hand copy-edit-commit of each piece separately.
6
+ //
7
+ // Every step confirms independently and defaults to the safe choice --
8
+ // this never auto-commits, and the branch-protection step in particular
9
+ // never runs without an explicit, un-implied "yes" (see
10
+ // maybeSetupBranchProtection), matching the same "always confirm, never
11
+ // silently run" treatment Pattern already gives install_command and
12
+ // post_ledger_provenance_to_github.
13
+ import { execFileSync } from "node:child_process";
14
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
15
+ import { dirname, join } from "node:path";
16
+ import { fileURLToPath } from "node:url";
17
+ import { createInterface } from "node:readline";
18
+ import { deriveProjectId } from "./project-id.js";
19
+ const HOOK_MARKER = "pattern-check-gate-hook";
20
+ // A queue-based prompt helper, not readline/promises' question() --
21
+ // question() only starts listening for a line *after* it's called, but
22
+ // with piped/non-TTY stdin (as in an automated test, or `init | cat`)
23
+ // every line arrives in one synchronous burst, ahead of any await
24
+ // cycle. Confirmed directly: two sequential `rl.question()` calls on a
25
+ // piped `printf 'a\nb\n'` answer only the first and hang forever on the
26
+ // second -- Node even logs "Detected unsettled top-level await" in that
27
+ // repro. The fix is a small always-listening queue: a persistent 'line'
28
+ // listener buffers answers that arrive before they're asked for, so
29
+ // `askLine` either drains an already-buffered answer immediately or
30
+ // waits for the next 'line' event, whichever comes first -- correct for
31
+ // both a real interactive TTY (waiter path) and piped/scripted input
32
+ // (queue path).
33
+ let rl = null;
34
+ const lineQueue = [];
35
+ const waiters = [];
36
+ function ensureRl() {
37
+ if (!rl) {
38
+ rl = createInterface({ input: process.stdin, output: process.stdout });
39
+ rl.on("line", (line) => {
40
+ const waiter = waiters.shift();
41
+ if (waiter)
42
+ waiter(line);
43
+ else
44
+ lineQueue.push(line);
45
+ });
46
+ }
47
+ return rl;
48
+ }
49
+ function askLine(promptStr) {
50
+ ensureRl();
51
+ process.stdout.write(promptStr);
52
+ const queued = lineQueue.shift();
53
+ if (queued !== undefined)
54
+ return Promise.resolve(queued);
55
+ return new Promise((resolve) => waiters.push(resolve));
56
+ }
57
+ function closeRl() {
58
+ rl?.close();
59
+ rl = null;
60
+ }
61
+ async function confirm(question, options, defaultYes) {
62
+ if (options.yes)
63
+ return defaultYes;
64
+ const suffix = defaultYes ? "[Y/n]" : "[y/N]";
65
+ const answer = (await askLine(`${question} ${suffix} `)).trim().toLowerCase();
66
+ if (!answer)
67
+ return defaultYes;
68
+ return answer === "y" || answer === "yes";
69
+ }
70
+ async function promptText(question, defaultValue, options) {
71
+ if (options.yes)
72
+ return defaultValue;
73
+ const answer = (await askLine(`${question} [${defaultValue}]: `)).trim();
74
+ return answer || defaultValue;
75
+ }
76
+ function shellQuote(value) {
77
+ return `'${value.replace(/'/g, `'\\''`)}'`;
78
+ }
79
+ async function setupClaudeSettings(root, projectIdOverride, options) {
80
+ const settingsPath = join(root, ".claude", "settings.json");
81
+ let settings = {};
82
+ let existed = false;
83
+ if (existsSync(settingsPath)) {
84
+ existed = true;
85
+ try {
86
+ settings = JSON.parse(readFileSync(settingsPath, "utf8"));
87
+ }
88
+ catch {
89
+ console.log(" .claude/settings.json exists but isn't valid JSON -- skipping, fix it manually first.");
90
+ return;
91
+ }
92
+ }
93
+ const preToolUse = settings.hooks?.PreToolUse ?? [];
94
+ const alreadyInstalled = preToolUse.some((entry) => (entry.hooks ?? []).some((h) => typeof h.command === "string" && h.command.includes(HOOK_MARKER)));
95
+ if (alreadyInstalled) {
96
+ console.log(" .claude/settings.json: hook already configured, skipping.");
97
+ return;
98
+ }
99
+ const command = projectIdOverride
100
+ ? `env PATTERN_PROJECT_ID=${shellQuote(projectIdOverride)} npx --yes pattern-check-gate-hook`
101
+ : "npx --yes pattern-check-gate-hook";
102
+ const newEntry = {
103
+ matcher: "Edit|Write",
104
+ hooks: [{ type: "command", command, timeout: 60 }],
105
+ };
106
+ console.log(`\n ${existed ? "Merging into" : "Creating"} .claude/settings.json:`);
107
+ console.log(JSON.stringify(newEntry, null, 2)
108
+ .split("\n")
109
+ .map((l) => ` ${l}`)
110
+ .join("\n"));
111
+ const proceed = await confirm(" Write this?", options, true);
112
+ if (!proceed) {
113
+ console.log(" Skipped.");
114
+ return;
115
+ }
116
+ const merged = {
117
+ ...settings,
118
+ hooks: {
119
+ ...settings.hooks,
120
+ PreToolUse: [...preToolUse, newEntry],
121
+ },
122
+ };
123
+ mkdirSync(dirname(settingsPath), { recursive: true });
124
+ writeFileSync(settingsPath, JSON.stringify(merged, null, 2) + "\n", "utf8");
125
+ console.log(" Written.");
126
+ }
127
+ function isGitHubRepo(root) {
128
+ try {
129
+ const url = execFileSync("git", ["remote", "get-url", "origin"], {
130
+ cwd: root,
131
+ encoding: "utf8",
132
+ stdio: ["ignore", "pipe", "ignore"],
133
+ timeout: 2000,
134
+ }).trim();
135
+ const match = url.match(/github\.com[:/]([^/]+)\/([^/]+?)(\.git)?$/);
136
+ if (match)
137
+ return { owner: match[1], repo: match[2] };
138
+ }
139
+ catch {
140
+ // no remote, or not git
141
+ }
142
+ return null;
143
+ }
144
+ async function setupWorkflowFile(root, options) {
145
+ const gh = isGitHubRepo(root);
146
+ if (!gh) {
147
+ console.log("\n No GitHub remote detected -- skipping the GitHub Action workflow file.");
148
+ return false;
149
+ }
150
+ const workflowPath = join(root, ".github", "workflows", "pattern-gate.yml");
151
+ const templatePath = fileURLToPath(new URL("../templates/github-workflows/pattern-gate.yml", import.meta.url));
152
+ const templateContent = readFileSync(templatePath, "utf8");
153
+ if (existsSync(workflowPath)) {
154
+ const existing = readFileSync(workflowPath, "utf8");
155
+ if (existing === templateContent) {
156
+ console.log("\n .github/workflows/pattern-gate.yml: already up to date, skipping.");
157
+ return true;
158
+ }
159
+ console.log("\n .github/workflows/pattern-gate.yml already exists with different content.");
160
+ const overwrite = await confirm(" Overwrite it?", options, false);
161
+ if (!overwrite) {
162
+ console.log(" Skipped -- left your existing file untouched.");
163
+ return false;
164
+ }
165
+ }
166
+ else {
167
+ console.log("\n Creating .github/workflows/pattern-gate.yml.");
168
+ const proceed = await confirm(" Write this?", options, true);
169
+ if (!proceed) {
170
+ console.log(" Skipped.");
171
+ return false;
172
+ }
173
+ }
174
+ mkdirSync(dirname(workflowPath), { recursive: true });
175
+ writeFileSync(workflowPath, templateContent, "utf8");
176
+ console.log(" Written.");
177
+ return true;
178
+ }
179
+ function ghCliAvailable() {
180
+ try {
181
+ execFileSync("gh", ["--version"], { stdio: "ignore", timeout: 5000 });
182
+ return true;
183
+ }
184
+ catch {
185
+ return false;
186
+ }
187
+ }
188
+ function ghAuthenticated() {
189
+ try {
190
+ execFileSync("gh", ["auth", "status"], { stdio: "ignore", timeout: 5000 });
191
+ return true;
192
+ }
193
+ catch {
194
+ return false;
195
+ }
196
+ }
197
+ function getDefaultBranch(gh) {
198
+ try {
199
+ const out = execFileSync("gh", ["api", `repos/${gh.owner}/${gh.repo}`, "--jq", ".default_branch"], {
200
+ encoding: "utf8",
201
+ timeout: 10000,
202
+ }).trim();
203
+ return out || null;
204
+ }
205
+ catch {
206
+ return null;
207
+ }
208
+ }
209
+ function stderrOf(err) {
210
+ if (err && typeof err === "object" && "stderr" in err) {
211
+ const stderr = err.stderr;
212
+ if (stderr)
213
+ return String(stderr);
214
+ }
215
+ return "";
216
+ }
217
+ function getExistingProtection(gh, branch) {
218
+ try {
219
+ execFileSync("gh", ["api", `repos/${gh.owner}/${gh.repo}/branches/${branch}/protection`], {
220
+ encoding: "utf8",
221
+ timeout: 10000,
222
+ });
223
+ return "exists";
224
+ }
225
+ catch (err) {
226
+ return stderrOf(err).includes("404") ? "none" : "unknown";
227
+ }
228
+ }
229
+ // Only ever called when getExistingProtection returned "none". The
230
+ // Update Branch Protection endpoint REPLACES the entire protection
231
+ // object, and its GET/PUT schemas differ for several fields
232
+ // (enforce_admins is {enabled} on GET but a bare boolean on PUT, for
233
+ // example) -- verified against GitHub's own REST API docs before writing
234
+ // this. Deliberately does not attempt to merge into pre-existing
235
+ // protection; that case is handled by the caller bailing out to manual
236
+ // instructions instead of risking a wrong reconstruction that silently
237
+ // drops an unrelated setting (e.g. required PR reviews).
238
+ function createMinimalProtection(gh, branch) {
239
+ const body = JSON.stringify({
240
+ required_status_checks: { strict: false, checks: [{ context: "pattern-gate", app_id: -1 }] },
241
+ enforce_admins: false,
242
+ required_pull_request_reviews: null,
243
+ restrictions: null,
244
+ });
245
+ try {
246
+ execFileSync("gh", ["api", "-X", "PUT", `repos/${gh.owner}/${gh.repo}/branches/${branch}/protection`, "--input", "-"], {
247
+ input: body,
248
+ encoding: "utf8",
249
+ timeout: 10000,
250
+ });
251
+ return true;
252
+ }
253
+ catch {
254
+ return false;
255
+ }
256
+ }
257
+ async function maybeSetupBranchProtection(root, options) {
258
+ const gh = isGitHubRepo(root);
259
+ if (!gh)
260
+ return;
261
+ console.log("");
262
+ // Never implied by --yes, and never defaults to yes -- see BACKLOG's
263
+ // "strictest confirmation of the four steps" note. This is the one
264
+ // step that reaches outside the local filesystem into real, shared
265
+ // GitHub config.
266
+ const wantsIt = await confirm(" Mark the pattern-gate check as required in branch protection?", options, false);
267
+ if (!wantsIt) {
268
+ console.log(` Skipped. To do this later, add "pattern-gate" as a required status check in\n` +
269
+ ` https://github.com/${gh.owner}/${gh.repo}/settings/branches`);
270
+ return;
271
+ }
272
+ if (!ghCliAvailable()) {
273
+ console.log(" `gh` CLI not found -- install it (https://cli.github.com) and rerun, or configure manually.");
274
+ return;
275
+ }
276
+ if (!ghAuthenticated()) {
277
+ console.log(" `gh` CLI isn't authenticated -- run `gh auth login` and rerun, or configure manually.");
278
+ return;
279
+ }
280
+ const branch = getDefaultBranch(gh);
281
+ if (!branch) {
282
+ console.log(" Couldn't determine the default branch -- configure manually.");
283
+ return;
284
+ }
285
+ const existing = getExistingProtection(gh, branch);
286
+ if (existing !== "none") {
287
+ console.log(existing === "exists"
288
+ ? ` Branch protection already exists on "${branch}". To avoid overwriting your other protection\n` +
289
+ ` settings (this endpoint replaces the whole configuration, not just required checks), add\n` +
290
+ ` "pattern-gate" to your required status checks manually instead of through this command.`
291
+ : ` Couldn't determine "${branch}"'s current protection state -- configure manually rather than\n` +
292
+ ` risk overwriting settings this command can't see.`);
293
+ return;
294
+ }
295
+ const ok = createMinimalProtection(gh, branch);
296
+ console.log(ok
297
+ ? ` Required "pattern-gate" check added to "${branch}" branch protection.`
298
+ : " Failed to update branch protection -- configure manually.");
299
+ }
300
+ export async function runInit(root, options) {
301
+ console.log("Setting up Pattern's enforcement boundary (hook + CI gate)...\n");
302
+ const derivedId = deriveProjectId(root);
303
+ const projectId = await promptText("Project id", derivedId, options);
304
+ const projectIdOverride = projectId !== derivedId ? projectId : null;
305
+ try {
306
+ await setupClaudeSettings(root, projectIdOverride, options);
307
+ await setupWorkflowFile(root, options);
308
+ await maybeSetupBranchProtection(root, options);
309
+ }
310
+ finally {
311
+ // Always close, even on error -- an open readline interface keeps
312
+ // the process alive waiting on stdin otherwise.
313
+ closeRl();
314
+ }
315
+ console.log("\nDone. Review the changes with `git status` / `git diff`, then commit when ready.");
316
+ }
@@ -0,0 +1,36 @@
1
+ // Option A from BACKLOG.md's "Enforcement boundary setup" entry:
2
+ // auto-derives a project id instead of requiring PATTERN_PROJECT_ID to be
3
+ // hand-set. Shared by check-gate.ts's write mode (runtime fallback when
4
+ // --project-id is omitted) and init-enforcement.ts (to pre-fill its
5
+ // prompt) -- one derivation, not two, so the hook's actual behavior and
6
+ // init's preview can never disagree.
7
+ import { execFileSync } from "node:child_process";
8
+ import { readFileSync } from "node:fs";
9
+ import { basename, join } from "node:path";
10
+ export function deriveProjectId(root) {
11
+ try {
12
+ const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
13
+ if (typeof pkg.name === "string" && pkg.name.trim())
14
+ return pkg.name.trim();
15
+ }
16
+ catch {
17
+ // no package.json, or unparseable -- fall through to the git remote
18
+ }
19
+ try {
20
+ const url = execFileSync("git", ["remote", "get-url", "origin"], {
21
+ cwd: root,
22
+ encoding: "utf8",
23
+ stdio: ["ignore", "pipe", "ignore"],
24
+ timeout: 2000,
25
+ }).trim();
26
+ // Matches the repo name out of either an https or ssh remote URL,
27
+ // with or without a trailing .git.
28
+ const match = url.match(/([^/:]+?)(\.git)?$/);
29
+ if (match && match[1])
30
+ return match[1];
31
+ }
32
+ catch {
33
+ // no git remote, or git not available -- fall through to the dir name
34
+ }
35
+ return basename(root);
36
+ }
package/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "pattern-mcp",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "description": "MCP server that turns your design guidance into a checkable process -- evaluates UI components from external libraries (shadcn/ui, 21st.dev, ReUI) or your own registered design system against a requirements checklist, then tells the agent whether to reuse an existing component or build one from a concrete design reference.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
7
7
  "bin": {
8
8
  "pattern-mcp": "dist/index.js",
9
- "pattern-check-gate": "dist/check-gate.js"
9
+ "pattern-check-gate": "dist/check-gate.js",
10
+ "pattern-check-gate-hook": "dist/check-gate-hook.js"
10
11
  },
11
12
  "author": "Don Richard",
12
13
  "license": "MIT",
@@ -6,7 +6,7 @@
6
6
  "hooks": [
7
7
  {
8
8
  "type": "command",
9
- "command": "env PATTERN_PROJECT_ID=your-project-id node ./node_modules/pattern-mcp/templates/hooks/check-gate-hook.mjs",
9
+ "command": "npx --yes pattern-check-gate-hook",
10
10
  "timeout": 60
11
11
  }
12
12
  ]
@@ -1,89 +0,0 @@
1
- #!/usr/bin/env node
2
- // Claude-Code-specific PreToolUse adapter for pattern-check-gate. Copy this
3
- // file into your repo (or reference it from node_modules/pattern-mcp) and
4
- // wire it up via .claude/settings.json -- see
5
- // ../claude-settings/settings.json for the exact hook config. Not
6
- // installed automatically by pattern-mcp; this is opt-in (see
7
- // BACKLOG.md's "Enforcement boundary: hook + CI gate" entry for why).
8
- //
9
- // Reads the PreToolUse stdin JSON, shells out to `pattern-check-gate
10
- // write`, and translates the result into the hook's blocking contract:
11
- // a JSON object on stdout with permissionDecision "deny" blocks the tool
12
- // call and feeds the reason back to Claude as retryable guidance (not a
13
- // hard turn failure); exiting 0 with no output allows it.
14
- //
15
- // Requires a PATTERN_PROJECT_ID env var (or --project-id below) -- set it
16
- // in the hook's own "command" (e.g. via `env PATTERN_PROJECT_ID=my-app
17
- // node ...`) or export it in your shell profile for local dev.
18
-
19
- import { existsSync, readFileSync } from "node:fs";
20
- import { spawnSync } from "node:child_process";
21
-
22
- async function main() {
23
- if (process.env.PATTERN_NO_ENFORCEMENT_HOOK) {
24
- process.exit(0);
25
- }
26
-
27
- const input = JSON.parse(readFileSync(0, "utf8"));
28
- const toolName = input.tool_name;
29
- if (toolName !== "Write" && toolName !== "Edit") {
30
- process.exit(0);
31
- }
32
-
33
- const filePath = input.tool_input?.file_path;
34
- if (!filePath) process.exit(0);
35
-
36
- // isNewFile is determined here, at hook time, before the write happens
37
- // -- this is the one piece of Claude-Code-specific state check-gate.ts
38
- // itself doesn't have access to. Edit calls always target an existing
39
- // file, so isNewFile is always false for them, which is why they're
40
- // effectively never gated by this hook (see component-gate.ts's
41
- // comment on isNewFile) -- the initial Write that creates the file is
42
- // the highest-signal moment.
43
- const isNewFile = !existsSync(filePath);
44
- const content = toolName === "Write" ? input.tool_input?.content ?? "" : "";
45
-
46
- const projectId = process.env.PATTERN_PROJECT_ID;
47
- if (!projectId) {
48
- // Fail open with a clear stderr note rather than blocking every write
49
- // in a repo that hasn't configured this yet -- misconfiguration
50
- // shouldn't look identical to "no ledger entry found."
51
- process.stderr.write("check-gate-hook: PATTERN_PROJECT_ID not set, skipping gate\n");
52
- process.exit(0);
53
- }
54
-
55
- const args = ["write", "--file", filePath, "--project-id", projectId, "--project-root", input.cwd ?? process.cwd()];
56
- if (isNewFile) args.push("--is-new");
57
-
58
- const result = spawnSync("npx", ["pattern-check-gate", ...args], {
59
- input: content,
60
- encoding: "utf8",
61
- timeout: 30000,
62
- });
63
-
64
- let parsed;
65
- try {
66
- parsed = JSON.parse((result.stdout || "").trim());
67
- } catch {
68
- // If pattern-check-gate itself crashed or produced no parseable
69
- // output, fail open (allow) rather than blocking on a plumbing bug --
70
- // stderr still carries the detail for debugging.
71
- if (result.stderr) process.stderr.write(result.stderr);
72
- process.exit(0);
73
- }
74
-
75
- if (parsed.ok === false) {
76
- process.stdout.write(
77
- JSON.stringify({
78
- hookSpecificOutput: {
79
- hookEventName: "PreToolUse",
80
- permissionDecision: "deny",
81
- permissionDecisionReason: parsed.reason ?? "pattern-check-gate blocked this file.",
82
- },
83
- }),
84
- );
85
- }
86
- process.exit(0);
87
- }
88
-
89
- main();