: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
#!/usr/bin/env node
import { createHash } from "node:crypto";
import { readFile, writeFile } from "node:fs/promises";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { assertMitLicense } from "../packages/harness/src/extensions/benjamin/license-guard.ts";
const __dirname = dirname(fileURLToPath(import.meta.url));
const REPO = "JetBrains/benjamin-plus-skill";
const FILE = "injected-instruction.md";
const CHECKSUMS_FILE = "SHA256SUMS.txt";
const LICENSE_FILE = "LICENSE";
const REF = process.env.BENJAMIN_REF ?? "main";
const VENDOR_DIR = resolve(
__dirname,
"..",
"packages",
"harness",
"src",
"extensions",
"benjamin",
);
const INSTRUCTION_PATH = join(VENDOR_DIR, "instruction.ts");
const LOCK_PATH = join(VENDOR_DIR, "benjamin.lock.json");
interface BenjaminLock {
repo: string;
commit: string;
file: string;
sha256: string;
fetched_at: string;
}
function githubHeaders(accept: string): Record<string, string> {
const token = process.env.GITHUB_TOKEN ?? process.env.GH_TOKEN;
return {
accept,
"user-agent": "posthog-sync-benjamin",
...(token ? { authorization: `Bearer ${token}` } : {}),
};
}
async function fetchText(url: string, accept: string): Promise<string> {
const response = await fetch(url, { headers: githubHeaders(accept) });
if (!response.ok) {
throw new Error(`GET ${url} failed with ${response.status}`);
}
return response.text();
}
async function resolveCommit(ref: string): Promise<string> {
const sha = (
await fetchText(
`https://api.github.com/repos/${REPO}/commits/${ref}`,
"application/vnd.github.sha",
)
).trim();
if (!/^[0-9a-f]{40}$/.test(sha)) {
throw new Error(`Unexpected commit sha for ${REPO}@${ref}: ${sha}`);
}
return sha;
}
function parseExpectedChecksum(checksums: string, file: string): string {
for (const line of checksums.split("\n")) {
const [digest, name] = line.trim().split(/\s+/);
if (name === file && digest) return digest;
}
throw new Error(`${CHECKSUMS_FILE} has no entry for ${file}`);
}
function toTemplateLiteral(text: string): string {
const escaped = text
.replace(/\\/g, "\\\\")
.replace(/`/g, "\\`")
.replace(/\$\{/g, "\\${");
return `\`${escaped}\``;
}
function renderInstructionModule(
instruction: string,
license: string,
commit: string,
sha256: string,
): string {
const licenseLines = license
.trim()
.split("\n")
.map((line) => ` * ${line}`.trimEnd())
.join("\n");
return `/**
* @license
* Benjamin-Plus injected instruction, vendored from ${REPO}.
* Upstream: https://github.com/${REPO}
* Commit: ${commit}
* File: ${FILE} (sha256 ${sha256})
*
${licenseLines}
*
* Generated by scripts/sync-benjamin.mts - do not edit by hand.
*/
export const BENJAMIN_UPSTREAM_COMMIT = "${commit.slice(0, 7)}";
export const BENJAMIN_INSTRUCTION = ${toTemplateLiteral(instruction)};
`;
}
async function readLock(): Promise<BenjaminLock | null> {
try {
return JSON.parse(await readFile(LOCK_PATH, "utf8")) as BenjaminLock;
} catch {
return null;
}
}
async function syncBenjamin(ref: string): Promise<{
commit: string;
sha256: string;
changed: boolean;
}> {
const commit = await resolveCommit(ref);
const base = `https://raw.githubusercontent.com/${REPO}/${commit}`;
const [instruction, checksums, license, existing, current] =
await Promise.all([
fetchText(`${base}/${FILE}`, "text/plain"),
fetchText(`${base}/${CHECKSUMS_FILE}`, "text/plain"),
fetchText(`${base}/${LICENSE_FILE}`, "text/plain"),
readLock(),
readFile(INSTRUCTION_PATH, "utf8").catch(() => ""),
]);
assertMitLicense(license);
const sha256 = createHash("sha256")
.update(Buffer.from(instruction, "utf8"))
.digest("hex");
const expected = parseExpectedChecksum(checksums, FILE);
if (sha256 !== expected) {
throw new Error(
`Checksum mismatch for ${FILE} at ${commit}: got ${sha256}, ${CHECKSUMS_FILE} says ${expected}`,
);
}
const rendered = renderInstructionModule(
instruction,
license,
commit,
sha256,
);
if (existing && current === rendered) {
return { commit, sha256, changed: false };
}
const lock: BenjaminLock = {
repo: REPO,
commit,
file: FILE,
sha256,
fetched_at: new Date().toISOString().slice(0, 10),
};
await Promise.all([
writeFile(INSTRUCTION_PATH, rendered, "utf8"),
writeFile(LOCK_PATH, `${JSON.stringify(lock, null, 2)}\n`, "utf8"),
]);
return { commit, sha256, changed: true };
}
async function main(): Promise<void> {
const result = await syncBenjamin(REF);
console.log(
result.changed
? `Vendored ${REPO}@${result.commit} (${FILE}, sha256 ${result.sha256})`
: `Already at ${REPO}@${result.commit} - nothing to write`,
);
}
if (
process.argv[1] &&
resolve(process.argv[1]) === fileURLToPath(import.meta.url)
) {
await main();
}