import { spawn } from "node:child_process"; import { randomUUID } from "node:crypto"; import { accessSync, constants, existsSync } from "node:fs"; import { basename, delimiter, join } from "node:path"; import type { Message, ThinkingLevel } from "@earendil-works/pi-ai"; import { buildSessionContext, convertToLlm, type ExtensionContext, SessionManager, SettingsManager, } from "@earendil-works/pi-coding-agent"; import { analysisPrompt, boundedError, type GoodJobJob, type GoodJobRecord, JOB_VERSION, lastAgentModel, type ModelRef, parseLearning, RECORD_VERSION, responseText, } from "./core.js"; import { claimJob, commitFailure, commitRecord, counts, enqueueJob, ensureLayout, type GoodJobLayout, goodJobDataDirectory, layout, loadRecords, pendingJobIds, recoverProcessing, } from "./storage.js"; import { showLearningDetail, showLearningList } from "./ui.js"; const STATUS_KEY = "good-job"; const SPINNER = ["◐", "◓", "◑", "◒"] as const; const MAX_TOKENS = 1_200; type ContextSnapshot = Message[]; type Opener = { command: string; args: string[] }; type GoodJobSettings = { model?: string; thinkingLevel?: ThinkingLevel; }; const THINKING_LEVELS = new Set([ "minimal", "low", "medium", "high", "xhigh", "max", ]); export interface GoodJobRuntime { start(ctx: ExtensionContext): Promise; stop(ctx: ExtensionContext): Promise; capture(praise: string, ctx: ExtensionContext): Promise; runCommand(args: string, ctx: ExtensionContext): Promise; } function modelRef(ctx: ExtensionContext): ModelRef | null { return ctx.model ? { provider: ctx.model.provider, id: ctx.model.id } : null; } function isObject(value: unknown): value is Record { return value !== null && typeof value === "object" && !Array.isArray(value); } export function parseModelRef(value: string | undefined): ModelRef | undefined { const trimmed = value?.trim() ?? ""; const separator = trimmed.indexOf("/"); if (separator <= 0 || separator === trimmed.length - 1) return undefined; return { provider: trimmed.slice(0, separator), id: trimmed.slice(separator + 1), }; } export function settingsFrom(cwd: string): GoodJobSettings { const manager = SettingsManager.create(cwd); const global = manager.getGlobalSettings() as Record; const project = manager.getProjectSettings() as Record; const merged = { ...(isObject(global.goodJob) ? global.goodJob : {}), ...(isObject(project.goodJob) ? project.goodJob : {}), }; const thinkingLevel = merged.thinkingLevel; if ( thinkingLevel !== undefined && (typeof thinkingLevel !== "string" || !THINKING_LEVELS.has(thinkingLevel as ThinkingLevel)) ) throw new Error( "goodJob.thinkingLevel must be minimal, low, medium, high, xhigh, or max", ); return { model: typeof merged.model === "string" && merged.model.trim() ? merged.model.trim() : undefined, thinkingLevel: thinkingLevel as ThinkingLevel | undefined, }; } function sourceFor( ctx: ExtensionContext, messages: readonly unknown[], ): GoodJobJob["source"] { return { cwd: ctx.cwd, sessionPath: ctx.sessionManager.getSessionFile() ?? null, sessionId: ctx.sessionManager.getSessionId(), sessionName: ctx.sessionManager.getSessionName() ?? null, leafId: ctx.sessionManager.getLeafId(), agentModel: lastAgentModel(messages), }; } function completionContext( conversation: readonly Message[], praise: string, ): Message[] { return [ ...conversation, { role: "user", content: [{ type: "text", text: analysisPrompt(praise) }], timestamp: Date.now(), }, ]; } function contextFromSession(job: GoodJobJob): ContextSnapshot { if (!job.source.sessionPath) throw new Error("source session was ephemeral and is no longer available"); const manager = SessionManager.open(job.source.sessionPath); if (job.source.leafId && !manager.getEntry(job.source.leafId)) throw new Error(`source session leaf ${job.source.leafId} is missing`); const context = buildSessionContext( manager.getEntries(), job.source.leafId, ).messages; return convertToLlm(context); } function findExecutable( name: string, env: NodeJS.ProcessEnv, ): string | undefined { for (const directory of (env.PATH ?? "").split(delimiter).filter(Boolean)) { const candidate = join(directory.replace(/^"|"$/g, ""), name); try { accessSync(candidate, constants.X_OK); return candidate; } catch { // Keep searching PATH. } } return undefined; } export function openerFor( platform = process.platform, env: NodeJS.ProcessEnv = process.env, ): Opener | undefined { if (platform === "win32") { const root = env.SystemRoot || env.WINDIR; const executable = root ? join(root, "explorer.exe") : undefined; return executable && existsSync(executable) ? { command: executable, args: [] } : undefined; } if (platform === "darwin") return existsSync("/usr/bin/open") ? { command: "/usr/bin/open", args: [] } : undefined; const executable = findExecutable("xdg-open", env); return executable ? { command: executable, args: [] } : undefined; } export function openDirectory( path: string, opener = openerFor(), ): Promise { if (!opener) return Promise.reject(new Error("no platform directory opener found")); return new Promise((resolve, reject) => { const child = spawn(opener.command, [...opener.args, path], { detached: true, stdio: "ignore", windowsHide: true, }); child.once("error", reject); child.once("spawn", () => { child.unref(); resolve(); }); }); } class Runtime implements GoodJobRuntime { private generation = 0; private activeController: AbortController | undefined; private pumpPromise: Promise | undefined; private pumpRequested = false; private readonly snapshots = new Map(); private spinnerTimer: ReturnType | undefined; private spinnerStartedAt = 0; private spinnerCount = 0; private openerChecked = false; private settings: GoodJobSettings = {}; private settingsCwd: string | undefined; private readonly paths: GoodJobLayout; private readonly opener: Opener | undefined; constructor(root = goodJobDataDirectory()) { this.paths = layout(root); this.opener = openerFor(); } async start(ctx: ExtensionContext): Promise { const previousPump = this.pumpPromise; const generation = ++this.generation; this.activeController?.abort(); if (previousPump) await previousPump; if (generation !== this.generation) return; this.pumpRequested = false; this.readSettings(ctx.cwd); if (!this.openerChecked) { this.openerChecked = true; if (!this.opener && ctx.hasUI) ctx.ui.notify( "good-job: directory opening unavailable; no platform opener found", "info", ); } if (!existsSync(this.paths.root)) return; await this.recoverAndPump(ctx, generation); } async stop(ctx: ExtensionContext): Promise { this.generation++; this.pumpRequested = false; this.activeController?.abort(); await this.pumpPromise; this.activeController = undefined; this.stopSpinner(ctx); } async capture(praise: string, ctx: ExtensionContext): Promise { this.readSettings(ctx.cwd); const sessionContext = buildSessionContext( ctx.sessionManager.getEntries(), ctx.sessionManager.getLeafId(), ); const snapshot = convertToLlm(sessionContext.messages); const job: GoodJobJob = { version: JOB_VERSION, id: randomUUID(), createdAt: new Date().toISOString(), praise: praise.trim(), source: sourceFor(ctx, sessionContext.messages), analysisModel: this.analysisModel(ctx), }; await ensureLayout(this.paths); await enqueueJob(job, this.paths); this.snapshots.set(job.id, snapshot); if (ctx.hasUI) ctx.ui.notify(`good-job queued · ${job.id.slice(0, 8)}`, "info"); void this.pump(ctx, this.generation, job.id); } async runCommand(args: string, ctx: ExtensionContext): Promise { this.readSettings(ctx.cwd); const [command = "list", id = ""] = args.trim().split(/\s+/, 2); if (command === "list" || command === "") { await this.list(ctx); return; } if (command === "show") { await this.show(id, ctx); return; } if (command === "status") { await this.status(ctx); return; } if (command === "open") { await this.open(ctx); return; } ctx.ui.notify("Usage: /good-job [list|show |status|open]", "warning"); } private readSettings(cwd: string): void { if (this.settingsCwd === cwd) return; this.settings = settingsFrom(cwd); this.settingsCwd = cwd; } private analysisModel(ctx: ExtensionContext): ModelRef | null { if (!this.settings.model) return modelRef(ctx); const configured = parseModelRef(this.settings.model); if (!configured) throw new Error( `invalid goodJob.model ${JSON.stringify(this.settings.model)}; expected provider/model`, ); return configured; } private async recoverAndPump( ctx: ExtensionContext, generation: number, ): Promise { await ensureLayout(this.paths); await recoverProcessing(this.paths); if (generation === this.generation) void this.pump(ctx, generation); } private pump( ctx: ExtensionContext, generation: number, preferredId?: string, ): Promise { if (this.pumpPromise) { this.pumpRequested = true; return this.pumpPromise; } this.pumpRequested = false; this.pumpPromise = this.pumpJobs(ctx, generation, preferredId) .catch((error) => { if (generation === this.generation && ctx.hasUI) ctx.ui.notify( `good-job queue failed: ${boundedError(error)}`, "error", ); }) .finally(() => { this.pumpPromise = undefined; if (this.pumpRequested && generation === this.generation) void this.pump(ctx, generation); }); return this.pumpPromise; } private async pumpJobs( ctx: ExtensionContext, generation: number, preferredId?: string, ): Promise { let ids = await pendingJobIds(this.paths); if (preferredId && ids.includes(preferredId)) ids = [preferredId, ...ids.filter((id) => id !== preferredId)]; this.startSpinner(ctx, ids.length); try { for (const [index, id] of ids.entries()) { if (generation !== this.generation) return; this.spinnerCount = ids.length - index; const claimed = await claimJob(id, this.paths); if (!claimed) continue; await this.process(claimed.job, claimed.path, ctx, generation); } } finally { this.stopSpinner(ctx); } } private async process( job: GoodJobJob, claimPath: string, ctx: ExtensionContext, generation: number, ): Promise { const controller = new AbortController(); this.activeController = controller; try { if (!job.analysisModel) throw new Error("no analysis model was available"); const model = ctx.modelRegistry.find( job.analysisModel.provider, job.analysisModel.id, ); if (!model) throw new Error( `analysis model ${job.analysisModel.provider}/${job.analysisModel.id} is unavailable`, ); const snapshot = this.snapshots.get(job.id) ?? contextFromSession(job); const response = await ctx.modelRegistry.complete( model, { systemPrompt: "Extract evidence-backed, reusable lessons from praised coding-agent work.", messages: completionContext(snapshot, job.praise), }, { maxTokens: MAX_TOKENS, reasoning: this.settings.thinkingLevel, cacheRetention: "none", sessionId: job.id, signal: controller.signal, }, ); if (controller.signal.aborted || generation !== this.generation) return; if (response.stopReason !== "stop") throw new Error( response.errorMessage || `analysis stopped with ${response.stopReason}`, ); const learning = parseLearning(responseText(response)); const record: GoodJobRecord = { version: RECORD_VERSION, id: job.id, createdAt: job.createdAt, completedAt: new Date().toISOString(), praise: job.praise, source: job.source, analysisModel: job.analysisModel, learning, usage: { input: response.usage.input, output: response.usage.output, cacheRead: response.usage.cacheRead, cacheWrite: response.usage.cacheWrite, totalTokens: response.usage.totalTokens, cost: response.usage.cost.total, }, }; await commitRecord(record, claimPath, this.paths); this.snapshots.delete(job.id); if (ctx.hasUI) ctx.ui.notify( `good-job learned · ${record.learning.achievement}`, "info", ); } catch (error) { if (controller.signal.aborted || generation !== this.generation) return; try { await commitFailure(job, error, claimPath, this.paths); this.snapshots.delete(job.id); } catch (storageError) { console.error("[good-job] could not persist failure", storageError); } if (ctx.hasUI) ctx.ui.notify(`good-job failed: ${boundedError(error)}`, "error"); } finally { if (this.activeController === controller) this.activeController = undefined; } } private startSpinner(ctx: ExtensionContext, count: number): void { this.stopSpinner(ctx); if (!ctx.hasUI || count === 0) return; this.spinnerCount = count; this.spinnerStartedAt = Date.now(); const render = () => { const frame = SPINNER[ Math.floor((Date.now() - this.spinnerStartedAt) / 120) % SPINNER.length ] ?? SPINNER[0]; ctx.ui.setStatus( STATUS_KEY, ctx.ui.theme.fg( "accent", `${frame} good-job learning${this.spinnerCount > 1 ? ` (${this.spinnerCount})` : ""}`, ), ); }; render(); this.spinnerTimer = setInterval(render, 120); this.spinnerTimer.unref?.(); } private stopSpinner(ctx: ExtensionContext): void { if (this.spinnerTimer) clearInterval(this.spinnerTimer); this.spinnerTimer = undefined; if (ctx.hasUI) ctx.ui.setStatus(STATUS_KEY, undefined); } private async list(ctx: ExtensionContext): Promise { const loaded = await loadRecords(this.paths); if (loaded.errors.length) ctx.ui.notify( `${loaded.errors.length} unreadable good-job record${loaded.errors.length === 1 ? "" : "s"}`, "warning", ); if (loaded.records.length === 0) { ctx.ui.notify("No good-job learnings yet", "info"); return; } const selected = await showLearningList( ctx, loaded.records, await counts(this.paths), ); if (!selected) return; const record = loaded.records.find( (candidate) => candidate.id === selected, ); if (record) await showLearningDetail(ctx, record); } private async show(id: string, ctx: ExtensionContext): Promise { if (!id) { ctx.ui.notify("Usage: /good-job show ", "warning"); return; } const loaded = await loadRecords(this.paths); const matches = loaded.records.filter((record) => record.id.startsWith(id)); if (matches.length !== 1) { ctx.ui.notify( matches.length === 0 ? `Unknown good-job id: ${id}` : `Ambiguous good-job id: ${id}`, "warning", ); return; } await showLearningDetail(ctx, matches[0] as GoodJobRecord); } private async status(ctx: ExtensionContext): Promise { const state = await counts(this.paths); ctx.ui.notify( [ `${state.records} learnings`, `${state.pending} pending`, `${state.processing} processing`, `${state.failed} failed`, `analysis model: ${this.settings.model ?? "current"}`, `thinking: ${this.settings.thinkingLevel ?? "provider default"}`, this.paths.root, ].join(" · "), state.failed ? "warning" : "info", ); } private async open(ctx: ExtensionContext): Promise { await ensureLayout(this.paths); try { await openDirectory(this.paths.root, this.opener); } catch (error) { ctx.ui.notify(`good-job open failed: ${boundedError(error)}`, "error"); return; } ctx.ui.notify(`Opened ${basename(this.paths.root)}`, "info"); } } export function createGoodJobRuntime( root = goodJobDataDirectory(), ): GoodJobRuntime { return new Runtime(root); }