Skip to content

Commit ae2a67d

Browse files
revert(cli): stage os skills writes and swap them in by rename, recording last (#35495) (#35616)
Fixes #35588 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:用命令行安装或更新技能包的开发者,回到上一个发布版的写入方式:更新中途失败(磁盘满、权限不足)时,技能目录可能新旧混杂,要再强制更新一次才能恢复。 - 为什么做:为主干每四小时一次的全量检查解决变红,它被技能写入新加的暂存目录卡住;按席位指令先撤回那次改动,让主干恢复全绿。 - 出错会怎样:本次只删不增,和原改动逐字节相反,影响只在技能安装与更新两条命令;万一有问题,可以直接撤回本次撤回。 - 要你做什么:无 ## This is a revert This PR reverts #35495 (578d3b1) and nothing else. The diff is byte-identical to the inverse of that commit (`cmp` of the two patches, exit 0). **Why.** #35495 added a staging directory, `mkdtempSync(join(dir, SKILLS_STAGING_PREFIX))` in `applySkillsWrite`. Its base `dir` is the caller's skills directory, which is cwd-relative (`resolveSkillsDir(args.dir, cwd)`). The dispatch-gates scratch-dir scan reads one file at a time and treats a cwd-relative base as unreadable on purpose, so the self-test case "no mkdtempSync site in this tree takes a base the scan cannot read" fails on that line. That one case of 2564 is what keeps main's scheduled full Lint & Type Check run red (#35588). No honest spelling inside the CLI file lets the scan read that base. Every spelling that turns the case green does so by a lie (a `tmpdir()` marker, a fabricated binding) or an evasion (`mkdirSync`, an aliased import), and the gate is not narrowed. The measurements are on #35588 (comment 7016701837). The seat ordered this revert as the named fallback. **What returns.** The defect #35079 addressed comes back: an `os skills install` or `os skills update` that fails partway (disk full, permission, a locked file) can again leave the skill directories gone or half-written under the old record, and the next plain `update` refuses them as changed locally until `--force`. #35079 reopens. **Re-landing.** The staged swap re-lands only after a gate-side ruling on how the scan judges a directory-creating call whose base is a caller's argument. Even a cross-file hop ends at `process.cwd()`, and a killed run at this repo's root would leave `.claude/skills/.objectstack-skills-staging-*`, which no tracked ignore rule covers. So the rule needs a policy, not a reading. That decision is outside this PR, and `scripts/pm/dispatch-gates.mjs` is untouched. ## DELIBERATE CORRECTION This PR deletes one pending release note it did not add: `.changeset/35079-skills-write-staged-swap.md`. It was never released. The behaviour it describes is the code this PR reverts, so the note would now be false. Its headline sentence, quoted as it stood on the merge base: "`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". Corrected to: no note. With the note gone, the published `@objectstack/cli` never carried the staged swap, so this PR releases nothing and adds no changeset of its own. `skip-changeset` is not applied (ruling D on #18375). `Check Changeset` stays red by design (route 0 of its refusal text), and the dispatching seat confirms this correction by its own record. ## What changes - `packages/cli/src/utils/skills-install-state.ts`: `applySkillsWrite` goes back to the pre-#35495 write (remove the dropped and replaced skill directories, write the new ones, write the record last). `SKILLS_STAGING_PREFIX`, the staging directory, the rename swap and its undo are removed. - `packages/cli/test/skills-commands.test.ts`: the `an interrupted write leaves the installed catalog usable` block and the `node:fs` fault injection that served it are removed with the code they pinned. - `.changeset/35079-skills-write-staged-swap.md`: deleted (see above). ## Read first 1. `packages/cli/src/utils/skills-install-state.ts`, the `applySkillsWrite` hunk: the riskiest change, the non-atomic write coming back. 2. `packages/cli/test/skills-commands.test.ts`: the deleted interrupted-write block. Every remaining test passes unchanged. 3. `.changeset/35079-skills-write-staged-swap.md`: the deletion the correction above declares. ## Two-minute verification From the repo root on this branch: ```sh node --input-type=module -e "const m = await import('./scripts/pm/dispatch-gates.mjs'); const u = m.exposedScratchDirs({}).unresolved.filter(function (s) { return s.call === 'mkdtempSync'; }); console.log(u.length); process.exit(u.length ? 1 : 0);" ``` Expect `0` and exit 0. On `main` the same command prints `1` and exits 1. ## Tests All readings below are on head `dc83a28e`. Exit codes were captured before any pipe. <details> <summary>The red case, before and after</summary> - Before, at `e35cf035`, where `packages/cli/src/utils/skills-install-state.ts` is byte-identical to the merge base `f981dce3` (`git diff --quiet` exit 0). `node scripts/pm/dispatch-gates.mjs --self-test` (both tiers) printed `✗ no mkdtempSync site in this tree takes a base the scan cannot read — UNRESOLVED: packages/cli/src/utils/skills-install-state.ts:246 (dir is not bound in this file)` and `✗ dispatch-gates self-test: 1 of 2564 case(s) failed.`, exit 1. - After: the one-case replay through the module's own `exposedScratchDirs` on this tree read sites=3127, inTree=93, exposed=0, unresolved(mkdtempSync)=0, exit 0. The classifier on the file alone gives 1 unresolved `mkdtempSync` site at base `f981dce3` (`:246 dir is not bound in this file`) and 0 at `dc83a28e`. - The full self-test on `dc83a28e` was still running when this PR opened. Its verdict follows in the os-dev-report on #35588. </details> <details> <summary>cli tests and typecheck</summary> - `pnpm --filter @objectstack/cli exec vitest run --maxWorkers=2 test/skills-commands.test.ts`: `Test Files 1 passed (1)`, `Tests 30 passed (30)`, lock VERDICT command-exit 0. - `pnpm --filter @objectstack/cli exec vitest run --project unit --maxWorkers=2`: `Test Files 431 passed (431)`, `Tests 6158 passed (6158)`, lock VERDICT command-exit 0. The integration layer is left to CI: the diff touches no integration file and no spawn entry. - `pnpm --filter @objectstack/cli typecheck` (`tsc --noEmit && check:test-typecheck`): lock VERDICT command-exit 0, `check:test-typecheck: OK`. - Dependency closure first: `pnpm --workspace-concurrency=2 --filter '@objectstack/cli^...' build`, VERDICT command-exit 0, then `pnpm --filter @objectstack/cli build`, VERDICT command-exit 0. </details> ## Acceptance notes - The case runs in the slow tier, so a pull request's own `Lint & Repo Gates` run (fast tier) does not execute it. The local full self-test under Tests is the evidence, and the next scheduled full run refreshes #35588. - Observation, not filed: the scan holds the completeness rule to the spelling `mkdtempSync` only. Async `mkdtemp(join(PKG, 'tmp', ...))` builds in-tree fixture roots it does not see (`packages/cli/src/utils/graft-runtime-hooks.test.ts:236`, `packages/cli/test/next-steps.test.ts:83`). Both are covered by `.gitignore` `tmp/`, so nothing is exposed. ## Verification The PR opened while the local gate runs were still finishing, so the local readings follow in the os-dev-report on #35588. CI on this PR is the gate. - Derived set: `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` gives 64 commands for this change set (3 paths vs merge base `f981dce3`). They run locally, byte for byte, and are reconciled with `--ran`. - Expected red, by design: `node scripts/check-empty-changeset.mjs --base origin/main` exits 1 on the deleted foreign changeset (the DELIBERATE CORRECTION class above), and so does `Check Changeset` on this PR. - `check:pm-dispatch-gates` on a pull request runs its fast tier only, so the red case is not in this PR's check-runs. The full self-test above is the reading for it. --- _Generated by [Claude Code](https://claude.ai/code/session_01L6bhgTyMahdAdhXSzgy2nt)_ Co-authored-by: Claude <noreply@anthropic.com>
1 parent 2e19f36 commit ae2a67d

3 files changed

Lines changed: 14 additions & 239 deletions

File tree

‎.changeset/35079-skills-write-staged-swap.md‎

Lines changed: 0 additions & 10 deletions
This file was deleted.

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

Lines changed: 12 additions & 109 deletions
Original file line numberDiff line numberDiff line change
@@ -19,44 +19,17 @@
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.
4222
*/
4323

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

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

5030
/** The record's file name, inside the skills directory. */
5131
export const SKILLS_MANIFEST_FILE = '.objectstack-skills.json';
5232

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-
6033
/** Where a Claude Code project keeps its skills, relative to the working directory. */
6134
export const DEFAULT_SKILLS_DIR = join('.claude', 'skills');
6235

@@ -219,103 +192,33 @@ function underRoot(root: string, target: string): string {
219192
return resolved;
220193
}
221194

222-
/** One undoable rename of {@link applySkillsWrite}'s swap. */
223-
interface SwapStep {
224-
from: string;
225-
to: string;
226-
}
227-
228195
/**
229196
* Write `catalog` into `dir` along `plan`: remove each dropped skill, replace
230197
* each recorded one and each conflict (the caller decided those may go), add
231198
* the rest, then write the record last. Only directories the plan names are
232-
* touched, and a failure partway leaves `dir` as it was (see the module
233-
* header), rethrowing the failure.
199+
* touched.
234200
*/
235201
export function applySkillsWrite(dir: string, catalog: SkillsCatalog, plan: SkillsWritePlan): SkillsManifest {
236202
// Every target is judged before the first write, so a refusal leaves the directory as it was.
237-
const dropped = plan.dropped.map((name) => ({ name, root: underRoot(dir, join(dir, name)) }));
203+
const dropped = plan.dropped.map((name) => underRoot(dir, join(dir, name)));
238204
const writes = [...catalog.skills].map(([name, files]) => {
239205
const root = underRoot(dir, join(dir, name));
240-
return { name, root, files: [...files].map(([path, bytes]) => ({ rel: relative(root, underRoot(root, join(root, ...path.split('/')))), bytes })) };
206+
return { root, files: [...files].map(([path, bytes]) => ({ target: underRoot(root, join(root, ...path.split('/'))), bytes })) };
241207
});
242-
const manifest = manifestForCatalog(catalog);
243-
244208
mkdirSync(dir, { recursive: true });
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.`;
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);
279215
}
280-
throw error;
281216
}
282-
removeStaging(staging);
217+
const manifest = manifestForCatalog(catalog);
218+
writeFileSync(join(dir, SKILLS_MANIFEST_FILE), `${JSON.stringify(manifest, null, 2)}\n`);
283219
return manifest;
284220
}
285221

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-
319222
/** One line per modified skill, for the text face: what changed, was removed or was added. */
320223
export function describeModifiedSkill(m: ModifiedSkill): string {
321224
const parts = [

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

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

1414
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
15-
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
15+
import { existsSync, mkdirSync, mkdtempSync, 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-
4422
const { default: SkillsInstall } = await import('../src/commands/skills/install.js');
4523
const { default: SkillsUpdate } = await import('../src/commands/skills/update.js');
4624
const { default: SkillsStatus } = await import('../src/commands/skills/status.js');
4725
const { skillsRegistry, catalogFromTarball, resolveSkillsVersion, npmPackInvocation } = await import('../src/utils/skills-catalog.js');
48-
const { SKILLS_MANIFEST_FILE, SKILLS_STAGING_PREFIX, applySkillsWrite, readSkillsManifest } = await import('../src/utils/skills-install-state.js');
26+
const { SKILLS_MANIFEST_FILE, applySkillsWrite, readSkillsManifest } = await import('../src/utils/skills-install-state.js');
4927

5028
const PKG = dirname(dirname(fileURLToPath(import.meta.url)));
5129
// The oclif config is loaded once, here: a clocked test window measures the commands, never this load.
@@ -480,99 +458,3 @@ describe('a malformed record is refused whole', () => {
480458
expect(() => readSkillsManifest(root)).toThrow(/cannot read/);
481459
});
482460
});
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)