@webpieces/rules-config 0.4.965 → 0.4.966

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webpieces/rules-config",
3
- "version": "0.4.965",
3
+ "version": "0.4.966",
4
4
  "description": "Shared webpieces.config.json loader. Single source of truth for validation rule configuration consumed by @webpieces/ai-hook-rules, @webpieces/code-rules, and @webpieces/nx-webpieces-rules.",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -19,9 +19,9 @@
19
19
  "inversify": "7.10.4",
20
20
  "reflect-metadata": "0.2.2",
21
21
  "minimatch": "10.0.1",
22
- "@webpieces/tooling-common": "0.4.965",
23
- "@webpieces/repo-workflow-core": "0.4.965",
24
- "@webpieces/rules-sdk": "0.4.965"
22
+ "@webpieces/tooling-common": "0.4.966",
23
+ "@webpieces/repo-workflow-core": "0.4.966",
24
+ "@webpieces/rules-sdk": "0.4.966"
25
25
  },
26
26
  "author": "Dean Hiller",
27
27
  "license": "Apache-2.0",
@@ -34,7 +34,7 @@
34
34
  "access": "public"
35
35
  },
36
36
  "devDependencies": {
37
- "@webpieces/tooling-testkit": "0.4.965"
37
+ "@webpieces/tooling-testkit": "0.4.966"
38
38
  },
39
39
  "types": "./src/index.d.ts",
40
40
  "bin": {
package/src/builds-log.js CHANGED
@@ -2,7 +2,6 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.BuildsLog = exports.RunningBuild = exports.BuildTermination = exports.BuildTicket = exports.MAX_ROW_BYTES = exports.BUILDS_LOG_GENERATIONS = exports.MAX_BUILDS_LOG_BYTES = exports.BUILD_DONE_FAIL = exports.BUILD_DONE_SUCCESS = exports.BUILD_START = exports.BUILDS_LOCK_FILE = exports.BUILDS_LOG_FILE = void 0;
4
4
  const tslib_1 = require("tslib");
5
- const child_process_1 = require("child_process");
6
5
  const crypto = tslib_1.__importStar(require("crypto"));
7
6
  const fs = tslib_1.__importStar(require("fs"));
8
7
  const os = tslib_1.__importStar(require("os"));
@@ -506,21 +505,9 @@ let BuildsLog = class BuildsLog {
506
505
  void error;
507
506
  }
508
507
  }
509
- // The checked-out branch in `startDir`, or '' when git cannot say. spawnSync does not throw on a
510
- // non-zero exit, so "not a repo" arrives as a status, not an exception.
508
+ // The checked-out branch in `startDir`, or '' when git cannot say.
511
509
  gitBranch(startDir) {
512
- // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
513
- try {
514
- const result = (0, child_process_1.spawnSync)('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: startDir, encoding: 'utf8' });
515
- if (result.status !== 0 || typeof result.stdout !== 'string')
516
- return '';
517
- return result.stdout.trim();
518
- }
519
- catch (err) {
520
- const error = (0, to_error_1.toError)(err);
521
- void error;
522
- return '';
523
- }
510
+ return tooling_common_1.gitCheckout.branch(startDir) ?? '';
524
511
  }
525
512
  };
526
513
  exports.BuildsLog = BuildsLog;
@@ -1 +1 @@
1
- {"version":3,"file":"builds-log.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/builds-log.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,uDAAiC;AACjC,+CAAyB;AACzB,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAE3D,8DAAyD;AACzD,+CAAgD;AAChD,iEAA6D;AAE7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACU,QAAA,eAAe,GAAG,YAAY,CAAC;AAC/B,QAAA,gBAAgB,GAAG,iBAAiB,CAAC;AAElD,kGAAkG;AACrF,QAAA,WAAW,GAAG,OAAO,CAAC;AACtB,QAAA,kBAAkB,GAAG,cAAc,CAAC;AACpC,QAAA,eAAe,GAAG,WAAW,CAAC;AAE3C,uFAAuF;AAC1E,QAAA,oBAAoB,GAAG,IAAI,GAAG,IAAI,CAAC;AACnC,QAAA,sBAAsB,GAAG,CAAC,CAAC;AAExC;;;;GAIG;AAC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9B,8DAA8D;QAC9D,IAAI,CAAC;YACD,MAAM,MAAM,GAAG,IAAA,yBAAS,EAAC,KAAK,EAAE,CAAC,WAAW,EAAE,cAAc,EAAE,MAAM,CAAC,EACjE,EAAE,GAAG,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC,CAAC;YACzC,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,IAAI,OAAO,MAAM,CAAC,MAAM,KAAK,QAAQ;gBAAE,OAAO,EAAE,CAAC;YACxE,OAAO,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC;QAChC,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,KAAK,KAAK,CAAC;YACX,OAAO,EAAE,CAAC;QACd,CAAC;IACL,CAAC;CACJ,CAAA;AA/YY,8BAAS;oBAAT,SAAS;IADrB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEA,6BAAY;GADxC,SAAS,CA+YrB","sourcesContent":["import { spawnSync } from 'child_process';\nimport * as crypto from 'crypto';\nimport * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { DotWebpieces } from '@webpieces/tooling-common';\nimport { HOME_CONFIG_DIR } from './home-config';\nimport { toError } from '@webpieces/tooling-common/to-error';\n\n/**\n * `~/.webpieces/builds.log` — the MACHINE-WIDE, append-only ledger of every build this box has started.\n *\n * ─── WHY THIS ONE FILE LIVES OUTSIDE THE REPO ─────────────────────────────────────────────────────────\n * `no-machine-global-state.spec.ts` records the standing rule: webpieces writes state under\n * `{repo}/.webpieces` and nowhere else. This is the ONE carve-out, and the argument is written out in\n * `decisions/0006-the-build-ledger-is-machine-global.md`. In short:\n *\n * • The FACT is machine-scoped. \"How many builds are burning this box's CPU right now\" is not a\n * property of any repo; it is a property of the machine. A per-repo ledger cannot answer it — every\n * linked worktree has its OWN `.webpieces/`, so it would be blind to the sibling worktree it is\n * actually contending with, never mind the four other repos on the disk.\n * • It is NOT A CACHE. The retired `PrBodyStore` that the no-machine-global rule was written for was a\n * local copy of a fact GitHub owned, so it could be stale, missing, or on the wrong computer. There\n * is no remote copy of this. The file IS the fact.\n * • Its key is an ABSOLUTE LOCAL PATH, which is stable precisely because it never leaves the machine —\n * the instability that killed `PrBodyStore`'s `<host>/<owner>/<repo>` key cannot arise here.\n *\n * ─── WHY IT IS SAFE TO WRITE CONCURRENTLY ─────────────────────────────────────────────────────────────\n * Rows are deliberately kept under `MAX_ROW_BYTES` (512, macOS `PIPE_BUF`). A single `O_APPEND`\n * `write(2)` at or below that size is indivisible, so two builds appending at the same instant cannot\n * interleave halves of a line. The lock is therefore belt-and-braces for the APPEND and genuinely\n * load-bearing for ROTATION, where a rename-and-reopen really does race.\n *\n * ─── IT MAY NEVER FAIL A BUILD ────────────────────────────────────────────────────────────────────────\n * Every method here is best-effort and swallows its own errors. A build must never die because a log\n * file was busy, unwritable, or on a full disk. Lock acquisition retries and then gives up and appends\n * anyway — which the row-size invariant above makes safe.\n */\nexport const BUILDS_LOG_FILE = 'builds.log';\nexport const BUILDS_LOCK_FILE = 'builds.log.lock';\n\n/** START, and the two terminal kinds. `DONE-` is the greppable prefix that pairs with a START. */\nexport const BUILD_START = 'START';\nexport const BUILD_DONE_SUCCESS = 'DONE-SUCCESS';\nexport const BUILD_DONE_FAIL = 'DONE-FAIL';\n\n/** Rotate at 1 MB, keeping five generations (`.1` … `.5`); the old `.5` is dropped. */\nexport const MAX_BUILDS_LOG_BYTES = 1024 * 1024;\nexport const BUILDS_LOG_GENERATIONS = 5;\n\n/**\n * macOS `PIPE_BUF`. A row at or under this size is written by ONE indivisible `write(2)`, which is what\n * makes a lost lock a non-event rather than a corrupted file. Long paths are clipped to hold the line\n * under it — see `clip`.\n */\nexport const MAX_ROW_BYTES = 512;\n\n/** How long a build may hold the lock before another writer stops waiting and appends anyway. */\nconst LOCK_RETRY_MS = 50;\nconst LOCK_TIMEOUT_MS = 2000;\n\n/**\n * The handle a START row hands back, and the ONLY thing `finish()` accepts. Data-only (a class, per\n * CLAUDE.md), carrying exactly the fields the DONE row needs to pair itself with its START: the uuid,\n * the caller, the repo, and when it began (so `took=` is computed from one clock, not two).\n */\nexport class BuildTicket {\n id: string;\n by: string;\n repo: string;\n startedMs: number;\n\n constructor(id: string, by: string, repo: string, startedMs: number) {\n this.id = id;\n this.by = by;\n this.repo = repo;\n this.startedMs = startedMs;\n }\n}\n\n/**\n * How the build process ended. Node reports a null code when a signal ended the process, so collapsing\n * this to a number would discard the only useful explanation for an otherwise silent build failure.\n * Data-only: the PR gate decides which CLI exit code to return, while the ledger records these raw facts.\n */\nexport class BuildTermination {\n code: number | null;\n signal: string | null;\n\n constructor(code: number | null, signal: string | null) {\n this.code = code;\n this.signal = signal;\n }\n}\n\n/**\n * One build that is STILL RUNNING — a START row with no matching `DONE-`, whose pid is still alive.\n * Data-only. This is what the refusal message renders, so it carries the three things a reader needs to\n * recognise the build in question: where it is, which tree, and how old it is.\n */\nexport class RunningBuild {\n id: string;\n by: string;\n repo: string;\n tree: string;\n cwd: string;\n branch: string;\n pid: number;\n startedMs: number;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n id: string, by: string, repo: string, tree: string,\n cwd: string, branch: string, pid: number, startedMs: number,\n ) {\n this.id = id;\n this.by = by;\n this.repo = repo;\n this.tree = tree;\n this.cwd = cwd;\n this.branch = branch;\n this.pid = pid;\n this.startedMs = startedMs;\n }\n}\n\n/**\n * The ledger. See the file docblock for why it is machine-global and why every operation swallows its\n * own errors.\n *\n * `homeDir` is a parameter on every public method, defaulted to `os.homedir()`, for exactly the reason\n * `HomeConfigService.configPath` takes one: a spec must be able to exercise the real code against a temp\n * directory and must never touch the developer's actual `~/.webpieces`.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class BuildsLog {\n constructor(private readonly dotDir: DotWebpieces) {}\n\n /** `~/.webpieces/builds.log`. */\n logPath(homeDir: string = os.homedir()): string {\n return path.join(homeDir, HOME_CONFIG_DIR, BUILDS_LOG_FILE);\n }\n\n /** `~/.webpieces/builds.log.lock` — `{\"pid\":N,\"started\":<epochMs>}`. */\n lockPath(homeDir: string = os.homedir()): string {\n return path.join(homeDir, HOME_CONFIG_DIR, BUILDS_LOCK_FILE);\n }\n\n /** `~/.webpieces/builds.log.<n>` — generation `n`, 1 being the most recent. */\n rotatedPath(generation: number, homeDir: string = os.homedir()): string {\n return `${this.logPath(homeDir)}.${String(generation)}`;\n }\n\n /**\n * Record that a build is starting, and hand back the ticket its DONE row will need.\n *\n * `by` is the CALLER — `BuildGateOptions.stage`, i.e. `build` | `review` | `finish`. There is no\n * second \"caller\" concept anywhere: the stage id already is one, and a second spelling of it would\n * be the shim `.claude/rules/no-backwards-compat.md` rejects.\n *\n * Returns a ticket even when the append failed. A build whose START row never landed still has to be\n * able to call `finish()`; the alternative is a nullable return that every call site must branch on\n * for a logging failure that is, by policy, not an error.\n */\n start(by: string, startDir: string, homeDir: string = os.homedir()): BuildTicket {\n const ticket = new BuildTicket(\n crypto.randomUUID(), by, this.dotDir.primaryRoot(startDir), Date.now());\n this.append(this.startRow(ticket, startDir), homeDir);\n return ticket;\n }\n\n /**\n * Record that the build behind `ticket` has ended. Only code 0 with no signal writes `DONE-SUCCESS`;\n * anything else writes `DONE-FAIL` carrying the raw code and signal, so a killed build does not become\n * an unexplained generic exit 1 in the machine record.\n */\n finish(ticket: BuildTicket, termination: BuildTermination, homeDir: string = os.homedir()): void {\n this.append(this.doneRow(ticket, termination), homeDir);\n }\n\n /**\n * Every build that is still live: a `START` with no matching `DONE-` row, whose pid is still alive.\n *\n * The pid filter is not an optimisation, it is what keeps the ledger from wedging the machine. A\n * build killed with SIGKILL — an agent cancelled mid-run, a terminal closed — writes no DONE row, so\n * without the liveness test its START would count forever and the fourth build would be refused for\n * the rest of the machine's life. The uuid answers \"which build\"; the pid answers \"is it still real\".\n *\n * Only the CURRENT generation is read. A rotated-away START is by definition at least 1 MB of rows\n * old and is not a build anyone is contending with.\n */\n running(homeDir: string = os.homedir()): RunningBuild[] {\n const lines = this.readLines(this.logPath(homeDir));\n const done = new Set<string>();\n for (const line of lines) {\n if (line.startsWith(`${BUILD_DONE_SUCCESS}\\t`) || line.startsWith(`${BUILD_DONE_FAIL}\\t`)) {\n done.add(this.field(line, 'id'));\n }\n }\n const live: RunningBuild[] = [];\n for (const line of lines) {\n if (!line.startsWith(`${BUILD_START}\\t`)) continue;\n const build = this.toRunningBuild(line);\n if (build === null || done.has(build.id)) continue;\n if (!this.isAlive(build.pid)) continue;\n live.push(build);\n }\n return live;\n }\n\n /**\n * The `@webpieces` release ACTUALLY EXECUTING — found by walking UP from this module's own directory\n * to the nearest enclosing `node_modules/@webpieces/<pkg>/package.json`. `''` when this code is\n * running from source rather than from an installed package (which is the state in this repo's own\n * specs, and a perfectly ordinary answer).\n *\n * ─── WHY THIS IS NOT `WebpiecesVersions.readInstalled(root)` ──────────────────────────────────────\n * They answer DIFFERENT QUESTIONS and merging them would break the older one. `readInstalled` joins\n * `<root>/node_modules/@webpieces/...` at a FIXED tree root ON PURPOSE: its whole job is to detect\n * DRIFT between what a tree PINS and what some other tree pins, and a walk-up would silently resolve\n * a worktree with no install of its own to the primary clone's copy — hiding exactly the skew that\n * guard exists to catch. This question is the opposite one: \"whichever copy is running, name it\", and\n * for that the walk-up is the only correct answer. Do not fold them together.\n */\n executingVersion(): string {\n let dir = __dirname;\n for (let hops = 0; hops < 40; hops += 1) {\n const version = this.versionOfEnclosingPackage(dir);\n if (version !== '') return version;\n const parent = path.dirname(dir);\n if (parent === dir) return '';\n dir = parent;\n }\n return '';\n }\n\n // `<dir>` is `node_modules/@webpieces/<pkg>/...`? Then that package's version, else ''.\n private versionOfEnclosingPackage(dir: string): string {\n const parent = path.dirname(dir);\n const grandparent = path.dirname(parent);\n if (path.basename(parent) !== '@webpieces' || path.basename(grandparent) !== 'node_modules') return '';\n const text = this.readTextOrEmpty(path.join(dir, 'package.json'));\n const match = /\"version\"\\s*:\\s*\"([^\"]+)\"/.exec(text);\n return match === null ? '' : match[1];\n }\n\n // ─── ROW RENDERING ────────────────────────────────────────────────────────────────────────────────\n\n private startRow(ticket: BuildTicket, startDir: string): string {\n return [\n BUILD_START,\n `id=${ticket.id}`,\n `t=${new Date(ticket.startedMs).toISOString()}`,\n `ms=${String(ticket.startedMs)}`,\n `by=${ticket.by}`,\n `repo=${this.clip(ticket.repo)}`,\n `tree=${this.dotDir.worktreeName(startDir) || 'primary'}`,\n `cwd=${this.clip(startDir)}`,\n `branch=${this.gitBranch(startDir)}`,\n `pid=${String(process.pid)}`,\n `wp=${this.executingVersion()}`,\n ].join('\\t');\n }\n\n private doneRow(ticket: BuildTicket, termination: BuildTermination): string {\n const now = Date.now();\n const success = termination.code === 0 && termination.signal === null;\n const fields = [\n success ? BUILD_DONE_SUCCESS : BUILD_DONE_FAIL,\n `id=${ticket.id}`,\n `t=${new Date(now).toISOString()}`,\n `ms=${String(now)}`,\n `by=${ticket.by}`,\n `repo=${this.clip(ticket.repo)}`,\n `took=${String(now - ticket.startedMs)}`,\n ];\n if (!success) fields.push(`exit=${termination.code === null ? 'null' : String(termination.code)}`);\n if (termination.signal !== null) fields.push(`signal=${this.clip(termination.signal)}`);\n fields.push(`pid=${String(process.pid)}`);\n return fields.join('\\t');\n }\n\n /**\n * Hold a long path down to `max` characters by keeping its TAIL, which is the half that identifies\n * the tree; a clipped value is marked with a leading `…` so nobody mistakes it for a real path.\n *\n * This is what keeps a row under `MAX_ROW_BYTES` — see the file docblock. `append` re-checks the\n * assembled line as a backstop, because three clipped fields plus a long branch name can still add up.\n */\n private clip(value: string, max = 120): string {\n const oneLine = value.replace(/[\\t\\n\\r]/g, ' ');\n return oneLine.length <= max ? oneLine : `…${oneLine.slice(oneLine.length - max)}`;\n }\n\n // ─── ROW PARSING ──────────────────────────────────────────────────────────────────────────────────\n\n /** The value of `<name>=` on a TSV row, or '' when the row does not carry it. */\n private field(line: string, name: string): string {\n for (const part of line.split('\\t')) {\n if (part.startsWith(`${name}=`)) return part.slice(name.length + 1);\n }\n return '';\n }\n\n // A START row as a RunningBuild, or null when it is missing the two fields that make it usable.\n private toRunningBuild(line: string): RunningBuild | null {\n const id = this.field(line, 'id');\n const pid = Number.parseInt(this.field(line, 'pid'), 10);\n if (id === '' || !Number.isInteger(pid) || pid <= 0) return null;\n const startedMs = Number.parseInt(this.field(line, 'ms'), 10);\n return new RunningBuild(\n id, this.field(line, 'by'), this.field(line, 'repo'), this.field(line, 'tree'),\n this.field(line, 'cwd'), this.field(line, 'branch'), pid,\n Number.isInteger(startedMs) ? startedMs : 0,\n );\n }\n\n /**\n * Is `pid` still addressable? `process.kill(pid, 0)` sends no signal — it only asks the kernel. ESRCH\n * is the ONE answer that proves death; EPERM proves the opposite (it exists, it is somebody else's).\n * Pid reuse is an accepted imprecision here: being wrong in the \"still running\" direction costs\n * one extra refusal, being wrong the other way lets a fourth build start.\n *\n * WHY A PID IS MEANINGFUL HERE AND WAS NOT FOR AGENT WORKTREE LOCKS. Every row in this ledger is\n * written BY the process it names — one real OS process per build — so its pid identifies it.\n * A Claude Code subagent is not a process at all: every agent in a session records the SAME pid,\n * the session's, which is why that check was deleted rather than shared (see\n * harness-agent-activity.ts). Do not generalise this one back out to anything but a real process.\n */\n private isAlive(pid: number): boolean {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n process.kill(pid, 0);\n return true;\n } catch (err: unknown) {\n const error = toError(err);\n return (error as NodeJS.ErrnoException).code !== 'ESRCH';\n }\n }\n\n // ─── APPEND, LOCK, ROTATE ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Append one row, best-effort. Takes the lock so rotation cannot race, and appends ANYWAY when the\n * lock cannot be had within `LOCK_TIMEOUT_MS` — the row is under `PIPE_BUF`, so an unlocked\n * `O_APPEND` write is still indivisible, and a build must never die because a log file was busy.\n */\n private append(row: string, homeDir: string): void {\n const line = `${this.truncateToRowLimit(row)}\\n`;\n const held = this.tryAcquireLock(homeDir);\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n this.ensureDir(this.logPath(homeDir));\n if (held) this.rotateIfLarge(homeDir);\n fs.appendFileSync(this.logPath(homeDir), line);\n } catch (err: unknown) {\n const error = toError(err);\n void error; // logging may never fail a build — see the file docblock\n } finally {\n if (held) this.releaseLock(homeDir);\n }\n }\n\n // The backstop for the PIPE_BUF invariant, measured in BYTES rather than characters because a path\n // may hold multi-byte characters. Truncating a row loses fields off the end, which is strictly better\n // than a torn line that breaks every row after it.\n private truncateToRowLimit(row: string): string {\n const bytes = Buffer.from(row, 'utf8');\n // -1 for the newline `append` adds.\n if (bytes.length <= MAX_ROW_BYTES - 1) return row;\n return bytes.subarray(0, MAX_ROW_BYTES - 1).toString('utf8');\n }\n\n /**\n * Take the ledger lock, retrying every `LOCK_RETRY_MS` until `LOCK_TIMEOUT_MS`. False means \"carry on\n * without it\" — never an error, and never a reason to skip the append.\n *\n * The mechanism is `MainSyncLockService.tryAcquireMainSyncLock`'s, proven and deliberately copied\n * rather than re-invented: an `wx` (O_CREAT|O_EXCL) create so exactly one of N racers wins, a payload\n * carrying pid + started so a dead holder is identifiable, stale reclaim gated on pid liveness, and a\n * re-read afterwards to confirm the entry on disk is OURS (a simultaneous reclaimer could have\n * unlinked ours and written its own between the two calls).\n */\n private tryAcquireLock(homeDir: string): boolean {\n const deadline = Date.now() + LOCK_TIMEOUT_MS;\n this.ensureDir(this.lockPath(homeDir));\n // Rendered rather than JSON.stringify'd off an anonymous object — two fields, both numbers, and\n // the file's whole contract is `{\"pid\":N,\"started\":M}`.\n const payload = `{\"pid\":${String(process.pid)},\"started\":${String(Date.now())}}\\n`;\n for (;;) {\n if (this.createExclusive(this.lockPath(homeDir), payload)) return true;\n if (!this.isHolderAlive(homeDir)) {\n this.unlinkQuietly(this.lockPath(homeDir));\n if (this.createExclusive(this.lockPath(homeDir), payload) && this.holderIsUs(homeDir)) return true;\n }\n if (Date.now() >= deadline) return false;\n this.sleep(LOCK_RETRY_MS);\n }\n }\n\n private releaseLock(homeDir: string): void {\n if (!this.holderIsUs(homeDir)) return;\n this.unlinkQuietly(this.lockPath(homeDir));\n }\n\n // O_CREAT|O_EXCL write: true when THIS call created the file, false when it already existed.\n private createExclusive(file: string, payload: string): boolean {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.writeFileSync(file, payload, { flag: 'wx' });\n return true;\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return false;\n }\n }\n\n // The pid recorded in the lock file, or 0 when there is no readable lock.\n private lockHolderPid(homeDir: string): number {\n const text = this.readTextOrEmpty(this.lockPath(homeDir));\n if (text === '') return 0;\n const match = /\"pid\"\\s*:\\s*(\\d+)/.exec(text);\n return match === null ? 0 : Number.parseInt(match[1], 10);\n }\n\n // An unreadable or pid-less lock file counts as DEAD: it is a corpse from a crashed writer, and\n // leaving it forever would mean every future append silently skips rotation.\n private isHolderAlive(homeDir: string): boolean {\n const pid = this.lockHolderPid(homeDir);\n return pid > 0 && this.isAlive(pid);\n }\n\n private holderIsUs(homeDir: string): boolean {\n return this.lockHolderPid(homeDir) === process.pid;\n }\n\n /**\n * `.4→.5, .3→.4, … .log→.1`, dropping the old `.5`. Runs INSIDE the lock, which is the one place the\n * lock is genuinely load-bearing: a rename-and-reopen really does race, and a writer that opened the\n * old inode mid-shift would append into a file nobody reads again.\n */\n private rotateIfLarge(homeDir: string): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n if (!fs.existsSync(this.logPath(homeDir))) return;\n if (fs.statSync(this.logPath(homeDir)).size < MAX_BUILDS_LOG_BYTES) return;\n this.unlinkQuietly(this.rotatedPath(BUILDS_LOG_GENERATIONS, homeDir));\n for (let gen = BUILDS_LOG_GENERATIONS - 1; gen >= 1; gen -= 1) {\n this.renameQuietly(this.rotatedPath(gen, homeDir), this.rotatedPath(gen + 1, homeDir));\n }\n this.renameQuietly(this.logPath(homeDir), this.rotatedPath(1, homeDir));\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n }\n\n // ─── FILESYSTEM PRIMITIVES, ALL SWALLOWING ────────────────────────────────────────────────────────\n\n private ensureDir(file: string): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.mkdirSync(path.dirname(file), { recursive: true });\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n }\n\n private unlinkQuietly(file: string): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n if (fs.existsSync(file)) fs.unlinkSync(file);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n }\n\n private renameQuietly(from: string, to: string): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n if (fs.existsSync(from)) fs.renameSync(from, to);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n }\n\n private readTextOrEmpty(file: string): string {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return '';\n }\n }\n\n private readLines(file: string): string[] {\n const text = this.readTextOrEmpty(file);\n if (text === '') return [];\n return text.split('\\n').filter((line: string): boolean => line.trim() !== '');\n }\n\n // A blocking sleep, because the lock retry sits on a synchronous append path that must not become\n // async — `finish()` is called from a `finally` and an async logger there could outlive the process.\n private sleep(ms: number): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n }\n\n // The checked-out branch in `startDir`, or '' when git cannot say. spawnSync does not throw on a\n // non-zero exit, so \"not a repo\" arrives as a status, not an exception.\n private gitBranch(startDir: string): string {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const result = spawnSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'],\n { cwd: startDir, encoding: 'utf8' });\n if (result.status !== 0 || typeof result.stdout !== 'string') return '';\n return result.stdout.trim();\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return '';\n }\n }\n}\n"]}
1
+ {"version":3,"file":"builds-log.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/builds-log.ts"],"names":[],"mappings":";;;;AAAA,uDAAiC;AACjC,+CAAyB;AACzB,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAE3D,8DAAsE;AACtE,+CAAgD;AAChD,iEAA6D;AAE7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACU,QAAA,eAAe,GAAG,YAAY,CAAC;AAC/B,QAAA,gBAAgB,GAAG,iBAAiB,CAAC;AAElD,kGAAkG;AACrF,QAAA,WAAW,GAAG,OAAO,CAAC;AACtB,QAAA,kBAAkB,GAAG,cAAc,CAAC;AACpC,QAAA,eAAe,GAAG,WAAW,CAAC;AAE3C,uFAAuF;AAC1E,QAAA,oBAAoB,GAAG,IAAI,GAAG,IAAI,CAAC;AACnC,QAAA,sBAAsB,GAAG,CAAC,CAAC;AAExC;;;;GAIG;AACU,QAAA,aAAa,GAAG,GAAG,CAAC;AAEjC,iGAAiG;AACjG,MAAM,aAAa,GAAG,EAAE,CAAC;AACzB,MAAM,eAAe,GAAG,IAAI,CAAC;AAE7B;;;;GAIG;AACH,MAAa,WAAW;IACpB,EAAE,CAAS;IACX,EAAE,CAAS;IACX,IAAI,CAAS;IACb,SAAS,CAAS;IAElB,YAAY,EAAU,EAAE,EAAU,EAAE,IAAY,EAAE,SAAiB;QAC/D,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;QACb,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;QACb,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC/B,CAAC;CACJ;AAZD,kCAYC;AAED;;;;GAIG;AACH,MAAa,gBAAgB;IAC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CAAC,IAAY;QAC1B,MAAM,IAAI,GAAG,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC;QACxC,IAAI,IAAI,KAAK,EAAE;YAAE,OAAO,EAAE,CAAC;QAC3B,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,IAAY,EAAW,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;IAClF,CAAC;IAED,kGAAkG;IAClG,qGAAqG;IAC7F,KAAK,CAAC,EAAU;QACpB,8DAA8D;QAC9D,IAAI,CAAC;YACD,OAAO,CAAC,IAAI,CAAC,IAAI,UAAU,CAAC,IAAI,iBAAiB,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC;QACrE,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,KAAK,KAAK,CAAC;QACf,CAAC;IACL,CAAC;IAED,mEAAmE;IAC3D,SAAS,CAAC,QAAgB;QAC9B,OAAO,4BAAW,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC;IAC9C,CAAC;CACJ,CAAA;AApYY,8BAAS;oBAAT,SAAS;IADrB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEA,6BAAY;GADxC,SAAS,CAoYrB","sourcesContent":["import * as crypto from 'crypto';\nimport * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { DotWebpieces, gitCheckout } from '@webpieces/tooling-common';\nimport { HOME_CONFIG_DIR } from './home-config';\nimport { toError } from '@webpieces/tooling-common/to-error';\n\n/**\n * `~/.webpieces/builds.log` — the MACHINE-WIDE, append-only ledger of every build this box has started.\n *\n * ─── WHY THIS ONE FILE LIVES OUTSIDE THE REPO ─────────────────────────────────────────────────────────\n * `no-machine-global-state.spec.ts` records the standing rule: webpieces writes state under\n * `{repo}/.webpieces` and nowhere else. This is the ONE carve-out, and the argument is written out in\n * `decisions/0006-the-build-ledger-is-machine-global.md`. In short:\n *\n * • The FACT is machine-scoped. \"How many builds are burning this box's CPU right now\" is not a\n * property of any repo; it is a property of the machine. A per-repo ledger cannot answer it — every\n * linked worktree has its OWN `.webpieces/`, so it would be blind to the sibling worktree it is\n * actually contending with, never mind the four other repos on the disk.\n * • It is NOT A CACHE. The retired `PrBodyStore` that the no-machine-global rule was written for was a\n * local copy of a fact GitHub owned, so it could be stale, missing, or on the wrong computer. There\n * is no remote copy of this. The file IS the fact.\n * • Its key is an ABSOLUTE LOCAL PATH, which is stable precisely because it never leaves the machine —\n * the instability that killed `PrBodyStore`'s `<host>/<owner>/<repo>` key cannot arise here.\n *\n * ─── WHY IT IS SAFE TO WRITE CONCURRENTLY ─────────────────────────────────────────────────────────────\n * Rows are deliberately kept under `MAX_ROW_BYTES` (512, macOS `PIPE_BUF`). A single `O_APPEND`\n * `write(2)` at or below that size is indivisible, so two builds appending at the same instant cannot\n * interleave halves of a line. The lock is therefore belt-and-braces for the APPEND and genuinely\n * load-bearing for ROTATION, where a rename-and-reopen really does race.\n *\n * ─── IT MAY NEVER FAIL A BUILD ────────────────────────────────────────────────────────────────────────\n * Every method here is best-effort and swallows its own errors. A build must never die because a log\n * file was busy, unwritable, or on a full disk. Lock acquisition retries and then gives up and appends\n * anyway — which the row-size invariant above makes safe.\n */\nexport const BUILDS_LOG_FILE = 'builds.log';\nexport const BUILDS_LOCK_FILE = 'builds.log.lock';\n\n/** START, and the two terminal kinds. `DONE-` is the greppable prefix that pairs with a START. */\nexport const BUILD_START = 'START';\nexport const BUILD_DONE_SUCCESS = 'DONE-SUCCESS';\nexport const BUILD_DONE_FAIL = 'DONE-FAIL';\n\n/** Rotate at 1 MB, keeping five generations (`.1` … `.5`); the old `.5` is dropped. */\nexport const MAX_BUILDS_LOG_BYTES = 1024 * 1024;\nexport const BUILDS_LOG_GENERATIONS = 5;\n\n/**\n * macOS `PIPE_BUF`. A row at or under this size is written by ONE indivisible `write(2)`, which is what\n * makes a lost lock a non-event rather than a corrupted file. Long paths are clipped to hold the line\n * under it — see `clip`.\n */\nexport const MAX_ROW_BYTES = 512;\n\n/** How long a build may hold the lock before another writer stops waiting and appends anyway. */\nconst LOCK_RETRY_MS = 50;\nconst LOCK_TIMEOUT_MS = 2000;\n\n/**\n * The handle a START row hands back, and the ONLY thing `finish()` accepts. Data-only (a class, per\n * CLAUDE.md), carrying exactly the fields the DONE row needs to pair itself with its START: the uuid,\n * the caller, the repo, and when it began (so `took=` is computed from one clock, not two).\n */\nexport class BuildTicket {\n id: string;\n by: string;\n repo: string;\n startedMs: number;\n\n constructor(id: string, by: string, repo: string, startedMs: number) {\n this.id = id;\n this.by = by;\n this.repo = repo;\n this.startedMs = startedMs;\n }\n}\n\n/**\n * How the build process ended. Node reports a null code when a signal ended the process, so collapsing\n * this to a number would discard the only useful explanation for an otherwise silent build failure.\n * Data-only: the PR gate decides which CLI exit code to return, while the ledger records these raw facts.\n */\nexport class BuildTermination {\n code: number | null;\n signal: string | null;\n\n constructor(code: number | null, signal: string | null) {\n this.code = code;\n this.signal = signal;\n }\n}\n\n/**\n * One build that is STILL RUNNING — a START row with no matching `DONE-`, whose pid is still alive.\n * Data-only. This is what the refusal message renders, so it carries the three things a reader needs to\n * recognise the build in question: where it is, which tree, and how old it is.\n */\nexport class RunningBuild {\n id: string;\n by: string;\n repo: string;\n tree: string;\n cwd: string;\n branch: string;\n pid: number;\n startedMs: number;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n id: string, by: string, repo: string, tree: string,\n cwd: string, branch: string, pid: number, startedMs: number,\n ) {\n this.id = id;\n this.by = by;\n this.repo = repo;\n this.tree = tree;\n this.cwd = cwd;\n this.branch = branch;\n this.pid = pid;\n this.startedMs = startedMs;\n }\n}\n\n/**\n * The ledger. See the file docblock for why it is machine-global and why every operation swallows its\n * own errors.\n *\n * `homeDir` is a parameter on every public method, defaulted to `os.homedir()`, for exactly the reason\n * `HomeConfigService.configPath` takes one: a spec must be able to exercise the real code against a temp\n * directory and must never touch the developer's actual `~/.webpieces`.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class BuildsLog {\n constructor(private readonly dotDir: DotWebpieces) {}\n\n /** `~/.webpieces/builds.log`. */\n logPath(homeDir: string = os.homedir()): string {\n return path.join(homeDir, HOME_CONFIG_DIR, BUILDS_LOG_FILE);\n }\n\n /** `~/.webpieces/builds.log.lock` — `{\"pid\":N,\"started\":<epochMs>}`. */\n lockPath(homeDir: string = os.homedir()): string {\n return path.join(homeDir, HOME_CONFIG_DIR, BUILDS_LOCK_FILE);\n }\n\n /** `~/.webpieces/builds.log.<n>` — generation `n`, 1 being the most recent. */\n rotatedPath(generation: number, homeDir: string = os.homedir()): string {\n return `${this.logPath(homeDir)}.${String(generation)}`;\n }\n\n /**\n * Record that a build is starting, and hand back the ticket its DONE row will need.\n *\n * `by` is the CALLER — `BuildGateOptions.stage`, i.e. `build` | `review` | `finish`. There is no\n * second \"caller\" concept anywhere: the stage id already is one, and a second spelling of it would\n * be the shim `.claude/rules/no-backwards-compat.md` rejects.\n *\n * Returns a ticket even when the append failed. A build whose START row never landed still has to be\n * able to call `finish()`; the alternative is a nullable return that every call site must branch on\n * for a logging failure that is, by policy, not an error.\n */\n start(by: string, startDir: string, homeDir: string = os.homedir()): BuildTicket {\n const ticket = new BuildTicket(\n crypto.randomUUID(), by, this.dotDir.primaryRoot(startDir), Date.now());\n this.append(this.startRow(ticket, startDir), homeDir);\n return ticket;\n }\n\n /**\n * Record that the build behind `ticket` has ended. Only code 0 with no signal writes `DONE-SUCCESS`;\n * anything else writes `DONE-FAIL` carrying the raw code and signal, so a killed build does not become\n * an unexplained generic exit 1 in the machine record.\n */\n finish(ticket: BuildTicket, termination: BuildTermination, homeDir: string = os.homedir()): void {\n this.append(this.doneRow(ticket, termination), homeDir);\n }\n\n /**\n * Every build that is still live: a `START` with no matching `DONE-` row, whose pid is still alive.\n *\n * The pid filter is not an optimisation, it is what keeps the ledger from wedging the machine. A\n * build killed with SIGKILL — an agent cancelled mid-run, a terminal closed — writes no DONE row, so\n * without the liveness test its START would count forever and the fourth build would be refused for\n * the rest of the machine's life. The uuid answers \"which build\"; the pid answers \"is it still real\".\n *\n * Only the CURRENT generation is read. A rotated-away START is by definition at least 1 MB of rows\n * old and is not a build anyone is contending with.\n */\n running(homeDir: string = os.homedir()): RunningBuild[] {\n const lines = this.readLines(this.logPath(homeDir));\n const done = new Set<string>();\n for (const line of lines) {\n if (line.startsWith(`${BUILD_DONE_SUCCESS}\\t`) || line.startsWith(`${BUILD_DONE_FAIL}\\t`)) {\n done.add(this.field(line, 'id'));\n }\n }\n const live: RunningBuild[] = [];\n for (const line of lines) {\n if (!line.startsWith(`${BUILD_START}\\t`)) continue;\n const build = this.toRunningBuild(line);\n if (build === null || done.has(build.id)) continue;\n if (!this.isAlive(build.pid)) continue;\n live.push(build);\n }\n return live;\n }\n\n /**\n * The `@webpieces` release ACTUALLY EXECUTING — found by walking UP from this module's own directory\n * to the nearest enclosing `node_modules/@webpieces/<pkg>/package.json`. `''` when this code is\n * running from source rather than from an installed package (which is the state in this repo's own\n * specs, and a perfectly ordinary answer).\n *\n * ─── WHY THIS IS NOT `WebpiecesVersions.readInstalled(root)` ──────────────────────────────────────\n * They answer DIFFERENT QUESTIONS and merging them would break the older one. `readInstalled` joins\n * `<root>/node_modules/@webpieces/...` at a FIXED tree root ON PURPOSE: its whole job is to detect\n * DRIFT between what a tree PINS and what some other tree pins, and a walk-up would silently resolve\n * a worktree with no install of its own to the primary clone's copy — hiding exactly the skew that\n * guard exists to catch. This question is the opposite one: \"whichever copy is running, name it\", and\n * for that the walk-up is the only correct answer. Do not fold them together.\n */\n executingVersion(): string {\n let dir = __dirname;\n for (let hops = 0; hops < 40; hops += 1) {\n const version = this.versionOfEnclosingPackage(dir);\n if (version !== '') return version;\n const parent = path.dirname(dir);\n if (parent === dir) return '';\n dir = parent;\n }\n return '';\n }\n\n // `<dir>` is `node_modules/@webpieces/<pkg>/...`? Then that package's version, else ''.\n private versionOfEnclosingPackage(dir: string): string {\n const parent = path.dirname(dir);\n const grandparent = path.dirname(parent);\n if (path.basename(parent) !== '@webpieces' || path.basename(grandparent) !== 'node_modules') return '';\n const text = this.readTextOrEmpty(path.join(dir, 'package.json'));\n const match = /\"version\"\\s*:\\s*\"([^\"]+)\"/.exec(text);\n return match === null ? '' : match[1];\n }\n\n // ─── ROW RENDERING ────────────────────────────────────────────────────────────────────────────────\n\n private startRow(ticket: BuildTicket, startDir: string): string {\n return [\n BUILD_START,\n `id=${ticket.id}`,\n `t=${new Date(ticket.startedMs).toISOString()}`,\n `ms=${String(ticket.startedMs)}`,\n `by=${ticket.by}`,\n `repo=${this.clip(ticket.repo)}`,\n `tree=${this.dotDir.worktreeName(startDir) || 'primary'}`,\n `cwd=${this.clip(startDir)}`,\n `branch=${this.gitBranch(startDir)}`,\n `pid=${String(process.pid)}`,\n `wp=${this.executingVersion()}`,\n ].join('\\t');\n }\n\n private doneRow(ticket: BuildTicket, termination: BuildTermination): string {\n const now = Date.now();\n const success = termination.code === 0 && termination.signal === null;\n const fields = [\n success ? BUILD_DONE_SUCCESS : BUILD_DONE_FAIL,\n `id=${ticket.id}`,\n `t=${new Date(now).toISOString()}`,\n `ms=${String(now)}`,\n `by=${ticket.by}`,\n `repo=${this.clip(ticket.repo)}`,\n `took=${String(now - ticket.startedMs)}`,\n ];\n if (!success) fields.push(`exit=${termination.code === null ? 'null' : String(termination.code)}`);\n if (termination.signal !== null) fields.push(`signal=${this.clip(termination.signal)}`);\n fields.push(`pid=${String(process.pid)}`);\n return fields.join('\\t');\n }\n\n /**\n * Hold a long path down to `max` characters by keeping its TAIL, which is the half that identifies\n * the tree; a clipped value is marked with a leading `…` so nobody mistakes it for a real path.\n *\n * This is what keeps a row under `MAX_ROW_BYTES` — see the file docblock. `append` re-checks the\n * assembled line as a backstop, because three clipped fields plus a long branch name can still add up.\n */\n private clip(value: string, max = 120): string {\n const oneLine = value.replace(/[\\t\\n\\r]/g, ' ');\n return oneLine.length <= max ? oneLine : `…${oneLine.slice(oneLine.length - max)}`;\n }\n\n // ─── ROW PARSING ──────────────────────────────────────────────────────────────────────────────────\n\n /** The value of `<name>=` on a TSV row, or '' when the row does not carry it. */\n private field(line: string, name: string): string {\n for (const part of line.split('\\t')) {\n if (part.startsWith(`${name}=`)) return part.slice(name.length + 1);\n }\n return '';\n }\n\n // A START row as a RunningBuild, or null when it is missing the two fields that make it usable.\n private toRunningBuild(line: string): RunningBuild | null {\n const id = this.field(line, 'id');\n const pid = Number.parseInt(this.field(line, 'pid'), 10);\n if (id === '' || !Number.isInteger(pid) || pid <= 0) return null;\n const startedMs = Number.parseInt(this.field(line, 'ms'), 10);\n return new RunningBuild(\n id, this.field(line, 'by'), this.field(line, 'repo'), this.field(line, 'tree'),\n this.field(line, 'cwd'), this.field(line, 'branch'), pid,\n Number.isInteger(startedMs) ? startedMs : 0,\n );\n }\n\n /**\n * Is `pid` still addressable? `process.kill(pid, 0)` sends no signal — it only asks the kernel. ESRCH\n * is the ONE answer that proves death; EPERM proves the opposite (it exists, it is somebody else's).\n * Pid reuse is an accepted imprecision here: being wrong in the \"still running\" direction costs\n * one extra refusal, being wrong the other way lets a fourth build start.\n *\n * WHY A PID IS MEANINGFUL HERE AND WAS NOT FOR AGENT WORKTREE LOCKS. Every row in this ledger is\n * written BY the process it names — one real OS process per build — so its pid identifies it.\n * A Claude Code subagent is not a process at all: every agent in a session records the SAME pid,\n * the session's, which is why that check was deleted rather than shared (see\n * harness-agent-activity.ts). Do not generalise this one back out to anything but a real process.\n */\n private isAlive(pid: number): boolean {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n process.kill(pid, 0);\n return true;\n } catch (err: unknown) {\n const error = toError(err);\n return (error as NodeJS.ErrnoException).code !== 'ESRCH';\n }\n }\n\n // ─── APPEND, LOCK, ROTATE ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Append one row, best-effort. Takes the lock so rotation cannot race, and appends ANYWAY when the\n * lock cannot be had within `LOCK_TIMEOUT_MS` — the row is under `PIPE_BUF`, so an unlocked\n * `O_APPEND` write is still indivisible, and a build must never die because a log file was busy.\n */\n private append(row: string, homeDir: string): void {\n const line = `${this.truncateToRowLimit(row)}\\n`;\n const held = this.tryAcquireLock(homeDir);\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n this.ensureDir(this.logPath(homeDir));\n if (held) this.rotateIfLarge(homeDir);\n fs.appendFileSync(this.logPath(homeDir), line);\n } catch (err: unknown) {\n const error = toError(err);\n void error; // logging may never fail a build — see the file docblock\n } finally {\n if (held) this.releaseLock(homeDir);\n }\n }\n\n // The backstop for the PIPE_BUF invariant, measured in BYTES rather than characters because a path\n // may hold multi-byte characters. Truncating a row loses fields off the end, which is strictly better\n // than a torn line that breaks every row after it.\n private truncateToRowLimit(row: string): string {\n const bytes = Buffer.from(row, 'utf8');\n // -1 for the newline `append` adds.\n if (bytes.length <= MAX_ROW_BYTES - 1) return row;\n return bytes.subarray(0, MAX_ROW_BYTES - 1).toString('utf8');\n }\n\n /**\n * Take the ledger lock, retrying every `LOCK_RETRY_MS` until `LOCK_TIMEOUT_MS`. False means \"carry on\n * without it\" — never an error, and never a reason to skip the append.\n *\n * The mechanism is `MainSyncLockService.tryAcquireMainSyncLock`'s, proven and deliberately copied\n * rather than re-invented: an `wx` (O_CREAT|O_EXCL) create so exactly one of N racers wins, a payload\n * carrying pid + started so a dead holder is identifiable, stale reclaim gated on pid liveness, and a\n * re-read afterwards to confirm the entry on disk is OURS (a simultaneous reclaimer could have\n * unlinked ours and written its own between the two calls).\n */\n private tryAcquireLock(homeDir: string): boolean {\n const deadline = Date.now() + LOCK_TIMEOUT_MS;\n this.ensureDir(this.lockPath(homeDir));\n // Rendered rather than JSON.stringify'd off an anonymous object — two fields, both numbers, and\n // the file's whole contract is `{\"pid\":N,\"started\":M}`.\n const payload = `{\"pid\":${String(process.pid)},\"started\":${String(Date.now())}}\\n`;\n for (;;) {\n if (this.createExclusive(this.lockPath(homeDir), payload)) return true;\n if (!this.isHolderAlive(homeDir)) {\n this.unlinkQuietly(this.lockPath(homeDir));\n if (this.createExclusive(this.lockPath(homeDir), payload) && this.holderIsUs(homeDir)) return true;\n }\n if (Date.now() >= deadline) return false;\n this.sleep(LOCK_RETRY_MS);\n }\n }\n\n private releaseLock(homeDir: string): void {\n if (!this.holderIsUs(homeDir)) return;\n this.unlinkQuietly(this.lockPath(homeDir));\n }\n\n // O_CREAT|O_EXCL write: true when THIS call created the file, false when it already existed.\n private createExclusive(file: string, payload: string): boolean {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.writeFileSync(file, payload, { flag: 'wx' });\n return true;\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return false;\n }\n }\n\n // The pid recorded in the lock file, or 0 when there is no readable lock.\n private lockHolderPid(homeDir: string): number {\n const text = this.readTextOrEmpty(this.lockPath(homeDir));\n if (text === '') return 0;\n const match = /\"pid\"\\s*:\\s*(\\d+)/.exec(text);\n return match === null ? 0 : Number.parseInt(match[1], 10);\n }\n\n // An unreadable or pid-less lock file counts as DEAD: it is a corpse from a crashed writer, and\n // leaving it forever would mean every future append silently skips rotation.\n private isHolderAlive(homeDir: string): boolean {\n const pid = this.lockHolderPid(homeDir);\n return pid > 0 && this.isAlive(pid);\n }\n\n private holderIsUs(homeDir: string): boolean {\n return this.lockHolderPid(homeDir) === process.pid;\n }\n\n /**\n * `.4→.5, .3→.4, … .log→.1`, dropping the old `.5`. Runs INSIDE the lock, which is the one place the\n * lock is genuinely load-bearing: a rename-and-reopen really does race, and a writer that opened the\n * old inode mid-shift would append into a file nobody reads again.\n */\n private rotateIfLarge(homeDir: string): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n if (!fs.existsSync(this.logPath(homeDir))) return;\n if (fs.statSync(this.logPath(homeDir)).size < MAX_BUILDS_LOG_BYTES) return;\n this.unlinkQuietly(this.rotatedPath(BUILDS_LOG_GENERATIONS, homeDir));\n for (let gen = BUILDS_LOG_GENERATIONS - 1; gen >= 1; gen -= 1) {\n this.renameQuietly(this.rotatedPath(gen, homeDir), this.rotatedPath(gen + 1, homeDir));\n }\n this.renameQuietly(this.logPath(homeDir), this.rotatedPath(1, homeDir));\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n }\n\n // ─── FILESYSTEM PRIMITIVES, ALL SWALLOWING ────────────────────────────────────────────────────────\n\n private ensureDir(file: string): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.mkdirSync(path.dirname(file), { recursive: true });\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n }\n\n private unlinkQuietly(file: string): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n if (fs.existsSync(file)) fs.unlinkSync(file);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n }\n\n private renameQuietly(from: string, to: string): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n if (fs.existsSync(from)) fs.renameSync(from, to);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n }\n\n private readTextOrEmpty(file: string): string {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return '';\n }\n }\n\n private readLines(file: string): string[] {\n const text = this.readTextOrEmpty(file);\n if (text === '') return [];\n return text.split('\\n').filter((line: string): boolean => line.trim() !== '');\n }\n\n // A blocking sleep, because the lock retry sits on a synchronous append path that must not become\n // async — `finish()` is called from a `finally` and an async logger there could outlive the process.\n private sleep(ms: number): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n }\n\n // The checked-out branch in `startDir`, or '' when git cannot say.\n private gitBranch(startDir: string): string {\n return gitCheckout.branch(startDir) ?? '';\n }\n}\n"]}
package/src/index.d.ts CHANGED
@@ -5,7 +5,7 @@ export { TurnOffRuleCure, LAST_RESORT_TURN_OFF_SECONDS } from './turn-off-rule-c
5
5
  export { CliExitError } from './cli-exit-error';
6
6
  export { CliUsage, CliFlag, CliArgSet, CliArgsCheck, CliArgs } from './cli-args';
7
7
  export { runMain } from './run-main';
8
- export { loadAndValidate, LoadedConfig, ConfigLoader } from './load-config';
8
+ export { loadAndValidate, assertPolicyTracked, LoadedConfig, ConfigLoader } from './load-config';
9
9
  export { formatConfigErrorsBanner, CONFIG_POLICY_DOC, RETIRED_KEY_MARKER, RETIRED_TOP_LEVEL_MARKER, } from './config-error-banner';
10
10
  export { findConfigFile, CONFIG_FILENAME, ConfigFile, ConfigParseAttempt, CONFIG_PARSE_ATTEMPTS, CONFIG_PARSE_RETRY_MILLIS, } from './config-file';
11
11
  export { RawConfigFile } from './config-file';
package/src/index.js CHANGED
@@ -1,11 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.globMatches = exports.matchesAnyGlob = exports.isPathExcluded = exports.isWebpiecesStateDir = exports.ExcludePaths = exports.DESIGN_METADATA_KEYS = exports.isDocumentDesign = exports.DocumentDesign = exports.RulesConfigDesign = exports.atRoot = exports.CLAUDE_PROJECT_DIR_UNSET = exports.CLAUDE_PROJECT_DIR_ENV = exports.claudeEnv = exports.ClaudeEnv = exports.RETENTION_DAYS = exports.SweepCount = exports.AgedTreeSweeper = exports.INSTRUCT_AI_LEAF = exports.INSTRUCT_AI_DIR = exports.RepoRootFinder = exports.RawConfigFile = exports.CONFIG_PARSE_RETRY_MILLIS = exports.CONFIG_PARSE_ATTEMPTS = exports.ConfigParseAttempt = exports.ConfigFile = exports.CONFIG_FILENAME = exports.findConfigFile = exports.RETIRED_TOP_LEVEL_MARKER = exports.RETIRED_KEY_MARKER = exports.CONFIG_POLICY_DOC = exports.formatConfigErrorsBanner = exports.ConfigLoader = exports.LoadedConfig = exports.loadAndValidate = exports.runMain = exports.CliArgs = exports.CliArgsCheck = exports.CliArgSet = exports.CliFlag = exports.CliUsage = exports.CliExitError = exports.LAST_RESORT_TURN_OFF_SECONDS = exports.TurnOffRuleCure = exports.formatFixOptions = exports.Option = exports.renderRuleFailForHuman = exports.renderRuleFailForAi = exports.RuleFailError = exports.ResolvedRuleConfig = exports.ResolvedConfig = void 0;
4
- exports.HOME_CONFIG_DIR = exports.RETIRED_HOME_CONFIG_KEYS = exports.RetiredHomeConfigKey = exports.HomeConfigService = exports.HomeConfig = exports.validateChecklistDocs = exports.PrunedKey = exports.PruneResult = exports.ConfigPruner = exports.retiredRuleFor = exports.retiredKeyErrorsIn = exports.retiredKeyError = exports.retiredEntry = exports.isRetiredKey = exports.RETIRED_SCOPE_RULE = exports.RETIRED_SCOPE_KEY = exports.RETIRED_CONFIG_KEYS = exports.CONFIG_DOCUMENTATION_PATH = exports.CONFIG_DOCUMENTATION_KEY = exports.validateTopLevelKeys = exports.unknownKeyErrors = exports.validateCommandsSection = exports.seedEntryForRule = exports.recommendedSeedModeFor = exports.recommendedSeedMode = exports.allRuleNames = exports.validateMatchRulesSection = exports.validateExcludePaths = exports.validateChecklistsSection = exports.validatePrGateSection = exports.validateWebpiecesConfig = exports.BUILD_LOG_DOC = exports.ReferenceMergeRun = exports.MergeRun = exports.MergeProcessText = exports.MERGE_PROCESS_DOC = exports.MergeProcessDoc = exports.InstructAiDocSet = exports.InstructAiDoc = exports.GitWorkflowDoc = exports.GIT_WORKFLOW_DOC = exports.TemplateWriter = exports.writeTemplate = exports.writeTemplateIfMissing = exports.loadTemplate = exports.PathScopeConfig = exports.NoCustomCssScope = exports.GENERATED_CODE_PATHS = exports.RuleFileExclusions = exports.RuleFileScope = void 0;
5
- exports.resolveBase = exports.detectBase = exports.SkipRuleResult = exports.HOTFIX_AUDIT_BANNER = exports.HOTFIX_BUILD_COMMAND = exports.shouldSkipRule = exports.sectionForRule = exports.isHookGuard = exports.schemaFieldNames = exports.DEFAULT_MATCH_RULES = exports.renderMatchRuleMessage = exports.compileMatchRulePatterns = exports.isMatchRuleAllowedPath = exports.findMatchRuleViolations = exports.MatchRuleViolation = exports.MatchRuleConfig = exports.OrphanSweepReport = exports.OrphanDirSweeper = exports.TRASH_RETENTION_DAYS = exports.TRASH_MANIFEST_FILE = exports.TRASH_STATE_DIR = exports.OrphanSweepManifest = exports.OrphanSweepResult = exports.FailedOrphan = exports.ArchivedOrphan = exports.OrphanDirArchiver = exports.OrphanCandidate = exports.OrphanDirScanner = exports.MAX_ROW_BYTES = exports.BUILDS_LOG_GENERATIONS = exports.MAX_BUILDS_LOG_BYTES = exports.BUILD_DONE_FAIL = exports.BUILD_DONE_SUCCESS = exports.BUILD_START = exports.BUILDS_LOCK_FILE = exports.BUILDS_LOG_FILE = exports.RunningBuild = exports.BuildTermination = exports.BuildTicket = exports.BuildsLog = exports.DOCUMENTATION_KEYS = exports.HOME_KEY_AI_DOC = exports.HOME_KEY_DOC = exports.DEFAULT_MAX_CONCURRENT_BUILDS = exports.HOME_KEY_TURN_OFF_ALL_REVIEWERS = exports.HOME_KEY_MAX_CONCURRENT_BUILDS = exports.HOME_KEY_WHOLE_REPO_BUILD_GUARD = exports.HOME_KEY_ORPHAN_DIR_SWEEP = exports.HOME_EXPERIMENTAL_SECTION = exports.HOME_CONFIG_FILE = void 0;
6
- exports.normalizeChecklistDoc = exports.toChecklist = exports.DEFAULT_REVIEWER_AGENT_NAME = exports.REVIEWER_AGENTS_PLACEHOLDER = exports.ReviewerAgentPolicy = exports.ChecklistDefinition = exports.MERGE_MODES = exports.MERGE_MODE_NONE = exports.MERGE_MODE_AUTO = exports.buildDevDeployConfig = exports.buildLandPrConfig = exports.buildPrGateConfig = exports.defaultDevDeployConfig = exports.defaultLandPrConfig = exports.defaultPrGateConfig = exports.defaultGates = exports.ReviewContextEntry = exports.DEFAULT_DEV_BRANCH = exports.DEFAULT_DEV_BRANCH_NAMESPACE = exports.DevDeployConfig = exports.LandPrConfig = exports.DEFAULT_BUILD_COMMAND = exports.PrGateConfig = exports.GateDefinition = exports.WP_FINISH_PUSH_DEV = exports.WP_PUSH_DEV = exports.WP_FINISH_UPSERT_PR = exports.WP_START_UPSERT_PR = exports.WP_FINISH_UPDATE = exports.WP_START_UPDATE = exports.SyncFlowGuidance = exports.WebpiecesRulesConfig = exports.UPGRADE_SHIM_COMMAND = exports.PRUNE_UNKNOWN_COMMAND = exports.PUSH_DEV_STATE_FILE = exports.MERGE_EXPLANATION_FILE = exports.MERGE_IN_PROGRESS_FILE = exports.MERGE_INFO_DIR = exports.hasDisable = exports.WEBPIECES_DISABLE = exports.AbstractRule = exports.ChangedFilesOptions = exports.DiffRange = exports.DiffScope = exports.isNewOrModified = exports.hasChangesInRange = exports.findNewMethodSignaturesInDiff = exports.getChangedLineNumbers = exports.getFileDiff = exports.getChangedFiles = void 0;
7
- exports.VERDICT_RED = exports.VERDICT_ORANGE = exports.VERDICT_YELLOW = exports.VERDICT_GREEN = exports.CK_BAD_FORMAT = exports.CK_MISSING = exports.CK_FAIL = exports.CK_ORANGE = exports.CK_ORANGE_FIXED = exports.CK_OVERRIDDEN = exports.CK_WARN = exports.CK_PASS = exports.checklistOverrideService = exports.ChecklistOverrideService = exports.ChecklistOverride = exports.ChecklistVerdict = exports.ChecklistResult = exports.PrContext = exports.AddressedIssue = exports.PrSummary = exports.DEFAULT_RETENTION_DAYS = exports.ProvenanceWriteRequest = exports.OfferedContext = exports.ReviewerPaths = exports.ReviewerTranscript = exports.ReviewProvenance = exports.ReviewProvenanceService = exports.PROVENANCE_SKIPPED = exports.PROVENANCE_MISSING = exports.PROVENANCE_OK = exports.ProvenanceResult = exports.TranscriptScan = exports.ExpectedReviewer = exports.ReviewerContext = exports.ReviewerEvidence = exports.SubagentProvenanceService = exports.verifyGateToken = exports.extractGateToken = exports.gateTokenMarker = exports.computeGateToken = exports.GateTokenService = exports.ALL_DIFF_ONE_READ_LINES = exports.READ_TRUNCATION_LINES = exports.ContextEntry = exports.BriefedFile = exports.ReviewerBriefing = exports.ReviewerInstructionsService = exports.ChecklistInstructionsService = exports.ChecklistValidator = exports.formatFileList = void 0;
8
- exports.PathMatchCandidate = exports.FirstPathMatchResult = exports.FirstPathMatch = exports.RuntimeContributionGroup = exports.NodeRuleRuntimeModuleLoader = exports.RuleRuntimeModuleLoader = exports.RuleRuntimeModules = exports.UntrackedPolicyError = exports.RepositoryLayoutRepair = exports.RunCommandCure = exports.EditFileCure = exports.ConfigRepairError = exports.ConfigRepairCure = exports.ConfigRepairBootstrap = exports.ConfigRepairAccess = exports.RulePackSync = exports.PackPolicyFiles = exports.PackPolicyFilesResult = exports.SelectedPolicyPack = exports.PackPolicyDeclaration = exports.LegacyUpgradeResult = exports.LegacyConfigDocument = exports.prepareLegacyUpgrade = exports.RulePackModuleLoader = exports.RulePackDiscovery = exports.NodeRulePackModuleLoader = exports.RulePackRegistry = exports.TMP_SCRATCH_PREFIX = exports.TMP_SCRATCH_RETENTION_DAYS = exports.TmpScratchSweeper = exports.SCRATCH_DIR_NAME = exports.RepoScratchDirs = exports.staleBinSweeper = exports.StaleBinSweeper = exports.StaleBinRemoval = exports.DEFAULT_MERGE_COMPLETE_COMMAND = exports.DEFAULT_UPSERT_PR_COMMAND = exports.buildCommandsConfig = exports.CommandsConfig = exports.summaryJsonSchemaHint = exports.summaryJsonPath = exports.prDirFor = exports.ReviewJsonService = exports.ChecklistReviewContext = exports.RequiredChecklist = exports.VERDICT_STATUSES = void 0;
3
+ exports.matchesAnyGlob = exports.isPathExcluded = exports.isWebpiecesStateDir = exports.ExcludePaths = exports.DESIGN_METADATA_KEYS = exports.isDocumentDesign = exports.DocumentDesign = exports.RulesConfigDesign = exports.atRoot = exports.CLAUDE_PROJECT_DIR_UNSET = exports.CLAUDE_PROJECT_DIR_ENV = exports.claudeEnv = exports.ClaudeEnv = exports.RETENTION_DAYS = exports.SweepCount = exports.AgedTreeSweeper = exports.INSTRUCT_AI_LEAF = exports.INSTRUCT_AI_DIR = exports.RepoRootFinder = exports.RawConfigFile = exports.CONFIG_PARSE_RETRY_MILLIS = exports.CONFIG_PARSE_ATTEMPTS = exports.ConfigParseAttempt = exports.ConfigFile = exports.CONFIG_FILENAME = exports.findConfigFile = exports.RETIRED_TOP_LEVEL_MARKER = exports.RETIRED_KEY_MARKER = exports.CONFIG_POLICY_DOC = exports.formatConfigErrorsBanner = exports.ConfigLoader = exports.LoadedConfig = exports.assertPolicyTracked = exports.loadAndValidate = exports.runMain = exports.CliArgs = exports.CliArgsCheck = exports.CliArgSet = exports.CliFlag = exports.CliUsage = exports.CliExitError = exports.LAST_RESORT_TURN_OFF_SECONDS = exports.TurnOffRuleCure = exports.formatFixOptions = exports.Option = exports.renderRuleFailForHuman = exports.renderRuleFailForAi = exports.RuleFailError = exports.ResolvedRuleConfig = exports.ResolvedConfig = void 0;
4
+ exports.RETIRED_HOME_CONFIG_KEYS = exports.RetiredHomeConfigKey = exports.HomeConfigService = exports.HomeConfig = exports.validateChecklistDocs = exports.PrunedKey = exports.PruneResult = exports.ConfigPruner = exports.retiredRuleFor = exports.retiredKeyErrorsIn = exports.retiredKeyError = exports.retiredEntry = exports.isRetiredKey = exports.RETIRED_SCOPE_RULE = exports.RETIRED_SCOPE_KEY = exports.RETIRED_CONFIG_KEYS = exports.CONFIG_DOCUMENTATION_PATH = exports.CONFIG_DOCUMENTATION_KEY = exports.validateTopLevelKeys = exports.unknownKeyErrors = exports.validateCommandsSection = exports.seedEntryForRule = exports.recommendedSeedModeFor = exports.recommendedSeedMode = exports.allRuleNames = exports.validateMatchRulesSection = exports.validateExcludePaths = exports.validateChecklistsSection = exports.validatePrGateSection = exports.validateWebpiecesConfig = exports.BUILD_LOG_DOC = exports.ReferenceMergeRun = exports.MergeRun = exports.MergeProcessText = exports.MERGE_PROCESS_DOC = exports.MergeProcessDoc = exports.InstructAiDocSet = exports.InstructAiDoc = exports.GitWorkflowDoc = exports.GIT_WORKFLOW_DOC = exports.TemplateWriter = exports.writeTemplate = exports.writeTemplateIfMissing = exports.loadTemplate = exports.PathScopeConfig = exports.NoCustomCssScope = exports.GENERATED_CODE_PATHS = exports.RuleFileExclusions = exports.RuleFileScope = exports.globMatches = void 0;
5
+ exports.detectBase = exports.SkipRuleResult = exports.HOTFIX_AUDIT_BANNER = exports.HOTFIX_BUILD_COMMAND = exports.shouldSkipRule = exports.sectionForRule = exports.isHookGuard = exports.schemaFieldNames = exports.DEFAULT_MATCH_RULES = exports.renderMatchRuleMessage = exports.compileMatchRulePatterns = exports.isMatchRuleAllowedPath = exports.findMatchRuleViolations = exports.MatchRuleViolation = exports.MatchRuleConfig = exports.OrphanSweepReport = exports.OrphanDirSweeper = exports.TRASH_RETENTION_DAYS = exports.TRASH_MANIFEST_FILE = exports.TRASH_STATE_DIR = exports.OrphanSweepManifest = exports.OrphanSweepResult = exports.FailedOrphan = exports.ArchivedOrphan = exports.OrphanDirArchiver = exports.OrphanCandidate = exports.OrphanDirScanner = exports.MAX_ROW_BYTES = exports.BUILDS_LOG_GENERATIONS = exports.MAX_BUILDS_LOG_BYTES = exports.BUILD_DONE_FAIL = exports.BUILD_DONE_SUCCESS = exports.BUILD_START = exports.BUILDS_LOCK_FILE = exports.BUILDS_LOG_FILE = exports.RunningBuild = exports.BuildTermination = exports.BuildTicket = exports.BuildsLog = exports.DOCUMENTATION_KEYS = exports.HOME_KEY_AI_DOC = exports.HOME_KEY_DOC = exports.DEFAULT_MAX_CONCURRENT_BUILDS = exports.HOME_KEY_TURN_OFF_ALL_REVIEWERS = exports.HOME_KEY_MAX_CONCURRENT_BUILDS = exports.HOME_KEY_WHOLE_REPO_BUILD_GUARD = exports.HOME_KEY_ORPHAN_DIR_SWEEP = exports.HOME_EXPERIMENTAL_SECTION = exports.HOME_CONFIG_FILE = exports.HOME_CONFIG_DIR = void 0;
6
+ exports.toChecklist = exports.DEFAULT_REVIEWER_AGENT_NAME = exports.REVIEWER_AGENTS_PLACEHOLDER = exports.ReviewerAgentPolicy = exports.ChecklistDefinition = exports.MERGE_MODES = exports.MERGE_MODE_NONE = exports.MERGE_MODE_AUTO = exports.buildDevDeployConfig = exports.buildLandPrConfig = exports.buildPrGateConfig = exports.defaultDevDeployConfig = exports.defaultLandPrConfig = exports.defaultPrGateConfig = exports.defaultGates = exports.ReviewContextEntry = exports.DEFAULT_DEV_BRANCH = exports.DEFAULT_DEV_BRANCH_NAMESPACE = exports.DevDeployConfig = exports.LandPrConfig = exports.DEFAULT_BUILD_COMMAND = exports.PrGateConfig = exports.GateDefinition = exports.WP_FINISH_PUSH_DEV = exports.WP_PUSH_DEV = exports.WP_FINISH_UPSERT_PR = exports.WP_START_UPSERT_PR = exports.WP_FINISH_UPDATE = exports.WP_START_UPDATE = exports.SyncFlowGuidance = exports.WebpiecesRulesConfig = exports.UPGRADE_SHIM_COMMAND = exports.PRUNE_UNKNOWN_COMMAND = exports.PUSH_DEV_STATE_FILE = exports.MERGE_EXPLANATION_FILE = exports.MERGE_IN_PROGRESS_FILE = exports.MERGE_INFO_DIR = exports.hasDisable = exports.WEBPIECES_DISABLE = exports.AbstractRule = exports.ChangedFilesOptions = exports.DiffRange = exports.DiffScope = exports.isNewOrModified = exports.hasChangesInRange = exports.findNewMethodSignaturesInDiff = exports.getChangedLineNumbers = exports.getFileDiff = exports.getChangedFiles = exports.resolveBase = void 0;
7
+ exports.VERDICT_ORANGE = exports.VERDICT_YELLOW = exports.VERDICT_GREEN = exports.CK_BAD_FORMAT = exports.CK_MISSING = exports.CK_FAIL = exports.CK_ORANGE = exports.CK_ORANGE_FIXED = exports.CK_OVERRIDDEN = exports.CK_WARN = exports.CK_PASS = exports.checklistOverrideService = exports.ChecklistOverrideService = exports.ChecklistOverride = exports.ChecklistVerdict = exports.ChecklistResult = exports.PrContext = exports.AddressedIssue = exports.PrSummary = exports.DEFAULT_RETENTION_DAYS = exports.ProvenanceWriteRequest = exports.OfferedContext = exports.ReviewerPaths = exports.ReviewerTranscript = exports.ReviewProvenance = exports.ReviewProvenanceService = exports.PROVENANCE_SKIPPED = exports.PROVENANCE_MISSING = exports.PROVENANCE_OK = exports.ProvenanceResult = exports.TranscriptScan = exports.ExpectedReviewer = exports.ReviewerContext = exports.ReviewerEvidence = exports.SubagentProvenanceService = exports.verifyGateToken = exports.extractGateToken = exports.gateTokenMarker = exports.computeGateToken = exports.GateTokenService = exports.ALL_DIFF_ONE_READ_LINES = exports.READ_TRUNCATION_LINES = exports.ContextEntry = exports.BriefedFile = exports.ReviewerBriefing = exports.ReviewerInstructionsService = exports.ChecklistInstructionsService = exports.ChecklistValidator = exports.formatFileList = exports.normalizeChecklistDoc = void 0;
8
+ exports.PathMatchCandidate = exports.FirstPathMatchResult = exports.FirstPathMatch = exports.RuntimeContributionGroup = exports.NodeRuleRuntimeModuleLoader = exports.RuleRuntimeModuleLoader = exports.RuleRuntimeModules = exports.UntrackedPolicyError = exports.RepositoryLayoutRepair = exports.RunCommandCure = exports.EditFileCure = exports.ConfigRepairError = exports.ConfigRepairCure = exports.ConfigRepairBootstrap = exports.ConfigRepairAccess = exports.RulePackSync = exports.PackPolicyFiles = exports.PackPolicyFilesResult = exports.SelectedPolicyPack = exports.PackPolicyDeclaration = exports.LegacyUpgradeResult = exports.LegacyConfigDocument = exports.prepareLegacyUpgrade = exports.RulePackModuleLoader = exports.RulePackDiscovery = exports.NodeRulePackModuleLoader = exports.RulePackRegistry = exports.TMP_SCRATCH_PREFIX = exports.TMP_SCRATCH_RETENTION_DAYS = exports.TmpScratchSweeper = exports.SCRATCH_DIR_NAME = exports.RepoScratchDirs = exports.staleBinSweeper = exports.StaleBinSweeper = exports.StaleBinRemoval = exports.DEFAULT_MERGE_COMPLETE_COMMAND = exports.DEFAULT_UPSERT_PR_COMMAND = exports.buildCommandsConfig = exports.CommandsConfig = exports.summaryJsonSchemaHint = exports.summaryJsonPath = exports.prDirFor = exports.ReviewJsonService = exports.ChecklistReviewContext = exports.RequiredChecklist = exports.VERDICT_STATUSES = exports.VERDICT_RED = void 0;
9
9
  const tslib_1 = require("tslib");
10
10
  var types_1 = require("./types");
11
11
  Object.defineProperty(exports, "ResolvedConfig", { enumerable: true, get: function () { return types_1.ResolvedConfig; } });
@@ -34,6 +34,7 @@ var run_main_1 = require("./run-main");
34
34
  Object.defineProperty(exports, "runMain", { enumerable: true, get: function () { return run_main_1.runMain; } });
35
35
  var load_config_1 = require("./load-config");
36
36
  Object.defineProperty(exports, "loadAndValidate", { enumerable: true, get: function () { return load_config_1.loadAndValidate; } });
37
+ Object.defineProperty(exports, "assertPolicyTracked", { enumerable: true, get: function () { return load_config_1.assertPolicyTracked; } });
37
38
  Object.defineProperty(exports, "LoadedConfig", { enumerable: true, get: function () { return load_config_1.LoadedConfig; } });
38
39
  Object.defineProperty(exports, "ConfigLoader", { enumerable: true, get: function () { return load_config_1.ConfigLoader; } });
39
40
  // The validation-failure banner: ONE cure (edit the file), plus the marker phrases the validator
package/src/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/index.ts"],"names":[],"mappings":";;;;;;;;;AAAA,iCAA0E;AAAjE,uGAAA,cAAc,OAAA;AAAE,2GAAA,kBAAkB,OAAA;AAE3C,qDAA+F;AAAtF,gHAAA,aAAa,OAAA;AAAE,sHAAA,mBAAmB,OAAA;AAAE,yHAAA,sBAAsB,OAAA;AACnE,uGAAuG;AACvG,sFAAsF;AACtF,2CAAwD;AAA/C,oGAAA,MAAM,OAAA;AAAE,8GAAA,gBAAgB,OAAA;AACjC,2DAAqF;AAA5E,qHAAA,eAAe,OAAA;AAAE,kIAAA,4BAA4B,OAAA;AACtD,mDAAgD;AAAvC,8GAAA,YAAY,OAAA;AACrB,uCAAiF;AAAxE,oGAAA,QAAQ,OAAA;AAAE,mGAAA,OAAO,OAAA;AAAE,qGAAA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AAEvB,yDAK6B;AAJzB,0HAAA,qBAAqB,OAAA;AACrB,uHAAA,kBAAkB,OAAA;AAClB,0HAAA,qBAAqB,OAAA;AACrB,oHAAA,eAAe,OAAA;AAEnB,mDAAgD;AAAvC,8GAAA,YAAY,OAAA;AACrB,+DAA4D;AAAnD,0HAAA,kBAAkB,OAAA;AAC3B,6DAA8D;AAArD,4HAAA,qBAAqB,OAAA;AAC9B,6DAM+B;AAL3B,uHAAA,gBAAgB,OAAA;AAChB,wHAAA,iBAAiB,OAAA;AACjB,mHAAA,YAAY,OAAA;AACZ,qHAAA,cAAc,OAAA;AACd,6HAAA,sBAAsB,OAAA;AAE1B,qDAAyD;AAAhD,uHAAA,oBAAoB,OAAA;AAC7B,+DAKgC;AAJ5B,0HAAA,kBAAkB,OAAA;AAClB,+HAAA,uBAAuB,OAAA;AACvB,mIAAA,2BAA2B,OAAA;AAC3B,gIAAA,wBAAwB,OAAA;AAG5B,uDAA8F;AAArF,kHAAA,cAAc,OAAA;AAAE,wHAAA,oBAAoB,OAAA;AAAE,sHAAA,kBAAkB,OAAA","sourcesContent":["export { ResolvedConfig, ResolvedRuleConfig, RuleOptions } from './types';\n\nexport { RuleFailError, renderRuleFailForAi, renderRuleFailForHuman } from './rule-fail-error';\n// THE one representation of a cure, shared by RuleFailError (build-time) and FixHint (edit-time), plus\n// the one renderer that owns the \"Fix Option N:\" numbering and the \"(preferred)\" tag.\nexport { Option, formatFixOptions } from './fix-option';\nexport { TurnOffRuleCure, LAST_RESORT_TURN_OFF_SECONDS } from './turn-off-rule-cure';\nexport { CliExitError } from './cli-exit-error';\nexport { CliUsage, CliFlag, CliArgSet, CliArgsCheck, CliArgs } from './cli-args';\nexport { runMain } from './run-main';\n\nexport { loadAndValidate, LoadedConfig, ConfigLoader } from './load-config';\n// The validation-failure banner: ONE cure (edit the file), plus the marker phrases the validator\n// messages embed rather than re-type.\nexport {\n formatConfigErrorsBanner,\n CONFIG_POLICY_DOC,\n RETIRED_KEY_MARKER,\n RETIRED_TOP_LEVEL_MARKER,\n} from './config-error-banner';\nexport {\n findConfigFile,\n CONFIG_FILENAME,\n ConfigFile,\n ConfigParseAttempt,\n CONFIG_PARSE_ATTEMPTS,\n CONFIG_PARSE_RETRY_MILLIS,\n} from './config-file';\n// The PARSED-BUT-UNVALIDATED config shape. Exported for readers that walk the file generically rather\n// than through the typed config (the pr-gate active-hatch dashboard section reads every rule's hatches).\nexport { RawConfigFile } from './config-file';\nexport { RepoRootFinder, INSTRUCT_AI_DIR, INSTRUCT_AI_LEAF } from './repo-root';\n// The scoped `.webpieces` resolver. EVERY reader/writer of `.webpieces/...` goes through one of its two\n// named methods so the call site declares whether the state is repo-wide or worktree-private.\n\n// There is NO machine-global state root. `MachineStateHome`/`StateHome`/`WEBPIECES_STATE_HOME` and the\n// `PrBodyStore` that used them are DELETED: the one artifact that needed a scope above the clone was the\n// gated squash body, and GitHub holds it now (it IS the PR description). Every `.webpieces` path a\n// webpieces tool writes is `{repo}/.webpieces`, resolved through `DotWebpieces` above. See\n// `decisions/0005-the-pr-description-is-the-merge-body.md`.\nexport { AgedTreeSweeper, SweepCount, RETENTION_DAYS } from './aged-tree-sweep';\nexport {\n ClaudeEnv,\n claudeEnv,\n CLAUDE_PROJECT_DIR_ENV,\n CLAUDE_PROJECT_DIR_UNSET,\n} from './claude-env';\n\n// The ONE formatter for a remedy that must run in a named directory: `cd '<root>' && <command>`.\n// Single-quoted so a repo path containing a space is still runnable (and still un-smuggleable).\nexport { atRoot } from './at-root';\nexport { RulesConfigDesign } from './rules-config-design';\nexport { DocumentDesign, isDocumentDesign, DESIGN_METADATA_KEYS } from './di';\nexport { ExcludePaths, isWebpiecesStateDir } from './exclude-hook-paths';\nexport { isPathExcluded, matchesAnyGlob } from './exclude-paths';\nexport { globMatches } from './glob-matches';\n// Framework-applied path exclusions for a rule run (#1253): the dispatcher enters the scope, DiffScope's\n// file listings honour it, so no rule filters its own files.\nexport { RuleFileScope, RuleFileExclusions } from './rule-file-scope';\n// The machine-generated trees a line-count rule never fires on. A FLOOR, not a default value:\n// `max-file-lines.excludePaths` adds to it, so configuring your own tree cannot lose it.\nexport { GENERATED_CODE_PATHS } from './generated-code-paths';\n// THE one `no-custom-css` path exemption. Both engines that enforce the rule (the edit-time hook and the\n// CI validator) consult this class, so `allowGlobs` cannot be honoured by one half and ignored by the other.\nexport { NoCustomCssScope, PathScopeConfig } from './no-custom-css-scope';\nexport {\n loadTemplate,\n writeTemplateIfMissing,\n writeTemplate,\n TemplateWriter,\n} from './load-template';\n// The instruct-ai docs are delivered as a SET: writing one writes the transitive closure of the docs it\n// links to, so a doc and everything it points at always land together. See instruct-ai-docs.ts.\nexport {\n GIT_WORKFLOW_DOC,\n GitWorkflowDoc,\n InstructAiDoc,\n InstructAiDocSet,\n MergeProcessDoc,\n} from './instruct-ai-docs';\nexport {\n MERGE_PROCESS_DOC,\n MergeProcessText,\n MergeRun,\n ReferenceMergeRun,\n} from './merge-process-doc';\nexport { BUILD_LOG_DOC } from './build-log-doc';\nexport {\n validateWebpiecesConfig,\n validatePrGateSection,\n validateChecklistsSection,\n validateExcludePaths,\n validateMatchRulesSection,\n allRuleNames,\n recommendedSeedMode,\n recommendedSeedModeFor,\n seedEntryForRule,\n} from './validate-config';\nexport { validateCommandsSection } from './commands-section-validators';\nexport {\n unknownKeyErrors,\n validateTopLevelKeys,\n} from './config-key-rules';\nexport { CONFIG_DOCUMENTATION_KEY, CONFIG_DOCUMENTATION_PATH } from './config-documentation';\n// The retired-key table + the no-back-compat policy it enforces. Exported so the installer can migrate\n// what the errors instruct, and so consumers can enumerate retirements.\nexport {\n RETIRED_CONFIG_KEYS,\n RETIRED_SCOPE_KEY,\n RETIRED_SCOPE_RULE,\n isRetiredKey,\n retiredEntry,\n retiredKeyError,\n retiredKeyErrorsIn,\n retiredRuleFor,\n} from './retired-config-keys';\n// The MECHANICAL cure the unknown-rule error and the banner both name: strip every key no validator has a\n// schema for, so cleanliness is one command rather than a judgement call made while every Bash call is\n// blocked. `PRUNE_UNKNOWN_COMMAND` (constants.ts) is the single spelling of that command.\nexport { ConfigPruner, PruneResult, PrunedKey } from './config-pruner';\nexport { validateChecklistDocs } from './checklist-docs-validator';\n// The OPTIONAL machine-local `~/.webpieces/config.json`: absent (the normal state for every consumer) means\n// each key's declared default, silently; present means STRICT about what it understands and FORWARD-COMPATIBLE\n// about what it does not. A retired key (its own retirement table), a known key of the wrong TYPE and an\n// unparseable document all REJECT; a key this release simply does not recognise is IGNORED with a warning,\n// because the file is machine-global and the repos reading it pin different releases — rejecting a newer\n// release's key would hard-block every repo on the machine that is not yet on it. See home-config.ts.\n// `isHomeConfigPath` is what grants the file its unconditional Write/Edit PASS in the hook guards, which is\n// what keeps a rejection repairable. Every `experimental.*` key is an OPT-IN that defaults OFF, including\n// `whole-repo-build-guard`: ON requires an explicit `true`, and there is no per-key default to export.\nexport {\n HomeConfig,\n HomeConfigService,\n RetiredHomeConfigKey,\n RETIRED_HOME_CONFIG_KEYS,\n HOME_CONFIG_DIR,\n HOME_CONFIG_FILE,\n HOME_EXPERIMENTAL_SECTION,\n HOME_KEY_ORPHAN_DIR_SWEEP,\n HOME_KEY_WHOLE_REPO_BUILD_GUARD,\n HOME_KEY_MAX_CONCURRENT_BUILDS,\n HOME_KEY_TURN_OFF_ALL_REVIEWERS,\n DEFAULT_MAX_CONCURRENT_BUILDS,\n HOME_KEY_DOC,\n HOME_KEY_AI_DOC,\n DOCUMENTATION_KEYS,\n} from './home-config';\n// The MACHINE-WIDE build ledger, `~/.webpieces/builds.log`. THE one carve-out from\n// `no-machine-global-state.spec.ts`'s rule that webpieces writes only under `{repo}/.webpieces` — the\n// argument is in `decisions/0006-the-build-ledger-is-machine-global.md`, and the short form is that \"how\n// many builds are burning this box's CPU\" is a fact about the MACHINE, is not a cache of anything a\n// remote owns, and cannot be answered from a per-repo file because every linked worktree has its own\n// `.webpieces/` and would be blind to the sibling it is contending with. See builds-log.ts.\nexport {\n BuildsLog,\n BuildTicket,\n BuildTermination,\n RunningBuild,\n BUILDS_LOG_FILE,\n BUILDS_LOCK_FILE,\n BUILD_START,\n BUILD_DONE_SUCCESS,\n BUILD_DONE_FAIL,\n MAX_BUILDS_LOG_BYTES,\n BUILDS_LOG_GENERATIONS,\n MAX_ROW_BYTES,\n} from './builds-log';\n// The orphan-directory sweep: the corpse an `nx g move` leaves on every clone, which git cannot remove\n// because an ignored dist/ or node_modules/ outlives every tracked file under it. See orphan-dir-scan.ts\n// for why the predicate is git's own `clean -Xdn` answer rather than a hand-rolled ignore walk.\nexport { OrphanDirScanner, OrphanCandidate } from './orphan-dir-scan';\nexport {\n OrphanDirArchiver,\n ArchivedOrphan,\n FailedOrphan,\n OrphanSweepResult,\n OrphanSweepManifest,\n TRASH_STATE_DIR,\n TRASH_MANIFEST_FILE,\n TRASH_RETENTION_DAYS,\n} from './orphan-dir-archive';\nexport { OrphanDirSweeper, OrphanSweepReport } from './orphan-dir-sweep';\nexport {\n MatchRuleConfig,\n MatchRuleViolation,\n findMatchRuleViolations,\n isMatchRuleAllowedPath,\n compileMatchRulePatterns,\n renderMatchRuleMessage,\n DEFAULT_MATCH_RULES,\n} from './match-rules-config';\nexport type { ConfigSection } from './sections';\nexport { schemaFieldNames } from './rule-schemas';\nexport { isHookGuard, sectionForRule } from './sections';\nexport { shouldSkipRule, HOTFIX_BUILD_COMMAND, HOTFIX_AUDIT_BANNER } from './skip-rule';\nexport { SkipRuleResult } from './skip-rule';\nexport {\n detectBase,\n resolveBase,\n getChangedFiles,\n getFileDiff,\n getChangedLineNumbers,\n findNewMethodSignaturesInDiff,\n hasChangesInRange,\n isNewOrModified,\n DiffScope,\n DiffRange,\n ChangedFilesOptions,\n} from './diff-scope';\nexport { AbstractRule } from './abstract-rule';\nexport {\n WEBPIECES_DISABLE,\n hasDisable,\n MERGE_INFO_DIR,\n MERGE_IN_PROGRESS_FILE,\n MERGE_EXPLANATION_FILE,\n PUSH_DEV_STATE_FILE,\n PRUNE_UNKNOWN_COMMAND,\n UPGRADE_SHIM_COMMAND,\n} from './constants';\nexport { WebpiecesRulesConfig } from './WebpiecesRulesConfig';\nexport {\n SyncFlowGuidance,\n WP_START_UPDATE,\n WP_FINISH_UPDATE,\n WP_START_UPSERT_PR,\n WP_FINISH_UPSERT_PR,\n WP_PUSH_DEV,\n WP_FINISH_PUSH_DEV,\n} from './sync-flow-guidance';\n\n// Mode unions + their value arrays — the single source of truth shared with code-rules.\n\n// The `no-state-paths-in-templates` config, in its own module for the same reason no-client-creation is:\n// rule-configs.ts is at its file-size cap and a rule that carries real defaults belongs beside them.\n\nexport {\n GateDefinition,\n PrGateConfig,\n DEFAULT_BUILD_COMMAND,\n LandPrConfig,\n DevDeployConfig,\n DEFAULT_DEV_BRANCH_NAMESPACE,\n DEFAULT_DEV_BRANCH,\n ReviewContextEntry,\n defaultGates,\n defaultPrGateConfig,\n defaultLandPrConfig,\n defaultDevDeployConfig,\n buildPrGateConfig,\n buildLandPrConfig,\n buildDevDeployConfig,\n MERGE_MODE_AUTO,\n MERGE_MODE_NONE,\n MERGE_MODES,\n} from './pr-gate-config';\nexport {\n ChecklistDefinition,\n ReviewerAgentPolicy,\n REVIEWER_AGENTS_PLACEHOLDER,\n DEFAULT_REVIEWER_AGENT_NAME,\n toChecklist,\n normalizeChecklistDoc,\n formatFileList,\n} from './checklist-config';\nexport type { RawChecklistItem } from './checklist-config';\nexport { ChecklistValidator } from './checklist-validator';\nexport { ChecklistInstructionsService } from './checklist-instructions';\nexport {\n ReviewerInstructionsService,\n ReviewerBriefing,\n BriefedFile,\n ContextEntry,\n READ_TRUNCATION_LINES,\n ALL_DIFF_ONE_READ_LINES,\n} from './reviewer-instructions';\nexport {\n GateTokenService,\n computeGateToken,\n gateTokenMarker,\n extractGateToken,\n verifyGateToken,\n} from './gate-token';\nexport {\n SubagentProvenanceService,\n ReviewerEvidence,\n ReviewerContext,\n ExpectedReviewer,\n TranscriptScan,\n ProvenanceResult,\n PROVENANCE_OK,\n PROVENANCE_MISSING,\n PROVENANCE_SKIPPED,\n} from './subagent-provenance';\n\nexport {\n ReviewProvenanceService,\n ReviewProvenance,\n ReviewerTranscript,\n ReviewerPaths,\n OfferedContext,\n ProvenanceWriteRequest,\n DEFAULT_RETENTION_DAYS,\n} from './review-provenance';\nexport {\n PrSummary,\n AddressedIssue,\n PrContext,\n ChecklistResult,\n ChecklistVerdict,\n ChecklistOverride,\n ChecklistOverrideService,\n checklistOverrideService,\n CK_PASS,\n CK_WARN,\n CK_OVERRIDDEN,\n CK_ORANGE_FIXED,\n CK_ORANGE,\n CK_FAIL,\n CK_MISSING,\n CK_BAD_FORMAT,\n VERDICT_GREEN,\n VERDICT_YELLOW,\n VERDICT_ORANGE,\n VERDICT_RED,\n VERDICT_STATUSES,\n RequiredChecklist,\n ChecklistReviewContext,\n ReviewJsonService,\n prDirFor,\n summaryJsonPath,\n summaryJsonSchemaHint,\n} from './review-json';\n\nexport {\n CommandsConfig,\n buildCommandsConfig,\n DEFAULT_UPSERT_PR_COMMAND,\n DEFAULT_MERGE_COMPLETE_COMMAND,\n} from './commands-config';\nexport { StaleBinRemoval, StaleBinSweeper, staleBinSweeper } from './stale-bin-sweep';\nexport { RepoScratchDirs, SCRATCH_DIR_NAME } from './repo-scratch-dirs';\nexport {\n TmpScratchSweeper,\n TMP_SCRATCH_RETENTION_DAYS,\n TMP_SCRATCH_PREFIX,\n} from './tmp-scratch-sweep';\n\nexport * from './hook-fault-codes';\nexport * from './hook-config-diagnostics';\nexport {\n RulePackRegistry,\n NodeRulePackModuleLoader,\n RulePackDiscovery,\n RulePackModuleLoader,\n} from './rule-pack-registry';\n\nexport {\n prepareLegacyUpgrade,\n LegacyConfigDocument,\n LegacyUpgradeResult,\n} from './legacy-config-upgrade';\nexport {\n PackPolicyDeclaration,\n SelectedPolicyPack,\n PackPolicyFilesResult,\n PackPolicyFiles,\n} from './pack-policy-files';\nexport { RulePackSync } from './rule-pack-sync';\nexport { ConfigRepairAccess } from './config-repair-access';\nexport { ConfigRepairBootstrap } from './config-repair-probe';\nexport {\n ConfigRepairCure,\n ConfigRepairError,\n EditFileCure,\n RunCommandCure,\n RepositoryLayoutRepair,\n} from './config-repair-error';\nexport { UntrackedPolicyError } from './policy-tracking';\nexport {\n RuleRuntimeModules,\n RuleRuntimeModuleLoader,\n NodeRuleRuntimeModuleLoader,\n RuntimeContributionGroup,\n} from './rule-runtime-modules';\n\nexport { FirstPathMatch, FirstPathMatchResult, PathMatchCandidate } from './first-path-match';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/index.ts"],"names":[],"mappings":";;;;;;;;;AAAA,iCAA0E;AAAjE,uGAAA,cAAc,OAAA;AAAE,2GAAA,kBAAkB,OAAA;AAE3C,qDAA+F;AAAtF,gHAAA,aAAa,OAAA;AAAE,sHAAA,mBAAmB,OAAA;AAAE,yHAAA,sBAAsB,OAAA;AACnE,uGAAuG;AACvG,sFAAsF;AACtF,2CAAwD;AAA/C,oGAAA,MAAM,OAAA;AAAE,8GAAA,gBAAgB,OAAA;AACjC,2DAAqF;AAA5E,qHAAA,eAAe,OAAA;AAAE,kIAAA,4BAA4B,OAAA;AACtD,mDAAgD;AAAvC,8GAAA,YAAY,OAAA;AACrB,uCAAiF;AAAxE,oGAAA,QAAQ,OAAA;AAAE,mGAAA,OAAO,OAAA;AAAE,qGAAA,SAAS,OAAA;AAAE,wGAAA,YAAY,OAAA;AAAE,mGAAA,OAAO,OAAA;AAC5D,uCAAqC;AAA5B,mGAAA,OAAO,OAAA;AAEhB,6CAAiG;AAAxF,8GAAA,eAAe,OAAA;AAAE,kHAAA,mBAAmB,OAAA;AAAE,2GAAA,YAAY,OAAA;AAAE,2GAAA,YAAY,OAAA;AACzE,iGAAiG;AACjG,sCAAsC;AACtC,6DAK+B;AAJ3B,+HAAA,wBAAwB,OAAA;AACxB,wHAAA,iBAAiB,OAAA;AACjB,yHAAA,kBAAkB,OAAA;AAClB,+HAAA,wBAAwB,OAAA;AAE5B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AA,cAAc,OAAA;AACd,6HAAA,sBAAsB,OAAA;AAE1B,qDAAyD;AAAhD,uHAAA,oBAAoB,OAAA;AAC7B,+DAKgC;AAJ5B,0HAAA,kBAAkB,OAAA;AAClB,+HAAA,uBAAuB,OAAA;AACvB,mIAAA,2BAA2B,OAAA;AAC3B,gIAAA,wBAAwB,OAAA;AAG5B,uDAA8F;AAArF,kHAAA,cAAc,OAAA;AAAE,wHAAA,oBAAoB,OAAA;AAAE,sHAAA,kBAAkB,OAAA","sourcesContent":["export { ResolvedConfig, ResolvedRuleConfig, RuleOptions } from './types';\n\nexport { RuleFailError, renderRuleFailForAi, renderRuleFailForHuman } from './rule-fail-error';\n// THE one representation of a cure, shared by RuleFailError (build-time) and FixHint (edit-time), plus\n// the one renderer that owns the \"Fix Option N:\" numbering and the \"(preferred)\" tag.\nexport { Option, formatFixOptions } from './fix-option';\nexport { TurnOffRuleCure, LAST_RESORT_TURN_OFF_SECONDS } from './turn-off-rule-cure';\nexport { CliExitError } from './cli-exit-error';\nexport { CliUsage, CliFlag, CliArgSet, CliArgsCheck, CliArgs } from './cli-args';\nexport { runMain } from './run-main';\n\nexport { loadAndValidate, assertPolicyTracked, LoadedConfig, ConfigLoader } from './load-config';\n// The validation-failure banner: ONE cure (edit the file), plus the marker phrases the validator\n// messages embed rather than re-type.\nexport {\n formatConfigErrorsBanner,\n CONFIG_POLICY_DOC,\n RETIRED_KEY_MARKER,\n RETIRED_TOP_LEVEL_MARKER,\n} from './config-error-banner';\nexport {\n findConfigFile,\n CONFIG_FILENAME,\n ConfigFile,\n ConfigParseAttempt,\n CONFIG_PARSE_ATTEMPTS,\n CONFIG_PARSE_RETRY_MILLIS,\n} from './config-file';\n// The PARSED-BUT-UNVALIDATED config shape. Exported for readers that walk the file generically rather\n// than through the typed config (the pr-gate active-hatch dashboard section reads every rule's hatches).\nexport { RawConfigFile } from './config-file';\nexport { RepoRootFinder, INSTRUCT_AI_DIR, INSTRUCT_AI_LEAF } from './repo-root';\n// The scoped `.webpieces` resolver. EVERY reader/writer of `.webpieces/...` goes through one of its two\n// named methods so the call site declares whether the state is repo-wide or worktree-private.\n\n// There is NO machine-global state root. `MachineStateHome`/`StateHome`/`WEBPIECES_STATE_HOME` and the\n// `PrBodyStore` that used them are DELETED: the one artifact that needed a scope above the clone was the\n// gated squash body, and GitHub holds it now (it IS the PR description). Every `.webpieces` path a\n// webpieces tool writes is `{repo}/.webpieces`, resolved through `DotWebpieces` above. See\n// `decisions/0005-the-pr-description-is-the-merge-body.md`.\nexport { AgedTreeSweeper, SweepCount, RETENTION_DAYS } from './aged-tree-sweep';\nexport {\n ClaudeEnv,\n claudeEnv,\n CLAUDE_PROJECT_DIR_ENV,\n CLAUDE_PROJECT_DIR_UNSET,\n} from './claude-env';\n\n// The ONE formatter for a remedy that must run in a named directory: `cd '<root>' && <command>`.\n// Single-quoted so a repo path containing a space is still runnable (and still un-smuggleable).\nexport { atRoot } from './at-root';\nexport { RulesConfigDesign } from './rules-config-design';\nexport { DocumentDesign, isDocumentDesign, DESIGN_METADATA_KEYS } from './di';\nexport { ExcludePaths, isWebpiecesStateDir } from './exclude-hook-paths';\nexport { isPathExcluded, matchesAnyGlob } from './exclude-paths';\nexport { globMatches } from './glob-matches';\n// Framework-applied path exclusions for a rule run (#1253): the dispatcher enters the scope, DiffScope's\n// file listings honour it, so no rule filters its own files.\nexport { RuleFileScope, RuleFileExclusions } from './rule-file-scope';\n// The machine-generated trees a line-count rule never fires on. A FLOOR, not a default value:\n// `max-file-lines.excludePaths` adds to it, so configuring your own tree cannot lose it.\nexport { GENERATED_CODE_PATHS } from './generated-code-paths';\n// THE one `no-custom-css` path exemption. Both engines that enforce the rule (the edit-time hook and the\n// CI validator) consult this class, so `allowGlobs` cannot be honoured by one half and ignored by the other.\nexport { NoCustomCssScope, PathScopeConfig } from './no-custom-css-scope';\nexport {\n loadTemplate,\n writeTemplateIfMissing,\n writeTemplate,\n TemplateWriter,\n} from './load-template';\n// The instruct-ai docs are delivered as a SET: writing one writes the transitive closure of the docs it\n// links to, so a doc and everything it points at always land together. See instruct-ai-docs.ts.\nexport {\n GIT_WORKFLOW_DOC,\n GitWorkflowDoc,\n InstructAiDoc,\n InstructAiDocSet,\n MergeProcessDoc,\n} from './instruct-ai-docs';\nexport {\n MERGE_PROCESS_DOC,\n MergeProcessText,\n MergeRun,\n ReferenceMergeRun,\n} from './merge-process-doc';\nexport { BUILD_LOG_DOC } from './build-log-doc';\nexport {\n validateWebpiecesConfig,\n validatePrGateSection,\n validateChecklistsSection,\n validateExcludePaths,\n validateMatchRulesSection,\n allRuleNames,\n recommendedSeedMode,\n recommendedSeedModeFor,\n seedEntryForRule,\n} from './validate-config';\nexport { validateCommandsSection } from './commands-section-validators';\nexport {\n unknownKeyErrors,\n validateTopLevelKeys,\n} from './config-key-rules';\nexport { CONFIG_DOCUMENTATION_KEY, CONFIG_DOCUMENTATION_PATH } from './config-documentation';\n// The retired-key table + the no-back-compat policy it enforces. Exported so the installer can migrate\n// what the errors instruct, and so consumers can enumerate retirements.\nexport {\n RETIRED_CONFIG_KEYS,\n RETIRED_SCOPE_KEY,\n RETIRED_SCOPE_RULE,\n isRetiredKey,\n retiredEntry,\n retiredKeyError,\n retiredKeyErrorsIn,\n retiredRuleFor,\n} from './retired-config-keys';\n// The MECHANICAL cure the unknown-rule error and the banner both name: strip every key no validator has a\n// schema for, so cleanliness is one command rather than a judgement call made while every Bash call is\n// blocked. `PRUNE_UNKNOWN_COMMAND` (constants.ts) is the single spelling of that command.\nexport { ConfigPruner, PruneResult, PrunedKey } from './config-pruner';\nexport { validateChecklistDocs } from './checklist-docs-validator';\n// The OPTIONAL machine-local `~/.webpieces/config.json`: absent (the normal state for every consumer) means\n// each key's declared default, silently; present means STRICT about what it understands and FORWARD-COMPATIBLE\n// about what it does not. A retired key (its own retirement table), a known key of the wrong TYPE and an\n// unparseable document all REJECT; a key this release simply does not recognise is IGNORED with a warning,\n// because the file is machine-global and the repos reading it pin different releases — rejecting a newer\n// release's key would hard-block every repo on the machine that is not yet on it. See home-config.ts.\n// `isHomeConfigPath` is what grants the file its unconditional Write/Edit PASS in the hook guards, which is\n// what keeps a rejection repairable. Every `experimental.*` key is an OPT-IN that defaults OFF, including\n// `whole-repo-build-guard`: ON requires an explicit `true`, and there is no per-key default to export.\nexport {\n HomeConfig,\n HomeConfigService,\n RetiredHomeConfigKey,\n RETIRED_HOME_CONFIG_KEYS,\n HOME_CONFIG_DIR,\n HOME_CONFIG_FILE,\n HOME_EXPERIMENTAL_SECTION,\n HOME_KEY_ORPHAN_DIR_SWEEP,\n HOME_KEY_WHOLE_REPO_BUILD_GUARD,\n HOME_KEY_MAX_CONCURRENT_BUILDS,\n HOME_KEY_TURN_OFF_ALL_REVIEWERS,\n DEFAULT_MAX_CONCURRENT_BUILDS,\n HOME_KEY_DOC,\n HOME_KEY_AI_DOC,\n DOCUMENTATION_KEYS,\n} from './home-config';\n// The MACHINE-WIDE build ledger, `~/.webpieces/builds.log`. THE one carve-out from\n// `no-machine-global-state.spec.ts`'s rule that webpieces writes only under `{repo}/.webpieces` — the\n// argument is in `decisions/0006-the-build-ledger-is-machine-global.md`, and the short form is that \"how\n// many builds are burning this box's CPU\" is a fact about the MACHINE, is not a cache of anything a\n// remote owns, and cannot be answered from a per-repo file because every linked worktree has its own\n// `.webpieces/` and would be blind to the sibling it is contending with. See builds-log.ts.\nexport {\n BuildsLog,\n BuildTicket,\n BuildTermination,\n RunningBuild,\n BUILDS_LOG_FILE,\n BUILDS_LOCK_FILE,\n BUILD_START,\n BUILD_DONE_SUCCESS,\n BUILD_DONE_FAIL,\n MAX_BUILDS_LOG_BYTES,\n BUILDS_LOG_GENERATIONS,\n MAX_ROW_BYTES,\n} from './builds-log';\n// The orphan-directory sweep: the corpse an `nx g move` leaves on every clone, which git cannot remove\n// because an ignored dist/ or node_modules/ outlives every tracked file under it. See orphan-dir-scan.ts\n// for why the predicate is git's own `clean -Xdn` answer rather than a hand-rolled ignore walk.\nexport { OrphanDirScanner, OrphanCandidate } from './orphan-dir-scan';\nexport {\n OrphanDirArchiver,\n ArchivedOrphan,\n FailedOrphan,\n OrphanSweepResult,\n OrphanSweepManifest,\n TRASH_STATE_DIR,\n TRASH_MANIFEST_FILE,\n TRASH_RETENTION_DAYS,\n} from './orphan-dir-archive';\nexport { OrphanDirSweeper, OrphanSweepReport } from './orphan-dir-sweep';\nexport {\n MatchRuleConfig,\n MatchRuleViolation,\n findMatchRuleViolations,\n isMatchRuleAllowedPath,\n compileMatchRulePatterns,\n renderMatchRuleMessage,\n DEFAULT_MATCH_RULES,\n} from './match-rules-config';\nexport type { ConfigSection } from './sections';\nexport { schemaFieldNames } from './rule-schemas';\nexport { isHookGuard, sectionForRule } from './sections';\nexport { shouldSkipRule, HOTFIX_BUILD_COMMAND, HOTFIX_AUDIT_BANNER } from './skip-rule';\nexport { SkipRuleResult } from './skip-rule';\nexport {\n detectBase,\n resolveBase,\n getChangedFiles,\n getFileDiff,\n getChangedLineNumbers,\n findNewMethodSignaturesInDiff,\n hasChangesInRange,\n isNewOrModified,\n DiffScope,\n DiffRange,\n ChangedFilesOptions,\n} from './diff-scope';\nexport { AbstractRule } from './abstract-rule';\nexport {\n WEBPIECES_DISABLE,\n hasDisable,\n MERGE_INFO_DIR,\n MERGE_IN_PROGRESS_FILE,\n MERGE_EXPLANATION_FILE,\n PUSH_DEV_STATE_FILE,\n PRUNE_UNKNOWN_COMMAND,\n UPGRADE_SHIM_COMMAND,\n} from './constants';\nexport { WebpiecesRulesConfig } from './WebpiecesRulesConfig';\nexport {\n SyncFlowGuidance,\n WP_START_UPDATE,\n WP_FINISH_UPDATE,\n WP_START_UPSERT_PR,\n WP_FINISH_UPSERT_PR,\n WP_PUSH_DEV,\n WP_FINISH_PUSH_DEV,\n} from './sync-flow-guidance';\n\n// Mode unions + their value arrays — the single source of truth shared with code-rules.\n\n// The `no-state-paths-in-templates` config, in its own module for the same reason no-client-creation is:\n// rule-configs.ts is at its file-size cap and a rule that carries real defaults belongs beside them.\n\nexport {\n GateDefinition,\n PrGateConfig,\n DEFAULT_BUILD_COMMAND,\n LandPrConfig,\n DevDeployConfig,\n DEFAULT_DEV_BRANCH_NAMESPACE,\n DEFAULT_DEV_BRANCH,\n ReviewContextEntry,\n defaultGates,\n defaultPrGateConfig,\n defaultLandPrConfig,\n defaultDevDeployConfig,\n buildPrGateConfig,\n buildLandPrConfig,\n buildDevDeployConfig,\n MERGE_MODE_AUTO,\n MERGE_MODE_NONE,\n MERGE_MODES,\n} from './pr-gate-config';\nexport {\n ChecklistDefinition,\n ReviewerAgentPolicy,\n REVIEWER_AGENTS_PLACEHOLDER,\n DEFAULT_REVIEWER_AGENT_NAME,\n toChecklist,\n normalizeChecklistDoc,\n formatFileList,\n} from './checklist-config';\nexport type { RawChecklistItem } from './checklist-config';\nexport { ChecklistValidator } from './checklist-validator';\nexport { ChecklistInstructionsService } from './checklist-instructions';\nexport {\n ReviewerInstructionsService,\n ReviewerBriefing,\n BriefedFile,\n ContextEntry,\n READ_TRUNCATION_LINES,\n ALL_DIFF_ONE_READ_LINES,\n} from './reviewer-instructions';\nexport {\n GateTokenService,\n computeGateToken,\n gateTokenMarker,\n extractGateToken,\n verifyGateToken,\n} from './gate-token';\nexport {\n SubagentProvenanceService,\n ReviewerEvidence,\n ReviewerContext,\n ExpectedReviewer,\n TranscriptScan,\n ProvenanceResult,\n PROVENANCE_OK,\n PROVENANCE_MISSING,\n PROVENANCE_SKIPPED,\n} from './subagent-provenance';\n\nexport {\n ReviewProvenanceService,\n ReviewProvenance,\n ReviewerTranscript,\n ReviewerPaths,\n OfferedContext,\n ProvenanceWriteRequest,\n DEFAULT_RETENTION_DAYS,\n} from './review-provenance';\nexport {\n PrSummary,\n AddressedIssue,\n PrContext,\n ChecklistResult,\n ChecklistVerdict,\n ChecklistOverride,\n ChecklistOverrideService,\n checklistOverrideService,\n CK_PASS,\n CK_WARN,\n CK_OVERRIDDEN,\n CK_ORANGE_FIXED,\n CK_ORANGE,\n CK_FAIL,\n CK_MISSING,\n CK_BAD_FORMAT,\n VERDICT_GREEN,\n VERDICT_YELLOW,\n VERDICT_ORANGE,\n VERDICT_RED,\n VERDICT_STATUSES,\n RequiredChecklist,\n ChecklistReviewContext,\n ReviewJsonService,\n prDirFor,\n summaryJsonPath,\n summaryJsonSchemaHint,\n} from './review-json';\n\nexport {\n CommandsConfig,\n buildCommandsConfig,\n DEFAULT_UPSERT_PR_COMMAND,\n DEFAULT_MERGE_COMPLETE_COMMAND,\n} from './commands-config';\nexport { StaleBinRemoval, StaleBinSweeper, staleBinSweeper } from './stale-bin-sweep';\nexport { RepoScratchDirs, SCRATCH_DIR_NAME } from './repo-scratch-dirs';\nexport {\n TmpScratchSweeper,\n TMP_SCRATCH_RETENTION_DAYS,\n TMP_SCRATCH_PREFIX,\n} from './tmp-scratch-sweep';\n\nexport * from './hook-fault-codes';\nexport * from './hook-config-diagnostics';\nexport {\n RulePackRegistry,\n NodeRulePackModuleLoader,\n RulePackDiscovery,\n RulePackModuleLoader,\n} from './rule-pack-registry';\n\nexport {\n prepareLegacyUpgrade,\n LegacyConfigDocument,\n LegacyUpgradeResult,\n} from './legacy-config-upgrade';\nexport {\n PackPolicyDeclaration,\n SelectedPolicyPack,\n PackPolicyFilesResult,\n PackPolicyFiles,\n} from './pack-policy-files';\nexport { RulePackSync } from './rule-pack-sync';\nexport { ConfigRepairAccess } from './config-repair-access';\nexport { ConfigRepairBootstrap } from './config-repair-probe';\nexport {\n ConfigRepairCure,\n ConfigRepairError,\n EditFileCure,\n RunCommandCure,\n RepositoryLayoutRepair,\n} from './config-repair-error';\nexport { UntrackedPolicyError } from './policy-tracking';\nexport {\n RuleRuntimeModules,\n RuleRuntimeModuleLoader,\n NodeRuleRuntimeModuleLoader,\n RuntimeContributionGroup,\n} from './rule-runtime-modules';\n\nexport { FirstPathMatch, FirstPathMatchResult, PathMatchCandidate } from './first-path-match';\n"]}
@@ -25,8 +25,20 @@ export declare class ConfigLoader {
25
25
  private readonly files;
26
26
  constructor(configFile: ConfigFile, files: PackPolicyFiles);
27
27
  loadAndValidate(cwd: string): LoadedConfig;
28
+ /**
29
+ * "Policy is shared through the git index": every declared owner file is tracked and not ignored.
30
+ *
31
+ * NOT part of loadAndValidate (#1355). It is a COMMIT-TIME invariant — nothing about it changes
32
+ * between two tool calls — and it costs two `git` processes, so running it on every config load put
33
+ * it on the hottest path there is: every guard-hook invocation. It runs where work is SHARED instead:
34
+ * `wp-ci`, which is the PR gate's build command and CI's. Its refusal (UntrackedPolicyError and the
35
+ * gitignored-policy ConfigRepairError) and their cures are unchanged.
36
+ */
37
+ assertPolicyTracked(cwd: string): void;
28
38
  private loaded;
29
39
  private empty;
30
40
  }
31
41
  /** Public function entry point and injected service use the same implementation. */
32
42
  export declare function loadAndValidate(cwd: string): LoadedConfig;
43
+ /** The gate-time policy-tracking check — see ConfigLoader.assertPolicyTracked. */
44
+ export declare function assertPolicyTracked(cwd: string): void;
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ConfigLoader = exports.LoadedConfig = void 0;
4
4
  exports.loadAndValidate = loadAndValidate;
5
+ exports.assertPolicyTracked = assertPolicyTracked;
5
6
  const tslib_1 = require("tslib");
6
7
  const path = tslib_1.__importStar(require("node:path"));
7
8
  const inversify_1 = require("inversify");
@@ -77,9 +78,24 @@ let ConfigLoader = class ConfigLoader {
77
78
  new config_repair_error_1.RepositoryLayoutRepair().run(() => new tooling_common_1.RepositoryLayout().assertCurrent(root));
78
79
  const declarations = this.files.declarations(raw.rulePacks, root);
79
80
  const policy = this.files.resolve(root, this.files.select(root, declarations));
80
- new policy_tracking_1.PolicyTracking().check(root, declarations);
81
81
  return this.loaded(configPath, raw.commands, raw.excludePaths, raw['match-rules'], policy);
82
82
  }
83
+ /**
84
+ * "Policy is shared through the git index": every declared owner file is tracked and not ignored.
85
+ *
86
+ * NOT part of loadAndValidate (#1355). It is a COMMIT-TIME invariant — nothing about it changes
87
+ * between two tool calls — and it costs two `git` processes, so running it on every config load put
88
+ * it on the hottest path there is: every guard-hook invocation. It runs where work is SHARED instead:
89
+ * `wp-ci`, which is the PR gate's build command and CI's. Its refusal (UntrackedPolicyError and the
90
+ * gitignored-policy ConfigRepairError) and their cures are unchanged.
91
+ */
92
+ assertPolicyTracked(cwd) {
93
+ const configPath = this.configFile.findConfigFile(cwd);
94
+ if (!configPath)
95
+ return;
96
+ const raw = this.configFile.readRawConfig(configPath), root = path.dirname(configPath);
97
+ new policy_tracking_1.PolicyTracking().check(root, this.files.declarations(raw.rulePacks, root));
98
+ }
83
99
  loaded(configPath,
84
100
  // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution
85
101
  commandsRaw, excluded, matches, policy) {
@@ -110,4 +126,9 @@ const configLoaderSvc = new ConfigLoader(new config_file_1.ConfigFile(), new pac
110
126
  function loadAndValidate(cwd) {
111
127
  return configLoaderSvc.loadAndValidate(cwd);
112
128
  }
129
+ /** The gate-time policy-tracking check — see ConfigLoader.assertPolicyTracked. */
130
+ // webpieces-disable no-function-outside-class -- the public function twin of loadAndValidate, for the wp-ci bin
131
+ function assertPolicyTracked(cwd) {
132
+ configLoaderSvc.assertPolicyTracked(cwd);
133
+ }
113
134
  //# sourceMappingURL=load-config.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"load-config.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/load-config.ts"],"names":[],"mappings":";;;AAuIA,0CAEC;;AAzID,wDAAkC;AAClC,yCAA2D;AAC3D,oDAAoD;AACpD,8DAA6D;AAC7D,uDAAwE;AACxE,+CAA2C;AAC3C,6DAAwD;AACxD,2DAA6E;AAC7E,6DAAoD;AAEpD,mCAA6D;AAC7D,+EAAwE;AACxE,yDAA0D;AAC1D,uDAAoF;AAEpF,iEAA8D;AAC9D,uDAAmD;AACnD,+DAAiE;AACjE,+DAAgH;AAChH,mDAAgD;AAChD,+DAA0D;AAC1D,2CAAoD;AAEpD,6GAA6G;AAC7G,MA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sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGJ,wBAAU;QACf,mCAAe;GAHlC,YAAY,CAyFxB;AAED,MAAM,eAAe,GAAG,IAAI,YAAY,CAAC,IAAI,wBAAU,EAAE,EAAE,IAAI,mCAAe,EAAE,CAAC,CAAC;AAElF,oFAAoF;AACpF,oHAAoH;AACpH,SAAgB,eAAe,CAAC,GAAW;IACvC,OAAO,eAAe,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC;AAChD,CAAC","sourcesContent":["import * as path from 'node:path';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { ConfigObject } from '@webpieces/rules-sdk';\nimport { RepositoryLayout } from '@webpieces/tooling-common';\nimport { buildCommandsConfig, CommandsConfig } from './commands-config';\nimport { ConfigFile } from './config-file';\nimport { RulePackRegistry } from './rule-pack-registry';\nimport { PackPolicyFiles, PackPolicyFilesResult } from './pack-policy-files';\nimport { ExcludePaths } from './exclude-hook-paths';\nimport { PrGateConfig } from './pr-gate-config';\nimport { ResolvedConfig, ResolvedRuleConfig } from './types';\nimport { validateCommandsSection } from './commands-section-validators';\nimport { validateTopLevelKeys } from './config-key-rules';\nimport { validateExcludePaths, validateMatchRulesSection } from './validate-config';\nimport { MatchRuleConfig } from './match-rules-config';\nimport { WebpiecesRulesConfig } from './WebpiecesRulesConfig';\nimport { PolicyTracking } from './policy-tracking';\nimport { formatConfigErrorsBanner } from './config-error-banner';\nimport { ConfigRepairError, EditFileCure, RepositoryLayoutRepair, RunCommandCure } from './config-repair-error';\nimport { writeTemplate } from './load-template';\nimport { CONFIG_POLICY_DOC } from './config-error-banner';\nimport { PRUNE_UNKNOWN_COMMAND } from './constants';\n\n/** One root parse and one owner-resolution pass supply all consumers with the same registry and settings. */\nexport class LoadedConfig {\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n readonly resolved: ResolvedConfig,\n readonly rulesConfig: WebpiecesRulesConfig,\n readonly commands: CommandsConfig,\n readonly prGate: PrGateConfig,\n readonly excludePaths: ExcludePaths,\n readonly matchRules: readonly MatchRuleConfig[],\n readonly configPath: string | null,\n readonly ruleRegistry: RulePackRegistry,\n readonly policyFiles: PackPolicyFilesResult | null,\n ) {}\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class ConfigLoader {\n constructor(\n private readonly configFile: ConfigFile,\n private readonly files: PackPolicyFiles,\n ) {}\n\n loadAndValidate(cwd: string): LoadedConfig {\n const configPath = this.configFile.findConfigFile(cwd);\n if (!configPath) return this.empty();\n const raw = this.configFile.readRawConfig(configPath),\n root = path.dirname(configPath);\n // webpieces-disable no-any-unknown -- the root parser returns opaque client JSON; these validators narrow every accepted field\n const document = raw as Record<string, unknown>;\n writeTemplate(root, CONFIG_POLICY_DOC);\n const errors = [\n ...validateTopLevelKeys(document),\n ...validateCommandsSection(raw.commands, document['pr-gate'], root),\n ...validateExcludePaths(raw.excludePaths),\n ...validateMatchRulesSection(raw['match-rules']),\n ];\n if (errors.length)\n throw new ConfigRepairError(formatConfigErrorsBanner(errors), [\n new EditFileCure(configPath, `Edit ${configPath} and apply every bullet above.`),\n new RunCommandCure(\n PRUNE_UNKNOWN_COMMAND,\n `${PRUNE_UNKNOWN_COMMAND} — deletes every key no validator has a schema for.`,\n ),\n ]);\n new RepositoryLayoutRepair().run(() => new RepositoryLayout().assertCurrent(root));\n const declarations = this.files.declarations(raw.rulePacks, root);\n const policy = this.files.resolve(root, this.files.select(root, declarations));\n new PolicyTracking().check(root, declarations);\n return this.loaded(\n configPath,\n raw.commands,\n raw.excludePaths as string[],\n raw['match-rules'] as MatchRuleConfig[],\n policy,\n );\n }\n\n private loaded(\n configPath: string,\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n commandsRaw: unknown,\n excluded: readonly string[],\n matches: readonly MatchRuleConfig[],\n policy: PackPolicyFilesResult,\n ): LoadedConfig {\n const commands = buildCommandsConfig(commandsRaw),\n values = new WebpiecesRulesConfig();\n const resolved = new Map<string, ResolvedRuleConfig>();\n for (const id of policy.registry.ruleIds()) {\n const explicit = policy.values[id];\n values[id] = explicit;\n const options = Object.assign(\n new ConfigObject(),\n policy.registry.optionalTuningFor(id),\n explicit,\n );\n resolved.set(id, new ResolvedRuleConfig(options));\n }\n return new LoadedConfig(\n new ResolvedConfig(resolved, new Set(policy.registry.ruleIds()), configPath),\n values,\n commands,\n commands.prGate,\n new ExcludePaths([...excluded]),\n matches,\n configPath,\n policy.registry,\n policy,\n );\n }\n\n private empty(): LoadedConfig {\n const commands = buildCommandsConfig(undefined);\n return new LoadedConfig(\n new ResolvedConfig(new Map(), new Set(), null),\n new WebpiecesRulesConfig(),\n commands,\n commands.prGate,\n new ExcludePaths([]),\n [],\n null,\n new RulePackRegistry([]),\n null,\n );\n }\n}\n\nconst configLoaderSvc = new ConfigLoader(new ConfigFile(), new PackPolicyFiles());\n\n/** Public function entry point and injected service use the same implementation. */\n// webpieces-disable no-function-outside-class -- canonical public loader function for CLI and executor entry points\nexport function loadAndValidate(cwd: string): LoadedConfig {\n return configLoaderSvc.loadAndValidate(cwd);\n}\n"]}
1
+ {"version":3,"file":"load-config.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/load-config.ts"],"names":[],"mappings":";;;AAuJA,0CAEC;AAID,kDAEC;;AA/JD,wDAAkC;AAClC,yCAA2D;AAC3D,oDAAoD;AACpD,8DAA6D;AAC7D,uDAAwE;AACxE,+CAA2C;AAC3C,6DAAwD;AACxD,2DAA6E;AAC7E,6DAAoD;AAEpD,mCAA6D;AAC7D,+EAAwE;AACxE,yDAA0D;AAC1D,uDAAoF;AAEpF,iEAA8D;AAC9D,uDAAmD;AACnD,+DAAiE;AACjE,+DAAgH;AAChH,mDAAgD;AAChD,+DAA0D;AAC1D,2CAAoD;AAEpD,6GAA6G;AAC7G,MAAa,YAAY;IAGR;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IAVb,yDAAyD;IACzD,YACa,QAAwB,EACxB,WAAiC,EACjC,QAAwB,EACxB,MAAoB,EAC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AI,2CAAoB,EAAE,EAC1B,QAAQ,EACR,QAAQ,CAAC,MAAM,EACf,IAAI,iCAAY,CAAC,EAAE,CAAC,EACpB,EAAE,EACF,IAAI,EACJ,IAAI,qCAAgB,CAAC,EAAE,CAAC,EACxB,IAAI,CACP,CAAC;IACN,CAAC;CACJ,CAAA;AAzGY,oCAAY;uBAAZ,YAAY;IADxB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGJ,wBAAU;QACf,mCAAe;GAHlC,YAAY,CAyGxB;AAED,MAAM,eAAe,GAAG,IAAI,YAAY,CAAC,IAAI,wBAAU,EAAE,EAAE,IAAI,mCAAe,EAAE,CAAC,CAAC;AAElF,oFAAoF;AACpF,oHAAoH;AACpH,SAAgB,eAAe,CAAC,GAAW;IACvC,OAAO,eAAe,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC;AAChD,CAAC;AAED,kFAAkF;AAClF,gHAAgH;AAChH,SAAgB,mBAAmB,CAAC,GAAW;IAC3C,eAAe,CAAC,mBAAmB,CAAC,GAAG,CAAC,CAAC;AAC7C,CAAC","sourcesContent":["import * as path from 'node:path';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { ConfigObject } from '@webpieces/rules-sdk';\nimport { RepositoryLayout } from '@webpieces/tooling-common';\nimport { buildCommandsConfig, CommandsConfig } from './commands-config';\nimport { ConfigFile } from './config-file';\nimport { RulePackRegistry } from './rule-pack-registry';\nimport { PackPolicyFiles, PackPolicyFilesResult } from './pack-policy-files';\nimport { ExcludePaths } from './exclude-hook-paths';\nimport { PrGateConfig } from './pr-gate-config';\nimport { ResolvedConfig, ResolvedRuleConfig } from './types';\nimport { validateCommandsSection } from './commands-section-validators';\nimport { validateTopLevelKeys } from './config-key-rules';\nimport { validateExcludePaths, validateMatchRulesSection } from './validate-config';\nimport { MatchRuleConfig } from './match-rules-config';\nimport { WebpiecesRulesConfig } from './WebpiecesRulesConfig';\nimport { PolicyTracking } from './policy-tracking';\nimport { formatConfigErrorsBanner } from './config-error-banner';\nimport { ConfigRepairError, EditFileCure, RepositoryLayoutRepair, RunCommandCure } from './config-repair-error';\nimport { writeTemplate } from './load-template';\nimport { CONFIG_POLICY_DOC } from './config-error-banner';\nimport { PRUNE_UNKNOWN_COMMAND } from './constants';\n\n/** One root parse and one owner-resolution pass supply all consumers with the same registry and settings. */\nexport class LoadedConfig {\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n readonly resolved: ResolvedConfig,\n readonly rulesConfig: WebpiecesRulesConfig,\n readonly commands: CommandsConfig,\n readonly prGate: PrGateConfig,\n readonly excludePaths: ExcludePaths,\n readonly matchRules: readonly MatchRuleConfig[],\n readonly configPath: string | null,\n readonly ruleRegistry: RulePackRegistry,\n readonly policyFiles: PackPolicyFilesResult | null,\n ) {}\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class ConfigLoader {\n constructor(\n private readonly configFile: ConfigFile,\n private readonly files: PackPolicyFiles,\n ) {}\n\n loadAndValidate(cwd: string): LoadedConfig {\n const configPath = this.configFile.findConfigFile(cwd);\n if (!configPath) return this.empty();\n const raw = this.configFile.readRawConfig(configPath),\n root = path.dirname(configPath);\n // webpieces-disable no-any-unknown -- the root parser returns opaque client JSON; these validators narrow every accepted field\n const document = raw as Record<string, unknown>;\n writeTemplate(root, CONFIG_POLICY_DOC);\n const errors = [\n ...validateTopLevelKeys(document),\n ...validateCommandsSection(raw.commands, document['pr-gate'], root),\n ...validateExcludePaths(raw.excludePaths),\n ...validateMatchRulesSection(raw['match-rules']),\n ];\n if (errors.length)\n throw new ConfigRepairError(formatConfigErrorsBanner(errors), [\n new EditFileCure(configPath, `Edit ${configPath} and apply every bullet above.`),\n new RunCommandCure(\n PRUNE_UNKNOWN_COMMAND,\n `${PRUNE_UNKNOWN_COMMAND} — deletes every key no validator has a schema for.`,\n ),\n ]);\n new RepositoryLayoutRepair().run(() => new RepositoryLayout().assertCurrent(root));\n const declarations = this.files.declarations(raw.rulePacks, root);\n const policy = this.files.resolve(root, this.files.select(root, declarations));\n return this.loaded(\n configPath,\n raw.commands,\n raw.excludePaths as string[],\n raw['match-rules'] as MatchRuleConfig[],\n policy,\n );\n }\n\n /**\n * \"Policy is shared through the git index\": every declared owner file is tracked and not ignored.\n *\n * NOT part of loadAndValidate (#1355). It is a COMMIT-TIME invariant — nothing about it changes\n * between two tool calls — and it costs two `git` processes, so running it on every config load put\n * it on the hottest path there is: every guard-hook invocation. It runs where work is SHARED instead:\n * `wp-ci`, which is the PR gate's build command and CI's. Its refusal (UntrackedPolicyError and the\n * gitignored-policy ConfigRepairError) and their cures are unchanged.\n */\n assertPolicyTracked(cwd: string): void {\n const configPath = this.configFile.findConfigFile(cwd);\n if (!configPath) return;\n const raw = this.configFile.readRawConfig(configPath),\n root = path.dirname(configPath);\n new PolicyTracking().check(root, this.files.declarations(raw.rulePacks, root));\n }\n\n private loaded(\n configPath: string,\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n commandsRaw: unknown,\n excluded: readonly string[],\n matches: readonly MatchRuleConfig[],\n policy: PackPolicyFilesResult,\n ): LoadedConfig {\n const commands = buildCommandsConfig(commandsRaw),\n values = new WebpiecesRulesConfig();\n const resolved = new Map<string, ResolvedRuleConfig>();\n for (const id of policy.registry.ruleIds()) {\n const explicit = policy.values[id];\n values[id] = explicit;\n const options = Object.assign(\n new ConfigObject(),\n policy.registry.optionalTuningFor(id),\n explicit,\n );\n resolved.set(id, new ResolvedRuleConfig(options));\n }\n return new LoadedConfig(\n new ResolvedConfig(resolved, new Set(policy.registry.ruleIds()), configPath),\n values,\n commands,\n commands.prGate,\n new ExcludePaths([...excluded]),\n matches,\n configPath,\n policy.registry,\n policy,\n );\n }\n\n private empty(): LoadedConfig {\n const commands = buildCommandsConfig(undefined);\n return new LoadedConfig(\n new ResolvedConfig(new Map(), new Set(), null),\n new WebpiecesRulesConfig(),\n commands,\n commands.prGate,\n new ExcludePaths([]),\n [],\n null,\n new RulePackRegistry([]),\n null,\n );\n }\n}\n\nconst configLoaderSvc = new ConfigLoader(new ConfigFile(), new PackPolicyFiles());\n\n/** Public function entry point and injected service use the same implementation. */\n// webpieces-disable no-function-outside-class -- canonical public loader function for CLI and executor entry points\nexport function loadAndValidate(cwd: string): LoadedConfig {\n return configLoaderSvc.loadAndValidate(cwd);\n}\n\n/** The gate-time policy-tracking check — see ConfigLoader.assertPolicyTracked. */\n// webpieces-disable no-function-outside-class -- the public function twin of loadAndValidate, for the wp-ci bin\nexport function assertPolicyTracked(cwd: string): void {\n configLoaderSvc.assertPolicyTracked(cwd);\n}\n"]}
@@ -1,15 +1,20 @@
1
1
  import type { PackPolicyDeclaration } from './pack-policy-files';
2
2
  import { ConfigRepairError } from './config-repair-error';
3
3
  /**
4
- * Declared policy files git's index does not hold (#1327). Its own type because the guard hook treats it
5
- * specially: while THIS refusal is why the config will not load, a plain `git add` is let through
6
- * (agent-workflow-rules `PolicyStagingCommand`) — staging is literally the cure, so refusing it was a loop.
4
+ * Declared policy files git's index does not hold (#1327) — the PR gate's refusal (`wp-ci`), never a
5
+ * config-load one (#1355): the guard hooks do not check tracking, so nothing blocks the `git add` cure.
7
6
  */
8
7
  export declare class UntrackedPolicyError extends ConfigRepairError {
9
8
  readonly untracked: readonly string[];
10
9
  constructor(untracked: readonly string[]);
11
10
  }
12
- /** Git repositories must share policy through their index, including rules switched OFF. */
11
+ /**
12
+ * Git repositories must share policy through their index, including rules switched OFF.
13
+ *
14
+ * Checked at the PR gate and in CI (`wp-ci` → ConfigLoader.assertPolicyTracked), NOT on config load:
15
+ * it is a commit-time invariant that costs two `git` processes, and config load runs on every guard-hook
16
+ * invocation (#1355). `stage()` is wp-migrate-dirs' cure and is unchanged.
17
+ */
13
18
  export declare class PolicyTracking {
14
19
  check(root: string, declarations: readonly PackPolicyDeclaration[]): void;
15
20
  stage(root: string, declarations: readonly PackPolicyDeclaration[]): void;
@@ -14,9 +14,8 @@ class ShellQuote {
14
14
  }
15
15
  }
16
16
  /**
17
- * Declared policy files git's index does not hold (#1327). Its own type because the guard hook treats it
18
- * specially: while THIS refusal is why the config will not load, a plain `git add` is let through
19
- * (agent-workflow-rules `PolicyStagingCommand`) — staging is literally the cure, so refusing it was a loop.
17
+ * Declared policy files git's index does not hold (#1327) — the PR gate's refusal (`wp-ci`), never a
18
+ * config-load one (#1355): the guard hooks do not check tracking, so nothing blocks the `git add` cure.
20
19
  */
21
20
  class UntrackedPolicyError extends config_repair_error_1.ConfigRepairError {
22
21
  untracked;
@@ -26,7 +25,6 @@ class UntrackedPolicyError extends config_repair_error_1.ConfigRepairError {
26
25
  'Webpieces policy files are not tracked by git. Policy is shared through the git index, so every',
27
26
  'declared owner file must be staged and committed with your change. Untracked:',
28
27
  ...untracked.map((file) => ` ${file}`),
29
- 'A plain `git add` is permitted while this refusal is active.',
30
28
  ].join('\n'), [
31
29
  new config_repair_error_1.RunCommandCure(`git add -- ${quoted}`, `git add -- ${quoted} — stages exactly the untracked files listed above.`),
32
30
  new config_repair_error_1.RunCommandCure(`${tooling_common_1.MIGRATE_DIRS_COMMAND} --stage`, `${tooling_common_1.MIGRATE_DIRS_COMMAND} --stage — stages webpieces.config.json, .gitignore and every declared owner file.`),
@@ -36,7 +34,13 @@ class UntrackedPolicyError extends config_repair_error_1.ConfigRepairError {
36
34
  }
37
35
  }
38
36
  exports.UntrackedPolicyError = UntrackedPolicyError;
39
- /** Git repositories must share policy through their index, including rules switched OFF. */
37
+ /**
38
+ * Git repositories must share policy through their index, including rules switched OFF.
39
+ *
40
+ * Checked at the PR gate and in CI (`wp-ci` → ConfigLoader.assertPolicyTracked), NOT on config load:
41
+ * it is a commit-time invariant that costs two `git` processes, and config load runs on every guard-hook
42
+ * invocation (#1355). `stage()` is wp-migrate-dirs' cure and is unchanged.
43
+ */
40
44
  class PolicyTracking {
41
45
  check(root, declarations) {
42
46
  // Standalone non-git schema validation is supported; CI and governed checkouts have .git.
@@ -1 +1 @@
1
- {"version":3,"file":"policy-tracking.js","sourceRoot":"","sources":["../../../../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C,CAAC,CAAC,CAAC;IAC9E,CAAC;IAEO,KAAK,CAAC,IAAY,EAAE,YAA8C;QACtE,MAAM,QAAQ,GAAG,YAAY,CAAC,GAAG,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;QACvE,OAAO;YACH,GAAG,IAAI,GAAG,CACN,QAAQ,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC;gBAC3B,QAAQ;gBACR,IAAI,CAAC,QAAQ,CACT,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,EACrB,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC,CAC7C;aACJ,CAAC,CACL;SACJ,CAAC;IACN,CAAC;CACJ;AA3FD,wCA2FC","sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { spawnSync } from 'node:child_process';\nimport { InformAiError, MIGRATE_DIRS_COMMAND } from '@webpieces/tooling-common';\nimport type { PackPolicyDeclaration } from './pack-policy-files';\nimport { ConfigRepairError, EditFileCure, RunCommandCure } from './config-repair-error';\n\n/** POSIX single-quoting for a path printed inside a command the reader will paste. */\nclass ShellQuote {\n quote(value: string): string {\n return /^[A-Za-z0-9_./@:+-]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\\\''`)}'`;\n }\n}\n\n/**\n * Declared policy files git's index does not hold (#1327). Its own type because the guard hook treats it\n * specially: while THIS refusal is why the config will not load, a plain `git add` is let through\n * (agent-workflow-rules `PolicyStagingCommand`) — staging is literally the cure, so refusing it was a loop.\n */\nexport class UntrackedPolicyError extends ConfigRepairError {\n readonly untracked: readonly string[];\n\n constructor(untracked: readonly string[]) {\n const quoted = untracked.map((file: string) => new ShellQuote().quote(file)).join(' ');\n super(\n [\n 'Webpieces policy files are not tracked by git. Policy is shared through the git index, so every',\n 'declared owner file must be staged and committed with your change. Untracked:',\n ...untracked.map((file: string) => ` ${file}`),\n 'A plain `git add` is permitted while this refusal is active.',\n ].join('\\n'),\n [\n new RunCommandCure(\n `git add -- ${quoted}`,\n `git add -- ${quoted} — stages exactly the untracked files listed above.`,\n ),\n new RunCommandCure(\n `${MIGRATE_DIRS_COMMAND} --stage`,\n `${MIGRATE_DIRS_COMMAND} --stage — stages webpieces.config.json, .gitignore and every declared owner file.`,\n ),\n ],\n );\n this.name = 'UntrackedPolicyError';\n this.untracked = untracked;\n }\n}\n\n/** Git repositories must share policy through their index, including rules switched OFF. */\nexport class PolicyTracking {\n check(root: string, declarations: readonly PackPolicyDeclaration[]): void {\n // Standalone non-git schema validation is supported; CI and governed checkouts have .git.\n if (!fs.existsSync(path.join(root, '.git'))) return;\n const files = this.files(root, declarations);\n const ignored = spawnSync('git', ['check-ignore', '--no-index', '--', ...files], {\n cwd: root,\n encoding: 'utf8',\n });\n if (ignored.status !== 0 && ignored.status !== 1)\n throw new InformAiError(\n `Cannot verify policy ignore status: ${ignored.stderr}. Repair git access, then retry.`,\n );\n if (ignored.stdout.trim())\n throw new ConfigRepairError(\n `Committed Webpieces policy is gitignored:\\n${ignored.stdout}Only .webpieces/ belongs in .gitignore; .webpieces-config/ must be tracked.`,\n [\n new EditFileCure(\n path.join(root, '.gitignore'),\n `Delete the .gitignore patterns that match the files listed above.`,\n ),\n ],\n );\n const untracked = this.untracked(root, files);\n if (untracked.length) throw new UntrackedPolicyError(untracked);\n }\n\n stage(root: string, declarations: readonly PackPolicyDeclaration[]): void {\n // `.webpieces/` is the gitignored state directory, so `git add` refuses its paths. Untrack whatever\n // policy older releases committed there with `rm --cached`, which keeps every file on disk.\n const retired = spawnSync(\n 'git',\n ['rm', '-r', '-q', '--cached', '--ignore-unmatch', '--', '.webpieces'],\n { cwd: root, encoding: 'utf8' },\n );\n if (retired.status !== 0)\n throw new InformAiError(\n `Cannot untrack retired policy paths in .webpieces/: ${retired.stderr}. Verify git access before retrying.`,\n );\n const result = spawnSync(\n 'git',\n [\n '--literal-pathspecs',\n 'add',\n '-A',\n '--',\n 'webpieces.config.json',\n '.gitignore',\n ...this.files(root, declarations),\n ],\n { cwd: root, encoding: 'utf8' },\n );\n if (result.status !== 0)\n throw new InformAiError(\n `Could not stage Webpieces policy: ${result.stderr}. Remove policy ignore patterns and verify git access before retrying.`,\n );\n }\n\n /** Which of `files` git's index does not hold — each one named, never git's own pathspec advice. */\n private untracked(root: string, files: readonly string[]): string[] {\n const listed = spawnSync('git', ['--literal-pathspecs', 'ls-files', '-z', '--', ...files], {\n cwd: root,\n encoding: 'utf8',\n });\n if (listed.status !== 0)\n throw new InformAiError(\n `Cannot verify policy tracking status: ${listed.stderr}. Repair git access, then retry.`,\n );\n const tracked = new Set(\n listed.stdout\n .split('\\0')\n .filter((entry: string) => entry !== '')\n .map((entry: string) => path.normalize(entry)),\n );\n return files.filter((file: string) => !tracked.has(path.normalize(file)));\n }\n\n private files(root: string, declarations: readonly PackPolicyDeclaration[]): string[] {\n const declared = declarations.map((declaration) => declaration.config);\n return [\n ...new Set(\n declared.flatMap((filename) => [\n filename,\n path.relative(\n fs.realpathSync(root),\n fs.realpathSync(path.join(root, filename)),\n ),\n ]),\n ),\n ];\n }\n}\n"]}
1
+ {"version":3,"file":"policy-tracking.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/policy-tracking.ts"],"names":[],"mappings":";;;;AAAA,oDAA8B;AAC9B,wDAAkC;AAClC,2DAA+C;AAC/C,8DAAgF;AAEhF,+DAAwF;AAExF,sFAAsF;AACtF,MAAM,UAAU;IACZ,KAAK,CAAC,KAAa;QACf,OAAO,uBAAuB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,GAAG,CAAC;IAC7F,CAAC;CACJ;AAED;;;GAGG;AACH,MAAa,oBAAqB,SAAQ,uCAAiB;IAC9C,SAAS,CAAoB;IAEtC,YAAY,SAA4B;QACpC,MAA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,CAAC;IACN,CAAC;CACJ;AA3FD,wCA2FC","sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { spawnSync } from 'node:child_process';\nimport { InformAiError, MIGRATE_DIRS_COMMAND } from '@webpieces/tooling-common';\nimport type { PackPolicyDeclaration } from './pack-policy-files';\nimport { ConfigRepairError, EditFileCure, RunCommandCure } from './config-repair-error';\n\n/** POSIX single-quoting for a path printed inside a command the reader will paste. */\nclass ShellQuote {\n quote(value: string): string {\n return /^[A-Za-z0-9_./@:+-]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\\\''`)}'`;\n }\n}\n\n/**\n * Declared policy files git's index does not hold (#1327) — the PR gate's refusal (`wp-ci`), never a\n * config-load one (#1355): the guard hooks do not check tracking, so nothing blocks the `git add` cure.\n */\nexport class UntrackedPolicyError extends ConfigRepairError {\n readonly untracked: readonly string[];\n\n constructor(untracked: readonly string[]) {\n const quoted = untracked.map((file: string) => new ShellQuote().quote(file)).join(' ');\n super(\n [\n 'Webpieces policy files are not tracked by git. Policy is shared through the git index, so every',\n 'declared owner file must be staged and committed with your change. Untracked:',\n ...untracked.map((file: string) => ` ${file}`),\n ].join('\\n'),\n [\n new RunCommandCure(\n `git add -- ${quoted}`,\n `git add -- ${quoted} — stages exactly the untracked files listed above.`,\n ),\n new RunCommandCure(\n `${MIGRATE_DIRS_COMMAND} --stage`,\n `${MIGRATE_DIRS_COMMAND} --stage — stages webpieces.config.json, .gitignore and every declared owner file.`,\n ),\n ],\n );\n this.name = 'UntrackedPolicyError';\n this.untracked = untracked;\n }\n}\n\n/**\n * Git repositories must share policy through their index, including rules switched OFF.\n *\n * Checked at the PR gate and in CI (`wp-ci` → ConfigLoader.assertPolicyTracked), NOT on config load:\n * it is a commit-time invariant that costs two `git` processes, and config load runs on every guard-hook\n * invocation (#1355). `stage()` is wp-migrate-dirs' cure and is unchanged.\n */\nexport class PolicyTracking {\n check(root: string, declarations: readonly PackPolicyDeclaration[]): void {\n // Standalone non-git schema validation is supported; CI and governed checkouts have .git.\n if (!fs.existsSync(path.join(root, '.git'))) return;\n const files = this.files(root, declarations);\n const ignored = spawnSync('git', ['check-ignore', '--no-index', '--', ...files], {\n cwd: root,\n encoding: 'utf8',\n });\n if (ignored.status !== 0 && ignored.status !== 1)\n throw new InformAiError(\n `Cannot verify policy ignore status: ${ignored.stderr}. Repair git access, then retry.`,\n );\n if (ignored.stdout.trim())\n throw new ConfigRepairError(\n `Committed Webpieces policy is gitignored:\\n${ignored.stdout}Only .webpieces/ belongs in .gitignore; .webpieces-config/ must be tracked.`,\n [\n new EditFileCure(\n path.join(root, '.gitignore'),\n `Delete the .gitignore patterns that match the files listed above.`,\n ),\n ],\n );\n const untracked = this.untracked(root, files);\n if (untracked.length) throw new UntrackedPolicyError(untracked);\n }\n\n stage(root: string, declarations: readonly PackPolicyDeclaration[]): void {\n // `.webpieces/` is the gitignored state directory, so `git add` refuses its paths. Untrack whatever\n // policy older releases committed there with `rm --cached`, which keeps every file on disk.\n const retired = spawnSync(\n 'git',\n ['rm', '-r', '-q', '--cached', '--ignore-unmatch', '--', '.webpieces'],\n { cwd: root, encoding: 'utf8' },\n );\n if (retired.status !== 0)\n throw new InformAiError(\n `Cannot untrack retired policy paths in .webpieces/: ${retired.stderr}. Verify git access before retrying.`,\n );\n const result = spawnSync(\n 'git',\n [\n '--literal-pathspecs',\n 'add',\n '-A',\n '--',\n 'webpieces.config.json',\n '.gitignore',\n ...this.files(root, declarations),\n ],\n { cwd: root, encoding: 'utf8' },\n );\n if (result.status !== 0)\n throw new InformAiError(\n `Could not stage Webpieces policy: ${result.stderr}. Remove policy ignore patterns and verify git access before retrying.`,\n );\n }\n\n /** Which of `files` git's index does not hold — each one named, never git's own pathspec advice. */\n private untracked(root: string, files: readonly string[]): string[] {\n const listed = spawnSync('git', ['--literal-pathspecs', 'ls-files', '-z', '--', ...files], {\n cwd: root,\n encoding: 'utf8',\n });\n if (listed.status !== 0)\n throw new InformAiError(\n `Cannot verify policy tracking status: ${listed.stderr}. Repair git access, then retry.`,\n );\n const tracked = new Set(\n listed.stdout\n .split('\\0')\n .filter((entry: string) => entry !== '')\n .map((entry: string) => path.normalize(entry)),\n );\n return files.filter((file: string) => !tracked.has(path.normalize(file)));\n }\n\n private files(root: string, declarations: readonly PackPolicyDeclaration[]): string[] {\n const declared = declarations.map((declaration) => declaration.config);\n return [\n ...new Set(\n declared.flatMap((filename) => [\n filename,\n path.relative(\n fs.realpathSync(root),\n fs.realpathSync(path.join(root, filename)),\n ),\n ]),\n ),\n ];\n }\n}\n"]}
@@ -306,8 +306,8 @@ export declare class SubagentProvenanceService {
306
306
  *
307
307
  * It reviewed A. Every past reviewer run in that clone would be credited for whatever branch is
308
308
  * checked out at finish time — which in a repo with a required reviewer on every PR is not an
309
- * exotic sequence, it is the normal one. So the fallback is gated on `dotWebpieces.isLinkedWorktree`
310
- * (git's own `--git-dir != --git-common-dir` test, reused rather than re-derived), and a primary
309
+ * exotic sequence, it is the normal one. So the fallback is gated on `gitCheckout.isLinkedWorktree`
310
+ * (git's own git-dir != common-git-dir test, read from the filesystem, reused rather than re-derived), and a primary
311
311
  * clone falls through to a refusal exactly as it does today.
312
312
  *
313
313
  * That gate keeps the anti-forgery property intact: `cwd` is harness-written in the same record by
@@ -2,7 +2,6 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.SubagentProvenanceService = exports.ExpectedReviewer = exports.ReviewerContext = exports.TranscriptScan = exports.ReviewerEvidence = exports.ProvenanceResult = exports.PROVENANCE_SKIPPED = exports.PROVENANCE_MISSING = exports.PROVENANCE_OK = void 0;
4
4
  const tslib_1 = require("tslib");
5
- const child_process_1 = require("child_process");
6
5
  const fs = tslib_1.__importStar(require("fs"));
7
6
  const path = tslib_1.__importStar(require("path"));
8
7
  const inversify_1 = require("inversify");
@@ -571,8 +570,8 @@ let SubagentProvenanceService = class SubagentProvenanceService {
571
570
  *
572
571
  * It reviewed A. Every past reviewer run in that clone would be credited for whatever branch is
573
572
  * checked out at finish time — which in a repo with a required reviewer on every PR is not an
574
- * exotic sequence, it is the normal one. So the fallback is gated on `dotWebpieces.isLinkedWorktree`
575
- * (git's own `--git-dir != --git-common-dir` test, reused rather than re-derived), and a primary
573
+ * exotic sequence, it is the normal one. So the fallback is gated on `gitCheckout.isLinkedWorktree`
574
+ * (git's own git-dir != common-git-dir test, read from the filesystem, reused rather than re-derived), and a primary
576
575
  * clone falls through to a refusal exactly as it does today.
577
576
  *
578
577
  * That gate keeps the anti-forgery property intact: `cwd` is harness-written in the same record by
@@ -690,13 +689,10 @@ let SubagentProvenanceService = class SubagentProvenanceService {
690
689
  pinnedBranch(cwd) {
691
690
  if (!fs.existsSync(cwd))
692
691
  return '';
693
- if (!tooling_common_2.dotWebpieces.isLinkedWorktree(cwd))
692
+ if (!tooling_common_2.gitCheckout.isLinkedWorktree(cwd))
694
693
  return '';
695
- const result = (0, child_process_1.spawnSync)('git', ['-C', cwd, 'rev-parse', '--abbrev-ref', 'HEAD'], { encoding: 'utf8' });
696
- if (result.status !== 0)
697
- return '';
698
- const printed = (result.stdout ?? '').trim();
699
- return printed === 'HEAD' ? '' : printed;
694
+ const branch = tooling_common_2.gitCheckout.branch(cwd);
695
+ return branch === null || branch === tooling_common_2.DETACHED_HEAD ? '' : branch;
700
696
  }
701
697
  stripWp(branch) {
702
698
  return branch.replace(/-?wp\d+$/i, '');
@@ -1 +1 @@
1
- {"version":3,"file":"subagent-provenance.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/subagent-provenance.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAC3D,8DAA4D;AAC5D,iEAA6D;AAC7D,8DAAyD;AACzD,sEAAqE;AAErE,iCAAiC;AACpB,QAAA,aAAa,GAAG,IAAI,CAAC,CAAW,+DAA+D;AAC/F,QAAA,kBAAkB,GAAG,SAAS,CAAC,CAAC,0EAA0E;AAC1G,QAAA,kBAAkB,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OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,KAAK,KAAK,CAAC;YACX,OAAO,IAAI,CAAC;QAChB,CAAC;IACL,CAAC;IAED,uFAAuF;IAC/E,SAAS,CAAC,IAAY;QAC1B,yFAAyF;QACzF,8DAA8D;QAC9D,IAAI,CAAC;YACD,yFAAyF;YACzF,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAA4B,CAAC;QACvD,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,KAAK,KAAK,CAAC;YACX,OAAO,IAAI,CAAC;QAChB,CAAC;IACL,CAAC;CACJ,CAAA;AAphBY,8DAAyB;oCAAzB,yBAAyB;IADrC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;GAC5B,yBAAyB,CAohBrC","sourcesContent":["import { spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { claudeConfigDir } from '@webpieces/tooling-common';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { dotWebpieces } from '@webpieces/tooling-common';\nimport { reviewIdentityStamps } from '@webpieces/repo-workflow-core';\n\n// Outcome of a provenance check.\nexport const PROVENANCE_OK = 'ok'; // a matching reviewer subagent demonstrably ran on this branch\nexport const PROVENANCE_MISSING = 'missing'; // session known, but no matching subagent artifact found → refuse (BLOCK)\nexport const PROVENANCE_SKIPPED = 'skipped'; // no CLAUDE_CODE_SESSION_ID → transcript evidence skipped; wp-write-review provenance still enforced (#863)\n\nexport class ProvenanceResult {\n status: string; // PROVENANCE_OK | PROVENANCE_MISSING | PROVENANCE_SKIPPED\n detail: string; // human-readable explanation for the warning/error/dashboard\n // agentIds credited, keyed by CHECKLIST ID, so an evidence pass does not re-scan to find them again. Two\n // checklists may map to the same agentId when `reviewerAgents` let one subagent cover both.\n agentIds: Record<string, string>;\n /**\n * The checklist ids that could NOT be credited — the FACT, with no remedy attached.\n *\n * Structured rather than only spelled into `detail` because the remedy depends on something this\n * service cannot see: whether that reviewer already wrote a verdict file. \"It never ran\" and \"it ran\n * and cannot be attributed\" need OPPOSITE instructions — spawn one, versus do not re-spawn into this\n * round, because a round's verdict is never overwritten and the re-spawn records nothing. Handing the caller a pre-worded\n * imperative is what produced the destructive loop this field exists to end; see ProvenanceEnforcer.\n */\n missing: string[];\n\n /**\n * `agentIds` and `missing` are REQUIRED, with no defaults.\n *\n * A default on `missing` is what made the dangerous state cheap to reach: the caller BLOCKS on this\n * list, so a `PROVENANCE_MISSING` built without it would report unverified and refuse NOTHING — a\n * silent pass, one forgotten argument away. Required parameters make the omission a compile error at\n * every construction site, present and future. The remaining `missing: []` on a blocking status is\n * caught by the caller, which refuses on the STATUS and falls back to `detail`; see\n * ProvenanceEnforcer.refuse.\n */\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(status: string, detail: string, agentIds: Record<string, string>, missing: string[]) {\n this.status = status;\n this.detail = detail;\n this.agentIds = agentIds;\n this.missing = missing;\n }\n}\n\n/**\n * What ONE credited reviewer actually DID, read from its own transcript. Data-only (per CLAUDE.md).\n *\n * `verifyReviewers` answers \"did a reviewer of this type run?\" — an INTEGRITY question, and it blocks. This\n * answers \"did it look at the change?\" — a QUALITY question, and it only warns. The distinction is\n * deliberate; see {@link SubagentProvenanceService.evidenceFor}.\n */\nexport class ReviewerEvidence {\n checklistId: string; // the checklist this evidence is FOR (one subagent may appear under several)\n agentType: string;\n agentId: string;\n readDiff: boolean; // opened the materialized diff dir (or its own instructions file)\n readDoc: boolean; // opened its checklist's guidance doc\n /**\n * Named its own verdict file — `.webpieces/pr-review/<featureSlug>/review-round<N>-<id>.json` — in a tool input.\n *\n * Recorded, not just consumed, because it is the field that answers \"who wrote this verdict?\" for an\n * auditor reading provenance.json later. It is also a CREDIT channel: see\n * {@link SubagentProvenanceService.creditedByWhatItTouched}.\n */\n wroteVerdict: boolean;\n toolCallCount: number;\n offRepoSearches: number; // tool calls that reached into node_modules — the archaeology signal\n /**\n * Distinct `message.model` values OBSERVED in the transcript, in first-seen order.\n *\n * The model that actually ran, never the one that was configured — and never anything the reviewer\n * says about itself. The reviewer agent's `.claude/agents/<name>.md` may declare `model:`, but that is the\n * REQUESTED value and it can silently disagree with what served the request: a repo was measured\n * running opus for a reviewer whose agent file said `model: sonnet`. Asking the model instead would\n * be worse — a model is unreliable about its own identity, naming a family instead of a version or\n * repeating whatever the system prompt implied, so a self-reported field is usually right and\n * silently wrong, which is the worst kind of telemetry because it looks authoritative.\n * `message.model` is written by the harness, so this inherits the anti-forgery property the rest of\n * this class documents.\n *\n * An ARRAY, not a string: one reviewer run can span more than one model (a fallback after a refusal,\n * a mid-run config change). Collapsing to one value forces a lossy choice at read time; recording\n * what happened lets the renderer decide.\n *\n * Token counts and cost are deliberately NOT here. Prices change, vary by platform and differ under\n * intro pricing, so a rate table in this package would rot silently — and the question this answers\n * is \"which model reviewed this?\", not \"what did it cost?\".\n */\n models: string[];\n // Absolute path of the transcript these counters were read out of, '' when it could not be resolved.\n // Carried out rather than recomputed because a reviewer subagent cannot learn its own transcript path\n // (the environment exposes the PARENT session id and no agent id), so this is the only place it is\n // known — see ReviewProvenanceService, which records it as the audit link for the verdict.\n transcriptPath: string;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(checklistId: string, agentType: string, agentId: string, readDiff = false, readDoc = false, toolCallCount = 0, offRepoSearches = 0, transcriptPath = '', models: string[] = [], wroteVerdict = false) {\n this.checklistId = checklistId;\n this.agentType = agentType;\n this.agentId = agentId;\n this.readDiff = readDiff;\n this.readDoc = readDoc;\n this.wroteVerdict = wroteVerdict;\n this.toolCallCount = toolCallCount;\n this.offRepoSearches = offRepoSearches;\n this.transcriptPath = transcriptPath;\n this.models = models;\n }\n}\n\n/**\n * One pass over one transcript: the tool inputs AND the models that served it. Data-only.\n *\n * They are gathered together rather than in two passes because they come from the SAME records — the\n * inputs from `message.content[].input`, the model from `message.model` one level up — and a transcript\n * is the largest file this service opens. Two reads of it to answer two questions about the same lines\n * would be the duplicate-work trap the diff materializer documents at length.\n */\nexport class TranscriptScan {\n inputs: string[]; // every tool_use input, JSON-stringified\n models: string[]; // distinct message.model values, first-seen order\n /**\n * The harness-written `cwd` of the transcript's FIRST record that carries one ('' when none does) —\n * what a relative path in a tool input resolves against. See\n * {@link SubagentProvenanceService.namesPath} for why a relative path has to be matched at all.\n */\n cwd: string;\n\n constructor(inputs: string[] = [], models: string[] = [], cwd = '') {\n this.inputs = inputs;\n this.models = models;\n this.cwd = cwd;\n }\n}\n\n/**\n * WHERE this branch's review materials live. Data-only.\n *\n * One class for BOTH passes — crediting (`verifyReviewers`) and evidence (`evidenceFor`) — because they\n * ask their questions of the same paths. `diffDir` is the per-branch materialization\n * (`.webpieces/pr-review/<featureSlug>/diff`), which is what makes it usable as PROOF of which branch a\n * reviewer looked at: the path names the branch, it is absolute, and stage ② recreates it per run.\n */\nexport class ReviewerContext {\n branch: string;\n diffDir: string; // '' when nothing was materialized\n docPaths: Record<string, string>; // checklist id → its checklist doc path ('' when none)\n /**\n * checklist id → the absolute path of the verdict file THAT checklist must write on THIS branch\n * (`.webpieces/pr-review/<featureSlug>/review-round<N>-<id>.json`). '' when unknown.\n *\n * The strongest attribution signal available, and stronger than `diffDir`: the path is\n * worktree-absolute (naming the tree), per-branch (naming the featureSlug) AND per-checklist (naming\n * the id), so a transcript containing it can only belong to a reviewer that authored that checklist's\n * verdict for that branch. `diffDir` proves the branch but not the checklist.\n */\n verdictPaths: Record<string, string>;\n /**\n * checklist id → the agentId `pnpm wp-write-review` recorded in THIS branch's verdict provenance\n * (`review-round<N>-<id>.provenance.json`); absent when there is none.\n *\n * What makes a `wp-write-review --checklist <id>` invocation in a transcript BRANCH-specific. The command\n * line names only the checklist, and checklist ids are shared by every branch (a universal checklist is\n * reviewed on every PR), so an invocation alone proves authorship of SOME verdict, never which branch's.\n * The bin wrote this branch's verdict from the harness's own `agent_id` for that call, so a transcript\n * of that same agentId that invoked it is the reviewer that submitted this branch's verdict.\n */\n submittedBy: Record<string, string>;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(branch: string, diffDir = '', docPaths: Record<string, string> = {}, verdictPaths: Record<string, string> = {}, submittedBy: Record<string, string> = {}) {\n this.branch = branch;\n this.diffDir = diffDir;\n this.docPaths = docPaths;\n this.verdictPaths = verdictPaths;\n this.submittedBy = submittedBy;\n }\n}\n\n/**\n * One checklist that must be credited to a reviewer run, plus the agent type the BRIEFING named. Data-only.\n *\n * The two used to be one string — a checklist's id WAS its agent type — and provenance keyed everything by\n * it. Now every checklist is reviewed by the same repo-wide agent type, so the id and the type are\n * separate facts.\n *\n * `agentType` is NOT a provenance input: nothing here matches a run on it (issue #964, see\n * {@link SubagentProvenanceService.isReviewerRun}). It is carried because it is what the BRIEFING told\n * the agent to spawn and what {@link ReviewerEvidence} reports, which are both worth recording even\n * though neither is worth gating on.\n */\nexport class ExpectedReviewer {\n checklistId: string;\n agentType: string;\n\n constructor(checklistId: string, agentType: string) {\n this.checklistId = checklistId;\n this.agentType = agentType;\n }\n}\n\n/**\n * Verifies — from the Claude Code harness's OWN artifacts, never from anything the model asserts — that\n * a real SUBAGENT actually ran on the current branch and did this checklist's work. Used to enforce that\n * every checklist was reviewed by an INDEPENDENT reviewer, rather than by the coding agent\n * self-certifying.\n *\n * The harness writes, beside each subagent transcript:\n * <config>/projects/<cwd-slug>/<sessionId>/subagents/agent-<id>.meta.json → { agentType, spawnDepth, … }\n * <config>/projects/<cwd-slug>/<sessionId>/subagents/agent-<id>.jsonl → record 0 { isSidechain, gitBranch, … }\n * `spawnDepth`/`isSidechain` are written by Claude Code, not by the model, and they are what carries the\n * anti-self-certification property. `agentType` is written there too and is deliberately NOT checked —\n * see {@link SubagentProvenanceService.isReviewerRun}. `<config>` is `$CLAUDE_CONFIG_DIR` when set, else\n * `~/.claude`; see {@link ClaudeConfigDir}, and never re-derive it here. Dirs are found by walking\n * every session, so the cwd-slug never has to be derived/guessed.\n *\n * IMPORTANT — this is NOT tamper-proof. A determined agent can `cat >` a fake agent-*.meta.json. This\n * raises the bar from \"trust the model's word\" to \"deliberate, auditable forgery outside the repo\"; it\n * is not cryptographic. Say so wherever reviewer provenance is documented.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it is drawn in the DI design and injected by type.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class SubagentProvenanceService {\n // cwd → the branch it is PINNED to ('' when it is not a linked worktree, or is unresolvable).\n // See branchOfCwd for why it is cached and pinnedBranch for what \"pinned\" buys.\n private readonly branchByCwd = new Map<string, string>();\n\n // transcript path → its one scan. The credit pass and the evidence pass ask different questions of\n // the same (largest) files this service opens, and the credit pass may look at candidates the\n // evidence pass then re-visits. See scanTranscript for why one pass answers both.\n private readonly scanByPath = new Map<string, TranscriptScan>();\n\n // Verify EVERY expected checklist was reviewed by a reviewer subagent that ran on `context.branch` — the\n // coding agent may not self-certify. SKIPPED (pass) without a session id.\n //\n // ONE run may cover SEVERAL checklists: `reviewerAgents` is a required config field and is a CAP, so\n // grouping is always something the repo asked for. A run is still only credited when it is a real\n // subagent of the right type that ran on this branch.\n //\n // (A removed `sharedRuns` flag once demanded a distinct run per checklist; a cap is a MAXIMUM, so it never could.)\n // Either way a run that NAMED (or wp-write-review-submitted) this checklist's verdict is preferred over one that merely ran on the\n // branch, so each checklist is credited to the reviewer that actually wrote it whenever that is knowable.\n //\n // Scoped by BRANCH across ALL sessions (not the current session): once a reviewer ran on this branch in\n // any session, a later re-push in a NEW session still finds it, so the review is NOT forced to re-run.\n // That is what keeps \"review once per branch\" true across sessions. A PR opened outside the gated flow\n // still has no review-round<N>-<id>.json, so wp-finish forces the review regardless of provenance.\n verifyReviewers(expected: readonly ExpectedReviewer[], context: ReviewerContext): ProvenanceResult {\n if (expected.length === 0) return new ProvenanceResult(PROVENANCE_OK, 'no reviewer subagents required', {}, []);\n if (!this.inClaudeSession()) return this.skipped('reviewer subagents');\n const dirs = this.allSubagentsDirs();\n const missing: string[] = [];\n const usedAgentIds = new Set<string>();\n const credited: Record<string, string> = {};\n for (const want of expected) {\n const agentId = this.findMatchingAgentId(dirs, want, context, new Set<string>());\n if (agentId === '') missing.push(want.checklistId);\n else {\n usedAgentIds.add(agentId);\n credited[want.checklistId] = agentId;\n }\n }\n const runs = new Set(Object.values(credited)).size;\n return missing.length === 0\n ? new ProvenanceResult(PROVENANCE_OK,\n `verified ${expected.length} checklist(s) were reviewed by ${runs} reviewer subagent run(s)`, credited, [])\n : new ProvenanceResult(PROVENANCE_MISSING,\n `${missing.length} checklist(s) could not be attributed to a reviewer subagent on this branch: ${missing.join(', ')}`,\n credited, missing);\n }\n\n /**\n * What each credited reviewer actually READ, from its own transcript.\n *\n * `verifyReviewers` proves a reviewer of the right type RAN. It cannot tell a reviewer that read the diff\n * and thought about it from one that wrote a verdict having opened nothing. This closes that gap — and\n * the motivating case is real: one reviewer spent 14 of 26 tool calls grepping `node_modules` because\n * nothing had told it where anything was, which `offRepoSearches` now makes visible.\n *\n * WARNING-ONLY by default, for three reasons, and `requireDiffEvidence` must stay opt-in until at least\n * one repo has watched it:\n * 1. The transcript layout is undocumented Claude Code internals. A format change would wedge every\n * consumer's PR with no self-service recovery — `sidechainOnBranch` is already lenient for exactly\n * this reason, and blocking on a richer read of the same files would be less safe, not more.\n * 2. A reviewer can legitimately receive the diff another way (inlined into its prompt, say).\n * 3. verifyReviewers is the INTEGRITY signal and rightly blocks; this is a QUALITY signal. Conflating\n * them would let a transcript-parsing quirk refuse a PR that a real reviewer really did review.\n *\n * Returns [] outside a Claude Code session, matching verifyReviewers's SKIP behavior.\n */\n evidenceFor(context: ReviewerContext, expected: readonly ExpectedReviewer[], agentIds: Record<string, string>): ReviewerEvidence[] {\n if (!this.inClaudeSession()) return [];\n const dirs = this.allSubagentsDirs();\n const out: ReviewerEvidence[] = [];\n for (const want of expected) {\n const agentId = agentIds[want.checklistId];\n if (agentId === undefined) continue;\n const jsonl = this.transcriptPath(dirs, agentId);\n if (jsonl === '') {\n out.push(new ReviewerEvidence(want.checklistId, want.agentType, agentId));\n continue;\n }\n out.push(this.evidenceFromTranscript(want, agentId, jsonl, context));\n }\n return out;\n }\n\n // eslint-disable-next-line @typescript-eslint/max-params\n private evidenceFromTranscript(want: ExpectedReviewer, agentId: string, jsonl: string, context: ReviewerContext): ReviewerEvidence {\n const scan = this.scanTranscript(jsonl);\n const inputs = scan.inputs;\n const docPath = context.docPaths[want.checklistId] ?? '';\n const verdictPath = context.verdictPaths[want.checklistId] ?? '';\n return new ReviewerEvidence(\n want.checklistId, want.agentType, agentId, this.readDiffDir(scan, context),\n this.namesPath(scan, docPath),\n inputs.length,\n inputs.filter((i: string): boolean => i.includes('node_modules')).length,\n jsonl,\n scan.models,\n this.submittedVerdict(scan, want.checklistId, verdictPath),\n );\n }\n\n // The instructions file counts as \"read the diff\": it lives in the same per-branch dir, it is what\n // the reviewer is told to open first, and it inlines the diff paths. A reviewer that opened it and\n // then its own diff files is the intended path; treating only the diff dir as proof would flag it.\n private readDiffDir(scan: TranscriptScan, context: ReviewerContext): boolean {\n return this.namesPath(scan, context.diffDir);\n }\n\n /**\n * Did a tool input name `absPath` — absolutely, or RELATIVE to the transcript's own recorded `cwd`?\n *\n * Relative because that is how a reviewer whose cwd IS the repo root naturally spells it. Measured\n * (issue #1211): a reviewer read the diff forty times as `D=.webpieces/pr-review/<slug>/diff/files;\n * cat $D/...` and was refused as never having opened it, because only the absolute spelling matched.\n *\n * Still branch-specific: the relative form is derived from `absPath` itself, so it carries the same\n * `<featureSlug>`, and it is only tried when `absPath` lies UNDER the recorded cwd — i.e. when the\n * relative spelling, resolved where the harness says the reviewer stood, IS this file. A reviewer of\n * another branch names another slug; a reviewer standing in another tree resolves to another path.\n * The relative needle must START a path token, so `/other/root/.webpieces/...` cannot satisfy it as a\n * mere substring.\n */\n private namesPath(scan: TranscriptScan, absPath: string): boolean {\n if (absPath === '') return false;\n if (this.mentions(scan.inputs, absPath)) return true;\n if (scan.cwd === '' || !path.isAbsolute(scan.cwd)) return false;\n const relative = path.relative(scan.cwd, absPath);\n if (relative === '' || relative.startsWith('..') || path.isAbsolute(relative)) return false;\n const escaped = relative.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n // A token starts after whitespace, a quote, a shell separator, or JSON's own escaped `\\n` / `\\t`\n // (inputs are JSON-stringified, so a heredoc line break reaches here as a literal backslash-n).\n const token = new RegExp(`(?:^|[\\\\s\"'=(:;|&<>\\`]|\\\\\\\\[nt]|\\\\./)${escaped}`);\n return scan.inputs.some((i: string): boolean => token.test(i));\n }\n\n /**\n * Record this line's `message.model`, deduped, in first-seen order.\n *\n * `<synthetic>` records are SKIPPED. The harness writes them for messages no model produced (tool\n * results, injected notices); counting one would put a non-model in a field whose entire purpose is\n * \"which model reviewed this\", and it would show up on every single reviewer.\n */\n // webpieces-disable no-any-unknown -- opaque transcript record, only `model` is read and it is type-guarded below\n private collectModel(message: Record<string, unknown>, models: string[]): void {\n const model = message['model'];\n if (typeof model !== 'string' || model === '' || model === '<synthetic>') return;\n if (!models.includes(model)) models.push(model);\n }\n\n // The absolute path of agent-<id>.jsonl across all session dirs, or '' if it is not there.\n private transcriptPath(dirs: readonly string[], agentId: string): string {\n for (const dir of dirs) {\n const candidate = path.join(dir, `agent-${agentId}.jsonl`);\n if (fs.existsSync(candidate)) return candidate;\n }\n return '';\n }\n\n /**\n * ONE pass over the transcript for both answers (see {@link TranscriptScan}), CACHED per path.\n *\n * Cached because two passes now ask questions of the same file: crediting (does it name this branch's\n * verdict/diff?) and evidence (what did it read, which model served it?). Without the cache the credit\n * pass would re-read every candidate the evidence pass then re-opens — on the largest files this\n * service touches, on the path that opens a PR.\n *\n * Tool inputs are JSON-stringified rather than walked field-by-field because the shape differs per\n * tool (Read takes file_path, Bash takes command, Grep takes path) and a substring test over the\n * serialized input is both simpler and robust to a tool we have not seen.\n *\n * Best-effort, like everything else that parses this file: a format change must never wedge the\n * gate, so an unreadable transcript yields empty rather than throwing. That matters more for the\n * models than for the counters — this is quality telemetry, not an integrity check, and a missing\n * `model` field must not be able to block a PR.\n */\n private scanTranscript(jsonl: string): TranscriptScan {\n const cached = this.scanByPath.get(jsonl);\n if (cached !== undefined) return cached;\n const scan = this.readTranscript(jsonl);\n this.scanByPath.set(jsonl, scan);\n return scan;\n }\n\n private readTranscript(jsonl: string): TranscriptScan {\n const scan = new TranscriptScan();\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unreadable transcript yields no evidence, never a crash\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n for (const line of fs.readFileSync(jsonl, 'utf8').split('\\n')) {\n if (line.trim() === '') continue;\n const rec = this.parseLine(line);\n const cwd = rec?.['cwd'];\n if (scan.cwd === '' && typeof cwd === 'string') scan.cwd = cwd;\n const message = rec?.['message'];\n if (typeof message !== 'object' || message === null) continue;\n // webpieces-disable no-any-unknown -- opaque transcript record, narrowed by the guard above\n const msg = message as Record<string, unknown>;\n this.collectModel(msg, scan.models);\n const content = msg['content'];\n if (!Array.isArray(content)) continue;\n for (const block of content) {\n // webpieces-disable no-any-unknown -- opaque content block, only `type`/`input` are read\n const b = block as Record<string, unknown>;\n if (b['type'] === 'tool_use') scan.inputs.push(JSON.stringify(b['input'] ?? {}));\n }\n }\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n return scan;\n }\n\n private mentions(inputs: readonly string[], needle: string): boolean {\n return inputs.some((i: string): boolean => i.includes(needle));\n }\n\n // Are we running under Claude Code at all? (CI / plain terminal → provenance is unverifiable → SKIP.)\n private inClaudeSession(): boolean {\n return (process.env['CLAUDE_CODE_SESSION_ID'] ?? '').trim() !== '';\n }\n\n private skipped(what: string): ProvenanceResult {\n return new ProvenanceResult(PROVENANCE_SKIPPED,\n `CLAUDE_CODE_SESSION_ID not set — no Claude transcripts to verify ${what} against (Codex / terminal / CI); each verdict's wp-write-review provenance is still enforced.`,\n {}, []);\n }\n\n // The agentId of a subagent run on `branch`, searched across ALL sessions' subagent dirs\n // (branch-scoped, so a run from a prior session still counts). '' if none. `exclude` skips agentIds\n // already credited to another checklist so one run can't satisfy two.\n //\n // The run is NOT matched on its agent type — see isReviewerRun for why that check was removed — so\n // several runs match and the one that NAMED this checklist's verdict file wins; the first\n // branch-matching run is the fallback, as before.\n // eslint-disable-next-line @typescript-eslint/max-params\n private findMatchingAgentId(dirs: readonly string[], want: ExpectedReviewer, context: ReviewerContext, exclude: ReadonlySet<string>): string {\n let fallback = '';\n for (const dir of dirs) {\n for (const metaFile of this.metaFiles(dir)) {\n const agentId = this.agentIdOf(metaFile);\n if (exclude.has(agentId) || !this.isReviewerRun(dir, metaFile)) continue;\n if (!this.sidechainOnBranch(dir, agentId, want.checklistId, context)) continue;\n if (this.namedVerdict(dir, agentId, want.checklistId, context)) return agentId;\n if (fallback === '') fallback = agentId;\n }\n }\n return fallback;\n }\n\n /**\n * A harness-written meta for a REAL SUBAGENT — `spawnDepth >= 1`, and nothing about its NAME.\n *\n * The agent TYPE used to be compared against the configured reviewer agent, and that check is\n * gone (issue #964). It proved nothing: `agentType` is a label on a prompt, and it does not show\n * the agent read the checklist, opened the diff, or looked at the right branch. The gates that DO\n * show those are untouched — `spawnDepth >= 1` plus `isSidechain === true` (see\n * {@link sidechainOnBranch}) are harness-written, so the main loop still cannot self-certify;\n * {@link creditedByWhatItTouched} proves the branch and the actual work; `requireDiffEvidence`\n * proves the diff was opened.\n *\n * It was also the ONLY gate with an unfixable failure mode. Claude Code snapshots agent\n * definitions per session and the refresh does not reach an already-running subagent, so a repo\n * that renames its reviewer agent mid-session leaves that subagent's registry offering only the\n * OLD names: the spawn is rejected, the agent falls back to `general-purpose`, does the real\n * review, writes every verdict — and is refused as unattributable, with no cwd, branch or respawn\n * able to change it. Measured: six checklists, six verdict files on disk, PR blocked.\n *\n * Accepted trade-off: without the name check the implementer's own subagent could in principle be\n * credited, since it touches the diff dir while running the gate. That is deliberate. The rule is\n * \"if the verdict file is there, a subagent wrote it\", and this gate's job is to catch \"no\n * subagent ran at all\" — not to adjudicate which subagent it was.\n */\n private isReviewerRun(dir: string, metaFile: string): boolean {\n const meta = this.readJson(path.join(dir, metaFile));\n if (!meta) return false;\n const spawnDepth = meta['spawnDepth'];\n return typeof spawnDepth === 'number' && spawnDepth >= 1;\n }\n\n // Did this run's transcript name the checklist's own verdict path?\n // eslint-disable-next-line @typescript-eslint/max-params\n private namedVerdict(dir: string, agentId: string, checklistId: string, context: ReviewerContext): boolean {\n const jsonl = path.join(dir, `agent-${agentId}.jsonl`);\n return fs.existsSync(jsonl) && this.submittedVerdict(this.scanTranscript(jsonl), checklistId, context.verdictPaths[checklistId] ?? '');\n }\n\n // Named its verdict file, or submitted it via wp-write-review (#863). Proves authorship, never branch.\n private submittedVerdict(scan: TranscriptScan, checklistId: string, verdictPath: string): boolean {\n if (this.namesPath(scan, verdictPath)) return true;\n return this.invokedWriteReview(scan, checklistId);\n }\n\n private invokedWriteReview(scan: TranscriptScan, checklistId: string): boolean {\n return scan.inputs.some((i: string): boolean => reviewIdentityStamps.invokedChecklists(i).includes(checklistId));\n }\n\n /**\n * Every `<config>/projects/&#42;/<session>/subagents` dir that exists — matching by the recorded\n * gitBranch (not by session id) is what makes provenance survive across sessions.\n *\n * `<config>` comes from {@link ClaudeConfigDir.projectsRoots}, which is BOTH the configured\n * `$CLAUDE_CONFIG_DIR` tree and `~/.claude`. This used to be a hardcoded `~/.claude`, and on a\n * machine with a relocated config dir that found nothing at all — so every PR was refused with a\n * message about the reviewers' cwd, which is not what was wrong and which no agent could act on.\n */\n private allSubagentsDirs(): string[] {\n const out: string[] = [];\n for (const projects of claudeConfigDir.projectsRoots()) {\n for (const proj of this.readDir(projects)) {\n const projDir = path.join(projects, proj);\n for (const session of this.readDir(projDir)) {\n const candidate = path.join(projDir, session, 'subagents');\n if (fs.existsSync(candidate)) out.push(candidate);\n }\n }\n }\n return out;\n }\n\n private metaFiles(dir: string): string[] {\n return this.readDir(dir).filter((f: string): boolean => f.endsWith('.meta.json'));\n }\n\n // agent-<id>.meta.json → <id>\n private agentIdOf(metaFile: string): string {\n return metaFile.replace(/^agent-/, '').replace(/\\.meta\\.json$/, '');\n }\n\n /**\n * Cross-check the sibling transcript's record 0: isSidechain true (a real subagent, not the main\n * loop) and the same branch. Lenient on branch drift (a leftover …wpN suffix from a mid-flight\n * branch rename) and on a missing jsonl (meta already matched — accept, best-effort).\n *\n * WHEN `gitBranch` DISAGREES, A PINNED `cwd` DECIDES. Record 0 carries both fields, and the harness\n * can write a `gitBranch` that CONTRADICTS the record's own `cwd`: a reviewer subagent spawned into\n * a worktree on `dean/one-2406-…` was stamped `worktree-agent-a54887200e40eb956` — an unrelated,\n * still-live worktree's scaffold branch — deterministically, on four consecutive attempts, blocking\n * a PR whose required reviewer genuinely ran and genuinely passed. `stripWp` cannot bridge that, so\n * the reviewer was never credited and `wp-finish-upsert-pr` refused a legitimately-reviewed PR with\n * no in-flow recovery. A sweep of 961 record-0s on one machine found the mis-stamp is the MAJORITY\n * case among subagents in dedicated worktrees, so trusting `gitBranch` alone can never be correct.\n *\n * ─── Why ONLY a linked worktree, and never the primary clone ──────────────────────────────────\n * \"Ask git what branch the cwd is on\" is correct only when that cwd CANNOT have moved since the\n * reviewer ran. A LINKED WORKTREE is 1:1 with the agent that owns it and nothing re-checks it out;\n * the PRIMARY CLONE gets checked out constantly. Falling back on a primary-clone cwd would credit a\n * STALE reviewer, and by construction rather than by accident:\n *\n * 1. a reviewer runs in the primary clone while it is on branch A\n * 2. the clone is later checked out to branch B\n * 3. `wp-finish-upsert-pr` runs on B — `gitBranch` (stamped A) mismatches\n * 4. `git -C <clone>` now answers B, because the CLONE moved → the reviewer is credited for B\n *\n * It reviewed A. Every past reviewer run in that clone would be credited for whatever branch is\n * checked out at finish time — which in a repo with a required reviewer on every PR is not an\n * exotic sequence, it is the normal one. So the fallback is gated on `dotWebpieces.isLinkedWorktree`\n * (git's own `--git-dir != --git-common-dir` test, reused rather than re-derived), and a primary\n * clone falls through to a refusal exactly as it does today.\n *\n * That gate keeps the anti-forgery property intact: `cwd` is harness-written in the same record by\n * the same writer as `gitBranch`, so it carries the same weight — and inside a pinned worktree it is\n * the field that is CORRECT. There is deliberately no config flag and no second comparison mode:\n * ONE rule, with `gitBranch` only ever a cheap way to skip the subprocess when it already agrees.\n *\n * An UNRESOLVABLE cwd does not credit either. A reaped worktree, a deleted directory, a non-repo\n * path or a detached HEAD yields '' and falls through to a refusal. Leniency here is bounded by\n * \"git can still prove it\", never by \"we could not check, so assume yes\".\n *\n * ─── Why neither field can settle it from a PRIMARY CLONE, and what does ──────────────────────\n * Both fields above are stamped from the SPAWNING session's cwd — the Agent tool has no cwd\n * parameter, so a subagent inherits its parent's. A session rooted in the primary clone that spawns\n * a reviewer for a WORKTREE branch therefore produces `gitBranch` = the clone's branch (mismatch)\n * and `cwd` = the clone (gated off, correctly) — and NO respawn can change either stamp. That is not\n * an exotic setup: it is what the flow instructs the moment a worker agent dies mid-flow and the\n * top-level session has to take over, and it deadlocked a branch whose seven reviewers had all run.\n *\n * So the third channel is not a loosening of the cwd rule — it is a DIFFERENT question, asked of\n * evidence the reviewer cannot inherit and cannot fake by accident: {@link creditedByWhatItTouched}.\n */\n // eslint-disable-next-line @typescript-eslint/max-params\n private sidechainOnBranch(dir: string, agentId: string, checklistId: string, context: ReviewerContext): boolean {\n const jsonl = path.join(dir, `agent-${agentId}.jsonl`);\n if (!fs.existsSync(jsonl)) return true;\n const first = this.firstNonEmptyLine(jsonl);\n if (first === '') return true;\n const rec = this.parseLine(first);\n if (!rec) return true;\n if (rec['isSidechain'] !== true) return false;\n const gitBranch = rec['gitBranch'];\n // Not recorded at all → accept, as before: nothing to contradict and nothing to verify against.\n if (typeof gitBranch !== 'string' || gitBranch === '') return true;\n const want = this.stripWp(context.branch);\n if (this.stripWp(gitBranch) === want) return true;\n if (want !== '' && this.stripWp(this.branchOfCwd(rec['cwd'])) === want) return true;\n return this.creditedByWhatItTouched(jsonl, agentId, checklistId, context);\n }\n\n /**\n * Credit a reviewer for WHAT IT TOUCHED when neither harness-stamped field can settle it.\n *\n * Both paths compared here are ABSOLUTE and BRANCH-SPECIFIC — they live under\n * `<worktree>/.webpieces/pr-review/<featureSlug>/`, so the string names the tree AND the branch. A\n * reviewer that worked on a different branch cannot have them in its transcript, and a reviewer of\n * this branch that ran from a mis-stamped cwd cannot avoid having them. That is the property\n * `gitBranch` lacks — this file's own sweep of 961 record-0s found the mis-stamp is the MAJORITY\n * case among subagents in dedicated worktrees.\n *\n * Three channels, any one sufficient:\n * 1. it WROTE this checklist's verdict file — proves branch AND checklist, and is the act the whole\n * gate is trying to attribute. Matched as a substring of any tool input, so a Write, an Edit and\n * a `cat > <path>` heredoc all count; the point is that the path was named, not which tool named it.\n * 2. it READ this branch's materialized diff dir — proves the branch. Kept as a second channel\n * because a reviewer whose verdict was relayed by its parent still demonstrably reviewed this\n * branch, and refusing that would re-open a narrower version of the same unrecoverable deadlock.\n * 3. it SUBMITTED this checklist through `pnpm wp-write-review --checklist <id>` AND this branch's\n * verdict provenance names this very agentId as the submitter (issue #1211). The invocation alone\n * proves authorship of some verdict, not which branch's — checklist ids are shared by every branch —\n * so the bin's own record is what ties it to this one. See {@link ReviewerContext.submittedBy}.\n *\n * Channels 1 and 2 match a path absolutely or relative to the transcript's recorded cwd; see\n * {@link namesPath}. The measured miss behind both additions: a reviewer with cwd = the repo root read\n * the diff through a relative path and submitted through wp-write-review, and was refused on all four\n * checklists because its gitBranch carried a DIFFERENT concurrent worktree's branch.\n *\n * Independence is NOT weakened by either: `isSidechain === true` and `spawnDepth >= 1` are checked\n * before we get here (so the main loop's own transcript can never qualify), and `verifyReviewers`\n * excludes an agentId already credited to another checklist. It remains non-tamper-proof in exactly\n * the way the class doc already states — forging this now means forging a transcript rather than a\n * meta.json, which is the same bar, not a lower one.\n */\n // eslint-disable-next-line @typescript-eslint/max-params\n private creditedByWhatItTouched(jsonl: string, agentId: string, checklistId: string, context: ReviewerContext): boolean {\n const scan = this.scanTranscript(jsonl);\n if (this.namesPath(scan, context.verdictPaths[checklistId] ?? '')) return true;\n if (this.readDiffDir(scan, context)) return true;\n const submitter = context.submittedBy[checklistId] ?? '';\n return submitter !== '' && submitter === agentId && this.invokedWriteReview(scan, checklistId);\n }\n\n /**\n * The branch record-0's own `cwd` is PINNED to, '' when that cannot be established or is not pinned.\n *\n * Cached per cwd because `findMatchingAgentId` walks every subagent of every session on the machine\n * and several of them share a worktree — one `git` process per RECORD would put dozens of spawns on\n * the path that opens a PR.\n */\n // webpieces-disable no-any-unknown -- one opaque record field, type-guarded on the next line\n private branchOfCwd(cwd: unknown): string {\n if (typeof cwd !== 'string' || cwd === '') return '';\n const cached = this.branchByCwd.get(cwd);\n if (cached !== undefined) return cached;\n const resolved = this.pinnedBranch(cwd);\n this.branchByCwd.set(cwd, resolved);\n return resolved;\n }\n\n /**\n * The branch of `cwd` when — and only when — `cwd` is a LINKED WORKTREE. '' otherwise.\n *\n * '' for the primary clone (it moves; see sidechainOnBranch for the false-accept that closes), for a\n * reaped or deleted directory, for a non-repo path, when git is unavailable, and for a detached HEAD,\n * which `--abbrev-ref` prints as the literal `HEAD` and which names no branch.\n */\n private pinnedBranch(cwd: string): string {\n if (!fs.existsSync(cwd)) return '';\n if (!dotWebpieces.isLinkedWorktree(cwd)) return '';\n const result = spawnSync('git', ['-C', cwd, 'rev-parse', '--abbrev-ref', 'HEAD'], { encoding: 'utf8' });\n if (result.status !== 0) return '';\n const printed = (result.stdout ?? '').trim();\n return printed === 'HEAD' ? '' : printed;\n }\n\n private stripWp(branch: string): string {\n return branch.replace(/-?wp\\d+$/i, '');\n }\n\n private readDir(dir: string): string[] {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unreadable dir yields [] (best-effort provenance)\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return fs.readdirSync(dir);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return [];\n }\n }\n\n private firstNonEmptyLine(filePath: string): string {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: unreadable transcript → '' (best-effort)\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n for (const line of fs.readFileSync(filePath, 'utf8').split('\\n')) {\n if (line.trim() !== '') return line;\n }\n return '';\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return '';\n }\n }\n\n // webpieces-disable no-any-unknown -- opaque parsed JSON object, keys read by the caller\n private readJson(filePath: string): Record<string, unknown> | null {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: malformed meta.json → null (skipped)\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // webpieces-disable no-any-unknown -- parsed JSON is opaque until narrowed by the caller\n return JSON.parse(fs.readFileSync(filePath, 'utf8')) as Record<string, unknown>;\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n\n // webpieces-disable no-any-unknown -- one opaque JSONL record, keys read by the caller\n private parseLine(line: string): Record<string, unknown> | null {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: malformed JSONL record → null\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // webpieces-disable no-any-unknown -- parsed JSON is opaque until narrowed by the caller\n return JSON.parse(line) as Record<string, unknown>;\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n}\n"]}
1
+ {"version":3,"file":"subagent-provenance.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/subagent-provenance.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAC3D,8DAA4D;AAC5D,iEAA6D;AAC7D,8DAAuE;AACvE,sEAAqE;AAErE,iCAAiC;AACpB,QAAA,aAAa,GAAG,IAAI,CAAC,CAAW,+DAA+D;AAC/F,QAAA,kBAAkB,GAAG,SAAS,CAAC,CAAC,0EAA0E;AAC1G,QAAA,kBAAkB,GAA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AC;YACD,yFAAyF;YACzF,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAA4B,CAAC;QACvD,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,KAAK,KAAK,CAAC;YACX,OAAO,IAAI,CAAC;QAChB,CAAC;IACL,CAAC;CACJ,CAAA;AAlhBY,8DAAyB;oCAAzB,yBAAyB;IADrC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;GAC5B,yBAAyB,CAkhBrC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { claudeConfigDir } from '@webpieces/tooling-common';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { gitCheckout, DETACHED_HEAD } from '@webpieces/tooling-common';\nimport { reviewIdentityStamps } from '@webpieces/repo-workflow-core';\n\n// Outcome of a provenance check.\nexport const PROVENANCE_OK = 'ok'; // a matching reviewer subagent demonstrably ran on this branch\nexport const PROVENANCE_MISSING = 'missing'; // session known, but no matching subagent artifact found → refuse (BLOCK)\nexport const PROVENANCE_SKIPPED = 'skipped'; // no CLAUDE_CODE_SESSION_ID → transcript evidence skipped; wp-write-review provenance still enforced (#863)\n\nexport class ProvenanceResult {\n status: string; // PROVENANCE_OK | PROVENANCE_MISSING | PROVENANCE_SKIPPED\n detail: string; // human-readable explanation for the warning/error/dashboard\n // agentIds credited, keyed by CHECKLIST ID, so an evidence pass does not re-scan to find them again. Two\n // checklists may map to the same agentId when `reviewerAgents` let one subagent cover both.\n agentIds: Record<string, string>;\n /**\n * The checklist ids that could NOT be credited — the FACT, with no remedy attached.\n *\n * Structured rather than only spelled into `detail` because the remedy depends on something this\n * service cannot see: whether that reviewer already wrote a verdict file. \"It never ran\" and \"it ran\n * and cannot be attributed\" need OPPOSITE instructions — spawn one, versus do not re-spawn into this\n * round, because a round's verdict is never overwritten and the re-spawn records nothing. Handing the caller a pre-worded\n * imperative is what produced the destructive loop this field exists to end; see ProvenanceEnforcer.\n */\n missing: string[];\n\n /**\n * `agentIds` and `missing` are REQUIRED, with no defaults.\n *\n * A default on `missing` is what made the dangerous state cheap to reach: the caller BLOCKS on this\n * list, so a `PROVENANCE_MISSING` built without it would report unverified and refuse NOTHING — a\n * silent pass, one forgotten argument away. Required parameters make the omission a compile error at\n * every construction site, present and future. The remaining `missing: []` on a blocking status is\n * caught by the caller, which refuses on the STATUS and falls back to `detail`; see\n * ProvenanceEnforcer.refuse.\n */\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(status: string, detail: string, agentIds: Record<string, string>, missing: string[]) {\n this.status = status;\n this.detail = detail;\n this.agentIds = agentIds;\n this.missing = missing;\n }\n}\n\n/**\n * What ONE credited reviewer actually DID, read from its own transcript. Data-only (per CLAUDE.md).\n *\n * `verifyReviewers` answers \"did a reviewer of this type run?\" — an INTEGRITY question, and it blocks. This\n * answers \"did it look at the change?\" — a QUALITY question, and it only warns. The distinction is\n * deliberate; see {@link SubagentProvenanceService.evidenceFor}.\n */\nexport class ReviewerEvidence {\n checklistId: string; // the checklist this evidence is FOR (one subagent may appear under several)\n agentType: string;\n agentId: string;\n readDiff: boolean; // opened the materialized diff dir (or its own instructions file)\n readDoc: boolean; // opened its checklist's guidance doc\n /**\n * Named its own verdict file — `.webpieces/pr-review/<featureSlug>/review-round<N>-<id>.json` — in a tool input.\n *\n * Recorded, not just consumed, because it is the field that answers \"who wrote this verdict?\" for an\n * auditor reading provenance.json later. It is also a CREDIT channel: see\n * {@link SubagentProvenanceService.creditedByWhatItTouched}.\n */\n wroteVerdict: boolean;\n toolCallCount: number;\n offRepoSearches: number; // tool calls that reached into node_modules — the archaeology signal\n /**\n * Distinct `message.model` values OBSERVED in the transcript, in first-seen order.\n *\n * The model that actually ran, never the one that was configured — and never anything the reviewer\n * says about itself. The reviewer agent's `.claude/agents/<name>.md` may declare `model:`, but that is the\n * REQUESTED value and it can silently disagree with what served the request: a repo was measured\n * running opus for a reviewer whose agent file said `model: sonnet`. Asking the model instead would\n * be worse — a model is unreliable about its own identity, naming a family instead of a version or\n * repeating whatever the system prompt implied, so a self-reported field is usually right and\n * silently wrong, which is the worst kind of telemetry because it looks authoritative.\n * `message.model` is written by the harness, so this inherits the anti-forgery property the rest of\n * this class documents.\n *\n * An ARRAY, not a string: one reviewer run can span more than one model (a fallback after a refusal,\n * a mid-run config change). Collapsing to one value forces a lossy choice at read time; recording\n * what happened lets the renderer decide.\n *\n * Token counts and cost are deliberately NOT here. Prices change, vary by platform and differ under\n * intro pricing, so a rate table in this package would rot silently — and the question this answers\n * is \"which model reviewed this?\", not \"what did it cost?\".\n */\n models: string[];\n // Absolute path of the transcript these counters were read out of, '' when it could not be resolved.\n // Carried out rather than recomputed because a reviewer subagent cannot learn its own transcript path\n // (the environment exposes the PARENT session id and no agent id), so this is the only place it is\n // known — see ReviewProvenanceService, which records it as the audit link for the verdict.\n transcriptPath: string;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(checklistId: string, agentType: string, agentId: string, readDiff = false, readDoc = false, toolCallCount = 0, offRepoSearches = 0, transcriptPath = '', models: string[] = [], wroteVerdict = false) {\n this.checklistId = checklistId;\n this.agentType = agentType;\n this.agentId = agentId;\n this.readDiff = readDiff;\n this.readDoc = readDoc;\n this.wroteVerdict = wroteVerdict;\n this.toolCallCount = toolCallCount;\n this.offRepoSearches = offRepoSearches;\n this.transcriptPath = transcriptPath;\n this.models = models;\n }\n}\n\n/**\n * One pass over one transcript: the tool inputs AND the models that served it. Data-only.\n *\n * They are gathered together rather than in two passes because they come from the SAME records — the\n * inputs from `message.content[].input`, the model from `message.model` one level up — and a transcript\n * is the largest file this service opens. Two reads of it to answer two questions about the same lines\n * would be the duplicate-work trap the diff materializer documents at length.\n */\nexport class TranscriptScan {\n inputs: string[]; // every tool_use input, JSON-stringified\n models: string[]; // distinct message.model values, first-seen order\n /**\n * The harness-written `cwd` of the transcript's FIRST record that carries one ('' when none does) —\n * what a relative path in a tool input resolves against. See\n * {@link SubagentProvenanceService.namesPath} for why a relative path has to be matched at all.\n */\n cwd: string;\n\n constructor(inputs: string[] = [], models: string[] = [], cwd = '') {\n this.inputs = inputs;\n this.models = models;\n this.cwd = cwd;\n }\n}\n\n/**\n * WHERE this branch's review materials live. Data-only.\n *\n * One class for BOTH passes — crediting (`verifyReviewers`) and evidence (`evidenceFor`) — because they\n * ask their questions of the same paths. `diffDir` is the per-branch materialization\n * (`.webpieces/pr-review/<featureSlug>/diff`), which is what makes it usable as PROOF of which branch a\n * reviewer looked at: the path names the branch, it is absolute, and stage ② recreates it per run.\n */\nexport class ReviewerContext {\n branch: string;\n diffDir: string; // '' when nothing was materialized\n docPaths: Record<string, string>; // checklist id → its checklist doc path ('' when none)\n /**\n * checklist id → the absolute path of the verdict file THAT checklist must write on THIS branch\n * (`.webpieces/pr-review/<featureSlug>/review-round<N>-<id>.json`). '' when unknown.\n *\n * The strongest attribution signal available, and stronger than `diffDir`: the path is\n * worktree-absolute (naming the tree), per-branch (naming the featureSlug) AND per-checklist (naming\n * the id), so a transcript containing it can only belong to a reviewer that authored that checklist's\n * verdict for that branch. `diffDir` proves the branch but not the checklist.\n */\n verdictPaths: Record<string, string>;\n /**\n * checklist id → the agentId `pnpm wp-write-review` recorded in THIS branch's verdict provenance\n * (`review-round<N>-<id>.provenance.json`); absent when there is none.\n *\n * What makes a `wp-write-review --checklist <id>` invocation in a transcript BRANCH-specific. The command\n * line names only the checklist, and checklist ids are shared by every branch (a universal checklist is\n * reviewed on every PR), so an invocation alone proves authorship of SOME verdict, never which branch's.\n * The bin wrote this branch's verdict from the harness's own `agent_id` for that call, so a transcript\n * of that same agentId that invoked it is the reviewer that submitted this branch's verdict.\n */\n submittedBy: Record<string, string>;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(branch: string, diffDir = '', docPaths: Record<string, string> = {}, verdictPaths: Record<string, string> = {}, submittedBy: Record<string, string> = {}) {\n this.branch = branch;\n this.diffDir = diffDir;\n this.docPaths = docPaths;\n this.verdictPaths = verdictPaths;\n this.submittedBy = submittedBy;\n }\n}\n\n/**\n * One checklist that must be credited to a reviewer run, plus the agent type the BRIEFING named. Data-only.\n *\n * The two used to be one string — a checklist's id WAS its agent type — and provenance keyed everything by\n * it. Now every checklist is reviewed by the same repo-wide agent type, so the id and the type are\n * separate facts.\n *\n * `agentType` is NOT a provenance input: nothing here matches a run on it (issue #964, see\n * {@link SubagentProvenanceService.isReviewerRun}). It is carried because it is what the BRIEFING told\n * the agent to spawn and what {@link ReviewerEvidence} reports, which are both worth recording even\n * though neither is worth gating on.\n */\nexport class ExpectedReviewer {\n checklistId: string;\n agentType: string;\n\n constructor(checklistId: string, agentType: string) {\n this.checklistId = checklistId;\n this.agentType = agentType;\n }\n}\n\n/**\n * Verifies — from the Claude Code harness's OWN artifacts, never from anything the model asserts — that\n * a real SUBAGENT actually ran on the current branch and did this checklist's work. Used to enforce that\n * every checklist was reviewed by an INDEPENDENT reviewer, rather than by the coding agent\n * self-certifying.\n *\n * The harness writes, beside each subagent transcript:\n * <config>/projects/<cwd-slug>/<sessionId>/subagents/agent-<id>.meta.json → { agentType, spawnDepth, … }\n * <config>/projects/<cwd-slug>/<sessionId>/subagents/agent-<id>.jsonl → record 0 { isSidechain, gitBranch, … }\n * `spawnDepth`/`isSidechain` are written by Claude Code, not by the model, and they are what carries the\n * anti-self-certification property. `agentType` is written there too and is deliberately NOT checked —\n * see {@link SubagentProvenanceService.isReviewerRun}. `<config>` is `$CLAUDE_CONFIG_DIR` when set, else\n * `~/.claude`; see {@link ClaudeConfigDir}, and never re-derive it here. Dirs are found by walking\n * every session, so the cwd-slug never has to be derived/guessed.\n *\n * IMPORTANT — this is NOT tamper-proof. A determined agent can `cat >` a fake agent-*.meta.json. This\n * raises the bar from \"trust the model's word\" to \"deliberate, auditable forgery outside the repo\"; it\n * is not cryptographic. Say so wherever reviewer provenance is documented.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it is drawn in the DI design and injected by type.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class SubagentProvenanceService {\n // cwd → the branch it is PINNED to ('' when it is not a linked worktree, or is unresolvable).\n // See branchOfCwd for why it is cached and pinnedBranch for what \"pinned\" buys.\n private readonly branchByCwd = new Map<string, string>();\n\n // transcript path → its one scan. The credit pass and the evidence pass ask different questions of\n // the same (largest) files this service opens, and the credit pass may look at candidates the\n // evidence pass then re-visits. See scanTranscript for why one pass answers both.\n private readonly scanByPath = new Map<string, TranscriptScan>();\n\n // Verify EVERY expected checklist was reviewed by a reviewer subagent that ran on `context.branch` — the\n // coding agent may not self-certify. SKIPPED (pass) without a session id.\n //\n // ONE run may cover SEVERAL checklists: `reviewerAgents` is a required config field and is a CAP, so\n // grouping is always something the repo asked for. A run is still only credited when it is a real\n // subagent of the right type that ran on this branch.\n //\n // (A removed `sharedRuns` flag once demanded a distinct run per checklist; a cap is a MAXIMUM, so it never could.)\n // Either way a run that NAMED (or wp-write-review-submitted) this checklist's verdict is preferred over one that merely ran on the\n // branch, so each checklist is credited to the reviewer that actually wrote it whenever that is knowable.\n //\n // Scoped by BRANCH across ALL sessions (not the current session): once a reviewer ran on this branch in\n // any session, a later re-push in a NEW session still finds it, so the review is NOT forced to re-run.\n // That is what keeps \"review once per branch\" true across sessions. A PR opened outside the gated flow\n // still has no review-round<N>-<id>.json, so wp-finish forces the review regardless of provenance.\n verifyReviewers(expected: readonly ExpectedReviewer[], context: ReviewerContext): ProvenanceResult {\n if (expected.length === 0) return new ProvenanceResult(PROVENANCE_OK, 'no reviewer subagents required', {}, []);\n if (!this.inClaudeSession()) return this.skipped('reviewer subagents');\n const dirs = this.allSubagentsDirs();\n const missing: string[] = [];\n const usedAgentIds = new Set<string>();\n const credited: Record<string, string> = {};\n for (const want of expected) {\n const agentId = this.findMatchingAgentId(dirs, want, context, new Set<string>());\n if (agentId === '') missing.push(want.checklistId);\n else {\n usedAgentIds.add(agentId);\n credited[want.checklistId] = agentId;\n }\n }\n const runs = new Set(Object.values(credited)).size;\n return missing.length === 0\n ? new ProvenanceResult(PROVENANCE_OK,\n `verified ${expected.length} checklist(s) were reviewed by ${runs} reviewer subagent run(s)`, credited, [])\n : new ProvenanceResult(PROVENANCE_MISSING,\n `${missing.length} checklist(s) could not be attributed to a reviewer subagent on this branch: ${missing.join(', ')}`,\n credited, missing);\n }\n\n /**\n * What each credited reviewer actually READ, from its own transcript.\n *\n * `verifyReviewers` proves a reviewer of the right type RAN. It cannot tell a reviewer that read the diff\n * and thought about it from one that wrote a verdict having opened nothing. This closes that gap — and\n * the motivating case is real: one reviewer spent 14 of 26 tool calls grepping `node_modules` because\n * nothing had told it where anything was, which `offRepoSearches` now makes visible.\n *\n * WARNING-ONLY by default, for three reasons, and `requireDiffEvidence` must stay opt-in until at least\n * one repo has watched it:\n * 1. The transcript layout is undocumented Claude Code internals. A format change would wedge every\n * consumer's PR with no self-service recovery — `sidechainOnBranch` is already lenient for exactly\n * this reason, and blocking on a richer read of the same files would be less safe, not more.\n * 2. A reviewer can legitimately receive the diff another way (inlined into its prompt, say).\n * 3. verifyReviewers is the INTEGRITY signal and rightly blocks; this is a QUALITY signal. Conflating\n * them would let a transcript-parsing quirk refuse a PR that a real reviewer really did review.\n *\n * Returns [] outside a Claude Code session, matching verifyReviewers's SKIP behavior.\n */\n evidenceFor(context: ReviewerContext, expected: readonly ExpectedReviewer[], agentIds: Record<string, string>): ReviewerEvidence[] {\n if (!this.inClaudeSession()) return [];\n const dirs = this.allSubagentsDirs();\n const out: ReviewerEvidence[] = [];\n for (const want of expected) {\n const agentId = agentIds[want.checklistId];\n if (agentId === undefined) continue;\n const jsonl = this.transcriptPath(dirs, agentId);\n if (jsonl === '') {\n out.push(new ReviewerEvidence(want.checklistId, want.agentType, agentId));\n continue;\n }\n out.push(this.evidenceFromTranscript(want, agentId, jsonl, context));\n }\n return out;\n }\n\n // eslint-disable-next-line @typescript-eslint/max-params\n private evidenceFromTranscript(want: ExpectedReviewer, agentId: string, jsonl: string, context: ReviewerContext): ReviewerEvidence {\n const scan = this.scanTranscript(jsonl);\n const inputs = scan.inputs;\n const docPath = context.docPaths[want.checklistId] ?? '';\n const verdictPath = context.verdictPaths[want.checklistId] ?? '';\n return new ReviewerEvidence(\n want.checklistId, want.agentType, agentId, this.readDiffDir(scan, context),\n this.namesPath(scan, docPath),\n inputs.length,\n inputs.filter((i: string): boolean => i.includes('node_modules')).length,\n jsonl,\n scan.models,\n this.submittedVerdict(scan, want.checklistId, verdictPath),\n );\n }\n\n // The instructions file counts as \"read the diff\": it lives in the same per-branch dir, it is what\n // the reviewer is told to open first, and it inlines the diff paths. A reviewer that opened it and\n // then its own diff files is the intended path; treating only the diff dir as proof would flag it.\n private readDiffDir(scan: TranscriptScan, context: ReviewerContext): boolean {\n return this.namesPath(scan, context.diffDir);\n }\n\n /**\n * Did a tool input name `absPath` — absolutely, or RELATIVE to the transcript's own recorded `cwd`?\n *\n * Relative because that is how a reviewer whose cwd IS the repo root naturally spells it. Measured\n * (issue #1211): a reviewer read the diff forty times as `D=.webpieces/pr-review/<slug>/diff/files;\n * cat $D/...` and was refused as never having opened it, because only the absolute spelling matched.\n *\n * Still branch-specific: the relative form is derived from `absPath` itself, so it carries the same\n * `<featureSlug>`, and it is only tried when `absPath` lies UNDER the recorded cwd — i.e. when the\n * relative spelling, resolved where the harness says the reviewer stood, IS this file. A reviewer of\n * another branch names another slug; a reviewer standing in another tree resolves to another path.\n * The relative needle must START a path token, so `/other/root/.webpieces/...` cannot satisfy it as a\n * mere substring.\n */\n private namesPath(scan: TranscriptScan, absPath: string): boolean {\n if (absPath === '') return false;\n if (this.mentions(scan.inputs, absPath)) return true;\n if (scan.cwd === '' || !path.isAbsolute(scan.cwd)) return false;\n const relative = path.relative(scan.cwd, absPath);\n if (relative === '' || relative.startsWith('..') || path.isAbsolute(relative)) return false;\n const escaped = relative.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n // A token starts after whitespace, a quote, a shell separator, or JSON's own escaped `\\n` / `\\t`\n // (inputs are JSON-stringified, so a heredoc line break reaches here as a literal backslash-n).\n const token = new RegExp(`(?:^|[\\\\s\"'=(:;|&<>\\`]|\\\\\\\\[nt]|\\\\./)${escaped}`);\n return scan.inputs.some((i: string): boolean => token.test(i));\n }\n\n /**\n * Record this line's `message.model`, deduped, in first-seen order.\n *\n * `<synthetic>` records are SKIPPED. The harness writes them for messages no model produced (tool\n * results, injected notices); counting one would put a non-model in a field whose entire purpose is\n * \"which model reviewed this\", and it would show up on every single reviewer.\n */\n // webpieces-disable no-any-unknown -- opaque transcript record, only `model` is read and it is type-guarded below\n private collectModel(message: Record<string, unknown>, models: string[]): void {\n const model = message['model'];\n if (typeof model !== 'string' || model === '' || model === '<synthetic>') return;\n if (!models.includes(model)) models.push(model);\n }\n\n // The absolute path of agent-<id>.jsonl across all session dirs, or '' if it is not there.\n private transcriptPath(dirs: readonly string[], agentId: string): string {\n for (const dir of dirs) {\n const candidate = path.join(dir, `agent-${agentId}.jsonl`);\n if (fs.existsSync(candidate)) return candidate;\n }\n return '';\n }\n\n /**\n * ONE pass over the transcript for both answers (see {@link TranscriptScan}), CACHED per path.\n *\n * Cached because two passes now ask questions of the same file: crediting (does it name this branch's\n * verdict/diff?) and evidence (what did it read, which model served it?). Without the cache the credit\n * pass would re-read every candidate the evidence pass then re-opens — on the largest files this\n * service touches, on the path that opens a PR.\n *\n * Tool inputs are JSON-stringified rather than walked field-by-field because the shape differs per\n * tool (Read takes file_path, Bash takes command, Grep takes path) and a substring test over the\n * serialized input is both simpler and robust to a tool we have not seen.\n *\n * Best-effort, like everything else that parses this file: a format change must never wedge the\n * gate, so an unreadable transcript yields empty rather than throwing. That matters more for the\n * models than for the counters — this is quality telemetry, not an integrity check, and a missing\n * `model` field must not be able to block a PR.\n */\n private scanTranscript(jsonl: string): TranscriptScan {\n const cached = this.scanByPath.get(jsonl);\n if (cached !== undefined) return cached;\n const scan = this.readTranscript(jsonl);\n this.scanByPath.set(jsonl, scan);\n return scan;\n }\n\n private readTranscript(jsonl: string): TranscriptScan {\n const scan = new TranscriptScan();\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unreadable transcript yields no evidence, never a crash\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n for (const line of fs.readFileSync(jsonl, 'utf8').split('\\n')) {\n if (line.trim() === '') continue;\n const rec = this.parseLine(line);\n const cwd = rec?.['cwd'];\n if (scan.cwd === '' && typeof cwd === 'string') scan.cwd = cwd;\n const message = rec?.['message'];\n if (typeof message !== 'object' || message === null) continue;\n // webpieces-disable no-any-unknown -- opaque transcript record, narrowed by the guard above\n const msg = message as Record<string, unknown>;\n this.collectModel(msg, scan.models);\n const content = msg['content'];\n if (!Array.isArray(content)) continue;\n for (const block of content) {\n // webpieces-disable no-any-unknown -- opaque content block, only `type`/`input` are read\n const b = block as Record<string, unknown>;\n if (b['type'] === 'tool_use') scan.inputs.push(JSON.stringify(b['input'] ?? {}));\n }\n }\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n return scan;\n }\n\n private mentions(inputs: readonly string[], needle: string): boolean {\n return inputs.some((i: string): boolean => i.includes(needle));\n }\n\n // Are we running under Claude Code at all? (CI / plain terminal → provenance is unverifiable → SKIP.)\n private inClaudeSession(): boolean {\n return (process.env['CLAUDE_CODE_SESSION_ID'] ?? '').trim() !== '';\n }\n\n private skipped(what: string): ProvenanceResult {\n return new ProvenanceResult(PROVENANCE_SKIPPED,\n `CLAUDE_CODE_SESSION_ID not set — no Claude transcripts to verify ${what} against (Codex / terminal / CI); each verdict's wp-write-review provenance is still enforced.`,\n {}, []);\n }\n\n // The agentId of a subagent run on `branch`, searched across ALL sessions' subagent dirs\n // (branch-scoped, so a run from a prior session still counts). '' if none. `exclude` skips agentIds\n // already credited to another checklist so one run can't satisfy two.\n //\n // The run is NOT matched on its agent type — see isReviewerRun for why that check was removed — so\n // several runs match and the one that NAMED this checklist's verdict file wins; the first\n // branch-matching run is the fallback, as before.\n // eslint-disable-next-line @typescript-eslint/max-params\n private findMatchingAgentId(dirs: readonly string[], want: ExpectedReviewer, context: ReviewerContext, exclude: ReadonlySet<string>): string {\n let fallback = '';\n for (const dir of dirs) {\n for (const metaFile of this.metaFiles(dir)) {\n const agentId = this.agentIdOf(metaFile);\n if (exclude.has(agentId) || !this.isReviewerRun(dir, metaFile)) continue;\n if (!this.sidechainOnBranch(dir, agentId, want.checklistId, context)) continue;\n if (this.namedVerdict(dir, agentId, want.checklistId, context)) return agentId;\n if (fallback === '') fallback = agentId;\n }\n }\n return fallback;\n }\n\n /**\n * A harness-written meta for a REAL SUBAGENT — `spawnDepth >= 1`, and nothing about its NAME.\n *\n * The agent TYPE used to be compared against the configured reviewer agent, and that check is\n * gone (issue #964). It proved nothing: `agentType` is a label on a prompt, and it does not show\n * the agent read the checklist, opened the diff, or looked at the right branch. The gates that DO\n * show those are untouched — `spawnDepth >= 1` plus `isSidechain === true` (see\n * {@link sidechainOnBranch}) are harness-written, so the main loop still cannot self-certify;\n * {@link creditedByWhatItTouched} proves the branch and the actual work; `requireDiffEvidence`\n * proves the diff was opened.\n *\n * It was also the ONLY gate with an unfixable failure mode. Claude Code snapshots agent\n * definitions per session and the refresh does not reach an already-running subagent, so a repo\n * that renames its reviewer agent mid-session leaves that subagent's registry offering only the\n * OLD names: the spawn is rejected, the agent falls back to `general-purpose`, does the real\n * review, writes every verdict — and is refused as unattributable, with no cwd, branch or respawn\n * able to change it. Measured: six checklists, six verdict files on disk, PR blocked.\n *\n * Accepted trade-off: without the name check the implementer's own subagent could in principle be\n * credited, since it touches the diff dir while running the gate. That is deliberate. The rule is\n * \"if the verdict file is there, a subagent wrote it\", and this gate's job is to catch \"no\n * subagent ran at all\" — not to adjudicate which subagent it was.\n */\n private isReviewerRun(dir: string, metaFile: string): boolean {\n const meta = this.readJson(path.join(dir, metaFile));\n if (!meta) return false;\n const spawnDepth = meta['spawnDepth'];\n return typeof spawnDepth === 'number' && spawnDepth >= 1;\n }\n\n // Did this run's transcript name the checklist's own verdict path?\n // eslint-disable-next-line @typescript-eslint/max-params\n private namedVerdict(dir: string, agentId: string, checklistId: string, context: ReviewerContext): boolean {\n const jsonl = path.join(dir, `agent-${agentId}.jsonl`);\n return fs.existsSync(jsonl) && this.submittedVerdict(this.scanTranscript(jsonl), checklistId, context.verdictPaths[checklistId] ?? '');\n }\n\n // Named its verdict file, or submitted it via wp-write-review (#863). Proves authorship, never branch.\n private submittedVerdict(scan: TranscriptScan, checklistId: string, verdictPath: string): boolean {\n if (this.namesPath(scan, verdictPath)) return true;\n return this.invokedWriteReview(scan, checklistId);\n }\n\n private invokedWriteReview(scan: TranscriptScan, checklistId: string): boolean {\n return scan.inputs.some((i: string): boolean => reviewIdentityStamps.invokedChecklists(i).includes(checklistId));\n }\n\n /**\n * Every `<config>/projects/&#42;/<session>/subagents` dir that exists — matching by the recorded\n * gitBranch (not by session id) is what makes provenance survive across sessions.\n *\n * `<config>` comes from {@link ClaudeConfigDir.projectsRoots}, which is BOTH the configured\n * `$CLAUDE_CONFIG_DIR` tree and `~/.claude`. This used to be a hardcoded `~/.claude`, and on a\n * machine with a relocated config dir that found nothing at all — so every PR was refused with a\n * message about the reviewers' cwd, which is not what was wrong and which no agent could act on.\n */\n private allSubagentsDirs(): string[] {\n const out: string[] = [];\n for (const projects of claudeConfigDir.projectsRoots()) {\n for (const proj of this.readDir(projects)) {\n const projDir = path.join(projects, proj);\n for (const session of this.readDir(projDir)) {\n const candidate = path.join(projDir, session, 'subagents');\n if (fs.existsSync(candidate)) out.push(candidate);\n }\n }\n }\n return out;\n }\n\n private metaFiles(dir: string): string[] {\n return this.readDir(dir).filter((f: string): boolean => f.endsWith('.meta.json'));\n }\n\n // agent-<id>.meta.json → <id>\n private agentIdOf(metaFile: string): string {\n return metaFile.replace(/^agent-/, '').replace(/\\.meta\\.json$/, '');\n }\n\n /**\n * Cross-check the sibling transcript's record 0: isSidechain true (a real subagent, not the main\n * loop) and the same branch. Lenient on branch drift (a leftover …wpN suffix from a mid-flight\n * branch rename) and on a missing jsonl (meta already matched — accept, best-effort).\n *\n * WHEN `gitBranch` DISAGREES, A PINNED `cwd` DECIDES. Record 0 carries both fields, and the harness\n * can write a `gitBranch` that CONTRADICTS the record's own `cwd`: a reviewer subagent spawned into\n * a worktree on `dean/one-2406-…` was stamped `worktree-agent-a54887200e40eb956` — an unrelated,\n * still-live worktree's scaffold branch — deterministically, on four consecutive attempts, blocking\n * a PR whose required reviewer genuinely ran and genuinely passed. `stripWp` cannot bridge that, so\n * the reviewer was never credited and `wp-finish-upsert-pr` refused a legitimately-reviewed PR with\n * no in-flow recovery. A sweep of 961 record-0s on one machine found the mis-stamp is the MAJORITY\n * case among subagents in dedicated worktrees, so trusting `gitBranch` alone can never be correct.\n *\n * ─── Why ONLY a linked worktree, and never the primary clone ──────────────────────────────────\n * \"Ask git what branch the cwd is on\" is correct only when that cwd CANNOT have moved since the\n * reviewer ran. A LINKED WORKTREE is 1:1 with the agent that owns it and nothing re-checks it out;\n * the PRIMARY CLONE gets checked out constantly. Falling back on a primary-clone cwd would credit a\n * STALE reviewer, and by construction rather than by accident:\n *\n * 1. a reviewer runs in the primary clone while it is on branch A\n * 2. the clone is later checked out to branch B\n * 3. `wp-finish-upsert-pr` runs on B — `gitBranch` (stamped A) mismatches\n * 4. `git -C <clone>` now answers B, because the CLONE moved → the reviewer is credited for B\n *\n * It reviewed A. Every past reviewer run in that clone would be credited for whatever branch is\n * checked out at finish time — which in a repo with a required reviewer on every PR is not an\n * exotic sequence, it is the normal one. So the fallback is gated on `gitCheckout.isLinkedWorktree`\n * (git's own git-dir != common-git-dir test, read from the filesystem, reused rather than re-derived), and a primary\n * clone falls through to a refusal exactly as it does today.\n *\n * That gate keeps the anti-forgery property intact: `cwd` is harness-written in the same record by\n * the same writer as `gitBranch`, so it carries the same weight — and inside a pinned worktree it is\n * the field that is CORRECT. There is deliberately no config flag and no second comparison mode:\n * ONE rule, with `gitBranch` only ever a cheap way to skip the subprocess when it already agrees.\n *\n * An UNRESOLVABLE cwd does not credit either. A reaped worktree, a deleted directory, a non-repo\n * path or a detached HEAD yields '' and falls through to a refusal. Leniency here is bounded by\n * \"git can still prove it\", never by \"we could not check, so assume yes\".\n *\n * ─── Why neither field can settle it from a PRIMARY CLONE, and what does ──────────────────────\n * Both fields above are stamped from the SPAWNING session's cwd — the Agent tool has no cwd\n * parameter, so a subagent inherits its parent's. A session rooted in the primary clone that spawns\n * a reviewer for a WORKTREE branch therefore produces `gitBranch` = the clone's branch (mismatch)\n * and `cwd` = the clone (gated off, correctly) — and NO respawn can change either stamp. That is not\n * an exotic setup: it is what the flow instructs the moment a worker agent dies mid-flow and the\n * top-level session has to take over, and it deadlocked a branch whose seven reviewers had all run.\n *\n * So the third channel is not a loosening of the cwd rule — it is a DIFFERENT question, asked of\n * evidence the reviewer cannot inherit and cannot fake by accident: {@link creditedByWhatItTouched}.\n */\n // eslint-disable-next-line @typescript-eslint/max-params\n private sidechainOnBranch(dir: string, agentId: string, checklistId: string, context: ReviewerContext): boolean {\n const jsonl = path.join(dir, `agent-${agentId}.jsonl`);\n if (!fs.existsSync(jsonl)) return true;\n const first = this.firstNonEmptyLine(jsonl);\n if (first === '') return true;\n const rec = this.parseLine(first);\n if (!rec) return true;\n if (rec['isSidechain'] !== true) return false;\n const gitBranch = rec['gitBranch'];\n // Not recorded at all → accept, as before: nothing to contradict and nothing to verify against.\n if (typeof gitBranch !== 'string' || gitBranch === '') return true;\n const want = this.stripWp(context.branch);\n if (this.stripWp(gitBranch) === want) return true;\n if (want !== '' && this.stripWp(this.branchOfCwd(rec['cwd'])) === want) return true;\n return this.creditedByWhatItTouched(jsonl, agentId, checklistId, context);\n }\n\n /**\n * Credit a reviewer for WHAT IT TOUCHED when neither harness-stamped field can settle it.\n *\n * Both paths compared here are ABSOLUTE and BRANCH-SPECIFIC — they live under\n * `<worktree>/.webpieces/pr-review/<featureSlug>/`, so the string names the tree AND the branch. A\n * reviewer that worked on a different branch cannot have them in its transcript, and a reviewer of\n * this branch that ran from a mis-stamped cwd cannot avoid having them. That is the property\n * `gitBranch` lacks — this file's own sweep of 961 record-0s found the mis-stamp is the MAJORITY\n * case among subagents in dedicated worktrees.\n *\n * Three channels, any one sufficient:\n * 1. it WROTE this checklist's verdict file — proves branch AND checklist, and is the act the whole\n * gate is trying to attribute. Matched as a substring of any tool input, so a Write, an Edit and\n * a `cat > <path>` heredoc all count; the point is that the path was named, not which tool named it.\n * 2. it READ this branch's materialized diff dir — proves the branch. Kept as a second channel\n * because a reviewer whose verdict was relayed by its parent still demonstrably reviewed this\n * branch, and refusing that would re-open a narrower version of the same unrecoverable deadlock.\n * 3. it SUBMITTED this checklist through `pnpm wp-write-review --checklist <id>` AND this branch's\n * verdict provenance names this very agentId as the submitter (issue #1211). The invocation alone\n * proves authorship of some verdict, not which branch's — checklist ids are shared by every branch —\n * so the bin's own record is what ties it to this one. See {@link ReviewerContext.submittedBy}.\n *\n * Channels 1 and 2 match a path absolutely or relative to the transcript's recorded cwd; see\n * {@link namesPath}. The measured miss behind both additions: a reviewer with cwd = the repo root read\n * the diff through a relative path and submitted through wp-write-review, and was refused on all four\n * checklists because its gitBranch carried a DIFFERENT concurrent worktree's branch.\n *\n * Independence is NOT weakened by either: `isSidechain === true` and `spawnDepth >= 1` are checked\n * before we get here (so the main loop's own transcript can never qualify), and `verifyReviewers`\n * excludes an agentId already credited to another checklist. It remains non-tamper-proof in exactly\n * the way the class doc already states — forging this now means forging a transcript rather than a\n * meta.json, which is the same bar, not a lower one.\n */\n // eslint-disable-next-line @typescript-eslint/max-params\n private creditedByWhatItTouched(jsonl: string, agentId: string, checklistId: string, context: ReviewerContext): boolean {\n const scan = this.scanTranscript(jsonl);\n if (this.namesPath(scan, context.verdictPaths[checklistId] ?? '')) return true;\n if (this.readDiffDir(scan, context)) return true;\n const submitter = context.submittedBy[checklistId] ?? '';\n return submitter !== '' && submitter === agentId && this.invokedWriteReview(scan, checklistId);\n }\n\n /**\n * The branch record-0's own `cwd` is PINNED to, '' when that cannot be established or is not pinned.\n *\n * Cached per cwd because `findMatchingAgentId` walks every subagent of every session on the machine\n * and several of them share a worktree — one `git` process per RECORD would put dozens of spawns on\n * the path that opens a PR.\n */\n // webpieces-disable no-any-unknown -- one opaque record field, type-guarded on the next line\n private branchOfCwd(cwd: unknown): string {\n if (typeof cwd !== 'string' || cwd === '') return '';\n const cached = this.branchByCwd.get(cwd);\n if (cached !== undefined) return cached;\n const resolved = this.pinnedBranch(cwd);\n this.branchByCwd.set(cwd, resolved);\n return resolved;\n }\n\n /**\n * The branch of `cwd` when — and only when — `cwd` is a LINKED WORKTREE. '' otherwise.\n *\n * '' for the primary clone (it moves; see sidechainOnBranch for the false-accept that closes), for a\n * reaped or deleted directory, for a non-repo path, when git is unavailable, and for a detached HEAD,\n * which `--abbrev-ref` prints as the literal `HEAD` and which names no branch.\n */\n private pinnedBranch(cwd: string): string {\n if (!fs.existsSync(cwd)) return '';\n if (!gitCheckout.isLinkedWorktree(cwd)) return '';\n const branch = gitCheckout.branch(cwd);\n return branch === null || branch === DETACHED_HEAD ? '' : branch;\n }\n\n private stripWp(branch: string): string {\n return branch.replace(/-?wp\\d+$/i, '');\n }\n\n private readDir(dir: string): string[] {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unreadable dir yields [] (best-effort provenance)\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return fs.readdirSync(dir);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return [];\n }\n }\n\n private firstNonEmptyLine(filePath: string): string {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: unreadable transcript → '' (best-effort)\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n for (const line of fs.readFileSync(filePath, 'utf8').split('\\n')) {\n if (line.trim() !== '') return line;\n }\n return '';\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return '';\n }\n }\n\n // webpieces-disable no-any-unknown -- opaque parsed JSON object, keys read by the caller\n private readJson(filePath: string): Record<string, unknown> | null {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: malformed meta.json → null (skipped)\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // webpieces-disable no-any-unknown -- parsed JSON is opaque until narrowed by the caller\n return JSON.parse(fs.readFileSync(filePath, 'utf8')) as Record<string, unknown>;\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n\n // webpieces-disable no-any-unknown -- one opaque JSONL record, keys read by the caller\n private parseLine(line: string): Record<string, unknown> | null {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: malformed JSONL record → null\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // webpieces-disable no-any-unknown -- parsed JSON is opaque until narrowed by the caller\n return JSON.parse(line) as Record<string, unknown>;\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n}\n"]}