@webpieces/rules-config 0.4.819 → 0.4.821

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.
@@ -1 +1 @@
1
- {"version":3,"file":"skip-rule.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/skip-rule.ts"],"names":[],"mappings":";;;AA2DA,4CAeC;AA2HD,wCA0CC;;AA/OD,iDAAyC;AACzC,+CAAyB;AAEzB,uDAAkD;AAClD,uDAAkD;AAClD,6CAAsC;AACtC,yCAAqC;AAErC,kFAAkF;AAClF,8EAA8E;AAC9E,uEAAuE;AACvE,sDAAsD;AAEtD;;;;;;;;;;;GAWG;AACH,MAAa,cAAc;IACvB,IAAI,CAAU;IACd,kEAAkE;IAClE,MAAM,CAAS;IACf,uFAAuF;IACvF,eAAe,CAAS;IAExB,YAAY,IAAa,EAAE,SAAiB,EAAE,EAAE,kBAA0B,EAAE;QACxE,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,eAAe,GAAG,eAAe,CAAC;IAC3C,CAAC;CACJ;AAZD,wCAYC;AAED,4FAA4F;AAC5F,gGAAgG;AAChG,oGAAoG;AACpG,2EAA2E;AAC3E,EAAE;AACF,qGAAqG;AACrG,qGAAqG;AACrG,qGAAqG;AACrG,+CAA+C;AAC/C,oGAAoG;AACpG,mGAAmG;AACnG,4FAA4F;AAC5F,4FAA4F;AAC5F,kFAAkF;AAClF,EAAE;AACF,qGAAqG;AACrG,qFAAqF;AACrF,oGAAoG;AACpG,kGAAkG;AAClG,uEAAuE;AACvE,SAAgB,gBAAgB;IAC5B,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC;IAChD,IAAI,QAAQ;QAAE,OAAO,QAAQ,CAAC;IAE9B,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC;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InformAiError } from './inform-ai-error';\nimport { RuleFailError } from './rule-fail-error';\nimport { Option } from './fix-option';\nimport { toError } from './to-error';\n\n// Universal \"should this rule be skipped right now?\" logic, shared by code-rules,\n// ai-hook-rules and the Nx executors so every rule honors the same two escape\n// hatches: turnOffRuleWhileOnBranch (skip while on a named branch) and\n// turnOffRuleUntilEpoch (skip until an epoch passes).\n\n/**\n * The skip decision. A CLASS, not an interface (CLAUDE.md rule 1), because it carries a THIRD fact\n * beyond yes/no that a caller has to be able to read rather than read about in a log line.\n *\n * `hatchNotApplied` is that fact: a branch hatch WAS configured, and it could NOT apply — today only\n * because HEAD is detached (a tag checkout, a `git bisect` step, a CI checkout of a merge ref). The rule\n * is ENFORCED in that case, so there is nothing to report unless the rule then FAILS; when it does, its\n * own RuleFailError is where this belongs, as context on why the hatch the config shows did not save it.\n *\n * It is deliberately NOT printed here. Everything in this framework throws to ONE place that renders per\n * audience; a console write from a library function cannot be caught, re-rendered or asserted on.\n */\nexport class SkipRuleResult {\n skip: boolean;\n /** Why the rule IS being skipped. '' whenever `skip` is false. */\n reason: string;\n /** Why a CONFIGURED branch hatch did not apply, or '' when there is nothing to say. */\n hatchNotApplied: string;\n\n constructor(skip: boolean, reason: string = '', hatchNotApplied: string = '') {\n this.skip = skip;\n this.reason = reason;\n this.hatchNotApplied = hatchNotApplied;\n }\n}\n\n// The actual checked-out branch. The grab bag of ambient env vars (BRANCH_NAME, GIT_BRANCH,\n// CI_COMMIT_BRANCH, …) was intentionally REMOVED and must stay removed: a stray GIT_BRANCH=main\n// locally made this return \"main\" on a feature branch, which (a) mislabeled the main-sync cache and\n// (b) silently disabled merged-PR detection (detectMergedPr skips \"main\").\n//\n// The two vars below are NOT that. They are consulted BEFORE git because git cannot answer at all in\n// the case they cover — a `pull_request` checkout leaves HEAD detached on refs/pull/<N>/merge, where\n// `git rev-parse --abbrev-ref HEAD` returns the literal string \"HEAD\" and no branch hatch can match.\n// Neither can go stale the way GIT_BRANCH did:\n// GITHUB_HEAD_REF — set by the GitHub runner ONLY on pull_request/pull_request_target, and it IS\n// the source branch name. Absent on push, so the fallthrough stays safe. (Not\n// GITHUB_REF_NAME: on pull_request that is \"<N>/merge\", not a branch.)\n// WEBPIECES_BRANCH — one documented opt-in override for CI systems not special-cased here\n// (GitLab, CircleCI, Buildkite). Nobody sets it by accident.\n//\n// This getter answers \"what branch am I on?\" and NOTHING about whether that answer may be TRUSTED to\n// unlock an escape hatch. That second question is asked by shouldSkipRule alone (see\n// assertBranchIsTrustworthy) because this getter has callers — the main-sync cache label, merged-PR\n// detection, code-rules' re-export of it — for which a fork's own branch name is a perfectly good\n// answer, and making the getter itself throw would redden all of them.\nexport function getCurrentBranch(): string {\n const prBranch = process.env['GITHUB_HEAD_REF'];\n if (prBranch) return prBranch;\n\n const override = process.env['WEBPIECES_BRANCH'];\n if (override) return override;\n\n // webpieces-disable no-unmanaged-exceptions -- rethrow as InformAiError so global catch surfaces readable message to AI\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- rethrow as InformAiError so global catch surfaces readable message to AI\n try {\n return execSync('git rev-parse --abbrev-ref HEAD', { encoding: 'utf8' }).trim();\n } catch (err: unknown) {\n const error = toError(err);\n throw new InformAiError(`Failed to determine current git branch: ${error.message}`, { cause: error });\n }\n}\n\n// The slice of the GitHub `pull_request` event payload that says WHO OWNS the head branch. Only the\n// one field below is read; everything else in that file is ignored.\ninterface RawPullRequestEvent {\n pull_request?: {\n head?: {\n repo?: {\n full_name?: string;\n };\n };\n };\n}\n\n/**\n * Refuse the branch hatch on a pull request whose head branch this repo does not own.\n *\n * The hole it closes: hatch names live in `webpieces.config.json`, which is COMMITTED and public. On a\n * `pull_request` from a FORK the runner sets GITHUB_HEAD_REF to the FORK AUTHOR's branch name, so an\n * outside contributor who names their branch after one of your hatches silently disables that rule on\n * their PR — the one place you least want a rule off.\n *\n * It is answered with no network and no token, from `$GITHUB_EVENT_PATH` — a JSON file the runner writes\n * before the job starts:\n * - `pull_request_target` runs with the BASE repo's secrets against contributor-authored code, so it is\n * untrusted unconditionally; there is nothing to compare.\n * - `pull_request` is trusted only when the head repo's `full_name` EQUALS `GITHUB_REPOSITORY`.\n *\n * \"Cannot tell\" counts as untrusted — a `pull_request` run with no readable event file cannot make the\n * comparison, and a hatch that cannot be proven to be yours must not fire.\n *\n * This is the ONE hard failure left in this module, and it is not the \"no branch here\" case (see\n * shouldSkipRule, which enforces quietly when HEAD is detached). It is a hatch name that DOES resolve but\n * is attacker-chosen — a security property, not a checkout that happens not to be editing.\n *\n * Called ONLY from inside `if (branchName)`. With turnOffRuleWhileOnBranch null — the overwhelmingly\n * common value — nothing here runs and no fork PR is affected in any way.\n */\n// webpieces-disable no-function-outside-class -- module-scope helper of the module-scope shouldSkipRule it serves; this whole module is functional by design (imported as free functions by code-rules, ai-hook-rules and the nx executors)\nfunction assertBranchIsTrustworthy(branchName: string): void {\n const eventName = process.env['GITHUB_EVENT_NAME'];\n if (eventName !== 'pull_request' && eventName !== 'pull_request_target') return;\n if (eventName === 'pull_request_target') throw forkRefusal(branchName, 'pull_request_target run');\n\n const headRepo = readHeadRepoFullName(branchName);\n const thisRepo = process.env['GITHUB_REPOSITORY'] ?? '';\n if (headRepo !== null && thisRepo !== '' && headRepo === thisRepo) return;\n throw forkRefusal(branchName, headRepo === null\n ? 'pull_request run with no readable $GITHUB_EVENT_PATH, so the head branch cannot be proven to belong to this repo'\n : `pull_request run whose head branch lives in \"${headRepo}\", not in \"${thisRepo}\"`);\n}\n\n/**\n * The head repo's `owner/name` from the runner's event file, or null when there is no such file.\n *\n * A file that exists but cannot be parsed is a different thing from one that is absent, and it throws:\n * it means the runner wrote something this code does not understand, and silently downgrading that to\n * \"untrusted\" would hide a real incompatibility behind a message about forks.\n */\n// webpieces-disable no-function-outside-class -- module-scope helper, see assertBranchIsTrustworthy\nfunction readHeadRepoFullName(branchName: string): string | null {\n const eventPath = process.env['GITHUB_EVENT_PATH'];\n if (!eventPath || !fs.existsSync(eventPath)) return null;\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: a raw SyntaxError from the runner's event file would say nothing about hatches; this names the hatch, the file and the rule that stayed ON\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- see above\n try {\n const parsed = JSON.parse(fs.readFileSync(eventPath, 'utf8')) as RawPullRequestEvent;\n return parsed.pull_request?.head?.repo?.full_name ?? null;\n } catch (err: unknown) {\n const error = toError(err);\n throw new RuleFailError(\n 'turnOffRuleWhileOnBranch',\n `turnOffRuleWhileOnBranch: \"${branchName}\" is configured and this is a pull_request run, so the ` +\n `head repository must be checked before the hatch may fire — but the runner's event file ` +\n `${eventPath} could not be read: ${error.message}`,\n undefined,\n undefined,\n [new Option('Use turnOffRuleUntilEpoch instead — it is TIME based and needs no event file.', true),\n new Option('Or clear turnOffRuleWhileOnBranch (set it to null) so no trust check is needed at all.')],\n undefined,\n error);\n }\n}\n\n/**\n * The fork refusal, as a `RuleFailError`.\n *\n * The cures are `fixOptions` — a LIST of `Option` — because the framework owns how they are labelled\n * and numbered (`formatFixOptions` renders \"Fix Option N:\" and the \"(preferred)\" tag for BOTH engines).\n * A hand-numbered \"WORKAROUNDS: 1. … 2. …\" string literal, which is what this used to be, is exactly\n * the shape `Option` exists to prevent. `Option` lives HERE in `rules-config`, so the same class serves\n * this build-time throw and `FixHint` in `ai-hook-rules` — one cure shape, one definition.\n *\n * `ruleName` is the HATCH, not the rule being evaluated: `shouldSkipRule` is handed only the two hatch\n * values and does not know whose rule it is deciding for — and the thing that failed genuinely is the\n * hatch, which cannot be honored here.\n */\n// webpieces-disable no-function-outside-class -- module-scope helper, see assertBranchIsTrustworthy\nfunction forkRefusal(branchName: string, what: string): RuleFailError {\n return new RuleFailError(\n 'turnOffRuleWhileOnBranch',\n `turnOffRuleWhileOnBranch: \"${branchName}\" is configured, but this is a ${what}. The branch name ` +\n `there is chosen by the PULL REQUEST AUTHOR, and hatch names are public (webpieces.config.json ` +\n `is committed), so honoring the hatch would let anyone turn this rule off on their own PR just ` +\n `by naming their branch after it. The rule is NOT skipped, and this fails loudly rather than ` +\n `quietly enforcing a rule the config says is off.`,\n undefined,\n undefined,\n [\n new Option(\n 'If the rule must be off for outside contributions too, use turnOffRuleUntilEpoch — it is TIME ' +\n 'based, so it cannot be self-granted by naming a branch. Keep the date short: it is repo-wide ' +\n 'while it lasts, so it also shelters unrelated work landing in the same window.',\n true,\n ),\n new Option(\n 'Otherwise clear turnOffRuleWhileOnBranch (set it to null) and fix the findings on the ' +\n 'contributed branch like any other.',\n ),\n ],\n );\n}\n\nexport function shouldSkipRule(\n epoch: number | undefined,\n // The branch hatch is an EXACT branch name — compared with `===`, never a glob, regex or prefix.\n // That is deliberate and is not to be \"improved\": the hatch turns a rule OFF, and a pattern lets one\n // config line switch rules off on branches nobody enumerated when it was written. If two branches\n // need the same rule off, that is two branches renamed to one hatch name, not one wildcard.\n //\n // null (the \"no branch / always on\" value of turnOffRuleWhileOnBranch) is treated exactly like\n // undefined — no branch scoping. Only a non-empty branch name activates the branch hatch.\n branchName: string | undefined | null\n): SkipRuleResult {\n if (branchName) {\n // The fork gate fires ONLY inside `if (branchName)`. With turnOffRuleWhileOnBranch=null — the\n // overwhelmingly common value — nothing below runs, so an outside contribution to a repo that\n // configured no hatch is an ordinary run.\n //\n // A DETACHED HEAD is NOT an error here. The branch hatch exists to relax a rule while you EDIT on\n // a branch; a tag checkout or a `git bisect` step is not editing (you cannot commit to a tag, and\n // to edit you branch off it first). So when no branch can be resolved the hatch simply does not\n // apply and THE RULE IS ENFORCED — whoever hits a violation then gets that rule's own message and\n // cure, which is the useful output. WHY the hatch did not fire rides back on the result\n // (SkipRuleResult.hatchNotApplied) rather than being printed, so a caller that does fail can fold\n // it into its own error instead of a library writing to a console nobody can catch.\n assertBranchIsTrustworthy(branchName);\n const current = getCurrentBranch();\n if (current === 'HEAD' || current === '') {\n return new SkipRuleResult(false, '',\n `turnOffRuleWhileOnBranch: \"${branchName}\" did not apply — HEAD is detached, so there is no ` +\n `branch to match (a tag checkout, a git bisect step, or a CI checkout of a merge ref).`);\n }\n if (current === branchName) {\n return new SkipRuleResult(true, `on branch \"${branchName}\"`);\n }\n }\n if (epoch !== undefined) {\n const nowSeconds = Date.now() / 1000;\n if (nowSeconds < epoch) {\n const expiresDate = new Date(epoch * 1000).toISOString().split('T')[0];\n return new SkipRuleResult(true, `turnOffRuleUntilEpoch active, expires: ${expiresDate}`);\n }\n }\n return new SkipRuleResult(false);\n}\n"]}
1
+ {"version":3,"file":"skip-rule.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/skip-rule.ts"],"names":[],"mappings":";;;AA2MA,wCAwCC;;AAnPD,iDAAyC;AACzC,+CAAyB;AACzB,yCAA2D;AAE3D,uDAAkD;AAClD,uDAAkD;AAClD,6CAAsC;AACtC,yCAAqC;AAErC,kFAAkF;AAClF,8EAA8E;AAC9E,uEAAuE;AACvE,sDAAsD;AAEtD;;;;;;;;;;;GAWG;AACH,MAAa,cAAc;IACvB,IAAI,CAAU;IACd,kEAAkE;IAClE,MAAM,CAAS;IACf,uFAAuF;IACvF,eAAe,CAAS;IAExB,YAAY,IAAa,EAAE,SAAiB,EAAE,EAAE,kBAA0B,EAAE;QACxE,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,eAAe,GAAG,eAAe,CAAC;IAC3C,CAAC;CACJ;AAZD,wCAYC;AAED,4FAA4F;AAC5F,gGAAgG;AAChG,oGAAoG;AACpG,2EAA2E;AAC3E,EAAE;AACF,qGAAqG;AACrG,qGAAqG;AACrG,qGAAqG;AACrG,+CAA+C;AAC/C,oGAAoG;AACpG,mGAAmG;AACnG,4FAA4F;AAC5F,4FAA4F;AAC5F,kFAAkF;AAClF,EAAE;AACF,qGAAqG;AACrG,qFAAqF;AACrF,oGAAoG;AACpG,kGAAkG;AAClG,uEAAuE;AAC1D,QAAA,qBAAqB,GAAG,UAAU,CAAC;AACnC,QAAA,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,IAAI,OAAO,KAAK,UAAU,EAAE,CAAC;YACzB,OAAO,IAAI,cAAc,CAAC,IAAI,EAAE,cAAc,UAAU,GAAG,CAAC,CAAC;QACjE,CAAC;IACL,CAAC;IACD,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;QACtB,MAAM,UAAU,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC;QACrC,IAAI,UAAU,GAAG,KAAK,EAAE,CAAC;YACrB,MAAM,WAAW,GAAG,IAAI,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;YACvE,OAAO,IAAI,cAAc,CAAC,IAAI,EAAE,0CAA0C,WAAW,EAAE,CAAC,CAAC;QAC7F,CAAC;IACL,CAAC;IACD,OAAO,IAAI,cAAc,CAAC,KAAK,CAAC,CAAC;AACrC,CAAC","sourcesContent":["import { execSync } from 'child_process';\nimport * as fs from 'fs';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { InformAiError } from './inform-ai-error';\nimport { RuleFailError } from './rule-fail-error';\nimport { Option } from './fix-option';\nimport { toError } from './to-error';\n\n// Universal \"should this rule be skipped right now?\" logic, shared by code-rules,\n// ai-hook-rules and the Nx executors so every rule honors the same two escape\n// hatches: turnOffRuleWhileOnBranch (skip while on a named branch) and\n// turnOffRuleUntilEpoch (skip until an epoch passes).\n\n/**\n * The skip decision. A CLASS, not an interface (CLAUDE.md rule 1), because it carries a THIRD fact\n * beyond yes/no that a caller has to be able to read rather than read about in a log line.\n *\n * `hatchNotApplied` is that fact: a branch hatch WAS configured, and it could NOT apply — today only\n * because HEAD is detached (a tag checkout, a `git bisect` step, a CI checkout of a merge ref). The rule\n * is ENFORCED in that case, so there is nothing to report unless the rule then FAILS; when it does, its\n * own RuleFailError is where this belongs, as context on why the hatch the config shows did not save it.\n *\n * It is deliberately NOT printed here. Everything in this framework throws to ONE place that renders per\n * audience; a console write from a library function cannot be caught, re-rendered or asserted on.\n */\nexport class SkipRuleResult {\n skip: boolean;\n /** Why the rule IS being skipped. '' whenever `skip` is false. */\n reason: string;\n /** Why a CONFIGURED branch hatch did not apply, or '' when there is nothing to say. */\n hatchNotApplied: string;\n\n constructor(skip: boolean, reason: string = '', hatchNotApplied: string = '') {\n this.skip = skip;\n this.reason = reason;\n this.hatchNotApplied = hatchNotApplied;\n }\n}\n\n// The actual checked-out branch. The grab bag of ambient env vars (BRANCH_NAME, GIT_BRANCH,\n// CI_COMMIT_BRANCH, …) was intentionally REMOVED and must stay removed: a stray GIT_BRANCH=main\n// locally made this return \"main\" on a feature branch, which (a) mislabeled the main-sync cache and\n// (b) silently disabled merged-PR detection (detectMergedPr skips \"main\").\n//\n// The two vars below are NOT that. They are consulted BEFORE git because git cannot answer at all in\n// the case they cover — a `pull_request` checkout leaves HEAD detached on refs/pull/<N>/merge, where\n// `git rev-parse --abbrev-ref HEAD` returns the literal string \"HEAD\" and no branch hatch can match.\n// Neither can go stale the way GIT_BRANCH did:\n// GITHUB_HEAD_REF — set by the GitHub runner ONLY on pull_request/pull_request_target, and it IS\n// the source branch name. Absent on push, so the fallthrough stays safe. (Not\n// GITHUB_REF_NAME: on pull_request that is \"<N>/merge\", not a branch.)\n// WEBPIECES_BRANCH — one documented opt-in override for CI systems not special-cased here\n// (GitLab, CircleCI, Buildkite). Nobody sets it by accident.\n//\n// This getter answers \"what branch am I on?\" and NOTHING about whether that answer may be TRUSTED to\n// unlock an escape hatch. That second question is asked by shouldSkipRule alone (see\n// assertBranchIsTrustworthy) because this getter has callers — the main-sync cache label, merged-PR\n// detection, code-rules' re-export of it — for which a fork's own branch name is a perfectly good\n// answer, and making the getter itself throw would redden all of them.\nexport const HOTFIX_BRANCH_SEGMENT = '/hotfix/';\nexport const HOTFIX_BUILD_COMMAND = 'pnpm nx affected --target=hotfix-ci --base=$(git merge-base origin/main HEAD)';\nexport const HOTFIX_AUDIT_BANNER = '# ⚠️ HOT FIX ⚠️\\n\\n' + 'This emergency PR bypassed required reviews, ticket enforcement, Webpieces rules, ESLint, and ' + 'Prettier/format checks. Compilation and tests ran.';\n\n/** One exact, case-sensitive hotfix convention shared by every Webpieces surface. */\n@injectable(bindingScopeValues.Singleton)\nexport class BranchIdentity {\n current(): string {\n const prBranch = process.env['GITHUB_HEAD_REF'];\n if (prBranch) return prBranch;\n\n const override = process.env['WEBPIECES_BRANCH'];\n if (override) return override;\n\n // webpieces-disable no-unmanaged-exceptions -- rethrow as InformAiError so global catch surfaces readable message to AI\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- rethrow as InformAiError so global catch surfaces readable message to AI\n try {\n return execSync('git rev-parse --abbrev-ref HEAD', { encoding: 'utf8' }).trim();\n } catch (err: unknown) {\n const error = toError(err);\n throw new InformAiError(`Failed to determine current git branch: ${error.message}`, { cause: error });\n }\n }\n\n isHotfix(branchName: string = this.current()): boolean {\n return branchName.includes(HOTFIX_BRANCH_SEGMENT);\n }\n}\n\nconst branchIdentity = new BranchIdentity();\n\n// The slice of the GitHub `pull_request` event payload that says WHO OWNS the head branch. Only the\n// one field below is read; everything else in that file is ignored.\ninterface RawPullRequestEvent {\n pull_request?: {\n head?: {\n repo?: {\n full_name?: string;\n };\n };\n };\n}\n\n/**\n * Refuse the branch hatch on a pull request whose head branch this repo does not own.\n *\n * The hole it closes: hatch names live in `webpieces.config.json`, which is COMMITTED and public. On a\n * `pull_request` from a FORK the runner sets GITHUB_HEAD_REF to the FORK AUTHOR's branch name, so an\n * outside contributor who names their branch after one of your hatches silently disables that rule on\n * their PR — the one place you least want a rule off.\n *\n * It is answered with no network and no token, from `$GITHUB_EVENT_PATH` — a JSON file the runner writes\n * before the job starts:\n * - `pull_request_target` runs with the BASE repo's secrets against contributor-authored code, so it is\n * untrusted unconditionally; there is nothing to compare.\n * - `pull_request` is trusted only when the head repo's `full_name` EQUALS `GITHUB_REPOSITORY`.\n *\n * \"Cannot tell\" counts as untrusted — a `pull_request` run with no readable event file cannot make the\n * comparison, and a hatch that cannot be proven to be yours must not fire.\n *\n * This is the ONE hard failure left in this module, and it is not the \"no branch here\" case (see\n * shouldSkipRule, which enforces quietly when HEAD is detached). It is a hatch name that DOES resolve but\n * is attacker-chosen — a security property, not a checkout that happens not to be editing.\n *\n * Called ONLY from inside `if (branchName)`. With turnOffRuleWhileOnBranch null — the overwhelmingly\n * common value — nothing here runs and no fork PR is affected in any way.\n */\n// webpieces-disable no-function-outside-class -- module-scope helper of the module-scope shouldSkipRule it serves; this whole module is functional by design (imported as free functions by code-rules, ai-hook-rules and the nx executors)\nfunction assertBranchIsTrustworthy(branchName: string): void {\n const eventName = process.env['GITHUB_EVENT_NAME'];\n if (eventName !== 'pull_request' && eventName !== 'pull_request_target') return;\n if (eventName === 'pull_request_target') throw forkRefusal(branchName, 'pull_request_target run');\n\n const headRepo = readHeadRepoFullName(branchName);\n const thisRepo = process.env['GITHUB_REPOSITORY'] ?? '';\n if (headRepo !== null && thisRepo !== '' && headRepo === thisRepo) return;\n throw forkRefusal(branchName, headRepo === null ? 'pull_request run with no readable $GITHUB_EVENT_PATH, so the head branch cannot be proven to belong to this repo' : `pull_request run whose head branch lives in \"${headRepo}\", not in \"${thisRepo}\"`);\n}\n\n/**\n * The head repo's `owner/name` from the runner's event file, or null when there is no such file.\n *\n * A file that exists but cannot be parsed is a different thing from one that is absent, and it throws:\n * it means the runner wrote something this code does not understand, and silently downgrading that to\n * \"untrusted\" would hide a real incompatibility behind a message about forks.\n */\n// webpieces-disable no-function-outside-class -- module-scope helper, see assertBranchIsTrustworthy\nfunction readHeadRepoFullName(branchName: string): string | null {\n const eventPath = process.env['GITHUB_EVENT_PATH'];\n if (!eventPath || !fs.existsSync(eventPath)) return null;\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: a raw SyntaxError from the runner's event file would say nothing about hatches; this names the hatch, the file and the rule that stayed ON\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- see above\n try {\n const parsed = JSON.parse(fs.readFileSync(eventPath, 'utf8')) as RawPullRequestEvent;\n return parsed.pull_request?.head?.repo?.full_name ?? null;\n } catch (err: unknown) {\n const error = toError(err);\n throw new RuleFailError(\n 'turnOffRuleWhileOnBranch',\n `turnOffRuleWhileOnBranch: \"${branchName}\" is configured and this is a pull_request run, so the ` + `head repository must be checked before the hatch may fire — but the runner's event file ` + `${eventPath} could not be read: ${error.message}`,\n undefined,\n undefined,\n [new Option('Use turnOffRuleUntilEpoch instead — it is TIME based and needs no event file.', true), new Option('Or clear turnOffRuleWhileOnBranch (set it to null) so no trust check is needed at all.')],\n undefined,\n error,\n );\n }\n}\n\n/**\n * The fork refusal, as a `RuleFailError`.\n *\n * The cures are `fixOptions` — a LIST of `Option` — because the framework owns how they are labelled\n * and numbered (`formatFixOptions` renders \"Fix Option N:\" and the \"(preferred)\" tag for BOTH engines).\n * A hand-numbered \"WORKAROUNDS: 1. … 2. …\" string literal, which is what this used to be, is exactly\n * the shape `Option` exists to prevent. `Option` lives HERE in `rules-config`, so the same class serves\n * this build-time throw and `FixHint` in `ai-hook-rules` — one cure shape, one definition.\n *\n * `ruleName` is the HATCH, not the rule being evaluated: `shouldSkipRule` is handed only the two hatch\n * values and does not know whose rule it is deciding for — and the thing that failed genuinely is the\n * hatch, which cannot be honored here.\n */\n// webpieces-disable no-function-outside-class -- module-scope helper, see assertBranchIsTrustworthy\nfunction forkRefusal(branchName: string, what: string): RuleFailError {\n return new RuleFailError(\n 'turnOffRuleWhileOnBranch',\n `turnOffRuleWhileOnBranch: \"${branchName}\" is configured, but this is a ${what}. The branch name ` +\n `there is chosen by the PULL REQUEST AUTHOR, and hatch names are public (webpieces.config.json ` +\n `is committed), so honoring the hatch would let anyone turn this rule off on their own PR just ` +\n `by naming their branch after it. The rule is NOT skipped, and this fails loudly rather than ` +\n `quietly enforcing a rule the config says is off.`,\n undefined,\n undefined,\n [\n new Option(\n 'If the rule must be off for outside contributions too, use turnOffRuleUntilEpoch — it is TIME ' + 'based, so it cannot be self-granted by naming a branch. Keep the date short: it is repo-wide ' + 'while it lasts, so it also shelters unrelated work landing in the same window.',\n true,\n ),\n new Option('Otherwise clear turnOffRuleWhileOnBranch (set it to null) and fix the findings on the ' + 'contributed branch like any other.'),\n ],\n );\n}\n\nexport function shouldSkipRule(\n epoch: number | undefined,\n // The branch hatch is an EXACT branch name — compared with `===`, never a glob, regex or prefix.\n // That is deliberate and is not to be \"improved\": the hatch turns a rule OFF, and a pattern lets one\n // config line switch rules off on branches nobody enumerated when it was written. If two branches\n // need the same rule off, that is two branches renamed to one hatch name, not one wildcard.\n //\n // null (the \"no branch / always on\" value of turnOffRuleWhileOnBranch) is treated exactly like\n // undefined — no branch scoping. Only a non-empty branch name activates the branch hatch.\n branchName: string | undefined | null,\n): SkipRuleResult {\n if (branchName) {\n // The fork gate fires ONLY inside `if (branchName)`. With turnOffRuleWhileOnBranch=null — the\n // overwhelmingly common value — nothing below runs, so an outside contribution to a repo that\n // configured no hatch is an ordinary run.\n //\n // A DETACHED HEAD is NOT an error here. The branch hatch exists to relax a rule while you EDIT on\n // a branch; a tag checkout or a `git bisect` step is not editing (you cannot commit to a tag, and\n // to edit you branch off it first). So when no branch can be resolved the hatch simply does not\n // apply and THE RULE IS ENFORCED — whoever hits a violation then gets that rule's own message and\n // cure, which is the useful output. WHY the hatch did not fire rides back on the result\n // (SkipRuleResult.hatchNotApplied) rather than being printed, so a caller that does fail can fold\n // it into its own error instead of a library writing to a console nobody can catch.\n assertBranchIsTrustworthy(branchName);\n const current = branchIdentity.current();\n if (current === 'HEAD' || current === '') {\n return new SkipRuleResult(false, '', `turnOffRuleWhileOnBranch: \"${branchName}\" did not apply — HEAD is detached, so there is no ` + `branch to match (a tag checkout, a git bisect step, or a CI checkout of a merge ref).`);\n }\n if (current === branchName) {\n return new SkipRuleResult(true, `on branch \"${branchName}\"`);\n }\n }\n if (epoch !== undefined) {\n const nowSeconds = Date.now() / 1000;\n if (nowSeconds < epoch) {\n const expiresDate = new Date(epoch * 1000).toISOString().split('T')[0];\n return new SkipRuleResult(true, `turnOffRuleUntilEpoch active, expires: ${expiresDate}`);\n }\n }\n return new SkipRuleResult(false);\n}\n"]}
@@ -32,6 +32,21 @@ verified, and stage ③ re-runs the build ONLY if HEAD moved since — three sta
32
32
  All three stages are required and none may be skipped: stage ③ refuses to post a PR unless stage ② has
33
33
  run on this branch AND summary.json exists.
34
34
 
35
+ ### Emergency `/hotfix/` branches
36
+
37
+ An exact, case-sensitive `/hotfix/` path segment selects the auditable emergency profile. Its flow is:
38
+
39
+ ```bash
40
+ pnpm wp-start-upsert-pr
41
+ # write summary.json at the path and schema stage ① prints
42
+ pnpm wp-finish-upsert-pr
43
+ ```
44
+
45
+ Do not run or manufacture reviewer verdicts. `wp-review-upsert-pr` is a successful no-op if invoked by
46
+ mistake. Finish validates any conflict resolution, requires a clean tree and meaningful summary, runs
47
+ affected `hotfix-ci` (build + tests only), materializes the diff, and posts the permanently-bannered audit
48
+ surfaces. Normal branches retain the three-stage flow above.
49
+
35
50
  The tooling never commits for you (see the golden rule below), so **commit your work first**, then run
36
51
  `pnpm wp-start-upsert-pr`. The only reasons to stop *before* posting are: the human explicitly said "don't
37
52
  open a PR yet," or the build/tests are red. Otherwise, finishing the feature and posting the PR are the
@@ -73,7 +73,7 @@ Export and call a **named function**; only a thin wrapper calls `main`.
73
73
  ## Rolling out gradually
74
74
 
75
75
  This is a config-driven webpieces rule (`webpieces.config.json` → `no-process-exit-outside-main`) with
76
- the standard knobs: `mode` (`OFF` | `NEW_AND_MODIFIED_CODE` | `NEW_AND_MODIFIED_FILES`),
76
+ the standard knobs: `mode` (`OFF` | `NEW_AND_MODIFIED_CODE` | `NEW_AND_MODIFIED_FILES` | `MODIFIED_PROJECTS` | `RUN_EVERY_TIME`),
77
77
  `turnOffRuleUntilEpoch`, `turnOffRuleWhileOnBranch`, and `disableAllowed`. Start narrow
78
78
  (`NEW_AND_MODIFIED_FILES`, `disableAllowed: true`) and fix the codebase slowly — only new/modified code
79
79
  is flagged.
@@ -1,79 +0,0 @@
1
- /**
2
- * The FILE SET a diff-scoped rule judges — the one central place the whole-scope modes of #1027
3
- * (`MODIFIED_PROJECTS`, `RUN_EVERY_TIME`) and the debug run's `--projects` filter are implemented.
4
- *
5
- * Every diff-scoped validator asks `DiffScope.getChangedFiles` which files to look at and
6
- * `DiffScope.getFileDiff` which lines changed. Both consult the {@link FileScope} the caller is
7
- * running inside (`diffScope.within(scope, work)`), so the widening happens ONCE, here, and no rule
8
- * carries its own copy of it:
9
- *
10
- * DIFF — today's behaviour: the files the diff changed.
11
- * MODIFIED_PROJECTS — those files PLUS every file of every project any changed file belongs to.
12
- * RUN_EVERY_TIME — every file in the repo (tracked + untracked, honouring .gitignore).
13
- *
14
- * Under both whole-scope kinds every file is judged WHOLE: `getFileDiff` reports every line as added,
15
- * so a rule's line- or method-scoped logic sees the entire file as new. A widening can therefore never
16
- * report LESS than the diff-scoped mode it replaces.
17
- *
18
- * `projectRoots`, when set, keeps only files whose owning project (nearest `project.json`) is one of
19
- * those roots. It is what `--projects` on the debug run compiles to; the gate never sets it.
20
- */
21
- import { WholeScopeMode } from './rule-configs';
22
- export type FileScopeKind = 'DIFF' | WholeScopeMode;
23
- /** Which files a rule run judges. Data-only; see the file comment. */
24
- export declare class FileScope {
25
- readonly kind: FileScopeKind;
26
- /** Repo-relative project roots to keep ('.' = a project at the repo root), or null = all. */
27
- readonly projectRoots: readonly string[] | null;
28
- static readonly DIFF: FileScope;
29
- constructor(kind: FileScopeKind,
30
- /** Repo-relative project roots to keep ('.' = a project at the repo root), or null = all. */
31
- projectRoots: readonly string[] | null);
32
- /** True when this is exactly today's diff scope — no widening, no project filter. */
33
- isPlainDiff(): boolean;
34
- /** True for MODIFIED_PROJECTS / RUN_EVERY_TIME: every selected file is judged whole. */
35
- isWhole(): boolean;
36
- }
37
- /** The two questions every consumer of the whole-scope modes asks about a mode string. */
38
- export declare class WholeScopeModes {
39
- /** True when `mode` is one of the two whole-scope modes. */
40
- isWholeScopeMode(mode: string | undefined): mode is WholeScopeMode;
41
- /**
42
- * The per-file mode a rule runs with while its FILE SET is widened, or null when the rule's mode
43
- * set has no diff-scoped mode at all (a PROJECT_MODES / STRUCTURAL_MODES rule, whose own
44
- * `MODIFIED_PROJECTS` / `RUN_EVERY_TIME` it implements itself and which must not be rewritten).
45
- */
46
- wholeFileJudgeMode(modeSet: readonly string[]): string | null;
47
- }
48
- /**
49
- * Maps files to the nx project that owns them (the nearest ancestor holding a `project.json`) and
50
- * project NAMES to their roots. Parser-free and cached per instance: one run builds one index.
51
- */
52
- export declare class ProjectIndex {
53
- private readonly workspaceRoot;
54
- private readonly rootByDir;
55
- private namesToRoots;
56
- constructor(workspaceRoot: string);
57
- /** Repo-relative root of the project owning `relFile` ('.' for a repo-root project), or null. */
58
- rootOf(relFile: string): string | null;
59
- /** The roots of the named projects. Throws naming every unknown name and the known ones. */
60
- rootsFor(names: readonly string[]): string[];
61
- /** The project name declared for `root`, for reports (the root itself when no project.json names it). */
62
- nameOf(root: string): string;
63
- private rootOfDir;
64
- private names;
65
- private readName;
66
- private readJsonName;
67
- }
68
- /** Lists repo files — tracked plus untracked-not-ignored — that still exist on disk. */
69
- export declare class RepoFileLister {
70
- list(workspaceRoot: string, pathspecs: readonly string[]): string[];
71
- }
72
- /**
73
- * Turns the diff's changed files into the files a {@link FileScope} selects. `keep` is the caller's
74
- * own filter (ts-only, no tests) so a widened set obeys exactly the same in-scope test as the diff.
75
- */
76
- export declare class ScopedFileSelector {
77
- select(workspaceRoot: string, scope: FileScope, diffFiles: readonly string[], touchedFiles: () => readonly string[], pathspecs: readonly string[], keep: (file: string) => boolean): string[];
78
- private widen;
79
- }
package/src/file-scope.js DELETED
@@ -1,221 +0,0 @@
1
- "use strict";
2
- /**
3
- * The FILE SET a diff-scoped rule judges — the one central place the whole-scope modes of #1027
4
- * (`MODIFIED_PROJECTS`, `RUN_EVERY_TIME`) and the debug run's `--projects` filter are implemented.
5
- *
6
- * Every diff-scoped validator asks `DiffScope.getChangedFiles` which files to look at and
7
- * `DiffScope.getFileDiff` which lines changed. Both consult the {@link FileScope} the caller is
8
- * running inside (`diffScope.within(scope, work)`), so the widening happens ONCE, here, and no rule
9
- * carries its own copy of it:
10
- *
11
- * DIFF — today's behaviour: the files the diff changed.
12
- * MODIFIED_PROJECTS — those files PLUS every file of every project any changed file belongs to.
13
- * RUN_EVERY_TIME — every file in the repo (tracked + untracked, honouring .gitignore).
14
- *
15
- * Under both whole-scope kinds every file is judged WHOLE: `getFileDiff` reports every line as added,
16
- * so a rule's line- or method-scoped logic sees the entire file as new. A widening can therefore never
17
- * report LESS than the diff-scoped mode it replaces.
18
- *
19
- * `projectRoots`, when set, keeps only files whose owning project (nearest `project.json`) is one of
20
- * those roots. It is what `--projects` on the debug run compiles to; the gate never sets it.
21
- */
22
- Object.defineProperty(exports, "__esModule", { value: true });
23
- exports.ScopedFileSelector = exports.RepoFileLister = exports.ProjectIndex = exports.WholeScopeModes = exports.FileScope = void 0;
24
- const tslib_1 = require("tslib");
25
- const child_process_1 = require("child_process");
26
- const fs = tslib_1.__importStar(require("fs"));
27
- const path = tslib_1.__importStar(require("path"));
28
- const inform_ai_error_1 = require("./inform-ai-error");
29
- const rule_configs_1 = require("./rule-configs");
30
- const to_error_1 = require("./to-error");
31
- /**
32
- * The per-file judging mode a whole-scope run substitutes, most-whole first. Since a whole-scope run
33
- * also reports every line as changed, any of these judges the entire file; the preference only picks
34
- * the rule's most natural spelling of "the whole file".
35
- */
36
- const WHOLE_FILE_JUDGE_PREFERENCE = [
37
- 'NEW_AND_MODIFIED_FILES',
38
- 'MODIFIED_CLASS',
39
- 'NEW_AND_MODIFIED_METHODS',
40
- 'NEW_AND_MODIFIED_CODE',
41
- 'NEW_METHODS',
42
- ];
43
- /** Which files a rule run judges. Data-only; see the file comment. */
44
- class FileScope {
45
- kind;
46
- projectRoots;
47
- static DIFF = new FileScope('DIFF', null);
48
- constructor(kind,
49
- /** Repo-relative project roots to keep ('.' = a project at the repo root), or null = all. */
50
- projectRoots) {
51
- this.kind = kind;
52
- this.projectRoots = projectRoots;
53
- }
54
- /** True when this is exactly today's diff scope — no widening, no project filter. */
55
- isPlainDiff() {
56
- return this.kind === 'DIFF' && this.projectRoots === null;
57
- }
58
- /** True for MODIFIED_PROJECTS / RUN_EVERY_TIME: every selected file is judged whole. */
59
- isWhole() {
60
- return this.kind !== 'DIFF';
61
- }
62
- }
63
- exports.FileScope = FileScope;
64
- /** The two questions every consumer of the whole-scope modes asks about a mode string. */
65
- class WholeScopeModes {
66
- /** True when `mode` is one of the two whole-scope modes. */
67
- isWholeScopeMode(mode) {
68
- return rule_configs_1.WHOLE_SCOPE_MODES.includes(mode ?? '');
69
- }
70
- /**
71
- * The per-file mode a rule runs with while its FILE SET is widened, or null when the rule's mode
72
- * set has no diff-scoped mode at all (a PROJECT_MODES / STRUCTURAL_MODES rule, whose own
73
- * `MODIFIED_PROJECTS` / `RUN_EVERY_TIME` it implements itself and which must not be rewritten).
74
- */
75
- wholeFileJudgeMode(modeSet) {
76
- return WHOLE_FILE_JUDGE_PREFERENCE.find((m) => modeSet.includes(m)) ?? null;
77
- }
78
- }
79
- exports.WholeScopeModes = WholeScopeModes;
80
- /**
81
- * Maps files to the nx project that owns them (the nearest ancestor holding a `project.json`) and
82
- * project NAMES to their roots. Parser-free and cached per instance: one run builds one index.
83
- */
84
- class ProjectIndex {
85
- workspaceRoot;
86
- rootByDir = new Map();
87
- namesToRoots = null;
88
- constructor(workspaceRoot) {
89
- this.workspaceRoot = workspaceRoot;
90
- }
91
- /** Repo-relative root of the project owning `relFile` ('.' for a repo-root project), or null. */
92
- rootOf(relFile) {
93
- return this.rootOfDir(path.posix.dirname(relFile.split(path.sep).join('/')));
94
- }
95
- /** The roots of the named projects. Throws naming every unknown name and the known ones. */
96
- rootsFor(names) {
97
- const index = this.names();
98
- const unknown = names.filter((n) => !index.has(n));
99
- if (unknown.length > 0) {
100
- const known = Array.from(index.keys()).sort();
101
- throw new inform_ai_error_1.InformAiError(`--projects names ${unknown.map((n) => `'${n}'`).join(', ')}, which no project.json in ` +
102
- `${this.workspaceRoot} declares. Known projects: ${known.join(', ')}`);
103
- }
104
- return names.map((n) => index.get(n));
105
- }
106
- /** The project name declared for `root`, for reports (the root itself when no project.json names it). */
107
- nameOf(root) {
108
- for (const entry of this.names()) {
109
- if (entry[1] === root)
110
- return entry[0];
111
- }
112
- return root;
113
- }
114
- rootOfDir(dir) {
115
- const cached = this.rootByDir.get(dir);
116
- if (cached !== undefined)
117
- return cached;
118
- let found;
119
- if (fs.existsSync(path.join(this.workspaceRoot, dir, 'project.json'))) {
120
- found = dir === '' ? '.' : dir;
121
- }
122
- else if (dir === '.' || dir === '' || dir === '/') {
123
- found = null;
124
- }
125
- else {
126
- found = this.rootOfDir(path.posix.dirname(dir));
127
- }
128
- this.rootByDir.set(dir, found);
129
- return found;
130
- }
131
- names() {
132
- if (this.namesToRoots !== null)
133
- return this.namesToRoots;
134
- const map = new Map();
135
- for (const projectJson of new RepoFileLister().list(this.workspaceRoot, ['project.json', '*/project.json'])) {
136
- const root = path.posix.dirname(projectJson);
137
- map.set(this.readName(root), root === '' ? '.' : root);
138
- }
139
- this.namesToRoots = map;
140
- return map;
141
- }
142
- // nx's own precedence: project.json `name`, else the sibling package.json `name`, else the dir.
143
- readName(root) {
144
- for (const file of ['project.json', 'package.json']) {
145
- const name = this.readJsonName(path.join(this.workspaceRoot, root, file));
146
- if (name !== null)
147
- return name;
148
- }
149
- return path.posix.basename(root);
150
- }
151
- readJsonName(fullPath) {
152
- if (!fs.existsSync(fullPath))
153
- return null;
154
- // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
155
- try {
156
- const parsed = JSON.parse(fs.readFileSync(fullPath, 'utf-8'));
157
- return typeof parsed.name === 'string' && parsed.name.length > 0 ? parsed.name : null;
158
- }
159
- catch (err) {
160
- const error = (0, to_error_1.toError)(err);
161
- void error; // swallow — a malformed project.json falls back to the directory name
162
- return null;
163
- }
164
- }
165
- }
166
- exports.ProjectIndex = ProjectIndex;
167
- /** Lists repo files — tracked plus untracked-not-ignored — that still exist on disk. */
168
- class RepoFileLister {
169
- list(workspaceRoot, pathspecs) {
170
- const spec = pathspecs.length === 0 ? '' : ` -- ${pathspecs.map((p) => `'${p}'`).join(' ')}`;
171
- // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
172
- try {
173
- const output = (0, child_process_1.execSync)(`git ls-files --cached --others --exclude-standard${spec}`, {
174
- cwd: workspaceRoot,
175
- encoding: 'utf-8',
176
- maxBuffer: 256 * 1024 * 1024,
177
- });
178
- const files = output.split('\n').filter((f) => f.length > 0);
179
- return Array.from(new Set(files)).filter((f) => fs.existsSync(path.join(workspaceRoot, f)));
180
- }
181
- catch (err) {
182
- const error = (0, to_error_1.toError)(err);
183
- // NOT swallowed: an empty list here would make a whole-scope run judge zero files and PASS,
184
- // and a debug run report "TOTAL 0" — a false "nothing left" that is worse than a failure.
185
- throw new inform_ai_error_1.InformAiError(`A whole-scope rule run (MODIFIED_PROJECTS / RUN_EVERY_TIME) could not list the repo's files: ` +
186
- `\`git ls-files\` failed in ${workspaceRoot}: ${error.message}`, { cause: error });
187
- }
188
- }
189
- }
190
- exports.RepoFileLister = RepoFileLister;
191
- /**
192
- * Turns the diff's changed files into the files a {@link FileScope} selects. `keep` is the caller's
193
- * own filter (ts-only, no tests) so a widened set obeys exactly the same in-scope test as the diff.
194
- */
195
- class ScopedFileSelector {
196
- select(workspaceRoot, scope, diffFiles, touchedFiles, pathspecs, keep) {
197
- const projects = new ProjectIndex(workspaceRoot);
198
- const selected = this.widen(workspaceRoot, scope, diffFiles, touchedFiles, pathspecs, keep, projects);
199
- if (scope.projectRoots === null)
200
- return selected;
201
- const allowed = new Set(scope.projectRoots);
202
- return selected.filter((f) => allowed.has(projects.rootOf(f) ?? ''));
203
- }
204
- widen(workspaceRoot, scope, diffFiles, touchedFiles, pathspecs, keep, projects) {
205
- if (scope.kind === 'DIFF')
206
- return [...diffFiles];
207
- const repoFiles = new RepoFileLister().list(workspaceRoot, pathspecs).filter(keep);
208
- if (scope.kind === 'RUN_EVERY_TIME')
209
- return repoFiles;
210
- const touched = new Set();
211
- for (const file of touchedFiles()) {
212
- const root = projects.rootOf(file);
213
- if (root !== null)
214
- touched.add(root);
215
- }
216
- const inTouched = repoFiles.filter((f) => touched.has(projects.rootOf(f) ?? ''));
217
- return Array.from(new Set([...diffFiles, ...inTouched]));
218
- }
219
- }
220
- exports.ScopedFileSelector = ScopedFileSelector;
221
- //# sourceMappingURL=file-scope.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"file-scope.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/file-scope.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;GAmBG;;;;AAEH,iDAAyC;AACzC,+CAAyB;AACzB,mDAA6B;AAE7B,uDAAkD;AAClD,iDAAmE;AACnE,yCAAqC;AAOrC;;;;GAIG;AACH,MAAM,2BAA2B,GAAG;IAChC,wBAAwB;IACxB,gBAAgB;IAChB,0BAA0B;IAC1B,uBAAuB;IACvB,aAAa;CACP,CAAC;AAEX,sEAAsE;AACtE,MAAa,SAAS;IAIL;IAEA;IALb,MAAM,CAAU,IAAI,GAAG,IAAI,SAAS,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;IAEnD,YACa,IAAmB;IAC5B,6FAA6F;IACpF,YAAsC;QAFtC,SAAI,GAAJ,IAAI,CAAe;QAEnB,iBAAY,GAAZ,YAAY,CAA0B;IAChD,CAAC;IAEJ,qFAAqF;IACrF,WAAW;QACP,OAAO,IAAI,CAAC,IAAI,KAAK,MAAM,IAAI,IAAI,CAAC,YAAY,KAAK,IAAI,CAAC;IAC9D,CAAC;IAED,wFAAwF;IACxF,OAAO;QACH,OAAO,IAAI,CAAC,IAAI,KAAK,MAAM,CAAC;IAChC,CAAC;;AAjBL,8BAkBC;AAED,0FAA0F;AAC1F,MAAa,eAAe;IACxB,4DAA4D;IAC5D,gBAAg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S,GAAG,IAAI,cAAc,EAAE,CAAC,IAAI,CAAC,aAAa,EAAE,SAAS,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QACnF,IAAI,KAAK,CAAC,IAAI,KAAK,gBAAgB;YAAE,OAAO,SAAS,CAAC;QACtD,MAAM,OAAO,GAAG,IAAI,GAAG,EAAU,CAAC;QAClC,KAAK,MAAM,IAAI,IAAI,YAAY,EAAE,EAAE,CAAC;YAChC,MAAM,IAAI,GAAG,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;YACnC,IAAI,IAAI,KAAK,IAAI;gBAAE,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACzC,CAAC;QACD,MAAM,SAAS,GAAG,SAAS,CAAC,MAAM,CAAC,CAAC,CAAS,EAAE,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;QACzF,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC,CAAC,GAAG,SAAS,EAAE,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC;IAC7D,CAAC;CACJ;AApCD,gDAoCC","sourcesContent":["/**\n * The FILE SET a diff-scoped rule judges — the one central place the whole-scope modes of #1027\n * (`MODIFIED_PROJECTS`, `RUN_EVERY_TIME`) and the debug run's `--projects` filter are implemented.\n *\n * Every diff-scoped validator asks `DiffScope.getChangedFiles` which files to look at and\n * `DiffScope.getFileDiff` which lines changed. Both consult the {@link FileScope} the caller is\n * running inside (`diffScope.within(scope, work)`), so the widening happens ONCE, here, and no rule\n * carries its own copy of it:\n *\n * DIFF — today's behaviour: the files the diff changed.\n * MODIFIED_PROJECTS — those files PLUS every file of every project any changed file belongs to.\n * RUN_EVERY_TIME — every file in the repo (tracked + untracked, honouring .gitignore).\n *\n * Under both whole-scope kinds every file is judged WHOLE: `getFileDiff` reports every line as added,\n * so a rule's line- or method-scoped logic sees the entire file as new. A widening can therefore never\n * report LESS than the diff-scoped mode it replaces.\n *\n * `projectRoots`, when set, keeps only files whose owning project (nearest `project.json`) is one of\n * those roots. It is what `--projects` on the debug run compiles to; the gate never sets it.\n */\n\nimport { execSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nimport { InformAiError } from './inform-ai-error';\nimport { WholeScopeMode, WHOLE_SCOPE_MODES } from './rule-configs';\nimport { toError } from './to-error';\n\n/** The one field of a project.json / package.json this module reads. */\ntype RawNamedJson = { name?: string };\n\nexport type FileScopeKind = 'DIFF' | WholeScopeMode;\n\n/**\n * The per-file judging mode a whole-scope run substitutes, most-whole first. Since a whole-scope run\n * also reports every line as changed, any of these judges the entire file; the preference only picks\n * the rule's most natural spelling of \"the whole file\".\n */\nconst WHOLE_FILE_JUDGE_PREFERENCE = [\n 'NEW_AND_MODIFIED_FILES',\n 'MODIFIED_CLASS',\n 'NEW_AND_MODIFIED_METHODS',\n 'NEW_AND_MODIFIED_CODE',\n 'NEW_METHODS',\n] as const;\n\n/** Which files a rule run judges. Data-only; see the file comment. */\nexport class FileScope {\n static readonly DIFF = new FileScope('DIFF', null);\n\n constructor(\n readonly kind: FileScopeKind,\n /** Repo-relative project roots to keep ('.' = a project at the repo root), or null = all. */\n readonly projectRoots: readonly string[] | null,\n ) {}\n\n /** True when this is exactly today's diff scope — no widening, no project filter. */\n isPlainDiff(): boolean {\n return this.kind === 'DIFF' && this.projectRoots === null;\n }\n\n /** True for MODIFIED_PROJECTS / RUN_EVERY_TIME: every selected file is judged whole. */\n isWhole(): boolean {\n return this.kind !== 'DIFF';\n }\n}\n\n/** The two questions every consumer of the whole-scope modes asks about a mode string. */\nexport class WholeScopeModes {\n /** True when `mode` is one of the two whole-scope modes. */\n isWholeScopeMode(mode: string | undefined): mode is WholeScopeMode {\n return (WHOLE_SCOPE_MODES as readonly string[]).includes(mode ?? '');\n }\n\n /**\n * The per-file mode a rule runs with while its FILE SET is widened, or null when the rule's mode\n * set has no diff-scoped mode at all (a PROJECT_MODES / STRUCTURAL_MODES rule, whose own\n * `MODIFIED_PROJECTS` / `RUN_EVERY_TIME` it implements itself and which must not be rewritten).\n */\n wholeFileJudgeMode(modeSet: readonly string[]): string | null {\n return WHOLE_FILE_JUDGE_PREFERENCE.find((m: string) => modeSet.includes(m)) ?? null;\n }\n}\n\n/**\n * Maps files to the nx project that owns them (the nearest ancestor holding a `project.json`) and\n * project NAMES to their roots. Parser-free and cached per instance: one run builds one index.\n */\nexport class ProjectIndex {\n private readonly rootByDir = new Map<string, string | null>();\n private namesToRoots: Map<string, string> | null = null;\n\n constructor(private readonly workspaceRoot: string) {}\n\n /** Repo-relative root of the project owning `relFile` ('.' for a repo-root project), or null. */\n rootOf(relFile: string): string | null {\n return this.rootOfDir(path.posix.dirname(relFile.split(path.sep).join('/')));\n }\n\n /** The roots of the named projects. Throws naming every unknown name and the known ones. */\n rootsFor(names: readonly string[]): string[] {\n const index = this.names();\n const unknown = names.filter((n: string) => !index.has(n));\n if (unknown.length > 0) {\n const known = Array.from(index.keys()).sort();\n throw new InformAiError(\n `--projects names ${unknown.map((n: string) => `'${n}'`).join(', ')}, which no project.json in ` +\n `${this.workspaceRoot} declares. Known projects: ${known.join(', ')}`,\n );\n }\n return names.map((n: string) => index.get(n) as string);\n }\n\n /** The project name declared for `root`, for reports (the root itself when no project.json names it). */\n nameOf(root: string): string {\n for (const entry of this.names()) {\n if (entry[1] === root) return entry[0];\n }\n return root;\n }\n\n private rootOfDir(dir: string): string | null {\n const cached = this.rootByDir.get(dir);\n if (cached !== undefined) return cached;\n let found: string | null;\n if (fs.existsSync(path.join(this.workspaceRoot, dir, 'project.json'))) {\n found = dir === '' ? '.' : dir;\n } else if (dir === '.' || dir === '' || dir === '/') {\n found = null;\n } else {\n found = this.rootOfDir(path.posix.dirname(dir));\n }\n this.rootByDir.set(dir, found);\n return found;\n }\n\n private names(): Map<string, string> {\n if (this.namesToRoots !== null) return this.namesToRoots;\n const map = new Map<string, string>();\n for (const projectJson of new RepoFileLister().list(this.workspaceRoot, ['project.json', '*/project.json'])) {\n const root = path.posix.dirname(projectJson);\n map.set(this.readName(root), root === '' ? '.' : root);\n }\n this.namesToRoots = map;\n return map;\n }\n\n // nx's own precedence: project.json `name`, else the sibling package.json `name`, else the dir.\n private readName(root: string): string {\n for (const file of ['project.json', 'package.json']) {\n const name = this.readJsonName(path.join(this.workspaceRoot, root, file));\n if (name !== null) return name;\n }\n return path.posix.basename(root);\n }\n\n private readJsonName(fullPath: string): string | null {\n if (!fs.existsSync(fullPath)) return null;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const parsed = JSON.parse(fs.readFileSync(fullPath, 'utf-8')) as RawNamedJson;\n return typeof parsed.name === 'string' && parsed.name.length > 0 ? parsed.name : null;\n } catch (err: unknown) {\n const error = toError(err);\n void error; // swallow — a malformed project.json falls back to the directory name\n return null;\n }\n }\n}\n\n/** Lists repo files — tracked plus untracked-not-ignored — that still exist on disk. */\nexport class RepoFileLister {\n list(workspaceRoot: string, pathspecs: readonly string[]): string[] {\n const spec = pathspecs.length === 0 ? '' : ` -- ${pathspecs.map((p: string) => `'${p}'`).join(' ')}`;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const output = execSync(`git ls-files --cached --others --exclude-standard${spec}`, {\n cwd: workspaceRoot,\n encoding: 'utf-8',\n maxBuffer: 256 * 1024 * 1024,\n });\n const files = output.split('\\n').filter((f: string) => f.length > 0);\n return Array.from(new Set(files)).filter((f: string) => fs.existsSync(path.join(workspaceRoot, f)));\n } catch (err: unknown) {\n const error = toError(err);\n // NOT swallowed: an empty list here would make a whole-scope run judge zero files and PASS,\n // and a debug run report \"TOTAL 0\" — a false \"nothing left\" that is worse than a failure.\n throw new InformAiError(\n `A whole-scope rule run (MODIFIED_PROJECTS / RUN_EVERY_TIME) could not list the repo's files: ` +\n `\\`git ls-files\\` failed in ${workspaceRoot}: ${error.message}`,\n { cause: error },\n );\n }\n }\n}\n\n/**\n * Turns the diff's changed files into the files a {@link FileScope} selects. `keep` is the caller's\n * own filter (ts-only, no tests) so a widened set obeys exactly the same in-scope test as the diff.\n */\nexport class ScopedFileSelector {\n select(\n workspaceRoot: string,\n scope: FileScope,\n diffFiles: readonly string[],\n touchedFiles: () => readonly string[],\n pathspecs: readonly string[],\n keep: (file: string) => boolean,\n ): string[] {\n const projects = new ProjectIndex(workspaceRoot);\n const selected = this.widen(workspaceRoot, scope, diffFiles, touchedFiles, pathspecs, keep, projects);\n if (scope.projectRoots === null) return selected;\n const allowed = new Set(scope.projectRoots);\n return selected.filter((f: string) => allowed.has(projects.rootOf(f) ?? ''));\n }\n\n private widen(\n workspaceRoot: string,\n scope: FileScope,\n diffFiles: readonly string[],\n touchedFiles: () => readonly string[],\n pathspecs: readonly string[],\n keep: (file: string) => boolean,\n projects: ProjectIndex,\n ): string[] {\n if (scope.kind === 'DIFF') return [...diffFiles];\n const repoFiles = new RepoFileLister().list(workspaceRoot, pathspecs).filter(keep);\n if (scope.kind === 'RUN_EVERY_TIME') return repoFiles;\n const touched = new Set<string>();\n for (const file of touchedFiles()) {\n const root = projects.rootOf(file);\n if (root !== null) touched.add(root);\n }\n const inTouched = repoFiles.filter((f: string) => touched.has(projects.rootOf(f) ?? ''));\n return Array.from(new Set([...diffFiles, ...inTouched]));\n }\n}\n"]}