Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): fold ledger re-point sweep into shared spine (PRD-7760) (#3266)
tim-inkeepad623b850262
diff --git a/.changeset/fold-sibling-repoint-spine.md b/.changeset/fold-sibling-repoint-spine.mdnew file mode 100644index 000000000..4fdd16a16--- /dev/null+++ b/.changeset/fold-sibling-repoint-spine.md@@ -0,0 +1,5 @@+---+'@inkeep/open-knowledge': patch+---++Skill relocation now runs a single sibling symlink re-point spine. The promote path's placement-ledger sweep was a hand-maintained second copy that claimed a narrower set of links and wrote link targets by a different rule; it now routes through the same helper as the host-dir sweep. A recorded placement that pointed at the old source is re-pointed directly at the new one instead of being left chained through it.diff --git a/packages/app/tests/integration/skills-in-place-list.test.ts b/packages/app/tests/integration/skills-in-place-list.test.tsindex 8d0189fc7..63d7bba3b 100644--- a/packages/app/tests/integration/skills-in-place-list.test.ts+++ b/packages/app/tests/integration/skills-in-place-list.test.ts@@ -566,6 +566,77 @@ describe('in-place skill install fan-out (R13 inversion)', () => {expect(((await noop.json()) as { sourceMovedTo?: string }).sourceMovedTo).toBeUndefined();});+ test('setSource flattens a recorded placement link that chained through the new source', async () => {+ const { dirname, isAbsolute, resolve } = await import('node:path');+ const { readlinkSync } = await import('node:fs');+ // .claude is the source; .codex a copy; a recorded placement LINKS to+ // .claude. Promoting .codex leaves .claude a link to it, so the placement+ // resolves to the real dir only by chaining through .claude.+ expect((await install(['claude', 'codex'])).status).toBe(200);+ const placed = await fetch(`${base()}/api/skill/install`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ name: 'fanout',+ scope: 'project',+ place: { dir: '.windsurf/skills', mode: 'link' },+ }),+ });+ expect(placed.status).toBe(200);+ const promoted = await fetch(`${base()}/api/skill/install`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ name: 'fanout', scope: 'project', setSource: 'codex' }),+ });+ expect(promoted.status).toBe(200);+ // The ledger sweep claims chains through the new source exactly as the+ // host-slot sweep does: ONE hop to the real dir, not two through .claude.+ const link = join(contentDir, '.windsurf/skills/fanout');+ const oneHop = resolve(dirname(link), readlinkSync(link));+ expect(oneHop).toBe(join(contentDir, '.codex/skills/fanout'));+ // `resolve(dirname, readlink)` normalizes a relative and an absolute target+ // to the same path, so pin the FORM separately: every target this call site+ // can produce is inside the project, which is the relative branch of+ // `skillLinkTarget`. The absolute branch is unreachable from here.+ expect(isAbsolute(readlinkSync(link))).toBe(false);+ });++ test('setSource does not re-point sibling host links the relocation sweep already owns', async () => {+ const { dirname, resolve } = await import('node:path');+ const { readlinkSync, lstatSync } = await import('node:fs');+ // The placement ledger records host slots too, so the ledger sweep's slot+ // list overlaps the relocation sweep's. Excluding the host-owned ones must+ // not leave any sibling stale: after the promote every non-source host link+ // still resolves in ONE hop to the new real dir.+ expect(+ (+ await fetch(`${base()}/api/skill/install`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ name: 'fanout',+ scope: 'project',+ targets: ['claude', 'codex', 'cursor'],+ linkMode: true,+ }),+ })+ ).status,+ ).toBe(200);+ const promoted = await fetch(`${base()}/api/skill/install`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ name: 'fanout', scope: 'project', setSource: 'codex' }),+ });+ expect(promoted.status).toBe(200);+ const dest = join(contentDir, '.codex/skills/fanout');+ expect(lstatSync(dest).isSymbolicLink()).toBe(false);+ for (const sib of ['.claude/skills/fanout', '.cursor/skills/fanout']) {+ const abs = join(contentDir, sib);+ expect(lstatSync(abs).isSymbolicLink()).toBe(true);+ expect(resolve(dirname(abs), readlinkSync(abs))).toBe(dest);+ }+ });+test('placing a skill at the location it already occupies is a no-op success', async () => {// Imports land IN-PLACE at the `.agents/skills` hub, so asking to place a// freshly imported skill there names its own canonical dir. That used todiff --git a/packages/server/src/services/skill-install-ops.ts b/packages/server/src/services/skill-install-ops.tsindex 4b780e240..c717b3a68 100644--- a/packages/server/src/services/skill-install-ops.ts+++ b/packages/server/src/services/skill-install-ops.ts@@ -1,4 +1,4 @@-import { existsSync, lstatSync, readFileSync, realpathSync } from 'node:fs';+import { existsSync, lstatSync, readFileSync } from 'node:fs';import { dirname, join, relative, resolve, sep } from 'node:path';import {applyPatchToFm,@@ -38,9 +38,11 @@ import {} from '../skill-placements.ts';import {classifyInPlaceDest,+ hostSlotPaths,projectInPlaceSkill,relocateInPlaceCanonical,removeInPlaceSkillCopies,+ repointSiblingLinks,skillProjectionRoots,} from '../skill-projection.ts';@@ -453,26 +455,31 @@ export function createSkillInstallOpsService(deps: SkillInstallOpsDeps): SkillInmode: 'link',});// Re-point recorded placement SYMLINKS that referenced the old- // source (the relocation loop only covers host dirs).- for (const p of readSkillPlacements(ledgerBase)[name] ?? []) {- const abs = resolve(ledgerBase, p.path);- if (abs === moved.newAbs) continue;- try {- if (!lstatSync(abs).isSymbolicLink()) continue;- } catch {- continue;- }- let target: string | null = null;- try {- target = realpathSync(abs);- } catch {- target = null; // dangling (pointed at the moved-away dir)- }- if (target === null || target === resolve(skillDir)) {- tracedRmSync(abs, { recursive: true, force: true });- tracedSymlinkSync(relative(dirname(abs), moved.newAbs), abs, 'dir');- }- }+ // source: `relocateInPlaceCanonical`'s own sweep only walks host dirs,+ // so the ledger is a second slot source over the same relocation. Both+ // run the shared spine with the same claim + skip sets, because two+ // sweeps of one relocation disagreeing is how a link or a directory the+ // other was written to preserve gets deleted.+ //+ // The ledger records host slots too, so the two slot sources OVERLAP.+ // Excluding the host-owned ones is what keeps a sibling host link from+ // being unlinked and rebuilt here microseconds after the host sweep+ // wrote it correctly -- byte-identical, tree-invisible, and exactly the+ // scar `skip` exists to avoid on the slots this sweep does own.+ const hostOwned = new Set(+ hostSlotPaths(base, name, skillProjectionRoots(scope)).map((p) => resolve(p)),+ );+ repointSiblingLinks({+ name,+ cwd: base,+ roots: skillProjectionRoots(scope),+ target: moved.newAbs,+ slots: (readSkillPlacements(ledgerBase)[name] ?? [])+ .map((pl) => resolve(ledgerBase, pl.path))+ .filter((abs) => !hostOwned.has(abs)),+ skip: [moved.newAbs, resolve(skillDir)],+ alsoClaim: [resolve(skillDir), moved.newAbs],+ });// The promoted path is now the REAL dir — refresh its receipt to// the promoted form (hash-less copy: no drift, resync skips it,// and a custom root stays registered with the scan). A leftoverdiff --git a/packages/server/src/skill-projection.ts b/packages/server/src/skill-projection.tsindex 0cb2e952f..25feb60fc 100644--- a/packages/server/src/skill-projection.ts+++ b/packages/server/src/skill-projection.ts@@ -615,19 +615,32 @@ const ALL_TARGET_HOSTS: readonly SkillHostId[] = [...(PROJECT_SKILL_EDITOR_IDS as readonly EditorId[]),];+/**+ * The host-dir slots for `name` — the slots {@link repointSiblingLinks} sweeps+ * by default, and therefore the ones a caller passing its OWN `slots` must+ * exclude: two sweeps claiming one slot on the same relocation is a redundant+ * unlink-and-rebuild of a link the other just wrote correctly.+ */+export function hostSlotPaths(cwd: string, name: string, roots: SkillProjectionRoots): string[] {+ return ALL_TARGET_HOSTS.map((host) => skillTargetDir(cwd, host, name, roots)).filter(+ (p): p is string => p !== null,+ );+}+/*** Re-point sibling symlinks at `target`: walk every install-target host, skip* anything that is not a symlink, and replace each CLAIMED link with one aimed* directly at `target`. Shared by relocation and removal, which walk the same* slots for the same reason.*- * A THIRD sweep of this shape lives in `api-extension.ts`, in the promote path.- * It is not shared because it walks the placement LEDGER rather than host slots,- * so folding it in needs a slot-source parameter this helper does not have. It- * also claims a narrower set: dangling or the old source, but not a link chained- * through the new dest, which this one claims via `alsoClaim`. Both sweeps fire- * on the same relocation, and the divergence is inert because a link resolving- * to `dest` already resolves to a real dir. Widen either and they must agree.+ * The promote path's placement-ledger sweep in `skill-install-ops.ts` routes+ * through here too, handing its ledger paths to `slots`. The two sweeps fire on+ * the same relocation and PARTITION the slots between them: the ledger caller+ * excludes {@link hostSlotPaths}, because a slot swept twice is an unlink and+ * rebuild of a link the first sweep already wrote correctly. Folding them also+ * widened the ledger sweep's claim set to match this one's, so a placement that+ * reached the real dir by chaining through the new source is now flattened+ * rather than left as a chain.** They differ in which links they claim, and that difference is data, not an* inverted condition. A dangling link is ALWAYS claimed: it resolves to@@ -647,12 +660,20 @@ const ALL_TARGET_HOSTS: readonly SkillHostId[] = [* sequence of filesystem operations is not, and in this file an unnecessary* unlink of a link standing in for a real directory is the scar being avoided.*/-function repointSiblingLinks(opts: {+export function repointSiblingLinks(opts: {name: string;cwd: string;roots: SkillProjectionRoots;/** Real bundle dir every claimed link is re-pointed at. */target: string;+ /**+ * Absolute slot paths to sweep. Defaults to {@link hostSlotPaths} for `name`;+ * the promote path passes its placement-ledger paths instead, so both slot+ * sources run the same claim + skip rules. When supplied, `name` and `roots`+ * are unused — they only feed the default — so the caller controls which+ * slots are swept without affecting the link target written (always `target`).+ */+ slots?: readonly string[];/** Sibling SLOTS never touched, matched on the slot path itself. */skip?: readonly string[];/** Link REALPATHS claimed on top of dangling ones. */@@ -661,9 +682,9 @@ function repointSiblingLinks(opts: {const { name, cwd, roots, target } = opts;const skip = new Set((opts.skip ?? []).map((p) => resolve(p)));const claim = new Set((opts.alsoClaim ?? []).map((p) => resolve(p)));- for (const host of ALL_TARGET_HOSTS) {- const sib = skillTargetDir(cwd, host, name, roots);- if (sib === null || skip.has(resolve(sib))) continue;+ const slots = opts.slots ?? hostSlotPaths(cwd, name, roots);+ for (const sib of slots) {+ if (skip.has(resolve(sib))) continue;try {if (!lstatSync(sib).isSymbolicLink()) continue;} catch {