[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M71F0K8ST8NCBAAN6YKAZ2NB":3,"skill-same:01M71F0K8ST8NCBAAN6YKAZ2NB":72},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":38,"linkOnly":39,"markdownContent":40,"markdownBody":41,"frontMatter":42,"refName":51,"commitSha":52,"skillDirectory":53,"forksCount":54,"repositoryHtmlUrl":55,"repositoryHomepageUrl":6,"ownerHtmlUrl":56,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":57,"install":58,"resources":71},"01M71F0K8ST8NCBAAN6YKAZ2NB","worktree-candidate-cleanup",null,"Conservative post-merge sweep for stale native review candidate views under .git\u002Fgentle-ai\u002Fcandidate-views. Trigger: after merged worktree cleanup, or when the candidate-view store accumulates orphaned owners whose process is dead and whose changes are already in the integration branch.","parada1104\u002Fai-specs-cli","parada1104","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F57575053?v=4","01M71EZZV71KAFZKJ47FQ99ZVS","01M71EZZW7JJBY2VAWA5HRD944",0,"MIT","https:\u002F\u002Fgithub.com\u002Fparada1104\u002Fai-specs-cli\u002Fblob\u002Fmain\u002Fai-specs\u002Fskills\u002Fworktree-candidate-cleanup\u002FSKILL.md",[],[18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37],"candidate","worktree candidate cleanup","worktree","cleanup","git","integration","merge","process","native","changes","post","worktree cleanup","store","sweep","review","when","trigger","for","view","branch","2026-11-10 10:12:30",false,"---\nname: worktree-candidate-cleanup\ndescription: >\n  Conservative post-merge sweep for stale native review candidate views under\n  .git\u002Fgentle-ai\u002Fcandidate-views. Trigger: after merged worktree cleanup, or\n  when the candidate-view store accumulates orphaned owners whose process is\n  dead and whose changes are already in the integration branch.\nlicense: MIT\nmetadata:\n  author: ai-specs\n  version: \"1.0\"\n  scope: [root]\n  auto_invoke:\n    - \"After merged worktree cleanup to sweep stale native review candidate views\"\n---\n\n# Worktree Candidate Cleanup\n\n## Purpose\n\nNative review materializes a frozen candidate tree as a detached Git worktree\nunder the shared git dir, plus a sibling controller owner marker:\n\n```text\n\u003Ccommon-dir>\u002Fgentle-ai\u002Fcandidate-views\u002F\u003Cuuid>\u002F            # frozen read-only tree\n\u003Ccommon-dir>\u002Fgentle-ai\u002Fcandidate-views\u002F\u003Cuuid>.owner.json  # owner marker\n```\n\n`\u003Ccommon-dir>` is `git rev-parse --git-common-dir` (the main worktree's `.git`).\n\nThese views and markers are **owned by the native review controller**. The\nstandard merged-worktree cleanup (`worktree-cleanup.sh` \u002F `\u002Fworktree-clean`)\nonly reclaims `.worktrees\u002F` and never touches this store. This skill defines the\nextra, strictly conservative manual sweep for the residue the controller can no\nlonger own.\n\n## Ownership boundary\n\n- Candidate views and `.owner.json` markers are controller-owned state.\n- Never delete the store, and never mutate review authority, transactions,\n  locks, or receipts.\n- The native controller reaps dead-owner views on its own startup. This skill is\n  for the residue that survives, and it is **more** conservative than that\n  sweep: it additionally requires the candidate's changes to be merged.\n- Process one candidate at a time. If any proof cannot be produced, preserve the\n  entry unchanged.\n\n## Eligibility (all proofs must hold)\n\nA candidate view is eligible for removal only when every proof below passes.\nA missing, malformed, ambiguous, unreadable, or unreproducible proof means\n**preserve**.\n\n1. **Registered candidate worktree.** `\u003Cuuid>` appears exactly once in\n   `git worktree list --porcelain`, that row has no `locked`\u002F`prunable` field,\n   and `\u003Cview>\u002F.git` points to `\u003Ccommon-dir>\u002Fworktrees\u002F\u003Cuuid>`.\n2. **Valid owner marker.** `\u003Cuuid>.owner.json` is a regular non-symlink file\n   whose JSON keys are exactly `commonDir,host,pid,root,token,uuid,version`,\n   with `version: 1`, `uuid == basename(view)`, `root == view`,\n   `commonDir == \u003Ccommon-dir>`, a UUID v4 `token`, a null-or-string `host`,\n   and integer `pid > 0`. Unknown, legacy, or malformed markers are preserved\n   untouched.\n3. **Owner process proven dead.** The marker `host` is non-null and equals the\n   local host identity, the PID is not this process, and `kill(pid, 0)` raises\n   `ESRCH`. A live PID, an `EPERM`\u002Fpermission error, a null host, or a host\n   mismatch all mean **preserve**: pid death cannot be proven across hosts or\n   reboots, and a recycled PID is indistinguishable from a live owner.\n4. **No review reference.** No file under\n   `\u003Ccommon-dir>\u002Fgentle-ai\u002Freview-transactions\u002F**\u002F*.json` mentions the\n   candidate's tree hash, UUID, or path, and no `\u003Cuuid>.reaper-lock` exists.\n   A contended or unreadable transaction store means **preserve**.\n5. **Changes already in the integration branch.** The candidate is contained in\n   the integration branch by ancestry, by tree identity, or by patch-id\n   equivalence (`git cherry`, which covers squash\u002Frebase merges), and the\n   candidate tree is clean (`git status --porcelain` is empty). Never infer the\n   integration branch: it is declared in recipe config, not guessed.\n\n## Dry-run first (read-only)\n\nRun from the main worktree, never from inside a candidate view or a worktree\nbeing removed. This audit prints one verdict per candidate and removes nothing.\n\n```bash\ncd \"$(git rev-parse --show-toplevel)\"          # main worktree root\n# `--git-common-dir` may print a relative `.git` from the main worktree; make it absolute.\ncommon_dir=\"$(CDPATH= cd \"$(git rev-parse --git-common-dir)\" && pwd)\" || {\n  echo \"unable to resolve git common dir\" >&2; exit 1; }\nviews_dir=\"$common_dir\u002Fgentle-ai\u002Fcandidate-views\"\nintegration_branch=\"${INTEGRATION_BRANCH:-development}\"\ngit rev-parse --verify --quiet \"$integration_branch\" >\u002Fdev\u002Fnull || {\n  echo \"unknown integration branch: $integration_branch\" >&2; exit 1; }\n\n# Read-only. Prints one verdict line per candidate; removes nothing.\ncandidate_audit() {\npython3 - \"$common_dir\" \"$integration_branch\" \u003C\u003C'PY'\nimport json, os, platform, re, subprocess, sys, glob\n\nUUID4 = re.compile(r\"^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$\")\n\ncommon_dir, base = sys.argv[1], sys.argv[2]\nviews_dir = os.path.join(common_dir, \"gentle-ai\", \"candidate-views\")\n\ndef git(*args):\n    return subprocess.run([\"git\", *args], capture_output=True, text=True).stdout.strip()\n\ndef local_host():\n    try:\n        if platform.system() == \"Darwin\":\n            boot = subprocess.run([\"\u002Fusr\u002Fsbin\u002Fsysctl\", \"-n\", \"kern.bootsessionuuid\"],\n                                  capture_output=True, text=True, timeout=2).stdout.strip().lower()\n            return f\"darwin:{boot}\" if boot else None\n        if platform.system() == \"Linux\":\n            with open(\"\u002Fproc\u002Fsys\u002Fkernel\u002Frandom\u002Fboot_id\") as fh:\n                boot = fh.read().strip()\n            return f\"linux:{boot}:{os.readlink('\u002Fproc\u002Fself\u002Fns\u002Fpid')}\"\n    except Exception:\n        return None\n    return None\n\ndef owner_dead(owner, host):\n    if not host or owner.get(\"host\") != host:\n        return False\n    pid = owner.get(\"pid\")\n    if not isinstance(pid, int) or pid \u003C= 1 or pid == os.getpid():\n        return False\n    try:\n        os.kill(pid, 0)\n        return False\n    except ProcessLookupError:\n        return True\n    except PermissionError:\n        return False\n\ndef valid_marker(view):\n    path = view + \".owner.json\"\n    try:\n        if os.path.islink(path) or not os.path.isfile(path):\n            return None\n        owner = json.load(open(path))\n    except Exception:\n        return None\n    if set(owner) != {\"commonDir\", \"host\", \"pid\", \"root\", \"token\", \"uuid\", \"version\"}:\n        return None\n    if owner[\"version\"] != 1 or owner[\"uuid\"] != os.path.basename(view):\n        return None\n    if owner[\"root\"] != view or owner[\"commonDir\"] != common_dir:\n        return None\n    if not isinstance(owner[\"pid\"], int) or owner[\"pid\"] \u003C= 0:\n        return None\n    if not isinstance(owner[\"token\"], str) or not UUID4.match(owner[\"token\"]):\n        return None\n    if not (owner[\"host\"] is None or isinstance(owner[\"host\"], str)):\n        return None\n    return owner\n\ndef registered(view):\n    rows = git(\"worktree\", \"list\", \"--porcelain\", \"-z\").split(\"\\0\\0\")\n    hits = [r for r in rows if r.startswith(\"worktree \") and r[9:].split(\"\\0\")[0] == view]\n    if len(hits) != 1:\n        return False\n    fields = hits[0].split(\"\\0\")\n    if any(f == \"locked\" or f.startswith(\"locked \") or\n           f == \"prunable\" or f.startswith(\"prunable \") for f in fields):\n        return False\n    try:\n        pointer = open(os.path.join(view, \".git\")).read()\n    except Exception:\n        return False\n    return (pointer.startswith(\"gitdir: \") and\n            os.path.dirname(pointer[8:].strip()) == os.path.join(common_dir, \"worktrees\"))\n\ndef referenced(tree_hash, view):\n    pattern = os.path.join(common_dir, \"gentle-ai\", \"review-transactions\", \"**\", \"*.json\")\n    for path in glob.glob(pattern, recursive=True):\n        try:\n            blob = open(path).read()\n        except Exception:\n            return True\n        if (tree_hash and tree_hash in blob) or os.path.basename(view) in blob or view in blob:\n            return True\n    return False\n\ndef merged(view):\n    head = git(\"-C\", view, \"rev-parse\", \"HEAD\")\n    if not head:\n        return False\n    if subprocess.run([\"git\", \"merge-base\", \"--is-ancestor\", head, base], capture_output=True).returncode == 0:\n        return True\n    if subprocess.run([\"git\", \"diff\", \"--quiet\", base, head], capture_output=True).returncode == 0:\n        return True\n    cherry = subprocess.run([\"git\", \"cherry\", base, head], capture_output=True, text=True).stdout\n    lines = [line for line in cherry.splitlines() if line.strip()]\n    return bool(lines) and all(line.startswith(\"-\") for line in lines)\n\nhost = local_host()\nif not os.path.isdir(views_dir):\n    print(f\"no candidate store at {views_dir}\")\n    sys.exit(0)\n\nfor entry in sorted(os.listdir(views_dir)):\n    view = os.path.join(views_dir, entry)\n    if entry.endswith(\".owner.json\") or not os.path.isdir(view) or os.path.islink(view):\n        continue\n    reasons = []\n    if not registered(view):\n        reasons.append(\"not a registered candidate worktree\")\n    owner = valid_marker(view)\n    if owner is None:\n        reasons.append(\"missing or malformed owner marker\")\n    elif not owner_dead(owner, host):\n        reasons.append(\"owner process not proven dead\")\n    tree = git(\"-C\", view, \"rev-parse\", \"HEAD^{tree}\")\n    if referenced(tree, view):\n        reasons.append(\"referenced by a review transaction\")\n    if os.path.exists(view + \".reaper-lock\"):\n        reasons.append(\"reaper lock present\")\n    if not merged(view):\n        reasons.append(f\"changes not provably merged into {base}\")\n    dirty = subprocess.run([\"git\", \"--no-optional-locks\", \"-C\", view, \"status\", \"--porcelain\"],\n                           capture_output=True, text=True).stdout.strip()\n    if dirty:\n        reasons.append(\"candidate worktree is dirty\")\n    verdict = \"ELIGIBLE\" if not reasons else \"PRESERVE\"\n    print(f\"{entry}: {verdict} - {'; '.join(reasons) or 'all proofs hold'}\")\nPY\n}\n\ncandidate_audit\n```\n\n## Removal (only after an ELIGIBLE verdict)\n\nRun from the main worktree, in the same shell that defined `candidate_audit`\n(see the dry-run section), one candidate at a time. `chmod -R u+w` mirrors the\ncontroller's cleanup unlocking; the frozen views are materialized read-only.\nThe owner marker is fingerprinted and the read-only audit is re-run immediately\nbefore removal so a candidate that changes or is re-owned mid-sweep is\npreserved instead of reaped.\n\n```bash\ncd \"$(git rev-parse --show-toplevel)\"\n# `--git-common-dir` may print a relative `.git` from the main worktree; make it absolute.\ncommon_dir=\"$(CDPATH= cd \"$(git rev-parse --git-common-dir)\" && pwd)\" || {\n  echo \"unable to resolve git common dir\" >&2; exit 1; }\nviews_dir=\"$common_dir\u002Fgentle-ai\u002Fcandidate-views\"\nintegration_branch=\"${INTEGRATION_BRANCH:-development}\"\nuuid=\"\u003Cuuid>\"                                  # exact ELIGIBLE candidate\nview=\"$views_dir\u002F$uuid\"\nmarker=\"$view.owner.json\"\n\nsha256_of() { if command -v shasum >\u002Fdev\u002Fnull 2>&1; then shasum -a 256 \"$1\" | awk '{print $1}'; else sha256sum \"$1\" | awk '{print $1}'; fi; }\ntype candidate_audit >\u002Fdev\u002Fnull 2>&1 || { echo \"define candidate_audit first (dry-run section)\" >&2; exit 1; }\nif [ ! -d \"$view\" ]; then echo \"no candidate view at $view\" >&2; exit 1; fi\n\nbefore=\"$(sha256_of \"$marker\")\"                # fingerprint the owner marker\nif ! candidate_audit | grep -qx \"$uuid: ELIGIBLE - all proofs hold\"; then\n  echo \"eligibility not re-proven for $uuid; preserving\" >&2; exit 1\nfi\n\nchmod -R u+w \"$view\"                           # unfreeze the read-only view\ngit worktree remove --force \"$view\"            # --force only after every proof\n\nif [ -e \"$view\" ]; then echo \"incomplete removal; preserving marker\" >&2; exit 1; fi\nif git worktree list --porcelain | grep -qF \"worktree $view\"; then\n  echo \"still registered; preserving marker\" >&2; exit 1\nfi\nif [ \"$(sha256_of \"$marker\")\" != \"$before\" ]; then\n  echo \"owner marker changed during removal; preserving\" >&2; exit 1\nfi\n\nrm -f \"$marker\"                                # remove ONLY the matching marker\n```\n\nIf any step after `chmod` fails, stop and preserve the marker and any partial\nview for conservative recovery; never fall back to recursive deletion.\n\n## Always preserve\n\n- missing, unknown, legacy, or malformed `.owner.json`\n- a live, unprovable, cross-host, or cross-boot owner\n- a present `\u003Cuuid>.reaper-lock` (contended)\n- a candidate referenced by any review transaction\n- a candidate whose changes are not provably merged\n- non-candidate entries (other worktrees, the main worktree, `.worktrees\u002F`,\n  any non-UUID directory in the store)\n\n## After the standard cleanup\n\nThe merged-worktree pass and this sweep are separate stores and separate steps.\nOnce the standard cleanup has reclaimed `.worktrees\u002F`:\n\n```bash\nbash ai-specs\u002Frecipes\u002Fworktree-flow\u002Foverrides\u002Fbin\u002Fworktree-cleanup.sh \\\n  --dir .worktrees --base development --dry-run   # preview\nbash ai-specs\u002Frecipes\u002Fworktree-flow\u002Foverrides\u002Fbin\u002Fworktree-cleanup.sh \\\n  --dir .worktrees --base development\n```\n\nThen invoke this skill explicitly to audit and, when every proof holds, reap\nstale candidate views:\n\n```text\nRun the worktree-candidate-cleanup skill: audit the native review candidate\nstore and reap only views that pass every eligibility proof.\n```\n\n## Non-goals\n\n- No automatic mutation of native review authority or transaction state.\n- No recursive deletion and no staging or committing inside this workflow.\n- No change to the Go cleanup implementation or to the native controller.\n","# Worktree Candidate Cleanup\n\n## Purpose\n\nNative review materializes a frozen candidate tree as a detached Git worktree\nunder the shared git dir, plus a sibling controller owner marker:\n\n```text\n\u003Ccommon-dir>\u002Fgentle-ai\u002Fcandidate-views\u002F\u003Cuuid>\u002F            # frozen read-only tree\n\u003Ccommon-dir>\u002Fgentle-ai\u002Fcandidate-views\u002F\u003Cuuid>.owner.json  # owner marker\n```\n\n`\u003Ccommon-dir>` is `git rev-parse --git-common-dir` (the main worktree's `.git`).\n\nThese views and markers are **owned by the native review controller**. The\nstandard merged-worktree cleanup (`worktree-cleanup.sh` \u002F `\u002Fworktree-clean`)\nonly reclaims `.worktrees\u002F` and never touches this store. This skill defines the\nextra, strictly conservative manual sweep for the residue the controller can no\nlonger own.\n\n## Ownership boundary\n\n- Candidate views and `.owner.json` markers are controller-owned state.\n- Never delete the store, and never mutate review authority, transactions,\n  locks, or receipts.\n- The native controller reaps dead-owner views on its own startup. This skill is\n  for the residue that survives, and it is **more** conservative than that\n  sweep: it additionally requires the candidate's changes to be merged.\n- Process one candidate at a time. If any proof cannot be produced, preserve the\n  entry unchanged.\n\n## Eligibility (all proofs must hold)\n\nA candidate view is eligible for removal only when every proof below passes.\nA missing, malformed, ambiguous, unreadable, or unreproducible proof means\n**preserve**.\n\n1. **Registered candidate worktree.** `\u003Cuuid>` appears exactly once in\n   `git worktree list --porcelain`, that row has no `locked`\u002F`prunable` field,\n   and `\u003Cview>\u002F.git` points to `\u003Ccommon-dir>\u002Fworktrees\u002F\u003Cuuid>`.\n2. **Valid owner marker.** `\u003Cuuid>.owner.json` is a regular non-symlink file\n   whose JSON keys are exactly `commonDir,host,pid,root,token,uuid,version`,\n   with `version: 1`, `uuid == basename(view)`, `root == view`,\n   `commonDir == \u003Ccommon-dir>`, a UUID v4 `token`, a null-or-string `host`,\n   and integer `pid > 0`. Unknown, legacy, or malformed markers are preserved\n   untouched.\n3. **Owner process proven dead.** The marker `host` is non-null and equals the\n   local host identity, the PID is not this process, and `kill(pid, 0)` raises\n   `ESRCH`. A live PID, an `EPERM`\u002Fpermission error, a null host, or a host\n   mismatch all mean **preserve**: pid death cannot be proven across hosts or\n   reboots, and a recycled PID is indistinguishable from a live owner.\n4. **No review reference.** No file under\n   `\u003Ccommon-dir>\u002Fgentle-ai\u002Freview-transactions\u002F**\u002F*.json` mentions the\n   candidate's tree hash, UUID, or path, and no `\u003Cuuid>.reaper-lock` exists.\n   A contended or unreadable transaction store means **preserve**.\n5. **Changes already in the integration branch.** The candidate is contained in\n   the integration branch by ancestry, by tree identity, or by patch-id\n   equivalence (`git cherry`, which covers squash\u002Frebase merges), and the\n   candidate tree is clean (`git status --porcelain` is empty). Never infer the\n   integration branch: it is declared in recipe config, not guessed.\n\n## Dry-run first (read-only)\n\nRun from the main worktree, never from inside a candidate view or a worktree\nbeing removed. This audit prints one verdict per candidate and removes nothing.\n\n```bash\ncd \"$(git rev-parse --show-toplevel)\"          # main worktree root\n# `--git-common-dir` may print a relative `.git` from the main worktree; make it absolute.\ncommon_dir=\"$(CDPATH= cd \"$(git rev-parse --git-common-dir)\" && pwd)\" || {\n  echo \"unable to resolve git common dir\" >&2; exit 1; }\nviews_dir=\"$common_dir\u002Fgentle-ai\u002Fcandidate-views\"\nintegration_branch=\"${INTEGRATION_BRANCH:-development}\"\ngit rev-parse --verify --quiet \"$integration_branch\" >\u002Fdev\u002Fnull || {\n  echo \"unknown integration branch: $integration_branch\" >&2; exit 1; }\n\n# Read-only. Prints one verdict line per candidate; removes nothing.\ncandidate_audit() {\npython3 - \"$common_dir\" \"$integration_branch\" \u003C\u003C'PY'\nimport json, os, platform, re, subprocess, sys, glob\n\nUUID4 = re.compile(r\"^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$\")\n\ncommon_dir, base = sys.argv[1], sys.argv[2]\nviews_dir = os.path.join(common_dir, \"gentle-ai\", \"candidate-views\")\n\ndef git(*args):\n    return subprocess.run([\"git\", *args], capture_output=True, text=True).stdout.strip()\n\ndef local_host():\n    try:\n        if platform.system() == \"Darwin\":\n            boot = subprocess.run([\"\u002Fusr\u002Fsbin\u002Fsysctl\", \"-n\", \"kern.bootsessionuuid\"],\n                                  capture_output=True, text=True, timeout=2).stdout.strip().lower()\n            return f\"darwin:{boot}\" if boot else None\n        if platform.system() == \"Linux\":\n            with open(\"\u002Fproc\u002Fsys\u002Fkernel\u002Frandom\u002Fboot_id\") as fh:\n                boot = fh.read().strip()\n            return f\"linux:{boot}:{os.readlink('\u002Fproc\u002Fself\u002Fns\u002Fpid')}\"\n    except Exception:\n        return None\n    return None\n\ndef owner_dead(owner, host):\n    if not host or owner.get(\"host\") != host:\n        return False\n    pid = owner.get(\"pid\")\n    if not isinstance(pid, int) or pid \u003C= 1 or pid == os.getpid():\n        return False\n    try:\n        os.kill(pid, 0)\n        return False\n    except ProcessLookupError:\n        return True\n    except PermissionError:\n        return False\n\ndef valid_marker(view):\n    path = view + \".owner.json\"\n    try:\n        if os.path.islink(path) or not os.path.isfile(path):\n            return None\n        owner = json.load(open(path))\n    except Exception:\n        return None\n    if set(owner) != {\"commonDir\", \"host\", \"pid\", \"root\", \"token\", \"uuid\", \"version\"}:\n        return None\n    if owner[\"version\"] != 1 or owner[\"uuid\"] != os.path.basename(view):\n        return None\n    if owner[\"root\"] != view or owner[\"commonDir\"] != common_dir:\n        return None\n    if not isinstance(owner[\"pid\"], int) or owner[\"pid\"] \u003C= 0:\n        return None\n    if not isinstance(owner[\"token\"], str) or not UUID4.match(owner[\"token\"]):\n        return None\n    if not (owner[\"host\"] is None or isinstance(owner[\"host\"], str)):\n        return None\n    return owner\n\ndef registered(view):\n    rows = git(\"worktree\", \"list\", \"--porcelain\", \"-z\").split(\"\\0\\0\")\n    hits = [r for r in rows if r.startswith(\"worktree \") and r[9:].split(\"\\0\")[0] == view]\n    if len(hits) != 1:\n        return False\n    fields = hits[0].split(\"\\0\")\n    if any(f == \"locked\" or f.startswith(\"locked \") or\n           f == \"prunable\" or f.startswith(\"prunable \") for f in fields):\n        return False\n    try:\n        pointer = open(os.path.join(view, \".git\")).read()\n    except Exception:\n        return False\n    return (pointer.startswith(\"gitdir: \") and\n            os.path.dirname(pointer[8:].strip()) == os.path.join(common_dir, \"worktrees\"))\n\ndef referenced(tree_hash, view):\n    pattern = os.path.join(common_dir, \"gentle-ai\", \"review-transactions\", \"**\", \"*.json\")\n    for path in glob.glob(pattern, recursive=True):\n        try:\n            blob = open(path).read()\n        except Exception:\n            return True\n        if (tree_hash and tree_hash in blob) or os.path.basename(view) in blob or view in blob:\n            return True\n    return False\n\ndef merged(view):\n    head = git(\"-C\", view, \"rev-parse\", \"HEAD\")\n    if not head:\n        return False\n    if subprocess.run([\"git\", \"merge-base\", \"--is-ancestor\", head, base], capture_output=True).returncode == 0:\n        return True\n    if subprocess.run([\"git\", \"diff\", \"--quiet\", base, head], capture_output=True).returncode == 0:\n        return True\n    cherry = subprocess.run([\"git\", \"cherry\", base, head], capture_output=True, text=True).stdout\n    lines = [line for line in cherry.splitlines() if line.strip()]\n    return bool(lines) and all(line.startswith(\"-\") for line in lines)\n\nhost = local_host()\nif not os.path.isdir(views_dir):\n    print(f\"no candidate store at {views_dir}\")\n    sys.exit(0)\n\nfor entry in sorted(os.listdir(views_dir)):\n    view = os.path.join(views_dir, entry)\n    if entry.endswith(\".owner.json\") or not os.path.isdir(view) or os.path.islink(view):\n        continue\n    reasons = []\n    if not registered(view):\n        reasons.append(\"not a registered candidate worktree\")\n    owner = valid_marker(view)\n    if owner is None:\n        reasons.append(\"missing or malformed owner marker\")\n    elif not owner_dead(owner, host):\n        reasons.append(\"owner process not proven dead\")\n    tree = git(\"-C\", view, \"rev-parse\", \"HEAD^{tree}\")\n    if referenced(tree, view):\n        reasons.append(\"referenced by a review transaction\")\n    if os.path.exists(view + \".reaper-lock\"):\n        reasons.append(\"reaper lock present\")\n    if not merged(view):\n        reasons.append(f\"changes not provably merged into {base}\")\n    dirty = subprocess.run([\"git\", \"--no-optional-locks\", \"-C\", view, \"status\", \"--porcelain\"],\n                           capture_output=True, text=True).stdout.strip()\n    if dirty:\n        reasons.append(\"candidate worktree is dirty\")\n    verdict = \"ELIGIBLE\" if not reasons else \"PRESERVE\"\n    print(f\"{entry}: {verdict} - {'; '.join(reasons) or 'all proofs hold'}\")\nPY\n}\n\ncandidate_audit\n```\n\n## Removal (only after an ELIGIBLE verdict)\n\nRun from the main worktree, in the same shell that defined `candidate_audit`\n(see the dry-run section), one candidate at a time. `chmod -R u+w` mirrors the\ncontroller's cleanup unlocking; the frozen views are materialized read-only.\nThe owner marker is fingerprinted and the read-only audit is re-run immediately\nbefore removal so a candidate that changes or is re-owned mid-sweep is\npreserved instead of reaped.\n\n```bash\ncd \"$(git rev-parse --show-toplevel)\"\n# `--git-common-dir` may print a relative `.git` from the main worktree; make it absolute.\ncommon_dir=\"$(CDPATH= cd \"$(git rev-parse --git-common-dir)\" && pwd)\" || {\n  echo \"unable to resolve git common dir\" >&2; exit 1; }\nviews_dir=\"$common_dir\u002Fgentle-ai\u002Fcandidate-views\"\nintegration_branch=\"${INTEGRATION_BRANCH:-development}\"\nuuid=\"\u003Cuuid>\"                                  # exact ELIGIBLE candidate\nview=\"$views_dir\u002F$uuid\"\nmarker=\"$view.owner.json\"\n\nsha256_of() { if command -v shasum >\u002Fdev\u002Fnull 2>&1; then shasum -a 256 \"$1\" | awk '{print $1}'; else sha256sum \"$1\" | awk '{print $1}'; fi; }\ntype candidate_audit >\u002Fdev\u002Fnull 2>&1 || { echo \"define candidate_audit first (dry-run section)\" >&2; exit 1; }\nif [ ! -d \"$view\" ]; then echo \"no candidate view at $view\" >&2; exit 1; fi\n\nbefore=\"$(sha256_of \"$marker\")\"                # fingerprint the owner marker\nif ! candidate_audit | grep -qx \"$uuid: ELIGIBLE - all proofs hold\"; then\n  echo \"eligibility not re-proven for $uuid; preserving\" >&2; exit 1\nfi\n\nchmod -R u+w \"$view\"                           # unfreeze the read-only view\ngit worktree remove --force \"$view\"            # --force only after every proof\n\nif [ -e \"$view\" ]; then echo \"incomplete removal; preserving marker\" >&2; exit 1; fi\nif git worktree list --porcelain | grep -qF \"worktree $view\"; then\n  echo \"still registered; preserving marker\" >&2; exit 1\nfi\nif [ \"$(sha256_of \"$marker\")\" != \"$before\" ]; then\n  echo \"owner marker changed during removal; preserving\" >&2; exit 1\nfi\n\nrm -f \"$marker\"                                # remove ONLY the matching marker\n```\n\nIf any step after `chmod` fails, stop and preserve the marker and any partial\nview for conservative recovery; never fall back to recursive deletion.\n\n## Always preserve\n\n- missing, unknown, legacy, or malformed `.owner.json`\n- a live, unprovable, cross-host, or cross-boot owner\n- a present `\u003Cuuid>.reaper-lock` (contended)\n- a candidate referenced by any review transaction\n- a candidate whose changes are not provably merged\n- non-candidate entries (other worktrees, the main worktree, `.worktrees\u002F`,\n  any non-UUID directory in the store)\n\n## After the standard cleanup\n\nThe merged-worktree pass and this sweep are separate stores and separate steps.\nOnce the standard cleanup has reclaimed `.worktrees\u002F`:\n\n```bash\nbash ai-specs\u002Frecipes\u002Fworktree-flow\u002Foverrides\u002Fbin\u002Fworktree-cleanup.sh \\\n  --dir .worktrees --base development --dry-run   # preview\nbash ai-specs\u002Frecipes\u002Fworktree-flow\u002Foverrides\u002Fbin\u002Fworktree-cleanup.sh \\\n  --dir .worktrees --base development\n```\n\nThen invoke this skill explicitly to audit and, when every proof holds, reap\nstale candidate views:\n\n```text\nRun the worktree-candidate-cleanup skill: audit the native review candidate\nstore and reap only views that pass every eligibility proof.\n```\n\n## Non-goals\n\n- No automatic mutation of native review authority or transaction state.\n- No recursive deletion and no staging or committing inside this workflow.\n- No change to the Go cleanup implementation or to the native controller.\n",{"name":5,"license":14,"metadata":43,"description":50},{"scope":44,"author":46,"version":47,"auto_invoke":48},[45],"root","ai-specs","1.0",[49],"After merged worktree cleanup to sweep stale native review candidate views","Conservative post-merge sweep for stale native review candidate views under .git\u002Fgentle-ai\u002Fcandidate-views. Trigger: after merged worktree cleanup, or when the candidate-view store accumulates orphaned owners whose process is dead and whose changes are already in the integration branch.\n","main","c092fc1f51280350a4434827e2f6d6d99e3431ca","ai-specs\u002Fskills\u002Fworktree-candidate-cleanup",2,"https:\u002F\u002Fgithub.com\u002Fparada1104\u002Fai-specs-cli","https:\u002F\u002Fgithub.com\u002Fparada1104","2026-11-15 03:00:26",{"source":8,"skillName":5,"commands":59,"prompt":69,"zipAvailable":70},[60,63,66],{"tool":61,"command":62},"npx","npx skills add parada1104\u002Fai-specs-cli --skill worktree-candidate-cleanup",{"tool":64,"command":65},"bunx","bunx skills add parada1104\u002Fai-specs-cli --skill worktree-candidate-cleanup",{"tool":67,"command":68},"pnpm","pnpm dlx skills add parada1104\u002Fai-specs-cli --skill worktree-candidate-cleanup","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fparada1104\u002Fai-specs-cli\u002Fblob\u002Fmain\u002Fai-specs\u002Fskills\u002Fworktree-candidate-cleanup\u002FSKILL.md",true,[],[73,85,96,105,114,124],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":38},"01M71F2TF9TS9DNCJ68M7C3B5S","test-skill","Test skill for fixture purposes.","https:\u002F\u002Fgithub.com\u002Fparada1104\u002Fai-specs-cli\u002Fblob\u002Fmain\u002Ftests\u002Ffixtures\u002Frecipes\u002Ftest-fixture\u002Fskills\u002Ftest-skill\u002FSKILL.md",[],[80,81,35,45,82,83,84],"Test Skill","test","fixtures","fixture","testing",{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":38},"01M71F2RTH94ZB7XEAW4P6ZG0D","obsidian-markdown","Fixture skill for obsidian-markdown.","https:\u002F\u002Fgithub.com\u002Fparada1104\u002Fai-specs-cli\u002Fblob\u002Fmain\u002Ftests\u002Ffixtures\u002Fkepano-obsidian-skills\u002Fskills\u002Fobsidian-markdown\u002FSKILL.md",[],[92,93,94,35,83,95],"markdown","obsidian markdown","obsidian","fixture skill",{"skillNo":97,"name":98,"nameZh":6,"description":99,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":100,"categories":101,"keywords":102,"publishedAt":38},"01M71F2R20CPTJXD9F7DP4JPP6","obsidian-cli","Fixture skill for obsidian-cli.","https:\u002F\u002Fgithub.com\u002Fparada1104\u002Fai-specs-cli\u002Fblob\u002Fmain\u002Ftests\u002Ffixtures\u002Fkepano-obsidian-skills\u002Fskills\u002Fobsidian-cli\u002FSKILL.md",[],[103,94,104,35,83,95],"obsidian cli","cli",{"skillNo":106,"name":107,"nameZh":6,"description":108,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":109,"categories":110,"keywords":111,"publishedAt":38},"01M71F2PCH4NWVTT1J57SHJX33","obsidian-bases","Fixture skill for obsidian-bases.","https:\u002F\u002Fgithub.com\u002Fparada1104\u002Fai-specs-cli\u002Fblob\u002Fmain\u002Ftests\u002Ffixtures\u002Fkepano-obsidian-skills\u002Fskills\u002Fobsidian-bases\u002FSKILL.md",[],[112,113,94,35,83,95],"bases","obsidian bases",{"skillNo":115,"name":116,"nameZh":6,"description":117,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":118,"categories":119,"keywords":120,"publishedAt":38},"01M71F2MSS6EVFEYVYAA1KBYCC","json-canvas","Fixture skill for json-canvas.","https:\u002F\u002Fgithub.com\u002Fparada1104\u002Fai-specs-cli\u002Fblob\u002Fmain\u002Ftests\u002Ffixtures\u002Fkepano-obsidian-skills\u002Fskills\u002Fjson-canvas\u002FSKILL.md",[],[121,122,123,95,83,35],"json","json canvas","canvas",{"skillNo":125,"name":126,"nameZh":6,"description":127,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":128,"categories":129,"keywords":130,"publishedAt":38},"01M71F2KY5QVNEN1Q3REFB0MQZ","defuddle","Fixture skill for defuddle.","https:\u002F\u002Fgithub.com\u002Fparada1104\u002Fai-specs-cli\u002Fblob\u002Fmain\u002Ftests\u002Ffixtures\u002Fkepano-obsidian-skills\u002Fskills\u002Fdefuddle\u002FSKILL.md",[],[126,95,83,35]]