@webpieces/rules-config 0.4.916 → 0.4.917

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 (78) hide show
  1. package/package.json +5 -5
  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/constants.js +3 -3
  17. package/src/constants.js.map +1 -1
  18. package/src/exclude-hook-paths.d.ts +5 -5
  19. package/src/exclude-hook-paths.js +5 -5
  20. package/src/exclude-hook-paths.js.map +1 -1
  21. package/src/exclude-paths.d.ts +1 -1
  22. package/src/exclude-paths.js +1 -1
  23. package/src/exclude-paths.js.map +1 -1
  24. package/src/hook-fault-codes.js.map +1 -1
  25. package/src/index.js +5 -5
  26. package/src/index.js.map +1 -1
  27. package/src/instruct-ai-docs.d.ts +3 -3
  28. package/src/instruct-ai-docs.js +3 -3
  29. package/src/instruct-ai-docs.js.map +1 -1
  30. package/src/legacy-config-upgrade.js +2 -2
  31. package/src/legacy-config-upgrade.js.map +1 -1
  32. package/src/load-template.d.ts +1 -1
  33. package/src/load-template.js +2 -2
  34. package/src/load-template.js.map +1 -1
  35. package/src/merge-process-doc.d.ts +1 -1
  36. package/src/merge-process-doc.js +2 -2
  37. package/src/merge-process-doc.js.map +1 -1
  38. package/src/migrate-dirs-cli.js +1 -1
  39. package/src/migrate-dirs-cli.js.map +1 -1
  40. package/src/orphan-dir-archive.d.ts +4 -4
  41. package/src/orphan-dir-archive.js +4 -4
  42. package/src/orphan-dir-archive.js.map +1 -1
  43. package/src/orphan-dir-scan.d.ts +1 -1
  44. package/src/orphan-dir-scan.js +1 -1
  45. package/src/orphan-dir-scan.js.map +1 -1
  46. package/src/orphan-dir-sweep.js +1 -1
  47. package/src/orphan-dir-sweep.js.map +1 -1
  48. package/src/policy-tracking.js +5 -8
  49. package/src/policy-tracking.js.map +1 -1
  50. package/src/pr-gate-config.d.ts +1 -1
  51. package/src/pr-gate-config.js +1 -1
  52. package/src/pr-gate-config.js.map +1 -1
  53. package/src/repo-root.d.ts +7 -7
  54. package/src/repo-root.js +8 -8
  55. package/src/repo-root.js.map +1 -1
  56. package/src/repo-scratch-dirs.d.ts +3 -3
  57. package/src/repo-scratch-dirs.js +5 -5
  58. package/src/repo-scratch-dirs.js.map +1 -1
  59. package/src/review-json-data.js +2 -2
  60. package/src/review-json-data.js.map +1 -1
  61. package/src/review-json.js +1 -1
  62. package/src/review-json.js.map +1 -1
  63. package/src/reviewer-instructions.d.ts +1 -1
  64. package/src/reviewer-instructions.js +1 -1
  65. package/src/reviewer-instructions.js.map +1 -1
  66. package/src/stale-bin-sweep.js +1 -1
  67. package/src/stale-bin-sweep.js.map +1 -1
  68. package/src/subagent-provenance.d.ts +6 -6
  69. package/src/subagent-provenance.js +6 -6
  70. package/src/subagent-provenance.js.map +1 -1
  71. package/src/sync-flow-guidance.js +1 -1
  72. package/src/sync-flow-guidance.js.map +1 -1
  73. package/templates/webpieces.branch-state-matrix.md +2 -2
  74. package/templates/webpieces.buildlog.md +3 -3
  75. package/templates/webpieces.ci-gate-setup.md +2 -2
  76. package/templates/webpieces.git-workflow.md +8 -9
  77. package/templates/webpieces.location-matrix.md +10 -10
  78. package/templates/webpieces.review-checklists.md +3 -3
@@ -1 +1 @@
1
- {"version":3,"file":"legacy-config-upgrade.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/legacy-config-upgrade.ts"],"names":[],"mappings":";;;AA+QA,oDAiEC;AA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/** Previous-root conversion is reachable only through an explicit upgrade command; normal loading never calls it. */\nimport { RulePackRegistry } from './rule-pack-registry';\nimport { allRuleNames, seedEntryForRule } from './validate-config';\nimport { schemaFieldNames } from './rule-schemas';\nimport { sectionForRule, isHookGuard } from './sections';\nimport { DEFAULT_MATCH_RULES } from './match-rules-config';\nimport { DEFAULT_BUILD_COMMAND } from './pr-gate-config';\nimport { RETIRED_SCOPE_RULE } from './retired-config-keys';\n\n// Explicit upgrade applies owner-declared retirements and writes reviewed settings.\nconst DEFAULT_UPSERT_PR = 'pnpm wp-start-upsert-pr';\nconst DEFAULT_MERGE_COMPLETE = 'pnpm wp-finish-upsert-pr';\n// ---------------------------------------------------------------------------\n// webpieces.config.json seeding + migration to the rules / hookGuards / commands layout.\n// ---------------------------------------------------------------------------\n// webpieces-disable no-any-unknown -- webpieces.config.json / settings.json are opaque consumer JSON\ntype Json = Record<string, unknown>;\ntype RuleEntry = Json;\ntype Section = Record<string, RuleEntry>;\n\nexport class LegacyConfigDocument {\n readonly 'match-rules': Json[];\n readonly extends: string | undefined;\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n readonly rules: Section,\n readonly hookGuards: Section,\n readonly commands: Json,\n readonly excludePaths: string[],\n matches: Json[],\n readonly rulesDir: string[],\n inheritedFrom: string | undefined,\n ) {\n this['match-rules'] = matches;\n this.extends = inheritedFrom;\n }\n}\n\nexport class LegacyUpgradeResult {\n constructor(\n readonly config: LegacyConfigDocument,\n readonly changes: string[],\n ) {}\n}\n\n// webpieces-disable no-function-outside-class -- sibling of the other seed* helpers; this module is config-shape builders by design\nfunction seedRule(ruleName: string, registry: RulePackRegistry): RuleEntry {\n // Both escape hatches are seeded (and REQUIRED) so every rule block shows them: 0 = active,\n // null = no branch scoping. A human/AI edits these to time-box or branch-scope a rule off.\n //\n // The ENTIRE entry comes from rules-config's seedEntryForRule() — the same module that owns the\n // schema the loader validates against, so the installer can never emit an entry the loader\n // rejects. It supplies: the recommended mode (the SAME recommendation the validator prints in its\n // copy-paste snippet, so seed and advice cannot disagree), both hatches, and a default for every\n // other schema-REQUIRED field. Seeding used to be a flat 'OFF' plus the two hatches, which was\n // wrong twice over: adopters got nothing enforced, AND the entry was missing required fields\n // (e.g. branch-creation-guard.autoReapMergedBranches), so the config failed to load on first run.\n return seedEntryForRule(ruleName, registry);\n}\n\n// The guard-hint command strings live under `guardHints`. The flat `upsertPr`/`mergeComplete` keys this\n// used to seed are RETIRED and now fail validation — seeding them meant every freshly installed repo was\n// born on a shape the validator rejects.\n\n// Required excludePaths block: ONE glob list suppressing hook enforcement per file path. Seeded empty\n// (enforce everywhere) — a client adds paths (e.g. \"repositories/**\") to exempt vendored trees.\n//\n// Deliberately NOT seeded with webpieces' own `.webpieces-logs/` state dir. That exemption lives in CODE\n// (`isWebpiecesStateDir`, consulted by `filterByExcludedPaths` ahead of this list and regardless of it),\n// and a glob here would be a second, weaker spelling of it — weaker because `.webpieces-logs/**` compiles to\n// an anchored regex that misses the bare directory the predicate matches, and because a config entry\n// invites a consumer to delete it and believe the exemption went with it.\n\n// Bring an existing `excludePaths` forward to the single-list shape. Already a list → untouched.\n// Legacy `{ rules, guards }` → unioned (order preserved, duplicates dropped) and recorded as a change\n// so `pnpm wp-rules-sync --upgrade` is the migration path rather than a hand-edit. Anything else → seeded [].\n// webpieces-disable no-any-unknown -- opaque legacy JSON is narrowed before use\n// webpieces-disable no-function-outside-class -- pure legacy config conversion helper\nfunction migrateExcludePaths(raw: unknown, changes: string[]): string[] {\n if (Array.isArray(raw)) return (raw as string[]).filter((p: string) => typeof p === 'string');\n if (typeof raw === 'object' && raw !== null) {\n // webpieces-disable no-any-unknown -- narrowing the opaque legacy block from consumer JSON\n const legacy = raw as Record<string, unknown>;\n const rules = Array.isArray(legacy['rules']) ? (legacy['rules'] as string[]) : [];\n const guards = Array.isArray(legacy['guards']) ? (legacy['guards'] as string[]) : [];\n const merged = [\n ...new Set([...rules, ...guards].filter((p: string) => typeof p === 'string')),\n ];\n changes.push(`migrated excludePaths {rules,guards} -> one list (${merged.length} path(s))`);\n return merged;\n }\n changes.push('added excludePaths ([])');\n return [];\n}\n\n/** One retired flat command string and the guardHints field it becomes. Data-only (per CLAUDE.md). */\nclass GuardHintMove {\n retiredKey: string;\n hintKey: string;\n fallback: string;\n\n constructor(retiredKey: string, hintKey: string, fallback: string) {\n this.retiredKey = retiredKey;\n this.hintKey = hintKey;\n this.fallback = fallback;\n }\n}\n\n/**\n * Bring `commands` forward to the `guardHints` shape, moving the RETIRED flat `upsertPr`/`mergeComplete`\n * strings and DELETING them. Deleting is the point: the validator now rejects them, so leaving them behind\n * would keep the config failing after a \"successful\" sync.\n *\n * The consumer's own value wins over the default — a repo that renamed its gated command keeps that name.\n */\n// webpieces-disable no-function-outside-class -- sibling of the other seed*/migrate* helpers; this module is config-shape builders by design\nfunction migrateGuardHints(commands: Json, changes: string[]): void {\n const hints: Json =\n typeof commands['guardHints'] === 'object' && commands['guardHints'] !== null\n ? (commands['guardHints'] as Json)\n : {};\n const moves: readonly GuardHintMove[] = [\n new GuardHintMove('upsertPr', 'prCreationOrPush', DEFAULT_UPSERT_PR),\n new GuardHintMove('mergeComplete', 'mergeInProgress', DEFAULT_MERGE_COMPLETE),\n ];\n for (const move of moves) {\n const retiredKey = move.retiredKey;\n const hintKey = move.hintKey;\n const fallback = move.fallback;\n const carried = commands[retiredKey];\n if (carried !== undefined) {\n delete commands[retiredKey];\n if (hints[hintKey] === undefined) hints[hintKey] = carried;\n changes.push(`moved retired commands.${retiredKey} -> commands.guardHints.${hintKey}`);\n }\n if (hints[hintKey] === undefined) {\n hints[hintKey] = fallback;\n changes.push(`added commands.guardHints.${hintKey}`);\n }\n }\n commands['guardHints'] = hints;\n}\n\n/**\n * Apply the RETIRED rule/guard retirements in place. These used to be rewritten silently at load time, so\n * a consumer's file kept the dead name forever; the loader now rejects it, which makes this the one\n * command that can fix the file. Skips a rename when the new name is already configured, so an explicit\n * entry is never clobbered by a stale one.\n *\n * NOT EVERY RETIREMENT IS A RENAME, and treating them all as one produced garbage. `whole-repo-build-guard`\n * moved OUT of webpieces.config.json entirely — its `movedTo` is the PROSE destination\n * `~/.webpieces/config.json → experimental.whole-repo-build-guard`, not a sibling key — so the rename\n * branch below would have created a hookGuards entry literally named that whole sentence, which no\n * validator knows and which the next run reports as another unknown rule. `prunable` is the discriminator:\n * when the entry says deleting is the whole fix, DELETE it, exactly as `ConfigPruner` does.\n */\n// webpieces-disable no-function-outside-class -- sibling of the other seed*/migrate* helpers; this module is config-shape builders by design\nfunction migrateRetiredRuleNames(\n section: Section,\n changes: string[],\n registry: RulePackRegistry,\n): void {\n for (const entry of registry.migrations()) {\n if (entry.scope !== RETIRED_SCOPE_RULE) continue;\n if (!(entry.key in section)) continue;\n if (entry.prunable) {\n delete section[entry.key];\n changes.push(`deleted retired \"${entry.key}\" (it moved to ${entry.movedTo})`);\n continue;\n }\n mergeIntoDestination(section, entry.key, entry.movedTo, changes, registry);\n }\n fillRequiredFields(section, changes, registry);\n}\n\n/**\n * Fold one retired key's entry into its destination, whether the destination exists yet or not.\n *\n * THIS IS N→1, NOT 1:1, and the difference is the whole reason this helper exists. Four retired keys\n * now point at ONE destination (`branch-state-guard`, `pr-lifecycle-guard`). The previous code renamed\n * the first key it met and then, finding the destination already present, DELETED each of the other\n * three outright — so which guard's settings survived depended on RETIRED_CONFIG_KEYS declaration\n * order rather than on the consumer's file, and the survivor carried only that one guard's fields, so\n * it was missing required fields of the merged schema. `pnpm wp-rules-sync --upgrade` is the command advertised\n * as the migration path; half-migrating every consumer into an invalid config is not an option.\n *\n * UNION, first writer wins per field. Earlier-declared keys are the more specific ones (only\n * feature-branch-guard carries `branchNamingConvention`), and a field already present on the\n * destination — because the consumer wrote it, or an earlier key contributed it — is never overwritten.\n * Fields the merged schema does not know are dropped by the same pass, since carrying a deleted field\n * across (`upsertPrCommand`) would produce a config the validator immediately rejects.\n */\n// webpieces-disable no-function-outside-class -- sibling of the other seed*/migrate* helpers; this module is config-shape builders by design\nfunction mergeIntoDestination(\n section: Section,\n key: string,\n destination: string,\n changes: string[],\n registry: RulePackRegistry,\n): void {\n const source = asSection(section[key]);\n delete section[key];\n const fields = schemaFieldNames(destination, registry);\n const target = asSection(section[destination]);\n const existed = destination in section;\n const carried: string[] = [];\n const dropped: string[] = [];\n for (const field of Object.keys(source)) {\n if (fields !== null && !fields.includes(field)) {\n dropped.push(field);\n continue;\n }\n if (field in target) continue;\n target[field] = source[field];\n carried.push(field);\n }\n section[destination] = target;\n const verb = existed ? 'merged' : 'renamed';\n const droppedNote =\n dropped.length > 0 ? `; dropped deleted field(s) ${dropped.join(', ')}` : '';\n changes.push(\n `${verb} retired \"${key}\" -> \"${destination}\" (carried ${carried.join(', ') || 'nothing new'}${droppedNote})`,\n );\n}\n\n/**\n * Fill any schema-REQUIRED field a migrated entry ended up without.\n *\n * A union of four partial entries is not guaranteed to satisfy the destination's schema — the merged\n * `branch-state-guard` needs `mode` and both escape hatches, and a consumer whose four old entries\n * predate one of them would land short. Seeding the gap from the SAME source the installer and the\n * validator use (seedEntryForRule) is what makes the install command a complete instruction\n * rather than a first step. Only ever ADDS; a value the consumer stated is never touched.\n */\n// webpieces-disable no-function-outside-class -- sibling of the other seed*/migrate* helpers; this module is config-shape builders by design\nfunction fillRequiredFields(section: Section, changes: string[], registry: RulePackRegistry): void {\n for (const name of Object.keys(section)) {\n if (schemaFieldNames(name, registry) === null) continue;\n // A rule ENTRY is a flat bag of scalars, so it is read as Json here rather than through\n // asSection (whose values are whole entries). Same object either way; only the view differs.\n const entry: Json = asSection(section[name]);\n const seed = seedEntryForRule(name, registry);\n const added: string[] = [];\n for (const field of Object.keys(seed)) {\n if (field in entry) continue;\n entry[field] = seed[field];\n added.push(field);\n }\n if (added.length === 0) continue;\n section[name] = entry;\n changes.push(`filled required field(s) on \"${name}\": ${added.join(', ')}`);\n }\n}\n\n// Deep-copy the framework's default match-rules (the no-fetch guard) into plain JSON for the config\n// file. Round-tripping through JSON turns the MatchRuleConfig instances into plain objects.\n// webpieces-disable no-function-outside-class -- this module is deliberately DI-FREE: `pnpm wp-rules-sync --upgrade` must run on a half-written node_modules (see install-entry.ts), so it cannot build a container to hold a method\nfunction seedMatchRules(): Json[] {\n return JSON.parse(JSON.stringify(DEFAULT_MATCH_RULES)) as Json[];\n}\n\n// webpieces-disable no-function-outside-class -- this module is deliberately DI-FREE: `pnpm wp-rules-sync --upgrade` must run on a half-written node_modules (see install-entry.ts), so it cannot build a container to hold a method\nfunction asSection(value: Json[string]): Section {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Section)\n : {};\n}\n\n// Migrate an existing config to the rules / hookGuards / commands layout and add any missing rules.\n// Returns a human-readable list of what changed (empty = already up to date).\n// webpieces-disable no-function-outside-class -- this module is deliberately DI-FREE: `pnpm wp-rules-sync --upgrade` must run on a half-written node_modules (see install-entry.ts), so it cannot build a container to hold a method\nexport function prepareLegacyUpgrade(\n existing: Json,\n registry: RulePackRegistry,\n): LegacyUpgradeResult {\n const changes: string[] = [];\n const rules: Section = asSection(existing['rules']);\n const hookGuards: Section = asSection(existing['hookGuards']);\n const commands: Json =\n typeof existing['commands'] === 'object' && existing['commands'] !== null\n ? (existing['commands'] as Json)\n : {};\n\n // Move a deprecated top-level pr-gate block under commands.\n if (existing['pr-gate'] !== undefined && commands['pr-gate'] === undefined) {\n commands['pr-gate'] = existing['pr-gate'];\n changes.push('moved top-level \"pr-gate\" → commands[\"pr-gate\"]');\n }\n // Apply retired RENAMES first, so a renamed guard is placed and presence-checked under its new name\n // rather than being treated as unknown and re-added alongside its own stale entry.\n migrateRetiredRuleNames(rules, changes, registry);\n migrateRetiredRuleNames(hookGuards, changes, registry);\n\n migratePolicySections(rules, hookGuards, changes, registry);\n // Add any missing built-in into its correct section, ENFORCING at its recommended mode (not OFF).\n for (const name of allRuleNames(registry)) {\n const target = sectionForRule(name, registry) === 'hookGuards' ? hookGuards : rules;\n if (!(name in target)) {\n const entry = seedRule(name, registry);\n target[name] = entry;\n changes.push(\n `added \"${name}\" (${String(entry['mode'])}) to ${sectionForRule(name, registry)}`,\n );\n }\n }\n // Fill command defaults.\n if (commands['pr-gate'] === undefined) {\n commands['pr-gate'] = { mode: 'OFF', buildCommand: DEFAULT_BUILD_COMMAND, gates: [] };\n changes.push('added commands[\"pr-gate\"] (OFF)');\n }\n migrateGuardHints(commands, changes);\n\n // Seed the now-required excludePaths list (empty = enforce everywhere) if the config predates it,\n // and MIGRATE the legacy `{ rules: [], guards: [] }` object to the single list by unioning them.\n // The union is behaviour-preserving for every config we have seen (both lists set identically), and\n // widening is the safe direction anyway: a path either side excluded stays excluded.\n const excludePaths: string[] = migrateExcludePaths(existing['excludePaths'], changes);\n\n const matchRules = upgradeMatchRules(existing, changes);\n\n const rulesDir: string[] = Array.isArray(existing['rulesDir'])\n ? (existing['rulesDir'] as string[])\n : [];\n const inherited = typeof existing['extends'] === 'string' ? existing['extends'] : undefined;\n return new LegacyUpgradeResult(\n new LegacyConfigDocument(\n rules,\n hookGuards,\n commands,\n excludePaths,\n matchRules,\n rulesDir,\n inherited,\n ),\n changes,\n );\n}\n\n// webpieces-disable no-function-outside-class -- explicit upgrade conversion remains independent of DI\nfunction migratePolicySections(rules: Section, hookGuards: Section, changes: string[], registry: RulePackRegistry): void {\n // Move guards mistakenly left in rules into hookGuards.\n for (const name of Object.keys(rules)) {\n if (isHookGuard(name, registry)) {\n hookGuards[name] = rules[name];\n delete rules[name];\n changes.push(`moved \"${name}\" from rules → hookGuards`);\n }\n }\n // Move code rules mistakenly placed in hookGuards back into rules.\n for (const name of Object.keys(hookGuards)) {\n if (!isHookGuard(name, registry) && allRuleNames(registry).includes(name)) {\n rules[name] = hookGuards[name];\n delete hookGuards[name];\n changes.push(`moved \"${name}\" from hookGuards → rules`);\n }\n }\n}\n\n// webpieces-disable no-function-outside-class -- pure explicit-upgrade conversion\nfunction upgradeMatchRules(existing: Json, changes: string[]): Json[] {\n // Seed the now-required match-rules array (with the default no-fetch guard) if the config predates\n // it. A client that has already customized it keeps their array untouched.\n let matchRules: Json[];\n if (Array.isArray(existing['match-rules'])) {\n matchRules = existing['match-rules'] as Json[];\n } else {\n matchRules = seedMatchRules();\n changes.push('added \"match-rules\" (seeded with the no-fetch guard)');\n }\n\n return matchRules;\n}\n"]}
1
+ {"version":3,"file":"legacy-config-upgrade.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/legacy-config-upgrade.ts"],"names":[],"mappings":";;;AA+QA,oDAiEC;AA9UD,uDAAmE;AACnE,iDAAkD;AAClD,yCAAyD;AACzD,6DAA2D;AAC3D,qDAAyD;AACzD,+DAA2D;AAE3D,oFAAoF;AACpF,MAAM,iBAAiB,GAAG,yBAAyB,CAAC;AACpD,MAAM,sBAAsB,GAAG,0BAA0B,CAAC;AAS1D,MAAa,oBAAoB;IAKhB;IACA;IACA;IACA;IAEA;IATJ,aAAa,CAAS;IACtB,OAAO,CAAqB;IACrC,yDAAyD;IACzD,YACa,KAAc,EACd,UAAmB,EACnB,QAAc,EACd,YAAsB,EAC/B,OAAe,EACN,QAAkB,EAC3B,aAAiC;QANxB,UAAK,GAAL,KAAK,CAAS;QACd,eAAU,GAAV,UAAU,CAAS;QACnB,aAAQ,GAAR,QAAQ,CAAM;QACd,iBAAY,GAAZ,YAAY,CAAU;QAEtB,aAAQ,GAAR,QAAQ,CAAU;QAG3B,IAAI,CAAC,aAAa,CAAC,GAAG,OAAO,CAAC;QAC9B,IAAI,CAAC,OAAO,GAAG,aAAa,CAAC;IACjC,CAAC;CACJ;AAhBD,oDAgBC;AAED,MAAa,mBAAmB;IAEf;IACA;IAFb,YACa,MAA4B,EAC5B,OAAiB;QADjB,WAAM,GAAN,MAAM,CAAsB;QAC5B,YAAO,GAAP,OAAO,CAAU;IAC3B,CAAC;CACP;AALD,kDAKC;AAED,oIAAoI;AACpI,SAAS,QAAQ,CAAC,QAAgB,EAAE,QAA0B;IAC1D,4FAA4F;IAC5F,2FAA2F;IAC3F,EAAE;IACF,gGAA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AAC;IACvB,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAC,CAAC,EAAE,CAAC;QACzC,UAAU,GAAG,QAAQ,CAAC,aAAa,CAAW,CAAC;IACnD,CAAC;SAAM,CAAC;QACJ,UAAU,GAAG,cAAc,EAAE,CAAC;QAC9B,OAAO,CAAC,IAAI,CAAC,sDAAsD,CAAC,CAAC;IACzE,CAAC;IAED,OAAO,UAAU,CAAC;AACtB,CAAC","sourcesContent":["/** Previous-root conversion is reachable only through an explicit upgrade command; normal loading never calls it. */\nimport { RulePackRegistry } from './rule-pack-registry';\nimport { allRuleNames, seedEntryForRule } from './validate-config';\nimport { schemaFieldNames } from './rule-schemas';\nimport { sectionForRule, isHookGuard } from './sections';\nimport { DEFAULT_MATCH_RULES } from './match-rules-config';\nimport { DEFAULT_BUILD_COMMAND } from './pr-gate-config';\nimport { RETIRED_SCOPE_RULE } from './retired-config-keys';\n\n// Explicit upgrade applies owner-declared retirements and writes reviewed settings.\nconst DEFAULT_UPSERT_PR = 'pnpm wp-start-upsert-pr';\nconst DEFAULT_MERGE_COMPLETE = 'pnpm wp-finish-upsert-pr';\n// ---------------------------------------------------------------------------\n// webpieces.config.json seeding + migration to the rules / hookGuards / commands layout.\n// ---------------------------------------------------------------------------\n// webpieces-disable no-any-unknown -- webpieces.config.json / settings.json are opaque consumer JSON\ntype Json = Record<string, unknown>;\ntype RuleEntry = Json;\ntype Section = Record<string, RuleEntry>;\n\nexport class LegacyConfigDocument {\n readonly 'match-rules': Json[];\n readonly extends: string | undefined;\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n readonly rules: Section,\n readonly hookGuards: Section,\n readonly commands: Json,\n readonly excludePaths: string[],\n matches: Json[],\n readonly rulesDir: string[],\n inheritedFrom: string | undefined,\n ) {\n this['match-rules'] = matches;\n this.extends = inheritedFrom;\n }\n}\n\nexport class LegacyUpgradeResult {\n constructor(\n readonly config: LegacyConfigDocument,\n readonly changes: string[],\n ) {}\n}\n\n// webpieces-disable no-function-outside-class -- sibling of the other seed* helpers; this module is config-shape builders by design\nfunction seedRule(ruleName: string, registry: RulePackRegistry): RuleEntry {\n // Both escape hatches are seeded (and REQUIRED) so every rule block shows them: 0 = active,\n // null = no branch scoping. A human/AI edits these to time-box or branch-scope a rule off.\n //\n // The ENTIRE entry comes from rules-config's seedEntryForRule() — the same module that owns the\n // schema the loader validates against, so the installer can never emit an entry the loader\n // rejects. It supplies: the recommended mode (the SAME recommendation the validator prints in its\n // copy-paste snippet, so seed and advice cannot disagree), both hatches, and a default for every\n // other schema-REQUIRED field. Seeding used to be a flat 'OFF' plus the two hatches, which was\n // wrong twice over: adopters got nothing enforced, AND the entry was missing required fields\n // (e.g. branch-creation-guard.autoReapMergedBranches), so the config failed to load on first run.\n return seedEntryForRule(ruleName, registry);\n}\n\n// The guard-hint command strings live under `guardHints`. The flat `upsertPr`/`mergeComplete` keys this\n// used to seed are RETIRED and now fail validation — seeding them meant every freshly installed repo was\n// born on a shape the validator rejects.\n\n// Required excludePaths block: ONE glob list suppressing hook enforcement per file path. Seeded empty\n// (enforce everywhere) — a client adds paths (e.g. \"repositories/**\") to exempt vendored trees.\n//\n// Deliberately NOT seeded with webpieces' own `.webpieces/` state dir. That exemption lives in CODE\n// (`isWebpiecesStateDir`, consulted by `filterByExcludedPaths` ahead of this list and regardless of it),\n// and a glob here would be a second, weaker spelling of it — weaker because `.webpieces/**` compiles to\n// an anchored regex that misses the bare directory the predicate matches, and because a config entry\n// invites a consumer to delete it and believe the exemption went with it.\n\n// Bring an existing `excludePaths` forward to the single-list shape. Already a list → untouched.\n// Legacy `{ rules, guards }` → unioned (order preserved, duplicates dropped) and recorded as a change\n// so `pnpm wp-rules-sync --upgrade` is the migration path rather than a hand-edit. Anything else → seeded [].\n// webpieces-disable no-any-unknown -- opaque legacy JSON is narrowed before use\n// webpieces-disable no-function-outside-class -- pure legacy config conversion helper\nfunction migrateExcludePaths(raw: unknown, changes: string[]): string[] {\n if (Array.isArray(raw)) return (raw as string[]).filter((p: string) => typeof p === 'string');\n if (typeof raw === 'object' && raw !== null) {\n // webpieces-disable no-any-unknown -- narrowing the opaque legacy block from consumer JSON\n const legacy = raw as Record<string, unknown>;\n const rules = Array.isArray(legacy['rules']) ? (legacy['rules'] as string[]) : [];\n const guards = Array.isArray(legacy['guards']) ? (legacy['guards'] as string[]) : [];\n const merged = [\n ...new Set([...rules, ...guards].filter((p: string) => typeof p === 'string')),\n ];\n changes.push(`migrated excludePaths {rules,guards} -> one list (${merged.length} path(s))`);\n return merged;\n }\n changes.push('added excludePaths ([])');\n return [];\n}\n\n/** One retired flat command string and the guardHints field it becomes. Data-only (per CLAUDE.md). */\nclass GuardHintMove {\n retiredKey: string;\n hintKey: string;\n fallback: string;\n\n constructor(retiredKey: string, hintKey: string, fallback: string) {\n this.retiredKey = retiredKey;\n this.hintKey = hintKey;\n this.fallback = fallback;\n }\n}\n\n/**\n * Bring `commands` forward to the `guardHints` shape, moving the RETIRED flat `upsertPr`/`mergeComplete`\n * strings and DELETING them. Deleting is the point: the validator now rejects them, so leaving them behind\n * would keep the config failing after a \"successful\" sync.\n *\n * The consumer's own value wins over the default — a repo that renamed its gated command keeps that name.\n */\n// webpieces-disable no-function-outside-class -- sibling of the other seed*/migrate* helpers; this module is config-shape builders by design\nfunction migrateGuardHints(commands: Json, changes: string[]): void {\n const hints: Json =\n typeof commands['guardHints'] === 'object' && commands['guardHints'] !== null\n ? (commands['guardHints'] as Json)\n : {};\n const moves: readonly GuardHintMove[] = [\n new GuardHintMove('upsertPr', 'prCreationOrPush', DEFAULT_UPSERT_PR),\n new GuardHintMove('mergeComplete', 'mergeInProgress', DEFAULT_MERGE_COMPLETE),\n ];\n for (const move of moves) {\n const retiredKey = move.retiredKey;\n const hintKey = move.hintKey;\n const fallback = move.fallback;\n const carried = commands[retiredKey];\n if (carried !== undefined) {\n delete commands[retiredKey];\n if (hints[hintKey] === undefined) hints[hintKey] = carried;\n changes.push(`moved retired commands.${retiredKey} -> commands.guardHints.${hintKey}`);\n }\n if (hints[hintKey] === undefined) {\n hints[hintKey] = fallback;\n changes.push(`added commands.guardHints.${hintKey}`);\n }\n }\n commands['guardHints'] = hints;\n}\n\n/**\n * Apply the RETIRED rule/guard retirements in place. These used to be rewritten silently at load time, so\n * a consumer's file kept the dead name forever; the loader now rejects it, which makes this the one\n * command that can fix the file. Skips a rename when the new name is already configured, so an explicit\n * entry is never clobbered by a stale one.\n *\n * NOT EVERY RETIREMENT IS A RENAME, and treating them all as one produced garbage. `whole-repo-build-guard`\n * moved OUT of webpieces.config.json entirely — its `movedTo` is the PROSE destination\n * `~/.webpieces/config.json → experimental.whole-repo-build-guard`, not a sibling key — so the rename\n * branch below would have created a hookGuards entry literally named that whole sentence, which no\n * validator knows and which the next run reports as another unknown rule. `prunable` is the discriminator:\n * when the entry says deleting is the whole fix, DELETE it, exactly as `ConfigPruner` does.\n */\n// webpieces-disable no-function-outside-class -- sibling of the other seed*/migrate* helpers; this module is config-shape builders by design\nfunction migrateRetiredRuleNames(\n section: Section,\n changes: string[],\n registry: RulePackRegistry,\n): void {\n for (const entry of registry.migrations()) {\n if (entry.scope !== RETIRED_SCOPE_RULE) continue;\n if (!(entry.key in section)) continue;\n if (entry.prunable) {\n delete section[entry.key];\n changes.push(`deleted retired \"${entry.key}\" (it moved to ${entry.movedTo})`);\n continue;\n }\n mergeIntoDestination(section, entry.key, entry.movedTo, changes, registry);\n }\n fillRequiredFields(section, changes, registry);\n}\n\n/**\n * Fold one retired key's entry into its destination, whether the destination exists yet or not.\n *\n * THIS IS N→1, NOT 1:1, and the difference is the whole reason this helper exists. Four retired keys\n * now point at ONE destination (`branch-state-guard`, `pr-lifecycle-guard`). The previous code renamed\n * the first key it met and then, finding the destination already present, DELETED each of the other\n * three outright — so which guard's settings survived depended on RETIRED_CONFIG_KEYS declaration\n * order rather than on the consumer's file, and the survivor carried only that one guard's fields, so\n * it was missing required fields of the merged schema. `pnpm wp-rules-sync --upgrade` is the command advertised\n * as the migration path; half-migrating every consumer into an invalid config is not an option.\n *\n * UNION, first writer wins per field. Earlier-declared keys are the more specific ones (only\n * feature-branch-guard carries `branchNamingConvention`), and a field already present on the\n * destination — because the consumer wrote it, or an earlier key contributed it — is never overwritten.\n * Fields the merged schema does not know are dropped by the same pass, since carrying a deleted field\n * across (`upsertPrCommand`) would produce a config the validator immediately rejects.\n */\n// webpieces-disable no-function-outside-class -- sibling of the other seed*/migrate* helpers; this module is config-shape builders by design\nfunction mergeIntoDestination(\n section: Section,\n key: string,\n destination: string,\n changes: string[],\n registry: RulePackRegistry,\n): void {\n const source = asSection(section[key]);\n delete section[key];\n const fields = schemaFieldNames(destination, registry);\n const target = asSection(section[destination]);\n const existed = destination in section;\n const carried: string[] = [];\n const dropped: string[] = [];\n for (const field of Object.keys(source)) {\n if (fields !== null && !fields.includes(field)) {\n dropped.push(field);\n continue;\n }\n if (field in target) continue;\n target[field] = source[field];\n carried.push(field);\n }\n section[destination] = target;\n const verb = existed ? 'merged' : 'renamed';\n const droppedNote =\n dropped.length > 0 ? `; dropped deleted field(s) ${dropped.join(', ')}` : '';\n changes.push(\n `${verb} retired \"${key}\" -> \"${destination}\" (carried ${carried.join(', ') || 'nothing new'}${droppedNote})`,\n );\n}\n\n/**\n * Fill any schema-REQUIRED field a migrated entry ended up without.\n *\n * A union of four partial entries is not guaranteed to satisfy the destination's schema — the merged\n * `branch-state-guard` needs `mode` and both escape hatches, and a consumer whose four old entries\n * predate one of them would land short. Seeding the gap from the SAME source the installer and the\n * validator use (seedEntryForRule) is what makes the install command a complete instruction\n * rather than a first step. Only ever ADDS; a value the consumer stated is never touched.\n */\n// webpieces-disable no-function-outside-class -- sibling of the other seed*/migrate* helpers; this module is config-shape builders by design\nfunction fillRequiredFields(section: Section, changes: string[], registry: RulePackRegistry): void {\n for (const name of Object.keys(section)) {\n if (schemaFieldNames(name, registry) === null) continue;\n // A rule ENTRY is a flat bag of scalars, so it is read as Json here rather than through\n // asSection (whose values are whole entries). Same object either way; only the view differs.\n const entry: Json = asSection(section[name]);\n const seed = seedEntryForRule(name, registry);\n const added: string[] = [];\n for (const field of Object.keys(seed)) {\n if (field in entry) continue;\n entry[field] = seed[field];\n added.push(field);\n }\n if (added.length === 0) continue;\n section[name] = entry;\n changes.push(`filled required field(s) on \"${name}\": ${added.join(', ')}`);\n }\n}\n\n// Deep-copy the framework's default match-rules (the no-fetch guard) into plain JSON for the config\n// file. Round-tripping through JSON turns the MatchRuleConfig instances into plain objects.\n// webpieces-disable no-function-outside-class -- this module is deliberately DI-FREE: `pnpm wp-rules-sync --upgrade` must run on a half-written node_modules (see install-entry.ts), so it cannot build a container to hold a method\nfunction seedMatchRules(): Json[] {\n return JSON.parse(JSON.stringify(DEFAULT_MATCH_RULES)) as Json[];\n}\n\n// webpieces-disable no-function-outside-class -- this module is deliberately DI-FREE: `pnpm wp-rules-sync --upgrade` must run on a half-written node_modules (see install-entry.ts), so it cannot build a container to hold a method\nfunction asSection(value: Json[string]): Section {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Section)\n : {};\n}\n\n// Migrate an existing config to the rules / hookGuards / commands layout and add any missing rules.\n// Returns a human-readable list of what changed (empty = already up to date).\n// webpieces-disable no-function-outside-class -- this module is deliberately DI-FREE: `pnpm wp-rules-sync --upgrade` must run on a half-written node_modules (see install-entry.ts), so it cannot build a container to hold a method\nexport function prepareLegacyUpgrade(\n existing: Json,\n registry: RulePackRegistry,\n): LegacyUpgradeResult {\n const changes: string[] = [];\n const rules: Section = asSection(existing['rules']);\n const hookGuards: Section = asSection(existing['hookGuards']);\n const commands: Json =\n typeof existing['commands'] === 'object' && existing['commands'] !== null\n ? (existing['commands'] as Json)\n : {};\n\n // Move a deprecated top-level pr-gate block under commands.\n if (existing['pr-gate'] !== undefined && commands['pr-gate'] === undefined) {\n commands['pr-gate'] = existing['pr-gate'];\n changes.push('moved top-level \"pr-gate\" → commands[\"pr-gate\"]');\n }\n // Apply retired RENAMES first, so a renamed guard is placed and presence-checked under its new name\n // rather than being treated as unknown and re-added alongside its own stale entry.\n migrateRetiredRuleNames(rules, changes, registry);\n migrateRetiredRuleNames(hookGuards, changes, registry);\n\n migratePolicySections(rules, hookGuards, changes, registry);\n // Add any missing built-in into its correct section, ENFORCING at its recommended mode (not OFF).\n for (const name of allRuleNames(registry)) {\n const target = sectionForRule(name, registry) === 'hookGuards' ? hookGuards : rules;\n if (!(name in target)) {\n const entry = seedRule(name, registry);\n target[name] = entry;\n changes.push(\n `added \"${name}\" (${String(entry['mode'])}) to ${sectionForRule(name, registry)}`,\n );\n }\n }\n // Fill command defaults.\n if (commands['pr-gate'] === undefined) {\n commands['pr-gate'] = { mode: 'OFF', buildCommand: DEFAULT_BUILD_COMMAND, gates: [] };\n changes.push('added commands[\"pr-gate\"] (OFF)');\n }\n migrateGuardHints(commands, changes);\n\n // Seed the now-required excludePaths list (empty = enforce everywhere) if the config predates it,\n // and MIGRATE the legacy `{ rules: [], guards: [] }` object to the single list by unioning them.\n // The union is behaviour-preserving for every config we have seen (both lists set identically), and\n // widening is the safe direction anyway: a path either side excluded stays excluded.\n const excludePaths: string[] = migrateExcludePaths(existing['excludePaths'], changes);\n\n const matchRules = upgradeMatchRules(existing, changes);\n\n const rulesDir: string[] = Array.isArray(existing['rulesDir'])\n ? (existing['rulesDir'] as string[])\n : [];\n const inherited = typeof existing['extends'] === 'string' ? existing['extends'] : undefined;\n return new LegacyUpgradeResult(\n new LegacyConfigDocument(\n rules,\n hookGuards,\n commands,\n excludePaths,\n matchRules,\n rulesDir,\n inherited,\n ),\n changes,\n );\n}\n\n// webpieces-disable no-function-outside-class -- explicit upgrade conversion remains independent of DI\nfunction migratePolicySections(rules: Section, hookGuards: Section, changes: string[], registry: RulePackRegistry): void {\n // Move guards mistakenly left in rules into hookGuards.\n for (const name of Object.keys(rules)) {\n if (isHookGuard(name, registry)) {\n hookGuards[name] = rules[name];\n delete rules[name];\n changes.push(`moved \"${name}\" from rules → hookGuards`);\n }\n }\n // Move code rules mistakenly placed in hookGuards back into rules.\n for (const name of Object.keys(hookGuards)) {\n if (!isHookGuard(name, registry) && allRuleNames(registry).includes(name)) {\n rules[name] = hookGuards[name];\n delete hookGuards[name];\n changes.push(`moved \"${name}\" from hookGuards → rules`);\n }\n }\n}\n\n// webpieces-disable no-function-outside-class -- pure explicit-upgrade conversion\nfunction upgradeMatchRules(existing: Json, changes: string[]): Json[] {\n // Seed the now-required match-rules array (with the default no-fetch guard) if the config predates\n // it. A client that has already customized it keeps their array untouched.\n let matchRules: Json[];\n if (Array.isArray(existing['match-rules'])) {\n matchRules = existing['match-rules'] as Json[];\n } else {\n matchRules = seedMatchRules();\n changes.push('added \"match-rules\" (seeded with the no-fetch guard)');\n }\n\n return matchRules;\n}\n"]}
@@ -3,7 +3,7 @@ import { InstructAiDocSet } from './instruct-ai-docs';
3
3
  import { DotWebpieces } from '@webpieces/tooling-common';
4
4
  import { StaleBinSweeper } from './stale-bin-sweep';
5
5
  /**
6
- * Writes the AI-facing instruct-ai template docs under `<workspaceRoot>/.webpieces-logs/instruct-ai/`.
6
+ * Writes the AI-facing instruct-ai template docs under `<workspaceRoot>/.webpieces/instruct-ai/`.
7
7
  * `@injectable(bindingScopeValues.Singleton)` so it can be injected and appear in the rules-config DI design.
8
8
  */
9
9
  export declare class TemplateWriter {
@@ -19,7 +19,7 @@ const TEMPLATES_DIR = path.join(__dirname, '..', 'templates');
19
19
  // unaffected; anything passing the default gets DotWebpieces.local() resolution.
20
20
  const DEFAULT_INSTRUCT_DIR = '';
21
21
  /**
22
- * Writes the AI-facing instruct-ai template docs under `<workspaceRoot>/.webpieces-logs/instruct-ai/`.
22
+ * Writes the AI-facing instruct-ai template docs under `<workspaceRoot>/.webpieces/instruct-ai/`.
23
23
  * `@injectable(bindingScopeValues.Singleton)` so it can be injected and appear in the rules-config DI design.
24
24
  */
25
25
  let TemplateWriter = class TemplateWriter {
@@ -93,7 +93,7 @@ let TemplateWriter = class TemplateWriter {
93
93
  for (const line of this.staleBins.report(removed))
94
94
  process.stdout.write(line + '\n');
95
95
  }
96
- // LOCAL `.webpieces-logs/instruct-ai/<name>` by default; an explicitly-passed relative dir is still
96
+ // LOCAL `.webpieces/instruct-ai/<name>` by default; an explicitly-passed relative dir is still
97
97
  // joined onto workspaceRoot exactly as before.
98
98
  destination(workspaceRoot, name, instructDir) {
99
99
  if (instructDir === DEFAULT_INSTRUCT_DIR) {
@@ -1 +1 @@
1
- {"version":3,"file":"load-template.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/load-template.ts"],"names":[],"mappings":";;;AAsGA,oCAEC;AAED,wDAMC;AAED,sCAMC;;AAxHD,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAE3D,8DAAuD;AACvD,yDAAsD;AACtD,2CAA+C;AAC/C,8DAAuE;AACvE,uDAAqE;AAErE,MAAM,aAAa,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,EAAE,WAAW,CAAC,CAAC;AAC9D,sGAAsG;AACtG,iGAAiG;AACjG,iFAAiF;AACjF,MAAM,oBAAoB,GAAG,EAAE,CAAC;AAEhC;;;GAGG;AAEI,IAAM,cAAc,GAApB,MAAM,cAAc;IAEF;IACA;IACA;IAGA;IANrB,YACqB,SAAuB,6BAAY,EACnC,aAAyB,IAAI,2BAAU,EAAE,EACzC,OAAyB,IAAI,mCAAgB,EAAE;IAChE,4FAA4F;IAC5F,+EAA+E;IAC9D,YAA6B,iCAAe;QAL5C,WAAM,GAAN,MAAM,CAA6B;QACnC,eAAU,GAAV,UAAU,CAA+B;QACzC,SAAI,GAAJ,IAAI,CAA2C;QAG/C,cAAS,GAAT,SAAS,CAAmC;IAC9D,CAAC;IAEJ,YAAY,CAAC,IAAY;QACrB,OAAO,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,IAAI,CAAC,EAAE,OAAO,CAAC,CAAC;IACpE,CAAC;IAED;;;;;;;;OAQG;IACH,sBAAsB,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C/E,CAAC;AAED,SAAgB,aAAa,CACzB,aAAqB,EACrB,IAAY,EACZ,cAAsB,oBAAoB;IAE1C,OAAO,iBAAiB,CAAC,aAAa,CAAC,aAAa,EAAE,IAAI,EAAE,WAAW,CAAC,CAAC;AAC7E,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { AtomicFile } from '@webpieces/tooling-common';\nimport { InstructAiDocSet } from './instruct-ai-docs';\nimport { INSTRUCT_AI_LEAF } from './repo-root';\nimport { DotWebpieces, dotWebpieces } from '@webpieces/tooling-common';\nimport { StaleBinSweeper, staleBinSweeper } from './stale-bin-sweep';\n\nconst TEMPLATES_DIR = path.join(__dirname, '..', 'templates');\n// Sentinel for \"use the resolved LOCAL instruct-ai dir\". Kept as the parameter default so the handful\n// of callers that pass an explicit relative dir (they join it onto workspaceRoot themselves) are\n// unaffected; anything passing the default gets DotWebpieces.local() resolution.\nconst DEFAULT_INSTRUCT_DIR = '';\n\n/**\n * Writes the AI-facing instruct-ai template docs under `<workspaceRoot>/.webpieces-logs/instruct-ai/`.\n * `@injectable(bindingScopeValues.Singleton)` so it can be injected and appear in the rules-config DI design.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class TemplateWriter {\n constructor(\n private readonly dotDir: DotWebpieces = dotWebpieces,\n private readonly atomicFile: AtomicFile = new AtomicFile(),\n private readonly docs: InstructAiDocSet = new InstructAiDocSet(),\n // The SHARED sweeper instance, never a fresh one: its \"already swept this root\" memo is per\n // instance, and that memo is what keeps the report to once per `wp-*` command.\n private readonly staleBins: StaleBinSweeper = staleBinSweeper,\n ) {}\n\n loadTemplate(name: string): string {\n return fs.readFileSync(path.join(TEMPLATES_DIR, name), 'utf-8');\n }\n\n /**\n * SEED `name` and everything it links to — writing only the ones that are not already on disk.\n *\n * Same closure as `writeTemplate`, for the same reason: a rule that drops\n * `webpieces.exceptions.md` next to its violation is delivering a doc a reader follows links out\n * of, and a seeded doc that later gains a sibling link would otherwise dangle exactly the way\n * git-workflow.md's link to the merge process did. The difference from `writeTemplate` is only\n * WHETHER an existing file is refreshed, never WHICH files are considered.\n */\n writeTemplateIfMissing(workspaceRoot: string, name: string, instructDir: string = DEFAULT_INSTRUCT_DIR): void {\n for (const doc of this.docs.closure(name, (docName: string): string => this.loadTemplate(docName))) {\n const target = this.destination(workspaceRoot, doc.name, instructDir);\n if (fs.existsSync(target)) continue;\n this.atomicFile.writeAtomic(target, doc.render(this.loadTemplate(doc.name), workspaceRoot));\n }\n }\n\n /**\n * Write `name` AND every instruct-ai doc it links to, ATOMICALLY and only where bytes changed.\n * Returns the absolute path of `name` itself.\n *\n * THE CLOSURE IS THE POINT. Callers name the ONE doc their command is about; the docs a reader is\n * sent on to arrive with it, because a doc whose links dangle is worse than no doc — it teaches the\n * reader that the paths in these files cannot be trusted. See instruct-ai-docs.ts for the incident.\n *\n * Every `wp-*` command regenerates these, and the AI is routinely told to open one by absolute\n * path. A plain truncating write means a reader can catch it empty; skip-if-unchanged means the\n * overwhelmingly common case (same package version ⇒ identical content) does not write at all.\n */\n writeTemplate(workspaceRoot: string, name: string, instructDir: string = DEFAULT_INSTRUCT_DIR): string {\n // THE SELF-HEAL. This is the pass every `wp-*` command takes, which makes it the only place a\n // RELEASED sweep reaches every clone on every developer's machine — see stale-bin-sweep.ts. Silent\n // when there is nothing to remove, and once per root per process.\n this.sweepStaleBins(workspaceRoot);\n for (const doc of this.docs.closure(name, (docName: string): string => this.loadTemplate(docName))) {\n const target = this.destination(workspaceRoot, doc.name, instructDir);\n // A doc stamped with live run state is SEEDED, never refreshed: `wp-finish-upsert-pr` runs\n // while a conflicted merge is still open, and clobbering that handback with the reference\n // copy would delete the file list the agent is working from.\n if (doc.seedOnly() && fs.existsSync(target)) continue;\n this.atomicFile.writeIfChanged(target, doc.render(this.loadTemplate(doc.name), workspaceRoot));\n }\n return this.destination(workspaceRoot, name, instructDir);\n }\n\n /**\n * Remove this tree's dangling `wp-*` bin symlinks and SAY what went, on stdout beside everything else\n * a `wp-*` command prints. Nothing removed ⇒ nothing printed, which is the overwhelmingly common case.\n */\n private sweepStaleBins(workspaceRoot: string): void {\n const removed = this.staleBins.sweepOnce(workspaceRoot);\n for (const line of this.staleBins.report(removed)) process.stdout.write(line + '\\n');\n }\n\n // LOCAL `.webpieces-logs/instruct-ai/<name>` by default; an explicitly-passed relative dir is still\n // joined onto workspaceRoot exactly as before.\n private destination(workspaceRoot: string, name: string, instructDir: string): string {\n if (instructDir === DEFAULT_INSTRUCT_DIR) {\n return this.dotDir.localFile(workspaceRoot, INSTRUCT_AI_LEAF, name);\n }\n return path.join(workspaceRoot, instructDir, name);\n }\n}\n\n// Temporary migration delegators — consumers migrate to injecting TemplateWriter over follow-up PRs.\nconst templateWriterSvc = new TemplateWriter();\n\nexport function loadTemplate(name: string): string {\n return templateWriterSvc.loadTemplate(name);\n}\n\nexport function writeTemplateIfMissing(\n workspaceRoot: string,\n name: string,\n instructDir: string = DEFAULT_INSTRUCT_DIR,\n): void {\n templateWriterSvc.writeTemplateIfMissing(workspaceRoot, name, instructDir);\n}\n\nexport function writeTemplate(\n workspaceRoot: string,\n name: string,\n instructDir: string = DEFAULT_INSTRUCT_DIR,\n): string {\n return templateWriterSvc.writeTemplate(workspaceRoot, name, instructDir);\n}\n"]}
1
+ {"version":3,"file":"load-template.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/load-template.ts"],"names":[],"mappings":";;;AAsGA,oCAEC;AAED,wDAMC;AAED,sCAMC;;AAxHD,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAE3D,8DAAuD;AACvD,yDAAsD;AACtD,2CAA+C;AAC/C,8DAAuE;AACvE,uDAAqE;AAErE,MAAM,aAAa,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,EAAE,WAAW,CAAC,CAAC;AAC9D,sGAAsG;AACtG,iGAAiG;AACjG,iFAAiF;AACjF,MAAM,oBAAoB,GAAG,EAAE,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AI,CAAC,aAAa,EAAE,WAAW,EAAE,IAAI,CAAC,CAAC;IACvD,CAAC;CACJ,CAAA;AA5EY,wCAAc;yBAAd,cAAc;IAD1B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGR,6BAAY;QACR,2BAAU;QAChB,mCAAgB;QAGX,iCAAe;GAPtC,cAAc,CA4E1B;AAED,qGAAqG;AACrG,MAAM,iBAAiB,GAAG,IAAI,cAAc,EAAE,CAAC;AAE/C,SAAgB,YAAY,CAAC,IAAY;IACrC,OAAO,iBAAiB,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;AAChD,CAAC;AAED,SAAgB,sBAAsB,CAClC,aAAqB,EACrB,IAAY,EACZ,cAAsB,oBAAoB;IAE1C,iBAAiB,CAAC,sBAAsB,CAAC,aAAa,EAAE,IAAI,EAAE,WAAW,CAAC,CAAC;AAC/E,CAAC;AAED,SAAgB,aAAa,CACzB,aAAqB,EACrB,IAAY,EACZ,cAAsB,oBAAoB;IAE1C,OAAO,iBAAiB,CAAC,aAAa,CAAC,aAAa,EAAE,IAAI,EAAE,WAAW,CAAC,CAAC;AAC7E,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { AtomicFile } from '@webpieces/tooling-common';\nimport { InstructAiDocSet } from './instruct-ai-docs';\nimport { INSTRUCT_AI_LEAF } from './repo-root';\nimport { DotWebpieces, dotWebpieces } from '@webpieces/tooling-common';\nimport { StaleBinSweeper, staleBinSweeper } from './stale-bin-sweep';\n\nconst TEMPLATES_DIR = path.join(__dirname, '..', 'templates');\n// Sentinel for \"use the resolved LOCAL instruct-ai dir\". Kept as the parameter default so the handful\n// of callers that pass an explicit relative dir (they join it onto workspaceRoot themselves) are\n// unaffected; anything passing the default gets DotWebpieces.local() resolution.\nconst DEFAULT_INSTRUCT_DIR = '';\n\n/**\n * Writes the AI-facing instruct-ai template docs under `<workspaceRoot>/.webpieces/instruct-ai/`.\n * `@injectable(bindingScopeValues.Singleton)` so it can be injected and appear in the rules-config DI design.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class TemplateWriter {\n constructor(\n private readonly dotDir: DotWebpieces = dotWebpieces,\n private readonly atomicFile: AtomicFile = new AtomicFile(),\n private readonly docs: InstructAiDocSet = new InstructAiDocSet(),\n // The SHARED sweeper instance, never a fresh one: its \"already swept this root\" memo is per\n // instance, and that memo is what keeps the report to once per `wp-*` command.\n private readonly staleBins: StaleBinSweeper = staleBinSweeper,\n ) {}\n\n loadTemplate(name: string): string {\n return fs.readFileSync(path.join(TEMPLATES_DIR, name), 'utf-8');\n }\n\n /**\n * SEED `name` and everything it links to — writing only the ones that are not already on disk.\n *\n * Same closure as `writeTemplate`, for the same reason: a rule that drops\n * `webpieces.exceptions.md` next to its violation is delivering a doc a reader follows links out\n * of, and a seeded doc that later gains a sibling link would otherwise dangle exactly the way\n * git-workflow.md's link to the merge process did. The difference from `writeTemplate` is only\n * WHETHER an existing file is refreshed, never WHICH files are considered.\n */\n writeTemplateIfMissing(workspaceRoot: string, name: string, instructDir: string = DEFAULT_INSTRUCT_DIR): void {\n for (const doc of this.docs.closure(name, (docName: string): string => this.loadTemplate(docName))) {\n const target = this.destination(workspaceRoot, doc.name, instructDir);\n if (fs.existsSync(target)) continue;\n this.atomicFile.writeAtomic(target, doc.render(this.loadTemplate(doc.name), workspaceRoot));\n }\n }\n\n /**\n * Write `name` AND every instruct-ai doc it links to, ATOMICALLY and only where bytes changed.\n * Returns the absolute path of `name` itself.\n *\n * THE CLOSURE IS THE POINT. Callers name the ONE doc their command is about; the docs a reader is\n * sent on to arrive with it, because a doc whose links dangle is worse than no doc — it teaches the\n * reader that the paths in these files cannot be trusted. See instruct-ai-docs.ts for the incident.\n *\n * Every `wp-*` command regenerates these, and the AI is routinely told to open one by absolute\n * path. A plain truncating write means a reader can catch it empty; skip-if-unchanged means the\n * overwhelmingly common case (same package version ⇒ identical content) does not write at all.\n */\n writeTemplate(workspaceRoot: string, name: string, instructDir: string = DEFAULT_INSTRUCT_DIR): string {\n // THE SELF-HEAL. This is the pass every `wp-*` command takes, which makes it the only place a\n // RELEASED sweep reaches every clone on every developer's machine — see stale-bin-sweep.ts. Silent\n // when there is nothing to remove, and once per root per process.\n this.sweepStaleBins(workspaceRoot);\n for (const doc of this.docs.closure(name, (docName: string): string => this.loadTemplate(docName))) {\n const target = this.destination(workspaceRoot, doc.name, instructDir);\n // A doc stamped with live run state is SEEDED, never refreshed: `wp-finish-upsert-pr` runs\n // while a conflicted merge is still open, and clobbering that handback with the reference\n // copy would delete the file list the agent is working from.\n if (doc.seedOnly() && fs.existsSync(target)) continue;\n this.atomicFile.writeIfChanged(target, doc.render(this.loadTemplate(doc.name), workspaceRoot));\n }\n return this.destination(workspaceRoot, name, instructDir);\n }\n\n /**\n * Remove this tree's dangling `wp-*` bin symlinks and SAY what went, on stdout beside everything else\n * a `wp-*` command prints. Nothing removed ⇒ nothing printed, which is the overwhelmingly common case.\n */\n private sweepStaleBins(workspaceRoot: string): void {\n const removed = this.staleBins.sweepOnce(workspaceRoot);\n for (const line of this.staleBins.report(removed)) process.stdout.write(line + '\\n');\n }\n\n // LOCAL `.webpieces/instruct-ai/<name>` by default; an explicitly-passed relative dir is still\n // joined onto workspaceRoot exactly as before.\n private destination(workspaceRoot: string, name: string, instructDir: string): string {\n if (instructDir === DEFAULT_INSTRUCT_DIR) {\n return this.dotDir.localFile(workspaceRoot, INSTRUCT_AI_LEAF, name);\n }\n return path.join(workspaceRoot, instructDir, name);\n }\n}\n\n// Temporary migration delegators — consumers migrate to injecting TemplateWriter over follow-up PRs.\nconst templateWriterSvc = new TemplateWriter();\n\nexport function loadTemplate(name: string): string {\n return templateWriterSvc.loadTemplate(name);\n}\n\nexport function writeTemplateIfMissing(\n workspaceRoot: string,\n name: string,\n instructDir: string = DEFAULT_INSTRUCT_DIR,\n): void {\n templateWriterSvc.writeTemplateIfMissing(workspaceRoot, name, instructDir);\n}\n\nexport function writeTemplate(\n workspaceRoot: string,\n name: string,\n instructDir: string = DEFAULT_INSTRUCT_DIR,\n): string {\n return templateWriterSvc.writeTemplate(workspaceRoot, name, instructDir);\n}\n"]}
@@ -1,4 +1,4 @@
1
- /** The rules-config template name, and the file name it lands under in `.webpieces-logs/instruct-ai/`. */
1
+ /** The rules-config template name, and the file name it lands under in `.webpieces/instruct-ai/`. */
2
2
  export declare const MERGE_PROCESS_DOC = "webpieces.mergeprocess.md";
3
3
  /**
4
4
  * The values one merge run stamps into the doc, plus the one rendering that depends on WHICH state
@@ -20,7 +20,7 @@
20
20
  Object.defineProperty(exports, "__esModule", { value: true });
21
21
  exports.MergeProcessText = exports.ReferenceMergeRun = exports.MergeRun = exports.MERGE_PROCESS_DOC = void 0;
22
22
  const constants_1 = require("./constants");
23
- /** The rules-config template name, and the file name it lands under in `.webpieces-logs/instruct-ai/`. */
23
+ /** The rules-config template name, and the file name it lands under in `.webpieces/instruct-ai/`. */
24
24
  exports.MERGE_PROCESS_DOC = 'webpieces.mergeprocess.md';
25
25
  const REFERENCE_RUN_STATE = `**Reference copy — no conflicted 3-point merge is in progress in this tree.** It is written beside
26
26
  \`webpieces.git-workflow.md\` on every \`wp-*\` command, so the link from that doc always resolves.
@@ -30,7 +30,7 @@ this file in place with the branch you are standing on, that run's absolute \`ME
30
30
  finish command for the flow you started, and the list of conflicted files. Until that happens, read
31
31
  what follows as the PROCESS and not as a live handback: \`<feature>Squash\` stands for the transient
32
32
  branch a conflicted merge puts you on, and \`MERGE_DIR\` for that run's
33
- \`.webpieces-logs/merge-info/<feature>/merge-<n>/\` directory.`;
33
+ \`.webpieces/merge-info/<feature>/merge-<n>/\` directory.`;
34
34
  const REFERENCE_FILE_LIST = '*(none — no conflicted merge is in progress; the live copy lists this run\'s conflicted files here)*';
35
35
  /**
36
36
  * The values one merge run stamps into the doc, plus the one rendering that depends on WHICH state
@@ -1 +1 @@
1
- {"version":3,"file":"merge-process-doc.js","sourceRoot":"","sources":["../../../../../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CAAC,CAAC;IAC5G,CAAC;IAEQ,QAAQ;QACb,OAAO,mBAAmB,CAAC;IAC/B,CAAC;CACJ;AARD,8CAQC;AAED,wGAAwG;AACxG,MAAa,gBAAgB;IACI;IAAmC;IAAhE,YAA6B,QAAgB,EAAmB,kBAA0B,kCAAsB;QAAnF,aAAQ,GAAR,QAAQ,CAAQ;QAAmB,oBAAe,GAAf,eAAe,CAAiC;IAAG,CAAC;IAEpH,MAAM,CAAC,GAAa;QAChB,OAAO,IAAI,CAAC,QAAQ;aACf,OAAO,CAAC,oBAAoB,EAAE,GAAG,CAAC,QAAQ,EAAE,CAAC;aAC7C,OAAO,CAAC,wBAAwB,EAAE,GAAG,CAAC,YAAY,CAAC;aACnD,OAAO,CAAC,oBAAoB,EAAE,GAAG,CAAC,QAAQ,CAAC;aAC3C,OAAO,CAAC,2BAA2B,EAAE,IAAI,CAAC,eAAe,CAAC;aAC1D,OAAO,CAAC,yBAAyB,EAAE,GAAG,CAAC,aAAa,CAAC;aACrD,OAAO,CAAC,wBAAwB,EAAE,GAAG,CAAC,YAAY,CAAC;aACnD,OAAO,CAAC,oBAAoB,EAAE,GAAG,CAAC,QAAQ,CAAC,CAAC;IACrD,CAAC;CACJ;AAbD,4CAaC","sourcesContent":["// ---------------------------------------------------------------------------\n// `webpieces.mergeprocess.md` — ONE template, TWO inputs.\n//\n// The merge-process doc used to live as a template literal inside pr-gate's `merge-start.ts`, and was\n// written ONLY when a 3-point merge actually conflicted. `webpieces.git-workflow.md` links to it\n// unconditionally, so in every tree that had not yet hit a conflict that link pointed at nothing —\n// measured in six of nine governed repos.\n//\n// The cure is not \"write it from one more place\". It is to make the doc a rules-config TEMPLATE like\n// every other instruct-ai doc, so `InstructAiDocSet` delivers it as part of git-workflow.md's LINK\n// CLOSURE, and to give that template one renderer with two possible inputs:\n//\n// new ReferenceMergeRun() the tree has no conflicted merge — the doc reads as the PROCESS\n// new MergeRun(...) pr-gate's conflict handback — the doc reads as a LIVE handback\n//\n// Two inputs, one output shape: there is exactly one spelling of the merge process, and the delivered\n// copy cannot drift from it because the delivered copy IS it.\n// ---------------------------------------------------------------------------\n\nimport { MERGE_EXPLANATION_FILE } from './constants';\n\n/** The rules-config template name, and the file name it lands under in `.webpieces-logs/instruct-ai/`. */\nexport const MERGE_PROCESS_DOC = 'webpieces.mergeprocess.md';\n\nconst REFERENCE_RUN_STATE = `**Reference copy — no conflicted 3-point merge is in progress in this tree.** It is written beside\n\\`webpieces.git-workflow.md\\` on every \\`wp-*\\` command, so the link from that doc always resolves.\n\nWhen a 3-point merge DOES conflict, \\`pnpm wp-start-upsert-pr\\` (or \\`pnpm wp-start-update\\`) rewrites\nthis file in place with the branch you are standing on, that run's absolute \\`MERGE_DIR\\`, the exact\nfinish command for the flow you started, and the list of conflicted files. Until that happens, read\nwhat follows as the PROCESS and not as a live handback: \\`<feature>Squash\\` stands for the transient\nbranch a conflicted merge puts you on, and \\`MERGE_DIR\\` for that run's\n\\`.webpieces-logs/merge-info/<feature>/merge-<n>/\\` directory.`;\n\nconst REFERENCE_FILE_LIST =\n '*(none — no conflicted merge is in progress; the live copy lists this run\\'s conflicted files here)*';\n\n/**\n * The values one merge run stamps into the doc, plus the one rendering that depends on WHICH state\n * this is.\n *\n * `ReferenceMergeRun` below is not a second document — it is these same fields standing for \"no run in\n * progress\", which is exactly what a reader of the delivered copy has to be told before following the\n * steps. One class and its subclass, so there is one merge process and two things it can be about.\n */\nexport class MergeRun {\n // eslint-disable-next-line @typescript-eslint/max-params -- the five values one merge run stamps in\n constructor(\n /** The `wp-start-*` command that produced this state. */\n readonly startCommand: string,\n /** Its paired `wp-finish-*` command — the ONLY way out of a conflicted merge. */\n readonly finishCommand: string,\n /** The transient `<feature>Squash` branch the merge put the caller on. */\n readonly squashBranch: string,\n /** Absolute path of this run's `merge-<n>/` context dir. */\n readonly mergeDir: string,\n /** Markdown bullet list of the conflicted files. */\n readonly fileList: string,\n ) {}\n\n /** The doc's opening block: a LIVE conflict handback naming this run's branch and dir. */\n runState(): string {\n return `This file was generated by \\`pnpm ${this.startCommand}\\` when the 3-point squash-merge hit conflicts.\\n` +\n 'It is the single source of truth for the merge process — follow it exactly.\\n\\n' +\n `You are on branch \\`${this.squashBranch}\\` with conflict markers in the working tree.\\n` +\n `\\`MERGE_DIR = ${this.mergeDir}\\``;\n }\n}\n\n/** The state of a tree with NO conflicted merge in it — what the delivered reference copy describes. */\nexport class ReferenceMergeRun extends MergeRun {\n constructor() {\n super('wp-start-upsert-pr', 'wp-finish-upsert-pr', '<feature>Squash', 'MERGE_DIR', REFERENCE_FILE_LIST);\n }\n\n override runState(): string {\n return REFERENCE_RUN_STATE;\n }\n}\n\n/** Substitutes one `MergeRun` (and the fixed explanation-file name) into the merge-process template. */\nexport class MergeProcessText {\n constructor(private readonly template: string, private readonly explanationFile: string = MERGE_EXPLANATION_FILE) {}\n\n render(run: MergeRun): string {\n return this.template\n .replace(/\\{\\{RUN_STATE\\}\\}/g, run.runState())\n .replace(/\\{\\{SQUASH_BRANCH\\}\\}/g, run.squashBranch)\n .replace(/\\{\\{MERGE_DIR\\}\\}/g, run.mergeDir)\n .replace(/\\{\\{EXPLANATION_FILE\\}\\}/g, this.explanationFile)\n .replace(/\\{\\{FINISH_COMMAND\\}\\}/g, run.finishCommand)\n .replace(/\\{\\{START_COMMAND\\}\\}/g, run.startCommand)\n .replace(/\\{\\{FILE_LIST\\}\\}/g, run.fileList);\n }\n}\n"]}
1
+ {"version":3,"file":"merge-process-doc.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/merge-process-doc.ts"],"names":[],"mappings":";AAAA,8EAA8E;AAC9E,0DAA0D;AAC1D,EAAE;AACF,sGAAsG;AACtG,iGAAiG;AACjG,mGAAmG;AACnG,0CAA0C;AAC1C,EAAE;AACF,qGAAqG;AACrG,mGAAmG;AACnG,4EAA4E;AAC5E,EAAE;AACF,6FAA6F;AAC7F,4FAA4F;AAC5F,EAAE;AACF,sGAAsG;AACtG,8DAA8D;AAC9D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AAa;QAChB,OAAO,IAAI,CAAC,QAAQ;aACf,OAAO,CAAC,oBAAoB,EAAE,GAAG,CAAC,QAAQ,EAAE,CAAC;aAC7C,OAAO,CAAC,wBAAwB,EAAE,GAAG,CAAC,YAAY,CAAC;aACnD,OAAO,CAAC,oBAAoB,EAAE,GAAG,CAAC,QAAQ,CAAC;aAC3C,OAAO,CAAC,2BAA2B,EAAE,IAAI,CAAC,eAAe,CAAC;aAC1D,OAAO,CAAC,yBAAyB,EAAE,GAAG,CAAC,aAAa,CAAC;aACrD,OAAO,CAAC,wBAAwB,EAAE,GAAG,CAAC,YAAY,CAAC;aACnD,OAAO,CAAC,oBAAoB,EAAE,GAAG,CAAC,QAAQ,CAAC,CAAC;IACrD,CAAC;CACJ;AAbD,4CAaC","sourcesContent":["// ---------------------------------------------------------------------------\n// `webpieces.mergeprocess.md` — ONE template, TWO inputs.\n//\n// The merge-process doc used to live as a template literal inside pr-gate's `merge-start.ts`, and was\n// written ONLY when a 3-point merge actually conflicted. `webpieces.git-workflow.md` links to it\n// unconditionally, so in every tree that had not yet hit a conflict that link pointed at nothing —\n// measured in six of nine governed repos.\n//\n// The cure is not \"write it from one more place\". It is to make the doc a rules-config TEMPLATE like\n// every other instruct-ai doc, so `InstructAiDocSet` delivers it as part of git-workflow.md's LINK\n// CLOSURE, and to give that template one renderer with two possible inputs:\n//\n// new ReferenceMergeRun() the tree has no conflicted merge — the doc reads as the PROCESS\n// new MergeRun(...) pr-gate's conflict handback — the doc reads as a LIVE handback\n//\n// Two inputs, one output shape: there is exactly one spelling of the merge process, and the delivered\n// copy cannot drift from it because the delivered copy IS it.\n// ---------------------------------------------------------------------------\n\nimport { MERGE_EXPLANATION_FILE } from './constants';\n\n/** The rules-config template name, and the file name it lands under in `.webpieces/instruct-ai/`. */\nexport const MERGE_PROCESS_DOC = 'webpieces.mergeprocess.md';\n\nconst REFERENCE_RUN_STATE = `**Reference copy — no conflicted 3-point merge is in progress in this tree.** It is written beside\n\\`webpieces.git-workflow.md\\` on every \\`wp-*\\` command, so the link from that doc always resolves.\n\nWhen a 3-point merge DOES conflict, \\`pnpm wp-start-upsert-pr\\` (or \\`pnpm wp-start-update\\`) rewrites\nthis file in place with the branch you are standing on, that run's absolute \\`MERGE_DIR\\`, the exact\nfinish command for the flow you started, and the list of conflicted files. Until that happens, read\nwhat follows as the PROCESS and not as a live handback: \\`<feature>Squash\\` stands for the transient\nbranch a conflicted merge puts you on, and \\`MERGE_DIR\\` for that run's\n\\`.webpieces/merge-info/<feature>/merge-<n>/\\` directory.`;\n\nconst REFERENCE_FILE_LIST =\n '*(none — no conflicted merge is in progress; the live copy lists this run\\'s conflicted files here)*';\n\n/**\n * The values one merge run stamps into the doc, plus the one rendering that depends on WHICH state\n * this is.\n *\n * `ReferenceMergeRun` below is not a second document — it is these same fields standing for \"no run in\n * progress\", which is exactly what a reader of the delivered copy has to be told before following the\n * steps. One class and its subclass, so there is one merge process and two things it can be about.\n */\nexport class MergeRun {\n // eslint-disable-next-line @typescript-eslint/max-params -- the five values one merge run stamps in\n constructor(\n /** The `wp-start-*` command that produced this state. */\n readonly startCommand: string,\n /** Its paired `wp-finish-*` command — the ONLY way out of a conflicted merge. */\n readonly finishCommand: string,\n /** The transient `<feature>Squash` branch the merge put the caller on. */\n readonly squashBranch: string,\n /** Absolute path of this run's `merge-<n>/` context dir. */\n readonly mergeDir: string,\n /** Markdown bullet list of the conflicted files. */\n readonly fileList: string,\n ) {}\n\n /** The doc's opening block: a LIVE conflict handback naming this run's branch and dir. */\n runState(): string {\n return `This file was generated by \\`pnpm ${this.startCommand}\\` when the 3-point squash-merge hit conflicts.\\n` +\n 'It is the single source of truth for the merge process — follow it exactly.\\n\\n' +\n `You are on branch \\`${this.squashBranch}\\` with conflict markers in the working tree.\\n` +\n `\\`MERGE_DIR = ${this.mergeDir}\\``;\n }\n}\n\n/** The state of a tree with NO conflicted merge in it — what the delivered reference copy describes. */\nexport class ReferenceMergeRun extends MergeRun {\n constructor() {\n super('wp-start-upsert-pr', 'wp-finish-upsert-pr', '<feature>Squash', 'MERGE_DIR', REFERENCE_FILE_LIST);\n }\n\n override runState(): string {\n return REFERENCE_RUN_STATE;\n }\n}\n\n/** Substitutes one `MergeRun` (and the fixed explanation-file name) into the merge-process template. */\nexport class MergeProcessText {\n constructor(private readonly template: string, private readonly explanationFile: string = MERGE_EXPLANATION_FILE) {}\n\n render(run: MergeRun): string {\n return this.template\n .replace(/\\{\\{RUN_STATE\\}\\}/g, run.runState())\n .replace(/\\{\\{SQUASH_BRANCH\\}\\}/g, run.squashBranch)\n .replace(/\\{\\{MERGE_DIR\\}\\}/g, run.mergeDir)\n .replace(/\\{\\{EXPLANATION_FILE\\}\\}/g, this.explanationFile)\n .replace(/\\{\\{FINISH_COMMAND\\}\\}/g, run.finishCommand)\n .replace(/\\{\\{START_COMMAND\\}\\}/g, run.startCommand)\n .replace(/\\{\\{FILE_LIST\\}\\}/g, run.fileList);\n }\n}\n"]}
@@ -23,7 +23,7 @@ class MigrateDirsCli {
23
23
  const raw = new config_file_1.ConfigFile().readRawConfig(`${root}/webpieces.config.json`);
24
24
  new policy_tracking_1.PolicyTracking().stage(root, new pack_policy_files_1.PackPolicyFiles().declarations(raw.rulePacks, root));
25
25
  }
26
- console.log(`Webpieces directories migrated. Review and commit .webpieces-config/ and webpieces.config.json; ignore only .webpieces-logs/.\n${changed.join('\n')}`);
26
+ console.log(`Webpieces directories migrated. Review and commit .webpieces-config/ and webpieces.config.json; ignore only .webpieces/.\n${changed.join('\n')}`);
27
27
  }
28
28
  }
29
29
  exports.MigrateDirsCli = MigrateDirsCli;
@@ -1 +1 @@
1
- {"version":3,"file":"migrate-dirs-cli.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/migrate-dirs-cli.ts"],"names":[],"mappings":";;;;AACA,8DAAwF;AACxF,+CAA2C;AAC3C,2DAAsD;AACtD,+DAA0D;AAC1D,qDAAqE;AACrE,uDAAmD;AACnD,2CAA6C;AAC7C,yCAAqC;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c,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\nimport { RepositoryLayout, AtomicFile, InformAiError } from '@webpieces/tooling-common';\nimport { ConfigFile } from './config-file';\nimport { PackPolicyFiles } from './pack-policy-files';\nimport { RulePackArtifacts } from './rule-pack-artifacts';\nimport { RulePackSync, RulePackSyncOptions } from './rule-pack-sync';\nimport { PolicyTracking } from './policy-tracking';\nimport { RepoRootFinder } from './repo-root';\nimport { runMain } from './run-main';\n\nexport class MigrateDirsCli {\n async main(): Promise<void> {\n const args = process.argv.slice(2);\n if (args.some((argument) => argument !== '--stage'))\n throw new InformAiError(\n 'Usage: pnpm wp-migrate-dirs [--stage]. --stage explicitly stages the migrated policy for commit.',\n );\n const root = new RepoRootFinder().resolveRepoRoot(process.cwd());\n const changed = new RepositoryLayout().migrate(root);\n const atomic = new AtomicFile();\n new RulePackSync(\n new ConfigFile(),\n new PackPolicyFiles(),\n new RulePackArtifacts(atomic),\n atomic,\n ).run(root, new RulePackSyncOptions('sync', null));\n if (args.includes('--stage')) {\n const raw = new ConfigFile().readRawConfig(`${root}/webpieces.config.json`);\n new PolicyTracking().stage(\n root,\n new PackPolicyFiles().declarations(raw.rulePacks, root),\n );\n }\n console.log(\n `Webpieces directories migrated. Review and commit .webpieces-config/ and webpieces.config.json; ignore only .webpieces-logs/.\\n${changed.join('\\n')}`,\n );\n }\n}\n\nif (require.main === module) runMain(() => new MigrateDirsCli().main());\n"]}
1
+ {"version":3,"file":"migrate-dirs-cli.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/migrate-dirs-cli.ts"],"names":[],"mappings":";;;;AACA,8DAAwF;AACxF,+CAA2C;AAC3C,2DAAsD;AACtD,+DAA0D;AAC1D,qDAAqE;AACrE,uDAAmD;AACnD,2CAA6C;AAC7C,yCAAqC;AAErC,MAAa,cAAc;IACvB,KAAK,CAAC,IAAI;QACN,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,C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@webpieces/tooling-common';\nimport { ConfigFile } from './config-file';\nimport { PackPolicyFiles } from './pack-policy-files';\nimport { RulePackArtifacts } from './rule-pack-artifacts';\nimport { RulePackSync, RulePackSyncOptions } from './rule-pack-sync';\nimport { PolicyTracking } from './policy-tracking';\nimport { RepoRootFinder } from './repo-root';\nimport { runMain } from './run-main';\n\nexport class MigrateDirsCli {\n async main(): Promise<void> {\n const args = process.argv.slice(2);\n if (args.some((argument) => argument !== '--stage'))\n throw new InformAiError(\n 'Usage: pnpm wp-migrate-dirs [--stage]. --stage explicitly stages the migrated policy for commit.',\n );\n const root = new RepoRootFinder().resolveRepoRoot(process.cwd());\n const changed = new RepositoryLayout().migrate(root);\n const atomic = new AtomicFile();\n new RulePackSync(\n new ConfigFile(),\n new PackPolicyFiles(),\n new RulePackArtifacts(atomic),\n atomic,\n ).run(root, new RulePackSyncOptions('sync', null));\n if (args.includes('--stage')) {\n const raw = new ConfigFile().readRawConfig(`${root}/webpieces.config.json`);\n new PolicyTracking().stage(\n root,\n new PackPolicyFiles().declarations(raw.rulePacks, root),\n );\n }\n console.log(\n `Webpieces directories migrated. Review and commit .webpieces-config/ and webpieces.config.json; ignore only .webpieces/.\\n${changed.join('\\n')}`,\n );\n }\n}\n\nif (require.main === module) runMain(() => new MigrateDirsCli().main());\n"]}
@@ -1,12 +1,12 @@
1
1
  import { OrphanCandidate } from './orphan-dir-scan';
2
- /** Where every sweep's archive lands, under the repo-wide `.webpieces-logs/` — never under a worktree's own. */
2
+ /** Where every sweep's archive lands, under the repo-wide `.webpieces/` — never under a worktree's own. */
3
3
  export declare const TRASH_STATE_DIR = "trash";
4
4
  /** The per-sweep manifest, holding what moved and the command that brings each one back. */
5
5
  export declare const TRASH_MANIFEST_FILE = "manifest.json";
6
6
  /** Sweeps older than this are reaped by the next sweep. Matches RETENTION_DAYS for the aged-tree sweep. */
7
7
  export declare const TRASH_RETENTION_DAYS = 30;
8
8
  /**
9
- * Moves orphan directories into `.webpieces-logs/trash/<sweepId>/` and records how to bring each one back.
9
+ * Moves orphan directories into `.webpieces/trash/<sweepId>/` and records how to bring each one back.
10
10
  *
11
11
  * ─── WHY `mv` AND NEVER `rm -rf` ──────────────────────────────────────────────────────────────────────
12
12
  * This runs unattended, on other people's machines, against a predicate that is very good but is still a
@@ -37,7 +37,7 @@ export declare class OrphanDirArchiver {
37
37
  * flag on. This one really does delete — it is deleting the archive, which is the second copy.
38
38
  */
39
39
  reapAged(repoRoot: string, now: Date): number;
40
- /** `<repo>/.webpieces-logs/trash` — the SHARED state dir, so a worktree's trash is not stranded with it. */
40
+ /** `<repo>/.webpieces/trash` — the SHARED state dir, so a worktree's trash is not stranded with it. */
41
41
  trashRoot(repoRoot: string): string;
42
42
  /**
43
43
  * `2026-08-19T14-32-05Z`. ISO order with `:` replaced, and milliseconds dropped — a sweep is a
@@ -52,7 +52,7 @@ export declare class OrphanDirArchiver {
52
52
  * failure's message — a directory we cannot move is REPORTED and skipped, never fatal.
53
53
  *
54
54
  * `fs.renameSync` first because it is atomic and instant within a filesystem; a cross-device rename
55
- * (EXDEV — a repo whose `.webpieces-logs` sits on a different mount) falls back to a recursive copy plus
55
+ * (EXDEV — a repo whose `.webpieces` sits on a different mount) falls back to a recursive copy plus
56
56
  * delete, which is what `mv` itself does in the same situation.
57
57
  */
58
58
  private move;
@@ -7,7 +7,7 @@ const path = tslib_1.__importStar(require("path"));
7
7
  const inversify_1 = require("inversify");
8
8
  const tooling_common_1 = require("@webpieces/tooling-common");
9
9
  const to_error_1 = require("@webpieces/tooling-common/to-error");
10
- /** Where every sweep's archive lands, under the repo-wide `.webpieces-logs/` — never under a worktree's own. */
10
+ /** Where every sweep's archive lands, under the repo-wide `.webpieces/` — never under a worktree's own. */
11
11
  exports.TRASH_STATE_DIR = 'trash';
12
12
  /** The per-sweep manifest, holding what moved and the command that brings each one back. */
13
13
  exports.TRASH_MANIFEST_FILE = 'manifest.json';
@@ -15,7 +15,7 @@ exports.TRASH_MANIFEST_FILE = 'manifest.json';
15
15
  exports.TRASH_RETENTION_DAYS = 30;
16
16
  const MILLIS_PER_DAY = 24 * 60 * 60 * 1000;
17
17
  /**
18
- * Moves orphan directories into `.webpieces-logs/trash/<sweepId>/` and records how to bring each one back.
18
+ * Moves orphan directories into `.webpieces/trash/<sweepId>/` and records how to bring each one back.
19
19
  *
20
20
  * ─── WHY `mv` AND NEVER `rm -rf` ──────────────────────────────────────────────────────────────────────
21
21
  * This runs unattended, on other people's machines, against a predicate that is very good but is still a
@@ -74,7 +74,7 @@ let OrphanDirArchiver = class OrphanDirArchiver {
74
74
  }
75
75
  return reaped;
76
76
  }
77
- /** `<repo>/.webpieces-logs/trash` — the SHARED state dir, so a worktree's trash is not stranded with it. */
77
+ /** `<repo>/.webpieces/trash` — the SHARED state dir, so a worktree's trash is not stranded with it. */
78
78
  trashRoot(repoRoot) {
79
79
  return path.join(tooling_common_1.dotWebpieces.shared(repoRoot), exports.TRASH_STATE_DIR);
80
80
  }
@@ -111,7 +111,7 @@ let OrphanDirArchiver = class OrphanDirArchiver {
111
111
  * failure's message — a directory we cannot move is REPORTED and skipped, never fatal.
112
112
  *
113
113
  * `fs.renameSync` first because it is atomic and instant within a filesystem; a cross-device rename
114
- * (EXDEV — a repo whose `.webpieces-logs` sits on a different mount) falls back to a recursive copy plus
114
+ * (EXDEV — a repo whose `.webpieces` sits on a different mount) falls back to a recursive copy plus
115
115
  * delete, which is what `mv` itself does in the same situation.
116
116
  */
117
117
  move(from, to) {
@@ -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,gHAAgH;AACnG,QAAA,eAAe,GAAG,OAAO,CAAC;AACvC,4FAA4F;AAC/E,QAAA,mBAAmB,GAAG,eAAe,CAAC;AACnD,2GAA2G;AAC9F,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B;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"]}
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,GAA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AAM,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/` — 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"]}
@@ -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-logs/` and friends are reported whole by `clean -Xdn` (their
60
+ * DOT SEGMENTS: `.nx/`, `.idea/`, `.webpieces/` 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-logs/` and friends are reported whole by `clean -Xdn` (their
95
+ * DOT SEGMENTS: `.nx/`, `.idea/`, `.webpieces/` 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,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,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"]}
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,CAA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,CAAC,IAAI,EAAE,QAAQ,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"]}
@@ -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-logs/trash/<sweepId>/ with a recover=\n`
101
+ + ` To archive them (never delete: they move to .webpieces/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`;