: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(tasks): list a user's store skills in the sandbox from run state (#94330)
Andrew Maguiref08a41bc8f09
diff --git a/docs/internal/skills/skill-bundle-api.md b/docs/internal/skills/skill-bundle-api.mdindex dfee89d121e7..8ecc15c25c27 100644--- a/docs/internal/skills/skill-bundle-api.md+++ b/docs/internal/skills/skill-bundle-api.md@@ -2,7 +2,8 @@The skill bundle is one zip of the skills a user created or owns in the team skills store.A consumer unpacks it into a skills directory (`~/.claude/skills`, `~/.agents/skills`) so a harness discovers the skills natively.-The first consumer is the agent server in a task sandbox, which fetches the bundle at session start.+It is for consumers outside a task sandbox, such as a local install into a developer's own skills directory.+A task sandbox does not download it: the task worker runs the same stub selection (`select_skill_stubs`) when it builds the run's processing context and writes the result into `TaskRun.state["store_skills"]`, and the sandbox agent renders one pointer `SKILL.md` per entry from that state, so session start makes no extra request.Viewset: `products/skills/backend/api/skills.py` (`LLMSkillViewSet.bundle`).Walk and caps: `products/skills/backend/marketplace/adapters.py` (`build_skill_bundle`).diff --git a/products/desktop/packages/agent/src/server/agent-server.test.ts b/products/desktop/packages/agent/src/server/agent-server.test.tsindex 5d85f8c78620..488c2d282ddc 100644--- a/products/desktop/packages/agent/src/server/agent-server.test.ts+++ b/products/desktop/packages/agent/src/server/agent-server.test.ts@@ -2077,9 +2077,11 @@ describe("AgentServer HTTP Mode", () => {function exposeRefresh(testServer: AgentServer) {return testServer as unknown as {session: {+ payload: { task_id: string; run_id: string };clientConnection: { extMethod: ReturnType<typeof vi.fn> };} | null;mcpRelayServer: { mcpServers: unknown[] } | null;+ posthogAPI: { getTaskRun: ReturnType<typeof vi.fn> };executeCommand(method: string,params: Record<string, unknown>,@@ -2087,10 +2089,28 @@ describe("AgentServer HTTP Mode", () => {};}+ // A refresh also resyncs the acting user's skills store stubs. That reads+ // the run and writes to the skill roots, so keep it out of these relay+ // assertions by failing the fetch it starts from.+ function attachSession(+ testServer: ReturnType<typeof exposeRefresh>,+ extMethod: ReturnType<typeof vi.fn>,+ ) {+ testServer.session = {+ payload: { task_id: "test-task-id", run_id: "test-run-id" },+ clientConnection: { extMethod },+ };+ testServer.posthogAPI = {+ getTaskRun: vi.fn(async () => {+ throw new Error("run fetch unavailable");+ }),+ };+ }+it("re-appends the loopback relay entries so a refresh doesn't drop them", async () => {const testServer = exposeRefresh(createServer());const extMethod = vi.fn(async () => ({ refreshed: true }));- testServer.session = { clientConnection: { extMethod } };+ attachSession(testServer, extMethod);const relayEntry = {type: "http",name: "slack",@@ -2125,7 +2145,7 @@ describe("AgentServer HTTP Mode", () => {// declare a server description; only pi reads it.const testServer = exposeRefresh(createServer());const extMethod = vi.fn(async () => ({ refreshed: true }));- testServer.session = { clientConnection: { extMethod } };+ attachSession(testServer, extMethod);testServer.mcpRelayServer = null;await testServer.executeCommand("refresh_session", {@@ -2151,7 +2171,7 @@ describe("AgentServer HTTP Mode", () => {it("does not duplicate a relay entry already present in the refresh list", async () => {const testServer = exposeRefresh(createServer());const extMethod = vi.fn(async () => ({ refreshed: true }));- testServer.session = { clientConnection: { extMethod } };+ attachSession(testServer, extMethod);testServer.mcpRelayServer = {mcpServers: [{@@ -5507,7 +5527,7 @@ describe("AgentServer HTTP Mode", () => {};} | null;posthogAPI: { getTaskRun: ReturnType<typeof vi.fn> };- resolveActivationSettings(): Promise<string | null>;+ resolveActivationSettings(): Promise<string[]>;buildCloudSystemPrompt(): string;};const makeWarmServer = (@@ -5545,7 +5565,7 @@ describe("AgentServer HTTP Mode", () => {};};posthogAPI: { getTaskRun: ReturnType<typeof vi.fn> };- resolveActivationSettings(): Promise<string | null>;+ resolveActivationSettings(): Promise<string[]>;};t.prewarmedRun = true;t.session = {@@ -5574,13 +5594,13 @@ describe("AgentServer HTTP Mode", () => {it("upgrades a prewarmed run to auto-publish from run state on the first message", async () => {const t = makeWarmServer({ prewarmed: true, auto_publish: true });- const override = await t.resolveActivationSettings();+ const override = (await t.resolveActivationSettings()).join("\n");expect(override).toContain("OVERRIDE PREVIOUS INSTRUCTIONS");expect(override).toContain("gh pr create --draft");// The flip persists for the rest of the session...expect(t.buildCloudSystemPrompt()).toContain("gh pr create --draft");// ...and the override is injected only once.- expect(await t.resolveActivationSettings()).toBeNull();+ expect(await t.resolveActivationSettings()).toEqual([]);expect(t.posthogAPI.getTaskRun).toHaveBeenCalledTimes(1);});@@ -5588,7 +5608,7 @@ describe("AgentServer HTTP Mode", () => {const t = makeWarmServer({ auto_publish: true });t.prewarmedRun = false;- const override = await t.resolveActivationSettings();+ const override = (await t.resolveActivationSettings()).join("\n");expect(override).toContain("OVERRIDE PREVIOUS INSTRUCTIONS");expect(t.buildCloudSystemPrompt()).toContain("gh pr create --draft");@@ -5598,11 +5618,11 @@ describe("AgentServer HTTP Mode", () => {it("keeps a prewarmed run review-first when run state has no auto_publish", async () => {const t = makeWarmServer({ prewarmed: true });- expect(await t.resolveActivationSettings()).toBeNull();+ expect(await t.resolveActivationSettings()).toEqual([]);expect(t.buildCloudSystemPrompt()).toContain("stop with local changes ready for review",);- expect(await t.resolveActivationSettings()).toBeNull();+ expect(await t.resolveActivationSettings()).toEqual([]);expect(t.posthogAPI.getTaskRun).toHaveBeenCalledTimes(1);});@@ -5614,7 +5634,7 @@ describe("AgentServer HTTP Mode", () => {{ createPr: false },);- expect(await t.resolveActivationSettings()).toBeNull();+ expect(await t.resolveActivationSettings()).toEqual([]);expect(t.posthogAPI.getTaskRun).toHaveBeenCalledOnce();expect(t.buildCloudSystemPrompt()).toContain("stop with local changes ready for review",@@ -5623,12 +5643,12 @@ describe("AgentServer HTTP Mode", () => {it("retries the state fetch on a later message when it fails", async () => {const t = makeWarmServer(new Error("fetch failed"));- expect(await t.resolveActivationSettings()).toBeNull();+ expect(await t.resolveActivationSettings()).toEqual([]);t.posthogAPI.getTaskRun = vi.fn(async () => ({state: { prewarmed: true, auto_publish: true },}));- expect(await t.resolveActivationSettings()).toContain(+ expect((await t.resolveActivationSettings()).join("\n")).toContain("gh pr create --draft",);});@@ -5644,8 +5664,8 @@ describe("AgentServer HTTP Mode", () => {setSessionConfigOption,);- await expect(t.resolveActivationSettings()).resolves.toBeNull();- await expect(t.resolveActivationSettings()).resolves.toBeNull();+ await expect(t.resolveActivationSettings()).resolves.toEqual([]);+ await expect(t.resolveActivationSettings()).resolves.toEqual([]);expect(setSessionConfigOption).toHaveBeenCalledTimes(2);expect(t.posthogAPI.getTaskRun).toHaveBeenCalledTimes(2);diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.tsindex ef11ae282d57..06a751066556 100644--- a/products/desktop/packages/agent/src/server/agent-server.ts+++ b/products/desktop/packages/agent/src/server/agent-server.ts@@ -136,6 +136,7 @@ import {import { createRtkSavingsNotification } from "./rtk-savings";import { RunUsageAccumulator, reportRunUsage, seedRunUsage } from "./run-usage";import { jsonRpcRequestSchema, validateCommandParams } from "./schemas";+import { buildStoreSkillsInstructions, syncStoreSkills } from "./store-skills";import type { AgentServerConfig, ClaudeCodeConfig } from "./types";import { waitForFile } from "./wait-for-file";@@ -553,6 +554,8 @@ export class AgentServer {// run's state when the first message arrives (see resolveActivationSettings).private prewarmedRun = false;private prewarmedStartupTurnPending = false;+ private storeSkillsInstalledCount = 0;+ private storeSkillsActivationResolved = false;private autoPublishStateResolved = false;private warmReasoningEffortResolved = false;private installedSkillBundles = new Set<string>();@@ -1313,9 +1316,9 @@ export class AgentServer {// effort while the final composer selection uses another.// Resolve before buildDetectedPrContext so a warm auto-publish upgrade// also flips the detected-PR context to its push variant.- const autoPublishUpgrade = await this.resolveActivationSettings();+ const activationContext = await this.resolveActivationSettings();const hostContext = [- ...(autoPublishUpgrade ? [autoPublishUpgrade] : []),+ ...activationContext,...(this.detectedPrUrl? [this.buildDetectedPrContext(this.detectedPrUrl)]: []),@@ -1598,6 +1601,11 @@ export class AgentServer {);}+ // The backend refreshes the session when the acting user changes, and+ // the store skills on disk are that user's. Resync them so the previous+ // actor's skill names and descriptions do not outlive their turn.+ await this.refreshStoreSkills("refresh_session");+if (mcpServers.length === 0) {return { refreshed: true };}@@ -1809,6 +1817,7 @@ export class AgentServer {this.nativeResume = null;this.preSessionEvents = [];this.prewarmedRun = false;+ this.storeSkillsActivationResolved = false;this.prewarmedStartupTurnPending = false;this.autoPublishStateResolved = false;this.warmReasoningEffortResolved = false;@@ -1907,6 +1916,13 @@ export class AgentServer {? `${this.config.apiUrl.replace(/\/$/, "")}/project/${this.config.projectId}/inbox/${signalReportId}`: null;+ // Before the prompt: its skills-store section counts the stubs on disk.+ await this.installStoreSkills(+ payload.task_id,+ payload.run_id,+ preTaskRun?.state ?? null,+ );+const sessionSystemPrompt = this.buildSessionSystemPrompt(prUrl,slackThreadUrl,@@ -3798,6 +3814,49 @@ export class AgentServer {return normalizedName;}+ /**+ * Put the user's skills-store skills on disk as pointer stubs before the+ * harness session starts, so it lists them like any local skill. The task+ * worker resolves the list into the run state when it builds the run, so+ * this is filesystem work only and adds no request to session start. Skill+ * bodies stay in the store and cross the PostHog MCP only when a skill is+ * invoked.+ */+ private async installStoreSkills(+ taskId: string,+ runId: string,+ runState: TaskRunState | null,+ ): Promise<void> {+ this.storeSkillsInstalledCount = await syncStoreSkills(+ runState,+ { taskId, runId },+ this.logger,+ );+ }++ /**+ * Re-read the run and bring the stubs on disk in line with it. The worker+ * rewrites `store_skills` when the acting user changes, after this session+ * started, and refreshes the session right after.+ */+ private async refreshStoreSkills(reason: string): Promise<void> {+ if (!this.session) {+ return;+ }+ const { task_id: taskId, run_id: runId } = this.session.payload;+ let state: TaskRunState | undefined;+ try {+ state = (await this.posthogAPI.getTaskRun(taskId, runId))?.state;+ } catch (error) {+ this.logger.debug("Failed to fetch run state for skills store refresh", {+ reason,+ error,+ });+ return;+ }+ await this.installStoreSkills(taskId, runId, state ?? null);+ }+private async waitForRepoReady(): Promise<void> {const readyFile = this.config.repoReadyFile;if (!readyFile) {@@ -3952,21 +4011,32 @@ export class AgentServer {);}- /** Apply settings from run state before the first turn when launch config is incomplete. */- private async resolveActivationSettings(): Promise<string | null> {+ /**+ * Apply settings from run state before the first turn when launch config is+ * incomplete, and return the host-context blocks that prompt needs for them.+ */+ private async resolveActivationSettings(): Promise<string[]> {if (!this.session) {- return null;+ return [];}const shouldResolveReasoning =this.prewarmedRun && !this.warmReasoningEffortResolved;+ // A warm run's stubs were installed at prewarm time; the worker rewrites+ // the list for the activating user before it forwards the first message.+ const shouldResolveStoreSkills =+ this.prewarmedRun && !this.storeSkillsActivationResolved;const shouldResolveAutoPublish =!this.autoPublishStateResolved &&this.config.autoPublish !== true &&this.config.createPr !== false &&!this.isAutomatedOrigin();- if (!shouldResolveReasoning && !shouldResolveAutoPublish) {- return null;+ if (+ !shouldResolveReasoning &&+ !shouldResolveStoreSkills &&+ !shouldResolveAutoPublish+ ) {+ return [];}let state: TaskRunState | undefined;@@ -3980,13 +4050,29 @@ export class AgentServer {// Keep the settings unresolved so a later message retries. A transient// control-plane failure must not prevent the first prompt from running.this.logger.debug("Failed to fetch activation settings", { error });- return null;+ return [];}if (shouldResolveReasoning) {await this.resolveWarmReasoningEffort(state);}- return this.resolveAutoPublishFromState(state);+ const context: string[] = [];+ if (shouldResolveStoreSkills) {+ const { task_id: taskId, run_id: runId } = this.session.payload;+ const previousCount = this.storeSkillsInstalledCount;+ await this.installStoreSkills(taskId, runId, state ?? null);+ this.storeSkillsActivationResolved = true;+ if (previousCount === 0 && this.storeSkillsInstalledCount > 0) {+ context.push(+ buildStoreSkillsInstructions(this.storeSkillsInstalledCount).trim(),+ );+ }+ }+ const autoPublishUpgrade = this.resolveAutoPublishFromState(state);+ if (autoPublishUpgrade) {+ context.push(autoPublishUpgrade);+ }+ return context;}private async resolveWarmReasoningEffort(@@ -4348,7 +4434,7 @@ Optimize for the fewest shell round trips.When you create a non-code file the user should be able to download (such as a report, chart, image, archive, or data file), call the \`upload_artifact\` tool with its path before your final reply. In your final reply, link to the download URL returned by the tool—never link to the file's local workspace path. Files left in the workspace don't reach the user. Don't upload source code or repository changes—those belong in a commit or PR.`;// Closes out every branch below, so a new section is added once rather than five times.- const commonInstructions = `${signedCommitInstructions}${stackInstructions}${prLinkInstructions}${shellEfficiencyInstructions}${artifactInstructions}${this.buildSlackDeliveryInstructions()}${this.buildGithubAccessInstructions(hasGithubToken)}`;+ const commonInstructions = `${signedCommitInstructions}${stackInstructions}${prLinkInstructions}${shellEfficiencyInstructions}${artifactInstructions}${this.buildSlackDeliveryInstructions()}${this.buildGithubAccessInstructions(hasGithubToken)}${buildStoreSkillsInstructions(this.storeSkillsInstalledCount)}`;const whyContextInstruction = ` - Add a brief **Why** to the body — one or two sentences capturing the reason the user asked for this change (the motivation, not a restatement of the diff). Keep it short.`;const publicRepoSafetyInstruction = ` - **Public-repo safety.** Treat the target repository as public-readable unless you have verified otherwise. The PR title, description, and commit messages must not contain private operational scale (exact event counts, internal row volumes, customer-usage percentages), customer names / emails / companies, references to internal tickets or incidents, the contents of Slack threads (do not quote or paraphrase what was said), or unreleased roadmap details. Linking to the originating Slack thread is fine and encouraged — Slack links are auth-gated and useful as context — as are channel references like "raised in #team-foo". Describe findings qualitatively ("present on nearly all X events, absent from Y") rather than with quantitative figures pulled from analytics queries — the reasoning that uses those numbers can stay in the thread; the PR copy cannot.`;diff --git a/products/desktop/packages/agent/src/server/pi-agent-server.ts b/products/desktop/packages/agent/src/server/pi-agent-server.tsindex c29572ba1a02..c11adc9574a5 100644--- a/products/desktop/packages/agent/src/server/pi-agent-server.ts+++ b/products/desktop/packages/agent/src/server/pi-agent-server.ts@@ -46,6 +46,7 @@ import { type JwtPayload, JwtValidationError, validateJwt } from "./jwt";import { createRtkSavingsNotification } from "./rtk-savings";import { RunUsageAccumulator, reportRunUsage, seedRunUsage } from "./run-usage";import { jsonRpcRequestSchema } from "./schemas";+import { buildStoreSkillsInstructions, syncStoreSkills } from "./store-skills";import type { AgentServerConfig } from "./types";const MODEL_CHANGING_RPC_COMMANDS: ReadonlySet<string> = new Set([@@ -594,6 +595,12 @@ export class PiAgentServer {]);const runState = taskRun?.state;seedRunUsage(this.runUsage, runState?.token_usage);+ // Before the prompt: its skills-store section counts the stubs on disk.+ const storeSkillsInstalledCount = await syncStoreSkills(+ runState,+ { taskId: payload.task_id, runId: payload.run_id },+ this.logger,+ );const taskSnapshotKind = taskRun? typeof runState?.snapshot_kind === "string"? runState.snapshot_kind@@ -603,6 +610,11 @@ export class PiAgentServer {typeof this.config.claudeCode?.systemPrompt === "string"? this.config.claudeCode.systemPrompt: this.config.claudeCode?.systemPrompt?.append;+ const storeSkillsInstructions = buildStoreSkillsInstructions(+ storeSkillsInstalledCount,+ );+ const additionalInstructions =+ `${configuredSystemPrompt ?? ""}${storeSkillsInstructions}` || undefined;// A repo-less run gets the tools to discover and clone a repository, and the// channel prompt that names them. Derive both from one condition so the tools// and the prompt that describes them can never disagree.@@ -614,7 +626,7 @@ export class PiAgentServer {cwd,environment: "cloud",channelMode,- additionalInstructions: configuredSystemPrompt,+ additionalInstructions,};const attributionHeaders = buildPosthogPropertyHeaderRecord({task_id: payload.task_id,diff --git a/products/desktop/packages/agent/src/server/store-skills.test.ts b/products/desktop/packages/agent/src/server/store-skills.test.tsnew file mode 100644index 000000000000..e596b7744bc0--- /dev/null+++ b/products/desktop/packages/agent/src/server/store-skills.test.ts@@ -0,0 +1,485 @@+import {+ mkdir,+ mkdtemp,+ readdir,+ readFile,+ rm,+ writeFile,+} from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import type { StoreSkillStub } from "@posthog/shared";+import { afterEach, describe, expect, it, vi } from "vitest";+import {+ buildStoreSkillsInstructions,+ getStoreSkillRoots,+ hasStoreMarker,+ installStoreSkillStubs,+ listStoreSkillStubs,+ removeStoreSkillStubs,+ renderStoreSkillStub,+ syncStoreSkills,+} from "./store-skills";++// Path prefixes whose removal or write must fail, to stand in for a busy directory or a full disk.+const failingRemovals = new Set<string>();+const failingWrites = new Set<string>();++vi.mock("node:fs/promises", async (importOriginal) => {+ const actual = await importOriginal<typeof import("node:fs/promises")>();+ const failFor = (prefixes: Set<string>, path: unknown): boolean =>+ [...prefixes].some((prefix) => String(path).startsWith(prefix));+ return {+ ...actual,+ rm: (+ path: Parameters<typeof actual.rm>[0],+ options?: Parameters<typeof actual.rm>[1],+ ) =>+ failFor(failingRemovals, path)+ ? Promise.reject(new Error(`EBUSY: ${String(path)}`))+ : actual.rm(path, options),+ writeFile: (+ path: Parameters<typeof actual.writeFile>[0],+ data: Parameters<typeof actual.writeFile>[1],+ options?: Parameters<typeof actual.writeFile>[2],+ ) =>+ failFor(failingWrites, path)+ ? Promise.reject(new Error(`ENOSPC: ${String(path)}`))+ : actual.writeFile(path, data, options),+ };+});++const directories: string[] = [];++afterEach(async () => {+ vi.unstubAllEnvs();+ failingRemovals.clear();+ failingWrites.clear();+ await Promise.all(+ directories+ .splice(0)+ .map((directory) => rm(directory, { recursive: true, force: true })),+ );+});++async function temporaryHome(): Promise<string> {+ const directory = await mkdtemp(join(tmpdir(), "store-skills-"));+ directories.push(directory);+ return directory;+}++// Pin the Claude root under the temporary home so a developer's CLAUDE_CONFIG_DIR never leaks in.+function rootsFor(home: string): string[] {+ return getStoreSkillRoots({ home, claudeConfigDir: join(home, ".claude") });+}++function stub(name: string, version = 3): StoreSkillStub {+ return { name, description: `${name} description`, version };+}++const exists = (path: string): Promise<boolean> =>+ readFile(path, "utf-8").then(+ () => true,+ () => false,+ );++async function writeSkill(+ root: string,+ name: string,+ skillMd: string,+): Promise<string> {+ const skillDir = join(root, name);+ await mkdir(skillDir, { recursive: true });+ await writeFile(join(skillDir, "SKILL.md"), skillMd);+ return skillDir;+}++describe("store skills", () => {+ it("renders a pointer SKILL.md the store marker and the fetch contract can be read from", () => {+ const skillMd = renderStoreSkillStub({+ name: "tam-quota-forecast",+ description: 'Forecast "quota" usage.\nSecond line.',+ version: 7,+ });++ expect(skillMd).toContain("name: tam-quota-forecast");+ expect(skillMd).toContain(+ 'description: "Forecast \\"quota\\" usage.\\nSecond line."',+ );+ expect(skillMd).toContain(" version: '7'");+ expect(skillMd).toContain(" source: posthog-skills-store");+ expect(skillMd).toContain(+ 'call skill-get {"skill_name": "tam-quota-forecast"}',+ );+ expect(skillMd).toContain("body_next_offset");+ expect(skillMd).toContain('"version": <version>');+ });++ it("writes every stub into every skill root", async () => {+ const home = await temporaryHome();+ const roots = rootsFor(home);++ const result = await installStoreSkillStubs(+ [stub("tam-quota-forecast"), stub("release-notes")],+ roots,+ );++ expect(result).toEqual({+ installed: ["tam-quota-forecast", "release-notes"],+ collisions: [],+ removed: [],+ rejected: 0,+ errors: [],+ });+ for (const root of roots) {+ await expect(+ readFile(join(root, "tam-quota-forecast", "SKILL.md"), "utf-8"),+ ).resolves.toContain("name: tam-quota-forecast");+ await expect(+ exists(join(root, "release-notes", "SKILL.md")),+ ).resolves.toBe(true);+ }+ });++ it("puts the Claude root under CLAUDE_CONFIG_DIR when it is set", () => {+ expect(+ getStoreSkillRoots({ home: "/home/u", claudeConfigDir: "/cfg/claude" }),+ ).toEqual(["/cfg/claude/skills", "/home/u/.agents/skills"]);+ expect(rootsFor("/home/u")).toEqual([+ "/home/u/.claude/skills",+ "/home/u/.agents/skills",+ ]);+ });++ it.each([+ ["set", "/cfg/claude", "/cfg/claude/skills"],+ [+ "empty, which the Claude adapter treats as unset",+ "",+ "/home/u/.claude/skills",+ ],+ ])(+ "reads CLAUDE_CONFIG_DIR from the environment when %s",+ (_label, value, claudeRoot) => {+ vi.stubEnv("CLAUDE_CONFIG_DIR", value);++ expect(getStoreSkillRoots({ home: "/home/u" })[0]).toBe(claudeRoot);+ },+ );++ it("never replaces a bundled skill with a stub of the same name, but refreshes its own stubs", async () => {+ const home = await temporaryHome();+ const [claudeRoot, agentsRoot] = rootsFor(home);+ const bundledSkill = await writeSkill(+ claudeRoot,+ "querying-posthog-data",+ "---\nname: querying-posthog-data\n---\nThe real skill.",+ );+ // A real skill whose body mentions the marker text is still a real skill.+ const mentionsStore = await writeSkill(+ claudeRoot,+ "release-notes",+ "---\nname: release-notes\n---\nStubs carry source: posthog-skills-store in their frontmatter.",+ );+ // So is one whose frontmatter has the marker line indented under another key.+ const describesStore = await writeSkill(+ claudeRoot,+ "store-guide",+ "---\nname: store-guide\ndescription: |\n Explains stubs whose frontmatter reads\n source: posthog-skills-store\n---\nThe real skill.",+ );+ const staleStub = await writeSkill(+ agentsRoot,+ "release-notes",+ renderStoreSkillStub(stub("release-notes", 1)),+ );+ // A directory with no SKILL.md yet is somebody's work in progress, not an empty slot.+ const inProgress = join(agentsRoot, "half-written");+ await mkdir(inProgress, { recursive: true });+ await writeFile(join(inProgress, "notes.md"), "draft");++ const result = await installStoreSkillStubs(+ [+ stub("querying-posthog-data"),+ stub("release-notes"),+ stub("half-written"),+ stub("store-guide"),+ ],+ [claudeRoot, agentsRoot],+ );++ expect(result).toEqual({+ installed: [+ "querying-posthog-data",+ "release-notes",+ "half-written",+ "store-guide",+ ],+ collisions: [+ "querying-posthog-data",+ "release-notes",+ "half-written",+ "store-guide",+ ],+ removed: [],+ rejected: 0,+ errors: [],+ });+ await expect(readFile(join(inProgress, "notes.md"), "utf-8")).resolves.toBe(+ "draft",+ );+ await expect(exists(join(inProgress, "SKILL.md"))).resolves.toBe(false);+ await expect(+ readFile(join(bundledSkill, "SKILL.md"), "utf-8"),+ ).resolves.toContain("The real skill.");+ await expect(+ readFile(join(mentionsStore, "SKILL.md"), "utf-8"),+ ).resolves.toContain("Stubs carry");+ await expect(+ readFile(join(describesStore, "SKILL.md"), "utf-8"),+ ).resolves.toContain("The real skill.");+ await expect(+ readFile(join(agentsRoot, "querying-posthog-data", "SKILL.md"), "utf-8"),+ ).resolves.toContain("source: posthog-skills-store");+ await expect(+ readFile(join(staleStub, "SKILL.md"), "utf-8"),+ ).resolves.toContain("version: '3'");+ });++ it("removes stubs from an earlier install that the run no longer lists", async () => {+ const home = await temporaryHome();+ const roots = rootsFor(home);+ for (const root of roots) {+ await writeSkill(+ root,+ "lost-access",+ renderStoreSkillStub(stub("lost-access")),+ );+ await writeSkill(+ root,+ "bundled-skill",+ "---\nname: bundled-skill\n---\nShipped by the image.",+ );+ }++ const result = await installStoreSkillStubs([stub("still-mine")], roots);++ expect(result.installed).toEqual(["still-mine"]);+ expect(result.removed).toEqual(["lost-access"]);+ for (const root of roots) {+ await expect(exists(join(root, "lost-access", "SKILL.md"))).resolves.toBe(+ false,+ );+ await expect(+ exists(join(root, "bundled-skill", "SKILL.md")),+ ).resolves.toBe(true);+ }+ });++ it("lists the stubs on disk so a session that keeps them still gets the pointer guidance", async () => {+ const home = await temporaryHome();+ const [claudeRoot, agentsRoot] = rootsFor(home);+ await writeSkill(+ claudeRoot,+ "kept-stub",+ renderStoreSkillStub(stub("kept-stub")),+ );+ await writeSkill(+ agentsRoot,+ "kept-stub",+ renderStoreSkillStub(stub("kept-stub")),+ );+ await writeSkill(+ agentsRoot,+ "other-stub",+ renderStoreSkillStub(stub("other-stub")),+ );+ await writeSkill(+ claudeRoot,+ "bundled-skill",+ "---\nname: bundled-skill\n---\nShipped by the image.",+ );++ await expect(+ listStoreSkillStubs([claudeRoot, agentsRoot]),+ ).resolves.toEqual(["kept-stub", "other-stub"]);+ });++ it("removes every stub when the run lists none, and leaves real skills", async () => {+ const home = await temporaryHome();+ const [claudeRoot, agentsRoot] = rootsFor(home);+ await writeSkill(claudeRoot, "gone", renderStoreSkillStub(stub("gone")));+ await writeSkill(+ claudeRoot,+ "bundled-skill",+ "---\nname: bundled-skill\n---\nShipped by the image.",+ );++ // The second root does not exist yet, which is the state of a fresh sandbox.+ const result = await removeStoreSkillStubs([claudeRoot, agentsRoot]);++ expect(result).toEqual({ removed: ["gone"], errors: [] });+ await expect(exists(join(claudeRoot, "gone", "SKILL.md"))).resolves.toBe(+ false,+ );+ await expect(+ exists(join(claudeRoot, "bundled-skill", "SKILL.md")),+ ).resolves.toBe(true);+ });++ it("still installs into a healthy root when another root cannot be written", async () => {+ const home = await temporaryHome();+ const [claudeRoot, agentsRoot] = rootsFor(home);+ // A file where the root directory should be makes every write there fail.+ await mkdir(join(claudeRoot, ".."), { recursive: true });+ await writeFile(claudeRoot, "not a directory");++ const result = await installStoreSkillStubs(+ [stub("still-mine")],+ [claudeRoot, agentsRoot],+ );++ expect(result.installed).toEqual(["still-mine"]);+ expect(result.errors.length).toBeGreaterThan(0);+ expect(new Set(result.errors.map((error) => error.root))).toEqual(+ new Set([claudeRoot]),+ );+ await expect(+ exists(join(agentsRoot, "still-mine", "SKILL.md")),+ ).resolves.toBe(true);+ });++ it.each([+ ["path traversal in the name", { ...stub("ok"), name: "../escape" }],+ ["an uppercase name", { ...stub("ok"), name: "Bad-Name" }],+ ["a double hyphen", { ...stub("ok"), name: "bad--name" }],+ ["an empty description", { ...stub("ok"), description: " " }],+ ["a fractional version", { ...stub("ok"), version: 1.5 }],+ ])("rejects a stub with %s", async (_label, badStub) => {+ const home = await temporaryHome();+ const roots = rootsFor(home);++ const result = await installStoreSkillStubs([badStub], roots);++ expect(result.installed).toEqual([]);+ expect(result.rejected).toBe(1);+ await expect(exists(join(home, "escape", "SKILL.md"))).resolves.toBe(false);+ });++ it.each([+ ["the stub the agent renders", renderStoreSkillStub(stub("a")), true],+ [+ "the stub the bundle endpoint renders",+ "---\nname: a\ndescription: A skill.\nmetadata:\n version: '3'\n source: posthog-skills-store\n---\n\nBody.",+ true,+ ],+ [+ "a quoted source value",+ "---\nname: a\nmetadata:\n source: 'posthog-skills-store'\n---\nBody.",+ true,+ ],+ [+ "the marker line inside a block-scalar description",+ "---\nname: a\ndescription: |\n Stubs read\n source: posthog-skills-store\nmetadata:\n version: '1'\n---\nBody.",+ false,+ ],+ [+ "the marker nested below metadata",+ "---\nname: a\nmetadata:\n origin:\n source: posthog-skills-store\n---\nBody.",+ false,+ ],+ [+ "a top-level source key",+ "---\nname: a\nsource: posthog-skills-store\n---\nBody.",+ false,+ ],+ ["no frontmatter", "source: posthog-skills-store\n", false],+ ])("reads the store marker from %s", (_label, skillMd, expected) => {+ expect(hasStoreMarker(skillMd)).toBe(expected);+ });++ it("keeps the previous stub when writing the replacement fails", async () => {+ const home = await temporaryHome();+ const [claudeRoot] = rootsFor(home);+ const previous = await writeSkill(+ claudeRoot,+ "flaky",+ renderStoreSkillStub(stub("flaky", 1)),+ );+ failingWrites.add(join(claudeRoot, ".flaky.store-stub-"));++ const result = await installStoreSkillStubs(+ [stub("flaky", 2)],+ [claudeRoot],+ );++ expect(result.installed).toEqual([]);+ expect(result.errors).toEqual([+ {+ root: claudeRoot,+ skillName: "flaky",+ message: expect.stringContaining("ENOSPC"),+ },+ ]);+ await expect(+ readFile(join(previous, "SKILL.md"), "utf-8"),+ ).resolves.toContain("version: '1'");+ // No staging directory is left behind for the harness to list.+ await expect(readdir(claudeRoot)).resolves.toEqual(["flaky"]);+ failingWrites.clear();+ // The next session repairs it.+ await expect(+ installStoreSkillStubs([stub("flaky", 2)], [claudeRoot]),+ ).resolves.toMatchObject({ installed: ["flaky"], errors: [] });+ });++ it("keeps pruning stale stubs after one cannot be removed", async () => {+ const home = await temporaryHome();+ const [claudeRoot] = rootsFor(home);+ for (const name of ["busy", "stale"]) {+ await writeSkill(claudeRoot, name, renderStoreSkillStub(stub(name)));+ }+ failingRemovals.add(join(claudeRoot, "busy"));++ const result = await removeStoreSkillStubs([claudeRoot]);++ expect(result.removed).toEqual(["stale"]);+ expect(result.errors).toEqual([+ {+ root: claudeRoot,+ skillName: "busy",+ message: expect.stringContaining("EBUSY"),+ },+ ]);+ await expect(exists(join(claudeRoot, "stale", "SKILL.md"))).resolves.toBe(+ false,+ );+ });++ it("counts what the harness will list: installed stubs, or the kept ones without run context", async () => {+ const home = await temporaryHome();+ const roots = rootsFor(home);+ const logger = { info: vi.fn(), warn: vi.fn() };+ const context = { taskId: "task", runId: "run" };++ await expect(+ syncStoreSkills(+ { store_skills: [stub("one"), stub("two")] },+ context,+ logger,+ roots,+ ),+ ).resolves.toBe(2);+ await expect(syncStoreSkills(null, context, logger, roots)).resolves.toBe(+ 2,+ );+ await expect(syncStoreSkills({}, context, logger, roots)).resolves.toBe(0);+ await expect(exists(join(roots[0], "one", "SKILL.md"))).resolves.toBe(+ false,+ );+ });++ it("adds a prompt section only when a stub was installed", () => {+ expect(buildStoreSkillsInstructions(0)).toBe("");+ expect(buildStoreSkillsInstructions(3)).toContain("skill-get");+ });+});diff --git a/products/desktop/packages/agent/src/server/store-skills.ts b/products/desktop/packages/agent/src/server/store-skills.tsnew file mode 100644index 000000000000..c5785e270a0c--- /dev/null+++ b/products/desktop/packages/agent/src/server/store-skills.ts@@ -0,0 +1,434 @@+import {+ mkdir,+ readdir,+ readFile,+ rename,+ rm,+ stat,+ writeFile,+} from "node:fs/promises";+import { homedir } from "node:os";+import { join } from "node:path";+import type { StoreSkillStub, TaskRunState } from "@posthog/shared";++/**+ * The store stamps every stub's frontmatter with `metadata.source`. Only a+ * SKILL.md whose frontmatter carries it, as a key of the top-level `metadata`+ * mapping, is treated as disposable: matching the text anywhere in the file,+ * or anywhere indented, would let a real skill that mentions the store in a+ * block-scalar description be deleted on the next install.+ */+const STORE_SKILL_SOURCE = "posthog-skills-store";+const FRONTMATTER_RE = /^---[^\n]*\n([\s\S]*?)\n---/;+const METADATA_KEY_RE = /^metadata:\s*(#.*)?$/;+const SOURCE_VALUE_RE = new RegExp(+ `^source:\\s*['"]?${STORE_SKILL_SOURCE}['"]?\\s*(#.*)?$`,+);++// The shape half of the store's skill-name contract (skill_name_is_well_formed+// in products/skills/backend/api/skill_services.py). A name is also a directory+// under the skill roots, so nothing that fails it may reach the filesystem.+const SKILL_NAME_PATTERN = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;+const MAX_SKILL_NAME_LENGTH = 64;++export interface StoreSkillsInstallResult {+ /** Skill names written to at least one skill root. */+ installed: string[];+ /** Skill names left alone because a non-store skill of that name is already on disk. */+ collisions: string[];+ /** Stubs from an earlier install that are not in this list, removed from at least one root. */+ removed: string[];+ /** Entries dropped for an unsafe name, an empty description, or a malformed version. */+ rejected: number;+ /** Filesystem failures, one per root and skill, so one broken root does not hide the rest. */+ errors: StoreSkillsInstallError[];+}++export interface StoreSkillsInstallError {+ root: string;+ skillName: string | null;+ message: string;+}++export interface StoreSkillRootsOptions {+ home?: string;+ /** Where Claude Code keeps user state; `CLAUDE_CONFIG_DIR` moves it off `~/.claude`. */+ claudeConfigDir?: string;+}++/**+ * The user-level skill directories every supported harness lists: Claude Code+ * reads its config dir, and Claude Code, Codex and Pi all read `~/.agents/skills`.+ */+export function getStoreSkillRoots(+ options: StoreSkillRootsOptions = {},+): string[] {+ const home = options.home ?? homedir();+ // `||`, not `??`: the Claude adapter treats an empty CLAUDE_CONFIG_DIR as unset, and so must this.+ const claudeConfigDir =+ options.claudeConfigDir ??+ (process.env.CLAUDE_CONFIG_DIR || join(home, ".claude"));+ return [join(claudeConfigDir, "skills"), join(home, ".agents", "skills")];+}++/**+ * The pointer SKILL.md for one store skill. Keep it in step with+ * `render_skill_stub_md` in products/skills/backend/marketplace/packaging.py,+ * which renders the same file for the bundle endpoint: the frontmatter marker+ * is what `listStoreSkillStubs` keys on, and the body is the fetch contract.+ * The description is written as a JSON string, which is a valid YAML+ * double-quoted scalar, so quotes and newlines in it cannot break the file.+ */+export function renderStoreSkillStub(stub: StoreSkillStub): string {+ const skillGet = `call skill-get {"skill_name": "${stub.name}"}`;+ const skillFileGet = `call skill-file-get {"skill_name": "${stub.name}", "file_path": "<path>", "version": <version>}`;+ return [+ "---",+ `name: ${stub.name}`,+ `description: ${JSON.stringify(stub.description)}`,+ "metadata:",+ ` version: '${stub.version}'`,+ ` source: ${STORE_SKILL_SOURCE}`,+ "---",+ "",+ "This skill lives in the PostHog skills store. This file is a pointer for discovery, not the skill itself.",+ "",+ "Before you act on it:",+ "",+ `1. Run \`${skillGet}\` with the PostHog MCP \`exec\` tool. Note the \`version\` in the response and pass it to every later call for this skill, so a publish in the meantime cannot mix two versions.`,+ '2. If the response has a non-null `body_next_offset`, call `skill-get` again with `"version"` set to that version and `"body_offset"` set to `body_next_offset`, and append the returned `body`. Repeat until `body_next_offset` is null.',+ "3. Follow the complete `body` as the instructions for this skill.",+ `4. If the body references bundled files, fetch each one with \`${skillFileGet}\` and write it into this directory before you use it.`,+ "",+ ].join("\n");+}++export interface StoreSkillsLogger {+ info(message: string, data?: unknown): void;+ warn(message: string, data?: unknown): void;+}++export interface StoreSkillsSyncContext {+ taskId: string;+ runId: string;+}++/**+ * Bring the skill roots in line with a run's `store_skills` and return how+ * many stubs the harness will list. Shared by every agent server so a runtime+ * cannot drift from the others. Never throws: a run without store skills is+ * the normal case, and a broken root must not stop the session.+ *+ * A null run state says nothing about access, so stubs from an earlier+ * session stay and still count: the harness lists them, so the pointer+ * instructions must stay in the prompt too.+ */+export async function syncStoreSkills(+ runState: TaskRunState | null | undefined,+ context: StoreSkillsSyncContext,+ logger: StoreSkillsLogger,+ roots: string[] = getStoreSkillRoots(),+): Promise<number> {+ try {+ if (runState === null || runState === undefined) {+ const retained = await listStoreSkillStubs(roots);+ if (retained.length > 0) {+ logger.warn(+ "Run context unavailable, keeping earlier skills store stubs",+ { ...context, retained },+ );+ }+ return retained.length;+ }+ const stubs = runState.store_skills ?? [];+ if (stubs.length === 0) {+ const cleanup = await removeStoreSkillStubs(roots);+ if (cleanup.removed.length > 0 || cleanup.errors.length > 0) {+ logger.info("Removed stale skills store stubs", {+ ...context,+ removed: cleanup.removed,+ errors: cleanup.errors,+ });+ }+ return 0;+ }+ const install = await installStoreSkillStubs(stubs, roots);+ logger.info("Installed skills store stubs", {+ ...context,+ listed: stubs.length,+ installed: install.installed,+ collisions: install.collisions,+ removed: install.removed,+ rejected: install.rejected,+ errors: install.errors,+ });+ return install.installed.length;+ } catch (error) {+ logger.warn("Skills store install failed", { ...context, error });+ return 0;+ }+}++/**+ * Write one pointer SKILL.md per stub into each skill root, and remove any+ * stub from an earlier install that the list no longer contains, so a skill+ * the user lost is not advertised on the next session. A directory that+ * already holds a skill not written by the store is never replaced: the+ * sandbox image ships bundled PostHog skills into the same roots, and a stub+ * must not shadow a real skill of the same name.+ *+ * Each root is handled on its own: a read-only or missing root is reported in+ * `errors` and the other roots still get their stubs.+ */+export async function installStoreSkillStubs(+ stubs: readonly StoreSkillStub[],+ skillRoots: string[],+): Promise<StoreSkillsInstallResult> {+ const { skills, rejected } = selectInstallable(stubs);+ const written = new Set<string>();+ const collided = new Set<string>();+ const removed = new Set<string>();+ const errors: StoreSkillsInstallError[] = [];++ for (const root of skillRoots) {+ for (const [skillName, stub] of skills) {+ try {+ const skillDir = join(root, skillName);+ if (!(await isReplaceable(skillDir))) {+ collided.add(skillName);+ continue;+ }+ await replaceStub(root, skillName, stub);+ written.add(skillName);+ } catch (error) {+ errors.push({ root, skillName, message: errorMessage(error) });+ }+ }+ const pruned = await pruneStaleStubs(root, skills);+ for (const name of pruned.removed) {+ removed.add(name);+ }+ errors.push(...pruned.errors);+ }++ return {+ installed: [...skills.keys()].filter((name) => written.has(name)),+ collisions: [...skills.keys()].filter((name) => collided.has(name)),+ removed: [...removed].sort(),+ rejected,+ errors,+ };+}++/**+ * Remove every stub the store wrote earlier. Used when the run lists no store+ * skills, so stale discovery does not outlive access.+ */+export async function removeStoreSkillStubs(+ skillRoots: string[],+): Promise<Pick<StoreSkillsInstallResult, "removed" | "errors">> {+ const removed = new Set<string>();+ const errors: StoreSkillsInstallError[] = [];+ for (const root of skillRoots) {+ const pruned = await pruneStaleStubs(root, new Map());+ for (const name of pruned.removed) {+ removed.add(name);+ }+ errors.push(...pruned.errors);+ }+ return { removed: [...removed].sort(), errors };+}++/** Names of the store stubs on disk across the roots, for a session that keeps the previous install. */+export async function listStoreSkillStubs(+ skillRoots: string[],+): Promise<string[]> {+ const names = new Set<string>();+ for (const root of skillRoots) {+ try {+ for (const name of await listStoreStubs(root)) {+ names.add(name);+ }+ } catch {+ // A root that cannot be read has no stubs to report.+ }+ }+ return [...names].sort();+}++export function buildStoreSkillsInstructions(installedCount: number): string {+ if (installedCount === 0) {+ return "";+ }+ return `+## Skills from the PostHog skills store+${installedCount} of the user's skills from the PostHog skills store are installed as local skills. Each one's SKILL.md is a pointer, not the skill: when you invoke one, follow the pointer and fetch the skill body with the PostHog MCP \`skill-get\` tool before you act. Never improvise the skill from the pointer text.`;+}++function selectInstallable(stubs: readonly StoreSkillStub[]): {+ skills: Map<string, StoreSkillStub>;+ rejected: number;+} {+ const skills = new Map<string, StoreSkillStub>();+ let rejected = 0;+ for (const stub of stubs) {+ if (+ !isWellFormedSkillName(stub.name) ||+ stub.description.trim().length === 0 ||+ !Number.isInteger(stub.version) ||+ stub.version < 0 ||+ skills.has(stub.name)+ ) {+ rejected += 1;+ continue;+ }+ skills.set(stub.name, stub);+ }+ return { skills, rejected };+}++function isWellFormedSkillName(name: string): boolean {+ return (+ name.length <= MAX_SKILL_NAME_LENGTH &&+ SKILL_NAME_PATTERN.test(name) &&+ !name.includes("--")+ );+}++/**+ * Stage the new stub beside its destination and rename it into place, so the+ * skill directory is either the previous stub or the complete new one. A+ * write that stops halfway would otherwise leave a markerless directory that+ * `isReplaceable` keeps as somebody else's skill on every later session.+ */+async function replaceStub(+ root: string,+ skillName: string,+ stub: StoreSkillStub,+): Promise<void> {+ const skillDir = join(root, skillName);+ // Dot-prefixed, so a harness that scans the root for skills skips it while it is being written.+ const stagingDir = join(root, `.${skillName}.store-stub-${process.pid}`);+ try {+ await rm(stagingDir, { recursive: true, force: true });+ await mkdir(stagingDir, { recursive: true });+ await writeFile(join(stagingDir, "SKILL.md"), renderStoreSkillStub(stub));+ await rm(skillDir, { recursive: true, force: true });+ await rename(stagingDir, skillDir);+ } catch (error) {+ await rm(stagingDir, { recursive: true, force: true }).catch(() => {});+ throw error;+ }+}++/**+ * Delete store stubs under `root` that are not in `keep`. A stub that cannot+ * be removed is reported and the walk goes on, so one busy directory does not+ * leave every later stale stub discoverable.+ */+async function pruneStaleStubs(+ root: string,+ keep: ReadonlyMap<string, unknown>,+): Promise<Pick<StoreSkillsInstallResult, "removed" | "errors">> {+ const removed: string[] = [];+ const errors: StoreSkillsInstallError[] = [];+ let stale: string[];+ try {+ stale = (await listStoreStubs(root)).filter((name) => !keep.has(name));+ } catch (error) {+ return {+ removed,+ errors: [{ root, skillName: null, message: errorMessage(error) }],+ };+ }+ for (const name of stale) {+ try {+ await rm(join(root, name), { recursive: true, force: true });+ removed.push(name);+ } catch (error) {+ errors.push({ root, skillName: name, message: errorMessage(error) });+ }+ }+ return { removed, errors };+}++/** Names of the directories under `root` whose SKILL.md carries the store marker. */+async function listStoreStubs(root: string): Promise<string[]> {+ const entries = await readdir(root, { withFileTypes: true }).catch(+ (error: NodeJS.ErrnoException) => {+ if (error.code === "ENOENT") {+ return [];+ }+ throw error;+ },+ );+ const names: string[] = [];+ for (const entry of entries) {+ if (entry.isDirectory() && (await isStoreStub(join(root, entry.name)))) {+ names.push(entry.name);+ }+ }+ return names;+}++/**+ * True when nothing is there, or when what is there is a stub the store wrote+ * earlier. A directory with no SKILL.md is somebody else's and is kept.+ */+async function isReplaceable(skillDir: string): Promise<boolean> {+ const present = await stat(skillDir).then(+ () => true,+ (error: NodeJS.ErrnoException) => error.code !== "ENOENT",+ );+ return !present || (await isStoreStub(skillDir));+}++async function isStoreStub(skillDir: string): Promise<boolean> {+ const existing = await readSkillMd(skillDir);+ return existing !== null && hasStoreMarker(existing);+}++/** The SKILL.md text, null when the directory has none, "" when it cannot be read. */+function readSkillMd(skillDir: string): Promise<string | null> {+ return readFile(join(skillDir, "SKILL.md"), "utf-8").catch(+ (error: NodeJS.ErrnoException) => (error.code === "ENOENT" ? null : ""),+ );+}++/**+ * True when the frontmatter's top-level `metadata` mapping has+ * `source: posthog-skills-store` as a direct key. Walks the block by+ * indentation instead of parsing YAML: the two shapes the store writes and a+ * hand-written skill can take are both plain block mappings, and a full parser+ * would be a dependency just for this check.+ */+export function hasStoreMarker(skillMd: string): boolean {+ const frontmatter = FRONTMATTER_RE.exec(skillMd)?.[1];+ if (frontmatter === undefined) {+ return false;+ }+ const lines = frontmatter.split("\n");+ const metadataIndex = lines.findIndex((line) => METADATA_KEY_RE.test(line));+ if (metadataIndex === -1) {+ return false;+ }+ let blockIndent: number | null = null;+ for (const line of lines.slice(metadataIndex + 1)) {+ if (line.trim().length === 0) {+ continue;+ }+ const indent = line.length - line.trimStart().length;+ if (indent === 0) {+ return false;+ }+ blockIndent ??= indent;+ if (indent === blockIndent && SOURCE_VALUE_RE.test(line.trim())) {+ return true;+ }+ }+ return false;+}++function errorMessage(error: unknown): string {+ return error instanceof Error ? error.message : String(error);+}diff --git a/products/desktop/packages/shared/src/domain-types.ts b/products/desktop/packages/shared/src/domain-types.tsindex 49d676b3d5b7..427187494ff2 100644--- a/products/desktop/packages/shared/src/domain-types.ts+++ b/products/desktop/packages/shared/src/domain-types.ts@@ -312,6 +312,19 @@ export function readPendingFollowupMessages(return parsed.success ? parsed.data : [];}+/**+ * One skills-store skill the sandbox agent lists as a local skill. The task+ * worker resolves the list into run state; the agent renders a pointer+ * SKILL.md per entry and fetches the body over MCP only when it is invoked.+ */+const storeSkillStubSchema = z.object({+ name: z.string(),+ description: z.string(),+ version: z.number(),+});++export type StoreSkillStub = z.infer<typeof storeSkillStubSchema>;+const taskRunStateFields = {ai_stage: optionalField(z.string()),auto_publish: optionalField(z.boolean()),@@ -337,6 +350,7 @@ const taskRunStateFields = {slack_notified_pr_url: optionalField(z.string()),slack_thread_url: optionalField(z.string()),snapshot_kind: optionalField(z.string()),+ store_skills: optionalField(z.array(storeSkillStubSchema)),token_usage: optionalField(z.record(z.string(), z.unknown())),} satisfies z.ZodRawShape;diff --git a/products/desktop/packages/shared/src/index.ts b/products/desktop/packages/shared/src/index.tsindex 351abbe3de47..f597bef1142b 100644--- a/products/desktop/packages/shared/src/index.ts+++ b/products/desktop/packages/shared/src/index.ts@@ -121,6 +121,7 @@ export {isSkillBundleArtifactMetadata,isTerminalStatus,type PendingFollowupMessage,+ type StoreSkillStub,type Task,type TaskRun,type TaskRunArtifact,diff --git a/products/skills/backend/api/skills.py b/products/skills/backend/api/skills.pyindex 68b9a778d812..1282b81ea756 100644--- a/products/skills/backend/api/skills.py+++ b/products/skills/backend/api/skills.py@@ -37,7 +37,14 @@ from posthog.renderers import SafeJSONRendererfrom products.access_control.backend.presentation.access_control import AccessControlViewSetMixinfrom products.ai_observability.backend.api.metrics import llma_track_latency-from ..marketplace.adapters import MARKETPLACE_NAME, PLUGIN_NAME, build_skill_bundle, load_skill_export+from ..marketplace.adapters import (+ MARKETPLACE_NAME,+ PLUGIN_NAME,+ SANDBOX_SKILLS_FEATURE_FLAG,+ build_skill_bundle,+ load_skill_export,+ sandbox_skills_flag_distinct_id,+)from ..marketplace.credentials import (build_codex_install_command,build_install_command,@@ -122,9 +129,6 @@ logger = structlog.get_logger(__name__)MAX_IMPORT_ZIP_BYTES = 10_000_000-SANDBOX_SKILLS_FEATURE_FLAG = "skills-store-in-sandbox"--def _file_extension(path: str) -> str:return path.rsplit(".", 1)[1].lower() if "." in path else ""@@ -828,7 +832,7 @@ class LLMSkillViewSet(user = cast(User, request.user)flag_value = posthog_feature_flag_value(SANDBOX_SKILLS_FEATURE_FLAG,- user.distinct_id or str(user.uuid),+ sandbox_skills_flag_distinct_id(user),organization_id=self.organization.id,team_id=self.team.id,)diff --git a/products/skills/backend/marketplace/README.md b/products/skills/backend/marketplace/README.mdindex 7e73b7118f1b..d67e1325422a 100644--- a/products/skills/backend/marketplace/README.md+++ b/products/skills/backend/marketplace/README.md@@ -40,6 +40,15 @@ unit-testable against the real `git` binary without booting the appBehind the `skills-store-in-sandbox` flag (off → 404, flag service unavailable → 503).`llm_skill:read`, which the sandbox OAuth token already carries. Throttled per user, so one callercannot 429 the rest of the project. Consumer-facing contract: `docs/internal/skills/skill-bundle-api.md`.+- **Sandbox run state** — `select_skill_stubs` in `adapters.py` is the same stub walk without the zip.+ The tasks worker calls it when it builds a run's processing context and writes the entries into+ `TaskRun.state["store_skills"]` (`products/tasks/backend/logic/services/store_skills.py`); the sandbox+ agent renders one pointer `SKILL.md` per entry into `~/.claude/skills` and `~/.agents/skills`+ (`products/desktop/packages/agent/src/server/store-skills.ts`), skipping any name a bundled skill+ already uses. The stub file the agent writes must stay in step with `render_skill_stub_md`.+ The list is the acting user's, so the worker writes it again when that user changes after the+ session started (a warm run activated by its first message, a shared Slack task whose next+ message comes from another member) and the agent re-reads the run and resyncs the stubs.- **Zip import** — `POST /api/projects/:team/llm_skills/import` (multipart `file` field, a specskill `.zip`) → creates the skill (web-authenticated, `llm_skill:write`). The inverse ofexport: `parse_skill_zip` reads `SKILL.md` frontmatter + bundled files. Round-trips with export.diff --git a/products/skills/backend/marketplace/adapters.py b/products/skills/backend/marketplace/adapters.pyindex bfcf904b02ec..79ab34f599e0 100644--- a/products/skills/backend/marketplace/adapters.py+++ b/products/skills/backend/marketplace/adapters.py@@ -68,6 +68,21 @@ _MAX_CACHEABLE_PACKFILE_BYTES = 16_000_000# not by what the team owns. The count limit lives with the other bundle policy in packaging.MAX_BUNDLE_BYTES = 5_000_000+# Gates every path that lists a user's store skills inside a sandbox: the bundle endpoint and the+# run-state stamp the task worker writes for the sandbox agent.+SANDBOX_SKILLS_FEATURE_FLAG = "skills-store-in-sandbox"+++def sandbox_skills_flag_distinct_id(user: User) -> str:+ """The identity every consumer of ``SANDBOX_SKILLS_FEATURE_FLAG`` evaluates it with.++ A person-targeted or percentage rollout hashes this value, so the bundle endpoint and the task+ worker must agree on the fallback for a user with no ``distinct_id`` or they can disagree on+ whether the store is on.+ """+ return user.distinct_id or str(user.uuid)++# A heavy user can skip very many skills, so the walk keeps only a fixed-size sample of their names# plus a running count — never a list proportional to the skip total. The warning logs that sample# and count; the response header carries the count only.@@ -226,6 +241,15 @@ class SkillBundle:BundleContent = Literal["stub", "full"]+@frozen+class SkillStubSelection:+ """The discovery half of a user's store skills, newest first, plus what the walk left out."""++ stubs: list[SkillStub]+ dropped_count: int+ skipped_count: int++@frozenclass _BundleWalk:trees: dict[str, FileTree]@@ -234,6 +258,14 @@ class _BundleWalk:skipped_sample: list[str]+@frozen+class _StubWalk:+ stubs: list[SkillStub]+ dropped_count: int+ skipped_count: int+ skipped_sample: list[str]++def _octet_length(expression: F | Cast) -> Func:return Func(expression, function="OCTET_LENGTH", output_field=IntegerField())@@ -295,8 +327,44 @@ def build_skill_bundle("""candidates = _bundle_candidates(team, user, readable_skills)limit = min(limit, MAX_BUNDLE_SKILLS)- walk = _walk_stubs(candidates, limit) if content == "stub" else _walk_full(candidates, limit)+ if content == "stub":+ stub_walk = _walk_stubs(candidates, limit)+ walk = _BundleWalk(+ trees={stub.name: build_skill_stub_tree(stub) for stub in stub_walk.stubs},+ dropped_count=stub_walk.dropped_count,+ skipped_count=stub_walk.skipped_count,+ skipped_sample=stub_walk.skipped_sample,+ )+ else:+ walk = _walk_full(candidates, limit)+ _log_walk(team, user, walk)++ return SkillBundle(+ zip_bytes=build_skills_bundle_zip(walk.trees),+ included=list(walk.trees),+ dropped_count=walk.dropped_count,+ skipped_count=walk.skipped_count,+ )+++def select_skill_stubs(+ team: Team,+ user: User,+ readable_skills: QuerySet[LLMSkill],+ limit: int = DEFAULT_BUNDLE_SKILLS,+) -> SkillStubSelection:+ """The stubs a stub bundle would hold, without the zip, for a consumer that renders them itself.++ Same selection, order, caps and checks as ``build_skill_bundle(content="stub")``, so a sandbox+ that reads its stubs from run state lists exactly the skills a bundle download would install.+ """+ candidates = _bundle_candidates(team, user, readable_skills)+ walk = _walk_stubs(candidates, min(limit, MAX_BUNDLE_SKILLS))+ _log_walk(team, user, walk)+ return SkillStubSelection(stubs=walk.stubs, dropped_count=walk.dropped_count, skipped_count=walk.skipped_count)++def _log_walk(team: Team, user: User, walk: _BundleWalk | _StubWalk) -> None:if walk.skipped_count:logger.warning("skills_bundle_skipped",@@ -310,18 +378,11 @@ def build_skill_bundle("skills_bundle_dropped_over_cap", team_id=team.id, user_id=user.id, dropped_count=walk.dropped_count)- return SkillBundle(- zip_bytes=build_skills_bundle_zip(walk.trees),- included=list(walk.trees),- dropped_count=walk.dropped_count,- skipped_count=walk.skipped_count,- )--def _dropped_count(candidates: QuerySet[LLMSkill], trees: dict[str, FileTree], skipped_count: int) -> int:+def _dropped_count(candidates: QuerySet[LLMSkill], included_count: int, skipped_count: int) -> int:# Every candidate the walk did not include or skip was dropped at the cap. One count query# instead of holding the tail of names in memory for a user with thousands of skills.- return candidates.count() - len(trees) - skipped_count+ return candidates.count() - included_count - skipped_countdef _record_skip(count: int, sample: list[str], name: str) -> int:@@ -332,15 +393,15 @@ def _record_skip(count: int, sample: list[str], name: str) -> int:return count + 1-def _walk_stubs(candidates: QuerySet[LLMSkill], limit: int) -> _BundleWalk:- trees: dict[str, FileTree] = {}+def _walk_stubs(candidates: QuerySet[LLMSkill], limit: int) -> _StubWalk:+ stubs: list[SkillStub] = []skipped_count = 0skipped_sample: list[str] = []for row in _candidate_batches(candidates.values("name", "description", "version")):- if len(trees) >= limit:- return _BundleWalk(- trees=trees,- dropped_count=_dropped_count(candidates, trees, skipped_count),+ if len(stubs) >= limit:+ return _StubWalk(+ stubs=stubs,+ dropped_count=_dropped_count(candidates, len(stubs), skipped_count),skipped_count=skipped_count,skipped_sample=skipped_sample,)@@ -348,10 +409,8 @@ def _walk_stubs(candidates: QuerySet[LLMSkill], limit: int) -> _BundleWalk:if not _name_and_description_are_valid(name, row["description"]):skipped_count = _record_skip(skipped_count, skipped_sample, name)continue- trees[name] = build_skill_stub_tree(- SkillStub(name=name, description=row["description"], version=row["version"])- )- return _BundleWalk(trees=trees, dropped_count=0, skipped_count=skipped_count, skipped_sample=skipped_sample)+ stubs.append(SkillStub(name=name, description=row["description"], version=row["version"]))+ return _StubWalk(stubs=stubs, dropped_count=0, skipped_count=skipped_count, skipped_sample=skipped_sample)def _name_and_description_are_valid(name: str, description: str) -> bool:@@ -454,7 +513,7 @@ def _walk_full(candidates: QuerySet[LLMSkill], limit: int) -> _BundleWalk:breaktotal_bytes += tree_bytestrees[name] = tree- dropped_count = _dropped_count(candidates, trees, skipped_count) if capped else 0+ dropped_count = _dropped_count(candidates, len(trees), skipped_count) if capped else 0return _BundleWalk(trees=trees, dropped_count=dropped_count, skipped_count=skipped_count, skipped_sample=skipped_sample)diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.pyindex 529a146c91f0..c0112d7d2691 100644--- a/products/tasks/backend/constants.py+++ b/products/tasks/backend/constants.py@@ -40,6 +40,8 @@ TASK_ANALYSIS_INSIGHTS_STATE_KEY = "task_analysis_insights"# Consumers read the stamp, so the decision stays stable for the run's whole lifetime.AGENT_OTEL_TELEMETRY_STATE_KEY = "agent_otel_telemetry_enabled"PR_LOOP_ENABLED_STATE_KEY = "pr_loop_enabled"+# The skills-store stubs the sandbox agent writes into its skill roots at session start.+STORE_SKILLS_STATE_KEY = "store_skills"SAME_RUN_RESUME_STATE_KEY = "same_run_resume"SAME_RUN_RESUME_IDLE_STATE_KEY = "same_run_resume_idle"_LEGACY_SAME_RUN_RESUME_STATE_KEY = "handoff_resumed"diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 2aa0d5688a3a..4d61265a6235 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -458,7 +458,8 @@ _TASK_RUN_PUBLIC_STATE_KEYS = frozenset(# event wholesale, which for a Slack trigger can be a private channel's message content.# `end_run_when_done` gates the sandbox's `finish` tool for workflow runs; a key this# filter drops never reaches the agent server, so the gate would silently do nothing.-_TASK_RUN_AGENT_STATE_KEYS = frozenset({"end_run_when_done", "initial_prompt_override"})+# `store_skills` is the acting user's skills-store listing, so it is for their sandbox only.+_TASK_RUN_AGENT_STATE_KEYS = frozenset({"end_run_when_done", "initial_prompt_override", "store_skills"})def _public_task_run_state(state: dict | None, *, include_agent_keys: bool = False) -> dict:diff --git a/products/tasks/backend/logic/services/store_skills.py b/products/tasks/backend/logic/services/store_skills.pynew file mode 100644index 000000000000..b2d5ec3d582d--- /dev/null+++ b/products/tasks/backend/logic/services/store_skills.py@@ -0,0 +1,95 @@+"""The skills-store skills a task sandbox lists as local skills.++The sandbox agent reads ``TaskRun.state["store_skills"]`` when its session starts and writes one+pointer ``SKILL.md`` per entry into its skill roots, so ``/<name>`` works there the way a local+skill does. The skill body still crosses the PostHog MCP only when the skill is invoked. The+selection runs here, in the worker, so the sandbox makes no request of its own for it on the+session boot path. The list is the acting user's, so it is resolved again whenever that user+changes: a warm run activated by someone other than its creator, or a shared Slack task whose+next message comes from another member.+"""++from typing import Any++import structlog++from posthog.models.team.team import Team+from posthog.models.user import User+from posthog.permissions import posthog_feature_flag_value++from products.access_control.backend.facade.user_access_control import UserAccessControl+from products.skills.backend.marketplace.adapters import (+ SANDBOX_SKILLS_FEATURE_FLAG,+ sandbox_skills_flag_distinct_id,+ select_skill_stubs,+)+from products.skills.backend.marketplace.packaging import DEFAULT_BUNDLE_SKILLS+from products.skills.backend.models.skills import LLMSkill+from products.tasks.backend.constants import STORE_SKILLS_STATE_KEY+from products.tasks.backend.models import TaskRun++logger = structlog.get_logger(__name__)++# Run state is read and rewritten by several activities, so each entry carries only what the+# harness needs to list the skill. The store allows 4096 characters; the harness listing shows far less.+STORE_SKILL_DESCRIPTION_MAX_CHARS = 300+++def resolve_store_skills(team: Team, user: User, *, run_id: str) -> list[dict[str, Any]] | None:+ """The ``store_skills`` entries for a run, ``[]`` when the store is off for ``user``.++ ``None`` means the flag service did not answer. The caller then leaves the key alone, so a+ sandbox that resumes with stubs from an earlier session keeps them instead of losing them to an+ outage. ``user`` is whoever the sandbox's PostHog credential belongs to, because that is the+ identity ``skill-get`` will run as.+ """+ flag_value = posthog_feature_flag_value(+ SANDBOX_SKILLS_FEATURE_FLAG,+ sandbox_skills_flag_distinct_id(user),+ organization_id=team.organization_id,+ team_id=team.id,+ )+ if flag_value is None:+ logger.warning("store_skills_flag_unavailable", run_id=run_id, team_id=team.id)+ return None+ if not flag_value:+ return []++ readable_skills = UserAccessControl(user=user, team=team).filter_queryset_by_access_level(+ LLMSkill.objects.filter(team=team), resource="llm_skill"+ )+ selection = select_skill_stubs(team, user, readable_skills, limit=DEFAULT_BUNDLE_SKILLS)+ logger.info(+ "store_skills_resolved",+ run_id=run_id,+ team_id=team.id,+ included=len(selection.stubs),+ dropped=selection.dropped_count,+ skipped=selection.skipped_count,+ )+ return [+ {+ "name": stub.name,+ "description": " ".join(stub.description.split())[:STORE_SKILL_DESCRIPTION_MAX_CHARS],+ "version": stub.version,+ }+ for stub in selection.stubs+ ]+++def refresh_store_skills_state(task_run: TaskRun, user: User, *, reason: str) -> None:+ """Rewrite ``store_skills`` for ``user`` on a run that already has a session.++ Best-effort: the run goes on either way, and a failure only leaves the sandbox with the list it+ had. The sandbox re-reads the run after the transition and brings its stubs in line.+ """+ run_id = str(task_run.id)+ try:+ store_skills = resolve_store_skills(task_run.task.team, user, run_id=run_id)+ if store_skills is None:+ return+ TaskRun.update_state_atomic(task_run.id, updates={STORE_SKILLS_STATE_KEY: store_skills})+ except Exception:+ logger.warning("store_skills_refresh_failed", run_id=run_id, reason=reason, exc_info=True)+ return+ logger.info("store_skills_refreshed", run_id=run_id, reason=reason, included=len(store_skills))diff --git a/products/tasks/backend/temporal/process_task/activities/forward_pending_message.py b/products/tasks/backend/temporal/process_task/activities/forward_pending_message.pyindex 3c8e26c0a449..e3be94ffc8fc 100644--- a/products/tasks/backend/temporal/process_task/activities/forward_pending_message.py+++ b/products/tasks/backend/temporal/process_task/activities/forward_pending_message.py@@ -61,6 +61,7 @@ def forward_pending_user_message(run_id: str) -> None:from products.tasks.backend.logic.services.agent_command import send_user_messagefrom products.tasks.backend.logic.services.connection_token import create_sandbox_connection_tokenfrom products.tasks.backend.logic.services.staged_artifacts import get_task_run_artifacts_by_id+ from products.tasks.backend.logic.services.store_skills import refresh_store_skills_statefrom products.tasks.backend.metrics import observe_followup_delivery_failedfrom products.tasks.backend.models import TaskRun, stamp_pending_user_message_id@@ -129,6 +130,10 @@ def forward_pending_user_message(run_id: str) -> None:auth_token = create_sandbox_connection_token(task_run, user_id=actor_user.id, distinct_id=get_actor_distinct_id(actor_user))+ # A warm run listed its store skills when it was prepared, before anyone owned it.+ # The agent re-reads the run on this first message, so the list must be current first.+ if state.get("await_user_message"):+ refresh_store_skills_state(task_run, actor_user, reason="warm_activation")from products.tasks.backend.logic.services.sandbox_usage import ( # noqa: PLC0415 — matches the file's deferred-import patternmeasure_task_run_cpu_attribution,diff --git a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.pyindex 140cd23b1d4e..ae2eab9ccb71 100644--- a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py+++ b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py@@ -2,6 +2,7 @@ import jsonimport hashlibfrom dataclasses import dataclassfrom datetime import timedelta+from typing import Anyfrom django.conf import settingsfrom django.core.exceptions import ObjectDoesNotExist@@ -30,6 +31,7 @@ from products.tasks.backend.constants import (RTK_DISABLED_FEATURE_FLAG,SANDBOX_EVENT_INGEST_FEATURE_FLAG,SANDBOX_ROTATION_FEATURE_FLAG,+ STORE_SKILLS_STATE_KEY,get_vm_sandbox_flag_payload,is_same_run_resume_state,vm_sandbox_allowed_origin_products,@@ -56,6 +58,7 @@ from products.tasks.backend.logic.services.sandbox_config import (MAX_SANDBOX_MEMORY_GB,MAX_SANDBOX_TTL_SECONDS,)+from products.tasks.backend.logic.services.store_skills import resolve_store_skillsfrom products.tasks.backend.models import SandboxCustomImage, SandboxEnvironment, Task, TaskRunfrom products.tasks.backend.temporal.constants import resolve_inactivity_timeout, resolve_max_run_durationfrom products.tasks.backend.temporal.oauth import is_interactive_signals_run@@ -1181,10 +1184,21 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskProor False) # Ensure we get a boolean value even if the flag is missingemit_agent_log(run_id, "debug", f"pr_loop_enabled: {pr_loop_enabled} for this task run")+ state_updates: dict[str, Any] = {PR_LOOP_ENABLED_STATE_KEY: pr_loop_enabled}+ # The sandbox agent renders these into its skill roots at session start. Resolved here so the+ # sandbox needs no extra request on its boot path, and best-effort: a store failure must not+ # stop the run, it only leaves the sandbox without store skills for this session.try:- TaskRun.update_state_atomic(task_run.id, updates={PR_LOOP_ENABLED_STATE_KEY: pr_loop_enabled})+ store_skills = resolve_store_skills(team, actor_user or task.created_by, run_id=run_id)except Exception as e:- log_with_activity_context("pr_loop_enabled_stamp_failed", run_id=run_id, error=str(e))+ log_with_activity_context("store_skills_resolve_failed", run_id=run_id, error=str(e))+ store_skills = None+ if store_skills is not None:+ state_updates[STORE_SKILLS_STATE_KEY] = store_skills+ try:+ TaskRun.update_state_atomic(task_run.id, updates=state_updates)+ except Exception as e:+ log_with_activity_context("run_state_stamp_failed", run_id=run_id, error=str(e))pi_persistent_streaming = task.runtime == Task.Runtime.PI and not is_slack_interaction_state(state)sandbox_event_ingest_override = state.get("sandbox_event_ingest_enabled")if pi_persistent_streaming and not isinstance(sandbox_event_ingest_override, bool):diff --git a/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py b/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.pyindex c955a2d057a7..5a8b50deb563 100644--- a/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py@@ -30,6 +30,7 @@ from products.tasks.backend.logic.services.connection_token import create_sandbofrom products.tasks.backend.logic.services.peer_messages import mark_peer_message_outcome, peer_message_id_from_contextfrom products.tasks.backend.logic.services.run_actor import slack_actor_state_updates, user_has_current_team_accessfrom products.tasks.backend.logic.services.staged_artifacts import get_task_run_artifacts_by_id+from products.tasks.backend.logic.services.store_skills import refresh_store_skills_statefrom products.tasks.backend.logic.stream.redis_stream import publish_task_run_stream_eventfrom products.tasks.backend.metrics import observe_followup_denied_permission_stop, observe_followup_sandbox_stoppedfrom products.tasks.backend.models import AgentPeerMessage, TaskRun@@ -383,6 +384,10 @@ def _deliver_followup(input: SendFollowupToSandboxInput) -> str | None:TaskRun.update_state_atomic(task_run.id, updates=updates)except Exception:logger.warning("send_followup_actor_stamp_failed", run_id=input.run_id, exc_info=True)+ # The store skills in run state are the previous actor's; the MCP refresh below makes+ # the sandbox re-read the run, so the new actor's list must be there first.+ if actor_user is not None and current.get("slack_actor_user_id") != actor_user.id:+ refresh_store_skills_state(task_run, actor_user, reason="slack_actor_change")auth_token = Noneif actor_user and actor_user.id:diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.pyindex 41f1e4632da8..07f5a476b55b 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py@@ -11,6 +11,7 @@ from asgiref.sync import async_to_syncfrom posthog.models import OrganizationMembership, Userfrom posthog.models.user_integration import UserIntegration+from products.skills.backend.models.skills import LLMSkillfrom products.tasks.backend.constants import (AGENT_PROXY_KEEP_STREAM_OPEN_FEATURE_FLAG,BENJAMIN_FEATURE_FLAG,@@ -21,6 +22,7 @@ from products.tasks.backend.constants import (PR_BABYSIT_SNAPSHOT_FEATURE_FLAG,RTK_DISABLED_FEATURE_FLAG,SANDBOX_EVENT_INGEST_FEATURE_FLAG,+ STORE_SKILLS_STATE_KEY,vm_sandbox_allowed_origin_products,vm_sandbox_default_base_origin_products,vm_sandbox_default_custom_image,@@ -28,7 +30,7 @@ from products.tasks.backend.constants import (vm_sandbox_origin_rollout_percentages,)from products.tasks.backend.exceptions import TaskInvalidStateError, TaskRunNotReadyError-from products.tasks.backend.models import TASK_OWNERSHIP_VERSION_STATE_KEY, SandboxEnvironment, Task+from products.tasks.backend.models import TASK_OWNERSHIP_VERSION_STATE_KEY, SandboxEnvironment, Task, TaskRunfrom products.tasks.backend.temporal.process_task.activities.get_task_processing_context import (GetTaskProcessingContextInput,TaskProcessingContext,@@ -514,8 +516,8 @@ class TestGetTaskProcessingContextActivity:org_id = str(test_task.team.organization_id)assert kwargs["groups"] == {"organization": org_id}assert kwargs["group_properties"] == {"organization": {"id": org_id}}- sandbox_args, _sandbox_kwargs = feature_enabled_mock.call_args_list[1]- assert sandbox_args[0] == SANDBOX_EVENT_INGEST_FEATURE_FLAG+ evaluated_flags = [args[0] for args, _kwargs in feature_enabled_mock.call_args_list]+ assert SANDBOX_EVENT_INGEST_FEATURE_FLAG in evaluated_flags@pytest.mark.django_db(transaction=True)def test_pi_runtime_enables_event_ingest_without_bypassing_persistent_upload_rollout(@@ -552,6 +554,49 @@ class TestGetTaskProcessingContextActivity:assert result.sandbox_event_ingest_enabled is Falseassert result.agent_proxy_keep_stream_open is False+ @pytest.mark.django_db(transaction=True)+ @pytest.mark.parametrize(+ "flag_value,expected_state",+ [+ (True, "resolved"),+ (False, []),+ (None, "untouched"), # a flag-service outage must not clear stubs a resumed sandbox still has+ ],+ )+ def test_store_skills_state_follows_the_sandbox_flag(+ self, activity_environment, test_task, user, flag_value, expected_state+ ):+ LLMSkill.objects.create(+ team=test_task.team,+ name="my-skill",+ description="Forecast quota\nusage. " + "x" * 400,+ body="# The real instructions\n",+ version=1,+ is_latest=True,+ created_by=user,+ )+ task_run = test_task.create_run()+ TaskRun.update_state_atomic(task_run.id, updates={STORE_SKILLS_STATE_KEY: [{"name": "from-last-session"}]})+ input_data = GetTaskProcessingContextInput(run_id=str(task_run.id))++ with patch(+ "products.tasks.backend.logic.services.store_skills.posthog_feature_flag_value",+ return_value=flag_value,+ ):+ async_to_sync(activity_environment.run)(get_task_processing_context, input_data)++ stored = TaskRun.objects.get(id=task_run.id).state[STORE_SKILLS_STATE_KEY]+ if expected_state == "untouched":+ assert stored == [{"name": "from-last-session"}]+ elif expected_state == "resolved":+ assert len(stored) == 1+ assert stored[0]["name"] == "my-skill"+ assert stored[0]["version"] == 1+ assert stored[0]["description"].startswith("Forecast quota usage. xxx")+ assert len(stored[0]["description"]) == 300+ else:+ assert stored == expected_state+@pytest.mark.django_db(transaction=True)def test_pr_loop_enabled_for_signal_report_origin_ignores_flag(self, activity_environment, test_task):# Signals implementation PRs are bot-authored and always opt into the PRdiff --git a/products/tasks/backend/temporal/process_task/tests/test_forward_pending_message.py b/products/tasks/backend/temporal/process_task/tests/test_forward_pending_message.pyindex 595abc0e63d6..22cf43d82a19 100644--- a/products/tasks/backend/temporal/process_task/tests/test_forward_pending_message.py+++ b/products/tasks/backend/temporal/process_task/tests/test_forward_pending_message.py@@ -97,9 +97,10 @@ class TestForwardPendingUserMessage(TestCase):forward_pending_user_message("550e8400-e29b-41d4-a716-446655440000")assert ctx.exception.non_retryable is True+ @patch("products.tasks.backend.logic.services.store_skills.refresh_store_skills_state")@patch("products.tasks.backend.logic.services.connection_token.create_sandbox_connection_token", return_value="jwt")@patch("products.tasks.backend.logic.services.agent_command.send_user_message")- def test_pending_message_delivered_successfully(self, mock_send, mock_token):+ def test_pending_message_delivered_successfully(self, mock_send, mock_token, mock_refresh_store_skills):run = self._make_run(state={"pending_user_message": "fix the tests",@@ -110,6 +111,8 @@ class TestForwardPendingUserMessage(TestCase):forward_pending_user_message(str(run.id))+ # Not a warm activation: the run's own boot already listed this user's skills.+ mock_refresh_store_skills.assert_not_called()mock_send.assert_called_once()assert mock_send.call_args[0][1] == "fix the tests"assert mock_send.call_args.kwargs["message_id"]@@ -117,10 +120,13 @@ class TestForwardPendingUserMessage(TestCase):assert "pending_user_message" not in run.stateassert "pending_user_message_id" not in run.state+ @patch("products.tasks.backend.logic.services.store_skills.refresh_store_skills_state")@patch("products.tasks.backend.logic.services.sandbox_usage.measure_task_run_cpu_attribution")@patch("products.tasks.backend.logic.services.connection_token.create_sandbox_connection_token", return_value="jwt")@patch("products.tasks.backend.logic.services.agent_command.send_user_message")- def test_successful_delivery_attributes_sandbox_usage(self, mock_send, mock_token, mock_measure):+ def test_successful_delivery_attributes_sandbox_usage(+ self, mock_send, mock_token, mock_measure, mock_refresh_store_skills+ ):run = self._make_run(state={"await_user_message": True,@@ -155,8 +161,12 @@ class TestForwardPendingUserMessage(TestCase):calls.append("send")return _command_result(success=True, status_code=200)+ def refresh_store_skills(*args, **kwargs):+ calls.append("refresh_store_skills")+mock_measure.side_effect = measuremock_send.side_effect = send+ mock_refresh_store_skills.side_effect = refresh_store_skillsforward_pending_user_message(str(run.id))@@ -166,7 +176,9 @@ class TestForwardPendingUserMessage(TestCase):assert session.provider_cpu_usage_attribution_usec == 1_234_567assert session.provider_billed_cpu_usage_attribution_usec == 1_500_000assert session.provider_cpu_usage_attribution_measured_at == measured_at- assert calls == ["measure", "send"]+ # The agent re-reads the run on this message, so the activating user's skills go in first.+ assert calls == ["refresh_store_skills", "measure", "send"]+ mock_refresh_store_skills.assert_called_once_with(run, self.user, reason="warm_activation")@patch("products.tasks.backend.logic.services.connection_token.create_sandbox_connection_token", return_value="jwt")@patch("products.tasks.backend.temporal.observability.posthoganalytics.capture")diff --git a/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py b/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.pyindex 18f8ca4bcfaf..b56f4723badb 100644--- a/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py+++ b/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py@@ -699,6 +699,9 @@ class TestSendFollowupActivityRefreshOrdering:patch("products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox._write_error_and_complete"),+ patch(+ "products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox.refresh_store_skills_state"+ ) as mock_refresh_store_skills,):task_run = _make_task_run_mock()task_run.task.created_by = MagicMock(id=42, distinct_id="u42")@@ -712,6 +715,7 @@ class TestSendFollowupActivityRefreshOrdering:"refresh_github": mock_refresh_github,"user_msg": mock_user_msg,"conn_token": mock_conn_token,+ "refresh_store_skills": mock_refresh_store_skills,}def test_refresh_called_before_user_message(self, _patches):@@ -837,10 +841,15 @@ class TestSendFollowupActivityRefreshOrdering:_patches["user_msg"].return_value = CommandResult(success=True, status_code=200)_patches["task_run"].state = {"interaction_origin": "slack", "slack_actor_user_id": 42}+ order: list[str] = []+ _patches["refresh_store_skills"].side_effect = lambda *args, **kwargs: order.append("store_skills")+ _patches["refresh"].side_effect = lambda *args, **kwargs: order.append("mcp")+with patch("products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox.get_task_run_credential_user") as mock_resolve:- mock_resolve.return_value = MagicMock(id=99)+ new_actor = MagicMock(id=99)+ mock_resolve.return_value = new_actorsend_followup_to_sandbox(SendFollowupToSandboxInput(run_id="run-1", message="hi", actor_user_id=99, context={"actor_slack_user_id": "U_BOB"}@@ -851,6 +860,11 @@ class TestSendFollowupActivityRefreshOrdering:_patches["task_run"].id,updates={"slack_actor_user_id": 99, "slack_actor_slack_user_id": "U_BOB"},)+ # The MCP refresh makes the sandbox re-read the run, so the new actor's skills go in first.+ _patches["refresh_store_skills"].assert_called_once_with(+ _patches["task_run"], new_actor, reason="slack_actor_change"+ )+ assert order == ["store_skills", "mcp"]def test_non_slack_delivery_does_not_stamp(self, _patches):_patches["user_msg"].return_value = CommandResult(success=True, status_code=200)@@ -858,6 +872,7 @@ class TestSendFollowupActivityRefreshOrdering:send_followup_to_sandbox(SendFollowupToSandboxInput(run_id="run-1", message="hi", actor_user_id=99))_patches["task_run_cls"].update_state_atomic.assert_not_called()+ _patches["refresh_store_skills"].assert_not_called()def test_default_scope_is_read_only(self, _patches):_patches["user_msg"].return_value = CommandResult(success=True, status_code=200)diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.pyindex ca04f2e01b41..42fade240771 100644--- a/products/tasks/backend/tests/test_facade.py+++ b/products/tasks/backend/tests/test_facade.py@@ -273,6 +273,7 @@ class TestFacadeReadsAndMappers(TestCase):state={"initial_prompt_override": "framed prompt","end_run_when_done": True,+ "store_skills": [{"name": "my-skill", "description": "Mine.", "version": 1}],"sandbox_jwt_kid": "secret",},)@@ -285,6 +286,8 @@ class TestFacadeReadsAndMappers(TestCase):# The finish-tool gate reads this key at agent boot; a filter that drops it makes# every unbound workflow run idle out instead of ending itself.assert detail.state.get("end_run_when_done") == (True if include_agent_state else None)+ # The agent writes these into its skill roots at boot; dropped, it installs none.+ assert ("store_skills" in detail.state) is include_agent_stateassert "sandbox_jwt_kid" not in detail.statedef test_get_task_run_maps_all_fields(self):