create-principles-disciple 1.147.18 → 1.148.1
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.
- package/_release/product-identity.json +1 -1
- package/codex-adapter/package.json +1 -1
- package/console/dist/server/config/pd-config-store.js +6 -6
- package/console/dist/server/index.d.ts +20 -0
- package/console/dist/server/index.js +104 -84
- package/console/dist/server/models/ApprovalsConsoleModel.d.ts +1 -1
- package/console/dist/server/models/ApprovalsConsoleModel.js +5 -2
- package/console/dist/server/models/GovernanceExperienceCollector.js +2 -1
- package/console/dist/server/models/GovernanceProjectionCollector.js +11 -10
- package/console/dist/server/models/IntentPageModel.js +1 -1
- package/console/dist/server/models/OwnerDecisionViewModel.d.ts +3 -2
- package/console/dist/server/models/OwnerDecisionViewModel.js +8 -7
- package/console/dist/server/routes/activations.js +5 -5
- package/console/dist/server/routes/approvals-grouped.js +2 -2
- package/console/dist/server/routes/approvals.js +7 -7
- package/console/dist/server/routes/config.d.ts +4 -4
- package/console/dist/server/routes/config.js +5 -5
- package/console/dist/server/routes/evidence-chain.d.ts +1 -1
- package/console/dist/server/routes/evidence-outcomes.d.ts +2 -2
- package/console/dist/server/routes/examiner.d.ts +12 -12
- package/console/dist/server/routes/examiner.js +2 -2
- package/console/dist/server/routes/failed-tasks.d.ts +4 -4
- package/console/dist/server/routes/failed-tasks.js +10 -10
- package/console/dist/server/routes/governance.d.ts +1 -1
- package/console/dist/server/routes/governance.js +3 -3
- package/console/dist/server/routes/intent-decisions.d.ts +6 -6
- package/console/dist/server/routes/intent-decisions.js +13 -13
- package/console/dist/server/routes/intent.js +6 -6
- package/console/dist/server/routes/lifecycle.js +3 -3
- package/console/dist/server/routes/onboarding.d.ts +1 -1
- package/console/dist/server/routes/onboarding.js +4 -4
- package/console/dist/server/routes/owner-decision.d.ts +5 -5
- package/console/dist/server/routes/owner-decision.js +3 -3
- package/console/dist/server/routes/owner-decisions.d.ts +3 -3
- package/console/dist/server/routes/owner-decisions.js +3 -3
- package/console/dist/server/routes/owner-identity.d.ts +1 -1
- package/console/dist/server/routes/owner-identity.js +1 -1
- package/console/dist/server/routes/principles.d.ts +4 -3
- package/console/dist/server/routes/principles.js +5 -4
- package/console/dist/server/routes/receipts.d.ts +2 -2
- package/console/dist/server/routes/receipts.js +4 -4
- package/console/dist/server.d.ts +2 -1
- package/console/dist/server.js +9 -1
- package/console/dist/shared/prompt-injection-contract.d.ts +1 -1
- package/console/dist/web/assets/app.js +23 -23
- package/core/dist/index.d.ts +1 -1
- package/core/dist/index.d.ts.map +1 -1
- package/core/dist/index.js +3 -2
- package/core/dist/index.js.map +1 -1
- package/core/dist/runtime/activation/approval-review-guard.d.ts +2 -2
- package/core/dist/runtime/activation/approval-review-guard.d.ts.map +1 -1
- package/core/dist/runtime/activation/approval-review-guard.js +6 -1
- package/core/dist/runtime/activation/approval-review-guard.js.map +1 -1
- package/core/dist/runtime/activation/prompt-budget-policy.d.ts +9 -1
- package/core/dist/runtime/activation/prompt-budget-policy.d.ts.map +1 -1
- package/core/dist/runtime/activation/prompt-budget-policy.js +9 -1
- package/core/dist/runtime/activation/prompt-budget-policy.js.map +1 -1
- package/core/dist/runtime/activation/recovery-control-surfaces.d.ts +1 -1
- package/core/dist/runtime/activation/recovery-control-surfaces.js +2 -2
- package/core/dist/runtime/activation/recovery-control-surfaces.js.map +1 -1
- package/core/dist/runtime/adapter/output-schema-registry.d.ts +1 -1
- package/core/dist/runtime/adapter/output-schema-registry.d.ts.map +1 -1
- package/core/dist/runtime/adapter/output-schema-registry.js +23 -18
- package/core/dist/runtime/adapter/output-schema-registry.js.map +1 -1
- package/core/dist/runtime/adapter/pi-ai-runtime-adapter.js +1 -1
- package/core/dist/runtime/adapter/pi-ai-runtime-adapter.js.map +1 -1
- package/core/dist/runtime/adapter/schema-json-converter.d.ts +1 -1
- package/core/dist/runtime/adapter/schema-json-converter.js +1 -1
- package/core/dist/runtime/adapter/tools/diagnostician-tool.js +1 -1
- package/core/dist/runtime/adapter/tools/diagnostician-tool.js.map +1 -1
- package/core/dist/runtime/diagnostician-output.d.ts +2 -2
- package/core/dist/runtime/diagnostician-output.d.ts.map +1 -1
- package/core/dist/runtime/diagnostician-output.js +1 -1
- package/core/dist/runtime/diagnostician-output.js.map +1 -1
- package/core/dist/runtime/feature-flags/plugin-surface-registry.d.ts.map +1 -1
- package/core/dist/runtime/feature-flags/plugin-surface-registry.js +10 -0
- package/core/dist/runtime/feature-flags/plugin-surface-registry.js.map +1 -1
- package/core/dist/runtime/governance-experience-contract.d.ts +4 -4
- package/core/dist/runtime/governance-experience-contract.d.ts.map +1 -1
- package/core/dist/runtime/governance-experience-contract.js +3 -2
- package/core/dist/runtime/governance-experience-contract.js.map +1 -1
- package/core/dist/runtime/governance-experience.d.ts.map +1 -1
- package/core/dist/runtime/governance-experience.js +2 -1
- package/core/dist/runtime/governance-experience.js.map +1 -1
- package/core/dist/runtime/governance-projection-contract.d.ts +14 -14
- package/core/dist/runtime/governance-projection-contract.d.ts.map +1 -1
- package/core/dist/runtime/governance-projection-contract.js +4 -3
- package/core/dist/runtime/governance-projection-contract.js.map +1 -1
- package/core/dist/runtime/governance-projection.d.ts.map +1 -1
- package/core/dist/runtime/governance-projection.js +2 -1
- package/core/dist/runtime/governance-projection.js.map +1 -1
- package/core/dist/runtime/index.d.ts +2 -2
- package/core/dist/runtime/index.d.ts.map +1 -1
- package/core/dist/runtime/index.js +2 -3
- package/core/dist/runtime/index.js.map +1 -1
- package/core/dist/runtime/internalization/artificer-runner.d.ts +1 -1
- package/core/dist/runtime/internalization/artificer-runner.d.ts.map +1 -1
- package/core/dist/runtime/internalization/artificer-runner.js +3 -2
- package/core/dist/runtime/internalization/artificer-runner.js.map +1 -1
- package/core/dist/runtime/internalization/diag-distiller-runner.d.ts.map +1 -1
- package/core/dist/runtime/internalization/diag-distiller-runner.js +3 -2
- package/core/dist/runtime/internalization/diag-distiller-runner.js.map +1 -1
- package/core/dist/runtime/internalization/diag-rootcause-runner.d.ts.map +1 -1
- package/core/dist/runtime/internalization/diag-rootcause-runner.js +3 -2
- package/core/dist/runtime/internalization/diag-rootcause-runner.js.map +1 -1
- package/core/dist/runtime/internalization/diag-router-runner.d.ts.map +1 -1
- package/core/dist/runtime/internalization/diag-router-runner.js +4 -3
- package/core/dist/runtime/internalization/diag-router-runner.js.map +1 -1
- package/core/dist/runtime/internalization/dreamer-runner.d.ts.map +1 -1
- package/core/dist/runtime/internalization/dreamer-runner.js +3 -2
- package/core/dist/runtime/internalization/dreamer-runner.js.map +1 -1
- package/core/dist/runtime/internalization/evaluator-runner.d.ts.map +1 -1
- package/core/dist/runtime/internalization/evaluator-runner.js +3 -2
- package/core/dist/runtime/internalization/evaluator-runner.js.map +1 -1
- package/core/dist/runtime/internalization/philosopher-runner.d.ts +1 -1
- package/core/dist/runtime/internalization/philosopher-runner.d.ts.map +1 -1
- package/core/dist/runtime/internalization/philosopher-runner.js +3 -2
- package/core/dist/runtime/internalization/philosopher-runner.js.map +1 -1
- package/core/dist/runtime/internalization/rollout-reviewer-output.d.ts +1 -1
- package/core/dist/runtime/internalization/rollout-reviewer-output.js +1 -1
- package/core/dist/runtime/internalization/rollout-reviewer-output.js.map +1 -1
- package/core/dist/runtime/internalization/rollout-reviewer-runner.d.ts.map +1 -1
- package/core/dist/runtime/internalization/rollout-reviewer-runner.js +3 -2
- package/core/dist/runtime/internalization/rollout-reviewer-runner.js.map +1 -1
- package/core/dist/runtime/internalization/router-context-evidence.d.ts +1 -1
- package/core/dist/runtime/internalization/router-context-evidence.d.ts.map +1 -1
- package/core/dist/runtime/internalization/router-context-evidence.js +4 -1
- package/core/dist/runtime/internalization/router-context-evidence.js.map +1 -1
- package/core/dist/runtime/internalization/scribe-runner.d.ts +1 -1
- package/core/dist/runtime/internalization/scribe-runner.d.ts.map +1 -1
- package/core/dist/runtime/internalization/scribe-runner.js +3 -2
- package/core/dist/runtime/internalization/scribe-runner.js.map +1 -1
- package/core/dist/runtime/learning-lab/actor-action-output.d.ts +1 -1
- package/core/dist/runtime/learning-lab/actor-action-output.d.ts.map +1 -1
- package/core/dist/runtime/learning-lab/actor-action-output.js +1 -1
- package/core/dist/runtime/learning-lab/actor-action-output.js.map +1 -1
- package/core/dist/runtime/observer/correction-observer.d.ts.map +1 -1
- package/core/dist/runtime/observer/correction-observer.js +3 -2
- package/core/dist/runtime/observer/correction-observer.js.map +1 -1
- package/core/dist/runtime/owner-decision/owner-decision-view-contract.d.ts +1 -1
- package/core/dist/runtime/owner-decision/owner-decision-view-contract.d.ts.map +1 -1
- package/core/dist/runtime/owner-decision/owner-decision-view-contract.js +2 -1
- package/core/dist/runtime/owner-decision/owner-decision-view-contract.js.map +1 -1
- package/core/dist/runtime/owner-decision/owner-decision-view.d.ts +8 -8
- package/core/dist/runtime/owner-decision/owner-decision-view.d.ts.map +1 -1
- package/core/dist/runtime/owner-decision/owner-decision-view.js +10 -9
- package/core/dist/runtime/owner-decision/owner-decision-view.js.map +1 -1
- package/core/dist/runtime/principle-reuse/reuse-evaluation-output.d.ts +1 -1
- package/core/dist/runtime/principle-reuse/reuse-evaluation-output.d.ts.map +1 -1
- package/core/dist/runtime/principle-reuse/reuse-evaluation-output.js +1 -1
- package/core/dist/runtime/principle-reuse/reuse-evaluation-output.js.map +1 -1
- package/core/dist/runtime/principle-reuse/reuse-evaluation-runner.d.ts.map +1 -1
- package/core/dist/runtime/principle-reuse/reuse-evaluation-runner.js +5 -4
- package/core/dist/runtime/principle-reuse/reuse-evaluation-runner.js.map +1 -1
- package/core/dist/runtime/schema-version.d.ts +30 -14
- package/core/dist/runtime/schema-version.d.ts.map +1 -1
- package/core/dist/runtime/schema-version.js +33 -13
- package/core/dist/runtime/schema-version.js.map +1 -1
- package/core/package.json +1 -1
- package/dist/installers/workbuddy-host-installer.d.ts +32 -1
- package/dist/installers/workbuddy-host-installer.d.ts.map +1 -1
- package/dist/installers/workbuddy-host-installer.js +819 -47
- package/dist/installers/workbuddy-host-installer.js.map +1 -1
- package/dist/utils/config-file-io.d.ts +27 -1
- package/dist/utils/config-file-io.d.ts.map +1 -1
- package/dist/utils/config-file-io.js +78 -3
- package/dist/utils/config-file-io.js.map +1 -1
- package/host-runtime/dist/prompt-injection-budget-observation.js +10 -8
- package/host-runtime/dist/signal-classifier.d.ts +3 -1
- package/host-runtime/dist/signal-classifier.js +5 -3
- package/host-runtime/package.json +1 -1
- package/package.json +3 -3
- package/pd-cli/package.json +1 -1
- package/pd-mcp-server/dist/version.d.ts +1 -1
- package/pd-mcp-server/dist/version.js +1 -1
- package/pd-mcp-server/package.json +1 -1
- package/plugin/dist/bundle.js +441 -441
- package/plugin/dist/core/event-log.d.ts +5 -0
- package/plugin/dist/governance-audit.js +2 -2
- package/plugin/dist/openclaw.plugin.json +1 -1
- package/plugin/dist/rulehost-evidence.js +9 -9
- package/plugin/openclaw.plugin.json +1 -1
- package/plugin/package.json +1 -1
- package/release-manager/dist/installers/workbuddy-host-installer.js +819 -47
- package/release-manager/dist/utils/config-file-io.js +78 -3
- package/release-manager/package.json +1 -1
- package/workbuddy-adapter/package.json +1 -1
|
@@ -42,7 +42,8 @@
|
|
|
42
42
|
* result reason; every result carries reason + nextAction.
|
|
43
43
|
*/
|
|
44
44
|
import { spawnSync, execFileSync } from 'node:child_process';
|
|
45
|
-
import {
|
|
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';
|
|
@@ -63,7 +64,7 @@ export const WORKBUDDY_MARKETPLACE_NAME = 'principles-disciple-market';
|
|
|
63
64
|
/** Registry/settings key: "principles-disciple@principles-disciple-market". */
|
|
64
65
|
export const WORKBUDDY_PLUGIN_KEY = `${WORKBUDDY_PLUGIN_NAME}@${WORKBUDDY_MARKETPLACE_NAME}`;
|
|
65
66
|
const WORKBUDDY_REQUIRED_SKILLS = ['pd-cli-operator', 'pd-pain-signal', 'pd-review', 'pd-control'];
|
|
66
|
-
import { atomicReplaceTextFile, errnoCode } from '../utils/config-file-io.js';
|
|
67
|
+
import { atomicReplaceTextFile, AtomicReplaceCleanupError, AtomicReplaceConflictError, errnoCode } from '../utils/config-file-io.js';
|
|
67
68
|
import { checkMcpRegistrationConflict } from './mcp-registration-conflict.js';
|
|
68
69
|
import { resolveMcpServerDir, resolveMcpServerEntry } from '../mcp-server-layout-compat.js';
|
|
69
70
|
import { getHomeDir, generateConfigYamlContent, getConfigYamlPath, resolveDefaultModelForProvider, isValidHttpBaseUrl } from '../mvp-config.js';
|
|
@@ -382,6 +383,616 @@ export function writeHostJsonFileProtected(filePath, content) {
|
|
|
382
383
|
};
|
|
383
384
|
}
|
|
384
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
|
+
}
|
|
385
996
|
export function findWorkbuddyPluginPayload(pluginDir, runtimeAdapterDir) {
|
|
386
997
|
for (const root of [path.join(pluginDir, 'workbuddy-adapter', 'plugin'), path.join(runtimeAdapterDir, 'plugin')]) {
|
|
387
998
|
const manifestPath = path.join(root, '.codebuddy-plugin', 'plugin.json');
|
|
@@ -451,7 +1062,7 @@ function readInstallJsonRecord(manifestPath) {
|
|
|
451
1062
|
* channel/autoCheck/releaseMetadataUrl — PRI-709 P0-1) are carried through.
|
|
452
1063
|
* Malformed existing manifest → hard stop, zero modification.
|
|
453
1064
|
*/
|
|
454
|
-
export function mergeWorkbuddyIntoInstallManifest(manifestPath, governanceDir) {
|
|
1065
|
+
export function mergeWorkbuddyIntoInstallManifest(manifestPath, governanceDir, atomicReplace = atomicReplaceTextFile) {
|
|
455
1066
|
let current;
|
|
456
1067
|
let existed = false;
|
|
457
1068
|
try {
|
|
@@ -493,16 +1104,28 @@ export function mergeWorkbuddyIntoInstallManifest(manifestPath, governanceDir) {
|
|
|
493
1104
|
hosts,
|
|
494
1105
|
workspaces,
|
|
495
1106
|
};
|
|
1107
|
+
const writtenContent = JSON.stringify(payload, null, 2) + '\n';
|
|
496
1108
|
try {
|
|
497
1109
|
mkdirSync(path.dirname(manifestPath), { recursive: true });
|
|
498
|
-
|
|
499
|
-
|
|
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 };
|
|
500
1115
|
}
|
|
501
1116
|
catch (error) {
|
|
1117
|
+
const committed = error instanceof AtomicReplaceCleanupError && error.committed;
|
|
502
1118
|
return {
|
|
503
1119
|
ok: false,
|
|
504
|
-
reason:
|
|
505
|
-
|
|
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 } : {}),
|
|
506
1129
|
};
|
|
507
1130
|
}
|
|
508
1131
|
}
|
|
@@ -877,6 +1500,7 @@ function applyFeatureFlagLineEdit(raw, request) {
|
|
|
877
1500
|
*/
|
|
878
1501
|
export function ensureWorkbuddyGovernanceEnabled(governanceDir, options = {}) {
|
|
879
1502
|
const persist = options.persist !== false;
|
|
1503
|
+
const atomicReplace = options.atomicReplace ?? atomicReplaceTextFile;
|
|
880
1504
|
const configPath = path.join(governanceDir, '.pd', 'config.yaml');
|
|
881
1505
|
let rawText;
|
|
882
1506
|
try {
|
|
@@ -959,12 +1583,24 @@ export function ensureWorkbuddyGovernanceEnabled(governanceDir, options = {}) {
|
|
|
959
1583
|
const finalKeyword = isRecord(finalFeatures) ? finalFeatures.workbuddy_live_keyword_pain : undefined;
|
|
960
1584
|
const keywordPainEnabled = isRecord(finalKeyword) && finalKeyword.enabled === true;
|
|
961
1585
|
try {
|
|
962
|
-
|
|
1586
|
+
atomicReplace(configPath, next);
|
|
963
1587
|
}
|
|
964
|
-
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
|
+
}
|
|
965
1601
|
return { ok: false, reason: 'fresh_workbuddy_flag_write_failed', nextAction: 'Repair config storage and retry.', hostExplicitOff, keywordExplicitOff, keywordPainEnabled, changed: false };
|
|
966
1602
|
}
|
|
967
|
-
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 };
|
|
968
1604
|
}
|
|
969
1605
|
/**
|
|
970
1606
|
* The single plugin-state judgment: registration (registry) and enablement
|
|
@@ -1173,7 +1809,7 @@ const GOVERNANCE_PROFILE_ID = 'pd.default';
|
|
|
1173
1809
|
* Module-private: the only writer/reader is install() below (step 6.5); the
|
|
1174
1810
|
* regression suite exercises it through the REAL install() boundary.
|
|
1175
1811
|
*/
|
|
1176
|
-
function applyWorkbuddyGovernanceRuntimeProfile(governanceDir, profile) {
|
|
1812
|
+
function applyWorkbuddyGovernanceRuntimeProfile(governanceDir, profile, atomicReplace = atomicReplaceTextFile) {
|
|
1177
1813
|
// rc-1/rc-3: validate here — upstream CLI validation is not trusted as a
|
|
1178
1814
|
// substitute for a guard at the write boundary.
|
|
1179
1815
|
const provider = typeof profile.provider === 'string' ? profile.provider.trim() : '';
|
|
@@ -1367,16 +2003,27 @@ function applyWorkbuddyGovernanceRuntimeProfile(governanceDir, profile) {
|
|
|
1367
2003
|
}
|
|
1368
2004
|
try {
|
|
1369
2005
|
mkdirSync(path.dirname(configPath), { recursive: true });
|
|
1370
|
-
|
|
2006
|
+
atomicReplace(configPath, next);
|
|
1371
2007
|
}
|
|
1372
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
|
+
}
|
|
1373
2020
|
return {
|
|
1374
2021
|
ok: false,
|
|
1375
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.`,
|
|
1376
2023
|
nextAction: `Check permissions under ${path.dirname(configPath)}, close tools holding the file, then re-run the installer.`,
|
|
1377
2024
|
};
|
|
1378
2025
|
}
|
|
1379
|
-
return { ok: true, configPath, profileId: GOVERNANCE_PROFILE_ID, model, pendingAgents };
|
|
2026
|
+
return { ok: true, configPath, writtenContent: next, profileId: GOVERNANCE_PROFILE_ID, model, pendingAgents };
|
|
1380
2027
|
}
|
|
1381
2028
|
// ─── WorkBuddyHostInstaller ─────────────────────────────────────────────────
|
|
1382
2029
|
/** Shared Git Bash failure message (win32 hooks launch through bash). */
|
|
@@ -1547,6 +2194,10 @@ export class WorkBuddyHostInstaller {
|
|
|
1547
2194
|
const entry = path.join(getInstallLayoutPaths(homeDir()).pdCliDir, 'dist', 'index.js');
|
|
1548
2195
|
return existsSync(entry) ? entry : undefined;
|
|
1549
2196
|
}),
|
|
2197
|
+
backupCopyDir: deps.backupCopyDir ?? cpSync,
|
|
2198
|
+
atomicReplaceConfig: deps.atomicReplaceConfig ?? atomicReplaceTextFile,
|
|
2199
|
+
beforeCompensation: deps.beforeCompensation ?? (() => undefined),
|
|
2200
|
+
cacheRollbackOps: deps.cacheRollbackOps ?? { copyDir: cpSync, rename: renameSync },
|
|
1550
2201
|
runCommand: deps.runCommand ?? ((file, args, opts) => {
|
|
1551
2202
|
const result = spawnSync(file, [...args], {
|
|
1552
2203
|
encoding: 'utf-8',
|
|
@@ -1694,8 +2345,79 @@ export class WorkBuddyHostInstaller {
|
|
|
1694
2345
|
// unaffected when the MCP component is missing or the write fails.
|
|
1695
2346
|
const mcpBinding = writeWorkbuddyMcpBinding(p.marketplaceRoot, this.deps.homeDir());
|
|
1696
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
|
+
};
|
|
1697
2397
|
const registration = this.registerPlugin(details, payload.version, payload.defaultEnabled);
|
|
1698
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
|
+
}
|
|
1699
2421
|
return {
|
|
1700
2422
|
success: false,
|
|
1701
2423
|
hostId: this.hostId,
|
|
@@ -1705,23 +2427,48 @@ export class WorkBuddyHostInstaller {
|
|
|
1705
2427
|
nextAction: registration.nextAction,
|
|
1706
2428
|
};
|
|
1707
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
|
+
}
|
|
1708
2443
|
// 6. Initialize the governance workspace (OD-07 explicit creation) with
|
|
1709
2444
|
// the FULL loader-valid state the hook/console/worker chain reads:
|
|
1710
2445
|
// .pd/config.yaml, .pd/state.db and the canonical .state/trajectory.db
|
|
1711
2446
|
// schema. Review 2026-10-13 R1: this step previously only mkdir'd the
|
|
1712
2447
|
// directory, so install reported success while the hook chain saw an
|
|
1713
2448
|
// uninitialized workspace.
|
|
1714
|
-
const
|
|
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);
|
|
1715
2464
|
if (!governance.ok) {
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
reason: governance.reason,
|
|
1722
|
-
nextAction: governance.nextAction,
|
|
1723
|
-
};
|
|
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);
|
|
1724
2470
|
}
|
|
2471
|
+
recordGovernanceInitWrite();
|
|
1725
2472
|
// 6.5 Round-3 remediation P1: the install-collected LLM runtime profile
|
|
1726
2473
|
// (--provider/--api-key-env/--model) is GOVERNANCE state for this
|
|
1727
2474
|
// host — it must land in the governance workspace config the
|
|
@@ -1736,17 +2483,17 @@ export class WorkBuddyHostInstaller {
|
|
|
1736
2483
|
let profileNote = '';
|
|
1737
2484
|
let profilePendingAgents = [];
|
|
1738
2485
|
if (ctx.runtimeProfile) {
|
|
1739
|
-
const applied = applyWorkbuddyGovernanceRuntimeProfile(p.governanceDir, ctx.runtimeProfile);
|
|
2486
|
+
const applied = applyWorkbuddyGovernanceRuntimeProfile(p.governanceDir, ctx.runtimeProfile, atomicReplaceConfig);
|
|
1740
2487
|
if (!applied.ok) {
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
};
|
|
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);
|
|
1749
2495
|
}
|
|
2496
|
+
recordWorkbuddyTxnWrite(txn, applied.configPath, snapshotWorkbuddyFile(applied.configPath).bytes ?? applied.writtenContent);
|
|
1750
2497
|
profileNote = ` LLM runtime profile '${applied.profileId}' (provider ${ctx.runtimeProfile.provider}, model ${applied.model}) written to ${applied.configPath}.`;
|
|
1751
2498
|
if (applied.pendingAgents.length > 0) {
|
|
1752
2499
|
profilePendingAgents = applied.pendingAgents;
|
|
@@ -1754,28 +2501,49 @@ export class WorkBuddyHostInstaller {
|
|
|
1754
2501
|
}
|
|
1755
2502
|
}
|
|
1756
2503
|
// 7. Record host + governance workspace in the install manifest (set union).
|
|
1757
|
-
const manifest = mergeWorkbuddyIntoInstallManifest(p.installManifestPath, p.governanceDir);
|
|
2504
|
+
const manifest = mergeWorkbuddyIntoInstallManifest(p.installManifestPath, p.governanceDir, atomicReplaceConfig);
|
|
1758
2505
|
if (!manifest.ok) {
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
};
|
|
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);
|
|
1767
2513
|
}
|
|
2514
|
+
recordWorkbuddyTxnWrite(txn, p.installManifestPath, snapshotWorkbuddyFile(p.installManifestPath).bytes ?? manifest.writtenContent);
|
|
1768
2515
|
// 8. Install ⇒ governance ON by default (PRI-1064, Owner directive
|
|
1769
2516
|
// 2026-10-31): the ONLY preserved-off state is an explicit opt-out the
|
|
1770
2517
|
// Owner wrote (enabled: false). Sparse/legacy configs left OFF by a
|
|
1771
2518
|
// failed install round are turned ON here — an install that ends with
|
|
1772
2519
|
// every hook skipping (host.workbuddy_disabled) is the P1 defect this
|
|
1773
2520
|
// replaces. The summary line below always states the effective state.
|
|
1774
|
-
const governanceConfigExists = existsSync(
|
|
1775
|
-
const governanceDefaults = governanceConfigExists
|
|
2521
|
+
const governanceConfigExists = existsSync(governanceConfigPath);
|
|
2522
|
+
const governanceDefaults = governanceConfigExists
|
|
2523
|
+
? ensureWorkbuddyGovernanceEnabled(p.governanceDir, { atomicReplace: atomicReplaceConfig })
|
|
2524
|
+
: null;
|
|
1776
2525
|
if (governanceDefaults !== null && !governanceDefaults.ok) {
|
|
1777
|
-
|
|
1778
|
-
|
|
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 */ }
|
|
1779
2547
|
}
|
|
1780
2548
|
const governanceDefaultsNote = describeGovernanceDefaults(governanceDefaults, p.governanceDir);
|
|
1781
2549
|
const effectiveNote = 'Registration takes effect in NEW WorkBuddy sessions (or /reload-plugins in a running CLI session).';
|
|
@@ -1828,7 +2596,7 @@ export class WorkBuddyHostInstaller {
|
|
|
1828
2596
|
* database initialization as an observable skip with an explicit next
|
|
1829
2597
|
* action — never a silent mkdir-only "success".
|
|
1830
2598
|
*/
|
|
1831
|
-
initializeGovernanceWorkspace(governanceDir) {
|
|
2599
|
+
initializeGovernanceWorkspace(governanceDir, atomicReplace = atomicReplaceTextFile) {
|
|
1832
2600
|
try {
|
|
1833
2601
|
mkdirSync(governanceDir, { recursive: true });
|
|
1834
2602
|
}
|
|
@@ -1867,7 +2635,7 @@ export class WorkBuddyHostInstaller {
|
|
|
1867
2635
|
if (!existsSync(configPath)) {
|
|
1868
2636
|
try {
|
|
1869
2637
|
mkdirSync(path.dirname(configPath), { recursive: true });
|
|
1870
|
-
|
|
2638
|
+
atomicReplace(configPath, generateConfigYamlContent());
|
|
1871
2639
|
}
|
|
1872
2640
|
catch (error) {
|
|
1873
2641
|
return {
|
|
@@ -1925,7 +2693,11 @@ export class WorkBuddyHostInstaller {
|
|
|
1925
2693
|
// an Owner-chosen true/false from before the install.
|
|
1926
2694
|
const applied = this.applyInstalledEnabledValue(installedEnabled.value);
|
|
1927
2695
|
if (!applied.ok) {
|
|
1928
|
-
|
|
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' };
|
|
1929
2701
|
}
|
|
1930
2702
|
return {
|
|
1931
2703
|
ok: true,
|