@webpieces/rules-config 0.4.910 → 0.4.912

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 (95) hide show
  1. package/package.json +7 -6
  2. package/src/aged-tree-sweep.d.ts +2 -2
  3. package/src/aged-tree-sweep.js +2 -2
  4. package/src/aged-tree-sweep.js.map +1 -1
  5. package/src/build-log-doc.d.ts +1 -1
  6. package/src/build-log-doc.js +3 -3
  7. package/src/build-log-doc.js.map +1 -1
  8. package/src/builds-log.d.ts +2 -2
  9. package/src/builds-log.js +2 -2
  10. package/src/builds-log.js.map +1 -1
  11. package/src/checklist-override.d.ts +1 -1
  12. package/src/checklist-override.js +1 -1
  13. package/src/checklist-override.js.map +1 -1
  14. package/src/config-error-banner.js +1 -1
  15. package/src/config-error-banner.js.map +1 -1
  16. package/src/config-repair-bootstrap-source.d.ts +1 -1
  17. package/src/config-repair-bootstrap-source.js +1 -1
  18. package/src/config-repair-bootstrap-source.js.map +1 -1
  19. package/src/config-repair-probe.js +3 -3
  20. package/src/config-repair-probe.js.map +1 -1
  21. package/src/constants.js +3 -3
  22. package/src/constants.js.map +1 -1
  23. package/src/exclude-hook-paths.d.ts +5 -5
  24. package/src/exclude-hook-paths.js +5 -5
  25. package/src/exclude-hook-paths.js.map +1 -1
  26. package/src/exclude-paths.d.ts +1 -1
  27. package/src/exclude-paths.js +1 -1
  28. package/src/exclude-paths.js.map +1 -1
  29. package/src/hook-fault-codes.js.map +1 -1
  30. package/src/index.js +5 -5
  31. package/src/index.js.map +1 -1
  32. package/src/instruct-ai-docs.d.ts +3 -3
  33. package/src/instruct-ai-docs.js +3 -3
  34. package/src/instruct-ai-docs.js.map +1 -1
  35. package/src/legacy-config-upgrade.js +2 -2
  36. package/src/legacy-config-upgrade.js.map +1 -1
  37. package/src/load-config.js +3 -0
  38. package/src/load-config.js.map +1 -1
  39. package/src/load-template.d.ts +1 -1
  40. package/src/load-template.js +2 -2
  41. package/src/load-template.js.map +1 -1
  42. package/src/merge-process-doc.d.ts +1 -1
  43. package/src/merge-process-doc.js +2 -2
  44. package/src/merge-process-doc.js.map +1 -1
  45. package/src/migrate-dirs-cli.d.ts +4 -0
  46. package/src/migrate-dirs-cli.js +32 -0
  47. package/src/migrate-dirs-cli.js.map +1 -0
  48. package/src/orphan-dir-archive.d.ts +4 -4
  49. package/src/orphan-dir-archive.js +4 -4
  50. package/src/orphan-dir-archive.js.map +1 -1
  51. package/src/orphan-dir-scan.d.ts +1 -1
  52. package/src/orphan-dir-scan.js +1 -1
  53. package/src/orphan-dir-scan.js.map +1 -1
  54. package/src/orphan-dir-sweep.js +1 -1
  55. package/src/orphan-dir-sweep.js.map +1 -1
  56. package/src/pack-policy-files.js +4 -3
  57. package/src/pack-policy-files.js.map +1 -1
  58. package/src/policy-tracking.d.ts +7 -0
  59. package/src/policy-tracking.js +68 -0
  60. package/src/policy-tracking.js.map +1 -0
  61. package/src/pr-gate-config.d.ts +1 -1
  62. package/src/pr-gate-config.js +1 -1
  63. package/src/pr-gate-config.js.map +1 -1
  64. package/src/repo-root.d.ts +7 -7
  65. package/src/repo-root.js +8 -8
  66. package/src/repo-root.js.map +1 -1
  67. package/src/repo-scratch-dirs.d.ts +3 -3
  68. package/src/repo-scratch-dirs.js +5 -5
  69. package/src/repo-scratch-dirs.js.map +1 -1
  70. package/src/review-json-data.js +2 -2
  71. package/src/review-json-data.js.map +1 -1
  72. package/src/review-json.js +1 -1
  73. package/src/review-json.js.map +1 -1
  74. package/src/reviewer-instructions.d.ts +1 -1
  75. package/src/reviewer-instructions.js +1 -1
  76. package/src/reviewer-instructions.js.map +1 -1
  77. package/src/rule-pack-artifacts.d.ts +2 -2
  78. package/src/rule-pack-artifacts.js +2 -2
  79. package/src/rule-pack-artifacts.js.map +1 -1
  80. package/src/rule-pack-sync.js +5 -4
  81. package/src/rule-pack-sync.js.map +1 -1
  82. package/src/stale-bin-sweep.js +1 -1
  83. package/src/stale-bin-sweep.js.map +1 -1
  84. package/src/subagent-provenance.d.ts +6 -6
  85. package/src/subagent-provenance.js +6 -6
  86. package/src/subagent-provenance.js.map +1 -1
  87. package/src/sync-flow-guidance.js +1 -1
  88. package/src/sync-flow-guidance.js.map +1 -1
  89. package/templates/webpieces.branch-state-matrix.md +2 -2
  90. package/templates/webpieces.buildlog.md +3 -3
  91. package/templates/webpieces.ci-gate-setup.md +2 -2
  92. package/templates/webpieces.git-workflow.md +9 -9
  93. package/templates/webpieces.guard-matrix.md +6 -5
  94. package/templates/webpieces.location-matrix.md +9 -9
  95. package/templates/webpieces.review-checklists.md +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"orphan-dir-archive.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/orphan-dir-archive.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAG3D,8DAAyD;AACzD,iEAA6D;AAE7D,2GAA2G;AAC9F,QAAA,eAAe,GAAG,OAAO,CAAC;AACvC,4FAA4F;AAC/E,QAAA,mBAAmB,GAAG,eAAe,CAAC;AACnD,2GAA2G;AAC9F,QAAA,oBAAoB,GAAG,EAAE,CAAC;AAEvC,MAAM,cAAc,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAE3C;;;;;;;;;;;;;;;;;;;GAmBG;AAEI,IAAM,iBAAiB,GAAvB,MAAM,iBAAiB;IAC1B;;;OAGG;IACH,OAAO,CAAC,QAAgB,EAAE,UAAsC,EAAE,GAAS;QACvE,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;QAClC,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,CAAC;QAC9D,MAAM,KAAK,GAAqB,EAAE,CAAC;QACnC,MAAM,MAAM,GAAmB,EAAE,CAAC;QAClC,KAAK,MAAM,SAAS,IAAI,UAAU,E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AgC,EAC3E,MAA+B;QAC/B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACzB,CAAC;CACJ;AAbD,kDAaC;AAED,wGAAwG;AACxG,MAAM,gBAAgB,GAAG,wCAAwC,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { OrphanCandidate } from './orphan-dir-scan';\nimport { dotWebpieces } from '@webpieces/tooling-common';\nimport { toError } from '@webpieces/tooling-common/to-error';\n\n/** Where every sweep's archive lands, under the repo-wide `.webpieces/` — never under a worktree's own. */\nexport const TRASH_STATE_DIR = 'trash';\n/** The per-sweep manifest, holding what moved and the command that brings each one back. */\nexport const TRASH_MANIFEST_FILE = 'manifest.json';\n/** Sweeps older than this are reaped by the next sweep. Matches RETENTION_DAYS for the aged-tree sweep. */\nexport const TRASH_RETENTION_DAYS = 30;\n\nconst MILLIS_PER_DAY = 24 * 60 * 60 * 1000;\n\n/**\n * Moves orphan directories into `.webpieces/trash/<sweepId>/` and records how to bring each one back.\n *\n * ─── WHY `mv` AND NEVER `rm -rf` ──────────────────────────────────────────────────────────────────────\n * This runs unattended, on other people's machines, against a predicate that is very good but is still a\n * predicate. A `mv` makes the worst possible outcome — a false positive on a directory somebody actually\n * wanted — a thing they undo in one command, instead of a thing they restore from a backup or lose. That\n * single decision is what makes it defensible to run this automatically at all, and it is the same trade\n * `wp-cleanup` already makes when it archives a branch to a tag before deleting the ref.\n *\n * ─── WHY ONE DIRECTORY PER SWEEP, TIMESTAMP-NAMED ─────────────────────────────────────────────────────\n * `<sweepId>` is a UTC timestamp with `:` swapped for `-` (path-safe everywhere, Windows included). That\n * spelling sorts LEXICALLY in chronological order, so `ls` reads oldest-first and `ls -r` newest-first,\n * with no flags to remember and no dates to parse. Grouping by sweep also answers the only question\n * anybody actually asks of this directory — \"what did the run I just did take?\" — which a single flat\n * pile of moved directories cannot answer at all.\n *\n * Each sweep directory reproduces the repo-relative path of what it holds, so the manifest's `recover=`\n * is an ordinary `mv` of one path to another, with no bookkeeping needed to reconstruct the destination.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class OrphanDirArchiver {\n /**\n * Move every candidate into a fresh sweep directory. `now` is a parameter so specs pin the sweep id\n * instead of racing the clock.\n */\n archive(repoRoot: string, candidates: readonly OrphanCandidate[], now: Date): OrphanSweepResult {\n const sweepId = this.sweepId(now);\n const sweepDir = path.join(this.trashRoot(repoRoot), sweepId);\n const moved: ArchivedOrphan[] = [];\n const failed: FailedOrphan[] = [];\n for (const candidate of candidates) {\n const destination = path.join(sweepDir, candidate.relativePath);\n const failure = this.move(candidate.absolutePath, destination);\n if (failure !== null) {\n failed.push(new FailedOrphan(candidate.relativePath, failure));\n continue;\n }\n moved.push(new ArchivedOrphan(candidate.relativePath, destination,\n `mv '${destination}' '${candidate.absolutePath}'`));\n }\n const manifestError = this.writeManifest(sweepDir, sweepId, repoRoot, moved, failed);\n return new OrphanSweepResult(sweepId, sweepDir, moved, failed, manifestError);\n }\n\n /**\n * Delete sweep directories older than TRASH_RETENTION_DAYS, and report how many went. Called by the\n * sweeper AFTER a successful archive, so trash cannot grow without bound on a machine that has the\n * flag on. This one really does delete — it is deleting the archive, which is the second copy.\n */\n reapAged(repoRoot: string, now: Date): number {\n const root = this.trashRoot(repoRoot);\n const cutoff = now.getTime() - TRASH_RETENTION_DAYS * MILLIS_PER_DAY;\n let reaped = 0;\n for (const entry of this.listSweeps(root)) {\n const stamp = this.parseSweepId(entry);\n if (stamp === null || stamp.getTime() >= cutoff) continue;\n if (this.removeTree(path.join(root, entry))) reaped += 1;\n }\n return reaped;\n }\n\n /** `<repo>/.webpieces/trash` — the SHARED state dir, so a worktree's trash is not stranded with it. */\n trashRoot(repoRoot: string): string {\n return path.join(dotWebpieces.shared(repoRoot), TRASH_STATE_DIR);\n }\n\n /**\n * `2026-08-19T14-32-05Z`. ISO order with `:` replaced, and milliseconds dropped — a sweep is a\n * human-scale event and a second is resolution enough to name one.\n */\n sweepId(now: Date): string {\n return now.toISOString().replace(/\\.\\d{3}Z$/, 'Z').replace(/:/g, '-');\n }\n\n /** The Date a sweep id names, or null when the entry is not one of ours (a stray file, say). */\n private parseSweepId(entry: string): Date | null {\n if (!SWEEP_ID_PATTERN.test(entry)) return null;\n const iso = `${entry.slice(0, 10)}T${entry.slice(11, 19).replace(/-/g, ':')}Z`;\n const parsed = new Date(iso);\n return Number.isNaN(parsed.getTime()) ? null : parsed;\n }\n\n private listSweeps(root: string): string[] {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: no trash directory yet is the normal\n // state on every machine that has never swept, and it is not a condition anybody needs told about\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return fs.readdirSync(root);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return [];\n }\n }\n\n /**\n * `mv` the directory, creating the destination's parent chain first. Returns null on success, or the\n * failure's message — a directory we cannot move is REPORTED and skipped, never fatal.\n *\n * `fs.renameSync` first because it is atomic and instant within a filesystem; a cross-device rename\n * (EXDEV — a repo whose `.webpieces` sits on a different mount) falls back to a recursive copy plus\n * delete, which is what `mv` itself does in the same situation.\n */\n private move(from: string, to: string): string | null {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: converts a per-directory move failure\n // into a reported line, because one unmovable directory may not abandon the rest of the sweep\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.mkdirSync(path.dirname(to), { recursive: true });\n fs.renameSync(from, to);\n return null;\n } catch (err: unknown) {\n const error = toError(err);\n return this.moveAcrossDevices(from, to, error);\n }\n }\n\n private moveAcrossDevices(from: string, to: string, cause: Error): string | null {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: the fallback's own failure becomes the\n // reported message for this directory, the same contract move() has\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n if (!this.isCrossDevice(cause)) return cause.message;\n fs.cpSync(from, to, { recursive: true });\n fs.rmSync(from, { recursive: true, force: true });\n return null;\n } catch (err: unknown) {\n const error = toError(err);\n return error.message;\n }\n }\n\n private isCrossDevice(error: Error): boolean {\n // webpieces-disable no-any-unknown -- node attaches `code` to fs errors without typing it on Error\n const code = (error as unknown as Record<string, unknown>)['code'];\n return code === 'EXDEV';\n }\n\n private removeTree(target: string): boolean {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: failing to reap OLD trash is cosmetic\n // and may never surface as an error on a command whose real work already succeeded\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.rmSync(target, { recursive: true, force: true });\n return true;\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return false;\n }\n }\n\n /**\n * The sweep's own record, beside what it took. Written even when every move failed, because \"this\n * sweep tried and could not\" is exactly the state somebody debugging needs to find on disk.\n *\n * Returns the failure message, or null on success. It is REPORTED rather than swallowed: the manifest\n * is the durable copy of every `recover=` command, so losing it silently is the one failure here that\n * costs somebody the ability to undo what just happened. Still never fatal — the directories are\n * already safely moved by this point, and the recover lines are still printed to the terminal.\n */\n private writeManifest(sweepDir: string, sweepId: string, repoRoot: string,\n moved: readonly ArchivedOrphan[], failed: readonly FailedOrphan[]): string | null {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: the directories are already safely\n // moved by this point, and an unwritable manifest may not turn that success into a failure\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.mkdirSync(sweepDir, { recursive: true });\n fs.writeFileSync(path.join(sweepDir, TRASH_MANIFEST_FILE),\n `${JSON.stringify(new OrphanSweepManifest(sweepId, repoRoot, moved, failed), null, 2)}\\n`, 'utf8');\n return null;\n } catch (err: unknown) {\n const error = toError(err);\n return error.message;\n }\n }\n}\n\n/** One directory that was moved, and the exact command that undoes it. Data-only. */\nexport class ArchivedOrphan {\n /** Where it used to live, repo-relative. */\n relativePath: string;\n /** Where it lives now, absolute. */\n archivedAt: string;\n /** The `mv` that puts it back — printed to the human and stored in the manifest verbatim. */\n recoverCommand: string;\n\n constructor(relativePath: string, archivedAt: string, recoverCommand: string) {\n this.relativePath = relativePath;\n this.archivedAt = archivedAt;\n this.recoverCommand = recoverCommand;\n }\n}\n\n/** One directory the sweep found but could not move, with the reason. Data-only. */\nexport class FailedOrphan {\n relativePath: string;\n reason: string;\n\n constructor(relativePath: string, reason: string) {\n this.relativePath = relativePath;\n this.reason = reason;\n }\n}\n\n/** What one sweep did. Data-only. */\nexport class OrphanSweepResult {\n sweepId: string;\n sweepDir: string;\n moved: readonly ArchivedOrphan[];\n failed: readonly FailedOrphan[];\n /**\n * Why the manifest could not be written, or null when it was. Non-null means the printed `recover=`\n * lines are the ONLY copy — see writeManifest().\n */\n manifestError: string | null;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(sweepId: string, sweepDir: string, moved: readonly ArchivedOrphan[],\n failed: readonly FailedOrphan[], manifestError: string | null) {\n this.sweepId = sweepId;\n this.sweepDir = sweepDir;\n this.moved = moved;\n this.failed = failed;\n this.manifestError = manifestError;\n }\n}\n\n/** The on-disk shape of `manifest.json`. Data-only. */\nexport class OrphanSweepManifest {\n sweepId: string;\n repoRoot: string;\n moved: readonly ArchivedOrphan[];\n failed: readonly FailedOrphan[];\n\n constructor(sweepId: string, repoRoot: string, moved: readonly ArchivedOrphan[],\n failed: readonly FailedOrphan[]) {\n this.sweepId = sweepId;\n this.repoRoot = repoRoot;\n this.moved = moved;\n this.failed = failed;\n }\n}\n\n// `2026-08-19T14-32-05Z` — the exact shape sweepId() writes, and the only shape reapAged() will delete.\nconst SWEEP_ID_PATTERN = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d{2}Z$/;\n"]}
1
+ {"version":3,"file":"orphan-dir-archive.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/orphan-dir-archive.ts"],"names":[],"mappings":";;;;AAAA,+CAAy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AAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACzB,CAAC;CACJ;AARD,oCAQC;AAED,qCAAqC;AACrC,MAAa,iBAAiB;IAC1B,OAAO,CAAS;IAChB,QAAQ,CAAS;IACjB,KAAK,CAA4B;IACjC,MAAM,CAA0B;IAChC;;;OAGG;IACH,aAAa,CAAgB;IAE7B,yDAAyD;IACzD,YAAY,OAAe,EAAE,QAAgB,EAAE,KAAgC,EAC3E,MAA+B,EAAE,aAA4B;QAC7D,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;IACvC,CAAC;CACJ;AApBD,8CAoBC;AAED,uDAAuD;AACvD,MAAa,mBAAmB;IAC5B,OAAO,CAAS;IAChB,QAAQ,CAAS;IACjB,KAAK,CAA4B;IACjC,MAAM,CAA0B;IAEhC,YAAY,OAAe,EAAE,QAAgB,EAAE,KAAgC,EAC3E,MAA+B;QAC/B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACzB,CAAC;CACJ;AAbD,kDAaC;AAED,wGAAwG;AACxG,MAAM,gBAAgB,GAAG,wCAAwC,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { OrphanCandidate } from './orphan-dir-scan';\nimport { dotWebpieces } from '@webpieces/tooling-common';\nimport { toError } from '@webpieces/tooling-common/to-error';\n\n/** Where every sweep's archive lands, under the repo-wide `.webpieces-logs/` — never under a worktree's own. */\nexport const TRASH_STATE_DIR = 'trash';\n/** The per-sweep manifest, holding what moved and the command that brings each one back. */\nexport const TRASH_MANIFEST_FILE = 'manifest.json';\n/** Sweeps older than this are reaped by the next sweep. Matches RETENTION_DAYS for the aged-tree sweep. */\nexport const TRASH_RETENTION_DAYS = 30;\n\nconst MILLIS_PER_DAY = 24 * 60 * 60 * 1000;\n\n/**\n * Moves orphan directories into `.webpieces-logs/trash/<sweepId>/` and records how to bring each one back.\n *\n * ─── WHY `mv` AND NEVER `rm -rf` ──────────────────────────────────────────────────────────────────────\n * This runs unattended, on other people's machines, against a predicate that is very good but is still a\n * predicate. A `mv` makes the worst possible outcome — a false positive on a directory somebody actually\n * wanted — a thing they undo in one command, instead of a thing they restore from a backup or lose. That\n * single decision is what makes it defensible to run this automatically at all, and it is the same trade\n * `wp-cleanup` already makes when it archives a branch to a tag before deleting the ref.\n *\n * ─── WHY ONE DIRECTORY PER SWEEP, TIMESTAMP-NAMED ─────────────────────────────────────────────────────\n * `<sweepId>` is a UTC timestamp with `:` swapped for `-` (path-safe everywhere, Windows included). That\n * spelling sorts LEXICALLY in chronological order, so `ls` reads oldest-first and `ls -r` newest-first,\n * with no flags to remember and no dates to parse. Grouping by sweep also answers the only question\n * anybody actually asks of this directory — \"what did the run I just did take?\" — which a single flat\n * pile of moved directories cannot answer at all.\n *\n * Each sweep directory reproduces the repo-relative path of what it holds, so the manifest's `recover=`\n * is an ordinary `mv` of one path to another, with no bookkeeping needed to reconstruct the destination.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class OrphanDirArchiver {\n /**\n * Move every candidate into a fresh sweep directory. `now` is a parameter so specs pin the sweep id\n * instead of racing the clock.\n */\n archive(repoRoot: string, candidates: readonly OrphanCandidate[], now: Date): OrphanSweepResult {\n const sweepId = this.sweepId(now);\n const sweepDir = path.join(this.trashRoot(repoRoot), sweepId);\n const moved: ArchivedOrphan[] = [];\n const failed: FailedOrphan[] = [];\n for (const candidate of candidates) {\n const destination = path.join(sweepDir, candidate.relativePath);\n const failure = this.move(candidate.absolutePath, destination);\n if (failure !== null) {\n failed.push(new FailedOrphan(candidate.relativePath, failure));\n continue;\n }\n moved.push(new ArchivedOrphan(candidate.relativePath, destination,\n `mv '${destination}' '${candidate.absolutePath}'`));\n }\n const manifestError = this.writeManifest(sweepDir, sweepId, repoRoot, moved, failed);\n return new OrphanSweepResult(sweepId, sweepDir, moved, failed, manifestError);\n }\n\n /**\n * Delete sweep directories older than TRASH_RETENTION_DAYS, and report how many went. Called by the\n * sweeper AFTER a successful archive, so trash cannot grow without bound on a machine that has the\n * flag on. This one really does delete — it is deleting the archive, which is the second copy.\n */\n reapAged(repoRoot: string, now: Date): number {\n const root = this.trashRoot(repoRoot);\n const cutoff = now.getTime() - TRASH_RETENTION_DAYS * MILLIS_PER_DAY;\n let reaped = 0;\n for (const entry of this.listSweeps(root)) {\n const stamp = this.parseSweepId(entry);\n if (stamp === null || stamp.getTime() >= cutoff) continue;\n if (this.removeTree(path.join(root, entry))) reaped += 1;\n }\n return reaped;\n }\n\n /** `<repo>/.webpieces-logs/trash` — the SHARED state dir, so a worktree's trash is not stranded with it. */\n trashRoot(repoRoot: string): string {\n return path.join(dotWebpieces.shared(repoRoot), TRASH_STATE_DIR);\n }\n\n /**\n * `2026-08-19T14-32-05Z`. ISO order with `:` replaced, and milliseconds dropped — a sweep is a\n * human-scale event and a second is resolution enough to name one.\n */\n sweepId(now: Date): string {\n return now.toISOString().replace(/\\.\\d{3}Z$/, 'Z').replace(/:/g, '-');\n }\n\n /** The Date a sweep id names, or null when the entry is not one of ours (a stray file, say). */\n private parseSweepId(entry: string): Date | null {\n if (!SWEEP_ID_PATTERN.test(entry)) return null;\n const iso = `${entry.slice(0, 10)}T${entry.slice(11, 19).replace(/-/g, ':')}Z`;\n const parsed = new Date(iso);\n return Number.isNaN(parsed.getTime()) ? null : parsed;\n }\n\n private listSweeps(root: string): string[] {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: no trash directory yet is the normal\n // state on every machine that has never swept, and it is not a condition anybody needs told about\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return fs.readdirSync(root);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return [];\n }\n }\n\n /**\n * `mv` the directory, creating the destination's parent chain first. Returns null on success, or the\n * failure's message — a directory we cannot move is REPORTED and skipped, never fatal.\n *\n * `fs.renameSync` first because it is atomic and instant within a filesystem; a cross-device rename\n * (EXDEV — a repo whose `.webpieces-logs` sits on a different mount) falls back to a recursive copy plus\n * delete, which is what `mv` itself does in the same situation.\n */\n private move(from: string, to: string): string | null {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: converts a per-directory move failure\n // into a reported line, because one unmovable directory may not abandon the rest of the sweep\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.mkdirSync(path.dirname(to), { recursive: true });\n fs.renameSync(from, to);\n return null;\n } catch (err: unknown) {\n const error = toError(err);\n return this.moveAcrossDevices(from, to, error);\n }\n }\n\n private moveAcrossDevices(from: string, to: string, cause: Error): string | null {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: the fallback's own failure becomes the\n // reported message for this directory, the same contract move() has\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n if (!this.isCrossDevice(cause)) return cause.message;\n fs.cpSync(from, to, { recursive: true });\n fs.rmSync(from, { recursive: true, force: true });\n return null;\n } catch (err: unknown) {\n const error = toError(err);\n return error.message;\n }\n }\n\n private isCrossDevice(error: Error): boolean {\n // webpieces-disable no-any-unknown -- node attaches `code` to fs errors without typing it on Error\n const code = (error as unknown as Record<string, unknown>)['code'];\n return code === 'EXDEV';\n }\n\n private removeTree(target: string): boolean {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: failing to reap OLD trash is cosmetic\n // and may never surface as an error on a command whose real work already succeeded\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.rmSync(target, { recursive: true, force: true });\n return true;\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return false;\n }\n }\n\n /**\n * The sweep's own record, beside what it took. Written even when every move failed, because \"this\n * sweep tried and could not\" is exactly the state somebody debugging needs to find on disk.\n *\n * Returns the failure message, or null on success. It is REPORTED rather than swallowed: the manifest\n * is the durable copy of every `recover=` command, so losing it silently is the one failure here that\n * costs somebody the ability to undo what just happened. Still never fatal — the directories are\n * already safely moved by this point, and the recover lines are still printed to the terminal.\n */\n private writeManifest(sweepDir: string, sweepId: string, repoRoot: string,\n moved: readonly ArchivedOrphan[], failed: readonly FailedOrphan[]): string | null {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: the directories are already safely\n // moved by this point, and an unwritable manifest may not turn that success into a failure\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.mkdirSync(sweepDir, { recursive: true });\n fs.writeFileSync(path.join(sweepDir, TRASH_MANIFEST_FILE),\n `${JSON.stringify(new OrphanSweepManifest(sweepId, repoRoot, moved, failed), null, 2)}\\n`, 'utf8');\n return null;\n } catch (err: unknown) {\n const error = toError(err);\n return error.message;\n }\n }\n}\n\n/** One directory that was moved, and the exact command that undoes it. Data-only. */\nexport class ArchivedOrphan {\n /** Where it used to live, repo-relative. */\n relativePath: string;\n /** Where it lives now, absolute. */\n archivedAt: string;\n /** The `mv` that puts it back — printed to the human and stored in the manifest verbatim. */\n recoverCommand: string;\n\n constructor(relativePath: string, archivedAt: string, recoverCommand: string) {\n this.relativePath = relativePath;\n this.archivedAt = archivedAt;\n this.recoverCommand = recoverCommand;\n }\n}\n\n/** One directory the sweep found but could not move, with the reason. Data-only. */\nexport class FailedOrphan {\n relativePath: string;\n reason: string;\n\n constructor(relativePath: string, reason: string) {\n this.relativePath = relativePath;\n this.reason = reason;\n }\n}\n\n/** What one sweep did. Data-only. */\nexport class OrphanSweepResult {\n sweepId: string;\n sweepDir: string;\n moved: readonly ArchivedOrphan[];\n failed: readonly FailedOrphan[];\n /**\n * Why the manifest could not be written, or null when it was. Non-null means the printed `recover=`\n * lines are the ONLY copy — see writeManifest().\n */\n manifestError: string | null;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(sweepId: string, sweepDir: string, moved: readonly ArchivedOrphan[],\n failed: readonly FailedOrphan[], manifestError: string | null) {\n this.sweepId = sweepId;\n this.sweepDir = sweepDir;\n this.moved = moved;\n this.failed = failed;\n this.manifestError = manifestError;\n }\n}\n\n/** The on-disk shape of `manifest.json`. Data-only. */\nexport class OrphanSweepManifest {\n sweepId: string;\n repoRoot: string;\n moved: readonly ArchivedOrphan[];\n failed: readonly FailedOrphan[];\n\n constructor(sweepId: string, repoRoot: string, moved: readonly ArchivedOrphan[],\n failed: readonly FailedOrphan[]) {\n this.sweepId = sweepId;\n this.repoRoot = repoRoot;\n this.moved = moved;\n this.failed = failed;\n }\n}\n\n// `2026-08-19T14-32-05Z` — the exact shape sweepId() writes, and the only shape reapAged() will delete.\nconst SWEEP_ID_PATTERN = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d{2}Z$/;\n"]}
@@ -57,7 +57,7 @@ export declare class OrphanDirScanner {
57
57
  /**
58
58
  * The two structural exclusions, both about where a moved nx PROJECT can possibly live.
59
59
  *
60
- * DOT SEGMENTS: `.nx/`, `.idea/`, `.webpieces/` and friends are reported whole by `clean -Xdn` (their
60
+ * DOT SEGMENTS: `.nx/`, `.idea/`, `.webpieces-logs/` and friends are reported whole by `clean -Xdn` (their
61
61
  * contents are ignored, the directories themselves are not) and would otherwise pass the discriminator
62
62
  * above perfectly. They are tool state, they are supposed to be there, and no nx project is named with
63
63
  * a leading dot. Excluding the whole class by shape beats naming today's four and meeting a fifth.
@@ -92,7 +92,7 @@ let OrphanDirScanner = class OrphanDirScanner {
92
92
  /**
93
93
  * The two structural exclusions, both about where a moved nx PROJECT can possibly live.
94
94
  *
95
- * DOT SEGMENTS: `.nx/`, `.idea/`, `.webpieces/` and friends are reported whole by `clean -Xdn` (their
95
+ * DOT SEGMENTS: `.nx/`, `.idea/`, `.webpieces-logs/` and friends are reported whole by `clean -Xdn` (their
96
96
  * contents are ignored, the directories themselves are not) and would otherwise pass the discriminator
97
97
  * above perfectly. They are tool state, they are supposed to be there, and no nx project is named with
98
98
  * a leading dot. Excluding the whole class by shape beats naming today's four and meeting a fifth.
@@ -1 +1 @@
1
- {"version":3,"file":"orphan-dir-scan.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/orphan-dir-scan.ts"],"names":[],"mappings":";;;;AAAA,mDAA6B;AAC7B,iDAA0C;AAC1C,yCAA2D;AAE3D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAEI,IAAM,gBAAgB,GAAtB,MAAM,gBAAgB;IACzB;;;;OAIG;IACH,IAAI,CAAC,QAAgB;QACjB,MAAM,QAAQ,GAAG,IAAI,CAAC,kBAAkB,CAAC,QAAQ,CAAC,CAAC;QACnD,MAAM,UAAU,GAAsB,EAAE,CAAC;QACzC,KAAK,MAAM,QAAQ,IAAI,QAAQ,EAAE,CAAC;YAC9B,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC;gBAAE,SAAS;YAC1C,IAAI,IAAI,CAAC,eAAe,CAAC,QAAQ,EAAE,QAAQ,CAAC;gBAAE,SAAS;YACvD,UAAU,CAAC,IAAI,CAAC,IAAI,eAAe,CAAC,QAAQ,EAAE,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC;QAClF,CAAC;QACD,OAAO,UAAU,CAAC,IAAI,CAAC,CAAC,IAAqB,EAAE,KAAsB,EAAU,EAAE,CAC7E,IAAI,CAAC,YAAY,CAAC,aAAa,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC,CAAC;IAC7D,CAAC;IAED;;;;;;;OAOG;IACK,kBAAkB,CAAC,QAAgB;QACvC,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC,CAAC;QAClD,IAAI,GA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Q,EAAE,GAAG,IAAI,CAAC,EAAE;YACvD,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,SAAS,EAAE,gBAAgB;SACrF,CAAC,CAAC;QACH,IAAI,MAAM,CAAC,KAAK,KAAK,SAAS,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,IAAI,CAAC;QACnE,OAAO,MAAM,CAAC,MAAM,CAAC;IACzB,CAAC;CACJ,CAAA;AArFY,4CAAgB;2BAAhB,gBAAgB;IAD5B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;GAC5B,gBAAgB,CAqF5B;AAED,0GAA0G;AAC1G,MAAa,eAAe;IACxB,kFAAkF;IAClF,YAAY,CAAS;IACrB,4EAA4E;IAC5E,YAAY,CAAS;IAErB,YAAY,YAAoB,EAAE,YAAoB;QAClD,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;IACrC,CAAC;CACJ;AAVD,0CAUC;AAED,MAAM,YAAY,GAAG,eAAe,CAAC;AACrC,+FAA+F;AAC/F,MAAM,SAAS,GAAG,CAAC,CAAC;AACpB,0GAA0G;AAC1G,MAAM,gBAAgB,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC","sourcesContent":["import * as path from 'path';\nimport { spawnSync } from 'child_process';\nimport { injectable, bindingScopeValues } from 'inversify';\n\n/**\n * Finds ORPHAN DIRECTORIES — the package directories an `nx g move` leaves behind on every clone, which\n * git cannot remove and which then accumulate on every developer's machine forever.\n *\n * ─── WHY GIT LEAVES THEM ──────────────────────────────────────────────────────────────────────────────\n * Git tracks files, not directories. When a move deletes every tracked file under `libraries/apis/foo/`,\n * git removes that directory ONLY if it is then truly empty — and it never is, because the build already\n * put an IGNORED `dist/` and `node_modules/` inside it. So the corpse stands, on every clone, and there\n * is no git setting that changes this (`core.pruneIgnoredDirs` does not exist).\n *\n * ─── WHY THE PREDICATE IS GIT'S OWN ANSWER AND NOT A HAND-ROLLED WALK ─────────────────────────────────\n * `git clean -Xdn` collapses a directory to a SINGLE entry exactly when everything beneath it is ignored,\n * and it does that using the repo's real ignore engine — nested `.gitignore` files, `!` negations and\n * all. Re-implementing that is how a sweeper ends up disagreeing with git about what is disposable.\n *\n * It also hands us the safety property for free, which is the reason this can run unattended: a directory\n * holding even ONE untracked-but-not-ignored file is NOT reported, so a developer's uncommitted new\n * package can never be a candidate. We do not check that ourselves; git's own output already encodes it.\n *\n * ─── THE ONE DISCRIMINATOR THAT NEEDS NO NAME LIST ────────────────────────────────────────────────────\n * `clean -Xdn` reports two very different things the same way:\n *\n * libraries/apis/pg-dataaccess-api/ ← a corpse: nothing tracked survives under it\n * libraries/apis/live-api/dist/ ← a LIVE project's build output, there on purpose\n *\n * They are separated by asking whether the directory ITSELF matches an ignore rule. `dist/` does\n * (`.gitignore:19:dist/`); `pg-dataaccess-api` does not, which is precisely the statement that this\n * directory was MEANT to hold tracked files — and none are left. No list of artifact directory names is\n * needed, and none is maintained, so the rule adapts to whatever any given consumer repo ignores.\n *\n * That also yields the opt-out, and it is one a developer would reach for anyway: adding `my-sandbox/`\n * to `.gitignore` makes the directory ignore-matched, which permanently protects it from this sweep.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class OrphanDirScanner {\n /**\n * Every orphan directory under `repoRoot`, as repo-RELATIVE paths with no trailing slash. Empty when\n * the tree is clean, when `repoRoot` is not a git repository, or when git cannot be run at all — a\n * sweeper is never important enough to fail somebody's checkout over.\n */\n scan(repoRoot: string): OrphanCandidate[] {\n const reported = this.reportedByGitClean(repoRoot);\n const candidates: OrphanCandidate[] = [];\n for (const relative of reported) {\n if (!this.isSweepable(relative)) continue;\n if (this.isIgnoredItself(repoRoot, relative)) continue;\n candidates.push(new OrphanCandidate(relative, path.join(repoRoot, relative)));\n }\n return candidates.sort((left: OrphanCandidate, right: OrphanCandidate): number =>\n left.relativePath.localeCompare(right.relativePath));\n }\n\n /**\n * The DIRECTORY paths `git clean -Xdn` would remove, relative to `repoRoot` and slash-stripped.\n *\n * Only entries ending in `/` are directories; a bare path is a single ignored FILE (`.env`,\n * `.claude/settings.local.json`) and is none of this sweep's business. `Would skip repository` lines\n * are git telling us it found a nested repo — a linked worktree — which it refuses to descend into,\n * and so do we.\n */\n private reportedByGitClean(repoRoot: string): string[] {\n const raw = this.git(repoRoot, ['clean', '-Xdn']);\n if (raw === null) return [];\n const paths: string[] = [];\n for (const line of raw.split('\\n')) {\n const trimmed = line.trim();\n if (!trimmed.startsWith(WOULD_REMOVE)) continue;\n const target = trimmed.slice(WOULD_REMOVE.length).trim();\n if (!target.endsWith('/')) continue;\n paths.push(target.slice(0, -1));\n }\n return paths;\n }\n\n /**\n * True when git matches an ignore rule against the DIRECTORY ITSELF — i.e. it is a build artifact\n * somebody declared disposable-but-expected, not a corpse. `check-ignore -q` exits 0 on a match and 1\n * on no match, so a null answer here (any non-zero exit, including a git we could not run) means\n * \"cannot confirm\", and the directory is SPARED. Every uncertainty in this class resolves that way.\n */\n private isIgnoredItself(repoRoot: string, relative: string): boolean {\n return this.git(repoRoot, ['check-ignore', '-q', '--', relative]) !== null;\n }\n\n /**\n * The two structural exclusions, both about where a moved nx PROJECT can possibly live.\n *\n * DOT SEGMENTS: `.nx/`, `.idea/`, `.webpieces/` and friends are reported whole by `clean -Xdn` (their\n * contents are ignored, the directories themselves are not) and would otherwise pass the discriminator\n * above perfectly. They are tool state, they are supposed to be there, and no nx project is named with\n * a leading dot. Excluding the whole class by shape beats naming today's four and meeting a fifth.\n *\n * DEPTH: a moved project lives at `libraries/x`, `apps/x`, `packages/y/z` — never at the top level.\n * Requiring depth >= 2 costs nothing real and takes every top-level directory in the repo permanently\n * out of reach of an automated `mv`.\n */\n private isSweepable(relative: string): boolean {\n const segments = relative.split('/');\n if (segments.length < MIN_DEPTH) return false;\n return !segments.some((segment: string): boolean => segment.startsWith('.'));\n }\n\n /**\n * `git <args>` in `repoRoot`, or null when git exits non-zero or could not be run at all.\n *\n * spawnSync rather than execFileSync because a non-zero exit is ORDINARY here — `check-ignore` says\n * \"not ignored\" that way — and a status code is a better answer to that question than an exception.\n *\n * An ARGUMENT ARRAY, never a shell string: these paths come from a filesystem scan and may hold\n * spaces, quotes or `$`, and interpolating them into a shell would be building a command injection\n * into the one tool whose entire job is moving directories around.\n */\n private git(repoRoot: string, args: string[]): string | null {\n const result = spawnSync('git', ['-C', repoRoot, ...args], {\n encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: GIT_OUTPUT_LIMIT,\n });\n if (result.error !== undefined || result.status !== 0) return null;\n return result.stdout;\n }\n}\n\n/** One directory the sweep may archive. Data-only (per CLAUDE.md — classes, not interfaces, for data). */\nexport class OrphanCandidate {\n /** Repo-relative, no trailing slash — e.g. `libraries/apis/pg-dataaccess-api`. */\n relativePath: string;\n /** The same directory as an absolute path, which is what any `mv` needs. */\n absolutePath: string;\n\n constructor(relativePath: string, absolutePath: string) {\n this.relativePath = relativePath;\n this.absolutePath = absolutePath;\n }\n}\n\nconst WOULD_REMOVE = 'Would remove ';\n// `libraries/foo` is depth 2. Anything shallower is a top-level directory — see isSweepable().\nconst MIN_DEPTH = 2;\n// `clean -Xdn` on a large monorepo prints a few hundred lines; 16MB is a ceiling no real repo approaches.\nconst GIT_OUTPUT_LIMIT = 16 * 1024 * 1024;\n"]}
1
+ {"version":3,"file":"orphan-dir-scan.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/orphan-dir-scan.ts"],"names":[],"mappings":";;;;AAAA,mDAA6B;AAC7B,iDAA0C;AAC1C,yCAA2D;AAE3D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAEI,IAAM,gBAAgB,GAAtB,MAAM,gBAAgB;IACzB;;;;OAIG;IACH,IAAI,CAAC,QAAgB;QACjB,MAAM,QAAQ,GAAG,IAAI,CAAC,kBAAkB,CAAC,QAAQ,CAAC,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,YAAY,CAAS;IAErB,YAAY,YAAoB,EAAE,YAAoB;QAClD,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;IACrC,CAAC;CACJ;AAVD,0CAUC;AAED,MAAM,YAAY,GAAG,eAAe,CAAC;AACrC,+FAA+F;AAC/F,MAAM,SAAS,GAAG,CAAC,CAAC;AACpB,0GAA0G;AAC1G,MAAM,gBAAgB,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC","sourcesContent":["import * as path from 'path';\nimport { spawnSync } from 'child_process';\nimport { injectable, bindingScopeValues } from 'inversify';\n\n/**\n * Finds ORPHAN DIRECTORIES — the package directories an `nx g move` leaves behind on every clone, which\n * git cannot remove and which then accumulate on every developer's machine forever.\n *\n * ─── WHY GIT LEAVES THEM ──────────────────────────────────────────────────────────────────────────────\n * Git tracks files, not directories. When a move deletes every tracked file under `libraries/apis/foo/`,\n * git removes that directory ONLY if it is then truly empty — and it never is, because the build already\n * put an IGNORED `dist/` and `node_modules/` inside it. So the corpse stands, on every clone, and there\n * is no git setting that changes this (`core.pruneIgnoredDirs` does not exist).\n *\n * ─── WHY THE PREDICATE IS GIT'S OWN ANSWER AND NOT A HAND-ROLLED WALK ─────────────────────────────────\n * `git clean -Xdn` collapses a directory to a SINGLE entry exactly when everything beneath it is ignored,\n * and it does that using the repo's real ignore engine — nested `.gitignore` files, `!` negations and\n * all. Re-implementing that is how a sweeper ends up disagreeing with git about what is disposable.\n *\n * It also hands us the safety property for free, which is the reason this can run unattended: a directory\n * holding even ONE untracked-but-not-ignored file is NOT reported, so a developer's uncommitted new\n * package can never be a candidate. We do not check that ourselves; git's own output already encodes it.\n *\n * ─── THE ONE DISCRIMINATOR THAT NEEDS NO NAME LIST ────────────────────────────────────────────────────\n * `clean -Xdn` reports two very different things the same way:\n *\n * libraries/apis/pg-dataaccess-api/ ← a corpse: nothing tracked survives under it\n * libraries/apis/live-api/dist/ ← a LIVE project's build output, there on purpose\n *\n * They are separated by asking whether the directory ITSELF matches an ignore rule. `dist/` does\n * (`.gitignore:19:dist/`); `pg-dataaccess-api` does not, which is precisely the statement that this\n * directory was MEANT to hold tracked files — and none are left. No list of artifact directory names is\n * needed, and none is maintained, so the rule adapts to whatever any given consumer repo ignores.\n *\n * That also yields the opt-out, and it is one a developer would reach for anyway: adding `my-sandbox/`\n * to `.gitignore` makes the directory ignore-matched, which permanently protects it from this sweep.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class OrphanDirScanner {\n /**\n * Every orphan directory under `repoRoot`, as repo-RELATIVE paths with no trailing slash. Empty when\n * the tree is clean, when `repoRoot` is not a git repository, or when git cannot be run at all — a\n * sweeper is never important enough to fail somebody's checkout over.\n */\n scan(repoRoot: string): OrphanCandidate[] {\n const reported = this.reportedByGitClean(repoRoot);\n const candidates: OrphanCandidate[] = [];\n for (const relative of reported) {\n if (!this.isSweepable(relative)) continue;\n if (this.isIgnoredItself(repoRoot, relative)) continue;\n candidates.push(new OrphanCandidate(relative, path.join(repoRoot, relative)));\n }\n return candidates.sort((left: OrphanCandidate, right: OrphanCandidate): number =>\n left.relativePath.localeCompare(right.relativePath));\n }\n\n /**\n * The DIRECTORY paths `git clean -Xdn` would remove, relative to `repoRoot` and slash-stripped.\n *\n * Only entries ending in `/` are directories; a bare path is a single ignored FILE (`.env`,\n * `.claude/settings.local.json`) and is none of this sweep's business. `Would skip repository` lines\n * are git telling us it found a nested repo — a linked worktree — which it refuses to descend into,\n * and so do we.\n */\n private reportedByGitClean(repoRoot: string): string[] {\n const raw = this.git(repoRoot, ['clean', '-Xdn']);\n if (raw === null) return [];\n const paths: string[] = [];\n for (const line of raw.split('\\n')) {\n const trimmed = line.trim();\n if (!trimmed.startsWith(WOULD_REMOVE)) continue;\n const target = trimmed.slice(WOULD_REMOVE.length).trim();\n if (!target.endsWith('/')) continue;\n paths.push(target.slice(0, -1));\n }\n return paths;\n }\n\n /**\n * True when git matches an ignore rule against the DIRECTORY ITSELF — i.e. it is a build artifact\n * somebody declared disposable-but-expected, not a corpse. `check-ignore -q` exits 0 on a match and 1\n * on no match, so a null answer here (any non-zero exit, including a git we could not run) means\n * \"cannot confirm\", and the directory is SPARED. Every uncertainty in this class resolves that way.\n */\n private isIgnoredItself(repoRoot: string, relative: string): boolean {\n return this.git(repoRoot, ['check-ignore', '-q', '--', relative]) !== null;\n }\n\n /**\n * The two structural exclusions, both about where a moved nx PROJECT can possibly live.\n *\n * DOT SEGMENTS: `.nx/`, `.idea/`, `.webpieces-logs/` and friends are reported whole by `clean -Xdn` (their\n * contents are ignored, the directories themselves are not) and would otherwise pass the discriminator\n * above perfectly. They are tool state, they are supposed to be there, and no nx project is named with\n * a leading dot. Excluding the whole class by shape beats naming today's four and meeting a fifth.\n *\n * DEPTH: a moved project lives at `libraries/x`, `apps/x`, `packages/y/z` — never at the top level.\n * Requiring depth >= 2 costs nothing real and takes every top-level directory in the repo permanently\n * out of reach of an automated `mv`.\n */\n private isSweepable(relative: string): boolean {\n const segments = relative.split('/');\n if (segments.length < MIN_DEPTH) return false;\n return !segments.some((segment: string): boolean => segment.startsWith('.'));\n }\n\n /**\n * `git <args>` in `repoRoot`, or null when git exits non-zero or could not be run at all.\n *\n * spawnSync rather than execFileSync because a non-zero exit is ORDINARY here — `check-ignore` says\n * \"not ignored\" that way — and a status code is a better answer to that question than an exception.\n *\n * An ARGUMENT ARRAY, never a shell string: these paths come from a filesystem scan and may hold\n * spaces, quotes or `$`, and interpolating them into a shell would be building a command injection\n * into the one tool whose entire job is moving directories around.\n */\n private git(repoRoot: string, args: string[]): string | null {\n const result = spawnSync('git', ['-C', repoRoot, ...args], {\n encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: GIT_OUTPUT_LIMIT,\n });\n if (result.error !== undefined || result.status !== 0) return null;\n return result.stdout;\n }\n}\n\n/** One directory the sweep may archive. Data-only (per CLAUDE.md — classes, not interfaces, for data). */\nexport class OrphanCandidate {\n /** Repo-relative, no trailing slash — e.g. `libraries/apis/pg-dataaccess-api`. */\n relativePath: string;\n /** The same directory as an absolute path, which is what any `mv` needs. */\n absolutePath: string;\n\n constructor(relativePath: string, absolutePath: string) {\n this.relativePath = relativePath;\n this.absolutePath = absolutePath;\n }\n}\n\nconst WOULD_REMOVE = 'Would remove ';\n// `libraries/foo` is depth 2. Anything shallower is a top-level directory — see isSweepable().\nconst MIN_DEPTH = 2;\n// `clean -Xdn` on a large monorepo prints a few hundred lines; 16MB is a ceiling no real repo approaches.\nconst GIT_OUTPUT_LIMIT = 16 * 1024 * 1024;\n"]}
@@ -98,7 +98,7 @@ class OrphanSweepReport {
98
98
  renderReportOnly() {
99
99
  return `${this.heading()}\n`
100
100
  + ` Nothing was moved — archiving is off on this machine.\n`
101
- + ` To archive them (never delete: they move to .webpieces/trash/<sweepId>/ with a recover=\n`
101
+ + ` To archive them (never delete: they move to .webpieces-logs/trash/<sweepId>/ with a recover=\n`
102
102
  + ` command printed for each), add this key in ~/.webpieces/config.json — every key in that\n`
103
103
  + ` file is optional, so this one line beside whatever is already there is the whole edit:\n\n`
104
104
  + ` { "${home_config_1.HOME_EXPERIMENTAL_SECTION}": { "${home_config_1.HOME_KEY_ORPHAN_DIR_SWEEP}": true } }\n`;
@@ -1 +1 @@
1
- {"version":3,"file":"orphan-dir-sweep.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/orphan-dir-sweep.ts"],"names":[],"mappings":";;;;AAAA,yCAA2D;AAE3D,uDAAsE;AACtE,6DAA0G;AAC1G,+CAAwG;AAExG;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEI,IAAM,gBAAgB,GAAtB,MAAM,gBAAgB;IAEJ;IACA;IACA;IAHrB,YACqB,OAAyB,EACzB,QAA2B,EAC3B,iBAAoC;QAFpC,YAAO,GAAP,OAAO,CAAkB;QACzB,aAAQ,GAAR,QAAQ,CAAmB;QAC3B,sBAAiB,GAAjB,iBAAiB,CAAmB;IACtD,CAAC;IAEJ;;;OAG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,CAAC,IAAI,CAAC,kDAAkD,MAAM,CAAC,aAAa,EAAE,CAAC,CAAC;YACrF,KAAK,CAAC,IAAI,CAAC,uFAAuF,CAAC,CAAC;QACxG,CAAC;QACD,IAAI,IAAI,CAAC,YAAY,GAAG,CAAC,EAAE,CAAC;YACxB,KAAK,CAAC,IAAI,CAAC,YAAY,IAAI,CAAC,YAAY,6CAA6C,CAAC,CAAC;QAC3F,CAAC;QACD,OAAO,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;IACnC,CAAC;IAEO,OAAO;QACX,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC;QAChC,OAAO,sFAAsF,KAAK,EAAE,CAAC;IACzG,CAAC;IAED,uGAAuG;IACvG,QAAQ;QACJ,OAAO,IAAI,CAAC,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC;IACzD,CAAC;IAED,qEAAqE;IACrE,OAAO;QACH,OAAO,IAAI,CAAC,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC;IAC1D,CAAC;CACJ;AA/ED,8CA+EC","sourcesContent":["import { injectable, bindingScopeValues } from 'inversify';\n\nimport { OrphanCandidate, OrphanDirScanner } from './orphan-dir-scan';\nimport { ArchivedOrphan, FailedOrphan, OrphanDirArchiver, OrphanSweepResult } from './orphan-dir-archive';\nimport { HOME_EXPERIMENTAL_SECTION, HOME_KEY_ORPHAN_DIR_SWEEP, HomeConfigService } from './home-config';\n\n/**\n * The orphan-directory sweep, end to end: find the corpses an `nx g move` left behind, and — only on a\n * machine that has explicitly opted in — archive them where they can be recovered.\n *\n * ─── WHY THE DEFAULT IS REPORT-ONLY ───────────────────────────────────────────────────────────────────\n * `experimental.orphan-dir-sweep` in `~/.webpieces/config.json` defaults to false, like every other key\n * in that optional, machine-local file. That gives the author of this feature exactly one thing nothing\n * else can: they can run it live across all of their own clones for a release, while every colleague\n * pulling the same version gets a report and an untouched working tree.\n *\n * The default direction is the whole safety argument, and it only points one way: absent means REPORT.\n * Nobody can discover this feature by finding their directories somewhere else — the machine has to say\n * `true` out loud first, and the key is greppable precisely because the permissive state is a token\n * rather than an absence.\n *\n * ─── WHY IT NEVER THROWS ──────────────────────────────────────────────────────────────────────────────\n * Every caller is a command whose real work is a checkout and a pull. Tidying is worth doing on the back\n * of that, and worth nothing at all if it can fail the thing it rode in on, so every failure below\n * resolves to a line of prose in the report. The one exception is deliberate: a MALFORMED\n * `~/.webpieces/config.json` propagates, because that file is the user's own instruction to this code and\n * silently ignoring a broken one is how a machine ends up in a state its owner did not choose.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class OrphanDirSweeper {\n constructor(\n private readonly scanner: OrphanDirScanner,\n private readonly archiver: OrphanDirArchiver,\n private readonly homeConfigService: HomeConfigService,\n ) {}\n\n /**\n * Scan `repoRoot`, and archive what was found when this machine has opted in. `now` is a parameter\n * so specs pin the sweep id rather than racing the clock.\n */\n sweep(repoRoot: string, now: Date): OrphanSweepReport {\n const candidates = this.scanner.scan(repoRoot);\n const enabled = this.homeConfigService.load().orphanDirSweep;\n if (candidates.length === 0) return new OrphanSweepReport(enabled, candidates, null, 0);\n if (!enabled) return new OrphanSweepReport(false, candidates, null, 0);\n const result = this.archiver.archive(repoRoot, candidates, now);\n return new OrphanSweepReport(true, candidates, result, this.archiver.reapAged(repoRoot, now));\n }\n}\n\n/**\n * What one sweep found and did, and how to say it out loud. Data-only apart from `render()`, which is\n * the report's own presentation of itself rather than business logic living somewhere else.\n */\nexport class OrphanSweepReport {\n /** Was archiving switched on for this machine? False means nothing on disk was touched. */\n enabled: boolean;\n /** Every orphan directory found, whether or not it was archived. */\n found: readonly OrphanCandidate[];\n /** The archive, or null when this was a report-only run or there was nothing to archive. */\n result: OrphanSweepResult | null;\n /** How many aged sweep directories were reaped from the trash on this run. */\n reapedSweeps: number;\n\n constructor(enabled: boolean, found: readonly OrphanCandidate[], result: OrphanSweepResult | null,\n reapedSweeps: number) {\n this.enabled = enabled;\n this.found = found;\n this.result = result;\n this.reapedSweeps = reapedSweeps;\n }\n\n /**\n * The human-facing block, or empty string when there is nothing to say. A clean tree prints NOTHING —\n * this rides along on somebody else's command, and a tidier that announces having found no work is a\n * tidier people start ignoring, and then stop reading the run where it did find some.\n */\n render(): string {\n if (this.found.length === 0) return '';\n if (!this.enabled) return this.renderReportOnly();\n return this.renderArchived();\n }\n\n /**\n * The opted-out form: name what was found, name the one edit that turns archiving on, and touch\n * nothing. It names the KEY rather than describing it, because the reader is usually an agent and the\n * mechanical edit is the only part of this it can act on.\n */\n private renderReportOnly(): string {\n return `${this.heading()}\\n`\n + ` Nothing was moved — archiving is off on this machine.\\n`\n + ` To archive them (never delete: they move to .webpieces/trash/<sweepId>/ with a recover=\\n`\n + ` command printed for each), add this key in ~/.webpieces/config.json — every key in that\\n`\n + ` file is optional, so this one line beside whatever is already there is the whole edit:\\n\\n`\n + ` { \"${HOME_EXPERIMENTAL_SECTION}\": { \"${HOME_KEY_ORPHAN_DIR_SWEEP}\": true } }\\n`;\n }\n\n private renderArchived(): string {\n const lines: string[] = [this.heading()];\n const result = this.result;\n if (result === null) return `${lines.join('\\n')}\\n`;\n lines.push(` archived to ${result.sweepDir}`);\n for (const moved of result.moved) {\n lines.push(` ${moved.relativePath}`);\n lines.push(` recover=${moved.recoverCommand}`);\n }\n for (const failure of result.failed) {\n lines.push(` SKIPPED ${failure.relativePath} — ${failure.reason}`);\n }\n if (result.manifestError !== null) {\n lines.push(` WARNING: the manifest could not be written — ${result.manifestError}`);\n lines.push(' The recover= lines above are the only copy. Save them before closing this terminal.');\n }\n if (this.reapedSweeps > 0) {\n lines.push(` reaped ${this.reapedSweeps} sweep(s) older than 30 days from the trash`);\n }\n return `${lines.join('\\n')}\\n`;\n }\n\n private heading(): string {\n const count = this.found.length;\n return `orphan directories (left by a project move; every file under them is git-ignored): ${count}`;\n }\n\n /** Everything archived on this run — empty on a report-only run. Convenience for callers and specs. */\n archived(): readonly ArchivedOrphan[] {\n return this.result === null ? [] : this.result.moved;\n }\n\n /** Everything found but not movable — empty on a report-only run. */\n skipped(): readonly FailedOrphan[] {\n return this.result === null ? [] : this.result.failed;\n }\n}\n"]}
1
+ {"version":3,"file":"orphan-dir-sweep.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/orphan-dir-sweep.ts"],"names":[],"mappings":";;;;AAAA,yCAA2D;AAE3D,uDAAsE;AACtE,6DAA0G;AAC1G,+CAAwG;AAExG;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEI,IAAM,gBAAgB,GAAtB,MAAM,gBAAgB;IAEJ;IACA;IACA;IAHrB,YACqB,OAAyB,EACzB,QAA2B,EAC3B,iBAAoC;QAFpC,YAAO,GAAP,OAAO,CAAkB;QACzB,aAAQ,GAAR,QAAQ,CAAmB;QAC3B,sBAAiB,GAAjB,iBAAiB,CAAmB;IACtD,CAAC;IAEJ;;;OAGG;IACH,KAAK,CAAC,QAAgB,EAAE,GAAS;QAC7B,MAAM,UAAU,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QAC/C,MAAM,OAAO,GAAG,IAAI,CAAC,iBAAiB,CAAC,IAAI,EAAE,CAAC,cAAc,CAAC;QAC7D,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,IAAI,iBAAiB,CAAC,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;QACxF,IAAI,CAAC,OAAO;YAAE,OAAO,IAAI,iBAAiB,CAAC,KAAK,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;QACvE,MAAM,MAAM,GAAG,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,QAAQ,EAAE,UAAU,EAAE,GAAG,CAAC,CAAC;QAChE,OAAO,IAAI,i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AC,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC;IACzD,CAAC;IAED,qEAAqE;IACrE,OAAO;QACH,OAAO,IAAI,CAAC,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC;IAC1D,CAAC;CACJ;AA/ED,8CA+EC","sourcesContent":["import { injectable, bindingScopeValues } from 'inversify';\n\nimport { OrphanCandidate, OrphanDirScanner } from './orphan-dir-scan';\nimport { ArchivedOrphan, FailedOrphan, OrphanDirArchiver, OrphanSweepResult } from './orphan-dir-archive';\nimport { HOME_EXPERIMENTAL_SECTION, HOME_KEY_ORPHAN_DIR_SWEEP, HomeConfigService } from './home-config';\n\n/**\n * The orphan-directory sweep, end to end: find the corpses an `nx g move` left behind, and — only on a\n * machine that has explicitly opted in — archive them where they can be recovered.\n *\n * ─── WHY THE DEFAULT IS REPORT-ONLY ───────────────────────────────────────────────────────────────────\n * `experimental.orphan-dir-sweep` in `~/.webpieces/config.json` defaults to false, like every other key\n * in that optional, machine-local file. That gives the author of this feature exactly one thing nothing\n * else can: they can run it live across all of their own clones for a release, while every colleague\n * pulling the same version gets a report and an untouched working tree.\n *\n * The default direction is the whole safety argument, and it only points one way: absent means REPORT.\n * Nobody can discover this feature by finding their directories somewhere else — the machine has to say\n * `true` out loud first, and the key is greppable precisely because the permissive state is a token\n * rather than an absence.\n *\n * ─── WHY IT NEVER THROWS ──────────────────────────────────────────────────────────────────────────────\n * Every caller is a command whose real work is a checkout and a pull. Tidying is worth doing on the back\n * of that, and worth nothing at all if it can fail the thing it rode in on, so every failure below\n * resolves to a line of prose in the report. The one exception is deliberate: a MALFORMED\n * `~/.webpieces/config.json` propagates, because that file is the user's own instruction to this code and\n * silently ignoring a broken one is how a machine ends up in a state its owner did not choose.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class OrphanDirSweeper {\n constructor(\n private readonly scanner: OrphanDirScanner,\n private readonly archiver: OrphanDirArchiver,\n private readonly homeConfigService: HomeConfigService,\n ) {}\n\n /**\n * Scan `repoRoot`, and archive what was found when this machine has opted in. `now` is a parameter\n * so specs pin the sweep id rather than racing the clock.\n */\n sweep(repoRoot: string, now: Date): OrphanSweepReport {\n const candidates = this.scanner.scan(repoRoot);\n const enabled = this.homeConfigService.load().orphanDirSweep;\n if (candidates.length === 0) return new OrphanSweepReport(enabled, candidates, null, 0);\n if (!enabled) return new OrphanSweepReport(false, candidates, null, 0);\n const result = this.archiver.archive(repoRoot, candidates, now);\n return new OrphanSweepReport(true, candidates, result, this.archiver.reapAged(repoRoot, now));\n }\n}\n\n/**\n * What one sweep found and did, and how to say it out loud. Data-only apart from `render()`, which is\n * the report's own presentation of itself rather than business logic living somewhere else.\n */\nexport class OrphanSweepReport {\n /** Was archiving switched on for this machine? False means nothing on disk was touched. */\n enabled: boolean;\n /** Every orphan directory found, whether or not it was archived. */\n found: readonly OrphanCandidate[];\n /** The archive, or null when this was a report-only run or there was nothing to archive. */\n result: OrphanSweepResult | null;\n /** How many aged sweep directories were reaped from the trash on this run. */\n reapedSweeps: number;\n\n constructor(enabled: boolean, found: readonly OrphanCandidate[], result: OrphanSweepResult | null,\n reapedSweeps: number) {\n this.enabled = enabled;\n this.found = found;\n this.result = result;\n this.reapedSweeps = reapedSweeps;\n }\n\n /**\n * The human-facing block, or empty string when there is nothing to say. A clean tree prints NOTHING —\n * this rides along on somebody else's command, and a tidier that announces having found no work is a\n * tidier people start ignoring, and then stop reading the run where it did find some.\n */\n render(): string {\n if (this.found.length === 0) return '';\n if (!this.enabled) return this.renderReportOnly();\n return this.renderArchived();\n }\n\n /**\n * The opted-out form: name what was found, name the one edit that turns archiving on, and touch\n * nothing. It names the KEY rather than describing it, because the reader is usually an agent and the\n * mechanical edit is the only part of this it can act on.\n */\n private renderReportOnly(): string {\n return `${this.heading()}\\n`\n + ` Nothing was moved — archiving is off on this machine.\\n`\n + ` To archive them (never delete: they move to .webpieces-logs/trash/<sweepId>/ with a recover=\\n`\n + ` command printed for each), add this key in ~/.webpieces/config.json — every key in that\\n`\n + ` file is optional, so this one line beside whatever is already there is the whole edit:\\n\\n`\n + ` { \"${HOME_EXPERIMENTAL_SECTION}\": { \"${HOME_KEY_ORPHAN_DIR_SWEEP}\": true } }\\n`;\n }\n\n private renderArchived(): string {\n const lines: string[] = [this.heading()];\n const result = this.result;\n if (result === null) return `${lines.join('\\n')}\\n`;\n lines.push(` archived to ${result.sweepDir}`);\n for (const moved of result.moved) {\n lines.push(` ${moved.relativePath}`);\n lines.push(` recover=${moved.recoverCommand}`);\n }\n for (const failure of result.failed) {\n lines.push(` SKIPPED ${failure.relativePath} — ${failure.reason}`);\n }\n if (result.manifestError !== null) {\n lines.push(` WARNING: the manifest could not be written — ${result.manifestError}`);\n lines.push(' The recover= lines above are the only copy. Save them before closing this terminal.');\n }\n if (this.reapedSweeps > 0) {\n lines.push(` reaped ${this.reapedSweeps} sweep(s) older than 30 days from the trash`);\n }\n return `${lines.join('\\n')}\\n`;\n }\n\n private heading(): string {\n const count = this.found.length;\n return `orphan directories (left by a project move; every file under them is git-ignored): ${count}`;\n }\n\n /** Everything archived on this run — empty on a report-only run. Convenience for callers and specs. */\n archived(): readonly ArchivedOrphan[] {\n return this.result === null ? [] : this.result.moved;\n }\n\n /** Everything found but not movable — empty on a report-only run. */\n skipped(): readonly FailedOrphan[] {\n return this.result === null ? [] : this.result.failed;\n }\n}\n"]}
@@ -51,7 +51,7 @@ let PackPolicyFiles = class PackPolicyFiles {
51
51
  // webpieces-disable no-any-unknown -- root JSON is narrowed before resolving modules or files.
52
52
  declarations(raw, root) {
53
53
  if (!Array.isArray(raw) || raw.length === 0) {
54
- throw new tooling_common_1.InformAiError('webpieces.config.json.rulePacks is required. Run pnpm wp-rules-sync --upgrade to split the existing explicit config, or add exact {"package":"<pack>","config":".webpieces/rules/<pack>.json"} declarations.');
54
+ throw new tooling_common_1.InformAiError('webpieces.config.json.rulePacks is required. Run pnpm wp-rules-sync --upgrade to split the existing explicit config, or add exact {"package":"<pack>","config":".webpieces-config/rules/<pack>.json"} declarations.');
55
55
  }
56
56
  const packages = new Set(), files = new Set();
57
57
  // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution
@@ -160,9 +160,10 @@ let PackPolicyFiles = class PackPolicyFiles {
160
160
  normalized.startsWith('..') ||
161
161
  !normalized.endsWith('.json') ||
162
162
  normalized === 'webpieces.config.json' ||
163
- normalized === '.webpieces/rules.lock.json') {
164
- throw new tooling_common_1.InformAiError(`Invalid pack config path ${relative}. Use a distinct repository-relative JSON path such as .webpieces/rules/code.json.`);
163
+ normalized === '.webpieces-config/rules.lock.json') {
164
+ throw new tooling_common_1.InformAiError(`Invalid pack config path ${relative}. Use a distinct repository-relative JSON path such as .webpieces-config/rules/code.json.`);
165
165
  }
166
+ new tooling_common_1.RepositoryLayout().assertPolicyPath(normalized);
166
167
  return target;
167
168
  }
168
169
  read(filename) {
@@ -1 +1 @@
1
- {"version":3,"file":"pack-policy-files.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/pack-policy-files.ts"],"names":[],"mappings":";;;;AAAA,yCAA2D;AAC3D,oDAA8B;AAC9B,wDAAkC;AAElC,8DAA0D;AAC1D,iEAA6D;AAC7D,6DAAkF;AAClF,uDAAmD;AACnD,+DAA4E;AAC5E,+DAAiE;AAEjE,kGAAkG;AAClG,MAAa,qBAAqB;IAKjB;IAJJ,OAAO,CAAS;IAEzB,YACI,WAAmB,EACV,MAAc;QAAd,WAAM,GAAN,MAAM,CAAQ;QAEvB,IAAI,CAAC,OAAO,GAAG,WAAW,CAAC;IAC/B,CAAC;IAED,UAAU;QACN,OAAO,mBAAmB,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,OAAO,YAAY,CAAC;IAC/F,CAAC;CACJ;AAbD,sDAaC;AAED,MAAa,kBAAkB;I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,KAAK,KAAK,CAAC,OAAO,yCAAyC,EACpG,EAAE,KAAK,EAAE,KAAK,EAAE,CACnB,CAAC;QACN,CAAC;IACL,CAAC;CACJ,CAAA;AA1LY,0CAAe;0BAAf,eAAe;IAD3B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;GAC5B,eAAe,CA0L3B","sourcesContent":["import { injectable, bindingScopeValues } from 'inversify';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { RulePackManifest, ConfigObject, RetiredConfigKey } from '@webpieces/rules-sdk';\nimport { InformAiError } from '@webpieces/tooling-common';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { NodeRulePackModuleLoader, RulePackRegistry } from './rule-pack-registry';\nimport { RepositoryPath } from './repository-path';\nimport { retiredKeyError, RETIRED_SCOPE_RULE } from './retired-config-keys';\nimport { formatConfigErrorsBanner } from './config-error-banner';\n\n/** The root declaration identifies an exact package/module and its owner-specific config file. */\nexport class PackPolicyDeclaration {\n readonly package: string;\n\n constructor(\n packageName: string,\n readonly config: string,\n ) {\n this.package = packageName;\n }\n\n moduleName(): string {\n return /\\.(?:cjs|mjs|js)$/.test(this.package) ? this.package : `${this.package}/rule-pack`;\n }\n}\n\nexport class SelectedPolicyPack {\n constructor(\n readonly declaration: PackPolicyDeclaration,\n readonly manifest: RulePackManifest,\n ) {}\n}\n\nexport class PackPolicyFilesResult {\n constructor(\n readonly registry: RulePackRegistry,\n readonly selected: readonly SelectedPolicyPack[],\n readonly values: Record<string, ConfigObject>,\n readonly targetFiles: ReadonlyMap<string, string>,\n ) {}\n}\n\n/** Configuration belongs to explicitly selected owners; loading never supplies recommended seeds. */\n@injectable(bindingScopeValues.Singleton)\nexport class PackPolicyFiles {\n // webpieces-disable no-any-unknown -- root JSON is narrowed before resolving modules or files.\n declarations(raw: unknown, root: string): PackPolicyDeclaration[] {\n if (!Array.isArray(raw) || raw.length === 0) {\n throw new InformAiError(\n 'webpieces.config.json.rulePacks is required. Run pnpm wp-rules-sync --upgrade to split the existing explicit config, or add exact {\"package\":\"<pack>\",\"config\":\".webpieces/rules/<pack>.json\"} declarations.',\n );\n }\n const packages = new Set<string>(),\n files = new Set<string>();\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n return raw.map((entry: unknown) => {\n if (\n !entry ||\n typeof entry !== 'object' ||\n Array.isArray(entry) ||\n !('package' in entry) ||\n !('config' in entry) ||\n typeof entry.package !== 'string' ||\n !entry.package ||\n typeof entry.config !== 'string' ||\n !entry.config ||\n Object.keys(entry).some((key: string) => !['package', 'config'].includes(key))\n ) {\n throw new InformAiError(\n 'Invalid rulePacks entry in webpieces.config.json. Supply exactly package and config strings.',\n );\n }\n const filename = this.configPath(root, entry.config);\n if (packages.has(entry.package) || files.has(filename)) {\n throw new InformAiError(\n `Duplicate rule-pack declaration or config path: ${entry.package}, ${entry.config}. Declare each pack and config once.`,\n );\n }\n packages.add(entry.package);\n files.add(filename);\n return new PackPolicyDeclaration(entry.package, entry.config);\n });\n }\n\n select(root: string, declarations: readonly PackPolicyDeclaration[]): SelectedPolicyPack[] {\n const loader = new NodeRulePackModuleLoader(root);\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- module failures identify the declaration's actual repair file.\n try {\n return declarations.map((declaration: PackPolicyDeclaration) => {\n const manifest = loader.load(declaration.moduleName());\n if (\n declaration.moduleName() === `${declaration.package}/rule-pack` &&\n manifest.packageName !== declaration.package\n ) {\n throw new InformAiError(\n `Declared package ${declaration.package} exports owner ${manifest.packageName}. Declare the actual owning package or an explicit client manifest module.`,\n );\n }\n return new SelectedPolicyPack(declaration, manifest);\n });\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n } catch (err: unknown) {\n const error = toError(err);\n throw new InformAiError(\n `Rule-pack selection in ${path.join(root, 'webpieces.config.json')} needs repair: ${error.message}`,\n { cause: error },\n );\n }\n }\n\n resolve(root: string, selected: readonly SelectedPolicyPack[]): PackPolicyFilesResult {\n const registry = new RulePackRegistry(\n selected.map((pack: SelectedPolicyPack) => pack.manifest),\n );\n for (const pack of selected)\n registry.recordModuleLocation(pack.manifest.packageName, pack.declaration.moduleName());\n const values: Record<string, ConfigObject> = {},\n targetFiles = new Map<string, string>();\n const errors: string[] = [];\n for (const pack of selected) {\n const filename = this.configPath(root, pack.declaration.config);\n for (const definition of pack.manifest.ownedRules)\n targetFiles.set(definition.id, filename);\n }\n for (const pack of selected) {\n const filename = this.configPath(root, pack.declaration.config);\n const entries = this.read(filename);\n for (const id of Object.keys(entries)) {\n if (!registry.hasRule(id)) {\n const retired = registry\n .migrations()\n .find(\n (entry: RetiredConfigKey) =>\n entry.scope === RETIRED_SCOPE_RULE && entry.key === id,\n );\n errors.push(\n `${filename}: ${retired ? retiredKeyError(retired) : `${id} has no declared configurable owner. Remove this entry.`}`,\n );\n } else if (registry.ownerOf(id) !== pack.manifest.packageName) {\n errors.push(\n `${filename}: ${id} belongs to ${registry.ownerOf(id)}. Move it to ${targetFiles.get(id)}.`,\n );\n }\n }\n for (const definition of pack.manifest.ownedRules) {\n if (!Object.hasOwn(entries, definition.id)) {\n errors.push(\n `${filename}: missing required entry ${definition.id}. Run pnpm wp-rules-sync to write its owner seed and review it, or configure it explicitly; OFF still requires every required field.`,\n );\n continue;\n }\n const value = entries[definition.id];\n errors.push(\n ...registry\n .validateRuleConfig(definition.id, value)\n .map((error: string) => `${filename}: ${error}`),\n );\n values[definition.id] = value;\n }\n }\n if (errors.length) {\n throw new InformAiError(\n formatConfigErrorsBanner(errors).replace(\n 'THE FIX: edit webpieces.config.json',\n 'THE FIX: edit declared owner config files',\n ) +\n '\\nEditing webpieces.config.json and the named owner files is ALWAYS allowed. Missing required settings can be written explicitly with pnpm wp-rules-sync; review and commit the diff. Required settings are never supplied during loading.',\n );\n }\n return new PackPolicyFilesResult(registry, selected, values, targetFiles);\n }\n\n configPath(root: string, relative: string): string {\n if (path.isAbsolute(relative) || !relative.endsWith('.json')) {\n throw new InformAiError(\n `Invalid pack config path ${relative}. Use a distinct repository-relative JSON file.`,\n );\n }\n let target: string;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- path faults name the declaration that needs repair\n try {\n target = new RepositoryPath(root).resolve(relative);\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n } catch (err: unknown) {\n const error = toError(err);\n throw new InformAiError(`Invalid pack config path ${relative}: ${error.message}`, {\n cause: error,\n });\n }\n const normalized = path.relative(fs.realpathSync(root), target);\n if (\n path.isAbsolute(relative) ||\n normalized.startsWith('..') ||\n !normalized.endsWith('.json') ||\n normalized === 'webpieces.config.json' ||\n normalized === '.webpieces/rules.lock.json'\n ) {\n throw new InformAiError(\n `Invalid pack config path ${relative}. Use a distinct repository-relative JSON path such as .webpieces/rules/code.json.`,\n );\n }\n return target;\n }\n\n read(filename: string): Record<string, ConfigObject> {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- malformed or absent pack files name their exact repair path.\n try {\n if (!fs.existsSync(filename)) {\n throw new InformAiError(\n `Missing rule-pack config ${filename}. Run pnpm wp-rules-sync to create explicit owner seeds, then review the diff.`,\n );\n }\n // webpieces-disable no-any-unknown -- registry validation narrows the parsed option bags.\n const entries: unknown = JSON.parse(fs.readFileSync(filename, 'utf8'));\n if (!entries || typeof entries !== 'object' || Array.isArray(entries)) {\n throw new InformAiError(\n `${filename} must be an object mapping owned rule IDs to explicit config objects.`,\n );\n }\n return entries as Record<string, ConfigObject>;\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n } catch (err: unknown) {\n const error = toError(err);\n if (error instanceof InformAiError) throw error;\n throw new InformAiError(\n `Cannot parse rule-pack config ${filename}: ${error.message}. Edit this file to restore valid JSON.`,\n { cause: error },\n );\n }\n }\n}\n"]}
1
+ {"version":3,"file":"pack-policy-files.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/pack-policy-files.ts"],"names":[],"mappings":";;;;AAAA,yCAA2D;AAC3D,oDAA8B;AAC9B,w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,0FAA0F;YAC1F,MAAM,OAAO,GAAY,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,YAAY,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC,CAAC;YACvE,IAAI,CAAC,OAAO,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;gBACpE,MAAM,IAAI,8BAAa,CACnB,GAAG,QAAQ,uEAAuE,CACrF,CAAC;YACN,CAAC;YACD,OAAO,OAAuC,CAAC;YAC/C,6GAA6G;QACjH,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,IAAI,KAAK,YAAY,8BAAa;gBAAE,MAAM,KAAK,CAAC;YAChD,MAAM,IAAI,8BAAa,CACnB,iCAAiC,QAAQ,KAAK,KAAK,CAAC,OAAO,yCAAyC,EACpG,EAAE,KAAK,EAAE,KAAK,EAAE,CACnB,CAAC;QACN,CAAC;IACL,CAAC;CACJ,CAAA;AA3LY,0CAAe;0BAAf,eAAe;IAD3B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;GAC5B,eAAe,CA2L3B","sourcesContent":["import { injectable, bindingScopeValues } from 'inversify';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { RulePackManifest, ConfigObject, RetiredConfigKey } from '@webpieces/rules-sdk';\nimport { InformAiError, RepositoryLayout } from '@webpieces/tooling-common';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { NodeRulePackModuleLoader, RulePackRegistry } from './rule-pack-registry';\nimport { RepositoryPath } from './repository-path';\nimport { retiredKeyError, RETIRED_SCOPE_RULE } from './retired-config-keys';\nimport { formatConfigErrorsBanner } from './config-error-banner';\n\n/** The root declaration identifies an exact package/module and its owner-specific config file. */\nexport class PackPolicyDeclaration {\n readonly package: string;\n\n constructor(\n packageName: string,\n readonly config: string,\n ) {\n this.package = packageName;\n }\n\n moduleName(): string {\n return /\\.(?:cjs|mjs|js)$/.test(this.package) ? this.package : `${this.package}/rule-pack`;\n }\n}\n\nexport class SelectedPolicyPack {\n constructor(\n readonly declaration: PackPolicyDeclaration,\n readonly manifest: RulePackManifest,\n ) {}\n}\n\nexport class PackPolicyFilesResult {\n constructor(\n readonly registry: RulePackRegistry,\n readonly selected: readonly SelectedPolicyPack[],\n readonly values: Record<string, ConfigObject>,\n readonly targetFiles: ReadonlyMap<string, string>,\n ) {}\n}\n\n/** Configuration belongs to explicitly selected owners; loading never supplies recommended seeds. */\n@injectable(bindingScopeValues.Singleton)\nexport class PackPolicyFiles {\n // webpieces-disable no-any-unknown -- root JSON is narrowed before resolving modules or files.\n declarations(raw: unknown, root: string): PackPolicyDeclaration[] {\n if (!Array.isArray(raw) || raw.length === 0) {\n throw new InformAiError(\n 'webpieces.config.json.rulePacks is required. Run pnpm wp-rules-sync --upgrade to split the existing explicit config, or add exact {\"package\":\"<pack>\",\"config\":\".webpieces-config/rules/<pack>.json\"} declarations.',\n );\n }\n const packages = new Set<string>(),\n files = new Set<string>();\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n return raw.map((entry: unknown) => {\n if (\n !entry ||\n typeof entry !== 'object' ||\n Array.isArray(entry) ||\n !('package' in entry) ||\n !('config' in entry) ||\n typeof entry.package !== 'string' ||\n !entry.package ||\n typeof entry.config !== 'string' ||\n !entry.config ||\n Object.keys(entry).some((key: string) => !['package', 'config'].includes(key))\n ) {\n throw new InformAiError(\n 'Invalid rulePacks entry in webpieces.config.json. Supply exactly package and config strings.',\n );\n }\n const filename = this.configPath(root, entry.config);\n if (packages.has(entry.package) || files.has(filename)) {\n throw new InformAiError(\n `Duplicate rule-pack declaration or config path: ${entry.package}, ${entry.config}. Declare each pack and config once.`,\n );\n }\n packages.add(entry.package);\n files.add(filename);\n return new PackPolicyDeclaration(entry.package, entry.config);\n });\n }\n\n select(root: string, declarations: readonly PackPolicyDeclaration[]): SelectedPolicyPack[] {\n const loader = new NodeRulePackModuleLoader(root);\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- module failures identify the declaration's actual repair file.\n try {\n return declarations.map((declaration: PackPolicyDeclaration) => {\n const manifest = loader.load(declaration.moduleName());\n if (\n declaration.moduleName() === `${declaration.package}/rule-pack` &&\n manifest.packageName !== declaration.package\n ) {\n throw new InformAiError(\n `Declared package ${declaration.package} exports owner ${manifest.packageName}. Declare the actual owning package or an explicit client manifest module.`,\n );\n }\n return new SelectedPolicyPack(declaration, manifest);\n });\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n } catch (err: unknown) {\n const error = toError(err);\n throw new InformAiError(\n `Rule-pack selection in ${path.join(root, 'webpieces.config.json')} needs repair: ${error.message}`,\n { cause: error },\n );\n }\n }\n\n resolve(root: string, selected: readonly SelectedPolicyPack[]): PackPolicyFilesResult {\n const registry = new RulePackRegistry(\n selected.map((pack: SelectedPolicyPack) => pack.manifest),\n );\n for (const pack of selected)\n registry.recordModuleLocation(pack.manifest.packageName, pack.declaration.moduleName());\n const values: Record<string, ConfigObject> = {},\n targetFiles = new Map<string, string>();\n const errors: string[] = [];\n for (const pack of selected) {\n const filename = this.configPath(root, pack.declaration.config);\n for (const definition of pack.manifest.ownedRules)\n targetFiles.set(definition.id, filename);\n }\n for (const pack of selected) {\n const filename = this.configPath(root, pack.declaration.config);\n const entries = this.read(filename);\n for (const id of Object.keys(entries)) {\n if (!registry.hasRule(id)) {\n const retired = registry\n .migrations()\n .find(\n (entry: RetiredConfigKey) =>\n entry.scope === RETIRED_SCOPE_RULE && entry.key === id,\n );\n errors.push(\n `${filename}: ${retired ? retiredKeyError(retired) : `${id} has no declared configurable owner. Remove this entry.`}`,\n );\n } else if (registry.ownerOf(id) !== pack.manifest.packageName) {\n errors.push(\n `${filename}: ${id} belongs to ${registry.ownerOf(id)}. Move it to ${targetFiles.get(id)}.`,\n );\n }\n }\n for (const definition of pack.manifest.ownedRules) {\n if (!Object.hasOwn(entries, definition.id)) {\n errors.push(\n `${filename}: missing required entry ${definition.id}. Run pnpm wp-rules-sync to write its owner seed and review it, or configure it explicitly; OFF still requires every required field.`,\n );\n continue;\n }\n const value = entries[definition.id];\n errors.push(\n ...registry\n .validateRuleConfig(definition.id, value)\n .map((error: string) => `${filename}: ${error}`),\n );\n values[definition.id] = value;\n }\n }\n if (errors.length) {\n throw new InformAiError(\n formatConfigErrorsBanner(errors).replace(\n 'THE FIX: edit webpieces.config.json',\n 'THE FIX: edit declared owner config files',\n ) +\n '\\nEditing webpieces.config.json and the named owner files is ALWAYS allowed. Missing required settings can be written explicitly with pnpm wp-rules-sync; review and commit the diff. Required settings are never supplied during loading.',\n );\n }\n return new PackPolicyFilesResult(registry, selected, values, targetFiles);\n }\n\n configPath(root: string, relative: string): string {\n if (path.isAbsolute(relative) || !relative.endsWith('.json')) {\n throw new InformAiError(\n `Invalid pack config path ${relative}. Use a distinct repository-relative JSON file.`,\n );\n }\n let target: string;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- path faults name the declaration that needs repair\n try {\n target = new RepositoryPath(root).resolve(relative);\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n } catch (err: unknown) {\n const error = toError(err);\n throw new InformAiError(`Invalid pack config path ${relative}: ${error.message}`, {\n cause: error,\n });\n }\n const normalized = path.relative(fs.realpathSync(root), target);\n if (\n path.isAbsolute(relative) ||\n normalized.startsWith('..') ||\n !normalized.endsWith('.json') ||\n normalized === 'webpieces.config.json' ||\n normalized === '.webpieces-config/rules.lock.json'\n ) {\n throw new InformAiError(\n `Invalid pack config path ${relative}. Use a distinct repository-relative JSON path such as .webpieces-config/rules/code.json.`,\n );\n }\n new RepositoryLayout().assertPolicyPath(normalized);\n return target;\n }\n\n read(filename: string): Record<string, ConfigObject> {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- malformed or absent pack files name their exact repair path.\n try {\n if (!fs.existsSync(filename)) {\n throw new InformAiError(\n `Missing rule-pack config ${filename}. Run pnpm wp-rules-sync to create explicit owner seeds, then review the diff.`,\n );\n }\n // webpieces-disable no-any-unknown -- registry validation narrows the parsed option bags.\n const entries: unknown = JSON.parse(fs.readFileSync(filename, 'utf8'));\n if (!entries || typeof entries !== 'object' || Array.isArray(entries)) {\n throw new InformAiError(\n `${filename} must be an object mapping owned rule IDs to explicit config objects.`,\n );\n }\n return entries as Record<string, ConfigObject>;\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n } catch (err: unknown) {\n const error = toError(err);\n if (error instanceof InformAiError) throw error;\n throw new InformAiError(\n `Cannot parse rule-pack config ${filename}: ${error.message}. Edit this file to restore valid JSON.`,\n { cause: error },\n );\n }\n }\n}\n"]}
@@ -0,0 +1,7 @@
1
+ import type { PackPolicyDeclaration } from './pack-policy-files';
2
+ /** Git repositories must share policy through their index, including rules switched OFF. */
3
+ export declare class PolicyTracking {
4
+ check(root: string, declarations: readonly PackPolicyDeclaration[]): void;
5
+ stage(root: string, declarations: readonly PackPolicyDeclaration[]): void;
6
+ private files;
7
+ }
@@ -0,0 +1,68 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PolicyTracking = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const fs = tslib_1.__importStar(require("node:fs"));
6
+ const path = tslib_1.__importStar(require("node:path"));
7
+ const node_child_process_1 = require("node:child_process");
8
+ const tooling_common_1 = require("@webpieces/tooling-common");
9
+ const rule_pack_artifacts_1 = require("./rule-pack-artifacts");
10
+ /** Git repositories must share policy through their index, including rules switched OFF. */
11
+ class PolicyTracking {
12
+ check(root, declarations) {
13
+ // Standalone non-git schema validation is supported; CI and governed checkouts have .git.
14
+ if (!fs.existsSync(path.join(root, '.git')))
15
+ return;
16
+ const files = this.files(root, declarations);
17
+ const ignored = (0, node_child_process_1.spawnSync)('git', ['check-ignore', '--no-index', '--', ...files], {
18
+ cwd: root,
19
+ encoding: 'utf8',
20
+ });
21
+ if (ignored.status !== 0 && ignored.status !== 1)
22
+ throw new tooling_common_1.InformAiError(`Cannot verify policy ignore status: ${ignored.stderr}. Repair git access, then retry.`);
23
+ if (ignored.stdout.trim())
24
+ throw new tooling_common_1.InformAiError(`Committed Webpieces policy is gitignored:\n${ignored.stdout}Remove the matching ignore patterns. Only .webpieces-logs/ belongs in .gitignore; .webpieces-config/ must be tracked.`);
25
+ const tracked = (0, node_child_process_1.spawnSync)('git', ['--literal-pathspecs', 'ls-files', '--error-unmatch', '--', ...files], {
26
+ cwd: root,
27
+ encoding: 'utf8',
28
+ });
29
+ if (tracked.status !== 0)
30
+ throw new tooling_common_1.InformAiError(`Webpieces policy must be tracked by git: ${tracked.stderr}\nReview the policy files, then run pnpm wp-migrate-dirs --stage to stage the declaration, owner files, lock and catalog. Commit them with your change.`);
31
+ }
32
+ stage(root, declarations) {
33
+ const retired = (0, node_child_process_1.spawnSync)('git', ['ls-files', '-z', '--', '.webpieces'], {
34
+ cwd: root,
35
+ encoding: 'utf8',
36
+ });
37
+ if (retired.status !== 0)
38
+ throw new tooling_common_1.InformAiError(`Cannot inspect retired policy paths for staging: ${retired.stderr}. Verify git access before retrying.`);
39
+ const deletions = retired.stdout.split('\0').filter((filename) => filename.length > 0);
40
+ const result = (0, node_child_process_1.spawnSync)('git', [
41
+ '--literal-pathspecs',
42
+ 'add',
43
+ '-A',
44
+ '--',
45
+ 'webpieces.config.json',
46
+ '.gitignore',
47
+ ...this.files(root, declarations),
48
+ ...deletions,
49
+ ], { cwd: root, encoding: 'utf8' });
50
+ if (result.status !== 0)
51
+ throw new tooling_common_1.InformAiError(`Could not stage Webpieces policy: ${result.stderr}. Remove policy ignore patterns and verify git access before retrying.`);
52
+ }
53
+ files(root, declarations) {
54
+ const declared = [
55
+ ...declarations.map((declaration) => declaration.config),
56
+ rule_pack_artifacts_1.RULE_LOCK_FILE,
57
+ rule_pack_artifacts_1.RULE_CATALOG_FILE,
58
+ ];
59
+ return [
60
+ ...new Set(declared.flatMap((filename) => [
61
+ filename,
62
+ path.relative(fs.realpathSync(root), fs.realpathSync(path.join(root, filename))),
63
+ ])),
64
+ ];
65
+ }
66
+ }
67
+ exports.PolicyTracking = PolicyTracking;
68
+ //# sourceMappingURL=policy-tracking.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"policy-tracking.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/policy-tracking.ts"],"names":[],"mappings":";;;;AAAA,oDAA8B;AAC9B,wDAAkC;AAClC,2DAA+C;AAC/C,8DAA0D;AAE1D,+DAA0E;AAE1E,4FAA4F;AAC5F,MAAa,cAAc;IACvB,KAAK,CAAC,IAAY,EAAE,YAA8C;QAC9D,0FAA0F;QAC1F,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;YAAE,OAAO;QACpD,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;QAC7C,MAAM,OAAO,GAAG,IAAA,8BAAS,EAAC,KAAK,EAAE,CAAC,cAAc,EAAE,YAAY,EAAE,IAAI,EAAE,GAAG,KAAK,CAAC,EAAE;YAC7E,GAAG,EAAE,IAAI;YACT,QAAQ,EAAE,MAAM;SACnB,CAAC,CAAC;QACH,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;YAC5C,MAAM,IAAI,8BAAa,CACnB,uCAAuC,OAAO,CAAC,MAAM,kCAAkC,CAC1F,CAAC;QACN,IAAI,OAAO,CAAC,MAAM,CAAC,IAAI,EAAE;YACrB,MAAM,IAAI,8BAAa,CACnB,8CAA8C,OAAO,CAAC,MAAM,uHAAuH,CACtL,CAAC;QACN,MAAM,OAAO,GAAG,IAAA,8BAAS,EACrB,KAAK,EACL,CAAC,qBAAqB,EAAE,UAAU,EAAE,iBAAiB,EAAE,IAAI,EAAE,GAAG,KAAK,CAAC,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AE,EAAE,CAAC,WAAW,CAAC,MAAM,CAAC;YACxD,oCAAc;YACd,uCAAiB;SACpB,CAAC;QACF,OAAO;YACH,GAAG,IAAI,GAAG,CACN,QAAQ,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC;gBAC3B,QAAQ;gBACR,IAAI,CAAC,QAAQ,CACT,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,EACrB,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC,CAC7C;aACJ,CAAC,CACL;SACJ,CAAC;IACN,CAAC;CACJ;AA/ED,wCA+EC","sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { spawnSync } from 'node:child_process';\nimport { InformAiError } from '@webpieces/tooling-common';\nimport type { PackPolicyDeclaration } from './pack-policy-files';\nimport { RULE_LOCK_FILE, RULE_CATALOG_FILE } from './rule-pack-artifacts';\n\n/** Git repositories must share policy through their index, including rules switched OFF. */\nexport class PolicyTracking {\n check(root: string, declarations: readonly PackPolicyDeclaration[]): void {\n // Standalone non-git schema validation is supported; CI and governed checkouts have .git.\n if (!fs.existsSync(path.join(root, '.git'))) return;\n const files = this.files(root, declarations);\n const ignored = spawnSync('git', ['check-ignore', '--no-index', '--', ...files], {\n cwd: root,\n encoding: 'utf8',\n });\n if (ignored.status !== 0 && ignored.status !== 1)\n throw new InformAiError(\n `Cannot verify policy ignore status: ${ignored.stderr}. Repair git access, then retry.`,\n );\n if (ignored.stdout.trim())\n throw new InformAiError(\n `Committed Webpieces policy is gitignored:\\n${ignored.stdout}Remove the matching ignore patterns. Only .webpieces-logs/ belongs in .gitignore; .webpieces-config/ must be tracked.`,\n );\n const tracked = spawnSync(\n 'git',\n ['--literal-pathspecs', 'ls-files', '--error-unmatch', '--', ...files],\n {\n cwd: root,\n encoding: 'utf8',\n },\n );\n if (tracked.status !== 0)\n throw new InformAiError(\n `Webpieces policy must be tracked by git: ${tracked.stderr}\\nReview the policy files, then run pnpm wp-migrate-dirs --stage to stage the declaration, owner files, lock and catalog. Commit them with your change.`,\n );\n }\n\n stage(root: string, declarations: readonly PackPolicyDeclaration[]): void {\n const retired = spawnSync('git', ['ls-files', '-z', '--', '.webpieces'], {\n cwd: root,\n encoding: 'utf8',\n });\n if (retired.status !== 0)\n throw new InformAiError(\n `Cannot inspect retired policy paths for staging: ${retired.stderr}. Verify git access before retrying.`,\n );\n const deletions = retired.stdout.split('\\0').filter((filename) => filename.length > 0);\n const result = spawnSync(\n 'git',\n [\n '--literal-pathspecs',\n 'add',\n '-A',\n '--',\n 'webpieces.config.json',\n '.gitignore',\n ...this.files(root, declarations),\n ...deletions,\n ],\n { cwd: root, encoding: 'utf8' },\n );\n if (result.status !== 0)\n throw new InformAiError(\n `Could not stage Webpieces policy: ${result.stderr}. Remove policy ignore patterns and verify git access before retrying.`,\n );\n }\n\n private files(root: string, declarations: readonly PackPolicyDeclaration[]): string[] {\n const declared = [\n ...declarations.map((declaration) => declaration.config),\n RULE_LOCK_FILE,\n RULE_CATALOG_FILE,\n ];\n return [\n ...new Set(\n declared.flatMap((filename) => [\n filename,\n path.relative(\n fs.realpathSync(root),\n fs.realpathSync(path.join(root, filename)),\n ),\n ]),\n ),\n ];\n }\n}\n"]}
@@ -138,7 +138,7 @@ export declare class PrGateConfig {
138
138
  */
139
139
  landPr: LandPrConfig;
140
140
  /**
141
- * Globs whose diffs are NOT extracted into `.webpieces/pr-review/<feature>/diff/` — regenerated noise a
141
+ * Globs whose diffs are NOT extracted into `.webpieces-logs/pr-review/<feature>/diff/` — regenerated noise a
142
142
  * reviewer should not spend context reading (lockfiles, generated graphs). Default [].
143
143
  *
144
144
  * They are still MATCHED against checklists and still listed in the manifest, with a stub naming the
@@ -205,7 +205,7 @@ class PrGateConfig {
205
205
  */
206
206
  landPr = defaultLandPrConfig();
207
207
  /**
208
- * Globs whose diffs are NOT extracted into `.webpieces/pr-review/<feature>/diff/` — regenerated noise a
208
+ * Globs whose diffs are NOT extracted into `.webpieces-logs/pr-review/<feature>/diff/` — regenerated noise a
209
209
  * reviewer should not spend context reading (lockfiles, generated graphs). Default [].
210
210
  *
211
211
  * They are still MATCHED against checklists and still listed in the manifest, with a stub naming the