@pareto4/pp-core 1.9.0 → 1.11.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 (48) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/agents/pp-code-fixer.md +11 -0
  3. package/agents/pp-code-reviewer.md +77 -1
  4. package/agents/pp-executor.md +34 -1
  5. package/agents/pp-planner.md +24 -103
  6. package/commands/pp-ns-manage.md +2 -1
  7. package/commands/pp-vault-promote.md +31 -0
  8. package/gemini-extension.json +1 -1
  9. package/package.json +5 -3
  10. package/pareto-skills/pp-brand/SKILL.md +1 -1
  11. package/pp-core/bin/lib/capability-registry.cjs +160 -3
  12. package/pp-core/bin/lib/capability-state.cjs +41 -3
  13. package/pp-core/bin/lib/check-command-router.cjs +473 -3
  14. package/pp-core/bin/lib/clusters.cjs +3 -0
  15. package/pp-core/bin/lib/compose-bindings.cjs +736 -0
  16. package/pp-core/bin/lib/git-provider.cjs +279 -0
  17. package/pp-core/bin/lib/init-contract.cjs +989 -0
  18. package/pp-core/bin/lib/init-interactive.cjs +183 -0
  19. package/pp-core/bin/lib/io.cjs +9 -0
  20. package/pp-core/bin/lib/org-profile.cjs +696 -0
  21. package/pp-core/bin/lib/platform-bindings.cjs +268 -64
  22. package/pp-core/bin/lib/practices-review-check.cjs +938 -0
  23. package/pp-core/bin/lib/vault-command-router.cjs +239 -2
  24. package/pp-core/bin/lib/vault-coordinates.cjs +485 -0
  25. package/pp-core/bin/lib/vault-practices.cjs +982 -0
  26. package/pp-core/bin/lib/vault-write-back.cjs +842 -0
  27. package/pp-core/bin/lib/vault.cjs +170 -51
  28. package/pp-core/bin/pp-tools.cjs +225 -2
  29. package/pp-core/references/planner-checkpoints.md +72 -0
  30. package/pp-core/references/planner-tdd.md +55 -0
  31. package/pp-core/references/planner-vault-practices.md +67 -0
  32. package/pp-core/templates/practices/README.md +122 -0
  33. package/pp-core/templates/practices/error-handling.md +18 -0
  34. package/pp-core/templates/practices/minimal-comments.md +14 -0
  35. package/pp-core/templates/practices/naming-convention.md +18 -0
  36. package/pp-core/templates/practices/practice-template.md +23 -0
  37. package/pp-core/workflows/code-review.md +74 -18
  38. package/pp-core/workflows/discovery-sprint.md +1 -1
  39. package/pp-core/workflows/discovery-to-build/steps/architecture-deliverables.md +1 -1
  40. package/pp-core/workflows/init.md +137 -76
  41. package/pp-core/workflows/ship.md +1 -0
  42. package/pp-core/workflows/vault-write-back.md +213 -0
  43. package/scripts/gen-capability-registry.cjs +68 -8
  44. package/scripts/gen-platform-bindings-schema.cjs +148 -0
  45. package/scripts/lint-allow-test-rule-refs.allowlist.json +8 -1
  46. package/scripts/lint-descriptions.cjs +3 -1
  47. package/scripts/lint-legacy-dir-name.cjs +5 -0
  48. package/scripts/lint-test-file-count.allowlist.json +10 -1
@@ -0,0 +1,842 @@
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
+ // 4. Secret scan — a hit refuses hard, no override (D-14). The matched
246
+ // text is never carried, quoted, echoed, logged, or truncated into the
247
+ // refusal — a truncated secret is still a partial disclosure.
248
+ const hit = scanForSecrets(raw);
249
+ if (hit) {
250
+ 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 });
251
+ }
252
+ // 5. Target resolution — client.vaultRepo / client.vaultRef / host.
253
+ // Deliberately does NOT call resolveBaseBranch (src/git-base-branch.cts)
254
+ // — that resolver answers a question about this project's OWN
255
+ // repository, a different repository from the client vault.
256
+ const bindings = vault.readBindings(cwd);
257
+ const client = bindings && typeof bindings.client === 'object' && bindings.client !== null
258
+ ? bindings.client
259
+ : null;
260
+ const targetRepo = client && typeof client.vaultRepo === 'string' ? client.vaultRepo : null;
261
+ if (!targetRepo) {
262
+ return refusal(PROMOTE_GUARD.WRITE_TARGET, ERROR_REASON.VAULT_PROMOTE_TARGET_REFUSED, 'This practice was not promoted: no client vault repository is configured. ' +
263
+ 'Check client.vaultRepo in .platform-bindings.json and run the promotion again.');
264
+ }
265
+ // T-29-26: a repo or ref that git would read as an option is refused here,
266
+ // before any transport exists, rather than being handed to git and surfacing
267
+ // as a confusing "repository does not exist". Fails closed.
268
+ const flagShaped = [
269
+ ['client.vaultRepo', targetRepo],
270
+ ['client.vaultRef', client && typeof client.vaultRef === 'string' ? client.vaultRef : ''],
271
+ ].find(([, v]) => typeof v === 'string' && v.trim().startsWith('-'));
272
+ if (flagShaped) {
273
+ 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. ` +
274
+ 'Fix it in .platform-bindings.json and run the promotion again.');
275
+ }
276
+ const targetRef = client && typeof client.vaultRef === 'string' && client.vaultRef.trim() ? client.vaultRef.trim() : 'main';
277
+ // Resolve the provider ONCE, here in the preflight (PROV-02/T-30-16) — both
278
+ // previewPromotion and confirmPromotion re-run this preflight and read the
279
+ // same `provider` field back off the result, so they cannot compose two
280
+ // different remotes for the same promotion. Moved ahead of target-host
281
+ // resolution (Phase 31, D-10): the host now comes from the coordinate
282
+ // resolver below, which itself takes the provider as an argument.
283
+ const providerResolution = (0, git_provider_cjs_1.resolveProvider)(cwd);
284
+ const provider = providerResolution.provider;
285
+ const providerWarnings = providerResolution.warnings.slice();
286
+ // Target host — from the coordinate resolver (Phase 31, D-10), not a
287
+ // config-only host chain. `client.vaultHost` wins when set; otherwise
288
+ // `.platform-bindings.json`'s `platform.host` (D-09), warned; otherwise
289
+ // the provider's default host. The `.planning/config.json`-only
290
+ // `platform.host` read this preflight used to fall back to last is gone
291
+ // — leaving it in place beside the resolver would not fix D-09, it would
292
+ // add a third disagreeing source of the same value.
293
+ const clientCoord = (0, vault_coordinates_cjs_1.resolveClientCoordinates)(cwd, provider);
294
+ const targetHost = clientCoord.host;
295
+ if (clientCoord.warnings.length > 0)
296
+ providerWarnings.push(...clientCoord.warnings);
297
+ // Shared-tier coordinates — resolved ONCE here in the preflight (D-09,
298
+ // T-31-09), carried forward on the success shape below rather than
299
+ // resolved a second time by `previewPromotion`. This is the same
300
+ // construction already used for `provider` and for `clientCoord` above:
301
+ // both `previewPromotion` and `confirmPromotion` re-run this preflight and
302
+ // read fields back off its result, so a promotion cannot end up resolving
303
+ // two disagreeing answers for its own shared-shadow lookup.
304
+ //
305
+ // `applyBuiltInDefault: false` is load-bearing, not a stylistic default.
306
+ // This path has never applied the built-in shared-vault default — it used
307
+ // to read `vault.fallback_repo` with an empty-string fallback, so a
308
+ // project that never set the key performed no shared-shadow clone at all.
309
+ // Passing `true` here would give every existing gitlab install a shared
310
+ // clone it does not perform today, breaking ROADMAP SC3. The read-path
311
+ // ladder and `assertVaultWriteTarget` both pass `true` because both of
312
+ // them already apply the built-in default today (they always have) — this
313
+ // is the one caller that deliberately withholds it.
314
+ const sharedCoord = (0, vault_coordinates_cjs_1.resolveSharedCoordinates)(cwd, provider, { applyBuiltInDefault: false });
315
+ if (sharedCoord.warnings.length > 0)
316
+ providerWarnings.push(...sharedCoord.warnings);
317
+ // D-13/WR-01: read the resolver's OWN verdict straight off `sharedCoord`
318
+ // — no local re-derivation. Before this fix, `sharedCoord.suppressed` was
319
+ // unconditionally `false` on this call regardless of provider, because
320
+ // withholding the built-in default (`applyBuiltInDefault: false`, above)
321
+ // also disabled the resolver's suppression branch. The resolver now
322
+ // reports `suppressed`/`suppressedKind` correctly even with the built-in
323
+ // default withheld, so this module no longer needs to (and must not)
324
+ // approximate the fact from `sharedRepo`/`provider` itself — that
325
+ // approximation was exactly the WR-01 defect (PROJECT.md: an operator who
326
+ // deliberately disabled the shared tier via an empty `vault.fallback_repo`
327
+ // was shown a note asking them to set the very key they already set,
328
+ // because this module could not tell that apart from "never configured").
329
+ const sharedSuppressed = sharedCoord.suppressed;
330
+ const sharedSuppressedKind = sharedCoord.suppressedKind;
331
+ // Any warning composing the primary clone target for THIS
332
+ // provider/repo/host (an operator-supplied `.git` suffix under azure) is
333
+ // folded in here too, alongside the provider and coordinate warnings
334
+ // already collected above, so a single `notes` push in the preview
335
+ // surfaces all of them.
336
+ if (!(0, git_provider_cjs_1.isLiteralCloneTarget)(targetRepo.trim())) {
337
+ const composedForWarnings = (0, git_provider_cjs_1.composeCloneTarget)(provider, targetRepo, targetHost);
338
+ if (composedForWarnings.warnings.length > 0)
339
+ providerWarnings.push(...composedForWarnings.warnings);
340
+ }
341
+ // 6. Write-target guard (D-05, D-10) — this arm delegates to
342
+ // assertVaultWriteTarget and never re-derives, wraps, relaxes, or
343
+ // reimplements any of its three refusals; it passes the resolved target
344
+ // repo and target host straight through.
345
+ try {
346
+ vault.assertVaultWriteTarget(cwd, targetRepo, targetHost);
347
+ }
348
+ catch (e) {
349
+ const msg = (e instanceof Error ? e.message : String(e)).replace(/^vault write refused:\s*/, '');
350
+ 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.`);
351
+ }
352
+ // Destination is derived from the stable frontmatter id — never the
353
+ // local filename, never an operator-supplied value (D-04).
354
+ const destination = node_path_1.default.posix.join('practices', `${parsed.practice.id}.md`);
355
+ return {
356
+ status: 'ok',
357
+ practice: parsed.practice,
358
+ raw,
359
+ repo: targetRepo,
360
+ ref: targetRef,
361
+ host: targetHost,
362
+ destination,
363
+ provider,
364
+ providerWarnings,
365
+ sharedRepo: sharedCoord.repo,
366
+ sharedRef: sharedCoord.ref,
367
+ sharedHost: sharedCoord.host,
368
+ sharedSuppressed,
369
+ sharedSuppressedKind,
370
+ };
371
+ }
372
+ // ─── Preview (read-only half of the write path) ─────────────────────────────────
373
+ /**
374
+ * Build the opaque `expect` token that pins BOTH what the operator confirmed
375
+ * locally and what the vault held at that moment, without any state file
376
+ * across two separate process invocations: the hex sha256 of the local raw
377
+ * content, a period, then either the hex sha256 of the remote baseline or
378
+ * the literal `absent` when the destination file does not (yet) exist in
379
+ * the vault. Callers must treat the result as opaque.
380
+ */
381
+ function buildExpectToken(localRaw, remoteBaseline) {
382
+ const localHash = node_crypto_1.default.createHash('sha256').update(localRaw).digest('hex');
383
+ const remoteHash = remoteBaseline === null ? 'absent' : node_crypto_1.default.createHash('sha256').update(remoteBaseline).digest('hex');
384
+ return `${localHash}.${remoteHash}`;
385
+ }
386
+ /**
387
+ * Preview a promotion: clone the client vault into a disposable temp
388
+ * directory, capture the destination's current content as a pinned
389
+ * baseline, stage the promoted content, and ask git for a diff (update) or
390
+ * hand back the full content (create). Runs the full 29-01 preflight guard
391
+ * chain first and returns its refusal unchanged, with no clone attempted,
392
+ * on any refusal. Never creates a commit, never moves a remote ref, and
393
+ * never reads or writes the project's own vault read cache (a fresh
394
+ * mkdtemp working copy is used and always removed, even on a thrown error).
395
+ */
396
+ // `isLiteralCloneTarget` and clone-target composition — the single
397
+ // definitions live in `src/git-provider.cts` (imported above) and are shared
398
+ // with the read path (`src/vault.cts`, 30-02). Do NOT reintroduce a local
399
+ // copy of either here: a read/write divergence in this predicate was defect
400
+ // P-1 in Phase 29 (the write path used `client.vaultRepo` verbatim while the
401
+ // read path always composed a URL, so a slug broke writing and a path broke
402
+ // reading) — duplicating the fix a second time is exactly how that class of
403
+ // bug recurs.
404
+ function previewPromotion({ cwd, filePath, _exec, _vault, _practices }) {
405
+ const gitExec = _exec ?? shell_command_projection_cjs_1.execGit;
406
+ // 1. Run the full preflight guard chain; refuse unchanged with no clone.
407
+ const pre = promotePreflight({ cwd, filePath, _vault, _practices });
408
+ if (pre.status !== 'ok')
409
+ return pre;
410
+ // No local `./vault.cjs` handle is needed here any more (Phase 31,
411
+ // Task 1): the shared-shadow lookup below reads its coordinates off `pre`
412
+ // instead of calling `vault.cfgGet` directly, so this function no longer
413
+ // touches the vault module at all — `_vault` is still threaded through to
414
+ // `promotePreflight` above for the test-seam injection convention.
415
+ const notes = [];
416
+ // Surface any warning resolving the provider or composing the primary
417
+ // clone target produced (an unrecognized `vault.provider` value, or an
418
+ // operator-supplied `.git` suffix under azure) — visible in the preview an
419
+ // operator reads before confirming, never a silent degrade.
420
+ notes.push(...pre.providerWarnings);
421
+ // The disposable working copy is a fresh mkdtemp directory — never the
422
+ // read cache, which is often a shallow/sparse clone from a different tier
423
+ // and is refreshed independently after a push. Removed on every exit path.
424
+ let cloneDir = null;
425
+ try {
426
+ cloneDir = node_fs_1.default.mkdtempSync(node_path_1.default.join(node_os_1.default.tmpdir(), 'pp-vault-promote-'));
427
+ // 2. Clone the resolved client repo at the resolved ref — a full
428
+ // single-branch clone (no shallow-depth flag: the confirmed path needs
429
+ // real history to fast-forward against). The target goes through the
430
+ // provider seam's composeCloneTarget so a `group/project` slug becomes a
431
+ // real URL on the resolved host and provider, instead of a relative path
432
+ // git cannot find.
433
+ const cl = gitExec([
434
+ 'clone',
435
+ '--branch',
436
+ pre.ref,
437
+ '--single-branch',
438
+ '--',
439
+ (0, git_provider_cjs_1.composeCloneTarget)(pre.provider, pre.repo, pre.host).url,
440
+ cloneDir,
441
+ ], { timeout: 120_000 });
442
+ if (cl.exitCode !== 0) {
443
+ const cause = boundedToken((cl.stderr || '').split(/\r?\n/)[0] || 'unknown error');
444
+ 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.`);
445
+ }
446
+ // 3. Capture the baseline BEFORE writing — an id already present in the
447
+ // client vault is an update, not a refusal and not an opt-in flag
448
+ // (D-06). The baseline captured here is what 29-03's concurrent-edit
449
+ // check pins against.
450
+ const destAbs = node_path_1.default.join(cloneDir, pre.destination);
451
+ const baselineExists = node_fs_1.default.existsSync(destAbs);
452
+ const baseline = baselineExists ? node_fs_1.default.readFileSync(destAbs, 'utf-8') : null;
453
+ const mode = baselineExists ? 'update' : 'create';
454
+ // 4. Write the raw content unchanged — no reformatting, no
455
+ // re-serialization, no line-ending normalization.
456
+ node_fs_1.default.mkdirSync(node_path_1.default.dirname(destAbs), { recursive: true });
457
+ node_fs_1.default.writeFileSync(destAbs, pre.raw, 'utf-8');
458
+ // 5. Ask git for the preview rather than computing one. `core.quotepath=off`
459
+ // so a non-ASCII destination path is not escaped in operator-read output.
460
+ let diff;
461
+ let content;
462
+ if (mode === 'update') {
463
+ const diffRes = gitExec(['-c', 'core.quotepath=off', 'diff', '--', pre.destination], { cwd: cloneDir });
464
+ diff = diffRes.stdout;
465
+ }
466
+ else {
467
+ content = pre.raw;
468
+ }
469
+ // 6. Shared-shadow lookup — the shared coordinates are resolved exactly
470
+ // ONCE, in the preflight above, with the built-in default explicitly
471
+ // withheld (D-09, T-31-09); this function reads them back off `pre`
472
+ // rather than resolving them a second time. Skipped entirely (flag stays
473
+ // false) when no shared repo resolved, or it equals the client repo —
474
+ // the same skip shape as before, now expressed against the resolved
475
+ // field: a `null` `pre.sharedRepo` is treated the way the empty string
476
+ // used to be treated.
477
+ //
478
+ // The shared vault is addressed on the resolved shared host, in D-03's
479
+ // order: `vault.fallback_host` first, then the authoritative
480
+ // `platform.host` (`.platform-bindings.json` first, `.planning/config.json`
481
+ // as a warned fallback per D-09), then the provider-derived default —
482
+ // never the client's own `client.vaultHost`, mirroring the fallback tier
483
+ // in `src/vault.cts`'s `cloneTier` so a client with a custom vaultHost
484
+ // never sends the shared-shadow lookup to their own host. Composed under
485
+ // the SAME resolved provider as the client clone (deliberate and
486
+ // symmetric with `cloneTier`'s one-provider-per-fetch rule).
487
+ //
488
+ // Per-tier provider selection does NOT arrive with this phase's CFG-01:
489
+ // D-01 answered that with a deliberate, permanent no. One provider per
490
+ // project stands — a client does not straddle two providers — and the
491
+ // fix for the azure-composing-a-gitlab-URL hazard is that the shared
492
+ // coordinates became per-client config, which is exactly what resolving
493
+ // them once in the preflight, above, does.
494
+ let sharedShadow = false;
495
+ let sharedShadowNote = null;
496
+ const sharedRepo = pre.sharedRepo;
497
+ const sharedRef = pre.sharedRef;
498
+ const sharedHost = pre.sharedHost;
499
+ if (sharedRepo && sharedRepo !== pre.repo) {
500
+ let sharedDir = null;
501
+ try {
502
+ sharedDir = node_fs_1.default.mkdtempSync(node_path_1.default.join(node_os_1.default.tmpdir(), 'pp-vault-shared-'));
503
+ // Shallow single-branch: only file presence matters, no history needed.
504
+ const sc = gitExec([
505
+ 'clone',
506
+ '--depth',
507
+ '1',
508
+ '--branch',
509
+ sharedRef,
510
+ '--single-branch',
511
+ '--',
512
+ (0, git_provider_cjs_1.composeCloneTarget)(pre.provider, sharedRepo, sharedHost).url,
513
+ sharedDir,
514
+ ], { timeout: 120_000 });
515
+ if (sc.exitCode === 0) {
516
+ if (node_fs_1.default.existsSync(node_path_1.default.join(sharedDir, pre.destination))) {
517
+ sharedShadow = true;
518
+ sharedShadowNote =
519
+ "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.";
520
+ }
521
+ }
522
+ else {
523
+ // An unreachable/failed shared vault must never block, fail, or
524
+ // slow-fail a preview — leave the flag false and note it.
525
+ notes.push('the shared vault could not be checked');
526
+ }
527
+ }
528
+ catch {
529
+ notes.push('the shared vault could not be checked');
530
+ }
531
+ finally {
532
+ if (sharedDir)
533
+ node_fs_1.default.rmSync(sharedDir, { recursive: true, force: true });
534
+ }
535
+ }
536
+ // Suppression note (D-02, D-11, D-13/WR-01) — pushed ONLY when the
537
+ // shared resolution reports suppression AND the kind is
538
+ // 'provider-default-unavailable'. A gitlab project with no
539
+ // `vault.fallback_repo` resolves `sharedSuppressed: false` (nothing was
540
+ // suppressed — no built-in default was withheld from a provider that
541
+ // would otherwise have gotten one) and emits nothing here, exactly as it
542
+ // did before this phase — this note is SC3-safe by construction.
543
+ //
544
+ // D-13/WR-01: an operator who set `vault.fallback_repo` to an empty
545
+ // string deliberately disabled the shared tier — `sharedSuppressedKind`
546
+ // is `'explicit-opt-out'` for that case, and telling them to set the key
547
+ // they already set is exactly the defect this closes. NO second note is
548
+ // added for the opt-out case: silence is the correct output for a
549
+ // choice the operator already made, and inventing a new note would be
550
+ // new behaviour rather than a fix. D-11's requirement to surface the
551
+ // skipped shared check is already met by the write guard's own refusal
552
+ // sentence (plan 03); this note additionally explains why, in the
553
+ // read-only preview an operator reads before confirming.
554
+ if (pre.sharedSuppressed && pre.sharedSuppressedKind === 'provider-default-unavailable') {
555
+ 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.`);
556
+ }
557
+ // 7 & 8. Pin both sides in the opaque expect token, then return.
558
+ const expect = buildExpectToken(pre.raw, baseline);
559
+ return {
560
+ status: 'preview',
561
+ repo: pre.repo,
562
+ ref: pre.ref,
563
+ destination: pre.destination,
564
+ mode,
565
+ id: boundedToken(pre.practice.id),
566
+ diff,
567
+ content,
568
+ sharedShadow,
569
+ sharedShadowNote,
570
+ expect,
571
+ notes,
572
+ };
573
+ }
574
+ finally {
575
+ if (cloneDir)
576
+ node_fs_1.default.rmSync(cloneDir, { recursive: true, force: true });
577
+ }
578
+ }
579
+ // ─── Confirm (write half of the write path) ──────────────────────────────────────
580
+ /** Build a TRANSPORT refusal from a failed git invocation's stderr (first line only). */
581
+ function transportRefusal(res) {
582
+ const cause = boundedToken((res.stderr || '').split(/\r?\n/)[0] || 'unknown error');
583
+ 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.`);
584
+ }
585
+ /**
586
+ * Confirm a promotion: re-run the full 29-01 preflight chain (never trust
587
+ * the preview), re-verify the opaque `expect` token against a freshly read
588
+ * local file AND a freshly cloned remote baseline, absorb unrelated remote
589
+ * movement with a fast-forward-only pull, then stage/commit/push exactly
590
+ * the destination path with no force flag on any code path. On success,
591
+ * refreshes the local read cache via `./vault.cjs`'s `vaultFetch` verbatim.
592
+ *
593
+ * Deliberate deviation from a literal `git show`-based remote-baseline read
594
+ * (Rule 1 bug avoidance): `execGit`'s shared `_spawnResult` unconditionally
595
+ * `.trim()`s captured stdout, which would silently strip a file's trailing
596
+ * newline and make every legitimate hash comparison spuriously mismatch.
597
+ * Instead this re-derives the remote baseline from the filesystem AFTER the
598
+ * fast-forward-only pull (the same fs-read technique `previewPromotion`
599
+ * already uses for its own baseline capture) — byte-exact, and the pull
600
+ * step the plan already requires does the "sync to the fetched ref" work
601
+ * for free, so no separate `git show`/`cat-file` call is needed.
602
+ */
603
+ function confirmPromotion({ cwd, filePath, expect, _exec, _vault, _practices }) {
604
+ const gitExec = _exec ?? shell_command_projection_cjs_1.execGit;
605
+ // 1. Full preflight re-run — never trust the preview. Re-derives repo,
606
+ // ref, host, and destination from scratch; never accepts a caller-
607
+ // supplied id/destination/repo/ref.
608
+ const pre = promotePreflight({ cwd, filePath, _vault, _practices });
609
+ if (pre.status !== 'ok')
610
+ return pre;
611
+ // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-unsafe-assignment
612
+ const vault = _vault ?? require('./vault.cjs');
613
+ // 2. Missing/empty token → refuse before any clone.
614
+ if (!expect || typeof expect !== 'string' || expect.length === 0) {
615
+ 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. ' +
616
+ 'Run the promotion without confirming first, then pass the token it prints.');
617
+ }
618
+ // 3. Split the token; a malformed token (no separator) naturally fails the
619
+ // local-hash comparison below rather than needing a distinct code path.
620
+ const sepIdx = expect.indexOf('.');
621
+ const pinnedLocal = sepIdx === -1 ? expect : expect.slice(0, sepIdx);
622
+ const pinnedRemote = sepIdx === -1 ? '' : expect.slice(sepIdx + 1);
623
+ // 4. Recompute the local hash from the FRESHLY read content (pre.raw came
624
+ // from this invocation's own promotePreflight, not the preview's). A
625
+ // mismatch means the local file changed since the operator previewed it —
626
+ // this is what makes D-10's byte-identity claim hold across two separate
627
+ // process invocations (T-29-13).
628
+ const localHash = node_crypto_1.default.createHash('sha256').update(pre.raw).digest('hex');
629
+ if (localHash !== pinnedLocal) {
630
+ 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. ' +
631
+ 'Run the promotion again to preview the new version.');
632
+ }
633
+ // 5. Clone into a fresh disposable mkdtemp directory — exactly as the
634
+ // preview does, but NEVER the preview's own clone directory and NEVER the
635
+ // read cache.
636
+ let cloneDir = null;
637
+ try {
638
+ cloneDir = node_fs_1.default.mkdtempSync(node_path_1.default.join(node_os_1.default.tmpdir(), 'pp-vault-confirm-'));
639
+ const cl = gitExec([
640
+ 'clone',
641
+ '--branch',
642
+ pre.ref,
643
+ '--single-branch',
644
+ '--',
645
+ (0, git_provider_cjs_1.composeCloneTarget)(pre.provider, pre.repo, pre.host).url,
646
+ cloneDir,
647
+ ], { timeout: 120_000 });
648
+ if (cl.exitCode !== 0)
649
+ return transportRefusal(cl);
650
+ // 6. Fetch the resolved ref from origin, then absorb any unrelated
651
+ // remote movement with a fast-forward-only pull. The file-scoped
652
+ // baseline check below runs AFTER this on purpose: a target-file race
653
+ // is still caught by the hash comparison, and a race that instead
654
+ // defeats the transport layer (an unrelated push landing between this
655
+ // pull and this module's own push, below) fails closed on the push
656
+ // itself — the intended structural backstop (T-29-04), never retried.
657
+ const ft = gitExec(['fetch', 'origin', pre.ref], { cwd: cloneDir, timeout: 120_000 });
658
+ if (ft.exitCode !== 0)
659
+ return transportRefusal(ft);
660
+ const pull = gitExec(['pull', '--ff-only', 'origin', pre.ref], { cwd: cloneDir, timeout: 120_000 });
661
+ if (pull.exitCode !== 0)
662
+ return transportRefusal(pull);
663
+ // 7. Re-derive the remote baseline from the now fast-forwarded working
664
+ // tree (fs-level read, byte-exact — never git-stdout-derived, which is
665
+ // silently trimmed by the shared exec helper). Scoped to the
666
+ // destination file only (D-15): commit/tree shas are never compared,
667
+ // so an unrelated promotion never blocks this one.
668
+ const destAbs = node_path_1.default.join(cloneDir, pre.destination);
669
+ const remoteExists = node_fs_1.default.existsSync(destAbs);
670
+ const remoteContent = remoteExists ? node_fs_1.default.readFileSync(destAbs, 'utf-8') : null;
671
+ const remoteHash = remoteContent === null ? 'absent' : node_crypto_1.default.createHash('sha256').update(remoteContent).digest('hex');
672
+ if (remoteHash !== pinnedRemote) {
673
+ 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. ` +
674
+ 'Run the promotion again to see their version before you push.');
675
+ }
676
+ const mode = remoteExists ? 'update' : 'create';
677
+ // 8. Write the promoted content, then stage exactly that one path.
678
+ node_fs_1.default.mkdirSync(node_path_1.default.dirname(destAbs), { recursive: true });
679
+ node_fs_1.default.writeFileSync(destAbs, pre.raw, 'utf-8');
680
+ const add = gitExec(['add', '--', pre.destination], { cwd: cloneDir });
681
+ if (add.exitCode !== 0)
682
+ return transportRefusal(add);
683
+ // 9. Configure identity only if git reports none — preserve an
684
+ // operator's own configured identity when present.
685
+ const idCheck = gitExec(['config', 'user.email'], { cwd: cloneDir });
686
+ if (idCheck.exitCode !== 0 || !idCheck.stdout.trim()) {
687
+ gitExec(['config', 'user.email', 'pp-core-vault-promote@pareto.local'], { cwd: cloneDir });
688
+ gitExec(['config', 'user.name', 'pp-core vault promote'], { cwd: cloneDir });
689
+ }
690
+ // 10. Commit once.
691
+ const id = pre.practice.id;
692
+ const commitMessage = `practice(${mode}): ${boundedToken(id)}\n\nPromoted from this project via pp-core's vault write-back arm.`;
693
+ const commitRes = gitExec(['commit', '-m', commitMessage], { cwd: cloneDir });
694
+ if (commitRes.exitCode !== 0)
695
+ return transportRefusal(commitRes);
696
+ // 11. Push once — origin, local HEAD mapped to the resolved ref. No
697
+ // force flag, no lease flag, no short-form alias, not on this call, not
698
+ // on a retry. A non-fast-forward rejection is the intended structural
699
+ // backstop for a race that defeats the file-scoped check above; never
700
+ // re-run, never looped, never escalated.
701
+ const push = gitExec(['push', 'origin', `HEAD:${pre.ref}`], { cwd: cloneDir, timeout: 120_000 });
702
+ if (push.exitCode !== 0) {
703
+ 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. ' +
704
+ 'Run the promotion again to preview against the current version.');
705
+ }
706
+ const shaRes = gitExec(['rev-parse', '--short', 'HEAD'], { cwd: cloneDir });
707
+ const commit = shaRes.stdout.trim();
708
+ // 12. Refresh the local read cache by reusing vaultFetch verbatim
709
+ // (D-11) — no new caching logic, never a direct write into
710
+ // .planning/vault/. A refresh failure is non-fatal: the push already
711
+ // succeeded and must be reported as such.
712
+ //
713
+ // vaultFetch has its own TTL-based freshness short-circuit (returns the
714
+ // PRIOR manifest untouched when it is recent and the ref matches — see
715
+ // src/vault.cts, frozen/unmodified here). Left alone, a promote that
716
+ // runs shortly after any recent fetch (routine — e.g. the plan:pre gate
717
+ // fetched minutes ago) would short-circuit on the now-stale prior
718
+ // manifest and serve pre-promotion content, defeating D-11's entire
719
+ // purpose ("the operator's next plan/review/ship sees the promoted
720
+ // practice"). Clearing ONLY the staleness marker (never writing cache
721
+ // content — that stays vaultFetch's job) forces a genuine re-fetch.
722
+ try {
723
+ node_fs_1.default.rmSync(node_path_1.default.join(cwd, '.planning', 'vault', '.manifest.json'), { force: true });
724
+ }
725
+ catch {
726
+ /* best-effort; a failed clear just means vaultFetch may short-circuit below */
727
+ }
728
+ let cacheRefreshed = false;
729
+ const notes = [];
730
+ try {
731
+ const manifest = vault.vaultFetch(cwd);
732
+ cacheRefreshed = !!manifest && manifest.source === 'fetched';
733
+ }
734
+ catch {
735
+ cacheRefreshed = false;
736
+ }
737
+ if (!cacheRefreshed) {
738
+ notes.push('the local copy could not be refreshed; the next fetch will pick it up');
739
+ }
740
+ return {
741
+ status: 'pushed',
742
+ repo: pre.repo,
743
+ ref: pre.ref,
744
+ destination: pre.destination,
745
+ mode,
746
+ id: boundedToken(id),
747
+ commit,
748
+ cacheRefreshed,
749
+ notes,
750
+ };
751
+ }
752
+ finally {
753
+ if (cloneDir)
754
+ node_fs_1.default.rmSync(cloneDir, { recursive: true, force: true });
755
+ }
756
+ }
757
+ /**
758
+ * Single entry point 29-04's router calls: dispatches to `confirmPromotion`
759
+ * when `confirmed` is true, otherwise to `previewPromotion`.
760
+ */
761
+ function promotePractice({ cwd, filePath, confirmed, expect, _exec, _vault, _practices, }) {
762
+ if (confirmed) {
763
+ return confirmPromotion({ cwd, filePath, expect, _exec, _vault, _practices });
764
+ }
765
+ return previewPromotion({ cwd, filePath, _exec, _vault, _practices });
766
+ }
767
+ // ─── Report rendering (human-readable half of the D-16 output contract) ────────
768
+ /**
769
+ * Render any verdict `promotePractice` can produce as plain English (the
770
+ * COMM-01 bar, `docs/practices-plain-english-standard.md`) — the form 29-04's
771
+ * CLI router selects when `--raw` is absent. Every vault-authored token (id,
772
+ * repo, destination, notes) passes through `boundedToken` before
773
+ * interpolation (T-29-07) — these values ultimately derive from an
774
+ * operator-supplied practice file, not this module's own logic. For a
775
+ * refusal this is exactly the single sentence `refusal()` already built. For
776
+ * a preview it states the target repo, the destination path, whether the
777
+ * promotion creates or updates a practice, the shared-vault disclosure
778
+ * sentence when that flag is set, a line stating the secret scan found
779
+ * nothing, the token line the confirmed run needs, and then the complete
780
+ * diff or complete content under a heading — never elided, because the
781
+ * operator is confirming exactly these bytes. For a push it states the
782
+ * repo, the destination, the new commit, and whether the local copy was
783
+ * refreshed.
784
+ */
785
+ function renderPromoteReport(verdict) {
786
+ if (verdict.status === 'refused') {
787
+ return verdict.message;
788
+ }
789
+ if (verdict.status === 'preview') {
790
+ const lines = [];
791
+ const action = verdict.mode === 'create' ? 'creates a new practice' : 'updates an existing practice';
792
+ lines.push(`This promotes "${boundedToken(verdict.id)}" to ${boundedToken(verdict.repo)} at ${boundedToken(verdict.destination)}.`);
793
+ lines.push(`This ${action} in the vault.`);
794
+ if (verdict.sharedShadow && verdict.sharedShadowNote) {
795
+ lines.push(boundedToken(verdict.sharedShadowNote));
796
+ }
797
+ lines.push('The secret scan found nothing to flag.');
798
+ // NOT boundedToken: the expect token is generated by buildExpectToken (a
799
+ // sha256 pair, fixed length, no untrusted input), and it is the one value
800
+ // on this page the operator must copy VERBATIM. Bounding it truncated the
801
+ // remote half with an ellipsis on every update — create mode escaped only
802
+ // because its remote half is the short literal "absent" — and pasting the
803
+ // truncated value produced the concurrent-edit refusal, telling the
804
+ // operator someone else had changed the practice when nobody had.
805
+ lines.push(`To push this, run the promotion again with --confirmed --expect ${verdict.expect}.`);
806
+ for (const note of verdict.notes) {
807
+ lines.push(`Note: ${boundedToken(note)}`);
808
+ }
809
+ lines.push('');
810
+ if (verdict.mode === 'update') {
811
+ lines.push('## Full diff');
812
+ lines.push(verdict.diff && verdict.diff.length > 0 ? verdict.diff : '(no changes)');
813
+ }
814
+ else {
815
+ lines.push('## Full content');
816
+ lines.push(verdict.content ?? '');
817
+ }
818
+ return lines.join('\n');
819
+ }
820
+ // verdict.status === 'pushed'
821
+ const pushedLines = [];
822
+ pushedLines.push(`Pushed "${boundedToken(verdict.id)}" to ${boundedToken(verdict.repo)} at ${boundedToken(verdict.destination)} — commit ${boundedToken(verdict.commit)}.`);
823
+ pushedLines.push(verdict.cacheRefreshed
824
+ ? 'Your local copy was refreshed with the new content.'
825
+ : 'Your local copy was not refreshed automatically; the next fetch will pick it up.');
826
+ for (const note of verdict.notes) {
827
+ pushedLines.push(`Note: ${boundedToken(note)}`);
828
+ }
829
+ return pushedLines.join('\n');
830
+ }
831
+ module.exports = {
832
+ SECRET_SHAPES,
833
+ scanForSecrets,
834
+ PROMOTE_GUARD,
835
+ promotePreflight,
836
+ refusal,
837
+ buildExpectToken,
838
+ previewPromotion,
839
+ confirmPromotion,
840
+ promotePractice,
841
+ renderPromoteReport,
842
+ };