diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2fa6a3b8e..63e545fb1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -835,7 +835,7 @@ When Conductor creates a new workspace, `bin/dev-setup` runs automatically. It d - **`.claude/skills/` is gitignored.** The symlinks never get committed. - **Never write raw `ln -snf` in `setup`.** Every link site in `setup` MUST route through the `_link_or_copy SRC DST` helper near the `IS_WINDOWS` detection. The helper preserves `ln -snf` on Unix and switches to `cp -R` / `cp -f` on Windows without Developer Mode, where plain `ln -snf` produces frozen file copies that don't refresh on `git pull`. `test/setup-windows-fallback.test.ts` enforces this with a static invariant — a single raw `ln` call outside the helper body fails CI. - **Synchronous subagent dispatches must state the flag.** Claude Code runs Agent-tool subagents in the background by default (since v2.1.198), so any template step that dispatches a subagent and consumes its output must carry `run_in_background: false`. Use the `{{FOREGROUND_DISPATCH_NOTE}}` placeholder (`scripts/resolvers/constants.ts`) instead of hand-writing the guidance, and add the generated carrier file to `GENERATED_WITH_GUIDANCE` in `test/run-in-background-guidance.test.ts` in the same commit — its structural scanner fails CI on any generated dispatch imperative that lacks the flag. -- **Never delete or link over a skill entry `setup` cannot prove is gstack's.** Every destructive site in `setup` (the linker, the alias installer, both prefix-flip cleanups) and in `bin/gstack-relink` goes through the ownership helpers (`_claude_entry_is_ours` / `_claude_entry_owned_strongly` in `setup`, `_entry_is_ours` / `_entry_owned_strongly` in relink). The retired-skill prune (`_prune_stale_generated`) applies the same strong/weak split through its own gate: a real host directory is a candidate only when its SKILL.md carries the generated banner (`_owned_for_windows_refresh`), a host symlink is removed only when it resolves into gstack (`_gstack_target_is_ours`), a bannered real directory is cleaned through `_cleanup_weak_dir`, and a symlink inside the render tree is never followed. A symlink into gstack or the `.gstack-owned` marker proves the whole directory; a byte-identical or generated-banner SKILL.md proves only that file, and a differing one is moved to `~/.gstack/backups/skills//` first. `test/setup-link-ownership.test.ts`, `test/setup-cleanup-orphans.test.ts`, `test/setup-prune-stale-generated.test.ts`, and `test/relink.test.ts` pin it. The rule is duplicated in the two scripts until the shared helper filed in TODOS.md lands: change both. The host-render prune (`gstack_prune_host_renders` in `bin/gstack-host-renders.sh`, #1694) applies the same split to the render dirs of hosts a checkout does not serve: a link into the checkout goes, a file proven generated moves to `~/.gstack/backups/host-renders/-/`, anything else stays, and only emptied directories are removed (`test/host-renders-prune.test.ts`). +- **Never delete or link over a skill entry `setup` cannot prove is gstack's.** Every destructive site in `setup` (the linker, the alias installer, both prefix-flip cleanups) and in `bin/gstack-relink` goes through the ownership helpers (`_claude_entry_is_ours` / `_claude_entry_owned_strongly` in `setup`, `_entry_is_ours` / `_entry_owned_strongly` in relink). The retired-skill prune (`_prune_stale_generated`) applies the same strong/weak split through its own gate: a real host directory is a candidate only when its SKILL.md carries the generated banner (`_owned_for_windows_refresh`), a host symlink is removed only when it resolves into gstack (`_gstack_target_is_ours`), a bannered real directory is cleaned through `_cleanup_weak_dir`, a real directory with neither a SKILL.md nor the marker (one an earlier upgrade stranded) loses only gstack's links, and a symlink inside the render tree is never followed. These cleanups also look one level into a real subdirectory such as `sections/` for gstack's links and byte-identical copies, and remove only a subdirectory they emptied (`test/retired-skill-sections-cleanup.test.ts`). A symlink into gstack or the `.gstack-owned` marker proves the whole directory; a byte-identical or generated-banner SKILL.md proves only that file, and a differing one is moved to `~/.gstack/backups/skills//` first. `test/setup-link-ownership.test.ts`, `test/setup-cleanup-orphans.test.ts`, `test/setup-prune-stale-generated.test.ts`, and `test/relink.test.ts` pin it. The rule is duplicated in the two scripts until the shared helper filed in TODOS.md lands: change both. The host-render prune (`gstack_prune_host_renders` in `bin/gstack-host-renders.sh`, #1694) applies the same split to the render dirs of hosts a checkout does not serve: a link into the checkout goes, a file proven generated moves to `~/.gstack/backups/host-renders/-/`, anything else stays, and only emptied directories are removed (`test/host-renders-prune.test.ts`). - **`./setup` never fails on Chromium.** The Playwright bootstrap (section `# 2` of `setup`) is best-effort and bounded: every failure becomes a reason code (`skipped`, `chromium-install`, `chromium-install-timeout`, `chromium-install-locked`, `windows-no-node`, `windows-node-modules`, `post-install-launch`) printed in the final summary alongside the browser-dependent skills, and skill registration always runs. `GSTACK_PLAYWRIGHT_INSTALL_TIMEOUT=` (default 600) bounds the download; `GSTACK_SKIP_PLAYWRIGHT=1` skips it, the right knob for a no-browser box or a setup-only test loop. `GSTACK_SKIP_ASIDE=1` makes the browser summary (like the skills' probe and the renderer) treat Aside as absent, so the summary never promises a fallback the bootstrap did not deliver (`test/setup-browser-hint.test.ts`). Anything you add after the bootstrap must stay independent of the browser. `test/setup-playwright-best-effort.test.ts` pins the block. ## Testing your changes in a real project diff --git a/bin/gstack-relink b/bin/gstack-relink index 14d50a7e4..f1133f38f 100755 --- a/bin/gstack-relink +++ b/bin/gstack-relink @@ -259,8 +259,11 @@ _backup_skill_md() { _cleanup_skill_entry() { local entry="$1" skill="${2:-}" whole="${3:-whole}" e dest src [ -e "$entry" ] || [ -L "$entry" ] || return 0 - # Unclaimed dir (no SKILL.md, no marker): nothing of ours to clean. + # Unclaimed dir (no SKILL.md, no marker): only our links can be left in it, + # such as the sections/ an older cleanup stranded (1.104.0.0, GST-3999). + # Those go, and the directory with them when nothing else is left. if [ -d "$entry" ] && [ ! -L "$entry" ] && [ ! -e "$entry/SKILL.md" ] && [ ! -L "$entry/SKILL.md" ] && [ ! -f "$entry/.gstack-owned" ]; then + if _remove_our_assets "$entry"; then rmdir "$entry" 2>/dev/null || true; fi return 0 fi if ! _entry_is_ours "$entry" "$skill"; then @@ -298,15 +301,39 @@ _cleanup_skill_entry() { fi fi rm -f "$entry/SKILL.md" "$entry/.gstack-owned" - for e in "$entry"/* "$entry"/.[!.]* "$entry"/..?*; do - [ -L "$e" ] || continue - dest="$(_link_target_abs "$e")" || continue - if _target_is_ours "$dest"; then rm -f "$e"; fi - done + if [ -n "$skill" ]; then _remove_our_assets "$entry" "$INSTALL_DIR/$skill" "$RENDER_DIR/$skill" || true; else _remove_our_assets "$entry" || true; fi rmdir "$entry" 2>/dev/null || echo " cleaned ${entry##*/}/SKILL.md (other files in that directory were left in place)" fi fi } +# _remove_our_assets DIR [SRC_DIR...] — remove the runtime assets gstack put +# beside a SKILL.md: links resolving into gstack, dangling ones from a removed +# skill included, and real files byte-identical to the same path under a +# SRC_DIR (Windows copies). It also looks one level into each real +# subdirectory such as sections/, never through a linked one, and removes a +# subdirectory it empties. The user's own files, links and directories stay, +# an empty one included. Returns 0 only when it removed something. +_remove_our_assets() { + local d="$1" e dest s ours removed=1 + shift + for e in "$d"/* "$d"/.[!.]* "$d"/..?* "$d"/*/* "$d"/*/.[!.]* "$d"/*/..?*; do + [ -L "${e%/*}" ] && continue + ours=0 + if [ -L "$e" ]; then + dest="$(_link_target_abs "$e")" || continue + if _target_is_ours "$dest"; then ours=1; fi + elif [ -f "$e" ]; then + for s in "$@"; do + if cmp -s "$e" "$s/${e#"$d"/}"; then ours=1; break; fi + done + fi + [ "$ours" -eq 1 ] || continue + rm -f "$e" + removed=0 + [ "${e%/*}" = "$d" ] || rmdir "${e%/*}" 2>/dev/null || true + done + return "$removed" +} # _dir_only_links DIR — deleting DIR whole loses no real data: every entry is # a symlink or our marker. _dir_only_links() { diff --git a/changelog.d/fix-retired-skill-sections-cleanup.md b/changelog.d/fix-retired-skill-sections-cleanup.md new file mode 100644 index 000000000..61e400a6e --- /dev/null +++ b/changelog.d/fix-retired-skill-sections-cleanup.md @@ -0,0 +1 @@ +**Upgrading now removes the old `ship` and `cso` skill folders that 1.104.0.0 left behind.** That upgrade removed each folder's `SKILL.md` but not its `sections/` folder, so `ship/` and `cso/` (and their `gstack-` versions) stayed in your skills directory holding only links. Running `./setup` or `/gstack-upgrade` again cleans them up, including on machines that already upgraded. Only links and copies gstack made are removed: a file, link or folder you added inside one of these folders stays where it is. diff --git a/docs/CONTRIBUTOR_REFERENCE.md b/docs/CONTRIBUTOR_REFERENCE.md index 86be3771b..6073bb85c 100644 --- a/docs/CONTRIBUTOR_REFERENCE.md +++ b/docs/CONTRIBUTOR_REFERENCE.md @@ -98,9 +98,17 @@ consulted): it scans the render tree and every host skills dir, deletes a real render directory, removes a host symlink only when it resolves into gstack, cleans a bannered real directory through `_cleanup_weak_dir`, never follows a symlink inside the render tree, and recognizes a skill renamed -through its frontmatter `name:`. Pinned by `test/setup-link-ownership.test.ts`, +through its frontmatter `name:`. A real directory with neither a SKILL.md nor +the marker (one an earlier upgrade left holding only `sections/`) is also passed +to `_cleanup_weak_dir` with no source, so only gstack's links leave it. That +cleanup, and relink's `_remove_our_assets`, remove gstack's links (dangling ones +included) and, when the skill's source is known, real files byte-identical to it +(Windows copies), at the top level and one level into each real subdirectory +such as `sections/`, never through a linked one; they remove only a +subdirectory they emptied, so the user's files, links and directories stay. +Pinned by `test/setup-link-ownership.test.ts`, `test/setup-cleanup-orphans.test.ts`, `test/setup-prune-stale-generated.test.ts`, -and `test/relink.test.ts`. +`test/retired-skill-sections-cleanup.test.ts` and `test/relink.test.ts`. ## Redaction guard diff --git a/setup b/setup index 93f8cb09e..b189eae8c 100755 --- a/setup +++ b/setup @@ -1045,11 +1045,17 @@ _backup_skill_md() { # name: line rewritten to NAME, which is how alias and prefixed copies differ), # or whose named source is gone, is a customized file: it is moved to the # backup root, never deleted, and if the backup fails it stays. Our -# runtime-asset links go; the user's files stay. BACKUP_NAME (default NAME) -# names the backup, so copies of one skill on several hosts never collide. +# runtime-asset links go, dangling ones included, and with SRC_SKILL_MD so do +# real files byte-identical to the same path beside it (Windows copies); both +# are also removed one level into each real subdirectory such as sections/ +# (never through a linked one), which goes once emptied (GST-3999). The +# user's files and directories stay, an empty one included. BACKUP_NAME +# (default NAME) names the backup, so copies of one skill on several hosts +# never collide. _cleanup_weak_dir() { - local d="$1" g="$2" src="${3:-}" name="${4:-${1##*/}}" e dest + local d="$1" g="$2" src="${3:-}" name="${4:-${1##*/}}" e dest had_md=0 swept=0 local bk="${5:-$name}" + { [ -e "$d/SKILL.md" ] || [ -L "$d/SKILL.md" ]; } && had_md=1 if [ -f "$d/SKILL.md" ] && [ ! -L "$d/SKILL.md" ] && [ -n "$src" ] \ && { [ ! -f "$src" ] || { ! cmp -s "$d/SKILL.md" "$src" \ && ! sed "1,/^---\$/ s/^name:[[:space:]].*/name: $name/" "$src" | cmp -s - "$d/SKILL.md"; }; }; then @@ -1061,12 +1067,20 @@ _cleanup_weak_dir() { rm -f "$d/SKILL.md" fi rm -f "$d/.gstack-owned" - for e in "$d"/* "$d"/.[!.]* "$d"/..?*; do - [ -L "$e" ] || continue - dest="$(_gstack_link_target_abs "$e")" || continue - if _gstack_target_is_ours "$dest" "$g"; then rm -f "$e"; fi + for e in "$d"/* "$d"/.[!.]* "$d"/..?* "$d"/*/* "$d"/*/.[!.]* "$d"/*/..?*; do + [ -L "${e%/*}" ] && continue + if [ -L "$e" ]; then + dest="$(_gstack_link_target_abs "$e")" || continue + _gstack_target_is_ours "$dest" "$g" || continue + elif [ ! -f "$e" ] || [ -z "$src" ] || ! cmp -s "$e" "${src%/*}/${e#"$d"/}"; then + continue + fi + rm -f "$e" + swept=1 + [ "${e%/*}" = "$d" ] || rmdir "${e%/*}" 2>/dev/null || true done - rmdir "$d" 2>/dev/null || echo " cleaned ${d##*/}/SKILL.md (other files in that directory were left in place)" + [ "$had_md" -eq 1 ] || [ "$swept" -eq 1 ] || return 0 + rmdir "$d" 2>/dev/null || [ "$had_md" -eq 0 ] || echo " cleaned ${d##*/}/SKILL.md (other files in that directory were left in place)" } # _gstack_dir_only_links DIR GSTACK_DIR — true when deleting DIR whole loses # nothing of the user's: every entry is a symlink resolving into gstack, or @@ -1175,6 +1189,12 @@ _prune_stale_generated() { _skill_source_exists "$gstack_dir" "$n" && continue for host in "$@"; do [ -n "$host" ] && { [ -e "$host/$n" ] || [ -L "$host/$n" ]; } || continue + # A real dir with no SKILL.md and no marker: an older cleanup stranded + # it with only our links left, such as sections/ (GST-3999). + if [ -d "$host/$n" ] && [ ! -L "$host/$n" ] && [ ! -e "$host/$n/SKILL.md" ] && [ ! -L "$host/$n/SKILL.md" ] && [ ! -f "$host/$n/.gstack-owned" ]; then + _cleanup_weak_dir "$host/$n" "$gstack_dir" + continue + fi _owned_for_windows_refresh "$host/$n" || continue if [ -L "$host/$n" ]; then # Strong proof only when the link resolves into gstack: the render tree diff --git a/test/retired-skill-sections-cleanup.test.ts b/test/retired-skill-sections-cleanup.test.ts new file mode 100644 index 000000000..751e9e732 --- /dev/null +++ b/test/retired-skill-sections-cleanup.test.ts @@ -0,0 +1,256 @@ +/** + * Retired and renamed skill entries keep no stranded sections/ directory. + * + * A gbrain-rendered install (and setup's Kiro and render paths) serves a + * skill's sections/ as a REAL directory of per-file links. When /ship became + * /gstack-ship and /cso was removed (1.104.0.0), the cleanup removed each old + * entry's SKILL.md, marker and top-level links but not that directory, so + * ship/ and cso/ stayed behind holding only sections/ (working links for ship, + * dangling ones for cso). The next relink or setup must remove what gstack put + * there, including on machines that already upgraded, and never a file, link + * or directory of the user's. + */ +import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; +import { spawnSync } from 'child_process'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; + +const ROOT = path.resolve(import.meta.dir, '..'); +const REGISTRY = path.join(ROOT, 'bin', 'gstack-install-registry.sh'); +const BINS = ['gstack-config', 'gstack-lock.sh', 'gstack-relink', 'gstack-patch-names', 'gstack-skill-name.sh', 'gstack-state-root.sh', 'gstack-install-registry.sh']; +const BANNER = '\n\n'; +const SHIP_SECTIONS = ['review.md', 'changelog.md', 'pr-body.md']; +const CSO_SECTIONS = ['owasp.md', 'secrets.md', 'supply-chain.md']; + +const gone = (p: string) => fs.lstatSync(p, { throwIfNoEntry: false }) === undefined; + +// Value: protects=relink removes gstack's stranded ship/, cso/, gstack-cso/ and gstack-ship-era entries whose sections/ is a real dir of our links; +// fails_when=the cleanup leaves a real sections/ directory of gstack links (working or dangling) or deletes a user's file, link or directory inside one; +// why_new=retired-skills and claude-code-reserved-names cover only entries with no real asset subdirectory; seam=the real gstack-relink on a fixture install +describe.skipIf(process.platform === 'win32')('gstack-relink: retired and renamed entries leave no sections/ behind (GST-3999)', () => { + let tmp: string; + let install: string; + let skills: string; + let render: string; + const relink = (config = 'skill_prefix: false\n') => { + fs.mkdirSync(path.join(tmp, 'state'), { recursive: true }); + fs.writeFileSync(path.join(tmp, 'state', 'config.yaml'), config); + return spawnSync('bash', [path.join(install, 'bin', 'gstack-relink')], { + encoding: 'utf8', + timeout: 60_000, + env: { + ...process.env, GSTACK_HOME: path.join(tmp, 'state'), GSTACK_STATE_ROOT: '', GSTACK_STATE_DIR: '', + GSTACK_INSTALL_DIR: install, GSTACK_SKILLS_DIR: skills, GSTACK_SETUP_RUNNING: '', GSTACK_USER_RENDER_DIR: render, GSTACK_USER_RENDER_PER_INSTALL: '', + }, + }); + }; + // The 1.103.x rendered shape: a real dir, SKILL.md linked, sections/ a real dir of per-file links. + const oldEntry = (name: string, skill: string, files: string[], opts: { marker?: boolean; skillMd?: boolean; via?: string } = {}) => { + const dir = path.join(skills, name); + fs.mkdirSync(path.join(dir, 'sections'), { recursive: true }); + if (opts.skillMd !== false) fs.symlinkSync(path.join(install, skill, 'SKILL.md'), path.join(dir, 'SKILL.md')); + if (opts.marker) fs.writeFileSync(path.join(dir, '.gstack-owned'), install + '\n'); + for (const f of files) fs.symlinkSync(path.join(opts.via ?? install, skill, 'sections', f), path.join(dir, 'sections', f)); + return dir; + }; + + beforeEach(() => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-stranded-sections-')); + install = path.join(tmp, 'gstack'); + skills = path.join(tmp, 'skills'); + render = path.join(tmp, 'render'); + fs.mkdirSync(path.join(install, 'bin'), { recursive: true }); + fs.writeFileSync(path.join(install, 'VERSION'), '2.0.0.0\n'); + for (const b of BINS) { + fs.copyFileSync(path.join(ROOT, 'bin', b), path.join(install, 'bin', b)); + fs.chmodSync(path.join(install, 'bin', b), 0o755); + } + for (const [dir, name] of [['ship', 'gstack-ship'], ['qa', 'qa']]) { + fs.mkdirSync(path.join(install, dir, 'sections'), { recursive: true }); + fs.writeFileSync(path.join(install, dir, 'SKILL.md'), `---\nname: ${name}\ndescription: test\n---\n# ${dir}\n`); + } + for (const f of SHIP_SECTIONS) fs.writeFileSync(path.join(install, 'ship', 'sections', f), `# ${f}\n`); + fs.mkdirSync(skills, { recursive: true }); + }); + afterEach(() => fs.rmSync(tmp, { recursive: true, force: true })); + + for (const prefix of ['false', 'true']) { + test(`skill_prefix ${prefix}, upgrading from 1.103.x: the old ship and cso entries go whole, sections/ included`, () => { + oldEntry('ship', 'ship', SHIP_SECTIONS, { marker: true }); + oldEntry('cso', 'cso', CSO_SECTIONS, { marker: true }); + oldEntry('gstack-cso', 'cso', CSO_SECTIONS, { via: render }); + const r = relink(`skill_prefix: ${prefix}\n`); + expect(r.status, r.stderr).toBe(0); + for (const name of ['ship', 'cso', 'gstack-cso']) expect(gone(path.join(skills, name))).toBe(true); + expect(fs.readFileSync(path.join(skills, 'gstack-ship', 'SKILL.md'), 'utf8')).toContain('name: gstack-ship'); + expect(r.stdout).not.toContain('other files in that directory were left in place'); + for (const f of SHIP_SECTIONS) expect(fs.existsSync(path.join(install, 'ship', 'sections', f))).toBe(true); + }); + } + + test('prefix mode: an unmarked legacy ship entry with a real sections/ of our links goes whole', () => { + oldEntry('ship', 'ship', SHIP_SECTIONS); + const r = relink('skill_prefix: true\n'); + expect(r.status, r.stderr).toBe(0); + expect(gone(path.join(skills, 'ship'))).toBe(true); + }); + + test('already on 1.104.0.0: entries holding only sections/ of working or dangling links are removed', () => { + oldEntry('ship', 'ship', SHIP_SECTIONS, { skillMd: false }); + oldEntry('cso', 'cso', CSO_SECTIONS, { skillMd: false }); + oldEntry('gstack-cso', 'cso', CSO_SECTIONS, { skillMd: false, via: render }); + oldEntry('gstack-investigate', 'investigate', ['a.md'], { skillMd: false }); + const r = relink(); + expect(r.status, r.stderr).toBe(0); + for (const name of ['ship', 'cso', 'gstack-cso', 'gstack-investigate']) expect(gone(path.join(skills, name))).toBe(true); + expect(fs.existsSync(path.join(skills, 'gstack-ship', 'SKILL.md'))).toBe(true); + }); + + test("the user's files, links and directories inside an old entry and its sections/ stay", () => { + const ship = oldEntry('ship', 'ship', SHIP_SECTIONS, { marker: true }); + fs.writeFileSync(path.join(ship, 'sections', 'mine.md'), 'mine\n'); + fs.writeFileSync(path.join(ship, 'notes.md'), 'keep\n'); + const cso = oldEntry('cso', 'cso', CSO_SECTIONS, { skillMd: false }); + const notes = path.join(tmp, 'my-notes.md'); + fs.writeFileSync(notes, 'mine\n'); + fs.symlinkSync(notes, path.join(cso, 'sections', 'notes.md')); + fs.mkdirSync(path.join(cso, 'sections', 'drafts')); + fs.writeFileSync(path.join(cso, 'sections', 'drafts', 'd.md'), 'draft\n'); + fs.mkdirSync(path.join(ship, 'empty')); + fs.mkdirSync(path.join(skills, 'gstack-cso', 'empty'), { recursive: true }); + const r = relink(); + expect(r.status, r.stderr).toBe(0); + expect(fs.readdirSync(path.join(skills, 'gstack-cso'))).toEqual(['empty']); + expect(fs.readdirSync(ship).sort()).toEqual(['empty', 'notes.md', 'sections']); + expect(fs.readdirSync(path.join(ship, 'sections'))).toEqual(['mine.md']); + expect(fs.readFileSync(path.join(ship, 'notes.md'), 'utf8')).toBe('keep\n'); + expect(fs.readdirSync(path.join(cso, 'sections')).sort()).toEqual(['drafts', 'notes.md']); + expect(fs.readlinkSync(path.join(cso, 'sections', 'notes.md'))).toBe(notes); + expect(fs.readFileSync(path.join(cso, 'sections', 'drafts', 'd.md'), 'utf8')).toBe('draft\n'); + }); + + test('a linked sections/ is unlinked or kept, never followed', () => { + const mine = path.join(tmp, 'my-sections'); + fs.mkdirSync(mine); + fs.writeFileSync(path.join(mine, 'x.md'), 'mine\n'); + fs.mkdirSync(path.join(skills, 'cso')); + fs.symlinkSync(mine, path.join(skills, 'cso', 'sections')); + fs.mkdirSync(path.join(skills, 'ship')); + fs.symlinkSync(path.join(install, 'ship', 'sections'), path.join(skills, 'ship', 'sections')); + const r = relink(); + expect(r.status, r.stderr).toBe(0); + expect(fs.readlinkSync(path.join(skills, 'cso', 'sections'))).toBe(mine); + expect(fs.readFileSync(path.join(mine, 'x.md'), 'utf8')).toBe('mine\n'); + expect(gone(path.join(skills, 'ship'))).toBe(true); + for (const f of SHIP_SECTIONS) expect(fs.existsSync(path.join(install, 'ship', 'sections', f))).toBe(true); + }); + + test('a customized SKILL.md is still backed up, and the sections/ beside it is cleaned', () => { + const cso = oldEntry('cso', 'cso', CSO_SECTIONS, { skillMd: false, marker: true }); + const edited = `---\nname: cso\ndescription: test\n---\n${BANNER}MY LOCAL EDITS\n`; + fs.writeFileSync(path.join(cso, 'SKILL.md'), edited); + const r = relink(); + expect(r.status, r.stderr).toBe(0); + expect(gone(cso)).toBe(true); + const root = path.join(tmp, 'state', 'backups', 'skills'); + const saved = fs.readdirSync(root).map(s => path.join(root, s, 'cso', 'SKILL.md')).filter(f => fs.existsSync(f)); + expect(saved.map(f => fs.readFileSync(f, 'utf8'))).toEqual([edited]); + }); + + test('Windows copy shape: copies identical to the source go, an edited copy stays', () => { + const ship = path.join(skills, 'ship'); + fs.mkdirSync(path.join(ship, 'sections'), { recursive: true }); + fs.writeFileSync(path.join(ship, '.gstack-owned'), install + '\n'); + fs.copyFileSync(path.join(install, 'ship', 'SKILL.md'), path.join(ship, 'SKILL.md')); + for (const f of SHIP_SECTIONS) fs.copyFileSync(path.join(install, 'ship', 'sections', f), path.join(ship, 'sections', f)); + fs.writeFileSync(path.join(ship, 'sections', 'review.md'), '# my edited review\n'); + const r = relink(); + expect(r.status, r.stderr).toBe(0); + expect(fs.readdirSync(ship)).toEqual(['sections']); + expect(fs.readdirSync(path.join(ship, 'sections'))).toEqual(['review.md']); + expect(fs.readFileSync(path.join(ship, 'sections', 'review.md'), 'utf8')).toBe('# my edited review\n'); + }); +}); + +// Value: protects=setup's own cleanup (_cleanup_weak_dir via _prune_stale_generated and _cleanup_linked_dir) removes a real sections/ of gstack links; +// fails_when=setup strands a retired host entry's sections/ (1.103.x shape or already-upgraded shape) or deletes the user's files in it; +// why_new=setup-prune-stale-generated and retired-skills cover entries without an asset subdirectory; seam=the setup helpers extracted and run on a temp tree +describe.skipIf(process.platform === 'win32')('setup: retired host entries leave no sections/ behind (GST-3999)', () => { + const SETUP_SRC = fs.readFileSync(path.join(ROOT, 'setup'), 'utf-8'); + const extractFn = (name: string) => { + const start = SETUP_SRC.indexOf(`${name}() {`); + const end = SETUP_SRC.indexOf('\n}\n', start); + if (start < 0 || end < 0) throw new Error(`Could not locate ${name}() in setup`); + return SETUP_SRC.slice(start, end + 2); + }; + const FNS = ['_gstack_link_target_abs', '_gstack_target_is_ours', '_gstack_generated_header', '_backup_skill_md', '_cleanup_weak_dir', + '_gstack_dir_only_links', '_cleanup_linked_dir', '_owned_for_windows_refresh', '_skill_source_exists', '_prune_stale_generated']; + let t: string; + let src: string; + let gen: string; + let host: string; + const run = (call: string) => spawnSync('bash', ['-c', [ + 'set -e', 'HOME=/nonexistent-home', 'log() { echo "$@"; }', `. "${REGISTRY}"`, `GSTACK_STATE_ROOT="${t}/state"`, `_SKILL_BACKUP_ROOT="${t}/backup"`, '_BACKED_UP_SKILL_MDS=()', + ...FNS.map(extractFn), call, + ].join('\n')], { encoding: 'utf-8', timeout: 30_000 }); + // Kiro-style host entry: a bannered SKILL.md copy and sections/ as a real dir of links into a render that is gone. + const hostEntry = (name: string, withSkillMd: boolean) => { + const dir = path.join(host, name); + fs.mkdirSync(path.join(dir, 'sections'), { recursive: true }); + if (withSkillMd) fs.writeFileSync(path.join(dir, 'SKILL.md'), `${BANNER}# ${name}\n`); + for (const f of CSO_SECTIONS) fs.symlinkSync(path.join(gen, name, 'sections', f), path.join(dir, 'sections', f)); + return dir; + }; + + beforeEach(() => { + t = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-setup-stranded-')); + src = path.join(t, 'gstack'); + gen = path.join(src, '.kiro', 'skills'); + host = path.join(t, 'host'); + fs.mkdirSync(path.join(src, 'qa'), { recursive: true }); + fs.writeFileSync(path.join(src, 'qa', 'SKILL.md.tmpl'), '---\nname: qa\n---\nx\n'); + fs.mkdirSync(gen, { recursive: true }); + fs.mkdirSync(host, { recursive: true }); + }); + afterEach(() => fs.rmSync(t, { recursive: true, force: true })); + + test('upgrading from 1.103.x: a retired gstack-cso copy and its sections/ of dangling links go whole', () => { + hostEntry('gstack-cso', true); + const r = run(`_prune_stale_generated "${src}" "${gen}" "${host}"`); + expect(r.status, r.stderr).toBe(0); + expect(r.stdout).toContain('pruned retired skill: gstack-cso'); + expect(fs.readdirSync(host)).toEqual([]); + }); + + test('already on 1.104.0.0: a gstack-cso holding only sections/ is removed; one holding a user file keeps it', () => { + hostEntry('gstack-cso', false); + const kept = hostEntry('gstack-investigate', false); + fs.writeFileSync(path.join(kept, 'sections', 'mine.md'), 'mine\n'); + fs.mkdirSync(path.join(host, 'gstack-verify', 'empty'), { recursive: true }); + const r = run(`_prune_stale_generated "${src}" "${gen}" "${host}"`); + expect(r.status, r.stderr).toBe(0); + expect(fs.readdirSync(host).sort()).toEqual(['gstack-investigate', 'gstack-verify']); + expect(fs.readdirSync(path.join(host, 'gstack-verify'))).toEqual(['empty']); + expect(fs.readdirSync(path.join(kept, 'sections'))).toEqual(['mine.md']); + }); + + test('a prefix flip: an old linked Claude entry whose sections/ is a real dir of our links goes whole, a user file stays', () => { + for (const name of ['review', 'qa']) { + fs.mkdirSync(path.join(src, name, 'sections'), { recursive: true }); + fs.writeFileSync(path.join(src, name, 'SKILL.md'), `---\nname: ${name}\n---\n`); + fs.writeFileSync(path.join(src, name, 'sections', 'a.md'), 'a\n'); + const dir = path.join(host, name); + fs.mkdirSync(path.join(dir, 'sections'), { recursive: true }); + fs.symlinkSync(path.join(src, name, 'SKILL.md'), path.join(dir, 'SKILL.md')); + fs.symlinkSync(path.join(src, name, 'sections', 'a.md'), path.join(dir, 'sections', 'a.md')); + } + fs.writeFileSync(path.join(host, 'qa', 'sections', 'mine.md'), 'mine\n'); + const r = run(`_cleanup_linked_dir "${host}/review" "${src}"; _cleanup_linked_dir "${host}/qa" "${src}"`); + expect(r.status, r.stderr).toBe(0); + expect(gone(path.join(host, 'review'))).toBe(true); + expect(fs.readdirSync(path.join(host, 'qa'))).toEqual(['sections']); + expect(fs.readdirSync(path.join(host, 'qa', 'sections'))).toEqual(['mine.md']); + expect(fs.readFileSync(path.join(src, 'qa', 'sections', 'a.md'), 'utf8')).toBe('a\n'); + }); +});