#!/usr/bin/env node // Regenerates the Paperclip Cloud direct PostHog delivery fixtures from a // checkout of the private telemetry-backend repository. // // Usage: // git -C fetch origin // git -C archive --format=tar --prefix=tb/ origin/HEAD | tar -x -C // node scripts/generate-posthog-direct-fixtures.mjs /tb // // It writes two files under server/src/services/posthog-direct/: // - enum-fallbacks.generated.ts: the backend's unknown-enum fallback rules // (`x-normalize.unknown_enum_value`). Enum domains come from the shared // generated contract, so only the fallback rule lives here. // - __fixtures__/loader-golden.json: one collector envelope, the canonical // records the backend ingest produces for it, and the PostHog capture // messages its loader builds from them. The golden test compares the // server's direct builder against these messages. // // The backend modules used here have no external dependencies, so a plain // source checkout is enough. No network or AWS access is needed: Firehose and // DynamoDB are replaced by in-memory test clients the backend already supports. import { writeFile, mkdir } from "node:fs/promises"; import path from "node:path"; import { pathToFileURL, fileURLToPath } from "node:url"; import { createRequire } from "node:module"; const backendDir = process.argv[2]; if (!backendDir) { console.error("usage: node scripts/generate-posthog-direct-fixtures.mjs "); process.exit(1); } const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); const outDir = path.join(repoRoot, "server/src/services/posthog-direct"); const backendUrl = (rel) => pathToFileURL(path.join(path.resolve(backendDir), rel)).href; const manifest = createRequire(import.meta.url)(path.join(path.resolve(backendDir), "src/registry/generated/manifest.json")); // --- enum fallback table --------------------------------------------------- const fallbacks = {}; for (const [eventName, spec] of Object.entries(manifest.events).sort(([a], [b]) => a.localeCompare(b))) { const required = new Set(spec.required ?? []); for (const [key, prop] of Object.entries(spec.properties ?? {})) { const fallback = prop?.["x-normalize"]?.unknown_enum_value; if (fallback === undefined) continue; (fallbacks[eventName] ??= {})[key] = { fallback, required: required.has(key) }; } } const fallbackSource = `// GENERATED by scripts/generate-posthog-direct-fixtures.mjs from the telemetry // backend's event manifest (x-normalize.unknown_enum_value). DO NOT EDIT. // Enum domains come from PAPERCLIP_ENUM_DESCRIPTIONS in @paperclipai/shared. export const UNKNOWN_ENUM_FALLBACKS = ${JSON.stringify(fallbacks, null, 2)} as const; `; await writeFile(path.join(outDir, "enum-fallbacks.generated.ts"), fallbackSource); // --- golden loader output ---------------------------------------------------- const { processV2Ingest, setV2IngestAwsClientsForTest } = await import(backendUrl("src/v2/ingest-core.mjs")); const { buildPostHogEvent } = await import(backendUrl("src/loader/sinks/posthog.mjs")); const NOW = "2026-11-17T12:00:00.000Z"; const HMAC_SECRET = "fixture-only-hmac-secret"; const RAW_TASK_ID = "6f1f3c2a-9b8e-4d7c-a1b2-c3d4e5f60718"; const HASHED_TASK_ID = "9c1e5b7a3d2f4e60"; // what hashPrivateRef emits on the collector path const envelope = { app: "paperclip", schemaVersion: "1", installId: "11111111-2222-4333-8444-555555555555", version: "2026.1117.0", batchId: "fixture-batch-0001", events: [ { name: "server.started", occurredAt: "2026-11-17T11:58:00.000Z", dimensions: { os_platform: "linux" } }, { name: "agent.task_run", occurredAt: "2026-11-17T11:58:01.000Z", dimensions: { agent_id: "2f6c7d1e-0a4b-4c3d-9e8f-112233445566", state: "succeeded", adapter_type: "claude_local", agent_role: "engineer", model: "claude-opus-5-5", duration_seconds: 42, input_tokens: 1200, output_tokens: 300, task_id: HASHED_TASK_ID, }, }, { name: "agent.created", occurredAt: "2026-11-17T11:58:02.000Z", dimensions: { agent_id: "3a7b8c9d-1e2f-4a5b-8c6d-778899aabbcc", agent_role: "astronaut" }, }, { name: "install.completed", occurredAt: "2026-11-17T11:58:03.000Z", dimensions: { adapter_type: "future_adapter" }, }, { name: "skill.imported", occurredAt: "2026-11-17T11:58:04.000Z", dimensions: { source_type: "mystery_source" }, }, { name: "interaction.resolved", occurredAt: "2026-11-17T11:58:05.000Z", dimensions: { interaction_kind: "suggest_tasks", status: "accepted", resolved_by_kind: "user", option_count: 3, selected_option_count: 2, legacy_inherited_restriction: false, }, }, { name: "routine.created", occurredAt: "2026-11-17T11:58:06.000Z", dimensions: {} }, { // Unregistered names are quarantined by the backend and never reach PostHog. name: "question_response.delivery", occurredAt: "2026-11-17T11:58:07.000Z", dimensions: { outcome: "delivered" }, }, ], }; const canonicalRecords = []; setV2IngestAwsClientsForTest({ firehose: { async send(command) { for (const record of command.input.Records ?? []) { const parsed = JSON.parse(Buffer.from(record.Data).toString("utf-8")); if (command.input.DeliveryStreamName === "canonical") canonicalRecords.push(parsed); } return { FailedPutCount: 0, RequestResponses: [] }; }, }, dynamoDb: { async send() { return {}; } }, }); process.env.V2_CANONICAL_FIREHOSE_STREAM_NAME = "canonical"; process.env.V2_QUARANTINE_FIREHOSE_STREAM_NAME = "quarantine"; process.env.V2_BATCH_LEDGER_TABLE_NAME = "ledger"; delete process.env.AGENT_ID_HASH_SECRET; const originalInfo = console.info; console.info = () => {}; // silence the backend's metric lines const response = await processV2Ingest( { requestContext: { http: { method: "POST" } }, headers: {}, isBase64Encoded: false, body: JSON.stringify(envelope) }, { source: "client", route: "/v2/ingest", now: new Date(NOW), deploymentSource: "cloud" }, ); console.info = originalInfo; if (response.statusCode !== 202) { throw new Error(`backend ingest rejected the fixture envelope: ${response.statusCode} ${response.body}`); } const loaderEvents = canonicalRecords.map((record) => buildPostHogEvent(record, { distinctIdHmacSecret: HMAC_SECRET })); await mkdir(path.join(outDir, "__fixtures__"), { recursive: true }); await writeFile( path.join(outDir, "__fixtures__/loader-golden.json"), `${JSON.stringify({ ingestedAt: NOW, rawTaskId: RAW_TASK_ID, hashedTaskId: HASHED_TASK_ID, envelope, canonicalRecords, loaderEvents }, null, 2)}\n`, ); console.log(`wrote ${loaderEvents.length} loader events and ${Object.keys(fallbacks).length} fallback rule sets`);