@webpieces/rules-config 0.4.836 → 0.4.838

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webpieces/rules-config",
3
- "version": "0.4.836",
3
+ "version": "0.4.838",
4
4
  "description": "Shared webpieces.config.json loader. Single source of truth for validation rule configuration consumed by @webpieces/ai-hook-rules, @webpieces/code-rules, and @webpieces/nx-webpieces-rules.",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -17,7 +17,9 @@
17
17
  "@inversifyjs/binding-decorators": "1.1.5",
18
18
  "inversify": "7.10.4",
19
19
  "reflect-metadata": "0.2.2",
20
- "minimatch": "10.0.1"
20
+ "minimatch": "10.0.1",
21
+ "@webpieces/tooling-common": "0.4.838",
22
+ "@webpieces/repo-workflow-core": "0.4.838"
21
23
  },
22
24
  "author": "Dean Hiller",
23
25
  "license": "Apache-2.0",
@@ -1,4 +1,4 @@
1
- import { DotWebpieces } from './state-dir';
1
+ import { DotWebpieces } from '@webpieces/tooling-common';
2
2
  /**
3
3
  * `~/.webpieces/builds.log` — the MACHINE-WIDE, append-only ledger of every build this box has started.
4
4
  *
package/src/builds-log.js CHANGED
@@ -8,9 +8,9 @@ const fs = tslib_1.__importStar(require("fs"));
8
8
  const os = tslib_1.__importStar(require("os"));
9
9
  const path = tslib_1.__importStar(require("path"));
10
10
  const inversify_1 = require("inversify");
11
- const state_dir_1 = require("./state-dir");
11
+ const tooling_common_1 = require("@webpieces/tooling-common");
12
12
  const home_config_1 = require("./home-config");
13
- const to_error_1 = require("./to-error");
13
+ const to_error_1 = require("@webpieces/tooling-common/to-error");
14
14
  /**
15
15
  * `~/.webpieces/builds.log` — the MACHINE-WIDE, append-only ledger of every build this box has started.
16
16
  *
@@ -526,6 +526,6 @@ let BuildsLog = class BuildsLog {
526
526
  exports.BuildsLog = BuildsLog;
527
527
  exports.BuildsLog = BuildsLog = tslib_1.__decorate([
528
528
  (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
529
- tslib_1.__metadata("design:paramtypes", [state_dir_1.DotWebpieces])
529
+ tslib_1.__metadata("design:paramtypes", [tooling_common_1.DotWebpieces])
530
530
  ], BuildsLog);
531
531
  //# sourceMappingURL=builds-log.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"builds-log.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/builds-log.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,uDAAiC;AACjC,+CAAyB;AACzB,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAE3D,2CAA2C;AAC3C,+CAAgD;AAChD,yCAAqC;AAErC;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACU,QAAA,eAAe,GAAG,YAAY,CAAC;AAC/B,QAAA,gBAAgB,GAAG,iBAAiB,CAAC;AAElD,kGAAkG;AACrF,QAAA,WAAW,GAAG,OAAO,CAAC;AACtB,QAAA,kBAAkB,GAAG,cAAc,CAAC;AACpC,QAAA,eAAe,GAAG,WAAW,CAAC;AAE3C,uFAAuF;AAC1E,QAAA,oBAAoB,GAAG,IAAI,GAAG,IAAI,CAAC;AACnC,QAAA,sBAAsB,GAAG,CAAC,CAAC;AAExC;;;;GAIG;AACU,QAAA,aAAa,GAAG,GAAG,CAAC;AAEjC,iGAAiG;AACjG,MAAM,aAAa,GAAG,EAAE,CAAC;AACzB,MAAM,eAAe,GAAG,IAAI,CAAC;AAE7B;;;;GAIG;AACH,MAAa,WAAW;IACpB,EAAE,CAAS;IACX,EAAE,CAAS;IACX,IAAI,CAAS;IACb,SAAS,CAAS;IAElB,YAAY,EAAU,EAAE,EAAU,EAAE,IAAY,EAAE,SAAiB;QAC/D,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;QACb,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;QACb,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC/B,CAAC;CACJ;AAZD,kCAYC;AAED;;;;GAIG;AACH,MAAa,gBAAgB;IACzB,IAAI,CAAgB;IACpB,MAAM,CAAgB;IAEtB,YAAY,IAAm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BAAT,SAAS;IADrB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEA,wBAAY;GADxC,SAAS,CA+YrB","sourcesContent":["import { spawnSync } from 'child_process';\nimport * as crypto from 'crypto';\nimport * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { DotWebpieces } from './state-dir';\nimport { HOME_CONFIG_DIR } from './home-config';\nimport { toError } from './to-error';\n\n/**\n * `~/.webpieces/builds.log` — the MACHINE-WIDE, append-only ledger of every build this box has started.\n *\n * ─── WHY THIS ONE FILE LIVES OUTSIDE THE REPO ─────────────────────────────────────────────────────────\n * `no-machine-global-state.spec.ts` records the standing rule: webpieces writes state under\n * `{repo}/.webpieces` and nowhere else. This is the ONE carve-out, and the argument is written out in\n * `decisions/0006-the-build-ledger-is-machine-global.md`. In short:\n *\n * • The FACT is machine-scoped. \"How many builds are burning this box's CPU right now\" is not a\n * property of any repo; it is a property of the machine. A per-repo ledger cannot answer it — every\n * linked worktree has its OWN `.webpieces/`, so it would be blind to the sibling worktree it is\n * actually contending with, never mind the four other repos on the disk.\n * • It is NOT A CACHE. The retired `PrBodyStore` that the no-machine-global rule was written for was a\n * local copy of a fact GitHub owned, so it could be stale, missing, or on the wrong computer. There\n * is no remote copy of this. The file IS the fact.\n * • Its key is an ABSOLUTE LOCAL PATH, which is stable precisely because it never leaves the machine —\n * the instability that killed `PrBodyStore`'s `<host>/<owner>/<repo>` key cannot arise here.\n *\n * ─── WHY IT IS SAFE TO WRITE CONCURRENTLY ─────────────────────────────────────────────────────────────\n * Rows are deliberately kept under `MAX_ROW_BYTES` (512, macOS `PIPE_BUF`). A single `O_APPEND`\n * `write(2)` at or below that size is indivisible, so two builds appending at the same instant cannot\n * interleave halves of a line. The lock is therefore belt-and-braces for the APPEND and genuinely\n * load-bearing for ROTATION, where a rename-and-reopen really does race.\n *\n * ─── IT MAY NEVER FAIL A BUILD ────────────────────────────────────────────────────────────────────────\n * Every method here is best-effort and swallows its own errors. A build must never die because a log\n * file was busy, unwritable, or on a full disk. Lock acquisition retries and then gives up and appends\n * anyway — which the row-size invariant above makes safe.\n */\nexport const BUILDS_LOG_FILE = 'builds.log';\nexport const BUILDS_LOCK_FILE = 'builds.log.lock';\n\n/** START, and the two terminal kinds. `DONE-` is the greppable prefix that pairs with a START. */\nexport const BUILD_START = 'START';\nexport const BUILD_DONE_SUCCESS = 'DONE-SUCCESS';\nexport const BUILD_DONE_FAIL = 'DONE-FAIL';\n\n/** Rotate at 1 MB, keeping five generations (`.1` … `.5`); the old `.5` is dropped. */\nexport const MAX_BUILDS_LOG_BYTES = 1024 * 1024;\nexport const BUILDS_LOG_GENERATIONS = 5;\n\n/**\n * macOS `PIPE_BUF`. A row at or under this size is written by ONE indivisible `write(2)`, which is what\n * makes a lost lock a non-event rather than a corrupted file. Long paths are clipped to hold the line\n * under it — see `clip`.\n */\nexport const MAX_ROW_BYTES = 512;\n\n/** How long a build may hold the lock before another writer stops waiting and appends anyway. */\nconst LOCK_RETRY_MS = 50;\nconst LOCK_TIMEOUT_MS = 2000;\n\n/**\n * The handle a START row hands back, and the ONLY thing `finish()` accepts. Data-only (a class, per\n * CLAUDE.md), carrying exactly the fields the DONE row needs to pair itself with its START: the uuid,\n * the caller, the repo, and when it began (so `took=` is computed from one clock, not two).\n */\nexport class BuildTicket {\n id: string;\n by: string;\n repo: string;\n startedMs: number;\n\n constructor(id: string, by: string, repo: string, startedMs: number) {\n this.id = id;\n this.by = by;\n this.repo = repo;\n this.startedMs = startedMs;\n }\n}\n\n/**\n * How the build process ended. Node reports a null code when a signal ended the process, so collapsing\n * this to a number would discard the only useful explanation for an otherwise silent build failure.\n * Data-only: the PR gate decides which CLI exit code to return, while the ledger records these raw facts.\n */\nexport class BuildTermination {\n code: number | null;\n signal: string | null;\n\n constructor(code: number | null, signal: string | null) {\n this.code = code;\n this.signal = signal;\n }\n}\n\n/**\n * One build that is STILL RUNNING — a START row with no matching `DONE-`, whose pid is still alive.\n * Data-only. This is what the refusal message renders, so it carries the three things a reader needs to\n * recognise the build in question: where it is, which tree, and how old it is.\n */\nexport class RunningBuild {\n id: string;\n by: string;\n repo: string;\n tree: string;\n cwd: string;\n branch: string;\n pid: number;\n startedMs: number;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n id: string, by: string, repo: string, tree: string,\n cwd: string, branch: string, pid: number, startedMs: number,\n ) {\n this.id = id;\n this.by = by;\n this.repo = repo;\n this.tree = tree;\n this.cwd = cwd;\n this.branch = branch;\n this.pid = pid;\n this.startedMs = startedMs;\n }\n}\n\n/**\n * The ledger. See the file docblock for why it is machine-global and why every operation swallows its\n * own errors.\n *\n * `homeDir` is a parameter on every public method, defaulted to `os.homedir()`, for exactly the reason\n * `HomeConfigService.configPath` takes one: a spec must be able to exercise the real code against a temp\n * directory and must never touch the developer's actual `~/.webpieces`.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class BuildsLog {\n constructor(private readonly dotDir: DotWebpieces) {}\n\n /** `~/.webpieces/builds.log`. */\n logPath(homeDir: string = os.homedir()): string {\n return path.join(homeDir, HOME_CONFIG_DIR, BUILDS_LOG_FILE);\n }\n\n /** `~/.webpieces/builds.log.lock` — `{\"pid\":N,\"started\":<epochMs>}`. */\n lockPath(homeDir: string = os.homedir()): string {\n return path.join(homeDir, HOME_CONFIG_DIR, BUILDS_LOCK_FILE);\n }\n\n /** `~/.webpieces/builds.log.<n>` — generation `n`, 1 being the most recent. */\n rotatedPath(generation: number, homeDir: string = os.homedir()): string {\n return `${this.logPath(homeDir)}.${String(generation)}`;\n }\n\n /**\n * Record that a build is starting, and hand back the ticket its DONE row will need.\n *\n * `by` is the CALLER — `BuildGateOptions.stage`, i.e. `build` | `review` | `finish`. There is no\n * second \"caller\" concept anywhere: the stage id already is one, and a second spelling of it would\n * be the shim `.claude/rules/no-backwards-compat.md` rejects.\n *\n * Returns a ticket even when the append failed. A build whose START row never landed still has to be\n * able to call `finish()`; the alternative is a nullable return that every call site must branch on\n * for a logging failure that is, by policy, not an error.\n */\n start(by: string, startDir: string, homeDir: string = os.homedir()): BuildTicket {\n const ticket = new BuildTicket(\n crypto.randomUUID(), by, this.dotDir.primaryRoot(startDir), Date.now());\n this.append(this.startRow(ticket, startDir), homeDir);\n return ticket;\n }\n\n /**\n * Record that the build behind `ticket` has ended. Only code 0 with no signal writes `DONE-SUCCESS`;\n * anything else writes `DONE-FAIL` carrying the raw code and signal, so a killed build does not become\n * an unexplained generic exit 1 in the machine record.\n */\n finish(ticket: BuildTicket, termination: BuildTermination, homeDir: string = os.homedir()): void {\n this.append(this.doneRow(ticket, termination), homeDir);\n }\n\n /**\n * Every build that is still live: a `START` with no matching `DONE-` row, whose pid is still alive.\n *\n * The pid filter is not an optimisation, it is what keeps the ledger from wedging the machine. A\n * build killed with SIGKILL — an agent cancelled mid-run, a terminal closed — writes no DONE row, so\n * without the liveness test its START would count forever and the fourth build would be refused for\n * the rest of the machine's life. The uuid answers \"which build\"; the pid answers \"is it still real\".\n *\n * Only the CURRENT generation is read. A rotated-away START is by definition at least 1 MB of rows\n * old and is not a build anyone is contending with.\n */\n running(homeDir: string = os.homedir()): RunningBuild[] {\n const lines = this.readLines(this.logPath(homeDir));\n const done = new Set<string>();\n for (const line of lines) {\n if (line.startsWith(`${BUILD_DONE_SUCCESS}\\t`) || line.startsWith(`${BUILD_DONE_FAIL}\\t`)) {\n done.add(this.field(line, 'id'));\n }\n }\n const live: RunningBuild[] = [];\n for (const line of lines) {\n if (!line.startsWith(`${BUILD_START}\\t`)) continue;\n const build = this.toRunningBuild(line);\n if (build === null || done.has(build.id)) continue;\n if (!this.isAlive(build.pid)) continue;\n live.push(build);\n }\n return live;\n }\n\n /**\n * The `@webpieces` release ACTUALLY EXECUTING — found by walking UP from this module's own directory\n * to the nearest enclosing `node_modules/@webpieces/<pkg>/package.json`. `''` when this code is\n * running from source rather than from an installed package (which is the state in this repo's own\n * specs, and a perfectly ordinary answer).\n *\n * ─── WHY THIS IS NOT `WebpiecesVersions.readInstalled(root)` ──────────────────────────────────────\n * They answer DIFFERENT QUESTIONS and merging them would break the older one. `readInstalled` joins\n * `<root>/node_modules/@webpieces/...` at a FIXED tree root ON PURPOSE: its whole job is to detect\n * DRIFT between what a tree PINS and what some other tree pins, and a walk-up would silently resolve\n * a worktree with no install of its own to the primary clone's copy — hiding exactly the skew that\n * guard exists to catch. This question is the opposite one: \"whichever copy is running, name it\", and\n * for that the walk-up is the only correct answer. Do not fold them together.\n */\n executingVersion(): string {\n let dir = __dirname;\n for (let hops = 0; hops < 40; hops += 1) {\n const version = this.versionOfEnclosingPackage(dir);\n if (version !== '') return version;\n const parent = path.dirname(dir);\n if (parent === dir) return '';\n dir = parent;\n }\n return '';\n }\n\n // `<dir>` is `node_modules/@webpieces/<pkg>/...`? Then that package's version, else ''.\n private versionOfEnclosingPackage(dir: string): string {\n const parent = path.dirname(dir);\n const grandparent = path.dirname(parent);\n if (path.basename(parent) !== '@webpieces' || path.basename(grandparent) !== 'node_modules') return '';\n const text = this.readTextOrEmpty(path.join(dir, 'package.json'));\n const match = /\"version\"\\s*:\\s*\"([^\"]+)\"/.exec(text);\n return match === null ? '' : match[1];\n }\n\n // ─── ROW RENDERING ────────────────────────────────────────────────────────────────────────────────\n\n private startRow(ticket: BuildTicket, startDir: string): string {\n return [\n BUILD_START,\n `id=${ticket.id}`,\n `t=${new Date(ticket.startedMs).toISOString()}`,\n `ms=${String(ticket.startedMs)}`,\n `by=${ticket.by}`,\n `repo=${this.clip(ticket.repo)}`,\n `tree=${this.dotDir.worktreeName(startDir) || 'primary'}`,\n `cwd=${this.clip(startDir)}`,\n `branch=${this.gitBranch(startDir)}`,\n `pid=${String(process.pid)}`,\n `wp=${this.executingVersion()}`,\n ].join('\\t');\n }\n\n private doneRow(ticket: BuildTicket, termination: BuildTermination): string {\n const now = Date.now();\n const success = termination.code === 0 && termination.signal === null;\n const fields = [\n success ? BUILD_DONE_SUCCESS : BUILD_DONE_FAIL,\n `id=${ticket.id}`,\n `t=${new Date(now).toISOString()}`,\n `ms=${String(now)}`,\n `by=${ticket.by}`,\n `repo=${this.clip(ticket.repo)}`,\n `took=${String(now - ticket.startedMs)}`,\n ];\n if (!success) fields.push(`exit=${termination.code === null ? 'null' : String(termination.code)}`);\n if (termination.signal !== null) fields.push(`signal=${this.clip(termination.signal)}`);\n fields.push(`pid=${String(process.pid)}`);\n return fields.join('\\t');\n }\n\n /**\n * Hold a long path down to `max` characters by keeping its TAIL, which is the half that identifies\n * the tree; a clipped value is marked with a leading `…` so nobody mistakes it for a real path.\n *\n * This is what keeps a row under `MAX_ROW_BYTES` — see the file docblock. `append` re-checks the\n * assembled line as a backstop, because three clipped fields plus a long branch name can still add up.\n */\n private clip(value: string, max = 120): string {\n const oneLine = value.replace(/[\\t\\n\\r]/g, ' ');\n return oneLine.length <= max ? oneLine : `…${oneLine.slice(oneLine.length - max)}`;\n }\n\n // ─── ROW PARSING ──────────────────────────────────────────────────────────────────────────────────\n\n /** The value of `<name>=` on a TSV row, or '' when the row does not carry it. */\n private field(line: string, name: string): string {\n for (const part of line.split('\\t')) {\n if (part.startsWith(`${name}=`)) return part.slice(name.length + 1);\n }\n return '';\n }\n\n // A START row as a RunningBuild, or null when it is missing the two fields that make it usable.\n private toRunningBuild(line: string): RunningBuild | null {\n const id = this.field(line, 'id');\n const pid = Number.parseInt(this.field(line, 'pid'), 10);\n if (id === '' || !Number.isInteger(pid) || pid <= 0) return null;\n const startedMs = Number.parseInt(this.field(line, 'ms'), 10);\n return new RunningBuild(\n id, this.field(line, 'by'), this.field(line, 'repo'), this.field(line, 'tree'),\n this.field(line, 'cwd'), this.field(line, 'branch'), pid,\n Number.isInteger(startedMs) ? startedMs : 0,\n );\n }\n\n /**\n * Is `pid` still addressable? `process.kill(pid, 0)` sends no signal — it only asks the kernel. ESRCH\n * is the ONE answer that proves death; EPERM proves the opposite (it exists, it is somebody else's).\n * Pid reuse is an accepted imprecision here: being wrong in the \"still running\" direction costs\n * one extra refusal, being wrong the other way lets a fourth build start.\n *\n * WHY A PID IS MEANINGFUL HERE AND WAS NOT FOR AGENT WORKTREE LOCKS. Every row in this ledger is\n * written BY the process it names — one real OS process per build — so its pid identifies it.\n * A Claude Code subagent is not a process at all: every agent in a session records the SAME pid,\n * the session's, which is why that check was deleted rather than shared (see\n * harness-agent-activity.ts). Do not generalise this one back out to anything but a real process.\n */\n private isAlive(pid: number): boolean {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n process.kill(pid, 0);\n return true;\n } catch (err: unknown) {\n const error = toError(err);\n return (error as NodeJS.ErrnoException).code !== 'ESRCH';\n }\n }\n\n // ─── APPEND, LOCK, ROTATE ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Append one row, best-effort. Takes the lock so rotation cannot race, and appends ANYWAY when the\n * lock cannot be had within `LOCK_TIMEOUT_MS` — the row is under `PIPE_BUF`, so an unlocked\n * `O_APPEND` write is still indivisible, and a build must never die because a log file was busy.\n */\n private append(row: string, homeDir: string): void {\n const line = `${this.truncateToRowLimit(row)}\\n`;\n const held = this.tryAcquireLock(homeDir);\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n this.ensureDir(this.logPath(homeDir));\n if (held) this.rotateIfLarge(homeDir);\n fs.appendFileSync(this.logPath(homeDir), line);\n } catch (err: unknown) {\n const error = toError(err);\n void error; // logging may never fail a build — see the file docblock\n } finally {\n if (held) this.releaseLock(homeDir);\n }\n }\n\n // The backstop for the PIPE_BUF invariant, measured in BYTES rather than characters because a path\n // may hold multi-byte characters. Truncating a row loses fields off the end, which is strictly better\n // than a torn line that breaks every row after it.\n private truncateToRowLimit(row: string): string {\n const bytes = Buffer.from(row, 'utf8');\n // -1 for the newline `append` adds.\n if (bytes.length <= MAX_ROW_BYTES - 1) return row;\n return bytes.subarray(0, MAX_ROW_BYTES - 1).toString('utf8');\n }\n\n /**\n * Take the ledger lock, retrying every `LOCK_RETRY_MS` until `LOCK_TIMEOUT_MS`. False means \"carry on\n * without it\" — never an error, and never a reason to skip the append.\n *\n * The mechanism is `MainSyncStatusService.tryAcquireMainSyncLock`'s, proven and deliberately copied\n * rather than re-invented: an `wx` (O_CREAT|O_EXCL) create so exactly one of N racers wins, a payload\n * carrying pid + started so a dead holder is identifiable, stale reclaim gated on pid liveness, and a\n * re-read afterwards to confirm the entry on disk is OURS (a simultaneous reclaimer could have\n * unlinked ours and written its own between the two calls).\n */\n private tryAcquireLock(homeDir: string): boolean {\n const deadline = Date.now() + LOCK_TIMEOUT_MS;\n this.ensureDir(this.lockPath(homeDir));\n // Rendered rather than JSON.stringify'd off an anonymous object — two fields, both numbers, and\n // the file's whole contract is `{\"pid\":N,\"started\":M}`.\n const payload = `{\"pid\":${String(process.pid)},\"started\":${String(Date.now())}}\\n`;\n for (;;) {\n if (this.createExclusive(this.lockPath(homeDir), payload)) return true;\n if (!this.isHolderAlive(homeDir)) {\n this.unlinkQuietly(this.lockPath(homeDir));\n if (this.createExclusive(this.lockPath(homeDir), payload) && this.holderIsUs(homeDir)) return true;\n }\n if (Date.now() >= deadline) return false;\n this.sleep(LOCK_RETRY_MS);\n }\n }\n\n private releaseLock(homeDir: string): void {\n if (!this.holderIsUs(homeDir)) return;\n this.unlinkQuietly(this.lockPath(homeDir));\n }\n\n // O_CREAT|O_EXCL write: true when THIS call created the file, false when it already existed.\n private createExclusive(file: string, payload: string): boolean {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.writeFileSync(file, payload, { flag: 'wx' });\n return true;\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return false;\n }\n }\n\n // The pid recorded in the lock file, or 0 when there is no readable lock.\n private lockHolderPid(homeDir: string): number {\n const text = this.readTextOrEmpty(this.lockPath(homeDir));\n if (text === '') return 0;\n const match = /\"pid\"\\s*:\\s*(\\d+)/.exec(text);\n return match === null ? 0 : Number.parseInt(match[1], 10);\n }\n\n // An unreadable or pid-less lock file counts as DEAD: it is a corpse from a crashed writer, and\n // leaving it forever would mean every future append silently skips rotation.\n private isHolderAlive(homeDir: string): boolean {\n const pid = this.lockHolderPid(homeDir);\n return pid > 0 && this.isAlive(pid);\n }\n\n private holderIsUs(homeDir: string): boolean {\n return this.lockHolderPid(homeDir) === process.pid;\n }\n\n /**\n * `.4→.5, .3→.4, … .log→.1`, dropping the old `.5`. Runs INSIDE the lock, which is the one place the\n * lock is genuinely load-bearing: a rename-and-reopen really does race, and a writer that opened the\n * old inode mid-shift would append into a file nobody reads again.\n */\n private rotateIfLarge(homeDir: string): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n if (!fs.existsSync(this.logPath(homeDir))) return;\n if (fs.statSync(this.logPath(homeDir)).size < MAX_BUILDS_LOG_BYTES) return;\n this.unlinkQuietly(this.rotatedPath(BUILDS_LOG_GENERATIONS, homeDir));\n for (let gen = BUILDS_LOG_GENERATIONS - 1; gen >= 1; gen -= 1) {\n this.renameQuietly(this.rotatedPath(gen, homeDir), this.rotatedPath(gen + 1, homeDir));\n }\n this.renameQuietly(this.logPath(homeDir), this.rotatedPath(1, homeDir));\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n }\n\n // ─── FILESYSTEM PRIMITIVES, ALL SWALLOWING ────────────────────────────────────────────────────────\n\n private ensureDir(file: string): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.mkdirSync(path.dirname(file), { recursive: true });\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n }\n\n private unlinkQuietly(file: string): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n if (fs.existsSync(file)) fs.unlinkSync(file);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n }\n\n private renameQuietly(from: string, to: string): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n if (fs.existsSync(from)) fs.renameSync(from, to);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n }\n\n private readTextOrEmpty(file: string): string {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return '';\n }\n }\n\n private readLines(file: string): string[] {\n const text = this.readTextOrEmpty(file);\n if (text === '') return [];\n return text.split('\\n').filter((line: string): boolean => line.trim() !== '');\n }\n\n // A blocking sleep, because the lock retry sits on a synchronous append path that must not become\n // async — `finish()` is called from a `finally` and an async logger there could outlive the process.\n private sleep(ms: number): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n }\n\n // The checked-out branch in `startDir`, or '' when git cannot say. spawnSync does not throw on a\n // non-zero exit, so \"not a repo\" arrives as a status, not an exception.\n private gitBranch(startDir: string): string {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const result = spawnSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'],\n { cwd: startDir, encoding: 'utf8' });\n if (result.status !== 0 || typeof result.stdout !== 'string') return '';\n return result.stdout.trim();\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return '';\n }\n }\n}\n"]}
1
+ {"version":3,"file":"builds-log.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/builds-log.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,uDAAiC;AACjC,+CAAyB;AACzB,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAE3D,8DAAyD;AACzD,+CAAgD;AAChD,iEAA6D;AAE7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACU,QAAA,eAAe,GAAG,YAAY,CAAC;AAC/B,QAAA,gBAAgB,GAAG,iBAAiB,CAAC;AAElD,kGAAkG;AACrF,QAAA,WAAW,GAAG,OAAO,CAAC;AACtB,QAAA,kBAAkB,GAAG,cAAc,CAAC;AACpC,QAAA,eAA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AG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,KAAK,KAAK,CAAC;QACf,CAAC;IACL,CAAC;IAED,iGAAiG;IACjG,wEAAwE;IAChE,SAAS,CAAC,QAAgB;QAC9B,8DAA8D;QAC9D,IAAI,CAAC;YACD,MAAM,MAAM,GAAG,IAAA,yBAAS,EAAC,KAAK,EAAE,CAAC,WAAW,EAAE,cAAc,EAAE,MAAM,CAAC,EACjE,EAAE,GAAG,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC,CAAC;YACzC,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,IAAI,OAAO,MAAM,CAAC,MAAM,KAAK,QAAQ;gBAAE,OAAO,EAAE,CAAC;YACxE,OAAO,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC;QAChC,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,KAAK,KAAK,CAAC;YACX,OAAO,EAAE,CAAC;QACd,CAAC;IACL,CAAC;CACJ,CAAA;AA/YY,8BAAS;oBAAT,SAAS;IADrB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEA,6BAAY;GADxC,SAAS,CA+YrB","sourcesContent":["import { spawnSync } from 'child_process';\nimport * as crypto from 'crypto';\nimport * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { DotWebpieces } from '@webpieces/tooling-common';\nimport { HOME_CONFIG_DIR } from './home-config';\nimport { toError } from '@webpieces/tooling-common/to-error';\n\n/**\n * `~/.webpieces/builds.log` — the MACHINE-WIDE, append-only ledger of every build this box has started.\n *\n * ─── WHY THIS ONE FILE LIVES OUTSIDE THE REPO ─────────────────────────────────────────────────────────\n * `no-machine-global-state.spec.ts` records the standing rule: webpieces writes state under\n * `{repo}/.webpieces` and nowhere else. This is the ONE carve-out, and the argument is written out in\n * `decisions/0006-the-build-ledger-is-machine-global.md`. In short:\n *\n * • The FACT is machine-scoped. \"How many builds are burning this box's CPU right now\" is not a\n * property of any repo; it is a property of the machine. A per-repo ledger cannot answer it — every\n * linked worktree has its OWN `.webpieces/`, so it would be blind to the sibling worktree it is\n * actually contending with, never mind the four other repos on the disk.\n * • It is NOT A CACHE. The retired `PrBodyStore` that the no-machine-global rule was written for was a\n * local copy of a fact GitHub owned, so it could be stale, missing, or on the wrong computer. There\n * is no remote copy of this. The file IS the fact.\n * • Its key is an ABSOLUTE LOCAL PATH, which is stable precisely because it never leaves the machine —\n * the instability that killed `PrBodyStore`'s `<host>/<owner>/<repo>` key cannot arise here.\n *\n * ─── WHY IT IS SAFE TO WRITE CONCURRENTLY ─────────────────────────────────────────────────────────────\n * Rows are deliberately kept under `MAX_ROW_BYTES` (512, macOS `PIPE_BUF`). A single `O_APPEND`\n * `write(2)` at or below that size is indivisible, so two builds appending at the same instant cannot\n * interleave halves of a line. The lock is therefore belt-and-braces for the APPEND and genuinely\n * load-bearing for ROTATION, where a rename-and-reopen really does race.\n *\n * ─── IT MAY NEVER FAIL A BUILD ────────────────────────────────────────────────────────────────────────\n * Every method here is best-effort and swallows its own errors. A build must never die because a log\n * file was busy, unwritable, or on a full disk. Lock acquisition retries and then gives up and appends\n * anyway — which the row-size invariant above makes safe.\n */\nexport const BUILDS_LOG_FILE = 'builds.log';\nexport const BUILDS_LOCK_FILE = 'builds.log.lock';\n\n/** START, and the two terminal kinds. `DONE-` is the greppable prefix that pairs with a START. */\nexport const BUILD_START = 'START';\nexport const BUILD_DONE_SUCCESS = 'DONE-SUCCESS';\nexport const BUILD_DONE_FAIL = 'DONE-FAIL';\n\n/** Rotate at 1 MB, keeping five generations (`.1` … `.5`); the old `.5` is dropped. */\nexport const MAX_BUILDS_LOG_BYTES = 1024 * 1024;\nexport const BUILDS_LOG_GENERATIONS = 5;\n\n/**\n * macOS `PIPE_BUF`. A row at or under this size is written by ONE indivisible `write(2)`, which is what\n * makes a lost lock a non-event rather than a corrupted file. Long paths are clipped to hold the line\n * under it — see `clip`.\n */\nexport const MAX_ROW_BYTES = 512;\n\n/** How long a build may hold the lock before another writer stops waiting and appends anyway. */\nconst LOCK_RETRY_MS = 50;\nconst LOCK_TIMEOUT_MS = 2000;\n\n/**\n * The handle a START row hands back, and the ONLY thing `finish()` accepts. Data-only (a class, per\n * CLAUDE.md), carrying exactly the fields the DONE row needs to pair itself with its START: the uuid,\n * the caller, the repo, and when it began (so `took=` is computed from one clock, not two).\n */\nexport class BuildTicket {\n id: string;\n by: string;\n repo: string;\n startedMs: number;\n\n constructor(id: string, by: string, repo: string, startedMs: number) {\n this.id = id;\n this.by = by;\n this.repo = repo;\n this.startedMs = startedMs;\n }\n}\n\n/**\n * How the build process ended. Node reports a null code when a signal ended the process, so collapsing\n * this to a number would discard the only useful explanation for an otherwise silent build failure.\n * Data-only: the PR gate decides which CLI exit code to return, while the ledger records these raw facts.\n */\nexport class BuildTermination {\n code: number | null;\n signal: string | null;\n\n constructor(code: number | null, signal: string | null) {\n this.code = code;\n this.signal = signal;\n }\n}\n\n/**\n * One build that is STILL RUNNING — a START row with no matching `DONE-`, whose pid is still alive.\n * Data-only. This is what the refusal message renders, so it carries the three things a reader needs to\n * recognise the build in question: where it is, which tree, and how old it is.\n */\nexport class RunningBuild {\n id: string;\n by: string;\n repo: string;\n tree: string;\n cwd: string;\n branch: string;\n pid: number;\n startedMs: number;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n id: string, by: string, repo: string, tree: string,\n cwd: string, branch: string, pid: number, startedMs: number,\n ) {\n this.id = id;\n this.by = by;\n this.repo = repo;\n this.tree = tree;\n this.cwd = cwd;\n this.branch = branch;\n this.pid = pid;\n this.startedMs = startedMs;\n }\n}\n\n/**\n * The ledger. See the file docblock for why it is machine-global and why every operation swallows its\n * own errors.\n *\n * `homeDir` is a parameter on every public method, defaulted to `os.homedir()`, for exactly the reason\n * `HomeConfigService.configPath` takes one: a spec must be able to exercise the real code against a temp\n * directory and must never touch the developer's actual `~/.webpieces`.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class BuildsLog {\n constructor(private readonly dotDir: DotWebpieces) {}\n\n /** `~/.webpieces/builds.log`. */\n logPath(homeDir: string = os.homedir()): string {\n return path.join(homeDir, HOME_CONFIG_DIR, BUILDS_LOG_FILE);\n }\n\n /** `~/.webpieces/builds.log.lock` — `{\"pid\":N,\"started\":<epochMs>}`. */\n lockPath(homeDir: string = os.homedir()): string {\n return path.join(homeDir, HOME_CONFIG_DIR, BUILDS_LOCK_FILE);\n }\n\n /** `~/.webpieces/builds.log.<n>` — generation `n`, 1 being the most recent. */\n rotatedPath(generation: number, homeDir: string = os.homedir()): string {\n return `${this.logPath(homeDir)}.${String(generation)}`;\n }\n\n /**\n * Record that a build is starting, and hand back the ticket its DONE row will need.\n *\n * `by` is the CALLER — `BuildGateOptions.stage`, i.e. `build` | `review` | `finish`. There is no\n * second \"caller\" concept anywhere: the stage id already is one, and a second spelling of it would\n * be the shim `.claude/rules/no-backwards-compat.md` rejects.\n *\n * Returns a ticket even when the append failed. A build whose START row never landed still has to be\n * able to call `finish()`; the alternative is a nullable return that every call site must branch on\n * for a logging failure that is, by policy, not an error.\n */\n start(by: string, startDir: string, homeDir: string = os.homedir()): BuildTicket {\n const ticket = new BuildTicket(\n crypto.randomUUID(), by, this.dotDir.primaryRoot(startDir), Date.now());\n this.append(this.startRow(ticket, startDir), homeDir);\n return ticket;\n }\n\n /**\n * Record that the build behind `ticket` has ended. Only code 0 with no signal writes `DONE-SUCCESS`;\n * anything else writes `DONE-FAIL` carrying the raw code and signal, so a killed build does not become\n * an unexplained generic exit 1 in the machine record.\n */\n finish(ticket: BuildTicket, termination: BuildTermination, homeDir: string = os.homedir()): void {\n this.append(this.doneRow(ticket, termination), homeDir);\n }\n\n /**\n * Every build that is still live: a `START` with no matching `DONE-` row, whose pid is still alive.\n *\n * The pid filter is not an optimisation, it is what keeps the ledger from wedging the machine. A\n * build killed with SIGKILL — an agent cancelled mid-run, a terminal closed — writes no DONE row, so\n * without the liveness test its START would count forever and the fourth build would be refused for\n * the rest of the machine's life. The uuid answers \"which build\"; the pid answers \"is it still real\".\n *\n * Only the CURRENT generation is read. A rotated-away START is by definition at least 1 MB of rows\n * old and is not a build anyone is contending with.\n */\n running(homeDir: string = os.homedir()): RunningBuild[] {\n const lines = this.readLines(this.logPath(homeDir));\n const done = new Set<string>();\n for (const line of lines) {\n if (line.startsWith(`${BUILD_DONE_SUCCESS}\\t`) || line.startsWith(`${BUILD_DONE_FAIL}\\t`)) {\n done.add(this.field(line, 'id'));\n }\n }\n const live: RunningBuild[] = [];\n for (const line of lines) {\n if (!line.startsWith(`${BUILD_START}\\t`)) continue;\n const build = this.toRunningBuild(line);\n if (build === null || done.has(build.id)) continue;\n if (!this.isAlive(build.pid)) continue;\n live.push(build);\n }\n return live;\n }\n\n /**\n * The `@webpieces` release ACTUALLY EXECUTING — found by walking UP from this module's own directory\n * to the nearest enclosing `node_modules/@webpieces/<pkg>/package.json`. `''` when this code is\n * running from source rather than from an installed package (which is the state in this repo's own\n * specs, and a perfectly ordinary answer).\n *\n * ─── WHY THIS IS NOT `WebpiecesVersions.readInstalled(root)` ──────────────────────────────────────\n * They answer DIFFERENT QUESTIONS and merging them would break the older one. `readInstalled` joins\n * `<root>/node_modules/@webpieces/...` at a FIXED tree root ON PURPOSE: its whole job is to detect\n * DRIFT between what a tree PINS and what some other tree pins, and a walk-up would silently resolve\n * a worktree with no install of its own to the primary clone's copy — hiding exactly the skew that\n * guard exists to catch. This question is the opposite one: \"whichever copy is running, name it\", and\n * for that the walk-up is the only correct answer. Do not fold them together.\n */\n executingVersion(): string {\n let dir = __dirname;\n for (let hops = 0; hops < 40; hops += 1) {\n const version = this.versionOfEnclosingPackage(dir);\n if (version !== '') return version;\n const parent = path.dirname(dir);\n if (parent === dir) return '';\n dir = parent;\n }\n return '';\n }\n\n // `<dir>` is `node_modules/@webpieces/<pkg>/...`? Then that package's version, else ''.\n private versionOfEnclosingPackage(dir: string): string {\n const parent = path.dirname(dir);\n const grandparent = path.dirname(parent);\n if (path.basename(parent) !== '@webpieces' || path.basename(grandparent) !== 'node_modules') return '';\n const text = this.readTextOrEmpty(path.join(dir, 'package.json'));\n const match = /\"version\"\\s*:\\s*\"([^\"]+)\"/.exec(text);\n return match === null ? '' : match[1];\n }\n\n // ─── ROW RENDERING ────────────────────────────────────────────────────────────────────────────────\n\n private startRow(ticket: BuildTicket, startDir: string): string {\n return [\n BUILD_START,\n `id=${ticket.id}`,\n `t=${new Date(ticket.startedMs).toISOString()}`,\n `ms=${String(ticket.startedMs)}`,\n `by=${ticket.by}`,\n `repo=${this.clip(ticket.repo)}`,\n `tree=${this.dotDir.worktreeName(startDir) || 'primary'}`,\n `cwd=${this.clip(startDir)}`,\n `branch=${this.gitBranch(startDir)}`,\n `pid=${String(process.pid)}`,\n `wp=${this.executingVersion()}`,\n ].join('\\t');\n }\n\n private doneRow(ticket: BuildTicket, termination: BuildTermination): string {\n const now = Date.now();\n const success = termination.code === 0 && termination.signal === null;\n const fields = [\n success ? BUILD_DONE_SUCCESS : BUILD_DONE_FAIL,\n `id=${ticket.id}`,\n `t=${new Date(now).toISOString()}`,\n `ms=${String(now)}`,\n `by=${ticket.by}`,\n `repo=${this.clip(ticket.repo)}`,\n `took=${String(now - ticket.startedMs)}`,\n ];\n if (!success) fields.push(`exit=${termination.code === null ? 'null' : String(termination.code)}`);\n if (termination.signal !== null) fields.push(`signal=${this.clip(termination.signal)}`);\n fields.push(`pid=${String(process.pid)}`);\n return fields.join('\\t');\n }\n\n /**\n * Hold a long path down to `max` characters by keeping its TAIL, which is the half that identifies\n * the tree; a clipped value is marked with a leading `…` so nobody mistakes it for a real path.\n *\n * This is what keeps a row under `MAX_ROW_BYTES` — see the file docblock. `append` re-checks the\n * assembled line as a backstop, because three clipped fields plus a long branch name can still add up.\n */\n private clip(value: string, max = 120): string {\n const oneLine = value.replace(/[\\t\\n\\r]/g, ' ');\n return oneLine.length <= max ? oneLine : `…${oneLine.slice(oneLine.length - max)}`;\n }\n\n // ─── ROW PARSING ──────────────────────────────────────────────────────────────────────────────────\n\n /** The value of `<name>=` on a TSV row, or '' when the row does not carry it. */\n private field(line: string, name: string): string {\n for (const part of line.split('\\t')) {\n if (part.startsWith(`${name}=`)) return part.slice(name.length + 1);\n }\n return '';\n }\n\n // A START row as a RunningBuild, or null when it is missing the two fields that make it usable.\n private toRunningBuild(line: string): RunningBuild | null {\n const id = this.field(line, 'id');\n const pid = Number.parseInt(this.field(line, 'pid'), 10);\n if (id === '' || !Number.isInteger(pid) || pid <= 0) return null;\n const startedMs = Number.parseInt(this.field(line, 'ms'), 10);\n return new RunningBuild(\n id, this.field(line, 'by'), this.field(line, 'repo'), this.field(line, 'tree'),\n this.field(line, 'cwd'), this.field(line, 'branch'), pid,\n Number.isInteger(startedMs) ? startedMs : 0,\n );\n }\n\n /**\n * Is `pid` still addressable? `process.kill(pid, 0)` sends no signal — it only asks the kernel. ESRCH\n * is the ONE answer that proves death; EPERM proves the opposite (it exists, it is somebody else's).\n * Pid reuse is an accepted imprecision here: being wrong in the \"still running\" direction costs\n * one extra refusal, being wrong the other way lets a fourth build start.\n *\n * WHY A PID IS MEANINGFUL HERE AND WAS NOT FOR AGENT WORKTREE LOCKS. Every row in this ledger is\n * written BY the process it names — one real OS process per build — so its pid identifies it.\n * A Claude Code subagent is not a process at all: every agent in a session records the SAME pid,\n * the session's, which is why that check was deleted rather than shared (see\n * harness-agent-activity.ts). Do not generalise this one back out to anything but a real process.\n */\n private isAlive(pid: number): boolean {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n process.kill(pid, 0);\n return true;\n } catch (err: unknown) {\n const error = toError(err);\n return (error as NodeJS.ErrnoException).code !== 'ESRCH';\n }\n }\n\n // ─── APPEND, LOCK, ROTATE ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Append one row, best-effort. Takes the lock so rotation cannot race, and appends ANYWAY when the\n * lock cannot be had within `LOCK_TIMEOUT_MS` — the row is under `PIPE_BUF`, so an unlocked\n * `O_APPEND` write is still indivisible, and a build must never die because a log file was busy.\n */\n private append(row: string, homeDir: string): void {\n const line = `${this.truncateToRowLimit(row)}\\n`;\n const held = this.tryAcquireLock(homeDir);\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n this.ensureDir(this.logPath(homeDir));\n if (held) this.rotateIfLarge(homeDir);\n fs.appendFileSync(this.logPath(homeDir), line);\n } catch (err: unknown) {\n const error = toError(err);\n void error; // logging may never fail a build — see the file docblock\n } finally {\n if (held) this.releaseLock(homeDir);\n }\n }\n\n // The backstop for the PIPE_BUF invariant, measured in BYTES rather than characters because a path\n // may hold multi-byte characters. Truncating a row loses fields off the end, which is strictly better\n // than a torn line that breaks every row after it.\n private truncateToRowLimit(row: string): string {\n const bytes = Buffer.from(row, 'utf8');\n // -1 for the newline `append` adds.\n if (bytes.length <= MAX_ROW_BYTES - 1) return row;\n return bytes.subarray(0, MAX_ROW_BYTES - 1).toString('utf8');\n }\n\n /**\n * Take the ledger lock, retrying every `LOCK_RETRY_MS` until `LOCK_TIMEOUT_MS`. False means \"carry on\n * without it\" — never an error, and never a reason to skip the append.\n *\n * The mechanism is `MainSyncStatusService.tryAcquireMainSyncLock`'s, proven and deliberately copied\n * rather than re-invented: an `wx` (O_CREAT|O_EXCL) create so exactly one of N racers wins, a payload\n * carrying pid + started so a dead holder is identifiable, stale reclaim gated on pid liveness, and a\n * re-read afterwards to confirm the entry on disk is OURS (a simultaneous reclaimer could have\n * unlinked ours and written its own between the two calls).\n */\n private tryAcquireLock(homeDir: string): boolean {\n const deadline = Date.now() + LOCK_TIMEOUT_MS;\n this.ensureDir(this.lockPath(homeDir));\n // Rendered rather than JSON.stringify'd off an anonymous object — two fields, both numbers, and\n // the file's whole contract is `{\"pid\":N,\"started\":M}`.\n const payload = `{\"pid\":${String(process.pid)},\"started\":${String(Date.now())}}\\n`;\n for (;;) {\n if (this.createExclusive(this.lockPath(homeDir), payload)) return true;\n if (!this.isHolderAlive(homeDir)) {\n this.unlinkQuietly(this.lockPath(homeDir));\n if (this.createExclusive(this.lockPath(homeDir), payload) && this.holderIsUs(homeDir)) return true;\n }\n if (Date.now() >= deadline) return false;\n this.sleep(LOCK_RETRY_MS);\n }\n }\n\n private releaseLock(homeDir: string): void {\n if (!this.holderIsUs(homeDir)) return;\n this.unlinkQuietly(this.lockPath(homeDir));\n }\n\n // O_CREAT|O_EXCL write: true when THIS call created the file, false when it already existed.\n private createExclusive(file: string, payload: string): boolean {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.writeFileSync(file, payload, { flag: 'wx' });\n return true;\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return false;\n }\n }\n\n // The pid recorded in the lock file, or 0 when there is no readable lock.\n private lockHolderPid(homeDir: string): number {\n const text = this.readTextOrEmpty(this.lockPath(homeDir));\n if (text === '') return 0;\n const match = /\"pid\"\\s*:\\s*(\\d+)/.exec(text);\n return match === null ? 0 : Number.parseInt(match[1], 10);\n }\n\n // An unreadable or pid-less lock file counts as DEAD: it is a corpse from a crashed writer, and\n // leaving it forever would mean every future append silently skips rotation.\n private isHolderAlive(homeDir: string): boolean {\n const pid = this.lockHolderPid(homeDir);\n return pid > 0 && this.isAlive(pid);\n }\n\n private holderIsUs(homeDir: string): boolean {\n return this.lockHolderPid(homeDir) === process.pid;\n }\n\n /**\n * `.4→.5, .3→.4, … .log→.1`, dropping the old `.5`. Runs INSIDE the lock, which is the one place the\n * lock is genuinely load-bearing: a rename-and-reopen really does race, and a writer that opened the\n * old inode mid-shift would append into a file nobody reads again.\n */\n private rotateIfLarge(homeDir: string): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n if (!fs.existsSync(this.logPath(homeDir))) return;\n if (fs.statSync(this.logPath(homeDir)).size < MAX_BUILDS_LOG_BYTES) return;\n this.unlinkQuietly(this.rotatedPath(BUILDS_LOG_GENERATIONS, homeDir));\n for (let gen = BUILDS_LOG_GENERATIONS - 1; gen >= 1; gen -= 1) {\n this.renameQuietly(this.rotatedPath(gen, homeDir), this.rotatedPath(gen + 1, homeDir));\n }\n this.renameQuietly(this.logPath(homeDir), this.rotatedPath(1, homeDir));\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n }\n\n // ─── FILESYSTEM PRIMITIVES, ALL SWALLOWING ────────────────────────────────────────────────────────\n\n private ensureDir(file: string): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.mkdirSync(path.dirname(file), { recursive: true });\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n }\n\n private unlinkQuietly(file: string): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n if (fs.existsSync(file)) fs.unlinkSync(file);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n }\n\n private renameQuietly(from: string, to: string): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n if (fs.existsSync(from)) fs.renameSync(from, to);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n }\n\n private readTextOrEmpty(file: string): string {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return '';\n }\n }\n\n private readLines(file: string): string[] {\n const text = this.readTextOrEmpty(file);\n if (text === '') return [];\n return text.split('\\n').filter((line: string): boolean => line.trim() !== '');\n }\n\n // A blocking sleep, because the lock retry sits on a synchronous append path that must not become\n // async — `finish()` is called from a `finally` and an async logger there could outlive the process.\n private sleep(ms: number): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n }\n\n // The checked-out branch in `startDir`, or '' when git cannot say. spawnSync does not throw on a\n // non-zero exit, so \"not a repo\" arrives as a status, not an exception.\n private gitBranch(startDir: string): string {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const result = spawnSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'],\n { cwd: startDir, encoding: 'utf8' });\n if (result.status !== 0 || typeof result.stdout !== 'string') return '';\n return result.stdout.trim();\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return '';\n }\n }\n}\n"]}
@@ -6,7 +6,7 @@ const fs = tslib_1.__importStar(require("fs"));
6
6
  const path = tslib_1.__importStar(require("path"));
7
7
  const config_file_1 = require("./config-file");
8
8
  const validate_config_1 = require("./validate-config");
9
- const to_error_1 = require("./to-error");
9
+ const to_error_1 = require("@webpieces/tooling-common/to-error");
10
10
  /**
11
11
  * Validate ONLY the pr-gate `checklists` array, in isolation — that it IS an array (the removed `{ doc }`
12
12
  * manifest shape is rejected with its migration steps), each entry's id is present, distinct and
@@ -1 +1 @@
1
- {"version":3,"file":"checklist-docs-validator.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/checklist-docs-validator.ts"],"names":[],"mappings":";;AAeA,sDAwBC;;AAvCD,+CAAyB;AACzB,mDAA6B;AAC7B,+CAA+C;AAC/C,uDAA8D;AAC9D,yCAAqC;AAErC;;;;;;;GAOG;AACH,2GAA2G;AAC3G,SAAgB,qBAAqB,CAAC,GAAW;IAC7C,MAAM,UAAU,GAAG,IAAA,4BAAc,EAAC,GAAG,CAAC,CAAC;IACvC,IAAI,CAAC,UAAU;QAAE,OAAO,EAAE,CAAC;IAC3B,wFAAwF;IACxF,IAAI,GAA4B,CAAC;IACjC,6GAA6G;IAC7G,8DAA8D;IAC9D,IAAI,CAAC;QACD,wFAAwF;QACxF,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,YAAY,CAAC,UAAU,EAAE,MAAM,CAAC,CAA4B,CAAC;IACrF,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,OAAO,CAAC,aAAa,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC,uBAAuB,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;IAC1F,CAAC;IACD,MAAM,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;IAC1C,sGAAsG;IACtG,yGAAyG;IACzG,wGAAwG;IACxG,2EAA2E;IAC3E,MAAM,QAAQ,GAAG,GAAG,CAAC,UAAU,CAAwC,CAAC;IACxE,2EAA2E;IAC3E,MAAM,MAAM,GAAG,QAAQ,EAAE,CAAC,SAAS,CAAwC,CAAC;IAC5E,IAAI,CAAC,MAAM,IAAI,CAAC,CAAC,YAAY,IAAI,MAAM,CAAC;QAAE,OAAO,EAAE,CAAC;IACpD,OAAO,IAAA,2CAAyB,EAAC,MAAM,CAAC,YAAY,CAAC,EAAE,QAAQ,CAAC,CAAC;AACrE,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { findConfigFile } from './config-file';\nimport { validateChecklistsSection } from './validate-config';\nimport { toError } from './to-error';\n\n/**\n * Validate ONLY the pr-gate `checklists` array, in isolation — that it IS an array (the removed `{ doc }`\n * manifest shape is rejected with its migration steps), each entry's id is present, distinct and\n * file-safe, each entry's repo-relative doc exists, a retired `subagent` key is rejected, and patterns are\n * string[]. Same logic loadAndValidate runs, but callable directly so broken checklists fail as their OWN\n * `validate-checklist-docs` check (clear owner) instead of surfacing as an unrelated validator's banner.\n * Returns errors; never throws.\n */\n// webpieces-disable no-function-outside-class -- module-level config validator, matches validate-config.ts\nexport function validateChecklistDocs(cwd: string): string[] {\n const configPath = findConfigFile(cwd);\n if (!configPath) return [];\n // webpieces-disable no-any-unknown -- parsed config JSON is opaque until narrowed below\n let raw: Record<string, unknown>;\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: a malformed config surfaces as one readable error\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // webpieces-disable no-any-unknown -- parsed config JSON is opaque until narrowed below\n raw = JSON.parse(fs.readFileSync(configPath, 'utf8')) as Record<string, unknown>;\n } catch (err: unknown) {\n const error = toError(err);\n return [`[pr-gate] ${path.basename(configPath)} is not valid JSON: ${error.message}`];\n }\n const repoRoot = path.dirname(configPath);\n // ONE location: commands[\"pr-gate\"]. This function parses the config itself rather than going through\n // loadAndValidate, so it used to also read the retired top-level `pr-gate` — which meant a config on the\n // dead layout validated its checklists silently here while loadAndValidate rejected it everywhere else.\n // webpieces-disable no-any-unknown -- narrowing the opaque command section\n const commands = raw['commands'] as Record<string, unknown> | undefined;\n // webpieces-disable no-any-unknown -- narrowing the opaque pr-gate section\n const prGate = commands?.['pr-gate'] as Record<string, unknown> | undefined;\n if (!prGate || !('checklists' in prGate)) return [];\n return validateChecklistsSection(prGate['checklists'], repoRoot);\n}\n"]}
1
+ {"version":3,"file":"checklist-docs-validator.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/checklist-docs-validator.ts"],"names":[],"mappings":";;AAeA,sDAwBC;;AAvCD,+CAAyB;AACzB,mDAA6B;AAC7B,+CAA+C;AAC/C,uDAA8D;AAC9D,iEAA6D;AAE7D;;;;;;;GAOG;AACH,2GAA2G;AAC3G,SAAgB,qBAAqB,CAAC,GAAW;IAC7C,MAAM,UAAU,GAAG,IAAA,4BAAc,EAAC,GAAG,CAAC,CAAC;IACvC,IAAI,CAAC,UAAU;QAAE,OAAO,EAAE,CAAC;IAC3B,wFAAwF;IACxF,IAAI,GAA4B,CAAC;IACjC,6GAA6G;IAC7G,8DAA8D;IAC9D,IAAI,CAAC;QACD,wFAAwF;QACxF,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,YAAY,CAAC,UAAU,EAAE,MAAM,CAAC,CAA4B,CAAC;IACrF,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,OAAO,CAAC,aAAa,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC,uBAAuB,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;IAC1F,CAAC;IACD,MAAM,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;IAC1C,sGAAsG;IACtG,yGAAyG;IACzG,wGAAwG;IACxG,2EAA2E;IAC3E,MAAM,QAAQ,GAAG,GAAG,CAAC,UAAU,CAAwC,CAAC;IACxE,2EAA2E;IAC3E,MAAM,MAAM,GAAG,QAAQ,EAAE,CAAC,SAAS,CAAwC,CAAC;IAC5E,IAAI,CAAC,MAAM,IAAI,CAAC,CAAC,YAAY,IAAI,MAAM,CAAC;QAAE,OAAO,EAAE,CAAC;IACpD,OAAO,IAAA,2CAAyB,EAAC,MAAM,CAAC,YAAY,CAAC,EAAE,QAAQ,CAAC,CAAC;AACrE,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { findConfigFile } from './config-file';\nimport { validateChecklistsSection } from './validate-config';\nimport { toError } from '@webpieces/tooling-common/to-error';\n\n/**\n * Validate ONLY the pr-gate `checklists` array, in isolation — that it IS an array (the removed `{ doc }`\n * manifest shape is rejected with its migration steps), each entry's id is present, distinct and\n * file-safe, each entry's repo-relative doc exists, a retired `subagent` key is rejected, and patterns are\n * string[]. Same logic loadAndValidate runs, but callable directly so broken checklists fail as their OWN\n * `validate-checklist-docs` check (clear owner) instead of surfacing as an unrelated validator's banner.\n * Returns errors; never throws.\n */\n// webpieces-disable no-function-outside-class -- module-level config validator, matches validate-config.ts\nexport function validateChecklistDocs(cwd: string): string[] {\n const configPath = findConfigFile(cwd);\n if (!configPath) return [];\n // webpieces-disable no-any-unknown -- parsed config JSON is opaque until narrowed below\n let raw: Record<string, unknown>;\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: a malformed config surfaces as one readable error\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // webpieces-disable no-any-unknown -- parsed config JSON is opaque until narrowed below\n raw = JSON.parse(fs.readFileSync(configPath, 'utf8')) as Record<string, unknown>;\n } catch (err: unknown) {\n const error = toError(err);\n return [`[pr-gate] ${path.basename(configPath)} is not valid JSON: ${error.message}`];\n }\n const repoRoot = path.dirname(configPath);\n // ONE location: commands[\"pr-gate\"]. This function parses the config itself rather than going through\n // loadAndValidate, so it used to also read the retired top-level `pr-gate` — which meant a config on the\n // dead layout validated its checklists silently here while loadAndValidate rejected it everywhere else.\n // webpieces-disable no-any-unknown -- narrowing the opaque command section\n const commands = raw['commands'] as Record<string, unknown> | undefined;\n // webpieces-disable no-any-unknown -- narrowing the opaque pr-gate section\n const prGate = commands?.['pr-gate'] as Record<string, unknown> | undefined;\n if (!prGate || !('checklists' in prGate)) return [];\n return validateChecklistsSection(prGate['checklists'], repoRoot);\n}\n"]}
@@ -5,7 +5,7 @@ const tslib_1 = require("tslib");
5
5
  const fs = tslib_1.__importStar(require("fs"));
6
6
  const path = tslib_1.__importStar(require("path"));
7
7
  const inversify_1 = require("inversify");
8
- const to_error_1 = require("./to-error");
8
+ const to_error_1 = require("@webpieces/tooling-common/to-error");
9
9
  // The literal the printed command leaves for the human's words. Named so the message, and any test that
10
10
  // asserts the command is still a fill-in rather than a pre-filled excuse, agree on one spelling.
11
11
  const REASON_FILL_IN = 'REPLACE THIS with the human\'s own words, verbatim';
@@ -1 +1 @@
1
- {"version":3,"file":"checklist-override.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/checklist-override.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAC3D,yCAAqC;AAErC,wGAAwG;AACxG,iGAAiG;AACjG,MAAM,cAAc,GAAG,oDAAoD,CAAC;AAE5E;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAa,iBAAiB;IAC1B,WAAW,CAAS,CAAG,4DAA4D;IACnF,YAAY,CAAS,CAAE,yCAAyC;IAChE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CAAC,mBAA2B,EAAE,WAAmB,EAAE,YAAoB,EAAE,MAAc;QACrG,MAAM,OAAO,GAAa,EAAE,CAAC;QAC7B,IAAI,YAAY,KAAK,EAAE;YAAE,OAAO,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC;QACxD,IAAI,MAAM,KAAK,EAAE;YAAE,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QAC5C,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,EAAE,CAAC;QACpC,MAAM,QAAQ,GAAG,IAAI,CAAC,YAAY,CAAC,mBAAmB,EAAE,WAAW,CAAC,CAAC;QACrE,OAAO,+BAA+B,WAAW,QAAQ,QAAQ,eAAe,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI;cACnG,iGAAiG;cACjG,2DAA2D;cAC3D,IAAI,CAAC,YAAY,CAAC,mBAAmB,EAAE,WAAW,CAAC,CAAC;IAC9D,CAAC;CACJ,CAAA;AA5IY,4DAAwB;mCAAxB,wBAAwB;IADpC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;GAC5B,wBAAwB,CA4IpC;AAED,0FAA0F;AAC1F,gGAAgG;AACnF,QAAA,wBAAwB,GAAG,IAAI,wBAAwB,EAAE,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { toError } from './to-error';\n\n// The literal the printed command leaves for the human's words. Named so the message, and any test that\n// asserts the command is still a fill-in rather than a pre-filled excuse, agree on one spelling.\nconst REASON_FILL_IN = 'REPLACE THIS with the human\\'s own words, verbatim';\n\n/**\n * The HUMAN's ship-anyway decision for ONE checklist, recorded in its own file beside the verdict:\n * `.webpieces/pr-review/<feature>/override-<id>.json`. Data-only (per CLAUDE.md).\n *\n * WHY IT IS A SEPARATE FILE FROM THE VERDICT. `review-round<N>-<id>.json` is a REVIEWER's verdict file, and a\n * coding agent editing a reviewer's verdict is refused by the harness — correctly, and by every route\n * (heredoc, `sed -i`, a rewrite). While the ship-anyway justification lived inside that same file as an\n * `override` field, the ONE participant who genuinely hears the human — the coordinating agent — was the\n * one participant physically unable to record what it heard, and a human had to hand-edit JSON. Meanwhile\n * the reviewer subagent refuses to write its own override, also correctly. Two acts, two files:\n *\n * review-round<N>-<id>.json written by the reviewer subagent, once — \"what I found\"\n * override-<id>.json written by the COORDINATING agent — \"the human saw this and said ship it\"\n *\n * The name says what the file is, so nothing has to infer intent from a field inside a verdict.\n *\n * PER-CHECKLIST, AND IT STANDS. There is no time scoping, no branch scoping, no sha scoping and no\n * re-authorization when a reviewer runs again: an authorization is about a checklist the human decided to\n * accept, not about a particular wording of a finding. An earlier draft carried a `findingDigest` (a\n * hash of the reviewer's `output`) meaning to invalidate an override when the finding changed. That was\n * removed deliberately: `output` is LLM-written prose, so a re-run words the SAME finding differently\n * almost every time, and the digest would have mismatched on essentially every re-review — delivering\n * \"any re-review ⇒ re-authorize\", which is the exact dance this file exists to delete. FRESHNESS IS\n * CARRIED BY TRANSPARENCY INSTEAD: the dashboard renders 🟠 OVERRIDDEN with the reason, who authorized it\n * and when, and any new red finding still publishes as its own finding on the PR, so a human reading the\n * PR sees both and can judge for themselves.\n */\nexport class ChecklistOverride {\n checklistId: string; // the checklist this authorizes — never \"the PR as a whole\"\n authorizedBy: string; // WHO decided (e.g. 'human, in-session')\n authorizedAt: string; // WHEN, ISO-8601\n reason: string; // the human's own words, verbatim — the provenance, not an agent's paraphrase\n /**\n * '' = a well-formed authorization. Non-empty = the file exists and parses but cannot be READ as one\n * (a missing field). Carried as DATA rather than thrown for the same reason `ChecklistResult.problem`\n * is: the complaint has to be reportable in identical words by every command that reads the file, and\n * a half-written override must never be silently mistaken for an absent one.\n */\n problem: string;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(checklistId: string, authorizedBy: string, authorizedAt: string, reason: string, problem = '') {\n this.checklistId = checklistId;\n this.authorizedBy = authorizedBy;\n this.authorizedAt = authorizedAt;\n this.reason = reason;\n this.problem = problem;\n }\n}\n\n/**\n * Reads `override-<id>.json`, and renders the ready-to-run command that WRITES one.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it is injected by type and drawn in the DI design.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ChecklistOverrideService {\n /** `override-<id>.json` — the ONE place this name is spelled. */\n overrideFileName(checklistId: string): string {\n return `override-${checklistId}.json`;\n }\n\n /** Absolute path of the override file, beside summary.json and review-round<N>-<id>.json in the AI-WRITABLE dir. */\n overridePath(summaryJsonFilePath: string, checklistId: string): string {\n return path.join(path.dirname(summaryJsonFilePath), this.overrideFileName(checklistId));\n }\n\n /**\n * The human's authorization for one checklist, or `null` when there is NO FILE — the only state that\n * genuinely means \"nobody authorized anything\".\n *\n * A file that EXISTS always yields a value, carrying any complaint in `problem` — whether a field is\n * missing or the bytes do not parse at all. `null` for those would collapse \"wrote an authorization\n * wrong\" into \"the human never authorized anything\", and send the reader off to ask for a decision that\n * was already made. `resolveVerdict` routes a non-empty `problem` to CK_BAD_FORMAT, so the gate still\n * REFUSES either way; the difference is entirely in whether the writer is told why it did not count.\n */\n // webpieces-disable no-any-unknown -- opaque parsed JSON, narrowed field-by-field below\n load(summaryJsonFilePath: string, checklistId: string): ChecklistOverride | null {\n const filePath = this.overridePath(summaryJsonFilePath, checklistId);\n if (!fs.existsSync(filePath)) return null;\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unparseable override reads as absent, never fatal\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // webpieces-disable no-any-unknown -- parsed JSON is opaque until narrowed below\n const raw = JSON.parse(fs.readFileSync(filePath, 'utf8')) as Record<string, unknown>;\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {\n return this.unreadable(summaryJsonFilePath, checklistId, 'it is not a JSON object');\n }\n const authorizedBy = this.stringField(raw, 'authorizedBy');\n const authorizedAt = this.stringField(raw, 'authorizedAt');\n const reason = this.stringField(raw, 'reason');\n return new ChecklistOverride(\n checklistId, authorizedBy, authorizedAt, reason,\n this.problemFor(summaryJsonFilePath, checklistId, authorizedBy, reason),\n );\n } catch (err: unknown) {\n const error = toError(err);\n return this.unreadable(summaryJsonFilePath, checklistId, error.message);\n }\n }\n\n /**\n * The value for an override file that EXISTS but cannot be read at all — unparseable bytes, or JSON that\n * is not an object. Reported rather than discarded, because \"you wrote it wrong\" and \"you never wrote\n * it\" call for opposite next actions and only the reader can tell them apart.\n */\n private unreadable(summaryJsonFilePath: string, checklistId: string, why: string): ChecklistOverride {\n const filePath = this.overridePath(summaryJsonFilePath, checklistId);\n const problem = `The override for checklist \"${checklistId}\" at ${filePath} cannot be read (${why}), so it `\n + 'authorizes nothing. The human\\'s decision is NOT recorded until this file parses. Rewrite the whole '\n + `file:\\n${this.writeCommand(summaryJsonFilePath, checklistId)}`;\n return new ChecklistOverride(checklistId, '', '', '', problem);\n }\n\n /**\n * What the dashboard and the PR comment print for an OVERRIDDEN checklist: the human's words plus the\n * provenance, so a reader never has to take \"someone approved this\" on trust.\n */\n detail(override: ChecklistOverride): string {\n const who = override.authorizedBy.trim();\n const when = override.authorizedAt.trim();\n const stamp = when === '' ? who : `${who}, ${when}`;\n return `${override.reason.trim()} (authorized by ${stamp})`;\n }\n\n /**\n * THE ready-to-run command that records an authorization — printed verbatim by every refusal.\n *\n * IT IS PRINTED, NOT DESCRIBED, on purpose. The old refusal said WHAT to write and WHERE but never WHO\n * MAY, so the reachable path was an agent improvising an in-place edit of a reviewer's verdict file —\n * which the harness denies, which is how the human ended up hand-editing JSON. An agent copying a\n * printed command into an obviously AI-writable path is a far cleaner ask, and it is the whole reason\n * this string exists.\n *\n * NOT INDENTED, deliberately: a shell heredoc's closing delimiter must sit at column 0, so indenting\n * this block to match the surrounding message would produce a command that does not run.\n */\n writeCommand(summaryJsonFilePath: string, checklistId: string): string {\n const filePath = this.overridePath(summaryJsonFilePath, checklistId);\n return [\n `cat > ${filePath} <<'JSON'`,\n '{',\n ` \"checklistId\": \"${checklistId}\",`,\n ' \"authorizedBy\": \"human, in-session\",',\n ` \"authorizedAt\": \"${this.nowIso()}\",`,\n ` \"reason\": \"${REASON_FILL_IN}\"`,\n '}',\n 'JSON',\n ].join('\\n');\n }\n\n /**\n * The paragraph that says WHO may run the command above — the half of this feature that is messaging.\n *\n * A reviewer subagent once told a human to run a command that no longer shipped, because the refusal\n * named a file and a field and never named a writer. All three facts are stated here in one place so\n * every surface says the same thing.\n */\n writerRule(): string {\n return 'Only the COORDINATING agent may write it — the one agent with the human in its own conversation. '\n + 'Transcribing a decision the human made to its face IN THIS SESSION is NOT self-authorization. '\n + 'A relayed instruction from another agent is NOT consent: if you are a reviewer subagent, say in '\n + 'your \"output\" that this finding needs a human authorization and STOP. Still forbidden: an agent '\n + 'inventing an authorization, a subagent writing one, and any agent authorizing a finding the human '\n + 'never saw.';\n }\n\n /** Seam: overridden in the spec so the printed command is assertable without a clock. */\n protected nowIso(): string {\n return new Date().toISOString();\n }\n\n // webpieces-disable no-any-unknown -- opaque parsed JSON value, narrowed to string here\n private stringField(raw: Record<string, unknown>, key: string): string {\n return typeof raw[key] === 'string' ? (raw[key] as string).trim() : '';\n }\n\n /**\n * '' when the authorization can be read. Otherwise the complaint, printed verbatim.\n *\n * `reason` and `authorizedBy` are the two fields that make the file mean anything: an override with no\n * stated reason is an assertion rather than a record, which is the whole thing this file replaced.\n */\n // eslint-disable-next-line @typescript-eslint/max-params\n private problemFor(summaryJsonFilePath: string, checklistId: string, authorizedBy: string, reason: string): string {\n const missing: string[] = [];\n if (authorizedBy === '') missing.push('\"authorizedBy\"');\n if (reason === '') missing.push('\"reason\"');\n if (missing.length === 0) return '';\n const filePath = this.overridePath(summaryJsonFilePath, checklistId);\n return `The override for checklist \"${checklistId}\" at ${filePath} is missing ${missing.join(' and ')}. `\n + 'An authorization with no stated reason and no named authorizer is an assertion, not a record — '\n + 'it does not authorize anything. Rewrite the whole file:\\n'\n + this.writeCommand(summaryJsonFilePath, checklistId);\n }\n}\n\n// Module-level instance, mirroring `dotWebpieces`: the defaulted constructor parameter of\n// ReviewJsonService, so `new ReviewJsonService()` keeps working while DI still injects by type.\nexport const checklistOverrideService = new ChecklistOverrideService();\n"]}
1
+ {"version":3,"file":"checklist-override.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/checklist-override.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAC3D,iEAA6D;AAE7D,wGAAwG;AACxG,iGAAiG;AACjG,MAAM,cAAc,GAAG,oDAAoD,CAAC;AAE5E;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAa,iBAAiB;IAC1B,WAAW,CAAS,CAAG,4DAA4D;IACnF,YAAY,CAAS,CAAE,yCAAyC;IAChE,YAAY,CAAS,CAAE,iBAAiB;IACxC,MAAM,CAAS,CAAQ,8EAA8E;IACrG;;;;;OAKG;IACH,OAAO,CAAS;IAEhB,yDAAyD;IACzD,YAAY,WAAmB,EAAE,YAAoB,EAAE,YAAoB,EAAE,MAAc,EAAE,OAAO,GAAG,EAAE;QACrG,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IAC3B,CAAC;CACJ;AArBD,8CAqBC;AAED;;;;GAIG;AAEI,IAAM,wBAAwB,GAA9B,MAAM,wBAAwB;IACjC,iEAAiE;IACjE,gBAAgB,CAAC,WAAmB;QAChC,OAAO,YAAY,WAAW,OAAO,CAAC;IAC1C,CAAC;IAED,oHAAoH;IACpH,YAAY,CAAC,mBAA2B,EAAE,WAAmB;QACzD,OAAO,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,mBAAmB,CAAC,EAAE,IAAI,CAAC,gBAAgB,CAAC,WAA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AAA,wBAAwB,GAAG,IAAI,wBAAwB,EAAE,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { toError } from '@webpieces/tooling-common/to-error';\n\n// The literal the printed command leaves for the human's words. Named so the message, and any test that\n// asserts the command is still a fill-in rather than a pre-filled excuse, agree on one spelling.\nconst REASON_FILL_IN = 'REPLACE THIS with the human\\'s own words, verbatim';\n\n/**\n * The HUMAN's ship-anyway decision for ONE checklist, recorded in its own file beside the verdict:\n * `.webpieces/pr-review/<feature>/override-<id>.json`. Data-only (per CLAUDE.md).\n *\n * WHY IT IS A SEPARATE FILE FROM THE VERDICT. `review-round<N>-<id>.json` is a REVIEWER's verdict file, and a\n * coding agent editing a reviewer's verdict is refused by the harness — correctly, and by every route\n * (heredoc, `sed -i`, a rewrite). While the ship-anyway justification lived inside that same file as an\n * `override` field, the ONE participant who genuinely hears the human — the coordinating agent — was the\n * one participant physically unable to record what it heard, and a human had to hand-edit JSON. Meanwhile\n * the reviewer subagent refuses to write its own override, also correctly. Two acts, two files:\n *\n * review-round<N>-<id>.json written by the reviewer subagent, once — \"what I found\"\n * override-<id>.json written by the COORDINATING agent — \"the human saw this and said ship it\"\n *\n * The name says what the file is, so nothing has to infer intent from a field inside a verdict.\n *\n * PER-CHECKLIST, AND IT STANDS. There is no time scoping, no branch scoping, no sha scoping and no\n * re-authorization when a reviewer runs again: an authorization is about a checklist the human decided to\n * accept, not about a particular wording of a finding. An earlier draft carried a `findingDigest` (a\n * hash of the reviewer's `output`) meaning to invalidate an override when the finding changed. That was\n * removed deliberately: `output` is LLM-written prose, so a re-run words the SAME finding differently\n * almost every time, and the digest would have mismatched on essentially every re-review — delivering\n * \"any re-review ⇒ re-authorize\", which is the exact dance this file exists to delete. FRESHNESS IS\n * CARRIED BY TRANSPARENCY INSTEAD: the dashboard renders 🟠 OVERRIDDEN with the reason, who authorized it\n * and when, and any new red finding still publishes as its own finding on the PR, so a human reading the\n * PR sees both and can judge for themselves.\n */\nexport class ChecklistOverride {\n checklistId: string; // the checklist this authorizes — never \"the PR as a whole\"\n authorizedBy: string; // WHO decided (e.g. 'human, in-session')\n authorizedAt: string; // WHEN, ISO-8601\n reason: string; // the human's own words, verbatim — the provenance, not an agent's paraphrase\n /**\n * '' = a well-formed authorization. Non-empty = the file exists and parses but cannot be READ as one\n * (a missing field). Carried as DATA rather than thrown for the same reason `ChecklistResult.problem`\n * is: the complaint has to be reportable in identical words by every command that reads the file, and\n * a half-written override must never be silently mistaken for an absent one.\n */\n problem: string;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(checklistId: string, authorizedBy: string, authorizedAt: string, reason: string, problem = '') {\n this.checklistId = checklistId;\n this.authorizedBy = authorizedBy;\n this.authorizedAt = authorizedAt;\n this.reason = reason;\n this.problem = problem;\n }\n}\n\n/**\n * Reads `override-<id>.json`, and renders the ready-to-run command that WRITES one.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it is injected by type and drawn in the DI design.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ChecklistOverrideService {\n /** `override-<id>.json` — the ONE place this name is spelled. */\n overrideFileName(checklistId: string): string {\n return `override-${checklistId}.json`;\n }\n\n /** Absolute path of the override file, beside summary.json and review-round<N>-<id>.json in the AI-WRITABLE dir. */\n overridePath(summaryJsonFilePath: string, checklistId: string): string {\n return path.join(path.dirname(summaryJsonFilePath), this.overrideFileName(checklistId));\n }\n\n /**\n * The human's authorization for one checklist, or `null` when there is NO FILE — the only state that\n * genuinely means \"nobody authorized anything\".\n *\n * A file that EXISTS always yields a value, carrying any complaint in `problem` — whether a field is\n * missing or the bytes do not parse at all. `null` for those would collapse \"wrote an authorization\n * wrong\" into \"the human never authorized anything\", and send the reader off to ask for a decision that\n * was already made. `resolveVerdict` routes a non-empty `problem` to CK_BAD_FORMAT, so the gate still\n * REFUSES either way; the difference is entirely in whether the writer is told why it did not count.\n */\n // webpieces-disable no-any-unknown -- opaque parsed JSON, narrowed field-by-field below\n load(summaryJsonFilePath: string, checklistId: string): ChecklistOverride | null {\n const filePath = this.overridePath(summaryJsonFilePath, checklistId);\n if (!fs.existsSync(filePath)) return null;\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unparseable override reads as absent, never fatal\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // webpieces-disable no-any-unknown -- parsed JSON is opaque until narrowed below\n const raw = JSON.parse(fs.readFileSync(filePath, 'utf8')) as Record<string, unknown>;\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {\n return this.unreadable(summaryJsonFilePath, checklistId, 'it is not a JSON object');\n }\n const authorizedBy = this.stringField(raw, 'authorizedBy');\n const authorizedAt = this.stringField(raw, 'authorizedAt');\n const reason = this.stringField(raw, 'reason');\n return new ChecklistOverride(\n checklistId, authorizedBy, authorizedAt, reason,\n this.problemFor(summaryJsonFilePath, checklistId, authorizedBy, reason),\n );\n } catch (err: unknown) {\n const error = toError(err);\n return this.unreadable(summaryJsonFilePath, checklistId, error.message);\n }\n }\n\n /**\n * The value for an override file that EXISTS but cannot be read at all — unparseable bytes, or JSON that\n * is not an object. Reported rather than discarded, because \"you wrote it wrong\" and \"you never wrote\n * it\" call for opposite next actions and only the reader can tell them apart.\n */\n private unreadable(summaryJsonFilePath: string, checklistId: string, why: string): ChecklistOverride {\n const filePath = this.overridePath(summaryJsonFilePath, checklistId);\n const problem = `The override for checklist \"${checklistId}\" at ${filePath} cannot be read (${why}), so it `\n + 'authorizes nothing. The human\\'s decision is NOT recorded until this file parses. Rewrite the whole '\n + `file:\\n${this.writeCommand(summaryJsonFilePath, checklistId)}`;\n return new ChecklistOverride(checklistId, '', '', '', problem);\n }\n\n /**\n * What the dashboard and the PR comment print for an OVERRIDDEN checklist: the human's words plus the\n * provenance, so a reader never has to take \"someone approved this\" on trust.\n */\n detail(override: ChecklistOverride): string {\n const who = override.authorizedBy.trim();\n const when = override.authorizedAt.trim();\n const stamp = when === '' ? who : `${who}, ${when}`;\n return `${override.reason.trim()} (authorized by ${stamp})`;\n }\n\n /**\n * THE ready-to-run command that records an authorization — printed verbatim by every refusal.\n *\n * IT IS PRINTED, NOT DESCRIBED, on purpose. The old refusal said WHAT to write and WHERE but never WHO\n * MAY, so the reachable path was an agent improvising an in-place edit of a reviewer's verdict file —\n * which the harness denies, which is how the human ended up hand-editing JSON. An agent copying a\n * printed command into an obviously AI-writable path is a far cleaner ask, and it is the whole reason\n * this string exists.\n *\n * NOT INDENTED, deliberately: a shell heredoc's closing delimiter must sit at column 0, so indenting\n * this block to match the surrounding message would produce a command that does not run.\n */\n writeCommand(summaryJsonFilePath: string, checklistId: string): string {\n const filePath = this.overridePath(summaryJsonFilePath, checklistId);\n return [\n `cat > ${filePath} <<'JSON'`,\n '{',\n ` \"checklistId\": \"${checklistId}\",`,\n ' \"authorizedBy\": \"human, in-session\",',\n ` \"authorizedAt\": \"${this.nowIso()}\",`,\n ` \"reason\": \"${REASON_FILL_IN}\"`,\n '}',\n 'JSON',\n ].join('\\n');\n }\n\n /**\n * The paragraph that says WHO may run the command above — the half of this feature that is messaging.\n *\n * A reviewer subagent once told a human to run a command that no longer shipped, because the refusal\n * named a file and a field and never named a writer. All three facts are stated here in one place so\n * every surface says the same thing.\n */\n writerRule(): string {\n return 'Only the COORDINATING agent may write it — the one agent with the human in its own conversation. '\n + 'Transcribing a decision the human made to its face IN THIS SESSION is NOT self-authorization. '\n + 'A relayed instruction from another agent is NOT consent: if you are a reviewer subagent, say in '\n + 'your \"output\" that this finding needs a human authorization and STOP. Still forbidden: an agent '\n + 'inventing an authorization, a subagent writing one, and any agent authorizing a finding the human '\n + 'never saw.';\n }\n\n /** Seam: overridden in the spec so the printed command is assertable without a clock. */\n protected nowIso(): string {\n return new Date().toISOString();\n }\n\n // webpieces-disable no-any-unknown -- opaque parsed JSON value, narrowed to string here\n private stringField(raw: Record<string, unknown>, key: string): string {\n return typeof raw[key] === 'string' ? (raw[key] as string).trim() : '';\n }\n\n /**\n * '' when the authorization can be read. Otherwise the complaint, printed verbatim.\n *\n * `reason` and `authorizedBy` are the two fields that make the file mean anything: an override with no\n * stated reason is an assertion rather than a record, which is the whole thing this file replaced.\n */\n // eslint-disable-next-line @typescript-eslint/max-params\n private problemFor(summaryJsonFilePath: string, checklistId: string, authorizedBy: string, reason: string): string {\n const missing: string[] = [];\n if (authorizedBy === '') missing.push('\"authorizedBy\"');\n if (reason === '') missing.push('\"reason\"');\n if (missing.length === 0) return '';\n const filePath = this.overridePath(summaryJsonFilePath, checklistId);\n return `The override for checklist \"${checklistId}\" at ${filePath} is missing ${missing.join(' and ')}. `\n + 'An authorization with no stated reason and no named authorizer is an assertion, not a record — '\n + 'it does not authorize anything. Rewrite the whole file:\\n'\n + this.writeCommand(summaryJsonFilePath, checklistId);\n }\n}\n\n// Module-level instance, mirroring `dotWebpieces`: the defaulted constructor parameter of\n// ReviewJsonService, so `new ReviewJsonService()` keeps working while DI still injects by type.\nexport const checklistOverrideService = new ChecklistOverrideService();\n"]}
@@ -7,8 +7,8 @@ const tslib_1 = require("tslib");
7
7
  const fs = tslib_1.__importStar(require("fs"));
8
8
  const path = tslib_1.__importStar(require("path"));
9
9
  const inversify_1 = require("inversify");
10
- const inform_ai_error_1 = require("./inform-ai-error");
11
- const to_error_1 = require("./to-error");
10
+ const tooling_common_1 = require("@webpieces/tooling-common");
11
+ const to_error_1 = require("@webpieces/tooling-common/to-error");
12
12
  exports.CONFIG_FILENAME = 'webpieces.config.json';
13
13
  /**
14
14
  * How many times a read+parse of webpieces.config.json is attempted before the failure is treated as
@@ -72,7 +72,7 @@ let ConfigFile = class ConfigFile {
72
72
  return outcome.config;
73
73
  lastError = outcome.error;
74
74
  }
75
- throw new inform_ai_error_1.InformAiError(this.formatParseFailure(configPath, lastError));
75
+ throw new tooling_common_1.InformAiError(this.formatParseFailure(configPath, lastError));
76
76
  }
77
77
  // ONE read+parse attempt. The read is inside the try too: a file being replaced can momentarily
78
78
  // fail to open (ENOENT between unlink and rename), which is the same transient class as a
@@ -1 +1 @@
1
- {"version":3,"file":"config-file.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/config-file.ts"],"names":[],"mappings":";;;AA+JA,wCAEC;AAKD,sCAEC;;AAxKD,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAE3D,uDAAkD;AAClD,yCAAqC;AAExB,QAAA,eAAe,GAAG,uBAAuB,CAAC;AAEvD;;;;;;;;;GASG;AACU,QAAA,qBAAqB,GAAG,CAAC,CAAC;AAEvC,uGAAuG;AAC1F,QAAA,yBAAyB,GAAG,EAAE,CAAC;AAE5C;;;GAGG;AACH,MAAa,kBAAkB;IAEd;IACA;IAFb,YACa,MAA4B,EAC5B,KAAmB;QADnB,WAAM,GAAN,MAAM,CAAsB;QAC5B,UAAK,GAAL,KAAK,CAAc;IAC7B,CAAC;CACP;AALD,gDAKC;AA8BD;;;GAGG;AAEI,IAAM,UAAU,GAAhB,MAAM,UAAU;IACnB,oGAAoG;IACpG,cAAc,CAAC,QAAgB;QAC3B,IAAI,GAAG,GAAG,QAAQ,CAAC;QACnB,OAAO,IAAI,EAAE,CAAC;YACV,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,uBAAe,CAAC,CAAC;YAChD,IAAI,EAAE,CAAC,UAAU,CAAC,OAAO,CAAC;gBAAE,OAAO,OAAO,CAAC;YAC3C,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;YACjC,IAAI,MAAM,KAAK,GAAG;gBAAE,OAAO,IAAI,CAAC;YAChC,GAAG,GAAG,MAAM,CAAC;QACjB,CAAC;IACL,CAAC;IAED;;;;;;;OAOG;IACH,aAAa,CAAC,UAAkB;QAC5B,IAAI,SAAS,GAAiB,IAAI,CAAC;QACnC,KAAK,IAAI,OAAO,GAAG,CAAC,EAAE,OAAO,IAAI,6BAAqB,EAAE,OAAO,EAAE,EAAE,CAAC;YAChE,IAAI,OAAO,GAAG,CAAC;gB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O,CACH,+DAA+D,6BAAqB,SAAS;YAC7F,SAAS,iCAAyB,GAAG,CAAC,6BAAqB,GAAG,CAAC,CAAC,gCAAgC;YAChG,gBAAgB,KAAK,EAAE,OAAO,IAAI,SAAS,IAAI;YAC/C,SAAS,UAAU,MAAM;YACzB,2CAA2C;YAC3C,6FAA6F;YAC7F,0FAA0F;YAC1F,6FAA6F;YAC7F,0BAA0B,6BAAqB,mDAAmD;YAClG,kGAAkG;YAClG,0BAA0B,uBAAe,qDAAqD;YAC9F,iGAAiG;YACjG,yFAAyF;YACzF,6FAA6F,CAChG,CAAC;IACN,CAAC;CACJ,CAAA;AAlFY,gCAAU;qBAAV,UAAU;IADtB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;GAC5B,UAAU,CAkFtB;AAED,sGAAsG;AACtG,oGAAoG;AACpG,MAAM,aAAa,GAAG,IAAI,UAAU,EAAE,CAAC;AAEvC;;GAEG;AACH,SAAgB,cAAc,CAAC,QAAgB;IAC3C,OAAO,aAAa,CAAC,cAAc,CAAC,QAAQ,CAAC,CAAC;AAClD,CAAC;AAED;;GAEG;AACH,SAAgB,aAAa,CAAC,UAAkB;IAC5C,OAAO,aAAa,CAAC,aAAa,CAAC,UAAU,CAAC,CAAC;AACnD,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { InformAiError } from './inform-ai-error';\nimport { toError } from './to-error';\n\nexport const CONFIG_FILENAME = 'webpieces.config.json';\n\n/**\n * How many times a read+parse of webpieces.config.json is attempted before the failure is treated as\n * REAL. On a machine running several agents at once the file is routinely rewritten underneath us\n * (a dep bump, another worktree's `wp-*` command, an editor's write-then-rename), and for the few\n * milliseconds of that write the bytes on disk are a truncated/half-written JSON document. Reading\n * exactly then produced a hard block that self-healed seconds later — a false positive that also\n * blocked the tools needed to look into it. Three attempts spanning ~50ms covers a normal write with\n * a cost no human or agent can perceive, and cannot mask a file that is genuinely malformed (a\n * conflict-marked or typo'd config fails all three, identically, and still blocks).\n */\nexport const CONFIG_PARSE_ATTEMPTS = 3;\n\n/** Pause between parse attempts. Small enough to be invisible, long enough to outlast a file write. */\nexport const CONFIG_PARSE_RETRY_MILLIS = 25;\n\n/**\n * One read+parse attempt: EITHER a parsed config OR the error that attempt hit, never both.\n * Data-only (per CLAUDE.md, classes for data).\n */\nexport class ConfigParseAttempt {\n constructor(\n readonly config: RawConfigFile | null,\n readonly error: Error | null,\n ) {}\n}\n\n// Raw shape of webpieces.config.json as parsed from JSON, before validation/typing.\n// - `rules` — code-style validators (scope edit/file).\n// - `hookGuards` — git/PR/branch protection guards (scope bash).\n// - `commands` — gated command config the guards point at; `pr-gate` lives inside it. Carried as\n// opaque JSON because its nested `gates` array can't be expressed in the FieldDef\n// schema; validated structurally by validateCommandsSection.\n// - `pr-gate` — DEPRECATED top-level block (pre-migration layout). Read only as a back-compat\n// fallback / to emit a \"move it under commands\" migration error.\n// webpieces-disable no-any-unknown -- consumer JSON config has opaque rule option values\nexport interface RawConfigFile {\n extends?: string;\n rules?: Record<string, Record<string, unknown>>;\n hookGuards?: Record<string, Record<string, unknown>>;\n // webpieces-disable no-any-unknown -- opaque commands JSON, validated by validateCommandsSection\n commands?: unknown;\n // REQUIRED top-level block: two glob lists that suppress hook enforcement per file path.\n // Opaque here (validated structurally by validateExcludePaths, then parsed into ExcludePaths).\n // webpieces-disable no-any-unknown -- opaque excludePaths JSON, validated by validateExcludePaths\n excludePaths?: unknown;\n // REQUIRED top-level array of client-authored content guards (regex patterns + message + scoping).\n // Opaque here; validated structurally by validateMatchRulesSection, then parsed into MatchRuleConfig[].\n // webpieces-disable no-any-unknown -- opaque match-rules JSON, validated by validateMatchRulesSection\n 'match-rules'?: unknown;\n rulesDir?: string[];\n // webpieces-disable no-any-unknown -- DEPRECATED top-level pr-gate, migrated under `commands`\n 'pr-gate'?: unknown;\n}\n\n/**\n * Locates + reads webpieces.config.json. `@injectable(bindingScopeValues.Singleton)` so it can be injected into the config\n * loader and appear in the rules-config DI design.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ConfigFile {\n /** Walk up from `startDir` looking for webpieces.config.json. Returns its absolute path or null. */\n findConfigFile(startDir: string): string | null {\n let dir = startDir;\n while (true) {\n const primary = path.join(dir, CONFIG_FILENAME);\n if (fs.existsSync(primary)) return primary;\n const parent = path.dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n }\n\n /**\n * Read + JSON.parse webpieces.config.json, RETRYING a failed attempt before escalating.\n *\n * A single failed read is not evidence of a broken config: another process on this machine may be\n * mid-write, and a half-written file is unparseable for a few milliseconds and then fine. Only a\n * failure that survives every attempt is treated as real — and then it still throws, so a\n * genuinely invalid config blocks exactly as before. See {@link CONFIG_PARSE_ATTEMPTS}.\n */\n readRawConfig(configPath: string): RawConfigFile {\n let lastError: Error | null = null;\n for (let attempt = 1; attempt <= CONFIG_PARSE_ATTEMPTS; attempt++) {\n if (attempt > 1) this.sleepSync(CONFIG_PARSE_RETRY_MILLIS);\n const outcome = this.attemptReadAndParse(configPath);\n if (outcome.config !== null) return outcome.config;\n lastError = outcome.error;\n }\n throw new InformAiError(this.formatParseFailure(configPath, lastError));\n }\n\n // ONE read+parse attempt. The read is inside the try too: a file being replaced can momentarily\n // fail to open (ENOENT between unlink and rename), which is the same transient class as a\n // half-written parse failure and must be retried the same way.\n private attemptReadAndParse(configPath: string): ConfigParseAttempt {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const raw = this.readFileText(configPath);\n return new ConfigParseAttempt(JSON.parse(raw) as RawConfigFile, null);\n } catch (err: unknown) {\n const error = toError(err);\n return new ConfigParseAttempt(null, error);\n }\n }\n\n /** Read the file's bytes. `protected` so a test can inject a transient failure deterministically. */\n protected readFileText(configPath: string): string {\n return fs.readFileSync(configPath, 'utf8');\n }\n\n /**\n * Block this thread for `millis`. The hook path is synchronous top to bottom (a PreToolUse hook\n * answers on stdout before the tool runs), so an async delay is not available; `Atomics.wait` on a\n * never-notified word is the standard dependency-free synchronous sleep.\n */\n protected sleepSync(millis: number): void {\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, millis);\n }\n\n // The AI-facing message for a parse failure that survived every attempt. It names the retry count\n // on purpose: an agent that sees \"invalid JSON\" for a file that reads fine three seconds later has\n // no way to tell a race from a real syntax error, and the FIRST thing it needs to know is that\n // read-only inspection of the file is still available so it can go look.\n private formatParseFailure(configPath: string, error: Error | null): string {\n return (\n `webpieces.config.json could not be parsed as JSON — retried ${CONFIG_PARSE_ATTEMPTS} times ` +\n `over ~${CONFIG_PARSE_RETRY_MILLIS * (CONFIG_PARSE_ATTEMPTS - 1)}ms and it failed every time.\\n` +\n `Parse error: ${error?.message ?? 'unknown'}\\n` +\n `File: ${configPath}\\n\\n` +\n `Two causes, in the order to check them:\\n` +\n ` 1. GENUINELY INVALID — most likely. Look at the file: a trailing comma, a missing brace, ` +\n `or leftover conflict markers (\\`<<<<<<< HEAD\\`) from a merge you are in the middle of.\\n` +\n ` 2. STILL BEING WRITTEN by another process (another agent/worktree on this machine, a dep ` +\n `bump, an editor save). ${CONFIG_PARSE_ATTEMPTS} attempts already ruled out a brief write, but a ` +\n `long-running writer can outlast them — if so, simply retrying your command now will succeed.\\n\\n` +\n `👉 READING AND EDITING ${CONFIG_FILENAME} IS ALWAYS ALLOWED, including right now: \\`Read\\`, ` +\n `\\`cat\\`, \\`grep\\`, \\`sed -n\\` and the other read-only inspection commands still work while the ` +\n `config is broken. Go look at the file, fix it, then retry. (Writes to OTHER files stay ` +\n `blocked — with an unparseable config every guard is disabled, so nothing else may proceed.)`\n );\n }\n}\n\n// Temporary migration delegators — consumers migrate to injecting ConfigFile over follow-up PRs, then\n// these free functions are removed. Declarations kept identical to the originals (unchanged lines).\nconst configFileSvc = new ConfigFile();\n\n/**\n * Walk up from `startDir` looking for webpieces.config.json. Returns its absolute path or null.\n */\nexport function findConfigFile(startDir: string): string | null {\n return configFileSvc.findConfigFile(startDir);\n}\n\n/**\n * Read + JSON.parse webpieces.config.json, surfacing parse failures as a readable InformAiError.\n */\nexport function readRawConfig(configPath: string): RawConfigFile {\n return configFileSvc.readRawConfig(configPath);\n}\n"]}
1
+ {"version":3,"file":"config-file.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/config-file.ts"],"names":[],"mappings":";;;AA+JA,wCAEC;AAKD,sCAEC;;AAxKD,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAE3D,8DAA0D;AAC1D,iEAA6D;AAEhD,QAAA,eAAe,GAAG,uBAAuB,CAAC;AAEvD;;;;;;;;;GASG;AACU,QAAA,qBAAqB,GAAG,CAAC,CAAC;AAEvC,uGAAuG;AAC1F,QAAA,yBAAyB,GAAG,EAAE,CAAC;AAE5C;;;GAGG;AACH,MAAa,kBAAkB;IAEd;IACA;IAFb,YACa,MAA4B,EAC5B,KAAmB;QADnB,WAAM,GAAN,MAAM,CAAsB;QAC5B,UAAK,GAAL,KAAK,CAAc;IAC7B,CAAC;CACP;AALD,gDAKC;AA8BD;;;GAGG;AAEI,IAAM,UAAU,GAAhB,MAAM,UAAU;IACnB,oGAAoG;IACpG,cAAc,CAAC,QAAgB;QAC3B,IAAI,GAAG,GAAG,QAAQ,CAAC;QACnB,OAAO,IAAI,EAAE,CAAC;YACV,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,uBAAe,CAAC,CAAC;YAChD,IAAI,EAAE,CAAC,UAAU,CAAC,OAAO,CAAC;gBAAE,OAAO,OAAO,CAAC;YAC3C,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;YACjC,IAAI,MAAM,KAAK,GAAG;gBAAE,OAAO,IAAI,CAAC;YAChC,GAAG,GAAG,MAAM,CAAC;QACjB,CAAC;IACL,CAAC;IAED;;;;;;;OAOG;IACH,aAAa,CAAC,UAAkB;QAC5B,IAAI,SAAS,GAAiB,IAAI,CAAC;QACnC,KAAK,IAAI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AED,kGAAkG;IAClG,mGAAmG;IACnG,+FAA+F;IAC/F,yEAAyE;IACjE,kBAAkB,CAAC,UAAkB,EAAE,KAAmB;QAC9D,OAAO,CACH,+DAA+D,6BAAqB,SAAS;YAC7F,SAAS,iCAAyB,GAAG,CAAC,6BAAqB,GAAG,CAAC,CAAC,gCAAgC;YAChG,gBAAgB,KAAK,EAAE,OAAO,IAAI,SAAS,IAAI;YAC/C,SAAS,UAAU,MAAM;YACzB,2CAA2C;YAC3C,6FAA6F;YAC7F,0FAA0F;YAC1F,6FAA6F;YAC7F,0BAA0B,6BAAqB,mDAAmD;YAClG,kGAAkG;YAClG,0BAA0B,uBAAe,qDAAqD;YAC9F,iGAAiG;YACjG,yFAAyF;YACzF,6FAA6F,CAChG,CAAC;IACN,CAAC;CACJ,CAAA;AAlFY,gCAAU;qBAAV,UAAU;IADtB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;GAC5B,UAAU,CAkFtB;AAED,sGAAsG;AACtG,oGAAoG;AACpG,MAAM,aAAa,GAAG,IAAI,UAAU,EAAE,CAAC;AAEvC;;GAEG;AACH,SAAgB,cAAc,CAAC,QAAgB;IAC3C,OAAO,aAAa,CAAC,cAAc,CAAC,QAAQ,CAAC,CAAC;AAClD,CAAC;AAED;;GAEG;AACH,SAAgB,aAAa,CAAC,UAAkB;IAC5C,OAAO,aAAa,CAAC,aAAa,CAAC,UAAU,CAAC,CAAC;AACnD,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { InformAiError } from '@webpieces/tooling-common';\nimport { toError } from '@webpieces/tooling-common/to-error';\n\nexport const CONFIG_FILENAME = 'webpieces.config.json';\n\n/**\n * How many times a read+parse of webpieces.config.json is attempted before the failure is treated as\n * REAL. On a machine running several agents at once the file is routinely rewritten underneath us\n * (a dep bump, another worktree's `wp-*` command, an editor's write-then-rename), and for the few\n * milliseconds of that write the bytes on disk are a truncated/half-written JSON document. Reading\n * exactly then produced a hard block that self-healed seconds later — a false positive that also\n * blocked the tools needed to look into it. Three attempts spanning ~50ms covers a normal write with\n * a cost no human or agent can perceive, and cannot mask a file that is genuinely malformed (a\n * conflict-marked or typo'd config fails all three, identically, and still blocks).\n */\nexport const CONFIG_PARSE_ATTEMPTS = 3;\n\n/** Pause between parse attempts. Small enough to be invisible, long enough to outlast a file write. */\nexport const CONFIG_PARSE_RETRY_MILLIS = 25;\n\n/**\n * One read+parse attempt: EITHER a parsed config OR the error that attempt hit, never both.\n * Data-only (per CLAUDE.md, classes for data).\n */\nexport class ConfigParseAttempt {\n constructor(\n readonly config: RawConfigFile | null,\n readonly error: Error | null,\n ) {}\n}\n\n// Raw shape of webpieces.config.json as parsed from JSON, before validation/typing.\n// - `rules` — code-style validators (scope edit/file).\n// - `hookGuards` — git/PR/branch protection guards (scope bash).\n// - `commands` — gated command config the guards point at; `pr-gate` lives inside it. Carried as\n// opaque JSON because its nested `gates` array can't be expressed in the FieldDef\n// schema; validated structurally by validateCommandsSection.\n// - `pr-gate` — DEPRECATED top-level block (pre-migration layout). Read only as a back-compat\n// fallback / to emit a \"move it under commands\" migration error.\n// webpieces-disable no-any-unknown -- consumer JSON config has opaque rule option values\nexport interface RawConfigFile {\n extends?: string;\n rules?: Record<string, Record<string, unknown>>;\n hookGuards?: Record<string, Record<string, unknown>>;\n // webpieces-disable no-any-unknown -- opaque commands JSON, validated by validateCommandsSection\n commands?: unknown;\n // REQUIRED top-level block: two glob lists that suppress hook enforcement per file path.\n // Opaque here (validated structurally by validateExcludePaths, then parsed into ExcludePaths).\n // webpieces-disable no-any-unknown -- opaque excludePaths JSON, validated by validateExcludePaths\n excludePaths?: unknown;\n // REQUIRED top-level array of client-authored content guards (regex patterns + message + scoping).\n // Opaque here; validated structurally by validateMatchRulesSection, then parsed into MatchRuleConfig[].\n // webpieces-disable no-any-unknown -- opaque match-rules JSON, validated by validateMatchRulesSection\n 'match-rules'?: unknown;\n rulesDir?: string[];\n // webpieces-disable no-any-unknown -- DEPRECATED top-level pr-gate, migrated under `commands`\n 'pr-gate'?: unknown;\n}\n\n/**\n * Locates + reads webpieces.config.json. `@injectable(bindingScopeValues.Singleton)` so it can be injected into the config\n * loader and appear in the rules-config DI design.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ConfigFile {\n /** Walk up from `startDir` looking for webpieces.config.json. Returns its absolute path or null. */\n findConfigFile(startDir: string): string | null {\n let dir = startDir;\n while (true) {\n const primary = path.join(dir, CONFIG_FILENAME);\n if (fs.existsSync(primary)) return primary;\n const parent = path.dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n }\n\n /**\n * Read + JSON.parse webpieces.config.json, RETRYING a failed attempt before escalating.\n *\n * A single failed read is not evidence of a broken config: another process on this machine may be\n * mid-write, and a half-written file is unparseable for a few milliseconds and then fine. Only a\n * failure that survives every attempt is treated as real — and then it still throws, so a\n * genuinely invalid config blocks exactly as before. See {@link CONFIG_PARSE_ATTEMPTS}.\n */\n readRawConfig(configPath: string): RawConfigFile {\n let lastError: Error | null = null;\n for (let attempt = 1; attempt <= CONFIG_PARSE_ATTEMPTS; attempt++) {\n if (attempt > 1) this.sleepSync(CONFIG_PARSE_RETRY_MILLIS);\n const outcome = this.attemptReadAndParse(configPath);\n if (outcome.config !== null) return outcome.config;\n lastError = outcome.error;\n }\n throw new InformAiError(this.formatParseFailure(configPath, lastError));\n }\n\n // ONE read+parse attempt. The read is inside the try too: a file being replaced can momentarily\n // fail to open (ENOENT between unlink and rename), which is the same transient class as a\n // half-written parse failure and must be retried the same way.\n private attemptReadAndParse(configPath: string): ConfigParseAttempt {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const raw = this.readFileText(configPath);\n return new ConfigParseAttempt(JSON.parse(raw) as RawConfigFile, null);\n } catch (err: unknown) {\n const error = toError(err);\n return new ConfigParseAttempt(null, error);\n }\n }\n\n /** Read the file's bytes. `protected` so a test can inject a transient failure deterministically. */\n protected readFileText(configPath: string): string {\n return fs.readFileSync(configPath, 'utf8');\n }\n\n /**\n * Block this thread for `millis`. The hook path is synchronous top to bottom (a PreToolUse hook\n * answers on stdout before the tool runs), so an async delay is not available; `Atomics.wait` on a\n * never-notified word is the standard dependency-free synchronous sleep.\n */\n protected sleepSync(millis: number): void {\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, millis);\n }\n\n // The AI-facing message for a parse failure that survived every attempt. It names the retry count\n // on purpose: an agent that sees \"invalid JSON\" for a file that reads fine three seconds later has\n // no way to tell a race from a real syntax error, and the FIRST thing it needs to know is that\n // read-only inspection of the file is still available so it can go look.\n private formatParseFailure(configPath: string, error: Error | null): string {\n return (\n `webpieces.config.json could not be parsed as JSON — retried ${CONFIG_PARSE_ATTEMPTS} times ` +\n `over ~${CONFIG_PARSE_RETRY_MILLIS * (CONFIG_PARSE_ATTEMPTS - 1)}ms and it failed every time.\\n` +\n `Parse error: ${error?.message ?? 'unknown'}\\n` +\n `File: ${configPath}\\n\\n` +\n `Two causes, in the order to check them:\\n` +\n ` 1. GENUINELY INVALID — most likely. Look at the file: a trailing comma, a missing brace, ` +\n `or leftover conflict markers (\\`<<<<<<< HEAD\\`) from a merge you are in the middle of.\\n` +\n ` 2. STILL BEING WRITTEN by another process (another agent/worktree on this machine, a dep ` +\n `bump, an editor save). ${CONFIG_PARSE_ATTEMPTS} attempts already ruled out a brief write, but a ` +\n `long-running writer can outlast them — if so, simply retrying your command now will succeed.\\n\\n` +\n `👉 READING AND EDITING ${CONFIG_FILENAME} IS ALWAYS ALLOWED, including right now: \\`Read\\`, ` +\n `\\`cat\\`, \\`grep\\`, \\`sed -n\\` and the other read-only inspection commands still work while the ` +\n `config is broken. Go look at the file, fix it, then retry. (Writes to OTHER files stay ` +\n `blocked — with an unparseable config every guard is disabled, so nothing else may proceed.)`\n );\n }\n}\n\n// Temporary migration delegators — consumers migrate to injecting ConfigFile over follow-up PRs, then\n// these free functions are removed. Declarations kept identical to the originals (unchanged lines).\nconst configFileSvc = new ConfigFile();\n\n/**\n * Walk up from `startDir` looking for webpieces.config.json. Returns its absolute path or null.\n */\nexport function findConfigFile(startDir: string): string | null {\n return configFileSvc.findConfigFile(startDir);\n}\n\n/**\n * Read + JSON.parse webpieces.config.json, surfacing parse failures as a readable InformAiError.\n */\nexport function readRawConfig(configPath: string): RawConfigFile {\n return configFileSvc.readRawConfig(configPath);\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { AtomicFile } from './atomic-file';
1
+ import { AtomicFile } from '@webpieces/tooling-common';
2
2
  import { ConfigFile } from './config-file';
3
3
  /**
4
4
  * `wp-prune-unknown-config` — the MECHANICAL cure for "[x] Unknown rule".
@@ -4,7 +4,7 @@ exports.ConfigPruner = exports.PruneResult = exports.PrunedKey = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const fs = tslib_1.__importStar(require("fs"));
6
6
  const inversify_1 = require("inversify");
7
- const atomic_file_1 = require("./atomic-file");
7
+ const tooling_common_1 = require("@webpieces/tooling-common");
8
8
  const config_file_1 = require("./config-file");
9
9
  const constants_1 = require("./constants");
10
10
  const rule_schemas_1 = require("./rule-schemas");
@@ -177,6 +177,6 @@ exports.ConfigPruner = ConfigPruner;
177
177
  exports.ConfigPruner = ConfigPruner = tslib_1.__decorate([
178
178
  (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
179
179
  tslib_1.__metadata("design:paramtypes", [config_file_1.ConfigFile,
180
- atomic_file_1.AtomicFile])
180
+ tooling_common_1.AtomicFile])
181
181
  ], ConfigPruner);
182
182
  //# sourceMappingURL=config-pruner.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"config-pruner.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/config-pruner.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,yCAA2D;AAE3D,+CAA2C;AAC3C,+CAA2C;AAC3C,2CAAoD;AACpD,iDAA8C;AAC9C,+DAAgF;AAEhF;;;;;;;;;;;;;;;;;;;;;;;;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,KAAK,KAAK,wCAAkB,IAAI,CAAC,CAAC,GAAG,KAAK,GAAG,CAAC,CAAC;QAC1D,IAAI,OAAO,EAAE,CAAC;YACV,IAAI,CAAC,OAAO,CAAC,QAAQ;gBAAE,OAAO,IAAI,CAAC;YACnC,OAAO,OAAO,CAAC,OAAO,KAAK,EAAE;gBACzB,CAAC,CAAC,yCAAyC;gBAC3C,CAAC,CAAC,sCAAsC,OAAO,CAAC,OAAO,EAAE,CAAC;QAClE,CAAC;QACD,OAAO,+DAA+D,CAAC;IAC3E,CAAC;IAED;;;OAGG;IACK,QAAQ,CAAC,IAAY;QACzB,MAAM,KAAK,GAAG,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACnC,IAAI,KAAK,KAAK,IAAI;YAAE,OAAO,CAAC,CAAC;QAC7B,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;IAC3B,CAAC;CACJ,CAAA;AArFY,oCAAY;uBAAZ,YAAY;IADxB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGJ,wBAAU;QACV,wBAAU;GAHlC,YAAY,CAqFxB","sourcesContent":["import * as fs from 'fs';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { AtomicFile } from './atomic-file';\nimport { ConfigFile } from './config-file';\nimport { PRUNE_UNKNOWN_COMMAND } from './constants';\nimport { RULE_SCHEMAS } from './rule-schemas';\nimport { RETIRED_CONFIG_KEYS, RETIRED_SCOPE_RULE } from './retired-config-keys';\n\n/**\n * `wp-prune-unknown-config` — the MECHANICAL cure for \"[x] Unknown rule\".\n *\n * ## Why a command and not just advice\n *\n * An unknown key controls nothing, so deleting it is the fix, and the validator now says so. But the\n * moment that advice is read is the worst possible moment to act on it by hand: the hook guard denies\n * every Bash call while the config is invalid, so the reader is editing JSON blind, with no way to\n * re-run the validator between edits. Making the cleanup one command means cleanliness is the default\n * path rather than a judgement call taken under a total block — and it makes \"the file validates\" mean\n * \"every key in it is real\", which is the property that keeps dead config from reading as live config.\n *\n * ## What it removes, and what it deliberately does NOT\n *\n * Removed, from the `rules` and `hookGuards` sections only:\n * - a name with no entry in RULE_SCHEMAS and no entry in RETIRED_CONFIG_KEYS (a typo, or a rule some\n * release deleted). Nothing reads it, by construction.\n * - a name in RETIRED_CONFIG_KEYS whose entry is `prunable` — the retirement's own instruction is\n * \"delete this entry\", because the setting left webpieces.config.json entirely.\n *\n * NOT removed:\n * - a RENAME or an in-file move (`prunable: false`). Deleting those discards a value the new key still\n * needs, so they keep their migration instruction and a human/agent applies it.\n * - anything at all when `rulesDir` is configured. A custom rule legitimately has no built-in schema,\n * and this command must never eat one.\n * - top-level keys, `commands`, `excludePaths`, `match-rules`. Those are validated by shape, not by a\n * name table, so \"unknown\" is not defined for them and a pruner would be guessing.\n *\n * ## The one destructive case, and why the drift guard already covers it\n *\n * A key CAN be valid-but-unlearned when package.json pins an @webpieces older than the config. Pruning\n * then would delete live config. That case cannot reach here: the shim's version-drift guard compares\n * the pin against the installed version and denies every tool call — including this one — before the\n * validator or this command ever runs. It is also why `PruneResult` names every key it removed rather\n * than reporting a count: a silent sweep is the thing that would make the rare case unrecoverable.\n */\n\n/** One key this run removed, and the reason it was safe to remove. Data-only (per CLAUDE.md). */\nexport class PrunedKey {\n /** `rules` or `hookGuards` — the section the key sat in. */\n section: string;\n /** The rule/guard name exactly as it appeared in the file. */\n key: string;\n /** Human-readable justification, printed per key so no removal is silent. */\n reason: string;\n\n constructor(section: string, key: string, reason: string) {\n this.section = section;\n this.key = key;\n this.reason = reason;\n }\n}\n\n/** The outcome of one prune. Data-only. */\nexport class PruneResult {\n /** The webpieces.config.json that was inspected. */\n configPath: string;\n removed: PrunedKey[];\n\n constructor(configPath: string, removed: PrunedKey[]) {\n this.configPath = configPath;\n this.removed = removed;\n }\n\n /** True when the file was rewritten. */\n changed(): boolean {\n return this.removed.length > 0;\n }\n\n /** The report the CLI prints. Every removed key is named; nothing is summarised away. */\n describeSelf(): string {\n if (!this.changed()) {\n return `[${PRUNE_UNKNOWN_COMMAND}] No unknown keys in ${this.configPath} — nothing to remove.`;\n }\n const lines = this.removed.map((r: PrunedKey): string => ` • ${r.section}.${r.key} — ${r.reason}`);\n return `[${PRUNE_UNKNOWN_COMMAND}] Removed ${this.removed.length} unknown key(s) from ` +\n `${this.configPath}:\\n${lines.join('\\n')}`;\n }\n}\n\n/** The sections a rule/guard name may legally sit in — the only two this command touches. */\nconst PRUNABLE_SECTIONS: readonly string[] = ['rules', 'hookGuards'];\n\n@injectable(bindingScopeValues.Singleton)\nexport class ConfigPruner {\n constructor(\n private readonly configFile: ConfigFile,\n private readonly atomicFile: AtomicFile,\n ) {}\n\n /**\n * Strip every unknown key from the webpieces.config.json above `cwd` and rewrite it. Throws when no\n * config file is found — a prune with no target is a mistake, not a no-op.\n */\n pruneFrom(cwd: string): PruneResult {\n const configPath = this.configFile.findConfigFile(cwd);\n if (configPath === null) {\n throw new Error(`[${PRUNE_UNKNOWN_COMMAND}] No webpieces.config.json found above ${cwd}.`);\n }\n return this.prune(configPath);\n }\n\n /**\n * Strip every unknown key from `configPath` and rewrite it in place. Reads the file directly rather\n * than through the loader: the loader VALIDATES, and this command's whole purpose is to run on a\n * file that fails validation.\n */\n prune(configPath: string): PruneResult {\n const text = fs.readFileSync(configPath, 'utf8');\n // webpieces-disable no-any-unknown -- the raw config document is opaque JSON until narrowed below\n const parsed: unknown = JSON.parse(text);\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n throw new Error(`[${PRUNE_UNKNOWN_COMMAND}] ${configPath} is not a JSON object.`);\n }\n // webpieces-disable no-any-unknown -- narrowed to a non-null, non-array object one line above\n const document = parsed as Record<string, unknown>;\n const removed = this.removeUnknown(document);\n if (removed.length > 0) {\n this.atomicFile.writeAtomic(configPath, JSON.stringify(document, null, this.indentOf(text)) + '\\n');\n }\n return new PruneResult(configPath, removed);\n }\n\n /** Mutates `document`, deleting every prunable name from the two rule sections. */\n // webpieces-disable no-any-unknown -- opaque parsed config document\n private removeUnknown(document: Record<string, unknown>): PrunedKey[] {\n // A custom rules directory means a name with no built-in schema may be entirely legitimate.\n const rulesDir = document['rulesDir'];\n if (Array.isArray(rulesDir) && rulesDir.length > 0) return [];\n\n const removed: PrunedKey[] = [];\n for (const sectionName of PRUNABLE_SECTIONS) {\n const section = document[sectionName];\n if (typeof section !== 'object' || section === null || Array.isArray(section)) continue;\n // webpieces-disable no-any-unknown -- narrowed to a non-null, non-array object one line above\n const entries = section as Record<string, unknown>;\n for (const key of Object.keys(entries)) {\n const reason = this.reasonToRemove(key);\n if (reason === null) continue;\n delete entries[key];\n removed.push(new PrunedKey(sectionName, key, reason));\n }\n }\n return removed;\n }\n\n /** Why `key` is safe to delete, or null when it must be kept. */\n private reasonToRemove(key: string): string | null {\n if (RULE_SCHEMAS[key]) return null;\n const retired = RETIRED_CONFIG_KEYS.find(\n e => e.scope === RETIRED_SCOPE_RULE && e.key === key);\n if (retired) {\n if (!retired.prunable) return null;\n return retired.movedTo === ''\n ? 'RETIRED and removed with no replacement'\n : `RETIRED — the setting now lives at ${retired.movedTo}`;\n }\n return 'no running validator has a schema for it, so nothing reads it';\n }\n\n /**\n * The file's own indentation, so a prune does not reformat every line it did not touch. Falls back to\n * 4 (the shape every webpieces.config.json in the wild uses) when the document is single-line.\n */\n private indentOf(text: string): number {\n const match = /\\n( +)\"/.exec(text);\n if (match === null) return 4;\n return match[1].length;\n }\n}\n"]}
1
+ {"version":3,"file":"config-pruner.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/config-pruner.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,yCAA2D;AAE3D,8DAAuD;AACvD,+CAA2C;AAC3C,2CAAoD;AACpD,iDAA8C;AAC9C,+DAAgF;AAEhF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AAEH,iGAAiG;AACjG,MAAa,SAAS;IAClB,4DAA4D;IAC5D,OAAO,CAAS;IAChB,8DAA8D;I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ACV,IAAI,CAAC,OAAO,CAAC,QAAQ;gBAAE,OAAO,IAAI,CAAC;YACnC,OAAO,OAAO,CAAC,OAAO,KAAK,EAAE;gBACzB,CAAC,CAAC,yCAAyC;gBAC3C,CAAC,CAAC,sCAAsC,OAAO,CAAC,OAAO,EAAE,CAAC;QAClE,CAAC;QACD,OAAO,+DAA+D,CAAC;IAC3E,CAAC;IAED;;;OAGG;IACK,QAAQ,CAAC,IAAY;QACzB,MAAM,KAAK,GAAG,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACnC,IAAI,KAAK,KAAK,IAAI;YAAE,OAAO,CAAC,CAAC;QAC7B,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;IAC3B,CAAC;CACJ,CAAA;AArFY,oCAAY;uBAAZ,YAAY;IADxB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGJ,wBAAU;QACV,2BAAU;GAHlC,YAAY,CAqFxB","sourcesContent":["import * as fs from 'fs';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { AtomicFile } from '@webpieces/tooling-common';\nimport { ConfigFile } from './config-file';\nimport { PRUNE_UNKNOWN_COMMAND } from './constants';\nimport { RULE_SCHEMAS } from './rule-schemas';\nimport { RETIRED_CONFIG_KEYS, RETIRED_SCOPE_RULE } from './retired-config-keys';\n\n/**\n * `wp-prune-unknown-config` — the MECHANICAL cure for \"[x] Unknown rule\".\n *\n * ## Why a command and not just advice\n *\n * An unknown key controls nothing, so deleting it is the fix, and the validator now says so. But the\n * moment that advice is read is the worst possible moment to act on it by hand: the hook guard denies\n * every Bash call while the config is invalid, so the reader is editing JSON blind, with no way to\n * re-run the validator between edits. Making the cleanup one command means cleanliness is the default\n * path rather than a judgement call taken under a total block — and it makes \"the file validates\" mean\n * \"every key in it is real\", which is the property that keeps dead config from reading as live config.\n *\n * ## What it removes, and what it deliberately does NOT\n *\n * Removed, from the `rules` and `hookGuards` sections only:\n * - a name with no entry in RULE_SCHEMAS and no entry in RETIRED_CONFIG_KEYS (a typo, or a rule some\n * release deleted). Nothing reads it, by construction.\n * - a name in RETIRED_CONFIG_KEYS whose entry is `prunable` — the retirement's own instruction is\n * \"delete this entry\", because the setting left webpieces.config.json entirely.\n *\n * NOT removed:\n * - a RENAME or an in-file move (`prunable: false`). Deleting those discards a value the new key still\n * needs, so they keep their migration instruction and a human/agent applies it.\n * - anything at all when `rulesDir` is configured. A custom rule legitimately has no built-in schema,\n * and this command must never eat one.\n * - top-level keys, `commands`, `excludePaths`, `match-rules`. Those are validated by shape, not by a\n * name table, so \"unknown\" is not defined for them and a pruner would be guessing.\n *\n * ## The one destructive case, and why the drift guard already covers it\n *\n * A key CAN be valid-but-unlearned when package.json pins an @webpieces older than the config. Pruning\n * then would delete live config. That case cannot reach here: the shim's version-drift guard compares\n * the pin against the installed version and denies every tool call — including this one — before the\n * validator or this command ever runs. It is also why `PruneResult` names every key it removed rather\n * than reporting a count: a silent sweep is the thing that would make the rare case unrecoverable.\n */\n\n/** One key this run removed, and the reason it was safe to remove. Data-only (per CLAUDE.md). */\nexport class PrunedKey {\n /** `rules` or `hookGuards` — the section the key sat in. */\n section: string;\n /** The rule/guard name exactly as it appeared in the file. */\n key: string;\n /** Human-readable justification, printed per key so no removal is silent. */\n reason: string;\n\n constructor(section: string, key: string, reason: string) {\n this.section = section;\n this.key = key;\n this.reason = reason;\n }\n}\n\n/** The outcome of one prune. Data-only. */\nexport class PruneResult {\n /** The webpieces.config.json that was inspected. */\n configPath: string;\n removed: PrunedKey[];\n\n constructor(configPath: string, removed: PrunedKey[]) {\n this.configPath = configPath;\n this.removed = removed;\n }\n\n /** True when the file was rewritten. */\n changed(): boolean {\n return this.removed.length > 0;\n }\n\n /** The report the CLI prints. Every removed key is named; nothing is summarised away. */\n describeSelf(): string {\n if (!this.changed()) {\n return `[${PRUNE_UNKNOWN_COMMAND}] No unknown keys in ${this.configPath} — nothing to remove.`;\n }\n const lines = this.removed.map((r: PrunedKey): string => ` • ${r.section}.${r.key} — ${r.reason}`);\n return `[${PRUNE_UNKNOWN_COMMAND}] Removed ${this.removed.length} unknown key(s) from ` +\n `${this.configPath}:\\n${lines.join('\\n')}`;\n }\n}\n\n/** The sections a rule/guard name may legally sit in — the only two this command touches. */\nconst PRUNABLE_SECTIONS: readonly string[] = ['rules', 'hookGuards'];\n\n@injectable(bindingScopeValues.Singleton)\nexport class ConfigPruner {\n constructor(\n private readonly configFile: ConfigFile,\n private readonly atomicFile: AtomicFile,\n ) {}\n\n /**\n * Strip every unknown key from the webpieces.config.json above `cwd` and rewrite it. Throws when no\n * config file is found — a prune with no target is a mistake, not a no-op.\n */\n pruneFrom(cwd: string): PruneResult {\n const configPath = this.configFile.findConfigFile(cwd);\n if (configPath === null) {\n throw new Error(`[${PRUNE_UNKNOWN_COMMAND}] No webpieces.config.json found above ${cwd}.`);\n }\n return this.prune(configPath);\n }\n\n /**\n * Strip every unknown key from `configPath` and rewrite it in place. Reads the file directly rather\n * than through the loader: the loader VALIDATES, and this command's whole purpose is to run on a\n * file that fails validation.\n */\n prune(configPath: string): PruneResult {\n const text = fs.readFileSync(configPath, 'utf8');\n // webpieces-disable no-any-unknown -- the raw config document is opaque JSON until narrowed below\n const parsed: unknown = JSON.parse(text);\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n throw new Error(`[${PRUNE_UNKNOWN_COMMAND}] ${configPath} is not a JSON object.`);\n }\n // webpieces-disable no-any-unknown -- narrowed to a non-null, non-array object one line above\n const document = parsed as Record<string, unknown>;\n const removed = this.removeUnknown(document);\n if (removed.length > 0) {\n this.atomicFile.writeAtomic(configPath, JSON.stringify(document, null, this.indentOf(text)) + '\\n');\n }\n return new PruneResult(configPath, removed);\n }\n\n /** Mutates `document`, deleting every prunable name from the two rule sections. */\n // webpieces-disable no-any-unknown -- opaque parsed config document\n private removeUnknown(document: Record<string, unknown>): PrunedKey[] {\n // A custom rules directory means a name with no built-in schema may be entirely legitimate.\n const rulesDir = document['rulesDir'];\n if (Array.isArray(rulesDir) && rulesDir.length > 0) return [];\n\n const removed: PrunedKey[] = [];\n for (const sectionName of PRUNABLE_SECTIONS) {\n const section = document[sectionName];\n if (typeof section !== 'object' || section === null || Array.isArray(section)) continue;\n // webpieces-disable no-any-unknown -- narrowed to a non-null, non-array object one line above\n const entries = section as Record<string, unknown>;\n for (const key of Object.keys(entries)) {\n const reason = this.reasonToRemove(key);\n if (reason === null) continue;\n delete entries[key];\n removed.push(new PrunedKey(sectionName, key, reason));\n }\n }\n return removed;\n }\n\n /** Why `key` is safe to delete, or null when it must be kept. */\n private reasonToRemove(key: string): string | null {\n if (RULE_SCHEMAS[key]) return null;\n const retired = RETIRED_CONFIG_KEYS.find(\n e => e.scope === RETIRED_SCOPE_RULE && e.key === key);\n if (retired) {\n if (!retired.prunable) return null;\n return retired.movedTo === ''\n ? 'RETIRED and removed with no replacement'\n : `RETIRED — the setting now lives at ${retired.movedTo}`;\n }\n return 'no running validator has a schema for it, so nothing reads it';\n }\n\n /**\n * The file's own indentation, so a prune does not reformat every line it did not touch. Falls back to\n * 4 (the shape every webpieces.config.json in the wild uses) when the document is single-line.\n */\n private indentOf(text: string): number {\n const match = /\\n( +)\"/.exec(text);\n if (match === null) return 4;\n return match[1].length;\n }\n}\n"]}
@@ -36,9 +36,7 @@ export declare const RULE_NAMES: {
36
36
  readonly FRAMEWORK_TSCONFIG: "framework-tsconfig";
37
37
  readonly FRAMEWORK_PACKAGES: "framework-packages";
38
38
  };
39
- export declare const WEBPIECES_TMP_DIR = ".webpieces";
40
39
  export declare const MERGE_INFO_DIR = "merge-info";
41
- export declare const PR_REVIEW_DIR = "pr-review";
42
40
  export declare const MERGE_IN_PROGRESS_FILE = "merge-in-progress.json";
43
41
  export declare const PUSH_DEV_STATE_FILE = "push-dev-in-progress.json";
44
42
  export declare const MERGE_EXPLANATION_FILE = "merge-explanation.md";
package/src/constants.js CHANGED
@@ -6,7 +6,7 @@
6
6
  // The legacy `ai-hook-disable` alias and the `-file`/`-next`/`-all` variants and the
7
7
  // `*`/bare (no-rule) wildcard have been removed — every disable MUST name a rule.
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.UPGRADE_SHIM_COMMAND = exports.PRUNE_UNKNOWN_COMMAND = exports.MERGE_EXPLANATION_FILE = exports.PUSH_DEV_STATE_FILE = exports.MERGE_IN_PROGRESS_FILE = exports.PR_REVIEW_DIR = exports.MERGE_INFO_DIR = exports.WEBPIECES_TMP_DIR = exports.RULE_NAMES = exports.WEBPIECES_DISABLE = void 0;
9
+ exports.UPGRADE_SHIM_COMMAND = exports.PRUNE_UNKNOWN_COMMAND = exports.MERGE_EXPLANATION_FILE = exports.PUSH_DEV_STATE_FILE = exports.MERGE_IN_PROGRESS_FILE = exports.MERGE_INFO_DIR = exports.RULE_NAMES = exports.WEBPIECES_DISABLE = void 0;
10
10
  exports.hasDisable = hasDisable;
11
11
  exports.WEBPIECES_DISABLE = 'webpieces-disable';
12
12
  // Rule-name tokens as they appear AFTER `webpieces-disable` in a disable comment.
@@ -66,12 +66,10 @@ exports.RULE_NAMES = {
66
66
  // `DotWebpieces.aiWritable()` (this worktree's state that a CODING AGENT writes) so the call site
67
67
  // declares its scope. In a linked worktree the three resolve to different places, and getting that
68
68
  // silently wrong is the bug those methods exist to prevent.
69
- exports.WEBPIECES_TMP_DIR = '.webpieces';
70
69
  exports.MERGE_INFO_DIR = 'merge-info';
71
70
  // The PR working home. Renamed from the legacy `pr-info` to `pr-review` for clarity (it holds the
72
71
  // AI's PR review + rendered body). Old `pr-info/` dirs are gitignored local state and self-clear via
73
72
  // cleanTmp's legacy `pr-` sweep.
74
- exports.PR_REVIEW_DIR = 'pr-review';
75
73
  exports.MERGE_IN_PROGRESS_FILE = 'merge-in-progress.json';
76
74
  // The dev-deploy resolve state file, written by `wp-push-dev --resolve` and cleared by
77
75
  // `wp-finish-push-dev` (or `--abort`). Named here for the same reason MERGE_IN_PROGRESS_FILE is: the