@pareto4/pp-core 1.13.0 → 1.18.0

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 (204) hide show
  1. package/.claude-plugin/plugin.json +3 -3
  2. package/README.md +31 -12
  3. package/agents/pp-code-fixer.md +0 -11
  4. package/agents/pp-code-reviewer.md +1 -77
  5. package/agents/pp-debug-session-manager.md +9 -6
  6. package/agents/pp-executor.md +12 -29
  7. package/agents/pp-plan-checker.md +4 -4
  8. package/agents/pp-planner.md +34 -20
  9. package/agents/pp-vault-reviewer.md +100 -23
  10. package/agents/pp-verifier.md +1 -3
  11. package/bin/install.js +10 -3
  12. package/commands/pp-execute-phase.md +1 -3
  13. package/commands/pp-ns-manage.md +1 -1
  14. package/commands/pp-ns-review.md +1 -1
  15. package/commands/pp-plan-phase.md +1 -2
  16. package/commands/pp-vault-promote.md +7 -8
  17. package/commands/pp-vault-review.md +6 -5
  18. package/commands/pp-verify-work.md +1 -2
  19. package/gemini-extension.json +1 -1
  20. package/hooks/dist/pp-check-update.js +0 -0
  21. package/hooks/dist/pp-cursor-session-start.js +1 -1
  22. package/hooks/dist/pp-statusline.js +1 -1
  23. package/hooks/dist/pp-update-banner.js +0 -0
  24. package/hooks/pp-check-update.js +0 -0
  25. package/hooks/pp-cursor-session-start.js +1 -1
  26. package/hooks/pp-statusline.js +1 -1
  27. package/hooks/pp-update-banner.js +0 -0
  28. package/package.json +10 -18
  29. package/pareto-skills/_shared/create-project-board.sh +0 -0
  30. package/pareto-skills/pp-project-setup/SKILL.md +1 -1
  31. package/pp-core/bin/check-latest-version.cjs +0 -0
  32. package/pp-core/bin/detect-build-commands.sh +2 -2
  33. package/pp-core/bin/lib/capability-activation.cjs +83 -9
  34. package/pp-core/bin/lib/capability-registry.cjs +201 -229
  35. package/pp-core/bin/lib/capability-state.cjs +93 -1
  36. package/pp-core/bin/lib/capability-writer.cjs +3 -3
  37. package/pp-core/bin/lib/check-command-router.cjs +1906 -1514
  38. package/pp-core/bin/lib/clusters.cjs +3 -0
  39. package/pp-core/bin/lib/command-aliases.cjs +0 -35
  40. package/pp-core/bin/lib/commands.cjs +9 -4
  41. package/pp-core/bin/lib/compose-bindings.cjs +251 -88
  42. package/pp-core/bin/lib/config-loader.cjs +7 -103
  43. package/pp-core/bin/lib/config-schema.cjs +1 -1
  44. package/pp-core/bin/lib/config.cjs +151 -62
  45. package/pp-core/bin/lib/decisions.cjs +4 -4
  46. package/pp-core/bin/lib/discovery-vault-check.cjs +246 -0
  47. package/pp-core/bin/lib/frontmatter.cjs +1 -38
  48. package/pp-core/bin/lib/git-base-branch.cjs +11 -12
  49. package/pp-core/bin/lib/git-provider.cjs +9 -10
  50. package/pp-core/bin/lib/init-command-router.cjs +5 -8
  51. package/pp-core/bin/lib/init-contract.cjs +620 -738
  52. package/pp-core/bin/lib/init-interactive.cjs +62 -4
  53. package/pp-core/bin/lib/init.cjs +24 -51
  54. package/pp-core/bin/lib/install-profiles.cjs +1 -1
  55. package/pp-core/bin/lib/io.cjs +4 -2
  56. package/pp-core/bin/lib/loop-resolver.cjs +165 -129
  57. package/pp-core/bin/lib/org-profile.cjs +402 -161
  58. package/pp-core/bin/lib/package-identity.cjs +3 -3
  59. package/pp-core/bin/lib/phase-command-router.cjs +1 -29
  60. package/pp-core/bin/lib/phase-scope.cjs +1 -1
  61. package/pp-core/bin/lib/phase.cjs +11 -253
  62. package/pp-core/bin/lib/platform-bindings.cjs +40 -19
  63. package/pp-core/bin/lib/profile-output.cjs +1 -1
  64. package/pp-core/bin/lib/shell-command-projection.cjs +104 -1
  65. package/pp-core/bin/lib/state.cjs +11 -85
  66. package/pp-core/bin/lib/template.cjs +1 -1
  67. package/pp-core/bin/lib/vault-command-router.cjs +1682 -477
  68. package/pp-core/bin/lib/vault-coordinates.cjs +16 -7
  69. package/pp-core/bin/lib/vault-index.cjs +656 -0
  70. package/pp-core/bin/lib/vault-seal.cjs +1851 -0
  71. package/pp-core/bin/lib/vault-standards-promote.cjs +577 -0
  72. package/pp-core/bin/lib/vault-standards-review.cjs +293 -0
  73. package/pp-core/bin/lib/vault-standards.cjs +1504 -0
  74. package/pp-core/bin/lib/vault-trace.cjs +155 -2778
  75. package/pp-core/bin/lib/vault-update.cjs +10 -59
  76. package/pp-core/bin/lib/vault.cjs +2570 -950
  77. package/pp-core/bin/lib/verify.cjs +0 -11
  78. package/pp-core/bin/portable-timeout.sh +1 -1
  79. package/pp-core/bin/pp-tools.cjs +157 -54
  80. package/pp-core/bin/shared/config-defaults.manifest.json +0 -7
  81. package/pp-core/bin/shared/config-schema.manifest.json +0 -3
  82. package/pp-core/bin/shared/model-catalog.json +2 -2
  83. package/pp-core/bin/verify-reapply-patches.cjs +0 -0
  84. package/pp-core/org-profile.json +26 -0
  85. package/pp-core/references/autonomous-best-effort.md +8 -7
  86. package/pp-core/references/loop-hook-dispatch.md +0 -25
  87. package/pp-core/references/planner-gap-closure.md +0 -1
  88. package/pp-core/references/planner-tdd.md +0 -1
  89. package/pp-core/references/planner-vault-standards.md +311 -0
  90. package/pp-core/references/planning-config.md +0 -8
  91. package/pp-core/references/tdd.md +0 -1
  92. package/pp-core/templates/README.md +1 -0
  93. package/pp-core/templates/VAULT-REVIEW.md +56 -0
  94. package/pp-core/templates/phase-prompt.md +2 -6
  95. package/pp-core/workflows/_runtime-launcher.snippet.sh +0 -0
  96. package/pp-core/workflows/add-tests.md +55 -4
  97. package/pp-core/workflows/audit-fix.md +63 -2
  98. package/pp-core/workflows/audit-milestone.md +1 -1
  99. package/pp-core/workflows/autonomous.md +85 -11
  100. package/pp-core/workflows/check-todos.md +13 -2
  101. package/pp-core/workflows/code-review-fix.md +59 -3
  102. package/pp-core/workflows/code-review.md +10 -57
  103. package/pp-core/workflows/complete-milestone.md +1 -1
  104. package/pp-core/workflows/debug.md +54 -4
  105. package/pp-core/workflows/discovery-sprint/prefill.md +19 -7
  106. package/pp-core/workflows/discovery-sprint/prototype.md +46 -49
  107. package/pp-core/workflows/discovery-sprint/session-13-gates.md +2 -0
  108. package/pp-core/workflows/discovery-sprint/sessions/01-kick-off.md +1 -3
  109. package/pp-core/workflows/discovery-sprint/sessions/02-as-is.md +1 -3
  110. package/pp-core/workflows/discovery-sprint/sessions/03-to-be.md +1 -3
  111. package/pp-core/workflows/discovery-sprint/sessions/04-ux-design.md +20 -24
  112. package/pp-core/workflows/discovery-sprint/sessions/05-architecture.md +1 -3
  113. package/pp-core/workflows/discovery-sprint/sessions/06-security.md +1 -3
  114. package/pp-core/workflows/discovery-sprint/sessions/07-identity.md +1 -3
  115. package/pp-core/workflows/discovery-sprint/sessions/08-integration.md +1 -3
  116. package/pp-core/workflows/discovery-sprint/sessions/09-qa.md +1 -3
  117. package/pp-core/workflows/discovery-sprint/sessions/10-infrastructure.md +1 -6
  118. package/pp-core/workflows/discovery-sprint/sessions/11-roadmap.md +1 -3
  119. package/pp-core/workflows/discovery-sprint/sessions/12-delivery-model.md +1 -3
  120. package/pp-core/workflows/discovery-sprint/sessions/13-wrap-up.md +1 -3
  121. package/pp-core/workflows/discovery-sprint/templates/context-template.md +1 -1
  122. package/pp-core/workflows/discovery-sprint/vault-context.md +207 -0
  123. package/pp-core/workflows/discovery-sprint.md +7 -3
  124. package/pp-core/workflows/discovery-to-build/steps/architecture-deliverables.md +4 -4
  125. package/pp-core/workflows/discovery-to-build/templates/pp-handoff.md +43 -1
  126. package/pp-core/workflows/discovery-to-build.md +10 -2
  127. package/pp-core/workflows/discuss-phase.md +3 -10
  128. package/pp-core/workflows/execute-phase/steps/check-query-gate.md +327 -0
  129. package/pp-core/workflows/execute-phase/steps/client-context-gate.md +3 -2
  130. package/pp-core/workflows/execute-phase/steps/cross-ai-delegation.md +1 -1
  131. package/pp-core/workflows/execute-phase/steps/execute-pre-dispatch.md +78 -0
  132. package/pp-core/workflows/execute-phase/steps/per-plan-worktree-gate.md +94 -0
  133. package/pp-core/workflows/execute-phase/steps/post-merge-gate.md +6 -8
  134. package/pp-core/workflows/execute-phase/steps/vault-fetch.md +115 -14
  135. package/pp-core/workflows/execute-phase/steps/vault-load-gate.md +219 -20
  136. package/pp-core/workflows/execute-phase/steps/verify-post-gate.md +147 -0
  137. package/pp-core/workflows/execute-phase.md +152 -128
  138. package/pp-core/workflows/execute-plan.md +54 -6
  139. package/pp-core/workflows/fast.md +53 -4
  140. package/pp-core/workflows/help/modes/full.md +3 -3
  141. package/pp-core/workflows/init/steps/client-context-capture.md +101 -0
  142. package/pp-core/workflows/init/steps/gitlab-provisioning.md +130 -0
  143. package/pp-core/workflows/init/steps/project-md-deferral-narration.md +66 -0
  144. package/pp-core/workflows/init/steps/reachability-outcome.md +70 -0
  145. package/pp-core/workflows/init.md +232 -272
  146. package/pp-core/workflows/new-project.md +31 -23
  147. package/pp-core/workflows/plan-phase.md +98 -45
  148. package/pp-core/workflows/quick.md +117 -3
  149. package/pp-core/workflows/secure-phase.md +1 -1
  150. package/pp-core/workflows/ship.md +57 -28
  151. package/pp-core/workflows/undo.md +1 -1
  152. package/pp-core/workflows/update.md +3 -3
  153. package/pp-core/workflows/validate-phase.md +58 -3
  154. package/pp-core/workflows/vault-review.md +161 -23
  155. package/pp-core/workflows/vault-write-back.md +73 -110
  156. package/pp-core/workflows/verify-work.md +12 -14
  157. package/scripts/changeset/cli.cjs +6 -5
  158. package/scripts/changeset/lint.cjs +0 -0
  159. package/scripts/changeset/new.cjs +33 -50
  160. package/scripts/dev-env.cjs +25 -85
  161. package/scripts/gen-capability-registry.cjs +120 -13
  162. package/scripts/lib/allowlist-ratchet.cjs +1 -103
  163. package/scripts/lint-allow-test-rule-refs.allowlist.json +0 -2
  164. package/scripts/lint-docs-required.cjs +0 -0
  165. package/scripts/lint-pr-check-project-dir.cjs +1 -3
  166. package/scripts/lint-test-file-count.allowlist.json +3 -19
  167. package/scripts/lint-test-file-count.cjs +5 -6
  168. package/scripts/prompt-injection-scan.sh +19 -17
  169. package/scripts/release-channel.cjs +0 -0
  170. package/scripts/sync-manifest-versions.cjs +5 -4
  171. package/scripts/sync-rulesets.sh +1 -1
  172. package/scripts/update-size-baseline.cjs +30 -274
  173. package/scripts/verify-opengsd-sweep.cjs +3 -5
  174. package/scripts/workflow-size.cjs +9 -61
  175. package/pp-core/bin/lib/dispatch-plan.cjs +0 -483
  176. package/pp-core/bin/lib/install-run.cjs +0 -536
  177. package/pp-core/bin/lib/loop-gates.cjs +0 -213
  178. package/pp-core/bin/lib/phase-manifest.cjs +0 -527
  179. package/pp-core/bin/lib/phase-tier.cjs +0 -480
  180. package/pp-core/bin/lib/plan-graph.cjs +0 -368
  181. package/pp-core/bin/lib/practices-review-check.cjs +0 -938
  182. package/pp-core/bin/lib/vault-audit.cjs +0 -2070
  183. package/pp-core/bin/lib/vault-practices.cjs +0 -1990
  184. package/pp-core/bin/lib/vault-review.cjs +0 -2359
  185. package/pp-core/bin/lib/vault-write-back.cjs +0 -877
  186. package/pp-core/references/executor-vault-trace.md +0 -47
  187. package/pp-core/references/planner-plan-graph.md +0 -66
  188. package/pp-core/references/planner-vault-practices.md +0 -112
  189. package/pp-core/templates/practices/README.md +0 -251
  190. package/pp-core/templates/practices/error-handling.md +0 -18
  191. package/pp-core/templates/practices/minimal-comments.md +0 -14
  192. package/pp-core/templates/practices/naming-convention.md +0 -18
  193. package/pp-core/templates/practices/practice-template.md +0 -23
  194. package/pp-core/workflows/discovery-sprint/vault-fetch.md +0 -37
  195. package/pp-core/workflows/execute-phase/steps/checkpoint-handling.md +0 -45
  196. package/pp-core/workflows/execute-phase/steps/install-run.md +0 -29
  197. package/pp-core/workflows/execute-phase/steps/phase-close-rebaseline.md +0 -23
  198. package/pp-core/workflows/execute-phase/steps/serial-group-dispatch.md +0 -73
  199. package/pp-core/workflows/execute-phase/steps/vault-door-gate.md +0 -19
  200. package/pp-core/workflows/plan-phase/steps/phase-tier.md +0 -43
  201. package/scripts/lib/size-budget.cjs +0 -311
  202. package/scripts/lint-neutrality-names.cjs +0 -694
  203. package/scripts/lint-org-coordinates.allowlist.json +0 -35
  204. package/scripts/lint-org-coordinates.cjs +0 -426
@@ -1,877 +0,0 @@
1
- 'use strict';
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- /**
6
- * src/vault-write-back.cts — Vault write-back promote arm, deterministic
7
- * guard core (milestone v1.10.0 Vault-Guided Code Generation, Phase 29-01).
8
- *
9
- * Responsibility (Phase 29-01 only — the guard-chain half of the arm):
10
- * A curated in-repo secret-content scanner (`SECRET_SHAPES` /
11
- * `scanForSecrets`) plus the preflight guard chain (`promotePreflight`)
12
- * that runs before any git subprocess exists in this module: the
13
- * activation gate, the Phase 24 format validator reused verbatim, the
14
- * secret scan, and the `assertVaultWriteTarget` write-target check. That
15
- * guard's identity is now the resolved `(repo, host)` pair for both
16
- * tiers (Phase 31, CFG-02/D-10) — it gained a required target-host
17
- * parameter, and this arm passes one derived from the coordinate
18
- * resolver rather than a config-only host chain. Every stage emits the
19
- * uniform refusal contract (D-16) via the `refusal` helper.
20
- *
21
- * Deliberately a NEW module (not folded into `src/vault.cts` or
22
- * `src/vault-command-router.cts`) — the name is load-bearing: it forms a
23
- * fresh `vault-write-back` test-file cluster for
24
- * `scripts/lint-test-file-count.cjs` instead of being swept into the
25
- * `vault` cluster, which is already at its allowlisted cap of five files.
26
- *
27
- * Responsibility (Phase 29-02 additions — the read-only half of the write
28
- * path): `previewPromotion` clones the client vault into a disposable temp
29
- * directory, captures the current content of the destination as a pinned
30
- * baseline, stages the promoted content, and asks git itself for the diff
31
- * (or the full content on a create) — so the thing an operator confirms is
32
- * generated from exactly the working-tree state a later confirmed run
33
- * would push. `buildExpectToken` pins both sides (local content + remote
34
- * baseline) into one opaque token 29-03's concurrent-edit guard checks
35
- * against. This is the ONLY function in this module that calls `execGit`,
36
- * and it never creates a commit or moves a remote ref.
37
- *
38
- * Responsibility (Phase 29-03 additions — the write half of the write
39
- * path): `confirmPromotion` re-runs the full 29-01 preflight chain, refuses
40
- * before any clone when the opaque `expect` token is missing or its pinned
41
- * LOCAL hash no longer matches the freshly-read file, clones fresh (never
42
- * reusing the preview's clone or the read cache), fetches the resolved ref
43
- * and fast-forward-only pulls to absorb any unrelated remote movement, then
44
- * re-derives the remote baseline from the now-current working tree and
45
- * compares it against the token's pinned REMOTE hash (file-scoped —
46
- * commit/tree shas are never compared, so an unrelated promotion never
47
- * blocks this one). On a match it stages exactly the destination path,
48
- * commits once, and pushes once with no force flag on any code path — a
49
- * genuine non-fast-forward rejection from git is the intended structural
50
- * backstop and is never retried. On success it refreshes the local read
51
- * cache via `./vault.cjs`'s `vaultFetch` verbatim (D-11), treating a
52
- * refresh failure as non-fatal (the push already succeeded). `promotePractice`
53
- * is the single entry point 29-04's router calls, dispatching to
54
- * `previewPromotion` or `confirmPromotion` on the `confirmed` flag.
55
- *
56
- * Responsibility (Phase 29-04 addition — the human-readable report half):
57
- * `renderPromoteReport` renders any verdict `promotePractice` can produce as
58
- * plain English (COMM-01), selected by the CLI router when `--raw` is
59
- * absent.
60
- *
61
- * Out of scope here (later plans): the workflow/command docs (29-05).
62
- *
63
- * Reuses (no new runtime dependency):
64
- * - `./vault-practices.cjs` (`parsePracticeFile`) — the ONLY format
65
- * validator in the write path (D-03). Reused verbatim, never
66
- * re-derived.
67
- * - `./vault.cjs` (`cfgGet`, `readBindings`, `assertVaultWriteTarget`) —
68
- * this module delegates to `assertVaultWriteTarget` and reimplements
69
- * none of it (D-05); the guard's signature gained a required target
70
- * host in Phase 31 (D-10), which this call site passes from the
71
- * coordinate resolver.
72
- * - `./io.cjs` (`ERROR_REASON`) — the typed refusal reason codes added
73
- * alongside this module.
74
- *
75
- * Test seams: pass `_vault` / `_practices` to inject mock modules (the
76
- * repo's established `_`-prefix convention — see
77
- * `src/vault-command-router.cts`). Production callers omit both; the real
78
- * `./vault.cjs` / `./vault-practices.cjs` are lazy-required inside
79
- * `promotePreflight` so they only load when a promotion actually runs.
80
- *
81
- * ADR-457 build-at-publish: this TypeScript file is the SOURCE OF TRUTH. It
82
- * compiles to the git-ignored `pp-core/bin/lib/vault-write-back.cjs`; do NOT
83
- * hand-edit the compiled output.
84
- */
85
- const node_fs_1 = __importDefault(require("node:fs"));
86
- const node_os_1 = __importDefault(require("node:os"));
87
- const node_path_1 = __importDefault(require("node:path"));
88
- const node_crypto_1 = __importDefault(require("node:crypto"));
89
- const shell_command_projection_cjs_1 = require("./shell-command-projection.cjs");
90
- const git_provider_cjs_1 = require("./git-provider.cjs");
91
- const vault_coordinates_cjs_1 = require("./vault-coordinates.cjs");
92
- // eslint-disable-next-line @typescript-eslint/no-require-imports
93
- const io = require("./io.cjs");
94
- const { ERROR_REASON } = io;
95
- // ─── Guard identity (PROMOTE_GUARD) ─────────────────────────────────────────────
96
- // 29-02/29-03 reuse CONCURRENT_EDIT and TRANSPORT — declare all seven now so
97
- // the enum is not edited twice.
98
- const PROMOTE_GUARD = Object.freeze({
99
- ACTIVATION: 'activation',
100
- INPUT: 'input',
101
- VALIDATION: 'validation',
102
- SECRET_SCAN: 'secret_scan',
103
- WRITE_TARGET: 'write_target',
104
- CONCURRENT_EDIT: 'concurrent_edit',
105
- TRANSPORT: 'transport',
106
- });
107
- // ─── Secret-content scanner (WRB-03 / D-13 / D-14) ──────────────────────────────
108
- //
109
- // Transliterated from scripts/secret-scan.sh's SECRET_PATTERNS (18 labeled
110
- // POSIX ERE patterns) into JavaScript RegExp, preserving every human label
111
- // verbatim, plus one ADDED shape the CI scanner is missing: a GitLab access
112
- // token keyed on the `glpat-` prefix (confirmed absent from
113
- // scripts/secret-scan.sh but already referenced in ad-hoc greps at
114
- // pp-core/workflows/docs-update.md and pp-core/workflows/map-codebase.md).
115
- //
116
- // Order is declaration order and is load-bearing: the Anthropic shape is
117
- // placed before the OpenAI shape so a key of the form `sk-ant-<alnum>` is
118
- // never reported under the OpenAI label (the OpenAI pattern's `[A-Za-z0-9]`
119
- // class alone would also match the alnum-only tail of an Anthropic key).
120
- //
121
- // Deliberately NOT ported: the `.secretscanignore` mechanism, an exclusion
122
- // parameter, a placeholder carve-out, or an entropy heuristic — D-14's
123
- // no-override rule is deliberate, and the generic assignment shapes' false-
124
- // positive exposure is an accepted residual (T-29-02b).
125
- const SECRET_SHAPES = Object.freeze([
126
- { label: 'AWS Access Key', re: /AKIA[0-9A-Z]{16}/ },
127
- { label: 'AWS Secret Key', re: /aws_secret_access_key\s*=\s*[A-Za-z0-9/+=]{40}/ },
128
- { label: 'Anthropic API Key', re: /sk-ant-[A-Za-z0-9_-]{20,}/ },
129
- { label: 'OpenAI API Key', re: /sk-[A-Za-z0-9]{20,}/ },
130
- { label: 'GitHub PAT', re: /ghp_[A-Za-z0-9]{36}/ },
131
- { label: 'GitHub OAuth', re: /gho_[A-Za-z0-9]{36}/ },
132
- { label: 'GitHub App Token', re: /ghs_[A-Za-z0-9]{36}/ },
133
- { label: 'GitHub Fine-grained PAT', re: /github_pat_[A-Za-z0-9_]{20,}/ },
134
- { label: 'GitLab access token', re: /glpat-[A-Za-z0-9_-]{20,}/ },
135
- { label: 'Stripe Secret Key', re: /sk_live_[A-Za-z0-9]{24,}/ },
136
- { label: 'Stripe Publishable Key', re: /pk_live_[A-Za-z0-9]{24,}/ },
137
- { label: 'Private Key Header', re: /-----BEGIN\s+(RSA|EC|DSA|OPENSSH)?\s*PRIVATE\s+KEY-----/ },
138
- { label: 'Slack Bot Token', re: /xoxb-[0-9]{10,}-[A-Za-z0-9]{20,}/ },
139
- {
140
- label: 'Slack Webhook',
141
- re: /hooks\.slack\.com\/services\/T[A-Z0-9]{8,}\/B[A-Z0-9]{8,}\/[A-Za-z0-9]{24}/,
142
- },
143
- { label: 'Google API Key', re: /AIza[A-Za-z0-9_-]{35}/ },
144
- { label: 'NPM Token', re: /npm_[A-Za-z0-9]{36}/ },
145
- {
146
- label: 'Env Variable Leak',
147
- re: /(DATABASE_URL|DB_PASSWORD|REDIS_URL|MONGO_URI|JWT_SECRET|SESSION_SECRET|ENCRYPTION_KEY)\s*=\s*[^\s]{8,}/,
148
- },
149
- { label: 'Generic API Key Assignment', re: /api[_-]?key\s*[:=]\s*['"][A-Za-z0-9_-]{20,}['"]/i },
150
- { label: 'Generic Secret Assignment', re: /secret\s*[:=]\s*['"][A-Za-z0-9_-]{20,}['"]/i },
151
- { label: 'Generic Token Assignment', re: /token\s*[:=]\s*['"][A-Za-z0-9_-]{20,}['"]/i },
152
- { label: 'Generic Password Assignment', re: /password\s*[:=]\s*['"][^'"]{8,}['"]/i },
153
- ]);
154
- /**
155
- * Scan `content` line by line, walking SECRET_SHAPES in declaration order
156
- * for each line, and return the FIRST match as `{ label, line }` (1-based).
157
- * Returns null on clean content. Never places the matched substring, a
158
- * slice of it, or a match index into the return value — name and line only
159
- * (T-29-01).
160
- */
161
- function scanForSecrets(content) {
162
- const lines = content.split(/\r?\n/);
163
- for (let i = 0; i < lines.length; i++) {
164
- const line = lines[i];
165
- for (const shape of SECRET_SHAPES) {
166
- if (shape.re.test(line)) {
167
- return { label: shape.label, line: i + 1 };
168
- }
169
- }
170
- }
171
- return null;
172
- }
173
- // ─── Refusal contract (D-16) ─────────────────────────────────────────────────────
174
- /**
175
- * Build a uniform refusal verdict. `message` is collapsed to a single line
176
- * (any CR/LF run becomes a space) so a client-authored fragment carried
177
- * into `extra` or the cause clause can never inject a fake second line into
178
- * operator output.
179
- */
180
- function refusal(guard, reason, message, extra = {}) {
181
- return {
182
- status: 'refused',
183
- guard,
184
- reason,
185
- message: message.replace(/[\r\n]+/g, ' '),
186
- ...extra,
187
- };
188
- }
189
- /** Bound an untrusted value before it is echoed into a refusal message. */
190
- function boundedToken(v, max = 80) {
191
- let s;
192
- try {
193
- s = typeof v === 'string' ? v : JSON.stringify(v);
194
- }
195
- catch {
196
- s = String(v);
197
- }
198
- s = s.replace(/[\r\n]+/g, ' ');
199
- return s.length > max ? `${s.slice(0, max)}…` : s;
200
- }
201
- // ─── Preflight guard chain ───────────────────────────────────────────────────────
202
- /**
203
- * Run the promote preflight guard chain: activation, input, format
204
- * validation (D-03), secret scan (D-13/D-14), target resolution, and the
205
- * write-target guard (D-05) — strictly in that order, refusing at the
206
- * first failing stage and never continuing past it. Makes no network
207
- * access and spawns no subprocess.
208
- */
209
- function promotePreflight({ cwd, filePath, _vault, _practices }) {
210
- // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-unsafe-assignment
211
- const vault = _vault ?? require('./vault.cjs');
212
- // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-unsafe-assignment
213
- const practices = _practices ?? require('./vault-practices.cjs');
214
- // 1. Activation — both vault.enabled and vault.practices_enabled must be
215
- // strictly true. Runs before any filesystem access; rides the two
216
- // existing default-false config keys (no new config key, no capability
217
- // surface widening).
218
- const enabled = vault.cfgGet(cwd, 'vault.enabled', false);
219
- const practicesEnabled = vault.cfgGet(cwd, 'vault.practices_enabled', false);
220
- if (enabled !== true || practicesEnabled !== true) {
221
- return refusal(PROMOTE_GUARD.ACTIVATION, ERROR_REASON.VAULT_PROMOTE_DISABLED, 'This practice was not promoted: vault write-back is switched off for this project. ' +
222
- 'Set both vault.enabled and vault.practices_enabled to true in .planning/config.json and run the promotion again.');
223
- }
224
- // 2. Input — a path to an already-authored practice file (D-02); this
225
- // module never composes, rewrites, reformats, or extracts a practice.
226
- if (typeof filePath !== 'string' ||
227
- filePath.length === 0 ||
228
- !filePath.endsWith('.md') ||
229
- !node_fs_1.default.existsSync(filePath) ||
230
- !node_fs_1.default.statSync(filePath).isFile()) {
231
- return refusal(PROMOTE_GUARD.INPUT, ERROR_REASON.SDK_MISSING_ARG, `This practice was not promoted: ${boundedToken(filePath)} is not an existing practice file. ` +
232
- 'Point at an existing .md practice file and run the promotion again.');
233
- }
234
- // Read the FULL file content — not the bounded prefix discovery uses —
235
- // because both the validation oracle and the secret scan must see the
236
- // whole file.
237
- const raw = node_fs_1.default.readFileSync(filePath, 'utf-8');
238
- // 3. Validation — the Phase 24 parser is the only format validator in
239
- // this write path (D-03). No second validator, no new format rule.
240
- const parsed = practices.parsePracticeFile(node_path_1.default.basename(filePath), raw);
241
- if (!parsed.ok) {
242
- const cause = parsed.warning.replace(/^.*?\s+skipped:\s*/, '');
243
- return refusal(PROMOTE_GUARD.VALIDATION, ERROR_REASON.VAULT_PROMOTE_INVALID_PRACTICE, `This practice was not promoted: ${cause} Fix the practice file and run the promotion again.`);
244
- }
245
- // 3b. Degraded-parse refusal. Write-side strictness is deliberate: the read
246
- // side keeps a practice it does not fully understand, because it already
247
- // governs work and dropping it would silently un-govern that work; promoting
248
- // it would push the defect into the shared vault every machine fetches. Both
249
- // consumers of DOCUMENTED_FRONTMATTER_KEYS move in the one change that
250
- // widened it — had only the reader moved, an unknown key would have quietly
251
- // become promotable.
252
- if (parsed.degradedWarnings !== undefined && parsed.degradedWarnings.length > 0) {
253
- const cause = parsed.degradedWarnings[0].replace(/^.*?\s+degraded:\s*/, '');
254
- return refusal(PROMOTE_GUARD.VALIDATION, ERROR_REASON.VAULT_PROMOTE_INVALID_PRACTICE, `This practice was not promoted: ${cause} Fix the practice file and run the promotion again.`);
255
- }
256
- // 3c. Invalid-check-block refusal. The reader reports this defect on its own
257
- // channel (`practice.checkInvalid`), which is neither `!parsed.ok` nor
258
- // `degradedWarnings` — discovery folds it into `degraded[]`, but this path
259
- // never calls discovery — so both rungs above miss it.
260
- if (typeof parsed.practice.checkInvalid === 'string' && parsed.practice.checkInvalid.length > 0) {
261
- return refusal(PROMOTE_GUARD.VALIDATION, ERROR_REASON.VAULT_PROMOTE_INVALID_PRACTICE, `This practice was not promoted: ${parsed.practice.checkInvalid} ` +
262
- 'Fix the practice file and run the promotion again.');
263
- }
264
- // 4. Secret scan — a hit refuses hard, no override (D-14). The matched
265
- // text is never carried, quoted, echoed, logged, or truncated into the
266
- // refusal — a truncated secret is still a partial disclosure.
267
- const hit = scanForSecrets(raw);
268
- if (hit) {
269
- return refusal(PROMOTE_GUARD.SECRET_SCAN, ERROR_REASON.VAULT_PROMOTE_SECRET_DETECTED, `This practice was not pushed: line ${hit.line} looks like ${hit.label}. Remove it and run the promotion again.`, { label: hit.label, line: hit.line });
270
- }
271
- // 5. Target resolution — client.vaultRepo / client.vaultRef / host.
272
- // Deliberately does NOT call resolveBaseBranch (src/git-base-branch.cts)
273
- // — that resolver answers a question about this project's OWN
274
- // repository, a different repository from the client vault.
275
- const bindings = vault.readBindings(cwd);
276
- const client = bindings && typeof bindings.client === 'object' && bindings.client !== null
277
- ? bindings.client
278
- : null;
279
- const targetRepo = client && typeof client.vaultRepo === 'string' ? client.vaultRepo : null;
280
- if (!targetRepo) {
281
- return refusal(PROMOTE_GUARD.WRITE_TARGET, ERROR_REASON.VAULT_PROMOTE_TARGET_REFUSED, 'This practice was not promoted: no client vault repository is configured. ' +
282
- 'Check client.vaultRepo in .platform-bindings.json and run the promotion again.');
283
- }
284
- // T-29-26: a repo or ref that git would read as an option is refused here,
285
- // before any transport exists, rather than being handed to git and surfacing
286
- // as a confusing "repository does not exist". Fails closed.
287
- const flagShaped = [
288
- ['client.vaultRepo', targetRepo],
289
- ['client.vaultRef', client && typeof client.vaultRef === 'string' ? client.vaultRef : ''],
290
- ].find(([, v]) => typeof v === 'string' && v.trim().startsWith('-'));
291
- if (flagShaped) {
292
- return refusal(PROMOTE_GUARD.WRITE_TARGET, ERROR_REASON.VAULT_PROMOTE_TARGET_REFUSED, `This practice was not promoted: ${flagShaped[0]} starts with "-", which git would read as an option rather than a location. ` +
293
- 'Fix it in .platform-bindings.json and run the promotion again.');
294
- }
295
- const targetRef = client && typeof client.vaultRef === 'string' && client.vaultRef.trim() ? client.vaultRef.trim() : 'main';
296
- // Resolve the provider ONCE, here in the preflight (PROV-02/T-30-16) — both
297
- // previewPromotion and confirmPromotion re-run this preflight and read the
298
- // same `provider` field back off the result, so they cannot compose two
299
- // different remotes for the same promotion. Moved ahead of target-host
300
- // resolution (Phase 31, D-10): the host now comes from the coordinate
301
- // resolver below, which itself takes the provider as an argument.
302
- const providerResolution = (0, git_provider_cjs_1.resolveProvider)(cwd);
303
- const provider = providerResolution.provider;
304
- const providerWarnings = providerResolution.warnings.slice();
305
- // Target host — from the coordinate resolver (Phase 31, D-10), not a
306
- // config-only host chain. `client.vaultHost` wins when set; otherwise
307
- // `.platform-bindings.json`'s `platform.host` (D-09), warned; otherwise
308
- // the provider's default host. The `.planning/config.json`-only
309
- // `platform.host` read this preflight used to fall back to last is gone
310
- // — leaving it in place beside the resolver would not fix D-09, it would
311
- // add a third disagreeing source of the same value.
312
- const clientCoord = (0, vault_coordinates_cjs_1.resolveClientCoordinates)(cwd, provider);
313
- const targetHost = clientCoord.host;
314
- if (clientCoord.warnings.length > 0)
315
- providerWarnings.push(...clientCoord.warnings);
316
- // Shared-tier coordinates — resolved ONCE here in the preflight (D-09,
317
- // T-31-09), carried forward on the success shape below rather than
318
- // resolved a second time by `previewPromotion`. This is the same
319
- // construction already used for `provider` and for `clientCoord` above:
320
- // both `previewPromotion` and `confirmPromotion` re-run this preflight and
321
- // read fields back off its result, so a promotion cannot end up resolving
322
- // two disagreeing answers for its own shared-shadow lookup.
323
- //
324
- // `applyBuiltInDefault: false` is load-bearing, not a stylistic default.
325
- // This path has never applied the built-in shared-vault default — it used
326
- // to read `vault.fallback_repo` with an empty-string fallback, so a
327
- // project that never set the key performed no shared-shadow clone at all.
328
- // Passing `true` here would give every existing gitlab install a shared
329
- // clone it does not perform today, breaking ROADMAP SC3. The read-path
330
- // ladder and `assertVaultWriteTarget` both pass `true` because both of
331
- // them already apply the built-in default today (they always have) — this
332
- // is the one caller that deliberately withholds it.
333
- const sharedCoord = (0, vault_coordinates_cjs_1.resolveSharedCoordinates)(cwd, provider, { applyBuiltInDefault: false });
334
- if (sharedCoord.warnings.length > 0)
335
- providerWarnings.push(...sharedCoord.warnings);
336
- // D-13/WR-01: read the resolver's OWN verdict straight off `sharedCoord`
337
- // — no local re-derivation. Before this fix, `sharedCoord.suppressed` was
338
- // unconditionally `false` on this call regardless of provider, because
339
- // withholding the built-in default (`applyBuiltInDefault: false`, above)
340
- // also disabled the resolver's suppression branch. The resolver now
341
- // reports `suppressed`/`suppressedKind` correctly even with the built-in
342
- // default withheld, so this module no longer needs to (and must not)
343
- // approximate the fact from `sharedRepo`/`provider` itself — that
344
- // approximation was exactly the WR-01 defect (PROJECT.md: an operator who
345
- // deliberately disabled the shared tier via an empty `vault.fallback_repo`
346
- // was shown a note asking them to set the very key they already set,
347
- // because this module could not tell that apart from "never configured").
348
- const sharedSuppressed = sharedCoord.suppressed;
349
- const sharedSuppressedKind = sharedCoord.suppressedKind;
350
- // Any warning composing the primary clone target for THIS
351
- // provider/repo/host (an operator-supplied `.git` suffix under azure) is
352
- // folded in here too, alongside the provider and coordinate warnings
353
- // already collected above, so a single `notes` push in the preview
354
- // surfaces all of them.
355
- if (!(0, git_provider_cjs_1.isLiteralCloneTarget)(targetRepo.trim())) {
356
- const composedForWarnings = (0, git_provider_cjs_1.composeCloneTarget)(provider, targetRepo, targetHost);
357
- if (composedForWarnings.warnings.length > 0)
358
- providerWarnings.push(...composedForWarnings.warnings);
359
- }
360
- // 6. Write-target guard (D-05, D-10) — this arm delegates to
361
- // assertVaultWriteTarget and never re-derives, wraps, relaxes, or
362
- // reimplements any of its three refusals; it passes the resolved target
363
- // repo and target host straight through.
364
- try {
365
- vault.assertVaultWriteTarget(cwd, targetRepo, targetHost);
366
- }
367
- catch (e) {
368
- const msg = (e instanceof Error ? e.message : String(e)).replace(/^vault write refused:\s*/, '');
369
- return refusal(PROMOTE_GUARD.WRITE_TARGET, ERROR_REASON.VAULT_PROMOTE_TARGET_REFUSED, `This practice was not promoted: ${msg} Check client.vaultRepo in .platform-bindings.json and run the promotion again.`);
370
- }
371
- // Destination is derived from the stable frontmatter id — never the
372
- // local filename, never an operator-supplied value (D-04).
373
- const destination = node_path_1.default.posix.join('practices', `${parsed.practice.id}.md`);
374
- return {
375
- status: 'ok',
376
- practice: parsed.practice,
377
- raw,
378
- repo: targetRepo,
379
- ref: targetRef,
380
- host: targetHost,
381
- destination,
382
- provider,
383
- providerWarnings,
384
- sharedRepo: sharedCoord.repo,
385
- sharedRef: sharedCoord.ref,
386
- sharedHost: sharedCoord.host,
387
- sharedSuppressed,
388
- sharedSuppressedKind,
389
- };
390
- }
391
- // ─── Preview (read-only half of the write path) ─────────────────────────────────
392
- /**
393
- * Build the opaque `expect` token that pins BOTH what the operator confirmed
394
- * locally and what the vault held at that moment, without any state file
395
- * across two separate process invocations: the hex sha256 of the local raw
396
- * content, a period, then either the hex sha256 of the remote baseline or
397
- * the literal `absent` when the destination file does not (yet) exist in
398
- * the vault. Callers must treat the result as opaque.
399
- */
400
- function buildExpectToken(localRaw, remoteBaseline) {
401
- const localHash = node_crypto_1.default.createHash('sha256').update(localRaw).digest('hex');
402
- const remoteHash = remoteBaseline === null ? 'absent' : node_crypto_1.default.createHash('sha256').update(remoteBaseline).digest('hex');
403
- return `${localHash}.${remoteHash}`;
404
- }
405
- /**
406
- * Preview a promotion: clone the client vault into a disposable temp
407
- * directory, capture the destination's current content as a pinned
408
- * baseline, stage the promoted content, and ask git for a diff (update) or
409
- * hand back the full content (create). Runs the full 29-01 preflight guard
410
- * chain first and returns its refusal unchanged, with no clone attempted,
411
- * on any refusal. Never creates a commit, never moves a remote ref, and
412
- * never reads or writes the project's own vault read cache (a fresh
413
- * mkdtemp working copy is used and always removed, even on a thrown error).
414
- */
415
- // `isLiteralCloneTarget` and clone-target composition — the single
416
- // definitions live in `src/git-provider.cts` (imported above) and are shared
417
- // with the read path (`src/vault.cts`, 30-02). Do NOT reintroduce a local
418
- // copy of either here: a read/write divergence in this predicate was defect
419
- // P-1 in Phase 29 (the write path used `client.vaultRepo` verbatim while the
420
- // read path always composed a URL, so a slug broke writing and a path broke
421
- // reading) — duplicating the fix a second time is exactly how that class of
422
- // bug recurs.
423
- function previewPromotion({ cwd, filePath, _exec, _vault, _practices }) {
424
- const gitExec = _exec ?? shell_command_projection_cjs_1.execGit;
425
- // 1. Run the full preflight guard chain; refuse unchanged with no clone.
426
- const pre = promotePreflight({ cwd, filePath, _vault, _practices });
427
- if (pre.status !== 'ok')
428
- return pre;
429
- // No local `./vault.cjs` handle is needed here any more (Phase 31,
430
- // Task 1): the shared-shadow lookup below reads its coordinates off `pre`
431
- // instead of calling `vault.cfgGet` directly, so this function no longer
432
- // touches the vault module at all — `_vault` is still threaded through to
433
- // `promotePreflight` above for the test-seam injection convention.
434
- const notes = [];
435
- // Surface any warning resolving the provider or composing the primary
436
- // clone target produced (an unrecognized `vault.provider` value, or an
437
- // operator-supplied `.git` suffix under azure) — visible in the preview an
438
- // operator reads before confirming, never a silent degrade.
439
- notes.push(...pre.providerWarnings);
440
- // The disposable working copy is a fresh mkdtemp directory — never the
441
- // read cache, which is often a shallow/sparse clone from a different tier
442
- // and is refreshed independently after a push. Removed on every exit path.
443
- let cloneDir = null;
444
- try {
445
- cloneDir = node_fs_1.default.mkdtempSync(node_path_1.default.join(node_os_1.default.tmpdir(), 'pp-vault-promote-'));
446
- // 2. Clone the resolved client repo at the resolved ref — a full
447
- // single-branch clone (no shallow-depth flag: the confirmed path needs
448
- // real history to fast-forward against). The target goes through the
449
- // provider seam's composeCloneTarget so a `group/project` slug becomes a
450
- // real URL on the resolved host and provider, instead of a relative path
451
- // git cannot find.
452
- const cl = gitExec([
453
- 'clone',
454
- '--branch',
455
- pre.ref,
456
- '--single-branch',
457
- '--',
458
- (0, git_provider_cjs_1.composeCloneTarget)(pre.provider, pre.repo, pre.host).url,
459
- cloneDir,
460
- ], { timeout: 120_000 });
461
- if (cl.exitCode !== 0) {
462
- const cause = shownCause(cl.stderr);
463
- return refusal(PROMOTE_GUARD.TRANSPORT, ERROR_REASON.VAULT_PROMOTE_TRANSPORT_FAILED, `This practice was not pushed: git could not reach the vault (${cause}). Check your access to the vault and run the promotion again.`);
464
- }
465
- // 3. Capture the baseline BEFORE writing — an id already present in the
466
- // client vault is an update, not a refusal and not an opt-in flag
467
- // (D-06). The baseline captured here is what 29-03's concurrent-edit
468
- // check pins against.
469
- const destAbs = node_path_1.default.join(cloneDir, pre.destination);
470
- const baselineExists = node_fs_1.default.existsSync(destAbs);
471
- const baseline = baselineExists ? node_fs_1.default.readFileSync(destAbs, 'utf-8') : null;
472
- const mode = baselineExists ? 'update' : 'create';
473
- // 4. Write the raw content unchanged — no reformatting, no
474
- // re-serialization, no line-ending normalization.
475
- node_fs_1.default.mkdirSync(node_path_1.default.dirname(destAbs), { recursive: true });
476
- node_fs_1.default.writeFileSync(destAbs, pre.raw, 'utf-8');
477
- // 5. Ask git for the preview rather than computing one. `core.quotepath=off`
478
- // so a non-ASCII destination path is not escaped in operator-read output.
479
- let diff;
480
- let content;
481
- if (mode === 'update') {
482
- const diffRes = gitExec(['-c', 'core.quotepath=off', 'diff', '--', pre.destination], { cwd: cloneDir });
483
- diff = diffRes.stdout;
484
- }
485
- else {
486
- content = pre.raw;
487
- }
488
- // 6. Shared-shadow lookup — the shared coordinates are resolved exactly
489
- // ONCE, in the preflight above, with the built-in default explicitly
490
- // withheld (D-09, T-31-09); this function reads them back off `pre`
491
- // rather than resolving them a second time. Skipped entirely (flag stays
492
- // false) when no shared repo resolved, or it equals the client repo —
493
- // the same skip shape as before, now expressed against the resolved
494
- // field: a `null` `pre.sharedRepo` is treated the way the empty string
495
- // used to be treated.
496
- //
497
- // The shared vault is addressed on the resolved shared host, in D-03's
498
- // order: `vault.fallback_host` first, then the authoritative
499
- // `platform.host` (`.platform-bindings.json` first, `.planning/config.json`
500
- // as a warned fallback per D-09), then the provider-derived default —
501
- // never the client's own `client.vaultHost`, mirroring the fallback tier
502
- // in `src/vault.cts`'s `cloneTier` so a client with a custom vaultHost
503
- // never sends the shared-shadow lookup to their own host. Composed under
504
- // the SAME resolved provider as the client clone (deliberate and
505
- // symmetric with `cloneTier`'s one-provider-per-fetch rule).
506
- //
507
- // Per-tier provider selection does NOT arrive with this phase's CFG-01:
508
- // D-01 answered that with a deliberate, permanent no. One provider per
509
- // project stands — a client does not straddle two providers — and the
510
- // fix for the azure-composing-a-gitlab-URL hazard is that the shared
511
- // coordinates became per-client config, which is exactly what resolving
512
- // them once in the preflight, above, does.
513
- let sharedShadow = false;
514
- let sharedShadowNote = null;
515
- const sharedRepo = pre.sharedRepo;
516
- const sharedRef = pre.sharedRef;
517
- const sharedHost = pre.sharedHost;
518
- if (sharedRepo && sharedRepo !== pre.repo) {
519
- let sharedDir = null;
520
- try {
521
- sharedDir = node_fs_1.default.mkdtempSync(node_path_1.default.join(node_os_1.default.tmpdir(), 'pp-vault-shared-'));
522
- // Shallow single-branch: only file presence matters, no history needed.
523
- const sc = gitExec([
524
- 'clone',
525
- '--depth',
526
- '1',
527
- '--branch',
528
- sharedRef,
529
- '--single-branch',
530
- '--',
531
- (0, git_provider_cjs_1.composeCloneTarget)(pre.provider, sharedRepo, sharedHost).url,
532
- sharedDir,
533
- ], { timeout: 120_000 });
534
- if (sc.exitCode === 0) {
535
- if (node_fs_1.default.existsSync(node_path_1.default.join(sharedDir, pre.destination))) {
536
- sharedShadow = true;
537
- sharedShadowNote =
538
- "This practice id already exists in the shared Pareto vault. After this promotion the client's version is the one that applies for this client.";
539
- }
540
- }
541
- else {
542
- // An unreachable/failed shared vault must never block, fail, or
543
- // slow-fail a preview — leave the flag false and note it.
544
- notes.push('the shared vault could not be checked');
545
- }
546
- }
547
- catch {
548
- notes.push('the shared vault could not be checked');
549
- }
550
- finally {
551
- if (sharedDir)
552
- node_fs_1.default.rmSync(sharedDir, { recursive: true, force: true });
553
- }
554
- }
555
- // Suppression note (D-02, D-11, D-13/WR-01) — pushed ONLY when the
556
- // shared resolution reports suppression AND the kind is
557
- // 'provider-default-unavailable'. A gitlab project with no
558
- // `vault.fallback_repo` resolves `sharedSuppressed: false` (nothing was
559
- // suppressed — no built-in default was withheld from a provider that
560
- // would otherwise have gotten one) and emits nothing here, exactly as it
561
- // did before this phase — this note is SC3-safe by construction.
562
- //
563
- // D-13/WR-01: an operator who set `vault.fallback_repo` to an empty
564
- // string deliberately disabled the shared tier — `sharedSuppressedKind`
565
- // is `'explicit-opt-out'` for that case, and telling them to set the key
566
- // they already set is exactly the defect this closes. NO second note is
567
- // added for the opt-out case: silence is the correct output for a
568
- // choice the operator already made, and inventing a new note would be
569
- // new behaviour rather than a fix. D-11's requirement to surface the
570
- // skipped shared check is already met by the write guard's own refusal
571
- // sentence (plan 03); this note additionally explains why, in the
572
- // read-only preview an operator reads before confirming.
573
- if (pre.sharedSuppressed && pre.sharedSuppressedKind === 'provider-default-unavailable') {
574
- notes.push(`No shared vault is configured for the ${pre.provider} provider — the built-in Pareto shared default applies only to the gitlab provider. Set vault.fallback_repo to enable the shared tier.`);
575
- }
576
- // 7 & 8. Pin both sides in the opaque expect token, then return.
577
- const expect = buildExpectToken(pre.raw, baseline);
578
- return {
579
- status: 'preview',
580
- repo: shownRepo(pre.repo),
581
- ref: pre.ref,
582
- destination: pre.destination,
583
- mode,
584
- id: boundedToken(pre.practice.id),
585
- diff,
586
- content,
587
- sharedShadow,
588
- sharedShadowNote,
589
- expect,
590
- notes,
591
- };
592
- }
593
- finally {
594
- if (cloneDir)
595
- node_fs_1.default.rmSync(cloneDir, { recursive: true, force: true });
596
- }
597
- }
598
- // ─── Confirm (write half of the write path) ──────────────────────────────────────
599
- /**
600
- * Pack 6 D-07: the display-safe forms used in every verdict and refusal this
601
- * module EMITS — the one owner in src/vault.cts, lazily required (the
602
- * module's `_vault` seam stays the fetch seam; redaction is never mocked).
603
- * Comparisons, the expect token and every git invocation keep the RAW values.
604
- */
605
- function shownRepo(repo) {
606
- // eslint-disable-next-line @typescript-eslint/no-require-imports
607
- const v = require('./vault.cjs');
608
- return v.redactCloneTarget(repo) ?? repo;
609
- }
610
- function shownCause(stderr) {
611
- // eslint-disable-next-line @typescript-eslint/no-require-imports
612
- const v = require('./vault.cjs');
613
- return boundedToken(v.redactRemoteText((stderr || '').split(/\r?\n/)[0] || 'unknown error'));
614
- }
615
- /** Build a TRANSPORT refusal from a failed git invocation's stderr (first line only). */
616
- function transportRefusal(res) {
617
- const cause = shownCause(res.stderr);
618
- return refusal(PROMOTE_GUARD.TRANSPORT, ERROR_REASON.VAULT_PROMOTE_TRANSPORT_FAILED, `This practice was not pushed: git could not reach the vault (${cause}). Check your access to the vault and run the promotion again.`);
619
- }
620
- /**
621
- * Confirm a promotion: re-run the full 29-01 preflight chain (never trust
622
- * the preview), re-verify the opaque `expect` token against a freshly read
623
- * local file AND a freshly cloned remote baseline, absorb unrelated remote
624
- * movement with a fast-forward-only pull, then stage/commit/push exactly
625
- * the destination path with no force flag on any code path. On success,
626
- * refreshes the local read cache via `./vault.cjs`'s `vaultFetch` verbatim.
627
- *
628
- * Deliberate deviation from a literal `git show`-based remote-baseline read
629
- * (Rule 1 bug avoidance): `execGit`'s shared `_spawnResult` unconditionally
630
- * `.trim()`s captured stdout, which would silently strip a file's trailing
631
- * newline and make every legitimate hash comparison spuriously mismatch.
632
- * Instead this re-derives the remote baseline from the filesystem AFTER the
633
- * fast-forward-only pull (the same fs-read technique `previewPromotion`
634
- * already uses for its own baseline capture) — byte-exact, and the pull
635
- * step the plan already requires does the "sync to the fetched ref" work
636
- * for free, so no separate `git show`/`cat-file` call is needed.
637
- */
638
- function confirmPromotion({ cwd, filePath, expect, _exec, _vault, _practices }) {
639
- const gitExec = _exec ?? shell_command_projection_cjs_1.execGit;
640
- // 1. Full preflight re-run — never trust the preview. Re-derives repo,
641
- // ref, host, and destination from scratch; never accepts a caller-
642
- // supplied id/destination/repo/ref.
643
- const pre = promotePreflight({ cwd, filePath, _vault, _practices });
644
- if (pre.status !== 'ok')
645
- return pre;
646
- // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-unsafe-assignment
647
- const vault = _vault ?? require('./vault.cjs');
648
- // 2. Missing/empty token → refuse before any clone.
649
- if (!expect || typeof expect !== 'string' || expect.length === 0) {
650
- return refusal(PROMOTE_GUARD.CONCURRENT_EDIT, ERROR_REASON.VAULT_PROMOTE_CONCURRENT_EDIT, 'This practice was not pushed: the confirmation is missing the preview token it needs. ' +
651
- 'Run the promotion without confirming first, then pass the token it prints.');
652
- }
653
- // 3. Split the token; a malformed token (no separator) naturally fails the
654
- // local-hash comparison below rather than needing a distinct code path.
655
- const sepIdx = expect.indexOf('.');
656
- const pinnedLocal = sepIdx === -1 ? expect : expect.slice(0, sepIdx);
657
- const pinnedRemote = sepIdx === -1 ? '' : expect.slice(sepIdx + 1);
658
- // 4. Recompute the local hash from the FRESHLY read content (pre.raw came
659
- // from this invocation's own promotePreflight, not the preview's). A
660
- // mismatch means the local file changed since the operator previewed it —
661
- // this is what makes D-10's byte-identity claim hold across two separate
662
- // process invocations (T-29-13).
663
- const localHash = node_crypto_1.default.createHash('sha256').update(pre.raw).digest('hex');
664
- if (localHash !== pinnedLocal) {
665
- return refusal(PROMOTE_GUARD.CONCURRENT_EDIT, ERROR_REASON.VAULT_PROMOTE_CONCURRENT_EDIT, 'This practice was not pushed: the file on your machine changed after you previewed it. ' +
666
- 'Run the promotion again to preview the new version.');
667
- }
668
- // 5. Clone into a fresh disposable mkdtemp directory — exactly as the
669
- // preview does, but NEVER the preview's own clone directory and NEVER the
670
- // read cache.
671
- let cloneDir = null;
672
- try {
673
- cloneDir = node_fs_1.default.mkdtempSync(node_path_1.default.join(node_os_1.default.tmpdir(), 'pp-vault-confirm-'));
674
- const cl = gitExec([
675
- 'clone',
676
- '--branch',
677
- pre.ref,
678
- '--single-branch',
679
- '--',
680
- (0, git_provider_cjs_1.composeCloneTarget)(pre.provider, pre.repo, pre.host).url,
681
- cloneDir,
682
- ], { timeout: 120_000 });
683
- if (cl.exitCode !== 0)
684
- return transportRefusal(cl);
685
- // 6. Fetch the resolved ref from origin, then absorb any unrelated
686
- // remote movement with a fast-forward-only pull. The file-scoped
687
- // baseline check below runs AFTER this on purpose: a target-file race
688
- // is still caught by the hash comparison, and a race that instead
689
- // defeats the transport layer (an unrelated push landing between this
690
- // pull and this module's own push, below) fails closed on the push
691
- // itself — the intended structural backstop (T-29-04), never retried.
692
- const ft = gitExec(['fetch', 'origin', pre.ref], { cwd: cloneDir, timeout: 120_000 });
693
- if (ft.exitCode !== 0)
694
- return transportRefusal(ft);
695
- const pull = gitExec(['pull', '--ff-only', 'origin', pre.ref], { cwd: cloneDir, timeout: 120_000 });
696
- if (pull.exitCode !== 0)
697
- return transportRefusal(pull);
698
- // 7. Re-derive the remote baseline from the now fast-forwarded working
699
- // tree (fs-level read, byte-exact — never git-stdout-derived, which is
700
- // silently trimmed by the shared exec helper). Scoped to the
701
- // destination file only (D-15): commit/tree shas are never compared,
702
- // so an unrelated promotion never blocks this one.
703
- const destAbs = node_path_1.default.join(cloneDir, pre.destination);
704
- const remoteExists = node_fs_1.default.existsSync(destAbs);
705
- const remoteContent = remoteExists ? node_fs_1.default.readFileSync(destAbs, 'utf-8') : null;
706
- const remoteHash = remoteContent === null ? 'absent' : node_crypto_1.default.createHash('sha256').update(remoteContent).digest('hex');
707
- if (remoteHash !== pinnedRemote) {
708
- return refusal(PROMOTE_GUARD.CONCURRENT_EDIT, ERROR_REASON.VAULT_PROMOTE_CONCURRENT_EDIT, `This practice was not pushed: someone else changed ${boundedToken(pre.destination)} in the vault since you previewed it. ` +
709
- 'Run the promotion again to see their version before you push.');
710
- }
711
- const mode = remoteExists ? 'update' : 'create';
712
- // 8. Write the promoted content, then stage exactly that one path.
713
- node_fs_1.default.mkdirSync(node_path_1.default.dirname(destAbs), { recursive: true });
714
- node_fs_1.default.writeFileSync(destAbs, pre.raw, 'utf-8');
715
- const add = gitExec(['add', '--', pre.destination], { cwd: cloneDir });
716
- if (add.exitCode !== 0)
717
- return transportRefusal(add);
718
- // 9. Configure identity only if git reports none — preserve an
719
- // operator's own configured identity when present.
720
- const idCheck = gitExec(['config', 'user.email'], { cwd: cloneDir });
721
- if (idCheck.exitCode !== 0 || !idCheck.stdout.trim()) {
722
- gitExec(['config', 'user.email', 'pp-core-vault-promote@pareto.local'], { cwd: cloneDir });
723
- gitExec(['config', 'user.name', 'pp-core vault promote'], { cwd: cloneDir });
724
- }
725
- // 10. Commit once.
726
- const id = pre.practice.id;
727
- const commitMessage = `practice(${mode}): ${boundedToken(id)}\n\nPromoted from this project via pp-core's vault write-back arm.`;
728
- const commitRes = gitExec(['commit', '-m', commitMessage], { cwd: cloneDir });
729
- if (commitRes.exitCode !== 0)
730
- return transportRefusal(commitRes);
731
- // 11. Push once — origin, local HEAD mapped to the resolved ref. No
732
- // force flag, no lease flag, no short-form alias, not on this call, not
733
- // on a retry. A non-fast-forward rejection is the intended structural
734
- // backstop for a race that defeats the file-scoped check above; never
735
- // re-run, never looped, never escalated.
736
- const push = gitExec(['push', 'origin', `HEAD:${pre.ref}`], { cwd: cloneDir, timeout: 120_000 });
737
- if (push.exitCode !== 0) {
738
- return refusal(PROMOTE_GUARD.TRANSPORT, ERROR_REASON.VAULT_PROMOTE_TRANSPORT_FAILED, 'This practice was not pushed: the vault moved ahead while the push was running. ' +
739
- 'Run the promotion again to preview against the current version.');
740
- }
741
- const shaRes = gitExec(['rev-parse', '--short', 'HEAD'], { cwd: cloneDir });
742
- const commit = shaRes.stdout.trim();
743
- // 12. Refresh the local read cache by reusing vaultFetch verbatim
744
- // (D-11) — no new caching logic, never a direct write into
745
- // .planning/vault/. A refresh failure is non-fatal: the push already
746
- // succeeded and must be reported as such.
747
- //
748
- // vaultFetch has its own TTL-based freshness short-circuit (returns the
749
- // PRIOR manifest untouched when it is recent and the ref matches — see
750
- // src/vault.cts, frozen/unmodified here). Left alone, a promote that
751
- // runs shortly after any recent fetch (routine — e.g. the plan:pre gate
752
- // fetched minutes ago) would short-circuit on the now-stale prior
753
- // manifest and serve pre-promotion content, defeating D-11's entire
754
- // purpose ("the operator's next plan/review/ship sees the promoted
755
- // practice"). Clearing ONLY the staleness marker (never writing cache
756
- // content — that stays vaultFetch's job) forces a genuine re-fetch.
757
- try {
758
- node_fs_1.default.rmSync(node_path_1.default.join(cwd, '.planning', 'vault', '.manifest.json'), { force: true });
759
- }
760
- catch {
761
- /* best-effort; a failed clear just means vaultFetch may short-circuit below */
762
- }
763
- let cacheRefreshed = false;
764
- const notes = [];
765
- try {
766
- const manifest = vault.vaultFetch(cwd);
767
- cacheRefreshed = !!manifest && manifest.source === 'fetched';
768
- }
769
- catch {
770
- cacheRefreshed = false;
771
- }
772
- if (!cacheRefreshed) {
773
- notes.push('the local copy could not be refreshed; the next fetch will pick it up');
774
- }
775
- return {
776
- status: 'pushed',
777
- repo: shownRepo(pre.repo),
778
- ref: pre.ref,
779
- destination: pre.destination,
780
- mode,
781
- id: boundedToken(id),
782
- commit,
783
- cacheRefreshed,
784
- notes,
785
- };
786
- }
787
- finally {
788
- if (cloneDir)
789
- node_fs_1.default.rmSync(cloneDir, { recursive: true, force: true });
790
- }
791
- }
792
- /**
793
- * Single entry point 29-04's router calls: dispatches to `confirmPromotion`
794
- * when `confirmed` is true, otherwise to `previewPromotion`.
795
- */
796
- function promotePractice({ cwd, filePath, confirmed, expect, _exec, _vault, _practices, }) {
797
- if (confirmed) {
798
- return confirmPromotion({ cwd, filePath, expect, _exec, _vault, _practices });
799
- }
800
- return previewPromotion({ cwd, filePath, _exec, _vault, _practices });
801
- }
802
- // ─── Report rendering (human-readable half of the D-16 output contract) ────────
803
- /**
804
- * Render any verdict `promotePractice` can produce as plain English (the
805
- * COMM-01 bar, `docs/practices-plain-english-standard.md`) — the form 29-04's
806
- * CLI router selects when `--raw` is absent. Every vault-authored token (id,
807
- * repo, destination, notes) passes through `boundedToken` before
808
- * interpolation (T-29-07) — these values ultimately derive from an
809
- * operator-supplied practice file, not this module's own logic. For a
810
- * refusal this is exactly the single sentence `refusal()` already built. For
811
- * a preview it states the target repo, the destination path, whether the
812
- * promotion creates or updates a practice, the shared-vault disclosure
813
- * sentence when that flag is set, a line stating the secret scan found
814
- * nothing, the token line the confirmed run needs, and then the complete
815
- * diff or complete content under a heading — never elided, because the
816
- * operator is confirming exactly these bytes. For a push it states the
817
- * repo, the destination, the new commit, and whether the local copy was
818
- * refreshed.
819
- */
820
- function renderPromoteReport(verdict) {
821
- if (verdict.status === 'refused') {
822
- return verdict.message;
823
- }
824
- if (verdict.status === 'preview') {
825
- const lines = [];
826
- const action = verdict.mode === 'create' ? 'creates a new practice' : 'updates an existing practice';
827
- lines.push(`This promotes "${boundedToken(verdict.id)}" to ${boundedToken(verdict.repo)} at ${boundedToken(verdict.destination)}.`);
828
- lines.push(`This ${action} in the vault.`);
829
- if (verdict.sharedShadow && verdict.sharedShadowNote) {
830
- lines.push(boundedToken(verdict.sharedShadowNote));
831
- }
832
- lines.push('The secret scan found nothing to flag.');
833
- // NOT boundedToken: the expect token is generated by buildExpectToken (a
834
- // sha256 pair, fixed length, no untrusted input), and it is the one value
835
- // on this page the operator must copy VERBATIM. Bounding it truncated the
836
- // remote half with an ellipsis on every update — create mode escaped only
837
- // because its remote half is the short literal "absent" — and pasting the
838
- // truncated value produced the concurrent-edit refusal, telling the
839
- // operator someone else had changed the practice when nobody had.
840
- lines.push(`To push this, run the promotion again with --confirmed --expect ${verdict.expect}.`);
841
- for (const note of verdict.notes) {
842
- lines.push(`Note: ${boundedToken(note)}`);
843
- }
844
- lines.push('');
845
- if (verdict.mode === 'update') {
846
- lines.push('## Full diff');
847
- lines.push(verdict.diff && verdict.diff.length > 0 ? verdict.diff : '(no changes)');
848
- }
849
- else {
850
- lines.push('## Full content');
851
- lines.push(verdict.content ?? '');
852
- }
853
- return lines.join('\n');
854
- }
855
- // verdict.status === 'pushed'
856
- const pushedLines = [];
857
- pushedLines.push(`Pushed "${boundedToken(verdict.id)}" to ${boundedToken(verdict.repo)} at ${boundedToken(verdict.destination)} — commit ${boundedToken(verdict.commit)}.`);
858
- pushedLines.push(verdict.cacheRefreshed
859
- ? 'Your local copy was refreshed with the new content.'
860
- : 'Your local copy was not refreshed automatically; the next fetch will pick it up.');
861
- for (const note of verdict.notes) {
862
- pushedLines.push(`Note: ${boundedToken(note)}`);
863
- }
864
- return pushedLines.join('\n');
865
- }
866
- module.exports = {
867
- SECRET_SHAPES,
868
- scanForSecrets,
869
- PROMOTE_GUARD,
870
- promotePreflight,
871
- refusal,
872
- buildExpectToken,
873
- previewPromotion,
874
- confirmPromotion,
875
- promotePractice,
876
- renderPromoteReport,
877
- };