Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(desktop): exclude dot-directories from skill file walks (#83471)

Phil Haack2661da0a468e
diff --git a/products/desktop/apps/web/src/web-skill-bundler.ts b/products/desktop/apps/web/src/web-skill-bundler.ts
index cab9ff97037f..e34976e41dca 100644
--- a/products/desktop/apps/web/src/web-skill-bundler.ts
+++ b/products/desktop/apps/web/src/web-skill-bundler.ts
@@ -1,6 +1,7 @@
import type { LocalSkillBundle } from "@posthog/core/sessions/cloudArtifactIdentifiers";
import {
type ExportedSkill,
+ isIgnoredSkillPath,
serializeSkillMarkdown,
type UploadableSkillSource,
} from "@posthog/shared";
@@ -14,12 +15,6 @@ import { strToU8, zipSync } from "fflate";
// reconstructed via the shared serializeSkillMarkdown so it matches desktop.
const SKILL_BUNDLE_MAX_BYTES = 30 * 1024 * 1024;
-const IGNORED_ENTRIES = new Set([
- ".DS_Store",
- ".git",
- "node_modules",
- "__pycache__",
-]);
const CHUNK_SIZE = 8192;
function bytesToBase64(bytes: Uint8Array): string {
@@ -61,8 +56,7 @@ export async function bundleExportedSkill(
);
for (const file of exported.files) {
const normalized = file.path.replaceAll("\\", "/");
- const base = normalized.split("/").pop() ?? "";
- if (!base || IGNORED_ENTRIES.has(base)) continue;
+ if (isIgnoredSkillPath(normalized)) continue;
if (normalized === "SKILL.md") continue; // body is the source of truth
files[normalized] = strToU8(file.content);
}
diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.ts
index 4753551fd1ab..c5284f79694d 100644
--- a/products/desktop/packages/agent/src/server/agent-server.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.ts
@@ -21,6 +21,7 @@ import {
type Adapter,
buildPrOutput,
getErrorMessage,
+ isIgnoredSkillPath,
type McpServerConnection,
mergePrUrls,
parseMcpToolName,
@@ -3284,6 +3285,12 @@ export class AgentServer {
) {
continue;
}
+ // Bundles from clients that predate export-side filtering can still
+ // carry ignored entries; drop them so the sandbox skill matches what
+ // current clients would have uploaded.
+ if (isIgnoredSkillPath(normalizedEntryName)) {
+ continue;
+ }
const destinationPath = join(destinationRoot, normalizedEntryName);
const relativeDestination = relative(destinationRoot, destinationPath);
diff --git a/products/desktop/packages/core/src/skills/teamSkillsService.test.ts b/products/desktop/packages/core/src/skills/teamSkillsService.test.ts
index 66348c395fad..05cca7102dd0 100644
--- a/products/desktop/packages/core/src/skills/teamSkillsService.test.ts
+++ b/products/desktop/packages/core/src/skills/teamSkillsService.test.ts
@@ -229,7 +229,7 @@ describe("TeamSkillsService.publishSkill", () => {
});
describe("TeamSkillsService.fetchSkillForInstall", () => {
- it("fetches the body plus every companion file", async () => {
+ it("fetches the body plus every companion file, skipping ignored paths", async () => {
const client = {
getLlmSkillByName: vi.fn().mockResolvedValue({
name: "pr-shepherd",
@@ -238,6 +238,7 @@ describe("TeamSkillsService.fetchSkillForInstall", () => {
files: [
{ path: "references/guide.md", content_type: "text/plain" },
{ path: "scripts/run.sh", content_type: "text/plain" },
+ { path: ".venv/lib/mod.py", content_type: "text/plain" },
],
}),
getLlmSkillFile: vi
@@ -266,6 +267,7 @@ describe("TeamSkillsService.fetchSkillForInstall", () => {
{ path: "scripts/run.sh", content: "content of scripts/run.sh" },
],
});
+ expect(client.getLlmSkillFile).toHaveBeenCalledTimes(2);
});
it("maps disable-model-invocation metadata onto the exported skill", async () => {
diff --git a/products/desktop/packages/core/src/skills/teamSkillsService.ts b/products/desktop/packages/core/src/skills/teamSkillsService.ts
index 69f2152267ec..20ac3d288806 100644
--- a/products/desktop/packages/core/src/skills/teamSkillsService.ts
+++ b/products/desktop/packages/core/src/skills/teamSkillsService.ts
@@ -5,6 +5,7 @@ import type {
import {
DISABLE_MODEL_INVOCATION_METADATA_KEY,
type ExportedSkill,
+ isIgnoredSkillPath,
} from "@posthog/shared";
import { inject, injectable } from "inversify";
import { SKILLS_WORKSPACE_CLIENT } from "./identifiers";
@@ -158,11 +159,15 @@ export class TeamSkillsService {
name: string,
): Promise<ExportedSkill> {
const detail = await client.getLlmSkillByName(name);
+ // Ignored entries in legacy-published skills are dropped downstream
+ // anyway; skipping the fetch avoids one request per junk file.
const files = await Promise.all(
- detail.files.map(async (manifest) => {
- const file = await client.getLlmSkillFile(name, manifest.path);
- return { path: file.path, content: file.content };
- }),
+ detail.files
+ .filter((manifest) => !isIgnoredSkillPath(manifest.path))
+ .map(async (manifest) => {
+ const file = await client.getLlmSkillFile(name, manifest.path);
+ return { path: file.path, content: file.content };
+ }),
);
return {
name: detail.name,
diff --git a/products/desktop/packages/shared/src/index.ts b/products/desktop/packages/shared/src/index.ts
index fbf7a1cfbbea..22b4b507a1d9 100644
--- a/products/desktop/packages/shared/src/index.ts
+++ b/products/desktop/packages/shared/src/index.ts
@@ -338,6 +338,8 @@ export type {
} from "./skills";
export {
DISABLE_MODEL_INVOCATION_METADATA_KEY,
+ isIgnoredSkillEntry,
+ isIgnoredSkillPath,
SKILL_EXISTS_MARKER,
serializeSkillMarkdown,
stripFrontmatter,
diff --git a/products/desktop/packages/shared/src/skills.test.ts b/products/desktop/packages/shared/src/skills.test.ts
new file mode 100644
index 000000000000..36e14d15e81e
--- /dev/null
+++ b/products/desktop/packages/shared/src/skills.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it } from "vitest";
+import { isIgnoredSkillEntry, isIgnoredSkillPath } from "./skills";
+
+describe("isIgnoredSkillEntry", () => {
+ it.each([
+ [".venv", "directory", true],
+ [".worktrees", "directory", true],
+ [".git", "directory", true],
+ [".git", "file", true],
+ [".DS_Store", "file", true],
+ ["node_modules", "directory", true],
+ ["__pycache__", "directory", true],
+ [".gitignore", "file", false],
+ [".env.example", "file", false],
+ ["references", "directory", false],
+ ["SKILL.md", "file", false],
+ ] as const)("isIgnoredSkillEntry(%j, %j) === %s", (name, kind, expected) => {
+ expect(isIgnoredSkillEntry(name, kind)).toBe(expected);
+ });
+});
+
+describe("isIgnoredSkillPath", () => {
+ it.each([
+ ["foo/.venv/x.py", true],
+ [".worktrees/a/b", true],
+ ["node_modules/pkg/index.js", true],
+ ["a/.DS_Store", true],
+ [".gitignore", false],
+ ["docs/.hidden.md", false],
+ ["docs/guide.md", false],
+ ["foo/", true],
+ ["", true],
+ ["../escape.md", true],
+ ["foo/..", true],
+ ["a//b.md", true],
+ ["/etc/evil.md", true],
+ // A backslash is an ordinary character here, not a separator: this is
+ // one literal filename with no "/" in it, so it is kept.
+ [".venv\\lib\\mod.py", false],
+ ] as const)("isIgnoredSkillPath(%j) === %s", (relativePath, expected) => {
+ expect(isIgnoredSkillPath(relativePath)).toBe(expected);
+ });
+});
diff --git a/products/desktop/packages/shared/src/skills.ts b/products/desktop/packages/shared/src/skills.ts
index 9932101128ef..dbaf2554ca8d 100644
--- a/products/desktop/packages/shared/src/skills.ts
+++ b/products/desktop/packages/shared/src/skills.ts
@@ -98,3 +98,50 @@ export function stripFrontmatter(content: string): string {
if (!match) return content;
return content.slice(match[0].length).replace(/^(?:[ \t]*\r?\n)+/, "");
}
+
+const IGNORED_SKILL_ENTRIES: ReadonlySet<string> = new Set([
+ ".DS_Store",
+ ".git",
+ "node_modules",
+ "__pycache__",
+]);
+
+/**
+ * Whether a skill directory entry is excluded from skill walks. Lives here
+ * (shared) so the file tree, team export, and cloud bundlers all agree on a
+ * skill's contents. Dot-directories are never skill content: skill-private
+ * state like a `.worktrees` or `.venv` would otherwise count toward the
+ * bundle file limit and upload with the skill. Dot-files such as `.gitignore`
+ * are legitimate assets and stay. The literal set covers junk that is not
+ * dot-named, plus `.git` when it is a worktree pointer file.
+ */
+export function isIgnoredSkillEntry(
+ name: string,
+ kind: "file" | "directory",
+): boolean {
+ if (IGNORED_SKILL_ENTRIES.has(name)) return true;
+ return kind === "directory" && name.startsWith(".");
+}
+
+/**
+ * Path form of `isIgnoredSkillEntry` for callers holding "/"-separated
+ * relative paths instead of walking a directory (the web bundler's
+ * API-supplied file lists, per `ExportedSkillFile`'s "using '/' separators"
+ * contract): every non-final segment is a directory and the final segment is
+ * the file. A backslash is an ordinary character, never a separator — this
+ * function is host-neutral and cannot assume a platform's path semantics, so
+ * a caller with a raw OS-native path decides for itself whether a backslash
+ * should be normalized or rejected. Empty segments (which cover "", trailing
+ * slashes, and absolute or doubled-slash paths) and `.`/`..` segments are
+ * rejected too, which hardens against hostile API-supplied paths.
+ */
+export function isIgnoredSkillPath(relativePath: string): boolean {
+ const segments = relativePath.split("/");
+ return segments.some((segment, index) => {
+ if (!segment || segment === "." || segment === "..") return true;
+ return isIgnoredSkillEntry(
+ segment,
+ index === segments.length - 1 ? "file" : "directory",
+ );
+ });
+}
diff --git a/products/desktop/packages/workspace-server/src/services/skills-marketplace/skills-marketplace.test.ts b/products/desktop/packages/workspace-server/src/services/skills-marketplace/skills-marketplace.test.ts
index 0f829334b9bc..a8ddc62ef30c 100644
--- a/products/desktop/packages/workspace-server/src/services/skills-marketplace/skills-marketplace.test.ts
+++ b/products/desktop/packages/workspace-server/src/services/skills-marketplace/skills-marketplace.test.ts
@@ -80,13 +80,15 @@ describe("findSkillDirPrefix", () => {
});
describe("collectSkillFiles", () => {
- it("drops entries that would escape the install directory", () => {
+ it("drops entries that would escape the install directory or are ignored", () => {
const prefix = "repo-HEAD/skills/commit/";
const entries = {
[`${prefix}SKILL.md`]: strToU8("ok"),
[`${prefix}../evil.md`]: strToU8("bad"),
[`${prefix}nested/../../evil2.md`]: strToU8("bad"),
[`${prefix}back\\slash.md`]: strToU8("bad"),
+ [`${prefix}.venv/lib/mod.py`]: strToU8("junk"),
+ [`${prefix}node_modules/pkg/i.js`]: strToU8("junk"),
};
const files = collectSkillFiles(entries, prefix);
diff --git a/products/desktop/packages/workspace-server/src/services/skills-marketplace/skills-marketplace.ts b/products/desktop/packages/workspace-server/src/services/skills-marketplace/skills-marketplace.ts
index ca17b6bd1c1c..8ddcd98be29c 100644
--- a/products/desktop/packages/workspace-server/src/services/skills-marketplace/skills-marketplace.ts
+++ b/products/desktop/packages/workspace-server/src/services/skills-marketplace/skills-marketplace.ts
@@ -1,6 +1,6 @@
import * as fs from "node:fs";
import * as path from "node:path";
-import { SKILL_EXISTS_MARKER } from "@posthog/shared";
+import { isIgnoredSkillPath, SKILL_EXISTS_MARKER } from "@posthog/shared";
import type { Unzipped } from "fflate";
import { injectable } from "inversify";
import { unzipAsync } from "../posthog-plugin/extract-zip";
@@ -98,7 +98,7 @@ export function collectSkillFiles(
for (const [key, bytes] of Object.entries(entries)) {
if (!key.startsWith(prefix) || key.endsWith("/")) continue;
const relPath = key.slice(prefix.length);
- if (!isSafeRelativePath(relPath)) continue;
+ if (!isSafeRelativePath(relPath) || isIgnoredSkillPath(relPath)) continue;
files.set(relPath, bytes);
}
return files;
diff --git a/products/desktop/packages/workspace-server/src/services/skills/skill-bundler.test.ts b/products/desktop/packages/workspace-server/src/services/skills/skill-bundler.test.ts
new file mode 100644
index 000000000000..79ac584014bd
--- /dev/null
+++ b/products/desktop/packages/workspace-server/src/services/skills/skill-bundler.test.ts
@@ -0,0 +1,91 @@
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { unzipSync } from "fflate";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { bundleLocalSkill, countFilesByTopLevelDir } from "./skill-bundler";
+
+let root: string;
+
+beforeEach(async () => {
+ root = await mkdtemp(path.join(tmpdir(), "skill-bundler-test-"));
+});
+
+afterEach(async () => {
+ await rm(root, { recursive: true, force: true });
+});
+
+describe("bundleLocalSkill", () => {
+ it("bundles dot-files but not ignored directories", async () => {
+ const skillPath = path.join(root, "my-skill");
+ await mkdir(path.join(skillPath, "references"), { recursive: true });
+ await mkdir(path.join(skillPath, ".venv", "lib"), { recursive: true });
+ await writeFile(path.join(skillPath, "SKILL.md"), "# my-skill");
+ await writeFile(path.join(skillPath, ".gitignore"), "junk");
+ await writeFile(path.join(skillPath, "..lock.md"), "dots");
+ await writeFile(path.join(skillPath, "references", "x.md"), "x");
+ await writeFile(path.join(skillPath, ".venv", "lib", "mod.py"), "m");
+
+ const bundle = await bundleLocalSkill({
+ name: "my-skill",
+ source: "user",
+ skillPath,
+ });
+
+ const zipped = unzipSync(
+ new Uint8Array(Buffer.from(bundle.contentBase64, "base64")),
+ );
+ expect(Object.keys(zipped).sort()).toEqual([
+ "..lock.md",
+ ".gitignore",
+ "SKILL.md",
+ "posthog-skill-bundle.json",
+ "references/x.md",
+ ]);
+ });
+
+ it("names the largest folders with full counts when the file cap is exceeded", async () => {
+ const skillPath = path.join(root, "big-skill");
+ await mkdir(path.join(skillPath, "aaa"), { recursive: true });
+ await mkdir(path.join(skillPath, "zzz"), { recursive: true });
+ await writeFile(path.join(skillPath, "SKILL.md"), "# big-skill");
+ await Promise.all(
+ Array.from({ length: 600 }, (_, i) =>
+ writeFile(path.join(skillPath, "aaa", `f${i}.txt`), "x"),
+ ),
+ );
+ await Promise.all(
+ Array.from({ length: 600 }, (_, i) =>
+ writeFile(path.join(skillPath, "zzz", `f${i}.txt`), "x"),
+ ),
+ );
+
+ // The collection walk stops at the cap, so only a full recount can
+ // attribute 600 files to whichever folder was walked second.
+ const failure = bundleLocalSkill({
+ name: "big-skill",
+ source: "user",
+ skillPath,
+ });
+ await expect(failure).rejects.toThrow(/more than 1000 files\./);
+ await expect(failure).rejects.toThrow(/aaa \(600 files\)/);
+ await expect(failure).rejects.toThrow(/zzz \(600 files\)/);
+ });
+});
+
+describe("countFilesByTopLevelDir", () => {
+ it("stops once the entry budget is spent instead of walking the whole tree", async () => {
+ const skillPath = path.join(root, "huge-skill");
+ await mkdir(path.join(skillPath, "aaa"), { recursive: true });
+ await Promise.all(
+ Array.from({ length: 20 }, (_, i) =>
+ writeFile(path.join(skillPath, "aaa", `f${i}.txt`), "x"),
+ ),
+ );
+
+ const counts = await countFilesByTopLevelDir(skillPath, 5);
+
+ const totalCounted = [...counts.values()].reduce((a, b) => a + b, 0);
+ expect(totalCounted).toBeLessThan(20);
+ });
+});
diff --git a/products/desktop/packages/workspace-server/src/services/skills/skill-bundler.ts b/products/desktop/packages/workspace-server/src/services/skills/skill-bundler.ts
index 0d674c12de2e..228b35a029f1 100644
--- a/products/desktop/packages/workspace-server/src/services/skills/skill-bundler.ts
+++ b/products/desktop/packages/workspace-server/src/services/skills/skill-bundler.ts
@@ -1,17 +1,12 @@
import * as crypto from "node:crypto";
import * as fs from "node:fs";
import * as path from "node:path";
+import { isIgnoredSkillEntry } from "@posthog/shared";
import { strToU8, zipSync } from "fflate";
import type { BundleLocalSkillOutput, UploadableSkillSource } from "./schemas";
const SKILL_BUNDLE_MAX_BYTES = 30 * 1024 * 1024;
const SKILL_BUNDLE_MAX_FILES = 1000;
-const IGNORED_ENTRIES = new Set([
- ".DS_Store",
- ".git",
- "node_modules",
- "__pycache__",
-]);
function toZipPath(filePath: string): string {
return filePath.split(path.sep).join("/");
@@ -59,6 +54,68 @@ interface SkillFileAccumulator {
totalBytes: number;
}
+class SkillBundleFileLimitError extends Error {}
+
+/**
+ * Generous relative to SKILL_BUNDLE_MAX_FILES so real "too many files"
+ * skills still get an exact count; bounds the recount below so a
+ * pathologically large committed tree can't turn the error path into
+ * unbounded I/O.
+ */
+const MAX_COUNT_WALK_ENTRIES = SKILL_BUNDLE_MAX_FILES * 50;
+
+/**
+ * Counts every non-ignored file per top-level folder. The collection walk
+ * stops at the file cap, so counts derived from it reflect readdir order and
+ * could name a minor folder while omitting the real offender; this walk runs
+ * only when the cap has tripped and reads no file contents. Stops once
+ * `maxEntries` directory entries have been visited, so an oversized tree
+ * still terminates promptly.
+ */
+export async function countFilesByTopLevelDir(
+ root: string,
+ maxEntries = MAX_COUNT_WALK_ENTRIES,
+): Promise<Map<string, number>> {
+ const counts = new Map<string, number>();
+ let visited = 0;
+ const walk = async (dir: string, topLevel: string | null): Promise<void> => {
+ if (visited >= maxEntries) return;
+ const entries = await fs.promises.readdir(dir, { withFileTypes: true });
+ for (const entry of entries) {
+ if (visited >= maxEntries) return;
+ visited++;
+ if (
+ isIgnoredSkillEntry(
+ entry.name,
+ entry.isDirectory() ? "directory" : "file",
+ )
+ ) {
+ continue;
+ }
+ if (entry.isDirectory()) {
+ await walk(path.join(dir, entry.name), topLevel ?? entry.name);
+ } else if (topLevel && (entry.isFile() || entry.isSymbolicLink())) {
+ counts.set(topLevel, (counts.get(topLevel) ?? 0) + 1);
+ }
+ }
+ };
+ await walk(root, null);
+ return counts;
+}
+
+async function tooManyFilesMessage(root: string): Promise<string> {
+ const counts = await countFilesByTopLevelDir(root).catch(
+ () => new Map<string, number>(),
+ );
+ const largest = [...counts.entries()]
+ .sort((a, b) => b[1] - a[1])
+ .slice(0, 3)
+ .map(([name, count]) => `${name} (${count} files)`)
+ .join(", ");
+ const hint = largest ? ` Largest folders: ${largest}.` : "";
+ return `Local skill bundle contains more than ${SKILL_BUNDLE_MAX_FILES} files.${hint} Remove or move files that are not part of the skill.`;
+}
+
async function addSkillFile(
acc: SkillFileAccumulator,
relativePath: string,
@@ -66,9 +123,7 @@ async function addSkillFile(
size: number,
): Promise<void> {
if (Object.keys(acc.files).length >= SKILL_BUNDLE_MAX_FILES) {
- throw new Error(
- `Local skill bundle contains more than ${SKILL_BUNDLE_MAX_FILES} files`,
- );
+ throw new SkillBundleFileLimitError();
}
if (acc.totalBytes + size > SKILL_BUNDLE_MAX_BYTES) {
throw new Error("Local skill bundle exceeds the 30MB cloud run limit");
@@ -88,7 +143,12 @@ async function collectSkillFiles(
});
for (const entry of entries) {
- if (IGNORED_ENTRIES.has(entry.name)) {
+ if (
+ isIgnoredSkillEntry(
+ entry.name,
+ entry.isDirectory() ? "directory" : "file",
+ )
+ ) {
continue;
}
@@ -96,7 +156,8 @@ async function collectSkillFiles(
const relativePath = path.relative(root, absolutePath);
if (
!relativePath ||
- relativePath.startsWith("..") ||
+ relativePath === ".." ||
+ relativePath.startsWith(`..${path.sep}`) ||
path.isAbsolute(relativePath)
) {
continue;
@@ -144,7 +205,14 @@ export async function bundleLocalSkill({
}): Promise<BundleLocalSkillOutput> {
const root = await assertSkillRoot(skillPath, allowRootSymlink);
const acc: SkillFileAccumulator = { files: {}, totalBytes: 0 };
- await collectSkillFiles(root, root, acc);
+ try {
+ await collectSkillFiles(root, root, acc);
+ } catch (error) {
+ if (error instanceof SkillBundleFileLimitError) {
+ throw new Error(await tooManyFilesMessage(root));
+ }
+ throw error;
+ }
const files = acc.files;
const fileNames = Object.keys(files).sort();
diff --git a/products/desktop/packages/workspace-server/src/services/skills/skill-discovery.test.ts b/products/desktop/packages/workspace-server/src/services/skills/skill-discovery.test.ts
index 944ae0959f63..cf111189f774 100644
--- a/products/desktop/packages/workspace-server/src/services/skills/skill-discovery.test.ts
+++ b/products/desktop/packages/workspace-server/src/services/skills/skill-discovery.test.ts
@@ -140,6 +140,25 @@ describe("listSkillFiles", () => {
expect(files.map((f) => f.path)).toEqual(["SKILL.md"]);
});
+ it("excludes ignored directories but keeps dot-files", async () => {
+ const skillsDir = path.join(root, "skills");
+ await createSkill(skillsDir, "alpha");
+ const skillPath = path.join(skillsDir, "alpha");
+ await mkdir(path.join(skillPath, "references"), { recursive: true });
+ await mkdir(path.join(skillPath, ".venv", "lib"), { recursive: true });
+ await writeFile(path.join(skillPath, ".gitignore"), "junk");
+ await writeFile(path.join(skillPath, "references", "x.md"), "x");
+ await writeFile(path.join(skillPath, ".venv", "lib", "mod.py"), "m");
+
+ const files = await listSkillFiles(skillPath, 500);
+
+ expect(files.map((f) => f.path)).toEqual([
+ "SKILL.md",
+ ".gitignore",
+ "references/x.md",
+ ]);
+ });
+
it("stops at the file cap", async () => {
const skillsDir = path.join(root, "skills");
await createSkill(skillsDir, "alpha");
diff --git a/products/desktop/packages/workspace-server/src/services/skills/skill-discovery.ts b/products/desktop/packages/workspace-server/src/services/skills/skill-discovery.ts
index 72ea3fcd95a2..757de3705aef 100644
--- a/products/desktop/packages/workspace-server/src/services/skills/skill-discovery.ts
+++ b/products/desktop/packages/workspace-server/src/services/skills/skill-discovery.ts
@@ -1,6 +1,7 @@
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
+import { isIgnoredSkillEntry } from "@posthog/shared";
import { parseSkillFrontmatter } from "./parse-skill-frontmatter";
import type { SkillFileEntry, SkillInfo, SkillSource } from "./schemas";
@@ -136,6 +137,8 @@ export async function getMarketplaceInstallPaths(): Promise<string[]> {
/**
* Recursively lists regular files inside a skill directory. Symlinks are
* skipped so a crafted skill cannot expose files outside its directory.
+ * Ignored entries (dot-directories and junk like node_modules) are excluded,
+ * applying the same ignore rule as the bundlers.
*/
export async function listSkillFiles(
skillDir: string,
@@ -147,6 +150,14 @@ export async function listSkillFiles(
const entries = await fs.promises.readdir(dir, { withFileTypes: true });
for (const entry of entries) {
if (files.length >= maxFiles) return;
+ if (
+ isIgnoredSkillEntry(
+ entry.name,
+ entry.isDirectory() ? "directory" : "file",
+ )
+ ) {
+ continue;
+ }
const relPath = prefix ? `${prefix}/${entry.name}` : entry.name;
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
diff --git a/products/desktop/packages/workspace-server/src/services/skills/skills.test.ts b/products/desktop/packages/workspace-server/src/services/skills/skills.test.ts
index fb71744234b4..69492a19a9ac 100644
--- a/products/desktop/packages/workspace-server/src/services/skills/skills.test.ts
+++ b/products/desktop/packages/workspace-server/src/services/skills/skills.test.ts
@@ -1,4 +1,4 @@
-import { existsSync } from "node:fs";
+import { existsSync, readdirSync } from "node:fs";
import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
@@ -363,6 +363,31 @@ describe("installTeamSkill", () => {
expect(guide).toBe("guide");
});
+ it("drops ignored paths from the payload instead of installing them", async () => {
+ const service = makeService();
+ const { path: target } = await service.installTeamSkill({
+ ...input,
+ name: "junk-team-skill",
+ files: [
+ { path: "references/guide.md", content: "guide" },
+ { path: "node_modules/pkg/i.js", content: "junk" },
+ { path: ".venv/lib/mod.py", content: "junk" },
+ { path: "SKILL.md", content: "HIJACKED" },
+ { path: "skill.md", content: "HIJACKED" },
+ ],
+ });
+
+ expect(existsSync(path.join(target, "references/guide.md"))).toBe(true);
+ expect(existsSync(path.join(target, "node_modules"))).toBe(false);
+ expect(existsSync(path.join(target, ".venv"))).toBe(false);
+ // On a case-insensitive filesystem "skill.md" would clobber the manifest
+ // content; on a case-sensitive one it would land as a separate file.
+ expect(readdirSync(target)).not.toContain("skill.md");
+ const manifest = await service.readSkillFile(target, "SKILL.md");
+ expect(manifest).toContain("From the team");
+ expect(manifest).not.toContain("HIJACKED");
+ });
+
it("writes disable-model-invocation back into the frontmatter", async () => {
const service = makeService();
const { path: target } = await service.installTeamSkill({
@@ -701,6 +726,30 @@ describe("write-path guard", () => {
makeService().saveSkillFile(skillPath, "../beta.md", "x"),
).rejects.toThrow("path outside skill directory");
});
+
+ it("rejects a path containing a backslash instead of writing it verbatim", async () => {
+ const skillPath = await createSkill(repoSkillsDir, "alpha");
+
+ // A local write must not create a filename the cloud sandbox's "\" to
+ // "/" extraction normalization would silently reinterpret as nested.
+ await expect(
+ makeService().saveSkillFile(skillPath, "references\\guide.md", "x"),
+ ).rejects.toThrow("cannot contain a backslash");
+ });
+
+ it("rejects write destinations the file tree would not show", async () => {
+ const skillPath = await createSkill(repoSkillsDir, "alpha");
+ const service = makeService();
+
+ await expect(
+ service.saveSkillFile(skillPath, ".venv/notes.md", "x"),
+ ).rejects.toThrow("excluded from skills");
+
+ await service.saveSkillFile(skillPath, "references/guide.md", "guide");
+ await expect(
+ service.renameSkillFile(skillPath, "references/guide.md", ".cache/g.md"),
+ ).rejects.toThrow("excluded from skills");
+ });
});
describe("skill mutations", () => {
diff --git a/products/desktop/packages/workspace-server/src/services/skills/skills.ts b/products/desktop/packages/workspace-server/src/services/skills/skills.ts
index 741908b75739..075d9a281654 100644
--- a/products/desktop/packages/workspace-server/src/services/skills/skills.ts
+++ b/products/desktop/packages/workspace-server/src/services/skills/skills.ts
@@ -1,6 +1,10 @@
import * as fs from "node:fs";
import * as path from "node:path";
-import { SKILL_EXISTS_MARKER, stripFrontmatter } from "@posthog/shared";
+import {
+ isIgnoredSkillPath,
+ SKILL_EXISTS_MARKER,
+ stripFrontmatter,
+} from "@posthog/shared";
import { inject, injectable } from "inversify";
import { WATCHER_SERVICE } from "../../di/tokens";
import type { FoldersService } from "../folders/folders";
@@ -167,6 +171,7 @@ export class SkillsService {
): Promise<void> {
const skillDir = await this.resolveWritableSkillDir(skillPath);
const target = resolveSkillFilePath(skillDir, filePath);
+ assertVisibleSkillFilePath(filePath);
await fs.promises.mkdir(path.dirname(target), { recursive: true });
await fs.promises.writeFile(target, content, "utf-8");
}
@@ -179,6 +184,9 @@ export class SkillsService {
const skillDir = await this.resolveWritableSkillDir(skillPath);
const from = resolveSkillFilePath(skillDir, fromPath);
const to = resolveSkillFilePath(skillDir, toPath);
+ // Only the destination is checked: renaming a file OUT of an ignored
+ // directory is the way to rescue one that is invisible in the file tree.
+ assertVisibleSkillFilePath(toPath);
if (from === path.join(skillDir, "SKILL.md")) {
throw new Error("SKILL.md cannot be renamed");
}
@@ -326,7 +334,15 @@ export class SkillsService {
);
await Promise.all(
input.files.map(async (file) => {
+ // Resolve first so a traversal path still fails the install loudly.
const filePath = resolveSkillFilePath(staging, file.path);
+ // The body is the source of truth for SKILL.md; the lowercase
+ // compare stops a case-variant from clobbering it on APFS.
+ if (file.path.toLowerCase() === "skill.md") return;
+ // Skills published before ignored entries were filtered at export
+ // can still carry junk; drop it at install so the directory matches
+ // what the file tree and bundlers report.
+ if (isIgnoredSkillPath(file.path)) return;
await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
await fs.promises.writeFile(filePath, file.content, "utf-8");
}),
@@ -760,9 +776,30 @@ function delay(ms: number, signal?: AbortSignal): Promise<void> {
}
function resolveSkillFilePath(skillDir: string, filePath: string): string {
+ // Skill-relative paths are always "/"-separated (see SkillFileEntry). A
+ // literal backslash on POSIX would sit inside one path.resolve segment
+ // here, but the cloud sandbox's extractor normalizes "\" to "/" on unzip,
+ // so such a file would reappear nested on extraction and could silently
+ // collide with (and overwrite) an unrelated file at that path.
+ if (filePath.includes("\\")) {
+ throw new Error("File and folder names cannot contain a backslash.");
+ }
const resolved = path.resolve(skillDir, filePath);
if (resolved === skillDir || !resolved.startsWith(skillDir + path.sep)) {
throw new Error("Access denied: path outside skill directory");
}
return resolved;
}
+
+/**
+ * Rejects write destinations the file tree would never show; without this a
+ * user-created file lands on disk but cannot be seen, renamed, or deleted
+ * through the UI, and is silently left out of publish and cloud bundles.
+ */
+function assertVisibleSkillFilePath(filePath: string): void {
+ if (isIgnoredSkillPath(filePath)) {
+ throw new Error(
+ 'Folders starting with "." and folders like node_modules are excluded from skills. Choose a different location.',
+ );
+ }
+}