import type { AssistantMessage } from "@earendil-works/pi-ai"; export const JOB_VERSION = 1 as const; export const RECORD_VERSION = 1 as const; export const FAILURE_VERSION = 1 as const; export interface ModelRef { provider: string; id: string; } export interface LearningSource { cwd: string; sessionPath: string | null; sessionId: string; sessionName: string | null; leafId: string | null; agentModel: ModelRef | null; } export interface GoodJobJob { version: typeof JOB_VERSION; id: string; createdAt: string; praise: string; source: LearningSource; analysisModel: ModelRef | null; } export interface Learning { achievement: string; evidence: string[]; successfulBehaviors: string[]; candidateRule: string | null; } export interface GoodJobRecord { version: typeof RECORD_VERSION; id: string; createdAt: string; completedAt: string; praise: string; source: LearningSource; analysisModel: ModelRef; learning: Learning; usage: { input: number; output: number; cacheRead: number; cacheWrite: number; totalTokens: number; cost: number; }; } export interface GoodJobFailure { version: typeof FAILURE_VERSION; job: GoodJobJob; failedAt: string; error: string; } const CONTROL_CHARACTERS = /[\x00-\x1F\x7F-\x9F]/g; const TRIGGER = /^(?:gj|good\s+job)[.!?]*$/i; const MAX_ACHIEVEMENT_CHARS = 180; const MAX_ITEM_CHARS = 500; const MAX_RULE_CHARS = 700; const MAX_ITEMS = 8; export function isGoodJobTrigger(text: string): boolean { return TRIGGER.test(text.trim()); } export function cleanText(text: string, maximum: number): string { const cleaned = text .replace(CONTROL_CHARACTERS, " ") .replace(/\s+/g, " ") .trim(); return Array.from(cleaned).slice(0, maximum).join(""); } function isRecord(value: unknown): value is Record { return value !== null && typeof value === "object" && !Array.isArray(value); } function cleanStringArray(value: unknown): string[] | undefined { if (!Array.isArray(value)) return undefined; const strings = value .slice(0, MAX_ITEMS) .map((item) => typeof item === "string" ? cleanText(item, MAX_ITEM_CHARS) : "", ) .filter(Boolean); return strings.length > 0 ? strings : undefined; } function jsonObject(text: string): unknown { const trimmed = text.trim(); const unfenced = trimmed .replace(/^```(?:json)?\s*/i, "") .replace(/\s*```$/, "") .trim(); const start = unfenced.indexOf("{"); const end = unfenced.lastIndexOf("}"); if (start < 0 || end < start) throw new Error("analysis did not return JSON"); return JSON.parse(unfenced.slice(start, end + 1)); } export function parseLearning(text: string): Learning { const value = jsonObject(text); if (!isRecord(value)) throw new Error("analysis returned a non-object"); const achievement = typeof value.achievement === "string" ? cleanText(value.achievement, MAX_ACHIEVEMENT_CHARS) : ""; const evidence = cleanStringArray(value.evidence); const successfulBehaviors = cleanStringArray( value.successful_behaviors ?? value.successfulBehaviors, ); const candidateValue = value.candidate_rule ?? value.candidateRule; const candidateRule = candidateValue === null ? null : typeof candidateValue === "string" ? cleanText(candidateValue, MAX_RULE_CHARS) : undefined; if (!achievement || !evidence || !successfulBehaviors) throw new Error("analysis JSON is missing required learning fields"); if (candidateRule === undefined) throw new Error("analysis JSON is missing candidate_rule"); return { achievement, evidence, successfulBehaviors, candidateRule }; } export function responseText(response: AssistantMessage): string { return response.content .filter( (part): part is { type: "text"; text: string } => part.type === "text", ) .map((part) => part.text) .join("\n"); } export function analysisPrompt(praise: string): string { return `The user just praised the preceding coding-agent work with: ${JSON.stringify(praise)} Analyze what concretely went well across the full conversation above. Infer causes only when supported by the transcript. Focus on reusable agent behavior, not compliments or personality. Do not reproduce credentials, secrets, long source excerpts, or private data. Return exactly one JSON object with this shape: { "achievement": "one concrete summary, at most 180 characters", "evidence": ["observable result or user-visible outcome"], "successful_behaviors": ["specific agent decision or behavior that contributed"], "candidate_rule": "concise reusable instruction for future agents, or null when evidence is insufficient" } Use 1-8 concise items per array. No markdown fences or commentary.`; } export function lastAgentModel(messages: readonly unknown[]): ModelRef | null { for (let index = messages.length - 1; index >= 0; index--) { const message = messages[index]; if (!isRecord(message) || message.role !== "assistant") continue; if ( typeof message.provider !== "string" || typeof message.model !== "string" ) continue; return { provider: message.provider, id: message.model }; } return null; } export function boundedError(error: unknown): string { const message = error instanceof Error ? error.message : String(error); return cleanText(message, 300) || "unknown error"; }