@webpieces/rules-config 0.4.837 → 0.4.838
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 +4 -2
- package/src/builds-log.d.ts +1 -1
- package/src/builds-log.js +3 -3
- package/src/builds-log.js.map +1 -1
- package/src/checklist-docs-validator.js +1 -1
- package/src/checklist-docs-validator.js.map +1 -1
- package/src/checklist-override.js +1 -1
- package/src/checklist-override.js.map +1 -1
- package/src/config-file.js +3 -3
- package/src/config-file.js.map +1 -1
- package/src/config-pruner.d.ts +1 -1
- package/src/config-pruner.js +2 -2
- package/src/config-pruner.js.map +1 -1
- package/src/constants.d.ts +0 -2
- package/src/constants.js +1 -3
- package/src/constants.js.map +1 -1
- package/src/diff-scope.js +1 -1
- package/src/diff-scope.js.map +1 -1
- package/src/exclude-hook-paths.js +2 -2
- package/src/exclude-hook-paths.js.map +1 -1
- package/src/home-config-doc-keys.js +2 -2
- package/src/home-config-doc-keys.js.map +1 -1
- package/src/home-config.js +9 -9
- package/src/home-config.js.map +1 -1
- package/src/index.d.ts +2 -21
- package/src/index.js +7 -129
- package/src/index.js.map +1 -1
- package/src/instruct-ai-docs.d.ts +1 -1
- package/src/instruct-ai-docs.js +3 -3
- package/src/instruct-ai-docs.js.map +1 -1
- package/src/load-config.js +2 -2
- package/src/load-config.js.map +1 -1
- package/src/load-template.d.ts +2 -2
- package/src/load-template.js +5 -5
- package/src/load-template.js.map +1 -1
- package/src/orphan-dir-archive.js +3 -3
- package/src/orphan-dir-archive.js.map +1 -1
- package/src/pr-gate-config.js +4 -4
- package/src/pr-gate-config.js.map +1 -1
- package/src/pr-gate-section-validators.js +7 -7
- package/src/pr-gate-section-validators.js.map +1 -1
- package/src/repo-root.d.ts +1 -1
- package/src/repo-root.js +5 -5
- package/src/repo-root.js.map +1 -1
- package/src/repo-scratch-dirs.d.ts +1 -1
- package/src/repo-scratch-dirs.js +3 -3
- package/src/repo-scratch-dirs.js.map +1 -1
- package/src/review-json.d.ts +1 -1
- package/src/review-json.js +11 -11
- package/src/review-json.js.map +1 -1
- package/src/review-provenance.js +4 -4
- package/src/review-provenance.js.map +1 -1
- package/src/reviewer-instructions.js +2 -2
- package/src/reviewer-instructions.js.map +1 -1
- package/src/rules-config-design.d.ts +2 -2
- package/src/rules-config-design.js +4 -4
- package/src/rules-config-design.js.map +1 -1
- package/src/skip-rule.d.ts +2 -8
- package/src/skip-rule.js +24 -61
- package/src/skip-rule.js.map +1 -1
- package/src/spec-temp-dirs.js +2 -1
- package/src/spec-temp-dirs.js.map +1 -1
- package/src/stale-bin-sweep.js +1 -1
- package/src/stale-bin-sweep.js.map +1 -1
- package/src/subagent-provenance.js +7 -7
- package/src/subagent-provenance.js.map +1 -1
- package/src/tmp-scratch-sweep.js +1 -1
- package/src/tmp-scratch-sweep.js.map +1 -1
- package/src/validate-config.js +1 -1
- package/src/validate-config.js.map +1 -1
- package/src/verdict-schema-renderer.js +2 -2
- package/src/verdict-schema-renderer.js.map +1 -1
- package/src/agent-worktree-lock.d.ts +0 -21
- package/src/agent-worktree-lock.js +0 -77
- package/src/agent-worktree-lock.js.map +0 -1
- package/src/atomic-file.d.ts +0 -46
- package/src/atomic-file.js +0 -114
- package/src/atomic-file.js.map +0 -1
- package/src/branch-archiver.d.ts +0 -70
- package/src/branch-archiver.js +0 -157
- package/src/branch-archiver.js.map +0 -1
- package/src/branch-mutation-log.d.ts +0 -77
- package/src/branch-mutation-log.js +0 -221
- package/src/branch-mutation-log.js.map +0 -1
- package/src/branch-reaper.d.ts +0 -121
- package/src/branch-reaper.js +0 -260
- package/src/branch-reaper.js.map +0 -1
- package/src/claude-config-dir.d.ts +0 -62
- package/src/claude-config-dir.js +0 -87
- package/src/claude-config-dir.js.map +0 -1
- package/src/harness-agent-activity.d.ts +0 -154
- package/src/harness-agent-activity.js +0 -346
- package/src/harness-agent-activity.js.map +0 -1
- package/src/inform-ai-error.d.ts +0 -6
- package/src/inform-ai-error.js +0 -13
- package/src/inform-ai-error.js.map +0 -1
- package/src/main-sync-file.d.ts +0 -121
- package/src/main-sync-file.js +0 -281
- package/src/main-sync-file.js.map +0 -1
- package/src/main-sync-status.d.ts +0 -197
- package/src/main-sync-status.js +0 -555
- package/src/main-sync-status.js.map +0 -1
- package/src/merged-branch-verdicts.d.ts +0 -189
- package/src/merged-branch-verdicts.js +0 -251
- package/src/merged-branch-verdicts.js.map +0 -1
- package/src/merged-branches.d.ts +0 -140
- package/src/merged-branches.js +0 -521
- package/src/merged-branches.js.map +0 -1
- package/src/review-identity-stamp.d.ts +0 -82
- package/src/review-identity-stamp.js +0 -172
- package/src/review-identity-stamp.js.map +0 -1
- package/src/state-dir-migration.d.ts +0 -79
- package/src/state-dir-migration.js +0 -185
- package/src/state-dir-migration.js.map +0 -1
- package/src/state-dir.d.ts +0 -209
- package/src/state-dir.js +0 -349
- package/src/state-dir.js.map +0 -1
- package/src/to-error.d.ts +0 -1
- package/src/to-error.js +0 -10
- package/src/to-error.js.map +0 -1
- package/src/worktree-lock-verdicts.d.ts +0 -149
- package/src/worktree-lock-verdicts.js +0 -225
- package/src/worktree-lock-verdicts.js.map +0 -1
- package/src/worktree-reaper.d.ts +0 -116
- package/src/worktree-reaper.js +0 -318
- package/src/worktree-reaper.js.map +0 -1
- package/src/worktrees.d.ts +0 -113
- package/src/worktrees.js +0 -260
- package/src/worktrees.js.map +0 -1
package/src/load-config.js
CHANGED
|
@@ -10,7 +10,7 @@ const config_error_banner_1 = require("./config-error-banner");
|
|
|
10
10
|
const config_file_1 = require("./config-file");
|
|
11
11
|
const default_rules_1 = require("./default-rules");
|
|
12
12
|
const exclude_hook_paths_1 = require("./exclude-hook-paths");
|
|
13
|
-
const
|
|
13
|
+
const tooling_common_1 = require("@webpieces/tooling-common");
|
|
14
14
|
const types_1 = require("./types");
|
|
15
15
|
const commands_section_validators_1 = require("./commands-section-validators");
|
|
16
16
|
const config_key_rules_1 = require("./config-key-rules");
|
|
@@ -88,7 +88,7 @@ let ConfigLoader = class ConfigLoader {
|
|
|
88
88
|
...(0, validate_config_1.validateMatchRulesSection)(consumerConfig['match-rules']),
|
|
89
89
|
];
|
|
90
90
|
if (errors.length > 0) {
|
|
91
|
-
throw new
|
|
91
|
+
throw new tooling_common_1.InformAiError(this.formatConfigErrorsBanner(errors));
|
|
92
92
|
}
|
|
93
93
|
const commands = (0, commands_config_1.buildCommandsConfig)(consumerConfig.commands);
|
|
94
94
|
const userConfiguredRuleNames = new Set(Object.keys(overrideRules));
|
package/src/load-config.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"load-config.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/load-config.ts"],"names":[],"mappings":";;;AAiMA,0CAEC;;AAnMD,mDAA6B;AAC7B,yCAA2D;AAE3D,uDAAwE;AACxE,+DAAiE;AACjE,+CAA2C;AAC3C,mDAA+C;AAC/C,6DAAoD;AACpD,uDAAkD;AAElD,mCAA0E;AAC1E,+EAAwE;AACxE,yDAA0D;AAC1D,uDAAuI;AAEvI,iEAA8D;AAE9D;;;GAGG;AACH,MAAa,YAAY;IAGR;IACA;IACA;IACA;IACA;IACA;IACA;IARb,yDAAyD;IACzD,YACa,QAAwB,EACxB,WAAiC,EACjC,QAAwB,EACxB,MAAoB,EACpB,YAA0B,EAC1B,UAAsC,EACtC,UAAyB;QANzB,aAAQ,GAAR,QAAQ,CAAgB;QACxB,gBAAW,GAAX,WAAW,CAAsB;QACjC,aAAQ,GAAR,QAAQ,CAAgB;QACxB,WAAM,GAAN,MAAM,CAAc;QACpB,iBAAY,GAAZ,YAAY,CAAc;QAC1B,eAAU,GAAV,UAAU,CAA4B;QACtC,eAAU,GAAV,UAAU,CAAe;IACnC,CAAC;CACP;AAXD,oCAWC;AAED,wGAAwG;AACxG,2GAA2G;AAC3G,kGAAkG;AAClG,oGAAoG;AAEpG;;;;GAIG;AAEI,IAAM,YAAY,GAAlB,MAAM,YAAY;IACQ;IAA7B,YAA6B,UAA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A2I;AAC3I,SAAgB,eAAe,CAAC,GAAW;IACvC,OAAO,eAAe,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC;AAChD,CAAC","sourcesContent":["import * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { buildCommandsConfig, CommandsConfig } from './commands-config';\nimport { formatConfigErrorsBanner } from './config-error-banner';\nimport { ConfigFile } from './config-file';\nimport { defaultRules } from './default-rules';\nimport { ExcludePaths } from './exclude-hook-paths';\nimport { InformAiError } from './inform-ai-error';\nimport { PrGateConfig } from './pr-gate-config';\nimport { ResolvedConfig, ResolvedRuleConfig, RuleOptions } from './types';\nimport { validateCommandsSection } from './commands-section-validators';\nimport { validateTopLevelKeys } from './config-key-rules';\nimport { validateExcludePaths, validateMatchRulesSection, validateSectionPlacement, validateWebpiecesConfig } from './validate-config';\nimport { MatchRuleConfig } from './match-rules-config';\nimport { WebpiecesRulesConfig } from './WebpiecesRulesConfig';\n\n/**\n * Everything a consumer might need from webpieces.config.json, produced from ONE parse + ONE\n * validation pass. Data-only (per CLAUDE.md, classes for data).\n */\nexport class LoadedConfig {\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n readonly resolved: ResolvedConfig,\n readonly rulesConfig: WebpiecesRulesConfig,\n readonly commands: CommandsConfig,\n readonly prGate: PrGateConfig,\n readonly excludePaths: ExcludePaths,\n readonly matchRules: readonly MatchRuleConfig[],\n readonly configPath: string | null,\n ) {}\n}\n\n// Renamed rules used to be normalized here — a DEPRECATED_RULE_ALIASES table rewrote the old key to its\n// canonical name BEFORE validation, so no validator ever saw it and no consumer was ever told. That is why\n// the aliases could never be removed: the old names kept working forever. The renames now live in\n// RETIRED_CONFIG_KEYS as hard errors naming the new key. See retired-config-keys.ts for the policy.\n\n/**\n * The single load+validate entry point for ALL consumers (ai-hook-rules, code-rules,\n * nx-webpieces-rules, pr-gate scripts). `@injectable(bindingScopeValues.Singleton)` + injects {@link ConfigFile} so it appears\n * in the rules-config DI design.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ConfigLoader {\n constructor(private readonly configFile: ConfigFile) {}\n\n /**\n * Reads webpieces.config.json once, validates BOTH the `rules` map and the top-level `pr-gate`\n * block, and throws one InformAiError listing every error. When no config file is found it returns\n * lenient empties/defaults (matching prior no-file behavior).\n */\n // webpieces-disable max-lines-new-methods -- the single load+validate pass is one cohesive method\n loadAndValidate(cwd: string): LoadedConfig {\n const configPath = this.configFile.findConfigFile(cwd);\n if (!configPath) {\n const emptyCommands = buildCommandsConfig(undefined);\n return new LoadedConfig(\n new ResolvedConfig(new Map(), new Set(), [], null),\n new WebpiecesRulesConfig(),\n emptyCommands,\n emptyCommands.prGate,\n new ExcludePaths([]),\n [],\n null,\n );\n }\n\n const consumerConfig = this.configFile.readRawConfig(configPath);\n const rulesSection = consumerConfig.rules || {};\n const hookGuardsSection = consumerConfig.hookGuards || {};\n // Read only so validateCommandsSection can REJECT it. There is no fallback to it — a config\n // carrying the retired top-level block never loads, so reading it as a value would be dead code.\n const legacyPrGate = consumerConfig['pr-gate'];\n\n // rules + hookGuards are validated/loaded as one flat name→config map (the runtime dispatches\n // by each rule's own `scope`). Placement is enforced separately.\n const overrideRules = { ...rulesSection, ...hookGuardsSection };\n\n const rulesDir = consumerConfig.rulesDir ?? [];\n\n // The repo root (dir holding webpieces.config.json) lets checklists[].docs existence be checked.\n const repoRoot = path.dirname(configPath);\n const errors = [\n // webpieces-disable no-any-unknown -- the raw parsed config is opaque; only key names are read\n ...validateTopLevelKeys(consumerConfig as unknown as Record<string, unknown>),\n ...validateWebpiecesConfig(overrideRules, rulesDir.length > 0),\n ...validateSectionPlacement(rulesSection, hookGuardsSection),\n ...validateCommandsSection(consumerConfig.commands, legacyPrGate, repoRoot),\n ...validateExcludePaths(consumerConfig.excludePaths),\n ...validateMatchRulesSection(consumerConfig['match-rules']),\n ];\n if (errors.length > 0) {\n throw new InformAiError(this.formatConfigErrorsBanner(errors));\n }\n\n const commands = buildCommandsConfig(consumerConfig.commands);\n\n const userConfiguredRuleNames = new Set(Object.keys(overrideRules));\n const mergedRules = new Map<string, ResolvedRuleConfig>();\n const allRuleNames = new Set([\n ...Object.keys(defaultRules),\n ...Object.keys(overrideRules),\n ]);\n for (const name of allRuleNames) {\n mergedRules.set(name, this.mergeRule(defaultRules[name], overrideRules[name]));\n }\n const resolved = new ResolvedConfig(mergedRules, userConfiguredRuleNames, rulesDir, configPath);\n\n const rulesConfig = this.buildWebpiecesRulesConfig(overrideRules, rulesDir);\n const excludePaths = this.parseExcludePaths(consumerConfig.excludePaths);\n const matchRules = this.parseMatchRules(consumerConfig['match-rules']);\n\n return new LoadedConfig(resolved, rulesConfig, commands, commands.prGate, excludePaths, matchRules, configPath);\n }\n\n // There is deliberately NO applyCommandDefaults here any more.\n //\n // It used to WRITE `commands.guardHints` values into two guard entries under the literal keys\n // 'pr-creation-or-push-guard' / 'merge-in-progress-guard', as a default beneath the guards' own\n // `upsertPrCommand` / `mergeCompleteCommand` fields. Two defects in one method: those per-guard\n // fields were a second spelling that BEAT the commands section (so the \"one place\" promise was\n // false), and the injection was keyed on guard-name literals — a key rename that missed it did NOT\n // fail the build, the lookup simply missed and both guards quietly printed their local defaults.\n //\n // Both fields are now deleted (see PrLifecycleGuardConfig and RETIRED_FIELD_HINTS), and the\n // resolved `CommandsConfig` strings are handed to the two rules at CONSTRUCTION — a compile-time\n // wire that cannot silently miss. whole-repo-build-guard was already fed that way off\n // LoadedConfig.prGate; this makes the guard-hint strings match.\n\n // webpieces-disable no-any-unknown -- merging opaque option bags from config JSON\n private mergeRule(\n // webpieces-disable no-any-unknown -- opaque option bag\n baseRule: Record<string, unknown> | undefined,\n // webpieces-disable no-any-unknown -- opaque option bag\n overrideRule: Record<string, unknown> | undefined,\n ): ResolvedRuleConfig {\n if (!baseRule && !overrideRule) return new ResolvedRuleConfig({ mode: 'OFF' });\n if (!baseRule) return new ResolvedRuleConfig(overrideRule! as RuleOptions);\n if (!overrideRule) return new ResolvedRuleConfig(baseRule as RuleOptions);\n\n // webpieces-disable no-any-unknown -- building merged option bag\n const merged: Record<string, unknown> = {};\n for (const key of Object.keys(baseRule)) merged[key] = baseRule[key];\n for (const key of Object.keys(overrideRule)) merged[key] = overrideRule[key];\n return new ResolvedRuleConfig(merged as RuleOptions);\n }\n\n // Parse the (already-validated) raw excludePaths block into the typed ExcludePaths. The ONLY accepted\n // shape is a bare string[]; the retired two-list object cannot reach here, because validateExcludePaths\n // has already failed the load with the migration instruction.\n // webpieces-disable no-any-unknown -- `raw` is opaque consumer JSON until narrowed here\n private parseExcludePaths(raw: unknown): ExcludePaths {\n if (!Array.isArray(raw)) return new ExcludePaths([]);\n return new ExcludePaths(raw.filter(p => typeof p === 'string'));\n }\n\n // Parse the (already-validated) raw match-rules array into typed MatchRuleConfig[]. The entries use\n // the canonical field names (turnOffRuleUntilEpoch / turnOffRuleWhileOnBranch) that the match-rules\n // engine reads directly, so no normalization is needed.\n // webpieces-disable no-any-unknown -- validated array; each entry cast to the typed MatchRuleConfig\n private parseMatchRules(raw: unknown): MatchRuleConfig[] {\n if (!Array.isArray(raw)) return [];\n return raw as MatchRuleConfig[];\n }\n\n private buildWebpiecesRulesConfig(\n // webpieces-disable no-any-unknown -- JSON values are opaque until assigned to typed fields\n rawRules: Record<string, Record<string, unknown>>,\n rulesDir: string[],\n ): WebpiecesRulesConfig {\n const typed = new WebpiecesRulesConfig();\n for (const key of Object.keys(rawRules)) {\n // webpieces-disable no-any-unknown -- dynamic key assignment to typed class\n (typed as Record<string, unknown>)[key] = rawRules[key];\n }\n typed.rulesDir = rulesDir;\n return typed;\n }\n\n // Assemble the validation-failure banner. Every error here came from validating this ONE file, so\n // the cure is always \"edit it\" — see config-error-banner.ts for why nothing else belongs in it.\n private formatConfigErrorsBanner(errors: string[]): string {\n return formatConfigErrorsBanner(errors);\n }\n}\n\n// Temporary migration delegator — consumers migrate to injecting ConfigLoader over follow-up PRs,\n// then this free function is removed. The logic now lives in the injected ConfigLoader class.\nconst configLoaderSvc = new ConfigLoader(new ConfigFile());\n\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to ConfigLoader; removed once all 118 consumers inject it\nexport function loadAndValidate(cwd: string): LoadedConfig {\n return configLoaderSvc.loadAndValidate(cwd);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"load-config.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/load-config.ts"],"names":[],"mappings":";;;AAiMA,0CAEC;;AAnMD,mDAA6B;AAC7B,yCAA2D;AAE3D,uDAAwE;AACxE,+DAAiE;AACjE,+CAA2C;AAC3C,mDAA+C;AAC/C,6DAAoD;AACpD,8DAA0D;AAE1D,mCAA0E;AAC1E,+EAAwE;AACxE,yDAA0D;AAC1D,uDAAuI;AAEvI,iEAA8D;AAE9D;;;GAGG;AACH,MAAa,YAAY;IAGR;IACA;IACA;IACA;IACA;IACA;IACA;IARb,yDAAyD;IACzD,YACa,QAAwB,EACxB,WAAiC,EACjC,QAAwB,EACxB,MAAoB,EACpB,YAA0B,EAC1B,UAAsC,EACtC,UAAyB;QANzB,aAAQ,GAAR,QAAQ,CAAgB;QACxB,gBAAW,GAAX,WAAW,CAAsB;QACjC,aAAQ,GAAR,QAAQ,CAAgB;QACxB,WAAM,GAAN,MAAM,CAAc;QACpB,iBAAY,GAAZ,YAAY,CAAc;QAC1B,eAAU,GAAV,UAAU,CAA4B;QACtC,eAAU,GAAV,UAAU,CAAe;IACnC,CAAC;CACP;AAXD,oCAWC;AAED,wGAAwG;AACxG,2GAA2G;AAC3G,kGAAkG;AAClG,oGAAoG;AAEpG;;;;GAIG;AAEI,IAAM,YAAY,GAAlB,MAAM,YAAY;IACQ;IAA7B,YAA6B,UAAsB;QAAtB,eAAU,GAAV,UAAU,CAAY;IAAG,CAAC;IAEvD;;;;OAIG;IACH,kGAAkG;IAClG,eAAe,CAAC,GAAW;QACvB,MAAM,UAAU,GAAG,IAAI,CAAC,UAAU,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC;QACvD,IAAI,C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AAY,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC;IACpE,CAAC;IAED,oGAAoG;IACpG,oGAAoG;IACpG,wDAAwD;IACxD,oGAAoG;IAC5F,eAAe,CAAC,GAAY;QAChC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC;YAAE,OAAO,EAAE,CAAC;QACnC,OAAO,GAAwB,CAAC;IACpC,CAAC;IAEO,yBAAyB;IAC7B,4FAA4F;IAC5F,QAAiD,EACjD,QAAkB;QAElB,MAAM,KAAK,GAAG,IAAI,2CAAoB,EAAE,CAAC;QACzC,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC;YACtC,4EAA4E;YAC3E,KAAiC,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC;QAC5D,CAAC;QACD,KAAK,CAAC,QAAQ,GAAG,QAAQ,CAAC;QAC1B,OAAO,KAAK,CAAC;IACjB,CAAC;IAED,kGAAkG;IAClG,gGAAgG;IACxF,wBAAwB,CAAC,MAAgB;QAC7C,OAAO,IAAA,8CAAwB,EAAC,MAAM,CAAC,CAAC;IAC5C,CAAC;CACJ,CAAA;AA7IY,oCAAY;uBAAZ,YAAY;IADxB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEI,wBAAU;GAD1C,YAAY,CA6IxB;AAED,kGAAkG;AAClG,8FAA8F;AAC9F,MAAM,eAAe,GAAG,IAAI,YAAY,CAAC,IAAI,wBAAU,EAAE,CAAC,CAAC;AAE3D,2IAA2I;AAC3I,SAAgB,eAAe,CAAC,GAAW;IACvC,OAAO,eAAe,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC;AAChD,CAAC","sourcesContent":["import * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { buildCommandsConfig, CommandsConfig } from './commands-config';\nimport { formatConfigErrorsBanner } from './config-error-banner';\nimport { ConfigFile } from './config-file';\nimport { defaultRules } from './default-rules';\nimport { ExcludePaths } from './exclude-hook-paths';\nimport { InformAiError } from '@webpieces/tooling-common';\nimport { PrGateConfig } from './pr-gate-config';\nimport { ResolvedConfig, ResolvedRuleConfig, RuleOptions } from './types';\nimport { validateCommandsSection } from './commands-section-validators';\nimport { validateTopLevelKeys } from './config-key-rules';\nimport { validateExcludePaths, validateMatchRulesSection, validateSectionPlacement, validateWebpiecesConfig } from './validate-config';\nimport { MatchRuleConfig } from './match-rules-config';\nimport { WebpiecesRulesConfig } from './WebpiecesRulesConfig';\n\n/**\n * Everything a consumer might need from webpieces.config.json, produced from ONE parse + ONE\n * validation pass. Data-only (per CLAUDE.md, classes for data).\n */\nexport class LoadedConfig {\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n readonly resolved: ResolvedConfig,\n readonly rulesConfig: WebpiecesRulesConfig,\n readonly commands: CommandsConfig,\n readonly prGate: PrGateConfig,\n readonly excludePaths: ExcludePaths,\n readonly matchRules: readonly MatchRuleConfig[],\n readonly configPath: string | null,\n ) {}\n}\n\n// Renamed rules used to be normalized here — a DEPRECATED_RULE_ALIASES table rewrote the old key to its\n// canonical name BEFORE validation, so no validator ever saw it and no consumer was ever told. That is why\n// the aliases could never be removed: the old names kept working forever. The renames now live in\n// RETIRED_CONFIG_KEYS as hard errors naming the new key. See retired-config-keys.ts for the policy.\n\n/**\n * The single load+validate entry point for ALL consumers (ai-hook-rules, code-rules,\n * nx-webpieces-rules, pr-gate scripts). `@injectable(bindingScopeValues.Singleton)` + injects {@link ConfigFile} so it appears\n * in the rules-config DI design.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ConfigLoader {\n constructor(private readonly configFile: ConfigFile) {}\n\n /**\n * Reads webpieces.config.json once, validates BOTH the `rules` map and the top-level `pr-gate`\n * block, and throws one InformAiError listing every error. When no config file is found it returns\n * lenient empties/defaults (matching prior no-file behavior).\n */\n // webpieces-disable max-lines-new-methods -- the single load+validate pass is one cohesive method\n loadAndValidate(cwd: string): LoadedConfig {\n const configPath = this.configFile.findConfigFile(cwd);\n if (!configPath) {\n const emptyCommands = buildCommandsConfig(undefined);\n return new LoadedConfig(\n new ResolvedConfig(new Map(), new Set(), [], null),\n new WebpiecesRulesConfig(),\n emptyCommands,\n emptyCommands.prGate,\n new ExcludePaths([]),\n [],\n null,\n );\n }\n\n const consumerConfig = this.configFile.readRawConfig(configPath);\n const rulesSection = consumerConfig.rules || {};\n const hookGuardsSection = consumerConfig.hookGuards || {};\n // Read only so validateCommandsSection can REJECT it. There is no fallback to it — a config\n // carrying the retired top-level block never loads, so reading it as a value would be dead code.\n const legacyPrGate = consumerConfig['pr-gate'];\n\n // rules + hookGuards are validated/loaded as one flat name→config map (the runtime dispatches\n // by each rule's own `scope`). Placement is enforced separately.\n const overrideRules = { ...rulesSection, ...hookGuardsSection };\n\n const rulesDir = consumerConfig.rulesDir ?? [];\n\n // The repo root (dir holding webpieces.config.json) lets checklists[].docs existence be checked.\n const repoRoot = path.dirname(configPath);\n const errors = [\n // webpieces-disable no-any-unknown -- the raw parsed config is opaque; only key names are read\n ...validateTopLevelKeys(consumerConfig as unknown as Record<string, unknown>),\n ...validateWebpiecesConfig(overrideRules, rulesDir.length > 0),\n ...validateSectionPlacement(rulesSection, hookGuardsSection),\n ...validateCommandsSection(consumerConfig.commands, legacyPrGate, repoRoot),\n ...validateExcludePaths(consumerConfig.excludePaths),\n ...validateMatchRulesSection(consumerConfig['match-rules']),\n ];\n if (errors.length > 0) {\n throw new InformAiError(this.formatConfigErrorsBanner(errors));\n }\n\n const commands = buildCommandsConfig(consumerConfig.commands);\n\n const userConfiguredRuleNames = new Set(Object.keys(overrideRules));\n const mergedRules = new Map<string, ResolvedRuleConfig>();\n const allRuleNames = new Set([\n ...Object.keys(defaultRules),\n ...Object.keys(overrideRules),\n ]);\n for (const name of allRuleNames) {\n mergedRules.set(name, this.mergeRule(defaultRules[name], overrideRules[name]));\n }\n const resolved = new ResolvedConfig(mergedRules, userConfiguredRuleNames, rulesDir, configPath);\n\n const rulesConfig = this.buildWebpiecesRulesConfig(overrideRules, rulesDir);\n const excludePaths = this.parseExcludePaths(consumerConfig.excludePaths);\n const matchRules = this.parseMatchRules(consumerConfig['match-rules']);\n\n return new LoadedConfig(resolved, rulesConfig, commands, commands.prGate, excludePaths, matchRules, configPath);\n }\n\n // There is deliberately NO applyCommandDefaults here any more.\n //\n // It used to WRITE `commands.guardHints` values into two guard entries under the literal keys\n // 'pr-creation-or-push-guard' / 'merge-in-progress-guard', as a default beneath the guards' own\n // `upsertPrCommand` / `mergeCompleteCommand` fields. Two defects in one method: those per-guard\n // fields were a second spelling that BEAT the commands section (so the \"one place\" promise was\n // false), and the injection was keyed on guard-name literals — a key rename that missed it did NOT\n // fail the build, the lookup simply missed and both guards quietly printed their local defaults.\n //\n // Both fields are now deleted (see PrLifecycleGuardConfig and RETIRED_FIELD_HINTS), and the\n // resolved `CommandsConfig` strings are handed to the two rules at CONSTRUCTION — a compile-time\n // wire that cannot silently miss. whole-repo-build-guard was already fed that way off\n // LoadedConfig.prGate; this makes the guard-hint strings match.\n\n // webpieces-disable no-any-unknown -- merging opaque option bags from config JSON\n private mergeRule(\n // webpieces-disable no-any-unknown -- opaque option bag\n baseRule: Record<string, unknown> | undefined,\n // webpieces-disable no-any-unknown -- opaque option bag\n overrideRule: Record<string, unknown> | undefined,\n ): ResolvedRuleConfig {\n if (!baseRule && !overrideRule) return new ResolvedRuleConfig({ mode: 'OFF' });\n if (!baseRule) return new ResolvedRuleConfig(overrideRule! as RuleOptions);\n if (!overrideRule) return new ResolvedRuleConfig(baseRule as RuleOptions);\n\n // webpieces-disable no-any-unknown -- building merged option bag\n const merged: Record<string, unknown> = {};\n for (const key of Object.keys(baseRule)) merged[key] = baseRule[key];\n for (const key of Object.keys(overrideRule)) merged[key] = overrideRule[key];\n return new ResolvedRuleConfig(merged as RuleOptions);\n }\n\n // Parse the (already-validated) raw excludePaths block into the typed ExcludePaths. The ONLY accepted\n // shape is a bare string[]; the retired two-list object cannot reach here, because validateExcludePaths\n // has already failed the load with the migration instruction.\n // webpieces-disable no-any-unknown -- `raw` is opaque consumer JSON until narrowed here\n private parseExcludePaths(raw: unknown): ExcludePaths {\n if (!Array.isArray(raw)) return new ExcludePaths([]);\n return new ExcludePaths(raw.filter(p => typeof p === 'string'));\n }\n\n // Parse the (already-validated) raw match-rules array into typed MatchRuleConfig[]. The entries use\n // the canonical field names (turnOffRuleUntilEpoch / turnOffRuleWhileOnBranch) that the match-rules\n // engine reads directly, so no normalization is needed.\n // webpieces-disable no-any-unknown -- validated array; each entry cast to the typed MatchRuleConfig\n private parseMatchRules(raw: unknown): MatchRuleConfig[] {\n if (!Array.isArray(raw)) return [];\n return raw as MatchRuleConfig[];\n }\n\n private buildWebpiecesRulesConfig(\n // webpieces-disable no-any-unknown -- JSON values are opaque until assigned to typed fields\n rawRules: Record<string, Record<string, unknown>>,\n rulesDir: string[],\n ): WebpiecesRulesConfig {\n const typed = new WebpiecesRulesConfig();\n for (const key of Object.keys(rawRules)) {\n // webpieces-disable no-any-unknown -- dynamic key assignment to typed class\n (typed as Record<string, unknown>)[key] = rawRules[key];\n }\n typed.rulesDir = rulesDir;\n return typed;\n }\n\n // Assemble the validation-failure banner. Every error here came from validating this ONE file, so\n // the cure is always \"edit it\" — see config-error-banner.ts for why nothing else belongs in it.\n private formatConfigErrorsBanner(errors: string[]): string {\n return formatConfigErrorsBanner(errors);\n }\n}\n\n// Temporary migration delegator — consumers migrate to injecting ConfigLoader over follow-up PRs,\n// then this free function is removed. The logic now lives in the injected ConfigLoader class.\nconst configLoaderSvc = new ConfigLoader(new ConfigFile());\n\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to ConfigLoader; removed once all 118 consumers inject it\nexport function loadAndValidate(cwd: string): LoadedConfig {\n return configLoaderSvc.loadAndValidate(cwd);\n}\n"]}
|
package/src/load-template.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { AtomicFile } from '
|
|
1
|
+
import { AtomicFile } from '@webpieces/tooling-common';
|
|
2
2
|
import { InstructAiDocSet } from './instruct-ai-docs';
|
|
3
|
-
import { DotWebpieces } from '
|
|
3
|
+
import { DotWebpieces } from '@webpieces/tooling-common';
|
|
4
4
|
import { StaleBinSweeper } from './stale-bin-sweep';
|
|
5
5
|
/**
|
|
6
6
|
* Writes the AI-facing instruct-ai template docs under `<workspaceRoot>/.webpieces/instruct-ai/`.
|
package/src/load-template.js
CHANGED
|
@@ -8,10 +8,10 @@ const tslib_1 = require("tslib");
|
|
|
8
8
|
const fs = tslib_1.__importStar(require("fs"));
|
|
9
9
|
const path = tslib_1.__importStar(require("path"));
|
|
10
10
|
const inversify_1 = require("inversify");
|
|
11
|
-
const
|
|
11
|
+
const tooling_common_1 = require("@webpieces/tooling-common");
|
|
12
12
|
const instruct_ai_docs_1 = require("./instruct-ai-docs");
|
|
13
13
|
const repo_root_1 = require("./repo-root");
|
|
14
|
-
const
|
|
14
|
+
const tooling_common_2 = require("@webpieces/tooling-common");
|
|
15
15
|
const stale_bin_sweep_1 = require("./stale-bin-sweep");
|
|
16
16
|
const TEMPLATES_DIR = path.join(__dirname, '..', 'templates');
|
|
17
17
|
// Sentinel for "use the resolved LOCAL instruct-ai dir". Kept as the parameter default so the handful
|
|
@@ -27,7 +27,7 @@ let TemplateWriter = class TemplateWriter {
|
|
|
27
27
|
atomicFile;
|
|
28
28
|
docs;
|
|
29
29
|
staleBins;
|
|
30
|
-
constructor(dotDir =
|
|
30
|
+
constructor(dotDir = tooling_common_2.dotWebpieces, atomicFile = new tooling_common_1.AtomicFile(), docs = new instruct_ai_docs_1.InstructAiDocSet(),
|
|
31
31
|
// The SHARED sweeper instance, never a fresh one: its "already swept this root" memo is per
|
|
32
32
|
// instance, and that memo is what keeps the report to once per `wp-*` command.
|
|
33
33
|
staleBins = stale_bin_sweep_1.staleBinSweeper) {
|
|
@@ -105,8 +105,8 @@ let TemplateWriter = class TemplateWriter {
|
|
|
105
105
|
exports.TemplateWriter = TemplateWriter;
|
|
106
106
|
exports.TemplateWriter = TemplateWriter = tslib_1.__decorate([
|
|
107
107
|
(0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
|
|
108
|
-
tslib_1.__metadata("design:paramtypes", [
|
|
109
|
-
|
|
108
|
+
tslib_1.__metadata("design:paramtypes", [tooling_common_2.DotWebpieces,
|
|
109
|
+
tooling_common_1.AtomicFile,
|
|
110
110
|
instruct_ai_docs_1.InstructAiDocSet,
|
|
111
111
|
stale_bin_sweep_1.StaleBinSweeper])
|
|
112
112
|
], TemplateWriter);
|
package/src/load-template.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"load-template.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/load-template.ts"],"names":[],"mappings":";;;AAsGA,oCAEC;AAED,wDAMC;AAED,sCAMC;;AAxHD,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAE3D
|
|
1
|
+
{"version":3,"file":"load-template.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/load-template.ts"],"names":[],"mappings":";;;AAsGA,oCAEC;AAED,wDAMC;AAED,sCAMC;;AAxHD,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAE3D,8DAAuD;AACvD,yDAAsD;AACtD,2CAA+C;AAC/C,8DAAuE;AACvE,uDAAqE;AAErE,MAAM,aAAa,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,EAAE,WAAW,CAAC,CAAC;AAC9D,sGAAsG;AACtG,iGAAiG;AACjG,iFAAiF;AACjF,MAAM,oBAAoB,GAAG,EAAE,CAAC;AAEhC;;;GAGG;AAEI,IAAM,cAAc,GAApB,MAAM,cAAc;IAEF;IACA;IACA;IAGA;IANrB,YACqB,SAAuB,6BAAY,EACnC,aAAyB,IAAI,2BAAU,EAAE,EACzC,OAAyB,IAAI,mCA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R,6BAAY;QACR,2BAAU;QAChB,mCAAgB;QAGX,iCAAe;GAPtC,cAAc,CA4E1B;AAED,qGAAqG;AACrG,MAAM,iBAAiB,GAAG,IAAI,cAAc,EAAE,CAAC;AAE/C,SAAgB,YAAY,CAAC,IAAY;IACrC,OAAO,iBAAiB,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;AAChD,CAAC;AAED,SAAgB,sBAAsB,CAClC,aAAqB,EACrB,IAAY,EACZ,cAAsB,oBAAoB;IAE1C,iBAAiB,CAAC,sBAAsB,CAAC,aAAa,EAAE,IAAI,EAAE,WAAW,CAAC,CAAC;AAC/E,CAAC;AAED,SAAgB,aAAa,CACzB,aAAqB,EACrB,IAAY,EACZ,cAAsB,oBAAoB;IAE1C,OAAO,iBAAiB,CAAC,aAAa,CAAC,aAAa,EAAE,IAAI,EAAE,WAAW,CAAC,CAAC;AAC7E,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { AtomicFile } from '@webpieces/tooling-common';\nimport { InstructAiDocSet } from './instruct-ai-docs';\nimport { INSTRUCT_AI_LEAF } from './repo-root';\nimport { DotWebpieces, dotWebpieces } from '@webpieces/tooling-common';\nimport { StaleBinSweeper, staleBinSweeper } from './stale-bin-sweep';\n\nconst TEMPLATES_DIR = path.join(__dirname, '..', 'templates');\n// Sentinel for \"use the resolved LOCAL instruct-ai dir\". Kept as the parameter default so the handful\n// of callers that pass an explicit relative dir (they join it onto workspaceRoot themselves) are\n// unaffected; anything passing the default gets DotWebpieces.local() resolution.\nconst DEFAULT_INSTRUCT_DIR = '';\n\n/**\n * Writes the AI-facing instruct-ai template docs under `<workspaceRoot>/.webpieces/instruct-ai/`.\n * `@injectable(bindingScopeValues.Singleton)` so it can be injected and appear in the rules-config DI design.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class TemplateWriter {\n constructor(\n private readonly dotDir: DotWebpieces = dotWebpieces,\n private readonly atomicFile: AtomicFile = new AtomicFile(),\n private readonly docs: InstructAiDocSet = new InstructAiDocSet(),\n // The SHARED sweeper instance, never a fresh one: its \"already swept this root\" memo is per\n // instance, and that memo is what keeps the report to once per `wp-*` command.\n private readonly staleBins: StaleBinSweeper = staleBinSweeper,\n ) {}\n\n loadTemplate(name: string): string {\n return fs.readFileSync(path.join(TEMPLATES_DIR, name), 'utf-8');\n }\n\n /**\n * SEED `name` and everything it links to — writing only the ones that are not already on disk.\n *\n * Same closure as `writeTemplate`, for the same reason: a rule that drops\n * `webpieces.exceptions.md` next to its violation is delivering a doc a reader follows links out\n * of, and a seeded doc that later gains a sibling link would otherwise dangle exactly the way\n * git-workflow.md's link to the merge process did. The difference from `writeTemplate` is only\n * WHETHER an existing file is refreshed, never WHICH files are considered.\n */\n writeTemplateIfMissing(workspaceRoot: string, name: string, instructDir: string = DEFAULT_INSTRUCT_DIR): void {\n for (const doc of this.docs.closure(name, (docName: string): string => this.loadTemplate(docName))) {\n const target = this.destination(workspaceRoot, doc.name, instructDir);\n if (fs.existsSync(target)) continue;\n this.atomicFile.writeAtomic(target, doc.render(this.loadTemplate(doc.name), workspaceRoot));\n }\n }\n\n /**\n * Write `name` AND every instruct-ai doc it links to, ATOMICALLY and only where bytes changed.\n * Returns the absolute path of `name` itself.\n *\n * THE CLOSURE IS THE POINT. Callers name the ONE doc their command is about; the docs a reader is\n * sent on to arrive with it, because a doc whose links dangle is worse than no doc — it teaches the\n * reader that the paths in these files cannot be trusted. See instruct-ai-docs.ts for the incident.\n *\n * Every `wp-*` command regenerates these, and the AI is routinely told to open one by absolute\n * path. A plain truncating write means a reader can catch it empty; skip-if-unchanged means the\n * overwhelmingly common case (same package version ⇒ identical content) does not write at all.\n */\n writeTemplate(workspaceRoot: string, name: string, instructDir: string = DEFAULT_INSTRUCT_DIR): string {\n // THE SELF-HEAL. This is the pass every `wp-*` command takes, which makes it the only place a\n // RELEASED sweep reaches every clone on every developer's machine — see stale-bin-sweep.ts. Silent\n // when there is nothing to remove, and once per root per process.\n this.sweepStaleBins(workspaceRoot);\n for (const doc of this.docs.closure(name, (docName: string): string => this.loadTemplate(docName))) {\n const target = this.destination(workspaceRoot, doc.name, instructDir);\n // A doc stamped with live run state is SEEDED, never refreshed: `wp-finish-upsert-pr` runs\n // while a conflicted merge is still open, and clobbering that handback with the reference\n // copy would delete the file list the agent is working from.\n if (doc.seedOnly() && fs.existsSync(target)) continue;\n this.atomicFile.writeIfChanged(target, doc.render(this.loadTemplate(doc.name), workspaceRoot));\n }\n return this.destination(workspaceRoot, name, instructDir);\n }\n\n /**\n * Remove this tree's dangling `wp-*` bin symlinks and SAY what went, on stdout beside everything else\n * a `wp-*` command prints. Nothing removed ⇒ nothing printed, which is the overwhelmingly common case.\n */\n private sweepStaleBins(workspaceRoot: string): void {\n const removed = this.staleBins.sweepOnce(workspaceRoot);\n for (const line of this.staleBins.report(removed)) process.stdout.write(line + '\\n');\n }\n\n // LOCAL `.webpieces/instruct-ai/<name>` by default; an explicitly-passed relative dir is still\n // joined onto workspaceRoot exactly as before.\n private destination(workspaceRoot: string, name: string, instructDir: string): string {\n if (instructDir === DEFAULT_INSTRUCT_DIR) {\n return this.dotDir.localFile(workspaceRoot, INSTRUCT_AI_LEAF, name);\n }\n return path.join(workspaceRoot, instructDir, name);\n }\n}\n\n// Temporary migration delegators — consumers migrate to injecting TemplateWriter over follow-up PRs.\nconst templateWriterSvc = new TemplateWriter();\n\nexport function loadTemplate(name: string): string {\n return templateWriterSvc.loadTemplate(name);\n}\n\nexport function writeTemplateIfMissing(\n workspaceRoot: string,\n name: string,\n instructDir: string = DEFAULT_INSTRUCT_DIR,\n): void {\n templateWriterSvc.writeTemplateIfMissing(workspaceRoot, name, instructDir);\n}\n\nexport function writeTemplate(\n workspaceRoot: string,\n name: string,\n instructDir: string = DEFAULT_INSTRUCT_DIR,\n): string {\n return templateWriterSvc.writeTemplate(workspaceRoot, name, instructDir);\n}\n"]}
|
|
@@ -5,8 +5,8 @@ const tslib_1 = require("tslib");
|
|
|
5
5
|
const fs = tslib_1.__importStar(require("fs"));
|
|
6
6
|
const path = tslib_1.__importStar(require("path"));
|
|
7
7
|
const inversify_1 = require("inversify");
|
|
8
|
-
const
|
|
9
|
-
const to_error_1 = require("
|
|
8
|
+
const tooling_common_1 = require("@webpieces/tooling-common");
|
|
9
|
+
const to_error_1 = require("@webpieces/tooling-common/to-error");
|
|
10
10
|
/** Where every sweep's archive lands, under the repo-wide `.webpieces/` — never under a worktree's own. */
|
|
11
11
|
exports.TRASH_STATE_DIR = 'trash';
|
|
12
12
|
/** The per-sweep manifest, holding what moved and the command that brings each one back. */
|
|
@@ -76,7 +76,7 @@ let OrphanDirArchiver = class OrphanDirArchiver {
|
|
|
76
76
|
}
|
|
77
77
|
/** `<repo>/.webpieces/trash` — the SHARED state dir, so a worktree's trash is not stranded with it. */
|
|
78
78
|
trashRoot(repoRoot) {
|
|
79
|
-
return path.join(
|
|
79
|
+
return path.join(tooling_common_1.dotWebpieces.shared(repoRoot), exports.TRASH_STATE_DIR);
|
|
80
80
|
}
|
|
81
81
|
/**
|
|
82
82
|
* `2026-08-19T14-32-05Z`. ISO order with `:` replaced, and milliseconds dropped — a sweep is a
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"orphan-dir-archive.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/orphan-dir-archive.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAG3D,2CAA2C;AAC3C,yCAAqC;AAErC,2GAA2G;AAC9F,QAAA,eAAe,GAAG,OAAO,CAAC;AACvC,4FAA4F;AAC/E,QAAA,mBAAmB,GAAG,eAAe,CAAC;AACnD,2GAA2G;AAC9F,QAAA,oBAAoB,GAAG,EAAE,CAAC;AAEvC,MAAM,cAAc,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAE3C;;;;;;;;;;;;;;;;;;;GAmBG;AAEI,IAAM,iBAAi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OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;IACvC,CAAC;CACJ;AApBD,8CAoBC;AAED,uDAAuD;AACvD,MAAa,mBAAmB;IAC5B,OAAO,CAAS;IAChB,QAAQ,CAAS;IACjB,KAAK,CAA4B;IACjC,MAAM,CAA0B;IAEhC,YAAY,OAAe,EAAE,QAAgB,EAAE,KAAgC,EAC3E,MAA+B;QAC/B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACzB,CAAC;CACJ;AAbD,kDAaC;AAED,wGAAwG;AACxG,MAAM,gBAAgB,GAAG,wCAAwC,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { OrphanCandidate } from './orphan-dir-scan';\nimport { dotWebpieces } from './state-dir';\nimport { toError } from './to-error';\n\n/** Where every sweep's archive lands, under the repo-wide `.webpieces/` — never under a worktree's own. */\nexport const TRASH_STATE_DIR = 'trash';\n/** The per-sweep manifest, holding what moved and the command that brings each one back. */\nexport const TRASH_MANIFEST_FILE = 'manifest.json';\n/** Sweeps older than this are reaped by the next sweep. Matches RETENTION_DAYS for the aged-tree sweep. */\nexport const TRASH_RETENTION_DAYS = 30;\n\nconst MILLIS_PER_DAY = 24 * 60 * 60 * 1000;\n\n/**\n * Moves orphan directories into `.webpieces/trash/<sweepId>/` and records how to bring each one back.\n *\n * ─── WHY `mv` AND NEVER `rm -rf` ──────────────────────────────────────────────────────────────────────\n * This runs unattended, on other people's machines, against a predicate that is very good but is still a\n * predicate. A `mv` makes the worst possible outcome — a false positive on a directory somebody actually\n * wanted — a thing they undo in one command, instead of a thing they restore from a backup or lose. That\n * single decision is what makes it defensible to run this automatically at all, and it is the same trade\n * `wp-cleanup` already makes when it archives a branch to a tag before deleting the ref.\n *\n * ─── WHY ONE DIRECTORY PER SWEEP, TIMESTAMP-NAMED ─────────────────────────────────────────────────────\n * `<sweepId>` is a UTC timestamp with `:` swapped for `-` (path-safe everywhere, Windows included). That\n * spelling sorts LEXICALLY in chronological order, so `ls` reads oldest-first and `ls -r` newest-first,\n * with no flags to remember and no dates to parse. Grouping by sweep also answers the only question\n * anybody actually asks of this directory — \"what did the run I just did take?\" — which a single flat\n * pile of moved directories cannot answer at all.\n *\n * Each sweep directory reproduces the repo-relative path of what it holds, so the manifest's `recover=`\n * is an ordinary `mv` of one path to another, with no bookkeeping needed to reconstruct the destination.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class OrphanDirArchiver {\n /**\n * Move every candidate into a fresh sweep directory. `now` is a parameter so specs pin the sweep id\n * instead of racing the clock.\n */\n archive(repoRoot: string, candidates: readonly OrphanCandidate[], now: Date): OrphanSweepResult {\n const sweepId = this.sweepId(now);\n const sweepDir = path.join(this.trashRoot(repoRoot), sweepId);\n const moved: ArchivedOrphan[] = [];\n const failed: FailedOrphan[] = [];\n for (const candidate of candidates) {\n const destination = path.join(sweepDir, candidate.relativePath);\n const failure = this.move(candidate.absolutePath, destination);\n if (failure !== null) {\n failed.push(new FailedOrphan(candidate.relativePath, failure));\n continue;\n }\n moved.push(new ArchivedOrphan(candidate.relativePath, destination,\n `mv '${destination}' '${candidate.absolutePath}'`));\n }\n const manifestError = this.writeManifest(sweepDir, sweepId, repoRoot, moved, failed);\n return new OrphanSweepResult(sweepId, sweepDir, moved, failed, manifestError);\n }\n\n /**\n * Delete sweep directories older than TRASH_RETENTION_DAYS, and report how many went. Called by the\n * sweeper AFTER a successful archive, so trash cannot grow without bound on a machine that has the\n * flag on. This one really does delete — it is deleting the archive, which is the second copy.\n */\n reapAged(repoRoot: string, now: Date): number {\n const root = this.trashRoot(repoRoot);\n const cutoff = now.getTime() - TRASH_RETENTION_DAYS * MILLIS_PER_DAY;\n let reaped = 0;\n for (const entry of this.listSweeps(root)) {\n const stamp = this.parseSweepId(entry);\n if (stamp === null || stamp.getTime() >= cutoff) continue;\n if (this.removeTree(path.join(root, entry))) reaped += 1;\n }\n return reaped;\n }\n\n /** `<repo>/.webpieces/trash` — the SHARED state dir, so a worktree's trash is not stranded with it. */\n trashRoot(repoRoot: string): string {\n return path.join(dotWebpieces.shared(repoRoot), TRASH_STATE_DIR);\n }\n\n /**\n * `2026-08-19T14-32-05Z`. ISO order with `:` replaced, and milliseconds dropped — a sweep is a\n * human-scale event and a second is resolution enough to name one.\n */\n sweepId(now: Date): string {\n return now.toISOString().replace(/\\.\\d{3}Z$/, 'Z').replace(/:/g, '-');\n }\n\n /** The Date a sweep id names, or null when the entry is not one of ours (a stray file, say). */\n private parseSweepId(entry: string): Date | null {\n if (!SWEEP_ID_PATTERN.test(entry)) return null;\n const iso = `${entry.slice(0, 10)}T${entry.slice(11, 19).replace(/-/g, ':')}Z`;\n const parsed = new Date(iso);\n return Number.isNaN(parsed.getTime()) ? null : parsed;\n }\n\n private listSweeps(root: string): string[] {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: no trash directory yet is the normal\n // state on every machine that has never swept, and it is not a condition anybody needs told about\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return fs.readdirSync(root);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return [];\n }\n }\n\n /**\n * `mv` the directory, creating the destination's parent chain first. Returns null on success, or the\n * failure's message — a directory we cannot move is REPORTED and skipped, never fatal.\n *\n * `fs.renameSync` first because it is atomic and instant within a filesystem; a cross-device rename\n * (EXDEV — a repo whose `.webpieces` sits on a different mount) falls back to a recursive copy plus\n * delete, which is what `mv` itself does in the same situation.\n */\n private move(from: string, to: string): string | null {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: converts a per-directory move failure\n // into a reported line, because one unmovable directory may not abandon the rest of the sweep\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.mkdirSync(path.dirname(to), { recursive: true });\n fs.renameSync(from, to);\n return null;\n } catch (err: unknown) {\n const error = toError(err);\n return this.moveAcrossDevices(from, to, error);\n }\n }\n\n private moveAcrossDevices(from: string, to: string, cause: Error): string | null {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: the fallback's own failure becomes the\n // reported message for this directory, the same contract move() has\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n if (!this.isCrossDevice(cause)) return cause.message;\n fs.cpSync(from, to, { recursive: true });\n fs.rmSync(from, { recursive: true, force: true });\n return null;\n } catch (err: unknown) {\n const error = toError(err);\n return error.message;\n }\n }\n\n private isCrossDevice(error: Error): boolean {\n // webpieces-disable no-any-unknown -- node attaches `code` to fs errors without typing it on Error\n const code = (error as unknown as Record<string, unknown>)['code'];\n return code === 'EXDEV';\n }\n\n private removeTree(target: string): boolean {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: failing to reap OLD trash is cosmetic\n // and may never surface as an error on a command whose real work already succeeded\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.rmSync(target, { recursive: true, force: true });\n return true;\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return false;\n }\n }\n\n /**\n * The sweep's own record, beside what it took. Written even when every move failed, because \"this\n * sweep tried and could not\" is exactly the state somebody debugging needs to find on disk.\n *\n * Returns the failure message, or null on success. It is REPORTED rather than swallowed: the manifest\n * is the durable copy of every `recover=` command, so losing it silently is the one failure here that\n * costs somebody the ability to undo what just happened. Still never fatal — the directories are\n * already safely moved by this point, and the recover lines are still printed to the terminal.\n */\n private writeManifest(sweepDir: string, sweepId: string, repoRoot: string,\n moved: readonly ArchivedOrphan[], failed: readonly FailedOrphan[]): string | null {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: the directories are already safely\n // moved by this point, and an unwritable manifest may not turn that success into a failure\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.mkdirSync(sweepDir, { recursive: true });\n fs.writeFileSync(path.join(sweepDir, TRASH_MANIFEST_FILE),\n `${JSON.stringify(new OrphanSweepManifest(sweepId, repoRoot, moved, failed), null, 2)}\\n`, 'utf8');\n return null;\n } catch (err: unknown) {\n const error = toError(err);\n return error.message;\n }\n }\n}\n\n/** One directory that was moved, and the exact command that undoes it. Data-only. */\nexport class ArchivedOrphan {\n /** Where it used to live, repo-relative. */\n relativePath: string;\n /** Where it lives now, absolute. */\n archivedAt: string;\n /** The `mv` that puts it back — printed to the human and stored in the manifest verbatim. */\n recoverCommand: string;\n\n constructor(relativePath: string, archivedAt: string, recoverCommand: string) {\n this.relativePath = relativePath;\n this.archivedAt = archivedAt;\n this.recoverCommand = recoverCommand;\n }\n}\n\n/** One directory the sweep found but could not move, with the reason. Data-only. */\nexport class FailedOrphan {\n relativePath: string;\n reason: string;\n\n constructor(relativePath: string, reason: string) {\n this.relativePath = relativePath;\n this.reason = reason;\n }\n}\n\n/** What one sweep did. Data-only. */\nexport class OrphanSweepResult {\n sweepId: string;\n sweepDir: string;\n moved: readonly ArchivedOrphan[];\n failed: readonly FailedOrphan[];\n /**\n * Why the manifest could not be written, or null when it was. Non-null means the printed `recover=`\n * lines are the ONLY copy — see writeManifest().\n */\n manifestError: string | null;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(sweepId: string, sweepDir: string, moved: readonly ArchivedOrphan[],\n failed: readonly FailedOrphan[], manifestError: string | null) {\n this.sweepId = sweepId;\n this.sweepDir = sweepDir;\n this.moved = moved;\n this.failed = failed;\n this.manifestError = manifestError;\n }\n}\n\n/** The on-disk shape of `manifest.json`. Data-only. */\nexport class OrphanSweepManifest {\n sweepId: string;\n repoRoot: string;\n moved: readonly ArchivedOrphan[];\n failed: readonly FailedOrphan[];\n\n constructor(sweepId: string, repoRoot: string, moved: readonly ArchivedOrphan[],\n failed: readonly FailedOrphan[]) {\n this.sweepId = sweepId;\n this.repoRoot = repoRoot;\n this.moved = moved;\n this.failed = failed;\n }\n}\n\n// `2026-08-19T14-32-05Z` — the exact shape sweepId() writes, and the only shape reapAged() will delete.\nconst SWEEP_ID_PATTERN = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d{2}Z$/;\n"]}
|
|
1
|
+
{"version":3,"file":"orphan-dir-archive.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/orphan-dir-archive.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAG3D,8DAAyD;AACzD,iEAA6D;AAE7D,2GAA2G;AAC9F,QAAA,eAAe,GAAG,OAAO,CAAC;AACvC,4FAA4F;AAC/E,QAAA,mBAAmB,GAAG,eAAe,CAAC;AACnD,2GAA2G;AAC9F,QAAA,oBAAoB,GAAG,EAAE,CAAC;AAEvC,MAAM,cAAc,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAE3C;;;;;;;;;;;;;;;;;;;GAmBG;AAEI,IAAM,iBAAiB,GAAvB,MAAM,iBAAiB;IAC1B;;;OAGG;IACH,OAAO,CAAC,QAAgB,EAAE,UAAsC,EAAE,GAAS;QACvE,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;QAClC,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,CAAC;QAC9D,MAAM,KAAK,GAAqB,EAAE,CAAC;QACnC,MAAM,MAAM,GAAmB,EAAE,CAAC;QAClC,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE,CAAC;YACjC,MAAM,WAAW,GAAG,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,SAAS,CAAC,YAAY,CAAC,CAAC;YAChE,MAAM,OAAO,GAAG,IAAI,CAAC,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AAK,CAAC;QACnB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACzB,CAAC;CACJ;AAbD,kDAaC;AAED,wGAAwG;AACxG,MAAM,gBAAgB,GAAG,wCAAwC,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { OrphanCandidate } from './orphan-dir-scan';\nimport { dotWebpieces } from '@webpieces/tooling-common';\nimport { toError } from '@webpieces/tooling-common/to-error';\n\n/** Where every sweep's archive lands, under the repo-wide `.webpieces/` — never under a worktree's own. */\nexport const TRASH_STATE_DIR = 'trash';\n/** The per-sweep manifest, holding what moved and the command that brings each one back. */\nexport const TRASH_MANIFEST_FILE = 'manifest.json';\n/** Sweeps older than this are reaped by the next sweep. Matches RETENTION_DAYS for the aged-tree sweep. */\nexport const TRASH_RETENTION_DAYS = 30;\n\nconst MILLIS_PER_DAY = 24 * 60 * 60 * 1000;\n\n/**\n * Moves orphan directories into `.webpieces/trash/<sweepId>/` and records how to bring each one back.\n *\n * ─── WHY `mv` AND NEVER `rm -rf` ──────────────────────────────────────────────────────────────────────\n * This runs unattended, on other people's machines, against a predicate that is very good but is still a\n * predicate. A `mv` makes the worst possible outcome — a false positive on a directory somebody actually\n * wanted — a thing they undo in one command, instead of a thing they restore from a backup or lose. That\n * single decision is what makes it defensible to run this automatically at all, and it is the same trade\n * `wp-cleanup` already makes when it archives a branch to a tag before deleting the ref.\n *\n * ─── WHY ONE DIRECTORY PER SWEEP, TIMESTAMP-NAMED ─────────────────────────────────────────────────────\n * `<sweepId>` is a UTC timestamp with `:` swapped for `-` (path-safe everywhere, Windows included). That\n * spelling sorts LEXICALLY in chronological order, so `ls` reads oldest-first and `ls -r` newest-first,\n * with no flags to remember and no dates to parse. Grouping by sweep also answers the only question\n * anybody actually asks of this directory — \"what did the run I just did take?\" — which a single flat\n * pile of moved directories cannot answer at all.\n *\n * Each sweep directory reproduces the repo-relative path of what it holds, so the manifest's `recover=`\n * is an ordinary `mv` of one path to another, with no bookkeeping needed to reconstruct the destination.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class OrphanDirArchiver {\n /**\n * Move every candidate into a fresh sweep directory. `now` is a parameter so specs pin the sweep id\n * instead of racing the clock.\n */\n archive(repoRoot: string, candidates: readonly OrphanCandidate[], now: Date): OrphanSweepResult {\n const sweepId = this.sweepId(now);\n const sweepDir = path.join(this.trashRoot(repoRoot), sweepId);\n const moved: ArchivedOrphan[] = [];\n const failed: FailedOrphan[] = [];\n for (const candidate of candidates) {\n const destination = path.join(sweepDir, candidate.relativePath);\n const failure = this.move(candidate.absolutePath, destination);\n if (failure !== null) {\n failed.push(new FailedOrphan(candidate.relativePath, failure));\n continue;\n }\n moved.push(new ArchivedOrphan(candidate.relativePath, destination,\n `mv '${destination}' '${candidate.absolutePath}'`));\n }\n const manifestError = this.writeManifest(sweepDir, sweepId, repoRoot, moved, failed);\n return new OrphanSweepResult(sweepId, sweepDir, moved, failed, manifestError);\n }\n\n /**\n * Delete sweep directories older than TRASH_RETENTION_DAYS, and report how many went. Called by the\n * sweeper AFTER a successful archive, so trash cannot grow without bound on a machine that has the\n * flag on. This one really does delete — it is deleting the archive, which is the second copy.\n */\n reapAged(repoRoot: string, now: Date): number {\n const root = this.trashRoot(repoRoot);\n const cutoff = now.getTime() - TRASH_RETENTION_DAYS * MILLIS_PER_DAY;\n let reaped = 0;\n for (const entry of this.listSweeps(root)) {\n const stamp = this.parseSweepId(entry);\n if (stamp === null || stamp.getTime() >= cutoff) continue;\n if (this.removeTree(path.join(root, entry))) reaped += 1;\n }\n return reaped;\n }\n\n /** `<repo>/.webpieces/trash` — the SHARED state dir, so a worktree's trash is not stranded with it. */\n trashRoot(repoRoot: string): string {\n return path.join(dotWebpieces.shared(repoRoot), TRASH_STATE_DIR);\n }\n\n /**\n * `2026-08-19T14-32-05Z`. ISO order with `:` replaced, and milliseconds dropped — a sweep is a\n * human-scale event and a second is resolution enough to name one.\n */\n sweepId(now: Date): string {\n return now.toISOString().replace(/\\.\\d{3}Z$/, 'Z').replace(/:/g, '-');\n }\n\n /** The Date a sweep id names, or null when the entry is not one of ours (a stray file, say). */\n private parseSweepId(entry: string): Date | null {\n if (!SWEEP_ID_PATTERN.test(entry)) return null;\n const iso = `${entry.slice(0, 10)}T${entry.slice(11, 19).replace(/-/g, ':')}Z`;\n const parsed = new Date(iso);\n return Number.isNaN(parsed.getTime()) ? null : parsed;\n }\n\n private listSweeps(root: string): string[] {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: no trash directory yet is the normal\n // state on every machine that has never swept, and it is not a condition anybody needs told about\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return fs.readdirSync(root);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return [];\n }\n }\n\n /**\n * `mv` the directory, creating the destination's parent chain first. Returns null on success, or the\n * failure's message — a directory we cannot move is REPORTED and skipped, never fatal.\n *\n * `fs.renameSync` first because it is atomic and instant within a filesystem; a cross-device rename\n * (EXDEV — a repo whose `.webpieces` sits on a different mount) falls back to a recursive copy plus\n * delete, which is what `mv` itself does in the same situation.\n */\n private move(from: string, to: string): string | null {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: converts a per-directory move failure\n // into a reported line, because one unmovable directory may not abandon the rest of the sweep\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.mkdirSync(path.dirname(to), { recursive: true });\n fs.renameSync(from, to);\n return null;\n } catch (err: unknown) {\n const error = toError(err);\n return this.moveAcrossDevices(from, to, error);\n }\n }\n\n private moveAcrossDevices(from: string, to: string, cause: Error): string | null {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: the fallback's own failure becomes the\n // reported message for this directory, the same contract move() has\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n if (!this.isCrossDevice(cause)) return cause.message;\n fs.cpSync(from, to, { recursive: true });\n fs.rmSync(from, { recursive: true, force: true });\n return null;\n } catch (err: unknown) {\n const error = toError(err);\n return error.message;\n }\n }\n\n private isCrossDevice(error: Error): boolean {\n // webpieces-disable no-any-unknown -- node attaches `code` to fs errors without typing it on Error\n const code = (error as unknown as Record<string, unknown>)['code'];\n return code === 'EXDEV';\n }\n\n private removeTree(target: string): boolean {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: failing to reap OLD trash is cosmetic\n // and may never surface as an error on a command whose real work already succeeded\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.rmSync(target, { recursive: true, force: true });\n return true;\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return false;\n }\n }\n\n /**\n * The sweep's own record, beside what it took. Written even when every move failed, because \"this\n * sweep tried and could not\" is exactly the state somebody debugging needs to find on disk.\n *\n * Returns the failure message, or null on success. It is REPORTED rather than swallowed: the manifest\n * is the durable copy of every `recover=` command, so losing it silently is the one failure here that\n * costs somebody the ability to undo what just happened. Still never fatal — the directories are\n * already safely moved by this point, and the recover lines are still printed to the terminal.\n */\n private writeManifest(sweepDir: string, sweepId: string, repoRoot: string,\n moved: readonly ArchivedOrphan[], failed: readonly FailedOrphan[]): string | null {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: the directories are already safely\n // moved by this point, and an unwritable manifest may not turn that success into a failure\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.mkdirSync(sweepDir, { recursive: true });\n fs.writeFileSync(path.join(sweepDir, TRASH_MANIFEST_FILE),\n `${JSON.stringify(new OrphanSweepManifest(sweepId, repoRoot, moved, failed), null, 2)}\\n`, 'utf8');\n return null;\n } catch (err: unknown) {\n const error = toError(err);\n return error.message;\n }\n }\n}\n\n/** One directory that was moved, and the exact command that undoes it. Data-only. */\nexport class ArchivedOrphan {\n /** Where it used to live, repo-relative. */\n relativePath: string;\n /** Where it lives now, absolute. */\n archivedAt: string;\n /** The `mv` that puts it back — printed to the human and stored in the manifest verbatim. */\n recoverCommand: string;\n\n constructor(relativePath: string, archivedAt: string, recoverCommand: string) {\n this.relativePath = relativePath;\n this.archivedAt = archivedAt;\n this.recoverCommand = recoverCommand;\n }\n}\n\n/** One directory the sweep found but could not move, with the reason. Data-only. */\nexport class FailedOrphan {\n relativePath: string;\n reason: string;\n\n constructor(relativePath: string, reason: string) {\n this.relativePath = relativePath;\n this.reason = reason;\n }\n}\n\n/** What one sweep did. Data-only. */\nexport class OrphanSweepResult {\n sweepId: string;\n sweepDir: string;\n moved: readonly ArchivedOrphan[];\n failed: readonly FailedOrphan[];\n /**\n * Why the manifest could not be written, or null when it was. Non-null means the printed `recover=`\n * lines are the ONLY copy — see writeManifest().\n */\n manifestError: string | null;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(sweepId: string, sweepDir: string, moved: readonly ArchivedOrphan[],\n failed: readonly FailedOrphan[], manifestError: string | null) {\n this.sweepId = sweepId;\n this.sweepDir = sweepDir;\n this.moved = moved;\n this.failed = failed;\n this.manifestError = manifestError;\n }\n}\n\n/** The on-disk shape of `manifest.json`. Data-only. */\nexport class OrphanSweepManifest {\n sweepId: string;\n repoRoot: string;\n moved: readonly ArchivedOrphan[];\n failed: readonly FailedOrphan[];\n\n constructor(sweepId: string, repoRoot: string, moved: readonly ArchivedOrphan[],\n failed: readonly FailedOrphan[]) {\n this.sweepId = sweepId;\n this.repoRoot = repoRoot;\n this.moved = moved;\n this.failed = failed;\n }\n}\n\n// `2026-08-19T14-32-05Z` — the exact shape sweepId() writes, and the only shape reapAged() will delete.\nconst SWEEP_ID_PATTERN = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d{2}Z$/;\n"]}
|
package/src/pr-gate-config.js
CHANGED
|
@@ -8,7 +8,7 @@ exports.defaultPrGateConfig = defaultPrGateConfig;
|
|
|
8
8
|
exports.buildPrGateConfig = buildPrGateConfig;
|
|
9
9
|
exports.buildDevDeployConfig = buildDevDeployConfig;
|
|
10
10
|
exports.buildLandPrConfig = buildLandPrConfig;
|
|
11
|
-
const
|
|
11
|
+
const repo_workflow_core_1 = require("@webpieces/repo-workflow-core");
|
|
12
12
|
const checklist_config_1 = require("./checklist-config");
|
|
13
13
|
// PrGateConfig is the "special section" for the pr-gate dashboard. It does NOT live in the
|
|
14
14
|
// validated `rules` map (the FieldDef schema can't express nested object arrays), but as a
|
|
@@ -78,14 +78,14 @@ class LandPrConfig {
|
|
|
78
78
|
// One of BRANCH_RETENTIONS. Defaults to 'archive-tag' — see BranchArchiver for why a tag beats
|
|
79
79
|
// keeping the branch, storing a patch, or trusting the reflog.
|
|
80
80
|
branchRetention;
|
|
81
|
-
constructor(branchRetention =
|
|
81
|
+
constructor(branchRetention = repo_workflow_core_1.BRANCH_RETENTION_ARCHIVE_TAG) {
|
|
82
82
|
this.branchRetention = branchRetention;
|
|
83
83
|
}
|
|
84
84
|
}
|
|
85
85
|
exports.LandPrConfig = LandPrConfig;
|
|
86
86
|
// webpieces-disable no-function-outside-class -- module-level config default, matches defaultGates/defaultPrGateConfig in this file
|
|
87
87
|
function defaultLandPrConfig() {
|
|
88
|
-
return new LandPrConfig(
|
|
88
|
+
return new LandPrConfig(repo_workflow_core_1.BRANCH_RETENTION_ARCHIVE_TAG);
|
|
89
89
|
}
|
|
90
90
|
// The two literal ref names the dev-deploy flow derives everything else from. Defaults, not policy —
|
|
91
91
|
// `pr-gate.devDeploy` overrides both, because a consumer whose shared environment is called `staging`
|
|
@@ -353,7 +353,7 @@ function buildLandPrConfig(raw) {
|
|
|
353
353
|
if (raw === undefined || raw === null || typeof raw !== 'object')
|
|
354
354
|
return defaults;
|
|
355
355
|
const retention = raw.branchRetention;
|
|
356
|
-
if (typeof retention !== 'string' || !
|
|
356
|
+
if (typeof retention !== 'string' || !repo_workflow_core_1.BRANCH_RETENTIONS.includes(retention))
|
|
357
357
|
return defaults;
|
|
358
358
|
return new LandPrConfig(retention);
|
|
359
359
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pr-gate-config.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/pr-gate-config.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CAAC,IAAI,EAAE;QAC5B,CAAC,CAAC,QAAQ,CAAC,eAAe,CAAC;IACnC,MAAM,SAAS,GACX,OAAO,GAAG,CAAC,SAAS,KAAK,QAAQ,IAAI,GAAG,CAAC,SAAS,CAAC,IAAI,EAAE,KAAK,EAAE;QAC5D,CAAC,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,EAAE;QACtB,CAAC,CAAC,QAAQ,CAAC,SAAS,CAAC;IAC7B,OAAO,IAAI,eAAe,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC;AACrD,CAAC;AAED;;;;GAIG;AACH,gHAAgH;AAChH,SAAgB,iBAAiB,CAAC,GAA0B;IACxD,MAAM,QAAQ,GAAG,mBAAmB,EAAE,CAAC;IACvC,IAAI,GAAG,KAAK,SAAS,IAAI,GAAG,KAAK,IAAI,IAAI,OAAO,GAAG,KAAK,QAAQ;QAAE,OAAO,QAAQ,CAAC;IAClF,MAAM,SAAS,GAAG,GAAG,CAAC,eAAe,CAAC;IACtC,IAAI,OAAO,SAAS,KAAK,QAAQ,IAAI,CAAC,mCAAiB,CAAC,QAAQ,CAAC,SAAS,CAAC;QAAE,OAAO,QAAQ,CAAC;IAC7F,OAAO,IAAI,YAAY,CAAC,SAAS,CAAC,CAAC;AACvC,CAAC","sourcesContent":["import { BRANCH_RETENTION_ARCHIVE_TAG, BRANCH_RETENTIONS } from './branch-archiver';\nimport {\n ChecklistDefinition,\n DEFAULT_REVIEWER_AGENT_NAME,\n RawChecklistItem,\n REVIEWER_AGENTS_PLACEHOLDER,\n ReviewerAgentPolicy,\n toChecklist,\n} from './checklist-config';\n\n// PrGateConfig is the \"special section\" for the pr-gate dashboard. It does NOT live in the\n// validated `rules` map (the FieldDef schema can't express nested object arrays), but as a\n// top-level `pr-gate` key in webpieces.config.json. It is built and validated by\n// loadAndValidate (load-config.ts); this module holds only the data classes + defaults + toGate.\n\n/**\n * The build the pr-gate runs when a repo configures no `commands.pr-gate.buildCommand` — and the ONE\n * definition of it, because two things now need it: the gate that RUNS it (pr-gate's BuildAffected)\n * and the guard that REFUSES a whole-monorepo build and prints it instead (ai-hook-rules'\n * whole-repo-build-guard). A second copy in either package is a message that can teach a command the\n * gate does not run.\n *\n * `--base=$(git merge-base origin/main HEAD)` — the FORK POINT, not `origin/main`: basing on\n * origin/main marks projects touched by other people's already-merged PRs as affected. The `$(…)`\n * resolves because the gate spawns with `shell: true`; the guard resolves it itself before printing,\n * so the AI is never handed a template it might paste somewhere without a shell.\n */\nexport const DEFAULT_BUILD_COMMAND =\n 'pnpm nx affected --target=ci --base=$(git merge-base origin/main HEAD)';\n\nexport class GateDefinition {\n name: string;\n patterns: string[];\n // The warning color shown on the dashboard WHEN this gate's patterns match a changed file. Green\n // is implicit (shown when nothing matched), so it is never configured. warningColor is purely\n // visual — even 'red' never fails/blocks the PR (only the build gate can). 'yellow' = caution,\n // 'red' = louder \"look here\" flag (e.g. DB schema / migration changes). REQUIRED on every gate.\n warningColor: string; // 'yellow' | 'red'\n // Example/inactive gate: parsed and kept in the file (JSON has no comments) but skipped at\n // compute/render time. Other projects flip this to false and tune patterns/warningColor.\n disabled: boolean;\n\n constructor(name: string, patterns: string[], warningColor: string, disabled = false) {\n this.name = name;\n this.patterns = patterns;\n this.warningColor = warningColor;\n this.disabled = disabled;\n }\n}\n\n// How wp-finish-upsert-pr should try to LAND the PR once it has posted it. GitHub's auto-merge queue\n// is a REPO-level setting (`allow_auto_merge`) that many orgs turn OFF as a policy control, and it\n// CANNOT be forced from the client: `gh pr merge --auto` calls the enablePullRequestAutoMerge GraphQL\n// mutation, which hard-errors with \"Auto merge is not allowed for this repository\" when the repo says\n// no. So the only lever a config knob has is WHICH PATHS WE ATTEMPT — never whether the queue exists.\nexport const MERGE_MODE_AUTO = 'AUTO';\nexport const MERGE_MODE_NONE = 'NONE';\nexport const MERGE_MODES = [MERGE_MODE_AUTO, MERGE_MODE_NONE];\n\n/**\n * `pr-gate.landPr` — what happens to the LOCAL branch once its PR has landed.\n *\n * A rich object rather than a bare string (the `commands.pr-gate` precedent) so the next knob about\n * landing has a home, and so the rationale can sit beside the setting as a `*Why` sibling: JSON has no\n * comments, and `<key>Why` is how this repo documents non-obvious config.\n */\n/**\n * One `pr-gate.reviewContext` entry: a human label and a repo-relative path a reviewer is handed instead of\n * having to find it. Data-only (per CLAUDE.md).\n */\nexport class ReviewContextEntry {\n label: string;\n path: string; // repo-relative in config; resolved to absolute when written into an instructions file\n\n constructor(label: string, entryPath: string) {\n this.label = label;\n this.path = entryPath;\n }\n}\n\nexport class LandPrConfig {\n // One of BRANCH_RETENTIONS. Defaults to 'archive-tag' — see BranchArchiver for why a tag beats\n // keeping the branch, storing a patch, or trusting the reflog.\n branchRetention: string;\n\n constructor(branchRetention: string = BRANCH_RETENTION_ARCHIVE_TAG) {\n this.branchRetention = branchRetention;\n }\n}\n\n// webpieces-disable no-function-outside-class -- module-level config default, matches defaultGates/defaultPrGateConfig in this file\nexport function defaultLandPrConfig(): LandPrConfig {\n return new LandPrConfig(BRANCH_RETENTION_ARCHIVE_TAG);\n}\n\n// The two literal ref names the dev-deploy flow derives everything else from. Defaults, not policy —\n// `pr-gate.devDeploy` overrides both, because a consumer whose shared environment is called `staging`\n// must not be forced onto webpieces' vocabulary.\nexport const DEFAULT_DEV_BRANCH_NAMESPACE = 'dev-include';\nexport const DEFAULT_DEV_BRANCH = 'dev';\n\n/**\n * `pr-gate.devDeploy` — where `wp-push-dev` publishes the throwaway copy of a feature branch, and which\n * ref is the shared dev branch itself.\n *\n * WHY A NAMESPACE AT ALL, i.e. why the copy is not just the feature branch: the feature branch is the PR\n * head, and landing that PR ships whatever is on it. The moment a conflict between two devs has to be\n * resolved SOMEWHERE for the shared environment to build, that resolution needs a home that is not the PR\n * branch — otherwise \"test it in dev\" silently ships another dev's unreviewed work to production. The\n * `<branchNamespace>/<feature>` copy is that home, and it is disposable by construction.\n *\n * `devBranch` is REFUSED as a source branch (you never push the composed branch back into itself); it is\n * written by the consumer's CI only, which recomputes it from `origin/main` on every run.\n */\nexport class DevDeployConfig {\n // Literal prefix on the feature branch name: `dev-include/dean/ONE-2275`. Git refs allow slashes, and\n // nobody ever types this — the command derives it.\n branchNamespace: string;\n // The composed, CI-owned branch that actually deploys. Never a source, never pushed to by this flow.\n devBranch: string;\n\n constructor(\n branchNamespace: string = DEFAULT_DEV_BRANCH_NAMESPACE,\n devBranch: string = DEFAULT_DEV_BRANCH,\n ) {\n this.branchNamespace = branchNamespace;\n this.devBranch = devBranch;\n }\n\n /** `<branchNamespace>/<branch>` — the remote ref holding the disposable copy of `branch`. */\n copyRefFor(branch: string): string {\n return `${this.branchNamespace}/${branch}`;\n }\n\n /** The `git ls-remote --heads origin <pattern>` pattern matching every live copy. */\n copyRefGlob(): string {\n return `${this.branchNamespace}/*`;\n }\n}\n\n// webpieces-disable no-function-outside-class -- module-level config default, matches defaultGates/defaultPrGateConfig in this file\nexport function defaultDevDeployConfig(): DevDeployConfig {\n return new DevDeployConfig(DEFAULT_DEV_BRANCH_NAMESPACE, DEFAULT_DEV_BRANCH);\n}\n\nexport class PrGateConfig {\n mode: string;\n /**\n * The nx-affected build gate command, shared by the two commands that can run it.\n *\n * It is NOT finish-only any more, and the change is the point. It used to run once, in\n * wp-finish-upsert-pr, which meant reviewers were spawned against a branch nobody had built — they could\n * spend a full review on code that does not compile, or on an unresolved 3-point merge.\n *\n * Now `wp-review-upsert-pr` finalizes the merge and runs this gate BEFORE briefing any reviewer, and\n * records the passing HEAD sha in the stage receipt. `wp-finish-upsert-pr` re-runs it only when HEAD has\n * moved since — so the flow gained a gate where it mattered without paying for two full builds.\n *\n * Empty string => BuildAffected falls back to DEFAULT_BUILD_COMMAND.\n */\n buildCommand: string;\n gates: GateDefinition[];\n /**\n * REQUIRED — every repo must state its policy; there is deliberately no default, because the two\n * answers are a real policy decision and guessing it either merges when a team did not want that,\n * or silently stops landing PRs on a team that relied on it.\n *\n * AUTO — wp-finish-upsert-pr LANDS the PR: squash-merge it right away when it is mergeable, else\n * enable GitHub auto-merge so it lands when the checks pass. Both carry an explicit --subject /\n * --body-file, which is the ONLY way main's history gets the PR title plus the compact\n * risk/flags body — no repo setting can produce that. Requires allow_auto_merge on the repo.\n * NONE — wp-finish-upsert-pr only opens/updates the PR and stops; a human merges. NOTE the cost:\n * a UI merge cannot use the compact body, so main's commit falls back to the repo's\n * squash_merge_commit_title/message settings. Set squash_merge_commit_title=PR_TITLE there, or\n * commits land as the internal \"Squash merge of <branch>\" subject.\n */\n mergeMode: string;\n // This repo's review checklists, straight from the `pr-gate.checklists` ARRAY in webpieces.config.json —\n // the ONLY accepted shape (`patterns` is a path-glob dispatch table and `id` the checklist's name, so both\n // are config). Every def carries {@link reviewer}. [] = no checklists. The removed `{ doc }` manifest\n // form is a hard config error; see validateChecklistsSection.\n checklists: ChecklistDefinition[];\n /**\n * The ONE agent type every checklist is reviewed by — `webpieces-reviewer` unless\n * `overrideReviewerAgent` is true, in which case `reviewerAgentName` — and `reviewerAgents`, the most such\n * subagents a round may use. The same instance is bound into every {@link checklists} entry, so a caller\n * holding only a checklist still knows what to spawn. Field-with-default because the constructor is at\n * max-params; the agent name defaults to the webpieces reviewer, exactly what a config that says nothing\n * gets, while the CAP is a required field, so the placeholder here is only ever overwritten by the real\n * number buildPrGateConfig reads.\n */\n reviewer: ReviewerAgentPolicy = new ReviewerAgentPolicy(DEFAULT_REVIEWER_AGENT_NAME, REVIEWER_AGENTS_PLACEHOLDER);\n /**\n * REQUIRED positive integer: the maximum number of complete global reviewer rounds a PR review state\n * may start. This is deliberately repository policy rather than a machine-local preference.\n */\n maxReviewerRounds!: number;\n // Whether wp-finish-upsert-pr publishes each reviewer's full `output` as ONE combined PR comment\n // (idempotently updated on every push). Defaults to true. Set false to keep the PR body-only.\n checklistComments: boolean;\n /**\n * Shared secret used to mint the server-verifiable gate token. `wp-finish-upsert-pr` writes it after\n * the automated gate passes; `wp-human-post-pr` writes the same token after explicit human attestation\n * and visibly labels review as skipped plus whether its optional local build ran. A CI check\n * recomputes it from the PR head + salt.\n *\n * Optional, defaults to '' — empty means \"no token minted, no CI enforcement\" (byte-identical to\n * before this field existed). This is COMMITTED, obscurity-grade: it stops unhooked teammates who\n * push + open a PR in the web UI, but is readable in-repo and therefore forgeable by a determined\n * reader. It is deliberately NOT cryptographically sound; nothing local can stop a filesystem-reading\n * agent. See RESPONSE-pr-gate-ci-enforcement / the design memo for the full tradeoff.\n */\n gateSalt: string;\n /**\n * What `wp-land-pr` (and `wp-cleanup`, which reaps the same branches) does with the LOCAL branch\n * once its PR is in main. Field-with-default rather than another positional constructor param —\n * this constructor is already at the max-params limit, and every existing `new PrGateConfig(...)`\n * call site correctly wants the default.\n */\n landPr: LandPrConfig = defaultLandPrConfig();\n /**\n * Globs whose diffs are NOT extracted into `.webpieces/pr-review/<feature>/diff/` — regenerated noise a\n * reviewer should not spend context reading (lockfiles, generated graphs). Default [].\n *\n * They are still MATCHED against checklists and still listed in the manifest, with a stub naming the\n * command that gets the real diff. Removing them from the changed-file set would read as \"this file did\n * not change\", which is a different and false claim.\n *\n * Fields-with-defaults rather than constructor params: that constructor is already at max-params, and\n * every existing `new PrGateConfig(...)` correctly wants the defaults.\n */\n reviewDiffExclude: string[] = [];\n /**\n * Repo-specific places a reviewer would otherwise hunt for, as `{label, path}` — e.g.\n * `{\"label\":\"Cloud Tasks queue names\",\"path\":\"terraform/services/\"}`. Resolved to absolute paths in each\n * generated instructions file; a configured-but-missing path is printed as missing, never dropped.\n */\n reviewContext: ReviewContextEntry[] = [];\n /**\n * Installed packages to resolve and hand reviewers by absolute directory. This is the knob aimed at a\n * measured failure: one reviewer burned three separate greps into `node_modules/@webpieces` looking for\n * a scanner the tooling could have pointed at directly.\n */\n reviewContextPackages: string[] = [];\n /**\n * Promote \"this reviewer wrote a verdict without ever opening the diff\" from a warning to a refusal.\n * Default false, and it should stay false until a repo has watched the warning for a while: the signal\n * is derived from undocumented Claude Code transcript internals, so a format change would otherwise\n * wedge every PR in the repo with no self-service way out.\n */\n requireDiffEvidence = false;\n /**\n * Where `wp-push-dev` publishes the disposable copy. Omitted ⇒ `dev-include` / `dev`, which is what\n * makes the whole flow work with NO config edit at all.\n */\n devDeploy: DevDeployConfig = defaultDevDeployConfig();\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n mode: string,\n buildCommand: string,\n gates: GateDefinition[],\n mergeMode: string,\n checklists: ChecklistDefinition[] = [],\n gateSalt = '',\n checklistComments = true,\n ) {\n this.mode = mode;\n this.buildCommand = buildCommand;\n this.gates = gates;\n this.mergeMode = mergeMode;\n this.checklists = checklists;\n this.gateSalt = gateSalt;\n this.checklistComments = checklistComments;\n }\n}\n\n// Default infra gates — path-pattern based, tuned for this monorepo. Clients override the\n// whole list via the `pr-gate.gates` array in webpieces.config.json.\nexport function defaultGates(): GateDefinition[] {\n return [\n new GateDefinition('API Changed', ['libraries/apis/**', '**/*Api.ts'], 'yellow'),\n new GateDefinition(\n 'Config Files Changed',\n ['**/package.json', '**/tsconfig*.json', 'nx.json', '**/*.config.*'],\n 'yellow',\n ),\n new GateDefinition(\n 'Dependency Graph Changed',\n ['architecture/dependencies.json'],\n 'yellow',\n ),\n new GateDefinition(\n 'Claude / Rules Changed',\n ['**/CLAUDE.md', '**/claude.*.md', '.claude/**', 'webpieces.config.json'],\n 'yellow',\n ),\n ];\n}\n\nexport function defaultPrGateConfig(): PrGateConfig {\n // No default checklists — the extension point is opt-in; the default monorepo ships none.\n return new PrGateConfig('ON', '', defaultGates(), MERGE_MODE_AUTO, []);\n}\n\ninterface RawGate {\n name?: string;\n patterns?: string[];\n warningColor?: string;\n disabled?: boolean;\n}\n\ninterface RawPrGateSection {\n mode?: string;\n buildCommand?: string;\n gates?: RawGate[];\n mergeMode?: string;\n // An ARRAY, always. validateChecklistsSection rejects every other shape (including the removed { doc }).\n checklists?: RawChecklistItem[];\n overrideReviewerAgent?: boolean;\n reviewerAgentName?: string;\n reviewerAgents?: number;\n maxReviewerRounds?: number;\n gateSalt?: string;\n checklistComments?: boolean;\n landPr?: RawLandPr;\n reviewDiffExclude?: string[];\n reviewContext?: RawReviewContext[];\n reviewContextPackages?: string[];\n requireDiffEvidence?: boolean;\n devDeploy?: RawDevDeploy;\n}\n\ninterface RawDevDeploy {\n branchNamespace?: string;\n devBranch?: string;\n}\n\ninterface RawLandPr {\n branchRetention?: string;\n}\n\ninterface RawReviewContext {\n label?: string;\n path?: string;\n}\n\nfunction toGate(raw: RawGate): GateDefinition {\n return new GateDefinition(\n raw.name ?? '',\n raw.patterns ?? [],\n raw.warningColor ?? 'yellow',\n raw.disabled ?? false,\n );\n}\n\n/**\n * Build a PrGateConfig from the already-parsed top-level `pr-gate` section, falling back to defaults\n * for any field the consumer omits. Pure transform — the file read + structural validation happen in\n * loadAndValidate (load-config.ts) so every consumer goes through one validated path. Pass undefined\n * (no `pr-gate` key / no config file) to get full defaults.\n */\n// webpieces-disable no-any-unknown -- `section` is opaque consumer JSON until narrowed here\nexport function buildPrGateConfig(section: unknown): PrGateConfig {\n const defaults = defaultPrGateConfig();\n if (section === undefined || section === null || typeof section !== 'object') return defaults;\n\n const raw = section as RawPrGateSection;\n const mode = raw.mode ?? defaults.mode;\n const buildCommand = raw.buildCommand ?? defaults.buildCommand;\n const gates = raw.gates !== undefined ? raw.gates.map(toGate) : defaults.gates;\n // REQUIRED — validatePrGateSection rejects an omitted/unknown value, so this fallback only ever\n // applies to the no-config-file path that defaultPrGateConfig() serves.\n const mergeMode = raw.mergeMode ?? defaults.mergeMode;\n // Optional extension point — omitted ⇒ [] ⇒ no checklists computed anywhere downstream. A non-array here\n // cannot reach us: validateChecklistsSection has already failed the load.\n // The webpieces reviewer unless `overrideReviewerAgent` is true, in which case `reviewerAgentName` names the\n // agent (validatePrGateSection rejects a name without the override, and the override without a name).\n // Required nonnegative integer: 0 disables reviewer-agent reviews; positive values cap the round.\n const agentName =\n raw.overrideReviewerAgent === true\n ? (raw.reviewerAgentName ?? '').trim()\n : DEFAULT_REVIEWER_AGENT_NAME;\n // `reviewerAgents` is REQUIRED and validated as a nonnegative integer before this runs, so the fallback is\n // unreachable in a loaded config and exists only to keep this total for a structure-only caller.\n const reviewer = new ReviewerAgentPolicy(\n agentName,\n typeof raw.reviewerAgents === 'number' ? raw.reviewerAgents : REVIEWER_AGENTS_PLACEHOLDER,\n );\n const checklists = Array.isArray(raw.checklists)\n ? raw.checklists.map(\n (item: RawChecklistItem): ChecklistDefinition => toChecklist(item, reviewer),\n )\n : defaults.checklists;\n // Optional — omitted ⇒ '' ⇒ no gate token minted and CI enforcement is a no-op (back-compat).\n const gateSalt = raw.gateSalt ?? defaults.gateSalt;\n // Optional — omitted ⇒ true ⇒ reviewer output published as a PR comment.\n const checklistComments = raw.checklistComments ?? defaults.checklistComments;\n const built = new PrGateConfig(\n mode,\n buildCommand,\n gates,\n mergeMode,\n checklists,\n gateSalt,\n checklistComments,\n );\n built.landPr = buildLandPrConfig(raw.landPr);\n built.reviewer = reviewer;\n built.maxReviewerRounds = raw.maxReviewerRounds as number;\n // Review-context knobs. All optional and all defaulted, so a config that omits every one of them (which\n // is every consumer's config today) behaves exactly as it did before they existed.\n built.reviewDiffExclude = Array.isArray(raw.reviewDiffExclude)\n ? raw.reviewDiffExclude\n : defaults.reviewDiffExclude;\n built.reviewContextPackages = Array.isArray(raw.reviewContextPackages)\n ? raw.reviewContextPackages\n : defaults.reviewContextPackages;\n built.reviewContext = Array.isArray(raw.reviewContext)\n ? raw.reviewContext.map(\n (e: RawReviewContext): ReviewContextEntry =>\n new ReviewContextEntry(e.label ?? '', e.path ?? ''),\n )\n : defaults.reviewContext;\n built.requireDiffEvidence = raw.requireDiffEvidence ?? defaults.requireDiffEvidence;\n built.devDeploy = buildDevDeployConfig(raw.devDeploy);\n return built;\n}\n\n/**\n * Build the `pr-gate.devDeploy` block. Omitted (the state of every consumer config today) ⇒ the\n * `dev-include` / `dev` defaults. An invalid value cannot reach here — validateDevDeploySection has\n * already failed the load.\n */\n// webpieces-disable no-function-outside-class -- module-level config transform, matches buildPrGateConfig above\nexport function buildDevDeployConfig(raw: RawDevDeploy | undefined): DevDeployConfig {\n const defaults = defaultDevDeployConfig();\n if (raw === undefined || raw === null || typeof raw !== 'object') return defaults;\n const namespace =\n typeof raw.branchNamespace === 'string' && raw.branchNamespace.trim() !== ''\n ? raw.branchNamespace.trim()\n : defaults.branchNamespace;\n const devBranch =\n typeof raw.devBranch === 'string' && raw.devBranch.trim() !== ''\n ? raw.devBranch.trim()\n : defaults.devBranch;\n return new DevDeployConfig(namespace, devBranch);\n}\n\n/**\n * Build the `pr-gate.landPr` block. Omitted (the current state of every consumer's config) ⇒ the\n * 'archive-tag' default, which is what makes this feature work with NO config edit at all. An invalid\n * value cannot reach here — validatePrGateSection has already failed the load.\n */\n// webpieces-disable no-function-outside-class -- module-level config transform, matches buildPrGateConfig above\nexport function buildLandPrConfig(raw: RawLandPr | undefined): LandPrConfig {\n const defaults = defaultLandPrConfig();\n if (raw === undefined || raw === null || typeof raw !== 'object') return defaults;\n const retention = raw.branchRetention;\n if (typeof retention !== 'string' || !BRANCH_RETENTIONS.includes(retention)) return defaults;\n return new LandPrConfig(retention);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"pr-gate-config.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/pr-gate-config.ts"],"names":[],"mappings":";;;AA2FA,kDAEC;AAgDD,wDAEC;AAwID,oCAmBC;AAED,kDAGC;AA4DD,8CAgEC;AAQD,oDAYC;AAQD,8CAMC;AA7cD,sEAAgG;AAChG,yDAO4B;AAE5B,2FAA2F;AAC3F,2FAA2F;AAC3F,iFAAiF;AACjF,iGAAiG;AAEjG;;;;;;;;;;;GAWG;AACU,QAAA,qBAAqB,GAC9B,wEAAwE,CAAC;AAE7E,MAAa,cAAc;IACvB,IAAI,CAAS;IACb,QAAQ,CAAW;IACnB,iGAAiG;IACjG,8FAA8F;IAC9F,+FAA+F;IAC/F,gGAAgG;IAChG,YAAY,CAAS,CAAC,mBAAmB;IACzC,2FAA2F;IAC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mB,EAAE,CAAC;IACvC,IAAI,GAAG,KAAK,SAAS,IAAI,GAAG,KAAK,IAAI,IAAI,OAAO,GAAG,KAAK,QAAQ;QAAE,OAAO,QAAQ,CAAC;IAClF,MAAM,SAAS,GAAG,GAAG,CAAC,eAAe,CAAC;IACtC,IAAI,OAAO,SAAS,KAAK,QAAQ,IAAI,CAAC,sCAAiB,CAAC,QAAQ,CAAC,SAAS,CAAC;QAAE,OAAO,QAAQ,CAAC;IAC7F,OAAO,IAAI,YAAY,CAAC,SAAS,CAAC,CAAC;AACvC,CAAC","sourcesContent":["import { BRANCH_RETENTION_ARCHIVE_TAG, BRANCH_RETENTIONS } from '@webpieces/repo-workflow-core';\nimport {\n ChecklistDefinition,\n DEFAULT_REVIEWER_AGENT_NAME,\n RawChecklistItem,\n REVIEWER_AGENTS_PLACEHOLDER,\n ReviewerAgentPolicy,\n toChecklist,\n} from './checklist-config';\n\n// PrGateConfig is the \"special section\" for the pr-gate dashboard. It does NOT live in the\n// validated `rules` map (the FieldDef schema can't express nested object arrays), but as a\n// top-level `pr-gate` key in webpieces.config.json. It is built and validated by\n// loadAndValidate (load-config.ts); this module holds only the data classes + defaults + toGate.\n\n/**\n * The build the pr-gate runs when a repo configures no `commands.pr-gate.buildCommand` — and the ONE\n * definition of it, because two things now need it: the gate that RUNS it (pr-gate's BuildAffected)\n * and the guard that REFUSES a whole-monorepo build and prints it instead (ai-hook-rules'\n * whole-repo-build-guard). A second copy in either package is a message that can teach a command the\n * gate does not run.\n *\n * `--base=$(git merge-base origin/main HEAD)` — the FORK POINT, not `origin/main`: basing on\n * origin/main marks projects touched by other people's already-merged PRs as affected. The `$(…)`\n * resolves because the gate spawns with `shell: true`; the guard resolves it itself before printing,\n * so the AI is never handed a template it might paste somewhere without a shell.\n */\nexport const DEFAULT_BUILD_COMMAND =\n 'pnpm nx affected --target=ci --base=$(git merge-base origin/main HEAD)';\n\nexport class GateDefinition {\n name: string;\n patterns: string[];\n // The warning color shown on the dashboard WHEN this gate's patterns match a changed file. Green\n // is implicit (shown when nothing matched), so it is never configured. warningColor is purely\n // visual — even 'red' never fails/blocks the PR (only the build gate can). 'yellow' = caution,\n // 'red' = louder \"look here\" flag (e.g. DB schema / migration changes). REQUIRED on every gate.\n warningColor: string; // 'yellow' | 'red'\n // Example/inactive gate: parsed and kept in the file (JSON has no comments) but skipped at\n // compute/render time. Other projects flip this to false and tune patterns/warningColor.\n disabled: boolean;\n\n constructor(name: string, patterns: string[], warningColor: string, disabled = false) {\n this.name = name;\n this.patterns = patterns;\n this.warningColor = warningColor;\n this.disabled = disabled;\n }\n}\n\n// How wp-finish-upsert-pr should try to LAND the PR once it has posted it. GitHub's auto-merge queue\n// is a REPO-level setting (`allow_auto_merge`) that many orgs turn OFF as a policy control, and it\n// CANNOT be forced from the client: `gh pr merge --auto` calls the enablePullRequestAutoMerge GraphQL\n// mutation, which hard-errors with \"Auto merge is not allowed for this repository\" when the repo says\n// no. So the only lever a config knob has is WHICH PATHS WE ATTEMPT — never whether the queue exists.\nexport const MERGE_MODE_AUTO = 'AUTO';\nexport const MERGE_MODE_NONE = 'NONE';\nexport const MERGE_MODES = [MERGE_MODE_AUTO, MERGE_MODE_NONE];\n\n/**\n * `pr-gate.landPr` — what happens to the LOCAL branch once its PR has landed.\n *\n * A rich object rather than a bare string (the `commands.pr-gate` precedent) so the next knob about\n * landing has a home, and so the rationale can sit beside the setting as a `*Why` sibling: JSON has no\n * comments, and `<key>Why` is how this repo documents non-obvious config.\n */\n/**\n * One `pr-gate.reviewContext` entry: a human label and a repo-relative path a reviewer is handed instead of\n * having to find it. Data-only (per CLAUDE.md).\n */\nexport class ReviewContextEntry {\n label: string;\n path: string; // repo-relative in config; resolved to absolute when written into an instructions file\n\n constructor(label: string, entryPath: string) {\n this.label = label;\n this.path = entryPath;\n }\n}\n\nexport class LandPrConfig {\n // One of BRANCH_RETENTIONS. Defaults to 'archive-tag' — see BranchArchiver for why a tag beats\n // keeping the branch, storing a patch, or trusting the reflog.\n branchRetention: string;\n\n constructor(branchRetention: string = BRANCH_RETENTION_ARCHIVE_TAG) {\n this.branchRetention = branchRetention;\n }\n}\n\n// webpieces-disable no-function-outside-class -- module-level config default, matches defaultGates/defaultPrGateConfig in this file\nexport function defaultLandPrConfig(): LandPrConfig {\n return new LandPrConfig(BRANCH_RETENTION_ARCHIVE_TAG);\n}\n\n// The two literal ref names the dev-deploy flow derives everything else from. Defaults, not policy —\n// `pr-gate.devDeploy` overrides both, because a consumer whose shared environment is called `staging`\n// must not be forced onto webpieces' vocabulary.\nexport const DEFAULT_DEV_BRANCH_NAMESPACE = 'dev-include';\nexport const DEFAULT_DEV_BRANCH = 'dev';\n\n/**\n * `pr-gate.devDeploy` — where `wp-push-dev` publishes the throwaway copy of a feature branch, and which\n * ref is the shared dev branch itself.\n *\n * WHY A NAMESPACE AT ALL, i.e. why the copy is not just the feature branch: the feature branch is the PR\n * head, and landing that PR ships whatever is on it. The moment a conflict between two devs has to be\n * resolved SOMEWHERE for the shared environment to build, that resolution needs a home that is not the PR\n * branch — otherwise \"test it in dev\" silently ships another dev's unreviewed work to production. The\n * `<branchNamespace>/<feature>` copy is that home, and it is disposable by construction.\n *\n * `devBranch` is REFUSED as a source branch (you never push the composed branch back into itself); it is\n * written by the consumer's CI only, which recomputes it from `origin/main` on every run.\n */\nexport class DevDeployConfig {\n // Literal prefix on the feature branch name: `dev-include/dean/ONE-2275`. Git refs allow slashes, and\n // nobody ever types this — the command derives it.\n branchNamespace: string;\n // The composed, CI-owned branch that actually deploys. Never a source, never pushed to by this flow.\n devBranch: string;\n\n constructor(\n branchNamespace: string = DEFAULT_DEV_BRANCH_NAMESPACE,\n devBranch: string = DEFAULT_DEV_BRANCH,\n ) {\n this.branchNamespace = branchNamespace;\n this.devBranch = devBranch;\n }\n\n /** `<branchNamespace>/<branch>` — the remote ref holding the disposable copy of `branch`. */\n copyRefFor(branch: string): string {\n return `${this.branchNamespace}/${branch}`;\n }\n\n /** The `git ls-remote --heads origin <pattern>` pattern matching every live copy. */\n copyRefGlob(): string {\n return `${this.branchNamespace}/*`;\n }\n}\n\n// webpieces-disable no-function-outside-class -- module-level config default, matches defaultGates/defaultPrGateConfig in this file\nexport function defaultDevDeployConfig(): DevDeployConfig {\n return new DevDeployConfig(DEFAULT_DEV_BRANCH_NAMESPACE, DEFAULT_DEV_BRANCH);\n}\n\nexport class PrGateConfig {\n mode: string;\n /**\n * The nx-affected build gate command, shared by the two commands that can run it.\n *\n * It is NOT finish-only any more, and the change is the point. It used to run once, in\n * wp-finish-upsert-pr, which meant reviewers were spawned against a branch nobody had built — they could\n * spend a full review on code that does not compile, or on an unresolved 3-point merge.\n *\n * Now `wp-review-upsert-pr` finalizes the merge and runs this gate BEFORE briefing any reviewer, and\n * records the passing HEAD sha in the stage receipt. `wp-finish-upsert-pr` re-runs it only when HEAD has\n * moved since — so the flow gained a gate where it mattered without paying for two full builds.\n *\n * Empty string => BuildAffected falls back to DEFAULT_BUILD_COMMAND.\n */\n buildCommand: string;\n gates: GateDefinition[];\n /**\n * REQUIRED — every repo must state its policy; there is deliberately no default, because the two\n * answers are a real policy decision and guessing it either merges when a team did not want that,\n * or silently stops landing PRs on a team that relied on it.\n *\n * AUTO — wp-finish-upsert-pr LANDS the PR: squash-merge it right away when it is mergeable, else\n * enable GitHub auto-merge so it lands when the checks pass. Both carry an explicit --subject /\n * --body-file, which is the ONLY way main's history gets the PR title plus the compact\n * risk/flags body — no repo setting can produce that. Requires allow_auto_merge on the repo.\n * NONE — wp-finish-upsert-pr only opens/updates the PR and stops; a human merges. NOTE the cost:\n * a UI merge cannot use the compact body, so main's commit falls back to the repo's\n * squash_merge_commit_title/message settings. Set squash_merge_commit_title=PR_TITLE there, or\n * commits land as the internal \"Squash merge of <branch>\" subject.\n */\n mergeMode: string;\n // This repo's review checklists, straight from the `pr-gate.checklists` ARRAY in webpieces.config.json —\n // the ONLY accepted shape (`patterns` is a path-glob dispatch table and `id` the checklist's name, so both\n // are config). Every def carries {@link reviewer}. [] = no checklists. The removed `{ doc }` manifest\n // form is a hard config error; see validateChecklistsSection.\n checklists: ChecklistDefinition[];\n /**\n * The ONE agent type every checklist is reviewed by — `webpieces-reviewer` unless\n * `overrideReviewerAgent` is true, in which case `reviewerAgentName` — and `reviewerAgents`, the most such\n * subagents a round may use. The same instance is bound into every {@link checklists} entry, so a caller\n * holding only a checklist still knows what to spawn. Field-with-default because the constructor is at\n * max-params; the agent name defaults to the webpieces reviewer, exactly what a config that says nothing\n * gets, while the CAP is a required field, so the placeholder here is only ever overwritten by the real\n * number buildPrGateConfig reads.\n */\n reviewer: ReviewerAgentPolicy = new ReviewerAgentPolicy(DEFAULT_REVIEWER_AGENT_NAME, REVIEWER_AGENTS_PLACEHOLDER);\n /**\n * REQUIRED positive integer: the maximum number of complete global reviewer rounds a PR review state\n * may start. This is deliberately repository policy rather than a machine-local preference.\n */\n maxReviewerRounds!: number;\n // Whether wp-finish-upsert-pr publishes each reviewer's full `output` as ONE combined PR comment\n // (idempotently updated on every push). Defaults to true. Set false to keep the PR body-only.\n checklistComments: boolean;\n /**\n * Shared secret used to mint the server-verifiable gate token. `wp-finish-upsert-pr` writes it after\n * the automated gate passes; `wp-human-post-pr` writes the same token after explicit human attestation\n * and visibly labels review as skipped plus whether its optional local build ran. A CI check\n * recomputes it from the PR head + salt.\n *\n * Optional, defaults to '' — empty means \"no token minted, no CI enforcement\" (byte-identical to\n * before this field existed). This is COMMITTED, obscurity-grade: it stops unhooked teammates who\n * push + open a PR in the web UI, but is readable in-repo and therefore forgeable by a determined\n * reader. It is deliberately NOT cryptographically sound; nothing local can stop a filesystem-reading\n * agent. See RESPONSE-pr-gate-ci-enforcement / the design memo for the full tradeoff.\n */\n gateSalt: string;\n /**\n * What `wp-land-pr` (and `wp-cleanup`, which reaps the same branches) does with the LOCAL branch\n * once its PR is in main. Field-with-default rather than another positional constructor param —\n * this constructor is already at the max-params limit, and every existing `new PrGateConfig(...)`\n * call site correctly wants the default.\n */\n landPr: LandPrConfig = defaultLandPrConfig();\n /**\n * Globs whose diffs are NOT extracted into `.webpieces/pr-review/<feature>/diff/` — regenerated noise a\n * reviewer should not spend context reading (lockfiles, generated graphs). Default [].\n *\n * They are still MATCHED against checklists and still listed in the manifest, with a stub naming the\n * command that gets the real diff. Removing them from the changed-file set would read as \"this file did\n * not change\", which is a different and false claim.\n *\n * Fields-with-defaults rather than constructor params: that constructor is already at max-params, and\n * every existing `new PrGateConfig(...)` correctly wants the defaults.\n */\n reviewDiffExclude: string[] = [];\n /**\n * Repo-specific places a reviewer would otherwise hunt for, as `{label, path}` — e.g.\n * `{\"label\":\"Cloud Tasks queue names\",\"path\":\"terraform/services/\"}`. Resolved to absolute paths in each\n * generated instructions file; a configured-but-missing path is printed as missing, never dropped.\n */\n reviewContext: ReviewContextEntry[] = [];\n /**\n * Installed packages to resolve and hand reviewers by absolute directory. This is the knob aimed at a\n * measured failure: one reviewer burned three separate greps into `node_modules/@webpieces` looking for\n * a scanner the tooling could have pointed at directly.\n */\n reviewContextPackages: string[] = [];\n /**\n * Promote \"this reviewer wrote a verdict without ever opening the diff\" from a warning to a refusal.\n * Default false, and it should stay false until a repo has watched the warning for a while: the signal\n * is derived from undocumented Claude Code transcript internals, so a format change would otherwise\n * wedge every PR in the repo with no self-service way out.\n */\n requireDiffEvidence = false;\n /**\n * Where `wp-push-dev` publishes the disposable copy. Omitted ⇒ `dev-include` / `dev`, which is what\n * makes the whole flow work with NO config edit at all.\n */\n devDeploy: DevDeployConfig = defaultDevDeployConfig();\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n mode: string,\n buildCommand: string,\n gates: GateDefinition[],\n mergeMode: string,\n checklists: ChecklistDefinition[] = [],\n gateSalt = '',\n checklistComments = true,\n ) {\n this.mode = mode;\n this.buildCommand = buildCommand;\n this.gates = gates;\n this.mergeMode = mergeMode;\n this.checklists = checklists;\n this.gateSalt = gateSalt;\n this.checklistComments = checklistComments;\n }\n}\n\n// Default infra gates — path-pattern based, tuned for this monorepo. Clients override the\n// whole list via the `pr-gate.gates` array in webpieces.config.json.\nexport function defaultGates(): GateDefinition[] {\n return [\n new GateDefinition('API Changed', ['libraries/apis/**', '**/*Api.ts'], 'yellow'),\n new GateDefinition(\n 'Config Files Changed',\n ['**/package.json', '**/tsconfig*.json', 'nx.json', '**/*.config.*'],\n 'yellow',\n ),\n new GateDefinition(\n 'Dependency Graph Changed',\n ['architecture/dependencies.json'],\n 'yellow',\n ),\n new GateDefinition(\n 'Claude / Rules Changed',\n ['**/CLAUDE.md', '**/claude.*.md', '.claude/**', 'webpieces.config.json'],\n 'yellow',\n ),\n ];\n}\n\nexport function defaultPrGateConfig(): PrGateConfig {\n // No default checklists — the extension point is opt-in; the default monorepo ships none.\n return new PrGateConfig('ON', '', defaultGates(), MERGE_MODE_AUTO, []);\n}\n\ninterface RawGate {\n name?: string;\n patterns?: string[];\n warningColor?: string;\n disabled?: boolean;\n}\n\ninterface RawPrGateSection {\n mode?: string;\n buildCommand?: string;\n gates?: RawGate[];\n mergeMode?: string;\n // An ARRAY, always. validateChecklistsSection rejects every other shape (including the removed { doc }).\n checklists?: RawChecklistItem[];\n overrideReviewerAgent?: boolean;\n reviewerAgentName?: string;\n reviewerAgents?: number;\n maxReviewerRounds?: number;\n gateSalt?: string;\n checklistComments?: boolean;\n landPr?: RawLandPr;\n reviewDiffExclude?: string[];\n reviewContext?: RawReviewContext[];\n reviewContextPackages?: string[];\n requireDiffEvidence?: boolean;\n devDeploy?: RawDevDeploy;\n}\n\ninterface RawDevDeploy {\n branchNamespace?: string;\n devBranch?: string;\n}\n\ninterface RawLandPr {\n branchRetention?: string;\n}\n\ninterface RawReviewContext {\n label?: string;\n path?: string;\n}\n\nfunction toGate(raw: RawGate): GateDefinition {\n return new GateDefinition(\n raw.name ?? '',\n raw.patterns ?? [],\n raw.warningColor ?? 'yellow',\n raw.disabled ?? false,\n );\n}\n\n/**\n * Build a PrGateConfig from the already-parsed top-level `pr-gate` section, falling back to defaults\n * for any field the consumer omits. Pure transform — the file read + structural validation happen in\n * loadAndValidate (load-config.ts) so every consumer goes through one validated path. Pass undefined\n * (no `pr-gate` key / no config file) to get full defaults.\n */\n// webpieces-disable no-any-unknown -- `section` is opaque consumer JSON until narrowed here\nexport function buildPrGateConfig(section: unknown): PrGateConfig {\n const defaults = defaultPrGateConfig();\n if (section === undefined || section === null || typeof section !== 'object') return defaults;\n\n const raw = section as RawPrGateSection;\n const mode = raw.mode ?? defaults.mode;\n const buildCommand = raw.buildCommand ?? defaults.buildCommand;\n const gates = raw.gates !== undefined ? raw.gates.map(toGate) : defaults.gates;\n // REQUIRED — validatePrGateSection rejects an omitted/unknown value, so this fallback only ever\n // applies to the no-config-file path that defaultPrGateConfig() serves.\n const mergeMode = raw.mergeMode ?? defaults.mergeMode;\n // Optional extension point — omitted ⇒ [] ⇒ no checklists computed anywhere downstream. A non-array here\n // cannot reach us: validateChecklistsSection has already failed the load.\n // The webpieces reviewer unless `overrideReviewerAgent` is true, in which case `reviewerAgentName` names the\n // agent (validatePrGateSection rejects a name without the override, and the override without a name).\n // Required nonnegative integer: 0 disables reviewer-agent reviews; positive values cap the round.\n const agentName =\n raw.overrideReviewerAgent === true\n ? (raw.reviewerAgentName ?? '').trim()\n : DEFAULT_REVIEWER_AGENT_NAME;\n // `reviewerAgents` is REQUIRED and validated as a nonnegative integer before this runs, so the fallback is\n // unreachable in a loaded config and exists only to keep this total for a structure-only caller.\n const reviewer = new ReviewerAgentPolicy(\n agentName,\n typeof raw.reviewerAgents === 'number' ? raw.reviewerAgents : REVIEWER_AGENTS_PLACEHOLDER,\n );\n const checklists = Array.isArray(raw.checklists)\n ? raw.checklists.map(\n (item: RawChecklistItem): ChecklistDefinition => toChecklist(item, reviewer),\n )\n : defaults.checklists;\n // Optional — omitted ⇒ '' ⇒ no gate token minted and CI enforcement is a no-op (back-compat).\n const gateSalt = raw.gateSalt ?? defaults.gateSalt;\n // Optional — omitted ⇒ true ⇒ reviewer output published as a PR comment.\n const checklistComments = raw.checklistComments ?? defaults.checklistComments;\n const built = new PrGateConfig(\n mode,\n buildCommand,\n gates,\n mergeMode,\n checklists,\n gateSalt,\n checklistComments,\n );\n built.landPr = buildLandPrConfig(raw.landPr);\n built.reviewer = reviewer;\n built.maxReviewerRounds = raw.maxReviewerRounds as number;\n // Review-context knobs. All optional and all defaulted, so a config that omits every one of them (which\n // is every consumer's config today) behaves exactly as it did before they existed.\n built.reviewDiffExclude = Array.isArray(raw.reviewDiffExclude)\n ? raw.reviewDiffExclude\n : defaults.reviewDiffExclude;\n built.reviewContextPackages = Array.isArray(raw.reviewContextPackages)\n ? raw.reviewContextPackages\n : defaults.reviewContextPackages;\n built.reviewContext = Array.isArray(raw.reviewContext)\n ? raw.reviewContext.map(\n (e: RawReviewContext): ReviewContextEntry =>\n new ReviewContextEntry(e.label ?? '', e.path ?? ''),\n )\n : defaults.reviewContext;\n built.requireDiffEvidence = raw.requireDiffEvidence ?? defaults.requireDiffEvidence;\n built.devDeploy = buildDevDeployConfig(raw.devDeploy);\n return built;\n}\n\n/**\n * Build the `pr-gate.devDeploy` block. Omitted (the state of every consumer config today) ⇒ the\n * `dev-include` / `dev` defaults. An invalid value cannot reach here — validateDevDeploySection has\n * already failed the load.\n */\n// webpieces-disable no-function-outside-class -- module-level config transform, matches buildPrGateConfig above\nexport function buildDevDeployConfig(raw: RawDevDeploy | undefined): DevDeployConfig {\n const defaults = defaultDevDeployConfig();\n if (raw === undefined || raw === null || typeof raw !== 'object') return defaults;\n const namespace =\n typeof raw.branchNamespace === 'string' && raw.branchNamespace.trim() !== ''\n ? raw.branchNamespace.trim()\n : defaults.branchNamespace;\n const devBranch =\n typeof raw.devBranch === 'string' && raw.devBranch.trim() !== ''\n ? raw.devBranch.trim()\n : defaults.devBranch;\n return new DevDeployConfig(namespace, devBranch);\n}\n\n/**\n * Build the `pr-gate.landPr` block. Omitted (the current state of every consumer's config) ⇒ the\n * 'archive-tag' default, which is what makes this feature work with NO config edit at all. An invalid\n * value cannot reach here — validatePrGateSection has already failed the load.\n */\n// webpieces-disable no-function-outside-class -- module-level config transform, matches buildPrGateConfig above\nexport function buildLandPrConfig(raw: RawLandPr | undefined): LandPrConfig {\n const defaults = defaultLandPrConfig();\n if (raw === undefined || raw === null || typeof raw !== 'object') return defaults;\n const retention = raw.branchRetention;\n if (typeof retention !== 'string' || !BRANCH_RETENTIONS.includes(retention)) return defaults;\n return new LandPrConfig(retention);\n}\n"]}
|
|
@@ -6,7 +6,7 @@ exports.validateChecklistsSection = validateChecklistsSection;
|
|
|
6
6
|
exports.validateReviewerAgentKeys = validateReviewerAgentKeys;
|
|
7
7
|
exports.validateLandPrSection = validateLandPrSection;
|
|
8
8
|
exports.validateDevDeploySection = validateDevDeploySection;
|
|
9
|
-
const
|
|
9
|
+
const repo_workflow_core_1 = require("@webpieces/repo-workflow-core");
|
|
10
10
|
const checklist_validator_1 = require("./checklist-validator");
|
|
11
11
|
const checklist_config_1 = require("./checklist-config");
|
|
12
12
|
const constants_1 = require("./constants");
|
|
@@ -296,23 +296,23 @@ function reviewerAgentsErrors(s) {
|
|
|
296
296
|
// webpieces-disable no-function-outside-class -- module-level config validator, matches the rest of this file
|
|
297
297
|
function validateLandPrSection(value) {
|
|
298
298
|
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
299
|
-
return [`[pr-gate] "landPr" must be an object, e.g. { "branchRetention": "${
|
|
299
|
+
return [`[pr-gate] "landPr" must be an object, e.g. { "branchRetention": "${repo_workflow_core_1.BRANCH_RETENTION_ARCHIVE_TAG}" }.`];
|
|
300
300
|
}
|
|
301
301
|
// webpieces-disable no-any-unknown -- narrowing the opaque landPr object from consumer JSON
|
|
302
302
|
const s = value;
|
|
303
303
|
if (!('branchRetention' in s))
|
|
304
304
|
return [];
|
|
305
305
|
const retention = s['branchRetention'];
|
|
306
|
-
if (typeof retention === 'string' &&
|
|
306
|
+
if (typeof retention === 'string' && repo_workflow_core_1.BRANCH_RETENTIONS.includes(retention))
|
|
307
307
|
return [];
|
|
308
308
|
return [
|
|
309
309
|
`[pr-gate] "landPr.branchRetention" = "${String(retention)}" is not valid. ` +
|
|
310
|
-
`Must be one of: ${
|
|
311
|
-
` "${
|
|
310
|
+
`Must be one of: ${repo_workflow_core_1.BRANCH_RETENTIONS.join(', ')}.\n` +
|
|
311
|
+
` "${repo_workflow_core_1.BRANCH_RETENTION_ARCHIVE_TAG}" — (default) tag the branch tip as archive/<date>/<branch>, THEN delete it. The\n` +
|
|
312
312
|
` history stays byte-identical and restorable, but the branch stops counting\n` +
|
|
313
313
|
` toward the branch cap and cannot be committed onto by accident.\n` +
|
|
314
|
-
` "${
|
|
315
|
-
` "${
|
|
314
|
+
` "${repo_workflow_core_1.BRANCH_RETENTION_DELETE}" — delete outright; recoverable only from the reflog, which expires.\n` +
|
|
315
|
+
` "${repo_workflow_core_1.BRANCH_RETENTION_KEEP}" — do not delete. Branches then accumulate until branch-creation-guard trips.`,
|
|
316
316
|
];
|
|
317
317
|
}
|
|
318
318
|
// A git ref COMPONENT this flow is willing to build a ref name out of. Deliberately much narrower than
|