1 +import { spawn }
from "node:child_process";
2 +import { randomUUID }
from "node:crypto";
3 +import { accessSync, constants, existsSync }
from "node:fs";
4 +import { basename, delimiter, join }
from "node:path";
5 +import type { Message, ThinkingLevel }
from "@earendil-works/pi-ai";
9 + type ExtensionContext,
12 +}
from "@earendil-works/pi-coding-agent";
33 + goodJobDataDirectory,
38 +}
from "./storage.js";
39 +import { showLearningDetail, showLearningList }
from "./ui.js";
41 +const STATUS_KEY
= "good-job";
42 +const SPINNER
= [
"◐",
"◓",
"◑",
"◒"]
as const;
43 +const MAX_TOKENS
= 1_200;
45 +type ContextSnapshot = Message[];
47 +type Opener = { command
: string; args
: string[] };
48 +type GoodJobSettings = {
50 + thinkingLevel
?: ThinkingLevel;
53 +const THINKING_LEVELS
= new Set<
ThinkingLevel>([
62 +export interface GoodJobRuntime {
63 + start(ctx
: ExtensionContext)
: Promise<
void>;
64 + stop(ctx
: ExtensionContext)
: Promise<
void>;
65 + capture(praise
: string, ctx
: ExtensionContext)
: Promise<
void>;
66 + runCommand(args
: string, ctx
: ExtensionContext)
: Promise<
void>;
69 +function modelRef(ctx
: ExtensionContext)
: ModelRef | null {
70 + return ctx.model
? { provider: ctx.model.provider, id: ctx.model.
id }
: null;
73 +function isObject(value
: unknown)
: value
is Record<
string,
unknown> {
74 + return value
!== null && typeof value
=== "object" && !Array.
isArray(value);
77 +export function parseModelRef(value
: string | undefined)
: ModelRef | undefined {
78 + const trimmed
= value?.
trim()
?? "";
79 + const separator
= trimmed.
indexOf(
"/");
80 + if (separator
<= 0 || separator
=== trimmed.
length - 1)
return undefined;
82 + provider: trimmed.
slice(
0, separator),
83 + id: trimmed.
slice(separator
+ 1),
87 +export function settingsFrom(cwd
: string)
: GoodJobSettings {
88 + const manager
= SettingsManager.
create(cwd);
89 + const global
= manager.
getGlobalSettings()
as Record<
string,
unknown>;
90 + const project
= manager.
getProjectSettings()
as Record<
string,
unknown>;
92 + ...(
isObject(
global.goodJob)
? global.goodJob
: {}),
93 + ...(
isObject(project.goodJob)
? project.goodJob
: {}),
95 + const thinkingLevel
= merged.thinkingLevel;
97 + thinkingLevel
!== undefined && 98 + (
typeof thinkingLevel
!== "string" || 99 + !THINKING_LEVELS.
has(thinkingLevel
as ThinkingLevel))
102 + "goodJob.thinkingLevel must be minimal, low, medium, high, xhigh, or max",
106 + typeof merged.model
=== "string" && merged.model.
trim()
107 + ? merged.model.
trim()
109 + thinkingLevel: thinkingLevel
as ThinkingLevel | undefined,
114 + ctx
: ExtensionContext,
115 + messages
: readonly unknown[],
116 +)
: GoodJobJob[
"source"] {
119 + sessionPath: ctx.sessionManager.
getSessionFile()
?? null,
120 + sessionId: ctx.sessionManager.
getSessionId(),
121 + sessionName: ctx.sessionManager.
getSessionName()
?? null,
122 + leafId: ctx.sessionManager.
getLeafId(),
123 + agentModel:
lastAgentModel(messages),
127 +function completionContext(
128 + conversation
: readonly Message[],
135 + content: [{ type:
"text", text:
analysisPrompt(praise) }],
136 + timestamp:
Date.
now(),
141 +function contextFromSession(job
: GoodJobJob)
: ContextSnapshot {
142 + if (
!job.
source.sessionPath)
143 + throw new Error(
"source session was ephemeral and is no longer available");
144 + const manager
= SessionManager.
open(job.
source.sessionPath);
145 + if (job.
source.leafId
&& !manager.
getEntry(job.
source.leafId))
146 + throw new Error(
`source session leaf ${job.source.leafId} is missing`);
147 + const context
= buildSessionContext(
148 + manager.
getEntries(),
151 + return convertToLlm(context);
154 +function findExecutable(
156 + env
: NodeJS.
ProcessEnv,
157 +)
: string | undefined {
158 + for (
const directory
of (env.PATH
?? "").
split(delimiter).
filter(
Boolean)) {
159 + const candidate
= join(directory.
replace(
/^"|"$/g,
""), name);
161 + accessSync(candidate, constants.X_OK);
170 +export function openerFor(
171 + platform
= process.
platform,
172 + env
: NodeJS.
ProcessEnv = process.
env,
173 +)
: Opener | undefined {
174 + if (platform
=== "win32") {
175 + const root
= env.SystemRoot
|| env.WINDIR;
176 + const executable
= root ? join(
root,
"explorer.exe")
: undefined;
177 + return executable
&& existsSync(executable)
178 + ? { command: executable, args: [] }
181 + if (platform
=== "darwin")
182 + return existsSync(
"/usr/bin/open")
183 + ? { command:
"/usr/bin/open", args: [] }
185 + const executable
= findExecutable(
"xdg-open", env);
186 + return executable
? { command: executable, args: [] }
: undefined;
189 +export function openDirectory(
191 + opener
= openerFor(),
194 + return Promise.
reject(
new Error(
"no platform directory opener found"));
195 + return new Promise((resolve, reject)
=> {
196 + const child
= spawn(opener.command, [
...opener.args, path], {
201 + child.
once(
"error", reject);
202 + child.
once(
"spawn", ()
=> {
209 +class Runtime implements GoodJobRuntime {
210 + private generation
= 0;
211 + private activeController
: AbortController | undefined;
212 + private pumpPromise
: Promise<
void>
| undefined;
213 + private pumpRequested
= false;
214 + private readonly snapshots
= new Map<
string,
ContextSnapshot>();
215 + private spinnerTimer
: ReturnType<
typeof setInterval>
| undefined;
216 + private spinnerStartedAt
= 0;
217 + private spinnerCount
= 0;
218 + private openerChecked
= false;
219 + private settings
: GoodJobSettings = {};
220 + private settingsCwd
: string | undefined;
221 + private readonly paths
: GoodJobLayout;
222 + private readonly opener
: Opener | undefined;
224 + constructor(root
= goodJobDataDirectory()) {
225 + this.paths
= layout(
root);
226 + this.
opener = openerFor();
229 + async start(ctx
: ExtensionContext)
: Promise<
void> {
230 + const previousPump
= this.pumpPromise;
231 + const generation
= ++this.generation;
232 + this.activeController?.
abort();
233 + if (previousPump)
await previousPump;
234 + if (generation
!== this.generation)
return;
235 + this.pumpRequested
= false;
236 + this.
readSettings(ctx.cwd);
237 + if (
!this.openerChecked) {
238 + this.openerChecked
= true;
239 + if (
!this.
opener && ctx.hasUI)
241 + "good-job: directory opening unavailable; no platform opener found",
245 + if (
!existsSync(this.paths.root))
return;
246 + await this.
recoverAndPump(ctx, generation);
249 + async stop(ctx
: ExtensionContext)
: Promise<
void> {
251 + this.pumpRequested
= false;
252 + this.activeController?.
abort();
253 + await this.pumpPromise;
254 + this.activeController
= undefined;
255 + this.
stopSpinner(ctx);
258 + async capture(praise
: string, ctx
: ExtensionContext)
: Promise<
void> {
259 + this.
readSettings(ctx.cwd);
260 + const sessionContext
= buildSessionContext(
261 + ctx.sessionManager.
getEntries(),
262 + ctx.sessionManager.
getLeafId(),
264 + const snapshot
= convertToLlm(sessionContext.messages);
265 + const job
: GoodJobJob = {
266 + version: JOB_VERSION,
268 + createdAt:
new Date().
toISOString(),
269 + praise: praise.
trim(),
270 + source:
sourceFor(ctx, sessionContext.messages),
271 + analysisModel: this.
analysisModel(ctx),
273 + await ensureLayout(this.paths);
274 + await enqueueJob(job, this.paths);
275 + this.snapshots.
set(job.
id, snapshot);
277 + ctx.ui.
notify(
`good-job queued · ${job.id.slice(0, 8)}`,
"info");
278 + void this.
pump(ctx, this.generation, job.
id);
281 + async runCommand(args
: string, ctx
: ExtensionContext)
: Promise<
void> {
282 + this.
readSettings(ctx.cwd);
283 + const [command
= "list", id
= ""]
= args.
trim().
split(
/\s+/,
2);
284 + if (command
=== "list" || command
=== "") {
285 + await this.
list(ctx);
288 + if (command
=== "show") {
289 + await this.
show(id, ctx);
292 + if (command
=== "status") {
293 + await this.
status(ctx);
296 + if (command
=== "open") {
297 + await this.
open(ctx);
300 + ctx.ui.
notify(
"Usage: /good-job [list|show <id>|status|open]",
"warning");
303 + private readSettings(cwd
: string)
: void {
304 + if (this.settingsCwd
=== cwd)
return;
305 + this.settings
= settingsFrom(cwd);
306 + this.settingsCwd
= cwd;
309 + private analysisModel(ctx
: ExtensionContext)
: ModelRef | null {
310 + if (
!this.settings.model)
return modelRef(ctx);
311 + const configured
= parseModelRef(this.settings.model);
314 + `invalid goodJob.model ${JSON.stringify(this.settings.model)}; expected provider/model`,
319 + private async recoverAndPump(
320 + ctx
: ExtensionContext,
321 + generation
: number,
323 + await ensureLayout(this.paths);
324 + await recoverProcessing(this.paths);
325 + if (generation
=== this.generation)
void this.
pump(ctx, generation);
329 + ctx
: ExtensionContext,
330 + generation
: number,
331 + preferredId
?: string,
333 + if (this.pumpPromise) {
334 + this.pumpRequested
= true;
335 + return this.pumpPromise;
337 + this.pumpRequested
= false;
338 + this.pumpPromise
= this.
pumpJobs(ctx, generation, preferredId)
339 + .
catch((error)
=> {
340 + if (generation
=== this.generation
&& ctx.hasUI)
342 + `good-job queue failed: ${boundedError(error)}`,
347 + this.pumpPromise
= undefined;
348 + if (this.pumpRequested
&& generation
=== this.generation)
349 + void this.
pump(ctx, generation);
351 + return this.pumpPromise;
354 + private async pumpJobs(
355 + ctx
: ExtensionContext,
356 + generation
: number,
357 + preferredId
?: string,
359 + let ids
= await pendingJobIds(this.paths);
360 + if (preferredId
&& ids.
includes(preferredId))
361 + ids
= [preferredId,
...ids.
filter((id)
=> id
!== preferredId)];
362 + this.
startSpinner(ctx, ids.
length);
364 + for (
const [index, id]
of ids.
entries()) {
365 + if (generation
!== this.generation)
return;
366 + this.spinnerCount
= ids.
length - index;
367 + const claimed
= await claimJob(id, this.paths);
368 + if (
!claimed)
continue;
369 + await this.
process(claimed.job, claimed.path, ctx, generation);
372 + this.
stopSpinner(ctx);
376 + private async process(
379 + ctx
: ExtensionContext,
380 + generation
: number,
382 + const controller
= new AbortController();
383 + this.activeController
= controller;
385 + if (
!job.analysisModel)
386 + throw new Error(
"no analysis model was available");
387 + const model
= ctx.modelRegistry.
find(
388 + job.analysisModel.provider,
389 + job.analysisModel.
id,
393 + `analysis model ${job.analysisModel.provider}/${job.analysisModel.id} is unavailable`,
395 + const snapshot
= this.snapshots.
get(job.
id)
?? contextFromSession(job);
396 + const response
= await ctx.modelRegistry.
complete(
400 + "Extract evidence-backed, reusable lessons from praised coding-agent work.",
401 + messages:
completionContext(snapshot, job.praise),
404 + maxTokens: MAX_TOKENS,
405 + reasoning: this.settings.thinkingLevel,
406 + cacheRetention:
"none",
408 + signal: controller.signal,
411 + if (controller.signal.aborted
|| generation
!== this.generation)
return;
412 + if (response.stopReason
!== "stop")
414 + response.errorMessage
|| 415 + `analysis stopped with ${response.stopReason}`,
417 + const learning
= parseLearning(
responseText(response));
418 + const record
: GoodJobRecord = {
419 + version: RECORD_VERSION,
421 + createdAt: job.createdAt,
422 + completedAt:
new Date().
toISOString(),
423 + praise: job.praise,
424 + source: job.
source,
425 + analysisModel: job.analysisModel,
428 + input: response.usage.
input,
429 + output: response.usage.output,
430 + cacheRead: response.usage.cacheRead,
431 + cacheWrite: response.usage.cacheWrite,
432 + totalTokens: response.usage.totalTokens,
433 + cost: response.usage.cost.total,
436 + await commitRecord(record, claimPath, this.paths);
437 + this.snapshots.
delete(job.
id);
440 + `good-job learned · ${record.learning.achievement}`,
444 + if (controller.signal.aborted
|| generation
!== this.generation)
return;
446 + await commitFailure(job, error, claimPath, this.paths);
447 + this.snapshots.
delete(job.
id);
448 + }
catch (storageError) {
449 + console.
error(
"[good-job] could not persist failure", storageError);
452 + ctx.ui.
notify(
`good-job failed: ${boundedError(error)}`,
"error");
454 + if (this.activeController
=== controller)
455 + this.activeController
= undefined;
459 + private startSpinner(ctx
: ExtensionContext, count
: number)
: void {
460 + this.
stopSpinner(ctx);
461 + if (
!ctx.hasUI
|| count
=== 0)
return;
462 + this.spinnerCount
= count;
463 + this.spinnerStartedAt
= Date.
now();
464 + const render = ()
=> {
467 + Math.
floor((
Date.
now()
- this.spinnerStartedAt)
/ 120)
% 474 + `${frame} good-job learning${this.spinnerCount > 1 ? ` (${this.spinnerCount})` : ""}`,
479 + this.spinnerTimer
= setInterval(render,
120);
480 + this.spinnerTimer.
unref?.();
483 + private stopSpinner(ctx
: ExtensionContext)
: void {
484 + if (this.spinnerTimer)
clearInterval(this.spinnerTimer);
485 + this.spinnerTimer
= undefined;
486 + if (ctx.hasUI) ctx.ui.
setStatus(STATUS_KEY,
undefined);
489 + private async list(ctx
: ExtensionContext)
: Promise<
void> {
490 + const loaded
= await loadRecords(this.paths);
491 + if (loaded.errors.
length)
493 + `${loaded.errors.length} unreadable good-job record${loaded.errors.length === 1 ? "" : "s"}`,
496 + if (loaded.records.
length === 0) {
497 + ctx.ui.
notify(
"No good-job learnings yet",
"info");
500 + const selected
= await showLearningList(
503 + await counts(this.paths),
505 + if (
!selected)
return;
506 + const record
= loaded.records.
find(
507 + (candidate)
=> candidate.
id === selected,
509 + if (record)
await showLearningDetail(ctx, record);
512 + private async show(id
: string, ctx
: ExtensionContext)
: Promise<
void> {
514 + ctx.ui.
notify(
"Usage: /good-job show <id>",
"warning");
517 + const loaded
= await loadRecords(this.paths);
518 + const matches
= loaded.records.
filter((record)
=> record.
id.
startsWith(id));
519 + if (matches.
length !== 1) {
521 + matches.
length === 0 522 + ? `Unknown good-job id: ${id}` 523 + : `Ambiguous good-job id: ${id}`,
528 + await showLearningDetail(ctx, matches[
0]
as GoodJobRecord);
531 + private async status(ctx
: ExtensionContext)
: Promise<
void> {
532 + const state
= await counts(this.paths);
535 + `${state.records} learnings`,
536 + `${state.pending} pending`,
537 + `${state.processing} processing`,
538 + `${state.failed} failed`,
539 + `analysis model: ${this.settings.model ?? "current"}`,
540 + `thinking: ${this.settings.thinkingLevel ?? "provider default"}`,
543 + state.failed
? "warning" : "info",
547 + private async open(ctx
: ExtensionContext)
: Promise<
void> {
548 + await ensureLayout(this.paths);
550 + await openDirectory(this.paths.root, this.
opener);
552 + ctx.ui.
notify(
`good-job open failed: ${boundedError(error)}`,
"error");
555 + ctx.ui.
notify(
`Opened ${basename(this.paths.root)}`,
"info");
559 +export function createGoodJobRuntime(
560 + root
= goodJobDataDirectory(),
562 + return new Runtime(
root);