diff --git a/packages/adapter-workbuddy/test/install-rollback.test.js b/packages/adapter-workbuddy/test/install-rollback.test.js
new file mode 100644
index 0000000..01c0a08
--- /dev/null
+++ b/packages/adapter-workbuddy/test/install-rollback.test.js
@@ -0,0 +1,88 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import {workbuddyWindowsPaths,workbuddyWindowsWiring} from '../../../scripts/workbuddy-windows-wiring.mjs';
+import {workbuddyLinuxPaths,workbuddyLinuxWiring} from '../../../scripts/workbuddy-linux-wiring.mjs';
+import {commitWorkbuddyInstall} from '../../../scripts/workbuddy-install-transaction.mjs';
+import {renderWindowsStartupVbs} from '../../../scripts/portable-runtime.mjs';
+
+function fixture(t){const root=fs.mkdtempSync(path.join(os.tmpdir(),'bc-install-tx-'));t.after(()=>fs.rmSync(root,{recursive:true,force:true}));return root;}
+test('late startup publication failure restores files and registry', t => {
+ const root = fixture(t), env = { APPDATA: root };
+ const paths = workbuddyWindowsPaths(env, root);
+ let registryValue = null;
+ const wiring = workbuddyWindowsWiring({
+ env, home: root, launcher: path.join(root, 'launcher.ps1'), journal: path.join(root, 'journal'),
+ registry: { read: () => registryValue, write: value => { registryValue = value; } },
+ replace(file, _before, value) {
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(file, value);
+ throw new Error('temporary cleanup failed');
+ },
+ });
+ assert.throws(() => wiring.install('9335'), /cleanup failed/);
+ assert.equal(fs.existsSync(paths.startup), false);
+ assert.equal(registryValue, null);
+});
+
+test('identical launcher contents still restore original POSIX permissions', { skip: process.platform === 'win32' }, async t => {
+ const root = fixture(t);
+ const runtime = { pointerPath: path.join(root, 'pointer'), launcher: path.join(root, 'launcher.sh') };
+ fs.writeFileSync(runtime.launcher, 'unchanged', { mode: 0o751 });
+ fs.chmodSync(runtime.launcher, 0o751);
+ await assert.rejects(commitWorkbuddyInstall({
+ runtime, expectedLauncher: 'unchanged', portFile: path.join(root, 'port'), portText: '9335',
+ install: () => ({ rollback() {} }), discard() {},
+ activate() { fs.chmodSync(runtime.launcher, 0o755); throw new Error('activation failed'); },
+ }), /activation failed/);
+ assert.equal(fs.statSync(runtime.launcher).mode & 0o777, 0o751);
+});
+
+test('preflight failures discard the candidate before any wiring', async t => {
+ const root = fixture(t);
+ let discarded = 0;
+ const options = {
+ runtime: { pointerPath: root, launcher: path.join(root, 'launcher') },
+ install: () => assert.fail('unexpected install'),
+ discard: () => { discarded++; },
+ };
+ await assert.rejects(commitWorkbuddyInstall(options), /regular file/);
+ await assert.rejects(commitWorkbuddyInstall({ ...options, expectedLauncher() { throw Error('render failed'); } }), /render failed/);
+ assert.equal(discarded, 2);
+});
+test('foreign startup and redirected APPDATA are checked before registry writes; later edits preserved',t=>{
+ const root=fixture(t),env={APPDATA:path.join(root,'redirected')},paths=workbuddyWindowsPaths(env,root);let value={value:'9000',kind:'String'};
+ assert.ok(paths.startup.startsWith(env.APPDATA));fs.mkdirSync(path.dirname(paths.startup),{recursive:true});fs.writeFileSync(paths.startup,'foreign');
+ const registry={read:()=>value,write:v=>{value=v}},journal=path.join(root,'journal');
+ const options={env,home:root,launcher:path.join(root,'launcher.ps1'),journal,registry};
+ assert.throws(()=>workbuddyWindowsWiring(options).install('9335'),/not owned/);assert.equal(value.value,'9000');
+ fs.unlinkSync(paths.startup);fs.writeFileSync(paths.legacy,'foreign legacy');
+ workbuddyWindowsWiring(options).install('9335');assert.equal(value.value,'9335');
+ assert.equal(fs.readFileSync(paths.legacy,'utf8'),'foreign legacy');
+ fs.writeFileSync(paths.startup,'user edited');assert.throws(()=>workbuddyWindowsWiring(options).remove(),/not owned/);assert.equal(value.value,'9335');
+});
+test('Windows startup write failure restores previous registry/journal state; successful wiring can undo',t=>{
+ const root=fixture(t),env={APPDATA:root};let value=null;
+ const registry={read:()=>value,write:v=>{value=v}},journal=path.join(root,'journal'),opts={env,home:root,launcher:path.join(root,'launcher.ps1'),journal,registry};
+ assert.throws(()=>workbuddyWindowsWiring({...opts,replace(){throw new Error('fixture disk full')}}).install('9335'),/disk full/);
+ assert.equal(value,null);assert.equal(fs.existsSync(journal),false);
+ const tx=workbuddyWindowsWiring(opts).install('9335');tx.rollback();assert.equal(value,null);
+ assert.equal(fs.existsSync(workbuddyWindowsPaths(env,root).startup),false);
+});
+test('Linux environment failure removes newly created autostart; rollback preserves externally changed target',t=>{
+ const root=fixture(t),env={XDG_CONFIG_HOME:path.join(root,'config')},paths=workbuddyLinuxPaths(env,root);fs.mkdirSync(env.XDG_CONFIG_HOME,{recursive:true});fs.writeFileSync(path.dirname(paths.environment),'block');
+ const opts={env,home:root,launcher:'/tmp/fixture/launcher.sh'};
+ assert.throws(()=>workbuddyLinuxWiring(opts).install('9335'));assert.equal(fs.existsSync(paths.desktop),false);
+ fs.unlinkSync(path.dirname(paths.environment));const tx=workbuddyLinuxWiring(opts).install('9335');
+ fs.writeFileSync(paths.environment,'external edit');assert.throws(()=>tx.rollback(),/recovery incomplete/);assert.equal(fs.readFileSync(paths.environment,'utf8'),'external edit');
+});
+test('runtime activation failure restores wiring, port, pointer and launcher before discarding candidate',async t=>{
+ const root=fixture(t),runtime={pointerPath:path.join(root,'current.json'),launcher:path.join(root,'launcher.ps1'),version:'v-new'};
+ const portFile=path.join(root,'port.json');fs.writeFileSync(runtime.pointerPath,'{"version":"v-old"}');fs.writeFileSync(runtime.launcher,'old launcher');fs.writeFileSync(portFile,'old port');let wired=false,discarded=false;
+ if(process.platform !== 'win32') fs.chmodSync(runtime.launcher, 0o751);
+ await assert.rejects(commitWorkbuddyInstall({runtime,expectedLauncher:'new launcher',portFile,portText:'new port',install:()=>{wired=true;return{rollback(){wired=false}}},activate:()=>{fs.writeFileSync(runtime.launcher,'new launcher');fs.writeFileSync(runtime.pointerPath,'{"version":"v-new"}');throw new Error('fixture activation')},discard:()=>{discarded=true}}),/fixture activation/);
+ if(process.platform !== 'win32') assert.equal(fs.statSync(runtime.launcher).mode & 0o777, 0o751);
+ assert.equal(wired,false);assert.equal(discarded,true);assert.equal(fs.readFileSync(runtime.pointerPath,'utf8'),'{"version":"v-old"}');assert.equal(fs.readFileSync(runtime.launcher,'utf8'),'old launcher');assert.equal(fs.readFileSync(portFile,'utf8'),'old port');
+});
diff --git a/packages/beauticode-desktop/test/followup-package.test.mjs b/packages/beauticode-desktop/test/followup-package.test.mjs
new file mode 100644
index 0000000..67e27f3
--- /dev/null
+++ b/packages/beauticode-desktop/test/followup-package.test.mjs
@@ -0,0 +1,13 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import {pathToFileURL} from 'node:url';
+import {stageDesktopAggregate} from '../../../scripts/pack-desktop-aggregate.mjs';
+
+test('packaged WorkBuddy wiring imports every transaction dependency without the workspace',async t=>{
+ const root=await fs.mkdtemp(path.join(os.tmpdir(),'bc-followup-pack-'));t.after(()=>fs.rm(root,{recursive:true,force:true}));
+ await stageDesktopAggregate(root,{build:false});
+ for(const name of ['workbuddy-windows-wiring.mjs','workbuddy-linux-wiring.mjs','workbuddy-install-transaction.mjs'])await import(pathToFileURL(path.join(root,'runtime/workbuddy/scripts',name)).href);
+});
diff --git a/scripts/owned-file.mjs b/scripts/owned-file.mjs
new file mode 100644
index 0000000..91d24de
--- /dev/null
+++ b/scripts/owned-file.mjs
@@ -0,0 +1,38 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import { randomUUID } from 'node:crypto';
+
+export function readOwnedFile(file) {
+ try {
+ const stat=fs.lstatSync(file);
+ if(!stat.isFile() || stat.isSymbolicLink()) throw new Error('Managed target is not a regular file.');
+ return fs.readFileSync(file,'utf8');
+ } catch(error) { if(error.code==='ENOENT')return null;throw error; }
+}
+export function replaceOwnedFile(file, before, after, mode) {
+ if(readOwnedFile(file)!==before)throw new Error('Managed file changed externally; preserved.');
+ if(after===null){if(before!==null)fs.unlinkSync(file);return;}
+ fs.mkdirSync(path.dirname(file),{recursive:true});
+ const temporary=file+'.tmp-'+randomUUID();
+ fs.writeFileSync(temporary,after,{flag:'wx',mode:0o600});
+ try {
+ if(before===null)fs.linkSync(temporary,file);
+ else {
+ if(readOwnedFile(file)!==before)throw new Error('Managed file changed externally; preserved.');
+ fs.chmodSync(temporary, mode ?? (fs.statSync(file).mode & 0o777));
+ fs.renameSync(temporary,file);
+ }
+ } finally {fs.rmSync(temporary,{force:true});}
+}
+// Register compensation before publication. A write can succeed before temp cleanup throws.
+export function undoFileChange(file, before, published, mode) {
+ const current = readOwnedFile(file);
+ if (current === before) return;
+ replaceOwnedFile(file, published, before, mode);
+}
+export function rollbackSteps(undos, original) {
+ const errors=[];
+ for(const undo of undos.reverse())try{undo();}catch(error){errors.push(error);}
+ if(errors.length)throw new AggregateError([...(original?[original]:[]),...errors],'Installation failed; recovery incomplete. Saved ownership records must be retained.');
+ if(original)throw original;
+}
diff --git a/scripts/pack-desktop-aggregate.mjs b/scripts/pack-desktop-aggregate.mjs
index 8c5fef6..6b3c30b 100644
--- a/scripts/pack-desktop-aggregate.mjs
+++ b/scripts/pack-desktop-aggregate.mjs
@@ -153,7 +153,7 @@ async function copyWorkbuddyRuntime(destRoot) {
rewriteWorkbuddyRunner,
);
await copyText(path.join(repoRoot, "scripts", "quick-launch.mjs"), path.join(workbuddy, "scripts", "quick-launch.mjs"));
- for (const name of ["wb-startup-media.mjs", "wb-runner-log.mjs", "wb-theme-name-diagnostic.mjs", "windows-owned-env.mjs", "workbuddy-linux-wiring.mjs", "xdg-autostart.mjs"]) {
+ for (const name of ["wb-startup-media.mjs", "wb-runner-log.mjs", "wb-theme-name-diagnostic.mjs", "windows-owned-env.mjs", "owned-file.mjs", "workbuddy-windows-wiring.mjs", "workbuddy-install-transaction.mjs", "workbuddy-linux-wiring.mjs", "xdg-autostart.mjs"]) {
await copyText(path.join(repoRoot, "scripts", name), path.join(workbuddy, "scripts", name));
}
await copyText(
diff --git a/scripts/wb-setup.mjs b/scripts/wb-setup.mjs
index 9b93813..4f3bc01 100644
--- a/scripts/wb-setup.mjs
+++ b/scripts/wb-setup.mjs
@@ -27,8 +27,10 @@
import { spawn, spawnSync, execSync } from 'node:child_process';
import { isManagedWorkBuddyRunner, readGuardianProcess } from './guardian-process.mjs';
import fs from 'node:fs';
+import { workbuddyWindowsPaths, workbuddyWindowsWiring } from './workbuddy-windows-wiring.mjs';
+import { commitWorkbuddyInstall } from './workbuddy-install-transaction.mjs';
import { workbuddyLinuxPaths, workbuddyLinuxWiring } from './workbuddy-linux-wiring.mjs';
-import { updateOwnedPort } from './windows-owned-env.mjs';
+
import net from 'node:net';
import os from 'node:os';
import path from 'node:path';
@@ -38,14 +40,14 @@ import {
beautiCodeLocalRoot,
discardStableRuntime,
hostRuntimeRoot,
- renderWindowsStartupVbs,
+ renderRuntimeLauncherPs1,
+ renderRuntimeLauncherSh,
renderXdgDesktopEntry,
resolveNodeExecutable,
stableRuntimeRoot,
startDetachedLauncher,
startupDirectory,
syncStableRuntime,
- writeTextAtomic,
} from './portable-runtime.mjs';
const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
@@ -197,8 +199,8 @@ async function prepareStableRuntime() {
activate: false,
});
try {
- await resolveNodeExecutable({ stableRoot: runtime.hostRoot });
- return await activateStableRuntime(runtime, { startupLogPath: PLAT === 'linux' ? LINUX_LOG : WIN_LOG });
+ runtime.node = await resolveNodeExecutable({ stableRoot: runtime.hostRoot });
+ return runtime;
} catch (error) {
await discardStableRuntime(runtime);
throw error;
@@ -210,8 +212,7 @@ const LAUNCHER_MAC = path.join(home, 'Library/LaunchAgents/com.beauticode.wb-run
const MAC_LOG = path.join(home, 'Library/Logs/beauticode-wb-runner.log');
const STABLE_ROOT = stableRuntimeRoot(process.env, home);
const STABLE_HOST_ROOT = hostRuntimeRoot(STABLE_ROOT, 'workbuddy');
-const STARTUP_VBS = path.join(home, 'AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup/beauticode-wb-runner.vbs');
-const LEGACY_STARTUP_VBS = path.join(process.env.APPDATA || path.join(home, 'AppData', 'Roaming'), 'beauticode-wb-runner.vbs');
+const STARTUP_VBS = workbuddyWindowsPaths(process.env, home).startup;
const WIN_LOG = path.join(
process.env.LOCALAPPDATA || path.join(home, 'AppData', 'Local'),
'beauticode', 'logs', 'wb-runner.log',
@@ -241,7 +242,6 @@ const macPlist = () => `
StandardErrorPath${MAC_LOG}
`;
-const winVbs = (launcher) => renderWindowsStartupVbs({ launcher, args: ['--watchdog'] });
function shSingleQuote(value) {
return `'${String(value).replace(/'/g, `'\\''`)}'`;
@@ -284,28 +284,14 @@ function statusMac() {
}
async function installWin(runtime) {
- updateOwnedPort({ journal: path.join(DATA_DIR, 'workbuddy-env-ownership.json'), port });
+ const transaction = workbuddyWindowsWiring({env:process.env,home,launcher:runtime.launcher,journal:path.join(DATA_DIR,'workbuddy-env-ownership.json')}).install(port);
log(' ✓ 用户端口配置已备份、写入并回读验证');
- broadcastWindowsEnvironment();
- log(' ✓ 已广播环境变更(无需注销即可让后续原图标启动继承端口)');
- fs.mkdirSync(path.dirname(STARTUP_VBS), { recursive: true });
- const startupContent = winVbs(runtime.launcher);
- let currentStartupContent = null;
- try { currentStartupContent = fs.readFileSync(STARTUP_VBS, 'utf8'); }
- catch (error) { if (error?.code !== 'ENOENT') throw error; }
- if (currentStartupContent !== startupContent) await writeTextAtomic(STARTUP_VBS, startupContent);
- if (path.resolve(LEGACY_STARTUP_VBS) !== path.resolve(STARTUP_VBS)) fs.rmSync(LEGACY_STARTUP_VBS, { force: true });
- log(currentStartupContent === startupContent
- ? ' ✓「启动」文件夹 VBS 已是当前配置(跳过无变化替换)'
- : ' ✓ 已写入「启动」文件夹 VBS(登录自启、隐藏窗口)');
- if (process.env[ENV_KEY] !== port) {
- log(' ⚠ 当前会话还没继承新 env:注销重登一次,或先手动带 env 启动一次 WorkBuddy');
- }
+
+ /* Startup ownership and reversible file writes are handled by the wiring transaction. */
+ return transaction;
}
function uninstallWin() {
- fs.rmSync(STARTUP_VBS, { force: true });
- fs.rmSync(LEGACY_STARTUP_VBS, { force: true });
- const restored = updateOwnedPort({ journal: path.join(DATA_DIR, 'workbuddy-env-ownership.json'), remove: true });
+ const restored = workbuddyWindowsWiring({env:process.env,home,launcher:path.join(STABLE_HOST_ROOT,'launcher.ps1'),journal:path.join(DATA_DIR,'workbuddy-env-ownership.json')}).remove();
broadcastWindowsEnvironment();
log(restored === 'restored' ? ' ✓ 已拆除启动项并恢复原用户环境变量' : ' ✓ 已拆除启动项;未受本次安装管理或后来修改的环境变量已保留');
}
@@ -323,8 +309,9 @@ function statusWin() {
function installLinux(runtime) {
if (!runtime) throw new Error('Stable WorkBuddy runtime required.');
- workbuddyLinuxWiring({ env: process.env, home, launcher: runtime.launcher }).install(port);
+ const transaction = workbuddyLinuxWiring({ env: process.env, home, launcher: runtime.launcher }).install(port);
log(' ✓ environment.d + autostart 已写入(下次登录生效;当前会话可手动 export)');
+ return transaction;
}
function uninstallLinux() {
workbuddyLinuxWiring({ env: process.env, home, launcher: path.join(STABLE_HOST_ROOT, 'launcher.sh') }).remove();
@@ -473,8 +460,15 @@ if (PACKAGED_RUNTIME) {
// the stable runtime and verified Node are ready.
log(`安装 beautiCode × WorkBuddy(${PLAT},端口 ${port}):`);
const stableRuntime = PLAT === 'win32' || PLAT === 'linux' ? await prepareStableRuntime() : null;
-writeConfiguredPort(port);
-if (PLAT === 'darwin') installMac(); else if (PLAT === 'win32') await installWin(stableRuntime); else installLinux(stableRuntime);
+if(stableRuntime) {
+ await commitWorkbuddyInstall({
+ runtime:stableRuntime, expectedLauncher:()=>PLAT==='linux'?renderRuntimeLauncherSh({host:'workbuddy',startupLogPath:LINUX_LOG,nodePath:stableRuntime.node.path}):renderRuntimeLauncherPs1({host:'workbuddy',startupLogPath:WIN_LOG}), portFile:PORT_FILE, portText:JSON.stringify({port:Number(port)},null,2)+'\n',
+ install:()=>PLAT==='win32'?installWin(stableRuntime):installLinux(stableRuntime),
+ activate:()=>activateStableRuntime(stableRuntime,{nodePath:stableRuntime.node.path,startupLogPath:PLAT==='linux'?LINUX_LOG:WIN_LOG}),
+ discard:()=>discardStableRuntime(stableRuntime),
+ });
+ if (PLAT === 'win32') broadcastWindowsEnvironment();
+} else { writeConfiguredPort(port); installMac(); }
startDaemon(stableRuntime);
diff --git a/scripts/workbuddy-install-transaction.mjs b/scripts/workbuddy-install-transaction.mjs
new file mode 100644
index 0000000..f0a65ac
--- /dev/null
+++ b/scripts/workbuddy-install-transaction.mjs
@@ -0,0 +1,51 @@
+import fs from 'node:fs';
+import { readOwnedFile, replaceOwnedFile, undoFileChange } from './owned-file.mjs';
+
+/** Keep the previous runtime active until wiring succeeds; restore only this operation's values. */
+export async function commitWorkbuddyInstall({runtime,expectedLauncher,portFile,portText,install,activate,discard}) {
+ let before;
+ try {
+ if (typeof expectedLauncher === 'function') expectedLauncher = expectedLauncher();
+ const launcher = readOwnedFile(runtime.launcher);
+ before = {
+ launcher,
+ launcherMode: launcher === null ? undefined : fs.statSync(runtime.launcher).mode & 0o777,
+ pointer: readOwnedFile(runtime.pointerPath),
+ port: readOwnedFile(portFile),
+ };
+ } catch (error) {
+ await discard();
+ throw error;
+ }
+ let wiring, portAttempted=false, activationAttempted=false;
+ try {
+ wiring=await install();
+ portAttempted = true;
+ replaceOwnedFile(portFile,before.port,portText);
+ activationAttempted = true;
+ await activate();
+ } catch(error) {
+ const errors=[];
+ for(const undo of [
+ ()=>{const current=readOwnedFile(runtime.pointerPath);if(current!==before.pointer){if(JSON.parse(current)?.version!==runtime.version)throw new Error('Runtime changed externally.');replaceOwnedFile(runtime.pointerPath,current,before.pointer);}},
+ ()=>{
+ if (!activationAttempted) return;
+ const current = readOwnedFile(runtime.launcher);
+ if (current !== before.launcher) {
+ undoFileChange(runtime.launcher, before.launcher, expectedLauncher, before.launcherMode);
+ } else if (current !== null && current === expectedLauncher && process.platform !== 'win32') {
+ const mode = fs.statSync(runtime.launcher).mode & 0o777;
+ if (mode !== before.launcherMode) {
+ if (mode !== 0o755 && mode !== (0o666 & ~process.umask())) throw new Error('Launcher mode changed externally; preserved.');
+ fs.chmodSync(runtime.launcher, before.launcherMode);
+ }
+ }
+ },
+ ()=>{if(portAttempted)undoFileChange(portFile,before.port,portText);},
+ ()=>wiring?.rollback(),
+ ])try{undo();}catch(restoreError){errors.push(restoreError);}
+ if(!errors.length)await discard();
+ if(errors.length)throw new AggregateError([error,...errors],'Installation failed; recovery incomplete. Retain runtime and ownership records.');
+ throw error;
+ }
+}
diff --git a/scripts/workbuddy-linux-wiring.mjs b/scripts/workbuddy-linux-wiring.mjs
index 0cec794..981b5cf 100644
--- a/scripts/workbuddy-linux-wiring.mjs
+++ b/scripts/workbuddy-linux-wiring.mjs
@@ -2,6 +2,7 @@ import fs from 'node:fs';
import path from 'node:path';
import { xdgConfigHome, xdgAutostartPath, renderXdgDesktopEntry } from './portable-runtime.mjs';
import { createXdgAutostartAdapter } from './xdg-autostart.mjs';
+import { readOwnedFile, replaceOwnedFile, undoFileChange, rollbackSteps } from './owned-file.mjs';
export function workbuddyLinuxPaths(env, home) {
return {
@@ -10,7 +11,7 @@ export function workbuddyLinuxPaths(env, home) {
};
}
-export function workbuddyLinuxWiring({ env, home, launcher }) {
+export function workbuddyLinuxWiring({ env, home, launcher, replace = replaceOwnedFile }) {
const paths = workbuddyLinuxPaths(env, home);
const desktop = createXdgAutostartAdapter(launcher, { file: paths.desktop, args: ['--watchdog'] });
const marker = '# beautiCode WorkBuddy environment';
@@ -18,12 +19,18 @@ export function workbuddyLinuxWiring({ env, home, launcher }) {
const checkEnv = () => { const text = readEnv(); if (text !== null && !text.startsWith(marker + '\n')) throw new Error('WorkBuddy environment file is not owned; preserved.'); return text; };
return {
install(port) {
- desktop.assertAbsentOrOwned(); checkEnv();
+ const beforeDesktop=desktop.assertAbsentOrOwned(),beforeEnv=checkEnv();
const value = Number(port);
if (!Number.isInteger(value) || value < 1 || value > 65535) throw new Error('Invalid WorkBuddy port');
- desktop.write(renderXdgDesktopEntry({ name: 'beautiCode WorkBuddy runner', launcher, args: ['--watchdog'] }));
- fs.mkdirSync(path.dirname(paths.environment), { recursive: true });
- fs.writeFileSync(paths.environment, `${marker}\nWORKBUDDY_REMOTE_DEBUGGING_PORT=${value}\n`);
+ const nextDesktop=renderXdgDesktopEntry({ name: 'beautiCode WorkBuddy runner', launcher, args: ['--watchdog'] });
+ const nextEnv=`${marker}\nWORKBUDDY_REMOTE_DEBUGGING_PORT=${value}\n`,undos=[];
+ try {
+ undos.push(()=>undoFileChange(paths.desktop,beforeDesktop,nextDesktop));
+ desktop.write(nextDesktop);
+ undos.push(()=>undoFileChange(paths.environment,beforeEnv,nextEnv));
+ replace(paths.environment,beforeEnv,nextEnv);
+ return {rollback(){rollbackSteps(undos);}};
+ } catch(error){rollbackSteps(undos,error);}
},
remove() {
desktop.assertAbsentOrOwned(); const previous = checkEnv();
diff --git a/scripts/workbuddy-windows-wiring.mjs b/scripts/workbuddy-windows-wiring.mjs
new file mode 100644
index 0000000..b9a155d
--- /dev/null
+++ b/scripts/workbuddy-windows-wiring.mjs
@@ -0,0 +1,46 @@
+import path from 'node:path';
+import { renderWindowsStartupVbs, startupDirectory } from './portable-runtime.mjs';
+import { updateOwnedPort, windowsPortRegistry } from './windows-owned-env.mjs';
+import { readOwnedFile, replaceOwnedFile, undoFileChange, rollbackSteps } from './owned-file.mjs';
+
+export function workbuddyWindowsPaths(env, home) {
+ const appData=env.APPDATA || path.join(home,'AppData','Roaming');
+ return {startup:path.join(startupDirectory(env,home),'beauticode-wb-runner.vbs'),legacy:path.join(appData,'beauticode-wb-runner.vbs')};
+}
+export function workbuddyWindowsWiring({env,home,launcher,journal,registry=windowsPortRegistry,replace=replaceOwnedFile}) {
+ const paths=workbuddyWindowsPaths(env,home),content=renderWindowsStartupVbs({launcher,args:['--watchdog']});
+ function inspect() {
+ const startup=readOwnedFile(paths.startup),legacy=readOwnedFile(paths.legacy);
+ if(startup!==null&&startup!==content)throw new Error('Startup file is not owned by this launcher; preserved.');
+ return {startup,legacy};
+ }
+ return {
+ install(port) {
+ const before=inspect(),oldValue=registry.read(),oldJournal=readOwnedFile(journal),undos=[];
+ const target={value:String(port),kind:'String'};
+ try {
+ // Register undo before the registry call: write verification can fail after a write.
+ undos.push(()=>{
+ const current=registry.read();
+ if(JSON.stringify(current)!==JSON.stringify(target)&&JSON.stringify(current)!==JSON.stringify(oldValue))throw new Error('Environment changed during install; preserved.');
+ registry.write(oldValue);
+ if(JSON.stringify(registry.read())!==JSON.stringify(oldValue))throw new Error('Environment recovery verification failed.');
+ const currentJournal=readOwnedFile(journal);
+ if(currentJournal!==oldJournal){const saved=JSON.parse(currentJournal);if(JSON.stringify(saved.written)!==JSON.stringify(target))throw new Error('Ownership journal changed; preserved.');replaceOwnedFile(journal,currentJournal,oldJournal);}
+ });
+ updateOwnedPort({journal,port,registry});
+ if(before.startup!==content){undos.push(()=>undoFileChange(paths.startup,before.startup,content));replace(paths.startup,before.startup,content);}
+ if(paths.legacy!==paths.startup&&before.legacy===content){undos.push(()=>undoFileChange(paths.legacy,content,null));replace(paths.legacy,content,null);}
+ return {rollback(){rollbackSteps(undos);}};
+ } catch(error){rollbackSteps(undos,error);}
+ },
+ remove() {
+ const before=inspect();
+ // Restore configuration first. A registry error must not already have removed startup.
+ const result=updateOwnedPort({journal,remove:true,registry});
+ if(before.startup===content)replace(paths.startup,content,null);
+ if(paths.legacy!==paths.startup&&before.legacy===content)replace(paths.legacy,content,null);
+ return result;
+ },
+ };
+}