@webpieces/ai-hook-rules 0.4.612 → 0.4.614

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webpieces/ai-hook-rules",
3
- "version": "0.4.612",
3
+ "version": "0.4.614",
4
4
  "description": "Pluggable write-time validation framework for AI coding agents (@webpieces/ai-hook-rules). Claude Code PreToolUse + openclaw before_tool_call adapters share one rule engine.",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -25,7 +25,7 @@
25
25
  "directory": "packages/tooling/ai-hook-rules"
26
26
  },
27
27
  "dependencies": {
28
- "@webpieces/rules-config": "0.4.612"
28
+ "@webpieces/rules-config": "0.4.614"
29
29
  },
30
30
  "publishConfig": {
31
31
  "access": "public"
@@ -1,5 +1,18 @@
1
1
  import { WebpiecesRulesConfig, MatchRuleConfig } from '@webpieces/rules-config';
2
2
  import type { Rule } from './types';
3
3
  export declare function loadRules(config: WebpiecesRulesConfig, workspaceRoot: string): readonly Rule[];
4
+ /**
5
+ * The EXPERIMENTAL bash guards: rules that have NO webpieces.config.json entry, are switched only from
6
+ * the optional machine-local `~/.webpieces/config.json`, and are therefore deliberately kept out of
7
+ * `builtInRuleNames`/`BUILT_IN_RULE_MAP` — so the config-sync check (fault Y, "every built-in rule needs
8
+ * an entry, or every Bash call is blocked") can never see them. That containment is the whole point:
9
+ * whole-repo-build-guard shipped inside the config-driven set once and took every upgrading consumer's
10
+ * shell down with it.
11
+ *
12
+ * Each rule here decides for itself, from the home config, whether it does anything at all.
13
+ * `affectedBuildCommand` is the project's gate command, passed through so a refusal quotes what THIS
14
+ * repo's gate actually runs.
15
+ */
16
+ export declare function loadExperimentalBashRules(affectedBuildCommand: string): Rule[];
4
17
  export declare function loadMatchRules(matchRules: readonly MatchRuleConfig[]): Rule[];
5
18
  export declare function globMatches(pattern: string, filePath: string): boolean;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.loadRules = loadRules;
4
+ exports.loadExperimentalBashRules = loadExperimentalBashRules;
4
5
  exports.loadMatchRules = loadMatchRules;
5
6
  exports.globMatches = globMatches;
6
7
  const tslib_1 = require("tslib");
@@ -60,7 +61,6 @@ const BUILT_IN_RULE_MAP = {
60
61
  'read-stale-guard': (c) => new read_stale_guard_1.ReadStaleGuardRule(c),
61
62
  'merged-branch-bash-guard': (c) => new merged_branch_bash_guard_1.MergedBranchBashGuardRule(c),
62
63
  'stale-main-bash-guard': (c) => new stale_main_bash_guard_1.StaleMainBashGuardRule(c),
63
- 'whole-repo-build-guard': (c) => new whole_repo_build_guard_1.WholeRepoBuildGuardRule(c),
64
64
  };
65
65
  // Index the typed config by rule name. Each value is the rule's *Config (a plain object from
66
66
  // JSON), or undefined when the rule has no entry yet (the sync check reports those).
@@ -73,6 +73,22 @@ function loadRules(config, workspaceRoot) {
73
73
  const custom = loadCustomRules(config, workspaceRoot);
74
74
  return [...builtIns, ...custom];
75
75
  }
76
+ /**
77
+ * The EXPERIMENTAL bash guards: rules that have NO webpieces.config.json entry, are switched only from
78
+ * the optional machine-local `~/.webpieces/config.json`, and are therefore deliberately kept out of
79
+ * `builtInRuleNames`/`BUILT_IN_RULE_MAP` — so the config-sync check (fault Y, "every built-in rule needs
80
+ * an entry, or every Bash call is blocked") can never see them. That containment is the whole point:
81
+ * whole-repo-build-guard shipped inside the config-driven set once and took every upgrading consumer's
82
+ * shell down with it.
83
+ *
84
+ * Each rule here decides for itself, from the home config, whether it does anything at all.
85
+ * `affectedBuildCommand` is the project's gate command, passed through so a refusal quotes what THIS
86
+ * repo's gate actually runs.
87
+ */
88
+ // webpieces-disable no-function-outside-class -- sibling of loadRules/loadMatchRules in this module; the whole loader is module-scope functions and a lone class for this one would break the file's shape
89
+ function loadExperimentalBashRules(affectedBuildCommand) {
90
+ return [new whole_repo_build_guard_1.WholeRepoBuildGuardRule(affectedBuildCommand)];
91
+ }
76
92
  // One MatchRule per entry of the `match-rules` array. Kept separate from loadRules (built-ins/custom)
77
93
  // because match-rules live in their own validated section — they must NOT flow through the
78
94
  // config-sync check, which compares rule names against the `rules`/`hookGuards` map.
@@ -1 +1 @@
1
- {"version":3,"file":"load-rules.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/core/load-rules.ts"],"names":[],"mappings":";;AAqFA,8BAIC;AAKD,wCAEC;AA2FD,kCAGC;;AA9LD,+CAAyB;AACzB,mDAA6B;AAa7B,mCAAwC;AACxC,yCAAqC;AACrC,2CAA8C;AAC9C,+DAA0D;AAC1D,yCAAiD;AACjD,2DAA0D;AAC1D,6DAA4D;AAC5D,2DAA0D;AAC1D,mEAAiE;AACjE,2DAA2D;AAC3D,qEAAoE;AACpE,6EAA4E;AAC5E,qEAAoE;AACpE,uEAAsE;AACtE,qEAAmE;AACnE,yDAAwD;AACxD,uFAAoF;AACpF,yEAAwE;AACxE,iFAA8E;AAC9E,6EAA2E;AAC3E,2DAA0D;AAC1D,mFAAgF;AAChF,qDAAoD;AACpD,uEAAsE;AACtE,+DAA8D;AAC9D,+EAA6E;AAC7E,yEAAuE;AACvE,2EAAyE;AACzE,mDAA+C;AAE/C,MAAM,eAAe,GAAsB,CAAC,MAAM,EAAE,aAAa,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;AAC9F,MAAM,YAAY,GAAG,IAAI,GAAG,CAAC,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;AAOvD,MAAM,iBAAiB,GAAgC;IACnD,gBAAgB,EAAE,CAAC,CAAiB,EAAE,EAAE,CAAC,IAAI,iCAAgB,CAAC,CAAuB,CAAC;IACtF,iBAAiB,EAAE,CAAC,CAAiB,EAAE,EAAE,CAAC,IAAI,mCAAiB,CAAC,CAAwB,CAAC;IACzF,gBAAgB,EAAE,CAAC,CAAiB,EAAE,EAAE,CAAC,IAAI,iCAAgB,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fs';\nimport * as path from 'path';\n\nimport {\n BaseRuleConfig, RuleOptions, WebpiecesRulesConfig,\n NoAnyUnknownConfig, NoImplicitAnyConfig, MaxFileLinesConfig, ValidateTsInSrcConfig,\n NoDestructureConfig, RequireReturnTypeConfig, NoUnmanagedExceptionsConfig,\n CatchErrorPatternConfig, ThrowCauseRequiredConfig,\n NoSymbolDiTokensConfig, NoCustomCssConfig, NoProcessExitOutsideMainConfig, BranchCreationGuardConfig, PrCreationOrPushGuardConfig,\n MergeInProgressGuardConfig, PrMergeGuardConfig, RedirectHowToMergeMainConfig,\n NoJsFilesConfig, FeatureBranchGuardConfig, ReadStaleGuardConfig, MergedBranchBashGuardConfig, StaleMainBashGuardConfig, WholeRepoBuildGuardConfig, MatchRuleConfig,\n} from '@webpieces/rules-config';\n\nimport type { Rule, PlainRule } from './types';\nimport { InformAiError } from './types';\nimport { toError } from './to-error';\nimport { EmptyRuleConfig } from './rule-base';\nimport { CustomRuleAdapter } from './custom-rule-adapter';\nimport { builtInRuleNames } from './rules/index';\nimport { NoAnyUnknownRule } from './rules/no-any-unknown';\nimport { NoImplicitAnyRule } from './rules/no-implicit-any';\nimport { MaxFileLinesRule } from './rules/max-file-lines';\nimport { ValidateTsInSrcRule } from './rules/validate-ts-in-src';\nimport { NoDestructureRule } from './rules/no-destructure';\nimport { RequireReturnTypeRule } from './rules/require-return-type';\nimport { NoUnmanagedExceptionsRule } from './rules/no-unmanaged-exceptions';\nimport { CatchErrorPatternRule } from './rules/catch-error-pattern';\nimport { ThrowCauseRequiredRule } from './rules/throw-cause-required';\nimport { NoSymbolDiTokensRule } from './rules/no-symbol-di-tokens';\nimport { NoCustomCssRule } from './rules/no-custom-css';\nimport { NoProcessExitOutsideMainRule } from './rules/no-process-exit-outside-main';\nimport { BranchCreationGuardRule } from './rules/branch-creation-guard';\nimport { PrCreationOrPushGuardRule } from './rules/pr-creation-or-push-guard';\nimport { MergeInProgressGuardRule } from './rules/merge-in-progress-guard';\nimport { PrMergeGuardRule } from './rules/pr-merge-guard';\nimport { RedirectHowToMergeMainRule } from './rules/redirect-how-to-merge-main';\nimport { NoJsFilesRule } from './rules/no-js-files';\nimport { FeatureBranchGuardRule } from './rules/feature-branch-guard';\nimport { ReadStaleGuardRule } from './rules/read-stale-guard';\nimport { MergedBranchBashGuardRule } from './rules/merged-branch-bash-guard';\nimport { StaleMainBashGuardRule } from './rules/stale-main-bash-guard';\nimport { WholeRepoBuildGuardRule } from './rules/whole-repo-build-guard';\nimport { MatchRule } from './rules/match-rule';\n\nconst REQUIRED_FIELDS: readonly string[] = ['name', 'description', 'scope', 'files', 'check'];\nconst VALID_SCOPES = new Set(['edit', 'file', 'bash']);\n\n// Each built-in rule is constructed from its typed *Config (the entry in webpieces.config.json).\n// The config arrives as a plain object structurally typed as the *Config class, so the `as`\n// narrows the shared BaseRuleConfig param back to the concrete config the rule consumes.\ntype RuleFactory = (config: BaseRuleConfig) => Rule;\n\nconst BUILT_IN_RULE_MAP: Record<string, RuleFactory> = {\n 'no-any-unknown': (c: BaseRuleConfig) => new NoAnyUnknownRule(c as NoAnyUnknownConfig),\n 'no-implicit-any': (c: BaseRuleConfig) => new NoImplicitAnyRule(c as NoImplicitAnyConfig),\n 'max-file-lines': (c: BaseRuleConfig) => new MaxFileLinesRule(c as MaxFileLinesConfig),\n 'validate-ts-in-src': (c: BaseRuleConfig) => new ValidateTsInSrcRule(c as ValidateTsInSrcConfig),\n 'no-destructure': (c: BaseRuleConfig) => new NoDestructureRule(c as NoDestructureConfig),\n 'require-return-type': (c: BaseRuleConfig) => new RequireReturnTypeRule(c as RequireReturnTypeConfig),\n 'no-unmanaged-exceptions': (c: BaseRuleConfig) => new NoUnmanagedExceptionsRule(c as NoUnmanagedExceptionsConfig),\n 'catch-error-pattern': (c: BaseRuleConfig) => new CatchErrorPatternRule(c as CatchErrorPatternConfig),\n 'throw-cause-required': (c: BaseRuleConfig) => new ThrowCauseRequiredRule(c as ThrowCauseRequiredConfig),\n 'no-symbol-di-tokens': (c: BaseRuleConfig) => new NoSymbolDiTokensRule(c as NoSymbolDiTokensConfig),\n 'no-custom-css': (c: BaseRuleConfig) => new NoCustomCssRule(c as NoCustomCssConfig),\n 'no-process-exit-outside-main': (c: BaseRuleConfig) => new NoProcessExitOutsideMainRule(c as NoProcessExitOutsideMainConfig),\n 'branch-creation-guard': (c: BaseRuleConfig) => new BranchCreationGuardRule(c as BranchCreationGuardConfig),\n 'pr-creation-or-push-guard': (c: BaseRuleConfig) => new PrCreationOrPushGuardRule(c as PrCreationOrPushGuardConfig),\n 'merge-in-progress-guard': (c: BaseRuleConfig) => new MergeInProgressGuardRule(c as MergeInProgressGuardConfig),\n 'pr-merge-guard': (c: BaseRuleConfig) => new PrMergeGuardRule(c as PrMergeGuardConfig),\n 'redirect-how-to-merge-main': (c: BaseRuleConfig) => new RedirectHowToMergeMainRule(c as RedirectHowToMergeMainConfig),\n 'no-js-files': (c: BaseRuleConfig) => new NoJsFilesRule(c as NoJsFilesConfig),\n 'feature-branch-guard': (c: BaseRuleConfig) => new FeatureBranchGuardRule(c as FeatureBranchGuardConfig),\n 'read-stale-guard': (c: BaseRuleConfig) => new ReadStaleGuardRule(c as ReadStaleGuardConfig),\n 'merged-branch-bash-guard': (c: BaseRuleConfig) => new MergedBranchBashGuardRule(c as MergedBranchBashGuardConfig),\n 'stale-main-bash-guard': (c: BaseRuleConfig) => new StaleMainBashGuardRule(c as StaleMainBashGuardConfig),\n 'whole-repo-build-guard': (c: BaseRuleConfig) => new WholeRepoBuildGuardRule(c as WholeRepoBuildGuardConfig),\n};\n\n// Index the typed config by rule name. Each value is the rule's *Config (a plain object from\n// JSON), or undefined when the rule has no entry yet (the sync check reports those).\nfunction asConfigMap(config: WebpiecesRulesConfig): Record<string, BaseRuleConfig | undefined> {\n // webpieces-disable no-any-unknown -- index the typed config by dynamic rule name\n return config as unknown as Record<string, BaseRuleConfig | undefined>;\n}\n\nexport function loadRules(config: WebpiecesRulesConfig, workspaceRoot: string): readonly Rule[] {\n const builtIns = loadBuiltInRules(config);\n const custom = loadCustomRules(config, workspaceRoot);\n return [...builtIns, ...custom];\n}\n\n// One MatchRule per entry of the `match-rules` array. Kept separate from loadRules (built-ins/custom)\n// because match-rules live in their own validated section — they must NOT flow through the\n// config-sync check, which compares rule names against the `rules`/`hookGuards` map.\nexport function loadMatchRules(matchRules: readonly MatchRuleConfig[]): Rule[] {\n return matchRules.map((c: MatchRuleConfig) => new MatchRule(c));\n}\n\nfunction loadBuiltInRules(config: WebpiecesRulesConfig): Rule[] {\n const map = asConfigMap(config);\n const rules: Rule[] = [];\n for (const name of builtInRuleNames) {\n const factory = BUILT_IN_RULE_MAP[name];\n if (!factory) {\n process.stderr.write(`[ai-hooks] unknown built-in rule: ${name}\\n`);\n continue;\n }\n const ruleConfig = map[name] ?? new EmptyRuleConfig();\n rules.push(factory(ruleConfig));\n }\n return rules;\n}\n\nfunction loadCustomRules(config: WebpiecesRulesConfig, workspaceRoot: string): Rule[] {\n const dirs = config.rulesDir ?? [];\n // webpieces-disable no-any-unknown -- index the typed config by dynamic custom-rule name\n const map = config as unknown as Record<string, RuleOptions | undefined>;\n const rules: Rule[] = [];\n for (const plain of loadCustomPlainRules(dirs, workspaceRoot)) {\n const rawConfig = map[plain.name] ?? {};\n rules.push(new CustomRuleAdapter(plain, rawConfig));\n }\n return rules;\n}\n\nfunction loadCustomPlainRules(rulesDirs: readonly string[], workspaceRoot: string): PlainRule[] {\n const modules: PlainRule[] = [];\n for (const dir of rulesDirs) {\n const absDir = path.isAbsolute(dir) ? dir : path.join(workspaceRoot, dir);\n if (!fs.existsSync(absDir)) {\n process.stderr.write(`[ai-hooks] rulesDir not found: ${absDir}\\n`);\n continue;\n }\n let entries: string[];\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n entries = fs.readdirSync(absDir).filter((e: string) => e.endsWith('.js'));\n } catch (err: unknown) {\n const error = toError(err);\n throw new InformAiError(`Cannot read custom rules directory '${absDir}'`, { cause: error });\n }\n for (const entry of entries) {\n const full = path.join(absDir, entry);\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const mod = require(full);\n const candidate = mod.default || mod;\n if (validateRule(candidate)) modules.push(candidate);\n } catch (err: unknown) {\n const error = toError(err);\n throw new InformAiError(`Cannot load custom rule '${full}'`, { cause: error });\n }\n }\n }\n return modules;\n}\n\n// webpieces-disable no-any-unknown -- validates untrusted require() output at system boundary\nfunction validateRule(rule: unknown): rule is PlainRule {\n if (!rule || typeof rule !== 'object') {\n process.stderr.write('[ai-hooks] rule is not an object, skipping\\n');\n return false;\n }\n // webpieces-disable no-any-unknown -- narrowing from unknown at system boundary\n const obj = rule as Record<string, unknown>;\n for (const field of REQUIRED_FIELDS) {\n if (obj[field] === undefined) {\n const name = typeof obj['name'] === 'string' ? obj['name'] : '<unnamed>';\n process.stderr.write(`[ai-hooks] rule \"${name}\" missing required field: ${field}\\n`);\n return false;\n }\n }\n if (!VALID_SCOPES.has(obj['scope'] as string)) {\n process.stderr.write(`[ai-hooks] rule \"${obj['name']}\" has invalid scope: ${String(obj['scope'])}\\n`);\n return false;\n }\n if (!Array.isArray(obj['files'])) {\n process.stderr.write(`[ai-hooks] rule \"${obj['name']}\" files must be an array\\n`);\n return false;\n }\n if (typeof obj['check'] !== 'function') {\n process.stderr.write(`[ai-hooks] rule \"${obj['name']}\" check must be a function\\n`);\n return false;\n }\n return true;\n}\n\nexport function globMatches(pattern: string, filePath: string): boolean {\n const regex = globToRegex(pattern);\n return regex.test(filePath);\n}\n\nfunction globToRegex(pattern: string): RegExp {\n let re = '';\n let i = 0;\n while (i < pattern.length) {\n const ch = pattern[i];\n if (ch === '*') {\n if (pattern[i + 1] === '*') {\n re += '.*';\n i += 2;\n if (pattern[i] === '/') i += 1;\n continue;\n }\n re += '[^/]*';\n i += 1;\n continue;\n }\n if (ch === '?') {\n re += '[^/]';\n i += 1;\n continue;\n }\n if ('.+^$(){}|[]\\\\'.includes(ch)) {\n re += '\\\\' + ch;\n i += 1;\n continue;\n }\n re += ch;\n i += 1;\n }\n return new RegExp('^' + re + '$');\n}\n"]}
1
+ {"version":3,"file":"load-rules.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/core/load-rules.ts"],"names":[],"mappings":";;AAoFA,8BAIC;AAeD,8DAEC;AAKD,wCAEC;AA2FD,kCAGC;;AA9MD,+CAAyB;AACzB,mDAA6B;AAa7B,mCAAwC;AACxC,yCAAqC;AACrC,2CAA8C;AAC9C,+DAA0D;AAC1D,yCAAiD;AACjD,2DAA0D;AAC1D,6DAA4D;AAC5D,2DAA0D;AAC1D,mEAAiE;AACjE,2DAA2D;AAC3D,qEAAoE;AACpE,6EAA4E;AAC5E,qEAAoE;AACpE,uEAAsE;AACtE,qEAAmE;AACnE,yDAAwD;AACxD,uFAAoF;AACpF,yEAAwE;AACxE,iFAA8E;AAC9E,6EAA2E;AAC3E,2DAA0D;AAC1D,mFAAgF;AAChF,qDAAoD;AACpD,uEAAsE;AACtE,+DAA8D;AAC9D,+EAA6E;AAC7E,yEAAuE;AACvE,2EAAyE;AACzE,mDAA+C;AAE/C,MAAM,eAAe,GAAsB,CAAC,MAAM,EAAE,aAAa,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;AAC9F,MAAM,YAAY,GAAG,IAAI,GAAG,CAAC,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;AAOvD,MAAM,iBAAiB,GAAgC;IACnD,gBAAgB,EAAE,CAAC,CAAiB,EAAE,EAAE,CAAC,IAAI,iCAAgB,CAAC,CAAuB,CAAC;IACtF,iBAAiB,EAAE,CAAC,CAAiB,EAAE,EAAE,CAAC,IAAI,mCAAiB,CAAC,CAAwB,CAAC;IACzF,gBAAgB,EAAE,CAAC,CAAiB,EAAE,EAAE,CAAC,IAAI,iCAAgB,CAAC,CAAuB,CAAC;IACtF,oBAAoB,EAAE,CAAC,CAAiB,EAAE,EAAE,CAAC,IAAI,wCAAmB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\n\nimport {\n BaseRuleConfig, RuleOptions, WebpiecesRulesConfig,\n NoAnyUnknownConfig, NoImplicitAnyConfig, MaxFileLinesConfig, ValidateTsInSrcConfig,\n NoDestructureConfig, RequireReturnTypeConfig, NoUnmanagedExceptionsConfig,\n CatchErrorPatternConfig, ThrowCauseRequiredConfig,\n NoSymbolDiTokensConfig, NoCustomCssConfig, NoProcessExitOutsideMainConfig, BranchCreationGuardConfig, PrCreationOrPushGuardConfig,\n MergeInProgressGuardConfig, PrMergeGuardConfig, RedirectHowToMergeMainConfig,\n NoJsFilesConfig, FeatureBranchGuardConfig, ReadStaleGuardConfig, MergedBranchBashGuardConfig, StaleMainBashGuardConfig, MatchRuleConfig,\n} from '@webpieces/rules-config';\n\nimport type { Rule, PlainRule } from './types';\nimport { InformAiError } from './types';\nimport { toError } from './to-error';\nimport { EmptyRuleConfig } from './rule-base';\nimport { CustomRuleAdapter } from './custom-rule-adapter';\nimport { builtInRuleNames } from './rules/index';\nimport { NoAnyUnknownRule } from './rules/no-any-unknown';\nimport { NoImplicitAnyRule } from './rules/no-implicit-any';\nimport { MaxFileLinesRule } from './rules/max-file-lines';\nimport { ValidateTsInSrcRule } from './rules/validate-ts-in-src';\nimport { NoDestructureRule } from './rules/no-destructure';\nimport { RequireReturnTypeRule } from './rules/require-return-type';\nimport { NoUnmanagedExceptionsRule } from './rules/no-unmanaged-exceptions';\nimport { CatchErrorPatternRule } from './rules/catch-error-pattern';\nimport { ThrowCauseRequiredRule } from './rules/throw-cause-required';\nimport { NoSymbolDiTokensRule } from './rules/no-symbol-di-tokens';\nimport { NoCustomCssRule } from './rules/no-custom-css';\nimport { NoProcessExitOutsideMainRule } from './rules/no-process-exit-outside-main';\nimport { BranchCreationGuardRule } from './rules/branch-creation-guard';\nimport { PrCreationOrPushGuardRule } from './rules/pr-creation-or-push-guard';\nimport { MergeInProgressGuardRule } from './rules/merge-in-progress-guard';\nimport { PrMergeGuardRule } from './rules/pr-merge-guard';\nimport { RedirectHowToMergeMainRule } from './rules/redirect-how-to-merge-main';\nimport { NoJsFilesRule } from './rules/no-js-files';\nimport { FeatureBranchGuardRule } from './rules/feature-branch-guard';\nimport { ReadStaleGuardRule } from './rules/read-stale-guard';\nimport { MergedBranchBashGuardRule } from './rules/merged-branch-bash-guard';\nimport { StaleMainBashGuardRule } from './rules/stale-main-bash-guard';\nimport { WholeRepoBuildGuardRule } from './rules/whole-repo-build-guard';\nimport { MatchRule } from './rules/match-rule';\n\nconst REQUIRED_FIELDS: readonly string[] = ['name', 'description', 'scope', 'files', 'check'];\nconst VALID_SCOPES = new Set(['edit', 'file', 'bash']);\n\n// Each built-in rule is constructed from its typed *Config (the entry in webpieces.config.json).\n// The config arrives as a plain object structurally typed as the *Config class, so the `as`\n// narrows the shared BaseRuleConfig param back to the concrete config the rule consumes.\ntype RuleFactory = (config: BaseRuleConfig) => Rule;\n\nconst BUILT_IN_RULE_MAP: Record<string, RuleFactory> = {\n 'no-any-unknown': (c: BaseRuleConfig) => new NoAnyUnknownRule(c as NoAnyUnknownConfig),\n 'no-implicit-any': (c: BaseRuleConfig) => new NoImplicitAnyRule(c as NoImplicitAnyConfig),\n 'max-file-lines': (c: BaseRuleConfig) => new MaxFileLinesRule(c as MaxFileLinesConfig),\n 'validate-ts-in-src': (c: BaseRuleConfig) => new ValidateTsInSrcRule(c as ValidateTsInSrcConfig),\n 'no-destructure': (c: BaseRuleConfig) => new NoDestructureRule(c as NoDestructureConfig),\n 'require-return-type': (c: BaseRuleConfig) => new RequireReturnTypeRule(c as RequireReturnTypeConfig),\n 'no-unmanaged-exceptions': (c: BaseRuleConfig) => new NoUnmanagedExceptionsRule(c as NoUnmanagedExceptionsConfig),\n 'catch-error-pattern': (c: BaseRuleConfig) => new CatchErrorPatternRule(c as CatchErrorPatternConfig),\n 'throw-cause-required': (c: BaseRuleConfig) => new ThrowCauseRequiredRule(c as ThrowCauseRequiredConfig),\n 'no-symbol-di-tokens': (c: BaseRuleConfig) => new NoSymbolDiTokensRule(c as NoSymbolDiTokensConfig),\n 'no-custom-css': (c: BaseRuleConfig) => new NoCustomCssRule(c as NoCustomCssConfig),\n 'no-process-exit-outside-main': (c: BaseRuleConfig) => new NoProcessExitOutsideMainRule(c as NoProcessExitOutsideMainConfig),\n 'branch-creation-guard': (c: BaseRuleConfig) => new BranchCreationGuardRule(c as BranchCreationGuardConfig),\n 'pr-creation-or-push-guard': (c: BaseRuleConfig) => new PrCreationOrPushGuardRule(c as PrCreationOrPushGuardConfig),\n 'merge-in-progress-guard': (c: BaseRuleConfig) => new MergeInProgressGuardRule(c as MergeInProgressGuardConfig),\n 'pr-merge-guard': (c: BaseRuleConfig) => new PrMergeGuardRule(c as PrMergeGuardConfig),\n 'redirect-how-to-merge-main': (c: BaseRuleConfig) => new RedirectHowToMergeMainRule(c as RedirectHowToMergeMainConfig),\n 'no-js-files': (c: BaseRuleConfig) => new NoJsFilesRule(c as NoJsFilesConfig),\n 'feature-branch-guard': (c: BaseRuleConfig) => new FeatureBranchGuardRule(c as FeatureBranchGuardConfig),\n 'read-stale-guard': (c: BaseRuleConfig) => new ReadStaleGuardRule(c as ReadStaleGuardConfig),\n 'merged-branch-bash-guard': (c: BaseRuleConfig) => new MergedBranchBashGuardRule(c as MergedBranchBashGuardConfig),\n 'stale-main-bash-guard': (c: BaseRuleConfig) => new StaleMainBashGuardRule(c as StaleMainBashGuardConfig),\n};\n\n// Index the typed config by rule name. Each value is the rule's *Config (a plain object from\n// JSON), or undefined when the rule has no entry yet (the sync check reports those).\nfunction asConfigMap(config: WebpiecesRulesConfig): Record<string, BaseRuleConfig | undefined> {\n // webpieces-disable no-any-unknown -- index the typed config by dynamic rule name\n return config as unknown as Record<string, BaseRuleConfig | undefined>;\n}\n\nexport function loadRules(config: WebpiecesRulesConfig, workspaceRoot: string): readonly Rule[] {\n const builtIns = loadBuiltInRules(config);\n const custom = loadCustomRules(config, workspaceRoot);\n return [...builtIns, ...custom];\n}\n\n/**\n * The EXPERIMENTAL bash guards: rules that have NO webpieces.config.json entry, are switched only from\n * the optional machine-local `~/.webpieces/config.json`, and are therefore deliberately kept out of\n * `builtInRuleNames`/`BUILT_IN_RULE_MAP` — so the config-sync check (fault Y, \"every built-in rule needs\n * an entry, or every Bash call is blocked\") can never see them. That containment is the whole point:\n * whole-repo-build-guard shipped inside the config-driven set once and took every upgrading consumer's\n * shell down with it.\n *\n * Each rule here decides for itself, from the home config, whether it does anything at all.\n * `affectedBuildCommand` is the project's gate command, passed through so a refusal quotes what THIS\n * repo's gate actually runs.\n */\n// webpieces-disable no-function-outside-class -- sibling of loadRules/loadMatchRules in this module; the whole loader is module-scope functions and a lone class for this one would break the file's shape\nexport function loadExperimentalBashRules(affectedBuildCommand: string): Rule[] {\n return [new WholeRepoBuildGuardRule(affectedBuildCommand)];\n}\n\n// One MatchRule per entry of the `match-rules` array. Kept separate from loadRules (built-ins/custom)\n// because match-rules live in their own validated section — they must NOT flow through the\n// config-sync check, which compares rule names against the `rules`/`hookGuards` map.\nexport function loadMatchRules(matchRules: readonly MatchRuleConfig[]): Rule[] {\n return matchRules.map((c: MatchRuleConfig) => new MatchRule(c));\n}\n\nfunction loadBuiltInRules(config: WebpiecesRulesConfig): Rule[] {\n const map = asConfigMap(config);\n const rules: Rule[] = [];\n for (const name of builtInRuleNames) {\n const factory = BUILT_IN_RULE_MAP[name];\n if (!factory) {\n process.stderr.write(`[ai-hooks] unknown built-in rule: ${name}\\n`);\n continue;\n }\n const ruleConfig = map[name] ?? new EmptyRuleConfig();\n rules.push(factory(ruleConfig));\n }\n return rules;\n}\n\nfunction loadCustomRules(config: WebpiecesRulesConfig, workspaceRoot: string): Rule[] {\n const dirs = config.rulesDir ?? [];\n // webpieces-disable no-any-unknown -- index the typed config by dynamic custom-rule name\n const map = config as unknown as Record<string, RuleOptions | undefined>;\n const rules: Rule[] = [];\n for (const plain of loadCustomPlainRules(dirs, workspaceRoot)) {\n const rawConfig = map[plain.name] ?? {};\n rules.push(new CustomRuleAdapter(plain, rawConfig));\n }\n return rules;\n}\n\nfunction loadCustomPlainRules(rulesDirs: readonly string[], workspaceRoot: string): PlainRule[] {\n const modules: PlainRule[] = [];\n for (const dir of rulesDirs) {\n const absDir = path.isAbsolute(dir) ? dir : path.join(workspaceRoot, dir);\n if (!fs.existsSync(absDir)) {\n process.stderr.write(`[ai-hooks] rulesDir not found: ${absDir}\\n`);\n continue;\n }\n let entries: string[];\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n entries = fs.readdirSync(absDir).filter((e: string) => e.endsWith('.js'));\n } catch (err: unknown) {\n const error = toError(err);\n throw new InformAiError(`Cannot read custom rules directory '${absDir}'`, { cause: error });\n }\n for (const entry of entries) {\n const full = path.join(absDir, entry);\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const mod = require(full);\n const candidate = mod.default || mod;\n if (validateRule(candidate)) modules.push(candidate);\n } catch (err: unknown) {\n const error = toError(err);\n throw new InformAiError(`Cannot load custom rule '${full}'`, { cause: error });\n }\n }\n }\n return modules;\n}\n\n// webpieces-disable no-any-unknown -- validates untrusted require() output at system boundary\nfunction validateRule(rule: unknown): rule is PlainRule {\n if (!rule || typeof rule !== 'object') {\n process.stderr.write('[ai-hooks] rule is not an object, skipping\\n');\n return false;\n }\n // webpieces-disable no-any-unknown -- narrowing from unknown at system boundary\n const obj = rule as Record<string, unknown>;\n for (const field of REQUIRED_FIELDS) {\n if (obj[field] === undefined) {\n const name = typeof obj['name'] === 'string' ? obj['name'] : '<unnamed>';\n process.stderr.write(`[ai-hooks] rule \"${name}\" missing required field: ${field}\\n`);\n return false;\n }\n }\n if (!VALID_SCOPES.has(obj['scope'] as string)) {\n process.stderr.write(`[ai-hooks] rule \"${obj['name']}\" has invalid scope: ${String(obj['scope'])}\\n`);\n return false;\n }\n if (!Array.isArray(obj['files'])) {\n process.stderr.write(`[ai-hooks] rule \"${obj['name']}\" files must be an array\\n`);\n return false;\n }\n if (typeof obj['check'] !== 'function') {\n process.stderr.write(`[ai-hooks] rule \"${obj['name']}\" check must be a function\\n`);\n return false;\n }\n return true;\n}\n\nexport function globMatches(pattern: string, filePath: string): boolean {\n const regex = globToRegex(pattern);\n return regex.test(filePath);\n}\n\nfunction globToRegex(pattern: string): RegExp {\n let re = '';\n let i = 0;\n while (i < pattern.length) {\n const ch = pattern[i];\n if (ch === '*') {\n if (pattern[i + 1] === '*') {\n re += '.*';\n i += 2;\n if (pattern[i] === '/') i += 1;\n continue;\n }\n re += '[^/]*';\n i += 1;\n continue;\n }\n if (ch === '?') {\n re += '[^/]';\n i += 1;\n continue;\n }\n if ('.+^$(){}|[]\\\\'.includes(ch)) {\n re += '\\\\' + ch;\n i += 1;\n continue;\n }\n re += ch;\n i += 1;\n }\n return new RegExp('^' + re + '$');\n}\n"]}
@@ -24,6 +24,5 @@ exports.builtInRuleNames = [
24
24
  'read-stale-guard',
25
25
  'merged-branch-bash-guard',
26
26
  'stale-main-bash-guard',
27
- 'whole-repo-build-guard',
28
27
  ];
29
28
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/ai-hook-rules/src/core/rules/index.ts"],"names":[],"mappings":";;;AAAa,QAAA,gBAAgB,GAAsB;IAC/C,gBAAgB;IAChB,iBAAiB;IACjB,gBAAgB;IAChB,oBAAoB;IACpB,aAAa;IACb,gBAAgB;IAChB,qBAAqB;IACrB,yBAAyB;IACzB,qBAAqB;IACrB,sBAAsB;IACtB,qBAAqB;IACrB,eAAe;IACf,8BAA8B;IAC9B,uBAAuB;IACvB,2BAA2B;IAC3B,yBAAyB;IACzB,gBAAgB;IAChB,4BAA4B;IAC5B,sBAAsB;IACtB,kBAAkB;IAClB,0BAA0B;IAC1B,uBAAuB;IACvB,wBAAwB;CAC3B,CAAC","sourcesContent":["export const builtInRuleNames: readonly string[] = [\n 'no-any-unknown',\n 'no-implicit-any',\n 'max-file-lines',\n 'validate-ts-in-src',\n 'no-js-files',\n 'no-destructure',\n 'require-return-type',\n 'no-unmanaged-exceptions',\n 'catch-error-pattern',\n 'throw-cause-required',\n 'no-symbol-di-tokens',\n 'no-custom-css',\n 'no-process-exit-outside-main',\n 'branch-creation-guard',\n 'pr-creation-or-push-guard',\n 'merge-in-progress-guard',\n 'pr-merge-guard',\n 'redirect-how-to-merge-main',\n 'feature-branch-guard',\n 'read-stale-guard',\n 'merged-branch-bash-guard',\n 'stale-main-bash-guard',\n 'whole-repo-build-guard',\n];\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/ai-hook-rules/src/core/rules/index.ts"],"names":[],"mappings":";;;AAAa,QAAA,gBAAgB,GAAsB;IAC/C,gBAAgB;IAChB,iBAAiB;IACjB,gBAAgB;IAChB,oBAAoB;IACpB,aAAa;IACb,gBAAgB;IAChB,qBAAqB;IACrB,yBAAyB;IACzB,qBAAqB;IACrB,sBAAsB;IACtB,qBAAqB;IACrB,eAAe;IACf,8BAA8B;IAC9B,uBAAuB;IACvB,2BAA2B;IAC3B,yBAAyB;IACzB,gBAAgB;IAChB,4BAA4B;IAC5B,sBAAsB;IACtB,kBAAkB;IAClB,0BAA0B;IAC1B,uBAAuB;CAC1B,CAAC","sourcesContent":["export const builtInRuleNames: readonly string[] = [\n 'no-any-unknown',\n 'no-implicit-any',\n 'max-file-lines',\n 'validate-ts-in-src',\n 'no-js-files',\n 'no-destructure',\n 'require-return-type',\n 'no-unmanaged-exceptions',\n 'catch-error-pattern',\n 'throw-cause-required',\n 'no-symbol-di-tokens',\n 'no-custom-css',\n 'no-process-exit-outside-main',\n 'branch-creation-guard',\n 'pr-creation-or-push-guard',\n 'merge-in-progress-guard',\n 'pr-merge-guard',\n 'redirect-how-to-merge-main',\n 'feature-branch-guard',\n 'read-stale-guard',\n 'merged-branch-bash-guard',\n 'stale-main-bash-guard',\n];\n"]}
@@ -1,6 +1,5 @@
1
- import { WholeRepoBuildGuardConfig } from '@webpieces/rules-config';
2
1
  import type { BashContext, Violation } from '../types';
3
- import { BashRuleBase } from '../rule-base';
2
+ import { BashRuleBase, EmptyRuleConfig } from '../rule-base';
4
3
  import { FixHint } from '../fix-hint';
5
4
  /**
6
5
  * Blocks a Bash command that would build or test the WHOLE monorepo, and hands back the narrow
@@ -32,12 +31,29 @@ import { FixHint } from '../fix-hint';
32
31
  * that reads like the guard's advice was wrong. Only `$(git …)` is expanded, and only read-only git;
33
32
  * anything else is left verbatim.
34
33
  *
35
- * ─── Two messages, chosen by ~/.webpieces/config.json ──────────────────────────────────────────────
36
- * With `experimental.buildGateLogCapture` ON, the pr-gate captures its build's full output to a log
37
- * file and hands the agent that path instead of a rebuild instruction so the right advice is not
38
- * "build smaller", it is "do not build; stage already builds and you can READ the result". That flag
39
- * lives in the OPTIONAL machine-local `~/.webpieces/config.json`; absent (the state of essentially
40
- * every consumer) means the first message. `HomeConfigService` is the one reader of that file.
34
+ * ─── EXPERIMENTAL: the ONLY switch is ~/.webpieces/config.json ─────────────────────────────────────
35
+ * `experimental.whole-repo-build-guard` (a boolean) decides whether this guard blocks anything at all.
36
+ * There is NO webpieces.config.json entry deliberately, and the reason is a live incident: this guard
37
+ * first shipped as an ordinary validated guard with `mode: 'ON'` by default AND a required entry under
38
+ * `hookGuards`, so every consumer that upgraded hit fault Y EVERY Bash call blocked — for a feature
39
+ * they had never asked for. An experimental feature is opted into from a machine-local file whose absent
40
+ * state is byte-for-byte the old behaviour, or it is not experimental.
41
+ *
42
+ * Three states, and only three:
43
+ * - the file does not exist (essentially every consumer) → this guard is INERT. It blocks nothing and
44
+ * logs nothing, for every command, including the ones it would otherwise refuse.
45
+ * - the file exists and defines the key → the key's value decides.
46
+ * - the file exists and is unparseable, or does not define the key → HARD FAILURE naming the edit. A
47
+ * file someone deliberately created must be correct, and `HomeConfigService` requires that key
48
+ * precisely because guessing either way is wrong (see readRequiredBoolean). Editing that file is an
49
+ * unconditional PASS in the guards, so the block is always self-curable.
50
+ *
51
+ * ─── Two messages, chosen by a DIFFERENT key ───────────────────────────────────────────────────────
52
+ * `experimental.buildGateLogCapture` is a separate feature (the pr-gate captures its build's full output
53
+ * to a log file and hands the agent that path instead of a rebuild instruction) and it is NOT this
54
+ * guard's switch. It only picks WHICH refusal is printed once the guard is on: with capture ON the right
55
+ * advice is not "build smaller", it is "do not build; stage ② already builds and you can READ the
56
+ * result". `HomeConfigService` is the one reader of both keys.
41
57
  *
42
58
  * ─── Humans are not affected, by construction ──────────────────────────────────────────────────────
43
59
  * This is a PreToolUse hook. It sees the AI's Bash tool calls and nothing else — a human typing
@@ -45,10 +61,18 @@ import { FixHint } from '../fix-hint';
45
61
  * deliberately left in package.json for exactly that reason. The guard is about what the AI does in a
46
62
  * loop, not about the command being wrong for a person who chooses to run it once.
47
63
  */
48
- export declare class WholeRepoBuildGuardRule extends BashRuleBase<WholeRepoBuildGuardConfig> {
49
- constructor(config: WholeRepoBuildGuardConfig);
64
+ export declare class WholeRepoBuildGuardRule extends BashRuleBase<EmptyRuleConfig> {
65
+ private readonly affectedBuildCommand;
66
+ /**
67
+ * `affectedBuildCommand` is the project's gate command (`commands.pr-gate.buildCommand`), handed in
68
+ * by the runner off the loaded config. It is a CONSTRUCTOR ARGUMENT rather than a config field
69
+ * because this guard has no config entry to read one from — and that is the point.
70
+ */
71
+ constructor(affectedBuildCommand: string);
50
72
  private readonly scanner;
51
73
  private readonly homeConfig;
74
+ /** Set by check() when the home config is unreadable, so the fix hint names the same repair. */
75
+ private homeConfigError;
52
76
  readonly description: string;
53
77
  /**
54
78
  * The command this rule last printed, so the fix hint and the violation message are one string and
@@ -59,13 +83,20 @@ export declare class WholeRepoBuildGuardRule extends BashRuleBase<WholeRepoBuild
59
83
  private resolvedCommand;
60
84
  get fixHint(): FixHint;
61
85
  check(ctx: BashContext): readonly Violation[];
86
+ /**
87
+ * The home config, or the Error explaining why it is unusable. NOT a boolean: "absent" is already
88
+ * folded into the returned HomeConfig (all-defaults, guard off), so the only thing left to
89
+ * distinguish is "present and wrong", which must be reported rather than swallowed.
90
+ */
91
+ private loadHome;
92
+ private blockOnBrokenHomeConfig;
93
+ private brokenHomeConfigMessage;
62
94
  private message;
63
95
  /**
64
- * The project's build command, unexpanded. ONE source: `commands.pr-gate.buildCommand`, injected
65
- * into this guard's config by load-config exactly as the other guards' command hints are, falling
66
- * back to the same DEFAULT_BUILD_COMMAND the gate itself falls back to. This guard never spells a
67
- * build command of its own — a second copy is how a refusal starts teaching a command the gate
68
- * does not run.
96
+ * The project's build command, unexpanded. ONE source: `commands.pr-gate.buildCommand`, handed to
97
+ * the constructor by the runner, falling back to the same DEFAULT_BUILD_COMMAND the gate itself
98
+ * falls back to. This guard never spells a build command of its own a second copy is how a refusal
99
+ * starts teaching a command the gate does not run.
69
100
  */
70
101
  private buildCommandTemplate;
71
102
  /**
@@ -75,12 +106,6 @@ export declare class WholeRepoBuildGuardRule extends BashRuleBase<WholeRepoBuild
75
106
  */
76
107
  private resolvedBuildCommand;
77
108
  private capture;
78
- /**
79
- * Is build-log capture on? The OPTIONAL `~/.webpieces/config.json` is absent for essentially every
80
- * consumer, and absent means false, silently — so a broken or unreadable home config can never be
81
- * the reason a Bash command is judged differently. Fail toward the ordinary message.
82
- */
83
- private captureEnabled;
84
109
  private allow;
85
110
  private block;
86
111
  private truncate;
@@ -41,12 +41,29 @@ const whole_repo_build_scan_1 = require("./whole-repo-build-scan");
41
41
  * that reads like the guard's advice was wrong. Only `$(git …)` is expanded, and only read-only git;
42
42
  * anything else is left verbatim.
43
43
  *
44
- * ─── Two messages, chosen by ~/.webpieces/config.json ──────────────────────────────────────────────
45
- * With `experimental.buildGateLogCapture` ON, the pr-gate captures its build's full output to a log
46
- * file and hands the agent that path instead of a rebuild instruction so the right advice is not
47
- * "build smaller", it is "do not build; stage already builds and you can READ the result". That flag
48
- * lives in the OPTIONAL machine-local `~/.webpieces/config.json`; absent (the state of essentially
49
- * every consumer) means the first message. `HomeConfigService` is the one reader of that file.
44
+ * ─── EXPERIMENTAL: the ONLY switch is ~/.webpieces/config.json ─────────────────────────────────────
45
+ * `experimental.whole-repo-build-guard` (a boolean) decides whether this guard blocks anything at all.
46
+ * There is NO webpieces.config.json entry deliberately, and the reason is a live incident: this guard
47
+ * first shipped as an ordinary validated guard with `mode: 'ON'` by default AND a required entry under
48
+ * `hookGuards`, so every consumer that upgraded hit fault Y EVERY Bash call blocked — for a feature
49
+ * they had never asked for. An experimental feature is opted into from a machine-local file whose absent
50
+ * state is byte-for-byte the old behaviour, or it is not experimental.
51
+ *
52
+ * Three states, and only three:
53
+ * - the file does not exist (essentially every consumer) → this guard is INERT. It blocks nothing and
54
+ * logs nothing, for every command, including the ones it would otherwise refuse.
55
+ * - the file exists and defines the key → the key's value decides.
56
+ * - the file exists and is unparseable, or does not define the key → HARD FAILURE naming the edit. A
57
+ * file someone deliberately created must be correct, and `HomeConfigService` requires that key
58
+ * precisely because guessing either way is wrong (see readRequiredBoolean). Editing that file is an
59
+ * unconditional PASS in the guards, so the block is always self-curable.
60
+ *
61
+ * ─── Two messages, chosen by a DIFFERENT key ───────────────────────────────────────────────────────
62
+ * `experimental.buildGateLogCapture` is a separate feature (the pr-gate captures its build's full output
63
+ * to a log file and hands the agent that path instead of a rebuild instruction) and it is NOT this
64
+ * guard's switch. It only picks WHICH refusal is printed once the guard is on: with capture ON the right
65
+ * advice is not "build smaller", it is "do not build; stage ② already builds and you can READ the
66
+ * result". `HomeConfigService` is the one reader of both keys.
50
67
  *
51
68
  * ─── Humans are not affected, by construction ──────────────────────────────────────────────────────
52
69
  * This is a PreToolUse hook. It sees the AI's Bash tool calls and nothing else — a human typing
@@ -55,9 +72,20 @@ const whole_repo_build_scan_1 = require("./whole-repo-build-scan");
55
72
  * loop, not about the command being wrong for a person who chooses to run it once.
56
73
  */
57
74
  class WholeRepoBuildGuardRule extends rule_base_1.BashRuleBase {
58
- constructor(config) { super(config, 'whole-repo-build-guard'); }
75
+ affectedBuildCommand;
76
+ /**
77
+ * `affectedBuildCommand` is the project's gate command (`commands.pr-gate.buildCommand`), handed in
78
+ * by the runner off the loaded config. It is a CONSTRUCTOR ARGUMENT rather than a config field
79
+ * because this guard has no config entry to read one from — and that is the point.
80
+ */
81
+ constructor(affectedBuildCommand) {
82
+ super(new rule_base_1.EmptyRuleConfig(), 'whole-repo-build-guard');
83
+ this.affectedBuildCommand = affectedBuildCommand;
84
+ }
59
85
  scanner = new command_scan_1.CommandScanner();
60
86
  homeConfig = new rules_config_1.HomeConfigService();
87
+ /** Set by check() when the home config is unreadable, so the fix hint names the same repair. */
88
+ homeConfigError = '';
61
89
  description = 'Block a whole-monorepo build (build-all, an unnarrowed nx run-many, nx affected with no ' +
62
90
  '--base, a bare vitest run) and name the affected-scoped command to run instead.';
63
91
  /**
@@ -68,14 +96,32 @@ class WholeRepoBuildGuardRule extends rule_base_1.BashRuleBase {
68
96
  */
69
97
  resolvedCommand = '';
70
98
  get fixHint() {
99
+ if (this.homeConfigError !== '') {
100
+ return new fix_hint_1.FixHint('~/.webpieces/config.json exists but cannot be read.', 'Edit ~/.webpieces/config.json (editing it is always permitted, including right now), or ' +
101
+ 'delete it outright — with no such file every webpieces command behaves exactly as it ' +
102
+ 'does by default.');
103
+ }
71
104
  const command = this.resolvedCommand !== '' ? this.resolvedCommand : this.buildCommandTemplate();
72
105
  return new fix_hint_1.FixHint('That command builds the WHOLE monorepo. Build only what your change affects.', 'Build the affected projects, or one project, or one spec file — never the workspace:\n' +
73
106
  ` ${command} # the gate's own build\n` +
74
107
  ' pnpm nx run <project>:ci # one project\n' +
75
108
  ' pnpm exec vitest run <path> # one suite\n' +
76
- 'Disable in webpieces.config.json under hookGuards whole-repo-build-guard (mode OFF) if intentional.');
109
+ 'Turn this guard off for this machine by setting "experimental": ' +
110
+ '{ "whole-repo-build-guard": false } in ~/.webpieces/config.json (there is no ' +
111
+ 'webpieces.config.json entry for it).');
77
112
  }
78
113
  check(ctx) {
114
+ const home = this.loadHome();
115
+ // A file someone deliberately created must be correct — see the class docstring. Reported for
116
+ // whatever command happens to be running, because a broken opt-in file is not a build question.
117
+ if (home instanceof Error)
118
+ return this.blockOnBrokenHomeConfig(ctx, home);
119
+ // THE EXPERIMENTAL GATE, and the state of essentially every consumer. Silent on purpose: no
120
+ // block, no log, no file touched — "no ~/.webpieces/config.json" must be indistinguishable from
121
+ // "this guard does not exist".
122
+ this.homeConfigError = '';
123
+ if (!home.wholeRepoBuildGuard)
124
+ return [];
79
125
  // Blocklist-shaped, so match on commandCode: stripping heredocs and quoted prose can only ever
80
126
  // block LESS, and this repo's own commit messages are full of the command names above.
81
127
  const hit = new whole_repo_build_scan_1.WholeRepoBuildScan(this.scanner, ctx.effectiveCwd === ctx.workspaceRoot)
@@ -84,12 +130,40 @@ class WholeRepoBuildGuardRule extends rule_base_1.BashRuleBase {
84
130
  return this.allow(ctx, 'not-a-whole-repo-build');
85
131
  // Resolved ONCE, here, and read by both the violation message and the fix hint.
86
132
  this.resolvedCommand = this.resolvedBuildCommand(ctx.workspaceRoot);
87
- return this.block(ctx, hit, this.message());
133
+ return this.block(ctx, hit, this.message(home));
134
+ }
135
+ /**
136
+ * The home config, or the Error explaining why it is unusable. NOT a boolean: "absent" is already
137
+ * folded into the returned HomeConfig (all-defaults, guard off), so the only thing left to
138
+ * distinguish is "present and wrong", which must be reported rather than swallowed.
139
+ */
140
+ loadHome() {
141
+ // webpieces-disable no-unmanaged-exceptions -- chokepoint: a rejected home config is converted
142
+ // into this guard's own block, which carries the loader's fix instruction verbatim
143
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
144
+ try {
145
+ return this.homeConfig.load();
146
+ }
147
+ catch (err) {
148
+ const error = (0, to_error_1.toError)(err);
149
+ return error;
150
+ }
151
+ }
152
+ blockOnBrokenHomeConfig(ctx, error) {
153
+ this.homeConfigError = error.message;
154
+ this.logDecision(ctx, 'BLOCK_AI_CURE', 'home-config-invalid');
155
+ return [new types_1.Violation(1, this.truncate(ctx.command), this.brokenHomeConfigMessage(error))];
156
+ }
157
+ brokenHomeConfigMessage(error) {
158
+ const detail = error instanceof rules_config_1.InformAiError
159
+ ? error.message
160
+ : `~/.webpieces/config.json could not be read: ${error.message}`;
161
+ return `Blocked: ~/.webpieces/config.json is present but unusable.\n\n${detail}`;
88
162
  }
89
163
  // The whole refusal. Short on purpose: it is read mid-task by an agent that needs the ONE command
90
164
  // to run next, and a guard message long enough to skim is a guard message that gets skimmed.
91
- message() {
92
- if (this.captureEnabled()) {
165
+ message(home) {
166
+ if (home.buildGateLogCapture) {
93
167
  return 'Blocked: that builds the WHOLE monorepo — and you should not be building at all.\n'
94
168
  + '`pnpm wp-review-upsert-pr` (stage ②) runs the build for you, captures the full output to a\n'
95
169
  + 'log file, and names that file if it fails. Read the file; do not rebuild.\n'
@@ -100,15 +174,13 @@ class WholeRepoBuildGuardRule extends rule_base_1.BashRuleBase {
100
174
  + 'Narrower still: pnpm nx run <project>:ci, or pnpm exec vitest run <path>.';
101
175
  }
102
176
  /**
103
- * The project's build command, unexpanded. ONE source: `commands.pr-gate.buildCommand`, injected
104
- * into this guard's config by load-config exactly as the other guards' command hints are, falling
105
- * back to the same DEFAULT_BUILD_COMMAND the gate itself falls back to. This guard never spells a
106
- * build command of its own — a second copy is how a refusal starts teaching a command the gate
107
- * does not run.
177
+ * The project's build command, unexpanded. ONE source: `commands.pr-gate.buildCommand`, handed to
178
+ * the constructor by the runner, falling back to the same DEFAULT_BUILD_COMMAND the gate itself
179
+ * falls back to. This guard never spells a build command of its own a second copy is how a refusal
180
+ * starts teaching a command the gate does not run.
108
181
  */
109
182
  buildCommandTemplate() {
110
- const configured = this.config.affectedBuildCommand ?? '';
111
- return configured.trim() === '' ? rules_config_1.DEFAULT_BUILD_COMMAND : configured;
183
+ return this.affectedBuildCommand.trim() === '' ? rules_config_1.DEFAULT_BUILD_COMMAND : this.affectedBuildCommand;
112
184
  }
113
185
  /**
114
186
  * The configured build command with its `$(git …)` substitutions expanded, so what is printed is
@@ -138,22 +210,6 @@ class WholeRepoBuildGuardRule extends rule_base_1.BashRuleBase {
138
210
  return null;
139
211
  }
140
212
  }
141
- /**
142
- * Is build-log capture on? The OPTIONAL `~/.webpieces/config.json` is absent for essentially every
143
- * consumer, and absent means false, silently — so a broken or unreadable home config can never be
144
- * the reason a Bash command is judged differently. Fail toward the ordinary message.
145
- */
146
- captureEnabled() {
147
- // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
148
- try {
149
- return this.homeConfig.load().buildGateLogCapture;
150
- }
151
- catch (err) {
152
- const error = (0, to_error_1.toError)(err);
153
- void error;
154
- return false;
155
- }
156
- }
157
213
  allow(ctx, reason) {
158
214
  this.logDecision(ctx, 'ALLOW', reason);
159
215
  return [];
@@ -1 +1 @@
1
- {"version":3,"file":"whole-repo-build-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/ai-hook-rules/src/core/rules/whole-repo-build-guard.ts"],"names":[],"mappings":";;;AAAA,iDAAyC;AAEzC,0DAA8G;AAG9G,oCAA0C;AAC1C,4CAA4C;AAC5C,0CAAsC;AACtC,0CAAsC;AACtC,sDAAkD;AAClD,kDAAsF;AACtF,kDAAiD;AACjD,mEAAgF;AAEhF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH,MAAa,uBAAwB,SAAQ,wBAAuC;IAChF,YAAY,MAAiC,IAAI,KAAK,CAAC,MAAM,EAAE,wBAAwB,CAAC,CAAC,CAAC,CAAC;IAE1E,OAAO,GAAG,IAAI,6BAAc,EAAE,CAAC;IAC/B,UAAU,GAAG,IAAI,gCAAiB,EAAE,CAAC;IAE7C,WAAW,GAChB,0FAA0F;QAC1F,iFAAiF,CAAC;IAEtF;;;;;OAKG;IACK,eAAe,GAAG,EAAE,CAAC;IAE7B,IAAI,OAAO;QACP,MAAM,OAAO,GAAG,IAAI,CAAC,eAAe,KAAK,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC,IAAI,CAAC,oBAAoB,EAAE,CAAC;QACjG,OAAO,IAAI,kBAA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CAAC,GAAG,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;QACvC,OAAO,EAAE,CAAC;IACd,CAAC;IAEO,KAAK,CAAC,GAAgB,EAAE,GAAsB,EAAE,OAAe;QACnE,yFAAyF;QACzF,0CAA0C;QAC1C,IAAI,CAAC,WAAW,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC;QAClD,OAAO,CAAC,IAAI,iBAAC,CAAC,CAAC,EAAE,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC;IAC3D,CAAC;IAEO,QAAQ,CAAC,CAAS;QACtB,MAAM,GAAG,GAAG,GAAG,CAAC;QAChB,OAAO,CAAC,CAAC,MAAM,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,GAAG,GAAG,CAAC;IACvD,CAAC;IAEO,WAAW,CAAC,GAAgB,EAAE,OAAgB,EAAE,MAAc;QAClE,IAAA,+BAAgB,EACZ,GAAG,CAAC,aAAa,EACjB,IAAI,4BAAa,CAAC,wBAAwB,EAAE,MAAM,EAAE,GAAG,CAAC,OAAO,EAAE,GAAG,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,8BAAa,EAAE,wBAAS,CAAC,CACxH,CAAC;IACN,CAAC;CACJ;AAvID,0DAuIC","sourcesContent":["import { execSync } from 'child_process';\n\nimport { WholeRepoBuildGuardConfig, DEFAULT_BUILD_COMMAND, HomeConfigService } from '@webpieces/rules-config';\n\nimport type { BashContext, Violation } from '../types';\nimport { Violation as V } from '../types';\nimport { BashRuleBase } from '../rule-base';\nimport { FixHint } from '../fix-hint';\nimport { toError } from '../to-error';\nimport { L0_FAULT_NONE } from '../l0-fault-codes';\nimport { logGuardDecision, GuardDecision, Verdict, MATRIX_L2 } from '../decision-log';\nimport { CommandScanner } from '../command-scan';\nimport { WholeRepoBuildScan, WholeRepoBuildHit } from './whole-repo-build-scan';\n\n/**\n * Blocks a Bash command that would build or test the WHOLE monorepo, and hands back the narrow\n * command to run instead. Which shapes count is `WholeRepoBuildScan`'s job; this rule owns the\n * decision, the log line and the two refusal messages.\n *\n * ─── Why: SCOPE and AGREEMENT, not a speed claim ───────────────────────────────────────────────────\n * `nx affected --target=ci --base=<fork point>` is the command the PR gate itself runs\n * (`commands.pr-gate.buildCommand`), so a green local result is evidence about the gate. A whole-repo\n * build is a different, wider command whose green says nothing extra — it just also compiles projects\n * the change cannot reach.\n *\n * It is NOT automatically faster, and this guard deliberately does not claim it is. Measured on a\n * `core-util` change, `affected` selected the IDENTICAL 20 projects / 104 tasks as the whole-repo\n * build: a package at the BASE of the dependency graph prunes nothing. The pruning win is real for\n * LEAF projects and absent for base ones. The long builds people blamed on scope were caused by a cold\n * nx cache and by CPU contention between agents running full sweeps at once (measured: ~3.2x total\n * test time under contention) — neither of which a narrower target list fixes on its own.\n *\n * So what this guard buys is the scope being right by default. Building the world is never the\n * correct inner-loop move in a monorepo; the correct one has existed all along, and nothing stopped\n * the wide one.\n *\n * ─── The message is READ FROM CONFIG, and it is RESOLVED ───────────────────────────────────────────\n * The replacement command comes from `commands.pr-gate.buildCommand` (injected into this guard's\n * config by load-config), so the refusal follows the project when the gate command changes. The `$(…)`\n * in it is EXPANDED before printing: handing an agent `--base=$(git merge-base origin/main HEAD)` is\n * handing it a template, and a template pasted where no shell expands it produces a confusing failure\n * that reads like the guard's advice was wrong. Only `$(git …)` is expanded, and only read-only git;\n * anything else is left verbatim.\n *\n * ─── Two messages, chosen by ~/.webpieces/config.json ──────────────────────────────────────────────\n * With `experimental.buildGateLogCapture` ON, the pr-gate captures its build's full output to a log\n * file and hands the agent that path instead of a rebuild instruction — so the right advice is not\n * \"build smaller\", it is \"do not build; stage ② already builds and you can READ the result\". That flag\n * lives in the OPTIONAL machine-local `~/.webpieces/config.json`; absent (the state of essentially\n * every consumer) means the first message. `HomeConfigService` is the one reader of that file.\n *\n * ─── Humans are not affected, by construction ──────────────────────────────────────────────────────\n * This is a PreToolUse hook. It sees the AI's Bash tool calls and nothing else — a human typing\n * `pnpm run build-all` in their own terminal never reaches a hook, and the `build-all` script itself is\n * deliberately left in package.json for exactly that reason. The guard is about what the AI does in a\n * loop, not about the command being wrong for a person who chooses to run it once.\n */\nexport class WholeRepoBuildGuardRule extends BashRuleBase<WholeRepoBuildGuardConfig> {\n constructor(config: WholeRepoBuildGuardConfig) { super(config, 'whole-repo-build-guard'); }\n\n private readonly scanner = new CommandScanner();\n private readonly homeConfig = new HomeConfigService();\n\n readonly description =\n 'Block a whole-monorepo build (build-all, an unnarrowed nx run-many, nx affected with no ' +\n '--base, a bare vitest run) and name the affected-scoped command to run instead.';\n\n /**\n * The command this rule last printed, so the fix hint and the violation message are one string and\n * cannot disagree. Empty until check() runs (fixHint is also read without it), at which point the\n * getter falls back to the configured TEMPLATE — never to a second literal, which is exactly the\n * drift this guard's own docstring says a duplicated command string causes.\n */\n private resolvedCommand = '';\n\n get fixHint(): FixHint {\n const command = this.resolvedCommand !== '' ? this.resolvedCommand : this.buildCommandTemplate();\n return new FixHint(\n 'That command builds the WHOLE monorepo. Build only what your change affects.',\n 'Build the affected projects, or one project, or one spec file — never the workspace:\\n' +\n ` ${command} # the gate's own build\\n` +\n ' pnpm nx run <project>:ci # one project\\n' +\n ' pnpm exec vitest run <path> # one suite\\n' +\n 'Disable in webpieces.config.json under hookGuards → whole-repo-build-guard (mode OFF) if intentional.',\n );\n }\n\n check(ctx: BashContext): readonly Violation[] {\n // Blocklist-shaped, so match on commandCode: stripping heredocs and quoted prose can only ever\n // block LESS, and this repo's own commit messages are full of the command names above.\n const hit = new WholeRepoBuildScan(this.scanner, ctx.effectiveCwd === ctx.workspaceRoot)\n .firstHit(ctx.commandCode);\n if (hit === null) return this.allow(ctx, 'not-a-whole-repo-build');\n\n // Resolved ONCE, here, and read by both the violation message and the fix hint.\n this.resolvedCommand = this.resolvedBuildCommand(ctx.workspaceRoot);\n return this.block(ctx, hit, this.message());\n }\n\n // The whole refusal. Short on purpose: it is read mid-task by an agent that needs the ONE command\n // to run next, and a guard message long enough to skim is a guard message that gets skimmed.\n private message(): string {\n if (this.captureEnabled()) {\n return 'Blocked: that builds the WHOLE monorepo — and you should not be building at all.\\n'\n + '`pnpm wp-review-upsert-pr` (stage ②) runs the build for you, captures the full output to a\\n'\n + 'log file, and names that file if it fails. Read the file; do not rebuild.\\n'\n + 'Need a check before then: pnpm exec vitest run <path>.';\n }\n return 'Blocked: that builds the WHOLE monorepo. Build only what your change affects:\\n\\n'\n + ` ${this.resolvedCommand}\\n\\n`\n + 'Narrower still: pnpm nx run <project>:ci, or pnpm exec vitest run <path>.';\n }\n\n /**\n * The project's build command, unexpanded. ONE source: `commands.pr-gate.buildCommand`, injected\n * into this guard's config by load-config exactly as the other guards' command hints are, falling\n * back to the same DEFAULT_BUILD_COMMAND the gate itself falls back to. This guard never spells a\n * build command of its own — a second copy is how a refusal starts teaching a command the gate\n * does not run.\n */\n private buildCommandTemplate(): string {\n const configured = this.config.affectedBuildCommand ?? '';\n return configured.trim() === '' ? DEFAULT_BUILD_COMMAND : configured;\n }\n\n /**\n * The configured build command with its `$(git …)` substitutions expanded, so what is printed is\n * runnable as-is. Expansion is limited to git, and any failure leaves the template untouched — a\n * guard may degrade its own message, never fail the tool call it is judging.\n */\n private resolvedBuildCommand(workspaceRoot: string): string {\n const template = this.buildCommandTemplate();\n return template.replace(/\\$\\(([^()]*)\\)/g, (match: string, inner: string): string => {\n const trimmed = inner.trim();\n if (!trimmed.startsWith('git ')) return match;\n const output = this.capture(trimmed, workspaceRoot);\n return output === null ? match : output;\n });\n }\n\n private capture(command: string, workspaceRoot: string): string | null {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return execSync(command, {\n cwd: workspaceRoot, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'],\n }).trim();\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n\n /**\n * Is build-log capture on? The OPTIONAL `~/.webpieces/config.json` is absent for essentially every\n * consumer, and absent means false, silently — so a broken or unreadable home config can never be\n * the reason a Bash command is judged differently. Fail toward the ordinary message.\n */\n private captureEnabled(): boolean {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return this.homeConfig.load().buildGateLogCapture;\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return false;\n }\n }\n\n private allow(ctx: BashContext, reason: string): readonly Violation[] {\n this.logDecision(ctx, 'ALLOW', reason);\n return [];\n }\n\n private block(ctx: BashContext, hit: WholeRepoBuildHit, message: string): readonly Violation[] {\n // BLOCK_AI_CURE, not BLOCK_HUMAN: the cure is one command the agent runs itself, and the\n // refusal hands it over already resolved.\n this.logDecision(ctx, 'BLOCK_AI_CURE', hit.shape);\n return [new V(1, this.truncate(ctx.command), message)];\n }\n\n private truncate(s: string): string {\n const MAX = 120;\n return s.length <= MAX ? s : s.slice(0, MAX) + '…';\n }\n\n private logDecision(ctx: BashContext, verdict: Verdict, reason: string): void {\n logGuardDecision(\n ctx.workspaceRoot,\n new GuardDecision('whole-repo-build-guard', 'Bash', ctx.command, '-', verdict, reason, '-', L0_FAULT_NONE, MATRIX_L2),\n );\n }\n}\n"]}
1
+ {"version":3,"file":"whole-repo-build-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/ai-hook-rules/src/core/rules/whole-repo-build-guard.ts"],"names":[],"mappings":";;;AAAA,iDAAyC;AAEzC,0DAA8G;AAG9G,oCAA0C;AAC1C,4CAA6D;AAC7D,0CAAsC;AACtC,0CAAsC;AACtC,sDAAkD;AAClD,kDAAsF;AACtF,kDAAiD;AACjD,mEAAgF;AAEhF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2DG;AACH,MAAa,uBAAwB,SAAQ,wBAA6B;IAMzC;IAL7B;;;;OAIG;IACH,YAA6B,oBAA4B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AAC;CACJ;AAlLD,0DAkLC","sourcesContent":["import { execSync } from 'child_process';\n\nimport { DEFAULT_BUILD_COMMAND, HomeConfig, HomeConfigService, InformAiError } from '@webpieces/rules-config';\n\nimport type { BashContext, Violation } from '../types';\nimport { Violation as V } from '../types';\nimport { BashRuleBase, EmptyRuleConfig } from '../rule-base';\nimport { FixHint } from '../fix-hint';\nimport { toError } from '../to-error';\nimport { L0_FAULT_NONE } from '../l0-fault-codes';\nimport { logGuardDecision, GuardDecision, Verdict, MATRIX_L2 } from '../decision-log';\nimport { CommandScanner } from '../command-scan';\nimport { WholeRepoBuildScan, WholeRepoBuildHit } from './whole-repo-build-scan';\n\n/**\n * Blocks a Bash command that would build or test the WHOLE monorepo, and hands back the narrow\n * command to run instead. Which shapes count is `WholeRepoBuildScan`'s job; this rule owns the\n * decision, the log line and the two refusal messages.\n *\n * ─── Why: SCOPE and AGREEMENT, not a speed claim ───────────────────────────────────────────────────\n * `nx affected --target=ci --base=<fork point>` is the command the PR gate itself runs\n * (`commands.pr-gate.buildCommand`), so a green local result is evidence about the gate. A whole-repo\n * build is a different, wider command whose green says nothing extra — it just also compiles projects\n * the change cannot reach.\n *\n * It is NOT automatically faster, and this guard deliberately does not claim it is. Measured on a\n * `core-util` change, `affected` selected the IDENTICAL 20 projects / 104 tasks as the whole-repo\n * build: a package at the BASE of the dependency graph prunes nothing. The pruning win is real for\n * LEAF projects and absent for base ones. The long builds people blamed on scope were caused by a cold\n * nx cache and by CPU contention between agents running full sweeps at once (measured: ~3.2x total\n * test time under contention) — neither of which a narrower target list fixes on its own.\n *\n * So what this guard buys is the scope being right by default. Building the world is never the\n * correct inner-loop move in a monorepo; the correct one has existed all along, and nothing stopped\n * the wide one.\n *\n * ─── The message is READ FROM CONFIG, and it is RESOLVED ───────────────────────────────────────────\n * The replacement command comes from `commands.pr-gate.buildCommand` (injected into this guard's\n * config by load-config), so the refusal follows the project when the gate command changes. The `$(…)`\n * in it is EXPANDED before printing: handing an agent `--base=$(git merge-base origin/main HEAD)` is\n * handing it a template, and a template pasted where no shell expands it produces a confusing failure\n * that reads like the guard's advice was wrong. Only `$(git …)` is expanded, and only read-only git;\n * anything else is left verbatim.\n *\n * ─── EXPERIMENTAL: the ONLY switch is ~/.webpieces/config.json ─────────────────────────────────────\n * `experimental.whole-repo-build-guard` (a boolean) decides whether this guard blocks anything at all.\n * There is NO webpieces.config.json entry — deliberately, and the reason is a live incident: this guard\n * first shipped as an ordinary validated guard with `mode: 'ON'` by default AND a required entry under\n * `hookGuards`, so every consumer that upgraded hit fault Y — EVERY Bash call blocked — for a feature\n * they had never asked for. An experimental feature is opted into from a machine-local file whose absent\n * state is byte-for-byte the old behaviour, or it is not experimental.\n *\n * Three states, and only three:\n * - the file does not exist (essentially every consumer) → this guard is INERT. It blocks nothing and\n * logs nothing, for every command, including the ones it would otherwise refuse.\n * - the file exists and defines the key → the key's value decides.\n * - the file exists and is unparseable, or does not define the key → HARD FAILURE naming the edit. A\n * file someone deliberately created must be correct, and `HomeConfigService` requires that key\n * precisely because guessing either way is wrong (see readRequiredBoolean). Editing that file is an\n * unconditional PASS in the guards, so the block is always self-curable.\n *\n * ─── Two messages, chosen by a DIFFERENT key ───────────────────────────────────────────────────────\n * `experimental.buildGateLogCapture` is a separate feature (the pr-gate captures its build's full output\n * to a log file and hands the agent that path instead of a rebuild instruction) and it is NOT this\n * guard's switch. It only picks WHICH refusal is printed once the guard is on: with capture ON the right\n * advice is not \"build smaller\", it is \"do not build; stage ② already builds and you can READ the\n * result\". `HomeConfigService` is the one reader of both keys.\n *\n * ─── Humans are not affected, by construction ──────────────────────────────────────────────────────\n * This is a PreToolUse hook. It sees the AI's Bash tool calls and nothing else — a human typing\n * `pnpm run build-all` in their own terminal never reaches a hook, and the `build-all` script itself is\n * deliberately left in package.json for exactly that reason. The guard is about what the AI does in a\n * loop, not about the command being wrong for a person who chooses to run it once.\n */\nexport class WholeRepoBuildGuardRule extends BashRuleBase<EmptyRuleConfig> {\n /**\n * `affectedBuildCommand` is the project's gate command (`commands.pr-gate.buildCommand`), handed in\n * by the runner off the loaded config. It is a CONSTRUCTOR ARGUMENT rather than a config field\n * because this guard has no config entry to read one from — and that is the point.\n */\n constructor(private readonly affectedBuildCommand: string) {\n super(new EmptyRuleConfig(), 'whole-repo-build-guard');\n }\n\n private readonly scanner = new CommandScanner();\n private readonly homeConfig = new HomeConfigService();\n\n /** Set by check() when the home config is unreadable, so the fix hint names the same repair. */\n private homeConfigError = '';\n\n readonly description =\n 'Block a whole-monorepo build (build-all, an unnarrowed nx run-many, nx affected with no ' +\n '--base, a bare vitest run) and name the affected-scoped command to run instead.';\n\n /**\n * The command this rule last printed, so the fix hint and the violation message are one string and\n * cannot disagree. Empty until check() runs (fixHint is also read without it), at which point the\n * getter falls back to the configured TEMPLATE — never to a second literal, which is exactly the\n * drift this guard's own docstring says a duplicated command string causes.\n */\n private resolvedCommand = '';\n\n get fixHint(): FixHint {\n if (this.homeConfigError !== '') {\n return new FixHint(\n '~/.webpieces/config.json exists but cannot be read.',\n 'Edit ~/.webpieces/config.json (editing it is always permitted, including right now), or ' +\n 'delete it outright — with no such file every webpieces command behaves exactly as it ' +\n 'does by default.',\n );\n }\n const command = this.resolvedCommand !== '' ? this.resolvedCommand : this.buildCommandTemplate();\n return new FixHint(\n 'That command builds the WHOLE monorepo. Build only what your change affects.',\n 'Build the affected projects, or one project, or one spec file — never the workspace:\\n' +\n ` ${command} # the gate's own build\\n` +\n ' pnpm nx run <project>:ci # one project\\n' +\n ' pnpm exec vitest run <path> # one suite\\n' +\n 'Turn this guard off for this machine by setting \"experimental\": ' +\n '{ \"whole-repo-build-guard\": false } in ~/.webpieces/config.json (there is no ' +\n 'webpieces.config.json entry for it).',\n );\n }\n\n check(ctx: BashContext): readonly Violation[] {\n const home = this.loadHome();\n // A file someone deliberately created must be correct — see the class docstring. Reported for\n // whatever command happens to be running, because a broken opt-in file is not a build question.\n if (home instanceof Error) return this.blockOnBrokenHomeConfig(ctx, home);\n\n // THE EXPERIMENTAL GATE, and the state of essentially every consumer. Silent on purpose: no\n // block, no log, no file touched — \"no ~/.webpieces/config.json\" must be indistinguishable from\n // \"this guard does not exist\".\n this.homeConfigError = '';\n if (!home.wholeRepoBuildGuard) return [];\n\n // Blocklist-shaped, so match on commandCode: stripping heredocs and quoted prose can only ever\n // block LESS, and this repo's own commit messages are full of the command names above.\n const hit = new WholeRepoBuildScan(this.scanner, ctx.effectiveCwd === ctx.workspaceRoot)\n .firstHit(ctx.commandCode);\n if (hit === null) return this.allow(ctx, 'not-a-whole-repo-build');\n\n // Resolved ONCE, here, and read by both the violation message and the fix hint.\n this.resolvedCommand = this.resolvedBuildCommand(ctx.workspaceRoot);\n return this.block(ctx, hit, this.message(home));\n }\n\n /**\n * The home config, or the Error explaining why it is unusable. NOT a boolean: \"absent\" is already\n * folded into the returned HomeConfig (all-defaults, guard off), so the only thing left to\n * distinguish is \"present and wrong\", which must be reported rather than swallowed.\n */\n private loadHome(): HomeConfig | Error {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: a rejected home config is converted\n // into this guard's own block, which carries the loader's fix instruction verbatim\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return this.homeConfig.load();\n } catch (err: unknown) {\n const error = toError(err);\n return error;\n }\n }\n\n private blockOnBrokenHomeConfig(ctx: BashContext, error: Error): readonly Violation[] {\n this.homeConfigError = error.message;\n this.logDecision(ctx, 'BLOCK_AI_CURE', 'home-config-invalid');\n return [new V(1, this.truncate(ctx.command), this.brokenHomeConfigMessage(error))];\n }\n\n private brokenHomeConfigMessage(error: Error): string {\n const detail = error instanceof InformAiError\n ? error.message\n : `~/.webpieces/config.json could not be read: ${error.message}`;\n return `Blocked: ~/.webpieces/config.json is present but unusable.\\n\\n${detail}`;\n }\n\n // The whole refusal. Short on purpose: it is read mid-task by an agent that needs the ONE command\n // to run next, and a guard message long enough to skim is a guard message that gets skimmed.\n private message(home: HomeConfig): string {\n if (home.buildGateLogCapture) {\n return 'Blocked: that builds the WHOLE monorepo — and you should not be building at all.\\n'\n + '`pnpm wp-review-upsert-pr` (stage ②) runs the build for you, captures the full output to a\\n'\n + 'log file, and names that file if it fails. Read the file; do not rebuild.\\n'\n + 'Need a check before then: pnpm exec vitest run <path>.';\n }\n return 'Blocked: that builds the WHOLE monorepo. Build only what your change affects:\\n\\n'\n + ` ${this.resolvedCommand}\\n\\n`\n + 'Narrower still: pnpm nx run <project>:ci, or pnpm exec vitest run <path>.';\n }\n\n /**\n * The project's build command, unexpanded. ONE source: `commands.pr-gate.buildCommand`, handed to\n * the constructor by the runner, falling back to the same DEFAULT_BUILD_COMMAND the gate itself\n * falls back to. This guard never spells a build command of its own — a second copy is how a refusal\n * starts teaching a command the gate does not run.\n */\n private buildCommandTemplate(): string {\n return this.affectedBuildCommand.trim() === '' ? DEFAULT_BUILD_COMMAND : this.affectedBuildCommand;\n }\n\n /**\n * The configured build command with its `$(git …)` substitutions expanded, so what is printed is\n * runnable as-is. Expansion is limited to git, and any failure leaves the template untouched — a\n * guard may degrade its own message, never fail the tool call it is judging.\n */\n private resolvedBuildCommand(workspaceRoot: string): string {\n const template = this.buildCommandTemplate();\n return template.replace(/\\$\\(([^()]*)\\)/g, (match: string, inner: string): string => {\n const trimmed = inner.trim();\n if (!trimmed.startsWith('git ')) return match;\n const output = this.capture(trimmed, workspaceRoot);\n return output === null ? match : output;\n });\n }\n\n private capture(command: string, workspaceRoot: string): string | null {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return execSync(command, {\n cwd: workspaceRoot, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'],\n }).trim();\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n\n private allow(ctx: BashContext, reason: string): readonly Violation[] {\n this.logDecision(ctx, 'ALLOW', reason);\n return [];\n }\n\n private block(ctx: BashContext, hit: WholeRepoBuildHit, message: string): readonly Violation[] {\n // BLOCK_AI_CURE, not BLOCK_HUMAN: the cure is one command the agent runs itself, and the\n // refusal hands it over already resolved.\n this.logDecision(ctx, 'BLOCK_AI_CURE', hit.shape);\n return [new V(1, this.truncate(ctx.command), message)];\n }\n\n private truncate(s: string): string {\n const MAX = 120;\n return s.length <= MAX ? s : s.slice(0, MAX) + '…';\n }\n\n private logDecision(ctx: BashContext, verdict: Verdict, reason: string): void {\n logGuardDecision(\n ctx.workspaceRoot,\n new GuardDecision('whole-repo-build-guard', 'Bash', ctx.command, '-', verdict, reason, '-', L0_FAULT_NONE, MATRIX_L2),\n );\n }\n}\n"]}
@@ -12,6 +12,7 @@ export declare class WholeRepoBuildScan {
12
12
  /** The first segment of `command` that builds the whole repo, or null when none does. */
13
13
  firstHit(command: string): WholeRepoBuildHit | null;
14
14
  private shapeOf;
15
+ private viaRunner;
15
16
  /**
16
17
  * The segment's words with wrappers stripped: shell prefixes (`time`, `sudo`, env assignments) by
17
18
  * CommandScanner, then the package-manager runner and its verb. `pnpm exec vitest run` and