Skip to content

Commit 578d3b1

Browse files
fix(cli): stage os skills writes and swap them in by rename, recording last (#35495)
Fixes #35079 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:`os skills install` / `update` 的写盘改为「先写进隐藏的暂存目录 → 逐个改名换入 → 最后改名落记录」,任何一步失败都按倒序撤回已做的改名。 - 为什么改:原先先删旧目录再写新文件、最后写记录;中途失败(磁盘满、权限、文件被占用)会让旧记录指向已删或半写的目录,下一次 `update` 必须加 `--force` 才能恢复。 - 风险与回滚:只动 `applySkillsWrite` 一处写路径;残留风险是进程被强杀(SIGKILL/断电)恰好落在纯改名的换入阶段,见 Acceptance notes。回滚即还原本 PR。 - 先看:`packages/cli/src/utils/skills-install-state.ts` 的 `applySkillsWrite` try/catch 与 `undoSwap`;其次 `packages/cli/test/skills-commands.test.ts` 末尾的新 describe 与顶部的 `node:fs` 故障注入。 - 两分钟验证:`pnpm --filter @objectstack/cli exec vitest run --project unit --maxWorkers=2 test/skills-commands.test.ts`,预期 34/34 通过(新增 4 例在修复前全红)。 - 需要你做的:无,席位落地。 ## What changes `applySkillsWrite` (`packages/cli/src/utils/skills-install-state.ts`) now writes in three phases, and the module header documents them: 1. **Stage.** Every new skill directory is written under `new/` inside one staging directory created in the skills directory itself (`SKILLS_STAGING_PREFIX` = `.objectstack-skills-staging-`, via `mkdtempSync`). Same filesystem as the targets, so every later step is a rename. 2. **Swap.** Each dropped skill is renamed aside into the staging directory's `old/`; each catalog skill's existing directory (recorded, or a conflict `install --force` adopted) is renamed aside, then its staged copy renamed into place. Rename-aside rather than rename-over, because a directory cannot be renamed over a non-empty one (POSIX `ENOTEMPTY`, Windows refuses outright). 3. **Record.** The record is written into the staging directory and renamed over `.objectstack-skills.json`: a file rename over a file is atomic on POSIX and replaces on Windows. Any throw in 1–3 undoes the renames already done, newest first, removes the staging directory and rethrows; the command prints the failure and exits 1 as before. If an undo itself fails, the error says which steps could not be undone and where the previous copies are, and the staging directory is kept. **What "the old skills and the record stay usable" means here: all or nothing across the skills.** A failure partway restores every skill, not only the one that failed, so the record never names a directory the failure removed nor one at a version it does not record. Per-skill would leave a mixed catalog under a record of one version, which `update` then refuses as changed locally: the defect this card files. **Leftovers.** The staging directory is hidden. `skillDirectories` already skips names starting with a dot, and `SKILL_NAME` requires a first letter or digit, so the plan, `status` and `inspectSkillsDir` never read it as a skill and no catalog skill can collide with it. Its contents sit one level deeper (`new/NAME`, `old/NAME`), so an agent loading `DIR/NAME/SKILL.md` does not load them either. The next write removes any `.objectstack-skills-staging-*` directory a killed run left (`removeStagingLeftovers`). Removing the staging directory after a successful write is best effort: a failure there is left for the next write and never masks the write's outcome. All path judgments (`underRoot`) still happen before the first write, unchanged, and the record is computed before the first write too. ## Tests The pin is a new top-level `describe` in the existing shared harness `packages/cli/test/skills-commands.test.ts` (the shared-harness rule). Failure injection: a hoisted `vi.mock('node:fs')` that passes everything through except the one `writeFileSync` / `renameSync` call `fault.when` matches, which throws `ENOSPC` once and disarms. Unarmed in every other test. - `it.each` over three failure points during `update` V1 → V2: a file of the second skill is written; the second skill is moved into place; the record is written after every skill is in place. Each asserts exit 1, the fault fired exactly once, and `ENOSPC` reaches the output. It then asserts V1 is intact (every file's bytes, record version, `status --version V1 --check --json` exit 0 with nothing missing, modified or extra, nothing hidden beside the record), and that a plain `update --version V2` with no `--force` lands V2 with no leftovers. - A staging directory a killed run left behind is not reported by `status` and is removed by the next plain `update`. Red before the fix: the new test commit 060bd8f, run against the unmodified source. Ablation after the fix: source restored to the base 6d833b5 with the fix committed, then put back with `git checkout HEAD`, the blob hash checked against HEAD, `git diff HEAD` empty. <details><summary>Red before (060bd8f, unmodified source) and ablation (b555879, source restored to 6d833b5): 4 failed | 30 passed (34), both runs</summary> ```text × the disk fails as a file of the second skill is written ... AssertionError: expected 'data v2' to be 'data v1' × the disk fails as the second skill is moved into place ... AssertionError: expected +0 to be 1 (the old code has no rename, so the fault never fires and the update "succeeds") × the disk fails as the record is written, after every skill is in place AssertionError: expected 'data v2' to be 'data v1' × a staging directory a killed run left behind ... status reports the leftover as a skill Test Files 1 failed (1) / Tests 4 failed | 30 passed (34) os-verify-lock: VERDICT command-exit 1 ``` In the first and third cases the old code had already rewritten `objectstack-data` at V2 under the V1 record, which is exactly the state `update` refuses without `--force`. The fourth case's red on the old source comes from the missing `SKILLS_STAGING_PREFIX` export, which makes the leftover's name visible: it shows that the export is needed, not that the old code mishandled a hidden leftover. Ablation restore proof: `git checkout HEAD -- packages/cli/src/utils/skills-install-state.ts`, then `git hash-object` = 36b9524 = the HEAD blob, `git diff HEAD` 0 lines, `git status --porcelain` empty. </details> ## Acceptance notes - **Residual window: a hard kill inside the swap phase.** A thrown failure is fully rolled back. A process killed without unwinding (SIGKILL, power loss; Node's default SIGINT also exits without running the catch) can still stop between two renames. The swap phase is renames only, after all the slow writing is done, so the window is small, but it exists. A kill there leaves some skills swapped under the old record, and `update` refuses those as changed locally. Closing it needs a journal that is read and replayed before the plan is computed, in `runSkillsWrite` (`packages/cli/src/utils/skills-command.ts`). That is outside this card's file surface, so it is noted, not built. A kill during the staging phase, which is where nearly all the time goes, leaves the old catalog untouched, and the next write removes the leftover. carrier: none. - The fault seam is a module-wide `vi.mock('node:fs')` in the shared harness, a pure pass-through while unarmed. No production seam was added for it. ## Verification All readings are on head b555879. The base is 6d833b5, and the 91 files `origin/main` has moved since then touch no skills file. <details><summary>Tests: the pin file 34/34; the cli unit tier 430 files / 6150 tests, all green</summary> ```text pnpm --filter @objectstack/cli exec vitest run --project unit --maxWorkers=2 test/skills-commands.test.ts Test Files 1 passed (1) / Tests 34 passed (34) / VERDICT command-exit 0 pnpm --filter @objectstack/cli exec vitest run --project unit --maxWorkers=2 Test Files 430 passed (430) / Tests 6150 passed (6150) / VERDICT command-exit 0 pnpm --filter @objectstack/cli build && pnpm --filter @objectstack/cli typecheck VERDICT command-exit 0; check:test-typecheck: OK (3 file(s) / 28 error(s) / 6 pinned signature(s) held, unchanged) ``` The `integration` tier was not run locally. CI runs it: this diff touches no integration-tier file and no spawn entry. </details> <details><summary>Gates: 64 derived by dispatch-gates.mjs; 61 exit 0, 3 NOT MEASURED (exit 3, prerequisite not met)</summary> ```text dispatch-gates --ran: 64 derived famil(ies) accounted for — 61 run, 3 NOT-MEASURED (3 DERIVED from a recorded exit 3) NOT MEASURED: node scripts/check-plugin-teardown-shape.mjs --self-test, reason: its positive control is pinned to a commit this shallow clone cannot reach NOT MEASURED: pnpm check:dual-build-cjs-loads, reason: it reads built output, and 14 packages outside this diff's closure have no dist/ in this worktree NOT MEASURED: pnpm check:i18n-coverage, reason: examples/app-showcase could not load, because @objectstack/connector-slack has no build output here overlap-check: VERDICT clean exit 0 (origin/main merges cleanly, 0 open PR heads share a file) ``` CI covers all three, in Lint and Repo Gates. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01L6bhgTyMahdAdhXSzgy2nt)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent eb1f85d commit 578d3b1

3 files changed

Lines changed: 239 additions & 14 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@objectstack/cli': patch
3+
---
4+
5+
fix(cli): `os skills install` and `os skills update` stage the new catalog and swap it in by rename, so a write that fails partway leaves the previous skills and their record as they were
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
Before, a write removed the recorded skill directories first, then wrote the new ones, and wrote the record last: a failure partway (disk full, permission, a locked file) left the directories gone or half-written under the old record, and the next `os skills update` refused them as changed locally until it was given `--force`. Now every new skill directory is written into a hidden staging directory inside the skills directory, each touched skill is renamed aside and its staged copy renamed into place, and the record is renamed over the old one last; any failure undoes the renames already done and is reported, so the catalog is either wholly the old one or wholly the new one, and a plain `os skills update` simply runs again. A staging directory a killed run leaves behind (`.objectstack-skills-staging-*`) is hidden, never read as a skill, and removed by the next write.

‎packages/cli/src/utils/skills-install-state.ts‎

Lines changed: 109 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -19,17 +19,44 @@
1919
* - `modified` — a recorded skill with a file changed, removed or added;
2020
* - `extra` — a skill directory the record does not name (the user's own,
2121
* reported and left alone).
22+
*
23+
* ## The write ({@link applySkillsWrite})
24+
*
25+
* Staged, swapped by rename, recorded last — so a write that fails partway
26+
* (disk full, permission, a locked file) leaves the previous catalog and its
27+
* record exactly as they were, and a plain `update` simply runs again:
28+
*
29+
* 1. every new skill directory is written into a staging directory inside
30+
* `dir` ({@link SKILLS_STAGING_PREFIX}, hidden, so on the same filesystem
31+
* and never read as a skill);
32+
* 2. each touched skill directory is renamed aside into the staging directory
33+
* and its staged copy renamed into place;
34+
* 3. the record is written into the staging directory and renamed over the
35+
* old one.
36+
*
37+
* Any failure in 1–3 undoes the renames already done, newest first, so it is
38+
* all or nothing across the skills: the record never names a directory the
39+
* failure removed, nor a directory at a version it does not record. The
40+
* staging directory goes last; one a killed run left behind is hidden, so
41+
* `status` and the plan ignore it, and the next write removes it.
2242
*/
2343

2444
import { createHash } from 'node:crypto';
25-
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
45+
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
2646
import { dirname, join, relative, resolve, sep } from 'node:path';
2747

2848
import { SKILLS_PACKAGE, SKILL_NAME, isExactVersion, isSafePathSegment, type SkillsCatalog } from './skills-catalog.js';
2949

3050
/** The record's file name, inside the skills directory. */
3151
export const SKILLS_MANIFEST_FILE = '.objectstack-skills.json';
3252

53+
/**
54+
* The name prefix of the staging directory a write builds inside the skills
55+
* directory. Hidden (a skill name starts with a letter or a digit), so neither
56+
* an agent nor {@link inspectSkillsDir} reads it as a skill.
57+
*/
58+
export const SKILLS_STAGING_PREFIX = '.objectstack-skills-staging-';
59+
3360
/** Where a Claude Code project keeps its skills, relative to the working directory. */
3461
export const DEFAULT_SKILLS_DIR = join('.claude', 'skills');
3562

@@ -192,33 +219,103 @@ function underRoot(root: string, target: string): string {
192219
return resolved;
193220
}
194221

222+
/** One undoable rename of {@link applySkillsWrite}'s swap. */
223+
interface SwapStep {
224+
from: string;
225+
to: string;
226+
}
227+
195228
/**
196229
* Write `catalog` into `dir` along `plan`: remove each dropped skill, replace
197230
* each recorded one and each conflict (the caller decided those may go), add
198231
* the rest, then write the record last. Only directories the plan names are
199-
* touched.
232+
* touched, and a failure partway leaves `dir` as it was (see the module
233+
* header), rethrowing the failure.
200234
*/
201235
export function applySkillsWrite(dir: string, catalog: SkillsCatalog, plan: SkillsWritePlan): SkillsManifest {
202236
// Every target is judged before the first write, so a refusal leaves the directory as it was.
203-
const dropped = plan.dropped.map((name) => underRoot(dir, join(dir, name)));
237+
const dropped = plan.dropped.map((name) => ({ name, root: underRoot(dir, join(dir, name)) }));
204238
const writes = [...catalog.skills].map(([name, files]) => {
205239
const root = underRoot(dir, join(dir, name));
206-
return { root, files: [...files].map(([path, bytes]) => ({ target: underRoot(root, join(root, ...path.split('/'))), bytes })) };
240+
return { name, root, files: [...files].map(([path, bytes]) => ({ rel: relative(root, underRoot(root, join(root, ...path.split('/')))), bytes })) };
207241
});
242+
const manifest = manifestForCatalog(catalog);
243+
208244
mkdirSync(dir, { recursive: true });
209-
for (const target of dropped) rmSync(target, { recursive: true, force: true });
210-
for (const { root, files } of writes) {
211-
rmSync(root, { recursive: true, force: true });
212-
for (const { target, bytes } of files) {
213-
mkdirSync(dirname(target), { recursive: true });
214-
writeFileSync(target, bytes);
245+
removeStagingLeftovers(dir);
246+
const staging = mkdtempSync(join(dir, SKILLS_STAGING_PREFIX));
247+
const staged = join(staging, 'new');
248+
const aside = join(staging, 'old');
249+
const done: SwapStep[] = [];
250+
const move = (from: string, to: string) => {
251+
renameSync(from, to);
252+
done.push({ from, to });
253+
};
254+
try {
255+
for (const { name, files } of writes) {
256+
for (const { rel, bytes } of files) {
257+
const target = join(staged, name, rel);
258+
mkdirSync(dirname(target), { recursive: true });
259+
writeFileSync(target, bytes);
260+
}
261+
}
262+
mkdirSync(aside);
263+
for (const { name, root } of dropped) {
264+
if (existsSync(root)) move(root, join(aside, name));
265+
}
266+
for (const { name, root } of writes) {
267+
if (existsSync(root)) move(root, join(aside, name));
268+
move(join(staged, name), root);
269+
}
270+
const record = join(staging, SKILLS_MANIFEST_FILE);
271+
writeFileSync(record, `${JSON.stringify(manifest, null, 2)}\n`);
272+
renameSync(record, join(dir, SKILLS_MANIFEST_FILE));
273+
} catch (error) {
274+
const stuck = undoSwap(done);
275+
if (stuck.length === 0) removeStaging(staging);
276+
else {
277+
(error as Error).message += ` Restoring the previous skills failed too (${stuck.join('; ')}); `
278+
+ `their copies are in ${aside}: move them back into ${dir} before running \`os skills\` again.`;
215279
}
280+
throw error;
216281
}
217-
const manifest = manifestForCatalog(catalog);
218-
writeFileSync(join(dir, SKILLS_MANIFEST_FILE), `${JSON.stringify(manifest, null, 2)}\n`);
282+
removeStaging(staging);
219283
return manifest;
220284
}
221285

286+
/**
287+
* Remove a staging directory, best effort: one that will not go is hidden and
288+
* read by nothing, and the next write removes it ({@link removeStagingLeftovers}),
289+
* so its failure never masks the outcome of the write it served.
290+
*/
291+
function removeStaging(staging: string): void {
292+
try {
293+
rmSync(staging, { recursive: true, force: true });
294+
} catch {
295+
// Left for the next write.
296+
}
297+
}
298+
299+
/** Undo `done`, newest first, trying every step; the steps that could not be undone, described. */
300+
function undoSwap(done: SwapStep[]): string[] {
301+
const stuck: string[] = [];
302+
for (const { from, to } of [...done].reverse()) {
303+
try {
304+
renameSync(to, from);
305+
} catch (error) {
306+
stuck.push(`${to} → ${from}: ${(error as Error).message}`);
307+
}
308+
}
309+
return stuck;
310+
}
311+
312+
/** Remove the staging directories an earlier, killed write left in `dir`. */
313+
function removeStagingLeftovers(dir: string): void {
314+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
315+
if (entry.isDirectory() && entry.name.startsWith(SKILLS_STAGING_PREFIX)) rmSync(join(dir, entry.name), { recursive: true, force: true });
316+
}
317+
}
318+
222319
/** One line per modified skill, for the text face: what changed, was removed or was added. */
223320
export function describeModifiedSkill(m: ModifiedSkill): string {
224321
const parts = [

‎packages/cli/test/skills-commands.test.ts‎

Lines changed: 120 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,18 +12,40 @@
1212
*/
1313

1414
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
15-
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
15+
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
1616
import { tmpdir } from 'node:os';
1717
import { dirname, join } from 'node:path';
1818
import { fileURLToPath } from 'node:url';
1919
import { gzipSync } from 'node:zlib';
2020
import { Config } from '@oclif/core';
2121

22+
/**
23+
* A disk failure on demand, for the interrupted-write pins at the end of this
24+
* file: `node:fs` passes straight through, except the one `writeFileSync` /
25+
* `renameSync` call `fault.when` matches, which throws `ENOSPC` once and
26+
* disarms. Unarmed — every other test — nothing differs.
27+
*/
28+
const fault = vi.hoisted(() => ({ when: null as null | ((op: string, args: unknown[]) => boolean), fired: 0 }));
29+
vi.mock('node:fs', async (importOriginal) => {
30+
const actual = await importOriginal<typeof import('node:fs')>();
31+
const inject = <F extends (...args: any[]) => any>(op: string, fn: F): F => ((...args: Parameters<F>) => {
32+
if (fault.when?.(op, args)) {
33+
fault.when = null;
34+
fault.fired += 1;
35+
throw Object.assign(new Error(`ENOSPC: no space left on device, ${op} '${String(args[op === 'renameSync' ? 1 : 0])}'`), { code: 'ENOSPC' });
36+
}
37+
return fn(...args);
38+
}) as F;
39+
const writeFileSync = inject('writeFileSync', actual.writeFileSync);
40+
const renameSync = inject('renameSync', actual.renameSync);
41+
return { ...actual, default: { ...actual, writeFileSync, renameSync }, writeFileSync, renameSync };
42+
});
43+
2244
const { default: SkillsInstall } = await import('../src/commands/skills/install.js');
2345
const { default: SkillsUpdate } = await import('../src/commands/skills/update.js');
2446
const { default: SkillsStatus } = await import('../src/commands/skills/status.js');
2547
const { skillsRegistry, catalogFromTarball, resolveSkillsVersion, npmPackInvocation } = await import('../src/utils/skills-catalog.js');
26-
const { SKILLS_MANIFEST_FILE, applySkillsWrite, readSkillsManifest } = await import('../src/utils/skills-install-state.js');
48+
const { SKILLS_MANIFEST_FILE, SKILLS_STAGING_PREFIX, applySkillsWrite, readSkillsManifest } = await import('../src/utils/skills-install-state.js');
2749

2850
const PKG = dirname(dirname(fileURLToPath(import.meta.url)));
2951
// The oclif config is loaded once, here: a clocked test window measures the commands, never this load.
@@ -458,3 +480,99 @@ describe('a malformed record is refused whole', () => {
458480
expect(() => readSkillsManifest(root)).toThrow(/cannot read/);
459481
});
460482
});
483+
484+
describe('an interrupted write leaves the installed catalog usable', () => {
485+
let work = '';
486+
const prevCwd = process.cwd();
487+
let output: string[] = [];
488+
489+
beforeEach(() => {
490+
work = mkdtempSync(join(tmpdir(), 'os-skills-35079-'));
491+
process.chdir(work);
492+
output = [];
493+
fault.when = null;
494+
fault.fired = 0;
495+
const record = (...args: unknown[]) => { output.push(args.map(String).join(' ').replace(/\u001b\[[0-9;]*m/g, '')); };
496+
vi.spyOn(console, 'log').mockImplementation(record);
497+
vi.spyOn(console, 'error').mockImplementation(record);
498+
stubRegistry({ [V1]: CATALOG_V1, [V2]: CATALOG_V2 });
499+
});
500+
501+
afterEach(() => {
502+
fault.when = null;
503+
process.chdir(prevCwd);
504+
vi.unstubAllGlobals();
505+
vi.restoreAllMocks();
506+
rmSync(work, { recursive: true, force: true });
507+
});
508+
509+
async function run(command: { run(argv: string[], opts?: Config): Promise<unknown> }, argv: string[]): Promise<number> {
510+
try {
511+
await command.run(argv, CONFIG);
512+
return 0;
513+
} catch (err: any) {
514+
const exit = err?.oclif?.exit ?? err?.exitCode;
515+
if (exit === undefined) throw err;
516+
return exit;
517+
}
518+
}
519+
520+
const skillsDir = () => join(work, '.claude', 'skills');
521+
const read = (...parts: string[]) => readFileSync(join(skillsDir(), ...parts), 'utf8');
522+
const hidden = () => readdirSync(skillsDir()).filter((name) => name.startsWith('.')).sort();
523+
524+
/** V1 as installed: every file, the record, a clean `status --check`, and nothing hidden left beside the record. */
525+
async function expectV1Intact() {
526+
expect(read('objectstack-data', 'SKILL.md')).toBe('data v1');
527+
expect(read('objectstack-data', 'rules', 'naming.md')).toBe('snake_case v1');
528+
expect(read('objectstack-query', 'SKILL.md')).toBe('query v1');
529+
expect(read('objectstack-legacy', 'SKILL.md')).toBe('legacy v1');
530+
expect(existsSync(join(skillsDir(), 'objectstack-ask'))).toBe(false);
531+
expect(JSON.parse(read(SKILLS_MANIFEST_FILE)).version).toBe(V1);
532+
output = [];
533+
expect(await run(SkillsStatus, ['--version', V1, '--check', '--json'])).toBe(0);
534+
expect(JSON.parse(output.join('\n'))).toMatchObject({ installedVersion: V1, missing: [], modified: [], extra: [], mismatch: false });
535+
expect(hidden()).toEqual([SKILLS_MANIFEST_FILE]);
536+
}
537+
538+
/** A plain `update` — no `--force` — then lands V2. */
539+
async function expectPlainUpdateRecovers() {
540+
output = [];
541+
expect(await run(SkillsUpdate, ['--version', V2])).toBe(0);
542+
expect(read('objectstack-data', 'SKILL.md')).toBe('data v2');
543+
expect(read('objectstack-ask', 'SKILL.md')).toBe('ask v2');
544+
expect(existsSync(join(skillsDir(), 'objectstack-legacy'))).toBe(false);
545+
expect(JSON.parse(read(SKILLS_MANIFEST_FILE)).version).toBe(V2);
546+
expect(hidden()).toEqual([SKILLS_MANIFEST_FILE]);
547+
}
548+
549+
it.each([
550+
['a file of the second skill is written', (op: string, args: unknown[]) =>
551+
op === 'writeFileSync' && String(args[0]).endsWith(join('objectstack-query', 'SKILL.md'))],
552+
['the second skill is moved into place', (op: string, args: unknown[]) =>
553+
op === 'renameSync' && String(args[1]) === join(skillsDir(), 'objectstack-query')],
554+
['the record is written, after every skill is in place', (op: string, args: unknown[]) =>
555+
String(op === 'renameSync' ? args[1] : args[0]) === join(skillsDir(), SKILLS_MANIFEST_FILE)],
556+
])('the disk fails as %s: the old skills and the record stay as they were, and a plain update recovers', async (_label, when) => {
557+
expect(await run(SkillsInstall, ['--version', V1])).toBe(0);
558+
fault.when = when;
559+
output = [];
560+
expect(await run(SkillsUpdate, ['--version', V2])).toBe(1);
561+
expect(fault.fired).toBe(1);
562+
expect(output.join('\n')).toContain('ENOSPC');
563+
await expectV1Intact();
564+
await expectPlainUpdateRecovers();
565+
});
566+
567+
it('a staging directory a killed run left behind is not read as a skill, and the next write removes it', async () => {
568+
expect(await run(SkillsInstall, ['--version', V1])).toBe(0);
569+
const leftover = join(skillsDir(), `${SKILLS_STAGING_PREFIX}killed`);
570+
mkdirSync(join(leftover, 'new', 'objectstack-ask'), { recursive: true });
571+
writeFileSync(join(leftover, 'new', 'objectstack-ask', 'SKILL.md'), 'half-written');
572+
output = [];
573+
expect(await run(SkillsStatus, ['--version', V1, '--check', '--json'])).toBe(0);
574+
expect(JSON.parse(output.join('\n'))).toMatchObject({ missing: [], modified: [], extra: [], mismatch: false });
575+
await expectPlainUpdateRecovers();
576+
expect(existsSync(leftover)).toBe(false);
577+
});
578+
});

0 commit comments

Comments
 (0)