repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

opencode/tests/skill-authoring.test.ts

Raw
import { beforeEach, describe, expect, mock, test } from "bun:test";
import path from "node:path";
import { Volume } from "memfs";

const vol = new Volume();

// Factory function for the fs mock - used at top level and in resetFsMock()
function createFsMock() {
  return {
    lstat: async (p: string) => vol.lstatSync(p),
    mkdir: async (p: string, opts?: any) => vol.mkdirSync(p, opts),
    cp: async (src: string, dest: string, opts?: any) =>
      vol.cpSync(src, dest, opts),
    rm: async (p: string, opts?: any) => {
      const stat = vol.lstatSync(p);
      if (stat.isSymbolicLink()) {
        vol.unlinkSync(p);
      } else {
        vol.rmSync(p, opts);
      }
    },
    symlink: async (target: string, p: string) => vol.symlinkSync(target, p),
    readlink: async (p: string) => vol.readlinkSync(p),
    readFile: async (p: string, opts?: any) => vol.readFileSync(p, opts),
    writeFile: async (p: string, data: any) => vol.writeFileSync(p, data),
    readdir: async (p: string, opts?: any) => vol.readdirSync(p, opts),
    stat: async (p: string) => vol.statSync(p),
    open: async () => ({ close: async () => {} }),
  };
}

// Top-level mock to ensure this mock is applied before any imports happen
mock.module("node:fs/promises", createFsMock);
mock.module(
  "node:os",
  () => ({ homedir: () => "/home/testuser", tmpdir: () => "/tmp" }),
);

function resetFsMock() {
  mock.module("node:fs/promises", createFsMock);
  mock.module(
    "node:os",
    () => ({ homedir: () => "/home/testuser", tmpdir: () => "/tmp" }),
  );
}

beforeEach(() => {
  vol.reset();
  resetFsMock();
});

// Context objects for testing
const ctxWithWorktree = {
  directory: "/test/project",
  worktree: "/test/project",
} as any;
const ctxNoWorktree = {
  directory: "/test/project",
  worktree: undefined as string | undefined,
} as any;

describe("list - parseFrontmatter behavior", () => {
  const globalBase = "/home/testuser/.config/opencode/skills";

  test("list parses valid frontmatter with name and description", async () => {
    vol.mkdirSync(globalBase, { recursive: true });
    vol.mkdirSync(path.join(globalBase, "my-skill"), { recursive: true });
    vol.writeFileSync(
      path.join(globalBase, "my-skill", "SKILL.md"),
      `---
name: my-skill
description: Does amazing things
---

# Body content`,
    );

    const { list } = await import("../tools/skill-authoring.ts");
    const result = await list.execute({}, ctxWithWorktree);

    expect(result).toContain("- my-skill (global)");
    expect(result).toContain("description: Does amazing things");
  });

  test("list handles no frontmatter - uses dir name + (no description)", async () => {
    vol.mkdirSync(globalBase, { recursive: true });
    vol.mkdirSync(path.join(globalBase, "orphan-skill"), { recursive: true });
    vol.writeFileSync(
      path.join(globalBase, "orphan-skill", "SKILL.md"),
      "# Just a header\n\nSome content",
    );

    const { list } = await import("../tools/skill-authoring.ts");
    const result = await list.execute({}, ctxWithWorktree);

    expect(result).toContain("- orphan-skill (global)");
    expect(result).toContain("description: (no description)");
  });

  test("list handles frontmatter with name only", async () => {
    vol.mkdirSync(globalBase, { recursive: true });
    vol.mkdirSync(path.join(globalBase, "name-only"), { recursive: true });
    vol.writeFileSync(
      path.join(globalBase, "name-only", "SKILL.md"),
      `---
name: name-only
---

# Body`,
    );

    const { list } = await import("../tools/skill-authoring.ts");
    const result = await list.execute({}, ctxWithWorktree);

    expect(result).toContain("- name-only (global)");
    expect(result).toContain("description: (no description)");
  });

  test("list handles frontmatter with description only", async () => {
    vol.mkdirSync(globalBase, { recursive: true });
    vol.mkdirSync(path.join(globalBase, "desc-only"), { recursive: true });
    vol.writeFileSync(
      path.join(globalBase, "desc-only", "SKILL.md"),
      `---
description: Just a description
---

# Body`,
    );

    const { list } = await import("../tools/skill-authoring.ts");
    const result = await list.execute({}, ctxWithWorktree);

    // Should use directory name for name, description from frontmatter
    expect(result).toContain("- desc-only (global)");
    expect(result).toContain("description: Just a description");
  });
});

describe("list - scanSkillsDir behavior", () => {
  const globalBase = "/home/testuser/.config/opencode/skills";

  test("list returns empty when directory does not exist (ENOENT)", async () => {
    // Don't create the directory at all
    const { list } = await import("../tools/skill-authoring.ts");
    const result = await list.execute({}, ctxWithWorktree);
    expect(result).toBe("No skills found.");
  });

  test("list returns empty when directory exists but empty", async () => {
    vol.mkdirSync(globalBase, { recursive: true });
    vol.mkdirSync("/test/project/.opencode/skills", { recursive: true });

    const { list } = await import("../tools/skill-authoring.ts");
    const result = await list.execute({}, ctxWithWorktree);
    expect(result).toBe("No skills found.");
  });

  test("list skips entry when it is a file (not directory)", async () => {
    vol.mkdirSync(globalBase, { recursive: true });
    vol.writeFileSync(path.join(globalBase, "not-a-dir.txt"), "content");
    vol.mkdirSync("/test/project/.opencode/skills", { recursive: true });

    const { list } = await import("../tools/skill-authoring.ts");
    const result = await list.execute({}, ctxWithWorktree);
    expect(result).toBe("No skills found.");
  });

  test("list skips subdirectory with no SKILL.md (inner catch)", async () => {
    vol.mkdirSync(globalBase, { recursive: true });
    vol.mkdirSync(path.join(globalBase, "empty-skill"), { recursive: true });
    // No SKILL.md file
    vol.mkdirSync("/test/project/.opencode/skills", { recursive: true });

    const { list } = await import("../tools/skill-authoring.ts");
    const result = await list.execute({}, ctxWithWorktree);
    expect(result).toBe("No skills found.");
  });

  test("list skips SKILL.md when lstat returns non-file (isFile() = false)", async () => {
    vol.mkdirSync(globalBase, { recursive: true });
    vol.mkdirSync(path.join(globalBase, "my-skill"), { recursive: true });
    vol.writeFileSync(path.join(globalBase, "my-skill", "SKILL.md"), "content");

    // Mock lstat to return isFile: false
    mock.module("node:fs/promises", () => ({
      lstat: mock(async () => ({
        isFile: () => false,
        isDirectory: () => false,
      })),
      mkdir: async (p: string, opts?: any) => vol.mkdirSync(p, opts),
      readdir: async (p: string, opts?: any) => vol.readdirSync(p, opts),
      readFile: async (p: string, opts?: any) => vol.readFileSync(p, opts),
      writeFile: async (p: string, data: any) => vol.writeFileSync(p, data),
    }));

    vol.mkdirSync("/test/project/.opencode/skills", { recursive: true });

    const { list } = await import("../tools/skill-authoring.ts");
    const result = await list.execute({}, ctxWithWorktree);
    expect(result).toBe("No skills found.");
  });

  test("list skips SKILL.md when readFile throws (inner catch)", async () => {
    vol.mkdirSync(globalBase, { recursive: true });
    vol.mkdirSync(path.join(globalBase, "bad-skill"), { recursive: true });
    vol.writeFileSync(
      path.join(globalBase, "bad-skill", "SKILL.md"),
      "content",
    );

    // Mock readFile to throw
    mock.module("node:fs/promises", () => ({
      lstat: async (p: string) => vol.lstatSync(p),
      mkdir: async (p: string, opts?: any) => vol.mkdirSync(p, opts),
      readdir: async (p: string, opts?: any) => vol.readdirSync(p, opts),
      readFile: mock(async () => {
        throw new Error("Read error");
      }),
      writeFile: async (p: string, data: any) => vol.writeFileSync(p, data),
    }));

    vol.mkdirSync("/test/project/.opencode/skills", { recursive: true });

    const { list } = await import("../tools/skill-authoring.ts");
    const result = await list.execute({}, ctxWithWorktree);
    // Should skip the bad skill and return empty
    expect(result).toBe("No skills found.");
  });

  test("list logs warning and returns empty on non-ENOENT error", async () => {
    const warnSpy = mock(() => {});
    console.warn = warnSpy;

    mock.module("node:fs/promises", () => ({
      lstat: async (p: string) => vol.lstatSync(p),
      mkdir: async (p: string, opts?: any) => vol.mkdirSync(p, opts),
      readdir: mock(async () => {
        const err = new Error("Permission denied") as NodeJS.ErrnoException;
        err.code = "EACCES";
        throw err;
      }),
      readFile: async (p: string, opts?: any) => vol.readFileSync(p, opts),
      writeFile: async (p: string, data: any) => vol.writeFileSync(p, data),
    }));

    const { list } = await import("../tools/skill-authoring.ts");
    const result = await list.execute({}, ctxWithWorktree);

    expect(result).toBe("No skills found.");
    expect(warnSpy).toHaveBeenCalled();
    expect(warnSpy).toHaveBeenCalledWith(
      expect.stringContaining("Failed to scan skills directory"),
    );
  });
});

describe("list", () => {
  const globalBase = "/home/testuser/.config/opencode/skills";

  test("returns 'No skills found.' when both dirs empty", async () => {
    vol.mkdirSync(globalBase, { recursive: true });
    vol.mkdirSync("/test/project/.opencode/skills", { recursive: true });

    const { list } = await import("../tools/skill-authoring.ts");
    const result = await list.execute({}, ctxWithWorktree);
    expect(result).toBe("No skills found.");
  });

  test("lists only global skills when project dir empty", async () => {
    vol.mkdirSync(globalBase, { recursive: true });
    vol.mkdirSync(path.join(globalBase, "global-skill"), { recursive: true });
    vol.writeFileSync(
      path.join(globalBase, "global-skill", "SKILL.md"),
      `---
name: global-skill
description: A global skill
---

# Body`,
    );
    vol.mkdirSync("/test/project/.opencode/skills", { recursive: true });

    const { list } = await import("../tools/skill-authoring.ts");
    const result = await list.execute({}, ctxWithWorktree);

    expect(result).toContain("=== Global Skills ===");
    expect(result).toContain("- global-skill (global)");
    expect(result).not.toContain("=== Project Skills ===");
  });

  test("lists only project skills when global dir empty", async () => {
    vol.mkdirSync(globalBase, { recursive: true });
    vol.mkdirSync("/test/project/.opencode/skills", { recursive: true });
    vol.mkdirSync("/test/project/.opencode/skills/project-skill", {
      recursive: true,
    });
    vol.writeFileSync(
      "/test/project/.opencode/skills/project-skill/SKILL.md",
      `---
name: project-skill
description: A project skill
---

# Body`,
    );

    const { list } = await import("../tools/skill-authoring.ts");
    const result = await list.execute({}, ctxWithWorktree);

    expect(result).toContain("=== Project Skills ===");
    expect(result).toContain("- project-skill (project)");
    expect(result).not.toContain("=== Global Skills ===");
  });

  test("lists both global and project skills", async () => {
    // Setup global
    vol.mkdirSync(globalBase, { recursive: true });
    vol.mkdirSync(path.join(globalBase, "global-skill"), { recursive: true });
    vol.writeFileSync(
      path.join(globalBase, "global-skill", "SKILL.md"),
      `---
name: global-skill
description: Global desc
---

# Body`,
    );

    // Setup project
    vol.mkdirSync("/test/project/.opencode/skills", { recursive: true });
    vol.mkdirSync("/test/project/.opencode/skills/project-skill", {
      recursive: true,
    });
    vol.writeFileSync(
      "/test/project/.opencode/skills/project-skill/SKILL.md",
      `---
name: project-skill
description: Project desc
---

# Body`,
    );

    const { list } = await import("../tools/skill-authoring.ts");
    const result = await list.execute({}, ctxWithWorktree);

    expect(result).toContain("=== Global Skills ===");
    expect(result).toContain("- global-skill (global)");
    expect(result).toContain("=== Project Skills ===");
    expect(result).toContain("- project-skill (project)");
  });

  test("uses context.worktree when set", async () => {
    // Only create in worktree path, not directory path
    vol.mkdirSync(globalBase, { recursive: true });
    vol.mkdirSync("/test/worktree/.opencode/skills", { recursive: true });
    vol.mkdirSync("/test/worktree/.opencode/skills/worktree-skill", {
      recursive: true,
    });
    vol.writeFileSync(
      "/test/worktree/.opencode/skills/worktree-skill/SKILL.md",
      `---
name: worktree-skill
description: Worktree skill
---

# Body`,
    );

    const ctxWithDifferentWorktree = {
      directory: "/test/project",
      worktree: "/test/worktree",
    } as any;

    const { list } = await import("../tools/skill-authoring.ts");
    const result = await list.execute({}, ctxWithDifferentWorktree);

    expect(result).toContain("worktree-skill");
    expect(result).toContain(
      "path: /test/worktree/.opencode/skills/worktree-skill/SKILL.md",
    );
  });

  test("falls back to context.directory when worktree is undefined", async () => {
    // Only create in directory path (not worktree)
    vol.mkdirSync(globalBase, { recursive: true });
    vol.mkdirSync("/test/project/.opencode/skills", { recursive: true });
    vol.mkdirSync("/test/project/.opencode/skills/dir-skill", {
      recursive: true,
    });
    vol.writeFileSync(
      "/test/project/.opencode/skills/dir-skill/SKILL.md",
      `---
name: dir-skill
description: Directory skill
---

# Body`,
    );

    const { list } = await import("../tools/skill-authoring.ts");
    const result = await list.execute({}, ctxNoWorktree);

    expect(result).toContain("dir-skill");
    expect(result).toContain(
      "path: /test/project/.opencode/skills/dir-skill/SKILL.md",
    );
  });

  test("falls back to context.directory when worktree is empty string", async () => {
    const ctxWithEmptyWorktree = {
      directory: "/test/project",
      worktree: "" as string,
    } as any;

    vol.mkdirSync(globalBase, { recursive: true });
    vol.mkdirSync("/test/project/.opencode/skills", { recursive: true });
    vol.mkdirSync("/test/project/.opencode/skills/empty-worktree-skill", {
      recursive: true,
    });
    vol.writeFileSync(
      "/test/project/.opencode/skills/empty-worktree-skill/SKILL.md",
      `---
name: empty-worktree-skill
description: Empty worktree skill
---

# Body`,
    );

    const { list } = await import("../tools/skill-authoring.ts");
    const result = await list.execute({}, ctxWithEmptyWorktree);

    expect(result).toContain("empty-worktree-skill");
  });
});

describe("write - validateSkillName behavior", () => {
  test("returns error for empty string", async () => {
    const { write } = await import("../tools/skill-authoring.ts");
    const result = await write.execute(
      { name: "", content: "test", scope: "global" },
      ctxWithWorktree,
    );
    expect(result).toBe("Skill name cannot be empty");
  });

  test("returns error for name > 64 chars", async () => {
    const { write } = await import("../tools/skill-authoring.ts");
    const longName = "a".repeat(65);
    const result = await write.execute(
      { name: longName, content: "test", scope: "global" },
      ctxWithWorktree,
    );
    expect(result).toBe("Skill name must be 64 characters or less");
  });

  test("returns error for uppercase letters", async () => {
    const { write } = await import("../tools/skill-authoring.ts");
    const result = await write.execute(
      { name: "My-Skill", content: "test", scope: "global" },
      ctxWithWorktree,
    );
    expect(result).toBe(
      "Skill name must be lowercase alphanumeric with hyphens only (e.g. 'my-skill')",
    );
  });

  test("returns error for spaces", async () => {
    const { write } = await import("../tools/skill-authoring.ts");
    const result = await write.execute(
      { name: "my skill", content: "test", scope: "global" },
      ctxWithWorktree,
    );
    expect(result).toBe(
      "Skill name must be lowercase alphanumeric with hyphens only (e.g. 'my-skill')",
    );
  });

  test("returns error for special characters", async () => {
    const { write } = await import("../tools/skill-authoring.ts");
    const result1 = await write.execute(
      { name: "my_skill", content: "test", scope: "global" },
      ctxWithWorktree,
    );
    expect(result1).toBe(
      "Skill name must be lowercase alphanumeric with hyphens only (e.g. 'my-skill')",
    );

    const result2 = await write.execute(
      { name: "my.skill", content: "test", scope: "global" },
      ctxWithWorktree,
    );
    expect(result2).toBe(
      "Skill name must be lowercase alphanumeric with hyphens only (e.g. 'my-skill')",
    );
  });

  test("returns error for name starting with hyphen", async () => {
    const { write } = await import("../tools/skill-authoring.ts");
    const result = await write.execute(
      { name: "-myskills", content: "test", scope: "global" },
      ctxWithWorktree,
    );
    expect(result).toBe(
      "Skill name must be lowercase alphanumeric with hyphens only (e.g. 'my-skill')",
    );
  });

  test("returns error for name ending with hyphen", async () => {
    const { write } = await import("../tools/skill-authoring.ts");
    const result = await write.execute(
      { name: "myskills-", content: "test", scope: "global" },
      ctxWithWorktree,
    );
    expect(result).toBe(
      "Skill name must be lowercase alphanumeric with hyphens only (e.g. 'my-skill')",
    );
  });

  test("returns error for double hyphen", async () => {
    const { write } = await import("../tools/skill-authoring.ts");
    const result = await write.execute(
      { name: "my--skill", content: "test", scope: "global" },
      ctxWithWorktree,
    );
    expect(result).toBe(
      "Skill name must be lowercase alphanumeric with hyphens only (e.g. 'my-skill')",
    );
  });

  test("returns null for valid name 'my-skill'", async () => {
    const { write } = await import("../tools/skill-authoring.ts");
    const result = await write.execute(
      { name: "my-skill", content: "# Test", scope: "global" },
      ctxWithWorktree,
    );
    expect(result).toContain("Created/updated skill:");
  });

  test("returns null for valid name 'abc123'", async () => {
    const { write } = await import("../tools/skill-authoring.ts");
    const result = await write.execute(
      { name: "abc123", content: "# Test", scope: "global" },
      ctxWithWorktree,
    );
    expect(result).toContain("Created/updated skill:");
  });

  test("returns null for exactly 64 characters", async () => {
    const { write } = await import("../tools/skill-authoring.ts");
    const exact64 = "a".repeat(64);
    const result = await write.execute(
      { name: exact64, content: "# Test", scope: "global" },
      ctxWithWorktree,
    );
    expect(result).toContain("Created/updated skill:");
  });
});

describe("write", () => {
  const globalBase = "/home/testuser/.config/opencode/skills";

  test("returns mismatch error when frontmatter name doesn't match arg name", async () => {
    const { write } = await import("../tools/skill-authoring.ts");
    const result = await write.execute(
      {
        name: "my-skill",
        content: `---\nname: other-skill\ndescription: test\n---\n\n# Body`,
        scope: "global",
      },
      ctxWithWorktree,
    );
    expect(result).toBe(
      "Skill name in content (other-skill) does not match the name argument (my-skill)",
    );
  });

  test("succeeds when frontmatter name matches arg name", async () => {
    const { write } = await import("../tools/skill-authoring.ts");
    const result = await write.execute(
      {
        name: "my-skill",
        content: `---\nname: my-skill\ndescription: test\n---\n\n# Body`,
        scope: "global",
      },
      ctxWithWorktree,
    );
    expect(result).toContain("Created/updated skill:");
    expect(result).toContain(path.join(globalBase, "my-skill", "SKILL.md"));
  });

  test("succeeds when no frontmatter name in content (no mismatch)", async () => {
    const { write } = await import("../tools/skill-authoring.ts");
    const result = await write.execute(
      {
        name: "my-skill",
        content: `# Just a skill\n\nNo frontmatter`,
        scope: "global",
      },
      ctxWithWorktree,
    );
    expect(result).toContain("Created/updated skill:");
  });

  test("writes to homedir path when scope is 'global'", async () => {
    const { write } = await import("../tools/skill-authoring.ts");
    const result = await write.execute(
      { name: "global-test", content: "# Test", scope: "global" },
      ctxWithWorktree,
    );

    expect(result).toContain(
      "/home/testuser/.config/opencode/skills/global-test/SKILL.md",
    );
    expect(
      vol.existsSync(
        "/home/testuser/.config/opencode/skills/global-test/SKILL.md",
      ),
    ).toBe(true);
  });

  test("writes to worktree path when scope is 'project'", async () => {
    const { write } = await import("../tools/skill-authoring.ts");
    const result = await write.execute(
      { name: "project-test", content: "# Test", scope: "project" },
      ctxWithWorktree,
    );

    expect(result).toContain(
      "/test/project/.opencode/skills/project-test/SKILL.md",
    );
    expect(
      vol.existsSync("/test/project/.opencode/skills/project-test/SKILL.md"),
    ).toBe(true);
  });

  test("falls back to directory when worktree is undefined and scope is 'project'", async () => {
    const { write } = await import("../tools/skill-authoring.ts");
    const result = await write.execute(
      { name: "fallback-test", content: "# Test", scope: "project" },
      ctxNoWorktree,
    );

    expect(result).toContain(
      "/test/project/.opencode/skills/fallback-test/SKILL.md",
    );
    expect(
      vol.existsSync("/test/project/.opencode/skills/fallback-test/SKILL.md"),
    ).toBe(true);
  });

  test("returns error when mkdir throws", async () => {
    mock.module("node:fs/promises", () => ({
      lstat: async (p: string) => vol.lstatSync(p),
      mkdir: mock(async () => {
        throw new Error("mkdir failed");
      }),
      readdir: async (p: string, opts?: any) => vol.readdirSync(p, opts),
      readFile: async (p: string, opts?: any) => vol.readFileSync(p, opts),
      writeFile: async (p: string, data: any) => vol.writeFileSync(p, data),
    }));

    const { write } = await import("../tools/skill-authoring.ts");
    const result = await write.execute(
      { name: "test-skill", content: "# Test", scope: "global" },
      ctxWithWorktree,
    );

    expect(result).toBe("Failed to write skill: mkdir failed");
  });

  test("returns error when writeFile throws", async () => {
    mock.module("node:fs/promises", () => ({
      lstat: async (p: string) => vol.lstatSync(p),
      mkdir: async (p: string, opts?: any) => vol.mkdirSync(p, opts),
      readdir: async (p: string, opts?: any) => vol.readdirSync(p, opts),
      readFile: async (p: string, opts?: any) => vol.readFileSync(p, opts),
      writeFile: mock(async () => {
        throw new Error("writeFile failed");
      }),
    }));

    const { write } = await import("../tools/skill-authoring.ts");
    const result = await write.execute(
      { name: "test-skill", content: "# Test", scope: "global" },
      ctxWithWorktree,
    );

    expect(result).toBe("Failed to write skill: writeFile failed");
  });

  test("creates nested directories with recursive: true", async () => {
    const { write } = await import("../tools/skill-authoring.ts");
    const result = await write.execute(
      { name: "nested-skill", content: "# Test", scope: "global" },
      ctxWithWorktree,
    );

    // Should succeed - mkdir with recursive: true creates parent dirs
    expect(result).toContain("Created/updated skill:");
    expect(
      vol.existsSync(
        "/home/testuser/.config/opencode/skills/nested-skill/SKILL.md",
      ),
    ).toBe(true);
  });
});

describe("append - validateSkillName behavior", () => {
  test("returns error for invalid name", async () => {
    const { append } = await import("../tools/skill-authoring.ts");
    const result = await append.execute(
      { name: "Invalid!", scope: "global", addition: "new content" },
      ctxWithWorktree,
    );
    expect(result).toBe(
      "Skill name must be lowercase alphanumeric with hyphens only (e.g. 'my-skill')",
    );
  });

  test("returns error for empty string name", async () => {
    const { append } = await import("../tools/skill-authoring.ts");
    const result = await append.execute(
      { name: "", scope: "global", addition: "new content" },
      ctxWithWorktree,
    );
    expect(result).toBe("Skill name cannot be empty");
  });

  test("returns error for name > 64 chars", async () => {
    const { append } = await import("../tools/skill-authoring.ts");
    const longName = "a".repeat(65);
    const result = await append.execute(
      { name: longName, scope: "global", addition: "new content" },
      ctxWithWorktree,
    );
    expect(result).toBe("Skill name must be 64 characters or less");
  });
});

describe("append", () => {
  const globalBase = "/home/testuser/.config/opencode/skills";

  test("returns 'Skill not found' when file doesn't exist (ENOENT)", async () => {
    // Don't create any files
    const { append } = await import("../tools/skill-authoring.ts");
    const result = await append.execute(
      { name: "nonexistent", scope: "global", addition: "new content" },
      ctxWithWorktree,
    );
    expect(result).toBe(
      "Skill not found: nonexistent (global). Use 'write' to create a new skill first.",
    );
  });

  test("returns error when readFile throws non-ENOENT error", async () => {
    // Create the skill dir but mock readFile to fail
    vol.mkdirSync(path.join(globalBase, "exists"), { recursive: true });
    vol.writeFileSync(path.join(globalBase, "exists", "SKILL.md"), "original");

    mock.module("node:fs/promises", () => ({
      lstat: async (p: string) => vol.lstatSync(p),
      mkdir: async (p: string, opts?: any) => vol.mkdirSync(p, opts),
      readdir: async (p: string, opts?: any) => vol.readdirSync(p, opts),
      readFile: mock(async () => {
        throw new Error("EACCES: permission denied");
      }),
      writeFile: async (p: string, data: any) => vol.writeFileSync(p, data),
    }));

    const { append } = await import("../tools/skill-authoring.ts");
    const result = await append.execute(
      { name: "exists", scope: "global", addition: "new content" },
      ctxWithWorktree,
    );
    expect(result).toBe("Failed to read skill: EACCES: permission denied");
  });

  test("returns error when writeFile throws", async () => {
    vol.mkdirSync(path.join(globalBase, "writable"), { recursive: true });
    vol.writeFileSync(
      path.join(globalBase, "writable", "SKILL.md"),
      "original",
    );

    mock.module("node:fs/promises", () => ({
      lstat: async (p: string) => vol.lstatSync(p),
      mkdir: async (p: string, opts?: any) => vol.mkdirSync(p, opts),
      readdir: async (p: string, opts?: any) => vol.readdirSync(p, opts),
      readFile: async (p: string, opts?: any) => vol.readFileSync(p, opts),
      writeFile: mock(async () => {
        throw new Error("writeFile failed");
      }),
    }));

    const { append } = await import("../tools/skill-authoring.ts");
    const result = await append.execute(
      { name: "writable", scope: "global", addition: "new content" },
      ctxWithWorktree,
    );
    expect(result).toBe("Failed to write skill: writeFile failed");
  });

  test("successfully patches skill and returns message", async () => {
    vol.mkdirSync(path.join(globalBase, "my-skill"), { recursive: true });
    vol.writeFileSync(
      path.join(globalBase, "my-skill", "SKILL.md"),
      "# Original content",
    );

    const { append } = await import("../tools/skill-authoring.ts");
    const result = await append.execute(
      {
        name: "my-skill",
        scope: "global",
        addition: "## New Section\n\nAdded content",
      },
      ctxWithWorktree,
    );

    expect(result).toContain("Appended to skill:");
    expect(result).toContain(path.join(globalBase, "my-skill", "SKILL.md"));

    // Verify content was appended
    const newContent = vol.readFileSync(
      path.join(globalBase, "my-skill", "SKILL.md"),
      "utf-8",
    );
    expect(newContent).toBe(
      "# Original content\n\n## New Section\n\nAdded content",
    );
  });

  test("uses global path when scope is 'global'", async () => {
    vol.mkdirSync(path.join(globalBase, "global-patch"), { recursive: true });
    vol.writeFileSync(
      path.join(globalBase, "global-patch", "SKILL.md"),
      "original",
    );

    const { append } = await import("../tools/skill-authoring.ts");
    const result = await append.execute(
      { name: "global-patch", scope: "global", addition: "added" },
      ctxWithWorktree,
    );

    expect(result).toContain(
      "/home/testuser/.config/opencode/skills/global-patch/SKILL.md",
    );
  });

  test("uses project path when scope is 'project'", async () => {
    vol.mkdirSync("/test/project/.opencode/skills/project-patch", {
      recursive: true,
    });
    vol.writeFileSync(
      "/test/project/.opencode/skills/project-patch/SKILL.md",
      "original",
    );

    const { append } = await import("../tools/skill-authoring.ts");
    const result = await append.execute(
      { name: "project-patch", scope: "project", addition: "added" },
      ctxWithWorktree,
    );

    expect(result).toContain(
      "/test/project/.opencode/skills/project-patch/SKILL.md",
    );
  });

  test("falls back to directory when worktree is undefined", async () => {
    vol.mkdirSync("/test/project/.opencode/skills/fallback-patch", {
      recursive: true,
    });
    vol.writeFileSync(
      "/test/project/.opencode/skills/fallback-patch/SKILL.md",
      "original",
    );

    const { append } = await import("../tools/skill-authoring.ts");
    const result = await append.execute(
      { name: "fallback-patch", scope: "project", addition: "added" },
      ctxNoWorktree,
    );

    expect(result).toContain(
      "/test/project/.opencode/skills/fallback-patch/SKILL.md",
    );
  });

  test("appends with proper separator (blank line)", async () => {
    vol.mkdirSync(path.join(globalBase, "sep-test"), { recursive: true });
    vol.writeFileSync(
      path.join(globalBase, "sep-test", "SKILL.md"),
      "Line 1\nLine 2",
    );

    const { append } = await import("../tools/skill-authoring.ts");
    await append.execute(
      { name: "sep-test", scope: "global", addition: "Line 3" },
      ctxWithWorktree,
    );

    const newContent = vol.readFileSync(
      path.join(globalBase, "sep-test", "SKILL.md"),
      "utf-8",
    );
    expect(newContent).toBe("Line 1\nLine 2\n\nLine 3");
  });
});