@webpieces/ai-hook-rules 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.
Files changed (47) hide show
  1. package/package.json +6 -4
  2. package/src/adapters/codex-subagent-guard.js +5 -3
  3. package/src/adapters/codex-subagent-guard.js.map +1 -1
  4. package/src/adapters/review-identity-stamper.d.ts +1 -1
  5. package/src/adapters/review-identity-stamper.js +3 -3
  6. package/src/adapters/review-identity-stamper.js.map +1 -1
  7. package/src/bin/shim-audit-log.js +4 -4
  8. package/src/bin/shim-audit-log.js.map +1 -1
  9. package/src/core/decision-log.js +7 -5
  10. package/src/core/decision-log.js.map +1 -1
  11. package/src/core/effective-tree.js +5 -4
  12. package/src/core/effective-tree.js.map +1 -1
  13. package/src/core/l0-tooling-doc.js +5 -4
  14. package/src/core/l0-tooling-doc.js.map +1 -1
  15. package/src/core/main-sync-log.js +3 -3
  16. package/src/core/main-sync-log.js.map +1 -1
  17. package/src/core/main-sync-timeout.js +4 -3
  18. package/src/core/main-sync-timeout.js.map +1 -1
  19. package/src/core/rejection-log.js +2 -1
  20. package/src/core/rejection-log.js.map +1 -1
  21. package/src/core/rules/branch-creation-guard.js +5 -4
  22. package/src/core/rules/branch-creation-guard.js.map +1 -1
  23. package/src/core/rules/feature-branch-guard.js +4 -3
  24. package/src/core/rules/feature-branch-guard.js.map +1 -1
  25. package/src/core/rules/main-freshness.d.ts +1 -1
  26. package/src/core/rules/main-freshness.js.map +1 -1
  27. package/src/core/rules/merge-in-progress-guard.js +2 -1
  28. package/src/core/rules/merge-in-progress-guard.js.map +1 -1
  29. package/src/core/rules/merged-branch-bash-guard.js +3 -2
  30. package/src/core/rules/merged-branch-bash-guard.js.map +1 -1
  31. package/src/core/rules/read-stale-guard.js +4 -3
  32. package/src/core/rules/read-stale-guard.js.map +1 -1
  33. package/src/core/rules/stale-main-bash-guard.js +3 -2
  34. package/src/core/rules/stale-main-bash-guard.js.map +1 -1
  35. package/src/core/rules/tree-recovery.js +2 -1
  36. package/src/core/rules/tree-recovery.js.map +1 -1
  37. package/src/core/rules/wait-spin-guard.js +2 -2
  38. package/src/core/rules/wait-spin-guard.js.map +1 -1
  39. package/src/core/rules/whole-repo-build-guard.js +2 -1
  40. package/src/core/rules/whole-repo-build-guard.js.map +1 -1
  41. package/src/core/session-call-history.js +2 -2
  42. package/src/core/session-call-history.js.map +1 -1
  43. package/src/core/sync-main.js +9 -8
  44. package/src/core/sync-main.js.map +1 -1
  45. package/src/core/types.d.ts +2 -1
  46. package/src/core/types.js +3 -2
  47. package/src/core/types.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"branch-creation-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/ai-hook-rules/src/core/rules/branch-creation-guard.ts"],"names":[],"mappings":";;;AAAA,iDAAyC;AAEzC,0DAA8L;AAG9L,oCAA0C;AAC1C,4CAA4C;AAC5C,0CAAsC;AACtC,iDAA6C;AAC7C,0CAAsC;AAEtC,8EAA8E;AAC9E,+FAA+F;AAC/F,kGAAkG;AAClG,MAAM,qBAAqB,GAAG,4HAA4H,CAAC;AAE3J,qGAAqG;AACrG,+EAA+E;AAC/E,EAAE;AACF,uGAAuG;AACvG,sGAAsG;AACtG,uGAAuG;AACvG,sCAAsC;AACtC,MAAM,0BAA0B,GAAG,CAAC,CAAC;AACrC,MAAM,qBAAqB,GAAG,CAAC,CAAC;AAEhC,oGAAoG;AACpG,kGAAkG;AAClG,mGAAmG;AACnG,MAAM,QAAQ,GAAG,MAAM,CAAC,GAAG,CAAA,6BAA6B,CAAC;AAEzD,MAAM,eAAe,GAAa;IAC9B,IAAI,MAAM,CAAC,MAAM,CAAC,GAAG,CAAA,6BAA6B,QAAQ,GAAG,CAAC;IAC9D,IAAI,MAAM,CAAC,MAAM,CAAC,GAAG,CAAA,2BAA2B,QAAQ,GAAG,CAAC;IAC5D,IAAI,MAAM,CAAC,MAAM,CAAC,GAAG,CAAA,wBAAwB,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AG,IAAI,CAAC,SAAS,CAAC,eAAe,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC,MAAM,CAAC;QACvE,IAAI,KAAK,GAAG,IAAI,CAAC,YAAY;YAAE,OAAO,IAAI,CAAC;QAE3C,MAAM,KAAK,GAAG,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAAC,CAAC;QAC5C,IAAI,CAAC,KAAK;YAAE,OAAO,IAAI,CAAC;QAExB,IAAI,CAAC,gBAAgB,GAAG,KAAK,CAAC;QAE9B,OAAO,IAAI,iBAAC,CAAC,CAAC,EAAE,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,YAAY,MAAM,CAAC,KAAK,CAAC,kEAAkE,GAAG,MAAM,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,wBAAwB,CAAC,CAAC;IAClM,CAAC;CACJ;AAtUD,0DAsUC","sourcesContent":["import { execSync } from 'child_process';\n\nimport { BranchCreationGuardConfig, BranchIdentity, DeletableBranch, MergedBranchesCache, MergedBranchesService, WorktreeService, readMainSyncStatus, Option } from '@webpieces/rules-config';\n\nimport type { BashContext, Violation } from '../types';\nimport { Violation as V } from '../types';\nimport { BashRuleBase } from '../rule-base';\nimport { FixHint } from '../fix-hint';\nimport { CapRemedies } from './cap-remedies';\nimport { toError } from '../to-error';\n\n// Defaults used when the rule has no explicit value in webpieces.config.json.\n// branchFormat is a human sentence telling the AI how to name a branch created off main; it is\n// intentionally NOT the sub-branch convention (sub-branches are a separate, human-approved path).\nconst DEFAULT_BRANCH_FORMAT = 'Name it {whoami}/<short-feature-description> — lowercase, no version numbers, no sub/ prefix (e.g. dean/upgrade-webpieces)';\n\n// Hard cap on local feature branches. Enforced at CREATION because that is the one moment cleanup is\n// both cheap and obviously worth it — reaping happens over time, never \"ASAP\".\n//\n// The branch cap counts PARKED branches only — branches not checked out in any worktree. Worktree-held\n// branches are counted by the worktree cap instead. Two budgets, because they are not substitutes: if\n// held branches also spent the branch budget, five worktrees would leave room for zero branches and no\n// branch could ever be created again.\nconst DEFAULT_MAX_LOCAL_BRANCHES = 5;\nconst DEFAULT_MAX_WORKTREES = 5;\n\n// A plausible git ref name. Deliberately NOT `[^\\s-]` — that class matches shell metacharacters, so\n// `git branch | wc -l` (a read-only LISTING, piped) was parsed as \"create a branch named `|`\" and\n// blocked. Cleanup work necessarily reads and deletes branches, so a listing must never trip this.\nconst REF_NAME = String.raw`[A-Za-z0-9][A-Za-z0-9_./-]*`;\n\nconst BRANCH_PATTERNS: RegExp[] = [\n new RegExp(String.raw`git\\s+checkout\\s+-[bB]\\s+(${REF_NAME})`),\n new RegExp(String.raw`git\\s+switch\\s+-[cC]\\s+(${REF_NAME})`),\n new RegExp(String.raw`git\\s+branch\\s+(?!-)(${REF_NAME})`),\n // `git worktree add ../dir -b <name> origin/main` — the form docs/git-workflow.md recommends for\n // starting a feature. It creates a branch just as surely as `checkout -b` does, and until this\n // pattern existed it walked straight past the cap, the reserved-suffix check and the sub-branch\n // check. `(?:\\S+\\s+)*?` absorbs the path and any other flags, so the -b may precede or follow them.\n new RegExp(String.raw`git\\s+worktree\\s+add\\s+(?:\\S+\\s+)*?-[bB]\\s+(${REF_NAME})`),\n];\n\n// ANY worktree creation, with or without -b. The no-`-b` forms (`git worktree add ../dir existing`,\n// `--detach`) create no branch but DO create a worktree, so they spend the worktree budget and must\n// still hit the cap.\nconst WORKTREE_ADD = /git\\s+worktree\\s+add\\b/;\n\n// `git worktree add <path> <existing-branch>` — the checkout-an-existing-branch form. Captures the\n// LAST bare (non-flag) argument, which is the committish; the first bare argument is the path.\n// Flags that take a value (`--reason <s>`, `-b <name>`) are excluded by the caller, which only uses\n// this on commands with no `-b`/`-B` at all.\nconst WORKTREE_ADD_EXISTING = new RegExp(String.raw`git\\s+worktree\\s+add\\s+(?:-{1,2}[A-Za-z-]+\\s+)*\\S+\\s+(${REF_NAME})`);\n\n// `git branch <name> <sha>` — RESTORING a branch at an explicit commit, which is exactly the\n// `recover=` command wp-cleanup writes to branch-mutations.log for every branch it reaps.\n//\n// This must be allowed UNCONDITIONALLY, ahead of even the caps. The entire argument for letting the\n// tooling delete branches unattended is that any delete is one logged command away from being undone\n// — so a guard that blocks that command turns a real guarantee into a decorative one. (It did: the\n// generic `git branch <name>` creation pattern matched the restore and refused it, demanding the\n// branch be recreated off origin/main, which is precisely the content the restore is meant to bring\n// back.) A restore also cannot grow the branch list beyond what already existed.\nconst RESTORE_AT_SHA = new RegExp(String.raw`git\\s+branch\\s+${REF_NAME}\\s+[0-9a-f]{7,40}(?:\\W|$)`);\n\n// A trailing `wp<number>` was the old squash-merge generation marker (base → basewp2 → basewp3).\n// The tooling NO LONGER produces it — a sync now lands back on the same feature name — but the suffix\n// stays RESERVED so a human branch can't collide with a leftover `…wpN` still floating in a consumer\n// repo mid-transition. Block it at creation time and steer the name back to the plain feature form.\nconst RESERVED_GENERATION_SUFFIX = /wp\\d+$/;\n\n// A branch-creation command that explicitly bases off origin/main (e.g. `git checkout -b feat\n// origin/main`). This is exactly the fresh-main base the guard wants, and it works from ANY current\n// branch or linked worktree — main need not (and in a worktree cannot) be checked out here. Allowed\n// unconditionally so the recovery messages can safely tell you to run it from a worktree.\n//\n// The trailing check is `\\W|$`, not `\\s|$`: the ALLOW pattern must not be stricter about delimiters\n// than the BLOCK pattern above, or a `git checkout -b x origin/main` that ends at a quote or backtick\n// is seen as a branch creation but NOT as an origin/main one — recognised, then wrongly blocked.\nconst ORIGIN_MAIN_BASE = /git\\s+(?:checkout\\s+-[bB]|switch\\s+-[cC])\\s+\\S+\\s+origin\\/main(?:\\W|$)/;\n\n// The worktree arm of the same allow: `git worktree add ../dir -b <name> origin/main`. Same fresh-main\n// base, same reasoning — and in a worktree it is the ONLY workable base, since `git checkout main`\n// fatals there. Kept separate from ORIGIN_MAIN_BASE because the argument shape differs (a path sits\n// between the subcommand and the flags).\nconst WORKTREE_ORIGIN_MAIN_BASE = /git\\s+worktree\\s+add\\s+(?:\\S+\\s+)*origin\\/main(?:\\W|$)/;\n\nfunction extractBranchName(command: string): string | null {\n for (const pattern of BRANCH_PATTERNS) {\n const m = pattern.exec(command);\n if (m) return m[1];\n }\n return null;\n}\n\nfunction truncate(s: string): string {\n const MAX = 120;\n return s.length <= MAX ? s : s.slice(0, MAX) + '…';\n}\n\nfunction checkMainIsUpToDate(ctx: BashContext, requestedName: string): readonly Violation[] {\n // `--no-write-fetch-head` for the same reason as the background refresher (see\n // MainSyncStatusService.fetchOriginMain): this refresh can run while the agent is mid\n // `git fetch`/`git pull`, and two overlapping writers of the unlocked `.git/FETCH_HEAD` can leave\n // a duplicate for-merge line that makes the agent's `git pull` fatal with \"multiple branches\". We\n // read `origin/main` below, never FETCH_HEAD. On a git too old for the flag, retry the plain form.\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n execSync('git fetch --no-write-fetch-head origin main --quiet', {\n cwd: ctx.workspaceRoot,\n encoding: 'utf8',\n });\n } catch (err: unknown) {\n const error = toError(err);\n const text = error.message.toLowerCase();\n const tooOld = text.includes('unknown option') || text.includes('unknown switch') || text.includes('unrecognized option');\n if (!tooOld) throw error;\n execSync('git fetch origin main --quiet', { cwd: ctx.workspaceRoot, encoding: 'utf8' });\n }\n const countStr = execSync('git rev-list HEAD..origin/main --count', {\n cwd: ctx.workspaceRoot,\n encoding: 'utf8',\n }).trim();\n const count = parseInt(countStr, 10);\n if (count > 0) {\n return [new V(1, truncate(ctx.command), `Local main is ${count} commit(s) behind origin/main. Run 'git pull origin main' first, then retry creating branch '${requestedName}'.`)];\n }\n return [];\n}\n\nexport class BranchCreationGuardRule extends BashRuleBase<BranchCreationGuardConfig> {\n constructor(config: BranchCreationGuardConfig) {\n super(config, 'branch-creation-guard', 'branch-creation-guard');\n }\n\n readonly description = 'Block new-branch and new-worktree creation when main is stale, when branching off a non-main ' + 'branch, or when the branch/worktree count is at its cap (forces cleanup of dead ones).';\n override readonly defaultOptions = {\n branchFormat: DEFAULT_BRANCH_FORMAT,\n maxLocalBranches: DEFAULT_MAX_LOCAL_BRANCHES,\n maxWorktrees: DEFAULT_MAX_WORKTREES,\n };\n\n private readonly worktrees = new WorktreeService();\n private readonly mergedBranches = new MergedBranchesService(this.worktrees);\n private readonly branchIdentity = new BranchIdentity();\n\n // Set by check() when (and only when) a cap is what blocked, so fixHint can render the reap\n // instructions instead of the branch-naming ones. Same instance-field handoff pr-merge-guard uses.\n // Two fields, because the two caps reap different things and their hints share no wording.\n private capCache: MergedBranchesCache | null = null;\n private worktreeCapCache: MergedBranchesCache | null = null;\n\n // True when the blocked command was a `git worktree add`, so the recovery command we hand back is\n // a worktree command and not a `git checkout -b` the user cannot use here.\n private worktreeAdd = false;\n\n private get branchFormat(): string {\n return this.config.branchFormat ?? DEFAULT_BRANCH_FORMAT;\n }\n\n // No `??` fallback: `subBranchNaming` is schema-REQUIRED (#1017), so a config that reached here\n // stated it. A default here would be the framework choosing a consumer's branch convention.\n private get subBranchNaming(): string {\n return this.config.subBranchNaming;\n }\n\n private get maxLocalBranches(): number {\n return this.config.maxLocalBranches ?? DEFAULT_MAX_LOCAL_BRANCHES;\n }\n\n private get maxWorktrees(): number {\n return this.config.maxWorktrees ?? DEFAULT_MAX_WORKTREES;\n }\n\n // The recovery command for \"base this off fresh main\", in the flavour of whatever was blocked.\n private freshMainCommand(name: string): string {\n return this.worktreeAdd ? `git fetch origin main && git worktree add ../${name.replace(/\\//g, '-')} -b ${name} origin/main` : `git fetch origin main && git checkout -b ${name} origin/main`;\n }\n\n // Mode-aware fix hints. Branches off main follow branchFormat — never the sub-branch\n // convention. The sub-branch affordance only appears under mode 'ON'; 'ON_NO_SUBBRANCHES'\n // hard-blocks it and points instead at the turnOffRuleUntilEpoch escape hatch.\n get fixHint(): FixHint {\n const remedies = new CapRemedies();\n if (this.worktreeCapCache) return remedies.worktreeCap();\n if (this.capCache) return remedies.branchCap();\n\n const create = this.worktreeAdd ? 'Create it off fresh main: git fetch origin main && git worktree add ../<dir> -b <name> origin/main' : 'Create it off fresh main from anywhere (incl. a worktree): git fetch origin main && git checkout -b <name> origin/main';\n\n const options = [new Option(create, true), new Option(`Name a branch off main per branch-creation-guard.branchFormat: ${this.branchFormat}`)];\n if (this.config.mode === 'ON_NO_SUBBRANCHES') {\n options.push(new Option('Sub-branches (branching off another feature branch) are disabled. To temporarily allow one, set ' + 'branch-creation-guard.turnOffRuleUntilEpoch to a future epoch in webpieces.config.json'));\n } else {\n options.push(new Option(`If you truly need a stacked sub-branch (requires human approval), name it per branch-creation-guard.subBranchNaming: ${this.subBranchNaming}`));\n }\n return new FixHint('Cannot create this branch (main is stale, or branching off a non-main branch).', 'Create your branch from an up-to-date main. Pick one:', options);\n }\n\n /**\n * Strip the parts of a shell command that are DATA rather than executable commands, so the guard\n * stops reading prose as instructions.\n *\n * This guard regex-scans the raw command string and has no notion of quoting, so\n * `git commit -m \"... git checkout -b foo ...\"` — or any heredoc commit message that mentions a\n * branch command — was parsed as an actual branch creation and blocked. That bit three separate\n * times while building the branch cap, including on the cap's own commit. It matters far more now\n * that the cap check runs BEFORE the origin/main allow: at the cap, a merely-MENTIONED branch\n * command would block your commit.\n *\n * A quoted span whose content has no whitespace is kept verbatim (it is a single token — the name\n * in `git checkout -b \"dean/foo\"`), so quoting a branch name cannot smuggle a creation past the\n * guard. Anything with whitespace inside quotes is prose, and collapses to a space.\n */\n check(ctx: BashContext): readonly Violation[] {\n this.capCache = this.worktreeCapCache = null;\n // Match against the command with heredoc bodies and prose-in-quotes removed (BashContext\n // computes it for every guard now — this rule's private copy was the original).\n const command = ctx.commandCode;\n const requestedName = extractBranchName(command);\n this.worktreeAdd = WORKTREE_ADD.test(command);\n\n // A worktree add with no -b creates no branch, but it DOES spend the worktree budget, so it must\n // survive this early-out and reach the worktree cap below.\n if (!requestedName && !this.worktreeAdd) return [];\n\n // Restoring a reaped branch at its logged SHA is undo, not creation — always allowed, and\n // checked before the caps so a full branch list can never trap you on the recovery path.\n if (!this.worktreeAdd && RESTORE_AT_SHA.test(command)) return [];\n\n const reserved = this.checkReservedSuffix(ctx, requestedName);\n if (reserved) return [reserved];\n\n const capViolation = this.checkCaps(ctx, requestedName !== null);\n if (capViolation) return [capViolation];\n\n // `git worktree add` of an EXISTING branch (or --detach) creates no branch, so the naming and\n // fresh-main rules below do not apply — but one thing still does: the branch may be DEAD.\n if (!requestedName) return this.checkWorktreeOntoDeadBranch(ctx, command);\n\n // Explicitly basing off origin/main is always allowed — it creates the branch from fresh main\n // regardless of the current branch, and is the ONLY way that also works inside a linked worktree\n // (where `git checkout main` fatals). Reserved-name check above still applies.\n if (ORIGIN_MAIN_BASE.test(command)) return [];\n if (this.worktreeAdd && WORKTREE_ORIGIN_MAIN_BASE.test(command)) return [];\n\n // The exact `/hotfix/` convention explicitly authorizes a nested emergency branch.\n if (this.branchIdentity.isHotfix(requestedName)) return [];\n\n const currentBranch = execSync('git rev-parse --abbrev-ref HEAD', {\n cwd: ctx.workspaceRoot,\n encoding: 'utf8',\n }).trim();\n\n if (currentBranch === 'main') {\n return checkMainIsUpToDate(ctx, requestedName);\n }\n\n // Not on main: creating this branch would stack it on a feature branch (a sub-branch).\n if (this.config.mode === 'ON_NO_SUBBRANCHES') {\n return [\n new V(\n 1,\n truncate(ctx.command),\n `You are on '${currentBranch}', not main. Create the branch OFF origin/main instead of ` +\n `stacking it on this branch: ${this.freshMainCommand(requestedName)} ` +\n `(works here and inside a worktree). ${this.branchFormat}. ` +\n `You can temporarily turn this off if you truly need a sub-branch by setting ` +\n `branch-creation-guard.turnOffRuleUntilEpoch (a future epoch) in webpieces.config.json.`,\n ),\n ];\n }\n\n return [\n new V(\n 1,\n truncate(ctx.command),\n `You are on '${currentBranch}', not main. Branches must be created from fresh main: ` +\n `${this.freshMainCommand(requestedName)}. ${this.branchFormat}. ` +\n `If you truly need a stacked sub-branch (requires human approval), name it per ` +\n `branch-creation-guard.subBranchNaming ('${this.subBranchNaming}').`,\n ),\n ];\n }\n\n /**\n * `git worktree add ../dir <existing-branch>` onto a branch whose PR is ALREADY MERGED.\n *\n * The count caps never catch this: the command creates no branch, and if you are under the\n * worktree cap it sails straight through — materialising a fresh directory full of PRE-MERGE\n * code that the AI will then read, plan from and edit. read-stale-guard blocks the reads and\n * feature-branch-guard blocks the edits once you are in there, but that is a turn wasted per\n * tool call. Refuse at the moment of creation instead, using the SAME merged-PR proof the caps\n * already have precomputed on disk.\n *\n * Fails OPEN exactly like both caps: no cache (fresh clone, no `gh`, refresher hasn't run) or an\n * unparseable command → no opinion.\n */\n private checkWorktreeOntoDeadBranch(ctx: BashContext, command: string): readonly Violation[] {\n if (!this.worktreeAdd) return [];\n\n const match = WORKTREE_ADD_EXISTING.exec(command);\n if (!match) return [];\n const branch = match[1];\n // `origin/main` (and any remote-tracking ref) is the RECOMMENDED base, never a dead branch.\n if (branch.startsWith('origin/')) return [];\n\n const cache = this.mergedBranches.readMergedBranches(ctx.workspaceRoot);\n if (!cache) return [];\n\n const dead = cache.deletable.find((entry: DeletableBranch): boolean => entry.branch === branch);\n if (!dead) return [];\n\n const dir = branch.replace(/\\//g, '-');\n return [\n new V(\n 1,\n truncate(ctx.command),\n `Branch '${branch}' is dead — ${dead.reason}. A worktree on it would be a directory full of ` +\n `PRE-MERGE code: everything you read there is stale relative to origin/main (read-stale-guard ` +\n `blocks those reads) and every edit is blocked by feature-branch-guard. Base the new worktree ` +\n `on fresh main instead: git fetch origin main && git worktree add ../${dir} -b <new-branch> origin/main`,\n ),\n ];\n }\n\n // The reserved `…wpN` generation suffix — see RESERVED_GENERATION_SUFFIX for why it stays blocked\n // even though the tooling no longer produces it.\n private checkReservedSuffix(ctx: BashContext, requestedName: string | null): Violation | null {\n if (!requestedName || !RESERVED_GENERATION_SUFFIX.test(requestedName)) return null;\n return new V(1, truncate(ctx.command), `Branch name '${requestedName}' ends in 'wp<number>', which is reserved for the ` + `squash-merge tool's generation marker (base → basewp2 → basewp3). ` + `Rename it to a plain feature branch. ${this.branchFormat}.`);\n }\n\n /**\n * Both budgets, in the order that produces the most useful complaint.\n *\n * Called BEFORE the origin/main allow in check() — `... -b <name> origin/main` is the normal,\n * always-permitted path, so a cap checked after it would never once fire.\n *\n * Worktree cap first: a `git worktree add -b` spends BOTH budgets, and when both are full the\n * worktree is the thing the command was actually trying to make, so it is the thing to talk about.\n */\n private checkCaps(ctx: BashContext, createsBranch: boolean): Violation | null {\n if (this.worktreeAdd) {\n const worktreeViolation = this.checkWorktreeCap(ctx);\n if (worktreeViolation) return worktreeViolation;\n }\n if (createsBranch) return this.checkBranchCap(ctx);\n return null;\n }\n\n /**\n * The cap. Blocks branch #N+1 until already-merged branches are reaped, which is the ONLY thing\n * keeping the local branch list bounded.\n *\n * Fails OPEN when the cache is absent (fresh clone, `gh` unavailable, refresher hasn't run yet):\n * never block on data we don't have. The detached refresher regenerates it within one hook call,\n * so the cap starts enforcing on its own.\n */\n private checkBranchCap(ctx: BashContext): Violation | null {\n // PARKED branches only — a branch checked out in a worktree is the worktree cap's problem, and\n // counting it twice would let five worktrees exhaust the branch budget on their own.\n const held = this.worktrees.heldBranches(ctx.workspaceRoot);\n const parked = this.mergedBranches.localBranches(ctx.workspaceRoot).filter((branch: string): boolean => !held.has(branch));\n const count = parked.length;\n const cap = this.effectiveBranchCap(ctx);\n if (count < cap) return null;\n\n const cache = this.loadReconciledCache(ctx);\n if (!cache) return null;\n\n this.capCache = cache;\n\n // No count of \"how many are dead\" any more. It was read off a cache that is stale BY DESIGN,\n // so every branch of that sentence had to hedge (\"None of them are dead\", \"NOT known right\n // now — the cached verdicts are stale\"), and none of the three variants changed the next\n // move: run pnpm wp-cleanup, which recomputes from scratch. Say the one thing that is true.\n return new V(1, truncate(ctx.command), `You have ${String(count)} parked local branches (worktree-held ones not counted); the cap ` + `(branch-creation-guard.maxLocalBranches) is ${String(this.maxLocalBranches)}. Run pnpm wp-cleanup.`);\n }\n\n /**\n * The cache, with entries for branches/worktrees that no longer exist dropped.\n *\n * Reconciling is the fix for the phantom count: the file is written by a detached refresher and is\n * DELIBERATELY allowed to go stale, so it keeps naming branches deleted minutes ago and worktrees\n * already removed. Quoting it verbatim is how the guard announced \"8 parked local branches … none of\n * them are dead\" over a repo that had ONE, and then blocked a legitimate `git worktree add` on that\n * figure. `reconcile` re-checks existence with instant local git reads; it does NOT re-derive any\n * verdict (that needs the network and belongs in the refresher).\n *\n * Its AGE is no longer read here. The cap messages stopped quoting verdict counts entirely, so\n * there is nothing left for a freshness caveat to qualify — `wp-cleanup` recomputes from scratch.\n */\n private loadReconciledCache(ctx: BashContext): MergedBranchesCache | null {\n const raw = this.mergedBranches.readMergedBranches(ctx.workspaceRoot);\n if (!raw) return null;\n return this.mergedBranches.reconcile(ctx.workspaceRoot, raw);\n }\n\n /**\n * The branch cap, yielding by ONE when the agent is standing on an already-merged branch.\n *\n * Two individually-correct guards were composing into a trap: merged-branch-bash-guard blocks\n * almost all Bash until you get off a merged branch, and the ONLY way off it that guard advertises\n * is creating a fresh branch — which this cap then refused. Every printed exit led to editing\n * webpieces.config.json, and that is what an unsupervised agent did.\n *\n * One over cap, and only while a merged branch is what is pushing you: the branch about to be\n * created replaces a branch that is already dead, so the steady-state count does not grow. The cap\n * still fires on the NEXT creation, so this defers the cleanup by exactly one branch, never skips it.\n *\n * Fails toward the strict cap: no cache, a cache for another branch, or a clean branch → no yield.\n */\n private effectiveBranchCap(ctx: BashContext): number {\n // The cache is branch-keyed, so the branch we are standing on is what we look the entry up by.\n // A branch the last refresh never saw misses (null) → the strict cap, as before.\n const current = this.currentBranchOrNull(ctx.workspaceRoot);\n if (current === null) return this.maxLocalBranches;\n const status = readMainSyncStatus(ctx.workspaceRoot, current);\n if (status === null || !status.branchAlreadyMerged) return this.maxLocalBranches;\n if (status.branch !== current) return this.maxLocalBranches;\n return this.maxLocalBranches + 1;\n }\n\n private currentBranchOrNull(workspaceRoot: string): string | null {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return execSync('git rev-parse --abbrev-ref HEAD', {\n cwd: workspaceRoot,\n encoding: 'utf8',\n stdio: ['pipe', 'pipe', 'pipe'],\n }).trim();\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n\n /**\n * The worktree cap — the second budget. Same gate, same fail-open rule as the branch cap: a\n * worktree list we cannot classify (no cache on disk) blocks nothing.\n *\n * Counts LINKED worktrees only. The primary clone is not a thing anyone can remove, so charging the\n * budget for it would just silently cost you one worktree.\n */\n private checkWorktreeCap(ctx: BashContext): Violation | null {\n const count = this.worktrees.linkedWorktrees(ctx.workspaceRoot).length;\n if (count < this.maxWorktrees) return null;\n\n const cache = this.loadReconciledCache(ctx);\n if (!cache) return null;\n\n this.worktreeCapCache = cache;\n\n return new V(1, truncate(ctx.command), `You have ${String(count)} linked worktrees; the cap (branch-creation-guard.maxWorktrees) ` + `is ${String(this.maxWorktrees)}. Run pnpm wp-cleanup.`);\n }\n}\n"]}
1
+ {"version":3,"file":"branch-creation-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/ai-hook-rules/src/core/rules/branch-creation-guard.ts"],"names":[],"mappings":";;;AAAA,iDAAyC;AAEzC,0DAA4E;AAC5E,sEAAiK;AAGjK,oCAA0C;AAC1C,4CAA4C;AAC5C,0CAAsC;AACtC,iDAA6C;AAC7C,0CAAsC;AAEtC,8EAA8E;AAC9E,+FAA+F;AAC/F,kGAAkG;AAClG,MAAM,qBAAqB,GAAG,4HAA4H,CAAC;AAE3J,qGAAqG;AACrG,+EAA+E;AAC/E,EAAE;AACF,uGAAuG;AACvG,sGAAsG;AACtG,uGAAuG;AACvG,sCAAsC;AACtC,MAAM,0BAA0B,GAAG,CAAC,CAAC;AACrC,MAAM,qBAAqB,GAAG,CAAC,CAAC;AAEhC,oGAAoG;AACpG,kGAAkG;AAClG,mGAAmG;AACnG,MAAM,QAAQ,GAAG,MAAM,CAAC,GAAG,CAAA,6BAA6B,CAAC;AAEzD,MAAM,eAAe,GAAa;IAC9B,IAAI,MAAM,CAAC,MAAM,CAAC,GAAG,CAAA,6BAA6B,QAAQ,GAAG,CAAC;IAC9D,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KAAK,KAAK,CAAC;YACX,OAAO,IAAI,CAAC;QAChB,CAAC;IACL,CAAC;IAED;;;;;;OAMG;IACK,gBAAgB,CAAC,GAAgB;QACrC,MAAM,KAAK,GAAG,IAAI,CAAC,SAAS,CAAC,eAAe,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC,MAAM,CAAC;QACvE,IAAI,KAAK,GAAG,IAAI,CAAC,YAAY;YAAE,OAAO,IAAI,CAAC;QAE3C,MAAM,KAAK,GAAG,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAAC,CAAC;QAC5C,IAAI,CAAC,KAAK;YAAE,OAAO,IAAI,CAAC;QAExB,IAAI,CAAC,gBAAgB,GAAG,KAAK,CAAC;QAE9B,OAAO,IAAI,iBAAC,CAAC,CAAC,EAAE,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,YAAY,MAAM,CAAC,KAAK,CAAC,kEAAkE,GAAG,MAAM,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,wBAAwB,CAAC,CAAC;IAClM,CAAC;CACJ;AAtUD,0DAsUC","sourcesContent":["import { execSync } from 'child_process';\n\nimport { BranchCreationGuardConfig, Option } from '@webpieces/rules-config';\nimport { BranchIdentity, DeletableBranch, MergedBranchesCache, MergedBranchesService, WorktreeService, readMainSyncStatus } from '@webpieces/repo-workflow-core';\n\nimport type { BashContext, Violation } from '../types';\nimport { Violation as V } from '../types';\nimport { BashRuleBase } from '../rule-base';\nimport { FixHint } from '../fix-hint';\nimport { CapRemedies } from './cap-remedies';\nimport { toError } from '../to-error';\n\n// Defaults used when the rule has no explicit value in webpieces.config.json.\n// branchFormat is a human sentence telling the AI how to name a branch created off main; it is\n// intentionally NOT the sub-branch convention (sub-branches are a separate, human-approved path).\nconst DEFAULT_BRANCH_FORMAT = 'Name it {whoami}/<short-feature-description> — lowercase, no version numbers, no sub/ prefix (e.g. dean/upgrade-webpieces)';\n\n// Hard cap on local feature branches. Enforced at CREATION because that is the one moment cleanup is\n// both cheap and obviously worth it — reaping happens over time, never \"ASAP\".\n//\n// The branch cap counts PARKED branches only — branches not checked out in any worktree. Worktree-held\n// branches are counted by the worktree cap instead. Two budgets, because they are not substitutes: if\n// held branches also spent the branch budget, five worktrees would leave room for zero branches and no\n// branch could ever be created again.\nconst DEFAULT_MAX_LOCAL_BRANCHES = 5;\nconst DEFAULT_MAX_WORKTREES = 5;\n\n// A plausible git ref name. Deliberately NOT `[^\\s-]` — that class matches shell metacharacters, so\n// `git branch | wc -l` (a read-only LISTING, piped) was parsed as \"create a branch named `|`\" and\n// blocked. Cleanup work necessarily reads and deletes branches, so a listing must never trip this.\nconst REF_NAME = String.raw`[A-Za-z0-9][A-Za-z0-9_./-]*`;\n\nconst BRANCH_PATTERNS: RegExp[] = [\n new RegExp(String.raw`git\\s+checkout\\s+-[bB]\\s+(${REF_NAME})`),\n new RegExp(String.raw`git\\s+switch\\s+-[cC]\\s+(${REF_NAME})`),\n new RegExp(String.raw`git\\s+branch\\s+(?!-)(${REF_NAME})`),\n // `git worktree add ../dir -b <name> origin/main` — the form docs/git-workflow.md recommends for\n // starting a feature. It creates a branch just as surely as `checkout -b` does, and until this\n // pattern existed it walked straight past the cap, the reserved-suffix check and the sub-branch\n // check. `(?:\\S+\\s+)*?` absorbs the path and any other flags, so the -b may precede or follow them.\n new RegExp(String.raw`git\\s+worktree\\s+add\\s+(?:\\S+\\s+)*?-[bB]\\s+(${REF_NAME})`),\n];\n\n// ANY worktree creation, with or without -b. The no-`-b` forms (`git worktree add ../dir existing`,\n// `--detach`) create no branch but DO create a worktree, so they spend the worktree budget and must\n// still hit the cap.\nconst WORKTREE_ADD = /git\\s+worktree\\s+add\\b/;\n\n// `git worktree add <path> <existing-branch>` — the checkout-an-existing-branch form. Captures the\n// LAST bare (non-flag) argument, which is the committish; the first bare argument is the path.\n// Flags that take a value (`--reason <s>`, `-b <name>`) are excluded by the caller, which only uses\n// this on commands with no `-b`/`-B` at all.\nconst WORKTREE_ADD_EXISTING = new RegExp(String.raw`git\\s+worktree\\s+add\\s+(?:-{1,2}[A-Za-z-]+\\s+)*\\S+\\s+(${REF_NAME})`);\n\n// `git branch <name> <sha>` — RESTORING a branch at an explicit commit, which is exactly the\n// `recover=` command wp-cleanup writes to branch-mutations.log for every branch it reaps.\n//\n// This must be allowed UNCONDITIONALLY, ahead of even the caps. The entire argument for letting the\n// tooling delete branches unattended is that any delete is one logged command away from being undone\n// — so a guard that blocks that command turns a real guarantee into a decorative one. (It did: the\n// generic `git branch <name>` creation pattern matched the restore and refused it, demanding the\n// branch be recreated off origin/main, which is precisely the content the restore is meant to bring\n// back.) A restore also cannot grow the branch list beyond what already existed.\nconst RESTORE_AT_SHA = new RegExp(String.raw`git\\s+branch\\s+${REF_NAME}\\s+[0-9a-f]{7,40}(?:\\W|$)`);\n\n// A trailing `wp<number>` was the old squash-merge generation marker (base → basewp2 → basewp3).\n// The tooling NO LONGER produces it — a sync now lands back on the same feature name — but the suffix\n// stays RESERVED so a human branch can't collide with a leftover `…wpN` still floating in a consumer\n// repo mid-transition. Block it at creation time and steer the name back to the plain feature form.\nconst RESERVED_GENERATION_SUFFIX = /wp\\d+$/;\n\n// A branch-creation command that explicitly bases off origin/main (e.g. `git checkout -b feat\n// origin/main`). This is exactly the fresh-main base the guard wants, and it works from ANY current\n// branch or linked worktree — main need not (and in a worktree cannot) be checked out here. Allowed\n// unconditionally so the recovery messages can safely tell you to run it from a worktree.\n//\n// The trailing check is `\\W|$`, not `\\s|$`: the ALLOW pattern must not be stricter about delimiters\n// than the BLOCK pattern above, or a `git checkout -b x origin/main` that ends at a quote or backtick\n// is seen as a branch creation but NOT as an origin/main one — recognised, then wrongly blocked.\nconst ORIGIN_MAIN_BASE = /git\\s+(?:checkout\\s+-[bB]|switch\\s+-[cC])\\s+\\S+\\s+origin\\/main(?:\\W|$)/;\n\n// The worktree arm of the same allow: `git worktree add ../dir -b <name> origin/main`. Same fresh-main\n// base, same reasoning — and in a worktree it is the ONLY workable base, since `git checkout main`\n// fatals there. Kept separate from ORIGIN_MAIN_BASE because the argument shape differs (a path sits\n// between the subcommand and the flags).\nconst WORKTREE_ORIGIN_MAIN_BASE = /git\\s+worktree\\s+add\\s+(?:\\S+\\s+)*origin\\/main(?:\\W|$)/;\n\nfunction extractBranchName(command: string): string | null {\n for (const pattern of BRANCH_PATTERNS) {\n const m = pattern.exec(command);\n if (m) return m[1];\n }\n return null;\n}\n\nfunction truncate(s: string): string {\n const MAX = 120;\n return s.length <= MAX ? s : s.slice(0, MAX) + '…';\n}\n\nfunction checkMainIsUpToDate(ctx: BashContext, requestedName: string): readonly Violation[] {\n // `--no-write-fetch-head` for the same reason as the background refresher (see\n // MainSyncStatusService.fetchOriginMain): this refresh can run while the agent is mid\n // `git fetch`/`git pull`, and two overlapping writers of the unlocked `.git/FETCH_HEAD` can leave\n // a duplicate for-merge line that makes the agent's `git pull` fatal with \"multiple branches\". We\n // read `origin/main` below, never FETCH_HEAD. On a git too old for the flag, retry the plain form.\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n execSync('git fetch --no-write-fetch-head origin main --quiet', {\n cwd: ctx.workspaceRoot,\n encoding: 'utf8',\n });\n } catch (err: unknown) {\n const error = toError(err);\n const text = error.message.toLowerCase();\n const tooOld = text.includes('unknown option') || text.includes('unknown switch') || text.includes('unrecognized option');\n if (!tooOld) throw error;\n execSync('git fetch origin main --quiet', { cwd: ctx.workspaceRoot, encoding: 'utf8' });\n }\n const countStr = execSync('git rev-list HEAD..origin/main --count', {\n cwd: ctx.workspaceRoot,\n encoding: 'utf8',\n }).trim();\n const count = parseInt(countStr, 10);\n if (count > 0) {\n return [new V(1, truncate(ctx.command), `Local main is ${count} commit(s) behind origin/main. Run 'git pull origin main' first, then retry creating branch '${requestedName}'.`)];\n }\n return [];\n}\n\nexport class BranchCreationGuardRule extends BashRuleBase<BranchCreationGuardConfig> {\n constructor(config: BranchCreationGuardConfig) {\n super(config, 'branch-creation-guard', 'branch-creation-guard');\n }\n\n readonly description = 'Block new-branch and new-worktree creation when main is stale, when branching off a non-main ' + 'branch, or when the branch/worktree count is at its cap (forces cleanup of dead ones).';\n override readonly defaultOptions = {\n branchFormat: DEFAULT_BRANCH_FORMAT,\n maxLocalBranches: DEFAULT_MAX_LOCAL_BRANCHES,\n maxWorktrees: DEFAULT_MAX_WORKTREES,\n };\n\n private readonly worktrees = new WorktreeService();\n private readonly mergedBranches = new MergedBranchesService(this.worktrees);\n private readonly branchIdentity = new BranchIdentity();\n\n // Set by check() when (and only when) a cap is what blocked, so fixHint can render the reap\n // instructions instead of the branch-naming ones. Same instance-field handoff pr-merge-guard uses.\n // Two fields, because the two caps reap different things and their hints share no wording.\n private capCache: MergedBranchesCache | null = null;\n private worktreeCapCache: MergedBranchesCache | null = null;\n\n // True when the blocked command was a `git worktree add`, so the recovery command we hand back is\n // a worktree command and not a `git checkout -b` the user cannot use here.\n private worktreeAdd = false;\n\n private get branchFormat(): string {\n return this.config.branchFormat ?? DEFAULT_BRANCH_FORMAT;\n }\n\n // No `??` fallback: `subBranchNaming` is schema-REQUIRED (#1017), so a config that reached here\n // stated it. A default here would be the framework choosing a consumer's branch convention.\n private get subBranchNaming(): string {\n return this.config.subBranchNaming;\n }\n\n private get maxLocalBranches(): number {\n return this.config.maxLocalBranches ?? DEFAULT_MAX_LOCAL_BRANCHES;\n }\n\n private get maxWorktrees(): number {\n return this.config.maxWorktrees ?? DEFAULT_MAX_WORKTREES;\n }\n\n // The recovery command for \"base this off fresh main\", in the flavour of whatever was blocked.\n private freshMainCommand(name: string): string {\n return this.worktreeAdd ? `git fetch origin main && git worktree add ../${name.replace(/\\//g, '-')} -b ${name} origin/main` : `git fetch origin main && git checkout -b ${name} origin/main`;\n }\n\n // Mode-aware fix hints. Branches off main follow branchFormat — never the sub-branch\n // convention. The sub-branch affordance only appears under mode 'ON'; 'ON_NO_SUBBRANCHES'\n // hard-blocks it and points instead at the turnOffRuleUntilEpoch escape hatch.\n get fixHint(): FixHint {\n const remedies = new CapRemedies();\n if (this.worktreeCapCache) return remedies.worktreeCap();\n if (this.capCache) return remedies.branchCap();\n\n const create = this.worktreeAdd ? 'Create it off fresh main: git fetch origin main && git worktree add ../<dir> -b <name> origin/main' : 'Create it off fresh main from anywhere (incl. a worktree): git fetch origin main && git checkout -b <name> origin/main';\n\n const options = [new Option(create, true), new Option(`Name a branch off main per branch-creation-guard.branchFormat: ${this.branchFormat}`)];\n if (this.config.mode === 'ON_NO_SUBBRANCHES') {\n options.push(new Option('Sub-branches (branching off another feature branch) are disabled. To temporarily allow one, set ' + 'branch-creation-guard.turnOffRuleUntilEpoch to a future epoch in webpieces.config.json'));\n } else {\n options.push(new Option(`If you truly need a stacked sub-branch (requires human approval), name it per branch-creation-guard.subBranchNaming: ${this.subBranchNaming}`));\n }\n return new FixHint('Cannot create this branch (main is stale, or branching off a non-main branch).', 'Create your branch from an up-to-date main. Pick one:', options);\n }\n\n /**\n * Strip the parts of a shell command that are DATA rather than executable commands, so the guard\n * stops reading prose as instructions.\n *\n * This guard regex-scans the raw command string and has no notion of quoting, so\n * `git commit -m \"... git checkout -b foo ...\"` — or any heredoc commit message that mentions a\n * branch command — was parsed as an actual branch creation and blocked. That bit three separate\n * times while building the branch cap, including on the cap's own commit. It matters far more now\n * that the cap check runs BEFORE the origin/main allow: at the cap, a merely-MENTIONED branch\n * command would block your commit.\n *\n * A quoted span whose content has no whitespace is kept verbatim (it is a single token — the name\n * in `git checkout -b \"dean/foo\"`), so quoting a branch name cannot smuggle a creation past the\n * guard. Anything with whitespace inside quotes is prose, and collapses to a space.\n */\n check(ctx: BashContext): readonly Violation[] {\n this.capCache = this.worktreeCapCache = null;\n // Match against the command with heredoc bodies and prose-in-quotes removed (BashContext\n // computes it for every guard now — this rule's private copy was the original).\n const command = ctx.commandCode;\n const requestedName = extractBranchName(command);\n this.worktreeAdd = WORKTREE_ADD.test(command);\n\n // A worktree add with no -b creates no branch, but it DOES spend the worktree budget, so it must\n // survive this early-out and reach the worktree cap below.\n if (!requestedName && !this.worktreeAdd) return [];\n\n // Restoring a reaped branch at its logged SHA is undo, not creation — always allowed, and\n // checked before the caps so a full branch list can never trap you on the recovery path.\n if (!this.worktreeAdd && RESTORE_AT_SHA.test(command)) return [];\n\n const reserved = this.checkReservedSuffix(ctx, requestedName);\n if (reserved) return [reserved];\n\n const capViolation = this.checkCaps(ctx, requestedName !== null);\n if (capViolation) return [capViolation];\n\n // `git worktree add` of an EXISTING branch (or --detach) creates no branch, so the naming and\n // fresh-main rules below do not apply — but one thing still does: the branch may be DEAD.\n if (!requestedName) return this.checkWorktreeOntoDeadBranch(ctx, command);\n\n // Explicitly basing off origin/main is always allowed — it creates the branch from fresh main\n // regardless of the current branch, and is the ONLY way that also works inside a linked worktree\n // (where `git checkout main` fatals). Reserved-name check above still applies.\n if (ORIGIN_MAIN_BASE.test(command)) return [];\n if (this.worktreeAdd && WORKTREE_ORIGIN_MAIN_BASE.test(command)) return [];\n\n // The exact `/hotfix/` convention explicitly authorizes a nested emergency branch.\n if (this.branchIdentity.isHotfix(requestedName)) return [];\n\n const currentBranch = execSync('git rev-parse --abbrev-ref HEAD', {\n cwd: ctx.workspaceRoot,\n encoding: 'utf8',\n }).trim();\n\n if (currentBranch === 'main') {\n return checkMainIsUpToDate(ctx, requestedName);\n }\n\n // Not on main: creating this branch would stack it on a feature branch (a sub-branch).\n if (this.config.mode === 'ON_NO_SUBBRANCHES') {\n return [\n new V(\n 1,\n truncate(ctx.command),\n `You are on '${currentBranch}', not main. Create the branch OFF origin/main instead of ` +\n `stacking it on this branch: ${this.freshMainCommand(requestedName)} ` +\n `(works here and inside a worktree). ${this.branchFormat}. ` +\n `You can temporarily turn this off if you truly need a sub-branch by setting ` +\n `branch-creation-guard.turnOffRuleUntilEpoch (a future epoch) in webpieces.config.json.`,\n ),\n ];\n }\n\n return [\n new V(\n 1,\n truncate(ctx.command),\n `You are on '${currentBranch}', not main. Branches must be created from fresh main: ` +\n `${this.freshMainCommand(requestedName)}. ${this.branchFormat}. ` +\n `If you truly need a stacked sub-branch (requires human approval), name it per ` +\n `branch-creation-guard.subBranchNaming ('${this.subBranchNaming}').`,\n ),\n ];\n }\n\n /**\n * `git worktree add ../dir <existing-branch>` onto a branch whose PR is ALREADY MERGED.\n *\n * The count caps never catch this: the command creates no branch, and if you are under the\n * worktree cap it sails straight through — materialising a fresh directory full of PRE-MERGE\n * code that the AI will then read, plan from and edit. read-stale-guard blocks the reads and\n * feature-branch-guard blocks the edits once you are in there, but that is a turn wasted per\n * tool call. Refuse at the moment of creation instead, using the SAME merged-PR proof the caps\n * already have precomputed on disk.\n *\n * Fails OPEN exactly like both caps: no cache (fresh clone, no `gh`, refresher hasn't run) or an\n * unparseable command → no opinion.\n */\n private checkWorktreeOntoDeadBranch(ctx: BashContext, command: string): readonly Violation[] {\n if (!this.worktreeAdd) return [];\n\n const match = WORKTREE_ADD_EXISTING.exec(command);\n if (!match) return [];\n const branch = match[1];\n // `origin/main` (and any remote-tracking ref) is the RECOMMENDED base, never a dead branch.\n if (branch.startsWith('origin/')) return [];\n\n const cache = this.mergedBranches.readMergedBranches(ctx.workspaceRoot);\n if (!cache) return [];\n\n const dead = cache.deletable.find((entry: DeletableBranch): boolean => entry.branch === branch);\n if (!dead) return [];\n\n const dir = branch.replace(/\\//g, '-');\n return [\n new V(\n 1,\n truncate(ctx.command),\n `Branch '${branch}' is dead — ${dead.reason}. A worktree on it would be a directory full of ` +\n `PRE-MERGE code: everything you read there is stale relative to origin/main (read-stale-guard ` +\n `blocks those reads) and every edit is blocked by feature-branch-guard. Base the new worktree ` +\n `on fresh main instead: git fetch origin main && git worktree add ../${dir} -b <new-branch> origin/main`,\n ),\n ];\n }\n\n // The reserved `…wpN` generation suffix — see RESERVED_GENERATION_SUFFIX for why it stays blocked\n // even though the tooling no longer produces it.\n private checkReservedSuffix(ctx: BashContext, requestedName: string | null): Violation | null {\n if (!requestedName || !RESERVED_GENERATION_SUFFIX.test(requestedName)) return null;\n return new V(1, truncate(ctx.command), `Branch name '${requestedName}' ends in 'wp<number>', which is reserved for the ` + `squash-merge tool's generation marker (base → basewp2 → basewp3). ` + `Rename it to a plain feature branch. ${this.branchFormat}.`);\n }\n\n /**\n * Both budgets, in the order that produces the most useful complaint.\n *\n * Called BEFORE the origin/main allow in check() — `... -b <name> origin/main` is the normal,\n * always-permitted path, so a cap checked after it would never once fire.\n *\n * Worktree cap first: a `git worktree add -b` spends BOTH budgets, and when both are full the\n * worktree is the thing the command was actually trying to make, so it is the thing to talk about.\n */\n private checkCaps(ctx: BashContext, createsBranch: boolean): Violation | null {\n if (this.worktreeAdd) {\n const worktreeViolation = this.checkWorktreeCap(ctx);\n if (worktreeViolation) return worktreeViolation;\n }\n if (createsBranch) return this.checkBranchCap(ctx);\n return null;\n }\n\n /**\n * The cap. Blocks branch #N+1 until already-merged branches are reaped, which is the ONLY thing\n * keeping the local branch list bounded.\n *\n * Fails OPEN when the cache is absent (fresh clone, `gh` unavailable, refresher hasn't run yet):\n * never block on data we don't have. The detached refresher regenerates it within one hook call,\n * so the cap starts enforcing on its own.\n */\n private checkBranchCap(ctx: BashContext): Violation | null {\n // PARKED branches only — a branch checked out in a worktree is the worktree cap's problem, and\n // counting it twice would let five worktrees exhaust the branch budget on their own.\n const held = this.worktrees.heldBranches(ctx.workspaceRoot);\n const parked = this.mergedBranches.localBranches(ctx.workspaceRoot).filter((branch: string): boolean => !held.has(branch));\n const count = parked.length;\n const cap = this.effectiveBranchCap(ctx);\n if (count < cap) return null;\n\n const cache = this.loadReconciledCache(ctx);\n if (!cache) return null;\n\n this.capCache = cache;\n\n // No count of \"how many are dead\" any more. It was read off a cache that is stale BY DESIGN,\n // so every branch of that sentence had to hedge (\"None of them are dead\", \"NOT known right\n // now — the cached verdicts are stale\"), and none of the three variants changed the next\n // move: run pnpm wp-cleanup, which recomputes from scratch. Say the one thing that is true.\n return new V(1, truncate(ctx.command), `You have ${String(count)} parked local branches (worktree-held ones not counted); the cap ` + `(branch-creation-guard.maxLocalBranches) is ${String(this.maxLocalBranches)}. Run pnpm wp-cleanup.`);\n }\n\n /**\n * The cache, with entries for branches/worktrees that no longer exist dropped.\n *\n * Reconciling is the fix for the phantom count: the file is written by a detached refresher and is\n * DELIBERATELY allowed to go stale, so it keeps naming branches deleted minutes ago and worktrees\n * already removed. Quoting it verbatim is how the guard announced \"8 parked local branches … none of\n * them are dead\" over a repo that had ONE, and then blocked a legitimate `git worktree add` on that\n * figure. `reconcile` re-checks existence with instant local git reads; it does NOT re-derive any\n * verdict (that needs the network and belongs in the refresher).\n *\n * Its AGE is no longer read here. The cap messages stopped quoting verdict counts entirely, so\n * there is nothing left for a freshness caveat to qualify — `wp-cleanup` recomputes from scratch.\n */\n private loadReconciledCache(ctx: BashContext): MergedBranchesCache | null {\n const raw = this.mergedBranches.readMergedBranches(ctx.workspaceRoot);\n if (!raw) return null;\n return this.mergedBranches.reconcile(ctx.workspaceRoot, raw);\n }\n\n /**\n * The branch cap, yielding by ONE when the agent is standing on an already-merged branch.\n *\n * Two individually-correct guards were composing into a trap: merged-branch-bash-guard blocks\n * almost all Bash until you get off a merged branch, and the ONLY way off it that guard advertises\n * is creating a fresh branch — which this cap then refused. Every printed exit led to editing\n * webpieces.config.json, and that is what an unsupervised agent did.\n *\n * One over cap, and only while a merged branch is what is pushing you: the branch about to be\n * created replaces a branch that is already dead, so the steady-state count does not grow. The cap\n * still fires on the NEXT creation, so this defers the cleanup by exactly one branch, never skips it.\n *\n * Fails toward the strict cap: no cache, a cache for another branch, or a clean branch → no yield.\n */\n private effectiveBranchCap(ctx: BashContext): number {\n // The cache is branch-keyed, so the branch we are standing on is what we look the entry up by.\n // A branch the last refresh never saw misses (null) → the strict cap, as before.\n const current = this.currentBranchOrNull(ctx.workspaceRoot);\n if (current === null) return this.maxLocalBranches;\n const status = readMainSyncStatus(ctx.workspaceRoot, current);\n if (status === null || !status.branchAlreadyMerged) return this.maxLocalBranches;\n if (status.branch !== current) return this.maxLocalBranches;\n return this.maxLocalBranches + 1;\n }\n\n private currentBranchOrNull(workspaceRoot: string): string | null {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return execSync('git rev-parse --abbrev-ref HEAD', {\n cwd: workspaceRoot,\n encoding: 'utf8',\n stdio: ['pipe', 'pipe', 'pipe'],\n }).trim();\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n\n /**\n * The worktree cap — the second budget. Same gate, same fail-open rule as the branch cap: a\n * worktree list we cannot classify (no cache on disk) blocks nothing.\n *\n * Counts LINKED worktrees only. The primary clone is not a thing anyone can remove, so charging the\n * budget for it would just silently cost you one worktree.\n */\n private checkWorktreeCap(ctx: BashContext): Violation | null {\n const count = this.worktrees.linkedWorktrees(ctx.workspaceRoot).length;\n if (count < this.maxWorktrees) return null;\n\n const cache = this.loadReconciledCache(ctx);\n if (!cache) return null;\n\n this.worktreeCapCache = cache;\n\n return new V(1, truncate(ctx.command), `You have ${String(count)} linked worktrees; the cap (branch-creation-guard.maxWorktrees) ` + `is ${String(this.maxWorktrees)}. Run pnpm wp-cleanup.`);\n }\n}\n"]}
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.FeatureBranchGuardRule = void 0;
4
4
  const child_process_1 = require("child_process");
5
5
  const rules_config_1 = require("@webpieces/rules-config");
6
+ const repo_workflow_core_1 = require("@webpieces/repo-workflow-core");
6
7
  const types_1 = require("../types");
7
8
  const rule_base_1 = require("../rule-base");
8
9
  const fix_hint_1 = require("../fix-hint");
@@ -84,7 +85,7 @@ class FeatureBranchGuardRule extends rule_base_1.FileRuleBase {
84
85
  files = ['**/*'];
85
86
  defaultOptions = {
86
87
  branchNamingConvention: '{whoami}/{featurename}',
87
- hangTimeoutMinutes: rules_config_1.DEFAULT_HANG_TIMEOUT_MINUTES,
88
+ hangTimeoutMinutes: repo_workflow_core_1.DEFAULT_HANG_TIMEOUT_MINUTES,
88
89
  };
89
90
  fixHint = new fix_hint_1.FixHint('You are not on a clean, up-to-date feature branch.', 'You must be on a clean, up-to-date feature branch to edit code. Pick one:', [
90
91
  new rules_config_1.Option('On main → create a feature branch. Already merged → branch off fresh main.', true),
@@ -120,7 +121,7 @@ class FeatureBranchGuardRule extends rule_base_1.FileRuleBase {
120
121
  // Keep the cache warm for the next call. Detached; never blocks this edit. Rooted at the JUDGED
121
122
  // tree, so the refresher recomputes the entry this guard is about to read rather than a sibling's.
122
123
  (0, main_sync_refresh_1.triggerMainSyncRefresh)(judgedRoot, (0, main_sync_timeout_1.hangTimeoutOf)(this.config));
123
- const status = (0, rules_config_1.readMainSyncStatus)(judgedRoot, branch);
124
+ const status = (0, repo_workflow_core_1.readMainSyncStatus)(judgedRoot, branch);
124
125
  // No cache yet (first edit of the session) → allow; the refresh we just spawned populates it
125
126
  // for the next call. Fail-open: never block on missing data.
126
127
  if (status === null)
@@ -316,7 +317,7 @@ class FeatureBranchGuardRule extends rule_base_1.FileRuleBase {
316
317
  'No fork point with origin/main — main appears to have been merged into this branch,',
317
318
  'so a clean squash-merge is impossible. A human must redo the work on a fresh branch:',
318
319
  '',
319
- ...(0, rules_config_1.squashRecoverySteps)(judged.branch),
320
+ ...(0, repo_workflow_core_1.squashRecoverySteps)(judged.branch),
320
321
  judged.redirectNote([judged.pnpmCure('wp-start-update')]),
321
322
  ].join('\n');
322
323
  }
@@ -1 +1 @@
1
- {"version":3,"file":"feature-branch-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/ai-hook-rules/src/core/rules/feature-branch-guard.ts"],"names":[],"mappings":";;;AAAA,iDAAyC;AAEzC,0DAA0M;AAG1M,oCAA0C;AAC1C,4CAA4C;AAC5C,0CAAsC;AACtC,0CAAsC;AACtC,4DAA8D;AAC9D,4DAAqD;AACrD,kDAAwF;AACxF,oDAAuF;AACvF,sDAAkD;AAClD,gDAAoD;AACpD,mEAA8D;AAC9D,+CAA2C;AAC3C,mDAA+C;AAE/C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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import { execSync } from 'child_process';\n\nimport { BranchStateGuardConfig, BRANCH_STATE_GUARD_KEY, DEFAULT_HANG_TIMEOUT_MINUTES, readMainSyncStatus, squashRecoverySteps, MainSyncStatus, SyncFlowGuidance, Option } from '@webpieces/rules-config';\n\nimport type { FileContext, Violation } from '../types';\nimport { Violation as V } from '../types';\nimport { FileRuleBase } from '../rule-base';\nimport { FixHint } from '../fix-hint';\nimport { toError } from '../to-error';\nimport { triggerMainSyncRefresh } from '../main-sync-refresh';\nimport { hangTimeoutOf } from '../main-sync-timeout';\nimport { logGuardDecision, GuardDecision, Verdict, matrixL2Row } from '../decision-log';\nimport { writeBranchStateMatrixDoc, branchStateMatrixPointer } from '../l2-matrix-doc';\nimport { L0_FAULT_NONE } from '../l0-fault-codes';\nimport { TargetTreeResolver } from '../target-tree';\nimport { MergedBranchMessage } from './merged-branch-message';\nimport { JudgedTree } from './judged-tree';\nimport { TreeRecovery } from './tree-recovery';\n\n/**\n * Comprehensive \"are you on a proper feature branch?\" guard — the single rule that blocks edits when\n * the branch isn't a healthy place to work. Four states, in priority order:\n * 1. On main (checked SYNCHRONOUSLY here) → block: create a feature branch.\n * 2. Branch already merged into main (merged PR) → block: your work is in main, branch off fresh.\n * 3. No fork point with origin/main → block: squash onto a new branch.\n * 4. origin/main moved & touches your files → block: merge main first.\n * States 2–4 are PRECOMPUTED into `.webpieces/main-sync-status.json` by the detached refresher, so\n * this check does NO network git (only a fast local `git rev-parse` for state 1). On every call it\n * fire-and-forget spawns the refresher so the NEXT call is fresh. Runs in the GUARDS hook (it's a\n * hookGuard); file-scoped, so only Write/Edit/MultiEdit are guarded — Bash passes through so the AI\n * can still run `pnpm wp-start-upsert-pr` and the rest of the recovery flow.\n *\n * ── STATE 1 IS UNCONDITIONAL, AND `B` NO LONGER TRACKS `E` HERE ──────────────────────────────────\n *\n * Earlier docblocks in this family argued that the Bash half of \"on `main`\" should match this one\n * exactly — one `git rev-parse`, no cache, so it fires on the first call of a session. That argument\n * has been split, deliberately, and the two halves now differ:\n *\n * `E` (here) blocks on ANY `main`, current or stale.\n * `B` (stale-main-bash-guard) blocks only once local `main` is KNOWN BEHIND `origin/main`.\n *\n * The hazards are not the same hazard. A WRITE on `main` puts work where it cannot be reviewed, cannot\n * be reverted as a unit, and is one `git checkout` from being lost — none of which depends on how\n * current `main` is, so nothing about freshness could make this block right or wrong. A READ or a\n * BUILD on a CURRENT `main` harms nothing at all, and denying it strands the agent immediately after\n * `pnpm wp-sync-main` — the very command this repo prescribes — put it there.\n *\n * So do NOT \"restore the symmetry\" by gating this on the cache. That would make writes on `main`\n * permitted for the whole first call of every session (the cache is populated for the NEXT call), and\n * permanently in a multi-worktree repo where another tree can hold the refresh lock. That ordering is\n * the most load-bearing thing in the L2 table, which is why row 5 sits ABOVE the cache divider.\n *\n * ── WHICH TREE IS JUDGED: THE ONE THAT OWNS THE FILE, NEVER THE ONE THE SESSION SITS IN ─────────────\n *\n * Every state above is a property of A BRANCH IN A CHECKOUT, so the first question this guard answers is\n * WHICH checkout — and the answer comes from the TARGET PATH, through TargetTreeResolver, which is\n * EffectiveTreeResolver asked about a file instead of a cwd. It is emphatically NOT `ctx.workspaceRoot`:\n * that is the walk-up from the session's cwd to the governing `webpieces.config.json`, and for a\n * main-session edit into an agent worktree it names the PRIMARY clone.\n *\n * Issue #851 is the incident. Claude Code checks a worktree out INSIDE the repo at\n * `<repo>/.claude/worktrees/agent-XXXX`, so a containment test answers \"primary\" for a path that is\n * plainly the worktree's. This guard then read the branch-keyed main-sync cache under the PRIMARY's\n * branch and enforced that verdict on a file belonging to a clean branch in another tree. The cache was\n * not stale and was not wrong — the correct entry sat in the same JSON file, one key over. Only the\n * lookup key was. Four tool calls were refused, including the `summary.json` that `wp-review-upsert-pr`\n * requires before `wp-finish-upsert-pr` will open a PR, which is the shape where this wedges the\n * sanctioned flow rather than merely annoying somebody.\n *\n * Two consequences worth stating out loud, because both were argued the other way at some point:\n *\n * - The DENY NAMES THE TREE (JudgedTree.header) and, when the judged tree is not the session's, the\n * `pnpm --dir=<tree>` form of the cure. A resolution nobody can see is a resolution nobody can\n * contradict, and the printed cure was measurably a no-op for the tree it was aimed at.\n * - DETACHED HEAD in the target tree fails OPEN, logged. There is no branch name, so there is no map\n * key and nothing to judge — matrix row 14. It used to reach here as the literal branch `HEAD`, miss\n * in the cache and fail open as `no-sync-cache`, which is the right verdict recorded under a reason\n * that says something else happened.\n */\nexport class FeatureBranchGuardRule extends FileRuleBase<BranchStateGuardConfig> {\n // NAME is this class's operator identity (every `rule=` in the log, every deny header);\n // CONFIG KEY is the one branch-state policy entry all four of these guards read. See AbstractRule.\n constructor(config: BranchStateGuardConfig) { super(config, 'feature-branch-guard', BRANCH_STATE_GUARD_KEY); }\n\n readonly description = 'Block edits unless you are on a proper feature branch (not main, not already-merged, forked, in sync with main).';\n override readonly files = ['**/*'];\n override readonly defaultOptions = {\n branchNamingConvention: '{whoami}/{featurename}',\n hangTimeoutMinutes: DEFAULT_HANG_TIMEOUT_MINUTES,\n };\n readonly fixHint = new FixHint(\n 'You are not on a clean, up-to-date feature branch.',\n 'You must be on a clean, up-to-date feature branch to edit code. Pick one:',\n [\n new Option('On main → create a feature branch. Already merged → branch off fresh main.', true),\n new Option('main moved/conflicts, NO PR yet → `pnpm wp-start-update` (merge), `/wp-merge` (resolve), `pnpm wp-finish-update`. An OPEN PR? then you MUST use `pnpm wp-start-upsert-pr` → `/wp-merge` → `pnpm wp-finish-upsert-pr` (the merge rewrites the branch, so the PR must be re-pointed in the same run). Never mix a start from one pair with a finish from the other.'),\n new Option('Disable in webpieces.config.json under hookGuards → branch-state-guard (mode OFF) if intentional — that one key governs the Write, Read and Bash halves of this policy together.'),\n ],\n );\n\n check(ctx: FileContext): readonly Violation[] {\n // Only files inside the workspace root — guard has no jurisdiction, nothing worth logging.\n if (ctx.relativePath.startsWith('..')) return [];\n\n // WHICH CHECKOUT owns this file? Git's answer, via the resolver the bash half already uses —\n // never a path-containment test, which is exactly what answered \"primary\" for a worktree\n // checked out INSIDE the repo (issue #851, and this class's header).\n const target = new TargetTreeResolver().resolve(ctx.filePath, ctx.workspaceRoot);\n // A NESTED CLONE under `repositories/**` is somebody else's repo. The bash path calls this\n // ALLOW_EXEMPT; here it is an abstention, because the state was not established, not waived.\n if (target.kind === 'foreign') return this.failOpen(ctx, null, 'target-tree-foreign');\n\n const judgedRoot = target.root;\n const branch = this.currentBranch(judgedRoot);\n // Can't determine branch (e.g. not a git repo) → don't block. Fail-open.\n if (branch === null) return this.failOpen(ctx, branch, 'branch-undeterminable', this.treeSummary(judgedRoot));\n // Mid-rebase / mid-bisect: `--abbrev-ref HEAD` prints the literal `HEAD`, there is no branch\n // name, and therefore no key into the branch-keyed cache. Matrix row 14 — abstain, out loud.\n if (branch === 'HEAD') return this.failOpen(ctx, branch, 'detached-head', this.treeSummary(judgedRoot));\n\n const judged = new JudgedTree(target, branch, target.governedRoot);\n\n // State 1: on main — synchronous, no cache needed.\n if (branch === 'main') {\n return this.block(ctx, branch, 'on-main', this.onMainMessage(judged), this.treeSummary(judgedRoot));\n }\n\n // Keep the cache warm for the next call. Detached; never blocks this edit. Rooted at the JUDGED\n // tree, so the refresher recomputes the entry this guard is about to read rather than a sibling's.\n triggerMainSyncRefresh(judgedRoot, hangTimeoutOf(this.config));\n\n const status = readMainSyncStatus(judgedRoot, branch);\n // No cache yet (first edit of the session) → allow; the refresh we just spawned populates it\n // for the next call. Fail-open: never block on missing data.\n if (status === null) return this.failOpen(ctx, branch, 'no-sync-cache', 'cache=none');\n\n const cache = `${this.treeSummary(judgedRoot)} ${this.cacheSummary(status)}`;\n // BELT-AND-BRACES since the cache became branch-keyed: we looked this entry up BY `branch`, so\n // a mismatch now means the map's key and the entry's own `branch` field disagree — a shape bug,\n // not a normal state. Kept (rather than deleted) so such a bug degrades to an allow instead of\n // blocking on another branch's signals. Unreachable in normal operation.\n if (status.branch !== branch) return this.failOpen(ctx, branch, 'stale-cross-branch-cache', cache);\n\n // State 2: this feature branch was already merged into main.\n if (status.branchAlreadyMerged) {\n const pr = status.mergedPr !== '' ? status.mergedPr : '?';\n const merged = this.alreadyMergedMessage(judged, status.mergedPr);\n return this.block(ctx, branch, `already-merged PR#${pr}`, merged, cache);\n }\n // State 3: no fork point — main was merged into the branch.\n if (!status.hasForkPoint) {\n return this.block(ctx, branch, 'no-fork-point', this.noForkPointMessage(judged), cache);\n }\n // State 4: origin/main moved and touches files you changed.\n if (status.conflict) {\n return this.block(ctx, branch, 'main-moved-conflict', this.conflictMessage(judged, status.conflictFiles, status.openPr), cache);\n }\n // NOT-MERGED, or NOT-ASKED? `branchAlreadyMerged: false` is produced both by \"this branch has\n // no merged PR\" and by \"the forge could not be reached\" (`gh` missing, unauthenticated,\n // rate-limited, offline). Same allow either way — never block on data you could not establish\n // — but the LOG must not call the second one an approval, or the trail cannot tell a policy\n // that is protecting something from one that is quietly standing down.\n // Reached only when the branch is NOT merged, HAS a fork point and does NOT conflict. The\n // last two are pure git; only the first depends on the forge, which is why an unreachable\n // forge downgrades this to an abstention rather than leaving it a clean approval.\n if (!status.forgeReachable) return this.failOpen(ctx, branch, 'no-forge', cache);\n return this.allow(ctx, branch, 'clean-feature-branch', cache);\n }\n\n /**\n * WHICH TREE this decision was judged against, for the log.\n *\n * The trail already carried a `tree=` field, but it is stamped from the root the decision is LOGGED\n * to (the session's), so during issue #851 every misfired block recorded `tree=primary` for a path\n * under `.claude/worktrees/` and read as perfectly ordinary. This one is the root the verdict was\n * actually computed from, so the two disagreeing is the defect, visible in one grep.\n */\n private treeSummary(judgedRoot: string): string {\n return `judged=${judgedRoot}`;\n }\n\n // One-line summary of the async-written cache that drove this decision, for the SYNC log — so a\n // wrong allow/block is traceable to the exact (possibly stale) main-sync-status.json read.\n private cacheSummary(status: MainSyncStatus): string {\n const merged = status.branchAlreadyMerged ? `PR#${status.mergedPr !== '' ? status.mergedPr : '?'}` : 'no';\n return `cache=${status.branch} merged=${merged} fork=${String(status.hasForkPoint)} conflict=${String(status.conflict)} ts=${status.timestamp}`;\n }\n\n // Log + return for the allow path. Centralizes the decision-log call so every exit of check()\n // is recorded with its reason + the async cache it read (this is the audit trail for \"why didn't\n // the guard fire?\"). `cache` is the summary of the main-sync-status.json that drove the decision.\n /**\n * The guard could not ESTABLISH the state it judges on, so it judged nothing.\n *\n * A sibling of allow() rather than a reason string passed to it, because the difference has to\n * reach the LOG as a value: `ALLOW_FAIL_OPEN` vs `ALLOW`. It was previously a `' (fail-open)'`\n * suffix on the free-text reason, which meant an abstention and a real approval were the same\n * verdict and the abstentions could not be counted — so nobody could tell whether these guards\n * were protecting anything or quietly standing down. Never block on data you could not\n * establish; but say out loud, in a field, that you did not establish it.\n */\n private failOpen(ctx: FileContext, branch: string | null, reason: string, cache: string = '-'): readonly Violation[] {\n this.logDecision(ctx, branch, 'ALLOW_FAIL_OPEN', reason, cache);\n return [];\n }\n\n private allow(ctx: FileContext, branch: string | null, reason: string, cache: string = '-'): readonly Violation[] {\n this.logDecision(ctx, branch, 'ALLOW', reason, cache);\n return [];\n }\n\n private block(ctx: FileContext, branch: string, reason: string, message: string, cache: string = '-'): readonly Violation[] {\n this.logDecision(ctx, branch, 'BLOCK_AI_CURE', reason, cache);\n // Deliver the matrix and name the row — see stale-main-bash-guard.block for why it is lazy.\n const pointer = branchStateMatrixPointer(writeBranchStateMatrixDoc(ctx.workspaceRoot), matrixL2Row(reason).row);\n return [new V(1, ctx.relativePath, message + pointer)];\n }\n\n private logDecision(ctx: FileContext, branch: string | null, verdict: Verdict, reason: string, cache: string): void {\n logGuardDecision(\n ctx.workspaceRoot,\n new GuardDecision('feature-branch-guard', ctx.tool, ctx.relativePath, branch ?? 'unknown', verdict, reason, cache, L0_FAULT_NONE, matrixL2Row(reason)),\n );\n }\n\n private currentBranch(workspaceRoot: string): string | null {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return execSync('git rev-parse --abbrev-ref HEAD', {\n cwd: workspaceRoot,\n encoding: 'utf8',\n stdio: ['pipe', 'pipe', 'pipe'],\n }).trim();\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n\n /**\n * The Write/Edit half of row 5. Same three points as stale-main-bash-guard's deny, told for THIS\n * surface: reading main while you plan is legitimate and is not what got blocked; the feature\n * branch is the unit of work; and a `main` that is behind makes the reads wrong too, so getting\n * current is not an extra step, it is what makes the plan you are about to write against correct.\n *\n * Per-surface, deliberately: this guard sees only Write/Edit, so it says the WRITE was blocked.\n * (read-stale-guard is the one that can close Read, and only once `main` falls behind.)\n *\n * ONE CURE, and it is the dirty-safe one. This half used to print `git pull origin main` and then\n * \"create a feature branch\" — but this guard fires on a WRITE, so uncommitted work is the LIKELY\n * state, and a pull is exactly the form that is not a clean fast-forward there. Its two siblings\n * (stale-main-bash-guard's rows-6/7 deny, StaleMainMessage.forReads) both prescribe\n * `git fetch origin main && git checkout -b <new> origin/main`, which fetches AND carries the\n * uncommitted work onto the new branch. Three halves of one row printing one cure is the point:\n * a fragile cure is a defect here even when it often happens to work.\n */\n private onMainMessage(judged: JudgedTree): string {\n const convention = this.config.branchNamingConvention ?? '{whoami}/{featurename}';\n return [\n judged.header(),\n 'Blocked: this is a WRITE on main. Reading main to PLAN is fine — writing here is not, because the feature branch is the unit of work: reviewable, revertable, and not one `git checkout` from being lost.',\n 'And if local main is BEHIND origin/main, what you read here was out of date too — so the fetch below is not an extra step, it is what makes your reads true.',\n 'Branch off origin/main (it fetches first, and uncommitted work comes with you):',\n ' git fetch origin main && git checkout -b <new-branch> origin/main',\n `Name <new-branch> by the convention (from webpieces.config.json): ${convention}`,\n 'Example: git fetch origin main && git checkout -b ' + convention.replace(/<[^>]+>/g, 'value') + ' origin/main',\n judged.redirectNote([judged.cdCure('git fetch origin main && git checkout -b <new-branch> origin/main')]),\n ].join('\\n');\n }\n\n // Shared with read-stale-guard, which blocks READS in this same state — see MergedBranchMessage.\n // The tree kind picks the flavour of the cure: a dead LINKED WORKTREE is told to open a new\n // worktree off origin/main and reap this one; the primary clone is told to branch off origin/main.\n // Every one of those questions is asked of the JUDGED tree, not the session's: the branch that is\n // merged, the checkout to recover, and the directory the cure has to run in are all properties of\n // the tree that owns the file (issue #851).\n private alreadyMergedMessage(judged: JudgedTree, mergedPr: string): string {\n const body = new MergedBranchMessage(judged.root).forEdits(\n judged.branch, mergedPr, new TreeRecovery().kindOf(judged.root), judged.root,\n );\n // NO redirect note here, deliberately. MergedBranchMessage was built with the JUDGED root and\n // already aims every command it prints through `atRoot` — and it picks the WORKTREE flavour of\n // the cure (open a NEW worktree off origin/main and reap this dead one) when that is what the\n // tree is. Appending a generic `checkout -b` would contradict the paragraph directly above it,\n // in exactly the redirected-and-a-worktree case where the worktree flavour is the right advice.\n return [judged.header(), body].join('\\n');\n }\n\n private conflictMessage(judged: JudgedTree, conflictFiles: readonly string[], openPr: string): string {\n const files = conflictFiles.length > 0\n ? conflictFiles.map((f: string): string => ` - ${f}`).join('\\n')\n : ' (see git diff)';\n // NAME THE BRANCH AND THE TREE. Without them this read \"files you also changed\", listing files\n // the edit had never touched on a branch it was not on, and there was nothing in the text to\n // contradict — see JudgedTree.\n const header = [\n judged.header(),\n `origin/main moved and touched files that \\`${judged.branch}\\` also changed since its fork point:`,\n files,\n '',\n ];\n const redirect = judged.redirectNote([\n judged.pnpmCure('wp-start-update'),\n `${judged.pnpmCure('wp-start-upsert-pr')} (instead, when a PR is open)`,\n ]);\n // Steer EARLY: if a PR already tracks this branch, the update-only flow would just fail-fast\n // (a 3-point update strands the PR on the old branch generation), so recommend ONLY the PR\n // flow and don't waste the AI's tokens on wp-start-update.\n const guidance = new SyncFlowGuidance();\n // An OPEN PR removes the choice, so print ONLY the PR flow here — showing the update-only flow\n // as if it were an option just burns tokens on a command that fail-fasts.\n if (openPr !== '') {\n return header\n .concat([\n `An OPEN PR (#${openPr}) already tracks this branch, so the PR flow is the ONLY option`,\n 'here — it re-merges main AND re-points the PR in the same run:',\n '',\n ])\n .concat(guidance.prFlow())\n .concat(['', ...guidance.whyPrForcesFlowB()])\n .concat([redirect])\n .join('\\n');\n }\n return header\n .concat([\n 'You must merge main in before editing further. No PR is open for this branch, so flow A',\n 'below is the one to use — but use flow B the moment a PR exists:',\n '',\n ])\n .concat(guidance.flows())\n .concat([redirect])\n .join('\\n');\n }\n\n private noForkPointMessage(judged: JudgedTree): string {\n return [\n judged.header(),\n 'No fork point with origin/main — main appears to have been merged into this branch,',\n 'so a clean squash-merge is impossible. A human must redo the work on a fresh branch:',\n '',\n ...squashRecoverySteps(judged.branch),\n judged.redirectNote([judged.pnpmCure('wp-start-update')]),\n ].join('\\n');\n }\n}\n"]}
1
+ {"version":3,"file":"feature-branch-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/ai-hook-rules/src/core/rules/feature-branch-guard.ts"],"names":[],"mappings":";;;AAAA,iDAAyC;AAEzC,0DAAmH;AACnH,sEAAsI;AAGtI,oCAA0C;AAC1C,4CAA4C;AAC5C,0CAAsC;AACtC,0CAAsC;AACtC,4DAA8D;AAC9D,4DAAqD;AACrD,kDAAwF;AACxF,oDAAuF;AACvF,sDAAkD;AAClD,gDAAoD;AACpD,mEAA8D;AAC9D,+CAA2C;AAC3C,mDAA+C;AAE/C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2DG;AACH,MAAa,sBAAuB,SAAQ,wBAAoC;IAC5E,wFAAwF;IACxF,mGAAmG;IACnG,YAAY,MAA8B,IAAI,KAAK,CAAC,MAAM,EAAE,sBAAsB,EAAE,qCAAsB,CAAC,CAAC,CAAC,CAAC;IAErG,WAAW,GAAG,kHAAkH,CAAC;IACxH,KAAK,GAAG,CAAC,MAAM,CAAC,CAAC;IACjB,cAAc,GAAG;QAC/B,sBAAsB,EAAE,wBAAwB;QAChD,kBAAkB,EAAE,iDAA4B;KACnD,CAAC;IACO,OAAO,GAAG,IAAI,kBAAO,CAC1B,oDAAoD,EACpD,2EAA2E,EAC3E;QACI,IAAI,qBAAM,CAAC,4EAA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AAC;iBACD,MAAM,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC;iBACzB,MAAM,CAAC,CAAC,EAAE,EAAE,GAAG,QAAQ,CAAC,gBAAgB,EAAE,CAAC,CAAC;iBAC5C,MAAM,CAAC,CAAC,QAAQ,CAAC,CAAC;iBAClB,IAAI,CAAC,IAAI,CAAC,CAAC;QACpB,CAAC;QACD,OAAO,MAAM;aACR,MAAM,CAAC;YACJ,yFAAyF;YACzF,kEAAkE;YAClE,EAAE;SACL,CAAC;aACD,MAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;aACxB,MAAM,CAAC,CAAC,QAAQ,CAAC,CAAC;aAClB,IAAI,CAAC,IAAI,CAAC,CAAC;IACpB,CAAC;IAEO,kBAAkB,CAAC,MAAkB;QACzC,OAAO;YACH,MAAM,CAAC,MAAM,EAAE;YACf,qFAAqF;YACrF,sFAAsF;YACtF,EAAE;YACF,GAAG,IAAA,wCAAmB,EAAC,MAAM,CAAC,MAAM,CAAC;YACrC,MAAM,CAAC,YAAY,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,iBAAiB,CAAC,CAAC,CAAC;SAC5D,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACjB,CAAC;CACJ;AA1QD,wDA0QC","sourcesContent":["import { execSync } from 'child_process';\n\nimport { BranchStateGuardConfig, BRANCH_STATE_GUARD_KEY, SyncFlowGuidance, Option } from '@webpieces/rules-config';\nimport { DEFAULT_HANG_TIMEOUT_MINUTES, readMainSyncStatus, squashRecoverySteps, MainSyncStatus } from '@webpieces/repo-workflow-core';\n\nimport type { FileContext, Violation } from '../types';\nimport { Violation as V } from '../types';\nimport { FileRuleBase } from '../rule-base';\nimport { FixHint } from '../fix-hint';\nimport { toError } from '../to-error';\nimport { triggerMainSyncRefresh } from '../main-sync-refresh';\nimport { hangTimeoutOf } from '../main-sync-timeout';\nimport { logGuardDecision, GuardDecision, Verdict, matrixL2Row } from '../decision-log';\nimport { writeBranchStateMatrixDoc, branchStateMatrixPointer } from '../l2-matrix-doc';\nimport { L0_FAULT_NONE } from '../l0-fault-codes';\nimport { TargetTreeResolver } from '../target-tree';\nimport { MergedBranchMessage } from './merged-branch-message';\nimport { JudgedTree } from './judged-tree';\nimport { TreeRecovery } from './tree-recovery';\n\n/**\n * Comprehensive \"are you on a proper feature branch?\" guard — the single rule that blocks edits when\n * the branch isn't a healthy place to work. Four states, in priority order:\n * 1. On main (checked SYNCHRONOUSLY here) → block: create a feature branch.\n * 2. Branch already merged into main (merged PR) → block: your work is in main, branch off fresh.\n * 3. No fork point with origin/main → block: squash onto a new branch.\n * 4. origin/main moved & touches your files → block: merge main first.\n * States 2–4 are PRECOMPUTED into `.webpieces/main-sync-status.json` by the detached refresher, so\n * this check does NO network git (only a fast local `git rev-parse` for state 1). On every call it\n * fire-and-forget spawns the refresher so the NEXT call is fresh. Runs in the GUARDS hook (it's a\n * hookGuard); file-scoped, so only Write/Edit/MultiEdit are guarded — Bash passes through so the AI\n * can still run `pnpm wp-start-upsert-pr` and the rest of the recovery flow.\n *\n * ── STATE 1 IS UNCONDITIONAL, AND `B` NO LONGER TRACKS `E` HERE ──────────────────────────────────\n *\n * Earlier docblocks in this family argued that the Bash half of \"on `main`\" should match this one\n * exactly — one `git rev-parse`, no cache, so it fires on the first call of a session. That argument\n * has been split, deliberately, and the two halves now differ:\n *\n * `E` (here) blocks on ANY `main`, current or stale.\n * `B` (stale-main-bash-guard) blocks only once local `main` is KNOWN BEHIND `origin/main`.\n *\n * The hazards are not the same hazard. A WRITE on `main` puts work where it cannot be reviewed, cannot\n * be reverted as a unit, and is one `git checkout` from being lost — none of which depends on how\n * current `main` is, so nothing about freshness could make this block right or wrong. A READ or a\n * BUILD on a CURRENT `main` harms nothing at all, and denying it strands the agent immediately after\n * `pnpm wp-sync-main` — the very command this repo prescribes — put it there.\n *\n * So do NOT \"restore the symmetry\" by gating this on the cache. That would make writes on `main`\n * permitted for the whole first call of every session (the cache is populated for the NEXT call), and\n * permanently in a multi-worktree repo where another tree can hold the refresh lock. That ordering is\n * the most load-bearing thing in the L2 table, which is why row 5 sits ABOVE the cache divider.\n *\n * ── WHICH TREE IS JUDGED: THE ONE THAT OWNS THE FILE, NEVER THE ONE THE SESSION SITS IN ─────────────\n *\n * Every state above is a property of A BRANCH IN A CHECKOUT, so the first question this guard answers is\n * WHICH checkout — and the answer comes from the TARGET PATH, through TargetTreeResolver, which is\n * EffectiveTreeResolver asked about a file instead of a cwd. It is emphatically NOT `ctx.workspaceRoot`:\n * that is the walk-up from the session's cwd to the governing `webpieces.config.json`, and for a\n * main-session edit into an agent worktree it names the PRIMARY clone.\n *\n * Issue #851 is the incident. Claude Code checks a worktree out INSIDE the repo at\n * `<repo>/.claude/worktrees/agent-XXXX`, so a containment test answers \"primary\" for a path that is\n * plainly the worktree's. This guard then read the branch-keyed main-sync cache under the PRIMARY's\n * branch and enforced that verdict on a file belonging to a clean branch in another tree. The cache was\n * not stale and was not wrong — the correct entry sat in the same JSON file, one key over. Only the\n * lookup key was. Four tool calls were refused, including the `summary.json` that `wp-review-upsert-pr`\n * requires before `wp-finish-upsert-pr` will open a PR, which is the shape where this wedges the\n * sanctioned flow rather than merely annoying somebody.\n *\n * Two consequences worth stating out loud, because both were argued the other way at some point:\n *\n * - The DENY NAMES THE TREE (JudgedTree.header) and, when the judged tree is not the session's, the\n * `pnpm --dir=<tree>` form of the cure. A resolution nobody can see is a resolution nobody can\n * contradict, and the printed cure was measurably a no-op for the tree it was aimed at.\n * - DETACHED HEAD in the target tree fails OPEN, logged. There is no branch name, so there is no map\n * key and nothing to judge — matrix row 14. It used to reach here as the literal branch `HEAD`, miss\n * in the cache and fail open as `no-sync-cache`, which is the right verdict recorded under a reason\n * that says something else happened.\n */\nexport class FeatureBranchGuardRule extends FileRuleBase<BranchStateGuardConfig> {\n // NAME is this class's operator identity (every `rule=` in the log, every deny header);\n // CONFIG KEY is the one branch-state policy entry all four of these guards read. See AbstractRule.\n constructor(config: BranchStateGuardConfig) { super(config, 'feature-branch-guard', BRANCH_STATE_GUARD_KEY); }\n\n readonly description = 'Block edits unless you are on a proper feature branch (not main, not already-merged, forked, in sync with main).';\n override readonly files = ['**/*'];\n override readonly defaultOptions = {\n branchNamingConvention: '{whoami}/{featurename}',\n hangTimeoutMinutes: DEFAULT_HANG_TIMEOUT_MINUTES,\n };\n readonly fixHint = new FixHint(\n 'You are not on a clean, up-to-date feature branch.',\n 'You must be on a clean, up-to-date feature branch to edit code. Pick one:',\n [\n new Option('On main → create a feature branch. Already merged → branch off fresh main.', true),\n new Option('main moved/conflicts, NO PR yet → `pnpm wp-start-update` (merge), `/wp-merge` (resolve), `pnpm wp-finish-update`. An OPEN PR? then you MUST use `pnpm wp-start-upsert-pr` → `/wp-merge` → `pnpm wp-finish-upsert-pr` (the merge rewrites the branch, so the PR must be re-pointed in the same run). Never mix a start from one pair with a finish from the other.'),\n new Option('Disable in webpieces.config.json under hookGuards → branch-state-guard (mode OFF) if intentional — that one key governs the Write, Read and Bash halves of this policy together.'),\n ],\n );\n\n check(ctx: FileContext): readonly Violation[] {\n // Only files inside the workspace root — guard has no jurisdiction, nothing worth logging.\n if (ctx.relativePath.startsWith('..')) return [];\n\n // WHICH CHECKOUT owns this file? Git's answer, via the resolver the bash half already uses —\n // never a path-containment test, which is exactly what answered \"primary\" for a worktree\n // checked out INSIDE the repo (issue #851, and this class's header).\n const target = new TargetTreeResolver().resolve(ctx.filePath, ctx.workspaceRoot);\n // A NESTED CLONE under `repositories/**` is somebody else's repo. The bash path calls this\n // ALLOW_EXEMPT; here it is an abstention, because the state was not established, not waived.\n if (target.kind === 'foreign') return this.failOpen(ctx, null, 'target-tree-foreign');\n\n const judgedRoot = target.root;\n const branch = this.currentBranch(judgedRoot);\n // Can't determine branch (e.g. not a git repo) → don't block. Fail-open.\n if (branch === null) return this.failOpen(ctx, branch, 'branch-undeterminable', this.treeSummary(judgedRoot));\n // Mid-rebase / mid-bisect: `--abbrev-ref HEAD` prints the literal `HEAD`, there is no branch\n // name, and therefore no key into the branch-keyed cache. Matrix row 14 — abstain, out loud.\n if (branch === 'HEAD') return this.failOpen(ctx, branch, 'detached-head', this.treeSummary(judgedRoot));\n\n const judged = new JudgedTree(target, branch, target.governedRoot);\n\n // State 1: on main — synchronous, no cache needed.\n if (branch === 'main') {\n return this.block(ctx, branch, 'on-main', this.onMainMessage(judged), this.treeSummary(judgedRoot));\n }\n\n // Keep the cache warm for the next call. Detached; never blocks this edit. Rooted at the JUDGED\n // tree, so the refresher recomputes the entry this guard is about to read rather than a sibling's.\n triggerMainSyncRefresh(judgedRoot, hangTimeoutOf(this.config));\n\n const status = readMainSyncStatus(judgedRoot, branch);\n // No cache yet (first edit of the session) → allow; the refresh we just spawned populates it\n // for the next call. Fail-open: never block on missing data.\n if (status === null) return this.failOpen(ctx, branch, 'no-sync-cache', 'cache=none');\n\n const cache = `${this.treeSummary(judgedRoot)} ${this.cacheSummary(status)}`;\n // BELT-AND-BRACES since the cache became branch-keyed: we looked this entry up BY `branch`, so\n // a mismatch now means the map's key and the entry's own `branch` field disagree — a shape bug,\n // not a normal state. Kept (rather than deleted) so such a bug degrades to an allow instead of\n // blocking on another branch's signals. Unreachable in normal operation.\n if (status.branch !== branch) return this.failOpen(ctx, branch, 'stale-cross-branch-cache', cache);\n\n // State 2: this feature branch was already merged into main.\n if (status.branchAlreadyMerged) {\n const pr = status.mergedPr !== '' ? status.mergedPr : '?';\n const merged = this.alreadyMergedMessage(judged, status.mergedPr);\n return this.block(ctx, branch, `already-merged PR#${pr}`, merged, cache);\n }\n // State 3: no fork point — main was merged into the branch.\n if (!status.hasForkPoint) {\n return this.block(ctx, branch, 'no-fork-point', this.noForkPointMessage(judged), cache);\n }\n // State 4: origin/main moved and touches files you changed.\n if (status.conflict) {\n return this.block(ctx, branch, 'main-moved-conflict', this.conflictMessage(judged, status.conflictFiles, status.openPr), cache);\n }\n // NOT-MERGED, or NOT-ASKED? `branchAlreadyMerged: false` is produced both by \"this branch has\n // no merged PR\" and by \"the forge could not be reached\" (`gh` missing, unauthenticated,\n // rate-limited, offline). Same allow either way — never block on data you could not establish\n // — but the LOG must not call the second one an approval, or the trail cannot tell a policy\n // that is protecting something from one that is quietly standing down.\n // Reached only when the branch is NOT merged, HAS a fork point and does NOT conflict. The\n // last two are pure git; only the first depends on the forge, which is why an unreachable\n // forge downgrades this to an abstention rather than leaving it a clean approval.\n if (!status.forgeReachable) return this.failOpen(ctx, branch, 'no-forge', cache);\n return this.allow(ctx, branch, 'clean-feature-branch', cache);\n }\n\n /**\n * WHICH TREE this decision was judged against, for the log.\n *\n * The trail already carried a `tree=` field, but it is stamped from the root the decision is LOGGED\n * to (the session's), so during issue #851 every misfired block recorded `tree=primary` for a path\n * under `.claude/worktrees/` and read as perfectly ordinary. This one is the root the verdict was\n * actually computed from, so the two disagreeing is the defect, visible in one grep.\n */\n private treeSummary(judgedRoot: string): string {\n return `judged=${judgedRoot}`;\n }\n\n // One-line summary of the async-written cache that drove this decision, for the SYNC log — so a\n // wrong allow/block is traceable to the exact (possibly stale) main-sync-status.json read.\n private cacheSummary(status: MainSyncStatus): string {\n const merged = status.branchAlreadyMerged ? `PR#${status.mergedPr !== '' ? status.mergedPr : '?'}` : 'no';\n return `cache=${status.branch} merged=${merged} fork=${String(status.hasForkPoint)} conflict=${String(status.conflict)} ts=${status.timestamp}`;\n }\n\n // Log + return for the allow path. Centralizes the decision-log call so every exit of check()\n // is recorded with its reason + the async cache it read (this is the audit trail for \"why didn't\n // the guard fire?\"). `cache` is the summary of the main-sync-status.json that drove the decision.\n /**\n * The guard could not ESTABLISH the state it judges on, so it judged nothing.\n *\n * A sibling of allow() rather than a reason string passed to it, because the difference has to\n * reach the LOG as a value: `ALLOW_FAIL_OPEN` vs `ALLOW`. It was previously a `' (fail-open)'`\n * suffix on the free-text reason, which meant an abstention and a real approval were the same\n * verdict and the abstentions could not be counted — so nobody could tell whether these guards\n * were protecting anything or quietly standing down. Never block on data you could not\n * establish; but say out loud, in a field, that you did not establish it.\n */\n private failOpen(ctx: FileContext, branch: string | null, reason: string, cache: string = '-'): readonly Violation[] {\n this.logDecision(ctx, branch, 'ALLOW_FAIL_OPEN', reason, cache);\n return [];\n }\n\n private allow(ctx: FileContext, branch: string | null, reason: string, cache: string = '-'): readonly Violation[] {\n this.logDecision(ctx, branch, 'ALLOW', reason, cache);\n return [];\n }\n\n private block(ctx: FileContext, branch: string, reason: string, message: string, cache: string = '-'): readonly Violation[] {\n this.logDecision(ctx, branch, 'BLOCK_AI_CURE', reason, cache);\n // Deliver the matrix and name the row — see stale-main-bash-guard.block for why it is lazy.\n const pointer = branchStateMatrixPointer(writeBranchStateMatrixDoc(ctx.workspaceRoot), matrixL2Row(reason).row);\n return [new V(1, ctx.relativePath, message + pointer)];\n }\n\n private logDecision(ctx: FileContext, branch: string | null, verdict: Verdict, reason: string, cache: string): void {\n logGuardDecision(\n ctx.workspaceRoot,\n new GuardDecision('feature-branch-guard', ctx.tool, ctx.relativePath, branch ?? 'unknown', verdict, reason, cache, L0_FAULT_NONE, matrixL2Row(reason)),\n );\n }\n\n private currentBranch(workspaceRoot: string): string | null {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return execSync('git rev-parse --abbrev-ref HEAD', {\n cwd: workspaceRoot,\n encoding: 'utf8',\n stdio: ['pipe', 'pipe', 'pipe'],\n }).trim();\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n\n /**\n * The Write/Edit half of row 5. Same three points as stale-main-bash-guard's deny, told for THIS\n * surface: reading main while you plan is legitimate and is not what got blocked; the feature\n * branch is the unit of work; and a `main` that is behind makes the reads wrong too, so getting\n * current is not an extra step, it is what makes the plan you are about to write against correct.\n *\n * Per-surface, deliberately: this guard sees only Write/Edit, so it says the WRITE was blocked.\n * (read-stale-guard is the one that can close Read, and only once `main` falls behind.)\n *\n * ONE CURE, and it is the dirty-safe one. This half used to print `git pull origin main` and then\n * \"create a feature branch\" — but this guard fires on a WRITE, so uncommitted work is the LIKELY\n * state, and a pull is exactly the form that is not a clean fast-forward there. Its two siblings\n * (stale-main-bash-guard's rows-6/7 deny, StaleMainMessage.forReads) both prescribe\n * `git fetch origin main && git checkout -b <new> origin/main`, which fetches AND carries the\n * uncommitted work onto the new branch. Three halves of one row printing one cure is the point:\n * a fragile cure is a defect here even when it often happens to work.\n */\n private onMainMessage(judged: JudgedTree): string {\n const convention = this.config.branchNamingConvention ?? '{whoami}/{featurename}';\n return [\n judged.header(),\n 'Blocked: this is a WRITE on main. Reading main to PLAN is fine — writing here is not, because the feature branch is the unit of work: reviewable, revertable, and not one `git checkout` from being lost.',\n 'And if local main is BEHIND origin/main, what you read here was out of date too — so the fetch below is not an extra step, it is what makes your reads true.',\n 'Branch off origin/main (it fetches first, and uncommitted work comes with you):',\n ' git fetch origin main && git checkout -b <new-branch> origin/main',\n `Name <new-branch> by the convention (from webpieces.config.json): ${convention}`,\n 'Example: git fetch origin main && git checkout -b ' + convention.replace(/<[^>]+>/g, 'value') + ' origin/main',\n judged.redirectNote([judged.cdCure('git fetch origin main && git checkout -b <new-branch> origin/main')]),\n ].join('\\n');\n }\n\n // Shared with read-stale-guard, which blocks READS in this same state — see MergedBranchMessage.\n // The tree kind picks the flavour of the cure: a dead LINKED WORKTREE is told to open a new\n // worktree off origin/main and reap this one; the primary clone is told to branch off origin/main.\n // Every one of those questions is asked of the JUDGED tree, not the session's: the branch that is\n // merged, the checkout to recover, and the directory the cure has to run in are all properties of\n // the tree that owns the file (issue #851).\n private alreadyMergedMessage(judged: JudgedTree, mergedPr: string): string {\n const body = new MergedBranchMessage(judged.root).forEdits(\n judged.branch, mergedPr, new TreeRecovery().kindOf(judged.root), judged.root,\n );\n // NO redirect note here, deliberately. MergedBranchMessage was built with the JUDGED root and\n // already aims every command it prints through `atRoot` — and it picks the WORKTREE flavour of\n // the cure (open a NEW worktree off origin/main and reap this dead one) when that is what the\n // tree is. Appending a generic `checkout -b` would contradict the paragraph directly above it,\n // in exactly the redirected-and-a-worktree case where the worktree flavour is the right advice.\n return [judged.header(), body].join('\\n');\n }\n\n private conflictMessage(judged: JudgedTree, conflictFiles: readonly string[], openPr: string): string {\n const files = conflictFiles.length > 0\n ? conflictFiles.map((f: string): string => ` - ${f}`).join('\\n')\n : ' (see git diff)';\n // NAME THE BRANCH AND THE TREE. Without them this read \"files you also changed\", listing files\n // the edit had never touched on a branch it was not on, and there was nothing in the text to\n // contradict — see JudgedTree.\n const header = [\n judged.header(),\n `origin/main moved and touched files that \\`${judged.branch}\\` also changed since its fork point:`,\n files,\n '',\n ];\n const redirect = judged.redirectNote([\n judged.pnpmCure('wp-start-update'),\n `${judged.pnpmCure('wp-start-upsert-pr')} (instead, when a PR is open)`,\n ]);\n // Steer EARLY: if a PR already tracks this branch, the update-only flow would just fail-fast\n // (a 3-point update strands the PR on the old branch generation), so recommend ONLY the PR\n // flow and don't waste the AI's tokens on wp-start-update.\n const guidance = new SyncFlowGuidance();\n // An OPEN PR removes the choice, so print ONLY the PR flow here — showing the update-only flow\n // as if it were an option just burns tokens on a command that fail-fasts.\n if (openPr !== '') {\n return header\n .concat([\n `An OPEN PR (#${openPr}) already tracks this branch, so the PR flow is the ONLY option`,\n 'here — it re-merges main AND re-points the PR in the same run:',\n '',\n ])\n .concat(guidance.prFlow())\n .concat(['', ...guidance.whyPrForcesFlowB()])\n .concat([redirect])\n .join('\\n');\n }\n return header\n .concat([\n 'You must merge main in before editing further. No PR is open for this branch, so flow A',\n 'below is the one to use — but use flow B the moment a PR exists:',\n '',\n ])\n .concat(guidance.flows())\n .concat([redirect])\n .join('\\n');\n }\n\n private noForkPointMessage(judged: JudgedTree): string {\n return [\n judged.header(),\n 'No fork point with origin/main — main appears to have been merged into this branch,',\n 'so a clean squash-merge is impossible. A human must redo the work on a fresh branch:',\n '',\n ...squashRecoverySteps(judged.branch),\n judged.redirectNote([judged.pnpmCure('wp-start-update')]),\n ].join('\\n');\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { MainSyncStatus } from '@webpieces/rules-config';
1
+ import { MainSyncStatus } from '@webpieces/repo-workflow-core';
2
2
  /**
3
3
  * The two primitives every "is local `main` stale?" ladder is built out of: the ANCESTRY test, and the
4
4
  * one-line cache summary the decision log records beside the verdict.
@@ -1 +1 @@
1
- {"version":3,"file":"main-freshness.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/ai-hook-rules/src/core/rules/main-freshness.ts"],"names":[],"mappings":";;;AAAA,iDAA0C;AAI1C;;;;;;;;;;GAUG;AACH,MAAa,aAAa;IACtB,kGAAkG;IAClG,oBAAoB,CAAC,MAAsB,EAAE,gBAAwB;QACjE,MAAM,MAAM,GAAG,MAAM,CAAC,aAAa,CAAC;QACpC,IAAI,MAAM,KAAK,IAAI,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,MAAM,GAAG,CAAC;YAAE,OAAO,IAAI,CAAC;QAC5E,OAAO,MAAM,IAAI,gBAAgB,CAAC;IACtC,CAAC;IAED;;;;;;;;;;;;;;OAcG;IACH,kBAAkB,CAAC,aAAqB,EAAE,MAAc;QACpD,MAAM,MAAM,GAAG,IAAA,yBAAS,EAAC,KAAK,EAAE,CAAC,YAAY,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE;YAC7E,GAAG,EAAE,aAAa;YAClB,QAAQ,EAAE,MAAM;SACnB,CAAC,CAAC;QACH,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,IAAI,CAAC;QACrC,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,KAAK,CAAC;QACtC,OAAO,IAAI,CAAC,CAAC,4DAA4D;IAC7E,CAAC;IAED;;;OAGG;IACH,SAAS,CAAC,MAAsB;QAC5B,MAAM,MAAM,GAAG,MAAM,CAAC,mBAAmB,CAAC,CAAC,CAAC,MAAM,MAAM,CAAC,QAAQ,KAAK,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;QAC1G,MAAM,MAAM,GAAG,MAAM,CAAC,aAAa,KAAK,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;QAClF,OAAO,SAAS,MAAM,CAAC,MAAM,cAAc,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,eAAe,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,WAAW,MAAM,WAAW,MAAM,OAAO,MAAM,CAAC,SAAS,EAAE,CAAC;IACnL,CAAC;CACJ;AA1CD,sCA0CC","sourcesContent":["import { spawnSync } from 'child_process';\n\nimport { MainSyncStatus } from '@webpieces/rules-config';\n\n/**\n * The two primitives every \"is local `main` stale?\" ladder is built out of: the ANCESTRY test, and the\n * one-line cache summary the decision log records beside the verdict.\n *\n * ONE implementation, because two guards now ask the same question of the same cache —\n * `read-stale-guard` for the Read tool (rows 6/7) and `stale-main-bash-guard` for Bash. The ladders\n * themselves deliberately stay in the guards: each exit's `reason` string is a LITERAL there, which is\n * what `l2-matrix.spec.ts` scrapes to prove every exit maps to a row. What must not be written twice is\n * the predicate — a second copy of the ancestry rule is exactly how the two halves of one row start\n * disagreeing about whether a pull has landed.\n */\nexport class MainFreshness {\n /** Null means the async cache predates the count or could not establish it: callers fail open. */\n isWithinAllowedDrift(status: MainSyncStatus, maxCommitsBehind: number): boolean | null {\n const behind = status.commitsBehind;\n if (behind === null || !Number.isInteger(behind) || behind < 0) return null;\n return behind <= maxCommitsBehind;\n }\n\n /**\n * Is `commit` an ancestor of (i.e. already contained in) HEAD? Local-only and fast — no network.\n *\n * ANCESTRY, NOT HASH EQUALITY, and this is the single most important line in the freshness story.\n * The cached `originMain` is written by the detached refresher and is arbitrarily old, so\n * `local !== origin` stays true for a while AFTER a successful pull — which would spin the agent\n * forever against a hash nobody can reach. Asking \"does local main already CONTAIN the cached\n * origin/main?\" flips the instant the pull lands, with no refresher round-trip.\n *\n * spawnSync, not execSync, precisely because the EXIT CODE is the answer and three outcomes must be\n * told apart: 0 = ancestor (up to date), 1 = cleanly NOT an ancestor (genuinely behind), anything\n * else = git could not answer (bad/pruned object, not a repo) which must fail OPEN. execSync\n * collapses 1 and \"git broke\" into the same thrown Error, so it cannot make that call. The\n * arg-array form also means the commit hash is never parsed by a shell.\n */\n containsOriginMain(workspaceRoot: string, commit: string): boolean {\n const result = spawnSync('git', ['merge-base', '--is-ancestor', commit, 'HEAD'], {\n cwd: workspaceRoot,\n encoding: 'utf8',\n });\n if (result.status === 0) return true;\n if (result.status === 1) return false;\n return true; // unknown/failed → treat as \"contained\" so the guard allows\n }\n\n /**\n * The async-written cache that drove this decision, as one log field — so a wrong allow/block is\n * traceable to the exact (possibly stale) `main-sync-status.json` that produced it.\n */\n summarize(status: MainSyncStatus): string {\n const merged = status.branchAlreadyMerged ? `PR#${status.mergedPr !== '' ? status.mergedPr : '?'}` : 'no';\n const behind = status.commitsBehind === null ? '?' : String(status.commitsBehind);\n return `cache=${status.branch} localMain=${status.localMain.slice(0, 8)} originMain=${status.originMain.slice(0, 8)} behind=${behind} merged=${merged} ts=${status.timestamp}`;\n }\n}\n"]}
1
+ {"version":3,"file":"main-freshness.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/ai-hook-rules/src/core/rules/main-freshness.ts"],"names":[],"mappings":";;;AAAA,iDAA0C;AAI1C;;;;;;;;;;GAUG;AACH,MAAa,aAAa;IACtB,kGAAkG;IAClG,oBAAoB,CAAC,MAAsB,EAAE,gBAAwB;QACjE,MAAM,MAAM,GAAG,MAAM,CAAC,aAAa,CAAC;QACpC,IAAI,MAAM,KAAK,IAAI,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,MAAM,GAAG,CAAC;YAAE,OAAO,IAAI,CAAC;QAC5E,OAAO,MAAM,IAAI,gBAAgB,CAAC;IACtC,CAAC;IAED;;;;;;;;;;;;;;OAcG;IACH,kBAAkB,CAAC,aAAqB,EAAE,MAAc;QACpD,MAAM,MAAM,GAAG,IAAA,yBAAS,EAAC,KAAK,EAAE,CAAC,YAAY,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE;YAC7E,GAAG,EAAE,aAAa;YAClB,QAAQ,EAAE,MAAM;SACnB,CAAC,CAAC;QACH,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,IAAI,CAAC;QACrC,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,KAAK,CAAC;QACtC,OAAO,IAAI,CAAC,CAAC,4DAA4D;IAC7E,CAAC;IAED;;;OAGG;IACH,SAAS,CAAC,MAAsB;QAC5B,MAAM,MAAM,GAAG,MAAM,CAAC,mBAAmB,CAAC,CAAC,CAAC,MAAM,MAAM,CAAC,QAAQ,KAAK,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;QAC1G,MAAM,MAAM,GAAG,MAAM,CAAC,aAAa,KAAK,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;QAClF,OAAO,SAAS,MAAM,CAAC,MAAM,cAAc,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,eAAe,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,WAAW,MAAM,WAAW,MAAM,OAAO,MAAM,CAAC,SAAS,EAAE,CAAC;IACnL,CAAC;CACJ;AA1CD,sCA0CC","sourcesContent":["import { spawnSync } from 'child_process';\n\nimport { MainSyncStatus } from '@webpieces/repo-workflow-core';\n\n/**\n * The two primitives every \"is local `main` stale?\" ladder is built out of: the ANCESTRY test, and the\n * one-line cache summary the decision log records beside the verdict.\n *\n * ONE implementation, because two guards now ask the same question of the same cache —\n * `read-stale-guard` for the Read tool (rows 6/7) and `stale-main-bash-guard` for Bash. The ladders\n * themselves deliberately stay in the guards: each exit's `reason` string is a LITERAL there, which is\n * what `l2-matrix.spec.ts` scrapes to prove every exit maps to a row. What must not be written twice is\n * the predicate — a second copy of the ancestry rule is exactly how the two halves of one row start\n * disagreeing about whether a pull has landed.\n */\nexport class MainFreshness {\n /** Null means the async cache predates the count or could not establish it: callers fail open. */\n isWithinAllowedDrift(status: MainSyncStatus, maxCommitsBehind: number): boolean | null {\n const behind = status.commitsBehind;\n if (behind === null || !Number.isInteger(behind) || behind < 0) return null;\n return behind <= maxCommitsBehind;\n }\n\n /**\n * Is `commit` an ancestor of (i.e. already contained in) HEAD? Local-only and fast — no network.\n *\n * ANCESTRY, NOT HASH EQUALITY, and this is the single most important line in the freshness story.\n * The cached `originMain` is written by the detached refresher and is arbitrarily old, so\n * `local !== origin` stays true for a while AFTER a successful pull — which would spin the agent\n * forever against a hash nobody can reach. Asking \"does local main already CONTAIN the cached\n * origin/main?\" flips the instant the pull lands, with no refresher round-trip.\n *\n * spawnSync, not execSync, precisely because the EXIT CODE is the answer and three outcomes must be\n * told apart: 0 = ancestor (up to date), 1 = cleanly NOT an ancestor (genuinely behind), anything\n * else = git could not answer (bad/pruned object, not a repo) which must fail OPEN. execSync\n * collapses 1 and \"git broke\" into the same thrown Error, so it cannot make that call. The\n * arg-array form also means the commit hash is never parsed by a shell.\n */\n containsOriginMain(workspaceRoot: string, commit: string): boolean {\n const result = spawnSync('git', ['merge-base', '--is-ancestor', commit, 'HEAD'], {\n cwd: workspaceRoot,\n encoding: 'utf8',\n });\n if (result.status === 0) return true;\n if (result.status === 1) return false;\n return true; // unknown/failed → treat as \"contained\" so the guard allows\n }\n\n /**\n * The async-written cache that drove this decision, as one log field — so a wrong allow/block is\n * traceable to the exact (possibly stale) `main-sync-status.json` that produced it.\n */\n summarize(status: MainSyncStatus): string {\n const merged = status.branchAlreadyMerged ? `PR#${status.mergedPr !== '' ? status.mergedPr : '?'}` : 'no';\n const behind = status.commitsBehind === null ? '?' : String(status.commitsBehind);\n return `cache=${status.branch} localMain=${status.localMain.slice(0, 8)} originMain=${status.originMain.slice(0, 8)} behind=${behind} merged=${merged} ts=${status.timestamp}`;\n }\n}\n"]}
@@ -4,6 +4,7 @@ exports.MergeInProgressGuardRule = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const fs = tslib_1.__importStar(require("fs"));
6
6
  const path = tslib_1.__importStar(require("path"));
7
+ const tooling_common_1 = require("@webpieces/tooling-common");
7
8
  const rules_config_1 = require("@webpieces/rules-config");
8
9
  const types_1 = require("../types");
9
10
  const rule_base_1 = require("../rule-base");
@@ -73,7 +74,7 @@ function findUnvalidatedMerge(workspaceRoot) {
73
74
  // LOCAL scope: the merge this guard blocks on is the one THIS worktree started. Another
74
75
  // worktree's in-flight merge must not block commits here — that was never the intent, and under a
75
76
  // shared merge-info dir it would be the behaviour.
76
- return findMarkerUnder(rules_config_1.dotWebpieces.localFile(workspaceRoot, rules_config_1.MERGE_INFO_DIR), MARKER_SCAN_MAX_DEPTH);
77
+ return findMarkerUnder(tooling_common_1.dotWebpieces.localFile(workspaceRoot, rules_config_1.MERGE_INFO_DIR), MARKER_SCAN_MAX_DEPTH);
77
78
  }
78
79
  const SCANNER = new command_scan_1.CommandScanner();
79
80
  // Built from BLOCKED_GH_PR_SUBCOMMANDS so the enforcement and the sentence the fixHint prints can
@@ -1 +1 @@
1
- {"version":3,"file":"merge-in-progress-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/ai-hook-rules/src/core/rules/merge-in-progress-guard.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAE7B,0DAA+I;AAG/I,oCAA0C;AAC1C,4CAA4C;AAC5C,0CAAsC;AACtC,kDAAiD;AAGjD,oGAAoG;AACpG,iGAAiG;AACjG,qGAAqG;AACrG,wGAAwG;AACxG,oGAAoG;AACpG,4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C,MAAM,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,GAAG,GAAG,CAAC;AACvD,CAAC;AAED,MAAa,wBAAyB,SAAQ,wBAAoC;IAC9E;;;;;OAKG;IACc,oBAAoB,CAAS;IAE9C,YAAY,MAA8B,EAAE,oBAA4B;QACpE,KAAK,CAAC,MAAM,EAAE,yBAAyB,EAAE,qCAAsB,CAAC,CAAC;QACjE,IAAI,CAAC,oBAAoB,GAAG,oBAAoB,CAAC;IACrD,CAAC;IAEQ,WAAW,GAAG,6GAA6G,CAAC;IACrI,IAAI,OAAO,KAAc,OAAO,UAAU,CAAC,IAAI,CAAC,oBAAoB,CAAC,CAAC,CAAC,CAAC;IAExE,KAAK,CAAC,GAAgB;QAClB,IAAI,CAAC,oBAAoB,CAAC,GAAG,CAAC,WAAW,CAAC;YAAE,OAAO,EAAE,CAAC;QACtD,MAAM,MAAM,GAAG,oBAAoB,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;QACvD,IAAI,CAAC,MAAM;YAAE,OAAO,EAAE,CAAC;QACvB,OAAO,CAAC,IAAI,iBAAC,CACT,CAAC,EACD,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,EACrB,2EAA2E;kBACzE,WAAW,MAAM,EAAE,CACxB,CAAC,CAAC;IACP,CAAC;CACJ;AA5BD,4DA4BC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\n\nimport { dotWebpieces, MERGE_INFO_DIR, MERGE_IN_PROGRESS_FILE, PrLifecycleGuardConfig, PR_LIFECYCLE_GUARD_KEY } from '@webpieces/rules-config';\n\nimport type { BashContext, Violation } from '../types';\nimport { Violation as V } from '../types';\nimport { BashRuleBase } from '../rule-base';\nimport { FixHint } from '../fix-hint';\nimport { CommandScanner } from '../command-scan';\n\n\n// The ENTIRE enforcement surface of this guard, declared up here because the fixHint RENDERS ITSELF\n// from these two lists (see `blockedCommandList`). The hint used to hand-write \"do not run other\n// commands\" — an unbounded claim that forbade the reads, the `git add`, the build and the tests that\n// finishing a merge actually requires, and that survived every edit to these lists. It was also wrapped\n// in an \"Add to memory\" directive, so it outlived the session that read it. Generating the sentence\n// from the code is what stops the two drifting apart again.\nconst BLOCKED_GIT_SUBCOMMANDS: readonly string[] = ['commit', 'push', 'merge', 'rebase'];\nconst BLOCKED_GH_PR_SUBCOMMANDS: readonly string[] = ['create', 'edit', 'merge'];\n\n// webpieces-disable no-function-outside-class -- module-level guard helper, matches the rest of this file\nfunction blockedCommandList(): string {\n return BLOCKED_GIT_SUBCOMMANDS.map((sub: string) => `\\`git ${sub}\\``).join(', ')\n + `, and \\`gh pr ${BLOCKED_GH_PR_SUBCOMMANDS.join('|')}\\``;\n}\n\n// webpieces-disable no-function-outside-class -- module-level guard helper, matches the rest of this file\nfunction fixHintFor(mergeCompleteCommand: string): FixHint {\n return new FixHint(\n 'A merge is in progress and not yet validated — this command is blocked.',\n 'You started a merge but never called the finish-merge command, so a 3-point merge is still in progress.\\n'\n + `Blocked until the merge is validated: ${blockedCommandList()}. That is the whole list;\\n`\n + 'the finish command below does the commit for you.\\n'\n + 'EXPECTED of you right now, and NOT blocked: read the conflicted files, edit them until every\\n'\n + 'conflict marker is gone, `git add` each file you resolve, write the merge explanation for each\\n'\n + 'one, and run the build and the tests. Finishing a merge requires all of those.\\n'\n + 'Then run:\\n'\n + ` ${mergeCompleteCommand}\\n`\n + 'That scans for leftover conflict markers and runs the build; only when green does it commit,\\n'\n + 'unblock commit/push/PR, render the dashboard, and create/update the PR.\\n'\n + 'Add to memory: finish a started merge before beginning other work.',\n );\n}\n\n// Returns the path of the first UNVALIDATED merge marker found, or null. We detect validation\n// by a raw substring (no JSON.parse) so a malformed marker can never crash the guard.\n/**\n * DEPTH-BOUNDED SCAN, not a fixed level. The marker's home has moved twice: it was\n * `merge-info/<feature>/`, then `merge-info/<feature>/merge-<n>/` once each sync got its own run dir,\n * and is now `merge-info/staged/<feature>/merge-<n>/` since merge-info split into staged/merged. This\n * guard was still looking only at the FIRST layout's depth, so it silently found nothing and stopped\n * blocking — a guard failing open without saying so. A bounded walk covers every layout, legacy\n * included, and stops long before it could descend into anything large.\n */\nconst MARKER_SCAN_MAX_DEPTH = 3;\n\n// webpieces-disable no-function-outside-class -- module-level guard helper, matches the rest of this file\nfunction findMarkerUnder(dir: string, depth: number): string | null {\n if (depth < 0 || !fs.existsSync(dir)) return null;\n const marker = path.join(dir, MERGE_IN_PROGRESS_FILE);\n if (fs.existsSync(marker)) {\n const raw = fs.readFileSync(marker, 'utf8');\n if (!/\"validated\"\\s*:\\s*true/.test(raw)) return marker;\n }\n if (depth === 0) return null;\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n const found = findMarkerUnder(path.join(dir, entry.name), depth - 1);\n if (found !== null) return found;\n }\n return null;\n}\n\n// webpieces-disable no-function-outside-class -- module-level guard helper, matches the rest of this file\nfunction findUnvalidatedMerge(workspaceRoot: string): string | null {\n // LOCAL scope: the merge this guard blocks on is the one THIS worktree started. Another\n // worktree's in-flight merge must not block commits here — that was never the intent, and under a\n // shared merge-info dir it would be the behaviour.\n return findMarkerUnder(dotWebpieces.localFile(workspaceRoot, MERGE_INFO_DIR), MARKER_SCAN_MAX_DEPTH);\n}\n\nconst SCANNER = new CommandScanner();\n// Built from BLOCKED_GH_PR_SUBCOMMANDS so the enforcement and the sentence the fixHint prints can\n// never name different commands.\nconst BLOCKED_GH_PR_PATTERN = new RegExp(`\\\\bgh\\\\s+pr\\\\s+(${BLOCKED_GH_PR_SUBCOMMANDS.join('|')})\\\\b`);\n\n// Operations that would let an agent route around the merge gate.\n//\n// Routed through CommandScanner rather than `/\\bgit\\s+merge\\b/`: that pattern matches the read-only\n// `git merge-base origin/main HEAD` (`\\b` sits between `e` and `-`), which appears in this repo's own\n// documented build command — so an in-progress merge used to block a harmless diff-scope lookup.\n// webpieces-disable no-function-outside-class -- module-level guard helper, matches the rest of this file\nfunction isBlockedDuringMerge(cmd: string): boolean {\n return SCANNER.commandInvokesAnyGit(cmd, BLOCKED_GIT_SUBCOMMANDS)\n || BLOCKED_GH_PR_PATTERN.test(cmd);\n}\n\nfunction truncate(s: string): string {\n const MAX = 120;\n return s.length <= MAX ? s : s.slice(0, MAX) + '…';\n}\n\nexport class MergeInProgressGuardRule extends BashRuleBase<PrLifecycleGuardConfig> {\n /**\n * The gated command this guard names, handed in by the LOADER from `commands.guardHints\n * .mergeInProgress` (already defaulted there). A constructor parameter, not a config field: the\n * field `merge-in-progress-guard.mergeCompleteCommand` was a SECOND SPELLING that beat the commands\n * section, and the loader's name-keyed injection that fed it could miss a rename silently.\n */\n private readonly mergeCompleteCommand: string;\n\n constructor(config: PrLifecycleGuardConfig, mergeCompleteCommand: string) {\n super(config, 'merge-in-progress-guard', PR_LIFECYCLE_GUARD_KEY);\n this.mergeCompleteCommand = mergeCompleteCommand;\n }\n\n readonly description = 'Block commit/push/merge/PR while a 3-point merge marker is unvalidated, forcing the merge-complete command.';\n get fixHint(): FixHint { return fixHintFor(this.mergeCompleteCommand); }\n\n check(ctx: BashContext): readonly Violation[] {\n if (!isBlockedDuringMerge(ctx.commandCode)) return [];\n const marker = findUnvalidatedMerge(ctx.workspaceRoot);\n if (!marker) return [];\n return [new V(\n 1,\n truncate(ctx.command),\n 'A merge is in progress and not yet validated — this command is blocked.\\n'\n + `Marker: ${marker}`,\n )];\n }\n}\n"]}
1
+ {"version":3,"file":"merge-in-progress-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/ai-hook-rules/src/core/rules/merge-in-progress-guard.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAE7B,8DAAyD;AACzD,0DAAiI;AAGjI,oCAA0C;AAC1C,4CAA4C;AAC5C,0CAAsC;AACtC,kDAAiD;AAGjD,oGAAoG;AACpG,iGAAiG;AACjG,qGAAqG;AACrG,wGAAwG;AACxG,oGAAoG;AACpG,4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C,MAAM,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,GAAG,GAAG,CAAC;AACvD,CAAC;AAED,MAAa,wBAAyB,SAAQ,wBAAoC;IAC9E;;;;;OAKG;IACc,oBAAoB,CAAS;IAE9C,YAAY,MAA8B,EAAE,oBAA4B;QACpE,KAAK,CAAC,MAAM,EAAE,yBAAyB,EAAE,qCAAsB,CAAC,CAAC;QACjE,IAAI,CAAC,oBAAoB,GAAG,oBAAoB,CAAC;IACrD,CAAC;IAEQ,WAAW,GAAG,6GAA6G,CAAC;IACrI,IAAI,OAAO,KAAc,OAAO,UAAU,CAAC,IAAI,CAAC,oBAAoB,CAAC,CAAC,CAAC,CAAC;IAExE,KAAK,CAAC,GAAgB;QAClB,IAAI,CAAC,oBAAoB,CAAC,GAAG,CAAC,WAAW,CAAC;YAAE,OAAO,EAAE,CAAC;QACtD,MAAM,MAAM,GAAG,oBAAoB,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;QACvD,IAAI,CAAC,MAAM;YAAE,OAAO,EAAE,CAAC;QACvB,OAAO,CAAC,IAAI,iBAAC,CACT,CAAC,EACD,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,EACrB,2EAA2E;kBACzE,WAAW,MAAM,EAAE,CACxB,CAAC,CAAC;IACP,CAAC;CACJ;AA5BD,4DA4BC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\n\nimport { dotWebpieces } from '@webpieces/tooling-common';\nimport { MERGE_INFO_DIR, MERGE_IN_PROGRESS_FILE, PrLifecycleGuardConfig, PR_LIFECYCLE_GUARD_KEY } from '@webpieces/rules-config';\n\nimport type { BashContext, Violation } from '../types';\nimport { Violation as V } from '../types';\nimport { BashRuleBase } from '../rule-base';\nimport { FixHint } from '../fix-hint';\nimport { CommandScanner } from '../command-scan';\n\n\n// The ENTIRE enforcement surface of this guard, declared up here because the fixHint RENDERS ITSELF\n// from these two lists (see `blockedCommandList`). The hint used to hand-write \"do not run other\n// commands\" — an unbounded claim that forbade the reads, the `git add`, the build and the tests that\n// finishing a merge actually requires, and that survived every edit to these lists. It was also wrapped\n// in an \"Add to memory\" directive, so it outlived the session that read it. Generating the sentence\n// from the code is what stops the two drifting apart again.\nconst BLOCKED_GIT_SUBCOMMANDS: readonly string[] = ['commit', 'push', 'merge', 'rebase'];\nconst BLOCKED_GH_PR_SUBCOMMANDS: readonly string[] = ['create', 'edit', 'merge'];\n\n// webpieces-disable no-function-outside-class -- module-level guard helper, matches the rest of this file\nfunction blockedCommandList(): string {\n return BLOCKED_GIT_SUBCOMMANDS.map((sub: string) => `\\`git ${sub}\\``).join(', ')\n + `, and \\`gh pr ${BLOCKED_GH_PR_SUBCOMMANDS.join('|')}\\``;\n}\n\n// webpieces-disable no-function-outside-class -- module-level guard helper, matches the rest of this file\nfunction fixHintFor(mergeCompleteCommand: string): FixHint {\n return new FixHint(\n 'A merge is in progress and not yet validated — this command is blocked.',\n 'You started a merge but never called the finish-merge command, so a 3-point merge is still in progress.\\n'\n + `Blocked until the merge is validated: ${blockedCommandList()}. That is the whole list;\\n`\n + 'the finish command below does the commit for you.\\n'\n + 'EXPECTED of you right now, and NOT blocked: read the conflicted files, edit them until every\\n'\n + 'conflict marker is gone, `git add` each file you resolve, write the merge explanation for each\\n'\n + 'one, and run the build and the tests. Finishing a merge requires all of those.\\n'\n + 'Then run:\\n'\n + ` ${mergeCompleteCommand}\\n`\n + 'That scans for leftover conflict markers and runs the build; only when green does it commit,\\n'\n + 'unblock commit/push/PR, render the dashboard, and create/update the PR.\\n'\n + 'Add to memory: finish a started merge before beginning other work.',\n );\n}\n\n// Returns the path of the first UNVALIDATED merge marker found, or null. We detect validation\n// by a raw substring (no JSON.parse) so a malformed marker can never crash the guard.\n/**\n * DEPTH-BOUNDED SCAN, not a fixed level. The marker's home has moved twice: it was\n * `merge-info/<feature>/`, then `merge-info/<feature>/merge-<n>/` once each sync got its own run dir,\n * and is now `merge-info/staged/<feature>/merge-<n>/` since merge-info split into staged/merged. This\n * guard was still looking only at the FIRST layout's depth, so it silently found nothing and stopped\n * blocking — a guard failing open without saying so. A bounded walk covers every layout, legacy\n * included, and stops long before it could descend into anything large.\n */\nconst MARKER_SCAN_MAX_DEPTH = 3;\n\n// webpieces-disable no-function-outside-class -- module-level guard helper, matches the rest of this file\nfunction findMarkerUnder(dir: string, depth: number): string | null {\n if (depth < 0 || !fs.existsSync(dir)) return null;\n const marker = path.join(dir, MERGE_IN_PROGRESS_FILE);\n if (fs.existsSync(marker)) {\n const raw = fs.readFileSync(marker, 'utf8');\n if (!/\"validated\"\\s*:\\s*true/.test(raw)) return marker;\n }\n if (depth === 0) return null;\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n const found = findMarkerUnder(path.join(dir, entry.name), depth - 1);\n if (found !== null) return found;\n }\n return null;\n}\n\n// webpieces-disable no-function-outside-class -- module-level guard helper, matches the rest of this file\nfunction findUnvalidatedMerge(workspaceRoot: string): string | null {\n // LOCAL scope: the merge this guard blocks on is the one THIS worktree started. Another\n // worktree's in-flight merge must not block commits here — that was never the intent, and under a\n // shared merge-info dir it would be the behaviour.\n return findMarkerUnder(dotWebpieces.localFile(workspaceRoot, MERGE_INFO_DIR), MARKER_SCAN_MAX_DEPTH);\n}\n\nconst SCANNER = new CommandScanner();\n// Built from BLOCKED_GH_PR_SUBCOMMANDS so the enforcement and the sentence the fixHint prints can\n// never name different commands.\nconst BLOCKED_GH_PR_PATTERN = new RegExp(`\\\\bgh\\\\s+pr\\\\s+(${BLOCKED_GH_PR_SUBCOMMANDS.join('|')})\\\\b`);\n\n// Operations that would let an agent route around the merge gate.\n//\n// Routed through CommandScanner rather than `/\\bgit\\s+merge\\b/`: that pattern matches the read-only\n// `git merge-base origin/main HEAD` (`\\b` sits between `e` and `-`), which appears in this repo's own\n// documented build command — so an in-progress merge used to block a harmless diff-scope lookup.\n// webpieces-disable no-function-outside-class -- module-level guard helper, matches the rest of this file\nfunction isBlockedDuringMerge(cmd: string): boolean {\n return SCANNER.commandInvokesAnyGit(cmd, BLOCKED_GIT_SUBCOMMANDS)\n || BLOCKED_GH_PR_PATTERN.test(cmd);\n}\n\nfunction truncate(s: string): string {\n const MAX = 120;\n return s.length <= MAX ? s : s.slice(0, MAX) + '…';\n}\n\nexport class MergeInProgressGuardRule extends BashRuleBase<PrLifecycleGuardConfig> {\n /**\n * The gated command this guard names, handed in by the LOADER from `commands.guardHints\n * .mergeInProgress` (already defaulted there). A constructor parameter, not a config field: the\n * field `merge-in-progress-guard.mergeCompleteCommand` was a SECOND SPELLING that beat the commands\n * section, and the loader's name-keyed injection that fed it could miss a rename silently.\n */\n private readonly mergeCompleteCommand: string;\n\n constructor(config: PrLifecycleGuardConfig, mergeCompleteCommand: string) {\n super(config, 'merge-in-progress-guard', PR_LIFECYCLE_GUARD_KEY);\n this.mergeCompleteCommand = mergeCompleteCommand;\n }\n\n readonly description = 'Block commit/push/merge/PR while a 3-point merge marker is unvalidated, forcing the merge-complete command.';\n get fixHint(): FixHint { return fixHintFor(this.mergeCompleteCommand); }\n\n check(ctx: BashContext): readonly Violation[] {\n if (!isBlockedDuringMerge(ctx.commandCode)) return [];\n const marker = findUnvalidatedMerge(ctx.workspaceRoot);\n if (!marker) return [];\n return [new V(\n 1,\n truncate(ctx.command),\n 'A merge is in progress and not yet validated — this command is blocked.\\n'\n + `Marker: ${marker}`,\n )];\n }\n}\n"]}
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MergedBranchBashGuardRule = void 0;
4
4
  const child_process_1 = require("child_process");
5
5
  const rules_config_1 = require("@webpieces/rules-config");
6
+ const repo_workflow_core_1 = require("@webpieces/repo-workflow-core");
6
7
  const types_1 = require("../types");
7
8
  const rule_base_1 = require("../rule-base");
8
9
  const fix_hint_1 = require("../fix-hint");
@@ -54,7 +55,7 @@ class MergedBranchBashGuardRule extends rule_base_1.BashRuleBase {
54
55
  description = 'Block ordinary Bash on an already-merged branch (allowlisting only recovery/cleanup and ' +
55
56
  'read-only inspection commands), so a session cannot proceed on a stale post-merge branch.';
56
57
  defaultOptions = {
57
- hangTimeoutMinutes: rules_config_1.DEFAULT_HANG_TIMEOUT_MINUTES,
58
+ hangTimeoutMinutes: repo_workflow_core_1.DEFAULT_HANG_TIMEOUT_MINUTES,
58
59
  };
59
60
  fixHint = new fix_hint_1.FixHint('This branch is already merged into main — do not keep working here.', 'Get onto a fresh branch off origin/main, then retry:', [
60
61
  new rules_config_1.Option('git fetch origin main && git checkout -b <new-branch> origin/main (in a worktree: git worktree add ../<dir> -b <new> origin/main). Then re-run your command.', true),
@@ -70,7 +71,7 @@ class MergedBranchBashGuardRule extends rule_base_1.BashRuleBase {
70
71
  // runner also warms it, but only when feature-branch-guard is loaded — do it here too so this
71
72
  // guard is self-sufficient when that one is off.)
72
73
  (0, main_sync_refresh_1.triggerMainSyncRefresh)(ctx.workspaceRoot, (0, main_sync_timeout_1.hangTimeoutOf)(this.config));
73
- const status = (0, rules_config_1.readMainSyncStatus)(ctx.workspaceRoot, branch);
74
+ const status = (0, repo_workflow_core_1.readMainSyncStatus)(ctx.workspaceRoot, branch);
74
75
  // No cache yet (first command of the session), or a branch this refresh has not seen → allow;
75
76
  // the refresh we just spawned populates it.
76
77
  if (status === null)