: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(desktop): add product engineering guidance to hog (#83158)
Jonathan Mieloof831aec1279f
diff --git a/products/desktop/apps/code/electron-builder.ts b/products/desktop/apps/code/electron-builder.tsindex 03c49356cc36..17f53e71bdc6 100644--- a/products/desktop/apps/code/electron-builder.ts+++ b/products/desktop/apps/code/electron-builder.ts@@ -49,6 +49,7 @@ const config: Configuration = {".vite/build/plugins/posthog/**",".vite/build/codex-acp/**",".vite/build/grammars/**",+ ".vite/build/product-engineer/**",".vite/build/rpc-host.js",".vite/build/rpc-host.js.map",...asarUnpackGlobs,diff --git a/products/desktop/apps/code/vite-main-plugins.mts b/products/desktop/apps/code/vite-main-plugins.mtsindex 1fe97279c7fd..1d8e460fa139 100644--- a/products/desktop/apps/code/vite-main-plugins.mts+++ b/products/desktop/apps/code/vite-main-plugins.mts@@ -181,7 +181,23 @@ export function copyPiRpcHost(): Plugin {`[copy-pi-rpc-host] Unable to find Pi RPC host, required at runtime by createPiRpcClient. Build @posthog/agent first. Checked:\n ${candidates.join("\n ")}`,);}- copyFileSync(source, join(__dirname, ".vite/build/rpc-host.js"));+ const buildDirectory = join(__dirname, ".vite/build");+ const productEngineerResources = join(+ dirname(source),+ "product-engineer",+ );+ if (!existsSync(productEngineerResources)) {+ throw new Error(+ `[copy-pi-rpc-host] Unable to find product engineer resources at ${productEngineerResources}. Build @posthog/agent first.`,+ );+ }++ copyFileSync(source, join(buildDirectory, "rpc-host.js"));+ cpSync(+ productEngineerResources,+ join(buildDirectory, "product-engineer"),+ { recursive: true },+ );},};}diff --git a/products/desktop/package.json b/products/desktop/package.jsonindex 4b476d3caea4..0a1127402dc3 100644--- a/products/desktop/package.json+++ b/products/desktop/package.json@@ -37,7 +37,7 @@"clean": "pnpm -r clean","knip": "knip","skills:pull": "node scripts/pull-skills.mjs",- "hosthog:build": "pnpm install --frozen-lockfile --ignore-scripts --filter @posthog/web... && pnpm exec turbo build --filter=@posthog/web && ln -sfn apps/web/dist dist"+ "hosthog:build": "pnpm install --frozen-lockfile --ignore-scripts --filter @posthog/web... && SKIP_PRODUCT_ENGINEER_SKILLS_DOWNLOAD=1 pnpm exec turbo build --filter=@posthog/web && ln -sfn apps/web/dist dist"},"keywords": ["posthog",diff --git a/products/desktop/packages/agent/tsup.config.ts b/products/desktop/packages/agent/tsup.config.tsindex 2e98c6a95a49..60bb6d55d708 100644--- a/products/desktop/packages/agent/tsup.config.ts+++ b/products/desktop/packages/agent/tsup.config.ts@@ -48,6 +48,14 @@ function copyAssets() {const distDir = resolve(import.meta.dirname, "dist");const templatesDir = resolve(distDir, "templates");const claudeCliDir = resolve(distDir, "claude-cli");+ const productEngineerResourcesSource = resolve(+ import.meta.dirname,+ "../harness/dist/extensions/product-engineer",+ );+ const productEngineerResourcesTarget = resolve(+ distDir,+ "pi/product-engineer",+ );const enricherGrammarsSource = resolve(import.meta.dirname,"../enricher/grammars",@@ -56,6 +64,14 @@ function copyAssets() {mkdirSync(templatesDir, { recursive: true });mkdirSync(claudeCliDir, { recursive: true });+ if (!existsSync(productEngineerResourcesSource)) {+ throw new Error(+ `Missing product engineer resources at ${productEngineerResourcesSource}`,+ );+ }+ cpSync(productEngineerResourcesSource, productEngineerResourcesTarget, {+ recursive: true,+ });cpSync(enricherGrammarsSource, enricherGrammarsTarget, {recursive: true,});diff --git a/products/desktop/packages/harness/package.json b/products/desktop/packages/harness/package.jsonindex b4c4cc4dd891..c390039a6be2 100644--- a/products/desktop/packages/harness/package.json+++ b/products/desktop/packages/harness/package.json@@ -52,6 +52,14 @@"types": "./dist/extensions/posthog-provider/*.d.ts","import": "./dist/extensions/posthog-provider/*.js"},+ "./extensions/product-engineer": {+ "types": "./dist/extensions/product-engineer/index.d.ts",+ "import": "./dist/extensions/product-engineer/index.js"+ },+ "./extensions/product-engineer/*": {+ "types": "./dist/extensions/product-engineer/*.d.ts",+ "import": "./dist/extensions/product-engineer/*.js"+ },"./extensions/web-access": {"types": "./dist/extensions/web-access/extension.d.ts","import": "./dist/extensions/web-access/extension.js"@@ -107,6 +115,7 @@"@earendil-works/pi-tui": "catalog:","@modelcontextprotocol/sdk": "^1.29.0","@posthog/shared": "workspace:*",+ "fflate": "^0.8.2","lru-cache": "^11.1.0","turndown": "^7.2.4","typebox": "1.3.7",diff --git a/products/desktop/packages/harness/src/extensions/product-engineer/extension.test.ts b/products/desktop/packages/harness/src/extensions/product-engineer/extension.test.tsnew file mode 100644index 000000000000..6c17c7fd9815--- /dev/null+++ b/products/desktop/packages/harness/src/extensions/product-engineer/extension.test.ts@@ -0,0 +1,65 @@+import { readFileSync } from "node:fs";+import { fileURLToPath } from "node:url";+import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";+import { describe, expect, it } from "vitest";+import { createProductEngineerExtension } from "./extension";++const PRODUCT_ENGINEER_PROMPT = readFileSync(+ new URL("./prompts/product-engineer.md", import.meta.url),+ "utf8",+).trim();+const UPSTREAM_SYSTEM_PROMPT = "Upstream pi instructions that may change.";++type BeforeAgentStart = (event: { systemPrompt: string }) => {+ systemPrompt: string;+};+type ResourcesDiscover = () => { skillPaths: string[] };++function setupExtension(): {+ beforeAgentStart: BeforeAgentStart;+ instrumentationSkillsDirectory: string;+ resourcesDiscover: ResourcesDiscover;+} {+ const handlers = new Map<string, unknown>();+ const instrumentationSkillsDirectory = fileURLToPath(+ new URL(".", import.meta.url),+ );++ createProductEngineerExtension(instrumentationSkillsDirectory)({+ on: (event: string, handler: unknown) => handlers.set(event, handler),+ } as unknown as ExtensionAPI);++ return {+ beforeAgentStart: handlers.get("before_agent_start") as BeforeAgentStart,+ instrumentationSkillsDirectory,+ resourcesDiscover: handlers.get("resources_discover") as ResourcesDiscover,+ };+}++describe("createProductEngineerExtension", () => {+ it("exposes bundled instrumentation skills through resource discovery", () => {+ const { instrumentationSkillsDirectory, resourcesDiscover } =+ setupExtension();++ expect(resourcesDiscover()).toEqual({+ skillPaths: [instrumentationSkillsDirectory],+ });+ });++ it("adds product engineering guidance without changing the upstream prompt", () => {+ const { beforeAgentStart } = setupExtension();++ expect(beforeAgentStart({ systemPrompt: UPSTREAM_SYSTEM_PROMPT })).toEqual({+ systemPrompt: `${PRODUCT_ENGINEER_PROMPT}\n\n${UPSTREAM_SYSTEM_PROMPT}`,+ });+ });++ it("does not add product engineering guidance twice", () => {+ const { beforeAgentStart } = setupExtension();+ const firstResult = beforeAgentStart({+ systemPrompt: UPSTREAM_SYSTEM_PROMPT,+ });++ expect(beforeAgentStart(firstResult)).toEqual(firstResult);+ });+});diff --git a/products/desktop/packages/harness/src/extensions/product-engineer/extension.ts b/products/desktop/packages/harness/src/extensions/product-engineer/extension.tsnew file mode 100644index 000000000000..1ad5fee712cd--- /dev/null+++ b/products/desktop/packages/harness/src/extensions/product-engineer/extension.ts@@ -0,0 +1,44 @@+import { existsSync, readFileSync } from "node:fs";+import { fileURLToPath } from "node:url";+import type {+ ExtensionAPI,+ ExtensionFactory,+} from "@earendil-works/pi-coding-agent";++function resolveProductEngineerResource(relativePath: string): string {+ const adjacentPath = fileURLToPath(new URL(relativePath, import.meta.url));+ if (existsSync(adjacentPath)) {+ return adjacentPath;+ }+ return fileURLToPath(+ new URL(`./product-engineer/${relativePath}`, import.meta.url),+ );+}++const PRODUCT_ENGINEER_PROMPT = readFileSync(+ resolveProductEngineerResource("prompts/product-engineer.md"),+ "utf8",+).trim();++function addProductEngineerPrompt(systemPrompt: string): string {+ return systemPrompt.startsWith(PRODUCT_ENGINEER_PROMPT)+ ? systemPrompt+ : `${PRODUCT_ENGINEER_PROMPT}\n\n${systemPrompt}`;+}++export function createProductEngineerExtension(+ instrumentationSkillsDirectory = resolveProductEngineerResource("skills"),+): ExtensionFactory {+ return (pi: ExtensionAPI) => {+ pi.on("resources_discover", () => ({+ skillPaths: existsSync(instrumentationSkillsDirectory)+ ? [instrumentationSkillsDirectory]+ : [],+ }));+ pi.on("before_agent_start", (event) => ({+ systemPrompt: addProductEngineerPrompt(event.systemPrompt),+ }));+ };+}++export default createProductEngineerExtension();diff --git a/products/desktop/packages/harness/src/extensions/product-engineer/index.ts b/products/desktop/packages/harness/src/extensions/product-engineer/index.tsnew file mode 100644index 000000000000..8ab1b728d353--- /dev/null+++ b/products/desktop/packages/harness/src/extensions/product-engineer/index.ts@@ -0,0 +1 @@+export { default } from "./extension";diff --git a/products/desktop/packages/harness/src/extensions/product-engineer/prompts/product-engineer.md b/products/desktop/packages/harness/src/extensions/product-engineer/prompts/product-engineer.mdnew file mode 100644index 000000000000..29201a97c79b--- /dev/null+++ b/products/desktop/packages/harness/src/extensions/product-engineer/prompts/product-engineer.md@@ -0,0 +1,35 @@+Operate as an expert product engineer. Use PostHog as the default platform for understanding users, observing quality, and shipping changes safely:+- Start from the user problem, desired experience, and product context. Understand why the work matters before deciding what to build.+- Use available evidence such as user feedback, product data, support signals, market context, and company strategy. Ask for missing context when it would change the decision.+- Exercise product judgment. Help decide both what to build and how to build it instead of treating the request as a fixed specification.+- Choose the smallest valuable solution that creates a fast, useful feedback loop. Prototype, descope, and avoid polishing assumptions that real users have not validated.+- Own the complete experience across implementation, usability, reliability, privacy, security, rollout, documentation, and support. Do not stop when the code compiles or the narrow task is complete.+- Ship safely and learn from reality. Use tests, feature flags, staged rollouts, and experiments when they fit the risk and uncertainty.+- Define what success means and make it observable. Measure adoption, outcomes, and failures.+- Follow through after shipping. Inspect usage and feedback, iterate on what works, and remove complexity that does not earn its place.++Choose the smallest set of PostHog products that solves the user problem. Know PostHog's product catalog:+- Product Analytics: Analyze event-based user behavior with trends, funnels, retention, paths, and cohorts.+- Web Analytics: Measure website traffic, acquisition, pages, conversions, and performance.+- Session Replay: Record and replay real user sessions to see behavior and friction.+- Feature Flags: Control who gets features and manage progressive rollouts.+- Experiments: Run A/B tests and measure causal impact against product metrics.+- Surveys: Collect in-product user feedback and link responses to behavior.+- Error Tracking: Capture, group, and diagnose exceptions with user and session context.+- Managed warehouse: Use a PostHog-managed analytical Postgres database that combines PostHog and connected source data.+- Data pipelines: Send event and warehouse data to external destinations in real time or batch.+- PostHog AI: Query product data, build insights, write SQL, find replays, and explain findings in plain English.+- AI Observability: Trace LLM calls, prompts, responses, tools, latency, tokens, and cost.+- Logs: Ingest, search, and retain structured application logs.+- Workflows: Trigger automated messages and actions from product behavior.+- Inbox: Review and steer prioritized self-driving reports and pull requests before they ship.+- Replay Vision: Use AI to turn session recordings into structured, queryable data.++Use PostHog throughout the product loop:+- Before building, use `mcp` to inspect relevant PostHog project data, existing events, feature flags, errors, logs, traces, insights, and user feedback when they would improve the decision. Search before calling. Read or list before writing or creating, and reuse existing resources.+- Before adding instrumentation, inspect the existing PostHog SDK setup and invoke the matching bundled instrumentation skill. Do not install duplicate SDKs or create parallel initialization paths.+- Use product analytics for meaningful user actions and outcomes, not low-value implementation events. Never capture secrets, sensitive content, or unnecessary personal data.+- Use PostHog feature flags for uncertain or risky rollouts. Use PostHog error tracking, logs, and traces to make failures diagnosable. Use PostHog AI Observability for AI model calls.+- After shipping, use PostHog to verify adoption, outcomes, regressions, and rollout health. Let observed behavior drive the next iteration.++Prefer customer impact and product quality over technical novelty. Treat code as one tool for creating useful, measurable outcomes.diff --git a/products/desktop/packages/harness/src/extensions/registry.ts b/products/desktop/packages/harness/src/extensions/registry.tsindex 4b614d61e8d0..3d8fc11a04b1 100644--- a/products/desktop/packages/harness/src/extensions/registry.ts+++ b/products/desktop/packages/harness/src/extensions/registry.ts@@ -11,6 +11,7 @@ import type { PosthogMcpPolicyOptions } from "./posthog-mcp-policy/extension";import { createPosthogMcpPolicyExtension } from "./posthog-mcp-policy/extension";import { createPosthogProviderExtension } from "./posthog-provider/extension";import type { PosthogProviderOptions } from "./posthog-provider/provider";+import { createProductEngineerExtension } from "./product-engineer/extension";import { createWebAccessExtension } from "./web-access/extension";export type HarnessExtensionOptions = PosthogProviderOptions &@@ -27,6 +28,7 @@ interface HarnessExtension {const EXTENSIONS: HarnessExtension[] = [{ name: "hog-branding", create: createHogBrandingExtension },{ name: "posthog-provider", create: createPosthogProviderExtension },+ { name: "product-engineer", create: () => createProductEngineerExtension() },{ name: "web-access", create: createWebAccessExtension },{name: "mcp",diff --git a/products/desktop/packages/harness/tsup.config.ts b/products/desktop/packages/harness/tsup.config.tsindex 9b0cddbd82a5..ed5508250d21 100644--- a/products/desktop/packages/harness/tsup.config.ts+++ b/products/desktop/packages/harness/tsup.config.ts@@ -1,6 +1,78 @@-import { cp } from "node:fs/promises";+import { cp, mkdir, rm, writeFile } from "node:fs/promises";+import { dirname, join } from "node:path";+import { unzipSync } from "fflate";import { defineConfig } from "tsup";+const CONTEXT_MILL_SKILLS_URL =+ "https://github.com/PostHog/context-mill/releases/latest/download/skills-mcp-resources.zip";++function safeArchivePath(archivePath: string): string | null {+ const normalizedPath = archivePath.replaceAll("\\", "/");+ const segments = normalizedPath.split("/");+ if (+ normalizedPath.startsWith("/") ||+ normalizedPath.endsWith("/") ||+ segments.some((segment) => !segment || segment === "." || segment === "..")+ ) {+ return null;+ }+ return normalizedPath;+}++async function copyOmnibusSkills(targetDirectory: string): Promise<void> {+ const response = await fetch(CONTEXT_MILL_SKILLS_URL, {+ signal: AbortSignal.timeout(30_000),+ });+ if (!response.ok) {+ throw new Error(+ `Failed to download context-mill skills: ${response.status} ${response.statusText}`,+ );+ }++ await rm(targetDirectory, { recursive: true, force: true });+ await mkdir(targetDirectory, { recursive: true });++ const outerEntries = unzipSync(new Uint8Array(await response.arrayBuffer()));+ let copiedSkills = 0;+ for (const [archivePath, archiveContent] of Object.entries(outerEntries)) {+ const archiveName = archivePath.replaceAll("\\", "/").split("/").at(-1);+ if (!archiveName?.startsWith("omnibus-") || !archiveName.endsWith(".zip")) {+ continue;+ }++ const skillName = archiveName.slice("omnibus-".length, -".zip".length);+ if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(skillName)) {+ continue;+ }++ const skillDirectory = join(targetDirectory, skillName);+ await mkdir(skillDirectory, { recursive: true });+ const innerEntries = unzipSync(new Uint8Array(archiveContent));+ for (const [innerPath, innerContent] of Object.entries(innerEntries)) {+ const relativePath = safeArchivePath(innerPath);+ if (!relativePath) {+ continue;+ }++ const outputPath = join(skillDirectory, relativePath);+ await mkdir(dirname(outputPath), { recursive: true });+ if (relativePath.split("/").at(-1) === "SKILL.md") {+ const skill = new TextDecoder()+ .decode(innerContent)+ .replace(/^(name:\s*)omnibus-/m, "$1");+ await writeFile(outputPath, skill);+ } else {+ await writeFile(outputPath, innerContent);+ }+ }+ copiedSkills += 1;+ }++ if (copiedSkills === 0) {+ throw new Error("No omnibus skills found in the context-mill release");+ }+}+export default defineConfig({entry: ["src/index.ts",@@ -20,6 +92,8 @@ export default defineConfig({"src/extensions/posthog-provider/oauth.ts","src/extensions/posthog-provider/gateway.ts","src/extensions/posthog-provider/gateway-auth.ts",+ "src/extensions/product-engineer/extension.ts",+ "src/extensions/product-engineer/index.ts","src/extensions/posthog-mcp-policy/extension.ts","src/extensions/posthog-mcp-policy/index.ts","src/extensions/background-jobs/extension.ts",@@ -104,6 +178,14 @@ export default defineConfig({await cp("src/extensions/mcp/skills", "dist/extensions/mcp/skills", {recursive: true,});+ if (process.env.SKIP_PRODUCT_ENGINEER_SKILLS_DOWNLOAD !== "1") {+ await copyOmnibusSkills("dist/extensions/product-engineer/skills");+ }+ await cp(+ "src/extensions/product-engineer/prompts",+ "dist/extensions/product-engineer/prompts",+ { recursive: true },+ );await cp("src/extensions/workflow/skills","dist/extensions/workflow/skills",diff --git a/products/desktop/pnpm-lock.yaml b/products/desktop/pnpm-lock.yamlindex 421c30d4051a..ed36a84a0edd 100644--- a/products/desktop/pnpm-lock.yaml+++ b/products/desktop/pnpm-lock.yaml@@ -1092,6 +1092,9 @@ importers:'@posthog/shared':specifier: workspace:*version: link:../shared+ fflate:+ specifier: ^0.8.2+ version: 0.8.3lru-cache:specifier: ^11.1.0version: 11.2.5diff --git a/products/desktop/turbo.json b/products/desktop/turbo.jsonindex 39a681c6eb6a..d52813a9974f 100644--- a/products/desktop/turbo.json+++ b/products/desktop/turbo.json@@ -3,6 +3,7 @@"tasks": {"build": {"dependsOn": ["^build"],+ "env": ["SKIP_PRODUCT_ENGINEER_SKILLS_DOWNLOAD"],"outputs": ["dist/**", ".vite/**"]},"typecheck": {