@webpieces/rules-config 0.4.837 → 0.4.839

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/package.json +4 -2
  2. package/src/builds-log.d.ts +1 -1
  3. package/src/builds-log.js +3 -3
  4. package/src/builds-log.js.map +1 -1
  5. package/src/checklist-docs-validator.js +1 -1
  6. package/src/checklist-docs-validator.js.map +1 -1
  7. package/src/checklist-override.js +1 -1
  8. package/src/checklist-override.js.map +1 -1
  9. package/src/config-file.js +3 -3
  10. package/src/config-file.js.map +1 -1
  11. package/src/config-pruner.d.ts +1 -1
  12. package/src/config-pruner.js +2 -2
  13. package/src/config-pruner.js.map +1 -1
  14. package/src/constants.d.ts +0 -2
  15. package/src/constants.js +1 -3
  16. package/src/constants.js.map +1 -1
  17. package/src/diff-scope.js +1 -1
  18. package/src/diff-scope.js.map +1 -1
  19. package/src/exclude-hook-paths.js +2 -2
  20. package/src/exclude-hook-paths.js.map +1 -1
  21. package/src/home-config-doc-keys.js +2 -2
  22. package/src/home-config-doc-keys.js.map +1 -1
  23. package/src/home-config.js +9 -9
  24. package/src/home-config.js.map +1 -1
  25. package/src/index.d.ts +2 -21
  26. package/src/index.js +7 -129
  27. package/src/index.js.map +1 -1
  28. package/src/instruct-ai-docs.d.ts +1 -1
  29. package/src/instruct-ai-docs.js +3 -3
  30. package/src/instruct-ai-docs.js.map +1 -1
  31. package/src/load-config.js +2 -2
  32. package/src/load-config.js.map +1 -1
  33. package/src/load-template.d.ts +2 -2
  34. package/src/load-template.js +5 -5
  35. package/src/load-template.js.map +1 -1
  36. package/src/orphan-dir-archive.js +3 -3
  37. package/src/orphan-dir-archive.js.map +1 -1
  38. package/src/pr-gate-config.js +4 -4
  39. package/src/pr-gate-config.js.map +1 -1
  40. package/src/pr-gate-section-validators.js +7 -7
  41. package/src/pr-gate-section-validators.js.map +1 -1
  42. package/src/repo-root.d.ts +1 -1
  43. package/src/repo-root.js +5 -5
  44. package/src/repo-root.js.map +1 -1
  45. package/src/repo-scratch-dirs.d.ts +1 -1
  46. package/src/repo-scratch-dirs.js +3 -3
  47. package/src/repo-scratch-dirs.js.map +1 -1
  48. package/src/review-json.d.ts +1 -1
  49. package/src/review-json.js +11 -11
  50. package/src/review-json.js.map +1 -1
  51. package/src/review-provenance.js +4 -4
  52. package/src/review-provenance.js.map +1 -1
  53. package/src/reviewer-instructions.js +2 -2
  54. package/src/reviewer-instructions.js.map +1 -1
  55. package/src/rules-config-design.d.ts +2 -2
  56. package/src/rules-config-design.js +4 -4
  57. package/src/rules-config-design.js.map +1 -1
  58. package/src/skip-rule.d.ts +2 -8
  59. package/src/skip-rule.js +24 -61
  60. package/src/skip-rule.js.map +1 -1
  61. package/src/spec-temp-dirs.js +2 -1
  62. package/src/spec-temp-dirs.js.map +1 -1
  63. package/src/stale-bin-sweep.js +1 -1
  64. package/src/stale-bin-sweep.js.map +1 -1
  65. package/src/subagent-provenance.js +7 -7
  66. package/src/subagent-provenance.js.map +1 -1
  67. package/src/tmp-scratch-sweep.js +1 -1
  68. package/src/tmp-scratch-sweep.js.map +1 -1
  69. package/src/validate-config.js +1 -1
  70. package/src/validate-config.js.map +1 -1
  71. package/src/verdict-schema-renderer.js +2 -2
  72. package/src/verdict-schema-renderer.js.map +1 -1
  73. package/src/agent-worktree-lock.d.ts +0 -21
  74. package/src/agent-worktree-lock.js +0 -77
  75. package/src/agent-worktree-lock.js.map +0 -1
  76. package/src/atomic-file.d.ts +0 -46
  77. package/src/atomic-file.js +0 -114
  78. package/src/atomic-file.js.map +0 -1
  79. package/src/branch-archiver.d.ts +0 -70
  80. package/src/branch-archiver.js +0 -157
  81. package/src/branch-archiver.js.map +0 -1
  82. package/src/branch-mutation-log.d.ts +0 -77
  83. package/src/branch-mutation-log.js +0 -221
  84. package/src/branch-mutation-log.js.map +0 -1
  85. package/src/branch-reaper.d.ts +0 -121
  86. package/src/branch-reaper.js +0 -260
  87. package/src/branch-reaper.js.map +0 -1
  88. package/src/claude-config-dir.d.ts +0 -62
  89. package/src/claude-config-dir.js +0 -87
  90. package/src/claude-config-dir.js.map +0 -1
  91. package/src/harness-agent-activity.d.ts +0 -154
  92. package/src/harness-agent-activity.js +0 -346
  93. package/src/harness-agent-activity.js.map +0 -1
  94. package/src/inform-ai-error.d.ts +0 -6
  95. package/src/inform-ai-error.js +0 -13
  96. package/src/inform-ai-error.js.map +0 -1
  97. package/src/main-sync-file.d.ts +0 -121
  98. package/src/main-sync-file.js +0 -281
  99. package/src/main-sync-file.js.map +0 -1
  100. package/src/main-sync-status.d.ts +0 -197
  101. package/src/main-sync-status.js +0 -555
  102. package/src/main-sync-status.js.map +0 -1
  103. package/src/merged-branch-verdicts.d.ts +0 -189
  104. package/src/merged-branch-verdicts.js +0 -251
  105. package/src/merged-branch-verdicts.js.map +0 -1
  106. package/src/merged-branches.d.ts +0 -140
  107. package/src/merged-branches.js +0 -521
  108. package/src/merged-branches.js.map +0 -1
  109. package/src/review-identity-stamp.d.ts +0 -82
  110. package/src/review-identity-stamp.js +0 -172
  111. package/src/review-identity-stamp.js.map +0 -1
  112. package/src/state-dir-migration.d.ts +0 -79
  113. package/src/state-dir-migration.js +0 -185
  114. package/src/state-dir-migration.js.map +0 -1
  115. package/src/state-dir.d.ts +0 -209
  116. package/src/state-dir.js +0 -349
  117. package/src/state-dir.js.map +0 -1
  118. package/src/to-error.d.ts +0 -1
  119. package/src/to-error.js +0 -10
  120. package/src/to-error.js.map +0 -1
  121. package/src/worktree-lock-verdicts.d.ts +0 -149
  122. package/src/worktree-lock-verdicts.js +0 -225
  123. package/src/worktree-lock-verdicts.js.map +0 -1
  124. package/src/worktree-reaper.d.ts +0 -116
  125. package/src/worktree-reaper.js +0 -318
  126. package/src/worktree-reaper.js.map +0 -1
  127. package/src/worktrees.d.ts +0 -113
  128. package/src/worktrees.js +0 -260
  129. package/src/worktrees.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"stale-bin-sweep.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/stale-bin-sweep.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,yCAAqC;AAErC,8EAA8E;AAC9E,oDAAoD;AACpD,EAAE;AACF,0GAA0G;AAC1G,wGAAwG;AACxG,uGAAuG;AACvG,sGAAsG;AACtG,sFAAsF;AACtF,EAAE;AACF,kGAAkG;AAClG,2GAA2G;AAC3G,yGAAyG;AACzG,0GAA0G;AAC1G,2GAA2G;AAC3G,gGAAgG;AAChG,sGAAsG;AACtG,0GAA0G;AAC1G,wBAAwB;AACxB,EAAE;AACF,yGAAyG;AACzG,kGAAkG;AAClG,oGAAoG;AACpG,yGAAyG;AACzG,qGAAqG;AACrG,uGAAuG;AACvG,yGAAyG;AACzG,0GAA0G;AAC1G,iGAAiG;AACjG,EAAE;AACF,yGAAyG;AACzG,0GAA0G;AAC1G,wFAAwF;AACxF,0GAA0G;AAC1G,gGAAgG;AAChG,EAAE;AACF,wGAAwG;AACxG,yGAAyG;AACzG,wGAAwG;AACxG,yGAAyG;AACzG,mGAAmG;AACnG,kHAAkH;AAClH,0GAA0G;AAC1G,oEAAoE;AACpE,EAAE;AACF,wGAAwG;AACxG,mGAAmG;AACnG,yGAAyG;AACzG,4GAA4G;AAC5G,yGAAyG;AACzG,oGAAoG;AACpG,EAAE;AACF,2GAA2G;AAC3G,2GAA2G;AAC3G,wGAAwG;AACxG,2GAA2G;AAC3G,0GAA0G;AAC1G,yEAAyE;AACzE,EAAE;AACF,yGAAyG;AACzG,8FAA8F;AAC9F,8EAA8E;AAE9E,4FAA4F;AAC5F,MAAM,aAAa,GAAG,KAAK,CAAC;AAE5B;;;;;;;;;GASG;AACH,MAAa,eAAe;IACxB,IAAI,CAAS,CAAI,4DAA4D;IAC7E,MAAM,CAAS,CAAE,kEAAkE;IACnF,OAAO,CAAS,CAAC,yDAAyD;IAE1E,YAAY,IAAY,EAAE,MAAc,EAAE,OAAO,GAAG,EAAE;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K,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,KAAK,KAAK,CAAC,CAAC,gEAAgE;YAC5E,OAAO,IAAI,CAAC;QAChB,CAAC;IACL,CAAC;CACJ;AAzHD,0CAyHC;AAED,oGAAoG;AACvF,QAAA,eAAe,GAAG,IAAI,eAAe,EAAE,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { toError } from './to-error';\n\n// ---------------------------------------------------------------------------\n// SWEEP DANGLING `node_modules/.bin/wp-*` SYMLINKS.\n//\n// THE DEFECT. pnpm's linker ADDS a link for every entry in the current manifest's `bin` map, but it never\n// sweeps `.bin` for orphans left behind by a PREVIOUS version of the SAME package. `@webpieces/pr-gate`\n// and `@webpieces/ai-hook-rules` are upgraded, never removed, so nothing ever triggers a delete: every\n// bin either package has EVER shipped stays linked forever, pointing at a script that is no longer on\n// disk. A scan of nine clones on ONE machine found 18 distinct dangling `wp-*` names.\n//\n// THE DEFECT IS ONGOING, AND A ROUTINE RENAME PRODUCES IT. Measured on this repo's own upgrade to\n// 0.4.728, DURING the session that wrote this file: PR #743 hard-renamed one `wp-*` command with no alias,\n// so the new manifest declares `wp-sync-main` and no longer declares its predecessor. One `pnpm install`\n// later, `.bin` held the NEW link created that minute AND the predecessor's link still sitting there from\n// the previous install, dangling — reproduced independently in two separate trees of this repo. So this is\n// not a historical mess left by a deleted feature that a one-time migration could mop up: it is\n// regenerated by the most ordinary change a package can make, on every clone, every time. That is the\n// argument for the call site below — the sweep has to ride a path that runs ROUTINELY, because the defect\n// is created routinely.\n//\n// The predecessor's NAME is deliberately not written here, and DO NOT WRITE IT BACK IN. Two reasons, and\n// the second is the one that matters. First, nothing in the code needs it: the predicate below is\n// STRUCTURAL — a `wp-*` entry whose link target does not resolve — so naming one particular retired\n// command would invite a reader to think the sweep is a list of known dead names somebody has to keep up\n// to date. Second, a retired command named in tracked source is exactly how a dead name outlives its\n// tooling: it gets copied into a cure string, and an agent reading that cure at the moment every other\n// route is closed is handed a command that does not exist. That is the very defect this module cleans up\n// one level out, and there is no longer an automated scan standing behind this paragraph — the reader is.\n// PR #743 and the issue this shipped under carry the literal name; nothing in the tree needs to.\n//\n// WHY IT MATTERS MORE THAN TIDINESS. `ls node_modules/.bin` lists them, so a dangling entry ADVERTISES a\n// capability that does not exist — a human and an AI were both misled by that listing before checking the\n// link target — and the failure it eventually produces is self-referential and useless:\n// `Command \"wp-authorize\" not found / Did you mean \"pnpm wp-authorize\"?`. This is `upgrade-shim.ts`'s own\n// governing principle one level out: an entry pointing at a missing file is WORSE than absence.\n//\n// WHY A PREFIX AND NOT A NAME LIST. A hardcoded list of retired bin names would go stale in exactly the\n// way the symlinks did — the list assembled from the two names that prompted this would have caught 2 of\n// the 18, and it would NOT have caught the rename above, which had not happened yet when the list would\n// have been written. That is the general case: the next orphan is always created by a release later than\n// any list. A name list is also unwriteable here on purpose — see the note above about naming dead\n// commands in source. The predicate is structural instead — a `wp-` prefixed entry that is a SYMLINK whose target\n// does not exist — so it needs no maintenance and cannot miss a name nobody has thought of. The prefix is\n// the whole safety story: another package's bins are never touched.\n//\n// WHY NOT A postinstall HOOK. `setupDebugging.md` records the postinstall approach as ABANDONED in this\n// repo. The call site is the `wp-*` startup pass that regenerates `.webpieces/instruct-ai/*` — see\n// TemplateWriter — and that placement is the load-bearing half of the fix. This is not a tidy-up for one\n// repo: every developer's machine has this graveyard, and a cure that only cleans the tree somebody happens\n// to run it in is worthless. Riding the pass EVERY `wp-*` command takes is what makes the RELEASED sweep\n// reach every clone on every machine, healing each one the next time any `wp-*` command runs there.\n//\n// NOT ALSO CALLED FROM `wp-upgrade-shim`, though it would read naturally there (that bin already deletes a\n// retired FILE on the same principle). `upgrade-shim.ts` may import only `fs`/`path` so it still runs on a\n// tree too broken to load the rule engine: this package's barrel would pull in inversify and the config\n// loader, and a subpath import would resolve against the INSTALLED rules-config, which is a release behind\n// the local source — so a spawned `wp-upgrade-shim` would die on module resolution, in the one command an\n// L0-blocked session has left. Its header records that, and points here.\n//\n// DEPENDENCY-FREE ANYWAY: `fs`, `path` and `toError`. No inversify (see StaleBinSweeper), so this module\n// stays cheap for the startup path it runs on and importable by anything that later needs it.\n// ---------------------------------------------------------------------------\n\n// The one place the prefix is spelled. Everything outside it belongs to some other package.\nconst WP_BIN_PREFIX = 'wp-';\n\n/**\n * One dangling entry the sweep ACTED ON: what was linked, the target that was not there, and — when the\n * removal itself failed — why. Data-only (per CLAUDE.md).\n *\n * `failure` exists because the removal is an `fs.rmSync`, not just a probe: an unwritable `.bin` (EACCES,\n * a read-only mount) would otherwise heal silently-never while the tree kept advertising a command that\n * does not exist, which is the precise defect this module exists to remove. Not thrown — the sweep is a\n * courtesy and must never fail the `wp-*` command that called it — so the diagnostic rides back here and\n * {@link StaleBinSweeper.report} states both outcomes.\n */\nexport class StaleBinRemoval {\n name: string; // the bin name as it appeared in .bin (e.g. 'wp-authorize')\n target: string; // the link target that does not exist, as recorded in the symlink\n failure: string; // '' = removed; non-empty = still there, and this is why\n\n constructor(name: string, target: string, failure = '') {\n this.name = name;\n this.target = target;\n this.failure = failure;\n }\n}\n\n/**\n * Removes `node_modules/.bin/wp-*` entries whose symlink target is gone.\n *\n * Deliberately NOT `@injectable`: decorating it would import inversify, and this module must stay loadable\n * by `wp-upgrade-shim` on a tree that cannot build a DI container (see the header). Callers use the shared\n * {@link staleBinSweeper} instance, which is also what makes {@link sweepOnce}'s memo process-wide.\n */\nexport class StaleBinSweeper {\n // Roots already swept in THIS process. `writeTemplate` is called several times per `wp-*` command (once\n // per instruct-ai doc), and a sweep that reported per call would print the same removals repeatedly.\n private readonly swept = new Set<string>();\n\n /** Where the bins live for a tree. Public so a test can point at a fixture without guessing the layout. */\n binDir(repoRoot: string): string {\n return path.join(repoRoot, 'node_modules', '.bin');\n }\n\n /**\n * Sweep once per root per process, returning what was removed ([] on every later call for the same\n * root, and [] when there was nothing to remove — the two are indistinguishable to a caller ON PURPOSE,\n * because both mean \"say nothing\").\n */\n sweepOnce(repoRoot: string): StaleBinRemoval[] {\n if (this.swept.has(repoRoot)) return [];\n this.swept.add(repoRoot);\n return this.sweep(repoRoot);\n }\n\n /**\n * Remove every dangling `wp-*` symlink under the tree's `.bin`, returning what went. [] when the\n * directory does not exist (a linked worktree with no install of its own is the common case) or when\n * everything there resolves.\n *\n * BEST EFFORT, PER ENTRY. A `.bin` that cannot be read, or one entry that cannot be removed, must never\n * take down the `wp-*` command that called this — the sweep is a courtesy, not the command's job.\n */\n sweep(repoRoot: string): StaleBinRemoval[] {\n const dir = this.binDir(repoRoot);\n const removed: StaleBinRemoval[] = [];\n for (const name of this.entries(dir)) {\n if (!name.startsWith(WP_BIN_PREFIX)) continue;\n const removal = this.removeIfDangling(path.join(dir, name), name);\n if (removal !== null) removed.push(removal);\n }\n return removed;\n }\n\n /**\n * The lines a caller prints for a sweep. [] for an empty sweep, so REMOVING NOTHING IS SILENT — this\n * runs on every `wp-*` command and the common case must add no noise at all.\n *\n * Rendered here rather than at each call site so the two callers cannot describe the same act\n * differently; each still chooses its own output channel and its own leading icon convention.\n */\n report(removed: readonly StaleBinRemoval[]): string[] {\n if (removed.length === 0) return [];\n const gone = removed.filter((r: StaleBinRemoval): boolean => r.failure === '');\n const stuck = removed.filter((r: StaleBinRemoval): boolean => r.failure !== '');\n const lines: string[] = [];\n if (gone.length > 0) {\n lines.push(`✅ @webpieces: removed ${gone.length} dangling node_modules/.bin/wp-* symlink(s) left by an earlier release:`);\n for (const r of gone) lines.push(` ${r.name} -> ${r.target} (target missing)`);\n lines.push(' They pointed at scripts this release no longer ships, so they could only ever fail on execution.');\n }\n // A failed removal is STATED, never quietly dropped: the entry is still there, still advertising a\n // command that does not exist, and only a human can fix an unwritable .bin.\n if (stuck.length > 0) {\n lines.push(`⚠️ @webpieces: ${stuck.length} dangling node_modules/.bin/wp-* symlink(s) could NOT be removed:`);\n for (const r of stuck) lines.push(` ${r.name} -> ${r.target} (target missing; ${r.failure})`);\n lines.push(' They still advertise commands this release does not ship. Nothing else is affected — remove them by hand.');\n }\n return lines;\n }\n\n // The directory listing, or [] when there is no .bin (or it cannot be read).\n private entries(dir: string): string[] {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unreadable .bin means \"nothing to sweep\", never a failed wp-* command\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n if (!fs.existsSync(dir)) return [];\n return fs.readdirSync(dir);\n } catch (err: unknown) {\n const error = toError(err);\n void error; // best effort: no readable .bin means there is nothing to sweep\n return [];\n }\n }\n\n /**\n * Remove ONE entry if — and only if — it is a symlink whose target does not exist. Returns what was\n * acted on, with `failure` set when the entry was dangling but could not be removed; `null` when the\n * entry was not a dangling `wp-*` link at all.\n */\n private removeIfDangling(full: string, name: string): StaleBinRemoval | null {\n const target = this.danglingTarget(full);\n if (target === null) return null;\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unremovable entry is REPORTED, never fatal to the wp-* command that called the sweep\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.rmSync(full, { force: true });\n return new StaleBinRemoval(name, target);\n } catch (err: unknown) {\n const error = toError(err);\n return new StaleBinRemoval(name, target, error.message);\n }\n }\n\n /**\n * The link target of a DANGLING symlink, or `null` when this entry is not one — a real file, a live\n * link, or something we cannot stat. `existsSync` FOLLOWS symlinks, so a false answer on a path `lstat`\n * calls a link is exactly the dangling case, with no need to resolve the target ourselves.\n *\n * Split from the removal so the two catches mean different things: an unreadable entry is simply not\n * ours to touch, while a failed REMOVAL is a fact worth printing.\n */\n private danglingTarget(full: string): string | null {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an entry we cannot stat is not ours to touch\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n if (!fs.lstatSync(full).isSymbolicLink()) return null;\n if (fs.existsSync(full)) return null;\n return fs.readlinkSync(full);\n } catch (err: unknown) {\n const error = toError(err);\n void error; // best effort: an entry we cannot read is left exactly as it is\n return null;\n }\n }\n}\n\n// The shared instance — the memo in `sweepOnce` is per-instance, so every caller must use this one.\nexport const staleBinSweeper = new StaleBinSweeper();\n"]}
1
+ {"version":3,"file":"stale-bin-sweep.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/stale-bin-sweep.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,iEAA6D;AAE7D,8EAA8E;AAC9E,oDAAoD;AACpD,EAAE;AACF,0GAA0G;AAC1G,wGAAwG;AACxG,uGAAuG;AACvG,sGAAsG;AACtG,sFAAsF;AACtF,EAAE;AACF,kGAAkG;AAClG,2GAA2G;AAC3G,yGAAyG;AACzG,0GAA0G;AAC1G,2GAA2G;AAC3G,gGAAgG;AAChG,sGAAsG;AACtG,0GAA0G;AAC1G,wBAAwB;AACxB,EAAE;AACF,yGAAyG;AACzG,kGAAkG;AAClG,oGAAoG;AACpG,yGAAyG;AACzG,qGAAqG;AACrG,uGAAuG;AACvG,yGAAyG;AACzG,0GAA0G;AAC1G,iGAAiG;AACjG,EAAE;AACF,yGAAyG;AACzG,0GAA0G;AAC1G,wFAAwF;AACxF,0GAA0G;AAC1G,gGAAgG;AAChG,EAAE;AACF,wGAAwG;AACxG,yGAAyG;AACzG,wGAAwG;AACxG,yGAAyG;AACzG,mGAAmG;AACnG,kHAAkH;AAClH,0GAA0G;AAC1G,oEAAoE;AACpE,EAAE;AACF,wGAAwG;AACxG,mGAAmG;AACnG,yGAAyG;AACzG,4GAA4G;AAC5G,yGAAyG;AACzG,oGAAoG;AACpG,EAAE;AACF,2GAA2G;AAC3G,2GAA2G;AAC3G,wGAAwG;AACxG,2GAA2G;AAC3G,0GAA0G;AAC1G,yEAAyE;AACzE,EAAE;AACF,yGAAyG;AACzG,8FAA8F;AAC9F,8EAA8E;AAE9E,4FAA4F;AAC5F,MAAM,aAAa,GAAG,KAAK,CAAC;AAE5B;;;;;;;;;GASG;AACH,MAAa,eAAe;IACxB,IAAI,CAAS,CAAI,4DAA4D;IAC7E,MAAM,CAAS,CA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EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;QACjC,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,KAAK,KAAK,CAAC,CAAC,gEAAgE;YAC5E,OAAO,IAAI,CAAC;QAChB,CAAC;IACL,CAAC;CACJ;AAzHD,0CAyHC;AAED,oGAAoG;AACvF,QAAA,eAAe,GAAG,IAAI,eAAe,EAAE,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { toError } from '@webpieces/tooling-common/to-error';\n\n// ---------------------------------------------------------------------------\n// SWEEP DANGLING `node_modules/.bin/wp-*` SYMLINKS.\n//\n// THE DEFECT. pnpm's linker ADDS a link for every entry in the current manifest's `bin` map, but it never\n// sweeps `.bin` for orphans left behind by a PREVIOUS version of the SAME package. `@webpieces/pr-gate`\n// and `@webpieces/ai-hook-rules` are upgraded, never removed, so nothing ever triggers a delete: every\n// bin either package has EVER shipped stays linked forever, pointing at a script that is no longer on\n// disk. A scan of nine clones on ONE machine found 18 distinct dangling `wp-*` names.\n//\n// THE DEFECT IS ONGOING, AND A ROUTINE RENAME PRODUCES IT. Measured on this repo's own upgrade to\n// 0.4.728, DURING the session that wrote this file: PR #743 hard-renamed one `wp-*` command with no alias,\n// so the new manifest declares `wp-sync-main` and no longer declares its predecessor. One `pnpm install`\n// later, `.bin` held the NEW link created that minute AND the predecessor's link still sitting there from\n// the previous install, dangling — reproduced independently in two separate trees of this repo. So this is\n// not a historical mess left by a deleted feature that a one-time migration could mop up: it is\n// regenerated by the most ordinary change a package can make, on every clone, every time. That is the\n// argument for the call site below — the sweep has to ride a path that runs ROUTINELY, because the defect\n// is created routinely.\n//\n// The predecessor's NAME is deliberately not written here, and DO NOT WRITE IT BACK IN. Two reasons, and\n// the second is the one that matters. First, nothing in the code needs it: the predicate below is\n// STRUCTURAL — a `wp-*` entry whose link target does not resolve — so naming one particular retired\n// command would invite a reader to think the sweep is a list of known dead names somebody has to keep up\n// to date. Second, a retired command named in tracked source is exactly how a dead name outlives its\n// tooling: it gets copied into a cure string, and an agent reading that cure at the moment every other\n// route is closed is handed a command that does not exist. That is the very defect this module cleans up\n// one level out, and there is no longer an automated scan standing behind this paragraph — the reader is.\n// PR #743 and the issue this shipped under carry the literal name; nothing in the tree needs to.\n//\n// WHY IT MATTERS MORE THAN TIDINESS. `ls node_modules/.bin` lists them, so a dangling entry ADVERTISES a\n// capability that does not exist — a human and an AI were both misled by that listing before checking the\n// link target — and the failure it eventually produces is self-referential and useless:\n// `Command \"wp-authorize\" not found / Did you mean \"pnpm wp-authorize\"?`. This is `upgrade-shim.ts`'s own\n// governing principle one level out: an entry pointing at a missing file is WORSE than absence.\n//\n// WHY A PREFIX AND NOT A NAME LIST. A hardcoded list of retired bin names would go stale in exactly the\n// way the symlinks did — the list assembled from the two names that prompted this would have caught 2 of\n// the 18, and it would NOT have caught the rename above, which had not happened yet when the list would\n// have been written. That is the general case: the next orphan is always created by a release later than\n// any list. A name list is also unwriteable here on purpose — see the note above about naming dead\n// commands in source. The predicate is structural instead — a `wp-` prefixed entry that is a SYMLINK whose target\n// does not exist — so it needs no maintenance and cannot miss a name nobody has thought of. The prefix is\n// the whole safety story: another package's bins are never touched.\n//\n// WHY NOT A postinstall HOOK. `setupDebugging.md` records the postinstall approach as ABANDONED in this\n// repo. The call site is the `wp-*` startup pass that regenerates `.webpieces/instruct-ai/*` — see\n// TemplateWriter — and that placement is the load-bearing half of the fix. This is not a tidy-up for one\n// repo: every developer's machine has this graveyard, and a cure that only cleans the tree somebody happens\n// to run it in is worthless. Riding the pass EVERY `wp-*` command takes is what makes the RELEASED sweep\n// reach every clone on every machine, healing each one the next time any `wp-*` command runs there.\n//\n// NOT ALSO CALLED FROM `wp-upgrade-shim`, though it would read naturally there (that bin already deletes a\n// retired FILE on the same principle). `upgrade-shim.ts` may import only `fs`/`path` so it still runs on a\n// tree too broken to load the rule engine: this package's barrel would pull in inversify and the config\n// loader, and a subpath import would resolve against the INSTALLED rules-config, which is a release behind\n// the local source — so a spawned `wp-upgrade-shim` would die on module resolution, in the one command an\n// L0-blocked session has left. Its header records that, and points here.\n//\n// DEPENDENCY-FREE ANYWAY: `fs`, `path` and `toError`. No inversify (see StaleBinSweeper), so this module\n// stays cheap for the startup path it runs on and importable by anything that later needs it.\n// ---------------------------------------------------------------------------\n\n// The one place the prefix is spelled. Everything outside it belongs to some other package.\nconst WP_BIN_PREFIX = 'wp-';\n\n/**\n * One dangling entry the sweep ACTED ON: what was linked, the target that was not there, and — when the\n * removal itself failed — why. Data-only (per CLAUDE.md).\n *\n * `failure` exists because the removal is an `fs.rmSync`, not just a probe: an unwritable `.bin` (EACCES,\n * a read-only mount) would otherwise heal silently-never while the tree kept advertising a command that\n * does not exist, which is the precise defect this module exists to remove. Not thrown — the sweep is a\n * courtesy and must never fail the `wp-*` command that called it — so the diagnostic rides back here and\n * {@link StaleBinSweeper.report} states both outcomes.\n */\nexport class StaleBinRemoval {\n name: string; // the bin name as it appeared in .bin (e.g. 'wp-authorize')\n target: string; // the link target that does not exist, as recorded in the symlink\n failure: string; // '' = removed; non-empty = still there, and this is why\n\n constructor(name: string, target: string, failure = '') {\n this.name = name;\n this.target = target;\n this.failure = failure;\n }\n}\n\n/**\n * Removes `node_modules/.bin/wp-*` entries whose symlink target is gone.\n *\n * Deliberately NOT `@injectable`: decorating it would import inversify, and this module must stay loadable\n * by `wp-upgrade-shim` on a tree that cannot build a DI container (see the header). Callers use the shared\n * {@link staleBinSweeper} instance, which is also what makes {@link sweepOnce}'s memo process-wide.\n */\nexport class StaleBinSweeper {\n // Roots already swept in THIS process. `writeTemplate` is called several times per `wp-*` command (once\n // per instruct-ai doc), and a sweep that reported per call would print the same removals repeatedly.\n private readonly swept = new Set<string>();\n\n /** Where the bins live for a tree. Public so a test can point at a fixture without guessing the layout. */\n binDir(repoRoot: string): string {\n return path.join(repoRoot, 'node_modules', '.bin');\n }\n\n /**\n * Sweep once per root per process, returning what was removed ([] on every later call for the same\n * root, and [] when there was nothing to remove — the two are indistinguishable to a caller ON PURPOSE,\n * because both mean \"say nothing\").\n */\n sweepOnce(repoRoot: string): StaleBinRemoval[] {\n if (this.swept.has(repoRoot)) return [];\n this.swept.add(repoRoot);\n return this.sweep(repoRoot);\n }\n\n /**\n * Remove every dangling `wp-*` symlink under the tree's `.bin`, returning what went. [] when the\n * directory does not exist (a linked worktree with no install of its own is the common case) or when\n * everything there resolves.\n *\n * BEST EFFORT, PER ENTRY. A `.bin` that cannot be read, or one entry that cannot be removed, must never\n * take down the `wp-*` command that called this — the sweep is a courtesy, not the command's job.\n */\n sweep(repoRoot: string): StaleBinRemoval[] {\n const dir = this.binDir(repoRoot);\n const removed: StaleBinRemoval[] = [];\n for (const name of this.entries(dir)) {\n if (!name.startsWith(WP_BIN_PREFIX)) continue;\n const removal = this.removeIfDangling(path.join(dir, name), name);\n if (removal !== null) removed.push(removal);\n }\n return removed;\n }\n\n /**\n * The lines a caller prints for a sweep. [] for an empty sweep, so REMOVING NOTHING IS SILENT — this\n * runs on every `wp-*` command and the common case must add no noise at all.\n *\n * Rendered here rather than at each call site so the two callers cannot describe the same act\n * differently; each still chooses its own output channel and its own leading icon convention.\n */\n report(removed: readonly StaleBinRemoval[]): string[] {\n if (removed.length === 0) return [];\n const gone = removed.filter((r: StaleBinRemoval): boolean => r.failure === '');\n const stuck = removed.filter((r: StaleBinRemoval): boolean => r.failure !== '');\n const lines: string[] = [];\n if (gone.length > 0) {\n lines.push(`✅ @webpieces: removed ${gone.length} dangling node_modules/.bin/wp-* symlink(s) left by an earlier release:`);\n for (const r of gone) lines.push(` ${r.name} -> ${r.target} (target missing)`);\n lines.push(' They pointed at scripts this release no longer ships, so they could only ever fail on execution.');\n }\n // A failed removal is STATED, never quietly dropped: the entry is still there, still advertising a\n // command that does not exist, and only a human can fix an unwritable .bin.\n if (stuck.length > 0) {\n lines.push(`⚠️ @webpieces: ${stuck.length} dangling node_modules/.bin/wp-* symlink(s) could NOT be removed:`);\n for (const r of stuck) lines.push(` ${r.name} -> ${r.target} (target missing; ${r.failure})`);\n lines.push(' They still advertise commands this release does not ship. Nothing else is affected — remove them by hand.');\n }\n return lines;\n }\n\n // The directory listing, or [] when there is no .bin (or it cannot be read).\n private entries(dir: string): string[] {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unreadable .bin means \"nothing to sweep\", never a failed wp-* command\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n if (!fs.existsSync(dir)) return [];\n return fs.readdirSync(dir);\n } catch (err: unknown) {\n const error = toError(err);\n void error; // best effort: no readable .bin means there is nothing to sweep\n return [];\n }\n }\n\n /**\n * Remove ONE entry if — and only if — it is a symlink whose target does not exist. Returns what was\n * acted on, with `failure` set when the entry was dangling but could not be removed; `null` when the\n * entry was not a dangling `wp-*` link at all.\n */\n private removeIfDangling(full: string, name: string): StaleBinRemoval | null {\n const target = this.danglingTarget(full);\n if (target === null) return null;\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unremovable entry is REPORTED, never fatal to the wp-* command that called the sweep\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.rmSync(full, { force: true });\n return new StaleBinRemoval(name, target);\n } catch (err: unknown) {\n const error = toError(err);\n return new StaleBinRemoval(name, target, error.message);\n }\n }\n\n /**\n * The link target of a DANGLING symlink, or `null` when this entry is not one — a real file, a live\n * link, or something we cannot stat. `existsSync` FOLLOWS symlinks, so a false answer on a path `lstat`\n * calls a link is exactly the dangling case, with no need to resolve the target ourselves.\n *\n * Split from the removal so the two catches mean different things: an unreadable entry is simply not\n * ours to touch, while a failed REMOVAL is a fact worth printing.\n */\n private danglingTarget(full: string): string | null {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an entry we cannot stat is not ours to touch\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n if (!fs.lstatSync(full).isSymbolicLink()) return null;\n if (fs.existsSync(full)) return null;\n return fs.readlinkSync(full);\n } catch (err: unknown) {\n const error = toError(err);\n void error; // best effort: an entry we cannot read is left exactly as it is\n return null;\n }\n }\n}\n\n// The shared instance — the memo in `sweepOnce` is per-instance, so every caller must use this one.\nexport const staleBinSweeper = new StaleBinSweeper();\n"]}
@@ -6,10 +6,10 @@ const child_process_1 = require("child_process");
6
6
  const fs = tslib_1.__importStar(require("fs"));
7
7
  const path = tslib_1.__importStar(require("path"));
8
8
  const inversify_1 = require("inversify");
9
- const claude_config_dir_1 = require("./claude-config-dir");
10
- const to_error_1 = require("./to-error");
11
- const state_dir_1 = require("./state-dir");
12
- const review_identity_stamp_1 = require("./review-identity-stamp");
9
+ const tooling_common_1 = require("@webpieces/tooling-common");
10
+ const to_error_1 = require("@webpieces/tooling-common/to-error");
11
+ const tooling_common_2 = require("@webpieces/tooling-common");
12
+ const repo_workflow_core_1 = require("@webpieces/repo-workflow-core");
13
13
  // Outcome of a provenance check.
14
14
  exports.PROVENANCE_OK = 'ok'; // a matching reviewer subagent demonstrably ran on this branch
15
15
  exports.PROVENANCE_MISSING = 'missing'; // session known, but no matching subagent artifact found → refuse (BLOCK)
@@ -457,7 +457,7 @@ let SubagentProvenanceService = class SubagentProvenanceService {
457
457
  submittedVerdict(inputs, checklistId, verdictPath) {
458
458
  if (verdictPath !== '' && this.mentions(inputs, verdictPath))
459
459
  return true;
460
- return inputs.some((i) => review_identity_stamp_1.reviewIdentityStamps.invokedChecklists(i).includes(checklistId));
460
+ return inputs.some((i) => repo_workflow_core_1.reviewIdentityStamps.invokedChecklists(i).includes(checklistId));
461
461
  }
462
462
  /**
463
463
  * Every `<config>/projects/&#42;/<session>/subagents` dir that exists — matching by the recorded
@@ -470,7 +470,7 @@ let SubagentProvenanceService = class SubagentProvenanceService {
470
470
  */
471
471
  allSubagentsDirs() {
472
472
  const out = [];
473
- for (const projects of claude_config_dir_1.claudeConfigDir.projectsRoots()) {
473
+ for (const projects of tooling_common_1.claudeConfigDir.projectsRoots()) {
474
474
  for (const proj of this.readDir(projects)) {
475
475
  const projDir = path.join(projects, proj);
476
476
  for (const session of this.readDir(projDir)) {
@@ -623,7 +623,7 @@ let SubagentProvenanceService = class SubagentProvenanceService {
623
623
  pinnedBranch(cwd) {
624
624
  if (!fs.existsSync(cwd))
625
625
  return '';
626
- if (!state_dir_1.dotWebpieces.isLinkedWorktree(cwd))
626
+ if (!tooling_common_2.dotWebpieces.isLinkedWorktree(cwd))
627
627
  return '';
628
628
  const result = (0, child_process_1.spawnSync)('git', ['-C', cwd, 'rev-parse', '--abbrev-ref', 'HEAD'], { encoding: 'utf8' });
629
629
  if (result.status !== 0)
@@ -1 +1 @@
1
- {"version":3,"file":"subagent-provenance.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/subagent-provenance.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAC3D,2DAAsD;AACtD,yCAAqC;AACrC,2CAA2C;AAC3C,mEAA+D;AAE/D,iCAAiC;AACpB,QAAA,aAAa,GAAG,IAAI,CAAC,CAAW,+DAA+D;AAC/F,QAAA,kBAAkB,GAAG,SAAS,CAAC,CAAC,0EAA0E;AAC1G,QAAA,kBAAkB,GAAG,SAAS,CAAC,CAAC,4GAA4G;AAEzJ,MAAa,gBAAgB;IACzB,MAAM,CAAS,CAAC,0DAA0D;IAC1E,MAAM,CAAS,CAAC,6DAA6D;IAC7E,yGAAyG;IACzG,4FAA4F;IAC5F,QAAQ,CAAyB;IACjC;;;;;;;;OAQG;IACH,OAAO,CAAW;IAElB;;;;;;;;;OASG;IACH,yDAAyD;IACzD,YAAY,MAAc,EAAE,MAAc,EAAE,QAAgC,EAAE,OAAiB;QAC3F,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,OAAO,GAAG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AAE,CAAC;gBAC/D,IAAI,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE;oBAAE,OAAO,IAAI,CAAC;YACxC,CAAC;YACD,OAAO,EAAE,CAAC;QACd,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,gGAAgG;QAChG,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;IAED,uFAAuF;IAC/E,SAAS,CAAC,IAAY;QAC1B,yFAAyF;QACzF,8DAA8D;QAC9D,IAAI,CAAC;YACD,yFAAyF;YACzF,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAA4B,CAAC;QACvD,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,KAAK,KAAK,CAAC;YACX,OAAO,IAAI,CAAC;QAChB,CAAC;IACL,CAAC;CACJ,CAAA;AAxeY,8DAAyB;oCAAzB,yBAAyB;IADrC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;GAC5B,yBAAyB,CAwerC","sourcesContent":["import { spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { claudeConfigDir } from './claude-config-dir';\nimport { toError } from './to-error';\nimport { dotWebpieces } from './state-dir';\nimport { reviewIdentityStamps } from './review-identity-stamp';\n\n// Outcome of a provenance check.\nexport const PROVENANCE_OK = 'ok'; // a matching reviewer subagent demonstrably ran on this branch\nexport const PROVENANCE_MISSING = 'missing'; // session known, but no matching subagent artifact found → refuse (BLOCK)\nexport const PROVENANCE_SKIPPED = 'skipped'; // no CLAUDE_CODE_SESSION_ID → transcript evidence skipped; wp-write-review provenance still enforced (#863)\n\nexport class ProvenanceResult {\n status: string; // PROVENANCE_OK | PROVENANCE_MISSING | PROVENANCE_SKIPPED\n detail: string; // human-readable explanation for the warning/error/dashboard\n // agentIds credited, keyed by CHECKLIST ID, so an evidence pass does not re-scan to find them again. Two\n // checklists may map to the same agentId when `reviewerAgents` let one subagent cover both.\n agentIds: Record<string, string>;\n /**\n * The checklist ids that could NOT be credited — the FACT, with no remedy attached.\n *\n * Structured rather than only spelled into `detail` because the remedy depends on something this\n * service cannot see: whether that reviewer already wrote a verdict file. \"It never ran\" and \"it ran\n * and cannot be attributed\" need OPPOSITE instructions — spawn one, versus do not re-spawn, because a\n * re-spawn overwrites the verdict and is stamped identically. Handing the caller a pre-worded\n * imperative is what produced the destructive loop this field exists to end; see ProvenanceEnforcer.\n */\n missing: string[];\n\n /**\n * `agentIds` and `missing` are REQUIRED, with no defaults.\n *\n * A default on `missing` is what made the dangerous state cheap to reach: the caller BLOCKS on this\n * list, so a `PROVENANCE_MISSING` built without it would report unverified and refuse NOTHING — a\n * silent pass, one forgotten argument away. Required parameters make the omission a compile error at\n * every construction site, present and future. The remaining `missing: []` on a blocking status is\n * caught by the caller, which refuses on the STATUS and falls back to `detail`; see\n * ProvenanceEnforcer.refuse.\n */\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(status: string, detail: string, agentIds: Record<string, string>, missing: string[]) {\n this.status = status;\n this.detail = detail;\n this.agentIds = agentIds;\n this.missing = missing;\n }\n}\n\n/**\n * What ONE credited reviewer actually DID, read from its own transcript. Data-only (per CLAUDE.md).\n *\n * `verifyReviewers` answers \"did a reviewer of this type run?\" — an INTEGRITY question, and it blocks. This\n * answers \"did it look at the change?\" — a QUALITY question, and it only warns. The distinction is\n * deliberate; see {@link SubagentProvenanceService.evidenceFor}.\n */\nexport class ReviewerEvidence {\n checklistId: string; // the checklist this evidence is FOR (one subagent may appear under several)\n agentType: string;\n agentId: string;\n readDiff: boolean; // opened the materialized diff dir (or its own instructions file)\n readDoc: boolean; // opened its checklist's guidance doc\n /**\n * Named its own verdict file — `.webpieces/pr-review/<featureSlug>/review-round<N>-<id>.json` — in a tool input.\n *\n * Recorded, not just consumed, because it is the field that answers \"who wrote this verdict?\" for an\n * auditor reading provenance.json later. It is also a CREDIT channel: see\n * {@link SubagentProvenanceService.creditedByWhatItTouched}.\n */\n wroteVerdict: boolean;\n toolCallCount: number;\n offRepoSearches: number; // tool calls that reached into node_modules — the archaeology signal\n /**\n * Distinct `message.model` values OBSERVED in the transcript, in first-seen order.\n *\n * The model that actually ran, never the one that was configured — and never anything the reviewer\n * says about itself. The reviewer agent's `.claude/agents/<name>.md` may declare `model:`, but that is the\n * REQUESTED value and it can silently disagree with what served the request: a repo was measured\n * running opus for a reviewer whose agent file said `model: sonnet`. Asking the model instead would\n * be worse — a model is unreliable about its own identity, naming a family instead of a version or\n * repeating whatever the system prompt implied, so a self-reported field is usually right and\n * silently wrong, which is the worst kind of telemetry because it looks authoritative.\n * `message.model` is written by the harness, so this inherits the anti-forgery property the rest of\n * this class documents.\n *\n * An ARRAY, not a string: one reviewer run can span more than one model (a fallback after a refusal,\n * a mid-run config change). Collapsing to one value forces a lossy choice at read time; recording\n * what happened lets the renderer decide.\n *\n * Token counts and cost are deliberately NOT here. Prices change, vary by platform and differ under\n * intro pricing, so a rate table in this package would rot silently — and the question this answers\n * is \"which model reviewed this?\", not \"what did it cost?\".\n */\n models: string[];\n // Absolute path of the transcript these counters were read out of, '' when it could not be resolved.\n // Carried out rather than recomputed because a reviewer subagent cannot learn its own transcript path\n // (the environment exposes the PARENT session id and no agent id), so this is the only place it is\n // known — see ReviewProvenanceService, which records it as the audit link for the verdict.\n transcriptPath: string;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(checklistId: string, agentType: string, agentId: string, readDiff = false, readDoc = false, toolCallCount = 0, offRepoSearches = 0, transcriptPath = '', models: string[] = [], wroteVerdict = false) {\n this.checklistId = checklistId;\n this.agentType = agentType;\n this.agentId = agentId;\n this.readDiff = readDiff;\n this.readDoc = readDoc;\n this.wroteVerdict = wroteVerdict;\n this.toolCallCount = toolCallCount;\n this.offRepoSearches = offRepoSearches;\n this.transcriptPath = transcriptPath;\n this.models = models;\n }\n}\n\n/**\n * One pass over one transcript: the tool inputs AND the models that served it. Data-only.\n *\n * They are gathered together rather than in two passes because they come from the SAME records — the\n * inputs from `message.content[].input`, the model from `message.model` one level up — and a transcript\n * is the largest file this service opens. Two reads of it to answer two questions about the same lines\n * would be the duplicate-work trap the diff materializer documents at length.\n */\nexport class TranscriptScan {\n inputs: string[]; // every tool_use input, JSON-stringified\n models: string[]; // distinct message.model values, first-seen order\n\n constructor(inputs: string[] = [], models: string[] = []) {\n this.inputs = inputs;\n this.models = models;\n }\n}\n\n/**\n * WHERE this branch's review materials live. Data-only.\n *\n * One class for BOTH passes — crediting (`verifyReviewers`) and evidence (`evidenceFor`) — because they\n * ask their questions of the same paths. `diffDir` is the per-branch materialization\n * (`.webpieces/pr-review/<featureSlug>/diff`), which is what makes it usable as PROOF of which branch a\n * reviewer looked at: the path names the branch, it is absolute, and stage ② recreates it per run.\n */\nexport class ReviewerContext {\n branch: string;\n diffDir: string; // '' when nothing was materialized\n docPaths: Record<string, string>; // checklist id → its checklist doc path ('' when none)\n /**\n * checklist id → the absolute path of the verdict file THAT checklist must write on THIS branch\n * (`.webpieces/pr-review/<featureSlug>/review-round<N>-<id>.json`). '' when unknown.\n *\n * The strongest attribution signal available, and stronger than `diffDir`: the path is\n * worktree-absolute (naming the tree), per-branch (naming the featureSlug) AND per-checklist (naming\n * the id), so a transcript containing it can only belong to a reviewer that authored that checklist's\n * verdict for that branch. `diffDir` proves the branch but not the checklist.\n */\n verdictPaths: Record<string, string>;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(branch: string, diffDir = '', docPaths: Record<string, string> = {}, verdictPaths: Record<string, string> = {}) {\n this.branch = branch;\n this.diffDir = diffDir;\n this.docPaths = docPaths;\n this.verdictPaths = verdictPaths;\n }\n}\n\n/**\n * One checklist that must be credited to a reviewer run, plus the agent type the BRIEFING named. Data-only.\n *\n * The two used to be one string — a checklist's id WAS its agent type — and provenance keyed everything by\n * it. Now every checklist is reviewed by the same repo-wide agent type, so the id and the type are\n * separate facts.\n *\n * `agentType` is NOT a provenance input: nothing here matches a run on it (issue #964, see\n * {@link SubagentProvenanceService.isReviewerRun}). It is carried because it is what the BRIEFING told\n * the agent to spawn and what {@link ReviewerEvidence} reports, which are both worth recording even\n * though neither is worth gating on.\n */\nexport class ExpectedReviewer {\n checklistId: string;\n agentType: string;\n\n constructor(checklistId: string, agentType: string) {\n this.checklistId = checklistId;\n this.agentType = agentType;\n }\n}\n\n/**\n * Verifies — from the Claude Code harness's OWN artifacts, never from anything the model asserts — that\n * a real SUBAGENT actually ran on the current branch and did this checklist's work. Used to enforce that\n * every checklist was reviewed by an INDEPENDENT reviewer, rather than by the coding agent\n * self-certifying.\n *\n * The harness writes, beside each subagent transcript:\n * <config>/projects/<cwd-slug>/<sessionId>/subagents/agent-<id>.meta.json → { agentType, spawnDepth, … }\n * <config>/projects/<cwd-slug>/<sessionId>/subagents/agent-<id>.jsonl → record 0 { isSidechain, gitBranch, … }\n * `spawnDepth`/`isSidechain` are written by Claude Code, not by the model, and they are what carries the\n * anti-self-certification property. `agentType` is written there too and is deliberately NOT checked —\n * see {@link SubagentProvenanceService.isReviewerRun}. `<config>` is `$CLAUDE_CONFIG_DIR` when set, else\n * `~/.claude`; see {@link ClaudeConfigDir}, and never re-derive it here. Dirs are found by walking\n * every session, so the cwd-slug never has to be derived/guessed.\n *\n * IMPORTANT — this is NOT tamper-proof. A determined agent can `cat >` a fake agent-*.meta.json. This\n * raises the bar from \"trust the model's word\" to \"deliberate, auditable forgery outside the repo\"; it\n * is not cryptographic. Say so wherever reviewer provenance is documented.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it is drawn in the DI design and injected by type.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class SubagentProvenanceService {\n // cwd → the branch it is PINNED to ('' when it is not a linked worktree, or is unresolvable).\n // See branchOfCwd for why it is cached and pinnedBranch for what \"pinned\" buys.\n private readonly branchByCwd = new Map<string, string>();\n\n // transcript path → its one scan. The credit pass and the evidence pass ask different questions of\n // the same (largest) files this service opens, and the credit pass may look at candidates the\n // evidence pass then re-visits. See scanTranscript for why one pass answers both.\n private readonly scanByPath = new Map<string, TranscriptScan>();\n\n // Verify EVERY expected checklist was reviewed by a reviewer subagent that ran on `context.branch` — the\n // coding agent may not self-certify. SKIPPED (pass) without a session id.\n //\n // ONE run may cover SEVERAL checklists: `reviewerAgents` is a required config field and is a CAP, so\n // grouping is always something the repo asked for. A run is still only credited when it is a real\n // subagent of the right type that ran on this branch.\n //\n // (A removed `sharedRuns` flag once demanded a distinct run per checklist; a cap is a MAXIMUM, so it never could.)\n // Either way a run that NAMED (or wp-write-review-submitted) this checklist's verdict is preferred over one that merely ran on the\n // branch, so each checklist is credited to the reviewer that actually wrote it whenever that is knowable.\n //\n // Scoped by BRANCH across ALL sessions (not the current session): once a reviewer ran on this branch in\n // any session, a later re-push in a NEW session still finds it, so the review is NOT forced to re-run.\n // That is what keeps \"review once per branch\" true across sessions. A PR opened outside the gated flow\n // still has no review-round<N>-<id>.json, so wp-finish forces the review regardless of provenance.\n verifyReviewers(expected: readonly ExpectedReviewer[], context: ReviewerContext): ProvenanceResult {\n if (expected.length === 0) return new ProvenanceResult(PROVENANCE_OK, 'no reviewer subagents required', {}, []);\n if (!this.inClaudeSession()) return this.skipped('reviewer subagents');\n const dirs = this.allSubagentsDirs();\n const missing: string[] = [];\n const usedAgentIds = new Set<string>();\n const credited: Record<string, string> = {};\n for (const want of expected) {\n const agentId = this.findMatchingAgentId(dirs, want, context, new Set<string>());\n if (agentId === '') missing.push(want.checklistId);\n else {\n usedAgentIds.add(agentId);\n credited[want.checklistId] = agentId;\n }\n }\n const runs = new Set(Object.values(credited)).size;\n return missing.length === 0\n ? new ProvenanceResult(PROVENANCE_OK,\n `verified ${expected.length} checklist(s) were reviewed by ${runs} reviewer subagent run(s)`, credited, [])\n : new ProvenanceResult(PROVENANCE_MISSING,\n `${missing.length} checklist(s) could not be attributed to a reviewer subagent on this branch: ${missing.join(', ')}`,\n credited, missing);\n }\n\n /**\n * What each credited reviewer actually READ, from its own transcript.\n *\n * `verifyReviewers` proves a reviewer of the right type RAN. It cannot tell a reviewer that read the diff\n * and thought about it from one that wrote a verdict having opened nothing. This closes that gap — and\n * the motivating case is real: one reviewer spent 14 of 26 tool calls grepping `node_modules` because\n * nothing had told it where anything was, which `offRepoSearches` now makes visible.\n *\n * WARNING-ONLY by default, for three reasons, and `requireDiffEvidence` must stay opt-in until at least\n * one repo has watched it:\n * 1. The transcript layout is undocumented Claude Code internals. A format change would wedge every\n * consumer's PR with no self-service recovery — `sidechainOnBranch` is already lenient for exactly\n * this reason, and blocking on a richer read of the same files would be less safe, not more.\n * 2. A reviewer can legitimately receive the diff another way (inlined into its prompt, say).\n * 3. verifyReviewers is the INTEGRITY signal and rightly blocks; this is a QUALITY signal. Conflating\n * them would let a transcript-parsing quirk refuse a PR that a real reviewer really did review.\n *\n * Returns [] outside a Claude Code session, matching verifyReviewers's SKIP behavior.\n */\n evidenceFor(context: ReviewerContext, expected: readonly ExpectedReviewer[], agentIds: Record<string, string>): ReviewerEvidence[] {\n if (!this.inClaudeSession()) return [];\n const dirs = this.allSubagentsDirs();\n const out: ReviewerEvidence[] = [];\n for (const want of expected) {\n const agentId = agentIds[want.checklistId];\n if (agentId === undefined) continue;\n const jsonl = this.transcriptPath(dirs, agentId);\n if (jsonl === '') {\n out.push(new ReviewerEvidence(want.checklistId, want.agentType, agentId));\n continue;\n }\n out.push(this.evidenceFromTranscript(want, agentId, jsonl, context));\n }\n return out;\n }\n\n // eslint-disable-next-line @typescript-eslint/max-params\n private evidenceFromTranscript(want: ExpectedReviewer, agentId: string, jsonl: string, context: ReviewerContext): ReviewerEvidence {\n const scan = this.scanTranscript(jsonl);\n const inputs = scan.inputs;\n const docPath = context.docPaths[want.checklistId] ?? '';\n const verdictPath = context.verdictPaths[want.checklistId] ?? '';\n return new ReviewerEvidence(\n want.checklistId, want.agentType, agentId, this.readDiffDir(scan, context),\n docPath !== '' && this.mentions(inputs, docPath),\n inputs.length,\n inputs.filter((i: string): boolean => i.includes('node_modules')).length,\n jsonl,\n scan.models,\n this.submittedVerdict(inputs, want.checklistId, verdictPath),\n );\n }\n\n // The instructions file counts as \"read the diff\": it lives in the same per-branch dir, it is what\n // the reviewer is told to open first, and it inlines the diff paths. A reviewer that opened it and\n // then its own diff files is the intended path; treating only the diff dir as proof would flag it.\n private readDiffDir(scan: TranscriptScan, context: ReviewerContext): boolean {\n return context.diffDir !== '' && this.mentions(scan.inputs, context.diffDir);\n }\n\n /**\n * Record this line's `message.model`, deduped, in first-seen order.\n *\n * `<synthetic>` records are SKIPPED. The harness writes them for messages no model produced (tool\n * results, injected notices); counting one would put a non-model in a field whose entire purpose is\n * \"which model reviewed this\", and it would show up on every single reviewer.\n */\n // webpieces-disable no-any-unknown -- opaque transcript record, only `model` is read and it is type-guarded below\n private collectModel(message: Record<string, unknown>, models: string[]): void {\n const model = message['model'];\n if (typeof model !== 'string' || model === '' || model === '<synthetic>') return;\n if (!models.includes(model)) models.push(model);\n }\n\n // The absolute path of agent-<id>.jsonl across all session dirs, or '' if it is not there.\n private transcriptPath(dirs: readonly string[], agentId: string): string {\n for (const dir of dirs) {\n const candidate = path.join(dir, `agent-${agentId}.jsonl`);\n if (fs.existsSync(candidate)) return candidate;\n }\n return '';\n }\n\n /**\n * ONE pass over the transcript for both answers (see {@link TranscriptScan}), CACHED per path.\n *\n * Cached because two passes now ask questions of the same file: crediting (does it name this branch's\n * verdict/diff?) and evidence (what did it read, which model served it?). Without the cache the credit\n * pass would re-read every candidate the evidence pass then re-opens — on the largest files this\n * service touches, on the path that opens a PR.\n *\n * Tool inputs are JSON-stringified rather than walked field-by-field because the shape differs per\n * tool (Read takes file_path, Bash takes command, Grep takes path) and a substring test over the\n * serialized input is both simpler and robust to a tool we have not seen.\n *\n * Best-effort, like everything else that parses this file: a format change must never wedge the\n * gate, so an unreadable transcript yields empty rather than throwing. That matters more for the\n * models than for the counters — this is quality telemetry, not an integrity check, and a missing\n * `model` field must not be able to block a PR.\n */\n private scanTranscript(jsonl: string): TranscriptScan {\n const cached = this.scanByPath.get(jsonl);\n if (cached !== undefined) return cached;\n const scan = this.readTranscript(jsonl);\n this.scanByPath.set(jsonl, scan);\n return scan;\n }\n\n private readTranscript(jsonl: string): TranscriptScan {\n const scan = new TranscriptScan();\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unreadable transcript yields no evidence, never a crash\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n for (const line of fs.readFileSync(jsonl, 'utf8').split('\\n')) {\n if (line.trim() === '') continue;\n const rec = this.parseLine(line);\n const message = rec?.['message'];\n if (typeof message !== 'object' || message === null) continue;\n // webpieces-disable no-any-unknown -- opaque transcript record, narrowed by the guard above\n const msg = message as Record<string, unknown>;\n this.collectModel(msg, scan.models);\n const content = msg['content'];\n if (!Array.isArray(content)) continue;\n for (const block of content) {\n // webpieces-disable no-any-unknown -- opaque content block, only `type`/`input` are read\n const b = block as Record<string, unknown>;\n if (b['type'] === 'tool_use') scan.inputs.push(JSON.stringify(b['input'] ?? {}));\n }\n }\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n return scan;\n }\n\n private mentions(inputs: readonly string[], needle: string): boolean {\n return inputs.some((i: string): boolean => i.includes(needle));\n }\n\n // Are we running under Claude Code at all? (CI / plain terminal → provenance is unverifiable → SKIP.)\n private inClaudeSession(): boolean {\n return (process.env['CLAUDE_CODE_SESSION_ID'] ?? '').trim() !== '';\n }\n\n private skipped(what: string): ProvenanceResult {\n return new ProvenanceResult(PROVENANCE_SKIPPED,\n `CLAUDE_CODE_SESSION_ID not set — no Claude transcripts to verify ${what} against (Codex / terminal / CI); each verdict's wp-write-review provenance is still enforced.`,\n {}, []);\n }\n\n // The agentId of a subagent run on `branch`, searched across ALL sessions' subagent dirs\n // (branch-scoped, so a run from a prior session still counts). '' if none. `exclude` skips agentIds\n // already credited to another checklist so one run can't satisfy two.\n //\n // The run is NOT matched on its agent type — see isReviewerRun for why that check was removed — so\n // several runs match and the one that NAMED this checklist's verdict file wins; the first\n // branch-matching run is the fallback, as before.\n // eslint-disable-next-line @typescript-eslint/max-params\n private findMatchingAgentId(dirs: readonly string[], want: ExpectedReviewer, context: ReviewerContext, exclude: ReadonlySet<string>): string {\n let fallback = '';\n for (const dir of dirs) {\n for (const metaFile of this.metaFiles(dir)) {\n const agentId = this.agentIdOf(metaFile);\n if (exclude.has(agentId) || !this.isReviewerRun(dir, metaFile)) continue;\n if (!this.sidechainOnBranch(dir, agentId, want.checklistId, context)) continue;\n if (this.namedVerdict(dir, agentId, want.checklistId, context)) return agentId;\n if (fallback === '') fallback = agentId;\n }\n }\n return fallback;\n }\n\n /**\n * A harness-written meta for a REAL SUBAGENT — `spawnDepth >= 1`, and nothing about its NAME.\n *\n * The agent TYPE used to be compared against the configured reviewer agent, and that check is\n * gone (issue #964). It proved nothing: `agentType` is a label on a prompt, and it does not show\n * the agent read the checklist, opened the diff, or looked at the right branch. The gates that DO\n * show those are untouched — `spawnDepth >= 1` plus `isSidechain === true` (see\n * {@link sidechainOnBranch}) are harness-written, so the main loop still cannot self-certify;\n * {@link creditedByWhatItTouched} proves the branch and the actual work; `requireDiffEvidence`\n * proves the diff was opened.\n *\n * It was also the ONLY gate with an unfixable failure mode. Claude Code snapshots agent\n * definitions per session and the refresh does not reach an already-running subagent, so a repo\n * that renames its reviewer agent mid-session leaves that subagent's registry offering only the\n * OLD names: the spawn is rejected, the agent falls back to `general-purpose`, does the real\n * review, writes every verdict — and is refused as unattributable, with no cwd, branch or respawn\n * able to change it. Measured: six checklists, six verdict files on disk, PR blocked.\n *\n * Accepted trade-off: without the name check the implementer's own subagent could in principle be\n * credited, since it touches the diff dir while running the gate. That is deliberate. The rule is\n * \"if the verdict file is there, a subagent wrote it\", and this gate's job is to catch \"no\n * subagent ran at all\" — not to adjudicate which subagent it was.\n */\n private isReviewerRun(dir: string, metaFile: string): boolean {\n const meta = this.readJson(path.join(dir, metaFile));\n if (!meta) return false;\n const spawnDepth = meta['spawnDepth'];\n return typeof spawnDepth === 'number' && spawnDepth >= 1;\n }\n\n // Did this run's transcript name the checklist's own verdict path?\n // eslint-disable-next-line @typescript-eslint/max-params\n private namedVerdict(dir: string, agentId: string, checklistId: string, context: ReviewerContext): boolean {\n const jsonl = path.join(dir, `agent-${agentId}.jsonl`);\n return fs.existsSync(jsonl) && this.submittedVerdict(this.scanTranscript(jsonl).inputs, checklistId, context.verdictPaths[checklistId] ?? '');\n }\n\n // Named its verdict file, or submitted it via wp-write-review (#863). Proves authorship, never branch.\n private submittedVerdict(inputs: readonly string[], checklistId: string, verdictPath: string): boolean {\n if (verdictPath !== '' && this.mentions(inputs, verdictPath)) return true;\n return inputs.some((i: string): boolean => reviewIdentityStamps.invokedChecklists(i).includes(checklistId));\n }\n\n /**\n * Every `<config>/projects/&#42;/<session>/subagents` dir that exists — matching by the recorded\n * gitBranch (not by session id) is what makes provenance survive across sessions.\n *\n * `<config>` comes from {@link ClaudeConfigDir.projectsRoots}, which is BOTH the configured\n * `$CLAUDE_CONFIG_DIR` tree and `~/.claude`. This used to be a hardcoded `~/.claude`, and on a\n * machine with a relocated config dir that found nothing at all — so every PR was refused with a\n * message about the reviewers' cwd, which is not what was wrong and which no agent could act on.\n */\n private allSubagentsDirs(): string[] {\n const out: string[] = [];\n for (const projects of claudeConfigDir.projectsRoots()) {\n for (const proj of this.readDir(projects)) {\n const projDir = path.join(projects, proj);\n for (const session of this.readDir(projDir)) {\n const candidate = path.join(projDir, session, 'subagents');\n if (fs.existsSync(candidate)) out.push(candidate);\n }\n }\n }\n return out;\n }\n\n private metaFiles(dir: string): string[] {\n return this.readDir(dir).filter((f: string): boolean => f.endsWith('.meta.json'));\n }\n\n // agent-<id>.meta.json → <id>\n private agentIdOf(metaFile: string): string {\n return metaFile.replace(/^agent-/, '').replace(/\\.meta\\.json$/, '');\n }\n\n /**\n * Cross-check the sibling transcript's record 0: isSidechain true (a real subagent, not the main\n * loop) and the same branch. Lenient on branch drift (a leftover …wpN suffix from a mid-flight\n * branch rename) and on a missing jsonl (meta already matched — accept, best-effort).\n *\n * WHEN `gitBranch` DISAGREES, A PINNED `cwd` DECIDES. Record 0 carries both fields, and the harness\n * can write a `gitBranch` that CONTRADICTS the record's own `cwd`: a reviewer subagent spawned into\n * a worktree on `dean/one-2406-…` was stamped `worktree-agent-a54887200e40eb956` — an unrelated,\n * still-live worktree's scaffold branch — deterministically, on four consecutive attempts, blocking\n * a PR whose required reviewer genuinely ran and genuinely passed. `stripWp` cannot bridge that, so\n * the reviewer was never credited and `wp-finish-upsert-pr` refused a legitimately-reviewed PR with\n * no in-flow recovery. A sweep of 961 record-0s on one machine found the mis-stamp is the MAJORITY\n * case among subagents in dedicated worktrees, so trusting `gitBranch` alone can never be correct.\n *\n * ─── Why ONLY a linked worktree, and never the primary clone ──────────────────────────────────\n * \"Ask git what branch the cwd is on\" is correct only when that cwd CANNOT have moved since the\n * reviewer ran. A LINKED WORKTREE is 1:1 with the agent that owns it and nothing re-checks it out;\n * the PRIMARY CLONE gets checked out constantly. Falling back on a primary-clone cwd would credit a\n * STALE reviewer, and by construction rather than by accident:\n *\n * 1. a reviewer runs in the primary clone while it is on branch A\n * 2. the clone is later checked out to branch B\n * 3. `wp-finish-upsert-pr` runs on B — `gitBranch` (stamped A) mismatches\n * 4. `git -C <clone>` now answers B, because the CLONE moved → the reviewer is credited for B\n *\n * It reviewed A. Every past reviewer run in that clone would be credited for whatever branch is\n * checked out at finish time — which in a repo with a required reviewer on every PR is not an\n * exotic sequence, it is the normal one. So the fallback is gated on `dotWebpieces.isLinkedWorktree`\n * (git's own `--git-dir != --git-common-dir` test, reused rather than re-derived), and a primary\n * clone falls through to a refusal exactly as it does today.\n *\n * That gate keeps the anti-forgery property intact: `cwd` is harness-written in the same record by\n * the same writer as `gitBranch`, so it carries the same weight — and inside a pinned worktree it is\n * the field that is CORRECT. There is deliberately no config flag and no second comparison mode:\n * ONE rule, with `gitBranch` only ever a cheap way to skip the subprocess when it already agrees.\n *\n * An UNRESOLVABLE cwd does not credit either. A reaped worktree, a deleted directory, a non-repo\n * path or a detached HEAD yields '' and falls through to a refusal. Leniency here is bounded by\n * \"git can still prove it\", never by \"we could not check, so assume yes\".\n *\n * ─── Why neither field can settle it from a PRIMARY CLONE, and what does ──────────────────────\n * Both fields above are stamped from the SPAWNING session's cwd — the Agent tool has no cwd\n * parameter, so a subagent inherits its parent's. A session rooted in the primary clone that spawns\n * a reviewer for a WORKTREE branch therefore produces `gitBranch` = the clone's branch (mismatch)\n * and `cwd` = the clone (gated off, correctly) — and NO respawn can change either stamp. That is not\n * an exotic setup: it is what the flow instructs the moment a worker agent dies mid-flow and the\n * top-level session has to take over, and it deadlocked a branch whose seven reviewers had all run.\n *\n * So the third channel is not a loosening of the cwd rule — it is a DIFFERENT question, asked of\n * evidence the reviewer cannot inherit and cannot fake by accident: {@link creditedByWhatItTouched}.\n */\n // eslint-disable-next-line @typescript-eslint/max-params\n private sidechainOnBranch(dir: string, agentId: string, checklistId: string, context: ReviewerContext): boolean {\n const jsonl = path.join(dir, `agent-${agentId}.jsonl`);\n if (!fs.existsSync(jsonl)) return true;\n const first = this.firstNonEmptyLine(jsonl);\n if (first === '') return true;\n const rec = this.parseLine(first);\n if (!rec) return true;\n if (rec['isSidechain'] !== true) return false;\n const gitBranch = rec['gitBranch'];\n // Not recorded at all → accept, as before: nothing to contradict and nothing to verify against.\n if (typeof gitBranch !== 'string' || gitBranch === '') return true;\n const want = this.stripWp(context.branch);\n if (this.stripWp(gitBranch) === want) return true;\n if (want !== '' && this.stripWp(this.branchOfCwd(rec['cwd'])) === want) return true;\n return this.creditedByWhatItTouched(jsonl, checklistId, context);\n }\n\n /**\n * Credit a reviewer for WHAT IT TOUCHED when neither harness-stamped field can settle it.\n *\n * Both paths compared here are ABSOLUTE and BRANCH-SPECIFIC — they live under\n * `<worktree>/.webpieces/pr-review/<featureSlug>/`, so the string names the tree AND the branch. A\n * reviewer that worked on a different branch cannot have them in its transcript, and a reviewer of\n * this branch that ran from a mis-stamped cwd cannot avoid having them. That is the property\n * `gitBranch` lacks — this file's own sweep of 961 record-0s found the mis-stamp is the MAJORITY\n * case among subagents in dedicated worktrees.\n *\n * Two channels, either sufficient:\n * 1. it WROTE this checklist's verdict file — proves branch AND checklist, and is the act the whole\n * gate is trying to attribute. Matched as a substring of any tool input, so a Write, an Edit and\n * a `cat > <path>` heredoc all count; the point is that the path was named, not which tool named it.\n * 2. it READ this branch's materialized diff dir — proves the branch. Kept as a second channel\n * because a reviewer whose verdict was relayed by its parent still demonstrably reviewed this\n * branch, and refusing that would re-open a narrower version of the same unrecoverable deadlock.\n *\n * Independence is NOT weakened by either: `isSidechain === true` and `spawnDepth >= 1` are checked\n * before we get here (so the main loop's own transcript can never qualify), and `verifyReviewers`\n * excludes an agentId already credited to another checklist. It remains non-tamper-proof in exactly\n * the way the class doc already states — forging this now means forging a transcript rather than a\n * meta.json, which is the same bar, not a lower one.\n */\n private creditedByWhatItTouched(jsonl: string, checklistId: string, context: ReviewerContext): boolean {\n const scan = this.scanTranscript(jsonl);\n const verdictPath = context.verdictPaths[checklistId] ?? '';\n if (verdictPath !== '' && this.mentions(scan.inputs, verdictPath)) return true;\n return this.readDiffDir(scan, context);\n }\n\n /**\n * The branch record-0's own `cwd` is PINNED to, '' when that cannot be established or is not pinned.\n *\n * Cached per cwd because `findMatchingAgentId` walks every subagent of every session on the machine\n * and several of them share a worktree — one `git` process per RECORD would put dozens of spawns on\n * the path that opens a PR.\n */\n // webpieces-disable no-any-unknown -- one opaque record field, type-guarded on the next line\n private branchOfCwd(cwd: unknown): string {\n if (typeof cwd !== 'string' || cwd === '') return '';\n const cached = this.branchByCwd.get(cwd);\n if (cached !== undefined) return cached;\n const resolved = this.pinnedBranch(cwd);\n this.branchByCwd.set(cwd, resolved);\n return resolved;\n }\n\n /**\n * The branch of `cwd` when — and only when — `cwd` is a LINKED WORKTREE. '' otherwise.\n *\n * '' for the primary clone (it moves; see sidechainOnBranch for the false-accept that closes), for a\n * reaped or deleted directory, for a non-repo path, when git is unavailable, and for a detached HEAD,\n * which `--abbrev-ref` prints as the literal `HEAD` and which names no branch.\n */\n private pinnedBranch(cwd: string): string {\n if (!fs.existsSync(cwd)) return '';\n if (!dotWebpieces.isLinkedWorktree(cwd)) return '';\n const result = spawnSync('git', ['-C', cwd, 'rev-parse', '--abbrev-ref', 'HEAD'], { encoding: 'utf8' });\n if (result.status !== 0) return '';\n const printed = (result.stdout ?? '').trim();\n return printed === 'HEAD' ? '' : printed;\n }\n\n private stripWp(branch: string): string {\n return branch.replace(/-?wp\\d+$/i, '');\n }\n\n private readDir(dir: string): string[] {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unreadable dir yields [] (best-effort provenance)\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return fs.readdirSync(dir);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return [];\n }\n }\n\n private firstNonEmptyLine(filePath: string): string {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: unreadable transcript → '' (best-effort)\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n for (const line of fs.readFileSync(filePath, 'utf8').split('\\n')) {\n if (line.trim() !== '') return line;\n }\n return '';\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return '';\n }\n }\n\n // webpieces-disable no-any-unknown -- opaque parsed JSON object, keys read by the caller\n private readJson(filePath: string): Record<string, unknown> | null {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: malformed meta.json → null (skipped)\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // webpieces-disable no-any-unknown -- parsed JSON is opaque until narrowed by the caller\n return JSON.parse(fs.readFileSync(filePath, 'utf8')) as Record<string, unknown>;\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n\n // webpieces-disable no-any-unknown -- one opaque JSONL record, keys read by the caller\n private parseLine(line: string): Record<string, unknown> | null {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: malformed JSONL record → null\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // webpieces-disable no-any-unknown -- parsed JSON is opaque until narrowed by the caller\n return JSON.parse(line) as Record<string, unknown>;\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n}\n"]}
1
+ {"version":3,"file":"subagent-provenance.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/subagent-provenance.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAC3D,8DAA4D;AAC5D,iEAA6D;AAC7D,8DAAyD;AACzD,sEAAqE;AAErE,iCAAiC;AACpB,QAAA,aAAa,GAAG,IAAI,CAAC,CAAW,+DAA+D;AAC/F,QAAA,kBAAkB,GAAG,SAAS,CAAC,CAAC,0EAA0E;AAC1G,QAAA,kBAAkB,GAAG,SAAS,CAAC,CAAC,4GAA4G;AAEzJ,MAAa,gBAAgB;IACzB,MAAM,CAAS,CAAC,0DAA0D;IAC1E,MAAM,CAAS,CAAC,6DAA6D;IAC7E,yGAAyG;IACzG,4FAA4F;IAC5F,QAAQ,CAAyB;IACjC;;;;;;;;OAQG;IACH,OAAO,CAAW;IAElB;;;;;;;;;OASG;IACH,yDAA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AxeY,8DAAyB;oCAAzB,yBAAyB;IADrC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;GAC5B,yBAAyB,CAwerC","sourcesContent":["import { spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { claudeConfigDir } from '@webpieces/tooling-common';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { dotWebpieces } from '@webpieces/tooling-common';\nimport { reviewIdentityStamps } from '@webpieces/repo-workflow-core';\n\n// Outcome of a provenance check.\nexport const PROVENANCE_OK = 'ok'; // a matching reviewer subagent demonstrably ran on this branch\nexport const PROVENANCE_MISSING = 'missing'; // session known, but no matching subagent artifact found → refuse (BLOCK)\nexport const PROVENANCE_SKIPPED = 'skipped'; // no CLAUDE_CODE_SESSION_ID → transcript evidence skipped; wp-write-review provenance still enforced (#863)\n\nexport class ProvenanceResult {\n status: string; // PROVENANCE_OK | PROVENANCE_MISSING | PROVENANCE_SKIPPED\n detail: string; // human-readable explanation for the warning/error/dashboard\n // agentIds credited, keyed by CHECKLIST ID, so an evidence pass does not re-scan to find them again. Two\n // checklists may map to the same agentId when `reviewerAgents` let one subagent cover both.\n agentIds: Record<string, string>;\n /**\n * The checklist ids that could NOT be credited — the FACT, with no remedy attached.\n *\n * Structured rather than only spelled into `detail` because the remedy depends on something this\n * service cannot see: whether that reviewer already wrote a verdict file. \"It never ran\" and \"it ran\n * and cannot be attributed\" need OPPOSITE instructions — spawn one, versus do not re-spawn, because a\n * re-spawn overwrites the verdict and is stamped identically. Handing the caller a pre-worded\n * imperative is what produced the destructive loop this field exists to end; see ProvenanceEnforcer.\n */\n missing: string[];\n\n /**\n * `agentIds` and `missing` are REQUIRED, with no defaults.\n *\n * A default on `missing` is what made the dangerous state cheap to reach: the caller BLOCKS on this\n * list, so a `PROVENANCE_MISSING` built without it would report unverified and refuse NOTHING — a\n * silent pass, one forgotten argument away. Required parameters make the omission a compile error at\n * every construction site, present and future. The remaining `missing: []` on a blocking status is\n * caught by the caller, which refuses on the STATUS and falls back to `detail`; see\n * ProvenanceEnforcer.refuse.\n */\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(status: string, detail: string, agentIds: Record<string, string>, missing: string[]) {\n this.status = status;\n this.detail = detail;\n this.agentIds = agentIds;\n this.missing = missing;\n }\n}\n\n/**\n * What ONE credited reviewer actually DID, read from its own transcript. Data-only (per CLAUDE.md).\n *\n * `verifyReviewers` answers \"did a reviewer of this type run?\" — an INTEGRITY question, and it blocks. This\n * answers \"did it look at the change?\" — a QUALITY question, and it only warns. The distinction is\n * deliberate; see {@link SubagentProvenanceService.evidenceFor}.\n */\nexport class ReviewerEvidence {\n checklistId: string; // the checklist this evidence is FOR (one subagent may appear under several)\n agentType: string;\n agentId: string;\n readDiff: boolean; // opened the materialized diff dir (or its own instructions file)\n readDoc: boolean; // opened its checklist's guidance doc\n /**\n * Named its own verdict file — `.webpieces/pr-review/<featureSlug>/review-round<N>-<id>.json` — in a tool input.\n *\n * Recorded, not just consumed, because it is the field that answers \"who wrote this verdict?\" for an\n * auditor reading provenance.json later. It is also a CREDIT channel: see\n * {@link SubagentProvenanceService.creditedByWhatItTouched}.\n */\n wroteVerdict: boolean;\n toolCallCount: number;\n offRepoSearches: number; // tool calls that reached into node_modules — the archaeology signal\n /**\n * Distinct `message.model` values OBSERVED in the transcript, in first-seen order.\n *\n * The model that actually ran, never the one that was configured — and never anything the reviewer\n * says about itself. The reviewer agent's `.claude/agents/<name>.md` may declare `model:`, but that is the\n * REQUESTED value and it can silently disagree with what served the request: a repo was measured\n * running opus for a reviewer whose agent file said `model: sonnet`. Asking the model instead would\n * be worse — a model is unreliable about its own identity, naming a family instead of a version or\n * repeating whatever the system prompt implied, so a self-reported field is usually right and\n * silently wrong, which is the worst kind of telemetry because it looks authoritative.\n * `message.model` is written by the harness, so this inherits the anti-forgery property the rest of\n * this class documents.\n *\n * An ARRAY, not a string: one reviewer run can span more than one model (a fallback after a refusal,\n * a mid-run config change). Collapsing to one value forces a lossy choice at read time; recording\n * what happened lets the renderer decide.\n *\n * Token counts and cost are deliberately NOT here. Prices change, vary by platform and differ under\n * intro pricing, so a rate table in this package would rot silently — and the question this answers\n * is \"which model reviewed this?\", not \"what did it cost?\".\n */\n models: string[];\n // Absolute path of the transcript these counters were read out of, '' when it could not be resolved.\n // Carried out rather than recomputed because a reviewer subagent cannot learn its own transcript path\n // (the environment exposes the PARENT session id and no agent id), so this is the only place it is\n // known — see ReviewProvenanceService, which records it as the audit link for the verdict.\n transcriptPath: string;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(checklistId: string, agentType: string, agentId: string, readDiff = false, readDoc = false, toolCallCount = 0, offRepoSearches = 0, transcriptPath = '', models: string[] = [], wroteVerdict = false) {\n this.checklistId = checklistId;\n this.agentType = agentType;\n this.agentId = agentId;\n this.readDiff = readDiff;\n this.readDoc = readDoc;\n this.wroteVerdict = wroteVerdict;\n this.toolCallCount = toolCallCount;\n this.offRepoSearches = offRepoSearches;\n this.transcriptPath = transcriptPath;\n this.models = models;\n }\n}\n\n/**\n * One pass over one transcript: the tool inputs AND the models that served it. Data-only.\n *\n * They are gathered together rather than in two passes because they come from the SAME records — the\n * inputs from `message.content[].input`, the model from `message.model` one level up — and a transcript\n * is the largest file this service opens. Two reads of it to answer two questions about the same lines\n * would be the duplicate-work trap the diff materializer documents at length.\n */\nexport class TranscriptScan {\n inputs: string[]; // every tool_use input, JSON-stringified\n models: string[]; // distinct message.model values, first-seen order\n\n constructor(inputs: string[] = [], models: string[] = []) {\n this.inputs = inputs;\n this.models = models;\n }\n}\n\n/**\n * WHERE this branch's review materials live. Data-only.\n *\n * One class for BOTH passes — crediting (`verifyReviewers`) and evidence (`evidenceFor`) — because they\n * ask their questions of the same paths. `diffDir` is the per-branch materialization\n * (`.webpieces/pr-review/<featureSlug>/diff`), which is what makes it usable as PROOF of which branch a\n * reviewer looked at: the path names the branch, it is absolute, and stage ② recreates it per run.\n */\nexport class ReviewerContext {\n branch: string;\n diffDir: string; // '' when nothing was materialized\n docPaths: Record<string, string>; // checklist id → its checklist doc path ('' when none)\n /**\n * checklist id → the absolute path of the verdict file THAT checklist must write on THIS branch\n * (`.webpieces/pr-review/<featureSlug>/review-round<N>-<id>.json`). '' when unknown.\n *\n * The strongest attribution signal available, and stronger than `diffDir`: the path is\n * worktree-absolute (naming the tree), per-branch (naming the featureSlug) AND per-checklist (naming\n * the id), so a transcript containing it can only belong to a reviewer that authored that checklist's\n * verdict for that branch. `diffDir` proves the branch but not the checklist.\n */\n verdictPaths: Record<string, string>;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(branch: string, diffDir = '', docPaths: Record<string, string> = {}, verdictPaths: Record<string, string> = {}) {\n this.branch = branch;\n this.diffDir = diffDir;\n this.docPaths = docPaths;\n this.verdictPaths = verdictPaths;\n }\n}\n\n/**\n * One checklist that must be credited to a reviewer run, plus the agent type the BRIEFING named. Data-only.\n *\n * The two used to be one string — a checklist's id WAS its agent type — and provenance keyed everything by\n * it. Now every checklist is reviewed by the same repo-wide agent type, so the id and the type are\n * separate facts.\n *\n * `agentType` is NOT a provenance input: nothing here matches a run on it (issue #964, see\n * {@link SubagentProvenanceService.isReviewerRun}). It is carried because it is what the BRIEFING told\n * the agent to spawn and what {@link ReviewerEvidence} reports, which are both worth recording even\n * though neither is worth gating on.\n */\nexport class ExpectedReviewer {\n checklistId: string;\n agentType: string;\n\n constructor(checklistId: string, agentType: string) {\n this.checklistId = checklistId;\n this.agentType = agentType;\n }\n}\n\n/**\n * Verifies — from the Claude Code harness's OWN artifacts, never from anything the model asserts — that\n * a real SUBAGENT actually ran on the current branch and did this checklist's work. Used to enforce that\n * every checklist was reviewed by an INDEPENDENT reviewer, rather than by the coding agent\n * self-certifying.\n *\n * The harness writes, beside each subagent transcript:\n * <config>/projects/<cwd-slug>/<sessionId>/subagents/agent-<id>.meta.json → { agentType, spawnDepth, … }\n * <config>/projects/<cwd-slug>/<sessionId>/subagents/agent-<id>.jsonl → record 0 { isSidechain, gitBranch, … }\n * `spawnDepth`/`isSidechain` are written by Claude Code, not by the model, and they are what carries the\n * anti-self-certification property. `agentType` is written there too and is deliberately NOT checked —\n * see {@link SubagentProvenanceService.isReviewerRun}. `<config>` is `$CLAUDE_CONFIG_DIR` when set, else\n * `~/.claude`; see {@link ClaudeConfigDir}, and never re-derive it here. Dirs are found by walking\n * every session, so the cwd-slug never has to be derived/guessed.\n *\n * IMPORTANT — this is NOT tamper-proof. A determined agent can `cat >` a fake agent-*.meta.json. This\n * raises the bar from \"trust the model's word\" to \"deliberate, auditable forgery outside the repo\"; it\n * is not cryptographic. Say so wherever reviewer provenance is documented.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it is drawn in the DI design and injected by type.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class SubagentProvenanceService {\n // cwd → the branch it is PINNED to ('' when it is not a linked worktree, or is unresolvable).\n // See branchOfCwd for why it is cached and pinnedBranch for what \"pinned\" buys.\n private readonly branchByCwd = new Map<string, string>();\n\n // transcript path → its one scan. The credit pass and the evidence pass ask different questions of\n // the same (largest) files this service opens, and the credit pass may look at candidates the\n // evidence pass then re-visits. See scanTranscript for why one pass answers both.\n private readonly scanByPath = new Map<string, TranscriptScan>();\n\n // Verify EVERY expected checklist was reviewed by a reviewer subagent that ran on `context.branch` — the\n // coding agent may not self-certify. SKIPPED (pass) without a session id.\n //\n // ONE run may cover SEVERAL checklists: `reviewerAgents` is a required config field and is a CAP, so\n // grouping is always something the repo asked for. A run is still only credited when it is a real\n // subagent of the right type that ran on this branch.\n //\n // (A removed `sharedRuns` flag once demanded a distinct run per checklist; a cap is a MAXIMUM, so it never could.)\n // Either way a run that NAMED (or wp-write-review-submitted) this checklist's verdict is preferred over one that merely ran on the\n // branch, so each checklist is credited to the reviewer that actually wrote it whenever that is knowable.\n //\n // Scoped by BRANCH across ALL sessions (not the current session): once a reviewer ran on this branch in\n // any session, a later re-push in a NEW session still finds it, so the review is NOT forced to re-run.\n // That is what keeps \"review once per branch\" true across sessions. A PR opened outside the gated flow\n // still has no review-round<N>-<id>.json, so wp-finish forces the review regardless of provenance.\n verifyReviewers(expected: readonly ExpectedReviewer[], context: ReviewerContext): ProvenanceResult {\n if (expected.length === 0) return new ProvenanceResult(PROVENANCE_OK, 'no reviewer subagents required', {}, []);\n if (!this.inClaudeSession()) return this.skipped('reviewer subagents');\n const dirs = this.allSubagentsDirs();\n const missing: string[] = [];\n const usedAgentIds = new Set<string>();\n const credited: Record<string, string> = {};\n for (const want of expected) {\n const agentId = this.findMatchingAgentId(dirs, want, context, new Set<string>());\n if (agentId === '') missing.push(want.checklistId);\n else {\n usedAgentIds.add(agentId);\n credited[want.checklistId] = agentId;\n }\n }\n const runs = new Set(Object.values(credited)).size;\n return missing.length === 0\n ? new ProvenanceResult(PROVENANCE_OK,\n `verified ${expected.length} checklist(s) were reviewed by ${runs} reviewer subagent run(s)`, credited, [])\n : new ProvenanceResult(PROVENANCE_MISSING,\n `${missing.length} checklist(s) could not be attributed to a reviewer subagent on this branch: ${missing.join(', ')}`,\n credited, missing);\n }\n\n /**\n * What each credited reviewer actually READ, from its own transcript.\n *\n * `verifyReviewers` proves a reviewer of the right type RAN. It cannot tell a reviewer that read the diff\n * and thought about it from one that wrote a verdict having opened nothing. This closes that gap — and\n * the motivating case is real: one reviewer spent 14 of 26 tool calls grepping `node_modules` because\n * nothing had told it where anything was, which `offRepoSearches` now makes visible.\n *\n * WARNING-ONLY by default, for three reasons, and `requireDiffEvidence` must stay opt-in until at least\n * one repo has watched it:\n * 1. The transcript layout is undocumented Claude Code internals. A format change would wedge every\n * consumer's PR with no self-service recovery — `sidechainOnBranch` is already lenient for exactly\n * this reason, and blocking on a richer read of the same files would be less safe, not more.\n * 2. A reviewer can legitimately receive the diff another way (inlined into its prompt, say).\n * 3. verifyReviewers is the INTEGRITY signal and rightly blocks; this is a QUALITY signal. Conflating\n * them would let a transcript-parsing quirk refuse a PR that a real reviewer really did review.\n *\n * Returns [] outside a Claude Code session, matching verifyReviewers's SKIP behavior.\n */\n evidenceFor(context: ReviewerContext, expected: readonly ExpectedReviewer[], agentIds: Record<string, string>): ReviewerEvidence[] {\n if (!this.inClaudeSession()) return [];\n const dirs = this.allSubagentsDirs();\n const out: ReviewerEvidence[] = [];\n for (const want of expected) {\n const agentId = agentIds[want.checklistId];\n if (agentId === undefined) continue;\n const jsonl = this.transcriptPath(dirs, agentId);\n if (jsonl === '') {\n out.push(new ReviewerEvidence(want.checklistId, want.agentType, agentId));\n continue;\n }\n out.push(this.evidenceFromTranscript(want, agentId, jsonl, context));\n }\n return out;\n }\n\n // eslint-disable-next-line @typescript-eslint/max-params\n private evidenceFromTranscript(want: ExpectedReviewer, agentId: string, jsonl: string, context: ReviewerContext): ReviewerEvidence {\n const scan = this.scanTranscript(jsonl);\n const inputs = scan.inputs;\n const docPath = context.docPaths[want.checklistId] ?? '';\n const verdictPath = context.verdictPaths[want.checklistId] ?? '';\n return new ReviewerEvidence(\n want.checklistId, want.agentType, agentId, this.readDiffDir(scan, context),\n docPath !== '' && this.mentions(inputs, docPath),\n inputs.length,\n inputs.filter((i: string): boolean => i.includes('node_modules')).length,\n jsonl,\n scan.models,\n this.submittedVerdict(inputs, want.checklistId, verdictPath),\n );\n }\n\n // The instructions file counts as \"read the diff\": it lives in the same per-branch dir, it is what\n // the reviewer is told to open first, and it inlines the diff paths. A reviewer that opened it and\n // then its own diff files is the intended path; treating only the diff dir as proof would flag it.\n private readDiffDir(scan: TranscriptScan, context: ReviewerContext): boolean {\n return context.diffDir !== '' && this.mentions(scan.inputs, context.diffDir);\n }\n\n /**\n * Record this line's `message.model`, deduped, in first-seen order.\n *\n * `<synthetic>` records are SKIPPED. The harness writes them for messages no model produced (tool\n * results, injected notices); counting one would put a non-model in a field whose entire purpose is\n * \"which model reviewed this\", and it would show up on every single reviewer.\n */\n // webpieces-disable no-any-unknown -- opaque transcript record, only `model` is read and it is type-guarded below\n private collectModel(message: Record<string, unknown>, models: string[]): void {\n const model = message['model'];\n if (typeof model !== 'string' || model === '' || model === '<synthetic>') return;\n if (!models.includes(model)) models.push(model);\n }\n\n // The absolute path of agent-<id>.jsonl across all session dirs, or '' if it is not there.\n private transcriptPath(dirs: readonly string[], agentId: string): string {\n for (const dir of dirs) {\n const candidate = path.join(dir, `agent-${agentId}.jsonl`);\n if (fs.existsSync(candidate)) return candidate;\n }\n return '';\n }\n\n /**\n * ONE pass over the transcript for both answers (see {@link TranscriptScan}), CACHED per path.\n *\n * Cached because two passes now ask questions of the same file: crediting (does it name this branch's\n * verdict/diff?) and evidence (what did it read, which model served it?). Without the cache the credit\n * pass would re-read every candidate the evidence pass then re-opens — on the largest files this\n * service touches, on the path that opens a PR.\n *\n * Tool inputs are JSON-stringified rather than walked field-by-field because the shape differs per\n * tool (Read takes file_path, Bash takes command, Grep takes path) and a substring test over the\n * serialized input is both simpler and robust to a tool we have not seen.\n *\n * Best-effort, like everything else that parses this file: a format change must never wedge the\n * gate, so an unreadable transcript yields empty rather than throwing. That matters more for the\n * models than for the counters — this is quality telemetry, not an integrity check, and a missing\n * `model` field must not be able to block a PR.\n */\n private scanTranscript(jsonl: string): TranscriptScan {\n const cached = this.scanByPath.get(jsonl);\n if (cached !== undefined) return cached;\n const scan = this.readTranscript(jsonl);\n this.scanByPath.set(jsonl, scan);\n return scan;\n }\n\n private readTranscript(jsonl: string): TranscriptScan {\n const scan = new TranscriptScan();\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unreadable transcript yields no evidence, never a crash\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n for (const line of fs.readFileSync(jsonl, 'utf8').split('\\n')) {\n if (line.trim() === '') continue;\n const rec = this.parseLine(line);\n const message = rec?.['message'];\n if (typeof message !== 'object' || message === null) continue;\n // webpieces-disable no-any-unknown -- opaque transcript record, narrowed by the guard above\n const msg = message as Record<string, unknown>;\n this.collectModel(msg, scan.models);\n const content = msg['content'];\n if (!Array.isArray(content)) continue;\n for (const block of content) {\n // webpieces-disable no-any-unknown -- opaque content block, only `type`/`input` are read\n const b = block as Record<string, unknown>;\n if (b['type'] === 'tool_use') scan.inputs.push(JSON.stringify(b['input'] ?? {}));\n }\n }\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n return scan;\n }\n\n private mentions(inputs: readonly string[], needle: string): boolean {\n return inputs.some((i: string): boolean => i.includes(needle));\n }\n\n // Are we running under Claude Code at all? (CI / plain terminal → provenance is unverifiable → SKIP.)\n private inClaudeSession(): boolean {\n return (process.env['CLAUDE_CODE_SESSION_ID'] ?? '').trim() !== '';\n }\n\n private skipped(what: string): ProvenanceResult {\n return new ProvenanceResult(PROVENANCE_SKIPPED,\n `CLAUDE_CODE_SESSION_ID not set — no Claude transcripts to verify ${what} against (Codex / terminal / CI); each verdict's wp-write-review provenance is still enforced.`,\n {}, []);\n }\n\n // The agentId of a subagent run on `branch`, searched across ALL sessions' subagent dirs\n // (branch-scoped, so a run from a prior session still counts). '' if none. `exclude` skips agentIds\n // already credited to another checklist so one run can't satisfy two.\n //\n // The run is NOT matched on its agent type — see isReviewerRun for why that check was removed — so\n // several runs match and the one that NAMED this checklist's verdict file wins; the first\n // branch-matching run is the fallback, as before.\n // eslint-disable-next-line @typescript-eslint/max-params\n private findMatchingAgentId(dirs: readonly string[], want: ExpectedReviewer, context: ReviewerContext, exclude: ReadonlySet<string>): string {\n let fallback = '';\n for (const dir of dirs) {\n for (const metaFile of this.metaFiles(dir)) {\n const agentId = this.agentIdOf(metaFile);\n if (exclude.has(agentId) || !this.isReviewerRun(dir, metaFile)) continue;\n if (!this.sidechainOnBranch(dir, agentId, want.checklistId, context)) continue;\n if (this.namedVerdict(dir, agentId, want.checklistId, context)) return agentId;\n if (fallback === '') fallback = agentId;\n }\n }\n return fallback;\n }\n\n /**\n * A harness-written meta for a REAL SUBAGENT — `spawnDepth >= 1`, and nothing about its NAME.\n *\n * The agent TYPE used to be compared against the configured reviewer agent, and that check is\n * gone (issue #964). It proved nothing: `agentType` is a label on a prompt, and it does not show\n * the agent read the checklist, opened the diff, or looked at the right branch. The gates that DO\n * show those are untouched — `spawnDepth >= 1` plus `isSidechain === true` (see\n * {@link sidechainOnBranch}) are harness-written, so the main loop still cannot self-certify;\n * {@link creditedByWhatItTouched} proves the branch and the actual work; `requireDiffEvidence`\n * proves the diff was opened.\n *\n * It was also the ONLY gate with an unfixable failure mode. Claude Code snapshots agent\n * definitions per session and the refresh does not reach an already-running subagent, so a repo\n * that renames its reviewer agent mid-session leaves that subagent's registry offering only the\n * OLD names: the spawn is rejected, the agent falls back to `general-purpose`, does the real\n * review, writes every verdict — and is refused as unattributable, with no cwd, branch or respawn\n * able to change it. Measured: six checklists, six verdict files on disk, PR blocked.\n *\n * Accepted trade-off: without the name check the implementer's own subagent could in principle be\n * credited, since it touches the diff dir while running the gate. That is deliberate. The rule is\n * \"if the verdict file is there, a subagent wrote it\", and this gate's job is to catch \"no\n * subagent ran at all\" — not to adjudicate which subagent it was.\n */\n private isReviewerRun(dir: string, metaFile: string): boolean {\n const meta = this.readJson(path.join(dir, metaFile));\n if (!meta) return false;\n const spawnDepth = meta['spawnDepth'];\n return typeof spawnDepth === 'number' && spawnDepth >= 1;\n }\n\n // Did this run's transcript name the checklist's own verdict path?\n // eslint-disable-next-line @typescript-eslint/max-params\n private namedVerdict(dir: string, agentId: string, checklistId: string, context: ReviewerContext): boolean {\n const jsonl = path.join(dir, `agent-${agentId}.jsonl`);\n return fs.existsSync(jsonl) && this.submittedVerdict(this.scanTranscript(jsonl).inputs, checklistId, context.verdictPaths[checklistId] ?? '');\n }\n\n // Named its verdict file, or submitted it via wp-write-review (#863). Proves authorship, never branch.\n private submittedVerdict(inputs: readonly string[], checklistId: string, verdictPath: string): boolean {\n if (verdictPath !== '' && this.mentions(inputs, verdictPath)) return true;\n return inputs.some((i: string): boolean => reviewIdentityStamps.invokedChecklists(i).includes(checklistId));\n }\n\n /**\n * Every `<config>/projects/&#42;/<session>/subagents` dir that exists — matching by the recorded\n * gitBranch (not by session id) is what makes provenance survive across sessions.\n *\n * `<config>` comes from {@link ClaudeConfigDir.projectsRoots}, which is BOTH the configured\n * `$CLAUDE_CONFIG_DIR` tree and `~/.claude`. This used to be a hardcoded `~/.claude`, and on a\n * machine with a relocated config dir that found nothing at all — so every PR was refused with a\n * message about the reviewers' cwd, which is not what was wrong and which no agent could act on.\n */\n private allSubagentsDirs(): string[] {\n const out: string[] = [];\n for (const projects of claudeConfigDir.projectsRoots()) {\n for (const proj of this.readDir(projects)) {\n const projDir = path.join(projects, proj);\n for (const session of this.readDir(projDir)) {\n const candidate = path.join(projDir, session, 'subagents');\n if (fs.existsSync(candidate)) out.push(candidate);\n }\n }\n }\n return out;\n }\n\n private metaFiles(dir: string): string[] {\n return this.readDir(dir).filter((f: string): boolean => f.endsWith('.meta.json'));\n }\n\n // agent-<id>.meta.json → <id>\n private agentIdOf(metaFile: string): string {\n return metaFile.replace(/^agent-/, '').replace(/\\.meta\\.json$/, '');\n }\n\n /**\n * Cross-check the sibling transcript's record 0: isSidechain true (a real subagent, not the main\n * loop) and the same branch. Lenient on branch drift (a leftover …wpN suffix from a mid-flight\n * branch rename) and on a missing jsonl (meta already matched — accept, best-effort).\n *\n * WHEN `gitBranch` DISAGREES, A PINNED `cwd` DECIDES. Record 0 carries both fields, and the harness\n * can write a `gitBranch` that CONTRADICTS the record's own `cwd`: a reviewer subagent spawned into\n * a worktree on `dean/one-2406-…` was stamped `worktree-agent-a54887200e40eb956` — an unrelated,\n * still-live worktree's scaffold branch — deterministically, on four consecutive attempts, blocking\n * a PR whose required reviewer genuinely ran and genuinely passed. `stripWp` cannot bridge that, so\n * the reviewer was never credited and `wp-finish-upsert-pr` refused a legitimately-reviewed PR with\n * no in-flow recovery. A sweep of 961 record-0s on one machine found the mis-stamp is the MAJORITY\n * case among subagents in dedicated worktrees, so trusting `gitBranch` alone can never be correct.\n *\n * ─── Why ONLY a linked worktree, and never the primary clone ──────────────────────────────────\n * \"Ask git what branch the cwd is on\" is correct only when that cwd CANNOT have moved since the\n * reviewer ran. A LINKED WORKTREE is 1:1 with the agent that owns it and nothing re-checks it out;\n * the PRIMARY CLONE gets checked out constantly. Falling back on a primary-clone cwd would credit a\n * STALE reviewer, and by construction rather than by accident:\n *\n * 1. a reviewer runs in the primary clone while it is on branch A\n * 2. the clone is later checked out to branch B\n * 3. `wp-finish-upsert-pr` runs on B — `gitBranch` (stamped A) mismatches\n * 4. `git -C <clone>` now answers B, because the CLONE moved → the reviewer is credited for B\n *\n * It reviewed A. Every past reviewer run in that clone would be credited for whatever branch is\n * checked out at finish time — which in a repo with a required reviewer on every PR is not an\n * exotic sequence, it is the normal one. So the fallback is gated on `dotWebpieces.isLinkedWorktree`\n * (git's own `--git-dir != --git-common-dir` test, reused rather than re-derived), and a primary\n * clone falls through to a refusal exactly as it does today.\n *\n * That gate keeps the anti-forgery property intact: `cwd` is harness-written in the same record by\n * the same writer as `gitBranch`, so it carries the same weight — and inside a pinned worktree it is\n * the field that is CORRECT. There is deliberately no config flag and no second comparison mode:\n * ONE rule, with `gitBranch` only ever a cheap way to skip the subprocess when it already agrees.\n *\n * An UNRESOLVABLE cwd does not credit either. A reaped worktree, a deleted directory, a non-repo\n * path or a detached HEAD yields '' and falls through to a refusal. Leniency here is bounded by\n * \"git can still prove it\", never by \"we could not check, so assume yes\".\n *\n * ─── Why neither field can settle it from a PRIMARY CLONE, and what does ──────────────────────\n * Both fields above are stamped from the SPAWNING session's cwd — the Agent tool has no cwd\n * parameter, so a subagent inherits its parent's. A session rooted in the primary clone that spawns\n * a reviewer for a WORKTREE branch therefore produces `gitBranch` = the clone's branch (mismatch)\n * and `cwd` = the clone (gated off, correctly) — and NO respawn can change either stamp. That is not\n * an exotic setup: it is what the flow instructs the moment a worker agent dies mid-flow and the\n * top-level session has to take over, and it deadlocked a branch whose seven reviewers had all run.\n *\n * So the third channel is not a loosening of the cwd rule — it is a DIFFERENT question, asked of\n * evidence the reviewer cannot inherit and cannot fake by accident: {@link creditedByWhatItTouched}.\n */\n // eslint-disable-next-line @typescript-eslint/max-params\n private sidechainOnBranch(dir: string, agentId: string, checklistId: string, context: ReviewerContext): boolean {\n const jsonl = path.join(dir, `agent-${agentId}.jsonl`);\n if (!fs.existsSync(jsonl)) return true;\n const first = this.firstNonEmptyLine(jsonl);\n if (first === '') return true;\n const rec = this.parseLine(first);\n if (!rec) return true;\n if (rec['isSidechain'] !== true) return false;\n const gitBranch = rec['gitBranch'];\n // Not recorded at all → accept, as before: nothing to contradict and nothing to verify against.\n if (typeof gitBranch !== 'string' || gitBranch === '') return true;\n const want = this.stripWp(context.branch);\n if (this.stripWp(gitBranch) === want) return true;\n if (want !== '' && this.stripWp(this.branchOfCwd(rec['cwd'])) === want) return true;\n return this.creditedByWhatItTouched(jsonl, checklistId, context);\n }\n\n /**\n * Credit a reviewer for WHAT IT TOUCHED when neither harness-stamped field can settle it.\n *\n * Both paths compared here are ABSOLUTE and BRANCH-SPECIFIC — they live under\n * `<worktree>/.webpieces/pr-review/<featureSlug>/`, so the string names the tree AND the branch. A\n * reviewer that worked on a different branch cannot have them in its transcript, and a reviewer of\n * this branch that ran from a mis-stamped cwd cannot avoid having them. That is the property\n * `gitBranch` lacks — this file's own sweep of 961 record-0s found the mis-stamp is the MAJORITY\n * case among subagents in dedicated worktrees.\n *\n * Two channels, either sufficient:\n * 1. it WROTE this checklist's verdict file — proves branch AND checklist, and is the act the whole\n * gate is trying to attribute. Matched as a substring of any tool input, so a Write, an Edit and\n * a `cat > <path>` heredoc all count; the point is that the path was named, not which tool named it.\n * 2. it READ this branch's materialized diff dir — proves the branch. Kept as a second channel\n * because a reviewer whose verdict was relayed by its parent still demonstrably reviewed this\n * branch, and refusing that would re-open a narrower version of the same unrecoverable deadlock.\n *\n * Independence is NOT weakened by either: `isSidechain === true` and `spawnDepth >= 1` are checked\n * before we get here (so the main loop's own transcript can never qualify), and `verifyReviewers`\n * excludes an agentId already credited to another checklist. It remains non-tamper-proof in exactly\n * the way the class doc already states — forging this now means forging a transcript rather than a\n * meta.json, which is the same bar, not a lower one.\n */\n private creditedByWhatItTouched(jsonl: string, checklistId: string, context: ReviewerContext): boolean {\n const scan = this.scanTranscript(jsonl);\n const verdictPath = context.verdictPaths[checklistId] ?? '';\n if (verdictPath !== '' && this.mentions(scan.inputs, verdictPath)) return true;\n return this.readDiffDir(scan, context);\n }\n\n /**\n * The branch record-0's own `cwd` is PINNED to, '' when that cannot be established or is not pinned.\n *\n * Cached per cwd because `findMatchingAgentId` walks every subagent of every session on the machine\n * and several of them share a worktree — one `git` process per RECORD would put dozens of spawns on\n * the path that opens a PR.\n */\n // webpieces-disable no-any-unknown -- one opaque record field, type-guarded on the next line\n private branchOfCwd(cwd: unknown): string {\n if (typeof cwd !== 'string' || cwd === '') return '';\n const cached = this.branchByCwd.get(cwd);\n if (cached !== undefined) return cached;\n const resolved = this.pinnedBranch(cwd);\n this.branchByCwd.set(cwd, resolved);\n return resolved;\n }\n\n /**\n * The branch of `cwd` when — and only when — `cwd` is a LINKED WORKTREE. '' otherwise.\n *\n * '' for the primary clone (it moves; see sidechainOnBranch for the false-accept that closes), for a\n * reaped or deleted directory, for a non-repo path, when git is unavailable, and for a detached HEAD,\n * which `--abbrev-ref` prints as the literal `HEAD` and which names no branch.\n */\n private pinnedBranch(cwd: string): string {\n if (!fs.existsSync(cwd)) return '';\n if (!dotWebpieces.isLinkedWorktree(cwd)) return '';\n const result = spawnSync('git', ['-C', cwd, 'rev-parse', '--abbrev-ref', 'HEAD'], { encoding: 'utf8' });\n if (result.status !== 0) return '';\n const printed = (result.stdout ?? '').trim();\n return printed === 'HEAD' ? '' : printed;\n }\n\n private stripWp(branch: string): string {\n return branch.replace(/-?wp\\d+$/i, '');\n }\n\n private readDir(dir: string): string[] {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unreadable dir yields [] (best-effort provenance)\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return fs.readdirSync(dir);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return [];\n }\n }\n\n private firstNonEmptyLine(filePath: string): string {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: unreadable transcript → '' (best-effort)\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n for (const line of fs.readFileSync(filePath, 'utf8').split('\\n')) {\n if (line.trim() !== '') return line;\n }\n return '';\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return '';\n }\n }\n\n // webpieces-disable no-any-unknown -- opaque parsed JSON object, keys read by the caller\n private readJson(filePath: string): Record<string, unknown> | null {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: malformed meta.json → null (skipped)\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // webpieces-disable no-any-unknown -- parsed JSON is opaque until narrowed by the caller\n return JSON.parse(fs.readFileSync(filePath, 'utf8')) as Record<string, unknown>;\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n\n // webpieces-disable no-any-unknown -- one opaque JSONL record, keys read by the caller\n private parseLine(line: string): Record<string, unknown> | null {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: malformed JSONL record → null\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // webpieces-disable no-any-unknown -- parsed JSON is opaque until narrowed by the caller\n return JSON.parse(line) as Record<string, unknown>;\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n}\n"]}
@@ -7,7 +7,7 @@ const os = tslib_1.__importStar(require("os"));
7
7
  const path = tslib_1.__importStar(require("path"));
8
8
  const inversify_1 = require("inversify");
9
9
  const aged_tree_sweep_1 = require("./aged-tree-sweep");
10
- const to_error_1 = require("./to-error");
10
+ const to_error_1 = require("@webpieces/tooling-common/to-error");
11
11
  // ---------------------------------------------------------------------------
12
12
  // THE BACKSTOP FOR SCRATCH TREES NO EXIT HANDLER GOT TO REAP.
13
13
  //
@@ -1 +1 @@
1
- {"version":3,"file":"tmp-scratch-sweep.js","sourceRoot":"","s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,CAAC;gBAChB,QAAQ,CAAC,IAAI,CAAC,CAAC;YACnB,CAAC;YAAC,OAAO,GAAY,EAAE,CAAC;gBACpB,wFAAwF;gBACxF,6FAA6F;gBAC7F,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;gBAC3B,IAAI,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC;oBAAE,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,8BAA8B,IAAI,KAAK,KAAK,CAAC,OAAO,IAAI,CAAC,CAAC;YAC5G,CAAC;QACL,CAAC;QACD,OAAO,KAAK,CAAC;IACjB,CAAC;IAED,gGAAgG;IACxF,UAAU,CAAC,IAAY;QAC3B,mGAAmG;QACnG,yDAAyD;QACzD,8DAA8D;QAC9D,IAAI,CAAC;YACD,OAAO,EAAE,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,IAAY,EAAW,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,0BAAkB,CAAC,CAAC,CAAC;QACvG,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,8FAA8F;YAC9F,6CAA6C;YAC7C,6BAA6B;YAC7B,OAAO,EAAE,CAAC;QACd,CAAC;IACL,CAAC;CACJ,CAAA;AAjDY,8CAAiB;4BAAjB,iBAAiB;IAD7B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;GAC5B,iBAAiB,CAiD7B","sourcesContent":["import * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { SweepCount } from './aged-tree-sweep';\nimport { toError } from './to-error';\n\n// ---------------------------------------------------------------------------\n// THE BACKSTOP FOR SCRATCH TREES NO EXIT HANDLER GOT TO REAP.\n//\n// `SpecTempDirs` and `vitest.setup.mts` both reap on `process.on('exit')`, which covers every ordinary\n// end of a run — pass, fail, thrown error, Ctrl-C. It does not cover a worker killed with SIGKILL, a\n// box that loses power, or a vitest pool torn down harder than the handler can survive. Those leak\n// exactly as before, at a much lower rate, and with nothing else on the machine owning the residue.\n//\n// So this exists, and it is deliberately NOT `AgedTreeSweeper` pointed at `os.tmpdir()`. That sweeper\n// deletes every file under a root older than the cutoff, which is correct for a directory webpieces\n// OWNS and catastrophic for one it SHARES with the operating system and every other program on the box.\n// This one removes whole subtrees and only ones whose NAME webpieces minted, so the blast radius is\n// stated in the predicate rather than trusted to the caller's choice of root.\n// ---------------------------------------------------------------------------\n\n/**\n * How long a `$TMPDIR` scratch tree survives before the backstop reaps it.\n *\n * Much shorter than `RETENTION_DAYS` (30) because the two are protecting different things: that one\n * guards logs and state somebody may still want to read, while a scratch tree here is dead the moment\n * its process ended. Three days is long enough that a suite running while a sweep happens cannot lose\n * its own fixture, and it matches the interval macOS's own temp cleaner is documented to use.\n */\nexport const TMP_SCRATCH_RETENTION_DAYS = 3;\n\n/** The one name prefix webpieces mints under `os.tmpdir()`. Nothing outside it is ever a candidate. */\nexport const TMP_SCRATCH_PREFIX = 'wp-';\n\n/**\n * Removes aged `wp-*` scratch trees from the shared user temp directory.\n *\n * Read `TMP_SCRATCH_PREFIX`'s comment before widening anything here: this walks a directory owned by\n * the OS and shared with every program the developer runs.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class TmpScratchSweeper {\n /**\n * Delete every direct child of `os.tmpdir()` whose name starts with `wp-` and whose mtime is older\n * than `cutoffMs`.\n *\n * Only DIRECT children, and only whole subtrees: it never descends looking for individual old files,\n * because a half-emptied fixture is worse than an intact stale one. Counts removals as `dirs`.\n *\n * Never throws. It runs at the tail of a merge/PR flow that has already succeeded, and a temp\n * directory that will not delete — held open, owned by another user — must not fail that flow.\n */\n sweep(cutoffMs: number, onDelete: (removed: string) => void = (): void => {}): SweepCount {\n const root = os.tmpdir();\n const count = new SweepCount();\n const now = Date.now();\n for (const name of this.candidates(root)) {\n const full = path.join(root, name);\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: this sweeps a directory shared with\n // the OS at the tail of an already-successful flow; one unremovable entry must not fail it\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n if (now - fs.statSync(full).mtimeMs < cutoffMs) continue;\n fs.rmSync(full, { recursive: true, force: true });\n count.dirs += 1;\n onDelete(full);\n } catch (err: unknown) {\n // A vanished entry is the common case — a concurrent run reaped its own fixture between\n // the listing and the stat — and is not worth a word. Anything else is reported and skipped.\n const error = toError(err);\n if (fs.existsSync(full)) process.stderr.write(`TmpScratchSweeper: skipped ${full}: ${error.message}\\n`);\n }\n }\n return count;\n }\n\n // An unreadable temp dir is a no-op, not an error: the backstop is best-effort by construction.\n private candidates(root: string): string[] {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unreadable temp dir is a no-op for a\n // best-effort backstop, never an error worth propagating\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return fs.readdirSync(root).filter((name: string): boolean => name.startsWith(TMP_SCRATCH_PREFIX));\n } catch (err: unknown) {\n // webpieces-disable catch-error-pattern -- the error is deliberately unused: \"cannot read it\"\n // and \"it is empty\" are the same answer here\n //const error = toError(err);\n return [];\n }\n }\n}\n"]}
1
+ {"version":3,"file":"tmp-scratch-sweep.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/tmp-scratch-sweep.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAC3D,uDAA+C;AAC/C,iEAA6D;AAE7D,8EAA8E;AAC9E,8DAA8D;AAC9D,EAAE;AACF,uGAAuG;AACvG,qGAAqG;AACrG,mGAAmG;AACnG,oGAAoG;AACpG,EAAE;AACF,sGAAsG;AACtG,oGAAoG;AACpG,wGAAwG;AACxG,oGAAoG;AACpG,8EAA8E;AAC9E,8EAA8E;AAE9E;;;;;;;GAOG;AACU,QAAA,0BAA0B,GAAG,CAAC,CAAC;AAE5C,uGAAuG;AAC1F,QAAA,kBAAkB,GAAG,KAAK,CAAC;AAExC;;;;;GAKG;AA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AI,CAAC;YACD,OAAO,EAAE,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,IAAY,EAAW,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,0BAAkB,CAAC,CAAC,CAAC;QACvG,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,8FAA8F;YAC9F,6CAA6C;YAC7C,6BAA6B;YAC7B,OAAO,EAAE,CAAC;QACd,CAAC;IACL,CAAC;CACJ,CAAA;AAjDY,8CAAiB;4BAAjB,iBAAiB;IAD7B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;GAC5B,iBAAiB,CAiD7B","sourcesContent":["import * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { SweepCount } from './aged-tree-sweep';\nimport { toError } from '@webpieces/tooling-common/to-error';\n\n// ---------------------------------------------------------------------------\n// THE BACKSTOP FOR SCRATCH TREES NO EXIT HANDLER GOT TO REAP.\n//\n// `SpecTempDirs` and `vitest.setup.mts` both reap on `process.on('exit')`, which covers every ordinary\n// end of a run — pass, fail, thrown error, Ctrl-C. It does not cover a worker killed with SIGKILL, a\n// box that loses power, or a vitest pool torn down harder than the handler can survive. Those leak\n// exactly as before, at a much lower rate, and with nothing else on the machine owning the residue.\n//\n// So this exists, and it is deliberately NOT `AgedTreeSweeper` pointed at `os.tmpdir()`. That sweeper\n// deletes every file under a root older than the cutoff, which is correct for a directory webpieces\n// OWNS and catastrophic for one it SHARES with the operating system and every other program on the box.\n// This one removes whole subtrees and only ones whose NAME webpieces minted, so the blast radius is\n// stated in the predicate rather than trusted to the caller's choice of root.\n// ---------------------------------------------------------------------------\n\n/**\n * How long a `$TMPDIR` scratch tree survives before the backstop reaps it.\n *\n * Much shorter than `RETENTION_DAYS` (30) because the two are protecting different things: that one\n * guards logs and state somebody may still want to read, while a scratch tree here is dead the moment\n * its process ended. Three days is long enough that a suite running while a sweep happens cannot lose\n * its own fixture, and it matches the interval macOS's own temp cleaner is documented to use.\n */\nexport const TMP_SCRATCH_RETENTION_DAYS = 3;\n\n/** The one name prefix webpieces mints under `os.tmpdir()`. Nothing outside it is ever a candidate. */\nexport const TMP_SCRATCH_PREFIX = 'wp-';\n\n/**\n * Removes aged `wp-*` scratch trees from the shared user temp directory.\n *\n * Read `TMP_SCRATCH_PREFIX`'s comment before widening anything here: this walks a directory owned by\n * the OS and shared with every program the developer runs.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class TmpScratchSweeper {\n /**\n * Delete every direct child of `os.tmpdir()` whose name starts with `wp-` and whose mtime is older\n * than `cutoffMs`.\n *\n * Only DIRECT children, and only whole subtrees: it never descends looking for individual old files,\n * because a half-emptied fixture is worse than an intact stale one. Counts removals as `dirs`.\n *\n * Never throws. It runs at the tail of a merge/PR flow that has already succeeded, and a temp\n * directory that will not delete — held open, owned by another user — must not fail that flow.\n */\n sweep(cutoffMs: number, onDelete: (removed: string) => void = (): void => {}): SweepCount {\n const root = os.tmpdir();\n const count = new SweepCount();\n const now = Date.now();\n for (const name of this.candidates(root)) {\n const full = path.join(root, name);\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: this sweeps a directory shared with\n // the OS at the tail of an already-successful flow; one unremovable entry must not fail it\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n if (now - fs.statSync(full).mtimeMs < cutoffMs) continue;\n fs.rmSync(full, { recursive: true, force: true });\n count.dirs += 1;\n onDelete(full);\n } catch (err: unknown) {\n // A vanished entry is the common case — a concurrent run reaped its own fixture between\n // the listing and the stat — and is not worth a word. Anything else is reported and skipped.\n const error = toError(err);\n if (fs.existsSync(full)) process.stderr.write(`TmpScratchSweeper: skipped ${full}: ${error.message}\\n`);\n }\n }\n return count;\n }\n\n // An unreadable temp dir is a no-op, not an error: the backstop is best-effort by construction.\n private candidates(root: string): string[] {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unreadable temp dir is a no-op for a\n // best-effort backstop, never an error worth propagating\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return fs.readdirSync(root).filter((name: string): boolean => name.startsWith(TMP_SCRATCH_PREFIX));\n } catch (err: unknown) {\n // webpieces-disable catch-error-pattern -- the error is deliberately unused: \"cannot read it\"\n // and \"it is empty\" are the same answer here\n //const error = toError(err);\n return [];\n }\n }\n}\n"]}
@@ -25,7 +25,7 @@ Object.defineProperty(exports, "recommendedSeedMode", { enumerable: true, get: f
25
25
  Object.defineProperty(exports, "recommendedSeedModeFor", { enumerable: true, get: function () { return seed_entry_2.recommendedSeedModeFor; } });
26
26
  Object.defineProperty(exports, "seedEntryForRule", { enumerable: true, get: function () { return seed_entry_2.seedEntryForRule; } });
27
27
  const match_rules_config_1 = require("./match-rules-config");
28
- const to_error_1 = require("./to-error");
28
+ const to_error_1 = require("@webpieces/tooling-common/to-error");
29
29
  /**
30
30
  * The longest a `turnOffRuleUntilEpoch` may reach into the future: ONE WEEK. Poke it again next week to
31
31
  * extend — that weekly re-set IS the intended workflow, not a workaround: it is what makes a rule that is