create-principles-disciple 1.147.17 → 1.147.19

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 (47) hide show
  1. package/_release/product-identity.json +1 -1
  2. package/codex-adapter/package.json +1 -1
  3. package/core/dist/host/host-installer.d.ts +11 -0
  4. package/core/dist/host/host-installer.d.ts.map +1 -1
  5. package/core/dist/host/host-installer.js.map +1 -1
  6. package/core/package.json +1 -1
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +23 -0
  9. package/dist/index.js.map +1 -1
  10. package/dist/installer.d.ts +20 -0
  11. package/dist/installer.d.ts.map +1 -1
  12. package/dist/installer.js +75 -12
  13. package/dist/installer.js.map +1 -1
  14. package/dist/installers/codex-host-installer.d.ts +21 -0
  15. package/dist/installers/codex-host-installer.d.ts.map +1 -1
  16. package/dist/installers/codex-host-installer.js +105 -4
  17. package/dist/installers/codex-host-installer.js.map +1 -1
  18. package/dist/installers/workbuddy-host-installer.d.ts +34 -3
  19. package/dist/installers/workbuddy-host-installer.d.ts.map +1 -1
  20. package/dist/installers/workbuddy-host-installer.js +841 -53
  21. package/dist/installers/workbuddy-host-installer.js.map +1 -1
  22. package/dist/utils/config-file-io.d.ts +27 -1
  23. package/dist/utils/config-file-io.d.ts.map +1 -1
  24. package/dist/utils/config-file-io.js +78 -3
  25. package/dist/utils/config-file-io.js.map +1 -1
  26. package/host-runtime/package.json +1 -1
  27. package/install-layout/dist/index.d.ts +49 -0
  28. package/install-layout/dist/index.js +59 -0
  29. package/install-layout/package.json +1 -1
  30. package/package.json +4 -4
  31. package/pd-cli/dist/commands/health-workbuddy.d.ts +31 -0
  32. package/pd-cli/dist/commands/health-workbuddy.d.ts.map +1 -0
  33. package/pd-cli/dist/commands/health-workbuddy.js +192 -0
  34. package/pd-cli/dist/commands/health-workbuddy.js.map +1 -0
  35. package/pd-cli/dist/commands/health.d.ts.map +1 -1
  36. package/pd-cli/dist/commands/health.js +12 -0
  37. package/pd-cli/dist/commands/health.js.map +1 -1
  38. package/pd-cli/package.json +1 -1
  39. package/plugin/dist/bundle.js +110 -110
  40. package/plugin/openclaw.plugin.json +1 -1
  41. package/plugin/package.json +1 -1
  42. package/release-manager/dist/installer.js +75 -12
  43. package/release-manager/dist/installers/codex-host-installer.js +105 -4
  44. package/release-manager/dist/installers/workbuddy-host-installer.js +841 -53
  45. package/release-manager/dist/utils/config-file-io.js +78 -3
  46. package/release-manager/package.json +1 -1
  47. package/workbuddy-adapter/package.json +1 -1
@@ -42,18 +42,21 @@
42
42
  * result reason; every result carries reason + nextAction.
43
43
  */
44
44
  import { spawnSync, execFileSync } from 'node:child_process';
45
- import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, cpSync, writeFileSync, openSync, closeSync } from 'node:fs';
45
+ import { createHash } from 'node:crypto';
46
+ import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, readlinkSync, renameSync, rmSync, cpSync, writeFileSync, openSync, closeSync } from 'node:fs';
46
47
  import * as path from 'node:path';
47
48
  import * as yaml from 'js-yaml';
48
49
  import semver from 'semver';
49
50
  import { getInstallLayoutPaths, getWorkbuddyWorkspaceDir, installManifestHostsForPersist, mergeInstallManifestWorkspaces, parseInstallManifest, INSTALL_LAYOUT_VERSION, } from '@principles/install-layout';
50
- import { atomicReplaceTextFile, errnoCode } from '../utils/config-file-io.js';
51
- import { checkMcpRegistrationConflict } from './mcp-registration-conflict.js';
52
- import { resolveMcpServerDir, resolveMcpServerEntry } from '../mcp-server-layout-compat.js';
53
- import { getHomeDir, generateConfigYamlContent, getConfigYamlPath, resolveDefaultModelForProvider, isValidHttpBaseUrl } from '../mvp-config.js';
54
- // Type-only import from @principles/core — erased at compile time; this
55
- // package ships self-contained without @principles/core (PRI-625/PRI-669).
56
- // ─── Frozen host contract constants ─────────────────────────────────────────
51
+ // 2026-11-08: the shared state DEFINITIONS for pd-cli health live in
52
+ // @principles/install-layout (interpretWorkbuddyPluginState /
53
+ // getWorkbuddyHostConfigPaths). The installer does NOT import them at
54
+ // runtime: its packaged dist must keep loading against the PUBLISHED
55
+ // install-layout (registry-parity smoke, PRI-669/RF-02), and a normal PR
56
+ // cannot raise the version floor (release-intent guard N-version). The
57
+ // local constants/judgment below are the pinned mirror — a CI parity test
58
+ // pins installer state == install-layout state on a fixture matrix (the
59
+ // same discipline as the Codex legacy-registration parser mirror).
57
60
  /** Plugin name inside the PD-owned marketplace (kebab-case per plugin.json contract). */
58
61
  export const WORKBUDDY_PLUGIN_NAME = 'principles-disciple';
59
62
  /** PD-owned local marketplace name. enabledPlugins keys use "plugin@marketplace". */
@@ -61,6 +64,12 @@ export const WORKBUDDY_MARKETPLACE_NAME = 'principles-disciple-market';
61
64
  /** Registry/settings key: "principles-disciple@principles-disciple-market". */
62
65
  export const WORKBUDDY_PLUGIN_KEY = `${WORKBUDDY_PLUGIN_NAME}@${WORKBUDDY_MARKETPLACE_NAME}`;
63
66
  const WORKBUDDY_REQUIRED_SKILLS = ['pd-cli-operator', 'pd-pain-signal', 'pd-review', 'pd-control'];
67
+ import { atomicReplaceTextFile, AtomicReplaceCleanupError, AtomicReplaceConflictError, errnoCode } from '../utils/config-file-io.js';
68
+ import { checkMcpRegistrationConflict } from './mcp-registration-conflict.js';
69
+ import { resolveMcpServerDir, resolveMcpServerEntry } from '../mcp-server-layout-compat.js';
70
+ import { getHomeDir, generateConfigYamlContent, getConfigYamlPath, resolveDefaultModelForProvider, isValidHttpBaseUrl } from '../mvp-config.js';
71
+ // Type-only import from @principles/core — erased at compile time; this
72
+ // package ships self-contained without @principles/core (PRI-625/PRI-669).
64
73
  /**
65
74
  * Files the host needs to load this plugin. One list serves both the
66
75
  * "is the cached payload current?" comparison and the "did the staged copy
@@ -374,6 +383,616 @@ export function writeHostJsonFileProtected(filePath, content) {
374
383
  };
375
384
  }
376
385
  }
386
+ function workbuddyDigestTree(root) {
387
+ const hash = createHash('sha256');
388
+ const walk = (dir, relative) => {
389
+ // Hash directory structure too: a new empty dir is a concurrent write.
390
+ // An unreadable subtree is UNPROVABLE, not a stable equal digest.
391
+ hash.update('dir:' + relative + '\n');
392
+ const entries = readdirSync(dir, { withFileTypes: true });
393
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
394
+ const rel = relative.length === 0 ? entry.name : relative + '/' + entry.name;
395
+ const entryPath = path.join(dir, entry.name);
396
+ if (entry.isSymbolicLink()) {
397
+ // A symlink/junction is not followed, but its target string is part
398
+ // of the identity of the cache, and must not be silently ignored.
399
+ hash.update('link:' + rel + ':' + readlinkSync(entryPath) + '\n');
400
+ }
401
+ else if (entry.isDirectory()) {
402
+ walk(entryPath, rel);
403
+ }
404
+ else if (entry.isFile()) {
405
+ hash.update('file:' + rel + ':' + createHash('sha256').update(readFileSync(entryPath)).digest('hex') + '\n');
406
+ }
407
+ else {
408
+ throw new Error('unsupported cache filesystem entry: ' + entryPath);
409
+ }
410
+ }
411
+ };
412
+ walk(root, '');
413
+ return hash.digest('hex');
414
+ }
415
+ /** Byte snapshot of one file (undefined bytes when absent). */
416
+ function snapshotWorkbuddyFile(filePath) {
417
+ try {
418
+ return { existed: true, bytes: readFileSync(filePath) };
419
+ }
420
+ catch (error) {
421
+ // Only ENOENT proves absence. EACCES/EISDIR and other read failures cannot
422
+ // be converted to "new file": rollback would then delete Owner content.
423
+ if (errnoCode(error) === 'ENOENT')
424
+ return { existed: false, bytes: undefined };
425
+ throw error;
426
+ }
427
+ }
428
+ function openWorkbuddyInstallTxn(p, version, deps = {}) {
429
+ const snapshots = new Map();
430
+ const governanceConfigPath = path.join(p.governanceDir, '.pd', 'config.yaml');
431
+ const governanceDirExistedBefore = existsSync(p.governanceDir);
432
+ try {
433
+ for (const filePath of [p.settingsPath, p.registryPath, p.installManifestPath, governanceConfigPath]) {
434
+ snapshots.set(filePath, snapshotWorkbuddyFile(filePath));
435
+ }
436
+ }
437
+ catch (error) {
438
+ return {
439
+ ok: false,
440
+ reason: 'workbuddy_transaction_snapshot_failed: cannot prove the previous host configuration before registration (' +
441
+ (error instanceof Error ? error.message : String(error)) + '). No host registration or cache replacement was started; the PD marketplace staging files may already exist.',
442
+ nextAction: 'Repair the unreadable host file or its permissions and retry; do not delete it to make the install proceed.',
443
+ };
444
+ }
445
+ const versionDir = workbuddyCacheVersionDir(p.cachePluginRoot, version);
446
+ let cacheExisted = false;
447
+ let cacheDigestBefore;
448
+ let cacheBackupDir;
449
+ if (versionDir !== undefined && existsSync(versionDir)) {
450
+ cacheExisted = true;
451
+ try {
452
+ cacheDigestBefore = workbuddyDigestTree(versionDir);
453
+ }
454
+ catch (error) {
455
+ return {
456
+ ok: false,
457
+ reason: 'workbuddy_cache_snapshot_failed: cache cannot be fully read before upgrade (' +
458
+ (error instanceof Error ? error.message : String(error)) + '); no cache replacement attempted.',
459
+ nextAction: 'Repair or remove the unreadable cache entry only after preserving Owner data, then retry.',
460
+ };
461
+ }
462
+ cacheBackupDir = path.join(path.dirname(path.resolve(p.cachePluginRoot)), `.pd-txn-backup-${process.pid}-${Date.now()}`);
463
+ // 2026-11-08 P1 fix: for an UPGRADE (a pre-existing cache payload), the
464
+ // backup is the rollback's only material. A backup that cannot be created
465
+ // — or one whose CONTENT cannot be proven identical to the payload it
466
+ // copied (content-level digest, not a mere existence/success check) —
467
+ // REFUSES the whole upgrade BEFORE any cache replacement is attempted.
468
+ // Returning without a usable backup used to let the install proceed and
469
+ // later delete the current cache against a rollback it could not serve.
470
+ // `deps.copyDir` is the same test seam class as deps.runCommand (real
471
+ // boundary substitution; safety is proven by real file assertions).
472
+ const copyDir = deps.copyDir ?? cpSync;
473
+ let backupError;
474
+ try {
475
+ rmSync(cacheBackupDir, { recursive: true, force: true });
476
+ copyDir(versionDir, cacheBackupDir, { recursive: true });
477
+ if (workbuddyDigestTree(cacheBackupDir) !== cacheDigestBefore) {
478
+ backupError = 'the copied backup does not match the current payload (digest mismatch)';
479
+ }
480
+ }
481
+ catch (error) {
482
+ backupError = error instanceof Error ? error.message : String(error);
483
+ }
484
+ if (backupError !== undefined) {
485
+ try {
486
+ rmSync(cacheBackupDir, { recursive: true, force: true });
487
+ }
488
+ catch { /* reported below */ }
489
+ return {
490
+ ok: false,
491
+ reason: `workbuddy_cache_backup_failed: could not prove a restorable backup of the current cache payload ${versionDir} — ${backupError}. The upgrade was REFUSED before any replacement: the current payload and the host registration are untouched.`,
492
+ nextAction: 'Free the storage / close the tools holding the plugin cache files, then re-run the installer. The previous plugin version remains installed and usable.',
493
+ };
494
+ }
495
+ }
496
+ return {
497
+ ok: true,
498
+ txn: {
499
+ evidenceDir: cacheExisted
500
+ ? (cacheBackupDir ?? '(pre-install backup unavailable)')
501
+ : '(no pre-existing cache payload — fresh install)',
502
+ fileSnapshots: snapshots,
503
+ writtenPaths: [],
504
+ lastWrittenBytes: new Map(),
505
+ fileEvidenceDir: undefined,
506
+ fileEvidenceRecords: [],
507
+ atomicReplace: deps.atomicReplace ?? atomicReplaceTextFile,
508
+ cacheOps: deps.cacheOps ?? { copyDir: cpSync, rename: renameSync },
509
+ governanceDir: p.governanceDir,
510
+ governanceDirExistedBefore,
511
+ settingsPath: p.settingsPath,
512
+ registryPath: p.registryPath,
513
+ cacheVersionDir: versionDir,
514
+ cacheExisted,
515
+ cacheBackupDir,
516
+ cacheDigestBefore,
517
+ cacheDigestAfterRegistration: undefined,
518
+ },
519
+ };
520
+ }
521
+ /** Record a successful PD write (rc-7: current state, not a prior iteration). */
522
+ function recordWorkbuddyTxnWrite(txn, filePath, bytesAfterWrite) {
523
+ if (!txn.writtenPaths.includes(filePath))
524
+ txn.writtenPaths.push(filePath);
525
+ txn.lastWrittenBytes.set(filePath, Buffer.from(bytesAfterWrite));
526
+ }
527
+ /** After registration committed, pin the guard baselines PD must restore against.
528
+ *
529
+ * Known limit (documented, accepted): the baselines are pinned by reading the
530
+ * files right after registration. Within this process the read is synchronous
531
+ * with the write (no yield point), so only a CROSS-PROCESS host write landing
532
+ * inside that sub-millisecond window can be pinned as "what PD wrote" — the
533
+ * same unavoidable FS race class writeHostJsonFileProtected already accepts.
534
+ * Every modification AFTER the pin is correctly detected by the guard. */
535
+ function captureWorkbuddyPostRegistration(txn, p, mode) {
536
+ // A no-op registration did not write any host files/cache. In particular,
537
+ // never attribute a concurrent Owner edit to PD and roll it back.
538
+ if (mode === 'already-registered') {
539
+ txn.cacheDigestAfterRegistration = txn.cacheDigestBefore;
540
+ return;
541
+ }
542
+ for (const filePath of [p.settingsPath, p.registryPath]) {
543
+ const before = txn.fileSnapshots.get(filePath);
544
+ const after = snapshotWorkbuddyFile(filePath);
545
+ if (after.existed && after.bytes !== undefined &&
546
+ (!before?.existed || before.bytes === undefined || !after.bytes.equals(before.bytes))) {
547
+ recordWorkbuddyTxnWrite(txn, filePath, after.bytes);
548
+ }
549
+ }
550
+ if (txn.cacheVersionDir !== undefined && existsSync(txn.cacheVersionDir)) {
551
+ txn.cacheDigestAfterRegistration = workbuddyDigestTree(txn.cacheVersionDir);
552
+ }
553
+ }
554
+ function preserveWorkbuddyFileSnapshot(txn, filePath) {
555
+ const snapshot = txn.fileSnapshots.get(filePath);
556
+ if (snapshot === undefined)
557
+ return { ok: false, reason: 'no original snapshot was recorded' };
558
+ try {
559
+ if (txn.fileEvidenceDir === undefined) {
560
+ mkdirSync(path.dirname(txn.settingsPath), { recursive: true });
561
+ txn.fileEvidenceDir = mkdtempSync(path.join(path.dirname(txn.settingsPath), '.pd-workbuddy-recovery-'));
562
+ }
563
+ let record = txn.fileEvidenceRecords.find((item) => item.originalPath === filePath);
564
+ if (record === undefined) {
565
+ record = { originalPath: filePath, existed: snapshot.existed };
566
+ if (snapshot.existed && snapshot.bytes !== undefined) {
567
+ const snapshotName = createHash('sha256').update(filePath).digest('hex') + '.bin';
568
+ const snapshotFile = path.join(txn.fileEvidenceDir, snapshotName);
569
+ writeFileSync(snapshotFile, snapshot.bytes, { flag: 'wx', mode: 0o600 });
570
+ record.snapshotFile = snapshotFile;
571
+ record.sha256 = createHash('sha256').update(snapshot.bytes).digest('hex');
572
+ }
573
+ txn.fileEvidenceRecords.push(record);
574
+ }
575
+ writeFileSync(path.join(txn.fileEvidenceDir, 'manifest.json'), JSON.stringify({ format: 'pd-workbuddy-file-recovery-v1', records: txn.fileEvidenceRecords }, null, 2) + '\n', 'utf-8');
576
+ return { ok: true, directory: txn.fileEvidenceDir };
577
+ }
578
+ catch (error) {
579
+ return {
580
+ ok: false,
581
+ reason: 'could not persist the original file snapshot (' + (error instanceof Error ? error.message : String(error)) + ')',
582
+ };
583
+ }
584
+ }
585
+ /** Restore one file snapshot under a byte guard. Returns an error detail or undefined. */
586
+ function restoreWorkbuddyFileSnapshot(txn, filePath) {
587
+ const snapshot = txn.fileSnapshots.get(filePath);
588
+ if (snapshot === undefined)
589
+ return undefined; // never tracked — not ours to touch
590
+ const expected = txn.lastWrittenBytes.get(filePath);
591
+ if (expected === undefined)
592
+ return undefined; // PD never wrote it in this txn — nothing to undo
593
+ const evidenceNote = () => {
594
+ const evidence = preserveWorkbuddyFileSnapshot(txn, filePath);
595
+ return evidence.ok
596
+ ? '; original snapshot preserved at ' + evidence.directory
597
+ : '; ' + evidence.reason;
598
+ };
599
+ let current;
600
+ try {
601
+ current = snapshotWorkbuddyFile(filePath);
602
+ }
603
+ catch (error) {
604
+ return filePath + ': unreadable during rollback (' +
605
+ (error instanceof Error ? error.message : String(error)) + ')' + evidenceNote();
606
+ }
607
+ if (current.existed !== true || current.bytes === undefined || !current.bytes.equals(expected)) {
608
+ return filePath + ': changed after PD wrote it (concurrent modification) — restore skipped to avoid clobbering' + evidenceNote();
609
+ }
610
+ if (snapshot.existed && snapshot.bytes !== undefined && current.bytes.equals(snapshot.bytes))
611
+ return undefined;
612
+ try {
613
+ if (!snapshot.existed || snapshot.bytes === undefined) {
614
+ // Only a file that did NOT exist before this transaction may be removed.
615
+ // Move the candidate out of the live path, RE-READ the moved bytes and
616
+ // compare them to what PD wrote before deleting anything. This narrows
617
+ // the check/delete race and keeps concurrent content instead of erasing
618
+ // it. (The residual read-then-rename window is documented above.)
619
+ const quarantine = filePath + '.pd-rollback-delete-' + process.pid + '-' + Date.now();
620
+ renameSync(filePath, quarantine);
621
+ const quarantinedBytes = readFileSync(quarantine);
622
+ if (!quarantinedBytes.equals(expected)) {
623
+ try {
624
+ if (!existsSync(filePath)) {
625
+ renameSync(quarantine, filePath);
626
+ return filePath + ': changed during rollback; deletion refused and the concurrent content was returned to its live path' + evidenceNote();
627
+ }
628
+ return filePath + ': changed during rollback; deletion refused, the moved content is preserved at ' +
629
+ quarantine + ' (a different file already occupies the live path)' + evidenceNote();
630
+ }
631
+ catch (restoreError) {
632
+ return filePath + ': changed during rollback; deletion refused, the concurrent content is preserved at ' +
633
+ quarantine + ' and could NOT be returned to its live path (' +
634
+ (restoreError instanceof Error ? restoreError.message : String(restoreError)) + ')' + evidenceNote();
635
+ }
636
+ }
637
+ rmSync(quarantine, { force: true });
638
+ }
639
+ else {
640
+ // Re-check the exact bytes at the atomic replacement boundary. A conflict
641
+ // is not repaired by copying the old backup over the concurrent edit.
642
+ // Routed through the txn seam so the read-then-rename boundary is
643
+ // testable with a real, non-cooperating concurrent write.
644
+ txn.atomicReplace(filePath, snapshot.bytes, undefined, {}, expected);
645
+ }
646
+ return undefined;
647
+ }
648
+ catch (error) {
649
+ if (error instanceof AtomicReplaceConflictError) {
650
+ return filePath + ': changed at the rollback commit boundary; restore refused to preserve the concurrent edit (' +
651
+ error.message + ')' + evidenceNote();
652
+ }
653
+ return filePath + ': restore failed (' + (error instanceof Error ? error.message : String(error)) + ')' + evidenceNote();
654
+ }
655
+ }
656
+ /** Restore the cache payload snapshot. Returns an error detail or undefined.
657
+ *
658
+ * 2026-11-08 P1 ordering fix — the restore NEVER deletes the current payload
659
+ * before its replacement material is proven:
660
+ * 1. the pre-install backup must EXIST,
661
+ * 2. its content must digest-match the digest recorded at transaction open,
662
+ * 3. the restore is staged into an isolated temp dir and the STAGED copy is
663
+ * digest-verified,
664
+ * 4. only then is the current payload swapped out via renames (no window
665
+ * where the version dir is absent), and a failed second rename puts the
666
+ * current payload back in place.
667
+ * A missing or corrupted backup REFUSES the destructive step: the current
668
+ * payload is preserved as-is and the caller reports ROLLBACK_INCOMPLETE —
669
+ * it never claims the previous version was restored. */
670
+ function restoreWorkbuddyCacheSnapshot(txn) {
671
+ if (txn.cacheVersionDir === undefined)
672
+ return undefined;
673
+ if (txn.cacheDigestAfterRegistration === txn.cacheDigestBefore && txn.cacheExisted) {
674
+ // The registration left the cache byte-identical to its starting state:
675
+ // an unrelated later cache change is not PD's to roll back.
676
+ return undefined;
677
+ }
678
+ if (txn.cacheDigestAfterRegistration === undefined) {
679
+ return txn.cacheExisted ? 'cache: post-registration digest missing — restore skipped' : undefined;
680
+ }
681
+ let currentDigest;
682
+ try {
683
+ currentDigest = existsSync(txn.cacheVersionDir) ? workbuddyDigestTree(txn.cacheVersionDir) : 'absent';
684
+ }
685
+ catch {
686
+ return 'cache: unreadable during rollback';
687
+ }
688
+ if (currentDigest !== txn.cacheDigestAfterRegistration) {
689
+ return 'cache: changed after PD wrote it (concurrent modification) — restore skipped to avoid clobbering';
690
+ }
691
+ // No-change short-circuit: an already-registered fast-path install (or any
692
+ // run whose registration left the payload identical) has nothing to undo —
693
+ // skip the destructive rm+cp cycle entirely instead of risking a healthy
694
+ // cache on a no-op restore.
695
+ if (currentDigest === txn.cacheDigestBefore)
696
+ return undefined;
697
+ try {
698
+ if (txn.cacheExisted && txn.cacheDigestBefore !== undefined) {
699
+ // 1+2. Verify the backup BEFORE touching the current payload.
700
+ if (txn.cacheBackupDir === undefined) {
701
+ return 'cache: pre-install backup missing — the CURRENT payload is preserved untouched; restore refused';
702
+ }
703
+ let backupDigest;
704
+ try {
705
+ backupDigest = workbuddyDigestTree(txn.cacheBackupDir);
706
+ }
707
+ catch {
708
+ return 'cache: pre-install backup unreadable — the CURRENT payload is preserved untouched; restore refused';
709
+ }
710
+ if (backupDigest !== txn.cacheDigestBefore) {
711
+ return 'cache: pre-install backup digest mismatch — the CURRENT payload is preserved untouched; restore refused';
712
+ }
713
+ // 3. Stage the replacement material in isolation and verify the staged copy.
714
+ const cacheParent = path.dirname(path.resolve(txn.cacheVersionDir));
715
+ const staging = path.join(cacheParent, `.pd-restore-${process.pid}-${Date.now()}`);
716
+ try {
717
+ rmSync(staging, { recursive: true, force: true });
718
+ txn.cacheOps.copyDir(txn.cacheBackupDir, staging, { recursive: true });
719
+ if (workbuddyDigestTree(staging) !== txn.cacheDigestBefore) {
720
+ try {
721
+ rmSync(staging, { recursive: true, force: true });
722
+ }
723
+ catch { /* reported below */ }
724
+ return 'cache: staged restore material failed verification — the CURRENT payload is preserved untouched; restore refused';
725
+ }
726
+ }
727
+ catch (stagingError) {
728
+ try {
729
+ rmSync(staging, { recursive: true, force: true });
730
+ }
731
+ catch { /* reported below */ }
732
+ return 'cache: staging the restore material failed (' + (stagingError instanceof Error ? stagingError.message : String(stagingError)) + ') — the CURRENT payload is preserved untouched; restore refused';
733
+ }
734
+ // 4. Swap via renames — the version dir is never absent: current → discard, staged → live.
735
+ const discard = path.join(cacheParent, `.pd-discard-${process.pid}-${Date.now()}`);
736
+ try {
737
+ txn.cacheOps.rename(txn.cacheVersionDir, discard);
738
+ }
739
+ catch (setAsideError) {
740
+ try {
741
+ rmSync(staging, { recursive: true, force: true });
742
+ }
743
+ catch { /* inert residue */ }
744
+ return 'cache: could not set the current payload aside (' + (setAsideError instanceof Error ? setAsideError.message : String(setAsideError)) + ') — the CURRENT payload is preserved untouched; restore refused';
745
+ }
746
+ // Re-hash the directory AFTER it has been moved out of the live path.
747
+ // This catches a writer that changed the payload between the initial
748
+ // digest and rename; do not discard or replace bytes that were not the
749
+ // exact tree PD observed after registration.
750
+ let movedDigest;
751
+ try {
752
+ movedDigest = workbuddyDigestTree(discard);
753
+ }
754
+ catch (error) {
755
+ try {
756
+ if (!existsSync(txn.cacheVersionDir))
757
+ txn.cacheOps.rename(discard, txn.cacheVersionDir);
758
+ }
759
+ catch (restoreError) {
760
+ return 'cache: moved payload became unreadable during rollback (' +
761
+ (error instanceof Error ? error.message : String(error)) +
762
+ ') and could not be returned to its live path (' +
763
+ (restoreError instanceof Error ? restoreError.message : String(restoreError)) +
764
+ '); preserved at ' + discard;
765
+ }
766
+ try {
767
+ rmSync(staging, { recursive: true, force: true });
768
+ }
769
+ catch { /* inert residue */ }
770
+ return 'cache: moved payload became unreadable during rollback; current payload restored to its live path and replacement refused';
771
+ }
772
+ if (movedDigest !== txn.cacheDigestAfterRegistration) {
773
+ try {
774
+ if (!existsSync(txn.cacheVersionDir))
775
+ txn.cacheOps.rename(discard, txn.cacheVersionDir);
776
+ }
777
+ catch (restoreError) {
778
+ return 'cache: payload changed during rollback and could not be returned to its live path (' +
779
+ (restoreError instanceof Error ? restoreError.message : String(restoreError)) +
780
+ '); concurrent payload preserved at ' + discard;
781
+ }
782
+ try {
783
+ rmSync(staging, { recursive: true, force: true });
784
+ }
785
+ catch { /* inert residue */ }
786
+ return 'cache: payload changed during rollback after the initial digest check; current payload restored to its live path and replacement refused';
787
+ }
788
+ try {
789
+ txn.cacheOps.rename(staging, txn.cacheVersionDir);
790
+ }
791
+ catch (swapError) {
792
+ // Best effort: put the current payload back in place, never leave the
793
+ // version dir absent.
794
+ try {
795
+ txn.cacheOps.rename(discard, txn.cacheVersionDir);
796
+ try {
797
+ rmSync(staging, { recursive: true, force: true });
798
+ }
799
+ catch { /* inert residue */ }
800
+ return 'cache: restore swap failed (' + (swapError instanceof Error ? swapError.message : String(swapError)) + ') — the CURRENT payload was recovered in place';
801
+ }
802
+ catch (recoverError) {
803
+ return 'cache: restore swap failed (' + (swapError instanceof Error ? swapError.message : String(swapError)) + ') and the current payload could NOT be recovered in place (' + (recoverError instanceof Error ? recoverError.message : String(recoverError)) + '); the previous current payload is preserved at ' + discard;
804
+ }
805
+ }
806
+ try {
807
+ rmSync(discard, { recursive: true, force: true });
808
+ }
809
+ catch { /* inert residue, named below if it matters */ }
810
+ if (workbuddyDigestTree(txn.cacheVersionDir) !== txn.cacheDigestBefore) {
811
+ return 'cache: restored payload digest mismatch — previous version may be unusable';
812
+ }
813
+ return undefined;
814
+ }
815
+ else {
816
+ // Fresh install: PD created this payload, so removal is eligible — but
817
+ // still never rmSync a LIVE tree blindly. Move it aside, re-hash the
818
+ // moved tree and only delete the exact payload PD left there. A host
819
+ // writer that added/changed files between the first digest and this step
820
+ // is preserved and reported instead of silently erased.
821
+ const cacheParent = path.dirname(path.resolve(txn.cacheVersionDir));
822
+ const discard = path.join(cacheParent, `.pd-discard-${process.pid}-${Date.now()}`);
823
+ renameSync(txn.cacheVersionDir, discard);
824
+ let movedDigest;
825
+ try {
826
+ movedDigest = workbuddyDigestTree(discard);
827
+ }
828
+ catch (error) {
829
+ try {
830
+ if (!existsSync(txn.cacheVersionDir))
831
+ txn.cacheOps.rename(discard, txn.cacheVersionDir);
832
+ return 'cache: moved payload became unreadable during rollback; deletion refused';
833
+ }
834
+ catch (restoreError) {
835
+ return 'cache: moved payload became unreadable during rollback (' +
836
+ (error instanceof Error ? error.message : String(error)) + ') and could not be returned to its live path (' +
837
+ (restoreError instanceof Error ? restoreError.message : String(restoreError)) + '); preserved at ' + discard;
838
+ }
839
+ }
840
+ if (movedDigest !== txn.cacheDigestAfterRegistration) {
841
+ try {
842
+ if (!existsSync(txn.cacheVersionDir))
843
+ txn.cacheOps.rename(discard, txn.cacheVersionDir);
844
+ return 'cache: payload changed during rollback; current payload restored to its live path and deletion refused';
845
+ }
846
+ catch (restoreError) {
847
+ return 'cache: payload changed during rollback and could not be returned to its live path (' +
848
+ (restoreError instanceof Error ? restoreError.message : String(restoreError)) + '); concurrent payload preserved at ' + discard;
849
+ }
850
+ }
851
+ try {
852
+ rmSync(discard, { recursive: true, force: true });
853
+ }
854
+ catch (deleteError) {
855
+ // No live path is missing data here — but never lose the bytes: put the
856
+ // verified PD payload back where it was and report the residue.
857
+ try {
858
+ txn.cacheOps.rename(discard, txn.cacheVersionDir);
859
+ }
860
+ catch { /* preserved at discard, named below */ }
861
+ return 'cache: could not delete the PD-created payload (' +
862
+ (deleteError instanceof Error ? deleteError.message : String(deleteError)) +
863
+ '); it was preserved at ' + discard;
864
+ }
865
+ }
866
+ return undefined;
867
+ }
868
+ catch (error) {
869
+ return 'cache: restore failed (' + (error instanceof Error ? error.message : String(error)) + ')';
870
+ }
871
+ }
872
+ function inspectWorkbuddyCacheEvidence(txn) {
873
+ if (!txn.cacheExisted || txn.cacheDigestAfterRegistration === txn.cacheDigestBefore) {
874
+ return { state: 'not-required' };
875
+ }
876
+ if (txn.cacheBackupDir === undefined || !existsSync(txn.cacheBackupDir)) {
877
+ return { state: 'missing', ...(txn.cacheBackupDir !== undefined ? { path: txn.cacheBackupDir } : {}) };
878
+ }
879
+ try {
880
+ if (txn.cacheDigestBefore === undefined || workbuddyDigestTree(txn.cacheBackupDir) !== txn.cacheDigestBefore) {
881
+ return { state: 'corrupt', path: txn.cacheBackupDir };
882
+ }
883
+ return { state: 'available', path: txn.cacheBackupDir };
884
+ }
885
+ catch (error) {
886
+ return {
887
+ state: 'unreadable',
888
+ path: txn.cacheBackupDir,
889
+ detail: error instanceof Error ? error.message : String(error),
890
+ };
891
+ }
892
+ }
893
+ /** Reverse-order, byte-guarded restore of every surface this transaction touched.
894
+ *
895
+ * The write order is: registration (settings/registry + cache) → governance
896
+ * init config → runtime profile → install manifest → governance flags.
897
+ * `writtenPaths` is appended in that exact order, so the reverse loop below
898
+ * restores the LATEST stages first. The cache belongs to the EARLIEST
899
+ * (registration) stage and is therefore undone LAST — after the registration
900
+ * files that point at it have been proven restorable. That dependency order
901
+ * is deliberate: deleting/swapping a cache while a registration still points
902
+ * at it would leave a dangling plugin, which is a worse outcome than a
903
+ * strict timestamp reversal. */
904
+ function compensateWorkbuddyInstall(txn, unprovenRegistration) {
905
+ const errors = [];
906
+ // When post-registration baselines could not be pinned, nothing may be
907
+ // claimed as restored. Force a partial-rollback verdict (which also keeps
908
+ // every evidence directory) instead of a false "fully restored".
909
+ if (unprovenRegistration !== undefined)
910
+ errors.push('registration: ' + unprovenRegistration);
911
+ // 1. Later-stage file writes, reverse chronological (latest first), deduped.
912
+ const seen = new Set();
913
+ for (let index = txn.writtenPaths.length - 1; index >= 0; index--) {
914
+ const rawPath = txn.writtenPaths[index];
915
+ if (rawPath === undefined)
916
+ continue;
917
+ if (seen.has(rawPath))
918
+ continue;
919
+ seen.add(rawPath);
920
+ const filePath = rawPath;
921
+ // The governance config inside a workspace CREATED by this attempt is
922
+ // part of the preserved fresh workspace (never auto-deleted) — skip the
923
+ // byte restore, report the preserved dir instead.
924
+ if (filePath === path.join(txn.governanceDir, '.pd', 'config.yaml') && !txn.governanceDirExistedBefore)
925
+ continue;
926
+ const error = restoreWorkbuddyFileSnapshot(txn, filePath);
927
+ if (error !== undefined)
928
+ errors.push(error);
929
+ }
930
+ // 2. The registry is the pointer to the cache. If a concurrent host edit
931
+ // blocked registry/settings recovery, deleting the cache would produce a
932
+ // dangling registration. Preserve the cache and report partial rollback.
933
+ const registrationRestoreFailed = errors.some((error) => error.startsWith(txn.settingsPath + ':') || error.startsWith(txn.registryPath + ':'));
934
+ if (registrationRestoreFailed) {
935
+ errors.push('cache: preserved because host registration/settings could not be safely restored');
936
+ }
937
+ else {
938
+ const cacheError = restoreWorkbuddyCacheSnapshot(txn);
939
+ if (cacheError !== undefined)
940
+ errors.push(cacheError);
941
+ }
942
+ // 3. Evidence retention: discard cache evidence only after every tracked
943
+ // surface is restored. A partial rollback keeps the backup and any
944
+ // original file snapshots needed for manual recovery.
945
+ if (errors.length === 0 && txn.cacheBackupDir !== undefined) {
946
+ try {
947
+ rmSync(txn.cacheBackupDir, { recursive: true, force: true });
948
+ }
949
+ catch { /* inert recovery copy; success state remains restored */ }
950
+ }
951
+ const cacheEvidence = inspectWorkbuddyCacheEvidence(txn);
952
+ // Verifiable recovery evidence: every skipped original is listed with its
953
+ // exact snapshot file and SHA-256, so the Owner can prove the bytes instead
954
+ // of trusting a directory name. Records for files that did not exist before
955
+ // the transaction carry no snapshot bytes by construction.
956
+ const evidenceManifest = txn.fileEvidenceDir !== undefined
957
+ ? path.join(txn.fileEvidenceDir, 'manifest.json')
958
+ : undefined;
959
+ const fileRecords = txn.fileEvidenceRecords.map((record) => record.originalPath + (record.snapshotFile !== undefined && record.sha256 !== undefined
960
+ ? ' -> ' + record.snapshotFile + ' (sha256=' + record.sha256 + ', existed=' + record.existed + ')'
961
+ : ' (absent before install: PD-created file, no original bytes)'));
962
+ const fileEvidenceNote = txn.fileEvidenceDir !== undefined
963
+ ? 'Original host-file snapshots preserved at ' + txn.fileEvidenceDir +
964
+ ' (manifest ' + (evidenceManifest ?? 'unavailable') + '): ' +
965
+ (fileRecords.length > 0 ? fileRecords.join(' | ') : 'no records') + '.'
966
+ : '';
967
+ const cacheEvidenceNote = cacheEvidence.state === 'available'
968
+ ? 'Verified pre-install cache snapshot preserved at ' + cacheEvidence.path + '.'
969
+ : cacheEvidence.state === 'missing'
970
+ ? 'Pre-install cache snapshot is MISSING' + (cacheEvidence.path !== undefined ? ' at ' + cacheEvidence.path : '') + '; do not rely on a cache backup.'
971
+ : cacheEvidence.state === 'corrupt'
972
+ ? 'Pre-install cache snapshot is CORRUPT at ' + cacheEvidence.path + '; do not rely on it.'
973
+ : cacheEvidence.state === 'unreadable'
974
+ ? 'Pre-install cache snapshot is UNREADABLE at ' + cacheEvidence.path + ' (' + cacheEvidence.detail + '); do not rely on it.'
975
+ : '';
976
+ const evidenceNotes = [cacheEvidenceNote, fileEvidenceNote].filter((note) => note.length > 0).join(' ');
977
+ const governanceNote = txn.governanceDirExistedBefore
978
+ ? 'The pre-existing governance workspace was preserved (only PD flag/profile edits were eligible for rollback).'
979
+ : 'The governance workspace created by this attempt is PRESERVED at ' + txn.governanceDir + ' (never auto-deleted; it may hold runtime-init databases) — remove it manually only after review or re-run the installer to complete initialization.';
980
+ const complete = errors.length === 0;
981
+ return {
982
+ complete,
983
+ summary: complete
984
+ ? 'Previous cache and registration state restored.'
985
+ : 'ROLLBACK_INCOMPLETE: ' + errors.join('; ') + (evidenceNotes.length > 0 ? '. ' + evidenceNotes : '. No verified recovery evidence is currently available.'),
986
+ nextAction: complete
987
+ ? 'Fix the reported cause and re-run the installer (idempotent).'
988
+ : 'Do not treat the WorkBuddy plugin as installed or usable. ' +
989
+ (cacheEvidence.state === 'available' ? 'The verified previous cache is at ' + cacheEvidence.path + '. ' : '') +
990
+ (evidenceManifest !== undefined ? 'Original host-file snapshots with SHA-256 values and their manifest are at ' + evidenceManifest + ' (directory ' + txn.fileEvidenceDir + '). ' : '') +
991
+ 'If a required evidence set is missing, unreadable, or corrupt, do not attempt an automatic restore from it; reconcile the listed surfaces manually before re-running the installer. ' +
992
+ 'A concurrent write inside the final read-then-rename window cannot be ruled out on portable filesystems; verify each named file against its snapshot before treating the rollback as complete.',
993
+ governanceNote,
994
+ };
995
+ }
377
996
  export function findWorkbuddyPluginPayload(pluginDir, runtimeAdapterDir) {
378
997
  for (const root of [path.join(pluginDir, 'workbuddy-adapter', 'plugin'), path.join(runtimeAdapterDir, 'plugin')]) {
379
998
  const manifestPath = path.join(root, '.codebuddy-plugin', 'plugin.json');
@@ -443,7 +1062,7 @@ function readInstallJsonRecord(manifestPath) {
443
1062
  * channel/autoCheck/releaseMetadataUrl — PRI-709 P0-1) are carried through.
444
1063
  * Malformed existing manifest → hard stop, zero modification.
445
1064
  */
446
- export function mergeWorkbuddyIntoInstallManifest(manifestPath, governanceDir) {
1065
+ export function mergeWorkbuddyIntoInstallManifest(manifestPath, governanceDir, atomicReplace = atomicReplaceTextFile) {
447
1066
  let current;
448
1067
  let existed = false;
449
1068
  try {
@@ -485,16 +1104,28 @@ export function mergeWorkbuddyIntoInstallManifest(manifestPath, governanceDir) {
485
1104
  hosts,
486
1105
  workspaces,
487
1106
  };
1107
+ const writtenContent = JSON.stringify(payload, null, 2) + '\n';
488
1108
  try {
489
1109
  mkdirSync(path.dirname(manifestPath), { recursive: true });
490
- writeFileSync(manifestPath, JSON.stringify(payload, null, 2) + '\n', 'utf-8');
491
- return { ok: true };
1110
+ // Atomic replace (temp + rename): a mid-write ENOSPC/EPERM must leave the
1111
+ // previous manifest intact. A committed rename followed by temp cleanup
1112
+ // failure is different: the new bytes are live and must enter compensation.
1113
+ atomicReplace(manifestPath, writtenContent);
1114
+ return { ok: true, writtenContent };
492
1115
  }
493
1116
  catch (error) {
1117
+ const committed = error instanceof AtomicReplaceCleanupError && error.committed;
494
1118
  return {
495
1119
  ok: false,
496
- reason: `install_manifest_write_failed: ${manifestPath} could not be written (${error instanceof Error ? error.message : String(error)}).`,
497
- nextAction: `Check permissions on ~/.pd and re-run the installer.`,
1120
+ reason: committed
1121
+ ? `install_manifest_write_committed_but_cleanup_failed: ${manifestPath} was already replaced (${error instanceof Error ? error.message : String(error)}).`
1122
+ : `install_manifest_write_failed: ${manifestPath} could not be written (${error instanceof Error ? error.message : String(error)}). The previous manifest was left unchanged.`,
1123
+ nextAction: committed
1124
+ ? `Check permissions on ~/.pd; the manifest was changed and must enter rollback before re-running the installer.`
1125
+ : `Check permissions on ~/.pd and re-run the installer.`,
1126
+ // The rename committed: these bytes ARE live. The caller MUST register
1127
+ // the write or compensation will leave a changed manifest behind (P1).
1128
+ ...(committed ? { committed: true, writtenContent } : {}),
498
1129
  };
499
1130
  }
500
1131
  }
@@ -869,6 +1500,7 @@ function applyFeatureFlagLineEdit(raw, request) {
869
1500
  */
870
1501
  export function ensureWorkbuddyGovernanceEnabled(governanceDir, options = {}) {
871
1502
  const persist = options.persist !== false;
1503
+ const atomicReplace = options.atomicReplace ?? atomicReplaceTextFile;
872
1504
  const configPath = path.join(governanceDir, '.pd', 'config.yaml');
873
1505
  let rawText;
874
1506
  try {
@@ -951,12 +1583,24 @@ export function ensureWorkbuddyGovernanceEnabled(governanceDir, options = {}) {
951
1583
  const finalKeyword = isRecord(finalFeatures) ? finalFeatures.workbuddy_live_keyword_pain : undefined;
952
1584
  const keywordPainEnabled = isRecord(finalKeyword) && finalKeyword.enabled === true;
953
1585
  try {
954
- atomicReplaceTextFile(configPath, next);
1586
+ atomicReplace(configPath, next);
955
1587
  }
956
- catch {
1588
+ catch (error) {
1589
+ // COMMITTED-BUT-CLEANUP-FAILED is a real write: the new bytes are live.
1590
+ // Reporting a plain "write failed" here would leave the changed config out
1591
+ // of the transaction, so compensation would never restore it (P1).
1592
+ if (error instanceof AtomicReplaceCleanupError && error.committed) {
1593
+ return {
1594
+ ok: false, configPath,
1595
+ reason: `fresh_workbuddy_flag_write_committed_but_cleanup_failed: ${error.message}`,
1596
+ nextAction: 'Repair config storage and retry; the governance config was already changed and must be rolled back.',
1597
+ hostExplicitOff, keywordExplicitOff, keywordPainEnabled,
1598
+ changed: true, committed: true, writtenContent: next,
1599
+ };
1600
+ }
957
1601
  return { ok: false, reason: 'fresh_workbuddy_flag_write_failed', nextAction: 'Repair config storage and retry.', hostExplicitOff, keywordExplicitOff, keywordPainEnabled, changed: false };
958
1602
  }
959
- return { ok: true, configPath, enabled: !hostExplicitOff, hostExplicitOff, keywordExplicitOff, keywordPainEnabled, changed: true };
1603
+ return { ok: true, configPath, enabled: !hostExplicitOff, hostExplicitOff, keywordExplicitOff, keywordPainEnabled, changed: true, writtenContent: next };
960
1604
  }
961
1605
  /**
962
1606
  * The single plugin-state judgment: registration (registry) and enablement
@@ -965,6 +1609,14 @@ export function ensureWorkbuddyGovernanceEnabled(governanceDir, options = {}) {
965
1609
  * exactly one implementation.
966
1610
  */
967
1611
  export function readWorkbuddyPluginState(p) {
1612
+ // Pinned mirror of install-layout's interpretWorkbuddyPluginState — the
1613
+ // shared judgment pd-cli health applies. A CI parity test
1614
+ // (workbuddy-plugin-state-parity.test.ts) pins the two implementations to
1615
+ // identical outputs on a fixture matrix; a runtime import cannot exist
1616
+ // here because the packaged installer must keep loading against the
1617
+ // PUBLISHED install-layout (registry-parity smoke, PRI-669/RF-02; the
1618
+ // release-intent guard N-version forbids raising the version floor in a
1619
+ // normal PR).
968
1620
  const registry = readHostJsonFile(p.registryPath);
969
1621
  const registered = registry.ok && registry.existed && isRecord(registry.value.plugins)
970
1622
  ? Object.hasOwn(registry.value.plugins, WORKBUDDY_PLUGIN_KEY)
@@ -1157,7 +1809,7 @@ const GOVERNANCE_PROFILE_ID = 'pd.default';
1157
1809
  * Module-private: the only writer/reader is install() below (step 6.5); the
1158
1810
  * regression suite exercises it through the REAL install() boundary.
1159
1811
  */
1160
- function applyWorkbuddyGovernanceRuntimeProfile(governanceDir, profile) {
1812
+ function applyWorkbuddyGovernanceRuntimeProfile(governanceDir, profile, atomicReplace = atomicReplaceTextFile) {
1161
1813
  // rc-1/rc-3: validate here — upstream CLI validation is not trusted as a
1162
1814
  // substitute for a guard at the write boundary.
1163
1815
  const provider = typeof profile.provider === 'string' ? profile.provider.trim() : '';
@@ -1351,16 +2003,27 @@ function applyWorkbuddyGovernanceRuntimeProfile(governanceDir, profile) {
1351
2003
  }
1352
2004
  try {
1353
2005
  mkdirSync(path.dirname(configPath), { recursive: true });
1354
- atomicReplaceTextFile(configPath, next);
2006
+ atomicReplace(configPath, next);
1355
2007
  }
1356
2008
  catch (error) {
2009
+ // A committed rename with a failed temp cleanup is NOT "left unchanged".
2010
+ // Surface the committed bytes so the install transaction registers the
2011
+ // write and compensation can restore the previous config (P1).
2012
+ if (error instanceof AtomicReplaceCleanupError && error.committed) {
2013
+ return {
2014
+ ok: false,
2015
+ reason: `workbuddy_governance_profile_write_committed_but_cleanup_failed: ${configPath} was already replaced (${error.message}).`,
2016
+ nextAction: `Check permissions under ${path.dirname(configPath)}; the governance config was changed and must enter rollback.`,
2017
+ committed: true, writtenContent: next, configPath,
2018
+ };
2019
+ }
1357
2020
  return {
1358
2021
  ok: false,
1359
2022
  reason: `workbuddy_governance_profile_write_failed: could not write ${configPath} (${error instanceof Error ? error.message : String(error)}). The previous governance config was left unchanged.`,
1360
2023
  nextAction: `Check permissions under ${path.dirname(configPath)}, close tools holding the file, then re-run the installer.`,
1361
2024
  };
1362
2025
  }
1363
- return { ok: true, configPath, profileId: GOVERNANCE_PROFILE_ID, model, pendingAgents };
2026
+ return { ok: true, configPath, writtenContent: next, profileId: GOVERNANCE_PROFILE_ID, model, pendingAgents };
1364
2027
  }
1365
2028
  // ─── WorkBuddyHostInstaller ─────────────────────────────────────────────────
1366
2029
  /** Shared Git Bash failure message (win32 hooks launch through bash). */
@@ -1531,6 +2194,10 @@ export class WorkBuddyHostInstaller {
1531
2194
  const entry = path.join(getInstallLayoutPaths(homeDir()).pdCliDir, 'dist', 'index.js');
1532
2195
  return existsSync(entry) ? entry : undefined;
1533
2196
  }),
2197
+ backupCopyDir: deps.backupCopyDir ?? cpSync,
2198
+ atomicReplaceConfig: deps.atomicReplaceConfig ?? atomicReplaceTextFile,
2199
+ beforeCompensation: deps.beforeCompensation ?? (() => undefined),
2200
+ cacheRollbackOps: deps.cacheRollbackOps ?? { copyDir: cpSync, rename: renameSync },
1534
2201
  runCommand: deps.runCommand ?? ((file, args, opts) => {
1535
2202
  const result = spawnSync(file, [...args], {
1536
2203
  encoding: 'utf-8',
@@ -1678,8 +2345,79 @@ export class WorkBuddyHostInstaller {
1678
2345
  // unaffected when the MCP component is missing or the write fails.
1679
2346
  const mcpBinding = writeWorkbuddyMcpBinding(p.marketplaceRoot, this.deps.homeDir());
1680
2347
  // 5. Register: engine commands first; observable direct-write fallback.
2348
+ // 2026-11-07: before this FIRST host-visible mutation the install
2349
+ // transaction snapshots every PD-owned mutation target; a failure in
2350
+ // any LATER stage compensates in reverse order (see
2351
+ // compensateWorkbuddyInstall). Registration-internal failures keep
2352
+ // their own established rollback (directWriteRegistration).
2353
+ // 2026-11-08 P1: opening the transaction can itself refuse the
2354
+ // upgrade — a pre-existing cache whose backup cannot be proven
2355
+ // restorable aborts the install BEFORE any cache replacement.
2356
+ const atomicReplaceConfig = this.deps.atomicReplaceConfig ?? atomicReplaceTextFile;
2357
+ const opened = openWorkbuddyInstallTxn(p, payload.version, {
2358
+ copyDir: this.deps.backupCopyDir,
2359
+ atomicReplace: atomicReplaceConfig,
2360
+ cacheOps: this.deps.cacheRollbackOps,
2361
+ });
2362
+ if (!opened.ok) {
2363
+ // Zero mutations so far (snapshots are read-only; the unusable backup
2364
+ // copy was already cleaned up inside the opener) — report and stop.
2365
+ return {
2366
+ success: false,
2367
+ hostId: this.hostId,
2368
+ configPath: p.settingsPath,
2369
+ configAction: 'skipped',
2370
+ reason: opened.reason,
2371
+ nextAction: opened.nextAction,
2372
+ };
2373
+ }
2374
+ const { txn } = opened;
2375
+ // Compensated failure: roll this transaction back, then report the
2376
+ // original cause TOGETHER WITH the verified rollback outcome (rc-9:
2377
+ // "restored" is only claimed after real state verification).
2378
+ // `unprovenRegistration` forces an honest partial-rollback verdict when
2379
+ // the post-registration baselines could not be pinned.
2380
+ const compensated = (cause, settingsAction, unprovenRegistration) => {
2381
+ // Deterministic non-cooperating host/Owner write seam: lands AFTER the
2382
+ // install stages and BEFORE the first rollback read (concurrency tests).
2383
+ try {
2384
+ this.deps.beforeCompensation?.();
2385
+ }
2386
+ catch { /* seam must not mask the real rollback */ }
2387
+ const rollback = compensateWorkbuddyInstall(txn, unprovenRegistration);
2388
+ return {
2389
+ success: false,
2390
+ hostId: this.hostId,
2391
+ configPath: p.settingsPath,
2392
+ configAction: settingsAction,
2393
+ reason: cause.reason + ' ' + rollback.summary + ' ' + rollback.governanceNote,
2394
+ nextAction: rollback.complete ? cause.nextAction : rollback.nextAction,
2395
+ };
2396
+ };
1681
2397
  const registration = this.registerPlugin(details, payload.version, payload.defaultEnabled);
1682
2398
  if (!registration.ok) {
2399
+ if (registration.committed === true) {
2400
+ // Engine registration already COMMITTED before a later engine-stage
2401
+ // read/write failed (review #13). Pin what is on disk, then run the
2402
+ // protected compensation instead of keeping a half-installed plugin.
2403
+ let unproven;
2404
+ try {
2405
+ captureWorkbuddyPostRegistration(txn, p, 'engine');
2406
+ }
2407
+ catch {
2408
+ unproven = 'engine registration committed but its post-registration state could not be pinned; manual reconciliation is required';
2409
+ }
2410
+ return compensated(registration, registration.settingsAction ?? 'updated', unproven);
2411
+ }
2412
+ // Registration-internal failures ran their own established rollback
2413
+ // (directWriteRegistration). The transaction never started mutating —
2414
+ // discard the evidence copy so this attempt leaves no residue.
2415
+ if (txn.cacheBackupDir !== undefined) {
2416
+ try {
2417
+ rmSync(txn.cacheBackupDir, { recursive: true, force: true });
2418
+ }
2419
+ catch { /* best effort */ }
2420
+ }
1683
2421
  return {
1684
2422
  success: false,
1685
2423
  hostId: this.hostId,
@@ -1689,23 +2427,48 @@ export class WorkBuddyHostInstaller {
1689
2427
  nextAction: registration.nextAction,
1690
2428
  };
1691
2429
  }
2430
+ try {
2431
+ captureWorkbuddyPostRegistration(txn, p, registration.mode);
2432
+ }
2433
+ catch (error) {
2434
+ // Missing/opaque post-registration evidence must not silently proceed:
2435
+ // registration may have changed files but their new ownership is unproven.
2436
+ // Force an incomplete verdict (which KEEPS all recovery evidence).
2437
+ return compensated({
2438
+ reason: 'workbuddy_registration_snapshot_failed: could not verify post-registration state (' +
2439
+ (error instanceof Error ? error.message : String(error)) + ').',
2440
+ nextAction: 'Inspect WorkBuddy settings, registry and plugin cache; do not assume registration was rolled back.',
2441
+ }, registration.settingsAction, 'post-registration state could not be pinned; registration rollback is UNPROVEN');
2442
+ }
1692
2443
  // 6. Initialize the governance workspace (OD-07 explicit creation) with
1693
2444
  // the FULL loader-valid state the hook/console/worker chain reads:
1694
2445
  // .pd/config.yaml, .pd/state.db and the canonical .state/trajectory.db
1695
2446
  // schema. Review 2026-10-13 R1: this step previously only mkdir'd the
1696
2447
  // directory, so install reported success while the hook chain saw an
1697
2448
  // uninitialized workspace.
1698
- const governance = this.initializeGovernanceWorkspace(p.governanceDir);
2449
+ const governanceConfigPath = path.join(p.governanceDir, '.pd', 'config.yaml');
2450
+ // A governance workspace that existed BEFORE this install but had no
2451
+ // config.yaml gets one created here. That file is a real PD write and MUST
2452
+ // enter the transaction: otherwise a later-stage failure leaves it behind
2453
+ // while the report claims the workspace was untouched (review #14).
2454
+ const recordGovernanceInitWrite = () => {
2455
+ const before = txn.fileSnapshots.get(governanceConfigPath);
2456
+ if (before === undefined || before.existed)
2457
+ return;
2458
+ const after = snapshotWorkbuddyFile(governanceConfigPath);
2459
+ if (after.existed && after.bytes !== undefined) {
2460
+ recordWorkbuddyTxnWrite(txn, governanceConfigPath, after.bytes);
2461
+ }
2462
+ };
2463
+ const governance = this.initializeGovernanceWorkspace(p.governanceDir, atomicReplaceConfig);
1699
2464
  if (!governance.ok) {
1700
- return {
1701
- success: false,
1702
- hostId: this.hostId,
1703
- configPath: p.settingsPath,
1704
- configAction: registration.settingsAction,
1705
- reason: governance.reason,
1706
- nextAction: governance.nextAction,
1707
- };
2465
+ // B2 row 2: a governance-init failure must not strand the just-completed
2466
+ // registration — restore the pre-registration host state. Even a failed
2467
+ // initializer may have created the config before failing on the DB step.
2468
+ recordGovernanceInitWrite();
2469
+ return compensated(governance, registration.settingsAction);
1708
2470
  }
2471
+ recordGovernanceInitWrite();
1709
2472
  // 6.5 Round-3 remediation P1: the install-collected LLM runtime profile
1710
2473
  // (--provider/--api-key-env/--model) is GOVERNANCE state for this
1711
2474
  // host — it must land in the governance workspace config the
@@ -1720,17 +2483,17 @@ export class WorkBuddyHostInstaller {
1720
2483
  let profileNote = '';
1721
2484
  let profilePendingAgents = [];
1722
2485
  if (ctx.runtimeProfile) {
1723
- const applied = applyWorkbuddyGovernanceRuntimeProfile(p.governanceDir, ctx.runtimeProfile);
2486
+ const applied = applyWorkbuddyGovernanceRuntimeProfile(p.governanceDir, ctx.runtimeProfile, atomicReplaceConfig);
1724
2487
  if (!applied.ok) {
1725
- return {
1726
- success: false,
1727
- hostId: this.hostId,
1728
- configPath: p.settingsPath,
1729
- configAction: registration.settingsAction,
1730
- reason: applied.reason,
1731
- nextAction: applied.nextAction,
1732
- };
2488
+ // A committed rename + failed temp cleanup IS a write. Register the
2489
+ // bytes that are already live BEFORE compensating (P1: never let a
2490
+ // changed config be missing from the transaction record).
2491
+ if (applied.committed === true && applied.configPath !== undefined && applied.writtenContent !== undefined) {
2492
+ recordWorkbuddyTxnWrite(txn, applied.configPath, applied.writtenContent);
2493
+ }
2494
+ return compensated(applied, registration.settingsAction);
1733
2495
  }
2496
+ recordWorkbuddyTxnWrite(txn, applied.configPath, snapshotWorkbuddyFile(applied.configPath).bytes ?? applied.writtenContent);
1734
2497
  profileNote = ` LLM runtime profile '${applied.profileId}' (provider ${ctx.runtimeProfile.provider}, model ${applied.model}) written to ${applied.configPath}.`;
1735
2498
  if (applied.pendingAgents.length > 0) {
1736
2499
  profilePendingAgents = applied.pendingAgents;
@@ -1738,28 +2501,49 @@ export class WorkBuddyHostInstaller {
1738
2501
  }
1739
2502
  }
1740
2503
  // 7. Record host + governance workspace in the install manifest (set union).
1741
- const manifest = mergeWorkbuddyIntoInstallManifest(p.installManifestPath, p.governanceDir);
2504
+ const manifest = mergeWorkbuddyIntoInstallManifest(p.installManifestPath, p.governanceDir, atomicReplaceConfig);
1742
2505
  if (!manifest.ok) {
1743
- return {
1744
- success: false,
1745
- hostId: this.hostId,
1746
- configPath: p.settingsPath,
1747
- configAction: registration.settingsAction,
1748
- reason: manifest.reason,
1749
- nextAction: manifest.nextAction,
1750
- };
2506
+ // The rename may have committed while temp-dir cleanup failed. Those
2507
+ // bytes ARE live: register them so the reverse-order restore removes
2508
+ // the new manifest instead of reporting a clean rollback (review #12).
2509
+ if (manifest.committed === true && manifest.writtenContent !== undefined) {
2510
+ recordWorkbuddyTxnWrite(txn, p.installManifestPath, manifest.writtenContent);
2511
+ }
2512
+ return compensated(manifest, registration.settingsAction);
1751
2513
  }
2514
+ recordWorkbuddyTxnWrite(txn, p.installManifestPath, snapshotWorkbuddyFile(p.installManifestPath).bytes ?? manifest.writtenContent);
1752
2515
  // 8. Install ⇒ governance ON by default (PRI-1064, Owner directive
1753
2516
  // 2026-10-31): the ONLY preserved-off state is an explicit opt-out the
1754
2517
  // Owner wrote (enabled: false). Sparse/legacy configs left OFF by a
1755
2518
  // failed install round are turned ON here — an install that ends with
1756
2519
  // every hook skipping (host.workbuddy_disabled) is the P1 defect this
1757
2520
  // replaces. The summary line below always states the effective state.
1758
- const governanceConfigExists = existsSync(path.join(p.governanceDir, '.pd', 'config.yaml'));
1759
- const governanceDefaults = governanceConfigExists ? ensureWorkbuddyGovernanceEnabled(p.governanceDir) : null;
2521
+ const governanceConfigExists = existsSync(governanceConfigPath);
2522
+ const governanceDefaults = governanceConfigExists
2523
+ ? ensureWorkbuddyGovernanceEnabled(p.governanceDir, { atomicReplace: atomicReplaceConfig })
2524
+ : null;
1760
2525
  if (governanceDefaults !== null && !governanceDefaults.ok) {
1761
- return { success: false, hostId: this.hostId, configPath: p.settingsPath,
1762
- configAction: registration.settingsAction, reason: governanceDefaults.reason, nextAction: governanceDefaults.nextAction };
2526
+ // B2 row 5: a governance-flag failure compensates EVERYTHING this
2527
+ // transaction changed, in reverse order. A committed-cleanup failure is
2528
+ // a real write and must be registered first.
2529
+ if (governanceDefaults.committed === true && governanceDefaults.configPath !== undefined && governanceDefaults.writtenContent !== undefined) {
2530
+ recordWorkbuddyTxnWrite(txn, governanceDefaults.configPath, governanceDefaults.writtenContent);
2531
+ }
2532
+ return compensated(governanceDefaults, registration.settingsAction);
2533
+ }
2534
+ // Only an ACTUAL change enters the transaction. An already-correct config
2535
+ // is byte-identical and must never be attributed to PD (an Owner edit in
2536
+ // the meantime would otherwise be clobbered by the rollback).
2537
+ if (governanceDefaults !== null && governanceDefaults.changed && governanceDefaults.configPath !== undefined) {
2538
+ recordWorkbuddyTxnWrite(txn, governanceDefaults.configPath, snapshotWorkbuddyFile(governanceDefaults.configPath).bytes ?? governanceDefaults.writtenContent ?? '');
2539
+ }
2540
+ // The install has committed: the transaction evidence copy is stale —
2541
+ // discard it so a successful install leaves no residue.
2542
+ if (txn.cacheBackupDir !== undefined) {
2543
+ try {
2544
+ rmSync(txn.cacheBackupDir, { recursive: true, force: true });
2545
+ }
2546
+ catch { /* best effort; a locked copy is inert */ }
1763
2547
  }
1764
2548
  const governanceDefaultsNote = describeGovernanceDefaults(governanceDefaults, p.governanceDir);
1765
2549
  const effectiveNote = 'Registration takes effect in NEW WorkBuddy sessions (or /reload-plugins in a running CLI session).';
@@ -1812,7 +2596,7 @@ export class WorkBuddyHostInstaller {
1812
2596
  * database initialization as an observable skip with an explicit next
1813
2597
  * action — never a silent mkdir-only "success".
1814
2598
  */
1815
- initializeGovernanceWorkspace(governanceDir) {
2599
+ initializeGovernanceWorkspace(governanceDir, atomicReplace = atomicReplaceTextFile) {
1816
2600
  try {
1817
2601
  mkdirSync(governanceDir, { recursive: true });
1818
2602
  }
@@ -1851,7 +2635,7 @@ export class WorkBuddyHostInstaller {
1851
2635
  if (!existsSync(configPath)) {
1852
2636
  try {
1853
2637
  mkdirSync(path.dirname(configPath), { recursive: true });
1854
- atomicReplaceTextFile(configPath, generateConfigYamlContent());
2638
+ atomicReplace(configPath, generateConfigYamlContent());
1855
2639
  }
1856
2640
  catch (error) {
1857
2641
  return {
@@ -1909,7 +2693,11 @@ export class WorkBuddyHostInstaller {
1909
2693
  // an Owner-chosen true/false from before the install.
1910
2694
  const applied = this.applyInstalledEnabledValue(installedEnabled.value);
1911
2695
  if (!applied.ok) {
1912
- return { ok: false, reason: applied.reason, nextAction: applied.nextAction };
2696
+ // Engine registration (marketplace add + plugin install) already
2697
+ // COMMITTED. A failure here must not leave it installed; flag it
2698
+ // so install() runs protected compensation instead of just
2699
+ // discarding the transaction evidence (review #13).
2700
+ return { ok: false, reason: applied.reason, nextAction: applied.nextAction, committed: true, settingsAction: 'updated' };
1913
2701
  }
1914
2702
  return {
1915
2703
  ok: true,