@webpieces/agent-workflow-rules 0.4.973 → 0.4.974
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +7 -7
- package/src/adapters/hook-core.js +9 -2
- package/src/adapters/hook-core.js.map +1 -1
- package/src/core/l2-doc.js +8 -0
- package/src/core/l2-doc.js.map +1 -1
- package/src/core/main-sync-log.js +2 -1
- package/src/core/main-sync-log.js.map +1 -1
- package/src/core/main-sync-refresh.d.ts +8 -2
- package/src/core/main-sync-refresh.js +30 -10
- package/src/core/main-sync-refresh.js.map +1 -1
- package/src/core/main-sync-timeout.js +6 -1
- package/src/core/main-sync-timeout.js.map +1 -1
- package/src/core/rules/feature-branch-guard.js +1 -1
- package/src/core/rules/feature-branch-guard.js.map +1 -1
- package/src/core/rules/merged-branch-bash-guard.js +1 -1
- package/src/core/rules/merged-branch-bash-guard.js.map +1 -1
- package/src/core/rules/read-stale-guard.js +1 -1
- package/src/core/rules/read-stale-guard.js.map +1 -1
- package/src/core/rules/stale-main-bash-guard.js +1 -1
- package/src/core/rules/stale-main-bash-guard.js.map +1 -1
- package/src/core/sync-main.d.ts +2 -1
- package/src/core/sync-main.js +2 -1
- package/src/core/sync-main.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"read-stale-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/agent-workflow-rules/src/core/rules/read-stale-guard.ts"],"names":[],"mappings":";;;AAAA,8DAAwD;AAExD,0DAAiD;AACjD,mDAA2D;AAC3D,mFAA2G;AAC3G,sEAAiI;AAGjI,0DAAyD;AACzD,0DAAuD;AACvD,0DAAkD;AAClD,4DAA8D;AAC9D,4DAAqD;AACrD,kDAAwF;AACxF,oDAAuF;AACvF,0DAAwD;AACxD,0DAA6D;AAC7D,mEAA8D;AAC9D,+CAA2C;AAC3C,6DAAwD;AACxD,qDAAiD;AACjD,mDAA+C;AAE/C;;;;;;;;;;;;;;;;;;;;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AAW,CAAC,GAAgB,EAAE,MAAqB,EAAE,OAAgB,EAAE,MAAc,EAAE,KAAa;QACxG,IAAA,+BAAgB,EACZ,GAAG,CAAC,aAAa,EACjB,IAAI,4BAAa,CAAC,kBAAkB,EAAE,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,YAAY,EAAE,MAAM,IAAI,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,4BAAa,EAAE,IAAA,0BAAW,EAAC,MAAM,CAAC,CAAC,CACrJ,CAAC;IACN,CAAC;IAED;;;;OAIG;IACK,aAAa,CAAC,aAAqB;QACvC,OAAO,4BAAW,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;IAC7C,CAAC;CACJ;AA3OD,gDA2OC","sourcesContent":["import { gitCheckout } from '@webpieces/tooling-common';\n\nimport { Option } from '@webpieces/rules-config';\nimport { BRANCH_STATE_GUARD_KEY } from '../../policy-keys';\nimport { BranchStateGuardConfig, DEFAULT_MAX_COMMITS_BEHIND } from \"../../configs/main-sync-guard-configs\";\nimport { BranchIdentity, DEFAULT_HANG_TIMEOUT_MINUTES, readMainSyncStatus, MainSyncStatus } from '@webpieces/repo-workflow-core';\n\nimport type { FileContext, Violation } from '@webpieces/hook-runtime';\nimport { Violation as V } from '@webpieces/hook-runtime';\nimport { FileRuleBase } from '@webpieces/hook-runtime';\nimport { FixHint } from '@webpieces/hook-runtime';\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 '@webpieces/rules-config';\nimport { TargetTreeResolver } from '@webpieces/hook-runtime';\nimport { MergedBranchMessage } from './merged-branch-message';\nimport { JudgedTree } from './judged-tree';\nimport { StaleMainMessage } from './stale-main-message';\nimport { MainFreshness } from './main-freshness';\nimport { TreeRecovery } from './tree-recovery';\n\n/**\n * Blocks READS while the checked-out branch is a stale place to read from. TWO states:\n *\n * A. on `main`, and local main is farther BEHIND origin/main than the configured tolerance\n * B. on a feature branch whose PR is ALREADY MERGED (a pre-merge snapshot; origin/main has moved\n * past it and a squash merge means its HEAD is not even an ancestor of main)\n *\n * WHY READ, of all tools: either state means the AI reads stale FILE CONTENT and then reasons,\n * plans and writes against code that no longer exists upstream. Blocking the write is too late —\n * the bad premise is already in context. So the block lands on the read. (feature-branch-guard\n * blocks the WRITE in state B; this guard is the read-side half of that same protection, and the\n * two share one recovery message via MergedBranchMessage.)\n *\n * THERE IS NO DIRTY-TREE ASYMMETRY, and there is no dirty-tree valve in either state. Both used to\n * fail open on uncommitted work; both now block. The argument for the state-A valve was that its cure,\n * an in-place pull, is not a fast-forward on a dirty tree — true, but that is a fact about the\n * MESSAGE, which printed only the pull. Row 6 has always carried a second cure, `git checkout -b <new>\n * origin/main`, and that one CARRIES uncommitted changes onto the new branch, so the work comes with\n * you and nothing is trapped. StaleMainMessage now prints both, labelled with which survives a dirty\n * tree, so the block no longer has to be suppressed to keep the printed cure runnable. State B's valve\n * never had an argument at all — its cure was always the branch form.\n *\n * Residual, in both states: if `origin/main` changed the same files you edited, git refuses the switch.\n * `git stash` is on the L2 skip list and is never blocked, so the path out is stash → branch → pop.\n *\n * WHY THIS CANNOT WEDGE: the block is scoped to Read ONLY. Every cure — `pnpm wp-sync-main`,\n * `pnpm install`, any webpieces upgrade — is a Bash command, and this guard never looks at Bash.\n * So there is no command allowlist to maintain and no way to lock the agent out of its own fix.\n * (Every `wp-*` bin is on the L2 skip list, and the pull it wraps is explicitly permitted on main by\n * redirect-how-to-merge-main, which returns null when the branch IS main — the guards are\n * complementary, not stacked.)\n *\n * That scoping is also this guard's HOLE, and it is closed elsewhere rather than here: leaving Bash\n * entirely alone let a session `cat`/`grep`/`ls` the same stale tree the Read block was rejecting,\n * for a whole session, while the logs read \"read-stale-guard handled\". stale-main-bash-guard is the\n * State-A Bash counterpart (as merged-branch-bash-guard is State B's): in the SAME state this guard\n * blocks — `main`, KNOWN BEYOND the cached commit-distance tolerance below — it default-denies Bash and\n * allowlists only the commands that get you out, so the cure is never blocked and this guard can stay\n * simple and Read-only.\n *\n * Everything here is FAIL-OPEN on data we could not ESTABLISH. A guard that blocks reads on bad data\n * is far worse than one that misses; every unknown resolves to \"allow\". Note the dual, which is what\n * the deleted dirty valve violated: never fail open on data you DID establish. A dirty tree is not an\n * unknown — it is a known state with a known cure. The three deliberate escape valves:\n *\n * 1. CACHE LAG — we do NOT compare hashes for equality. The cached `originMain` is written by\n * the detached refresher and is arbitrarily old, so `local !== origin` stays\n * true for a while AFTER a successful pull, which would spin the agent forever.\n * Instead: is the cached origin/main an ANCESTOR of local main? If local main\n * already contains it, we are not behind. That flips the instant the pull lands,\n * with no refresher round-trip. This is the single most important line here.\n * 2. CONFIG READ — webpieces.config.json stays readable so the agent can always read-then-edit\n * it to set `mode: OFF`. Its EDIT is already bypassed in runner.ts + hook-core;\n * this closes the read half of that same escape hatch.\n * 3. NO DATA — no cache, cache for another branch, empty originMain (offline), or no local\n * main at all (fresh clone / worktree) → allow.\n *\n * Runs from the Read fast path in hook-core (Read is neither a file-edit nor a bash payload, so it\n * never reaches the runner's rule loop). Fires the detached refresher on every call, which is also\n * what makes reads keep the shared main-sync cache warm for feature-branch-guard.\n */\nexport class ReadStaleGuardRule extends FileRuleBase<BranchStateGuardConfig> {\n constructor(config: BranchStateGuardConfig) { super(config, 'read-stale-guard', BRANCH_STATE_GUARD_KEY); }\n\n // The ancestry test and the cache summary, shared with stale-main-bash-guard — see main-freshness.ts.\n private readonly freshness = new MainFreshness();\n private readonly branches = new BranchIdentity();\n\n readonly description = 'Block reads on a branch that is stale to read from — a `main` beyond its configured commit-distance tolerance, or a feature branch whose PR is already merged.';\n override readonly files = ['**/*'];\n override readonly defaultOptions = {\n hangTimeoutMinutes: DEFAULT_HANG_TIMEOUT_MINUTES,\n };\n readonly fixHint = new FixHint(\n 'This branch is stale to read from — reading it would give you pre-merge/out-of-date content.',\n 'Get onto current code before reading anything else:',\n [\n new Option('On main, beyond branch-state-guard.maxCommitsBehind → pnpm wp-sync-main (CLEAN TREE ONLY), or git checkout -b <new-branch> origin/main which works with UNCOMMITTED CHANGES and brings them along. On an already-merged branch → git fetch origin main && git checkout -b <new-branch> origin/main, which likewise carries your edits. Then retry the read.', true),\n new Option('If a checkout -b refuses because origin/main changed the same files you edited: git stash (never blocked), redo the checkout, then git stash pop.'),\n new Option(\"If pnpm wp-sync-main dies with 'fatal: Cannot fast-forward to multiple branches', .git/FETCH_HEAD holds a duplicate line — run 'git fetch --prune origin main' to rewrite it cleanly, then run it again.\"),\n new Option('Still allowed right now: reading webpieces.config.json, and the Bash commands that get you OUT or tell you where you are — git checkout -b <new> origin/main, git switch, git pull/fetch, git status|log|diff|show|branch, git stash, gh, curl/wget, every wp-* bin, installs. Everything ELSE through Bash is blocked in this same state (a main beyond maxCommitsBehind → stale-main-bash-guard; a merged branch → merged-branch-bash-guard), and Write/Edit on main is blocked by feature-branch-guard however current main is. There is no side door: get onto a branch off origin/main.'),\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 /**\n * WHICH TREE is judged — the one that owns the FILE BEING READ, resolved by git through\n * TargetTreeResolver, never by `ctx.workspaceRoot`. Same fix and same reasoning as\n * feature-branch-guard's (issue #851): `ctx.workspaceRoot` is the walk-up from the SESSION's cwd, so\n * a main-session Read of a file inside an agent worktree was judged on the PRIMARY clone's branch —\n * and a `main` that the primary happened to be sitting on would close reads of another tree's\n * feature branch.\n */\n check(ctx: FileContext): readonly Violation[] {\n // Outside the workspace root — no jurisdiction.\n if (ctx.relativePath.startsWith('..')) return [];\n\n const target = new TargetTreeResolver().resolve(ctx.filePath, ctx.workspaceRoot);\n // A nested clone under `repositories/**` is out of scope, exactly as it is on the bash path.\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 if (branch === null) return this.failOpen(ctx, branch, 'branch-undeterminable');\n // Mid-rebase in the target tree: no branch name, so no key into the branch-keyed cache and\n // nothing to judge. Matrix row 14 — abstain, and say WHY rather than logging a cache miss.\n if (branch === 'HEAD') return this.failOpen(ctx, branch, 'detached-head');\n // A `/hotfix/` branch never takes main (issue #1371), so \"merged\" and \"stale\" are not states it can\n // be cured out of by branching off main. L2 row 14: exempt.\n if (this.branches.isHotfix(branch)) return this.exempt(ctx, branch, 'hotfix-branch (cut from production; main is never merged in)');\n\n // Keep the shared cache warm for the next call. Detached; never blocks this read. Fired for\n // BOTH states — the merged-branch signal comes out of that same cache. Rooted at the JUDGED\n // tree so the entry refreshed is the one this guard reads.\n triggerMainSyncRefresh(judgedRoot, hangTimeoutOf(this.config));\n\n // Escape valve 3 — the read half of the config escape hatch. Ahead of BOTH states' blocks so\n // the agent can always read-then-edit the file that turns this guard off.\n if (this.isConfigFile(ctx.relativePath)) return this.allow(ctx, branch, 'webpieces-config-read (escape hatch)');\n\n const judged = new JudgedTree(target, branch, target.governedRoot);\n return branch === 'main'\n ? this.checkStaleMain(ctx, judged)\n : this.checkMergedBranch(ctx, judged);\n }\n\n // State A — on main, possibly behind origin/main.\n private checkStaleMain(ctx: FileContext, judged: JudgedTree): readonly Violation[] {\n const branch = judged.branch;\n const status = readMainSyncStatus(judged.root, 'main');\n if (status === null) return this.failOpen(ctx, branch, 'no-sync-cache', 'cache=none');\n\n const cache = this.cacheSummary(status);\n // BELT-AND-BRACES since the cache became branch-keyed: we asked for the 'main' entry by key, so\n // a mismatch means the map's key and the entry's own `branch` disagree — a shape bug. Kept so\n // that degrades to an allow. Unreachable in normal operation.\n if (status.branch !== 'main') return this.failOpen(ctx, branch, 'stale-cross-branch-cache', cache);\n // Offline / origin unresolvable, or no local main to compare against.\n if (status.originMain === '') return this.failOpen(ctx, branch, 'origin-main-unknown', cache);\n\n // Escape valve 2 — ancestry, NOT equality. See the class comment.\n if (this.freshness.containsOriginMain(judged.root, status.originMain)) {\n return this.allow(ctx, branch, 'local-main-contains-origin (up to date)', cache);\n }\n\n const maxCommitsBehind = this.config.maxCommitsBehind ?? DEFAULT_MAX_COMMITS_BEHIND;\n const withinThreshold = this.freshness.isWithinAllowedDrift(status, maxCommitsBehind);\n if (withinThreshold === null) return this.failOpen(ctx, branch, 'commit-distance-unknown', cache);\n if (withinThreshold) return this.allow(ctx, branch, 'within-max-commits-behind', cache);\n\n // NO DIRTY VALVE. It used to fail open here, on the argument that the prescribed in-place pull\n // is not a clean fast-forward on a dirty tree. That argument was about the MESSAGE, not the row:\n // row 6's cure cell has always offered `git checkout -b <new> origin/main` as an alternative,\n // and THAT works dirty — it carries uncommitted changes onto the new branch and lands you on\n // current code, which is the whole point. The message now leads with it when the tree is dirty\n // (StaleMainMessage.forReads), so the cure an agent reads is one it can actually run.\n // Residual, same as row 8: if origin/main touched the files you edited, git refuses the switch\n // — `git stash` is on the skip list and clears it. Two steps worst case, never a dead end.\n return this.block(\n ctx, branch, 'on-stale-main',\n this.staleMainMessage(judged, status.commitsBehind ?? 0), cache);\n }\n\n /**\n * State B — a feature branch whose PR is already merged. Reads a PRE-MERGE snapshot, so every\n * plan built from it is built on code origin/main has moved past.\n *\n * `branchAlreadyMerged` comes straight from the shared cache (the refresher's `gh pr list --state\n * merged`), so this path spawns nothing. No `gh` / offline → `mergedPr` is '' → not merged → allow,\n * which is the fail-open direction for free.\n *\n * NO DIRTY-TREE VALVE. `git checkout -b <new> origin/main` carries uncommitted changes onto the\n * fresh branch, so the work comes with you and there is nothing to rescue by reading. When it does\n * NOT (an overlapping change landed in main, so git refuses the switch), `git stash` is on the L2\n * skip list and is never blocked: stash → branch → pop. The valve that used to sit here was drift\n * from the documented design, not a decision — this docblock described the strict behaviour for\n * releases while the code failed open.\n */\n private checkMergedBranch(ctx: FileContext, judged: JudgedTree): readonly Violation[] {\n const branch = judged.branch;\n const status = readMainSyncStatus(judged.root, branch);\n if (status === null) return this.failOpen(ctx, branch, 'no-sync-cache', 'cache=none');\n\n const cache = this.cacheSummary(status);\n // BELT-AND-BRACES since the cache became branch-keyed: the entry was looked up BY `branch`, so\n // a mismatch is a shape bug rather than the old \"cache is for another branch\" state. Kept so\n // such a bug degrades to an allow. Unreachable in normal operation. (A branch the refresh has\n // not seen yet is the `status === null` case above — still fail-open.)\n if (status.branch !== branch) return this.failOpen(ctx, branch, 'stale-cross-branch-cache', cache);\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 if (!status.branchAlreadyMerged) {\n return status.forgeReachable\n ? this.allow(ctx, branch, 'clean-feature-branch', cache)\n : this.failOpen(ctx, branch, 'no-forge', cache);\n }\n // NO DIRTY VALVE — and this one never had an argument behind it at all. Row 8's cure is\n // `git fetch origin main && git checkout -b <new> origin/main`, which carries uncommitted work\n // with you, so a dirty tree traps nobody. The valve was code drift from the documented design;\n // read-stale-guard's own class comment said so while the code did the opposite.\n const pr = status.mergedPr !== '' ? status.mergedPr : '?';\n return this.block(\n ctx,\n branch,\n `already-merged PR#${pr}`,\n this.mergedMessage(judged, status.mergedPr),\n cache,\n );\n }\n\n // The merged-branch text, told in the flavour of the tree we are standing in: a linked worktree\n // is told to open a NEW worktree off origin/main and reap this dead one; the primary clone is\n // told to branch off origin/main. Neither is ever told to `git checkout main` (fatal in a\n // worktree). Detection is one statSync — see WorktreeService.isLinkedWorktree.\n private mergedMessage(judged: JudgedTree, mergedPr: string): string {\n const recovery = new TreeRecovery();\n const body = new MergedBranchMessage(judged.root).forReads(\n judged.branch, mergedPr, recovery.kindOf(judged.root), judged.root,\n );\n // NO redirect note here, deliberately — see feature-branch-guard.alreadyMergedMessage for the\n // argument. MergedBranchMessage already aims its commands at the judged root through `atRoot`\n // and prints the WORKTREE flavour of the cure when the judged tree is one.\n return [judged.header(), body].join('\\n');\n }\n\n\n private isConfigFile(relativePath: string): boolean {\n return relativePath === 'webpieces.config.json';\n }\n\n // StaleMainMessage's remaining consumer. It used to be shared with stale-main-bash-guard so the two\n // halves of the State-A block could never prescribe different cures; that guard now blocks on the\n // BRANCH (row 5) rather than on staleness and carries its own message, so this is the only caller.\n private staleMainMessage(judged: JudgedTree, commitsBehind: number): string {\n return [\n judged.header(),\n new StaleMainMessage(judged.root).forReads(String(commitsBehind)),\n judged.redirectNote([judged.pnpmCure('wp-sync-main')]),\n ].join('\\n');\n }\n\n private cacheSummary(status: MainSyncStatus): string {\n return this.freshness.summarize(status);\n }\n\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 /** The policy does not apply to this branch at all — logged `ALLOW_EXEMPT`, never confused with an approval. */\n private exempt(ctx: FileContext, branch: string, reason: string): readonly Violation[] {\n this.logDecision(ctx, branch, 'ALLOW_EXEMPT', reason, '-');\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('read-stale-guard', ctx.tool, ctx.relativePath, branch ?? 'unknown', verdict, reason, cache, L0_FAULT_NONE, matrixL2Row(reason)),\n );\n }\n\n /**\n * The current branch, WITHOUT spawning git for it. This runs on EVERY read, so it is the one call\n * whose cost matters most: `GitCheckout.branch()` reads the worktree's own HEAD file (primary clone\n * and linked worktree alike, detached HEAD included) with no git process at all (#1355).\n */\n private currentBranch(workspaceRoot: string): string | null {\n return gitCheckout.branch(workspaceRoot);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"read-stale-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/agent-workflow-rules/src/core/rules/read-stale-guard.ts"],"names":[],"mappings":";;;AAAA,8DAAwD;AAExD,0DAAiD;AACjD,mDAA2D;AAC3D,mFAA2G;AAC3G,sEAAiI;AAGjI,0DAAyD;AACzD,0DAAuD;AACvD,0DAAkD;AAClD,4DAA8D;AAC9D,4DAAqD;AACrD,kDAAwF;AACxF,oDAAuF;AACvF,0DAAwD;AACxD,0DAA6D;AAC7D,mEAA8D;AAC9D,+CAA2C;AAC3C,6DAAwD;AACxD,qDAAiD;AACjD,mDAA+C;AAE/C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4DG;AACH,MAAa,kBAAmB,SAAQ,2BAAoC;IACxE,YAAY,MAA8B,IAAI,KAAK,CAAC,MAAM,EAAE,kBAAkB,EAAE,oCAAsB,CAAC,CAAC,CAAC,CAAC;IAE1G,sGAAsG;IACrF,SAAS,GAAG,IAAI,8BAAa,EAAE,CAAC;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AE,MAAM,EAAE,KAAK,EAAE,4BAAa,EAAE,IAAA,0BAAW,EAAC,MAAM,CAAC,CAAC,CACrJ,CAAC;IACN,CAAC;IAED;;;;OAIG;IACK,aAAa,CAAC,aAAqB;QACvC,OAAO,4BAAW,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;IAC7C,CAAC;CACJ;AA3OD,gDA2OC","sourcesContent":["import { gitCheckout } from '@webpieces/tooling-common';\n\nimport { Option } from '@webpieces/rules-config';\nimport { BRANCH_STATE_GUARD_KEY } from '../../policy-keys';\nimport { BranchStateGuardConfig, DEFAULT_MAX_COMMITS_BEHIND } from \"../../configs/main-sync-guard-configs\";\nimport { BranchIdentity, DEFAULT_HANG_TIMEOUT_MINUTES, readMainSyncStatus, MainSyncStatus } from '@webpieces/repo-workflow-core';\n\nimport type { FileContext, Violation } from '@webpieces/hook-runtime';\nimport { Violation as V } from '@webpieces/hook-runtime';\nimport { FileRuleBase } from '@webpieces/hook-runtime';\nimport { FixHint } from '@webpieces/hook-runtime';\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 '@webpieces/rules-config';\nimport { TargetTreeResolver } from '@webpieces/hook-runtime';\nimport { MergedBranchMessage } from './merged-branch-message';\nimport { JudgedTree } from './judged-tree';\nimport { StaleMainMessage } from './stale-main-message';\nimport { MainFreshness } from './main-freshness';\nimport { TreeRecovery } from './tree-recovery';\n\n/**\n * Blocks READS while the checked-out branch is a stale place to read from. TWO states:\n *\n * A. on `main`, and local main is farther BEHIND origin/main than the configured tolerance\n * B. on a feature branch whose PR is ALREADY MERGED (a pre-merge snapshot; origin/main has moved\n * past it and a squash merge means its HEAD is not even an ancestor of main)\n *\n * WHY READ, of all tools: either state means the AI reads stale FILE CONTENT and then reasons,\n * plans and writes against code that no longer exists upstream. Blocking the write is too late —\n * the bad premise is already in context. So the block lands on the read. (feature-branch-guard\n * blocks the WRITE in state B; this guard is the read-side half of that same protection, and the\n * two share one recovery message via MergedBranchMessage.)\n *\n * THERE IS NO DIRTY-TREE ASYMMETRY, and there is no dirty-tree valve in either state. Both used to\n * fail open on uncommitted work; both now block. The argument for the state-A valve was that its cure,\n * an in-place pull, is not a fast-forward on a dirty tree — true, but that is a fact about the\n * MESSAGE, which printed only the pull. Row 6 has always carried a second cure, `git checkout -b <new>\n * origin/main`, and that one CARRIES uncommitted changes onto the new branch, so the work comes with\n * you and nothing is trapped. StaleMainMessage now prints both, labelled with which survives a dirty\n * tree, so the block no longer has to be suppressed to keep the printed cure runnable. State B's valve\n * never had an argument at all — its cure was always the branch form.\n *\n * Residual, in both states: if `origin/main` changed the same files you edited, git refuses the switch.\n * `git stash` is on the L2 skip list and is never blocked, so the path out is stash → branch → pop.\n *\n * WHY THIS CANNOT WEDGE: the block is scoped to Read ONLY. Every cure — `pnpm wp-sync-main`,\n * `pnpm install`, any webpieces upgrade — is a Bash command, and this guard never looks at Bash.\n * So there is no command allowlist to maintain and no way to lock the agent out of its own fix.\n * (Every `wp-*` bin is on the L2 skip list, and the pull it wraps is explicitly permitted on main by\n * redirect-how-to-merge-main, which returns null when the branch IS main — the guards are\n * complementary, not stacked.)\n *\n * That scoping is also this guard's HOLE, and it is closed elsewhere rather than here: leaving Bash\n * entirely alone let a session `cat`/`grep`/`ls` the same stale tree the Read block was rejecting,\n * for a whole session, while the logs read \"read-stale-guard handled\". stale-main-bash-guard is the\n * State-A Bash counterpart (as merged-branch-bash-guard is State B's): in the SAME state this guard\n * blocks — `main`, KNOWN BEYOND the cached commit-distance tolerance below — it default-denies Bash and\n * allowlists only the commands that get you out, so the cure is never blocked and this guard can stay\n * simple and Read-only.\n *\n * Everything here is FAIL-OPEN on data we could not ESTABLISH. A guard that blocks reads on bad data\n * is far worse than one that misses; every unknown resolves to \"allow\". Note the dual, which is what\n * the deleted dirty valve violated: never fail open on data you DID establish. A dirty tree is not an\n * unknown — it is a known state with a known cure. The three deliberate escape valves:\n *\n * 1. CACHE LAG — we do NOT compare hashes for equality. The cached `originMain` is written by\n * the detached refresher and is arbitrarily old, so `local !== origin` stays\n * true for a while AFTER a successful pull, which would spin the agent forever.\n * Instead: is the cached origin/main an ANCESTOR of local main? If local main\n * already contains it, we are not behind. That flips the instant the pull lands,\n * with no refresher round-trip. This is the single most important line here.\n * 2. CONFIG READ — webpieces.config.json stays readable so the agent can always read-then-edit\n * it to set `mode: OFF`. Its EDIT is already bypassed in runner.ts + hook-core;\n * this closes the read half of that same escape hatch.\n * 3. NO DATA — no cache, cache for another branch, empty originMain (offline), or no local\n * main at all (fresh clone / worktree) → allow.\n *\n * Runs from the Read fast path in hook-core (Read is neither a file-edit nor a bash payload, so it\n * never reaches the runner's rule loop). Fires the detached refresher on every call, which is also\n * what makes reads keep the shared main-sync cache warm for feature-branch-guard.\n */\nexport class ReadStaleGuardRule extends FileRuleBase<BranchStateGuardConfig> {\n constructor(config: BranchStateGuardConfig) { super(config, 'read-stale-guard', BRANCH_STATE_GUARD_KEY); }\n\n // The ancestry test and the cache summary, shared with stale-main-bash-guard — see main-freshness.ts.\n private readonly freshness = new MainFreshness();\n private readonly branches = new BranchIdentity();\n\n readonly description = 'Block reads on a branch that is stale to read from — a `main` beyond its configured commit-distance tolerance, or a feature branch whose PR is already merged.';\n override readonly files = ['**/*'];\n override readonly defaultOptions = {\n hangTimeoutMinutes: DEFAULT_HANG_TIMEOUT_MINUTES,\n };\n readonly fixHint = new FixHint(\n 'This branch is stale to read from — reading it would give you pre-merge/out-of-date content.',\n 'Get onto current code before reading anything else:',\n [\n new Option('On main, beyond branch-state-guard.maxCommitsBehind → pnpm wp-sync-main (CLEAN TREE ONLY), or git checkout -b <new-branch> origin/main which works with UNCOMMITTED CHANGES and brings them along. On an already-merged branch → git fetch origin main && git checkout -b <new-branch> origin/main, which likewise carries your edits. Then retry the read.', true),\n new Option('If a checkout -b refuses because origin/main changed the same files you edited: git stash (never blocked), redo the checkout, then git stash pop.'),\n new Option(\"If pnpm wp-sync-main dies with 'fatal: Cannot fast-forward to multiple branches', .git/FETCH_HEAD holds a duplicate line — run 'git fetch --prune origin main' to rewrite it cleanly, then run it again.\"),\n new Option('Still allowed right now: reading webpieces.config.json, and the Bash commands that get you OUT or tell you where you are — git checkout -b <new> origin/main, git switch, git pull/fetch, git status|log|diff|show|branch, git stash, gh, curl/wget, every wp-* bin, installs. Everything ELSE through Bash is blocked in this same state (a main beyond maxCommitsBehind → stale-main-bash-guard; a merged branch → merged-branch-bash-guard), and Write/Edit on main is blocked by feature-branch-guard however current main is. There is no side door: get onto a branch off origin/main.'),\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 /**\n * WHICH TREE is judged — the one that owns the FILE BEING READ, resolved by git through\n * TargetTreeResolver, never by `ctx.workspaceRoot`. Same fix and same reasoning as\n * feature-branch-guard's (issue #851): `ctx.workspaceRoot` is the walk-up from the SESSION's cwd, so\n * a main-session Read of a file inside an agent worktree was judged on the PRIMARY clone's branch —\n * and a `main` that the primary happened to be sitting on would close reads of another tree's\n * feature branch.\n */\n check(ctx: FileContext): readonly Violation[] {\n // Outside the workspace root — no jurisdiction.\n if (ctx.relativePath.startsWith('..')) return [];\n\n const target = new TargetTreeResolver().resolve(ctx.filePath, ctx.workspaceRoot);\n // A nested clone under `repositories/**` is out of scope, exactly as it is on the bash path.\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 if (branch === null) return this.failOpen(ctx, branch, 'branch-undeterminable');\n // Mid-rebase in the target tree: no branch name, so no key into the branch-keyed cache and\n // nothing to judge. Matrix row 14 — abstain, and say WHY rather than logging a cache miss.\n if (branch === 'HEAD') return this.failOpen(ctx, branch, 'detached-head');\n // A `/hotfix/` branch never takes main (issue #1371), so \"merged\" and \"stale\" are not states it can\n // be cured out of by branching off main. L2 row 14: exempt.\n if (this.branches.isHotfix(branch)) return this.exempt(ctx, branch, 'hotfix-branch (cut from production; main is never merged in)');\n\n // Keep the shared cache warm for the next call. Detached; never blocks this read. Fired for\n // BOTH states — the merged-branch signal comes out of that same cache. Rooted at the JUDGED\n // tree so the entry refreshed is the one this guard reads.\n triggerMainSyncRefresh(judgedRoot, branch, hangTimeoutOf(this.config));\n\n // Escape valve 3 — the read half of the config escape hatch. Ahead of BOTH states' blocks so\n // the agent can always read-then-edit the file that turns this guard off.\n if (this.isConfigFile(ctx.relativePath)) return this.allow(ctx, branch, 'webpieces-config-read (escape hatch)');\n\n const judged = new JudgedTree(target, branch, target.governedRoot);\n return branch === 'main'\n ? this.checkStaleMain(ctx, judged)\n : this.checkMergedBranch(ctx, judged);\n }\n\n // State A — on main, possibly behind origin/main.\n private checkStaleMain(ctx: FileContext, judged: JudgedTree): readonly Violation[] {\n const branch = judged.branch;\n const status = readMainSyncStatus(judged.root, 'main');\n if (status === null) return this.failOpen(ctx, branch, 'no-sync-cache', 'cache=none');\n\n const cache = this.cacheSummary(status);\n // BELT-AND-BRACES since the cache became branch-keyed: we asked for the 'main' entry by key, so\n // a mismatch means the map's key and the entry's own `branch` disagree — a shape bug. Kept so\n // that degrades to an allow. Unreachable in normal operation.\n if (status.branch !== 'main') return this.failOpen(ctx, branch, 'stale-cross-branch-cache', cache);\n // Offline / origin unresolvable, or no local main to compare against.\n if (status.originMain === '') return this.failOpen(ctx, branch, 'origin-main-unknown', cache);\n\n // Escape valve 2 — ancestry, NOT equality. See the class comment.\n if (this.freshness.containsOriginMain(judged.root, status.originMain)) {\n return this.allow(ctx, branch, 'local-main-contains-origin (up to date)', cache);\n }\n\n const maxCommitsBehind = this.config.maxCommitsBehind ?? DEFAULT_MAX_COMMITS_BEHIND;\n const withinThreshold = this.freshness.isWithinAllowedDrift(status, maxCommitsBehind);\n if (withinThreshold === null) return this.failOpen(ctx, branch, 'commit-distance-unknown', cache);\n if (withinThreshold) return this.allow(ctx, branch, 'within-max-commits-behind', cache);\n\n // NO DIRTY VALVE. It used to fail open here, on the argument that the prescribed in-place pull\n // is not a clean fast-forward on a dirty tree. That argument was about the MESSAGE, not the row:\n // row 6's cure cell has always offered `git checkout -b <new> origin/main` as an alternative,\n // and THAT works dirty — it carries uncommitted changes onto the new branch and lands you on\n // current code, which is the whole point. The message now leads with it when the tree is dirty\n // (StaleMainMessage.forReads), so the cure an agent reads is one it can actually run.\n // Residual, same as row 8: if origin/main touched the files you edited, git refuses the switch\n // — `git stash` is on the skip list and clears it. Two steps worst case, never a dead end.\n return this.block(\n ctx, branch, 'on-stale-main',\n this.staleMainMessage(judged, status.commitsBehind ?? 0), cache);\n }\n\n /**\n * State B — a feature branch whose PR is already merged. Reads a PRE-MERGE snapshot, so every\n * plan built from it is built on code origin/main has moved past.\n *\n * `branchAlreadyMerged` comes straight from the shared cache (the refresher's `gh pr list --state\n * merged`), so this path spawns nothing. No `gh` / offline → `mergedPr` is '' → not merged → allow,\n * which is the fail-open direction for free.\n *\n * NO DIRTY-TREE VALVE. `git checkout -b <new> origin/main` carries uncommitted changes onto the\n * fresh branch, so the work comes with you and there is nothing to rescue by reading. When it does\n * NOT (an overlapping change landed in main, so git refuses the switch), `git stash` is on the L2\n * skip list and is never blocked: stash → branch → pop. The valve that used to sit here was drift\n * from the documented design, not a decision — this docblock described the strict behaviour for\n * releases while the code failed open.\n */\n private checkMergedBranch(ctx: FileContext, judged: JudgedTree): readonly Violation[] {\n const branch = judged.branch;\n const status = readMainSyncStatus(judged.root, branch);\n if (status === null) return this.failOpen(ctx, branch, 'no-sync-cache', 'cache=none');\n\n const cache = this.cacheSummary(status);\n // BELT-AND-BRACES since the cache became branch-keyed: the entry was looked up BY `branch`, so\n // a mismatch is a shape bug rather than the old \"cache is for another branch\" state. Kept so\n // such a bug degrades to an allow. Unreachable in normal operation. (A branch the refresh has\n // not seen yet is the `status === null` case above — still fail-open.)\n if (status.branch !== branch) return this.failOpen(ctx, branch, 'stale-cross-branch-cache', cache);\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 if (!status.branchAlreadyMerged) {\n return status.forgeReachable\n ? this.allow(ctx, branch, 'clean-feature-branch', cache)\n : this.failOpen(ctx, branch, 'no-forge', cache);\n }\n // NO DIRTY VALVE — and this one never had an argument behind it at all. Row 8's cure is\n // `git fetch origin main && git checkout -b <new> origin/main`, which carries uncommitted work\n // with you, so a dirty tree traps nobody. The valve was code drift from the documented design;\n // read-stale-guard's own class comment said so while the code did the opposite.\n const pr = status.mergedPr !== '' ? status.mergedPr : '?';\n return this.block(\n ctx,\n branch,\n `already-merged PR#${pr}`,\n this.mergedMessage(judged, status.mergedPr),\n cache,\n );\n }\n\n // The merged-branch text, told in the flavour of the tree we are standing in: a linked worktree\n // is told to open a NEW worktree off origin/main and reap this dead one; the primary clone is\n // told to branch off origin/main. Neither is ever told to `git checkout main` (fatal in a\n // worktree). Detection is one statSync — see WorktreeService.isLinkedWorktree.\n private mergedMessage(judged: JudgedTree, mergedPr: string): string {\n const recovery = new TreeRecovery();\n const body = new MergedBranchMessage(judged.root).forReads(\n judged.branch, mergedPr, recovery.kindOf(judged.root), judged.root,\n );\n // NO redirect note here, deliberately — see feature-branch-guard.alreadyMergedMessage for the\n // argument. MergedBranchMessage already aims its commands at the judged root through `atRoot`\n // and prints the WORKTREE flavour of the cure when the judged tree is one.\n return [judged.header(), body].join('\\n');\n }\n\n\n private isConfigFile(relativePath: string): boolean {\n return relativePath === 'webpieces.config.json';\n }\n\n // StaleMainMessage's remaining consumer. It used to be shared with stale-main-bash-guard so the two\n // halves of the State-A block could never prescribe different cures; that guard now blocks on the\n // BRANCH (row 5) rather than on staleness and carries its own message, so this is the only caller.\n private staleMainMessage(judged: JudgedTree, commitsBehind: number): string {\n return [\n judged.header(),\n new StaleMainMessage(judged.root).forReads(String(commitsBehind)),\n judged.redirectNote([judged.pnpmCure('wp-sync-main')]),\n ].join('\\n');\n }\n\n private cacheSummary(status: MainSyncStatus): string {\n return this.freshness.summarize(status);\n }\n\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 /** The policy does not apply to this branch at all — logged `ALLOW_EXEMPT`, never confused with an approval. */\n private exempt(ctx: FileContext, branch: string, reason: string): readonly Violation[] {\n this.logDecision(ctx, branch, 'ALLOW_EXEMPT', reason, '-');\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('read-stale-guard', ctx.tool, ctx.relativePath, branch ?? 'unknown', verdict, reason, cache, L0_FAULT_NONE, matrixL2Row(reason)),\n );\n }\n\n /**\n * The current branch, WITHOUT spawning git for it. This runs on EVERY read, so it is the one call\n * whose cost matters most: `GitCheckout.branch()` reads the worktree's own HEAD file (primary clone\n * and linked worktree alike, detached HEAD included) with no git process at all (#1355).\n */\n private currentBranch(workspaceRoot: string): string | null {\n return gitCheckout.branch(workspaceRoot);\n }\n}\n"]}
|
|
@@ -166,7 +166,7 @@ class StaleMainBashGuardRule extends hook_runtime_2.BashRuleBase {
|
|
|
166
166
|
if (branch === null)
|
|
167
167
|
return this.failOpen(ctx, branch, 'branch-undeterminable');
|
|
168
168
|
// Keep the shared cache warm for the next call. Detached; never blocks this command.
|
|
169
|
-
(0, main_sync_refresh_1.triggerMainSyncRefresh)(ctx.workspaceRoot, (0, main_sync_timeout_1.hangTimeoutOf)(this.config));
|
|
169
|
+
(0, main_sync_refresh_1.triggerMainSyncRefresh)(ctx.workspaceRoot, branch, (0, main_sync_timeout_1.hangTimeoutOf)(this.config));
|
|
170
170
|
// State A is on `main` only. A merged feature branch is merged-branch-bash-guard's job.
|
|
171
171
|
if (branch !== 'main')
|
|
172
172
|
return this.allow(ctx, branch, 'not-on-main (state B is another guard)');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stale-main-bash-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/agent-workflow-rules/src/core/rules/stale-main-bash-guard.ts"],"names":[],"mappings":";;;AAAA,8DAAwD;AAExD,0DAAiD;AACjD,mDAA2D;AAC3D,mFAA2G;AAC3G,sEAAiG;AAGjG,0DAAyD;AACzD,0DAAuD;AACvD,0DAAkD;AAClD,4DAA8D;AAC9D,4DAAqD;AACrD,kDAAwF;AACxF,oDAAuF;AACvF,0DAAwD;AACxD,0DAAyD;AACzD,mDAA+C;AAC/C,6DAAwD;AACxD,6DAAyD;AACzD,qD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,aAAa,CAAC,aAAqB;QACvC,OAAO,4BAAW,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;IAC7C,CAAC;CACJ;AArQD,wDAqQC","sourcesContent":["import { gitCheckout } from '@webpieces/tooling-common';\n\nimport { Option } from '@webpieces/rules-config';\nimport { BRANCH_STATE_GUARD_KEY } from '../../policy-keys';\nimport { BranchStateGuardConfig, DEFAULT_MAX_COMMITS_BEHIND } from \"../../configs/main-sync-guard-configs\";\nimport { DEFAULT_HANG_TIMEOUT_MINUTES, readMainSyncStatus } from '@webpieces/repo-workflow-core';\n\nimport type { BashContext, Violation } from '@webpieces/hook-runtime';\nimport { Violation as V } from '@webpieces/hook-runtime';\nimport { BashRuleBase } from '@webpieces/hook-runtime';\nimport { FixHint } from '@webpieces/hook-runtime';\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 '@webpieces/rules-config';\nimport { CommandScanner } from '@webpieces/hook-runtime';\nimport { TreeRecovery } from './tree-recovery';\nimport { BranchSwitchScan } from './branch-switch-scan';\nimport { RecoveryAllowlist } from './recovery-allowlist';\nimport { MainFreshness } from './main-freshness';\nimport { CurePrefixScan, CurePrefix } from './cure-prefix-scan';\n\n/**\n * The BASH half of the STALE-MAIN protection (read-stale-guard's State A), in two halves of its own:\n * a PREVENTIVE check that stops a session landing on a stale `main`, and the REACTIVE check that\n * contains the damage once it is already there.\n *\n * ── PREVENTIVE: a bare `git checkout main` is blocked; the pull must ride along ──────────────────\n *\n * Everything below this paragraph fires only once the session is ALREADY sitting on a stale `main`.\n * Nothing stopped it ARRIVING there, and arriving is one keystroke. In the incident that added this\n * half, an agent ran `git checkout main` after a merge, in a clone whose local `main` was **157\n * commits behind** origin. That checkout did not merely produce stale files — it reverted:\n *\n * 1. `package.json`'s `@webpieces` pin, to a version OLDER than the installed `node_modules`;\n * 2. `.claude/webpieces/ai-hook.sh` — the version-drift guard ITSELF — to a 157-commit-old copy\n * whose message stated the drift BACKWARDS (\"your installed webpieces is older than required\")\n * and named a single cure, `pnpm install`;\n * 3. and so the agent's judgment: it ran that `pnpm install`, DOWNGRADING `node_modules` to match\n * the stale pin, and had to undo it with the `git pull` that should have come first.\n *\n * The shim on current main already diagnoses drift correctly — it distinguishes \"the pin is newer\"\n * from \"the pin is stale, and `pnpm install` would downgrade you\". None of that helped, because the\n * checkout had replaced the shim with the version that could not say it. **A guard a stale checkout\n * can revert cannot be relied on to catch a stale checkout**, which is why this check is preventive\n * and why it lives here rather than in a second rule: same failure, one step earlier, one switch.\n *\n * It matches on command TEXT alone and asks git nothing. That is not laziness — this runs BEFORE the\n * checkout, so the only `main` it could measure is the one it is about to leave. The interesting\n * `main` does not exist yet, and consulting HEAD-at-hook-time is the exact trap\n * `redirect-how-to-merge-main` documents at length. Pairing is unconditionally correct instead: when\n * `main` is already current the chained pull is a sub-second no-op, so no exception is worth carving.\n *\n * BLOCKED `git checkout main`, `git switch main` — with or without flags — when no `git pull`\n * appears anywhere in the SAME command.\n * ALLOWED `git checkout main && git pull origin main`, the pairing this forces — and\n * `pnpm wp-sync-main`, which IS that pairing with the cleanup and the\n * orphan-directory sweep welded on. The message prescribes the one command; the raw pair\n * stays legal because it is plain git and because it is the L0 recovery cure, where\n * `node_modules` is the thing in doubt and no `pnpm` bin can be relied on.\n * ALLOWED `git checkout -b <x> origin/main` (current by construction), `git checkout <sha>`,\n * `git checkout -- <file>`, and any other branch.\n *\n * ── ROWS 6/7: the block fires only beyond the configured stale threshold ────────────────────\n *\n * The finding is not \"you are on `main`\" — it is **\"what you would read here is out of date\"**. So the\n * ladder below asks the main-sync cache, exactly as read-stale-guard's State A does, and BLOCKS only\n * when cached `commitsBehind` is greater than `maxCommitsBehind`. Unknown → allow. At or below\n * the threshold → allow. The detached refresher computes the count; this hot path never does.\n *\n * WHY, when this guard spent a release judging the branch alone: because the branch alone denies\n * everything off a narrow allowlist on a PERFECTLY CURRENT `main`, and a current `main` is exactly\n * where the prescribed cure leaves you. An agent lands a PR, runs `pnpm wp-sync-main` — the\n * command this repo tells it to run — and the next `curl`, `gh pr close` or test run is refused by a\n * guard whose own name says STALE. The tool that got it there could not be the cure for being there,\n * and the refusal had nothing to do with staleness, which is the confusion reported from the field.\n *\n * THE ASYMMETRY WITH `E` IS DELIBERATE, and the docblocks that argued `B` should track `E` were right\n * about the mechanism and wrong about the policy. A WRITE on `main` creates work in the wrong place\n * whatever `main`'s freshness — unreviewable, and unrevertable as a unit — so feature-branch-guard\n * stays unconditional and keeps its one `git rev-parse`. A READ or a BUILD on a CURRENT `main` harms\n * nothing, and blocking it strands the agent at the exact moment the prescribed cure put it there.\n * Same tree, different hazard, so one precondition was never right for both.\n *\n * THE ANCESTRY TEST, NOT HASH EQUALITY. `MainFreshness.containsOriginMain` asks \"does local `main`\n * already contain the cached `origin/main`?\", so the block lifts the instant a pull lands rather than\n * waiting for the detached refresher to catch up. It is the SAME object read-stale-guard uses — one\n * implementation, so the Read and Bash halves of one state can never disagree about whether the pull\n * took.\n *\n * FAIL-OPEN ON EVERYTHING NOT ESTABLISHED, logged as `ALLOW_FAIL_OPEN` so abstentions stay countable:\n * no cache (the first call of every session), a cache for another branch, an empty `originMain`\n * (offline), no local `main` at all (fresh clone / worktree), branch undeterminable. The refresher is\n * fired detached on every call to keep the cache warm for the NEXT one; it is never waited on, and no\n * synchronous `git fetch` is ever run on the blocking path.\n *\n * THE POLARITY INSIDE THE BLOCKED STATE IS UNCHANGED: default-DENY plus row 4's skip list, the shape\n * merged-branch-bash-guard uses for state B, via the same shared RecoveryAllowlist. A content-read\n * BLOCKLIST could not replace it — enumerating readers catches `cat` and `grep`, and structurally\n * cannot catch `pnpm install`, `npx expo install`, a formatter, codegen or a `>` redirect: commands\n * whose stated purpose is something else and whose effect is to modify tracked files. What changed is\n * WHEN that polarity applies, not the polarity.\n *\n * BLOCKED on a `main` known beyond the configured threshold: anything not on the skip list — builds, tests,\n * installers, formatters, codegen, `cat`/`grep`/`ls` of the tree, git writes.\n * ALLOWED every command on a `main` that is current or whose freshness is unknown — and, in the\n * blocked state, everything that gets you OUT or tells you where you are:\n * `git checkout -b <new> origin/main`, `git switch`, `git pull`/`fetch`,\n * `git status|log|diff|show|branch`, `git stash`, `gh` (it talks to GitHub, not to this\n * tree), `curl`/`wget`, every `wp-*` bin, installs.\n *\n * ── ROWS 12/13: the cure may be COMPOSED with the work, but only with `&&` ───────────────────────\n *\n * `pnpm wp-sync-main && cat src/app.ts` is allowed and `pnpm wp-sync-main ; cat\n * src/app.ts` is not, and the difference is the shell's rather than this guard's: `&&` short-circuits,\n * so the work cannot run when the cure failed — the exact property the block is here to guarantee. `;`\n * discards the exit code and runs the work anyway. See cure-prefix-scan.ts for the measured shapes.\n *\n * There is no dirty-tree valve here and none in read-stale-guard either: the cure is\n * `git checkout -b`, which CARRIES uncommitted work onto the new branch, so a dirty tree traps nobody\n * in any L2 state. (`git stash` covers the residual where origin/main touched the same files.)\n */\nexport class StaleMainBashGuardRule extends BashRuleBase<BranchStateGuardConfig> {\n constructor(config: BranchStateGuardConfig) { super(config, 'stale-main-bash-guard', BRANCH_STATE_GUARD_KEY); }\n\n private readonly scanner = new CommandScanner();\n private readonly recovery = new TreeRecovery();\n private readonly switches = new BranchSwitchScan(this.scanner);\n // ROW 4, the skip list — the SAME instance-shape merged-branch-bash-guard uses, so the two states\n // cannot drift apart about what \"gets you out\" means. See recovery-allowlist.ts.\n private readonly recoveryList = new RecoveryAllowlist(this.scanner);\n // The ancestry test and the cache summary, shared with read-stale-guard — see main-freshness.ts.\n private readonly freshness = new MainFreshness();\n // ROWS 12/13 — `<cure> && <work>` vs `<cure> ; <work>`. See cure-prefix-scan.ts.\n private readonly curePrefix = new CurePrefixScan(this.scanner);\n\n readonly description =\n 'Block a bare `git checkout main` (use `pnpm wp-sync-main`, or chain the pull into ' +\n 'the same command), and — once local main is beyond maxCommitsBehind — block Bash ' +\n 'there, allowlisting only the commands that get you off it. A main that is current, or whose ' +\n 'freshness is unknown, is left alone.';\n override readonly defaultOptions = {\n hangTimeoutMinutes: DEFAULT_HANG_TIMEOUT_MINUTES,\n };\n readonly fixHint = new FixHint(\n 'Landing on `main` without pulling, or working on `main` at all, both put your work somewhere it does not belong.',\n 'Get onto a feature branch, or go to main with the one command that pulls it too:',\n [\n // TREE-SHAPED, from the one source of tree-shaped cures. A static rule-level hint has no\n // workspace root, so it renders the 'unknown' kind — TreeRecovery's deliberate answer for\n // \"we cannot detect the tree\": both forms, each labelled. That matters here because the\n // primary-clone form goes to `main`, and a linked worktree has no `main` to go to — it is\n // checked out in the primary clone — so a preferred option naming it unconditionally hands\n // the AI a cure that cannot work where it is standing. The per-block message\n // (pairingMessage) is detected and prints exactly one form; this is the fallback for the\n // hint that cannot look.\n new Option(this.recovery.updateMainSteps('unknown').join('\\n')\n + '\\nIf you hand-roll the git instead, the pull must be in the SAME command as the checkout.', true),\n new Option('Already on main: pnpm wp-sync-main (then re-run) — it pulls main and takes the trash out in the one command this repo prescribes. You may chain your command onto it with && (pnpm wp-sync-main && <your command>), which is skipped if the pull fails; a ; instead runs your command anyway and is refused.'),\n new Option('Still allowed: every BASH command, on a main at or below branch-state-guard.maxCommitsBehind or whose commit distance is not known. (Write/Edit on main is a different policy and is blocked by feature-branch-guard however current main is.) Beyond that threshold you keep the commands that get you OUT or tell you where you are: git checkout -b <new> origin/main, git switch, git pull/fetch, git status|log|diff|show|branch, git stash, gh, curl/wget, every wp-* bin, installs, and reading webpieces.config.json.'),\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: BashContext): readonly Violation[] {\n // PREVENTIVE half, FIRST and unconditional. Deliberately ahead of every fail-open bailout\n // below: those all ask \"is the main we are ON stale?\", and this asks about the main we are\n // about to MOVE TO — a different branch, and one no cache can describe yet.\n const bare = this.bareCheckoutOfMain(ctx);\n if (bare !== null) {\n return this.block(ctx, 'any', `bare checkout of main (${bare})`, this.pairingMessage(ctx), '-');\n }\n\n const branch = this.currentBranch(ctx.workspaceRoot);\n if (branch === null) return this.failOpen(ctx, branch, 'branch-undeterminable');\n\n // Keep the shared cache warm for the next call. Detached; never blocks this command.\n triggerMainSyncRefresh(ctx.workspaceRoot, hangTimeoutOf(this.config));\n\n // State A is on `main` only. A merged feature branch is merged-branch-bash-guard's job.\n if (branch !== 'main') return this.allow(ctx, branch, 'not-on-main (state B is another guard)');\n\n // ROW 4 — the skip list, ahead of the block, so no command that gets you OUT is ever denied.\n if (this.recoveryList.isFullyRecovery(ctx)) {\n return this.allow(ctx, branch, 'not-a-content-read (cure/build/metadata)');\n }\n\n return this.checkFreshness(ctx, branch);\n }\n\n /**\n * ROWS 6/7 — block ONLY when cached `commitsBehind` exceeds `maxCommitsBehind`.\n *\n * Read this beside read-stale-guard.checkStaleMain: it is the same ladder over the same cache, and\n * that is on purpose — the Read and the Bash halves of one state must not disagree about whether\n * `main` is stale. What differs is the VERDICT SHAPE once it is stale, because a Read names one\n * file and a Bash command is opaque: the Read is judged per file, Bash is default-deny plus the\n * row 4 skip list already applied above.\n *\n * Every exit that is not \"established BEHIND\" is an ALLOW, and the not-established ones are\n * `ALLOW_FAIL_OPEN` so they stay countable. A guard that cannot see the state judges nothing.\n */\n private checkFreshness(ctx: BashContext, branch: string): readonly Violation[] {\n const status = readMainSyncStatus(ctx.workspaceRoot, 'main');\n // The first call of every session, and every call while another worktree holds the refresh\n // lock. The refresher fired above populates it for the NEXT call; nothing waits here.\n if (status === null) return this.failOpen(ctx, branch, 'no-sync-cache', 'cache=none');\n\n const cache = this.freshness.summarize(status);\n // BELT-AND-BRACES since the cache became branch-keyed: we asked for the 'main' entry BY KEY, so\n // a mismatch means the map's key and the entry's own `branch` disagree — a shape bug. Kept so\n // that degrades to an allow. Unreachable in normal operation.\n if (status.branch !== 'main') return this.failOpen(ctx, branch, 'stale-cross-branch-cache', cache);\n // Offline / origin unresolvable, or no local main to compare against.\n if (status.originMain === '') return this.failOpen(ctx, branch, 'origin-main-unknown', cache);\n\n // ANCESTRY, not equality — the line that makes a pull take effect immediately. See\n // MainFreshness.containsOriginMain.\n if (this.freshness.containsOriginMain(ctx.workspaceRoot, status.originMain)) {\n return this.allow(ctx, branch, 'local-main-contains-origin (up to date)', cache);\n }\n\n const maxCommitsBehind = this.config.maxCommitsBehind ?? DEFAULT_MAX_COMMITS_BEHIND;\n const withinThreshold = this.freshness.isWithinAllowedDrift(status, maxCommitsBehind);\n if (withinThreshold === null) return this.failOpen(ctx, branch, 'commit-distance-unknown', cache);\n if (withinThreshold) return this.allow(ctx, branch, 'within-max-commits-behind', cache);\n\n // ESTABLISHED BEYOND THE CONFIGURED THRESHOLD. Only now does default-deny apply.\n return this.judgeComposition(ctx, branch, cache, status.commitsBehind ?? 0, maxCommitsBehind);\n }\n\n /**\n * ROWS 12/13 — `<cure> && <work>` is allowed; `<cure> ; <work>` is not.\n *\n * The distinction is the shell's, not this guard's invention. `&&` short-circuits, so the work\n * cannot run when the cure exits non-zero — which is precisely the property the block exists to\n * guarantee, already enforced by the interpreter. Refusing it bought nothing and cost a round\n * trip, and the fleet audit files that as a TOOLING defect.\n *\n * `;` discards the exit code and runs the work regardless, and it was measured with\n * `>/dev/null 2>&1` on the cure in 7 of 9 observed cases — so the failure was invisible as well as\n * ignored. The two-step is genuinely safer there: the NEXT tool call is a fresh evaluation that\n * recomputes `localMain` against `originMain`, so a pull that failed re-blocks. An allowed `;`\n * compound never gets that second look.\n */\n private judgeComposition(\n ctx: BashContext, branch: string, cache: string, commitsBehind: number, maxCommitsBehind: number,\n ): readonly Violation[] {\n const prefix = this.curePrefix.classify(ctx.command);\n if (prefix.kind === 'short-circuits') {\n return this.allow(ctx, branch, 'cure-prefixed, && short-circuits the work', cache);\n }\n if (prefix.kind === 'runs-anyway') {\n return this.block(ctx, branch, 'cure-prefixed, work runs anyway', this.compositionMessage(prefix), cache);\n }\n return this.block(\n ctx, branch, 'on-stale-main',\n this.staleMainMessage(ctx.workspaceRoot, commitsBehind, maxCommitsBehind), cache);\n }\n\n /**\n * The first segment that switches to the `main` BRANCH with no `git pull` anywhere in the same\n * command, or null. The pull is looked for across the WHOLE command, not the matched segment,\n * because `git checkout main && git pull origin main` splits into two segments and the pairing is\n * the point.\n */\n private bareCheckoutOfMain(ctx: BashContext): string | null {\n for (const segment of this.scanner.commandSegments(ctx.command)) {\n // BranchSwitchScan answers \"which branch does this land on\" for both guards, flag-tolerantly:\n // `git checkout -q main` lands on main exactly as the bare form does, while\n // `git checkout -b x origin/main` (creates), `git checkout -- main` (pathspec) and\n // `git checkout <sha>` do not. See branch-switch-scan.ts for why that lives in one place.\n if (!this.switches.landsOnExistingMain(segment)) continue;\n return this.scanner.commandInvokesAnyGit(ctx.command, ['pull']) ? null : segment;\n }\n return null;\n }\n\n /**\n * The stale-`main` deny. Deliberately SHORT, and now deliberately ABOUT STALENESS — which is what\n * the guard's name promised all along.\n *\n * The two versions before this one are both instructive. The oldest opened with how many commits\n * behind `main` was, which invited the wrong cure: an agent that reads \"behind\" reaches for a pull,\n * lands on a CURRENT `main`, and is still on `main`. The one after it swung the other way and said\n * `main` is not a place to work \"whether or not it is current\" — true of a WRITE, but this guard\n * does not see writes, and it made every refusal on a freshly-pulled `main` unanswerable.\n *\n * So the text says what is now actually true and nothing more: local `main` is BEHIND, so what you\n * read here is out of date; Bash is default-deny in this state rather than a list of readers,\n * because a command's stated purpose never says whether it also WRITES; and the branch cure fetches,\n * so it makes the reads true as well as moving the work somewhere reviewable. Reading `main` to PLAN\n * stays legitimate — on a CURRENT `main` nothing here fires at all.\n *\n * ONE cure, and it is the dirty-safe one, the same call feature-branch-guard made: `git checkout -b`\n * carries uncommitted work onto the new branch. (Row 6 also lists the pull, and read-stale-guard\n * prints it, because a Read really can be cured by staying put. A Bash session cannot — the next\n * command is as likely to write as to read.)\n */\n private staleMainMessage(workspaceRoot: string, commitsBehind: number, maxCommitsBehind: number): string {\n return `Blocked: local \\`main\\` is ${commitsBehind} commits behind origin/main, exceeding `\n + `branch-state-guard.maxCommitsBehind=${maxCommitsBehind}, so what you would read here is out of `\n + 'date and a plan built on it is built on code upstream has moved past. A CURRENT main is '\n + 'not blocked — reading main to PLAN is fine, and this fires only once being behind is '\n + 'established. Bash is default-deny in this state rather than a list of readers, because a '\n + \"command's stated purpose never says whether it also WRITES. The feature branch is the \"\n + 'unit of work in any case: reviewable, revertable — and the cure fetches, so it makes '\n + 'your reads true as well as moving you off main.\\n'\n + `Start a branch (uncommitted work comes with you):\\n cd '${workspaceRoot}' && git fetch origin main && git checkout -b <new-branch> origin/main`;\n }\n\n /**\n * ROW 13's deny. It NAMES the operator the agent typed, because the fix is a one-character edit\n * and an agent told only \"use `&&`\" has to diff the two spellings itself to find where.\n */\n private compositionMessage(prefix: CurePrefix): string {\n return `Your cure is joined with \\`${prefix.operator}\\` — the work runs even if the pull fails. `\n + 'Use `&&` so it is skipped:\\n'\n + '\\n pnpm wp-sync-main && <your command>\\n\\n'\n + 'Or run the cure alone and re-issue your command in the next call.';\n }\n\n private pairingMessage(ctx: BashContext): string {\n const steps = this.recovery.updateMainSteps(this.recovery.kindOf(ctx.workspaceRoot)).join('\\n');\n // Deliberately SHORT. The incident that bought this guard (a main 157 commits behind; the\n // downgrade the reverted shim then prescribed) is maintainer material and lives in the class\n // docblock above — the reader of THIS text needs only what changes what they type.\n return 'Blocked: a bare `git checkout main` lands you on whatever local `main` you last had — '\n + 'stale files, plus a reverted @webpieces pin and guard shim, so the drift guard then '\n + 'reports the drift BACKWARDS. Go to main with the one command that also pulls it:\\n' + steps;\n }\n\n\n\n\n\n\n\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: BashContext, 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: BashContext, 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: BashContext, 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, the same way an L0 block does. The doc is written\n // LAZILY here rather than up front: only a blocked agent needs it, and this is the one path\n // that knows the row it should be opened at.\n const row = matrixL2Row(reason).row;\n const pointer = branchStateMatrixPointer(writeBranchStateMatrixDoc(ctx.workspaceRoot), row);\n return [new V(1, this.truncate(ctx.command), message + pointer)];\n }\n\n private truncate(s: string): string {\n const MAX = 120;\n return s.length <= MAX ? s : s.slice(0, MAX) + '…';\n }\n\n private logDecision(ctx: BashContext, branch: string | null, verdict: Verdict, reason: string, cache: string): void {\n logGuardDecision(\n ctx.workspaceRoot,\n new GuardDecision('stale-main-bash-guard', 'Bash', ctx.command, branch ?? 'unknown', verdict, reason, cache, L0_FAULT_NONE, matrixL2Row(reason)),\n );\n }\n\n private currentBranch(workspaceRoot: string): string | null {\n return gitCheckout.branch(workspaceRoot);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"stale-main-bash-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/agent-workflow-rules/src/core/rules/stale-main-bash-guard.ts"],"names":[],"mappings":";;;AAAA,8DAAwD;AAExD,0DAAiD;AACjD,mDAA2D;AAC3D,mFAA2G;AAC3G,sEAAiG;AAGjG,0DAAyD;AACzD,0DAA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,EAAE,GAAG,CAAC,OAAO,EAAE,MAAM,IAAI,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,4BAAa,EAAE,IAAA,0BAAW,EAAC,MAAM,CAAC,CAAC,CACnJ,CAAC;IACN,CAAC;IAEO,aAAa,CAAC,aAAqB;QACvC,OAAO,4BAAW,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;IAC7C,CAAC;CACJ;AArQD,wDAqQC","sourcesContent":["import { gitCheckout } from '@webpieces/tooling-common';\n\nimport { Option } from '@webpieces/rules-config';\nimport { BRANCH_STATE_GUARD_KEY } from '../../policy-keys';\nimport { BranchStateGuardConfig, DEFAULT_MAX_COMMITS_BEHIND } from \"../../configs/main-sync-guard-configs\";\nimport { DEFAULT_HANG_TIMEOUT_MINUTES, readMainSyncStatus } from '@webpieces/repo-workflow-core';\n\nimport type { BashContext, Violation } from '@webpieces/hook-runtime';\nimport { Violation as V } from '@webpieces/hook-runtime';\nimport { BashRuleBase } from '@webpieces/hook-runtime';\nimport { FixHint } from '@webpieces/hook-runtime';\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 '@webpieces/rules-config';\nimport { CommandScanner } from '@webpieces/hook-runtime';\nimport { TreeRecovery } from './tree-recovery';\nimport { BranchSwitchScan } from './branch-switch-scan';\nimport { RecoveryAllowlist } from './recovery-allowlist';\nimport { MainFreshness } from './main-freshness';\nimport { CurePrefixScan, CurePrefix } from './cure-prefix-scan';\n\n/**\n * The BASH half of the STALE-MAIN protection (read-stale-guard's State A), in two halves of its own:\n * a PREVENTIVE check that stops a session landing on a stale `main`, and the REACTIVE check that\n * contains the damage once it is already there.\n *\n * ── PREVENTIVE: a bare `git checkout main` is blocked; the pull must ride along ──────────────────\n *\n * Everything below this paragraph fires only once the session is ALREADY sitting on a stale `main`.\n * Nothing stopped it ARRIVING there, and arriving is one keystroke. In the incident that added this\n * half, an agent ran `git checkout main` after a merge, in a clone whose local `main` was **157\n * commits behind** origin. That checkout did not merely produce stale files — it reverted:\n *\n * 1. `package.json`'s `@webpieces` pin, to a version OLDER than the installed `node_modules`;\n * 2. `.claude/webpieces/ai-hook.sh` — the version-drift guard ITSELF — to a 157-commit-old copy\n * whose message stated the drift BACKWARDS (\"your installed webpieces is older than required\")\n * and named a single cure, `pnpm install`;\n * 3. and so the agent's judgment: it ran that `pnpm install`, DOWNGRADING `node_modules` to match\n * the stale pin, and had to undo it with the `git pull` that should have come first.\n *\n * The shim on current main already diagnoses drift correctly — it distinguishes \"the pin is newer\"\n * from \"the pin is stale, and `pnpm install` would downgrade you\". None of that helped, because the\n * checkout had replaced the shim with the version that could not say it. **A guard a stale checkout\n * can revert cannot be relied on to catch a stale checkout**, which is why this check is preventive\n * and why it lives here rather than in a second rule: same failure, one step earlier, one switch.\n *\n * It matches on command TEXT alone and asks git nothing. That is not laziness — this runs BEFORE the\n * checkout, so the only `main` it could measure is the one it is about to leave. The interesting\n * `main` does not exist yet, and consulting HEAD-at-hook-time is the exact trap\n * `redirect-how-to-merge-main` documents at length. Pairing is unconditionally correct instead: when\n * `main` is already current the chained pull is a sub-second no-op, so no exception is worth carving.\n *\n * BLOCKED `git checkout main`, `git switch main` — with or without flags — when no `git pull`\n * appears anywhere in the SAME command.\n * ALLOWED `git checkout main && git pull origin main`, the pairing this forces — and\n * `pnpm wp-sync-main`, which IS that pairing with the cleanup and the\n * orphan-directory sweep welded on. The message prescribes the one command; the raw pair\n * stays legal because it is plain git and because it is the L0 recovery cure, where\n * `node_modules` is the thing in doubt and no `pnpm` bin can be relied on.\n * ALLOWED `git checkout -b <x> origin/main` (current by construction), `git checkout <sha>`,\n * `git checkout -- <file>`, and any other branch.\n *\n * ── ROWS 6/7: the block fires only beyond the configured stale threshold ────────────────────\n *\n * The finding is not \"you are on `main`\" — it is **\"what you would read here is out of date\"**. So the\n * ladder below asks the main-sync cache, exactly as read-stale-guard's State A does, and BLOCKS only\n * when cached `commitsBehind` is greater than `maxCommitsBehind`. Unknown → allow. At or below\n * the threshold → allow. The detached refresher computes the count; this hot path never does.\n *\n * WHY, when this guard spent a release judging the branch alone: because the branch alone denies\n * everything off a narrow allowlist on a PERFECTLY CURRENT `main`, and a current `main` is exactly\n * where the prescribed cure leaves you. An agent lands a PR, runs `pnpm wp-sync-main` — the\n * command this repo tells it to run — and the next `curl`, `gh pr close` or test run is refused by a\n * guard whose own name says STALE. The tool that got it there could not be the cure for being there,\n * and the refusal had nothing to do with staleness, which is the confusion reported from the field.\n *\n * THE ASYMMETRY WITH `E` IS DELIBERATE, and the docblocks that argued `B` should track `E` were right\n * about the mechanism and wrong about the policy. A WRITE on `main` creates work in the wrong place\n * whatever `main`'s freshness — unreviewable, and unrevertable as a unit — so feature-branch-guard\n * stays unconditional and keeps its one `git rev-parse`. A READ or a BUILD on a CURRENT `main` harms\n * nothing, and blocking it strands the agent at the exact moment the prescribed cure put it there.\n * Same tree, different hazard, so one precondition was never right for both.\n *\n * THE ANCESTRY TEST, NOT HASH EQUALITY. `MainFreshness.containsOriginMain` asks \"does local `main`\n * already contain the cached `origin/main`?\", so the block lifts the instant a pull lands rather than\n * waiting for the detached refresher to catch up. It is the SAME object read-stale-guard uses — one\n * implementation, so the Read and Bash halves of one state can never disagree about whether the pull\n * took.\n *\n * FAIL-OPEN ON EVERYTHING NOT ESTABLISHED, logged as `ALLOW_FAIL_OPEN` so abstentions stay countable:\n * no cache (the first call of every session), a cache for another branch, an empty `originMain`\n * (offline), no local `main` at all (fresh clone / worktree), branch undeterminable. The refresher is\n * fired detached on every call to keep the cache warm for the NEXT one; it is never waited on, and no\n * synchronous `git fetch` is ever run on the blocking path.\n *\n * THE POLARITY INSIDE THE BLOCKED STATE IS UNCHANGED: default-DENY plus row 4's skip list, the shape\n * merged-branch-bash-guard uses for state B, via the same shared RecoveryAllowlist. A content-read\n * BLOCKLIST could not replace it — enumerating readers catches `cat` and `grep`, and structurally\n * cannot catch `pnpm install`, `npx expo install`, a formatter, codegen or a `>` redirect: commands\n * whose stated purpose is something else and whose effect is to modify tracked files. What changed is\n * WHEN that polarity applies, not the polarity.\n *\n * BLOCKED on a `main` known beyond the configured threshold: anything not on the skip list — builds, tests,\n * installers, formatters, codegen, `cat`/`grep`/`ls` of the tree, git writes.\n * ALLOWED every command on a `main` that is current or whose freshness is unknown — and, in the\n * blocked state, everything that gets you OUT or tells you where you are:\n * `git checkout -b <new> origin/main`, `git switch`, `git pull`/`fetch`,\n * `git status|log|diff|show|branch`, `git stash`, `gh` (it talks to GitHub, not to this\n * tree), `curl`/`wget`, every `wp-*` bin, installs.\n *\n * ── ROWS 12/13: the cure may be COMPOSED with the work, but only with `&&` ───────────────────────\n *\n * `pnpm wp-sync-main && cat src/app.ts` is allowed and `pnpm wp-sync-main ; cat\n * src/app.ts` is not, and the difference is the shell's rather than this guard's: `&&` short-circuits,\n * so the work cannot run when the cure failed — the exact property the block is here to guarantee. `;`\n * discards the exit code and runs the work anyway. See cure-prefix-scan.ts for the measured shapes.\n *\n * There is no dirty-tree valve here and none in read-stale-guard either: the cure is\n * `git checkout -b`, which CARRIES uncommitted work onto the new branch, so a dirty tree traps nobody\n * in any L2 state. (`git stash` covers the residual where origin/main touched the same files.)\n */\nexport class StaleMainBashGuardRule extends BashRuleBase<BranchStateGuardConfig> {\n constructor(config: BranchStateGuardConfig) { super(config, 'stale-main-bash-guard', BRANCH_STATE_GUARD_KEY); }\n\n private readonly scanner = new CommandScanner();\n private readonly recovery = new TreeRecovery();\n private readonly switches = new BranchSwitchScan(this.scanner);\n // ROW 4, the skip list — the SAME instance-shape merged-branch-bash-guard uses, so the two states\n // cannot drift apart about what \"gets you out\" means. See recovery-allowlist.ts.\n private readonly recoveryList = new RecoveryAllowlist(this.scanner);\n // The ancestry test and the cache summary, shared with read-stale-guard — see main-freshness.ts.\n private readonly freshness = new MainFreshness();\n // ROWS 12/13 — `<cure> && <work>` vs `<cure> ; <work>`. See cure-prefix-scan.ts.\n private readonly curePrefix = new CurePrefixScan(this.scanner);\n\n readonly description =\n 'Block a bare `git checkout main` (use `pnpm wp-sync-main`, or chain the pull into ' +\n 'the same command), and — once local main is beyond maxCommitsBehind — block Bash ' +\n 'there, allowlisting only the commands that get you off it. A main that is current, or whose ' +\n 'freshness is unknown, is left alone.';\n override readonly defaultOptions = {\n hangTimeoutMinutes: DEFAULT_HANG_TIMEOUT_MINUTES,\n };\n readonly fixHint = new FixHint(\n 'Landing on `main` without pulling, or working on `main` at all, both put your work somewhere it does not belong.',\n 'Get onto a feature branch, or go to main with the one command that pulls it too:',\n [\n // TREE-SHAPED, from the one source of tree-shaped cures. A static rule-level hint has no\n // workspace root, so it renders the 'unknown' kind — TreeRecovery's deliberate answer for\n // \"we cannot detect the tree\": both forms, each labelled. That matters here because the\n // primary-clone form goes to `main`, and a linked worktree has no `main` to go to — it is\n // checked out in the primary clone — so a preferred option naming it unconditionally hands\n // the AI a cure that cannot work where it is standing. The per-block message\n // (pairingMessage) is detected and prints exactly one form; this is the fallback for the\n // hint that cannot look.\n new Option(this.recovery.updateMainSteps('unknown').join('\\n')\n + '\\nIf you hand-roll the git instead, the pull must be in the SAME command as the checkout.', true),\n new Option('Already on main: pnpm wp-sync-main (then re-run) — it pulls main and takes the trash out in the one command this repo prescribes. You may chain your command onto it with && (pnpm wp-sync-main && <your command>), which is skipped if the pull fails; a ; instead runs your command anyway and is refused.'),\n new Option('Still allowed: every BASH command, on a main at or below branch-state-guard.maxCommitsBehind or whose commit distance is not known. (Write/Edit on main is a different policy and is blocked by feature-branch-guard however current main is.) Beyond that threshold you keep the commands that get you OUT or tell you where you are: git checkout -b <new> origin/main, git switch, git pull/fetch, git status|log|diff|show|branch, git stash, gh, curl/wget, every wp-* bin, installs, and reading webpieces.config.json.'),\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: BashContext): readonly Violation[] {\n // PREVENTIVE half, FIRST and unconditional. Deliberately ahead of every fail-open bailout\n // below: those all ask \"is the main we are ON stale?\", and this asks about the main we are\n // about to MOVE TO — a different branch, and one no cache can describe yet.\n const bare = this.bareCheckoutOfMain(ctx);\n if (bare !== null) {\n return this.block(ctx, 'any', `bare checkout of main (${bare})`, this.pairingMessage(ctx), '-');\n }\n\n const branch = this.currentBranch(ctx.workspaceRoot);\n if (branch === null) return this.failOpen(ctx, branch, 'branch-undeterminable');\n\n // Keep the shared cache warm for the next call. Detached; never blocks this command.\n triggerMainSyncRefresh(ctx.workspaceRoot, branch, hangTimeoutOf(this.config));\n\n // State A is on `main` only. A merged feature branch is merged-branch-bash-guard's job.\n if (branch !== 'main') return this.allow(ctx, branch, 'not-on-main (state B is another guard)');\n\n // ROW 4 — the skip list, ahead of the block, so no command that gets you OUT is ever denied.\n if (this.recoveryList.isFullyRecovery(ctx)) {\n return this.allow(ctx, branch, 'not-a-content-read (cure/build/metadata)');\n }\n\n return this.checkFreshness(ctx, branch);\n }\n\n /**\n * ROWS 6/7 — block ONLY when cached `commitsBehind` exceeds `maxCommitsBehind`.\n *\n * Read this beside read-stale-guard.checkStaleMain: it is the same ladder over the same cache, and\n * that is on purpose — the Read and the Bash halves of one state must not disagree about whether\n * `main` is stale. What differs is the VERDICT SHAPE once it is stale, because a Read names one\n * file and a Bash command is opaque: the Read is judged per file, Bash is default-deny plus the\n * row 4 skip list already applied above.\n *\n * Every exit that is not \"established BEHIND\" is an ALLOW, and the not-established ones are\n * `ALLOW_FAIL_OPEN` so they stay countable. A guard that cannot see the state judges nothing.\n */\n private checkFreshness(ctx: BashContext, branch: string): readonly Violation[] {\n const status = readMainSyncStatus(ctx.workspaceRoot, 'main');\n // The first call of every session, and every call while another worktree holds the refresh\n // lock. The refresher fired above populates it for the NEXT call; nothing waits here.\n if (status === null) return this.failOpen(ctx, branch, 'no-sync-cache', 'cache=none');\n\n const cache = this.freshness.summarize(status);\n // BELT-AND-BRACES since the cache became branch-keyed: we asked for the 'main' entry BY KEY, so\n // a mismatch means the map's key and the entry's own `branch` disagree — a shape bug. Kept so\n // that degrades to an allow. Unreachable in normal operation.\n if (status.branch !== 'main') return this.failOpen(ctx, branch, 'stale-cross-branch-cache', cache);\n // Offline / origin unresolvable, or no local main to compare against.\n if (status.originMain === '') return this.failOpen(ctx, branch, 'origin-main-unknown', cache);\n\n // ANCESTRY, not equality — the line that makes a pull take effect immediately. See\n // MainFreshness.containsOriginMain.\n if (this.freshness.containsOriginMain(ctx.workspaceRoot, status.originMain)) {\n return this.allow(ctx, branch, 'local-main-contains-origin (up to date)', cache);\n }\n\n const maxCommitsBehind = this.config.maxCommitsBehind ?? DEFAULT_MAX_COMMITS_BEHIND;\n const withinThreshold = this.freshness.isWithinAllowedDrift(status, maxCommitsBehind);\n if (withinThreshold === null) return this.failOpen(ctx, branch, 'commit-distance-unknown', cache);\n if (withinThreshold) return this.allow(ctx, branch, 'within-max-commits-behind', cache);\n\n // ESTABLISHED BEYOND THE CONFIGURED THRESHOLD. Only now does default-deny apply.\n return this.judgeComposition(ctx, branch, cache, status.commitsBehind ?? 0, maxCommitsBehind);\n }\n\n /**\n * ROWS 12/13 — `<cure> && <work>` is allowed; `<cure> ; <work>` is not.\n *\n * The distinction is the shell's, not this guard's invention. `&&` short-circuits, so the work\n * cannot run when the cure exits non-zero — which is precisely the property the block exists to\n * guarantee, already enforced by the interpreter. Refusing it bought nothing and cost a round\n * trip, and the fleet audit files that as a TOOLING defect.\n *\n * `;` discards the exit code and runs the work regardless, and it was measured with\n * `>/dev/null 2>&1` on the cure in 7 of 9 observed cases — so the failure was invisible as well as\n * ignored. The two-step is genuinely safer there: the NEXT tool call is a fresh evaluation that\n * recomputes `localMain` against `originMain`, so a pull that failed re-blocks. An allowed `;`\n * compound never gets that second look.\n */\n private judgeComposition(\n ctx: BashContext, branch: string, cache: string, commitsBehind: number, maxCommitsBehind: number,\n ): readonly Violation[] {\n const prefix = this.curePrefix.classify(ctx.command);\n if (prefix.kind === 'short-circuits') {\n return this.allow(ctx, branch, 'cure-prefixed, && short-circuits the work', cache);\n }\n if (prefix.kind === 'runs-anyway') {\n return this.block(ctx, branch, 'cure-prefixed, work runs anyway', this.compositionMessage(prefix), cache);\n }\n return this.block(\n ctx, branch, 'on-stale-main',\n this.staleMainMessage(ctx.workspaceRoot, commitsBehind, maxCommitsBehind), cache);\n }\n\n /**\n * The first segment that switches to the `main` BRANCH with no `git pull` anywhere in the same\n * command, or null. The pull is looked for across the WHOLE command, not the matched segment,\n * because `git checkout main && git pull origin main` splits into two segments and the pairing is\n * the point.\n */\n private bareCheckoutOfMain(ctx: BashContext): string | null {\n for (const segment of this.scanner.commandSegments(ctx.command)) {\n // BranchSwitchScan answers \"which branch does this land on\" for both guards, flag-tolerantly:\n // `git checkout -q main` lands on main exactly as the bare form does, while\n // `git checkout -b x origin/main` (creates), `git checkout -- main` (pathspec) and\n // `git checkout <sha>` do not. See branch-switch-scan.ts for why that lives in one place.\n if (!this.switches.landsOnExistingMain(segment)) continue;\n return this.scanner.commandInvokesAnyGit(ctx.command, ['pull']) ? null : segment;\n }\n return null;\n }\n\n /**\n * The stale-`main` deny. Deliberately SHORT, and now deliberately ABOUT STALENESS — which is what\n * the guard's name promised all along.\n *\n * The two versions before this one are both instructive. The oldest opened with how many commits\n * behind `main` was, which invited the wrong cure: an agent that reads \"behind\" reaches for a pull,\n * lands on a CURRENT `main`, and is still on `main`. The one after it swung the other way and said\n * `main` is not a place to work \"whether or not it is current\" — true of a WRITE, but this guard\n * does not see writes, and it made every refusal on a freshly-pulled `main` unanswerable.\n *\n * So the text says what is now actually true and nothing more: local `main` is BEHIND, so what you\n * read here is out of date; Bash is default-deny in this state rather than a list of readers,\n * because a command's stated purpose never says whether it also WRITES; and the branch cure fetches,\n * so it makes the reads true as well as moving the work somewhere reviewable. Reading `main` to PLAN\n * stays legitimate — on a CURRENT `main` nothing here fires at all.\n *\n * ONE cure, and it is the dirty-safe one, the same call feature-branch-guard made: `git checkout -b`\n * carries uncommitted work onto the new branch. (Row 6 also lists the pull, and read-stale-guard\n * prints it, because a Read really can be cured by staying put. A Bash session cannot — the next\n * command is as likely to write as to read.)\n */\n private staleMainMessage(workspaceRoot: string, commitsBehind: number, maxCommitsBehind: number): string {\n return `Blocked: local \\`main\\` is ${commitsBehind} commits behind origin/main, exceeding `\n + `branch-state-guard.maxCommitsBehind=${maxCommitsBehind}, so what you would read here is out of `\n + 'date and a plan built on it is built on code upstream has moved past. A CURRENT main is '\n + 'not blocked — reading main to PLAN is fine, and this fires only once being behind is '\n + 'established. Bash is default-deny in this state rather than a list of readers, because a '\n + \"command's stated purpose never says whether it also WRITES. The feature branch is the \"\n + 'unit of work in any case: reviewable, revertable — and the cure fetches, so it makes '\n + 'your reads true as well as moving you off main.\\n'\n + `Start a branch (uncommitted work comes with you):\\n cd '${workspaceRoot}' && git fetch origin main && git checkout -b <new-branch> origin/main`;\n }\n\n /**\n * ROW 13's deny. It NAMES the operator the agent typed, because the fix is a one-character edit\n * and an agent told only \"use `&&`\" has to diff the two spellings itself to find where.\n */\n private compositionMessage(prefix: CurePrefix): string {\n return `Your cure is joined with \\`${prefix.operator}\\` — the work runs even if the pull fails. `\n + 'Use `&&` so it is skipped:\\n'\n + '\\n pnpm wp-sync-main && <your command>\\n\\n'\n + 'Or run the cure alone and re-issue your command in the next call.';\n }\n\n private pairingMessage(ctx: BashContext): string {\n const steps = this.recovery.updateMainSteps(this.recovery.kindOf(ctx.workspaceRoot)).join('\\n');\n // Deliberately SHORT. The incident that bought this guard (a main 157 commits behind; the\n // downgrade the reverted shim then prescribed) is maintainer material and lives in the class\n // docblock above — the reader of THIS text needs only what changes what they type.\n return 'Blocked: a bare `git checkout main` lands you on whatever local `main` you last had — '\n + 'stale files, plus a reverted @webpieces pin and guard shim, so the drift guard then '\n + 'reports the drift BACKWARDS. Go to main with the one command that also pulls it:\\n' + steps;\n }\n\n\n\n\n\n\n\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: BashContext, 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: BashContext, 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: BashContext, 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, the same way an L0 block does. The doc is written\n // LAZILY here rather than up front: only a blocked agent needs it, and this is the one path\n // that knows the row it should be opened at.\n const row = matrixL2Row(reason).row;\n const pointer = branchStateMatrixPointer(writeBranchStateMatrixDoc(ctx.workspaceRoot), row);\n return [new V(1, this.truncate(ctx.command), message + pointer)];\n }\n\n private truncate(s: string): string {\n const MAX = 120;\n return s.length <= MAX ? s : s.slice(0, MAX) + '…';\n }\n\n private logDecision(ctx: BashContext, branch: string | null, verdict: Verdict, reason: string, cache: string): void {\n logGuardDecision(\n ctx.workspaceRoot,\n new GuardDecision('stale-main-bash-guard', 'Bash', ctx.command, branch ?? 'unknown', verdict, reason, cache, L0_FAULT_NONE, matrixL2Row(reason)),\n );\n }\n\n private currentBranch(workspaceRoot: string): string | null {\n return gitCheckout.branch(workspaceRoot);\n }\n}\n"]}
|
package/src/core/sync-main.d.ts
CHANGED
|
@@ -7,7 +7,8 @@ import { StreamIdentity } from './log-stream';
|
|
|
7
7
|
*
|
|
8
8
|
* Concurrency: `.webpieces/main-sync.lock.json` is a mutex whose EXISTENCE is the lock (it holds only
|
|
9
9
|
* the holder's pid and start epoch). The SPAWNER creates it exclusively (main-sync-refresh.ts →
|
|
10
|
-
* claimRefresh), only once MIN_REFRESH_INTERVAL_MINUTES have passed since the last start
|
|
10
|
+
* claimRefresh), only once MIN_REFRESH_INTERVAL_MINUTES have passed since the last start (at once for a
|
|
11
|
+
* branch the status file has never seen, #1377), and passes
|
|
11
12
|
* its `startedMs` on argv. This child ADOPTS that lock (rewriting the pid to its own) and never creates
|
|
12
13
|
* one itself, so it cannot race its spawner. A lock that is no longer on disk (reclaimed while this
|
|
13
14
|
* child booted) means another refresher owns the run, and we exit.
|
package/src/core/sync-main.js
CHANGED
|
@@ -20,7 +20,8 @@ const locks = new repo_workflow_core_1.MainSyncLockService(undefined, undefined,
|
|
|
20
20
|
*
|
|
21
21
|
* Concurrency: `.webpieces/main-sync.lock.json` is a mutex whose EXISTENCE is the lock (it holds only
|
|
22
22
|
* the holder's pid and start epoch). The SPAWNER creates it exclusively (main-sync-refresh.ts →
|
|
23
|
-
* claimRefresh), only once MIN_REFRESH_INTERVAL_MINUTES have passed since the last start
|
|
23
|
+
* claimRefresh), only once MIN_REFRESH_INTERVAL_MINUTES have passed since the last start (at once for a
|
|
24
|
+
* branch the status file has never seen, #1377), and passes
|
|
24
25
|
* its `startedMs` on argv. This child ADOPTS that lock (rewriting the pid to its own) and never creates
|
|
25
26
|
* one itself, so it cannot race its spawner. A lock that is no longer on disk (reclaimed while this
|
|
26
27
|
* child booted) means another refresher owns the run, and we exit.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sync-main.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/core/sync-main.ts"],"names":[],"mappings":";;AAwCA,oBAOC;AAQD,oDAGC;AAWD,0CAEC;AAOD,0CAkEC;AA/ID,sEAAqM;AAC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,OAAO,CAAC,CAAC;QAEhF,MAAM,MAAM,GAAe,IAAI,iCAAY,EAAE,CAAC,IAAI,CAAC,QAAQ,EAAE,WAAW,EAAE,KAAK,CAAC,CAAC;QACjF,KAAK,MAAM,OAAO,IAAI,MAAM,CAAC,MAAM,EAAE,CAAC;YAClC,IAAA,4BAAY,EAAC,QAAQ,EAAE,IAAI,4BAAY,CACnC,OAAO,EAAE,OAAO,CAAC,GAAG,EAAE,OAAO,CAAC,MAAM,EAAE,gBAAgB,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;QAChF,CAAC;QACD,OAAO,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC;IAChC,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,IAAA,4BAAY,EAAC,QAAQ,EAAE,IAAI,4BAAY,CAAC,OAAO,EAAE,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,aAAa,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;QAClG,OAAO,CAAC,CAAC;IACb,CAAC;AACL,CAAC;AAED,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;IAC1B,IAAI,EAAE,CAAC;AACX,CAAC","sourcesContent":["import { BranchCreationGuardConfig } from '../configs/rule-configs';\nimport { BranchReaper, MainSyncLockService, MainSyncStatusFile, MainSyncStatusService, MergedBranchesCache, MergedBranchesService, ReapResult, RefreshOutcome } from '@webpieces/repo-workflow-core';\nimport { loadAndValidate } from '@webpieces/rules-config';\n\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { logSyncEvent, SyncLogEvent } from './main-sync-log';\nimport { logStream, StreamIdentity } from './log-stream';\n\n// The services this detached process writes its results through, and adopts and deletes its lock through.\nconst status = new MainSyncStatusService();\nconst locks = new MainSyncLockService(undefined, undefined, status);\n\n/**\n * The detached, fire-and-forget refresher spawned (by file path, not a bin) from\n * main-sync-refresh.ts. It does the SLOW work (merged-PR lookup + git fetch + merge-base +\n * same-file-overlap) and writes `.webpieces/main-sync-status.json` so the next hook call reads it\n * instantly. Nobody reads our exit code or output — we run after the spawning hook has returned.\n *\n * Concurrency: `.webpieces/main-sync.lock.json` is a mutex whose EXISTENCE is the lock (it holds only\n * the holder's pid and start epoch). The SPAWNER creates it exclusively (main-sync-refresh.ts →\n * claimRefresh), only once MIN_REFRESH_INTERVAL_MINUTES have passed since the last start, and passes\n * its `startedMs` on argv. This child ADOPTS that lock (rewriting the pid to its own) and never creates\n * one itself, so it cannot race its spawner. A lock that is no longer on disk (reclaimed while this\n * child booted) means another refresher owns the run, and we exit.\n *\n * Ordering at the end is the point: the status file, carrying `lastRefreshStartedMs` and the outcome,\n * is written FIRST and the lock deleted LAST, so no process can win the next lock race and still read\n * the previous stamp.\n *\n * argv: [, , repoRoot, claimStarted, sessionId, agentId, hook]\n *\n * The last three are the SPAWNER's LogStream identity, and adopting them here is the whole reason\n * they are passed. This process has its own fresh module-level `logStream`; left unidentified it\n * named every line `unknown-coordinator-hook.log` — one shared file that every\n * agent's refresher child appended to concurrently (the PIPE_BUF tearing LogStream exists to remove),\n * and which held this run's START/FINISH while the parent's SPAWN_ATTEMPT sat in a different file\n * entirely. Adopting the parent's identity puts one refresh cycle back in one stream. Absent argv\n * (a hand-run of this file) leaves the default, which still prefixes.\n */\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nexport function main(): void {\n logStream.identify(spawnerIdentity(process.argv));\n refreshMainSync(\n process.argv[2] ?? process.cwd(),\n claimStartedFromArgv(process.argv),\n process.argv.slice(2).join(' '),\n );\n}\n\n/**\n * The `started` of the lock claim the spawner took for this run — argv position 3, which is\n * `refresherArgv`'s 2 (see the offset note there). NaN when absent or malformed, which matches no\n * lock, so a hand-run of this file without a claim adopts nothing and exits as SKIP_INPROGRESS.\n */\n// webpieces-disable no-function-outside-class -- argv parse for this detached main(), matching the file's existing shape\nexport function claimStartedFromArgv(argv: string[]): number {\n const raw = argv[3];\n return raw === undefined || raw.trim() === '' ? Number.NaN : Number(raw);\n}\n\n/**\n * The spawner's LogStream identity as it arrives on this child's argv — positions 4/5/6, which is\n * where `triggerMainSyncRefresh` puts them (its own array is offset by two: node + script path).\n *\n * Exported so ONE test can pin BOTH ends of the contract at once. The bug this closes is precisely a\n * disagreement between two files about argv positions, and a test that only checks the reader would\n * have stayed green through it.\n */\n// webpieces-disable no-function-outside-class -- argv parse for this detached main(), matching the file's existing shape\nexport function spawnerIdentity(argv: string[]): StreamIdentity {\n return new StreamIdentity(argv[4] ?? '', argv[5] ?? '', argv[6] ?? 'hook');\n}\n\n/**\n * The refresh itself, argv-free so it can be driven by a test. `main()` is only the argv parse — a\n * test importing another module's `main` is what no-process-exit-outside-main exists to prevent.\n */\n// webpieces-disable no-function-outside-class -- module-level entry point of this detached refresher, matching the file's existing shape\nexport function refreshMainSync(repoRoot: string, claimStarted: number, argvDetail: string = ''): void {\n const startedMs = Date.now();\n\n // First action: prove the detached child actually started. If the async-refresh stream has no START line\n // for a spawn, the child never launched (or died before this point).\n logSyncEvent(repoRoot, new SyncLogEvent('START', process.pid, '-', `argv=${argvDetail}`));\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // ADOPT the spawner's lock, never create one: the spawner already won it atomically.\n const lock = locks.adoptMainSyncLock(repoRoot, claimStarted);\n if (!lock) {\n logSyncEvent(repoRoot, new SyncLogEvent('SKIP_INPROGRESS', process.pid, '-', `the spawner's lock ${String(claimStarted)} is no longer on disk; another refresh owns this run`));\n return;\n }\n let file: MainSyncStatusFile | null = null;\n let outcome = RefreshOutcome.ERROR;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // EVERY worktree's branch, not just ours. The cache is shared by the whole repo but used\n // to describe only the branch of whichever tree won this lock, so every other worktree's\n // guards read a cross-branch cache and abstained. One fetch + one `gh` call now arms all\n // of them; the map is rebuilt from the live worktree set, so dead branches drop out.\n file = status.computeAllMainSyncStatuses(repoRoot);\n\n // Second slow signal, same lock, same detached run: which local branches are dead. One bulk\n // `gh pr list --state merged` call. The branch-creation-guard reads the result to enforce its\n // cap without ever touching the network itself. Deliberately allowed to go stale.\n const mergedBranches = new MergedBranchesService();\n // `false`: the background refresher NEVER ignores a standing agent lock. That flag is\n // wp-cleanup's, and it means \"a human asked for this run\" — nothing an unattended\n // refresher can claim on somebody's behalf.\n const cache = mergedBranches.computeMergedBranches(repoRoot, false);\n mergedBranches.writeMergedBranches(repoRoot, cache);\n\n // Third step, same detached run: actually DELETE the dead branches. Reporting them was\n // never enough — the reap was only ever a `git branch -D` string in a fix hint, which an\n // agent reads as destructive and stalls on, so nothing was ever cleaned. Here nobody has\n // to be asked. Reuses the verdicts we JUST computed (no second `gh` call).\n const reaped = autoReap(repoRoot, cache);\n\n // FINISH after a successful run — START-without-FINISH means we were killed mid-run.\n outcome = RefreshOutcome.OK;\n const names = Object.keys(file.branches);\n logSyncEvent(repoRoot, new SyncLogEvent(\n 'FINISH', process.pid, names.join(','),\n `branches=${String(names.length)} ${names.map(summarize(file)).join(' ')} deletableBranches=${String(cache.deletable.length)} reaped=${String(reaped)} ms=${String(Date.now() - startedMs)}`,\n ));\n } finally {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // Stamp FIRST: a failed run (offline, gh auth) still counts as a run, so it is retried\n // after MIN_REFRESH_INTERVAL_MINUTES rather than hammered on every tool call.\n recordRun(repoRoot, file, lock.startedMs, outcome);\n } finally {\n // Lock LAST, and only if still ours: a run that hung past its window was reclaimed,\n // and deleting the newer holder's lock would let a third refresher start beside it.\n locks.releaseMainSyncLock(repoRoot, lock);\n }\n }\n } catch (err: unknown) {\n const error = toError(err);\n // Detached: swallow so a transient git/fs error never leaves poison state (the next hook call\n // spawns a fresh refresher) — but record WHY it died so the failure isn't invisible.\n logSyncEvent(repoRoot, new SyncLogEvent('ERROR', process.pid, '-', `${error.message} | ${error.stack ?? ''}`));\n }\n}\n\n/**\n * Write this run's results and its stamp to main-sync-status.json (atomically). With fresh branch data\n * the whole document is replaced; without it (the compute threw) only the stamp and outcome are\n * updated, keeping the previous branch data the guards are still reading.\n */\n// webpieces-disable no-function-outside-class -- module-level helper of this detached main(), matching the file's existing shape\nfunction recordRun(repoRoot: string, file: MainSyncStatusFile | null, startedMs: number, outcome: RefreshOutcome): void {\n if (file === null) {\n status.recordRefreshOutcome(repoRoot, startedMs, outcome);\n return;\n }\n file.lastRefreshStartedMs = startedMs;\n file.lastRefreshOutcome = outcome;\n status.writeMainSyncStatusFile(repoRoot, file);\n}\n\n/**\n * One `branch(merged/forkPoint/conflict)` token per recorded branch, for the FINISH log line. The log\n * is the only evidence that a given worktree's branch was actually armed by a refresh, so it has to\n * name every branch written, not just the tree the refresher happened to run in.\n */\n// webpieces-disable no-function-outside-class -- module-level log formatter of this detached main(), matching the file's existing shape\nfunction summarize(file: MainSyncStatusFile): (branch: string) => string {\n return (branch: string): string => {\n const status = file.branches[branch];\n if (status === undefined) return `${branch}(?)`;\n return `${branch}(merged=${String(status.branchAlreadyMerged)}:${status.mergedPr} fork=${String(status.hasForkPoint)} conflict=${String(status.conflict)})`;\n };\n}\n\n/**\n * Delete the branches the verdicts just declared dead. Returns how many actually went.\n *\n * WHY it is safe to do this unattended: every candidate is provably dead (merged PR / squash backup\n * of a merged branch / zero commits of its own), `main` and any worktree-held branch are excluded\n * upstream, and each delete is logged with the branch's pre-delete SHA plus the exact command that\n * restores it. WHY it is safe to do it HERE: this refresher already recomputed those verdicts on\n * this very run, so it is acting on evidence seconds old, not on the deliberately-stale cache file.\n *\n * Swallows everything. We are detached and fire-and-forget: cleanup failing must never damage the\n * main-sync status this process exists to produce — but every failure is logged, because a silent\n * background deletion is exactly what nobody should have to trust.\n */\n// webpieces-disable no-function-outside-class -- module-level helper of this detached main(), matching the file's existing shape\nfunction autoReap(repoRoot: string, cache: MergedBranchesCache): number {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const config = loadAndValidate(repoRoot).rulesConfig['branch-creation-guard'] as BranchCreationGuardConfig | undefined;\n // Strictly opt-IN: only an explicit `true` reaps. `autoReapMergedBranches` is schema-required,\n // so every validated config states an answer — which means \"absent\" here is not a consumer\n // who wants the default, it is a config that never passed validation. Deleting branches on\n // that basis would be deleting on a preference nobody expressed.\n if (config?.mode === 'OFF' || config?.autoReapMergedBranches !== true) return 0;\n\n const result: ReapResult = new BranchReaper().reap(repoRoot, 'auto-reap', cache);\n for (const failure of result.failed) {\n logSyncEvent(repoRoot, new SyncLogEvent(\n 'ERROR', process.pid, failure.branch, `reap failed: ${failure.error}`));\n }\n return result.reaped.length;\n } catch (err: unknown) {\n const error = toError(err);\n logSyncEvent(repoRoot, new SyncLogEvent('ERROR', process.pid, '-', `autoReap: ${error.message}`));\n return 0;\n }\n}\n\nif (require.main === module) {\n main();\n}\n"]}
|
|
1
|
+
{"version":3,"file":"sync-main.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/core/sync-main.ts"],"names":[],"mappings":";;AAyCA,oBAOC;AAQD,oDAGC;AAWD,0CAEC;AAOD,0CAkEC;AAhJD,sEAAqM;AACrM,0DAA0D;AAE1D,iEAA6D;AAC7D,mDAA6D;AAC7D,6CAAyD;AAEzD,0GAA0G;AAC1G,MAAM,MAAM,GAAG,IAAI,0CAAqB,EAAE,CAAC;AAC3C,MAAM,KAAK,GAAG,IAAI,wCAAmB,CAAC,SAAS,EAAE,SAAS,EAAE,MAAM,CAAC,CAAC;AAEpE;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,mKAAmK;AACnK,SAAgB,IAAI;IAChB,sBAAS,CAAC,QAAQ,CAAC,eAAe,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC;IAClD,eAAe,CACX,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,OAAO,CAAC,GAAG,EAAE,EAChC,oBAAoB,CAAC,OAAO,CAAC,IAA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,EAAC,GAAG,CAAC,CAAC;QAC3B,IAAA,4BAAY,EAAC,QAAQ,EAAE,IAAI,4BAAY,CAAC,OAAO,EAAE,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,aAAa,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;QAClG,OAAO,CAAC,CAAC;IACb,CAAC;AACL,CAAC;AAED,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;IAC1B,IAAI,EAAE,CAAC;AACX,CAAC","sourcesContent":["import { BranchCreationGuardConfig } from '../configs/rule-configs';\nimport { BranchReaper, MainSyncLockService, MainSyncStatusFile, MainSyncStatusService, MergedBranchesCache, MergedBranchesService, ReapResult, RefreshOutcome } from '@webpieces/repo-workflow-core';\nimport { loadAndValidate } from '@webpieces/rules-config';\n\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { logSyncEvent, SyncLogEvent } from './main-sync-log';\nimport { logStream, StreamIdentity } from './log-stream';\n\n// The services this detached process writes its results through, and adopts and deletes its lock through.\nconst status = new MainSyncStatusService();\nconst locks = new MainSyncLockService(undefined, undefined, status);\n\n/**\n * The detached, fire-and-forget refresher spawned (by file path, not a bin) from\n * main-sync-refresh.ts. It does the SLOW work (merged-PR lookup + git fetch + merge-base +\n * same-file-overlap) and writes `.webpieces/main-sync-status.json` so the next hook call reads it\n * instantly. Nobody reads our exit code or output — we run after the spawning hook has returned.\n *\n * Concurrency: `.webpieces/main-sync.lock.json` is a mutex whose EXISTENCE is the lock (it holds only\n * the holder's pid and start epoch). The SPAWNER creates it exclusively (main-sync-refresh.ts →\n * claimRefresh), only once MIN_REFRESH_INTERVAL_MINUTES have passed since the last start (at once for a\n * branch the status file has never seen, #1377), and passes\n * its `startedMs` on argv. This child ADOPTS that lock (rewriting the pid to its own) and never creates\n * one itself, so it cannot race its spawner. A lock that is no longer on disk (reclaimed while this\n * child booted) means another refresher owns the run, and we exit.\n *\n * Ordering at the end is the point: the status file, carrying `lastRefreshStartedMs` and the outcome,\n * is written FIRST and the lock deleted LAST, so no process can win the next lock race and still read\n * the previous stamp.\n *\n * argv: [, , repoRoot, claimStarted, sessionId, agentId, hook]\n *\n * The last three are the SPAWNER's LogStream identity, and adopting them here is the whole reason\n * they are passed. This process has its own fresh module-level `logStream`; left unidentified it\n * named every line `unknown-coordinator-hook.log` — one shared file that every\n * agent's refresher child appended to concurrently (the PIPE_BUF tearing LogStream exists to remove),\n * and which held this run's START/FINISH while the parent's SPAWN_ATTEMPT sat in a different file\n * entirely. Adopting the parent's identity puts one refresh cycle back in one stream. Absent argv\n * (a hand-run of this file) leaves the default, which still prefixes.\n */\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nexport function main(): void {\n logStream.identify(spawnerIdentity(process.argv));\n refreshMainSync(\n process.argv[2] ?? process.cwd(),\n claimStartedFromArgv(process.argv),\n process.argv.slice(2).join(' '),\n );\n}\n\n/**\n * The `started` of the lock claim the spawner took for this run — argv position 3, which is\n * `refresherArgv`'s 2 (see the offset note there). NaN when absent or malformed, which matches no\n * lock, so a hand-run of this file without a claim adopts nothing and exits as SKIP_INPROGRESS.\n */\n// webpieces-disable no-function-outside-class -- argv parse for this detached main(), matching the file's existing shape\nexport function claimStartedFromArgv(argv: string[]): number {\n const raw = argv[3];\n return raw === undefined || raw.trim() === '' ? Number.NaN : Number(raw);\n}\n\n/**\n * The spawner's LogStream identity as it arrives on this child's argv — positions 4/5/6, which is\n * where `triggerMainSyncRefresh` puts them (its own array is offset by two: node + script path).\n *\n * Exported so ONE test can pin BOTH ends of the contract at once. The bug this closes is precisely a\n * disagreement between two files about argv positions, and a test that only checks the reader would\n * have stayed green through it.\n */\n// webpieces-disable no-function-outside-class -- argv parse for this detached main(), matching the file's existing shape\nexport function spawnerIdentity(argv: string[]): StreamIdentity {\n return new StreamIdentity(argv[4] ?? '', argv[5] ?? '', argv[6] ?? 'hook');\n}\n\n/**\n * The refresh itself, argv-free so it can be driven by a test. `main()` is only the argv parse — a\n * test importing another module's `main` is what no-process-exit-outside-main exists to prevent.\n */\n// webpieces-disable no-function-outside-class -- module-level entry point of this detached refresher, matching the file's existing shape\nexport function refreshMainSync(repoRoot: string, claimStarted: number, argvDetail: string = ''): void {\n const startedMs = Date.now();\n\n // First action: prove the detached child actually started. If the async-refresh stream has no START line\n // for a spawn, the child never launched (or died before this point).\n logSyncEvent(repoRoot, new SyncLogEvent('START', process.pid, '-', `argv=${argvDetail}`));\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // ADOPT the spawner's lock, never create one: the spawner already won it atomically.\n const lock = locks.adoptMainSyncLock(repoRoot, claimStarted);\n if (!lock) {\n logSyncEvent(repoRoot, new SyncLogEvent('SKIP_INPROGRESS', process.pid, '-', `the spawner's lock ${String(claimStarted)} is no longer on disk; another refresh owns this run`));\n return;\n }\n let file: MainSyncStatusFile | null = null;\n let outcome = RefreshOutcome.ERROR;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // EVERY worktree's branch, not just ours. The cache is shared by the whole repo but used\n // to describe only the branch of whichever tree won this lock, so every other worktree's\n // guards read a cross-branch cache and abstained. One fetch + one `gh` call now arms all\n // of them; the map is rebuilt from the live worktree set, so dead branches drop out.\n file = status.computeAllMainSyncStatuses(repoRoot);\n\n // Second slow signal, same lock, same detached run: which local branches are dead. One bulk\n // `gh pr list --state merged` call. The branch-creation-guard reads the result to enforce its\n // cap without ever touching the network itself. Deliberately allowed to go stale.\n const mergedBranches = new MergedBranchesService();\n // `false`: the background refresher NEVER ignores a standing agent lock. That flag is\n // wp-cleanup's, and it means \"a human asked for this run\" — nothing an unattended\n // refresher can claim on somebody's behalf.\n const cache = mergedBranches.computeMergedBranches(repoRoot, false);\n mergedBranches.writeMergedBranches(repoRoot, cache);\n\n // Third step, same detached run: actually DELETE the dead branches. Reporting them was\n // never enough — the reap was only ever a `git branch -D` string in a fix hint, which an\n // agent reads as destructive and stalls on, so nothing was ever cleaned. Here nobody has\n // to be asked. Reuses the verdicts we JUST computed (no second `gh` call).\n const reaped = autoReap(repoRoot, cache);\n\n // FINISH after a successful run — START-without-FINISH means we were killed mid-run.\n outcome = RefreshOutcome.OK;\n const names = Object.keys(file.branches);\n logSyncEvent(repoRoot, new SyncLogEvent(\n 'FINISH', process.pid, names.join(','),\n `branches=${String(names.length)} ${names.map(summarize(file)).join(' ')} deletableBranches=${String(cache.deletable.length)} reaped=${String(reaped)} ms=${String(Date.now() - startedMs)}`,\n ));\n } finally {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // Stamp FIRST: a failed run (offline, gh auth) still counts as a run, so it is retried\n // after MIN_REFRESH_INTERVAL_MINUTES rather than hammered on every tool call.\n recordRun(repoRoot, file, lock.startedMs, outcome);\n } finally {\n // Lock LAST, and only if still ours: a run that hung past its window was reclaimed,\n // and deleting the newer holder's lock would let a third refresher start beside it.\n locks.releaseMainSyncLock(repoRoot, lock);\n }\n }\n } catch (err: unknown) {\n const error = toError(err);\n // Detached: swallow so a transient git/fs error never leaves poison state (the next hook call\n // spawns a fresh refresher) — but record WHY it died so the failure isn't invisible.\n logSyncEvent(repoRoot, new SyncLogEvent('ERROR', process.pid, '-', `${error.message} | ${error.stack ?? ''}`));\n }\n}\n\n/**\n * Write this run's results and its stamp to main-sync-status.json (atomically). With fresh branch data\n * the whole document is replaced; without it (the compute threw) only the stamp and outcome are\n * updated, keeping the previous branch data the guards are still reading.\n */\n// webpieces-disable no-function-outside-class -- module-level helper of this detached main(), matching the file's existing shape\nfunction recordRun(repoRoot: string, file: MainSyncStatusFile | null, startedMs: number, outcome: RefreshOutcome): void {\n if (file === null) {\n status.recordRefreshOutcome(repoRoot, startedMs, outcome);\n return;\n }\n file.lastRefreshStartedMs = startedMs;\n file.lastRefreshOutcome = outcome;\n status.writeMainSyncStatusFile(repoRoot, file);\n}\n\n/**\n * One `branch(merged/forkPoint/conflict)` token per recorded branch, for the FINISH log line. The log\n * is the only evidence that a given worktree's branch was actually armed by a refresh, so it has to\n * name every branch written, not just the tree the refresher happened to run in.\n */\n// webpieces-disable no-function-outside-class -- module-level log formatter of this detached main(), matching the file's existing shape\nfunction summarize(file: MainSyncStatusFile): (branch: string) => string {\n return (branch: string): string => {\n const status = file.branches[branch];\n if (status === undefined) return `${branch}(?)`;\n return `${branch}(merged=${String(status.branchAlreadyMerged)}:${status.mergedPr} fork=${String(status.hasForkPoint)} conflict=${String(status.conflict)})`;\n };\n}\n\n/**\n * Delete the branches the verdicts just declared dead. Returns how many actually went.\n *\n * WHY it is safe to do this unattended: every candidate is provably dead (merged PR / squash backup\n * of a merged branch / zero commits of its own), `main` and any worktree-held branch are excluded\n * upstream, and each delete is logged with the branch's pre-delete SHA plus the exact command that\n * restores it. WHY it is safe to do it HERE: this refresher already recomputed those verdicts on\n * this very run, so it is acting on evidence seconds old, not on the deliberately-stale cache file.\n *\n * Swallows everything. We are detached and fire-and-forget: cleanup failing must never damage the\n * main-sync status this process exists to produce — but every failure is logged, because a silent\n * background deletion is exactly what nobody should have to trust.\n */\n// webpieces-disable no-function-outside-class -- module-level helper of this detached main(), matching the file's existing shape\nfunction autoReap(repoRoot: string, cache: MergedBranchesCache): number {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const config = loadAndValidate(repoRoot).rulesConfig['branch-creation-guard'] as BranchCreationGuardConfig | undefined;\n // Strictly opt-IN: only an explicit `true` reaps. `autoReapMergedBranches` is schema-required,\n // so every validated config states an answer — which means \"absent\" here is not a consumer\n // who wants the default, it is a config that never passed validation. Deleting branches on\n // that basis would be deleting on a preference nobody expressed.\n if (config?.mode === 'OFF' || config?.autoReapMergedBranches !== true) return 0;\n\n const result: ReapResult = new BranchReaper().reap(repoRoot, 'auto-reap', cache);\n for (const failure of result.failed) {\n logSyncEvent(repoRoot, new SyncLogEvent(\n 'ERROR', process.pid, failure.branch, `reap failed: ${failure.error}`));\n }\n return result.reaped.length;\n } catch (err: unknown) {\n const error = toError(err);\n logSyncEvent(repoRoot, new SyncLogEvent('ERROR', process.pid, '-', `autoReap: ${error.message}`));\n return 0;\n }\n}\n\nif (require.main === module) {\n main();\n}\n"]}
|