@webpieces/rules-config 0.4.543 → 0.4.545
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 +1 -1
- package/src/index.d.ts +3 -2
- package/src/index.js +13 -4
- package/src/index.js.map +1 -1
- package/src/main-sync-file.d.ts +94 -0
- package/src/main-sync-file.js +243 -0
- package/src/main-sync-file.js.map +1 -0
- package/src/main-sync-status.d.ts +87 -34
- package/src/main-sync-status.js +147 -91
- package/src/main-sync-status.js.map +1 -1
- package/src/review-provenance.d.ts +8 -0
- package/src/review-provenance.js +9 -0
- package/src/review-provenance.js.map +1 -1
- package/src/subagent-provenance.d.ts +55 -5
- package/src/subagent-provenance.js +77 -12
- package/src/subagent-provenance.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"main-sync-status.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/main-sync-status.ts"],"names":[],"mappings":";;;AAyfA,gDAAiH;AAEjH,4CAA6G;AAE7G,gDAAgI;AAEhI,kDAA0I;AAE1I,4CAA0H;AAE1H,8CAAgI;AAEhI,kCAAiL;AAEjL,kDAAmM;AAEnM,wDAAqP;AAErP,sCAAgJ;AAEhJ,oCAAyG;AAEzG,sDAA+H;AAE/H,kDAA+H;AAE/H,4DAAoH;;AAnhBpH,iDAA0C;AAC1C,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAE3D,+CAA2C;AAC3C,2CAAyD;AACzD,yCAAqC;AAErC,sGAAsG;AACtG,wGAAwG;AACxG,qGAAqG;AACrG,wFAAwF;AAExF,oGAAoG;AACvF,QAAA,4BAA4B,GAAG,CAAC,CAAC;AAE9C,MAAM,qBAAqB,GAAG,uBAAuB,CAAC;AACtD,MAAM,mBAAmB,GAAG,qBAAqB,CAAC;AAElD,MAAM,oBAAoB,GAAG,WAAW,CAAC;AACzC,MAAM,mBAAmB,GAAG,UAAU,CAAC;AAEvC,+CAA+C;AAC/C,MAA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W,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;AACzG,4IAA4I;AAC5I,SAAgB,qBAAqB,CAAC,QAAgB,IAAoB,OAAO,WAAW,CAAC,qBAAqB,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;AAC/H,4IAA4I;AAC5I,SAAgB,mBAAmB,CAAC,aAAqB,IAAc,OAAO,WAAW,CAAC,mBAAmB,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC;AAC/H,4IAA4I;AAC5I,SAAgB,wBAAwB,CAAC,QAAgB,IAAU,WAAW,CAAC,wBAAwB,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC","sourcesContent":["import { spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { AtomicFile } from './atomic-file';\nimport { DotWebpieces, dotWebpieces } from './state-dir';\nimport { toError } from './to-error';\n\n// Shared \"is my feature branch healthy relative to origin/main?\" state. The SLOW signals (git fetch +\n// merge-base + same-file-overlap + a merged-PR lookup) are computed by the ai-hook-rules refresher in a\n// DETACHED background process; the feature-branch-guard only READS this cached file. pr-gate's merge\n// flow also writes it synchronously after a merge. Lives here (the shared dep of both).\n\n// How long an `inprocess` refresher lock may sit before a new refresher assumes the prior run hung.\nexport const DEFAULT_HANG_TIMEOUT_MINUTES = 5;\n\nconst MAIN_SYNC_STATUS_FILE = 'main-sync-status.json';\nconst MAIN_SYNC_LOCK_FILE = 'main-sync.lock.json';\n\nconst LOCK_STATE_INPROCESS = 'inprocess';\nconst LOCK_STATE_FINISHED = 'finished';\n\n// Data-only (per CLAUDE.md, classes for data).\nexport class MainSyncStatus {\n branch: string;\n branchAlreadyMerged: boolean;\n mergedPr: string;\n hasForkPoint: boolean;\n forkPoint: string | null;\n originMain: string;\n featureHead: string;\n conflict: boolean;\n conflictFiles: string[];\n timestamp: string;\n // An OPEN (not merged) PR tracking this branch, if any — '' = none or not-yet-known. Advisory.\n // Kept OUT of the positional constructor (a defaulted field) so existing call sites don't churn.\n openPr: string = '';\n // The LOCAL refs/heads/main hash — '' = main does not exist locally (fresh clone / worktree) or\n // could not be read. Paired with `originMain`, this is what tells the read-stale-guard whether a\n // checked-out `main` is behind its remote. Defaulted field for the same reason as `openPr`.\n localMain: string = '';\n\n constructor(\n branch: string,\n branchAlreadyMerged: boolean,\n mergedPr: string,\n hasForkPoint: boolean,\n forkPoint: string | null,\n originMain: string,\n featureHead: string,\n conflict: boolean,\n conflictFiles: string[],\n timestamp: string,\n ) {\n this.branch = branch;\n this.branchAlreadyMerged = branchAlreadyMerged;\n this.mergedPr = mergedPr;\n this.hasForkPoint = hasForkPoint;\n this.forkPoint = forkPoint;\n this.originMain = originMain;\n this.featureHead = featureHead;\n this.conflict = conflict;\n this.conflictFiles = conflictFiles;\n this.timestamp = timestamp;\n }\n}\n\n// Concurrency state machine for the detached refresher. `started` is epoch ms. `pid` is the refresher\n// process's pid (0 = unknown) — used so a KILLED refresher doesn't wedge `inprocess` for the timeout.\nexport class MainSyncLock {\n state: string;\n started: number;\n pid: number;\n\n constructor(state: string, started: number, pid: number = 0) {\n this.state = state;\n this.started = started;\n this.pid = pid;\n }\n}\n\n// Raw JSON shapes for the cast at the parse boundary.\ninterface RawStatus {\n branch?: string;\n branchAlreadyMerged?: boolean;\n mergedPr?: string;\n hasForkPoint?: boolean;\n forkPoint?: string | null;\n originMain?: string;\n featureHead?: string;\n conflict?: boolean;\n conflictFiles?: string[];\n timestamp?: string;\n openPr?: string;\n localMain?: string;\n}\n\ninterface RawLock {\n state?: string;\n started?: number;\n pid?: number;\n}\n\n// Result of a captured git/gh invocation: ok=false on spawn failure or non-zero exit.\ninterface CmdCapture {\n ok: boolean;\n out: string;\n}\n\n/**\n * Reads/writes the main-sync cache + lock and computes the slow \"is my branch healthy vs origin/main?\"\n * status. `@injectable(bindingScopeValues.Singleton)` so it's injectable and drawn in the rules-config DI design.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class MainSyncStatusService {\n constructor(\n private readonly dotDir: DotWebpieces = dotWebpieces,\n private readonly atomicFile: AtomicFile = new AtomicFile(),\n ) {}\n\n /**\n * SHARED scope: `<primary>/.webpieces/main-sync-status.json`, one per repo.\n *\n * It is the OUTPUT of the single-flight refresher below, so it has to live where the lock lives —\n * one `.git`, one `origin/main`, one fetch, one answer. A per-worktree copy under single-flight\n * would only ever be written for whichever worktree won the lock anyway.\n *\n * KNOWN CONSEQUENCE, stated plainly rather than discovered later: the file's CONTENT is keyed to\n * one branch (`branch`, `featureHead`, `conflict`, `conflictFiles`), and every reader fails OPEN\n * when the cached branch is not the branch being judged (`merged-branch-bash-guard` and\n * `stale-main-bash-guard` both log `stale-cross-branch-cache (fail-open)`). With several worktrees\n * on several branches, the losers of the lock therefore see a cross-branch cache and their guards\n * allow rather than block. That is the fail-SAFE direction and it is inherent to single-flight, not\n * to the shared path — but making the entries branch-keyed (a map of branch → status, written\n * atomically) is the obvious follow-up.\n */\n mainSyncStatusPath(repoRoot: string): string {\n return this.dotDir.sharedFile(repoRoot, MAIN_SYNC_STATUS_FILE);\n }\n\n /**\n * SHARED scope — the single-flight lock for the whole repo.\n *\n * This is the fix for the filed bug \"the detached main-sync refresher's `git fetch` races the\n * agent's foreground `git fetch`/`git pull` and corrupts `.git/FETCH_HEAD`\". The lock was already\n * atomic (O_CREAT|O_EXCL) and already serialised refreshers against each other — but only WITHIN\n * one worktree, so N worktrees meant N locks and up to N concurrent `git fetch`es against the ONE\n * shared `.git`, which is exactly how a duplicate `for-merge` line lands in FETCH_HEAD. There is\n * one `.git`, so there is now one lock: at most one refresher in flight across all worktrees.\n *\n * Stale-lock handling is unchanged and still required (a lock nobody can clear is worse than the\n * race): the holder records pid + start epoch, and `tryAcquireMainSyncLock` reclaims it once\n * `isRefreshInProgress` proves the holder is finished, hung past hangTimeoutMinutes, or dead.\n */\n mainSyncLockPath(repoRoot: string): string {\n return this.dotDir.sharedFile(repoRoot, MAIN_SYNC_LOCK_FILE);\n }\n\n // Pure read — any error (missing file, malformed JSON) returns null so the guard fails OPEN.\n readMainSyncStatus(repoRoot: string): MainSyncStatus | null {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const statusPath = this.mainSyncStatusPath(repoRoot);\n if (!fs.existsSync(statusPath)) return null;\n const raw = JSON.parse(fs.readFileSync(statusPath, 'utf8')) as RawStatus;\n const status = new MainSyncStatus(\n raw.branch ?? '',\n raw.branchAlreadyMerged ?? false,\n raw.mergedPr ?? '',\n raw.hasForkPoint ?? true,\n raw.forkPoint ?? null,\n raw.originMain ?? '',\n raw.featureHead ?? '',\n raw.conflict ?? false,\n raw.conflictFiles ?? [],\n raw.timestamp ?? '',\n );\n status.openPr = raw.openPr ?? '';\n status.localMain = raw.localMain ?? '';\n return status;\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n\n /**\n * ATOMIC write (temp file + `rename()` in the same directory). The refresher writes this file while\n * guards on the blocking path read it; a plain `writeFileSync` truncates first, so a reader landing\n * in that window gets a torn document. Now that the file is repo-wide the reader may be in another\n * worktree entirely, which widens the window rather than creating it. See AtomicFile.\n */\n writeMainSyncStatus(repoRoot: string, status: MainSyncStatus): void {\n this.atomicFile.writeJsonAtomic(this.mainSyncStatusPath(repoRoot), status);\n }\n\n readMainSyncLock(repoRoot: string): MainSyncLock | null {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const lockPath = this.mainSyncLockPath(repoRoot);\n if (!fs.existsSync(lockPath)) return null;\n const raw = JSON.parse(fs.readFileSync(lockPath, 'utf8')) as RawLock;\n return new MainSyncLock(raw.state ?? LOCK_STATE_FINISHED, raw.started ?? 0, raw.pid ?? 0);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n\n writeMainSyncLock(repoRoot: string, lock: MainSyncLock): void {\n const lockPath = this.mainSyncLockPath(repoRoot);\n this.ensureDir(lockPath);\n fs.writeFileSync(lockPath, JSON.stringify(lock, null, 2) + '\\n');\n }\n\n // A lock is stale (prior refresher assumed hung) once `inprocess` longer than hangTimeoutMinutes.\n isLockStale(lock: MainSyncLock, hangTimeoutMinutes: number, now: number = Date.now()): boolean {\n return now - lock.started > hangTimeoutMinutes * 60 * 1000;\n }\n\n // True when another refresher is actively running and we should NOT start a second one.\n isRefreshInProgress(repoRoot: string, hangTimeoutMinutes: number, now: number = Date.now()): boolean {\n const lock = this.readMainSyncLock(repoRoot);\n if (!lock) return false;\n if (lock.state !== LOCK_STATE_INPROCESS) return false;\n if (this.isLockStale(lock, hangTimeoutMinutes, now)) return false;\n return this.isProcessAlive(lock.pid);\n }\n\n /**\n * ATOMICALLY take the refresher lock. Returns the held lock, or null when someone else holds it.\n *\n * Replaces the check-then-write pair (`isRefreshInProgress` then `writeMainSyncLock`), whose gap\n * let two detached refreshers both pass the check and then both run `git fetch` at once — the\n * concurrency this lock exists to prevent. The create uses the `wx` flag (O_CREAT|O_EXCL), so of\n * N racing refreshers exactly one creates the file.\n *\n * A lock file left behind by a FINISHED, hung, or killed refresher is reclaimed: we only unlink\n * and re-take it once `isRefreshInProgress` says the holder is provably not running, and we\n * re-read afterwards to confirm the entry we see is ours before claiming the lock.\n */\n tryAcquireMainSyncLock(\n repoRoot: string,\n hangTimeoutMinutes: number,\n now: number = Date.now(),\n pid: number = process.pid,\n ): MainSyncLock | null {\n const lockPath = this.mainSyncLockPath(repoRoot);\n this.ensureDir(lockPath);\n const lock = this.inProcessLock(now, pid);\n const payload = JSON.stringify(lock, null, 2) + '\\n';\n\n if (this.createExclusive(lockPath, payload)) return lock;\n\n // The file already exists. Leave it alone while a live refresher owns it.\n if (this.isRefreshInProgress(repoRoot, hangTimeoutMinutes, now)) return null;\n\n // Reclaim it: remove the dead entry, then re-take it exclusively so only one reclaimer wins.\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.unlinkSync(lockPath);\n } catch (err: unknown) {\n const error = toError(err);\n void error; // someone else reclaimed it first — the exclusive create below decides\n }\n if (!this.createExclusive(lockPath, payload)) return null;\n\n // Confirm the lock on disk is OURS (a simultaneous reclaimer could have unlinked ours and\n // written its own between the two calls above).\n const held = this.readMainSyncLock(repoRoot);\n if (!held || held.pid !== pid || held.started !== lock.started) return null;\n return lock;\n }\n\n // O_CREAT|O_EXCL write: true when THIS call created the file, false when it already existed.\n private createExclusive(lockPath: string, payload: string): boolean {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.writeFileSync(lockPath, 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 inProcessLock(now: number = Date.now(), pid: number = process.pid): MainSyncLock {\n return new MainSyncLock(LOCK_STATE_INPROCESS, now, pid);\n }\n\n finishedLock(started: number): MainSyncLock {\n return new MainSyncLock(LOCK_STATE_FINISHED, started, 0);\n }\n\n /**\n * The SLOW path, run only inside the detached refresher. Computes every cached signal the\n * feature-branch-guard needs. Never run on the hook's blocking path.\n */\n // webpieces-disable max-lines-new-methods -- one cohesive slow-path computation\n computeMainSyncStatus(repoRoot: string): MainSyncStatus {\n const branch = this.gitBranch(repoRoot);\n const mergedPr = this.detectMergedPr(repoRoot, branch);\n const openPr = this.detectOpenPr(repoRoot, branch);\n\n // Best-effort network refresh; offline just means we evaluate against the last-fetched ref.\n this.fetchOriginMain(repoRoot);\n\n const head = this.capture(repoRoot, 'git', ['rev-parse', 'HEAD']);\n const originMain = this.capture(repoRoot, 'git', ['rev-parse', 'origin/main']);\n const localMain = this.localMainHash(repoRoot);\n const featureHead = head.ok ? head.out : '';\n if (!head.ok || !originMain.ok) {\n const status = this.benignStatus(branch, featureHead);\n status.branchAlreadyMerged = mergedPr !== '';\n status.mergedPr = mergedPr;\n status.openPr = openPr;\n status.localMain = localMain;\n return status;\n }\n\n const forkPoint = this.capture(repoRoot, 'git', ['merge-base', 'origin/main', 'HEAD']);\n if (!forkPoint.ok || forkPoint.out === '') {\n const noFork = new MainSyncStatus(branch, mergedPr !== '', mergedPr, false, null, originMain.out, featureHead, false, [], new Date().toISOString());\n noFork.openPr = openPr;\n noFork.localMain = localMain;\n return noFork;\n }\n\n const featureFiles = new Set(this.featureChangedFiles(repoRoot, forkPoint.out));\n const mainFiles = this.changedFiles(repoRoot, forkPoint.out, 'origin/main');\n const conflictFiles = mainFiles.filter((file: string): boolean => featureFiles.has(file));\n\n const status = new MainSyncStatus(\n branch,\n mergedPr !== '',\n mergedPr,\n true,\n forkPoint.out,\n originMain.out,\n featureHead,\n conflictFiles.length > 0,\n conflictFiles,\n new Date().toISOString(),\n );\n status.openPr = openPr;\n status.localMain = localMain;\n return status;\n }\n\n // The recovery steps when there is no fork point with origin/main (a bad merge of main into branch).\n squashRecoverySteps(currentBranch: string): string[] {\n return [\n '1. Fetch latest main: git fetch origin main',\n `2. New branch off origin/main: git checkout -b ${currentBranch}-v2 origin/main`,\n `3. Squash-merge old branch: git merge --squash ${currentBranch}`,\n ' ^^ HUMAN-ONLY. `git merge` is blocked for AI (redirect-how-to-merge-main). AI: ask the',\n ' human to run step 3, and warn them it is a raw merge — only correct here because the',\n ' branch is already broken. For a normal update from main they should push back and',\n ' tell you to use the gated 3-point merge instead: `pnpm wp-start-update` (paired with',\n ' `pnpm wp-finish-update`) when no PR is open, or `pnpm wp-start-upsert-pr` (paired with',\n ' `pnpm wp-finish-upsert-pr`) when a PR IS open — a PR MUST use the upsert-pr pair.',\n `4. Commit the squash: git add -A && git commit -m \"Squashed from ${currentBranch}\"`,\n '5. If a PR exists: open a NEW PR for the -v2 branch and close the old one.',\n ];\n }\n\n // Synchronously stamp a clean \"up to date with main\" status — call right after a successful merge.\n stampCleanMainSyncStatus(repoRoot: string): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const branch = this.gitBranch(repoRoot);\n const originMain = this.capture(repoRoot, 'git', ['rev-parse', 'origin/main']);\n const featureHead = this.capture(repoRoot, 'git', ['rev-parse', 'HEAD']);\n if (!originMain.ok || !featureHead.ok) return;\n const status = new MainSyncStatus(\n branch, false, '', true, originMain.out, originMain.out, featureHead.out, false, [], new Date().toISOString(),\n );\n status.localMain = this.localMainHash(repoRoot);\n this.writeMainSyncStatus(repoRoot, status);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n }\n\n /**\n * Refresh `origin/main` WITHOUT writing `.git/FETCH_HEAD`.\n *\n * WHY the flag is not optional: this runs in a DETACHED background process while the agent is\n * running its own foreground `git fetch` / `git pull` in the very same repo. `.git/FETCH_HEAD` is\n * a single file that git takes no lock on, so two overlapping fetches interleave their writes and\n * can leave the SAME `for-merge` line twice. `git pull` then reads two for-merge entries and dies\n * with `fatal: Cannot fast-forward to multiple branches` — wedging the exact command the\n * read-stale-guard tells the agent to run. `--no-write-fetch-head` (git >= 2.29) still updates the\n * remote-tracking ref, which is all anything downstream reads (`origin/main`, merge-base), so\n * nothing here needs FETCH_HEAD written at all.\n *\n * Older git rejects the flag; only then do we retry the plain form, accepting the old behaviour\n * rather than losing the refresh entirely on a pre-2020 git.\n */\n private fetchOriginMain(repoRoot: string): void {\n const safe = spawnSync('git', ['fetch', '--no-write-fetch-head', 'origin', 'main'], {\n cwd: repoRoot, encoding: 'utf8', stdio: ['ignore', 'ignore', 'pipe'],\n });\n if (safe.status === 0) return;\n if (!this.isUnknownGitOption(safe.stderr)) return; // a real failure (offline, auth) — not our business\n spawnSync('git', ['fetch', 'origin', 'main'], { cwd: repoRoot, stdio: 'ignore' });\n }\n\n // Did git reject the flag itself (too old), as opposed to failing the network refresh?\n private isUnknownGitOption(stderr: string | null): boolean {\n const text = (stderr ?? '').toLowerCase();\n return text.includes('unknown option') || text.includes('unknown switch') || text.includes('unrecognized option');\n }\n\n private ensureDir(filePath: string): void {\n fs.mkdirSync(path.dirname(filePath), { recursive: true });\n }\n\n // Liveness probe: is `pid` still a running process? pid <= 0 (unknown) → assume alive.\n private isProcessAlive(pid: number): boolean {\n if (pid <= 0) return true;\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.message.includes('ESRCH');\n }\n }\n\n // Run a command capturing trimmed stdout; ok=false on spawn failure or non-zero exit.\n private capture(repoRoot: string, cmd: string, args: string[]): CmdCapture {\n const result = spawnSync(cmd, args, { cwd: repoRoot, encoding: 'utf8' });\n if (result.status !== 0 || typeof result.stdout !== 'string') return { ok: false, out: '' };\n return { ok: true, out: result.stdout.trim() };\n }\n\n // The actual checked-out branch in repoRoot — cwd-correct so the cache's `branch` label matches.\n private gitBranch(repoRoot: string): string {\n const result = this.capture(repoRoot, 'git', ['rev-parse', '--abbrev-ref', 'HEAD']);\n return result.ok ? result.out : '';\n }\n\n // The LOCAL main hash. `refs/heads/main` (not the bare name) so it can never resolve to a remote\n // ref or a tag. '' when main does not exist locally — which the guard treats as fail-open.\n private localMainHash(repoRoot: string): string {\n const result = this.capture(repoRoot, 'git', ['rev-parse', 'refs/heads/main']);\n return result.ok ? result.out : '';\n }\n\n private changedFiles(repoRoot: string, base: string, head: string): string[] {\n const result = this.capture(repoRoot, 'git', ['diff', '--name-only', base, head]);\n if (!result.ok || result.out === '') return [];\n return result.out.split('\\n').map((line: string): string => line.trim()).filter((line: string): boolean => line.length > 0);\n }\n\n // Every file this feature branch has touched since the fork point — committed AND still in the\n // working tree (staged / unstaged / untracked), so a conflict is visible WHILE editing.\n private featureChangedFiles(repoRoot: string, forkPoint: string): string[] {\n const out = new Set<string>();\n const add = (args: string[]): void => {\n const r = this.capture(repoRoot, 'git', args);\n if (!r.ok || r.out === '') return;\n for (const line of r.out.split('\\n')) {\n const f = line.trim();\n if (f.length > 0) out.add(f);\n }\n };\n add(['diff', '--name-only', forkPoint, 'HEAD']); // committed since the fork point\n add(['diff', '--name-only', 'HEAD']); // unstaged working-tree edits\n add(['diff', '--name-only', '--cached', 'HEAD']); // staged edits\n add(['ls-files', '--others', '--exclude-standard']); // untracked new files (respects .gitignore)\n return [...out];\n }\n\n // Has this feature branch already been merged into main? Reliable signal: a MERGED PR exists.\n private detectMergedPr(repoRoot: string, branch: string): string {\n if (!branch || branch === 'main') return '';\n const result = this.capture(repoRoot, 'gh', ['pr', 'list', '--head', branch, '--state', 'merged', '--json', 'number', '--jq', '.[0].number']);\n return result.ok ? result.out : '';\n }\n\n // An OPEN PR tracking this branch, if any. Best-effort/advisory.\n private detectOpenPr(repoRoot: string, branch: string): string {\n if (!branch || branch === 'main') return '';\n const result = this.capture(repoRoot, 'gh', ['pr', 'list', '--head', branch, '--state', 'open', '--json', 'number', '--jq', '.[0].number']);\n return result.ok ? result.out : '';\n }\n\n // A benign status that never blocks — used when origin/main can't be resolved.\n private benignStatus(branch: string, featureHead: string): MainSyncStatus {\n return new MainSyncStatus(branch, false, '', true, null, '', featureHead, false, [], new Date().toISOString());\n }\n}\n\n// Temporary migration delegators to MainSyncStatusService — removed once consumers inject it.\nconst mainSyncSvc = new MainSyncStatusService();\n\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function mainSyncStatusPath(repoRoot: string): string { return mainSyncSvc.mainSyncStatusPath(repoRoot); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function mainSyncLockPath(repoRoot: string): string { return mainSyncSvc.mainSyncLockPath(repoRoot); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function readMainSyncStatus(repoRoot: string): MainSyncStatus | null { return mainSyncSvc.readMainSyncStatus(repoRoot); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function writeMainSyncStatus(repoRoot: string, status: MainSyncStatus): void { mainSyncSvc.writeMainSyncStatus(repoRoot, status); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function readMainSyncLock(repoRoot: string): MainSyncLock | null { return mainSyncSvc.readMainSyncLock(repoRoot); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function writeMainSyncLock(repoRoot: string, lock: MainSyncLock): void { mainSyncSvc.writeMainSyncLock(repoRoot, lock); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function isLockStale(lock: MainSyncLock, hangTimeoutMinutes: number, now: number = Date.now()): boolean { return mainSyncSvc.isLockStale(lock, hangTimeoutMinutes, now); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function isRefreshInProgress(repoRoot: string, hangTimeoutMinutes: number, now: number = Date.now()): boolean { return mainSyncSvc.isRefreshInProgress(repoRoot, hangTimeoutMinutes, now); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function tryAcquireMainSyncLock(repoRoot: string, hangTimeoutMinutes: number, now: number = Date.now(), pid: number = process.pid): MainSyncLock | null { return mainSyncSvc.tryAcquireMainSyncLock(repoRoot, hangTimeoutMinutes, now, pid); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function inProcessLock(now: number = Date.now(), pid: number = process.pid): MainSyncLock { return mainSyncSvc.inProcessLock(now, pid); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function finishedLock(started: number): MainSyncLock { return mainSyncSvc.finishedLock(started); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function computeMainSyncStatus(repoRoot: string): MainSyncStatus { return mainSyncSvc.computeMainSyncStatus(repoRoot); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function squashRecoverySteps(currentBranch: string): string[] { return mainSyncSvc.squashRecoverySteps(currentBranch); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function stampCleanMainSyncStatus(repoRoot: string): void { mainSyncSvc.stampCleanMainSyncStatus(repoRoot); }\n"]}
|
|
1
|
+
{"version":3,"file":"main-sync-status.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/main-sync-status.ts"],"names":[],"mappings":";;;AA4gBA,gDAAiH;AAEjH,4CAA6G;AAE7G,gDAAwJ;AAExJ,wDAA4I;AAE5I,kDAA0I;AAE1I,0DAAkJ;AAElJ,4CAA0H;AAE1H,8CAAgI;AAEhI,kCAAiL;AAEjL,kDAAmM;AAEnM,wDAAqP;AAErP,sCAAgJ;AAEhJ,oCAAyG;AAEzG,sDAA+H;AAE/H,gEAA6I;AAE7I,kDAA+H;AAE/H,4DAAoH;;AA5iBpH,iDAA0C;AAC1C,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAE3D,+CAA2C;AAC3C,qDAM0B;AAOqC,yGAZ3D,yCAAwB,OAY2D;AAA9E,+FAVL,+BAAc,OAUK;AAAE,mGATrB,mCAAkB,OASqB;AAAE,iGARzC,iCAAgB,OAQyC;AAN7D,2CAAyD;AACzD,yCAAqC;AACrC,2CAA8C;AAM9C,sGAAsG;AACtG,wGAAwG;AACxG,qGAAqG;AACrG,wFAAwF;AAExF,oGAAoG;AACvF,QAAA,4BAA4B,GAAG,CAAC,CAAC;AAE9C,MAAM,qBAAqB,GAAG,uBAAuB,CAAC;AACtD,MAAM,mBAAmB,GAAG,qBAAqB,CAAC;AAElD,MAAM,oBAAoB,GAAG,WAAW,CAAC;AACzC,MAAM,mBAAmB,GAAG,UAAU,CAAC;AAEvC,sGAAsG;AACtG,sGAAsG;AACtG,MAAa,YAAY;IACrB,KAAK,CAAS;IACd,OAAO,CAAS;IAChB,GAAG,CAAS;IAEZ,YAAY,KAAa,EAAE,OAAe,EAAE,MAAc,CAAC;QACvD,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC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AG,CAAC,CAAC,CAAC,CAAC;AAChJ,4IAA4I;AAC5I,SAAgB,YAAY,CAAC,OAAe,IAAkB,OAAO,WAAW,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;AACzG,4IAA4I;AAC5I,SAAgB,qBAAqB,CAAC,QAAgB,IAAoB,OAAO,WAAW,CAAC,qBAAqB,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;AAC/H,4IAA4I;AAC5I,SAAgB,0BAA0B,CAAC,QAAgB,IAAwB,OAAO,WAAW,CAAC,0BAA0B,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;AAC7I,4IAA4I;AAC5I,SAAgB,mBAAmB,CAAC,aAAqB,IAAc,OAAO,WAAW,CAAC,mBAAmB,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC;AAC/H,4IAA4I;AAC5I,SAAgB,wBAAwB,CAAC,QAAgB,IAAU,WAAW,CAAC,wBAAwB,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC","sourcesContent":["import { spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { AtomicFile } from './atomic-file';\nimport {\n MAIN_SYNC_STATUS_VERSION,\n MainSyncFileStore,\n MainSyncStatus,\n MainSyncStatusFile,\n PullRequestIndex,\n} from './main-sync-file';\nimport { DotWebpieces, dotWebpieces } from './state-dir';\nimport { toError } from './to-error';\nimport { WorktreeService } from './worktrees';\n\n// The on-disk shape lives in main-sync-file.ts; re-exported so every existing importer of\n// `MainSyncStatus` from this module keeps working.\nexport { MainSyncStatus, MainSyncStatusFile, PullRequestIndex, MAIN_SYNC_STATUS_VERSION };\n\n// Shared \"is my feature branch healthy relative to origin/main?\" state. The SLOW signals (git fetch +\n// merge-base + same-file-overlap + a merged-PR lookup) are computed by the ai-hook-rules refresher in a\n// DETACHED background process; the feature-branch-guard only READS this cached file. pr-gate's merge\n// flow also writes it synchronously after a merge. Lives here (the shared dep of both).\n\n// How long an `inprocess` refresher lock may sit before a new refresher assumes the prior run hung.\nexport const DEFAULT_HANG_TIMEOUT_MINUTES = 5;\n\nconst MAIN_SYNC_STATUS_FILE = 'main-sync-status.json';\nconst MAIN_SYNC_LOCK_FILE = 'main-sync.lock.json';\n\nconst LOCK_STATE_INPROCESS = 'inprocess';\nconst LOCK_STATE_FINISHED = 'finished';\n\n// Concurrency state machine for the detached refresher. `started` is epoch ms. `pid` is the refresher\n// process's pid (0 = unknown) — used so a KILLED refresher doesn't wedge `inprocess` for the timeout.\nexport class MainSyncLock {\n state: string;\n started: number;\n pid: number;\n\n constructor(state: string, started: number, pid: number = 0) {\n this.state = state;\n this.started = started;\n this.pid = pid;\n }\n}\n\n// Raw JSON shape for the cast at the parse boundary.\ninterface RawLock {\n state?: string;\n started?: number;\n pid?: number;\n}\n\n// Result of a captured git/gh invocation: ok=false on spawn failure or non-zero exit.\ninterface CmdCapture {\n ok: boolean;\n out: string;\n}\n\n/**\n * Reads/writes the main-sync cache + lock and computes the slow \"is my branch healthy vs origin/main?\"\n * status. `@injectable(bindingScopeValues.Singleton)` so it's injectable and drawn in the rules-config DI design.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class MainSyncStatusService {\n constructor(\n private readonly dotDir: DotWebpieces = dotWebpieces,\n private readonly atomicFile: AtomicFile = new AtomicFile(),\n private readonly store: MainSyncFileStore = new MainSyncFileStore(atomicFile),\n private readonly worktrees: WorktreeService = new WorktreeService(),\n ) {}\n\n /**\n * SHARED scope: `<primary>/.webpieces/main-sync-status.json`, one per repo.\n *\n * It is the OUTPUT of the single-flight refresher below, so it has to live where the lock lives —\n * one `.git`, one `origin/main`, one fetch, one answer. A per-worktree copy under single-flight\n * would only ever be written for whichever worktree won the lock anyway.\n *\n * FORMERLY a known defect, now fixed: the file's CONTENT used to be keyed to ONE branch, and every\n * reader fails OPEN when the cached branch is not the branch being judged (`stale-cross-branch-cache\n * (fail-open)`). With several worktrees on several branches, only the winner of the lock was ever\n * described, so every other worktree's guards abstained — and which one was armed thrashed as the\n * lock changed hands. The file is now a MAP of branch -> status (see MainSyncStatusFile): the single\n * winning refresher enumerates every worktree and records all of their branches in one atomic write,\n * so one fetch arms everyone. Single-flight is unchanged; only what the winner writes changed.\n */\n mainSyncStatusPath(repoRoot: string): string {\n return this.dotDir.sharedFile(repoRoot, MAIN_SYNC_STATUS_FILE);\n }\n\n /**\n * SHARED scope — the single-flight lock for the whole repo.\n *\n * This is the fix for the filed bug \"the detached main-sync refresher's `git fetch` races the\n * agent's foreground `git fetch`/`git pull` and corrupts `.git/FETCH_HEAD`\". The lock was already\n * atomic (O_CREAT|O_EXCL) and already serialised refreshers against each other — but only WITHIN\n * one worktree, so N worktrees meant N locks and up to N concurrent `git fetch`es against the ONE\n * shared `.git`, which is exactly how a duplicate `for-merge` line lands in FETCH_HEAD. There is\n * one `.git`, so there is now one lock: at most one refresher in flight across all worktrees.\n *\n * Stale-lock handling is unchanged and still required (a lock nobody can clear is worse than the\n * race): the holder records pid + start epoch, and `tryAcquireMainSyncLock` reclaims it once\n * `isRefreshInProgress` proves the holder is finished, hung past hangTimeoutMinutes, or dead.\n */\n mainSyncLockPath(repoRoot: string): string {\n return this.dotDir.sharedFile(repoRoot, MAIN_SYNC_LOCK_FILE);\n }\n\n /**\n * The cached status FOR ONE BRANCH — the only read the four main-sync guards perform.\n *\n * `branch` is mandatory and is the branch being judged. A branch the last refresh never saw\n * returns null, which every guard already treats as `no-sync-cache (fail-open)`, so an unknown\n * branch degrades exactly as a missing file did. Any error (missing, truncated, malformed JSON)\n * also returns null — this must never throw on the blocking path.\n */\n readMainSyncStatus(repoRoot: string, branch: string): MainSyncStatus | null {\n return this.store.branchStatus(this.readMainSyncStatusFile(repoRoot), branch);\n }\n\n // The whole branch-keyed document, or null. Callers that need more than one branch use this.\n readMainSyncStatusFile(repoRoot: string): MainSyncStatusFile | null {\n return this.store.readFile(this.mainSyncStatusPath(repoRoot));\n }\n\n /**\n * Merge ONE branch's entry into the existing map, atomically, leaving siblings untouched.\n *\n * Read-modify-write rather than replace: this is the writer used by everyone who is NOT the\n * single-flight refresher (notably pr-gate's post-merge stamp, which holds no lock and knows about\n * exactly one branch). Replacing the document from there would erase every other worktree's entry\n * and silently disarm their guards until the next refresh.\n */\n writeMainSyncStatus(repoRoot: string, status: MainSyncStatus): void {\n this.store.mergeBranch(this.mainSyncStatusPath(repoRoot), status);\n }\n\n /**\n * Replace the WHOLE document — only the winning refresher may do this.\n *\n * ATOMIC (temp file + `rename()` in the same directory). The refresher writes this file while\n * guards on the blocking path read it, possibly from another worktree; a plain `writeFileSync`\n * truncates first, so a reader landing in that window gets a torn document. See AtomicFile.\n */\n writeMainSyncStatusFile(repoRoot: string, file: MainSyncStatusFile): void {\n this.store.writeFile(this.mainSyncStatusPath(repoRoot), file);\n }\n\n readMainSyncLock(repoRoot: string): MainSyncLock | null {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const lockPath = this.mainSyncLockPath(repoRoot);\n if (!fs.existsSync(lockPath)) return null;\n const raw = JSON.parse(fs.readFileSync(lockPath, 'utf8')) as RawLock;\n return new MainSyncLock(raw.state ?? LOCK_STATE_FINISHED, raw.started ?? 0, raw.pid ?? 0);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n\n writeMainSyncLock(repoRoot: string, lock: MainSyncLock): void {\n const lockPath = this.mainSyncLockPath(repoRoot);\n this.ensureDir(lockPath);\n fs.writeFileSync(lockPath, JSON.stringify(lock, null, 2) + '\\n');\n }\n\n // A lock is stale (prior refresher assumed hung) once `inprocess` longer than hangTimeoutMinutes.\n isLockStale(lock: MainSyncLock, hangTimeoutMinutes: number, now: number = Date.now()): boolean {\n return now - lock.started > hangTimeoutMinutes * 60 * 1000;\n }\n\n // True when another refresher is actively running and we should NOT start a second one.\n isRefreshInProgress(repoRoot: string, hangTimeoutMinutes: number, now: number = Date.now()): boolean {\n const lock = this.readMainSyncLock(repoRoot);\n if (!lock) return false;\n if (lock.state !== LOCK_STATE_INPROCESS) return false;\n if (this.isLockStale(lock, hangTimeoutMinutes, now)) return false;\n return this.isProcessAlive(lock.pid);\n }\n\n /**\n * ATOMICALLY take the refresher lock. Returns the held lock, or null when someone else holds it.\n *\n * Replaces the check-then-write pair (`isRefreshInProgress` then `writeMainSyncLock`), whose gap\n * let two detached refreshers both pass the check and then both run `git fetch` at once — the\n * concurrency this lock exists to prevent. The create uses the `wx` flag (O_CREAT|O_EXCL), so of\n * N racing refreshers exactly one creates the file.\n *\n * A lock file left behind by a FINISHED, hung, or killed refresher is reclaimed: we only unlink\n * and re-take it once `isRefreshInProgress` says the holder is provably not running, and we\n * re-read afterwards to confirm the entry we see is ours before claiming the lock.\n */\n tryAcquireMainSyncLock(\n repoRoot: string,\n hangTimeoutMinutes: number,\n now: number = Date.now(),\n pid: number = process.pid,\n ): MainSyncLock | null {\n const lockPath = this.mainSyncLockPath(repoRoot);\n this.ensureDir(lockPath);\n const lock = this.inProcessLock(now, pid);\n const payload = JSON.stringify(lock, null, 2) + '\\n';\n\n if (this.createExclusive(lockPath, payload)) return lock;\n\n // The file already exists. Leave it alone while a live refresher owns it.\n if (this.isRefreshInProgress(repoRoot, hangTimeoutMinutes, now)) return null;\n\n // Reclaim it: remove the dead entry, then re-take it exclusively so only one reclaimer wins.\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.unlinkSync(lockPath);\n } catch (err: unknown) {\n const error = toError(err);\n void error; // someone else reclaimed it first — the exclusive create below decides\n }\n if (!this.createExclusive(lockPath, payload)) return null;\n\n // Confirm the lock on disk is OURS (a simultaneous reclaimer could have unlinked ours and\n // written its own between the two calls above).\n const held = this.readMainSyncLock(repoRoot);\n if (!held || held.pid !== pid || held.started !== lock.started) return null;\n return lock;\n }\n\n // O_CREAT|O_EXCL write: true when THIS call created the file, false when it already existed.\n private createExclusive(lockPath: string, payload: string): boolean {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.writeFileSync(lockPath, 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 inProcessLock(now: number = Date.now(), pid: number = process.pid): MainSyncLock {\n return new MainSyncLock(LOCK_STATE_INPROCESS, now, pid);\n }\n\n finishedLock(started: number): MainSyncLock {\n return new MainSyncLock(LOCK_STATE_FINISHED, started, 0);\n }\n\n /**\n * The SLOW path for ONE branch: the branch checked out in `repoRoot`. Runs its own fetch and its\n * own `gh` query, so it is the right entry point for a single-worktree caller and for tests.\n * The refresher uses computeAllMainSyncStatuses instead — see there for why.\n */\n computeMainSyncStatus(repoRoot: string): MainSyncStatus {\n // Best-effort network refresh; offline just means we evaluate against the last-fetched ref.\n this.fetchOriginMain(repoRoot);\n return this.computeBranchStatus(repoRoot, this.gitBranch(repoRoot), this.loadPullRequestIndex(repoRoot));\n }\n\n /**\n * The SLOW path for EVERY branch this repo has checked out — what the detached refresher runs.\n *\n * The cache is shared by all worktrees but was written for one branch, so only one worktree's\n * guards were ever armed. Enumerating the worktrees here and writing all of their branches in one\n * atomic map arms every worktree off a single refresh.\n *\n * NETWORK COST DOES NOT SCALE WITH BRANCH COUNT, which is the whole reason this is a separate\n * method: ONE `git fetch` and ONE repo-wide `gh pr list` for all N branches (the old code asked\n * `gh` twice per branch, so looping it would have cost 2N round trips). Everything after that is\n * local git in each worktree — merge-base, rev-parse, diff, ls-files.\n *\n * The map is rebuilt from the LIVE worktree set every refresh, so a deleted branch or removed\n * worktree simply stops appearing. No pruning pass, no unbounded growth.\n */\n computeAllMainSyncStatuses(repoRoot: string): MainSyncStatusFile {\n this.fetchOriginMain(repoRoot);\n const index = this.loadPullRequestIndex(repoRoot);\n const branches: Record<string, MainSyncStatus> = {};\n for (const tree of this.worktrees.listWorktrees(repoRoot)) {\n // Detached HEAD (and a bare worktree) has no branch to key an entry on. Skipping it must\n // not stop the others being recorded, which is why this is a `continue`, not a bail-out.\n if (tree.branch === '' || this.hasBranch(branches, tree.branch)) continue;\n branches[tree.branch] = this.computeBranchStatus(tree.path, tree.branch, index);\n }\n // `main` always present, even with no worktree on it: read-stale-guard's state A looks itself\n // up under 'main', and an absent entry there would silently disarm the stale-main block.\n if (!this.hasBranch(branches, 'main')) branches['main'] = this.mainOnlyStatus(repoRoot);\n return new MainSyncStatusFile(MAIN_SYNC_STATUS_VERSION, new Date().toISOString(), branches);\n }\n\n private hasBranch(branches: Record<string, MainSyncStatus>, branch: string): boolean {\n return Object.prototype.hasOwnProperty.call(branches, branch);\n }\n\n /**\n * One branch's status, computed in `worktreePath` (the tree that has it checked out — the\n * working-tree overlap signals are only correct from there). Does NOT fetch and does NOT call\n * `gh`: both are done once per refresh by the caller.\n */\n // webpieces-disable max-lines-new-methods -- one cohesive slow-path computation\n private computeBranchStatus(repoRoot: string, branch: string, index: PullRequestIndex): MainSyncStatus {\n const mergedPr = index.mergedFor(branch);\n const openPr = index.openFor(branch);\n\n const head = this.capture(repoRoot, 'git', ['rev-parse', 'HEAD']);\n const originMain = this.capture(repoRoot, 'git', ['rev-parse', 'origin/main']);\n const localMain = this.localMainHash(repoRoot);\n const featureHead = head.ok ? head.out : '';\n if (!head.ok || !originMain.ok) {\n const status = this.benignStatus(branch, featureHead);\n status.branchAlreadyMerged = mergedPr !== '';\n status.mergedPr = mergedPr;\n status.openPr = openPr;\n status.localMain = localMain;\n return status;\n }\n\n const forkPoint = this.capture(repoRoot, 'git', ['merge-base', 'origin/main', 'HEAD']);\n if (!forkPoint.ok || forkPoint.out === '') {\n const noFork = new MainSyncStatus(branch, mergedPr !== '', mergedPr, false, null, originMain.out, featureHead, false, [], new Date().toISOString());\n noFork.openPr = openPr;\n noFork.localMain = localMain;\n return noFork;\n }\n\n const featureFiles = new Set(this.featureChangedFiles(repoRoot, forkPoint.out));\n const mainFiles = this.changedFiles(repoRoot, forkPoint.out, 'origin/main');\n const conflictFiles = mainFiles.filter((file: string): boolean => featureFiles.has(file));\n\n const status = new MainSyncStatus(\n branch,\n mergedPr !== '',\n mergedPr,\n true,\n forkPoint.out,\n originMain.out,\n featureHead,\n conflictFiles.length > 0,\n conflictFiles,\n new Date().toISOString(),\n );\n status.openPr = openPr;\n status.localMain = localMain;\n return status;\n }\n\n // The recovery steps when there is no fork point with origin/main (a bad merge of main into branch).\n squashRecoverySteps(currentBranch: string): string[] {\n return [\n '1. Fetch latest main: git fetch origin main',\n `2. New branch off origin/main: git checkout -b ${currentBranch}-v2 origin/main`,\n `3. Squash-merge old branch: git merge --squash ${currentBranch}`,\n ' ^^ HUMAN-ONLY. `git merge` is blocked for AI (redirect-how-to-merge-main). AI: ask the',\n ' human to run step 3, and warn them it is a raw merge — only correct here because the',\n ' branch is already broken. For a normal update from main they should push back and',\n ' tell you to use the gated 3-point merge instead: `pnpm wp-start-update` (paired with',\n ' `pnpm wp-finish-update`) when no PR is open, or `pnpm wp-start-upsert-pr` (paired with',\n ' `pnpm wp-finish-upsert-pr`) when a PR IS open — a PR MUST use the upsert-pr pair.',\n `4. Commit the squash: git add -A && git commit -m \"Squashed from ${currentBranch}\"`,\n '5. If a PR exists: open a NEW PR for the -v2 branch and close the old one.',\n ];\n }\n\n /**\n * Synchronously stamp a clean \"up to date with main\" status — call right after a successful merge.\n *\n * This is the one writer that takes NO lock, and it knows about exactly one branch. It therefore\n * goes through writeMainSyncStatus, which MERGES its entry into the existing map; writing a whole\n * document from here would wipe every other worktree's entry.\n */\n stampCleanMainSyncStatus(repoRoot: string): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const branch = this.gitBranch(repoRoot);\n const originMain = this.capture(repoRoot, 'git', ['rev-parse', 'origin/main']);\n const featureHead = this.capture(repoRoot, 'git', ['rev-parse', 'HEAD']);\n if (!originMain.ok || !featureHead.ok) return;\n const status = new MainSyncStatus(\n branch, false, '', true, originMain.out, originMain.out, featureHead.out, false, [], new Date().toISOString(),\n );\n status.localMain = this.localMainHash(repoRoot);\n this.writeMainSyncStatus(repoRoot, status);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n }\n\n /**\n * Refresh `origin/main` WITHOUT writing `.git/FETCH_HEAD`.\n *\n * WHY the flag is not optional: this runs in a DETACHED background process while the agent is\n * running its own foreground `git fetch` / `git pull` in the very same repo. `.git/FETCH_HEAD` is\n * a single file that git takes no lock on, so two overlapping fetches interleave their writes and\n * can leave the SAME `for-merge` line twice. `git pull` then reads two for-merge entries and dies\n * with `fatal: Cannot fast-forward to multiple branches` — wedging the exact command the\n * read-stale-guard tells the agent to run. `--no-write-fetch-head` (git >= 2.29) still updates the\n * remote-tracking ref, which is all anything downstream reads (`origin/main`, merge-base), so\n * nothing here needs FETCH_HEAD written at all.\n *\n * Older git rejects the flag; only then do we retry the plain form, accepting the old behaviour\n * rather than losing the refresh entirely on a pre-2020 git.\n */\n private fetchOriginMain(repoRoot: string): void {\n const safe = spawnSync('git', ['fetch', '--no-write-fetch-head', 'origin', 'main'], {\n cwd: repoRoot, encoding: 'utf8', stdio: ['ignore', 'ignore', 'pipe'],\n });\n if (safe.status === 0) return;\n if (!this.isUnknownGitOption(safe.stderr)) return; // a real failure (offline, auth) — not our business\n spawnSync('git', ['fetch', 'origin', 'main'], { cwd: repoRoot, stdio: 'ignore' });\n }\n\n // Did git reject the flag itself (too old), as opposed to failing the network refresh?\n private isUnknownGitOption(stderr: string | null): boolean {\n const text = (stderr ?? '').toLowerCase();\n return text.includes('unknown option') || text.includes('unknown switch') || text.includes('unrecognized option');\n }\n\n private ensureDir(filePath: string): void {\n fs.mkdirSync(path.dirname(filePath), { recursive: true });\n }\n\n // Liveness probe: is `pid` still a running process? pid <= 0 (unknown) → assume alive.\n private isProcessAlive(pid: number): boolean {\n if (pid <= 0) return true;\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.message.includes('ESRCH');\n }\n }\n\n // Run a command capturing trimmed stdout; ok=false on spawn failure or non-zero exit.\n private capture(repoRoot: string, cmd: string, args: string[]): CmdCapture {\n const result = spawnSync(cmd, args, { cwd: repoRoot, encoding: 'utf8' });\n if (result.status !== 0 || typeof result.stdout !== 'string') return { ok: false, out: '' };\n return { ok: true, out: result.stdout.trim() };\n }\n\n // The actual checked-out branch in repoRoot — cwd-correct so the cache's `branch` label matches.\n private gitBranch(repoRoot: string): string {\n const result = this.capture(repoRoot, 'git', ['rev-parse', '--abbrev-ref', 'HEAD']);\n return result.ok ? result.out : '';\n }\n\n // The LOCAL main hash. `refs/heads/main` (not the bare name) so it can never resolve to a remote\n // ref or a tag. '' when main does not exist locally — which the guard treats as fail-open.\n private localMainHash(repoRoot: string): string {\n const result = this.capture(repoRoot, 'git', ['rev-parse', 'refs/heads/main']);\n return result.ok ? result.out : '';\n }\n\n private changedFiles(repoRoot: string, base: string, head: string): string[] {\n const result = this.capture(repoRoot, 'git', ['diff', '--name-only', base, head]);\n if (!result.ok || result.out === '') return [];\n return result.out.split('\\n').map((line: string): string => line.trim()).filter((line: string): boolean => line.length > 0);\n }\n\n // Every file this feature branch has touched since the fork point — committed AND still in the\n // working tree (staged / unstaged / untracked), so a conflict is visible WHILE editing.\n private featureChangedFiles(repoRoot: string, forkPoint: string): string[] {\n const out = new Set<string>();\n const add = (args: string[]): void => {\n const r = this.capture(repoRoot, 'git', args);\n if (!r.ok || r.out === '') return;\n for (const line of r.out.split('\\n')) {\n const f = line.trim();\n if (f.length > 0) out.add(f);\n }\n };\n add(['diff', '--name-only', forkPoint, 'HEAD']); // committed since the fork point\n add(['diff', '--name-only', 'HEAD']); // unstaged working-tree edits\n add(['diff', '--name-only', '--cached', 'HEAD']); // staged edits\n add(['ls-files', '--others', '--exclude-standard']); // untracked new files (respects .gitignore)\n return [...out];\n }\n\n /**\n * ONE repo-wide `gh pr list` giving every branch's merged/open PR — replaces the two per-branch\n * `--head <branch>` queries. `--limit 200` bounds it; a branch whose only PR is older than that\n * falls out of the index and reads as \"no PR\", which is the fail-OPEN direction (no merged PR =\n * no block), the same way a missing `gh` or an offline machine already degraded.\n */\n private loadPullRequestIndex(repoRoot: string): PullRequestIndex {\n const result = this.capture(repoRoot, 'gh', [\n 'pr', 'list', '--state', 'all', '--json', 'number,headRefName,state', '--limit', '200',\n ]);\n if (!result.ok || result.out === '') return new PullRequestIndex({}, {});\n return this.store.indexPullRequests(result.out);\n }\n\n /**\n * A `main` entry synthesised WITHOUT a worktree standing on main. Carries only the two hashes\n * read-stale-guard / stale-main-bash-guard actually compare (originMain vs the live tree's\n * ancestry) — never merged, never conflicting, so it can only ever produce the stale-main verdict.\n */\n private mainOnlyStatus(repoRoot: string): MainSyncStatus {\n const originMain = this.capture(repoRoot, 'git', ['rev-parse', 'origin/main']);\n const localMain = this.localMainHash(repoRoot);\n const status = new MainSyncStatus(\n 'main', false, '', true, localMain === '' ? null : localMain,\n originMain.ok ? originMain.out : '', localMain, false, [], new Date().toISOString(),\n );\n status.localMain = localMain;\n return status;\n }\n\n // A benign status that never blocks — used when origin/main can't be resolved.\n private benignStatus(branch: string, featureHead: string): MainSyncStatus {\n return new MainSyncStatus(branch, false, '', true, null, '', featureHead, false, [], new Date().toISOString());\n }\n}\n\n// Temporary migration delegators to MainSyncStatusService — removed once consumers inject it.\nconst mainSyncSvc = new MainSyncStatusService();\n\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function mainSyncStatusPath(repoRoot: string): string { return mainSyncSvc.mainSyncStatusPath(repoRoot); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function mainSyncLockPath(repoRoot: string): string { return mainSyncSvc.mainSyncLockPath(repoRoot); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function readMainSyncStatus(repoRoot: string, branch: string): MainSyncStatus | null { return mainSyncSvc.readMainSyncStatus(repoRoot, branch); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function readMainSyncStatusFile(repoRoot: string): MainSyncStatusFile | null { return mainSyncSvc.readMainSyncStatusFile(repoRoot); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function writeMainSyncStatus(repoRoot: string, status: MainSyncStatus): void { mainSyncSvc.writeMainSyncStatus(repoRoot, status); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function writeMainSyncStatusFile(repoRoot: string, file: MainSyncStatusFile): void { mainSyncSvc.writeMainSyncStatusFile(repoRoot, file); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function readMainSyncLock(repoRoot: string): MainSyncLock | null { return mainSyncSvc.readMainSyncLock(repoRoot); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function writeMainSyncLock(repoRoot: string, lock: MainSyncLock): void { mainSyncSvc.writeMainSyncLock(repoRoot, lock); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function isLockStale(lock: MainSyncLock, hangTimeoutMinutes: number, now: number = Date.now()): boolean { return mainSyncSvc.isLockStale(lock, hangTimeoutMinutes, now); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function isRefreshInProgress(repoRoot: string, hangTimeoutMinutes: number, now: number = Date.now()): boolean { return mainSyncSvc.isRefreshInProgress(repoRoot, hangTimeoutMinutes, now); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function tryAcquireMainSyncLock(repoRoot: string, hangTimeoutMinutes: number, now: number = Date.now(), pid: number = process.pid): MainSyncLock | null { return mainSyncSvc.tryAcquireMainSyncLock(repoRoot, hangTimeoutMinutes, now, pid); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function inProcessLock(now: number = Date.now(), pid: number = process.pid): MainSyncLock { return mainSyncSvc.inProcessLock(now, pid); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function finishedLock(started: number): MainSyncLock { return mainSyncSvc.finishedLock(started); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function computeMainSyncStatus(repoRoot: string): MainSyncStatus { return mainSyncSvc.computeMainSyncStatus(repoRoot); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function computeAllMainSyncStatuses(repoRoot: string): MainSyncStatusFile { return mainSyncSvc.computeAllMainSyncStatuses(repoRoot); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function squashRecoverySteps(currentBranch: string): string[] { return mainSyncSvc.squashRecoverySteps(currentBranch); }\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to MainSyncStatusService; removed once consumers inject it\nexport function stampCleanMainSyncStatus(repoRoot: string): void { mainSyncSvc.stampCleanMainSyncStatus(repoRoot); }\n"]}
|
|
@@ -33,6 +33,14 @@ export declare class ReviewerTranscript {
|
|
|
33
33
|
readDoc: boolean;
|
|
34
34
|
toolCallCount: number;
|
|
35
35
|
offRepoSearches: number;
|
|
36
|
+
/**
|
|
37
|
+
* The model(s) that ACTUALLY served this reviewer, observed in its transcript — not the `model:` its
|
|
38
|
+
* agent file requested, which can silently disagree, and not anything the reviewer claimed.
|
|
39
|
+
*
|
|
40
|
+
* Copied here for the reason the whole class exists: the transcript is a wasting asset (~30 days),
|
|
41
|
+
* and after it expires this row is the only surviving answer to "which model reviewed this?".
|
|
42
|
+
*/
|
|
43
|
+
models: string[];
|
|
36
44
|
constructor(evidence: ReviewerEvidence, paths: ReviewerPaths);
|
|
37
45
|
}
|
|
38
46
|
/** What the reviewers were handed, whether or not any of them opened it. Data-only. */
|
package/src/review-provenance.js
CHANGED
|
@@ -55,6 +55,14 @@ class ReviewerTranscript {
|
|
|
55
55
|
readDoc;
|
|
56
56
|
toolCallCount;
|
|
57
57
|
offRepoSearches;
|
|
58
|
+
/**
|
|
59
|
+
* The model(s) that ACTUALLY served this reviewer, observed in its transcript — not the `model:` its
|
|
60
|
+
* agent file requested, which can silently disagree, and not anything the reviewer claimed.
|
|
61
|
+
*
|
|
62
|
+
* Copied here for the reason the whole class exists: the transcript is a wasting asset (~30 days),
|
|
63
|
+
* and after it expires this row is the only surviving answer to "which model reviewed this?".
|
|
64
|
+
*/
|
|
65
|
+
models;
|
|
58
66
|
constructor(evidence, paths) {
|
|
59
67
|
this.id = evidence.agentType; // a checklist's id IS its subagent name (see ChecklistDefinition)
|
|
60
68
|
this.agentType = evidence.agentType;
|
|
@@ -68,6 +76,7 @@ class ReviewerTranscript {
|
|
|
68
76
|
this.readDoc = evidence.readDoc;
|
|
69
77
|
this.toolCallCount = evidence.toolCallCount;
|
|
70
78
|
this.offRepoSearches = evidence.offRepoSearches;
|
|
79
|
+
this.models = evidence.models;
|
|
71
80
|
}
|
|
72
81
|
}
|
|
73
82
|
exports.ReviewerTranscript = ReviewerTranscript;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"review-provenance.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/review-provenance.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,+CAAyB;AACzB,yCAA2D;AAC3D,yCAAqC;AAGrC,4GAA4G;AAC5G,MAAM,eAAe,GAAG,iBAAiB,CAAC;AAC1C,MAAM,mBAAmB,GAAG,qBAAqB,CAAC;AAElD;;;;GAIG;AACU,QAAA,sBAAsB,GAAG,EAAE,CAAC;AAEzC,MAAM,YAAY,GACd,uGAAuG;IACvG,yGAAyG;IACzG,qGAAqG;IACrG,yGAAyG;IACzG,yGAAyG;IACzG,kFAAkF,CAAC;AAEvF,sFAAsF;AACtF,MAAa,aAAa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AAC;YACX,OAAO,CAAC,CAAC;QACb,CAAC;IACL,CAAC;IAEO,OAAO,CAAC,GAAW;QACvB,qGAAqG;QACrG,8DAA8D;QAC9D,IAAI,CAAC;YACD,OAAO,EAAE,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC;QAC/B,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;IAED,yFAAyF;IACjF,QAAQ,CAAC,QAAgB;QAC7B,mHAAmH;QACnH,8DAA8D;QAC9D,IAAI,CAAC;YACD,yFAAyF;YACzF,OAAO,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,YAAY,CAAC,QAAQ,EAAE,MAAM,CAAC,CAA4B,CAAC;QACpF,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;AA9JY,0DAAuB;kCAAvB,uBAAuB;IADnC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;GAC5B,uBAAuB,CA8JnC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { toError } from './to-error';\nimport { ReviewerEvidence } from './subagent-provenance';\n\n// The audit record `wp-finish-upsert-pr` writes beside review.json, and where a consumed one is retired to.\nconst PROVENANCE_FILE = 'provenance.json';\nconst OLD_PROVENANCE_FILE = 'old-provenance.json';\n\n/**\n * Claude Code deletes transcripts after `cleanupPeriodDays`; 30 is its default and what applies when the\n * setting is absent, which is the common case. Recorded in every provenance file so a reader knows how\n * long the links it is holding remain resolvable rather than discovering it by following a dead path.\n */\nexport const DEFAULT_RETENTION_DAYS = 30;\n\nconst WHAT_THIS_IS =\n 'AUDIT RECORD — written by wp-finish-upsert-pr, never by an AI. It links each reviewer verdict to the ' +\n 'transcript of the subagent that produced it, and records what that reviewer was OFFERED versus what it ' +\n 'demonstrably READ. Open it to audit the review process itself: whether a verdict was written by an ' +\n 'agent that actually opened the diff and its checklist doc. Do not hand-edit it, and do not treat it as ' +\n 'a review — it says nothing about whether the code is good, only about how it was looked at. The linked ' +\n 'transcripts expire (see transcriptsExpireOn); the counters recorded here do not.';\n\n/** Where ONE reviewer's inputs and output live on disk. Data-only (per CLAUDE.md). */\nexport class ReviewerPaths {\n verdictFile: string; // the review-<id>.json this reviewer was told to write\n instructionsFile: string; // its generated <subagent>.instructions.md\n docPath: string; // its checklist's guidance doc ('' when the checklist names none)\n\n constructor(verdictFile: string, instructionsFile: string, docPath: string) {\n this.verdictFile = verdictFile;\n this.instructionsFile = instructionsFile;\n this.docPath = docPath;\n }\n}\n\n/**\n * ONE reviewer's provenance row: which agent ran, where its transcript is, and the evidence counters read\n * out of that transcript. Data-only, and its FIELD NAMES ARE THE JSON KEYS — the file is written by\n * serializing these objects directly, so renaming a field renames it in every consumer's audit record.\n *\n * The counters are copied here rather than left to be re-derived because the transcript they came from is a\n * wasting asset (~30 days). After it expires this row still answers \"did that reviewer read the diff?\".\n */\nexport class ReviewerTranscript {\n id: string;\n agentType: string;\n agentId: string;\n transcript: string; // absolute path to agent-<id>.jsonl, '' when it could not be resolved\n transcriptExists: boolean;\n verdictFile: string;\n instructionsFile: string;\n docPath: string;\n readDiff: boolean;\n readDoc: boolean;\n toolCallCount: number;\n offRepoSearches: number;\n\n constructor(evidence: ReviewerEvidence, paths: ReviewerPaths) {\n this.id = evidence.agentType; // a checklist's id IS its subagent name (see ChecklistDefinition)\n this.agentType = evidence.agentType;\n this.agentId = evidence.agentId;\n this.transcript = evidence.transcriptPath;\n this.transcriptExists = evidence.transcriptPath !== '' && fs.existsSync(evidence.transcriptPath);\n this.verdictFile = paths.verdictFile;\n this.instructionsFile = paths.instructionsFile;\n this.docPath = paths.docPath;\n this.readDiff = evidence.readDiff;\n this.readDoc = evidence.readDoc;\n this.toolCallCount = evidence.toolCallCount;\n this.offRepoSearches = evidence.offRepoSearches;\n }\n}\n\n/** What the reviewers were handed, whether or not any of them opened it. Data-only. */\nexport class OfferedContext {\n diffDir: string;\n instructionsDir: string;\n\n constructor(diffDir: string, instructionsDir: string) {\n this.diffDir = diffDir;\n this.instructionsDir = instructionsDir;\n }\n}\n\n/**\n * What {@link ReviewProvenanceService.write} is asked to record. Data-only; `offered` and `reviewers` are\n * assigned after construction (the same shape ChecklistCommentRow uses) so this never becomes a 7-param\n * constructor.\n */\nexport class ProvenanceWriteRequest {\n prDir: string;\n branch: string;\n headSha: string;\n provenanceStatus: string; // PROVENANCE_OK | PROVENANCE_MISSING | PROVENANCE_SKIPPED\n offered: OfferedContext = new OfferedContext('', '');\n reviewers: ReviewerTranscript[] = [];\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(prDir: string, branch: string, headSha: string, provenanceStatus: string) {\n this.prDir = prDir;\n this.branch = branch;\n this.headSha = headSha;\n this.provenanceStatus = provenanceStatus;\n }\n}\n\n/**\n * The written record. Field names are the JSON keys, in this order — `_WHAT_THIS_IS` is declared FIRST so\n * anything that opens the file reads what it is before it reads anything it might act on, exactly as\n * ReviewJsonService.archiveReviewJson stamps its note first.\n */\nexport class ReviewProvenance {\n // webpieces-disable naming-convention -- the leading underscore marks a note-to-the-reader key, not data\n _WHAT_THIS_IS = WHAT_THIS_IS;\n sessionId: string;\n mainTranscript: string;\n branch: string;\n headSha: string;\n stampedAt: string;\n transcriptRetentionDays: number;\n transcriptsExpireOn: string;\n provenanceStatus: string;\n offered: OfferedContext;\n reviewers: ReviewerTranscript[];\n\n constructor(request: ProvenanceWriteRequest) {\n this.sessionId = '';\n this.mainTranscript = '';\n this.branch = request.branch;\n this.headSha = request.headSha;\n this.stampedAt = '';\n this.transcriptRetentionDays = DEFAULT_RETENTION_DAYS;\n this.transcriptsExpireOn = '';\n this.provenanceStatus = request.provenanceStatus;\n this.offered = request.offered;\n this.reviewers = request.reviewers;\n }\n}\n\n/**\n * Records WHICH transcript produced which verdict, so the review process itself can be audited later.\n *\n * Why a service and not a field the AI writes: a reviewer subagent CANNOT know its own transcript path. The\n * environment exposes `CLAUDE_CODE_SESSION_ID` — the PARENT session — and no agent id, so a self-reported\n * link would be invented. Every path here is derived from the harness's own artifacts:\n * ~/.claude/projects/*/<sessionId>.jsonl → the main agent's transcript\n * ~/.claude/projects/*/<sessionId>/subagents/agent-<id>.jsonl → one reviewer's transcript\n * The subagent half is already resolved by {@link SubagentProvenanceService}; this carries it to disk and\n * adds the session-level facts (which session, how long the links live).\n *\n * Deliberately a SEPARATE file from review.json / review-<id>.json: those are AI-authored and stay\n * byte-untouched, so nothing here can be confused for something a reviewer claimed about itself.\n *\n * Best-effort throughout — an unreadable ~/.claude degrades the record to empty links, never fails a PR.\n * Same reasoning as SubagentProvenanceService: this reads undocumented Claude Code internals, and a format\n * change must not wedge a consumer's PR.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it is drawn in the DI design and injected by type.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ReviewProvenanceService {\n // Where the audit record for a branch lives, beside review.json.\n provenancePath(prDir: string): string {\n return path.join(prDir, PROVENANCE_FILE);\n }\n\n // Where a consumed record is retired to — the mirror of ReviewJsonService.oldReviewJsonPath, so an\n // archived old-review.json keeps the transcript links belonging to the round that produced it.\n oldProvenancePath(prDir: string): string {\n return path.join(prDir, OLD_PROVENANCE_FILE);\n }\n\n // The current Claude Code session id, or '' outside a Claude Code session (plain terminal / CI).\n sessionId(): string {\n return (process.env['CLAUDE_CODE_SESSION_ID'] ?? '').trim();\n }\n\n /**\n * The main agent's own transcript: `~/.claude/projects/<cwd-slug>/<sessionId>.jsonl`. Located by\n * scanning every project dir for the file named after the session, so the cwd-slug — which is a\n * mangling of the working directory we would otherwise have to reproduce exactly — never has to be\n * derived. '' when there is no session or the file is not there.\n */\n mainTranscript(): string {\n const session = this.sessionId();\n if (session === '') return '';\n const projects = path.join(os.homedir(), '.claude', 'projects');\n for (const proj of this.readDir(projects)) {\n const candidate = path.join(projects, proj, `${session}.jsonl`);\n if (fs.existsSync(candidate)) return candidate;\n }\n return '';\n }\n\n /**\n * How many days Claude Code keeps transcripts: `cleanupPeriodDays` from ~/.claude/settings.json (then\n * settings.local.json), else {@link DEFAULT_RETENTION_DAYS}. The setting is usually absent, which is\n * why the default is documented rather than left implicit.\n */\n retentionDays(): number {\n const dir = path.join(os.homedir(), '.claude');\n for (const file of ['settings.json', 'settings.local.json']) {\n const settings = this.readJson(path.join(dir, file));\n const days = settings?.['cleanupPeriodDays'];\n if (typeof days === 'number' && Number.isFinite(days) && days > 0) return days;\n }\n return DEFAULT_RETENTION_DAYS;\n }\n\n /**\n * The date the FIRST of these transcripts becomes unreadable: the oldest one's mtime + retentionDays,\n * as an ISO date. The oldest rather than the newest because that is when the audit trail starts losing\n * links, and a reader planning to follow them needs the pessimistic answer. '' when none exist.\n */\n expiresOn(transcripts: readonly string[], retentionDays: number): string {\n let oldest = 0;\n for (const file of transcripts) {\n const mtime = this.mtimeOf(file);\n if (mtime !== 0 && (oldest === 0 || mtime < oldest)) oldest = mtime;\n }\n if (oldest === 0) return '';\n const expiry = new Date(oldest + retentionDays * 24 * 60 * 60 * 1000);\n return expiry.toISOString().slice(0, 10);\n }\n\n /**\n * Write the record to `<prDir>/provenance.json` and return its path ('' if it could not be written).\n *\n * Written on EVERY finish, including one that refuses for a missing reviewer: a refused round is\n * precisely the one worth auditing, and a record that only ever appears on success cannot answer \"what\n * did the reviewers do the time this was rejected?\".\n */\n write(request: ProvenanceWriteRequest): string {\n const provenance = this.build(request);\n const target = this.provenancePath(request.prDir);\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: the audit record is never worth failing a PR over\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.mkdirSync(request.prDir, { recursive: true });\n fs.writeFileSync(target, JSON.stringify(provenance, null, 2) + '\\n');\n return target;\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return '';\n }\n }\n\n // Retire the record for the round that just shipped: copy it to old-provenance.json beside the\n // old-review.json it belongs to. A COPY, not a move — unlike review.json this file is not an input to\n // anything, so leaving it in place cannot mislead a later reviewer, and the next finish overwrites it.\n archive(prDir: string): string {\n const source = this.provenancePath(prDir);\n if (!fs.existsSync(source)) return '';\n const target = this.oldProvenancePath(prDir);\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: a failed archive must not fail the command\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.copyFileSync(source, target);\n return target;\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return '';\n }\n }\n\n // Fill in the session-level facts the caller cannot know: which session, which transcripts, how long.\n private build(request: ProvenanceWriteRequest): ReviewProvenance {\n const provenance = new ReviewProvenance(request);\n provenance.sessionId = this.sessionId();\n provenance.mainTranscript = this.mainTranscript();\n provenance.stampedAt = new Date().toISOString();\n provenance.transcriptRetentionDays = this.retentionDays();\n const linked = [provenance.mainTranscript, ...request.reviewers.map(\n (r: ReviewerTranscript): string => r.transcript)].filter((p: string): boolean => p !== '');\n provenance.transcriptsExpireOn = this.expiresOn(linked, provenance.transcriptRetentionDays);\n return provenance;\n }\n\n // Epoch millis of a file's mtime, or 0 when it cannot be read.\n private mtimeOf(filePath: string): number {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unstattable transcript contributes no expiry\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return fs.statSync(filePath).mtime.getTime();\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return 0;\n }\n }\n\n private readDir(dir: string): string[] {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unreadable dir yields [] (best-effort)\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 // 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 settings → null (fall through to the default)\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"]}
|
|
1
|
+
{"version":3,"file":"review-provenance.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/review-provenance.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,+CAAyB;AACzB,yCAA2D;AAC3D,yCAAqC;AAGrC,4GAA4G;AAC5G,MAAM,eAAe,GAAG,iBAAiB,CAAC;AAC1C,MAAM,mBAAmB,GAAG,qBAAqB,CAAC;AAElD;;;;GAIG;AACU,QAAA,sBAAsB,GAAG,EAAE,CAAC;AAEzC,MAAM,YAAY,GACd,uGAAuG;IACvG,yGAAyG;IACzG,qGAAqG;IACrG,yGAAyG;IACzG,yGAAyG;IACzG,kFAAkF,CAAC;AAEvF,sFAAsF;AACtF,MAAa,aAAa;IACtB,WAAW,CAAS,CAAO,uDAAuD;IAClF,gBAAgB,CAAS,CAAE,2CAA2C;IACtE,OAAO,CAAS,CAAW,kEAAkE;IAE7F,YAAY,WAAmB,EAAE,gBAAwB,EAAE,OAAe;QACtE,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,IAAI,CAAC,gBAAgB,GAAG,gBAAgB,CAAC;QACzC,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IAC3B,CAAC;CACJ;AAVD,sCAUC;AAED;;;;;;;GAOG;AACH,MAAa,kBAAkB;IAC3B,EAAE,CAAS;IACX,SAAS,CAAS;IAClB,OAAO,CAAS;IAChB,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,CAAC;QACd,CAAC;IACL,CAAC;IAED,yFAAyF;IACjF,QAAQ,CAAC,QAAgB;QAC7B,mHAAmH;QACnH,8DAA8D;QAC9D,IAAI,CAAC;YACD,yFAAyF;YACzF,OAAO,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,YAAY,CAAC,QAAQ,EAAE,MAAM,CAAC,CAA4B,CAAC;QACpF,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;AA9JY,0DAAuB;kCAAvB,uBAAuB;IADnC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;GAC5B,uBAAuB,CA8JnC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { toError } from './to-error';\nimport { ReviewerEvidence } from './subagent-provenance';\n\n// The audit record `wp-finish-upsert-pr` writes beside review.json, and where a consumed one is retired to.\nconst PROVENANCE_FILE = 'provenance.json';\nconst OLD_PROVENANCE_FILE = 'old-provenance.json';\n\n/**\n * Claude Code deletes transcripts after `cleanupPeriodDays`; 30 is its default and what applies when the\n * setting is absent, which is the common case. Recorded in every provenance file so a reader knows how\n * long the links it is holding remain resolvable rather than discovering it by following a dead path.\n */\nexport const DEFAULT_RETENTION_DAYS = 30;\n\nconst WHAT_THIS_IS =\n 'AUDIT RECORD — written by wp-finish-upsert-pr, never by an AI. It links each reviewer verdict to the ' +\n 'transcript of the subagent that produced it, and records what that reviewer was OFFERED versus what it ' +\n 'demonstrably READ. Open it to audit the review process itself: whether a verdict was written by an ' +\n 'agent that actually opened the diff and its checklist doc. Do not hand-edit it, and do not treat it as ' +\n 'a review — it says nothing about whether the code is good, only about how it was looked at. The linked ' +\n 'transcripts expire (see transcriptsExpireOn); the counters recorded here do not.';\n\n/** Where ONE reviewer's inputs and output live on disk. Data-only (per CLAUDE.md). */\nexport class ReviewerPaths {\n verdictFile: string; // the review-<id>.json this reviewer was told to write\n instructionsFile: string; // its generated <subagent>.instructions.md\n docPath: string; // its checklist's guidance doc ('' when the checklist names none)\n\n constructor(verdictFile: string, instructionsFile: string, docPath: string) {\n this.verdictFile = verdictFile;\n this.instructionsFile = instructionsFile;\n this.docPath = docPath;\n }\n}\n\n/**\n * ONE reviewer's provenance row: which agent ran, where its transcript is, and the evidence counters read\n * out of that transcript. Data-only, and its FIELD NAMES ARE THE JSON KEYS — the file is written by\n * serializing these objects directly, so renaming a field renames it in every consumer's audit record.\n *\n * The counters are copied here rather than left to be re-derived because the transcript they came from is a\n * wasting asset (~30 days). After it expires this row still answers \"did that reviewer read the diff?\".\n */\nexport class ReviewerTranscript {\n id: string;\n agentType: string;\n agentId: string;\n transcript: string; // absolute path to agent-<id>.jsonl, '' when it could not be resolved\n transcriptExists: boolean;\n verdictFile: string;\n instructionsFile: string;\n docPath: string;\n readDiff: boolean;\n readDoc: boolean;\n toolCallCount: number;\n offRepoSearches: number;\n /**\n * The model(s) that ACTUALLY served this reviewer, observed in its transcript — not the `model:` its\n * agent file requested, which can silently disagree, and not anything the reviewer claimed.\n *\n * Copied here for the reason the whole class exists: the transcript is a wasting asset (~30 days),\n * and after it expires this row is the only surviving answer to \"which model reviewed this?\".\n */\n models: string[];\n\n constructor(evidence: ReviewerEvidence, paths: ReviewerPaths) {\n this.id = evidence.agentType; // a checklist's id IS its subagent name (see ChecklistDefinition)\n this.agentType = evidence.agentType;\n this.agentId = evidence.agentId;\n this.transcript = evidence.transcriptPath;\n this.transcriptExists = evidence.transcriptPath !== '' && fs.existsSync(evidence.transcriptPath);\n this.verdictFile = paths.verdictFile;\n this.instructionsFile = paths.instructionsFile;\n this.docPath = paths.docPath;\n this.readDiff = evidence.readDiff;\n this.readDoc = evidence.readDoc;\n this.toolCallCount = evidence.toolCallCount;\n this.offRepoSearches = evidence.offRepoSearches;\n this.models = evidence.models;\n }\n}\n\n/** What the reviewers were handed, whether or not any of them opened it. Data-only. */\nexport class OfferedContext {\n diffDir: string;\n instructionsDir: string;\n\n constructor(diffDir: string, instructionsDir: string) {\n this.diffDir = diffDir;\n this.instructionsDir = instructionsDir;\n }\n}\n\n/**\n * What {@link ReviewProvenanceService.write} is asked to record. Data-only; `offered` and `reviewers` are\n * assigned after construction (the same shape ChecklistCommentRow uses) so this never becomes a 7-param\n * constructor.\n */\nexport class ProvenanceWriteRequest {\n prDir: string;\n branch: string;\n headSha: string;\n provenanceStatus: string; // PROVENANCE_OK | PROVENANCE_MISSING | PROVENANCE_SKIPPED\n offered: OfferedContext = new OfferedContext('', '');\n reviewers: ReviewerTranscript[] = [];\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(prDir: string, branch: string, headSha: string, provenanceStatus: string) {\n this.prDir = prDir;\n this.branch = branch;\n this.headSha = headSha;\n this.provenanceStatus = provenanceStatus;\n }\n}\n\n/**\n * The written record. Field names are the JSON keys, in this order — `_WHAT_THIS_IS` is declared FIRST so\n * anything that opens the file reads what it is before it reads anything it might act on, exactly as\n * ReviewJsonService.archiveReviewJson stamps its note first.\n */\nexport class ReviewProvenance {\n // webpieces-disable naming-convention -- the leading underscore marks a note-to-the-reader key, not data\n _WHAT_THIS_IS = WHAT_THIS_IS;\n sessionId: string;\n mainTranscript: string;\n branch: string;\n headSha: string;\n stampedAt: string;\n transcriptRetentionDays: number;\n transcriptsExpireOn: string;\n provenanceStatus: string;\n offered: OfferedContext;\n reviewers: ReviewerTranscript[];\n\n constructor(request: ProvenanceWriteRequest) {\n this.sessionId = '';\n this.mainTranscript = '';\n this.branch = request.branch;\n this.headSha = request.headSha;\n this.stampedAt = '';\n this.transcriptRetentionDays = DEFAULT_RETENTION_DAYS;\n this.transcriptsExpireOn = '';\n this.provenanceStatus = request.provenanceStatus;\n this.offered = request.offered;\n this.reviewers = request.reviewers;\n }\n}\n\n/**\n * Records WHICH transcript produced which verdict, so the review process itself can be audited later.\n *\n * Why a service and not a field the AI writes: a reviewer subagent CANNOT know its own transcript path. The\n * environment exposes `CLAUDE_CODE_SESSION_ID` — the PARENT session — and no agent id, so a self-reported\n * link would be invented. Every path here is derived from the harness's own artifacts:\n * ~/.claude/projects/*/<sessionId>.jsonl → the main agent's transcript\n * ~/.claude/projects/*/<sessionId>/subagents/agent-<id>.jsonl → one reviewer's transcript\n * The subagent half is already resolved by {@link SubagentProvenanceService}; this carries it to disk and\n * adds the session-level facts (which session, how long the links live).\n *\n * Deliberately a SEPARATE file from review.json / review-<id>.json: those are AI-authored and stay\n * byte-untouched, so nothing here can be confused for something a reviewer claimed about itself.\n *\n * Best-effort throughout — an unreadable ~/.claude degrades the record to empty links, never fails a PR.\n * Same reasoning as SubagentProvenanceService: this reads undocumented Claude Code internals, and a format\n * change must not wedge a consumer's PR.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it is drawn in the DI design and injected by type.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ReviewProvenanceService {\n // Where the audit record for a branch lives, beside review.json.\n provenancePath(prDir: string): string {\n return path.join(prDir, PROVENANCE_FILE);\n }\n\n // Where a consumed record is retired to — the mirror of ReviewJsonService.oldReviewJsonPath, so an\n // archived old-review.json keeps the transcript links belonging to the round that produced it.\n oldProvenancePath(prDir: string): string {\n return path.join(prDir, OLD_PROVENANCE_FILE);\n }\n\n // The current Claude Code session id, or '' outside a Claude Code session (plain terminal / CI).\n sessionId(): string {\n return (process.env['CLAUDE_CODE_SESSION_ID'] ?? '').trim();\n }\n\n /**\n * The main agent's own transcript: `~/.claude/projects/<cwd-slug>/<sessionId>.jsonl`. Located by\n * scanning every project dir for the file named after the session, so the cwd-slug — which is a\n * mangling of the working directory we would otherwise have to reproduce exactly — never has to be\n * derived. '' when there is no session or the file is not there.\n */\n mainTranscript(): string {\n const session = this.sessionId();\n if (session === '') return '';\n const projects = path.join(os.homedir(), '.claude', 'projects');\n for (const proj of this.readDir(projects)) {\n const candidate = path.join(projects, proj, `${session}.jsonl`);\n if (fs.existsSync(candidate)) return candidate;\n }\n return '';\n }\n\n /**\n * How many days Claude Code keeps transcripts: `cleanupPeriodDays` from ~/.claude/settings.json (then\n * settings.local.json), else {@link DEFAULT_RETENTION_DAYS}. The setting is usually absent, which is\n * why the default is documented rather than left implicit.\n */\n retentionDays(): number {\n const dir = path.join(os.homedir(), '.claude');\n for (const file of ['settings.json', 'settings.local.json']) {\n const settings = this.readJson(path.join(dir, file));\n const days = settings?.['cleanupPeriodDays'];\n if (typeof days === 'number' && Number.isFinite(days) && days > 0) return days;\n }\n return DEFAULT_RETENTION_DAYS;\n }\n\n /**\n * The date the FIRST of these transcripts becomes unreadable: the oldest one's mtime + retentionDays,\n * as an ISO date. The oldest rather than the newest because that is when the audit trail starts losing\n * links, and a reader planning to follow them needs the pessimistic answer. '' when none exist.\n */\n expiresOn(transcripts: readonly string[], retentionDays: number): string {\n let oldest = 0;\n for (const file of transcripts) {\n const mtime = this.mtimeOf(file);\n if (mtime !== 0 && (oldest === 0 || mtime < oldest)) oldest = mtime;\n }\n if (oldest === 0) return '';\n const expiry = new Date(oldest + retentionDays * 24 * 60 * 60 * 1000);\n return expiry.toISOString().slice(0, 10);\n }\n\n /**\n * Write the record to `<prDir>/provenance.json` and return its path ('' if it could not be written).\n *\n * Written on EVERY finish, including one that refuses for a missing reviewer: a refused round is\n * precisely the one worth auditing, and a record that only ever appears on success cannot answer \"what\n * did the reviewers do the time this was rejected?\".\n */\n write(request: ProvenanceWriteRequest): string {\n const provenance = this.build(request);\n const target = this.provenancePath(request.prDir);\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: the audit record is never worth failing a PR over\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.mkdirSync(request.prDir, { recursive: true });\n fs.writeFileSync(target, JSON.stringify(provenance, null, 2) + '\\n');\n return target;\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return '';\n }\n }\n\n // Retire the record for the round that just shipped: copy it to old-provenance.json beside the\n // old-review.json it belongs to. A COPY, not a move — unlike review.json this file is not an input to\n // anything, so leaving it in place cannot mislead a later reviewer, and the next finish overwrites it.\n archive(prDir: string): string {\n const source = this.provenancePath(prDir);\n if (!fs.existsSync(source)) return '';\n const target = this.oldProvenancePath(prDir);\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: a failed archive must not fail the command\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.copyFileSync(source, target);\n return target;\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return '';\n }\n }\n\n // Fill in the session-level facts the caller cannot know: which session, which transcripts, how long.\n private build(request: ProvenanceWriteRequest): ReviewProvenance {\n const provenance = new ReviewProvenance(request);\n provenance.sessionId = this.sessionId();\n provenance.mainTranscript = this.mainTranscript();\n provenance.stampedAt = new Date().toISOString();\n provenance.transcriptRetentionDays = this.retentionDays();\n const linked = [provenance.mainTranscript, ...request.reviewers.map(\n (r: ReviewerTranscript): string => r.transcript)].filter((p: string): boolean => p !== '');\n provenance.transcriptsExpireOn = this.expiresOn(linked, provenance.transcriptRetentionDays);\n return provenance;\n }\n\n // Epoch millis of a file's mtime, or 0 when it cannot be read.\n private mtimeOf(filePath: string): number {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unstattable transcript contributes no expiry\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return fs.statSync(filePath).mtime.getTime();\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return 0;\n }\n }\n\n private readDir(dir: string): string[] {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unreadable dir yields [] (best-effort)\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 // 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 settings → null (fall through to the default)\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"]}
|
|
@@ -21,8 +21,43 @@ export declare class ReviewerEvidence {
|
|
|
21
21
|
readDoc: boolean;
|
|
22
22
|
toolCallCount: number;
|
|
23
23
|
offRepoSearches: number;
|
|
24
|
+
/**
|
|
25
|
+
* Distinct `message.model` values OBSERVED in the transcript, in first-seen order.
|
|
26
|
+
*
|
|
27
|
+
* The model that actually ran, never the one that was configured — and never anything the reviewer
|
|
28
|
+
* says about itself. A checklist's `.claude/agents/<subagent>.md` declares `model:`, but that is the
|
|
29
|
+
* REQUESTED value and it can silently disagree with what served the request: a repo was measured
|
|
30
|
+
* running opus for a reviewer whose agent file said `model: sonnet`. Asking the model instead would
|
|
31
|
+
* be worse — a model is unreliable about its own identity, naming a family instead of a version or
|
|
32
|
+
* repeating whatever the system prompt implied, so a self-reported field is usually right and
|
|
33
|
+
* silently wrong, which is the worst kind of telemetry because it looks authoritative.
|
|
34
|
+
* `message.model` is written by the harness, so this inherits the anti-forgery property the rest of
|
|
35
|
+
* this class documents.
|
|
36
|
+
*
|
|
37
|
+
* An ARRAY, not a string: one reviewer run can span more than one model (a fallback after a refusal,
|
|
38
|
+
* a mid-run config change). Collapsing to one value forces a lossy choice at read time; recording
|
|
39
|
+
* what happened lets the renderer decide.
|
|
40
|
+
*
|
|
41
|
+
* Token counts and cost are deliberately NOT here. Prices change, vary by platform and differ under
|
|
42
|
+
* intro pricing, so a rate table in this package would rot silently — and the question this answers
|
|
43
|
+
* is "which model reviewed this?", not "what did it cost?".
|
|
44
|
+
*/
|
|
45
|
+
models: string[];
|
|
24
46
|
transcriptPath: string;
|
|
25
|
-
constructor(agentType: string, agentId: string, readDiff?: boolean, readDoc?: boolean, toolCallCount?: number, offRepoSearches?: number, transcriptPath?: string);
|
|
47
|
+
constructor(agentType: string, agentId: string, readDiff?: boolean, readDoc?: boolean, toolCallCount?: number, offRepoSearches?: number, transcriptPath?: string, models?: string[]);
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* One pass over one transcript: the tool inputs AND the models that served it. Data-only.
|
|
51
|
+
*
|
|
52
|
+
* They are gathered together rather than in two passes because they come from the SAME records — the
|
|
53
|
+
* inputs from `message.content[].input`, the model from `message.model` one level up — and a transcript
|
|
54
|
+
* is the largest file this service opens. Two reads of it to answer two questions about the same lines
|
|
55
|
+
* would be the duplicate-work trap the diff materializer documents at length.
|
|
56
|
+
*/
|
|
57
|
+
export declare class TranscriptScan {
|
|
58
|
+
inputs: string[];
|
|
59
|
+
models: string[];
|
|
60
|
+
constructor(inputs?: string[], models?: string[]);
|
|
26
61
|
}
|
|
27
62
|
/** What to look for when reading reviewer transcripts. Data-only — avoids a 5-param method. */
|
|
28
63
|
export declare class EvidenceRequest {
|
|
@@ -75,13 +110,28 @@ export declare class SubagentProvenanceService {
|
|
|
75
110
|
*/
|
|
76
111
|
evidenceFor(request: EvidenceRequest): ReviewerEvidence[];
|
|
77
112
|
private evidenceFromTranscript;
|
|
113
|
+
/**
|
|
114
|
+
* Record this line's `message.model`, deduped, in first-seen order.
|
|
115
|
+
*
|
|
116
|
+
* `<synthetic>` records are SKIPPED. The harness writes them for messages no model produced (tool
|
|
117
|
+
* results, injected notices); counting one would put a non-model in a field whose entire purpose is
|
|
118
|
+
* "which model reviewed this", and it would show up on every single reviewer.
|
|
119
|
+
*/
|
|
120
|
+
private collectModel;
|
|
78
121
|
private transcriptPath;
|
|
79
122
|
/**
|
|
80
|
-
*
|
|
81
|
-
*
|
|
82
|
-
*
|
|
123
|
+
* ONE pass over the transcript for both answers (see {@link TranscriptScan}).
|
|
124
|
+
*
|
|
125
|
+
* Tool inputs are JSON-stringified rather than walked field-by-field because the shape differs per
|
|
126
|
+
* tool (Read takes file_path, Bash takes command, Grep takes path) and a substring test over the
|
|
127
|
+
* serialized input is both simpler and robust to a tool we have not seen.
|
|
128
|
+
*
|
|
129
|
+
* Best-effort, like everything else that parses this file: a format change must never wedge the
|
|
130
|
+
* gate, so an unreadable transcript yields empty rather than throwing. That matters more for the
|
|
131
|
+
* models than for the counters — this is quality telemetry, not an integrity check, and a missing
|
|
132
|
+
* `model` field must not be able to block a PR.
|
|
83
133
|
*/
|
|
84
|
-
private
|
|
134
|
+
private scanTranscript;
|
|
85
135
|
private mentions;
|
|
86
136
|
private inClaudeSession;
|
|
87
137
|
private skipped;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.SubagentProvenanceService = exports.EvidenceRequest = exports.ReviewerEvidence = exports.ProvenanceResult = exports.PROVENANCE_SKIPPED = exports.PROVENANCE_MISSING = exports.PROVENANCE_OK = void 0;
|
|
3
|
+
exports.SubagentProvenanceService = exports.EvidenceRequest = 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
5
|
const fs = tslib_1.__importStar(require("fs"));
|
|
6
6
|
const path = tslib_1.__importStar(require("path"));
|
|
@@ -37,13 +37,35 @@ class ReviewerEvidence {
|
|
|
37
37
|
readDoc; // opened its checklist's guidance doc
|
|
38
38
|
toolCallCount;
|
|
39
39
|
offRepoSearches; // tool calls that reached into node_modules — the archaeology signal
|
|
40
|
+
/**
|
|
41
|
+
* Distinct `message.model` values OBSERVED in the transcript, in first-seen order.
|
|
42
|
+
*
|
|
43
|
+
* The model that actually ran, never the one that was configured — and never anything the reviewer
|
|
44
|
+
* says about itself. A checklist's `.claude/agents/<subagent>.md` declares `model:`, but that is the
|
|
45
|
+
* REQUESTED value and it can silently disagree with what served the request: a repo was measured
|
|
46
|
+
* running opus for a reviewer whose agent file said `model: sonnet`. Asking the model instead would
|
|
47
|
+
* be worse — a model is unreliable about its own identity, naming a family instead of a version or
|
|
48
|
+
* repeating whatever the system prompt implied, so a self-reported field is usually right and
|
|
49
|
+
* silently wrong, which is the worst kind of telemetry because it looks authoritative.
|
|
50
|
+
* `message.model` is written by the harness, so this inherits the anti-forgery property the rest of
|
|
51
|
+
* this class documents.
|
|
52
|
+
*
|
|
53
|
+
* An ARRAY, not a string: one reviewer run can span more than one model (a fallback after a refusal,
|
|
54
|
+
* a mid-run config change). Collapsing to one value forces a lossy choice at read time; recording
|
|
55
|
+
* what happened lets the renderer decide.
|
|
56
|
+
*
|
|
57
|
+
* Token counts and cost are deliberately NOT here. Prices change, vary by platform and differ under
|
|
58
|
+
* intro pricing, so a rate table in this package would rot silently — and the question this answers
|
|
59
|
+
* is "which model reviewed this?", not "what did it cost?".
|
|
60
|
+
*/
|
|
61
|
+
models;
|
|
40
62
|
// Absolute path of the transcript these counters were read out of, '' when it could not be resolved.
|
|
41
63
|
// Carried out rather than recomputed because a reviewer subagent cannot learn its own transcript path
|
|
42
64
|
// (the environment exposes the PARENT session id and no agent id), so this is the only place it is
|
|
43
65
|
// known — see ReviewProvenanceService, which records it as the audit link for the verdict.
|
|
44
66
|
transcriptPath;
|
|
45
67
|
// eslint-disable-next-line @typescript-eslint/max-params
|
|
46
|
-
constructor(agentType, agentId, readDiff = false, readDoc = false, toolCallCount = 0, offRepoSearches = 0, transcriptPath = '') {
|
|
68
|
+
constructor(agentType, agentId, readDiff = false, readDoc = false, toolCallCount = 0, offRepoSearches = 0, transcriptPath = '', models = []) {
|
|
47
69
|
this.agentType = agentType;
|
|
48
70
|
this.agentId = agentId;
|
|
49
71
|
this.readDiff = readDiff;
|
|
@@ -51,9 +73,27 @@ class ReviewerEvidence {
|
|
|
51
73
|
this.toolCallCount = toolCallCount;
|
|
52
74
|
this.offRepoSearches = offRepoSearches;
|
|
53
75
|
this.transcriptPath = transcriptPath;
|
|
76
|
+
this.models = models;
|
|
54
77
|
}
|
|
55
78
|
}
|
|
56
79
|
exports.ReviewerEvidence = ReviewerEvidence;
|
|
80
|
+
/**
|
|
81
|
+
* One pass over one transcript: the tool inputs AND the models that served it. Data-only.
|
|
82
|
+
*
|
|
83
|
+
* They are gathered together rather than in two passes because they come from the SAME records — the
|
|
84
|
+
* inputs from `message.content[].input`, the model from `message.model` one level up — and a transcript
|
|
85
|
+
* is the largest file this service opens. Two reads of it to answer two questions about the same lines
|
|
86
|
+
* would be the duplicate-work trap the diff materializer documents at length.
|
|
87
|
+
*/
|
|
88
|
+
class TranscriptScan {
|
|
89
|
+
inputs; // every tool_use input, JSON-stringified
|
|
90
|
+
models; // distinct message.model values, first-seen order
|
|
91
|
+
constructor(inputs = [], models = []) {
|
|
92
|
+
this.inputs = inputs;
|
|
93
|
+
this.models = models;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
exports.TranscriptScan = TranscriptScan;
|
|
57
97
|
/** What to look for when reading reviewer transcripts. Data-only — avoids a 5-param method. */
|
|
58
98
|
class EvidenceRequest {
|
|
59
99
|
branch;
|
|
@@ -166,13 +206,29 @@ let SubagentProvenanceService = class SubagentProvenanceService {
|
|
|
166
206
|
}
|
|
167
207
|
// eslint-disable-next-line @typescript-eslint/max-params
|
|
168
208
|
evidenceFromTranscript(agentType, agentId, jsonl, request) {
|
|
169
|
-
const
|
|
209
|
+
const scan = this.scanTranscript(jsonl);
|
|
210
|
+
const inputs = scan.inputs;
|
|
170
211
|
const docPath = request.docPaths[agentType] ?? '';
|
|
171
212
|
// The instructions file counts as "read the diff": it lives in the same per-branch dir, it is what
|
|
172
213
|
// the reviewer is told to open first, and it inlines the diff paths. A reviewer that opened it and
|
|
173
214
|
// then its own diff files is the intended path; treating only the diff dir as proof would flag it.
|
|
174
215
|
const readDiff = request.diffDir !== '' && this.mentions(inputs, request.diffDir);
|
|
175
|
-
return new ReviewerEvidence(agentType, agentId, readDiff, docPath !== '' && this.mentions(inputs, docPath), inputs.length, inputs.filter((i) => i.includes('node_modules')).length, jsonl);
|
|
216
|
+
return new ReviewerEvidence(agentType, agentId, readDiff, docPath !== '' && this.mentions(inputs, docPath), inputs.length, inputs.filter((i) => i.includes('node_modules')).length, jsonl, scan.models);
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* Record this line's `message.model`, deduped, in first-seen order.
|
|
220
|
+
*
|
|
221
|
+
* `<synthetic>` records are SKIPPED. The harness writes them for messages no model produced (tool
|
|
222
|
+
* results, injected notices); counting one would put a non-model in a field whose entire purpose is
|
|
223
|
+
* "which model reviewed this", and it would show up on every single reviewer.
|
|
224
|
+
*/
|
|
225
|
+
// webpieces-disable no-any-unknown -- opaque transcript record, only `model` is read and it is type-guarded below
|
|
226
|
+
collectModel(message, models) {
|
|
227
|
+
const model = message['model'];
|
|
228
|
+
if (typeof model !== 'string' || model === '' || model === '<synthetic>')
|
|
229
|
+
return;
|
|
230
|
+
if (!models.includes(model))
|
|
231
|
+
models.push(model);
|
|
176
232
|
}
|
|
177
233
|
// The absolute path of agent-<id>.jsonl across all session dirs, or '' if it is not there.
|
|
178
234
|
transcriptPath(dirs, agentId) {
|
|
@@ -184,12 +240,19 @@ let SubagentProvenanceService = class SubagentProvenanceService {
|
|
|
184
240
|
return '';
|
|
185
241
|
}
|
|
186
242
|
/**
|
|
187
|
-
*
|
|
188
|
-
*
|
|
189
|
-
*
|
|
243
|
+
* ONE pass over the transcript for both answers (see {@link TranscriptScan}).
|
|
244
|
+
*
|
|
245
|
+
* Tool inputs are JSON-stringified rather than walked field-by-field because the shape differs per
|
|
246
|
+
* tool (Read takes file_path, Bash takes command, Grep takes path) and a substring test over the
|
|
247
|
+
* serialized input is both simpler and robust to a tool we have not seen.
|
|
248
|
+
*
|
|
249
|
+
* Best-effort, like everything else that parses this file: a format change must never wedge the
|
|
250
|
+
* gate, so an unreadable transcript yields empty rather than throwing. That matters more for the
|
|
251
|
+
* models than for the counters — this is quality telemetry, not an integrity check, and a missing
|
|
252
|
+
* `model` field must not be able to block a PR.
|
|
190
253
|
*/
|
|
191
|
-
|
|
192
|
-
const
|
|
254
|
+
scanTranscript(jsonl) {
|
|
255
|
+
const scan = new TranscriptScan();
|
|
193
256
|
// webpieces-disable no-unmanaged-exceptions -- chokepoint: an unreadable transcript yields no evidence, never a crash
|
|
194
257
|
// eslint-disable-next-line @webpieces/no-unmanaged-exceptions
|
|
195
258
|
try {
|
|
@@ -201,14 +264,16 @@ let SubagentProvenanceService = class SubagentProvenanceService {
|
|
|
201
264
|
if (typeof message !== 'object' || message === null)
|
|
202
265
|
continue;
|
|
203
266
|
// webpieces-disable no-any-unknown -- opaque transcript record, narrowed by the guard above
|
|
204
|
-
const
|
|
267
|
+
const msg = message;
|
|
268
|
+
this.collectModel(msg, scan.models);
|
|
269
|
+
const content = msg['content'];
|
|
205
270
|
if (!Array.isArray(content))
|
|
206
271
|
continue;
|
|
207
272
|
for (const block of content) {
|
|
208
273
|
// webpieces-disable no-any-unknown -- opaque content block, only `type`/`input` are read
|
|
209
274
|
const b = block;
|
|
210
275
|
if (b['type'] === 'tool_use')
|
|
211
|
-
|
|
276
|
+
scan.inputs.push(JSON.stringify(b['input'] ?? {}));
|
|
212
277
|
}
|
|
213
278
|
}
|
|
214
279
|
}
|
|
@@ -216,7 +281,7 @@ let SubagentProvenanceService = class SubagentProvenanceService {
|
|
|
216
281
|
const error = (0, to_error_1.toError)(err);
|
|
217
282
|
void error;
|
|
218
283
|
}
|
|
219
|
-
return
|
|
284
|
+
return scan;
|
|
220
285
|
}
|
|
221
286
|
mentions(inputs, needle) {
|
|
222
287
|
return inputs.some((i) => i.includes(needle));
|