Skip to content
Python

feat(skills): confirm replacement and retain installation backups

Rohit P8b27b396814d
diff --git a/docs/harness/guides/desktop.md b/docs/harness/guides/desktop.md
index da049d7e..e5c54064 100644
--- a/docs/harness/guides/desktop.md
+++ b/docs/harness/guides/desktop.md
@@ -64,8 +64,9 @@ npx @openworkerai/openworker-harness-builder --agent claude --project .
Open a new coding-agent session in that project. The installer copies the same
skill, SDK snippets and Desktop/Web references into the tool's project skills directory.
For all your projects on this machine, replace `--project .` with `--global`.
-That installs to your user skills directory; neither mode overwrites an existing
-skill. Both project and global installation are available in the published Skill.
+That installs to your user skills directory. Existing installs prompt before
+replacement; `--replace-existing` skips the prompt. Both save a backup outside the
+active skills directory. Non-interactive updates require the flag.
See the [skill installation guide](../../../skills/README.md) for availability,
local candidate installation and invocation details.
diff --git a/docs/harness/guides/server.md b/docs/harness/guides/server.md
index 120b8c26..28134d7a 100644
--- a/docs/harness/guides/server.md
+++ b/docs/harness/guides/server.md
@@ -64,8 +64,9 @@ npx @openworkerai/openworker-harness-builder --agent claude --project .
Open a new coding-agent session in that project. The installer copies the same
skill, SDK snippets and Desktop/Web references into the tool's project skills directory.
For all your projects on this machine, replace `--project .` with `--global`.
-That installs to your user skills directory; neither mode overwrites an existing
-skill. Both project and global installation are available in the published Skill.
+That installs to your user skills directory. Existing installs prompt before
+replacement; `--replace-existing` skips the prompt. Both save a backup outside the
+active skills directory. Non-interactive updates require the flag.
See the [skill installation guide](../../../skills/README.md) for availability,
local candidate installation and invocation details.
diff --git a/harness/typescript-sdk/README.md b/harness/typescript-sdk/README.md
index 86113df2..4a1a305f 100644
--- a/harness/typescript-sdk/README.md
+++ b/harness/typescript-sdk/README.md
@@ -24,6 +24,11 @@ npx @openworkerai/openworker-harness-builder --agent codex --project .
# For Claude Code, use --agent claude. For user-wide installation, use --global.
```
+If the Skill is already installed, interactive runs ask before replacing it.
+Use `--replace-existing` for an explicit update without prompting. Both paths
+save a backup outside the active skills directory; non-interactive updates require
+the flag. See the [Skill update instructions](../../skills/README.md#update-an-existing-installation).
+
See the [Desktop guide](https://openworker.com/docs/sdk/desktop/),
[Web guide](https://openworker.com/docs/sdk/server/) or the bundled
[plain Node file-organizer example](../../skills/openworker-harness-builder/references/local-script.md).
diff --git a/skills/README.md b/skills/README.md
index 032b7b4a..d16070e8 100644
--- a/skills/README.md
+++ b/skills/README.md
@@ -24,8 +24,8 @@ npx @openworkerai/openworker-harness-builder --agent claude --project .
These project commands create `.agents/skills/openworker-harness-builder/` for Codex or
`.claude/skills/openworker-harness-builder/` for Claude Code. It supports quoted project paths
-on Windows and macOS, leaves global settings alone, and refuses to overwrite an
-existing skill. Review/back up an existing installation before replacing it.
+on Windows and macOS and leaves global settings alone. If a skill already exists,
+an interactive terminal asks before replacing it and saves the old copy as a backup.
`references/installation.json` records the matching SDK version, without local
checkout paths or credentials. Use `sdkVersion` from that file for the SDK. Skill and SDK package versions may
differ; this skill release targets SDK `0.1.0-beta.3`.
@@ -46,8 +46,45 @@ This installs into `~/.claude/skills/openworker-harness-builder/` for Claude Cod
`~/.agents/skills/openworker-harness-builder/` for Codex, making the skill available across
projects for your user on this machine. It does not install into Claude web or
Cowork, change account settings, or require `npm install -g` or administrator
-access. Choose either `--global` or `--project`, not both. Both modes preserve an
-existing installation.
+access. Choose either `--global` or `--project`, not both. Both modes require
+confirmation or the explicit replacement flag before replacing an existing skill.
+
+### Update an existing installation
+
+Run the same install command again. In an interactive terminal it asks:
+
+```text
+Replace the existing skill? A backup will be saved. [y/N]
+```
+
+Enter `y` or `yes` to replace it. Enter or `n` leaves it unchanged. For scripts,
+or to skip the prompt explicitly, use:
+
+```sh
+npx @openworkerai/openworker-harness-builder --agent claude --global --replace-existing
+```
+
+```sh
+npx @openworkerai/openworker-harness-builder --agent codex --project . --replace-existing
+```
+
+Non-interactive installs never prompt and require `--replace-existing` to update.
+Every replacement saves the complete old directory, including custom files, under
+`.claude/skill-backups/` or `.agents/skill-backups/` in the selected project or home.
+The installer prints the exact backup path. Backups are outside the active skills
+directory, so coding agents do not load duplicates. A new complete copy replaces
+the old one; obsolete files are not merged into it. If activation fails, the
+installer attempts to restore the previous copy and reports its backup location
+if automatic restoration fails. Review customizations before copying any back.
+
+An interrupted installer can leave an installation lock in `.claude/` or `.agents/`.
+If the next install reports that lock, first confirm no installer is running,
+then review and remove the reported lock directory before retrying. Existing
+backups are never automatically deleted.
+
+Skill and SDK publications are independent: updating this Skill does not replace
+the README inside an already-installed SDK package. Use the bundled version-matched
+references for these examples and `installation.json` for the exact SDK pin.
Unversioned commands select npm's `latest` release. To pin an installation for
reproducibility, append `@<version>` to the package name. The installer records
@@ -97,7 +134,7 @@ node skills/prepare.mjs /absolute/new-skills-candidate
Install the resulting archive into a temporary project or use it through npm exec:
```sh
-npm exec --package /absolute/new-skills-candidate/archives/openworkerai-openworker-harness-builder-0.1.0-beta.5.tgz -- openworker-harness-builder --agent codex --project /path/to/your-app
+npm exec --package /absolute/new-skills-candidate/archives/openworkerai-openworker-harness-builder-0.1.0-beta.6.tgz -- openworker-harness-builder --agent codex --project /path/to/your-app
```
The preparer never publishes. Source package manifests remain private; staged
@@ -144,4 +181,4 @@ cancellation, graceful shutdown, unchanged session references after redeployment
and real Anthropic recall of earlier conversation content. This qualifies the
single-service recipe; it does not establish multi-replica or zero-downtime behavior.
-When upgrading from the earlier `openworker-apps` skill, review and remove that old skill from the same installation scope after installing the new name. The installer preserves existing skill directories and local customizations.
+When upgrading from the earlier `openworker-apps` skill, review and remove that old skill from the same installation scope after installing the new name. Replacement applies only to `openworker-harness-builder`; the old-named skill is left untouched.
diff --git a/skills/install.mjs b/skills/install.mjs
index 7a8c6477..d4d5c3ba 100644
--- a/skills/install.mjs
+++ b/skills/install.mjs
@@ -1,63 +1,135 @@
#!/usr/bin/env node
-// Project or user-wide installation; never overwrite an existing skill.
-import { mkdir, lstat, realpath, readFile, writeFile } from 'node:fs/promises';
+// Project or user-wide installation with explicit replacement and retained backups.
+import { mkdir, mkdtemp, lstat, realpath, readFile, writeFile, rename, rm, rmdir } from 'node:fs/promises';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { homedir } from 'node:os';
import { parseArgs } from 'node:util';
+import { createInterface } from 'node:readline/promises';
+import { stdin, stdout, stderr } from 'node:process';
const source = dirname(fileURLToPath(import.meta.url));
-const usage = 'openworker-harness-builder --agent codex|claude (--project /path/to/your-app | --global)';
+const usage = 'openworker-harness-builder --agent codex|claude (--project /path/to/your-app | --global) [--replace-existing]';
const files = ['SKILL.md','references/desktop.md','references/web.md','references/sdk.md','references/tools.md','references/approvals.md','references/local-script.md','references/runtime-options.md','references/subagents.md','references/observability.md','references/railway.md','assets/railway/Dockerfile','assets/railway/.dockerignore','assets/local-script/file-tools.mjs','assets/local-script/organizer.mjs','agents/openai.yaml'];
-function validate({agent, project, global: userWide = false}) {
- if (!['codex','claude'].includes(agent) || typeof userWide !== 'boolean' ||
+function validate({agent, project, global: userWide = false, replaceExisting = false}) {
+ if (!['codex','claude'].includes(agent) || typeof userWide !== 'boolean' || typeof replaceExisting !== 'boolean' ||
(project !== undefined && (typeof project !== 'string' || !project.trim())) ||
userWide === (project !== undefined)) throw Error(`Use ${usage}; choose exactly one installation scope.`);
}
export function parseInstallArgs(args) {
- const {values} = parseArgs({args, options:{agent:{type:'string'}, project:{type:'string'}, global:{type:'boolean'}}});
- validate(values);
- return values;
+ const {values} = parseArgs({args, options:{agent:{type:'string'}, project:{type:'string'}, global:{type:'boolean'}, 'replace-existing':{type:'boolean'}}});
+ const {'replace-existing': replaceExisting, ...options} = values;
+ if (replaceExisting !== undefined) options.replaceExisting = replaceExisting;
+ validate(options);
+ return options;
+}
+async function realDirectory(path) {
+ try { await mkdir(path); } catch(error) { if(error.code !== 'EEXIST') throw error; }
+ const stat = await lstat(path);
+ if (stat.isSymbolicLink() || !stat.isDirectory()) throw Error(`Expected a real directory: ${path}`);
+}
+async function existingDirectory(path) {
+ try {
+ const stat = await lstat(path);
+ if (stat.isSymbolicLink() || !stat.isDirectory()) throw Error(`Expected a real skill directory: ${path}`);
+ return stat;
+ } catch(error) { if(error.code === 'ENOENT') return null; throw error; }
}
-export async function install(options, {userHome = homedir()} = {}) {
+export async function install(options, {
+ userHome = homedir(), confirmReplace, onBackup = () => {}, renamePath = rename,
+} = {}) {
validate(options);
- const {agent, project, global: userWide = false} = options;
+ const {agent, project, global: userWide = false, replaceExisting = false} = options;
const pkg = JSON.parse(await readFile(join(source,'package.json'),'utf8'));
- // Validate package completeness before creating an installation directory.
+ // Read and validate the complete package before touching an existing install.
const content = await Promise.all(files.map(name => readFile(join(source,'openworker-harness-builder',name))));
const root = await realpath(userWide ? userHome : project);
if (!(await lstat(root)).isDirectory()) throw Error('Installation root must be an existing directory.');
- let parent = root;
- for (const component of [agent === 'codex' ? '.agents' : '.claude', 'skills']) {
- parent = join(parent, component);
- try { await mkdir(parent); } catch(error) { if(error.code !== 'EEXIST') throw error; }
- const stat = await lstat(parent);
- if (stat.isSymbolicLink() || !stat.isDirectory()) throw Error(`Expected a real directory: ${parent}`);
- }
+ const settings = join(root, agent === 'codex' ? '.agents' : '.claude');
+ await realDirectory(settings);
+ const parent = join(settings, 'skills'); await realDirectory(parent);
const destination = join(parent, 'openworker-harness-builder');
- await mkdir(destination); // Exclusive: an existing install must be reviewed by its owner.
- for (const [index,name] of files.entries()) {
- await mkdir(dirname(join(destination,name)), {recursive:true});
- await writeFile(join(destination,name), content[index], {flag:'wx'});
+ // Serialize installers; an interrupted process leaves a visible, reviewable lock.
+ const lock = join(settings, '.openworker-harness-builder.install-lock');
+ try { await mkdir(lock); }
+ catch(error) {
+ if(error.code !== 'EEXIST') throw error;
+ throw Error(`Installation lock exists: ${lock}. If no installer is running, review and remove that lock directory before retrying.`);
+ }
+ let stage, backup, backupContainer, moved = false;
+ try {
+ const previous = await existingDirectory(destination);
+ if (previous && !replaceExisting) {
+ if (!confirmReplace) throw Object.assign(Error('An installation already exists. Run interactively to review replacement, or use --replace-existing to replace it with a backup.'), {code:'EEXIST'});
+ if (await confirmReplace(destination) !== true)
+ throw Object.assign(Error('Installation cancelled; existing skill unchanged.'), {code:'INSTALL_CANCELLED'});
+ }
+ // Staging and backups stay outside the watched skills directory, so neither
+ // partial installs nor old copies can be discovered as additional skills.
+ stage = await mkdtemp(join(settings, '.harness-builder-stage-'));
+ for (const [index,name] of files.entries()) {
+ await mkdir(dirname(join(stage,name)), {recursive:true});
+ await writeFile(join(stage,name), content[index], {flag:'wx'});
+ }
+ await writeFile(join(stage,'references/installation.json'), JSON.stringify({
+ package:pkg.name, version:pkg.version, sdkPackage:'@openworkerai/harness-sdk', sdkVersion:pkg.openworkerSdkVersion,
+ },null,2)+'\n', {flag:'wx'});
+ const current = await existingDirectory(destination);
+ if (!!previous !== !!current || (previous && (previous.ino !== current.ino || previous.dev !== current.dev)))
+ throw Error('The existing installation changed while preparing. Review it and retry.');
+ if (previous) {
+ const backupRoot = join(settings, 'skill-backups'); await realDirectory(backupRoot);
+ backupContainer = await mkdtemp(join(backupRoot, 'openworker-harness-builder-'));
+ backup = join(backupContainer, 'openworker-harness-builder');
+ await renamePath(destination, backup); moved = true;
+ }
+ try { await renamePath(stage, destination); stage = undefined; }
+ catch(error) {
+ if (moved) {
+ try { await renamePath(backup, destination); moved = false; }
+ catch { throw Error(`Replacement failed and the previous installation could not be restored automatically. Its backup is preserved at ${backup}. Inspect ${destination} before retrying.`, {cause:error}); }
+ throw Error('Replacement failed; the previous installation was restored.', {cause:error});
+ }
+ throw error;
+ }
+ } finally {
+ if(stage) await rm(stage, {recursive:true,force:true});
+ if(backupContainer && !moved) await rmdir(backupContainer);
+ await rmdir(lock);
}
- await writeFile(join(destination,'references/installation.json'), JSON.stringify({
- package:pkg.name, version:pkg.version, sdkPackage:'@openworkerai/harness-sdk', sdkVersion:pkg.openworkerSdkVersion,
- },null,2)+'\n');
+ if(backup) onBackup(backup);
return destination;
}
-// Canonicalize both sides: Windows may spell the same installed path with
-// different drive-letter casing or a short (8.3) temporary-directory name.
+export async function runCli(args, {input = stdin, output = stdout, errorOutput = stderr, userHome = homedir()} = {}) {
+ if(args.length === 1 && args[0] === '--help') {
+ output.write(`${usage}\n--global installs across projects for this user (Codex: ~/.agents/skills; Claude Code: ~/.claude/skills).\nExisting skills prompt in an interactive terminal; --replace-existing skips that prompt.\nReplacements always save a backup outside the active skills directory.\n`);
+ return 0;
+ }
+ try {
+ const options = parseInstallArgs(args);
+ let backup;
+ const confirmReplace = input.isTTY && output.isTTY ? async destination => {
+ output.write(`Existing skill: ${destination}\n`);
+ const terminal = createInterface({input,output,terminal:false});
+ const controller = new AbortController();
+ terminal.once('close',()=>controller.abort());
+ try {
+ const answer = await terminal.question('Replace the existing skill? A backup will be saved. [y/N] ', {signal:controller.signal});
+ return /^(y|yes)$/i.test(answer.trim());
+ } catch { return false; } // EOF/cancel never authorizes replacement.
+ finally { terminal.close(); }
+ } : undefined;
+ const destination = await install(options, {userHome,confirmReplace,onBackup:path => {backup = path;}});
+ if(backup) output.write(`Backup saved: ${backup}\n`);
+ output.write(`Installed: ${destination}\nOpen a new coding-agent session${options.global ? '' : ' in that project'} to use openworker-harness-builder.\n`);
+ return 0;
+ } catch(error) {
+ if(error.code === 'INSTALL_CANCELLED') { output.write(error.message+'\n'); return 0; }
+ errorOutput.write(error.message+'\n'); return 1;
+ }
+}
+// Canonicalize both sides for Windows directory casing and npm's symlinked bin.
const entryPath = process.argv[1] && await realpath(process.argv[1]).catch(() => resolve(process.argv[1]));
const modulePath = await realpath(fileURLToPath(import.meta.url));
const isMain = entryPath && (process.platform === 'win32'
- ? entryPath.toLowerCase() === modulePath.toLowerCase()
- : entryPath === modulePath);
-if (isMain) {
- const args=process.argv.slice(2);
- if(args.length===1 && args[0]==='--help') console.log(`${usage}\n--global installs for your user across projects on this machine (Codex: ~/.agents/skills; Claude Code: ~/.claude/skills).`);
- else {
- try {
- const options = parseInstallArgs(args);
- console.log(`Installed: ${await install(options)}\nOpen a new coding-agent session${options.global ? '' : ' in that project'} to use openworker-harness-builder.`);
- } catch(error) { console.error(error.code==='EEXIST' ? 'An installation already exists. Review or back it up before replacing it.' : error.message);process.exitCode=1; }
- }
-}
+ ? entryPath.toLowerCase() === modulePath.toLowerCase() : entryPath === modulePath);
+if (isMain) process.exitCode = await runCli(process.argv.slice(2));
diff --git a/skills/install.test.mjs b/skills/install.test.mjs
index 0df8defe..fac45130 100644
--- a/skills/install.test.mjs
+++ b/skills/install.test.mjs
@@ -1,9 +1,10 @@
import test from 'node:test';
import assert from 'node:assert/strict';
-import {mkdtemp,readFile,writeFile,rm,mkdir,symlink,readdir,realpath} from 'node:fs/promises';
+import {mkdtemp,readFile,writeFile,rm,mkdir,symlink,readdir,realpath,rename,lstat} from 'node:fs/promises';
import {tmpdir} from 'node:os';
-import {join} from 'node:path';
-import {install,parseInstallArgs} from './install.mjs';
+import {join,dirname,relative,sep} from 'node:path';
+import {PassThrough} from 'node:stream';
+import {install,parseInstallArgs,runCli} from './install.mjs';
for (const agent of ['codex','claude']) test(`install complete ${agent} skill; preserve existing content`, async()=>{
const root=await mkdtemp(join(tmpdir(),'ow skill '));
try {
@@ -45,13 +46,149 @@ test('require exactly one scope and reject unknown CLI arguments',async()=>{
try {
assert.deepEqual({...parseInstallArgs(['--global','--agent','claude'])},{global:true,agent:'claude'});
assert.deepEqual({...parseInstallArgs(['--project',root,'--agent','codex'])},{project:root,agent:'codex'});
+ assert.deepEqual({...parseInstallArgs(['--agent','claude','--global','--replace-existing'])},{agent:'claude',global:true,replaceExisting:true});
for(const args of [[],['--agent','claude'],['--global'],['--agent','claude','--global','--project',root],['--agent','claude','--global','extra'],['--agent','claude','--globall'],['--agent','claude','--project','']])
assert.throws(()=>parseInstallArgs(args));
await assert.rejects(install({agent:'claude',project:root,global:true},{userHome:root}),/exactly one/);
await assert.rejects(install({agent:'claude',global:'yes'},{userHome:root}),/exactly one/);
+ await assert.rejects(install({agent:'claude',global:true,replaceExisting:'yes'},{userHome:root}),/exactly one/);
assert.deepEqual(await readdir(root),[]);
} finally {await rm(root,{recursive:true,force:true});}
});
+
+for(const agent of ['codex','claude'])for(const global of [false,true]) {
+ const scope = global ? 'global' : 'project';
+ test(`${agent} ${scope} replacement backs up custom files and removes obsolete active files`,async()=>{
+ const root=await mkdtemp(join(tmpdir(),'ow-replace-'));
+ try {
+ const options={agent,...(global?{global:true}:{project:root})};
+ const dest=await install(options,{userHome:root});
+ await writeFile(join(dest,'SKILL.md'),'my customization');
+ await writeFile(join(dest,'obsolete.md'),'old reference');
+ const backups=[];
+ assert.equal(await install({...options,replaceExisting:true},{userHome:root,
+ confirmReplace:()=>{throw Error('Flag must not prompt');},onBackup:path=>backups.push(path)}),dest);
+ assert.equal(await readFile(join(backups[0],'SKILL.md'),'utf8'),'my customization');
+ assert.equal(await readFile(join(backups[0],'obsolete.md'),'utf8'),'old reference');
+ assert.ok(relative(dirname(dest),backups[0]).startsWith('..'+sep),'Backup is outside active skills');
+ assert.match(await readFile(join(dest,'SKILL.md'),'utf8'),/^name: openworker-harness-builder$/m);
+ await assert.rejects(lstat(join(dest,'obsolete.md')),{code:'ENOENT'});
+ await install({...options,replaceExisting:true},{userHome:root,onBackup:path=>backups.push(path)});
+ assert.notEqual(backups[0],backups[1]);
+ assert.equal(await readFile(join(backups[0],'SKILL.md'),'utf8'),'my customization');
+ assert.deepEqual(await readdir(dirname(dest)),['openworker-harness-builder']);
+ }finally{await rm(root,{recursive:true,force:true});}
+ });
+ test(`${agent} ${scope} CLI prompt accepts yes and defaults to no`,async()=>{
+ const root=await mkdtemp(join(tmpdir(),'ow-prompt-'));
+ try {
+ const options={agent,...(global?{global:true}:{project:root})};
+ const args=['--agent',agent,...(global?['--global']:['--project',root])];
+ const dest=await install(options,{userHome:root});
+ await writeFile(join(dest,'SKILL.md'),'prompt customization');
+ async function invoke(answer,tty=true) {
+ const input=new PassThrough(),output=new PassThrough(),errorOutput=new PassThrough();
+ input.isTTY=tty;output.isTTY=tty;
+ let text='',errors='',answered=false;
+ output.on('data',chunk=>{
+ text+=chunk.toString();
+ if(!answered&&text.includes('[y/N]')){answered=true;queueMicrotask(()=>input.end(answer===null?'':answer+'\n'));}
+ });
+ errorOutput.on('data',chunk=>{errors+=chunk.toString();});
+ const code=await runCli(args,{userHome:root,input,output,errorOutput});
+ input.destroy();output.destroy();errorOutput.destroy();
+ return {code,text,errors};
+ }
+ for(const answer of ['n','',null]) {
+ const result=await invoke(answer);
+ assert.equal(result.code,0);assert.match(result.text,/cancelled/);
+ assert.equal(await readFile(join(dest,'SKILL.md'),'utf8'),'prompt customization');
+ }
+ const noninteractive=await invoke('y',false);
+ assert.equal(noninteractive.code,1);assert.match(noninteractive.errors,/--replace-existing/);
+ assert.ok(!noninteractive.text.includes('[y/N]'));
+ const result=await invoke('yes');
+ assert.equal(result.code,0);assert.match(result.text,/Backup saved:/);
+ const backup=result.text.split('Backup saved: ')[1].split('\n')[0];
+ assert.equal(await readFile(join(backup,'SKILL.md'),'utf8'),'prompt customization');
+ assert.match(await readFile(join(dest,'SKILL.md'),'utf8'),/^name: openworker-harness-builder$/m);
+ }finally{await rm(root,{recursive:true,force:true});}
+ });
+}
+
+test('failed activation restores the complete previous installation',async()=>{
+ const root=await mkdtemp(join(tmpdir(),'ow-rollback-'));
+ try {
+ const options={agent:'claude',project:root};
+ const dest=await install(options);
+ await writeFile(join(dest,'SKILL.md'),'original');
+ await writeFile(join(dest,'custom.txt'),'keep me');
+ await assert.rejects(install({...options,replaceExisting:true},{renamePath:async(from,to)=>{
+ if(from.includes('.harness-builder-stage-'))throw Error('Simulated activation failure');
+ await rename(from,to);
+ }}),/previous installation was restored/);
+ assert.equal(await readFile(join(dest,'SKILL.md'),'utf8'),'original');
+ assert.equal(await readFile(join(dest,'custom.txt'),'utf8'),'keep me');
+ const settings=dirname(dirname(dest));
+ assert.deepEqual((await readdir(settings)).sort(),['skill-backups','skills']);
+ assert.deepEqual(await readdir(join(settings,'skill-backups')),[]);
+ }finally{await rm(root,{recursive:true,force:true});}
+});
+
+test('replacement rejects linked skill and backup directories without modifying existing files',async()=>{
+ const root=await mkdtemp(join(tmpdir(),'ow-replace-links-'));
+ const outside=await mkdtemp(join(tmpdir(),'ow-replace-outside-'));
+ try {
+ const options={agent:'codex',project:root};
+ const dest=await install(options);
+ await writeFile(join(dest,'SKILL.md'),'original');
+ await symlink(outside,join(root,'.agents/skill-backups'),'junction');
+ await assert.rejects(install({...options,replaceExisting:true}),/real directory/);
+ assert.equal(await readFile(join(dest,'SKILL.md'),'utf8'),'original');
+ assert.deepEqual(await readdir(outside),[]);
+ await rm(dest,{recursive:true});
+ await symlink(outside,dest,'junction');
+ await assert.rejects(install({...options,replaceExisting:true}),/real skill directory/);
+ assert.deepEqual(await readdir(outside),[]);
+ }finally{await rm(root,{recursive:true,force:true});await rm(outside,{recursive:true,force:true});}
+});
+
+test('backup failure leaves the active copy unchanged; failed rollback retains the original backup',async()=>{
+ const root=await mkdtemp(join(tmpdir(),'ow-backup-failure-'));
+ try {
+ const options={agent:'claude',project:root};
+ const dest=await install(options);
+ await writeFile(join(dest,'SKILL.md'),'original');
+ const backupRoot=join(root,'.claude/skill-backups');
+ await writeFile(backupRoot,'blocked backup path');
+ await assert.rejects(install({...options,replaceExisting:true}),/real directory/);
+ assert.equal(await readFile(join(dest,'SKILL.md'),'utf8'),'original');
+ await rm(backupRoot);
+ await assert.rejects(install({...options,replaceExisting:true},{renamePath:async(from,to)=>{
+ if(from!==dest)throw Error('Simulated activation and restoration failure');
+ await rename(from,to);
+ }}),/backup is preserved at/);
+ const backups=await readdir(backupRoot);
+ assert.equal(backups.length,1);
+ assert.equal(await readFile(join(backupRoot,backups[0],'openworker-harness-builder/SKILL.md'),'utf8'),'original');
+ await assert.rejects(lstat(join(root,'.claude/.openworker-harness-builder.install-lock')),{code:'ENOENT'});
+ }finally{await rm(root,{recursive:true,force:true});}
+});
+
+test('concurrent installer cannot replace an installation being reviewed',async()=>{
+ const root=await mkdtemp(join(tmpdir(),'ow-install-lock-'));
+ try {
+ const options={agent:'claude',project:root};await install(options);
+ let reached,finish;
+ const reviewing=new Promise(done=>{reached=done;});
+ const decision=new Promise(done=>{finish=done;});
+ const first=install(options,{confirmReplace:()=>{reached();return decision;}});
+ const declined=assert.rejects(first,{code:'INSTALL_CANCELLED'});
+ await reviewing;
+ await assert.rejects(install({...options,replaceExisting:true}),/Installation lock exists/);
+ finish(false);await declined;
+ }finally{await rm(root,{recursive:true,force:true});}
+});
for(const folder of ['.agents','.claude'])test(`user-wide install refuses a linked ${folder} directory`,async()=>{
const root=await mkdtemp(join(tmpdir(),'ow-global-linked-')),outside=await mkdtemp(join(tmpdir(),'ow-global-outside-'));
try {
diff --git a/skills/package.json b/skills/package.json
index fb0e4dae..cb805c16 100644
--- a/skills/package.json
+++ b/skills/package.json
@@ -1,6 +1,6 @@
{
"name": "@openworkerai/openworker-harness-builder",
- "version": "0.1.0-beta.5",
+ "version": "0.1.0-beta.6",
"description": "Install the OpenWorker app-building skill for Codex or Claude Code",
"type": "module",
"license": "MIT",
diff --git a/skills/package.test.mjs b/skills/package.test.mjs
index 4184791a..c7081c11 100644
--- a/skills/package.test.mjs
+++ b/skills/package.test.mjs
@@ -34,6 +34,7 @@ test('packed installer works outside the checkout without SDK or native dependen
: execFileSync(bin,args,{cwd:consumer,encoding:'utf8'});
assert.match(run(['--help']), /--agent codex\|claude/);
assert.match(run(['--help']), /--global/);
+ assert.match(run(['--help']), /--replace-existing/);
if(process.platform==='win32')assert.match(execFileSync(process.execPath,[join(installed.toUpperCase(),'install.mjs'),'--help'],{cwd:consumer,encoding:'utf8'}),/--agent codex\|claude/);
// Mock only the child's OS home resolver; never write to the developer's
// actual home or override HOME/USERPROFILE while exercising the real CLI.
@@ -59,6 +60,10 @@ test('packed installer works outside the checkout without SDK or native dependen
await writeFile(join(globalDest,'SKILL.md'),'personal customization');
assert.throws(()=>runGlobal(['--global','--agent',agent]));
assert.equal(await readFile(join(globalDest,'SKILL.md'),'utf8'),'personal customization');
+ const globalReplacement=runGlobal(['--global','--agent',agent,'--replace-existing']);
+ const globalBackup=globalReplacement.split('Backup saved: ')[1].split('\n')[0];
+ assert.equal(await readFile(join(globalBackup,'SKILL.md'),'utf8'),'personal customization');
+ assert.match(await readFile(join(globalDest,'SKILL.md'),'utf8'),/^name: openworker-harness-builder$/m);
for (const folder of ['', 'references', 'agents']) {
for (const file of await readdir(join(dest,folder))) {
if (!/\.(md|json|yaml)$/.test(file)) continue;
@@ -73,6 +78,10 @@ test('packed installer works outside the checkout without SDK or native dependen
await writeFile(join(dest,'SKILL.md'),'developer customization');
assert.throws(() => run(['--agent',agent,'--project',project]));
assert.equal(await readFile(join(dest,'SKILL.md'),'utf8'),'developer customization');
+ const replacement=run(['--agent',agent,'--project',project,'--replace-existing']);
+ const backup=replacement.split('Backup saved: ')[1].split('\n')[0];
+ assert.equal(await readFile(join(backup,'SKILL.md'),'utf8'),'developer customization');
+ assert.match(await readFile(join(dest,'SKILL.md'),'utf8'),/^name: openworker-harness-builder$/m);
}
} finally { await rm(root, {recursive:true,force:true}); }
});