@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":"rule-pack-artifacts.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/rule-pack-artifacts.ts"],"names":[],"mappings":";;;;AAAA,yCAA2D;AAC3D,oDAA8B;AAC9B,uDAAmD;AACnD,6CAAyC;AAOzC,8DAAsE;AAGzD,QAAA,cAAc,GAAG,4BAA4B,CAAC;AAC9C,QAAA,iBAAiB,GAAG,yCAAyC,CAAC;AAE3E,MAAM,eAAe;IAEJ;IACA;IAFb,YACa,EAAU,EACV,gBAAwB;QADxB,OAAE,GAAF,EAAE,CAAQ;QACV,qBAAgB,GAAhB,gBAAgB,CAAQ;IAClC,CAAC;CACP;AAED,MAAM,cAAc;IAYH;IAXJ,OAAO,CAAS;IAChB,MAAM,CAAS;IACf,WAAW,CAAS;IACpB,cAAc,CAAS;IACvB,kBAAkB,CAAS;IAC3B,UAAU,CAA6B;IACvC,aAAa,CAA8B;IAC3C,UAAU,CAAiC;IAEpD,YACI,IAAwB,EACf,cAAsB;QAAtB,mBAAc,GAAd,cAAc,CAAQ;QAE/B,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC;QACxC,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC;QACtC,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,QAAQ,CAAC,WAAW,C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AAE,CAAC;YAC5B,MAAM,IAAI,8BAAa,CACnB,uHAAuH,CAC1H,CAAC;QACN,CAAC;QACD,6GAA6G;QAC7G,MAAM,MAAM,GAAG,KAAgC,CAAC;QAChD,OAAO,MAAM,CAAC,WAAW,CACrB,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC;aACd,IAAI,EAAE;aACN,MAAM,CAAC,CAAC,GAAW,EAAE,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,SAAS,CAAC;aAClD,GAAG,CAAC,CAAC,GAAW,EAAE,EAAE,CAAC,CAAC,GAAG,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAChE,CAAC;IACN,CAAC;CACJ,CAAA;AApJY,8CAAiB;4BAAjB,iBAAiB;IAD7B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEA,2BAAU;GADtC,iBAAiB,CAoJ7B","sourcesContent":["import { injectable, bindingScopeValues } from 'inversify';\nimport * as fs from 'node:fs';\nimport { RepositoryPath } from './repository-path';\nimport { createHash } from 'node:crypto';\nimport {\n ConfigObject,\n OwnedRuleDefinition,\n RuleContribution,\n SafeguardDefinition,\n} from '@webpieces/rules-sdk';\nimport { AtomicFile, InformAiError } from '@webpieces/tooling-common';\nimport { PackPolicyFilesResult, SelectedPolicyPack } from './pack-policy-files';\n\nexport const RULE_LOCK_FILE = '.webpieces/rules.lock.json';\nexport const RULE_CATALOG_FILE = '.webpieces/instruct-ai/rules-catalog.md';\n\nclass LockedOwnedRule {\n constructor(\n readonly id: string,\n readonly schemaApiVersion: number,\n ) {}\n}\n\nclass LockedRulePack {\n readonly package: string;\n readonly config: string;\n readonly packageName: string;\n readonly packageVersion: string;\n readonly manifestApiVersion: number;\n readonly ownedRules: readonly LockedOwnedRule[];\n readonly contributions: readonly RuleContribution[];\n readonly safeguards: readonly SafeguardDefinition[];\n\n constructor(\n pack: SelectedPolicyPack,\n readonly manifestDigest: string,\n ) {\n this.package = pack.declaration.package;\n this.config = pack.declaration.config;\n this.packageName = pack.manifest.packageName;\n this.packageVersion = pack.manifest.packageVersion;\n this.manifestApiVersion = pack.manifest.apiVersion;\n this.ownedRules = pack.manifest.ownedRules.map(\n (definition: OwnedRuleDefinition) =>\n new LockedOwnedRule(definition.id, definition.schemaApiVersion),\n );\n this.contributions = pack.manifest.contributions;\n this.safeguards = pack.manifest.safeguards;\n }\n}\n\nclass RuleLock {\n readonly schemaVersion = 1;\n constructor(readonly packs: readonly LockedRulePack[]) {}\n}\n\nexport class RuleArtifactContents {\n constructor(\n readonly lock: string,\n readonly catalog: string,\n ) {}\n}\n\n/** One resolved owner/contributor registry produces both deterministic committed artifacts. */\n@injectable(bindingScopeValues.Singleton)\nexport class RulePackArtifacts {\n constructor(private readonly atomic: AtomicFile) {}\n\n paths(root: string): readonly string[] {\n const repository = new RepositoryPath(root);\n return [repository.resolve(RULE_LOCK_FILE), repository.resolve(RULE_CATALOG_FILE)];\n }\n\n render(resolved: PackPolicyFilesResult): RuleArtifactContents {\n const selected = [...resolved.selected].sort(\n (a: SelectedPolicyPack, b: SelectedPolicyPack) =>\n a.manifest.packageName < b.manifest.packageName\n ? -1\n : a.manifest.packageName > b.manifest.packageName\n ? 1\n : 0,\n );\n const locks = selected.map(\n (pack: SelectedPolicyPack) => new LockedRulePack(pack, this.digest(pack.manifest)),\n );\n const rows: string[] = [];\n for (const pack of selected) {\n for (const definition of pack.manifest.ownedRules) {\n rows.push(\n this.policyRow(pack, definition, resolved.values[definition.id], selected),\n );\n }\n for (const safeguard of pack.manifest.safeguards) {\n rows.push(\n `| ${this.cell(safeguard.id)} | ${this.cell(pack.manifest.packageName)} | ${safeguard.activation} safeguard | — | ${this.cell(safeguard.description)} | Owner safety invariant |`,\n );\n }\n }\n const catalog = [\n '# Declared rule catalog',\n '',\n 'Generated by `pnpm wp-rules-sync` from the selected installed manifests and explicit owner config files.',\n 'Configurable policies require every required setting even when mode is `OFF`. Fixed safeguards have no config switch.',\n '',\n '| Policy | Owner | Status / contributors | Config file | Description | Remediation |',\n '| --- | --- | --- | --- | --- | --- |',\n ...rows,\n '',\n ].join('\\n');\n return new RuleArtifactContents(this.stable(new RuleLock(locks)), catalog);\n }\n\n check(root: string, resolved: PackPolicyFilesResult): void {\n const contents = this.render(resolved);\n const errors: string[] = [];\n for (const artifact of [\n [RULE_LOCK_FILE, contents.lock],\n [RULE_CATALOG_FILE, contents.catalog],\n ]) {\n const filename = new RepositoryPath(root).resolve(artifact[0]);\n if (!fs.existsSync(filename)) errors.push(`Missing ${filename}.`);\n else if (fs.readFileSync(filename, 'utf8') !== artifact[1]) {\n errors.push(\n `${filename} disagrees with the root declaration, installed manifests, or explicit owner config.`,\n );\n }\n }\n if (errors.length) {\n throw new InformAiError(\n `Rule artifacts need repair:\\n${errors.map((error: string) => `• ${error}`).join('\\n')}\\nRun pnpm wp-rules-sync, review the generated diff, and commit the lock and catalog.`,\n );\n }\n }\n\n write(root: string, resolved: PackPolicyFilesResult): readonly string[] {\n const contents = this.render(resolved),\n changed: string[] = [];\n for (const artifact of [\n [RULE_LOCK_FILE, contents.lock],\n [RULE_CATALOG_FILE, contents.catalog],\n ]) {\n const filename = new RepositoryPath(root).resolve(artifact[0]);\n if (this.atomic.writeIfChanged(filename, artifact[1])) changed.push(filename);\n }\n return changed;\n }\n\n private policyRow(\n pack: SelectedPolicyPack,\n definition: OwnedRuleDefinition,\n config: ConfigObject,\n selected: readonly SelectedPolicyPack[],\n ): string {\n const contributors = selected.flatMap((provider: SelectedPolicyPack) =>\n provider.manifest.contributions\n .filter((contribution: RuleContribution) => contribution.ruleId === definition.id)\n .map(\n (contribution: RuleContribution) =>\n `${provider.manifest.packageName}:${contribution.executionKind}`,\n ),\n );\n const status = `${String(config['mode'])}; ${contributors.join(', ')}`;\n const remediation = definition.help.remediation.replaceAll(\n '{configFile}',\n pack.declaration.config,\n );\n return [\n definition.id,\n pack.manifest.packageName,\n status,\n pack.declaration.config,\n definition.help.description,\n remediation,\n ]\n .map((text: string) => this.cell(text))\n .join(' | ')\n .replace(/^/, '| ')\n .concat(' |');\n }\n\n private cell(value: string): string {\n return value.replaceAll('|', '\\\\|').replaceAll('\\n', ' ');\n }\n\n // webpieces-disable no-any-unknown -- canonical serialization accepts only the manifest's data boundary.\n private digest(value: unknown): string {\n return createHash('sha256').update(this.stable(value)).digest('hex');\n }\n\n // webpieces-disable no-any-unknown -- JSON keys are sorted recursively; functions must stay in runtime modules.\n private stable(value: unknown): string {\n return JSON.stringify(this.canonical(value), null, 2) + '\\n';\n }\n\n // webpieces-disable no-any-unknown -- recursively narrow arbitrary manifest data before serialization.\n private canonical(value: unknown): unknown {\n if (value === null || ['string', 'boolean', 'number'].includes(typeof value)) return value;\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n if (Array.isArray(value)) return value.map((entry: unknown) => this.canonical(entry));\n if (typeof value !== 'object') {\n throw new InformAiError(\n 'Rule manifests must contain only serializable data. Keep executable functions in the declared implementation modules.',\n );\n }\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n const record = value as Record<string, unknown>;\n return Object.fromEntries(\n Object.keys(record)\n .sort()\n .filter((key: string) => record[key] !== undefined)\n .map((key: string) => [key, this.canonical(record[key])]),\n );\n }\n}\n"]}
1
+ {"version":3,"file":"rule-pack-artifacts.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/rule-pack-artifacts.ts"],"names":[],"mappings":";;;;AAAA,yCAA2D;AAC3D,oDAA8B;AAC9B,uDAAmD;AACnD,6CAAyC;AAOzC,8DAAsE;AAGzD,QAAA,cAAc,GAAG,mCAAmC,CAAC;AACrD,QAAA,iBAAiB,GAAG,oCAAoC,CAAC;AAEtE,MAAM,eAAe;IAEJ;IACA;IAFb,YACa,EAAU,EACV,gBAAwB;QADxB,OAAE,GAAF,EAAE,CAAQ;QACV,qBAAgB,GAAhB,gBAAgB,CAAQ;IAClC,CAAC;CACP;AAED,MAA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AAG,IAAI,CAAC;IACjE,CAAC;IAED,uGAAuG;IAC/F,SAAS,CAAC,KAAc;QAC5B,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,QAAQ,EAAE,SAAS,EAAE,QAAQ,CAAC,CAAC,QAAQ,CAAC,OAAO,KAAK,CAAC;YAAE,OAAO,KAAK,CAAC;QAC3F,6GAA6G;QAC7G,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;YAAE,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC,KAAc,EAAE,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC;QACtF,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;YAC5B,MAAM,IAAI,8BAAa,CACnB,uHAAuH,CAC1H,CAAC;QACN,CAAC;QACD,6GAA6G;QAC7G,MAAM,MAAM,GAAG,KAAgC,CAAC;QAChD,OAAO,MAAM,CAAC,WAAW,CACrB,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC;aACd,IAAI,EAAE;aACN,MAAM,CAAC,CAAC,GAAW,EAAE,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,SAAS,CAAC;aAClD,GAAG,CAAC,CAAC,GAAW,EAAE,EAAE,CAAC,CAAC,GAAG,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAChE,CAAC;IACN,CAAC;CACJ,CAAA;AApJY,8CAAiB;4BAAjB,iBAAiB;IAD7B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEA,2BAAU;GADtC,iBAAiB,CAoJ7B","sourcesContent":["import { injectable, bindingScopeValues } from 'inversify';\nimport * as fs from 'node:fs';\nimport { RepositoryPath } from './repository-path';\nimport { createHash } from 'node:crypto';\nimport {\n ConfigObject,\n OwnedRuleDefinition,\n RuleContribution,\n SafeguardDefinition,\n} from '@webpieces/rules-sdk';\nimport { AtomicFile, InformAiError } from '@webpieces/tooling-common';\nimport { PackPolicyFilesResult, SelectedPolicyPack } from './pack-policy-files';\n\nexport const RULE_LOCK_FILE = '.webpieces-config/rules.lock.json';\nexport const RULE_CATALOG_FILE = '.webpieces-config/rules-catalog.md';\n\nclass LockedOwnedRule {\n constructor(\n readonly id: string,\n readonly schemaApiVersion: number,\n ) {}\n}\n\nclass LockedRulePack {\n readonly package: string;\n readonly config: string;\n readonly packageName: string;\n readonly packageVersion: string;\n readonly manifestApiVersion: number;\n readonly ownedRules: readonly LockedOwnedRule[];\n readonly contributions: readonly RuleContribution[];\n readonly safeguards: readonly SafeguardDefinition[];\n\n constructor(\n pack: SelectedPolicyPack,\n readonly manifestDigest: string,\n ) {\n this.package = pack.declaration.package;\n this.config = pack.declaration.config;\n this.packageName = pack.manifest.packageName;\n this.packageVersion = pack.manifest.packageVersion;\n this.manifestApiVersion = pack.manifest.apiVersion;\n this.ownedRules = pack.manifest.ownedRules.map(\n (definition: OwnedRuleDefinition) =>\n new LockedOwnedRule(definition.id, definition.schemaApiVersion),\n );\n this.contributions = pack.manifest.contributions;\n this.safeguards = pack.manifest.safeguards;\n }\n}\n\nclass RuleLock {\n readonly schemaVersion = 1;\n constructor(readonly packs: readonly LockedRulePack[]) {}\n}\n\nexport class RuleArtifactContents {\n constructor(\n readonly lock: string,\n readonly catalog: string,\n ) {}\n}\n\n/** One resolved owner/contributor registry produces both deterministic committed artifacts. */\n@injectable(bindingScopeValues.Singleton)\nexport class RulePackArtifacts {\n constructor(private readonly atomic: AtomicFile) {}\n\n paths(root: string): readonly string[] {\n const repository = new RepositoryPath(root);\n return [repository.resolve(RULE_LOCK_FILE), repository.resolve(RULE_CATALOG_FILE)];\n }\n\n render(resolved: PackPolicyFilesResult): RuleArtifactContents {\n const selected = [...resolved.selected].sort(\n (a: SelectedPolicyPack, b: SelectedPolicyPack) =>\n a.manifest.packageName < b.manifest.packageName\n ? -1\n : a.manifest.packageName > b.manifest.packageName\n ? 1\n : 0,\n );\n const locks = selected.map(\n (pack: SelectedPolicyPack) => new LockedRulePack(pack, this.digest(pack.manifest)),\n );\n const rows: string[] = [];\n for (const pack of selected) {\n for (const definition of pack.manifest.ownedRules) {\n rows.push(\n this.policyRow(pack, definition, resolved.values[definition.id], selected),\n );\n }\n for (const safeguard of pack.manifest.safeguards) {\n rows.push(\n `| ${this.cell(safeguard.id)} | ${this.cell(pack.manifest.packageName)} | ${safeguard.activation} safeguard | — | ${this.cell(safeguard.description)} | Owner safety invariant |`,\n );\n }\n }\n const catalog = [\n '# Declared rule catalog',\n '',\n 'Generated by `pnpm wp-rules-sync` from the selected installed manifests and explicit owner config files.',\n 'Configurable policies require every required setting even when mode is `OFF`. Fixed safeguards have no config switch.',\n '',\n '| Policy | Owner | Status / contributors | Config file | Description | Remediation |',\n '| --- | --- | --- | --- | --- | --- |',\n ...rows,\n '',\n ].join('\\n');\n return new RuleArtifactContents(this.stable(new RuleLock(locks)), catalog);\n }\n\n check(root: string, resolved: PackPolicyFilesResult): void {\n const contents = this.render(resolved);\n const errors: string[] = [];\n for (const artifact of [\n [RULE_LOCK_FILE, contents.lock],\n [RULE_CATALOG_FILE, contents.catalog],\n ]) {\n const filename = new RepositoryPath(root).resolve(artifact[0]);\n if (!fs.existsSync(filename)) errors.push(`Missing ${filename}.`);\n else if (fs.readFileSync(filename, 'utf8') !== artifact[1]) {\n errors.push(\n `${filename} disagrees with the root declaration, installed manifests, or explicit owner config.`,\n );\n }\n }\n if (errors.length) {\n throw new InformAiError(\n `Rule artifacts need repair:\\n${errors.map((error: string) => `• ${error}`).join('\\n')}\\nRun pnpm wp-rules-sync, review the generated diff, and commit the lock and catalog.`,\n );\n }\n }\n\n write(root: string, resolved: PackPolicyFilesResult): readonly string[] {\n const contents = this.render(resolved),\n changed: string[] = [];\n for (const artifact of [\n [RULE_LOCK_FILE, contents.lock],\n [RULE_CATALOG_FILE, contents.catalog],\n ]) {\n const filename = new RepositoryPath(root).resolve(artifact[0]);\n if (this.atomic.writeIfChanged(filename, artifact[1])) changed.push(filename);\n }\n return changed;\n }\n\n private policyRow(\n pack: SelectedPolicyPack,\n definition: OwnedRuleDefinition,\n config: ConfigObject,\n selected: readonly SelectedPolicyPack[],\n ): string {\n const contributors = selected.flatMap((provider: SelectedPolicyPack) =>\n provider.manifest.contributions\n .filter((contribution: RuleContribution) => contribution.ruleId === definition.id)\n .map(\n (contribution: RuleContribution) =>\n `${provider.manifest.packageName}:${contribution.executionKind}`,\n ),\n );\n const status = `${String(config['mode'])}; ${contributors.join(', ')}`;\n const remediation = definition.help.remediation.replaceAll(\n '{configFile}',\n pack.declaration.config,\n );\n return [\n definition.id,\n pack.manifest.packageName,\n status,\n pack.declaration.config,\n definition.help.description,\n remediation,\n ]\n .map((text: string) => this.cell(text))\n .join(' | ')\n .replace(/^/, '| ')\n .concat(' |');\n }\n\n private cell(value: string): string {\n return value.replaceAll('|', '\\\\|').replaceAll('\\n', ' ');\n }\n\n // webpieces-disable no-any-unknown -- canonical serialization accepts only the manifest's data boundary.\n private digest(value: unknown): string {\n return createHash('sha256').update(this.stable(value)).digest('hex');\n }\n\n // webpieces-disable no-any-unknown -- JSON keys are sorted recursively; functions must stay in runtime modules.\n private stable(value: unknown): string {\n return JSON.stringify(this.canonical(value), null, 2) + '\\n';\n }\n\n // webpieces-disable no-any-unknown -- recursively narrow arbitrary manifest data before serialization.\n private canonical(value: unknown): unknown {\n if (value === null || ['string', 'boolean', 'number'].includes(typeof value)) return value;\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n if (Array.isArray(value)) return value.map((entry: unknown) => this.canonical(entry));\n if (typeof value !== 'object') {\n throw new InformAiError(\n 'Rule manifests must contain only serializable data. Keep executable functions in the declared implementation modules.',\n );\n }\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n const record = value as Record<string, unknown>;\n return Object.fromEntries(\n Object.keys(record)\n .sort()\n .filter((key: string) => record[key] !== undefined)\n .map((key: string) => [key, this.canonical(record[key])]),\n );\n }\n}\n"]}
@@ -45,6 +45,7 @@ let RulePackSync = class RulePackSync {
45
45
  this.atomic = atomic;
46
46
  }
47
47
  run(root, options) {
48
+ const layoutChanges = new tooling_common_1.RepositoryLayout().migrate(root);
48
49
  const filename = path.join(root, config_file_1.CONFIG_FILENAME);
49
50
  // webpieces-disable no-any-unknown -- migration reads opaque JSON only at this explicit command boundary
50
51
  const document = this.configFile.readRawConfig(filename);
@@ -63,7 +64,7 @@ let RulePackSync = class RulePackSync {
63
64
  // Validate artifact data and canonical destination paths before changing any owner file.
64
65
  this.artifacts.render(prepared.resolved);
65
66
  this.artifacts.paths(root);
66
- const changed = [];
67
+ const changed = [...layoutChanges];
67
68
  for (const plan of prepared.plans) {
68
69
  if (this.atomic.writeIfChanged(plan.filename, JSON.stringify(plan.entries, null, 2) + '\n'))
69
70
  changed.push(plan.filename);
@@ -86,7 +87,7 @@ let RulePackSync = class RulePackSync {
86
87
  const metadata = this.object(pkg['webpieces'], 'package.json.webpieces');
87
88
  const entries = metadata['rulePacks'];
88
89
  if (!Array.isArray(entries) || !entries.length) {
89
- throw new tooling_common_1.InformAiError('Upgrade requires explicit pack selection. Supply --pack=<package>=.webpieces/rules/<owner>.json for every selected pack. Installed dependencies are never inferred as selected packs.');
90
+ throw new tooling_common_1.InformAiError('Upgrade requires explicit pack selection. Supply --pack=<package>=.webpieces-config/rules/<owner>.json for every selected pack. Installed dependencies are never inferred as selected packs.');
90
91
  }
91
92
  // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution
92
93
  return entries.map((entry) => {
@@ -96,7 +97,7 @@ let RulePackSync = class RulePackSync {
96
97
  throw new tooling_common_1.InformAiError('Legacy pack modules must end in /rule-pack. Supply explicit --pack=<package-or-module>=<config.json> declarations for other modules.');
97
98
  }
98
99
  const packageName = moduleName.slice(0, -'/rule-pack'.length);
99
- return new pack_policy_files_1.PackPolicyDeclaration(packageName, `.webpieces/rules/${packageName.split('/').at(-1)}.json`);
100
+ return new pack_policy_files_1.PackPolicyDeclaration(packageName, `.webpieces-config/rules/${packageName.split('/').at(-1)}.json`);
100
101
  });
101
102
  }
102
103
  // webpieces-disable no-any-unknown -- inherited settings and untyped directory rules cannot be silently converted into declared owners
@@ -193,8 +194,8 @@ let RulePackSync = class RulePackSync {
193
194
  document, declarations, mode) {
194
195
  const next = { ...document, rulePacks: declarations };
195
196
  if (mode === 'upgrade')
197
+ // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution
196
198
  for (const key of ['rules', 'hookGuards', 'rulesDir', 'extends'])
197
- // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution
198
199
  delete next[key];
199
200
  return next;
200
201
  }
@@ -1 +1 @@
1
- {"version":3,"file":"rule-pack-sync.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/rule-pack-sync.ts"],"names":[],"mappings":";;;;AAAA,oDAA8B;AAC9B,wDAAkC;AAClC,yCAA2D;AAC3D,oDAAyE;AACzE,8DAAsE;AACtE,+CAA4D;AAC5D,2DAK6B;AAC7B,+DAA0D;AAC1D,6DAAwD;AACxD,yDAA0D;AAC1D,+EAAwE;AACxE,uDAAoF;AACpF,mEAA+D;AAE/D,MAAa,mBAAmB;IAEf;IACA;IAFb,YACa,IAAwB,EACxB,YAAqD;QADrD,SAAI,GAAJ,IAAI,CAAoB;QACxB,iBAAY,GAAZ,YAAY,CAAyC;IAC/D,CAAC;CACP;AALD,kDAKC;AAED,MAAM,aAAa;IAEF;IACA;IAFb,YACa,QAAgB,EAChB,OAAqC;QADrC,aAAQ,GAAR,QAAQ,CAAQ;QAChB,YAAO,GAAP,OAAO,CAA8B;IAC/C,CAAC;CACP;AAED,qFAAqF;AAE9E,IAAM,YAAY,GAAlB,MAAM,YAAY;IAEA;IACA;IACA;IACA;IAJrB,YACqB,UAAsB,EACtB,KAAsB,EACtB,SAA4B,EAC5B,MAAkB;QAHlB,eAAU,GAAV,UAAU,CAAY;QACtB,UAAK,GAAL,KAAK,CAAiB;QACtB,cAAS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A6G;QAC7G,OAAO,KAAgC,CAAC;IAC5C,CAAC;CACJ,CAAA;AA/PY,oCAAY;uBAAZ,YAAY;IADxB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGJ,wBAAU;QACf,mCAAe;QACX,uCAAiB;QACpB,2BAAU;GAL9B,YAAY,CA+PxB;AAED,MAAM,gBAAgB;IAEL;IACA;IAFb,YACa,KAA+B,EAC/B,QAA+B;QAD/B,UAAK,GAAL,KAAK,CAA0B;QAC/B,aAAQ,GAAR,QAAQ,CAAuB;IACzC,CAAC;CACP","sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { ConfigObject, OwnedRuleDefinition } from '@webpieces/rules-sdk';\nimport { AtomicFile, InformAiError } from '@webpieces/tooling-common';\nimport { ConfigFile, CONFIG_FILENAME } from './config-file';\nimport {\n PackPolicyDeclaration,\n PackPolicyFiles,\n PackPolicyFilesResult,\n SelectedPolicyPack,\n} from './pack-policy-files';\nimport { RulePackArtifacts } from './rule-pack-artifacts';\nimport { RulePackRegistry } from './rule-pack-registry';\nimport { validateTopLevelKeys } from './config-key-rules';\nimport { validateCommandsSection } from './commands-section-validators';\nimport { validateExcludePaths, validateMatchRulesSection } from './validate-config';\nimport { prepareLegacyUpgrade } from './legacy-config-upgrade';\n\nexport class RulePackSyncOptions {\n constructor(\n readonly mode: 'sync' | 'upgrade',\n readonly declarations: readonly PackPolicyDeclaration[] | null,\n ) {}\n}\n\nclass OwnerFilePlan {\n constructor(\n readonly filename: string,\n readonly entries: Record<string, ConfigObject>,\n ) {}\n}\n\n/** Explicit file mutation; normal configuration loading never calls this service. */\n@injectable(bindingScopeValues.Singleton)\nexport class RulePackSync {\n constructor(\n private readonly configFile: ConfigFile,\n private readonly files: PackPolicyFiles,\n private readonly artifacts: RulePackArtifacts,\n private readonly atomic: AtomicFile,\n ) {}\n\n run(root: string, options: RulePackSyncOptions): readonly string[] {\n const filename = path.join(root, CONFIG_FILENAME);\n // webpieces-disable no-any-unknown -- migration reads opaque JSON only at this explicit command boundary\n const document = this.configFile.readRawConfig(filename) as Record<string, unknown>;\n const declarations =\n options.declarations ?? this.selectedDeclarations(document, root, options.mode);\n const selected = this.files.select(root, this.files.declarations(declarations, root));\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 upgraded =\n options.mode === 'upgrade' ? this.upgradeDocument(document, registry) : document;\n const legacy =\n options.mode === 'upgrade'\n ? this.legacyEntries(upgraded, registry)\n : new Map<string, ConfigObject>();\n const prepared = this.prepare(root, selected, registry, legacy);\n const next = this.rootDocument(upgraded, declarations, options.mode);\n this.validateRoot(next, root);\n // Validate artifact data and canonical destination paths before changing any owner file.\n this.artifacts.render(prepared.resolved);\n this.artifacts.paths(root);\n const changed: string[] = [];\n for (const plan of prepared.plans) {\n if (\n this.atomic.writeIfChanged(\n plan.filename,\n JSON.stringify(plan.entries, null, 2) + '\\n',\n )\n )\n changed.push(plan.filename);\n }\n changed.push(...this.artifacts.write(root, prepared.resolved));\n // Commit the root declaration last: all referenced files have already been validated and written.\n if (this.atomic.writeIfChanged(filename, JSON.stringify(next, null, 2) + '\\n'))\n changed.push(filename);\n return changed;\n }\n\n // webpieces-disable no-any-unknown -- only an explicit upgrade may read the previous root shape\n private selectedDeclarations(\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n document: Record<string, unknown>,\n root: string,\n mode: 'sync' | 'upgrade',\n ): readonly PackPolicyDeclaration[] {\n if (document['rulePacks'] !== undefined)\n return this.files.declarations(document['rulePacks'], root);\n if (mode !== 'upgrade') return this.files.declarations(undefined, root);\n const pkg = this.configFile.readRawConfig(path.join(root, 'package.json')) as Record<\n string,\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n unknown\n >;\n const metadata = this.object(pkg['webpieces'], 'package.json.webpieces');\n const entries = metadata['rulePacks'];\n if (!Array.isArray(entries) || !entries.length) {\n throw new InformAiError(\n 'Upgrade requires explicit pack selection. Supply --pack=<package>=.webpieces/rules/<owner>.json for every selected pack. Installed dependencies are never inferred as selected packs.',\n );\n }\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n return entries.map((entry: unknown) => {\n const declaration = this.object(entry, 'legacy package.json.webpieces.rulePacks entry');\n const moduleName = declaration['module'];\n if (typeof moduleName !== 'string' || !moduleName.endsWith('/rule-pack')) {\n throw new InformAiError(\n 'Legacy pack modules must end in /rule-pack. Supply explicit --pack=<package-or-module>=<config.json> declarations for other modules.',\n );\n }\n const packageName = moduleName.slice(0, -'/rule-pack'.length);\n return new PackPolicyDeclaration(\n packageName,\n `.webpieces/rules/${packageName.split('/').at(-1)}.json`,\n );\n });\n }\n\n // webpieces-disable no-any-unknown -- inherited settings and untyped directory rules cannot be silently converted into declared owners\n private upgradeDocument(\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n document: Record<string, unknown>,\n registry: RulePackRegistry,\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n ): Record<string, unknown> {\n if (document['extends'] !== undefined)\n throw new InformAiError(\n 'Remove extends after making inherited values explicit. Upgrade cannot infer inherited policy settings.',\n );\n const directories = document['rulesDir'];\n if (\n directories !== undefined &&\n (!Array.isArray(directories) || directories.length !== 0)\n ) {\n throw new InformAiError(\n 'Replace rulesDir with a declared client rule pack, its owned schemas, and implementation modules before upgrade. Directory implementations cannot supply an inferred schema.',\n );\n }\n if (!Object.hasOwn(document, 'rules') && !Object.hasOwn(document, 'hookGuards'))\n return document;\n const prepared = prepareLegacyUpgrade(structuredClone(document), registry);\n return { ...document, ...prepared.config };\n }\n\n // webpieces-disable no-any-unknown -- explicit upgrade gathers settings by canonical owner after applying owner-declared retirements\n private legacyEntries(\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n document: Record<string, unknown>,\n registry: RulePackRegistry,\n ): Map<string, ConfigObject> {\n if (document['extends'] !== undefined)\n throw new InformAiError(\n 'Remove extends after making inherited values explicit. Upgrade cannot infer inherited policy settings.',\n );\n const directories = document['rulesDir'];\n if (\n directories !== undefined &&\n (!Array.isArray(directories) || directories.length !== 0)\n ) {\n throw new InformAiError(\n 'Replace rulesDir with a declared client rule pack, its owned schemas, and implementation modules before upgrade. Directory implementations cannot supply an inferred schema.',\n );\n }\n const entries = new Map<string, ConfigObject>();\n for (const section of ['rules', 'hookGuards']) {\n if (document[section] === undefined) continue;\n const old = this.object(document[section], section);\n for (const id of Object.keys(old)) {\n if (!registry.hasRule(id))\n throw new InformAiError(\n `${section}.${id} has no selected owner. Declare its owner or remove the entry explicitly before upgrading.`,\n );\n if (entries.has(id))\n throw new InformAiError(\n `${id} appears in both legacy sections. Choose one explicit value before upgrading.`,\n );\n entries.set(id, this.object(old[id], `${section}.${id}`) as ConfigObject);\n }\n }\n return entries;\n }\n\n private prepare(\n root: string,\n selected: readonly SelectedPolicyPack[],\n registry: RulePackRegistry,\n legacy: ReadonlyMap<string, ConfigObject>,\n ): RulePackSyncPlan {\n const plans: OwnerFilePlan[] = [],\n values: Record<string, ConfigObject> = {},\n targets = new Map<string, string>();\n const errors: string[] = [];\n for (const pack of selected) {\n const filename = this.files.configPath(root, pack.declaration.config);\n const entries = fs.existsSync(filename) ? this.files.read(filename) : {};\n for (const id of Object.keys(entries)) {\n if (!registry.hasRule(id) || registry.ownerOf(id) !== pack.manifest.packageName) {\n errors.push(\n `${filename}: ${id} has another owner or is unknown. Move or remove it explicitly before sync.`,\n );\n }\n }\n for (const definition of pack.manifest.ownedRules) {\n const previous = Object.hasOwn(entries, definition.id)\n ? entries[definition.id]\n : legacy.get(definition.id);\n if (\n entries[definition.id] !== undefined &&\n legacy.has(definition.id) &&\n JSON.stringify(entries[definition.id]) !==\n JSON.stringify(legacy.get(definition.id))\n ) {\n errors.push(\n `${filename}: ${definition.id} conflicts with the legacy value. Choose one explicit value before upgrade.`,\n );\n }\n const value = this.seedMissing(previous, definition);\n errors.push(\n ...registry\n .validateRuleConfig(definition.id, value)\n .map((error: string) => `${filename}: ${error}`),\n );\n entries[definition.id] = value;\n values[definition.id] = value;\n targets.set(definition.id, filename);\n }\n plans.push(new OwnerFilePlan(filename, entries));\n }\n if (errors.length) throw new InformAiError(`Sync made no changes:\\n${errors.join('\\n')}`);\n return new RulePackSyncPlan(\n plans,\n new PackPolicyFilesResult(registry, selected, values, targets),\n );\n }\n\n private seedMissing(\n previous: ConfigObject | undefined,\n definition: OwnedRuleDefinition,\n ): ConfigObject {\n const value =\n previous === undefined\n ? structuredClone(definition.recommendedSeed)\n : Object.assign(new ConfigObject(), this.object(previous, definition.id));\n for (const field of Object.keys(definition.schema)) {\n if (!definition.schema[field].optional && !Object.hasOwn(value, field)) {\n value[field] = structuredClone(definition.recommendedSeed[field]);\n }\n }\n return value;\n }\n\n // webpieces-disable no-any-unknown -- explicit upgrade removes only the retired sections it actually converted\n private rootDocument(\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n document: Record<string, unknown>,\n declarations: readonly PackPolicyDeclaration[],\n mode: 'sync' | 'upgrade',\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n ): Record<string, unknown> {\n const next = { ...document, rulePacks: declarations };\n if (mode === 'upgrade')\n for (const key of ['rules', 'hookGuards', 'rulesDir', 'extends'])\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n delete (next as Record<string, unknown>)[key];\n return next;\n }\n\n // webpieces-disable no-any-unknown -- the same generic-root validators run before any write\n private validateRoot(document: Record<string, unknown>, root: string): void {\n const errors = [\n ...validateTopLevelKeys(document),\n ...validateCommandsSection(document['commands'], document['pr-gate'], root),\n ...validateExcludePaths(document['excludePaths']),\n ...validateMatchRulesSection(document['match-rules']),\n ];\n if (errors.length) throw new InformAiError(`Sync made no changes:\\n${errors.join('\\n')}`);\n }\n\n // webpieces-disable no-any-unknown -- JSON object narrowing preserves explicit values for subsequent schema validation\n private object(value: unknown, label: string): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value))\n throw new InformAiError(`${label} must be a JSON object. Repair it before sync.`);\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n return value as Record<string, unknown>;\n }\n}\n\nclass RulePackSyncPlan {\n constructor(\n readonly plans: readonly OwnerFilePlan[],\n readonly resolved: PackPolicyFilesResult,\n ) {}\n}\n"]}
1
+ {"version":3,"file":"rule-pack-sync.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/rule-pack-sync.ts"],"names":[],"mappings":";;;;AAAA,oDAA8B;AAC9B,wDAAkC;AAClC,yCAA2D;AAC3D,oDAAyE;AACzE,8DAAwF;AACxF,+CAA4D;AAC5D,2DAK6B;AAC7B,+DAA0D;AAC1D,6DAAwD;AACxD,yDAA0D;AAC1D,+EAAwE;AACxE,uDAAoF;AACpF,mEAA+D;AAE/D,MAAa,mBAAmB;IAEf;IACA;IAFb,YACa,IAAwB,EACxB,YAAqD;QADrD,SAAI,GAAJ,IAAI,CAAoB;QACxB,iBAAY,GAAZ,YAAY,CAAyC;IAC/D,CAAC;CACP;AALD,kDAKC;AAED,MAAM,aAAa;IAEF;IACA;IAFb,YACa,QAAgB,EAChB,OAAqC;QADrC,aAAQ,GAAR,QAAQ,CAAQ;QAChB,YAAO,GAAP,OAAO,CAA8B;IAC/C,CAAC;CACP;AAED,qFAAqF;AAE9E,IAAM,YAAY,GAAlB,MAAM,YAAY;IAEA;IACA;IACA;IACA;IAJrB,YACqB,UAAsB,EACtB,KAAsB,EACtB,SAA4B,EAC5B,MAAkB;QAHlB,eAAU,GAAV,UAAU,CAAY;QACtB,UAAK,GAAL,KAAK,CAAiB;QACtB,cAAS,GAAT,SAAS,CAAmB;QAC5B,WAAM,GAAN,MAAM,CAAY;IACpC,CAAC;IAEJ,GAAG,CAAC,IAAY,EAAE,OAA4B;QAC1C,MAAM,a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AgC,CAAC;IAC5C,CAAC;CACJ,CAAA;AAhQY,oCAAY;uBAAZ,YAAY;IADxB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGJ,wBAAU;QACf,mCAAe;QACX,uCAAiB;QACpB,2BAAU;GAL9B,YAAY,CAgQxB;AAED,MAAM,gBAAgB;IAEL;IACA;IAFb,YACa,KAA+B,EAC/B,QAA+B;QAD/B,UAAK,GAAL,KAAK,CAA0B;QAC/B,aAAQ,GAAR,QAAQ,CAAuB;IACzC,CAAC;CACP","sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { ConfigObject, OwnedRuleDefinition } from '@webpieces/rules-sdk';\nimport { AtomicFile, InformAiError, RepositoryLayout } from '@webpieces/tooling-common';\nimport { ConfigFile, CONFIG_FILENAME } from './config-file';\nimport {\n PackPolicyDeclaration,\n PackPolicyFiles,\n PackPolicyFilesResult,\n SelectedPolicyPack,\n} from './pack-policy-files';\nimport { RulePackArtifacts } from './rule-pack-artifacts';\nimport { RulePackRegistry } from './rule-pack-registry';\nimport { validateTopLevelKeys } from './config-key-rules';\nimport { validateCommandsSection } from './commands-section-validators';\nimport { validateExcludePaths, validateMatchRulesSection } from './validate-config';\nimport { prepareLegacyUpgrade } from './legacy-config-upgrade';\n\nexport class RulePackSyncOptions {\n constructor(\n readonly mode: 'sync' | 'upgrade',\n readonly declarations: readonly PackPolicyDeclaration[] | null,\n ) {}\n}\n\nclass OwnerFilePlan {\n constructor(\n readonly filename: string,\n readonly entries: Record<string, ConfigObject>,\n ) {}\n}\n\n/** Explicit file mutation; normal configuration loading never calls this service. */\n@injectable(bindingScopeValues.Singleton)\nexport class RulePackSync {\n constructor(\n private readonly configFile: ConfigFile,\n private readonly files: PackPolicyFiles,\n private readonly artifacts: RulePackArtifacts,\n private readonly atomic: AtomicFile,\n ) {}\n\n run(root: string, options: RulePackSyncOptions): readonly string[] {\n const layoutChanges = new RepositoryLayout().migrate(root);\n const filename = path.join(root, CONFIG_FILENAME);\n // webpieces-disable no-any-unknown -- migration reads opaque JSON only at this explicit command boundary\n const document = this.configFile.readRawConfig(filename) as Record<string, unknown>;\n const declarations =\n options.declarations ?? this.selectedDeclarations(document, root, options.mode);\n const selected = this.files.select(root, this.files.declarations(declarations, root));\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 upgraded =\n options.mode === 'upgrade' ? this.upgradeDocument(document, registry) : document;\n const legacy =\n options.mode === 'upgrade'\n ? this.legacyEntries(upgraded, registry)\n : new Map<string, ConfigObject>();\n const prepared = this.prepare(root, selected, registry, legacy);\n const next = this.rootDocument(upgraded, declarations, options.mode);\n this.validateRoot(next, root);\n // Validate artifact data and canonical destination paths before changing any owner file.\n this.artifacts.render(prepared.resolved);\n this.artifacts.paths(root);\n const changed: string[] = [...layoutChanges];\n for (const plan of prepared.plans) {\n if (\n this.atomic.writeIfChanged(\n plan.filename,\n JSON.stringify(plan.entries, null, 2) + '\\n',\n )\n )\n changed.push(plan.filename);\n }\n changed.push(...this.artifacts.write(root, prepared.resolved));\n // Commit the root declaration last: all referenced files have already been validated and written.\n if (this.atomic.writeIfChanged(filename, JSON.stringify(next, null, 2) + '\\n'))\n changed.push(filename);\n return changed;\n }\n\n // webpieces-disable no-any-unknown -- only an explicit upgrade may read the previous root shape\n private selectedDeclarations(\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n document: Record<string, unknown>,\n root: string,\n mode: 'sync' | 'upgrade',\n ): readonly PackPolicyDeclaration[] {\n if (document['rulePacks'] !== undefined)\n return this.files.declarations(document['rulePacks'], root);\n if (mode !== 'upgrade') return this.files.declarations(undefined, root);\n const pkg = this.configFile.readRawConfig(path.join(root, 'package.json')) as Record<\n string,\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n unknown\n >;\n const metadata = this.object(pkg['webpieces'], 'package.json.webpieces');\n const entries = metadata['rulePacks'];\n if (!Array.isArray(entries) || !entries.length) {\n throw new InformAiError(\n 'Upgrade requires explicit pack selection. Supply --pack=<package>=.webpieces-config/rules/<owner>.json for every selected pack. Installed dependencies are never inferred as selected packs.',\n );\n }\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n return entries.map((entry: unknown) => {\n const declaration = this.object(entry, 'legacy package.json.webpieces.rulePacks entry');\n const moduleName = declaration['module'];\n if (typeof moduleName !== 'string' || !moduleName.endsWith('/rule-pack')) {\n throw new InformAiError(\n 'Legacy pack modules must end in /rule-pack. Supply explicit --pack=<package-or-module>=<config.json> declarations for other modules.',\n );\n }\n const packageName = moduleName.slice(0, -'/rule-pack'.length);\n return new PackPolicyDeclaration(\n packageName,\n `.webpieces-config/rules/${packageName.split('/').at(-1)}.json`,\n );\n });\n }\n\n // webpieces-disable no-any-unknown -- inherited settings and untyped directory rules cannot be silently converted into declared owners\n private upgradeDocument(\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n document: Record<string, unknown>,\n registry: RulePackRegistry,\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n ): Record<string, unknown> {\n if (document['extends'] !== undefined)\n throw new InformAiError(\n 'Remove extends after making inherited values explicit. Upgrade cannot infer inherited policy settings.',\n );\n const directories = document['rulesDir'];\n if (\n directories !== undefined &&\n (!Array.isArray(directories) || directories.length !== 0)\n ) {\n throw new InformAiError(\n 'Replace rulesDir with a declared client rule pack, its owned schemas, and implementation modules before upgrade. Directory implementations cannot supply an inferred schema.',\n );\n }\n if (!Object.hasOwn(document, 'rules') && !Object.hasOwn(document, 'hookGuards'))\n return document;\n const prepared = prepareLegacyUpgrade(structuredClone(document), registry);\n return { ...document, ...prepared.config };\n }\n\n // webpieces-disable no-any-unknown -- explicit upgrade gathers settings by canonical owner after applying owner-declared retirements\n private legacyEntries(\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n document: Record<string, unknown>,\n registry: RulePackRegistry,\n ): Map<string, ConfigObject> {\n if (document['extends'] !== undefined)\n throw new InformAiError(\n 'Remove extends after making inherited values explicit. Upgrade cannot infer inherited policy settings.',\n );\n const directories = document['rulesDir'];\n if (\n directories !== undefined &&\n (!Array.isArray(directories) || directories.length !== 0)\n ) {\n throw new InformAiError(\n 'Replace rulesDir with a declared client rule pack, its owned schemas, and implementation modules before upgrade. Directory implementations cannot supply an inferred schema.',\n );\n }\n const entries = new Map<string, ConfigObject>();\n for (const section of ['rules', 'hookGuards']) {\n if (document[section] === undefined) continue;\n const old = this.object(document[section], section);\n for (const id of Object.keys(old)) {\n if (!registry.hasRule(id))\n throw new InformAiError(\n `${section}.${id} has no selected owner. Declare its owner or remove the entry explicitly before upgrading.`,\n );\n if (entries.has(id))\n throw new InformAiError(\n `${id} appears in both legacy sections. Choose one explicit value before upgrading.`,\n );\n entries.set(id, this.object(old[id], `${section}.${id}`) as ConfigObject);\n }\n }\n return entries;\n }\n\n private prepare(\n root: string,\n selected: readonly SelectedPolicyPack[],\n registry: RulePackRegistry,\n legacy: ReadonlyMap<string, ConfigObject>,\n ): RulePackSyncPlan {\n const plans: OwnerFilePlan[] = [],\n values: Record<string, ConfigObject> = {},\n targets = new Map<string, string>();\n const errors: string[] = [];\n for (const pack of selected) {\n const filename = this.files.configPath(root, pack.declaration.config);\n const entries = fs.existsSync(filename) ? this.files.read(filename) : {};\n for (const id of Object.keys(entries)) {\n if (!registry.hasRule(id) || registry.ownerOf(id) !== pack.manifest.packageName) {\n errors.push(\n `${filename}: ${id} has another owner or is unknown. Move or remove it explicitly before sync.`,\n );\n }\n }\n for (const definition of pack.manifest.ownedRules) {\n const previous = Object.hasOwn(entries, definition.id)\n ? entries[definition.id]\n : legacy.get(definition.id);\n if (\n entries[definition.id] !== undefined &&\n legacy.has(definition.id) &&\n JSON.stringify(entries[definition.id]) !==\n JSON.stringify(legacy.get(definition.id))\n ) {\n errors.push(\n `${filename}: ${definition.id} conflicts with the legacy value. Choose one explicit value before upgrade.`,\n );\n }\n const value = this.seedMissing(previous, definition);\n errors.push(\n ...registry\n .validateRuleConfig(definition.id, value)\n .map((error: string) => `${filename}: ${error}`),\n );\n entries[definition.id] = value;\n values[definition.id] = value;\n targets.set(definition.id, filename);\n }\n plans.push(new OwnerFilePlan(filename, entries));\n }\n if (errors.length) throw new InformAiError(`Sync made no changes:\\n${errors.join('\\n')}`);\n return new RulePackSyncPlan(\n plans,\n new PackPolicyFilesResult(registry, selected, values, targets),\n );\n }\n\n private seedMissing(\n previous: ConfigObject | undefined,\n definition: OwnedRuleDefinition,\n ): ConfigObject {\n const value =\n previous === undefined\n ? structuredClone(definition.recommendedSeed)\n : Object.assign(new ConfigObject(), this.object(previous, definition.id));\n for (const field of Object.keys(definition.schema)) {\n if (!definition.schema[field].optional && !Object.hasOwn(value, field)) {\n value[field] = structuredClone(definition.recommendedSeed[field]);\n }\n }\n return value;\n }\n\n // webpieces-disable no-any-unknown -- explicit upgrade removes only the retired sections it actually converted\n private rootDocument(\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n document: Record<string, unknown>,\n declarations: readonly PackPolicyDeclaration[],\n mode: 'sync' | 'upgrade',\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n ): Record<string, unknown> {\n const next = { ...document, rulePacks: declarations };\n if (mode === 'upgrade')\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n for (const key of ['rules', 'hookGuards', 'rulesDir', 'extends'])\n delete (next as Record<string, unknown>)[key];\n return next;\n }\n\n // webpieces-disable no-any-unknown -- the same generic-root validators run before any write\n private validateRoot(document: Record<string, unknown>, root: string): void {\n const errors = [\n ...validateTopLevelKeys(document),\n ...validateCommandsSection(document['commands'], document['pr-gate'], root),\n ...validateExcludePaths(document['excludePaths']),\n ...validateMatchRulesSection(document['match-rules']),\n ];\n if (errors.length) throw new InformAiError(`Sync made no changes:\\n${errors.join('\\n')}`);\n }\n\n // webpieces-disable no-any-unknown -- JSON object narrowing preserves explicit values for subsequent schema validation\n private object(value: unknown, label: string): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value))\n throw new InformAiError(`${label} must be a JSON object. Repair it before sync.`);\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n return value as Record<string, unknown>;\n }\n}\n\nclass RulePackSyncPlan {\n constructor(\n readonly plans: readonly OwnerFilePlan[],\n readonly resolved: PackPolicyFilesResult,\n ) {}\n}\n"]}
@@ -50,7 +50,7 @@ const to_error_1 = require("@webpieces/tooling-common/to-error");
50
50
  // the whole safety story: another package's bins are never touched.
51
51
  //
52
52
  // WHY NOT A postinstall HOOK. `setupDebugging.md` records the postinstall approach as ABANDONED in this
53
- // repo. The call site is the `wp-*` startup pass that regenerates `.webpieces/instruct-ai/*` — see
53
+ // repo. The call site is the `wp-*` startup pass that regenerates `.webpieces-logs/instruct-ai/*` — see
54
54
  // TemplateWriter — and that placement is the load-bearing half of the fix. This is not a tidy-up for one
55
55
  // repo: every developer's machine has this graveyard, and a cure that only cleans the tree somebody happens
56
56
  // to run it in is worthless. Riding the pass EVERY `wp-*` command takes is what makes the RELEASED sweep
@@ -1 +1 @@
1
- {"version":3,"file":"stale-bin-sweep.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/stale-bin-sweep.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,iEAA6D;AAE7D,8EAA8E;AAC9E,oDAAoD;AACpD,EAAE;AACF,0GAA0G;AAC1G,wGAAwG;AACxG,uGAAuG;AACvG,sGAAsG;AACtG,sFAAsF;AACtF,EAAE;AACF,kGAAkG;AAClG,2GAA2G;AAC3G,yGAAyG;AACzG,0GAA0G;AAC1G,2GAA2G;AAC3G,gGAAgG;AAChG,sGAAsG;AACtG,0GAA0G;AAC1G,wBAAwB;AACxB,EAAE;AACF,yGAAyG;AACzG,kGAAkG;AA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AAK,IAAI;YAAE,OAAO,IAAI,CAAC;QACjC,mJAAmJ;QACnJ,8DAA8D;QAC9D,IAAI,CAAC;YACD,EAAE,CAAC,MAAM,CAAC,IAAI,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;YACjC,OAAO,IAAI,eAAe,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QAC7C,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,OAAO,IAAI,eAAe,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;QAC5D,CAAC;IACL,CAAC;IAED;;;;;;;OAOG;IACK,cAAc,CAAC,IAAY;QAC/B,wGAAwG;QACxG,8DAA8D;QAC9D,IAAI,CAAC;YACD,IAAI,CAAC,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,cAAc,EAAE;gBAAE,OAAO,IAAI,CAAC;YACtD,IAAI,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC;gBAAE,OAAO,IAAI,CAAC;YACrC,OAAO,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;QACjC,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,KAAK,KAAK,CAAC,CAAC,gEAAgE;YAC5E,OAAO,IAAI,CAAC;QAChB,CAAC;IACL,CAAC;CACJ;AAzHD,0CAyHC;AAED,oGAAoG;AACvF,QAAA,eAAe,GAAG,IAAI,eAAe,EAAE,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { toError } from '@webpieces/tooling-common/to-error';\n\n// ---------------------------------------------------------------------------\n// SWEEP DANGLING `node_modules/.bin/wp-*` SYMLINKS.\n//\n// THE DEFECT. pnpm's linker ADDS a link for every entry in the current manifest's `bin` map, but it never\n// sweeps `.bin` for orphans left behind by a PREVIOUS version of the SAME package. `@webpieces/pr-gate`\n// and `@webpieces/ai-hook-rules` are upgraded, never removed, so nothing ever triggers a delete: every\n// bin either package has EVER shipped stays linked forever, pointing at a script that is no longer on\n// disk. A scan of nine clones on ONE machine found 18 distinct dangling `wp-*` names.\n//\n// THE DEFECT IS ONGOING, AND A ROUTINE RENAME PRODUCES IT. Measured on this repo's own upgrade to\n// 0.4.728, DURING the session that wrote this file: PR #743 hard-renamed one `wp-*` command with no alias,\n// so the new manifest declares `wp-sync-main` and no longer declares its predecessor. One `pnpm install`\n// later, `.bin` held the NEW link created that minute AND the predecessor's link still sitting there from\n// the previous install, dangling — reproduced independently in two separate trees of this repo. So this is\n// not a historical mess left by a deleted feature that a one-time migration could mop up: it is\n// regenerated by the most ordinary change a package can make, on every clone, every time. That is the\n// argument for the call site below — the sweep has to ride a path that runs ROUTINELY, because the defect\n// is created routinely.\n//\n// The predecessor's NAME is deliberately not written here, and DO NOT WRITE IT BACK IN. Two reasons, and\n// the second is the one that matters. First, nothing in the code needs it: the predicate below is\n// STRUCTURAL — a `wp-*` entry whose link target does not resolve — so naming one particular retired\n// command would invite a reader to think the sweep is a list of known dead names somebody has to keep up\n// to date. Second, a retired command named in tracked source is exactly how a dead name outlives its\n// tooling: it gets copied into a cure string, and an agent reading that cure at the moment every other\n// route is closed is handed a command that does not exist. That is the very defect this module cleans up\n// one level out, and there is no longer an automated scan standing behind this paragraph — the reader is.\n// PR #743 and the issue this shipped under carry the literal name; nothing in the tree needs to.\n//\n// WHY IT MATTERS MORE THAN TIDINESS. `ls node_modules/.bin` lists them, so a dangling entry ADVERTISES a\n// capability that does not exist — a human and an AI were both misled by that listing before checking the\n// link target — and the failure it eventually produces is self-referential and useless:\n// `Command \"wp-authorize\" not found / Did you mean \"pnpm wp-authorize\"?`. This is `upgrade-shim.ts`'s own\n// governing principle one level out: an entry pointing at a missing file is WORSE than absence.\n//\n// WHY A PREFIX AND NOT A NAME LIST. A hardcoded list of retired bin names would go stale in exactly the\n// way the symlinks did — the list assembled from the two names that prompted this would have caught 2 of\n// the 18, and it would NOT have caught the rename above, which had not happened yet when the list would\n// have been written. That is the general case: the next orphan is always created by a release later than\n// any list. A name list is also unwriteable here on purpose — see the note above about naming dead\n// commands in source. The predicate is structural instead — a `wp-` prefixed entry that is a SYMLINK whose target\n// does not exist — so it needs no maintenance and cannot miss a name nobody has thought of. The prefix is\n// the whole safety story: another package's bins are never touched.\n//\n// WHY NOT A postinstall HOOK. `setupDebugging.md` records the postinstall approach as ABANDONED in this\n// repo. The call site is the `wp-*` startup pass that regenerates `.webpieces/instruct-ai/*` — see\n// TemplateWriter — and that placement is the load-bearing half of the fix. This is not a tidy-up for one\n// repo: every developer's machine has this graveyard, and a cure that only cleans the tree somebody happens\n// to run it in is worthless. Riding the pass EVERY `wp-*` command takes is what makes the RELEASED sweep\n// reach every clone on every machine, healing each one the next time any `wp-*` command runs there.\n//\n// NOT ALSO CALLED FROM `wp-upgrade-shim`, though it would read naturally there (that bin already deletes a\n// retired FILE on the same principle). `upgrade-shim.ts` may import only `fs`/`path` so it still runs on a\n// tree too broken to load the rule engine: this package's barrel would pull in inversify and the config\n// loader, and a subpath import would resolve against the INSTALLED rules-config, which is a release behind\n// the local source — so a spawned `wp-upgrade-shim` would die on module resolution, in the one command an\n// L0-blocked session has left. Its header records that, and points here.\n//\n// DEPENDENCY-FREE ANYWAY: `fs`, `path` and `toError`. No inversify (see StaleBinSweeper), so this module\n// stays cheap for the startup path it runs on and importable by anything that later needs it.\n// ---------------------------------------------------------------------------\n\n// The one place the prefix is spelled. Everything outside it belongs to some other package.\nconst WP_BIN_PREFIX = 'wp-';\n\n/**\n * One dangling entry the sweep ACTED ON: what was linked, the target that was not there, and — when the\n * removal itself failed — why. Data-only (per CLAUDE.md).\n *\n * `failure` exists because the removal is an `fs.rmSync`, not just a probe: an unwritable `.bin` (EACCES,\n * a read-only mount) would otherwise heal silently-never while the tree kept advertising a command that\n * does not exist, which is the precise defect this module exists to remove. Not thrown — the sweep is a\n * courtesy and must never fail the `wp-*` command that called it — so the diagnostic rides back here and\n * {@link StaleBinSweeper.report} states both outcomes.\n */\nexport class StaleBinRemoval {\n name: string; // the bin name as it appeared in .bin (e.g. 'wp-authorize')\n target: string; // the link target that does not exist, as recorded in the symlink\n failure: string; // '' = removed; non-empty = still there, and this is why\n\n constructor(name: string, target: string, failure = '') {\n this.name = name;\n this.target = target;\n this.failure = failure;\n }\n}\n\n/**\n * Removes `node_modules/.bin/wp-*` entries whose symlink target is gone.\n *\n * Deliberately NOT `@injectable`: decorating it would import inversify, and this module must stay loadable\n * by `wp-upgrade-shim` on a tree that cannot build a DI container (see the header). Callers use the shared\n * {@link staleBinSweeper} instance, which is also what makes {@link sweepOnce}'s memo process-wide.\n */\nexport class StaleBinSweeper {\n // Roots already swept in THIS process. `writeTemplate` is called several times per `wp-*` command (once\n // per instruct-ai doc), and a sweep that reported per call would print the same removals repeatedly.\n private readonly swept = new Set<string>();\n\n /** Where the bins live for a tree. Public so a test can point at a fixture without guessing the layout. */\n binDir(repoRoot: string): string {\n return path.join(repoRoot, 'node_modules', '.bin');\n }\n\n /**\n * Sweep once per root per process, returning what was removed ([] on every later call for the same\n * root, and [] when there was nothing to remove — the two are indistinguishable to a caller ON PURPOSE,\n * because both mean \"say nothing\").\n */\n sweepOnce(repoRoot: string): StaleBinRemoval[] {\n if (this.swept.has(repoRoot)) return [];\n this.swept.add(repoRoot);\n return this.sweep(repoRoot);\n }\n\n /**\n * Remove every dangling `wp-*` symlink under the tree's `.bin`, returning what went. [] when the\n * directory does not exist (a linked worktree with no install of its own is the common case) or when\n * everything there resolves.\n *\n * BEST EFFORT, PER ENTRY. A `.bin` that cannot be read, or one entry that cannot be removed, must never\n * take down the `wp-*` command that called this — the sweep is a courtesy, not the command's job.\n */\n sweep(repoRoot: string): StaleBinRemoval[] {\n const dir = this.binDir(repoRoot);\n const removed: StaleBinRemoval[] = [];\n for (const name of this.entries(dir)) {\n if (!name.startsWith(WP_BIN_PREFIX)) continue;\n const removal = this.removeIfDangling(path.join(dir, name), name);\n if (removal !== null) removed.push(removal);\n }\n return removed;\n }\n\n /**\n * The lines a caller prints for a sweep. [] for an empty sweep, so REMOVING NOTHING IS SILENT — this\n * runs on every `wp-*` command and the common case must add no noise at all.\n *\n * Rendered here rather than at each call site so the two callers cannot describe the same act\n * differently; each still chooses its own output channel and its own leading icon convention.\n */\n report(removed: readonly StaleBinRemoval[]): string[] {\n if (removed.length === 0) return [];\n const gone = removed.filter((r: StaleBinRemoval): boolean => r.failure === '');\n const stuck = removed.filter((r: StaleBinRemoval): boolean => r.failure !== '');\n const lines: string[] = [];\n if (gone.length > 0) {\n lines.push(`✅ @webpieces: removed ${gone.length} dangling node_modules/.bin/wp-* symlink(s) left by an earlier release:`);\n for (const r of gone) lines.push(` ${r.name} -> ${r.target} (target missing)`);\n lines.push(' They pointed at scripts this release no longer ships, so they could only ever fail on execution.');\n }\n // A failed removal is STATED, never quietly dropped: the entry is still there, still advertising a\n // command that does not exist, and only a human can fix an unwritable .bin.\n if (stuck.length > 0) {\n lines.push(`⚠️ @webpieces: ${stuck.length} dangling node_modules/.bin/wp-* symlink(s) could NOT be removed:`);\n for (const r of stuck) lines.push(` ${r.name} -> ${r.target} (target missing; ${r.failure})`);\n lines.push(' They still advertise commands this release does not ship. Nothing else is affected — remove them by hand.');\n }\n return lines;\n }\n\n // The directory listing, or [] when there is no .bin (or it cannot be read).\n private entries(dir: string): string[] {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unreadable .bin means \"nothing to sweep\", never a failed wp-* command\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n if (!fs.existsSync(dir)) return [];\n return fs.readdirSync(dir);\n } catch (err: unknown) {\n const error = toError(err);\n void error; // best effort: no readable .bin means there is nothing to sweep\n return [];\n }\n }\n\n /**\n * Remove ONE entry if — and only if — it is a symlink whose target does not exist. Returns what was\n * acted on, with `failure` set when the entry was dangling but could not be removed; `null` when the\n * entry was not a dangling `wp-*` link at all.\n */\n private removeIfDangling(full: string, name: string): StaleBinRemoval | null {\n const target = this.danglingTarget(full);\n if (target === null) return null;\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unremovable entry is REPORTED, never fatal to the wp-* command that called the sweep\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.rmSync(full, { force: true });\n return new StaleBinRemoval(name, target);\n } catch (err: unknown) {\n const error = toError(err);\n return new StaleBinRemoval(name, target, error.message);\n }\n }\n\n /**\n * The link target of a DANGLING symlink, or `null` when this entry is not one — a real file, a live\n * link, or something we cannot stat. `existsSync` FOLLOWS symlinks, so a false answer on a path `lstat`\n * calls a link is exactly the dangling case, with no need to resolve the target ourselves.\n *\n * Split from the removal so the two catches mean different things: an unreadable entry is simply not\n * ours to touch, while a failed REMOVAL is a fact worth printing.\n */\n private danglingTarget(full: string): string | null {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an entry we cannot stat is not ours to touch\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n if (!fs.lstatSync(full).isSymbolicLink()) return null;\n if (fs.existsSync(full)) return null;\n return fs.readlinkSync(full);\n } catch (err: unknown) {\n const error = toError(err);\n void error; // best effort: an entry we cannot read is left exactly as it is\n return null;\n }\n }\n}\n\n// The shared instance — the memo in `sweepOnce` is per-instance, so every caller must use this one.\nexport const staleBinSweeper = new StaleBinSweeper();\n"]}
1
+ {"version":3,"file":"stale-bin-sweep.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/stale-bin-sweep.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,iEAA6D;AAE7D,8EAA8E;AAC9E,oDAAoD;AACpD,EAAE;AACF,0GAA0G;AAC1G,wGAAwG;AACxG,uGAAuG;AACvG,sGAAsG;AACtG,sFAAsF;AACtF,EAAE;AACF,kGAAkG;AAClG,2GAA2G;AAC3G,yGAAyG;AACzG,0GAA0G;AAC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gB,CAAC,IAAY,EAAE,IAAY;QAC/C,MAAM,MAAM,GAAG,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC;QACzC,IAAI,MAAM,KAAK,IAAI;YAAE,OAAO,IAAI,CAAC;QACjC,mJAAmJ;QACnJ,8DAA8D;QAC9D,IAAI,CAAC;YACD,EAAE,CAAC,MAAM,CAAC,IAAI,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;YACjC,OAAO,IAAI,eAAe,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QAC7C,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,OAAO,IAAI,eAAe,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;QAC5D,CAAC;IACL,CAAC;IAED;;;;;;;OAOG;IACK,cAAc,CAAC,IAAY;QAC/B,wGAAwG;QACxG,8DAA8D;QAC9D,IAAI,CAAC;YACD,IAAI,CAAC,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,cAAc,EAAE;gBAAE,OAAO,IAAI,CAAC;YACtD,IAAI,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC;gBAAE,OAAO,IAAI,CAAC;YACrC,OAAO,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;QACjC,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,KAAK,KAAK,CAAC,CAAC,gEAAgE;YAC5E,OAAO,IAAI,CAAC;QAChB,CAAC;IACL,CAAC;CACJ;AAzHD,0CAyHC;AAED,oGAAoG;AACvF,QAAA,eAAe,GAAG,IAAI,eAAe,EAAE,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { toError } from '@webpieces/tooling-common/to-error';\n\n// ---------------------------------------------------------------------------\n// SWEEP DANGLING `node_modules/.bin/wp-*` SYMLINKS.\n//\n// THE DEFECT. pnpm's linker ADDS a link for every entry in the current manifest's `bin` map, but it never\n// sweeps `.bin` for orphans left behind by a PREVIOUS version of the SAME package. `@webpieces/pr-gate`\n// and `@webpieces/ai-hook-rules` are upgraded, never removed, so nothing ever triggers a delete: every\n// bin either package has EVER shipped stays linked forever, pointing at a script that is no longer on\n// disk. A scan of nine clones on ONE machine found 18 distinct dangling `wp-*` names.\n//\n// THE DEFECT IS ONGOING, AND A ROUTINE RENAME PRODUCES IT. Measured on this repo's own upgrade to\n// 0.4.728, DURING the session that wrote this file: PR #743 hard-renamed one `wp-*` command with no alias,\n// so the new manifest declares `wp-sync-main` and no longer declares its predecessor. One `pnpm install`\n// later, `.bin` held the NEW link created that minute AND the predecessor's link still sitting there from\n// the previous install, dangling — reproduced independently in two separate trees of this repo. So this is\n// not a historical mess left by a deleted feature that a one-time migration could mop up: it is\n// regenerated by the most ordinary change a package can make, on every clone, every time. That is the\n// argument for the call site below — the sweep has to ride a path that runs ROUTINELY, because the defect\n// is created routinely.\n//\n// The predecessor's NAME is deliberately not written here, and DO NOT WRITE IT BACK IN. Two reasons, and\n// the second is the one that matters. First, nothing in the code needs it: the predicate below is\n// STRUCTURAL — a `wp-*` entry whose link target does not resolve — so naming one particular retired\n// command would invite a reader to think the sweep is a list of known dead names somebody has to keep up\n// to date. Second, a retired command named in tracked source is exactly how a dead name outlives its\n// tooling: it gets copied into a cure string, and an agent reading that cure at the moment every other\n// route is closed is handed a command that does not exist. That is the very defect this module cleans up\n// one level out, and there is no longer an automated scan standing behind this paragraph — the reader is.\n// PR #743 and the issue this shipped under carry the literal name; nothing in the tree needs to.\n//\n// WHY IT MATTERS MORE THAN TIDINESS. `ls node_modules/.bin` lists them, so a dangling entry ADVERTISES a\n// capability that does not exist — a human and an AI were both misled by that listing before checking the\n// link target — and the failure it eventually produces is self-referential and useless:\n// `Command \"wp-authorize\" not found / Did you mean \"pnpm wp-authorize\"?`. This is `upgrade-shim.ts`'s own\n// governing principle one level out: an entry pointing at a missing file is WORSE than absence.\n//\n// WHY A PREFIX AND NOT A NAME LIST. A hardcoded list of retired bin names would go stale in exactly the\n// way the symlinks did — the list assembled from the two names that prompted this would have caught 2 of\n// the 18, and it would NOT have caught the rename above, which had not happened yet when the list would\n// have been written. That is the general case: the next orphan is always created by a release later than\n// any list. A name list is also unwriteable here on purpose — see the note above about naming dead\n// commands in source. The predicate is structural instead — a `wp-` prefixed entry that is a SYMLINK whose target\n// does not exist — so it needs no maintenance and cannot miss a name nobody has thought of. The prefix is\n// the whole safety story: another package's bins are never touched.\n//\n// WHY NOT A postinstall HOOK. `setupDebugging.md` records the postinstall approach as ABANDONED in this\n// repo. The call site is the `wp-*` startup pass that regenerates `.webpieces-logs/instruct-ai/*` — see\n// TemplateWriter — and that placement is the load-bearing half of the fix. This is not a tidy-up for one\n// repo: every developer's machine has this graveyard, and a cure that only cleans the tree somebody happens\n// to run it in is worthless. Riding the pass EVERY `wp-*` command takes is what makes the RELEASED sweep\n// reach every clone on every machine, healing each one the next time any `wp-*` command runs there.\n//\n// NOT ALSO CALLED FROM `wp-upgrade-shim`, though it would read naturally there (that bin already deletes a\n// retired FILE on the same principle). `upgrade-shim.ts` may import only `fs`/`path` so it still runs on a\n// tree too broken to load the rule engine: this package's barrel would pull in inversify and the config\n// loader, and a subpath import would resolve against the INSTALLED rules-config, which is a release behind\n// the local source — so a spawned `wp-upgrade-shim` would die on module resolution, in the one command an\n// L0-blocked session has left. Its header records that, and points here.\n//\n// DEPENDENCY-FREE ANYWAY: `fs`, `path` and `toError`. No inversify (see StaleBinSweeper), so this module\n// stays cheap for the startup path it runs on and importable by anything that later needs it.\n// ---------------------------------------------------------------------------\n\n// The one place the prefix is spelled. Everything outside it belongs to some other package.\nconst WP_BIN_PREFIX = 'wp-';\n\n/**\n * One dangling entry the sweep ACTED ON: what was linked, the target that was not there, and — when the\n * removal itself failed — why. Data-only (per CLAUDE.md).\n *\n * `failure` exists because the removal is an `fs.rmSync`, not just a probe: an unwritable `.bin` (EACCES,\n * a read-only mount) would otherwise heal silently-never while the tree kept advertising a command that\n * does not exist, which is the precise defect this module exists to remove. Not thrown — the sweep is a\n * courtesy and must never fail the `wp-*` command that called it — so the diagnostic rides back here and\n * {@link StaleBinSweeper.report} states both outcomes.\n */\nexport class StaleBinRemoval {\n name: string; // the bin name as it appeared in .bin (e.g. 'wp-authorize')\n target: string; // the link target that does not exist, as recorded in the symlink\n failure: string; // '' = removed; non-empty = still there, and this is why\n\n constructor(name: string, target: string, failure = '') {\n this.name = name;\n this.target = target;\n this.failure = failure;\n }\n}\n\n/**\n * Removes `node_modules/.bin/wp-*` entries whose symlink target is gone.\n *\n * Deliberately NOT `@injectable`: decorating it would import inversify, and this module must stay loadable\n * by `wp-upgrade-shim` on a tree that cannot build a DI container (see the header). Callers use the shared\n * {@link staleBinSweeper} instance, which is also what makes {@link sweepOnce}'s memo process-wide.\n */\nexport class StaleBinSweeper {\n // Roots already swept in THIS process. `writeTemplate` is called several times per `wp-*` command (once\n // per instruct-ai doc), and a sweep that reported per call would print the same removals repeatedly.\n private readonly swept = new Set<string>();\n\n /** Where the bins live for a tree. Public so a test can point at a fixture without guessing the layout. */\n binDir(repoRoot: string): string {\n return path.join(repoRoot, 'node_modules', '.bin');\n }\n\n /**\n * Sweep once per root per process, returning what was removed ([] on every later call for the same\n * root, and [] when there was nothing to remove — the two are indistinguishable to a caller ON PURPOSE,\n * because both mean \"say nothing\").\n */\n sweepOnce(repoRoot: string): StaleBinRemoval[] {\n if (this.swept.has(repoRoot)) return [];\n this.swept.add(repoRoot);\n return this.sweep(repoRoot);\n }\n\n /**\n * Remove every dangling `wp-*` symlink under the tree's `.bin`, returning what went. [] when the\n * directory does not exist (a linked worktree with no install of its own is the common case) or when\n * everything there resolves.\n *\n * BEST EFFORT, PER ENTRY. A `.bin` that cannot be read, or one entry that cannot be removed, must never\n * take down the `wp-*` command that called this — the sweep is a courtesy, not the command's job.\n */\n sweep(repoRoot: string): StaleBinRemoval[] {\n const dir = this.binDir(repoRoot);\n const removed: StaleBinRemoval[] = [];\n for (const name of this.entries(dir)) {\n if (!name.startsWith(WP_BIN_PREFIX)) continue;\n const removal = this.removeIfDangling(path.join(dir, name), name);\n if (removal !== null) removed.push(removal);\n }\n return removed;\n }\n\n /**\n * The lines a caller prints for a sweep. [] for an empty sweep, so REMOVING NOTHING IS SILENT — this\n * runs on every `wp-*` command and the common case must add no noise at all.\n *\n * Rendered here rather than at each call site so the two callers cannot describe the same act\n * differently; each still chooses its own output channel and its own leading icon convention.\n */\n report(removed: readonly StaleBinRemoval[]): string[] {\n if (removed.length === 0) return [];\n const gone = removed.filter((r: StaleBinRemoval): boolean => r.failure === '');\n const stuck = removed.filter((r: StaleBinRemoval): boolean => r.failure !== '');\n const lines: string[] = [];\n if (gone.length > 0) {\n lines.push(`✅ @webpieces: removed ${gone.length} dangling node_modules/.bin/wp-* symlink(s) left by an earlier release:`);\n for (const r of gone) lines.push(` ${r.name} -> ${r.target} (target missing)`);\n lines.push(' They pointed at scripts this release no longer ships, so they could only ever fail on execution.');\n }\n // A failed removal is STATED, never quietly dropped: the entry is still there, still advertising a\n // command that does not exist, and only a human can fix an unwritable .bin.\n if (stuck.length > 0) {\n lines.push(`⚠️ @webpieces: ${stuck.length} dangling node_modules/.bin/wp-* symlink(s) could NOT be removed:`);\n for (const r of stuck) lines.push(` ${r.name} -> ${r.target} (target missing; ${r.failure})`);\n lines.push(' They still advertise commands this release does not ship. Nothing else is affected — remove them by hand.');\n }\n return lines;\n }\n\n // The directory listing, or [] when there is no .bin (or it cannot be read).\n private entries(dir: string): string[] {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unreadable .bin means \"nothing to sweep\", never a failed wp-* command\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n if (!fs.existsSync(dir)) return [];\n return fs.readdirSync(dir);\n } catch (err: unknown) {\n const error = toError(err);\n void error; // best effort: no readable .bin means there is nothing to sweep\n return [];\n }\n }\n\n /**\n * Remove ONE entry if — and only if — it is a symlink whose target does not exist. Returns what was\n * acted on, with `failure` set when the entry was dangling but could not be removed; `null` when the\n * entry was not a dangling `wp-*` link at all.\n */\n private removeIfDangling(full: string, name: string): StaleBinRemoval | null {\n const target = this.danglingTarget(full);\n if (target === null) return null;\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unremovable entry is REPORTED, never fatal to the wp-* command that called the sweep\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.rmSync(full, { force: true });\n return new StaleBinRemoval(name, target);\n } catch (err: unknown) {\n const error = toError(err);\n return new StaleBinRemoval(name, target, error.message);\n }\n }\n\n /**\n * The link target of a DANGLING symlink, or `null` when this entry is not one — a real file, a live\n * link, or something we cannot stat. `existsSync` FOLLOWS symlinks, so a false answer on a path `lstat`\n * calls a link is exactly the dangling case, with no need to resolve the target ourselves.\n *\n * Split from the removal so the two catches mean different things: an unreadable entry is simply not\n * ours to touch, while a failed REMOVAL is a fact worth printing.\n */\n private danglingTarget(full: string): string | null {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an entry we cannot stat is not ours to touch\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n if (!fs.lstatSync(full).isSymbolicLink()) return null;\n if (fs.existsSync(full)) return null;\n return fs.readlinkSync(full);\n } catch (err: unknown) {\n const error = toError(err);\n void error; // best effort: an entry we cannot read is left exactly as it is\n return null;\n }\n }\n}\n\n// The shared instance — the memo in `sweepOnce` is per-instance, so every caller must use this one.\nexport const staleBinSweeper = new StaleBinSweeper();\n"]}
@@ -41,7 +41,7 @@ export declare class ReviewerEvidence {
41
41
  readDiff: boolean;
42
42
  readDoc: boolean;
43
43
  /**
44
- * Named its own verdict file — `.webpieces/pr-review/<featureSlug>/review-round<N>-<id>.json` — in a tool input.
44
+ * Named its own verdict file — `.webpieces-logs/pr-review/<featureSlug>/review-round<N>-<id>.json` — in a tool input.
45
45
  *
46
46
  * Recorded, not just consumed, because it is the field that answers "who wrote this verdict?" for an
47
47
  * auditor reading provenance.json later. It is also a CREDIT channel: see
@@ -99,7 +99,7 @@ export declare class TranscriptScan {
99
99
  *
100
100
  * One class for BOTH passes — crediting (`verifyReviewers`) and evidence (`evidenceFor`) — because they
101
101
  * ask their questions of the same paths. `diffDir` is the per-branch materialization
102
- * (`.webpieces/pr-review/<featureSlug>/diff`), which is what makes it usable as PROOF of which branch a
102
+ * (`.webpieces-logs/pr-review/<featureSlug>/diff`), which is what makes it usable as PROOF of which branch a
103
103
  * reviewer looked at: the path names the branch, it is absolute, and stage ② recreates it per run.
104
104
  */
105
105
  export declare class ReviewerContext {
@@ -108,7 +108,7 @@ export declare class ReviewerContext {
108
108
  docPaths: Record<string, string>;
109
109
  /**
110
110
  * checklist id → the absolute path of the verdict file THAT checklist must write on THIS branch
111
- * (`.webpieces/pr-review/<featureSlug>/review-round<N>-<id>.json`). '' when unknown.
111
+ * (`.webpieces-logs/pr-review/<featureSlug>/review-round<N>-<id>.json`). '' when unknown.
112
112
  *
113
113
  * The strongest attribution signal available, and stronger than `diffDir`: the path is
114
114
  * worktree-absolute (naming the tree), per-branch (naming the featureSlug) AND per-checklist (naming
@@ -197,14 +197,14 @@ export declare class SubagentProvenanceService {
197
197
  * Did a tool input name `absPath` — absolutely, or RELATIVE to the transcript's own recorded `cwd`?
198
198
  *
199
199
  * Relative because that is how a reviewer whose cwd IS the repo root naturally spells it. Measured
200
- * (issue #1211): a reviewer read the diff forty times as `D=.webpieces/pr-review/<slug>/diff/files;
200
+ * (issue #1211): a reviewer read the diff forty times as `D=.webpieces-logs/pr-review/<slug>/diff/files;
201
201
  * cat $D/...` and was refused as never having opened it, because only the absolute spelling matched.
202
202
  *
203
203
  * Still branch-specific: the relative form is derived from `absPath` itself, so it carries the same
204
204
  * `<featureSlug>`, and it is only tried when `absPath` lies UNDER the recorded cwd — i.e. when the
205
205
  * relative spelling, resolved where the harness says the reviewer stood, IS this file. A reviewer of
206
206
  * another branch names another slug; a reviewer standing in another tree resolves to another path.
207
- * The relative needle must START a path token, so `/other/root/.webpieces/...` cannot satisfy it as a
207
+ * The relative needle must START a path token, so `/other/root/.webpieces-logs/...` cannot satisfy it as a
208
208
  * mere substring.
209
209
  */
210
210
  private namesPath;
@@ -335,7 +335,7 @@ export declare class SubagentProvenanceService {
335
335
  * Credit a reviewer for WHAT IT TOUCHED when neither harness-stamped field can settle it.
336
336
  *
337
337
  * Both paths compared here are ABSOLUTE and BRANCH-SPECIFIC — they live under
338
- * `<worktree>/.webpieces/pr-review/<featureSlug>/`, so the string names the tree AND the branch. A
338
+ * `<worktree>/.webpieces-logs/pr-review/<featureSlug>/`, so the string names the tree AND the branch. A
339
339
  * reviewer that worked on a different branch cannot have them in its transcript, and a reviewer of
340
340
  * this branch that ran from a mis-stamped cwd cannot avoid having them. That is the property
341
341
  * `gitBranch` lacks — this file's own sweep of 961 record-0s found the mis-stamp is the MAJORITY
@@ -63,7 +63,7 @@ class ReviewerEvidence {
63
63
  readDiff; // opened the materialized diff dir (or its own instructions file)
64
64
  readDoc; // opened its checklist's guidance doc
65
65
  /**
66
- * Named its own verdict file — `.webpieces/pr-review/<featureSlug>/review-round<N>-<id>.json` — in a tool input.
66
+ * Named its own verdict file — `.webpieces-logs/pr-review/<featureSlug>/review-round<N>-<id>.json` — in a tool input.
67
67
  *
68
68
  * Recorded, not just consumed, because it is the field that answers "who wrote this verdict?" for an
69
69
  * auditor reading provenance.json later. It is also a CREDIT channel: see
@@ -143,7 +143,7 @@ exports.TranscriptScan = TranscriptScan;
143
143
  *
144
144
  * One class for BOTH passes — crediting (`verifyReviewers`) and evidence (`evidenceFor`) — because they
145
145
  * ask their questions of the same paths. `diffDir` is the per-branch materialization
146
- * (`.webpieces/pr-review/<featureSlug>/diff`), which is what makes it usable as PROOF of which branch a
146
+ * (`.webpieces-logs/pr-review/<featureSlug>/diff`), which is what makes it usable as PROOF of which branch a
147
147
  * reviewer looked at: the path names the branch, it is absolute, and stage ② recreates it per run.
148
148
  */
149
149
  class ReviewerContext {
@@ -152,7 +152,7 @@ class ReviewerContext {
152
152
  docPaths; // checklist id → its checklist doc path ('' when none)
153
153
  /**
154
154
  * checklist id → the absolute path of the verdict file THAT checklist must write on THIS branch
155
- * (`.webpieces/pr-review/<featureSlug>/review-round<N>-<id>.json`). '' when unknown.
155
+ * (`.webpieces-logs/pr-review/<featureSlug>/review-round<N>-<id>.json`). '' when unknown.
156
156
  *
157
157
  * The strongest attribution signal available, and stronger than `diffDir`: the path is
158
158
  * worktree-absolute (naming the tree), per-branch (naming the featureSlug) AND per-checklist (naming
@@ -324,14 +324,14 @@ let SubagentProvenanceService = class SubagentProvenanceService {
324
324
  * Did a tool input name `absPath` — absolutely, or RELATIVE to the transcript's own recorded `cwd`?
325
325
  *
326
326
  * Relative because that is how a reviewer whose cwd IS the repo root naturally spells it. Measured
327
- * (issue #1211): a reviewer read the diff forty times as `D=.webpieces/pr-review/<slug>/diff/files;
327
+ * (issue #1211): a reviewer read the diff forty times as `D=.webpieces-logs/pr-review/<slug>/diff/files;
328
328
  * cat $D/...` and was refused as never having opened it, because only the absolute spelling matched.
329
329
  *
330
330
  * Still branch-specific: the relative form is derived from `absPath` itself, so it carries the same
331
331
  * `<featureSlug>`, and it is only tried when `absPath` lies UNDER the recorded cwd — i.e. when the
332
332
  * relative spelling, resolved where the harness says the reviewer stood, IS this file. A reviewer of
333
333
  * another branch names another slug; a reviewer standing in another tree resolves to another path.
334
- * The relative needle must START a path token, so `/other/root/.webpieces/...` cannot satisfy it as a
334
+ * The relative needle must START a path token, so `/other/root/.webpieces-logs/...` cannot satisfy it as a
335
335
  * mere substring.
336
336
  */
337
337
  namesPath(scan, absPath) {
@@ -623,7 +623,7 @@ let SubagentProvenanceService = class SubagentProvenanceService {
623
623
  * Credit a reviewer for WHAT IT TOUCHED when neither harness-stamped field can settle it.
624
624
  *
625
625
  * Both paths compared here are ABSOLUTE and BRANCH-SPECIFIC — they live under
626
- * `<worktree>/.webpieces/pr-review/<featureSlug>/`, so the string names the tree AND the branch. A
626
+ * `<worktree>/.webpieces-logs/pr-review/<featureSlug>/`, so the string names the tree AND the branch. A
627
627
  * reviewer that worked on a different branch cannot have them in its transcript, and a reviewer of
628
628
  * this branch that ran from a mis-stamped cwd cannot avoid having them. That is the property
629
629
  * `gitBranch` lacks — this file's own sweep of 961 record-0s found the mis-stamp is the MAJORITY