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.

feat(desktop): use checkout skills in local desktop and cloud tasks (#96381)

Peter Kirkhamed461543e7bd
diff --git a/bin/start-desktop b/bin/start-desktop
index c09b36446beb..d682a3ca29bc 100755
--- a/bin/start-desktop
+++ b/bin/start-desktop
@@ -1,8 +1,15 @@
#!/usr/bin/env bash
set -euo pipefail
-cd "$(dirname "$0")/../products/desktop"
+cd "$(dirname "$0")/.."
+
+export POSTHOG_DESKTOP_SKILLS="${POSTHOG_DESKTOP_SKILLS:-local}"
+if [[ "$POSTHOG_DESKTOP_SKILLS" == "local" ]]; then
+ bin/wait-for-postgres-tables posthog_team posthog_project posthog_instancesetting
+fi
+
+cd products/desktop
pnpm install --frozen-lockfile
-exec pnpm exec turbo dev --filter=@posthog/code --filter=@posthog/agent --filter=@posthog/git --filter=@posthog/platform --filter=@posthog/enricher
+exec node scripts/dev-with-skills.mjs pnpm exec turbo dev --filter=@posthog/code --filter=@posthog/agent --filter=@posthog/git --filter=@posthog/platform --filter=@posthog/enricher
diff --git a/products/desktop/.gitignore b/products/desktop/.gitignore
index 094b915434ee..e111d90241c3 100644
--- a/products/desktop/.gitignore
+++ b/products/desktop/.gitignore
@@ -72,6 +72,9 @@ apps/code/assets/fonts/BerkeleyMono/
# Local dev skills (override shipped + remote skills in dev mode)
plugins/posthog/local-skills/
+plugins/posthog/checkout-skills/
+plugins/posthog/checkout-skills.staging-*/
+plugins/posthog/checkout-skills.ready
.claude/settings.local.json
diff --git a/products/desktop/apps/code/vite-main-plugins.mts b/products/desktop/apps/code/vite-main-plugins.mts
index 0b297db78be4..9023ba54c110 100644
--- a/products/desktop/apps/code/vite-main-plugins.mts
+++ b/products/desktop/apps/code/vite-main-plugins.mts
@@ -491,18 +491,26 @@ let remoteSkillsFetched = false;
export function copyPosthogPlugin(isDev: boolean): Plugin {
const sourceDir = join(__dirname, "../../plugins/posthog");
const localSkillsDir = join(sourceDir, "local-skills");
+ const checkoutSkillsDir = join(sourceDir, "checkout-skills");
+ const useCheckoutSkills =
+ isDev && process.env.POSTHOG_DESKTOP_SKILLS === "local";
return {
name: "copy-posthog-plugin",
buildStart() {
if (existsSync(sourceDir)) {
for (const file of getFilesRecursive(sourceDir)) {
+ if (file.startsWith(checkoutSkillsDir)) continue;
// Don't watch local-skills in production builds
if (!isDev && file.startsWith(localSkillsDir)) continue;
this.addWatchFile(file);
}
}
+ if (useCheckoutSkills) {
+ this.addWatchFile(join(sourceDir, "checkout-skills.ready"));
+ }
+
// Watch local-skills dir in dev mode
if (isDev && existsSync(localSkillsDir)) {
for (const file of getFilesRecursive(localSkillsDir)) {
@@ -513,6 +521,11 @@ export function copyPosthogPlugin(isDev: boolean): Plugin {
async writeBundle() {
const destDir = join(__dirname, ".vite/build/plugins/posthog");
const destSkillsDir = join(destDir, "skills");
+ const baseSkillsDir = join(__dirname, ".vite/production-skills");
+
+ if (!remoteSkillsFetched) {
+ await rm(destSkillsDir, { recursive: true, force: true });
+ }
// 1. Copy allowed plugin entries
await mkdir(destDir, { recursive: true });
@@ -534,7 +547,12 @@ export function copyPosthogPlugin(isDev: boolean): Plugin {
// 2b. Download and overlay context-mill omnibus skills (overrides same-named skills)
await downloadAndExtractContextMillSkills(destSkillsDir);
+ await rm(baseSkillsDir, { recursive: true, force: true });
+ await cp(destSkillsDir, baseSkillsDir, { recursive: true });
remoteSkillsFetched = true;
+ } else {
+ await rm(destSkillsDir, { recursive: true, force: true });
+ await cp(baseSkillsDir, destSkillsDir, { recursive: true });
}
// 3. In dev mode: overlay local-skills (overrides both shipped and remote)
@@ -551,6 +569,20 @@ export function copyPosthogPlugin(isDev: boolean): Plugin {
}
console.log("[copy-posthog-plugin] Local dev skills overlaid");
}
+ if (useCheckoutSkills) {
+ const entries = await readdir(checkoutSkillsDir, {
+ withFileTypes: true,
+ });
+ for (const entry of entries) {
+ if (!entry.isDirectory()) continue;
+ const dest = join(destSkillsDir, entry.name);
+ await rm(dest, { recursive: true, force: true });
+ await cp(join(checkoutSkillsDir, entry.name), dest, {
+ recursive: true,
+ });
+ }
+ console.log("[copy-posthog-plugin] Checkout skills active");
+ }
},
};
}
diff --git a/products/desktop/apps/code/vite.main.config.mts b/products/desktop/apps/code/vite.main.config.mts
index 196400db7e35..6d52ac569b6e 100644
--- a/products/desktop/apps/code/vite.main.config.mts
+++ b/products/desktop/apps/code/vite.main.config.mts
@@ -413,18 +413,26 @@ let remoteSkillsFetched = false;
function copyPosthogPlugin(isDev: boolean): Plugin {
const sourceDir = join(__dirname, "../../plugins/posthog");
const localSkillsDir = join(sourceDir, "local-skills");
+ const checkoutSkillsDir = join(sourceDir, "checkout-skills");
+ const useCheckoutSkills =
+ isDev && process.env.POSTHOG_DESKTOP_SKILLS === "local";
return {
name: "copy-posthog-plugin",
buildStart() {
if (existsSync(sourceDir)) {
for (const file of getFilesRecursive(sourceDir)) {
+ if (file.startsWith(checkoutSkillsDir)) continue;
// Don't watch local-skills in production builds
if (!isDev && file.startsWith(localSkillsDir)) continue;
this.addWatchFile(file);
}
}
+ if (useCheckoutSkills) {
+ this.addWatchFile(join(sourceDir, "checkout-skills.ready"));
+ }
+
// Watch local-skills dir in dev mode
if (isDev && existsSync(localSkillsDir)) {
for (const file of getFilesRecursive(localSkillsDir)) {
@@ -435,6 +443,11 @@ function copyPosthogPlugin(isDev: boolean): Plugin {
async writeBundle() {
const destDir = join(__dirname, ".vite/build/plugins/posthog");
const destSkillsDir = join(destDir, "skills");
+ const baseSkillsDir = join(__dirname, ".vite/production-skills");
+
+ if (!remoteSkillsFetched) {
+ await rm(destSkillsDir, { recursive: true, force: true });
+ }
// 1. Copy allowed plugin entries
await mkdir(destDir, { recursive: true });
@@ -456,7 +469,12 @@ function copyPosthogPlugin(isDev: boolean): Plugin {
// 2b. Download and overlay context-mill omnibus skills (overrides same-named skills)
await downloadAndExtractContextMillSkills(destSkillsDir);
+ await rm(baseSkillsDir, { recursive: true, force: true });
+ await cp(destSkillsDir, baseSkillsDir, { recursive: true });
remoteSkillsFetched = true;
+ } else {
+ await rm(destSkillsDir, { recursive: true, force: true });
+ await cp(baseSkillsDir, destSkillsDir, { recursive: true });
}
// 3. In dev mode: overlay local-skills (overrides both shipped and remote)
@@ -473,6 +491,20 @@ function copyPosthogPlugin(isDev: boolean): Plugin {
}
console.log("[copy-posthog-plugin] Local dev skills overlaid");
}
+ if (useCheckoutSkills) {
+ const entries = await readdir(checkoutSkillsDir, {
+ withFileTypes: true,
+ });
+ for (const entry of entries) {
+ if (!entry.isDirectory()) continue;
+ const dest = join(destSkillsDir, entry.name);
+ await rm(dest, { recursive: true, force: true });
+ await cp(join(checkoutSkillsDir, entry.name), dest, {
+ recursive: true,
+ });
+ }
+ console.log("[copy-posthog-plugin] Checkout skills active");
+ }
},
};
}
diff --git a/products/desktop/docs/LOCAL-DEVELOPMENT.md b/products/desktop/docs/LOCAL-DEVELOPMENT.md
index 6e8593b89c1a..257fe38d8277 100644
--- a/products/desktop/docs/LOCAL-DEVELOPMENT.md
+++ b/products/desktop/docs/LOCAL-DEVELOPMENT.md
@@ -89,6 +89,24 @@ cp .env.example .env
pnpm dev
```
+## Test local code and skill changes together
+
+- `hogli start` with the Desktop intent uses local checkout skills and rebuilds them when you edit them. Select the intent once with `hogli dev:setup`.
+- `hogli desktop:dev` (or `pnpm dev` from `products/desktop`) uses production skills by default.
+
+To change the source, run from the repository root:
+
+```bash
+POSTHOG_DESKTOP_SKILLS=production hogli start
+POSTHOG_DESKTOP_SKILLS=local hogli desktop:dev
+```
+
+Local skills require `uv sync` and a running local backend with at least one project.
+Start a new agent session after skills rebuild.
+
+Local cloud tasks use the stack's setting with `SANDBOX_PROVIDER=docker`; `production` keeps the image's built-in skills.
+Each new sandbox gets its own skill copy. Skill edits do not change running tasks; build failures stop new tasks.
+
## Connect
1. Select **Local development** for `localhost:8010`, or select **Dev Cloud** for `app.dev.posthog.dev`.
diff --git a/products/desktop/package.json b/products/desktop/package.json
index 2cb45bcc9031..781fb2db83da 100644
--- a/products/desktop/package.json
+++ b/products/desktop/package.json
@@ -11,11 +11,13 @@
"preinstall": "node scripts/enforce-pnpm.mjs",
"postinstall": "bash scripts/ensure-phrocs.sh --update",
"bootstrap:cloud-task": "pnpm install --frozen-lockfile --prefer-offline --ignore-scripts && pnpm build:deps",
- "dev": "pnpm skills:local && pnpm build:deps && bash scripts/ensure-phrocs.sh && bin/phrocs --config mprocs.yaml",
- "dev:mprocs": "pnpm skills:local && pnpm build:deps && mprocs",
+ "dev": "node scripts/dev-with-skills.mjs pnpm dev:app",
+ "dev:app": "pnpm build:deps && bash scripts/ensure-phrocs.sh && bin/phrocs --config mprocs.yaml",
+ "dev:mprocs": "node scripts/dev-with-skills.mjs pnpm dev:app:mprocs",
+ "dev:app:mprocs": "pnpm build:deps && mprocs",
"dev:agent": "pnpm --filter agent dev",
"dev:git": "pnpm --filter @posthog/git dev",
- "dev:code": "pnpm skills:local && pnpm --filter code start",
+ "dev:code": "node scripts/dev-with-skills.mjs pnpm --filter code start",
"app:cdp": "node scripts/electron-cdp.mjs",
"build": "turbo build",
"build:deps": "turbo build --filter=@posthog/code^...",
@@ -36,7 +38,6 @@
"clean": "pnpm -r clean",
"knip": "knip",
"benjamin:sync": "node scripts/sync-benjamin.mts",
- "skills:local": "node scripts/sync-local-skills.mjs",
"skills:pull": "node scripts/pull-skills.mjs",
"hosthog:build": "pnpm install --frozen-lockfile --ignore-scripts --filter @posthog/web... && SKIP_PRODUCT_ENGINEER_SKILLS_DOWNLOAD=1 pnpm exec turbo build --filter=@posthog/web && ln -sfn apps/web/dist dist"
},
diff --git a/products/desktop/packages/workspace-server/src/services/posthog-plugin/README.md b/products/desktop/packages/workspace-server/src/services/posthog-plugin/README.md
index 42b1de9a9e2f..bea30825cce4 100644
--- a/products/desktop/packages/workspace-server/src/services/posthog-plugin/README.md
+++ b/products/desktop/packages/workspace-server/src/services/posthog-plugin/README.md
@@ -12,13 +12,14 @@ Skills are published independently from the desktop app at a stable GitHub relea
### Skill Sources
-The plugin directory is assembled from three skill sources, merged in priority order (later overrides earlier for same-named skills):
+The plugin directory is assembled from these skill sources, merged in priority order (later overrides earlier for same-named skills):
| Source | Location | When used |
|---|---|---|
| **Shipped** | `plugins/posthog/skills/` | Always — committed to the repo |
| **Remote** | GitHub releases `skills.zip` | Downloaded at build time and every 30 min at runtime |
| **Local dev** | `plugins/posthog/local-skills/` | Dev mode only — gitignored |
+| **Local checkout** | `plugins/posthog/checkout-skills/` | Dev mode with `POSTHOG_DESKTOP_SKILLS=local` — generated and gitignored |
A "skill name" is its directory name. If remote and shipped both have `query-data/`, the remote version wins. If local-dev also has `query-data/`, that wins over both.
@@ -29,9 +30,12 @@ A "skill name" is its directory name. If remote and shipped both have `query-dat
1. Copies allowed plugin entries into `.vite/build/plugins/posthog/`
2. Downloads `skills.zip` via `curl`, extracts with `unzip`, overlays into the build output
3. In dev mode only: overlays `plugins/posthog/local-skills/` on top
-4. Download failure is non-fatal — build continues with shipped skills only
+4. In local-stack mode: overlays the rendered checkout skills
+5. Download failure is non-fatal — build continues with shipped skills only
Vite watches `plugins/posthog/` (and `local-skills/` in dev) for hot-reload.
+For checkout skills, it watches a readiness file that changes only after a successful build and copy.
+Each rebuild restores the production base before applying overrides, so removed skills do not persist in the bundle.
## Runtime
@@ -69,17 +73,17 @@ Vite watches `plugins/posthog/` (and `local-skills/` in dev) for hot-reload.
### Testing with local skills
-`pnpm dev` and `pnpm dev:code` sync the context layer skills from the current monorepo checkout into `plugins/posthog/local-skills/` before starting Desktop. This makes local agent sessions use the checked-out context layer skill sources instead of the production release.
+Select the Desktop intent with `hogli dev:setup`, then run `hogli start` from the repository root.
+Startup waits for PostgreSQL tables, renders checkout skills, and watches their sources for changes.
+Start a new agent session after each successful rebuild to use the new instructions.
+See [local development](../../../../../docs/LOCAL-DEVELOPMENT.md#test-local-code-and-skill-changes-together) for backend setup and scope.
-To refresh the overlay without restarting Desktop, run:
-
-```sh
-pnpm skills:local
-```
+`hogli desktop:dev`, `pnpm dev`, and `pnpm dev:code` use production skills unless `POSTHOG_DESKTOP_SKILLS=local` is set.
+Manual overrides stay separate from generated checkout skills.
For a Desktop-only skill that is not part of the monorepo skill build:
-1. Start Desktop once so the checkout skills are synced.
+1. Start Desktop in development mode.
2. Create a skill directory in `plugins/posthog/local-skills/`, e.g.:
```
plugins/posthog/local-skills/my-skill/SKILL.md
diff --git a/products/desktop/scripts/dev-with-skills.mjs b/products/desktop/scripts/dev-with-skills.mjs
new file mode 100644
index 000000000000..bcd6e27cbfc8
--- /dev/null
+++ b/products/desktop/scripts/dev-with-skills.mjs
@@ -0,0 +1,124 @@
+import { spawn } from "node:child_process";
+import { writeFile } from "node:fs/promises";
+import { dirname, join, resolve } from "node:path";
+import { setTimeout } from "node:timers/promises";
+import { fileURLToPath } from "node:url";
+
+import {
+ REPOSITORY_DIR,
+ skillSourceFingerprint,
+ syncCheckoutSkills,
+} from "./sync-local-skills.mjs";
+
+const desktopDir = resolve(dirname(fileURLToPath(import.meta.url)), "..");
+const pluginDir = join(desktopDir, "plugins/posthog");
+
+function run(command, args, { cwd, signal, env = process.env }) {
+ return new Promise((resolve, reject) => {
+ signal.throwIfAborted();
+ const child = spawn(command, args, {
+ cwd,
+ stdio: "inherit",
+ detached: process.platform !== "win32",
+ env,
+ });
+ const stop = () => {
+ if (!child.pid) return;
+ try {
+ if (process.platform === "win32") child.kill("SIGTERM");
+ else process.kill(-child.pid, "SIGTERM");
+ } catch (error) {
+ if (error.code !== "ESRCH") throw error;
+ }
+ };
+ signal.addEventListener("abort", stop, { once: true });
+ child.on("error", reject);
+ child.on("close", (code) => {
+ signal.removeEventListener("abort", stop);
+ if (code === 0 || signal.aborted) resolve();
+ else reject(new Error(`${command} exited with code ${code}`));
+ });
+ });
+}
+
+async function buildSkills(signal) {
+ console.log("[skills] Building skills from this checkout...");
+ await run(
+ "uv",
+ ["run", "python", "products/posthog_ai/scripts/build_skills.py"],
+ {
+ cwd: REPOSITORY_DIR,
+ signal,
+ env: { ...process.env, DEBUG: "1" },
+ },
+ );
+ signal.throwIfAborted();
+ await syncCheckoutSkills({
+ checkoutSkillsDir: join(REPOSITORY_DIR, "products/posthog_ai/dist/skills"),
+ localSkillsDir: join(pluginDir, "checkout-skills"),
+ });
+ await writeFile(join(pluginDir, "checkout-skills.ready"), `${Date.now()}\n`);
+ console.log(
+ "[skills] Local skills ready. Start a new agent session to use them.",
+ );
+}
+
+async function watchSkills(signal, fingerprint) {
+ while (!signal.aborted) {
+ await setTimeout(1000, undefined, { signal });
+ try {
+ const next = await skillSourceFingerprint();
+ if (next === fingerprint) continue;
+ fingerprint = next;
+ await buildSkills(signal);
+ } catch (error) {
+ if (signal.aborted) return;
+ console.error(
+ "[skills] Build failed. The last successful local skills remain active. Fix the error and save a skill to retry.",
+ error,
+ );
+ }
+ }
+}
+
+async function main() {
+ const [command, ...args] = process.argv.slice(2);
+ if (!command)
+ throw new Error(
+ "Usage: node scripts/dev-with-skills.mjs <command> [args...]",
+ );
+ const source = process.env.POSTHOG_DESKTOP_SKILLS ?? "production";
+ if (source !== "local" && source !== "production") {
+ throw new Error("POSTHOG_DESKTOP_SKILLS must be local or production");
+ }
+ const controller = new AbortController();
+ for (const signal of ["SIGINT", "SIGTERM"]) {
+ process.once(signal, () => controller.abort());
+ }
+ let watcher;
+ try {
+ console.log(
+ `[skills] Source: ${source}. Manual local-skills overrides remain enabled in development.`,
+ );
+ if (source === "local") {
+ const fingerprint = await skillSourceFingerprint();
+ await buildSkills(controller.signal);
+ watcher = watchSkills(controller.signal, fingerprint).catch((error) => {
+ if (!controller.signal.aborted) throw error;
+ });
+ }
+ await run(command, args, { cwd: desktopDir, signal: controller.signal });
+ } finally {
+ controller.abort();
+ await watcher;
+ }
+}
+
+await main().catch((error) => {
+ if (error.name === "AbortError") return;
+ console.error(
+ "[skills] Desktop startup stopped. Fix the error before restarting.",
+ error,
+ );
+ process.exitCode = 1;
+});
diff --git a/products/desktop/scripts/sync-local-skills.mjs b/products/desktop/scripts/sync-local-skills.mjs
index 5104109947b9..86e816bd9bd2 100644
--- a/products/desktop/scripts/sync-local-skills.mjs
+++ b/products/desktop/scripts/sync-local-skills.mjs
@@ -1,62 +1,88 @@
#!/usr/bin/env node
-import { cp, mkdir, readdir, rm } from "node:fs/promises";
+import { createHash } from "node:crypto";
+import {
+ cp,
+ mkdir,
+ mkdtemp,
+ readdir,
+ rename,
+ rm,
+ stat,
+} from "node:fs/promises";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = dirname(fileURLToPath(import.meta.url));
-const REPOSITORY_DIR = resolve(__dirname, "../../..");
-const CHECKOUT_SKILLS_DIR = join(
- REPOSITORY_DIR,
- "products",
- "context_layer",
- "skills",
-);
-const LOCAL_SKILLS_DIR = join(
- __dirname,
- "..",
- "plugins",
- "posthog",
- "local-skills",
-);
+export const REPOSITORY_DIR = resolve(__dirname, "../../..");
export async function syncCheckoutSkills({
checkoutSkillsDir,
localSkillsDir,
}) {
- const entries = await readdir(checkoutSkillsDir);
+ const candidates = await readdir(checkoutSkillsDir, { withFileTypes: true });
+ const entries = [];
+ for (const entry of candidates) {
+ if (
+ entry.isDirectory() &&
+ (
+ await stat(join(checkoutSkillsDir, entry.name, "SKILL.md")).catch(
+ () => null,
+ )
+ )?.isFile()
+ ) {
+ entries.push(entry.name);
+ }
+ }
if (entries.length === 0) {
throw new Error(`No checkout skills found at ${checkoutSkillsDir}`);
}
- await mkdir(localSkillsDir, { recursive: true });
- const localEntries = await readdir(localSkillsDir);
- await Promise.all(
- localEntries
- .filter((entry) => entry.startsWith("context-layer-"))
- .map((entry) =>
- rm(join(localSkillsDir, entry), { recursive: true, force: true }),
+ await mkdir(dirname(localSkillsDir), { recursive: true });
+ const stagingDir = await mkdtemp(`${localSkillsDir}.staging-`);
+ try {
+ await Promise.all(
+ entries.map((entry) =>
+ cp(join(checkoutSkillsDir, entry), join(stagingDir, entry), {
+ recursive: true,
+ }),
),
- );
- await Promise.all(
- entries.map((entry) =>
- cp(join(checkoutSkillsDir, entry), join(localSkillsDir, entry), {
- recursive: true,
- }),
- ),
- );
-}
-
-async function main() {
- await syncCheckoutSkills({
- checkoutSkillsDir: CHECKOUT_SKILLS_DIR,
- localSkillsDir: LOCAL_SKILLS_DIR,
- });
- console.log(
- `Context layer skills synced from this checkout to ${LOCAL_SKILLS_DIR}`,
- );
+ );
+ await rm(localSkillsDir, { recursive: true, force: true });
+ await rename(stagingDir, localSkillsDir);
+ } finally {
+ await rm(stagingDir, { recursive: true, force: true });
+ }
}
-if (fileURLToPath(import.meta.url) === resolve(process.argv[1])) {
- await main();
+export async function skillSourceFingerprint(repositoryDir = REPOSITORY_DIR) {
+ const productsDir = join(repositoryDir, "products");
+ const products = await readdir(productsDir, { withFileTypes: true });
+ const roots = products
+ .filter((entry) => entry.isDirectory())
+ .map((entry) => join(productsDir, entry.name, "skills"));
+ roots.push(join(productsDir, "posthog_ai", "scripts"));
+ const hash = createHash("sha256");
+ for (const root of roots.sort()) {
+ let entries;
+ try {
+ entries = await readdir(root, { recursive: true, withFileTypes: true });
+ } catch (error) {
+ if (error.code === "ENOENT") continue;
+ throw error;
+ }
+ const paths = entries
+ .filter(
+ (entry) => entry.isFile() && !entry.parentPath.includes("__pycache__"),
+ )
+ .map((entry) => join(entry.parentPath, entry.name))
+ .sort();
+ for (const path of paths) {
+ const metadata = await stat(path);
+ hash.update(
+ `${path}:${metadata.mtimeMs}:${metadata.ctimeMs}:${metadata.size}\n`,
+ );
+ }
+ }
+ return hash.digest("hex");
}
diff --git a/products/desktop/scripts/sync-local-skills.test.mjs b/products/desktop/scripts/sync-local-skills.test.mjs
index 5d4532462c38..d754d1a26aae 100644
--- a/products/desktop/scripts/sync-local-skills.test.mjs
+++ b/products/desktop/scripts/sync-local-skills.test.mjs
@@ -1,10 +1,20 @@
import assert from "node:assert/strict";
-import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import {
+ mkdir,
+ mkdtemp,
+ readFile,
+ rename,
+ rm,
+ writeFile,
+} from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, test } from "node:test";
-import { syncCheckoutSkills } from "./sync-local-skills.mjs";
+import {
+ skillSourceFingerprint,
+ syncCheckoutSkills,
+} from "./sync-local-skills.mjs";
const temporaryDirectories = [];
@@ -16,18 +26,34 @@ afterEach(async () => {
);
});
-test("overrides context layer skills without removing other local skills", async () => {
+test("replaces managed skills and removes deleted files without changing manual overrides", async () => {
const root = await mkdtemp(join(tmpdir(), "posthog-local-skills-"));
temporaryDirectories.push(root);
const checkoutSkillsDir = join(root, "checkout");
const localSkillsDir = join(root, "local");
+ const manualSkillsDir = join(root, "manual");
await mkdir(join(checkoutSkillsDir, "context-layer-dreaming"), {
recursive: true,
});
await mkdir(join(localSkillsDir, "context-layer-dreaming"), {
recursive: true,
});
- await mkdir(join(localSkillsDir, "production-only"), { recursive: true });
+ await mkdir(join(manualSkillsDir, "manual-only"), { recursive: true });
+ await mkdir(join(localSkillsDir, "deleted-skill"), { recursive: true });
+ await mkdir(join(checkoutSkillsDir, "query-data"), { recursive: true });
+ await mkdir(join(localSkillsDir, "query-data", "references"), {
+ recursive: true,
+ });
+ await writeFile(
+ join(checkoutSkillsDir, "query-data", "SKILL.md"),
+ "rendered",
+ );
+ await writeFile(join(checkoutSkillsDir, ".build-hash"), "build metadata");
+ await writeFile(join(localSkillsDir, "query-data", "SKILL.md"), "old");
+ await writeFile(
+ join(localSkillsDir, "query-data", "references", "removed.md"),
+ "outdated reference",
+ );
await writeFile(
join(checkoutSkillsDir, "context-layer-dreaming", "SKILL.md"),
"checkout version",
@@ -36,7 +62,8 @@ test("overrides context layer skills without removing other local skills", async
join(localSkillsDir, "context-layer-dreaming", "SKILL.md"),
"production version",
);
- await writeFile(join(localSkillsDir, "production-only", "SKILL.md"), "keep");
+ await writeFile(join(manualSkillsDir, "manual-only", "SKILL.md"), "keep");
+ await writeFile(join(localSkillsDir, "deleted-skill", "SKILL.md"), "remove");
await syncCheckoutSkills({ checkoutSkillsDir, localSkillsDir });
@@ -48,7 +75,66 @@ test("overrides context layer skills without removing other local skills", async
"checkout version",
);
assert.equal(
- await readFile(join(localSkillsDir, "production-only", "SKILL.md"), "utf8"),
+ await readFile(join(manualSkillsDir, "manual-only", "SKILL.md"), "utf8"),
"keep",
);
+ assert.equal(
+ await readFile(join(localSkillsDir, "query-data", "SKILL.md"), "utf8"),
+ "rendered",
+ );
+ await assert.rejects(
+ readFile(join(localSkillsDir, "query-data", "references", "removed.md")),
+ { code: "ENOENT" },
+ );
+ await assert.rejects(readFile(join(localSkillsDir, ".build-hash")), {
+ code: "ENOENT",
+ });
+ await assert.rejects(
+ readFile(join(localSkillsDir, "deleted-skill", "SKILL.md")),
+ {
+ code: "ENOENT",
+ },
+ );
+ await rm(checkoutSkillsDir, { recursive: true });
+ await mkdir(checkoutSkillsDir);
+ await assert.rejects(
+ syncCheckoutSkills({ checkoutSkillsDir, localSkillsDir }),
+ /No checkout skills/,
+ );
+ assert.equal(
+ await readFile(join(localSkillsDir, "query-data", "SKILL.md"), "utf8"),
+ "rendered",
+ );
+});
+
+test("detects skill edits, additions, renames, removals and renderer changes but ignores output", async () => {
+ const root = await mkdtemp(join(tmpdir(), "posthog-skill-watch-"));
+ temporaryDirectories.push(root);
+ await mkdir(join(root, "products"));
+ const skillDir = join(root, "products", "example", "skills", "example");
+ const rendererDir = join(root, "products", "posthog_ai", "scripts");
+ const outputDir = join(root, "products", "posthog_ai", "dist", "skills");
+ let fingerprint = await skillSourceFingerprint(root);
+ const changes = [
+ async () => {
+ await mkdir(skillDir, { recursive: true });
+ await writeFile(join(skillDir, "SKILL.md"), "first");
+ },
+ () => writeFile(join(skillDir, "SKILL.md"), "updated instructions"),
+ () => rename(join(skillDir, "SKILL.md"), join(skillDir, "SKILL.md.j2")),
+ () => rm(join(skillDir, "SKILL.md.j2")),
+ async () => {
+ await mkdir(rendererDir, { recursive: true });
+ await writeFile(join(rendererDir, "build_skills.py"), "renderer");
+ },
+ ];
+ for (const change of changes) {
+ await change();
+ const next = await skillSourceFingerprint(root);
+ assert.notEqual(next, fingerprint);
+ fingerprint = next;
+ }
+ await mkdir(outputDir, { recursive: true });
+ await writeFile(join(outputDir, "SKILL.md"), "generated");
+ assert.equal(await skillSourceFingerprint(root), fingerprint);
});
diff --git a/products/tasks/backend/logic/services/docker_sandbox.py b/products/tasks/backend/logic/services/docker_sandbox.py
index 71bc16a3599a..63ec17339036 100644
--- a/products/tasks/backend/logic/services/docker_sandbox.py
+++ b/products/tasks/backend/logic/services/docker_sandbox.py
@@ -28,6 +28,7 @@ if TYPE_CHECKING:
from products.tasks.backend.constants import POSTHOG_EXEC_PERMISSION_REGEX, SANDBOX_AGENT_LAUNCH_UNSET_ENV_VARS
from products.tasks.backend.exceptions import (
ProcessTaskError,
+ ProcessTaskFatalError,
SandboxCleanupError,
SandboxExecutionError,
SandboxNotFoundError,
@@ -50,7 +51,7 @@ from .agentsh import (
generate_policy_yaml,
read_gh_guard_script,
)
-from .local_skills import ENV_LOCAL_SKILLS_HOST_PATH, LocalSkillsCache
+from .local_skills import ENV_LOCAL_SKILLS_HOST_PATH, LocalSkillsCache, snapshot_local_task_skills
from .sandbox import (
WORKING_DIR,
AgentServerResult,
@@ -477,7 +478,19 @@ class DockerSandbox(SandboxBase):
@staticmethod
def create(config: SandboxConfig) -> DockerSandbox:
+ skills_snapshot: tempfile.TemporaryDirectory[str] | None = None
try:
+ skill_source = DockerSandbox._local_skill_source(config)
+ if skill_source == "local":
+ skills_snapshot = tempfile.TemporaryDirectory(prefix="posthog-task-skills-")
+ try:
+ snapshot_local_task_skills(Path(skills_snapshot.name))
+ except Exception as error:
+ raise ProcessTaskFatalError(
+ "Failed to build local task skills. Fix the skill error before starting another task.",
+ {"config_name": config.name, "error": _truncate_output(str(error))},
+ cause=error,
+ ) from error
image = DockerSandbox._get_image(config)
DockerSandbox._verify_image_available(image, config)
container_name = f"{config.name}-{uuid.uuid4().hex[:6]}"
@@ -512,7 +525,7 @@ class DockerSandbox(SandboxBase):
# the baked-in rendered skills in the image stay visible — only
# the specific skills the user has on disk get overlaid.
local_skills_host = os.environ.get(ENV_LOCAL_SKILLS_HOST_PATH)
- if local_skills_host and os.path.isdir(local_skills_host):
+ if skill_source != "local" and local_skills_host and os.path.isdir(local_skills_host):
for entry in sorted(os.listdir(local_skills_host)):
if entry.startswith(".") or entry == "__pycache__":
continue
@@ -555,6 +568,17 @@ class DockerSandbox(SandboxBase):
container_id = result.stdout.strip()
sandbox = DockerSandbox(container_id=container_id, config=config, host_port=host_port)
+ if skill_source is not None:
+ try:
+ sandbox._install_local_skills(Path(skills_snapshot.name) if skills_snapshot else None)
+ except Exception as error:
+ sandbox.destroy()
+ raise SandboxProvisionError(
+ "Failed to install local task skills",
+ {"config_name": config.name, "error": _truncate_output(str(error))},
+ cause=error,
+ ) from error
+ logger.info("Docker task skill source: %s", skill_source)
logger.info(f"Created Docker sandbox {sandbox.id} for {config.name} (port {host_port})")
return sandbox
@@ -577,6 +601,43 @@ class DockerSandbox(SandboxBase):
{"config_name": config.name, "error": _truncate_output(str(e))},
cause=e,
)
+ finally:
+ if skills_snapshot is not None:
+ skills_snapshot.cleanup()
+
+ @staticmethod
+ def _local_skill_source(config: SandboxConfig) -> str | None:
+ if not settings.DEBUG or config.template not in {
+ SandboxTemplate.DEFAULT_BASE,
+ SandboxTemplate.VM_BASE,
+ SandboxTemplate.PI_BASE,
+ }:
+ return None
+ source = os.environ.get("POSTHOG_DESKTOP_SKILLS")
+ if source not in {None, "local", "production"}:
+ raise ValueError("POSTHOG_DESKTOP_SKILLS must be local or production")
+ return source
+
+ def _install_local_skills(self, skills_dir: Path | None) -> None:
+ container_dir = "/tmp/posthog-local-skills"
+ if skills_dir is not None:
+ self._run(["docker", "cp", str(skills_dir), f"{self._container_id}:{container_dir}"], check=True)
+ script = (Path(__file__).parents[2] / "sandbox" / "images" / "install-local-skills.sh").read_text()
+ self._run(
+ [
+ "docker",
+ "exec",
+ self._container_id,
+ "bash",
+ "-c",
+ script,
+ "install-local-skills",
+ container_dir if skills_dir is not None else "--restore",
+ ],
+ check=True,
+ )
+ if skills_dir is not None:
+ self._run(["docker", "exec", self._container_id, "rm", "-rf", container_dir], check=True)
@staticmethod
def _recover_published_host_port(container_id: str) -> int | None:
diff --git a/products/tasks/backend/logic/services/local_skills.py b/products/tasks/backend/logic/services/local_skills.py
index 3cc5d4dbd250..c31d76e2cf82 100644
--- a/products/tasks/backend/logic/services/local_skills.py
+++ b/products/tasks/backend/logic/services/local_skills.py
@@ -20,6 +20,7 @@ destination directory — used by the Modal build-context path.
from __future__ import annotations
import os
+import fcntl
import shutil
import hashlib
import logging
@@ -83,12 +84,13 @@ class LocalSkillsCache:
automatically — no manual busting required.
"""
- def __init__(self, base_dir: Path | None = None) -> None:
+ def __init__(self, base_dir: Path | None = None, *, output_dir: Path | None = None) -> None:
self.base_dir = base_dir or Path(settings.BASE_DIR)
- self.dist_dir = self.base_dir / BUILT_SKILLS_RELATIVE_PATH
+ self.output_dir = output_dir or self.base_dir / "products" / "posthog_ai"
+ self.dist_dir = self.output_dir / "dist" / "skills"
self.hash_file = self.dist_dir / BUILD_HASH_FILENAME
- def ensure_built(self) -> Path:
+ def ensure_built(self, *, allow_stale: bool = True) -> Path:
"""Build skills if source changed; return ``dist/skills``.
Priority:
@@ -114,6 +116,8 @@ class LocalSkillsCache:
self._build(source_hash)
return self.dist_dir
except Exception as exc:
+ if not allow_stale:
+ raise RuntimeError(f"Local skill build failed: {exc}") from exc
logger.warning("Local skill build failed: %s", exc)
if self._has_existing_output():
@@ -153,7 +157,7 @@ class LocalSkillsCache:
def _build(self, source_hash: str) -> None:
from products.posthog_ai.scripts.build_skills import SkillBuilder
- builder = SkillBuilder(self.base_dir, self.base_dir / "products", self.base_dir / "products" / "posthog_ai")
+ builder = SkillBuilder(self.base_dir, self.base_dir / "products", self.output_dir)
manifest = builder.build_all()
if not manifest.resources:
raise RuntimeError("build_skills produced no skills")
@@ -194,8 +198,20 @@ class LocalSkillsCache:
continue
files.append(Path(dirpath) / name)
- builder_script = self.base_dir / "products" / "posthog_ai" / "scripts" / "build_skills.py"
- if builder_script.exists():
- files.append(builder_script)
+ scripts_dir = self.base_dir / "products" / "posthog_ai" / "scripts"
+ if scripts_dir.exists():
+ files.extend(path for path in scripts_dir.rglob("*.py") if "__pycache__" not in path.parts)
return sorted(files)
+
+
+def snapshot_local_task_skills(destination: Path, base_dir: Path | None = None) -> None:
+ root = base_dir or Path(settings.BASE_DIR)
+ output_dir = root / ".posthog" / ".generated" / "cloud-task-skills"
+ output_dir.mkdir(parents=True, exist_ok=True)
+ with (output_dir / ".build.lock").open("a") as lock:
+ fcntl.flock(lock, fcntl.LOCK_EX)
+ skills_dir = LocalSkillsCache(root, output_dir=output_dir).ensure_built(allow_stale=False)
+ if not any(skills_dir.glob("*/SKILL.md")):
+ raise RuntimeError(f"No rendered local skills found at {skills_dir}")
+ shutil.copytree(skills_dir, destination, dirs_exist_ok=True, ignore=shutil.ignore_patterns(BUILD_HASH_FILENAME))
diff --git a/products/tasks/backend/logic/services/test_docker_sandbox.py b/products/tasks/backend/logic/services/test_docker_sandbox.py
index 5836879d2d54..edf792ae53a9 100644
--- a/products/tasks/backend/logic/services/test_docker_sandbox.py
+++ b/products/tasks/backend/logic/services/test_docker_sandbox.py
@@ -1,14 +1,16 @@
+from __future__ import annotations
+
import os
import shlex
import subprocess
-from typing import Any
+from typing import TYPE_CHECKING, Any
import pytest
from unittest.mock import MagicMock, patch
from parameterized import parameterized
-from products.tasks.backend.exceptions import SandboxExecutionError, SandboxProvisionError
+from products.tasks.backend.exceptions import ProcessTaskError, SandboxExecutionError, SandboxProvisionError
from products.tasks.backend.logic.services.docker_sandbox import DockerSandbox
from products.tasks.backend.logic.services.sandbox import (
ExecutionResult,
@@ -20,6 +22,9 @@ from products.tasks.backend.logic.services.sandbox import (
redact_sandbox_command,
)
+if TYPE_CHECKING:
+ from pytest_django.fixtures import Settings
+
def _agent_server_launch_command(mock_execute: Any) -> str:
"""Return the agent-server launch command among the execute calls.
@@ -109,6 +114,65 @@ class TestSandboxFactory:
class TestDockerSandboxUnit:
+ @pytest.mark.parametrize(
+ "source,debug,template,expected",
+ [
+ ("local", True, SandboxTemplate.DEFAULT_BASE, "local"),
+ ("production", True, SandboxTemplate.DEFAULT_BASE, "production"),
+ ("local", False, SandboxTemplate.DEFAULT_BASE, None),
+ ("local", True, SandboxTemplate.SLIM_BASE, None),
+ ],
+ )
+ def test_create_installs_fixed_skills_only_for_development_tasks(
+ self, settings: Settings, source: str, debug: bool, template: SandboxTemplate, expected: str | None
+ ) -> None:
+ settings.DEBUG = debug
+ with (
+ patch.dict(os.environ, {"POSTHOG_DESKTOP_SKILLS": source}),
+ patch.object(DockerSandbox, "_get_image", return_value="test-image"),
+ patch.object(DockerSandbox, "_run", return_value=MagicMock(stdout="test-container", returncode=0)) as run,
+ patch("products.tasks.backend.logic.services.docker_sandbox.snapshot_local_task_skills") as snapshot,
+ patch.object(DockerSandbox, "_install_local_skills") as install,
+ ):
+ DockerSandbox.create(SandboxConfig(name="test-skills", template=template))
+ if expected == "local":
+ snapshot.assert_called_once()
+ snapshot_dir = snapshot.call_args.args[0]
+ install.assert_called_once_with(snapshot_dir)
+ assert not snapshot_dir.exists()
+ else:
+ snapshot.assert_not_called()
+ if expected == "production":
+ install.assert_called_once_with(None)
+ else:
+ install.assert_not_called()
+ assert any(call.args[0][:2] == ["docker", "run"] for call in run.call_args_list)
+
+ @pytest.mark.parametrize("failure_stage", ["build", "install"])
+ def test_create_stops_on_local_skill_failure(self, settings: Settings, failure_stage: str) -> None:
+ settings.DEBUG = True
+ with (
+ patch.dict(os.environ, {"POSTHOG_DESKTOP_SKILLS": "local"}),
+ patch.object(DockerSandbox, "_get_image", return_value="test-image"),
+ patch.object(DockerSandbox, "_run", return_value=MagicMock(stdout="test-container", returncode=0)) as run,
+ patch("products.tasks.backend.logic.services.docker_sandbox.snapshot_local_task_skills") as snapshot,
+ patch.object(DockerSandbox, "_install_local_skills") as install,
+ patch.object(DockerSandbox, "destroy") as destroy,
+ ):
+ failing_step = snapshot if failure_stage == "build" else install
+ failing_step.side_effect = RuntimeError("skill failure")
+ with pytest.raises(ProcessTaskError, match="local task skills") as error:
+ DockerSandbox.create(SandboxConfig(name="test-skills"))
+ assert error.value.context["error"] == "skill failure"
+ assert not snapshot.call_args.args[0].exists()
+ if failure_stage == "build":
+ assert error.value.non_retryable
+ assert not any(call.args[0][:2] == ["docker", "run"] for call in run.call_args_list)
+ install.assert_not_called()
+ destroy.assert_not_called()
+ else:
+ destroy.assert_called_once()
+
"""Unit tests that don't require Docker."""
@pytest.mark.parametrize(
diff --git a/products/tasks/backend/logic/services/test_local_skills.py b/products/tasks/backend/logic/services/test_local_skills.py
index a03f73b466fb..7ea0142eeb59 100644
--- a/products/tasks/backend/logic/services/test_local_skills.py
+++ b/products/tasks/backend/logic/services/test_local_skills.py
@@ -1,6 +1,9 @@
from __future__ import annotations
+import os
+import shutil
import tempfile
+import subprocess
from pathlib import Path
from posthog.test.base import BaseTest
@@ -11,6 +14,7 @@ from products.tasks.backend.logic.services.local_skills import (
BUILT_SKILLS_RELATIVE_PATH,
LocalSkillsCache,
populate_skills_directory,
+ snapshot_local_task_skills,
)
PATCH_TARGET = "products.posthog_ai.scripts.build_skills.SkillBuilder"
@@ -104,6 +108,14 @@ class TestLocalSkills(BaseTest):
self.assertFalse(self.cache.hash_file.exists())
+ def test_strict_build_does_not_accept_or_pin_stale_skills(self) -> None:
+ self._seed_dist()
+ with patch(PATCH_TARGET) as mock_cls:
+ mock_cls.return_value.build_all.side_effect = RuntimeError("broken template")
+ with self.assertRaisesRegex(RuntimeError, "broken template"):
+ self.cache.ensure_built(allow_stale=False)
+ self.assertFalse(self.cache.hash_file.exists())
+
def test_ensure_built_empty_manifest_raises(self) -> None:
mock_cls = _mock_builder(self.cache, produce_files=False)
@@ -129,6 +141,11 @@ class TestLocalSkills(BaseTest):
builder_script.write_text(original_builder)
self.assertEqual(self.cache._compute_source_hash(), baseline)
+ helper = builder_script.parent / "schema_helpers.py"
+ helper.write_text("schema helper")
+ self.assertNotEqual(self.cache._compute_source_hash(), baseline)
+ helper.unlink()
+
pycache = skill_file.parent / "__pycache__"
pycache.mkdir()
(pycache / "x.pyc").write_bytes(b"\x00\x01")
@@ -183,3 +200,71 @@ class TestLocalSkills(BaseTest):
def test_module_constants_are_stable(self) -> None:
self.assertEqual(BUILD_HASH_FILENAME, ".build-hash")
self.assertEqual(BUILT_SKILLS_RELATIVE_PATH, Path("products/posthog_ai/dist/skills"))
+
+ def test_task_snapshots_stay_fixed_and_do_not_share_desktop_build_output(self) -> None:
+ source = self.base_dir / "products" / "alpha" / "skills" / "my-skill" / "SKILL.md"
+ desktop_skill = self._seed_dist()
+ first_snapshot = self.base_dir / "first-run"
+ next_snapshot = self.base_dir / "next-run"
+ with patch(PATCH_TARGET) as mock_cls:
+
+ def render() -> MagicMock:
+ output = mock_cls.call_args.args[2] / "dist" / "skills" / "my-skill"
+ output.mkdir(parents=True, exist_ok=True)
+ (output / "SKILL.md").write_text(source.read_text())
+ return MagicMock(resources=[MagicMock()])
+
+ mock_cls.return_value.build_all.side_effect = render
+ snapshot_local_task_skills(first_snapshot, self.base_dir)
+ source.write_text("new instructions")
+ snapshot_local_task_skills(next_snapshot, self.base_dir)
+ snapshot_local_task_skills(self.base_dir / "cached-run", self.base_dir)
+
+ self.assertEqual(mock_cls.return_value.build_all.call_count, 2)
+ self.assertEqual((first_snapshot / "my-skill" / "SKILL.md").read_text(), "# skill body\n")
+ self.assertEqual((next_snapshot / "my-skill" / "SKILL.md").read_text(), "new instructions")
+ self.assertEqual(desktop_skill.read_text(), "rendered content")
+ self.assertFalse((next_snapshot / BUILD_HASH_FILENAME).exists())
+
+ def test_installer_updates_all_agents_and_restores_only_its_overrides(self) -> None:
+ script = Path(__file__).parents[2] / "sandbox" / "images" / "install-local-skills.sh"
+ home = self.base_dir / "home"
+ plugin = self.base_dir / "plugin"
+ targets = [plugin / "skills", home / ".agents" / "skills", home / ".claude" / "skills"]
+ source = self.base_dir / "local"
+ for target in targets:
+ (target / "shared" / "references").mkdir(parents=True)
+ (target / "shared" / "SKILL.md").write_text("production")
+ (target / "shared" / "references" / "old.md").write_text("old reference")
+ (target / "unrelated").mkdir()
+ (target / "unrelated" / "SKILL.md").write_text("keep")
+ for name in ["shared", "local-only"]:
+ (source / name).mkdir(parents=True)
+ (source / name / "SKILL.md").write_text("checkout")
+
+ def install(source_arg: str) -> None:
+ subprocess.run(
+ ["bash", str(script), source_arg, str(plugin)],
+ env={**os.environ, "HOME": str(home)},
+ check=True,
+ capture_output=True,
+ )
+
+ install(str(source))
+ for target in targets:
+ self.assertEqual((target / "shared" / "SKILL.md").read_text(), "checkout")
+ self.assertFalse((target / "shared" / "references" / "old.md").exists())
+ (target / "unrelated" / "SKILL.md").write_text("user edit")
+
+ shutil.rmtree(source / "local-only")
+ (source / "shared" / "SKILL.md").write_text("updated checkout")
+ install(str(source))
+ for target in targets:
+ self.assertFalse((target / "local-only").exists())
+ self.assertEqual((target / "shared" / "SKILL.md").read_text(), "updated checkout")
+
+ install("--restore")
+ for target in targets:
+ self.assertEqual((target / "shared" / "SKILL.md").read_text(), "production")
+ self.assertTrue((target / "shared" / "references" / "old.md").exists())
+ self.assertEqual((target / "unrelated" / "SKILL.md").read_text(), "user edit")
diff --git a/products/tasks/backend/sandbox/images/install-local-skills.sh b/products/tasks/backend/sandbox/images/install-local-skills.sh
new file mode 100644
index 000000000000..997cf8aa219b
--- /dev/null
+++ b/products/tasks/backend/sandbox/images/install-local-skills.sh
@@ -0,0 +1,39 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+source_dir="${1:?Expected a local skill directory or --restore}"
+plugin_dir="${2:-/scripts/plugins/posthog}"
+
+if [[ "$source_dir" != "--restore" ]] && ! compgen -G "$source_dir/*/SKILL.md" > /dev/null; then
+ echo "Local skill snapshot contains no rendered skills." >&2
+ exit 1
+fi
+
+for target in "$plugin_dir/skills" "$HOME/.agents/skills" "$HOME/.claude/skills"; do
+ backup="$target.posthog-base"
+ manifest="$target.posthog-local"
+ if [[ -f "$manifest" ]]; then
+ while IFS= read -r name; do
+ case "$name" in ''|.*|*/*) echo "Invalid local skill name" >&2; exit 1 ;; esac
+ rm -rf -- "$target/$name"
+ if [[ -e "$backup/$name" ]]; then
+ cp -a "$backup/$name" "$target/$name"
+ fi
+ done < "$manifest"
+ rm -rf -- "$backup" "$manifest"
+ fi
+ if [[ "$source_dir" == "--restore" ]]; then
+ continue
+ fi
+ mkdir -p "$target" "$backup"
+ for skill in "$source_dir"/*; do
+ [[ -d "$skill" && -f "$skill/SKILL.md" ]] || continue
+ name="$(basename "$skill")"
+ if [[ -e "$target/$name" ]]; then
+ cp -a "$target/$name" "$backup/$name"
+ fi
+ printf '%s\n' "$name" >> "$manifest"
+ rm -rf -- "$target/$name"
+ cp -a "$skill" "$target/$name"
+ done
+done
diff --git a/tools/hogli-commands/hogli_commands/devenv/generator.py b/tools/hogli-commands/hogli_commands/devenv/generator.py
index 4543ea0b30f8..4a133bc31c50 100644
--- a/tools/hogli-commands/hogli_commands/devenv/generator.py
+++ b/tools/hogli-commands/hogli_commands/devenv/generator.py
@@ -305,6 +305,11 @@ class MprocsGenerator(ConfigGenerator):
if name == "temporal-worker":
proc_config = self._add_uv_groups(proc_config, resolved)
+ if name in {"desktop", "temporal-worker"} and "desktop_app" in resolved.capabilities:
+ proc_config["shell"] = (
+ 'export POSTHOG_DESKTOP_SKILLS="${POSTHOG_DESKTOP_SKILLS:-local}"; ' + proc_config["shell"]
+ )
+
# Wrap Python/Node service commands in the dev sandbox when opted in
proc_config = self._add_sandbox_wrapper(proc_config, name)
diff --git a/tools/hogli-commands/hogli_commands/tests/test_devenv.py b/tools/hogli-commands/hogli_commands/tests/test_devenv.py
index 97e774f5dfec..b8b93f91679b 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_devenv.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_devenv.py
@@ -916,6 +916,14 @@ class TestInfoProcess:
class TestMprocsGeneratorRegression:
"""Regression tests for generator behavior with the real intent map."""
+ def test_desktop_and_task_worker_share_local_skill_default(self) -> None:
+ registry = create_mprocs_registry()
+ resolved = IntentResolver(load_intent_map(), registry).resolve(["desktop"])
+ config = MprocsGenerator(registry).generate(resolved)
+ for name in ["desktop", "temporal-worker"]:
+ assert 'export POSTHOG_DESKTOP_SKILLS="${POSTHOG_DESKTOP_SKILLS:-local}"' in config.procs[name]["shell"]
+ assert "POSTHOG_DESKTOP_SKILLS" not in config.procs["backend"]["shell"]
+
def test_product_analytics_keeps_native_core_services(self) -> None:
intent_map = load_intent_map()
registry = create_mprocs_registry()