: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): add a /phs bridge skill to every task sandbox (#128162)
posthog[bot]857e2c949d1d
diff --git a/docs/internal/skills/skill-bundle-api.md b/docs/internal/skills/skill-bundle-api.mdindex 3c2730c61af7..b51dd57e26af 100644--- a/docs/internal/skills/skill-bundle-api.md+++ b/docs/internal/skills/skill-bundle-api.md@@ -67,3 +67,20 @@ Its body tells the agent to:Pinning the version keeps a publish that lands mid-fetch from mixing two versions of the skill.Skill content only crosses the MCP server when a skill is invoked; the bundle itself carries discovery metadata only.++## The `phs` bridge in task sandboxes++A task sandbox lists only the user's own skills as stubs, so it also gets a fixed `phs` skill that runs any store skill the user can read, such as a teammate's.+`/phs <name> [arguments]` fetches the skill with `skill-get`, pages through the body and pins the version, the same way a stub does.+`/phs` or `/phs list [keyword]` calls `skill-list`, and a name `skill-get` cannot find triggers a `skill-list` search for close matches.+The bridge reads and runs skills only.++The task worker sets `TaskRun.state["store_skills_bridge"]` from the same `skills-store-in-sandbox` evaluation as `store_skills`.+`store_skills` is empty both when the flag is off and when the user owns no skills, so it cannot carry this switch.+The sandbox agent writes the bridge in `syncStoreSkills` (`packages/agent/packages/harness/src/extensions/skills-store/store-skills.ts`), so the Claude, Codex and Pi servers share it:++- It is written even when `store_skills` is empty, because a user with no skills of their own needs it most.+- It carries the store marker and `metadata.role: bridge`. Pruning keeps it while the switch is on and removes it when the switch is off. It is not counted in the prompt's number of the user's skills.+- A null run state leaves the bridge on disk as it is, the same as stubs.+- A team skill named `phs` in `store_skills` replaces it, including on a resumed sandbox. A non-store skill named `phs` is never replaced.+- `skill-get` resolves in the run's project, so the bridge cannot fetch skills from another project.diff --git a/packages/agent/packages/agent-contracts/src/domain-types.ts b/packages/agent/packages/agent-contracts/src/domain-types.tsindex 67ab3a9e69f7..3a28d5731392 100644--- a/packages/agent/packages/agent-contracts/src/domain-types.ts+++ b/packages/agent/packages/agent-contracts/src/domain-types.ts@@ -395,6 +395,7 @@ const taskRunStateFields = {slack_thread_url: optionalField(z.string()),snapshot_kind: optionalField(z.string()),store_skills: optionalField(z.array(storeSkillStubSchema)),+ store_skills_bridge: optionalField(z.boolean()),token_usage: optionalField(z.record(z.string(), z.unknown())),} satisfies z.ZodRawShape;diff --git a/packages/agent/packages/agent/src/server/agent-server.ts b/packages/agent/packages/agent/src/server/agent-server.tsindex 450492d87910..8a9ddec274ec 100644--- a/packages/agent/packages/agent/src/server/agent-server.ts+++ b/packages/agent/packages/agent/src/server/agent-server.ts@@ -64,6 +64,8 @@ import {import { appendRtkGuidanceForCodex } from "@posthog/harness/extensions/rtk";import {buildStoreSkillsInstructions,+ NO_STORE_SKILLS,+ type StoreSkillsListing,syncStoreSkills,} from "@posthog/harness/extensions/skills-store";import {@@ -562,7 +564,7 @@ export class AgentServer {// run's state when the first message arrives (see resolveActivationSettings).private prewarmedRun = false;private prewarmedStartupTurnPending = false;- private storeSkillsInstalledCount = 0;+ private storeSkills: StoreSkillsListing = NO_STORE_SKILLS;private storeSkillsActivationResolved = false;private agentInstructions: string | null = null;private autoPublishStateResolved = false;@@ -4434,7 +4436,7 @@ export class AgentServer {runId: string,runState: TaskRunState | null,): Promise<void> {- this.storeSkillsInstalledCount = await syncStoreSkills(+ this.storeSkills = await syncStoreSkills(runState,{ taskId, runId },this.logger,@@ -4676,13 +4678,20 @@ export class AgentServer {const context: string[] = [];if (shouldResolveStoreSkills) {const { task_id: taskId, run_id: runId } = this.session.payload;- const previousCount = this.storeSkillsInstalledCount;+ const previousInstructions = buildStoreSkillsInstructions(+ this.storeSkills,+ );await this.installStoreSkills(taskId, runId, state ?? null);this.storeSkillsActivationResolved = true;- if (previousCount === 0 && this.storeSkillsInstalledCount > 0) {- context.push(- buildStoreSkillsInstructions(this.storeSkillsInstalledCount).trim(),- );+ const storeSkillsInstructions = buildStoreSkillsInstructions(+ this.storeSkills,+ );+ // The system prompt still carries the prewarm section, so only a changed one is worth sending.+ if (+ storeSkillsInstructions &&+ storeSkillsInstructions !== previousInstructions+ ) {+ context.push(storeSkillsInstructions.trim());}const instructions = await new AgentInstructionFiles(this.logger).sync(state ?? null,@@ -4816,7 +4825,7 @@ export class AgentServer {projectId: this.config.projectId,repositoryAttached: Boolean(this.config.repositoryPath),shouldAutoPublish: this.shouldAutoPublishCloudChanges(),- storeSkillsInstalledCount: this.storeSkillsInstalledCount,+ storeSkills: this.storeSkills,taskId: this.config.taskId,taskRepositories: this.taskRepositories,});diff --git a/packages/agent/packages/agent/src/server/pi-agent-server.ts b/packages/agent/packages/agent/src/server/pi-agent-server.tsindex 5c925fee4fd7..18843e68f105 100644--- a/packages/agent/packages/agent/src/server/pi-agent-server.ts+++ b/packages/agent/packages/agent/src/server/pi-agent-server.ts@@ -693,7 +693,7 @@ export class PiAgentServer {});seedRunUsage(this.runUsage, launch.tokenUsage);// Before the prompt: its skills-store section counts the stubs on disk.- const storeSkillsInstalledCount = await syncStoreSkills(+ const storeSkills = await syncStoreSkills(launch.runState,{ taskId: payload.task_id, runId: payload.run_id },this.logger,@@ -707,9 +707,7 @@ export class PiAgentServer {typeof this.config.claudeCode?.systemPrompt === "string"? this.config.claudeCode.systemPrompt: this.config.claudeCode?.systemPrompt?.append;- const storeSkillsInstructions = buildStoreSkillsInstructions(- storeSkillsInstalledCount,- );+ const storeSkillsInstructions = buildStoreSkillsInstructions(storeSkills);const additionalInstructions =`${configuredSystemPrompt ?? ""}${storeSkillsInstructions}` || undefined;// A repo-less run gets the tools to discover and clone a repository, and thediff --git a/packages/agent/packages/harness/src/extensions/skills-store/index.ts b/packages/agent/packages/harness/src/extensions/skills-store/index.tsindex 5c2a906ee851..d38f2f31e05e 100644--- a/packages/agent/packages/harness/src/extensions/skills-store/index.ts+++ b/packages/agent/packages/harness/src/extensions/skills-store/index.ts@@ -2,13 +2,18 @@ export {buildStoreSkillsInstructions,getStoreSkillRoots,hasStoreMarker,+ type InstallStoreSkillStubsOptions,installStoreSkillStubs,listStoreSkillStubs,+ NO_STORE_SKILLS,removeStoreSkillStubs,+ renderStoreBridgeSkill,renderStoreSkillStub,+ STORE_BRIDGE_SKILL_NAME,type StoreSkillRootsOptions,type StoreSkillsInstallError,type StoreSkillsInstallResult,+ type StoreSkillsListing,type StoreSkillsLogger,type StoreSkillsSyncContext,syncStoreSkills,diff --git a/packages/agent/packages/harness/src/extensions/skills-store/store-skills.test.ts b/packages/agent/packages/harness/src/extensions/skills-store/store-skills.test.tsindex de3359b73d31..71afd79c94f1 100644--- a/packages/agent/packages/harness/src/extensions/skills-store/store-skills.test.ts+++ b/packages/agent/packages/harness/src/extensions/skills-store/store-skills.test.ts@@ -17,6 +17,7 @@ import {installStoreSkillStubs,listStoreSkillStubs,removeStoreSkillStubs,+ renderStoreBridgeSkill,renderStoreSkillStub,syncStoreSkills,} from "./store-skills";@@ -126,6 +127,7 @@ describe("store skills", () => {expect(result).toEqual({installed: ["tam-quota-forecast", "release-notes"],+ bridge: false,collisions: [],removed: [],rejected: 0,@@ -214,6 +216,7 @@ describe("store skills", () => {"half-written","store-guide",],+ bridge: false,collisions: ["querying-posthog-data","release-notes",@@ -463,23 +466,99 @@ describe("store skills", () => {await expect(syncStoreSkills(- { store_skills: [stub("one"), stub("two")] },+ { store_skills: [stub("one"), stub("two")], store_skills_bridge: true },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);+ ).resolves.toEqual({ installedCount: 2, bridge: true });+ await expect(+ syncStoreSkills(null, context, logger, roots),+ ).resolves.toEqual({ installedCount: 2, bridge: true });+ // A user who owns no skills still gets the bridge, and it survives the pruning of their old stubs.+ await expect(+ syncStoreSkills(+ { store_skills: [], store_skills_bridge: true },+ context,+ logger,+ roots,+ ),+ ).resolves.toEqual({ installedCount: 0, bridge: true });await expect(exists(join(roots[0], "one", "SKILL.md"))).resolves.toBe(false,);+ await expect(exists(join(roots[0], "phs", "SKILL.md"))).resolves.toBe(true);+ await expect(syncStoreSkills({}, context, logger, roots)).resolves.toEqual({+ installedCount: 0,+ bridge: false,+ });+ await expect(exists(join(roots[0], "phs", "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");+ it.each([+ [+ "a team skill of that name, over an earlier bridge",+ renderStoreBridgeSkill(),+ [stub("phs")],+ "metadata:\n version: '3'",+ { installed: ["phs"], bridge: false },+ ],+ [+ "a local skill of that name",+ "---\nname: phs\n---\nThe user's own bridge.",+ [],+ "The user's own bridge.",+ { installed: [], bridge: false },+ ],+ [+ "nothing, so a team stub from an earlier session",+ renderStoreSkillStub(stub("phs")),+ [],+ "role: bridge",+ { installed: [], bridge: true },+ ],+ ])(+ "gives the phs directory to %s",+ async (_label, onDisk, stubs, expectedText, expected) => {+ const home = await temporaryHome();+ const [claudeRoot] = rootsFor(home);+ await writeSkill(claudeRoot, "phs", onDisk);++ const result = await installStoreSkillStubs(stubs, [claudeRoot], {+ bridge: true,+ });++ expect(result).toMatchObject({ ...expected, errors: [] });+ await expect(+ readFile(join(claudeRoot, "phs", "SKILL.md"), "utf-8"),+ ).resolves.toContain(expectedText);+ },+ );++ it.each([+ [{ installedCount: 0, bridge: false }, [], ["skill-get", "/phs"]],+ [+ { installedCount: 3, bridge: false },+ ["3 of the user's", "skill-get"],+ ["/phs"],+ ],+ [+ { installedCount: 0, bridge: true },+ ["/phs <skill-name>"],+ ["of the user's"],+ ],+ [{ installedCount: 3, bridge: true }, ["3 of the user's", "/phs list"], []],+ ])("builds the prompt section for %o", (listing, present, absent) => {+ const instructions = buildStoreSkillsInstructions(listing);++ expect(instructions === "").toBe(present.length === 0);+ for (const text of present) {+ expect(instructions).toContain(text);+ }+ for (const text of absent) {+ expect(instructions).not.toContain(text);+ }});});diff --git a/packages/agent/packages/harness/src/extensions/skills-store/store-skills.ts b/packages/agent/packages/harness/src/extensions/skills-store/store-skills.tsindex 377ec88b7272..4453c3686884 100644--- a/packages/agent/packages/harness/src/extensions/skills-store/store-skills.ts+++ b/packages/agent/packages/harness/src/extensions/skills-store/store-skills.ts@@ -24,6 +24,10 @@ const METADATA_KEY_RE = /^metadata:\s*(#.*)?$/;const SOURCE_VALUE_RE = new RegExp(`^source:\\s*['"]?${STORE_SKILL_SOURCE}['"]?\\s*(#.*)?$`,);+// The bridge also carries the store marker, so pruning and replacement treat it as a stub.+const BRIDGE_ROLE_VALUE_RE = /^role:\s*['"]?bridge['"]?\s*(#.*)?$/;++export const STORE_BRIDGE_SKILL_NAME = "phs";// 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@@ -34,6 +38,8 @@ const MAX_SKILL_NAME_LENGTH = 64;export interface StoreSkillsInstallResult {/** Skill names written to at least one skill root. */installed: string[];+ /** True when the bridge was written to at least one skill root. */+ bridge: boolean;/** 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. */@@ -50,6 +56,17 @@ export interface StoreSkillsInstallError {message: string;}+export interface StoreSkillsListing {+ /** Stubs for the user's own store skills. The bridge is not one of them. */+ installedCount: number;+ bridge: boolean;+}++export const NO_STORE_SKILLS: StoreSkillsListing = {+ installedCount: 0,+ bridge: false,+};+export interface StoreSkillRootsOptions {home?: string;/** Where Claude Code keeps user state; `CLAUDE_CONFIG_DIR` moves it off `~/.claude`. */@@ -103,6 +120,43 @@ export function renderStoreSkillStub(stub: StoreSkillStub): string {].join("\n");}+/** Reads and runs skills only, because a `read_only` run cannot write to the store. */+export function renderStoreBridgeSkill(): string {+ const name = STORE_BRIDGE_SKILL_NAME;+ const description =+ "Run any skill from the PostHog skills store by name, including a teammate's skill that is not installed here. " ++ `Use when the user types /${name} <skill-name> [arguments], asks to run a store skill that is not installed, or asks which store skills exist.`;+ return [+ "---",+ `name: ${name}`,+ `description: ${JSON.stringify(description)}`,+ "metadata:",+ ` source: ${STORE_SKILL_SOURCE}`,+ " role: bridge",+ "---",+ "",+ "This skill runs skills from the PostHog skills store. It only reads and runs them. To create, edit or publish a skill, follow the `skills-store` guidance instead.",+ "",+ `Read the text the user gave after \`${name}\`. The first word selects what to do, and the rest is the arguments. Run every call below with the PostHog MCP \`exec\` tool.`,+ "",+ "## List skills",+ "",+ 'When there is no text, or the first word is `list`, run `call skill-list {}`. When a keyword follows `list`, run `call skill-list {"search": "<keyword>"}` instead. Show each skill\'s name and description, then stop.',+ "",+ "## Run a skill",+ "",+ "Otherwise the first word is the name of the skill to run.",+ "",+ '1. Run `call skill-get {"skill_name": "<name>"}`. 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 task, with the rest of the user's text as its arguments.",+ '4. When the body references a bundled file, fetch it with `call skill-file-get {"skill_name": "<name>", "file_path": "<path>", "version": <version>}` only when you need it.',+ "",+ 'If `skill-get` finds no skill with that name, run `call skill-list {"search": "<name>"}` and show the closest matches. Never improvise a skill you could not fetch.',+ "",+ ].join("\n");+}+export interface StoreSkillsLogger {info(message: string, data?: unknown): void;warn(message: string, data?: unknown): void;@@ -114,34 +168,36 @@ export interface StoreSkillsSyncContext {}/**- * 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.+ * Bring the skill roots in line with a run's `store_skills` and+ * `store_skills_bridge`, and return what 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.+ * A null run state says nothing about access, so stubs and the bridge 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> {+): Promise<StoreSkillsListing> {try {if (runState === null || runState === undefined) {- const retained = await listStoreSkillStubs(roots);- if (retained.length > 0) {+ const retained = await readStoreListing(roots);+ if (retained.names.length > 0 || retained.bridge) {logger.warn("Run context unavailable, keeping earlier skills store stubs",- { ...context, retained },+ { ...context, retained: retained.names, bridge: retained.bridge },);}- return retained.length;+ return { installedCount: retained.names.length, bridge: retained.bridge };}const stubs = runState.store_skills ?? [];- if (stubs.length === 0) {+ const bridge = runState.store_skills_bridge === true;+ if (stubs.length === 0 && !bridge) {const cleanup = await removeStoreSkillStubs(roots);if (cleanup.removed.length > 0 || cleanup.errors.length > 0) {logger.info("Removed stale skills store stubs", {@@ -150,25 +206,33 @@ export async function syncStoreSkills(errors: cleanup.errors,});}- return 0;+ return NO_STORE_SKILLS;}- const install = await installStoreSkillStubs(stubs, roots);+ const install = await installStoreSkillStubs(stubs, roots, { bridge });logger.info("Installed skills store stubs", {...context,listed: stubs.length,installed: install.installed,+ bridge: install.bridge,collisions: install.collisions,removed: install.removed,rejected: install.rejected,errors: install.errors,});- return install.installed.length;+ return {+ installedCount: install.installed.length,+ bridge: install.bridge,+ };} catch (error) {logger.warn("Skills store install failed", { ...context, error });- return 0;+ return NO_STORE_SKILLS;}}+export interface InstallStoreSkillStubsOptions {+ bridge?: boolean;+}+/*** 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@@ -179,16 +243,27 @@ export async function syncStoreSkills(** 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.+ *+ * The bridge follows the same rules, so it never replaces a non-store skill+ * named `phs`, and a team skill of that name in `stubs` replaces it.*/export async function installStoreSkillStubs(stubs: readonly StoreSkillStub[],skillRoots: string[],+ options: InstallStoreSkillStubsOptions = {},): Promise<StoreSkillsInstallResult> {const { skills, rejected } = selectInstallable(stubs);+ const wantBridge =+ options.bridge === true && !skills.has(STORE_BRIDGE_SKILL_NAME);+ const keep = new Set<string>(skills.keys());+ if (wantBridge) {+ keep.add(STORE_BRIDGE_SKILL_NAME);+ }const written = new Set<string>();const collided = new Set<string>();const removed = new Set<string>();const errors: StoreSkillsInstallError[] = [];+ let bridgeWritten = false;for (const root of skillRoots) {for (const [skillName, stub] of skills) {@@ -198,13 +273,24 @@ export async function installStoreSkillStubs(collided.add(skillName);continue;}- await replaceStub(root, skillName, stub);+ await replaceStub(root, skillName, renderStoreSkillStub(stub));written.add(skillName);} catch (error) {errors.push({ root, skillName, message: errorMessage(error) });}}- const pruned = await pruneStaleStubs(root, skills);+ if (wantBridge) {+ const skillName = STORE_BRIDGE_SKILL_NAME;+ try {+ if (await isReplaceable(join(root, skillName))) {+ await replaceStub(root, skillName, renderStoreBridgeSkill());+ bridgeWritten = true;+ }+ } catch (error) {+ errors.push({ root, skillName, message: errorMessage(error) });+ }+ }+ const pruned = await pruneStaleStubs(root, keep);for (const name of pruned.removed) {removed.add(name);}@@ -213,6 +299,7 @@ export async function installStoreSkillStubs(return {installed: [...skills.keys()].filter((name) => written.has(name)),+ bridge: bridgeWritten,collisions: [...skills.keys()].filter((name) => collided.has(name)),removed: [...removed].sort(),rejected,@@ -221,8 +308,8 @@ export async function installStoreSkillStubs(}/**- * Remove every stub the store wrote earlier. Used when the run lists no store- * skills, so stale discovery does not outlive access.+ * Remove every stub the store wrote earlier, the bridge included. Used when+ * the run lists no store skills, so stale discovery does not outlive access.*/export async function removeStoreSkillStubs(skillRoots: string[],@@ -230,7 +317,7 @@ export async function removeStoreSkillStubs(const removed = new Set<string>();const errors: StoreSkillsInstallError[] = [];for (const root of skillRoots) {- const pruned = await pruneStaleStubs(root, new Map());+ const pruned = await pruneStaleStubs(root, new Set());for (const name of pruned.removed) {removed.add(name);}@@ -239,30 +326,54 @@ export async function removeStoreSkillStubs(return { removed: [...removed].sort(), errors };}-/** Names of the store stubs on disk across the roots, for a session that keeps the previous install. */+/** Names of the store stubs on disk across the roots, the bridge excluded, for a session that keeps the previous install. */export async function listStoreSkillStubs(skillRoots: string[],): Promise<string[]> {+ return (await readStoreListing(skillRoots)).names;+}++async function readStoreListing(+ skillRoots: string[],+): Promise<{ names: string[]; bridge: boolean }> {const names = new Set<string>();+ let bridge = false;for (const root of skillRoots) {try {- for (const name of await listStoreStubs(root)) {- names.add(name);+ for (const stub of await listStoreStubs(root)) {+ if (stub.bridge) {+ bridge = true;+ } else {+ names.add(stub.name);+ }}} catch {// A root that cannot be read has no stubs to report.}}- return [...names].sort();+ return { names: [...names].sort(), bridge };}-export function buildStoreSkillsInstructions(installedCount: number): string {- if (installedCount === 0) {+export function buildStoreSkillsInstructions(+ listing: StoreSkillsListing,+): string {+ const sections: string[] = [];+ if (listing.installedCount > 0) {+ sections.push(+ `${listing.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.`,+ );+ }+ if (listing.bridge) {+ sections.push(+ `To run a store skill that is not installed here, such as a teammate's, use the \`${STORE_BRIDGE_SKILL_NAME}\` skill: \`/${STORE_BRIDGE_SKILL_NAME} <skill-name> [arguments]\` runs it, and \`/${STORE_BRIDGE_SKILL_NAME} list [keyword]\` lists the store.`,+ );+ }+ if (sections.length === 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.`;+${sections.join("\n")}`;}function selectInstallable(stubs: readonly StoreSkillStub[]): {@@ -304,7 +415,7 @@ function isWellFormedSkillName(name: string): boolean {async function replaceStub(root: string,skillName: string,- stub: StoreSkillStub,+ skillMd: string,): 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.@@ -312,7 +423,7 @@ async function replaceStub(try {await rm(stagingDir, { recursive: true, force: true });await mkdir(stagingDir, { recursive: true });- await writeFile(join(stagingDir, "SKILL.md"), renderStoreSkillStub(stub));+ await writeFile(join(stagingDir, "SKILL.md"), skillMd);await rm(skillDir, { recursive: true, force: true });await rename(stagingDir, skillDir);} catch (error) {@@ -328,13 +439,15 @@ async function replaceStub(*/async function pruneStaleStubs(root: string,- keep: ReadonlyMap<string, unknown>,+ keep: ReadonlySet<string>,): Promise<Pick<StoreSkillsInstallResult, "removed" | "errors">> {const removed: string[] = [];const errors: StoreSkillsInstallError[] = [];let stale: string[];try {- stale = (await listStoreStubs(root)).filter((name) => !keep.has(name));+ stale = (await listStoreStubs(root))+ .map((stub) => stub.name)+ .filter((name) => !keep.has(name));} catch (error) {return {removed,@@ -352,8 +465,10 @@ async function pruneStaleStubs(return { removed, errors };}-/** Names of the directories under `root` whose SKILL.md carries the store marker. */-async function listStoreStubs(root: string): Promise<string[]> {+/** The directories under `root` whose SKILL.md carries the store marker. */+async function listStoreStubs(+ root: string,+): Promise<{ name: string; bridge: boolean }[]> {const entries = await readdir(root, { withFileTypes: true }).catch((error: NodeJS.ErrnoException) => {if (error.code === "ENOENT") {@@ -362,13 +477,20 @@ async function listStoreStubs(root: string): Promise<string[]> {throw error;},);- const names: string[] = [];+ const stubs: { name: string; bridge: boolean }[] = [];for (const entry of entries) {- if (entry.isDirectory() && (await isStoreStub(join(root, entry.name)))) {- names.push(entry.name);+ if (!entry.isDirectory()) {+ continue;+ }+ const skillMd = await readSkillMd(join(root, entry.name));+ if (skillMd !== null && hasStoreMarker(skillMd)) {+ stubs.push({+ name: entry.name,+ bridge: hasMetadataEntry(skillMd, BRIDGE_ROLE_VALUE_RE),+ });}}- return names;+ return stubs;}/**@@ -403,6 +525,10 @@ function readSkillMd(skillDir: string): Promise<string | null> {* would be a dependency just for this check.*/export function hasStoreMarker(skillMd: string): boolean {+ return hasMetadataEntry(skillMd, SOURCE_VALUE_RE);+}++function hasMetadataEntry(skillMd: string, entryRe: RegExp): boolean {const frontmatter = FRONTMATTER_RE.exec(skillMd)?.[1];if (frontmatter === undefined) {return false;@@ -422,7 +548,7 @@ export function hasStoreMarker(skillMd: string): boolean {return false;}blockIndent ??= indent;- if (indent === blockIndent && SOURCE_VALUE_RE.test(line.trim())) {+ if (indent === blockIndent && entryRe.test(line.trim())) {return true;}}diff --git a/packages/agent/packages/harness/src/extensions/task-system-prompt/cloud.ts b/packages/agent/packages/harness/src/extensions/task-system-prompt/cloud.tsindex 3220889d7da2..ae4dbc3618b5 100644--- a/packages/agent/packages/harness/src/extensions/task-system-prompt/cloud.ts+++ b/packages/agent/packages/harness/src/extensions/task-system-prompt/cloud.ts@@ -4,7 +4,10 @@ import {SIGNED_MERGE_QUALIFIED_TOOL_NAME,SIGNED_REWRITE_QUALIFIED_TOOL_NAME,} from "../local-tools";-import { buildStoreSkillsInstructions } from "../skills-store";+import {+ buildStoreSkillsInstructions,+ type StoreSkillsListing,+} from "../skills-store";import {buildTaskSummaryInstructions,TASK_SUMMARY_TOOL_NAME,@@ -20,7 +23,7 @@ export interface CloudTaskPromptOptions {hasGithubToken: boolean;repositoryAttached: boolean;shouldAutoPublish: boolean;- storeSkillsInstalledCount: number;+ storeSkills: StoreSkillsListing;taskId: string;taskRepositories: string[];}@@ -188,7 +191,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.options.deliveryInstructions ?? ""}${this.buildGithubAccessInstructions(hasGithubToken)}${buildStoreSkillsInstructions(this.options.storeSkillsInstalledCount)}+ const commonInstructions = `${signedCommitInstructions}${stackInstructions}${prLinkInstructions}${shellEfficiencyInstructions}${artifactInstructions}${this.options.deliveryInstructions ?? ""}${this.buildGithubAccessInstructions(hasGithubToken)}${buildStoreSkillsInstructions(this.options.storeSkills)}${buildTaskSummaryInstructions()}`;// The shared block above is shaped for a run that ends with work landed. Adiff --git a/products/skills/skills/skills-store/SKILL.md b/products/skills/skills/skills-store/SKILL.mdindex e0901804092b..270a1d176037 100644--- a/products/skills/skills/skills-store/SKILL.md+++ b/products/skills/skills/skills-store/SKILL.md@@ -274,6 +274,19 @@ The bridge is intentionally minimal — it just routes to the MCP tools. The rea> **Agent-specific setup:** Where to save this depends on your agent. For Claude Code, save as `~/.claude/skills/phs/SKILL.md`. For other agents, consult your agent's docs on local skill or slash command configuration.+### In a PostHog task sandbox++A PostHog task sandbox installs its own `phs` bridge when the skills store is on for the run, so do not write one there.+It reads and runs skills only:++- `/phs <skill-name> [arguments]` fetches the skill with `skill-get`, pages through the body, pins the version, and follows it.+- `/phs` or `/phs list [keyword]` calls `skill-list`.+- A name `skill-get` cannot find triggers a `skill-list` search for close matches.++Use it to run a teammate's skill, because the sandbox lists only the user's own skills as local skills.+For writes, use the tools in this skill directly.+A team skill named `phs` takes precedence over the sandbox bridge, and so does a local skill of that name.+## Default behavior- **Always prefer PostHog MCP** for skill storage and retrievaldiff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.pyindex 0a3c5dc7e6ff..dd03a8751cbb 100644--- a/products/tasks/backend/constants.py+++ b/products/tasks/backend/constants.py@@ -60,6 +60,8 @@ PR_LOOP_ENABLED_STATE_KEY = "pr_loop_enabled"TIMED_OUT_INACTIVITY_STATE_KEY = "timed_out_inactivity"# The skills-store stubs the sandbox agent writes into its skill roots at session start.STORE_SKILLS_STATE_KEY = "store_skills"+# Separate from `store_skills`, which is also empty when the store is on and the user owns no skills.+STORE_SKILLS_BRIDGE_STATE_KEY = "store_skills_bridge"AGENT_INSTRUCTIONS_STATE_KEY = "agent_instructions"# Matches the cap PostHog Code applies to its local personalization.AGENT_INSTRUCTIONS_MAX_LENGTH = 20_000diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 7557ce07b502..db93c7769932 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -637,6 +637,7 @@ _TASK_RUN_AGENT_STATE_KEYS = frozenset("end_run_when_done","initial_prompt_override","store_skills",+ "store_skills_bridge","systemPrompt",})diff --git a/products/tasks/backend/logic/services/store_skills.py b/products/tasks/backend/logic/services/store_skills.pyindex 6d828f72983e..bb73b2cc7a3a 100644--- a/products/tasks/backend/logic/services/store_skills.py+++ b/products/tasks/backend/logic/services/store_skills.py@@ -7,6 +7,10 @@ selection runs here, in the worker, so the sandbox makes no request of its own fsession boot path. The list is the acting user's, so it is resolved again whenever that userchanges: a warm run activated by someone other than its creator, or a shared Slack task whosenext message comes from another member.++The same flag also turns on the ``phs`` bridge skill, which runs any store skill the user can read,+including a teammate's skill that is not in the list. ``TaskRun.state["store_skills_bridge"]`` tells+the sandbox to write it."""from typing import Any@@ -25,7 +29,7 @@ from products.skills.backend.marketplace.adapters import ()from products.skills.backend.marketplace.packaging import DEFAULT_BUNDLE_SKILLSfrom products.skills.backend.models.skills import LLMSkill-from products.tasks.backend.constants import STORE_SKILLS_STATE_KEY+from products.tasks.backend.constants import STORE_SKILLS_BRIDGE_STATE_KEY, STORE_SKILLS_STATE_KEYfrom products.tasks.backend.models import TaskRunlogger = structlog.get_logger(__name__)@@ -35,10 +39,15 @@ logger = structlog.get_logger(__name__)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``.+def disabled_store_skills_state() -> dict[str, Any]:+ """The run state updates that remove every store stub and the bridge from the sandbox."""+ return {STORE_SKILLS_STATE_KEY: [], STORE_SKILLS_BRIDGE_STATE_KEY: False}+++def resolve_store_skills_state(team: Team, user: User, *, run_id: str) -> dict[str, Any] | None:+ """The run state updates for a run's store skills: the ``store_skills`` entries and the bridge switch.- ``None`` means the flag service did not answer. The caller then leaves the key alone, so a+ ``None`` means the flag service did not answer. The caller then leaves both keys alone, so asandbox that resumes with stubs from an earlier session keeps them instead of losing them to anoutage. ``user`` is whoever the sandbox's PostHog credential belongs to, because that is theidentity ``skill-get`` will run as.@@ -53,7 +62,7 @@ def resolve_store_skills(team: Team, user: User, *, run_id: str) -> list[dict[stlogger.warning("store_skills_flag_unavailable", run_id=run_id, team_id=team.id)return Noneif not flag_value:- return []+ return disabled_store_skills_state()readable_skills = UserAccessControl(user=user, team=team).filter_queryset_by_access_level(LLMSkill.objects.filter(team=team), resource="llm_skill"@@ -67,34 +76,43 @@ def resolve_store_skills(team: Team, user: User, *, run_id: str) -> list[dict[stdropped=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- ]+ return {+ STORE_SKILLS_STATE_KEY: [+ {+ "name": stub.name,+ "description": " ".join(stub.description.split())[:STORE_SKILL_DESCRIPTION_MAX_CHARS],+ "version": stub.version,+ }+ for stub in selection.stubs+ ],+ STORE_SKILLS_BRIDGE_STATE_KEY: True,+ }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.+ """Rewrite ``store_skills`` and the bridge switch 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 ithad. The sandbox re-reads the run after the transition and brings its stubs in line."""run_id = str(task_run.id)try:- store_skills = (- []+ updates = (+ disabled_store_skills_state()if (task_run.state or {}).get("include_live_context") is Falseor (task_run.state or {}).get("disable_skills") is True- else resolve_store_skills(task_run.task.team, user, run_id=run_id)+ else resolve_store_skills_state(task_run.task.team, user, run_id=run_id))- if store_skills is None:+ if updates is None:return- TaskRun.update_state_atomic(task_run.id, updates={STORE_SKILLS_STATE_KEY: store_skills})+ TaskRun.update_state_atomic(task_run.id, updates=updates)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))+ logger.info(+ "store_skills_refreshed",+ run_id=run_id,+ reason=reason,+ included=len(updates[STORE_SKILLS_STATE_KEY]),+ bridge=updates[STORE_SKILLS_BRIDGE_STATE_KEY],+ )diff --git a/products/tasks/backend/logic/services/test_store_skills.py b/products/tasks/backend/logic/services/test_store_skills.pyindex ce4928bbf7a4..9fa09557cd58 100644--- a/products/tasks/backend/logic/services/test_store_skills.py+++ b/products/tasks/backend/logic/services/test_store_skills.py@@ -4,7 +4,7 @@ from unittest.mock import patchfrom parameterized import parameterizedfrom products.skills.backend.models.skills import LLMSkill-from products.tasks.backend.constants import STORE_SKILLS_STATE_KEY+from products.tasks.backend.constants import STORE_SKILLS_BRIDGE_STATE_KEY, STORE_SKILLS_STATE_KEYfrom products.tasks.backend.logic.services.store_skills import refresh_store_skills_statefrom products.tasks.backend.models import Task, TaskRun@@ -49,7 +49,10 @@ class TestRefreshStoreSkillsState(BaseTest):assert run.state[STORE_SKILLS_STATE_KEY] == [{"name": "invoice-review", "description": "Check invoice failures.", "version": 1}]+ assert run.state[STORE_SKILLS_BRIDGE_STATE_KEY] is Trueelif expected == "unchanged":assert run.state[STORE_SKILLS_STATE_KEY] == [{"name": "stale-live-skill"}]+ assert STORE_SKILLS_BRIDGE_STATE_KEY not in run.stateelse:assert run.state[STORE_SKILLS_STATE_KEY] == []+ assert run.state[STORE_SKILLS_BRIDGE_STATE_KEY] is Falsediff --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 0f4744d209e8..011f6ce1e5f2 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@@ -32,7 +32,6 @@ from products.tasks.backend.constants import (PI_ACP_FEATURE_FLAG,PR_LOOP_ENABLED_STATE_KEY,RTK_DISABLED_FEATURE_FLAG,- STORE_SKILLS_STATE_KEY,SUBSCRIPTION_PLAN_NAMES,is_same_run_resume_state,vm_sandbox_allowed_origin_products,@@ -69,7 +68,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_skills+from products.tasks.backend.logic.services.store_skills import disabled_store_skills_state, resolve_store_skills_statefrom products.tasks.backend.logic.stream.redis_stream import get_task_run_stream_generationfrom products.tasks.backend.models import SandboxCustomImage, SandboxEnvironment, Task, TaskRunfrom products.tasks.backend.redis import run_uses_dedicated_stream@@ -1079,18 +1078,19 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro# 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.+ store_skills_updates: dict[str, Any] | Nonetry:if not include_live_context or state.get("disable_skills") is True:- store_skills: list[dict[str, Any]] | None = []- state[STORE_SKILLS_STATE_KEY] = []+ store_skills_updates = disabled_store_skills_state()+ state.update(store_skills_updates)else:with StepTimer("store_skills"):- store_skills = resolve_store_skills(team, actor_user or task.created_by, run_id=run_id)+ store_skills_updates = resolve_store_skills_state(team, actor_user or task.created_by, run_id=run_id)except Exception as 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+ store_skills_updates = None+ if store_skills_updates is not None:+ state_updates.update(store_skills_updates)# The sandbox writes these as the agent's user-level AGENTS.md / CLAUDE.md at session start.# Best-effort for the same reason as store skills.state_remove_keys: list[str] = []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 78c090bd49cd..b78b5022367c 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@@ -26,6 +26,7 @@ from products.tasks.backend.constants import (HOGLAND_SANDBOX_FEATURE_FLAG,MODAL_VM_SANDBOX_FEATURE_FLAG,RTK_DISABLED_FEATURE_FLAG,+ STORE_SKILLS_BRIDGE_STATE_KEY,STORE_SKILLS_STATE_KEY,vm_sandbox_allowed_origin_products,vm_sandbox_default_base_origin_products,@@ -894,7 +895,10 @@ class TestGetTaskProcessingContextActivity:assert environment.get("POSTHOG_CONTEXT_LAYER_PATH") == ("/tmp/workspace/context" if include_live_context is not False else None)- stored = TaskRun.objects.get(id=task_run.id).state[STORE_SKILLS_STATE_KEY]+ stored_state = TaskRun.objects.get(id=task_run.id).state+ stored = stored_state[STORE_SKILLS_STATE_KEY]+ expected_bridge = None if expected_state == "untouched" else expected_state == "resolved"+ assert stored_state.get(STORE_SKILLS_BRIDGE_STATE_KEY) == expected_bridgeif expected_state == "untouched":assert stored == [{"name": "from-last-session"}]elif expected_state == "resolved":diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.pyindex b3e7d55eb3a0..54a583f4dadb 100644--- a/products/tasks/backend/tests/test_facade.py+++ b/products/tasks/backend/tests/test_facade.py@@ -349,6 +349,7 @@ class TestFacadeReadsAndMappers(TestCase):"initial_prompt_override": "framed prompt","end_run_when_done": True,"store_skills": [{"name": "my-skill", "description": "Mine.", "version": 1}],+ "store_skills_bridge": True,"systemPrompt": {"type": "preset", "preset": "claude_code", "append": "PostHog AI"},"sandbox_jwt_kid": "secret","unknown_server_context": {"title": "Saved context"},@@ -372,6 +373,7 @@ class TestFacadeReadsAndMappers(TestCase):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_state+ assert ("store_skills_bridge" in detail.state) is include_agent_stateassert ("systemPrompt" in detail.state) is include_agent_stateassert "sandbox_jwt_kid" not in detail.stateassert "unknown_server_context" not in detail.state