repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat(good-job): capture praised-work learnings

9497e944ef1a57e8419f1f9aabb2bba861f49ee4

Oliver Krylow <o.krylow@isp-insoft.de> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (14)

extensions/good-job/README.md

Added
new file mode 100644
1 +# good-job
3 +Turns standalone `gj` and `good job` praise into durable, evidence-backed learnings without starting another agent turn.
5 +## Install / load
7 +Pi loads this extension through the [root pi-ext package](../../README.md).
9 +## Commands / tools / settings
11 +- `/good-job` or `/good-job list` lists learnings.
12 +- `/good-job show <id>` shows one learning.
13 +- `/good-job status` reports queue state.
14 +- `/good-job open` opens the app-data directory.
16 +There are no tools.
17 +By default, analysis uses the current session model.
18 +Set an optional model override in global or project `settings.json`:
20 +```json
22 + "goodJob": {
23 + "model": "provider/model-id",
24 + "thinkingLevel": "xhigh"
25 + }
27 +```
29 +Project settings override global settings.
30 +Records and crash-recoverable queue files live under the platform app-data directory in `pi/good-job`.

extensions/good-job/__benches__/storage.bench.ts

Added
new file mode 100644
1 +import { mkdtemp, rm, writeFile } from "node:fs/promises";
2 +import { tmpdir } from "node:os";
3 +import { join } from "node:path";
4 +import { ensureLayout, layout, loadRecords } from "../storage.ts";
6 +const RECORD_COUNT = Number(process.env.GOOD_JOB_BENCH_RECORDS ?? 1_000);
7 +const MINIMUM_MILLISECONDS = Number(
8 + process.env.GOOD_JOB_BENCH_MILLISECONDS ?? 750,
9 +);
11 +function record(index: number) {
12 + const id = index.toString().padStart(8, "0");
13 + return {
14 + version: 1,
15 + id,
16 + createdAt: "2026-01-01T00:00:00.000Z",
17 + completedAt: `2026-01-01T00:${String(index % 60).padStart(2, "0")}:00.000Z`,
18 + praise: "gj",
19 + source: {
20 + cwd: "/project",
21 + sessionPath: "/sessions/example.jsonl",
22 + sessionId: "session-1",
23 + sessionName: null,
24 + leafId: "leaf-1",
25 + agentModel: { provider: "provider", id: "worker" },
26 + },
27 + analysisModel: { provider: "provider", id: "analyzer" },
28 + learning: {
29 + achievement: `Achievement ${id}`,
30 + evidence: ["Focused tests passed"],
31 + successfulBehaviors: ["Inspected callers before editing"],
32 + candidateRule: "Fix shared routes before leaf callers.",
33 + },
34 + usage: {
35 + input: 100,
36 + output: 50,
37 + cacheRead: 0,
38 + cacheWrite: 0,
39 + totalTokens: 150,
40 + cost: 0,
41 + },
42 + };
45 +async function main(): Promise<void> {
46 + if (!Number.isInteger(RECORD_COUNT) || RECORD_COUNT < 1)
47 + throw new Error("GOOD_JOB_BENCH_RECORDS must be a positive integer");
48 + const root = await mkdtemp(join(tmpdir(), "good-job-bench-"));
49 + const paths = layout(root);
50 + try {
51 + await ensureLayout(paths);
52 + await Promise.all(
53 + Array.from({ length: RECORD_COUNT }, async (_, index) => {
54 + await writeFile(
55 + join(paths.records, `${index.toString().padStart(8, "0")}.json`),
56 + JSON.stringify(record(index)),
57 + );
58 + }),
59 + );
60 + const control = await loadRecords(paths);
61 + if (control.records.length !== RECORD_COUNT || control.errors.length !== 0)
62 + throw new Error("benchmark fixture failed control load");
64 + let iterations = 1;
65 + let elapsed = 0;
66 + const minimumNanoseconds = MINIMUM_MILLISECONDS * 1_000_000;
67 + do {
68 + const start = process.hrtime.bigint();
69 + for (let index = 0; index < iterations; index++) {
70 + const loaded = await loadRecords(paths);
71 + if (
72 + loaded.records.length !== RECORD_COUNT ||
73 + loaded.errors.length !== 0
74 + )
75 + throw new Error("loadRecords returned an invalid result");
76 + }
77 + elapsed = Number(process.hrtime.bigint() - start);
78 + if (elapsed < minimumNanoseconds) iterations *= 2;
79 + } while (elapsed < minimumNanoseconds);
81 + console.log(
82 + `BenchmarkLoadRecords${RECORD_COUNT}-${process.arch}\t${iterations}\t${(elapsed / iterations).toFixed(0)} ns/op`,
83 + );
84 + } finally {
85 + await rm(root, { recursive: true, force: true });
86 + }
89 +await main();

extensions/good-job/__tests__/core.test.ts

Added
new file mode 100644
1 +import { describe, expect, it } from "vitest";
2 +import { analysisPrompt, isGoodJobTrigger, parseLearning } from "../core.js";
4 +describe("good-job core", () => {
5 + it("matches only explicit standalone praise", () => {
6 + for (const trigger of ["gj", "GJ!", " good job ", "Good Job..."])
7 + expect(isGoodJobTrigger(trigger), trigger).toBe(true);
8 + for (const other of [
9 + "great job",
10 + "good job, now continue",
11 + "thanks",
12 + "object.gj",
13 + "",
14 + ])
15 + expect(isGoodJobTrigger(other), other).toBe(false);
16 + });
18 + it("parses and bounds structured learnings", () => {
19 + const learning = parseLearning(`\`\`\`json
21 + "achievement": " Fixed the shared route ",
22 + "evidence": ["All tests passed", "Caller uses one path"],
23 + "successful_behaviors": ["Inspected callers first"],
24 + "candidate_rule": "Fix shared routes before leaf callers."
26 +\`\`\``);
27 + expect(learning).toEqual({
28 + achievement: "Fixed the shared route",
29 + evidence: ["All tests passed", "Caller uses one path"],
30 + successfulBehaviors: ["Inspected callers first"],
31 + candidateRule: "Fix shared routes before leaf callers.",
32 + });
33 + });
35 + it("rejects incomplete model output", () => {
36 + expect(() => parseLearning('{"achievement":"done","evidence":[]}')).toThrow(
37 + "missing required learning fields",
38 + );
39 + });
41 + it("asks for evidence-backed reusable behavior without raw secrets", () => {
42 + const prompt = analysisPrompt("gj");
43 + expect(prompt).toContain("full conversation");
44 + expect(prompt).toContain("successful_behaviors");
45 + expect(prompt).toContain("Do not reproduce credentials");
46 + });
47 +});

extensions/good-job/__tests__/harness.test.ts

Added
new file mode 100644
1 +import path from "node:path";
2 +import { fauxAssistantMessage, fauxProvider } from "@earendil-works/pi-ai";
3 +import { SettingsManager } from "@earendil-works/pi-coding-agent";
4 +import { afterEach, describe, expect, it, vi } from "vitest";
5 +import {
6 + createTestSession,
7 + type TestSession,
8 + withProcessEnv,
9 +} from "../../../test/harness";
10 +import {
11 + counts,
12 + goodJobDataDirectory,
13 + layout,
14 + loadRecords,
15 +} from "../storage.js";
17 +function extensionPath(): string {
18 + return path.resolve(import.meta.dirname, "../index.ts");
21 +async function eventually<T>(
22 + read: () => Promise<T>,
23 + accept: (value: T) => boolean,
24 +): Promise<T> {
25 + const deadline = Date.now() + 3_000;
26 + let value = await read();
27 + while (!accept(value) && Date.now() < deadline) {
28 + await new Promise((resolve) => setTimeout(resolve, 20));
29 + value = await read();
30 + }
31 + return value;
34 +describe("good-job pi-test-harness", () => {
35 + let t: TestSession | undefined;
37 + afterEach(() => {
38 + t?.dispose();
39 + t = undefined;
40 + vi.restoreAllMocks();
41 + });
43 + it("loads through the real Pi runtime with one command and no tools", async () => {
44 + t = await createTestSession({ extensions: [extensionPath()] });
45 + const extension = t.session.extensionRunner.extensions[0];
46 + expect(extension.path).toBe(extensionPath());
47 + expect([...extension.commands.keys()]).toEqual(["good-job"]);
48 + expect([...extension.tools.keys()]).toEqual([]);
49 + expect(
50 + extension.commands.get("good-job").getArgumentCompletions(""),
51 + ).toEqual([
52 + { value: "list", label: "list" },
53 + { value: "show", label: "show" },
54 + { value: "status", label: "status" },
55 + { value: "open", label: "open" },
56 + ]);
57 + });
59 + it("handles praise without an agent turn and persists the analyzed learning", async () => {
60 + t = await createTestSession({ extensions: [extensionPath()] });
61 + const runner = t.session.extensionRunner;
62 + const extension = runner.extensions[0];
63 + const input = extension.handlers.get("input")[0];
64 + const base = runner.createContext();
65 + const faux = fauxProvider({
66 + provider: "good-job-test",
67 + models: [{ id: "worker", maxTokens: 4_096 }],
68 + });
69 + faux.setResponses([
70 + fauxAssistantMessage(
71 + JSON.stringify({
72 + achievement: "Fixed the shared route",
73 + evidence: ["Focused tests passed"],
74 + successful_behaviors: ["Inspected callers before editing"],
75 + candidate_rule: "Fix shared routes before leaf callers.",
76 + }),
77 + ),
78 + ]);
79 + const stream = vi.spyOn(faux.provider, "stream");
80 + base.modelRegistry.registerProvider(faux.provider);
81 + const model = base.modelRegistry.find("good-job-test", "worker");
82 + if (!model) throw new Error("missing faux model");
83 + const ctx = Object.create(base) as typeof base;
84 + Object.defineProperty(ctx, "model", { value: model });
85 + const manager = ctx.sessionManager as any;
86 + manager.appendMessage({
87 + role: "user",
88 + content: "Fix the shared route",
89 + timestamp: Date.now(),
90 + });
91 + manager.appendMessage(
92 + fauxAssistantMessage("Implemented and tested the shared fix."),
93 + );
95 + const result = await withProcessEnv(t.env, () =>
96 + input({ type: "input", text: "good job!", source: "interactive" }, ctx),
97 + );
98 + expect(result).toEqual({ action: "handled" });
100 + const root = goodJobDataDirectory(t.env, process.platform, t.env.HOME);
101 + const loaded = await eventually(
102 + () => loadRecords(layout(root)),
103 + (value) => value.records.length === 1,
104 + );
105 + expect(loaded.errors).toEqual([]);
106 + expect(loaded.records[0]?.learning).toMatchObject({
107 + achievement: "Fixed the shared route",
108 + candidateRule: "Fix shared routes before leaf callers.",
109 + });
110 + expect(loaded.records[0]?.source.cwd).toBe(ctx.cwd);
111 + const sentMessages = stream.mock.calls[0]?.[1].messages ?? [];
112 + expect(sentMessages).toHaveLength(3);
113 + expect(JSON.stringify(sentMessages[1])).toContain(
114 + "Implemented and tested the shared fix.",
115 + );
116 + expect(JSON.stringify(sentMessages[2])).toContain("successful_behaviors");
117 + const notifications = t.events.ui
118 + .filter((call) => call.method === "notify")
119 + .map((call) => call.args[0]);
120 + expect(notifications).toEqual(
121 + expect.arrayContaining([
122 + expect.stringContaining("good-job queued"),
123 + expect.stringContaining("good-job learned"),
124 + ]),
125 + );
126 + const statuses = t.events.ui
127 + .filter((call) => call.method === "setStatus")
128 + .map((call) => call.args);
129 + expect(statuses.some((args) => String(args[1]).includes("good-job"))).toBe(
130 + true,
131 + );
132 + expect(statuses.at(-1)).toEqual(["good-job", undefined]);
134 + await withProcessEnv(t.env, () =>
135 + extension.commands.get("good-job").handler("status", ctx as never),
136 + );
137 + expect(t.events.ui.at(-1)?.args[0]).toContain("1 learnings");
138 + });
140 + it("uses the optional settings model override", async () => {
141 + t = await createTestSession({ extensions: [extensionPath()] });
142 + vi.spyOn(SettingsManager, "create").mockReturnValue(
143 + SettingsManager.inMemory({
144 + goodJob: {
145 + model: "good-job-override/background",
146 + thinkingLevel: "xhigh",
147 + },
148 + }),
149 + );
150 + const runner = t.session.extensionRunner;
151 + const extension = runner.extensions[0];
152 + const input = extension.handlers.get("input")[0];
153 + const base = runner.createContext();
154 + const faux = fauxProvider({
155 + provider: "good-job-override",
156 + models: [
157 + { id: "active", maxTokens: 4_096 },
158 + { id: "background", maxTokens: 4_096 },
159 + ],
160 + });
161 + faux.setResponses([
162 + fauxAssistantMessage(
163 + JSON.stringify({
164 + achievement: "Used configured model",
165 + evidence: ["Override handled the request"],
166 + successful_behaviors: ["Separated background analysis"],
167 + candidate_rule: "Configure background models explicitly.",
168 + }),
169 + ),
170 + ]);
171 + const stream = vi.spyOn(faux.provider, "stream");
172 + base.modelRegistry.registerProvider(faux.provider);
173 + const active = base.modelRegistry.find("good-job-override", "active");
174 + if (!active) throw new Error("missing active faux model");
175 + const ctx = Object.create(base) as typeof base;
176 + Object.defineProperty(ctx, "model", { value: active });
178 + const result = await withProcessEnv(t.env, () =>
179 + input({ type: "input", text: "gj", source: "interactive" }, ctx),
180 + );
181 + expect(result).toEqual({ action: "handled" });
183 + const root = goodJobDataDirectory(t.env, process.platform, t.env.HOME);
184 + const loaded = await eventually(
185 + () => loadRecords(layout(root)),
186 + (value) => value.records.length === 1,
187 + );
188 + expect(loaded.records[0]?.analysisModel).toEqual({
189 + provider: "good-job-override",
190 + id: "background",
191 + });
192 + expect(stream.mock.calls[0]?.[0].id).toBe("background");
193 + expect(stream.mock.calls[0]?.[2]?.reasoning).toBe("xhigh");
194 + });
196 + it("reports invalid settings during startup", async () => {
197 + t = await createTestSession({ extensions: [extensionPath()] });
198 + vi.spyOn(SettingsManager, "create").mockReturnValue(
199 + SettingsManager.inMemory({
200 + goodJob: { thinkingLevel: "invalid" },
201 + } as never),
202 + );
203 + const runner = t.session.extensionRunner;
204 + const start = runner.extensions[0].handlers.get("session_start")[0];
205 + start({ type: "session_start", reason: "startup" }, runner.createContext());
207 + const notification = await eventually(
208 + async () =>
209 + t?.events.ui
210 + .filter((call) => call.method === "notify")
211 + .map((call) => String(call.args[0]))
212 + .find((message) => message.includes("startup failed")),
213 + (value) => value !== undefined,
214 + );
215 + expect(notification).toContain("goodJob.thinkingLevel");
216 + });
218 + it("recovers in-flight work when a new session starts", async () => {
219 + t = await createTestSession({ extensions: [extensionPath()] });
220 + const runner = t.session.extensionRunner;
221 + const extension = runner.extensions[0];
222 + const input = extension.handlers.get("input")[0];
223 + const start = extension.handlers.get("session_start")[0];
224 + const base = runner.createContext();
225 + const faux = fauxProvider({
226 + provider: "good-job-restart",
227 + models: [{ id: "worker", maxTokens: 4_096 }],
228 + });
229 + let releaseFirst = () => {};
230 + let markStarted = () => {};
231 + const firstStarted = new Promise<void>((resolve) => {
232 + markStarted = resolve;
233 + });
234 + let firstAborted = false;
235 + const learning = (achievement: string) =>
236 + fauxAssistantMessage(
237 + JSON.stringify({
238 + achievement,
239 + evidence: ["Session transition completed"],
240 + successful_behaviors: ["Recovered queued work"],
241 + candidate_rule: "Resume claimed work after session changes.",
242 + }),
243 + );
244 + faux.setResponses([
245 + async (_context, options) => {
246 + markStarted();
247 + await new Promise<void>((resolve) => {
248 + releaseFirst = resolve;
249 + options?.signal?.addEventListener(
250 + "abort",
251 + () => {
252 + firstAborted = true;
253 + resolve();
254 + },
255 + { once: true },
256 + );
257 + });
258 + return learning("Stale response");
259 + },
260 + learning("Recovered after session change"),
261 + ]);
262 + base.modelRegistry.registerProvider(faux.provider);
263 + const model = base.modelRegistry.find("good-job-restart", "worker");
264 + if (!model) throw new Error("missing restart faux model");
265 + const ctx = Object.create(base) as typeof base;
266 + Object.defineProperty(ctx, "model", { value: model });
268 + await withProcessEnv(t.env, () =>
269 + input({ type: "input", text: "gj", source: "interactive" }, ctx),
270 + );
271 + await firstStarted;
272 + start({ type: "session_start", reason: "switch" }, ctx);
273 + await new Promise((resolve) => setTimeout(resolve, 50));
274 + releaseFirst();
276 + const root = goodJobDataDirectory(t.env, process.platform, t.env.HOME);
277 + const paths = layout(root);
278 + const loaded = await eventually(
279 + () => loadRecords(paths),
280 + (value) => value.records.length === 1,
281 + );
282 + expect(firstAborted).toBe(true);
283 + expect(loaded.records[0]?.learning.achievement).toBe(
284 + "Recovered after session change",
285 + );
286 + expect(await counts(paths)).toEqual({
287 + pending: 0,
288 + processing: 0,
289 + failed: 0,
290 + records: 1,
291 + });
292 + });
294 + it("ignores non-trigger text", async () => {
295 + t = await createTestSession({ extensions: [extensionPath()] });
296 + const extension = t.session.extensionRunner.extensions[0];
297 + const input = extension.handlers.get("input")[0];
298 + const result = await input(
299 + { type: "input", text: "good job, continue", source: "interactive" },
300 + t.session.extensionRunner.createContext(),
301 + );
302 + expect(result).toEqual({ action: "continue" });
303 + });
304 +});

extensions/good-job/__tests__/storage.test.ts

Added
new file mode 100644
1 +import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
2 +import { tmpdir } from "node:os";
3 +import { join } from "node:path";
4 +import { afterEach, describe, expect, it } from "vitest";
5 +import type { GoodJobJob, GoodJobRecord } from "../core.js";
6 +import { openDirectory, openerFor } from "../implementation.js";
7 +import {
8 + atomicWriteJson,
9 + claimJob,
10 + commitFailure,
11 + commitRecord,
12 + counts,
13 + enqueueJob,
14 + ensureLayout,
15 + goodJobDataDirectory,
16 + layout,
17 + loadRecords,
18 + parseRecord,
19 + recoverProcessing,
20 +} from "../storage.js";
22 +const roots: string[] = [];
24 +function temporaryRoot(): string {
25 + const root = mkdtempSync(join(tmpdir(), "good-job-test-"));
26 + roots.push(root);
27 + return root;
30 +function job(id = "job-1"): GoodJobJob {
31 + return {
32 + version: 1,
33 + id,
34 + createdAt: "2026-01-01T00:00:00.000Z",
35 + praise: "gj",
36 + source: {
37 + cwd: "/repo",
38 + sessionPath: "/sessions/one.jsonl",
39 + sessionId: "session-1",
40 + sessionName: "Shared route",
41 + leafId: "leaf-1",
42 + agentModel: { provider: "provider", id: "worker" },
43 + },
44 + analysisModel: { provider: "provider", id: "worker" },
45 + };
48 +function record(source = job()): GoodJobRecord {
49 + if (!source.analysisModel) throw new Error("fixture analysis model missing");
50 + return {
51 + version: 1,
52 + id: source.id,
53 + createdAt: source.createdAt,
54 + completedAt: "2026-01-01T00:01:00.000Z",
55 + praise: source.praise,
56 + source: source.source,
57 + analysisModel: source.analysisModel,
58 + learning: {
59 + achievement: "Fixed the shared route",
60 + evidence: ["Tests passed"],
61 + successfulBehaviors: ["Inspected callers"],
62 + candidateRule: "Fix shared routes first.",
63 + },
64 + usage: {
65 + input: 10,
66 + output: 5,
67 + cacheRead: 0,
68 + cacheWrite: 0,
69 + totalTokens: 15,
70 + cost: 0.01,
71 + },
72 + };
75 +afterEach(() => {
76 + for (const root of roots.splice(0))
77 + rmSync(root, { recursive: true, force: true });
78 +});
80 +describe("good-job storage", () => {
81 + it("uses platform app-data directories", () => {
82 + expect(
83 + goodJobDataDirectory({ XDG_DATA_HOME: "/data" }, "linux", "/home/o"),
84 + ).toBe("/data/pi/good-job");
85 + expect(
86 + goodJobDataDirectory(
87 + { LOCALAPPDATA: "C:\\Users\\o\\AppData\\Local" },
88 + "win32",
89 + "C:\\Users\\o",
90 + ),
91 + ).toBe("C:\\Users\\o\\AppData\\Local\\pi\\good-job");
92 + expect(goodJobDataDirectory({}, "darwin", "/Users/o")).toBe(
93 + "/Users/o/Library/Application Support/pi/good-job",
94 + );
95 + });
97 + it("rejects records with incomplete or invalid usage", () => {
98 + const valid = record();
99 + expect(parseRecord(valid)).toEqual(valid);
100 + expect(parseRecord({ ...valid, usage: {} })).toBeUndefined();
101 + expect(
102 + parseRecord({ ...valid, usage: { ...valid.usage, input: "10" } }),
103 + ).toBeUndefined();
104 + expect(
105 + parseRecord({ ...valid, usage: { ...valid.usage, cost: -1 } }),
106 + ).toBeUndefined();
107 + });
109 + it("claims jobs atomically and commits immutable records", async () => {
110 + const paths = layout(temporaryRoot());
111 + await ensureLayout(paths);
112 + const queued = job();
113 + await enqueueJob(queued, paths);
114 + expect(await counts(paths)).toMatchObject({ pending: 1, processing: 0 });
116 + const claimed = await claimJob(queued.id, paths);
117 + expect(claimed?.job).toEqual(queued);
118 + expect(await claimJob(queued.id, paths)).toBeUndefined();
119 + expect(await counts(paths)).toMatchObject({ pending: 0, processing: 1 });
120 + if (!claimed) throw new Error("missing claimed job");
122 + await commitRecord(record(queued), claimed.path, paths);
123 + expect(await counts(paths)).toEqual({
124 + pending: 0,
125 + processing: 0,
126 + failed: 0,
127 + records: 1,
128 + });
129 + expect((await loadRecords(paths)).records[0]?.learning.achievement).toBe(
130 + "Fixed the shared route",
131 + );
132 + });
134 + it("loads valid records concurrently while preserving sort and errors", async () => {
135 + const paths = layout(temporaryRoot());
136 + await ensureLayout(paths);
137 + const older = record(job("older"));
138 + const newer = record(job("newer"));
139 + older.completedAt = "2026-01-01T00:01:00.000Z";
140 + newer.completedAt = "2026-01-02T00:01:00.000Z";
141 + await Promise.all([
142 + atomicWriteJson(join(paths.records, "older.json"), older),
143 + atomicWriteJson(join(paths.records, "newer.json"), newer),
144 + ]);
145 + writeFileSync(join(paths.records, "broken.json"), "not json", "utf8");
147 + const loaded = await loadRecords(paths);
148 + expect(loaded.records.map(({ id }) => id)).toEqual(["newer", "older"]);
149 + expect(loaded.errors).toHaveLength(1);
150 + expect(loaded.errors[0]).toContain("broken.json");
151 + });
153 + it("persists failed analysis before releasing its processing claim", async () => {
154 + const paths = layout(temporaryRoot());
155 + await ensureLayout(paths);
156 + await enqueueJob(job("failed"), paths);
157 + const claimed = await claimJob("failed", paths);
158 + if (!claimed) throw new Error("missing claimed job");
159 + await commitFailure(
160 + claimed.job,
161 + new Error("provider unavailable"),
162 + claimed.path,
163 + paths,
164 + );
165 + expect(await counts(paths)).toMatchObject({
166 + pending: 0,
167 + processing: 0,
168 + failed: 1,
169 + });
170 + });
172 + it("recovers interrupted processing without duplicating completed work", async () => {
173 + const paths = layout(temporaryRoot());
174 + await ensureLayout(paths);
175 + await enqueueJob(job("retry"), paths);
176 + await claimJob("retry", paths);
177 + await recoverProcessing(paths);
178 + expect(await counts(paths)).toMatchObject({ pending: 1, processing: 0 });
180 + const claimed = await claimJob("retry", paths);
181 + if (!claimed) throw new Error("missing recovered job");
182 + await commitRecord(record(claimed.job), claimed.path, paths);
183 + await recoverProcessing(paths);
184 + expect(await counts(paths)).toMatchObject({ processing: 0, records: 1 });
185 + });
187 + it("resolves Linux openers from PATH and launches the selected opener", async () => {
188 + const root = temporaryRoot();
189 + const executable = join(root, "xdg-open");
190 + writeFileSync(executable, "#!/bin/sh\nexit 0\n", "utf8");
191 + chmodSync(executable, 0o755);
192 + expect(openerFor("linux", { PATH: root })).toEqual({
193 + command: executable,
194 + args: [],
195 + });
196 + await expect(
197 + openDirectory(root, {
198 + command: process.execPath,
199 + args: ["-e", "process.exit(0)", "--"],
200 + }),
201 + ).resolves.toBeUndefined();
202 + });
203 +});

extensions/good-job/__tests__/ui.test.ts

Added
new file mode 100644
1 +import { visibleWidth } from "@earendil-works/pi-tui";
2 +import { describe, expect, it, vi } from "vitest";
3 +import type { GoodJobRecord } from "../core.js";
4 +import { formatLearningMarkdown, LearningListComponent } from "../ui.js";
6 +const record: GoodJobRecord = {
7 + version: 1,
8 + id: "12345678-1234-1234-1234-123456789abc",
9 + createdAt: "2026-01-01T00:00:00.000Z",
10 + completedAt: "2026-01-01T00:01:00.000Z",
11 + praise: "gj",
12 + source: {
13 + cwd: "/work/shared-route",
14 + sessionPath: "/sessions/one.jsonl",
15 + sessionId: "session-1",
16 + sessionName: "Shared route",
17 + leafId: "leaf-1",
18 + agentModel: { provider: "openai", id: "worker" },
19 + },
20 + analysisModel: { provider: "openai", id: "worker" },
21 + learning: {
22 + achievement: "Fixed the shared route",
23 + evidence: ["All focused tests passed"],
24 + successfulBehaviors: ["Inspected callers before editing"],
25 + candidateRule: "Fix the shared route before leaf callers.",
26 + },
27 + usage: {
28 + input: 10,
29 + output: 5,
30 + cacheRead: 0,
31 + cacheWrite: 0,
32 + totalTokens: 15,
33 + cost: 0.01,
34 + },
35 +};
37 +describe("good-job UI", () => {
38 + it("renders labeled learning sections instead of JSON", () => {
39 + const markdown = formatLearningMarkdown(record);
40 + expect(markdown).toContain("## Achievement\nFixed the shared route");
41 + expect(markdown).toContain("## Evidence\n- All focused tests passed");
42 + expect(markdown).toContain("## Successful behaviors");
43 + expect(markdown).toContain("## Candidate rule");
44 + expect(markdown).not.toContain('"learning"');
45 + });
47 + it("renders a width-safe searchable list and returns the selected id", () => {
48 + const done = vi.fn();
49 + const requestRender = vi.fn();
50 + const theme = {
51 + fg: (_color: string, text: string) => text,
52 + bold: (text: string) => text,
53 + } as never;
54 + const component = new LearningListComponent(
55 + theme,
56 + [record],
57 + { pending: 1, processing: 0, failed: 0, records: 1 },
58 + requestRender,
59 + done,
60 + );
61 + for (const character of "route") component.handleInput(character);
62 + const lines = component.render(48);
63 + expect(lines.join("\n")).toContain("Fixed the shared route");
64 + expect(lines.every((line) => visibleWidth(line) <= 48)).toBe(true);
65 + expect(requestRender).toHaveBeenCalled();
66 + component.handleInput("\r");
67 + expect(done).toHaveBeenCalledWith(record.id);
68 + });
69 +});

extensions/good-job/core.ts

Added
new file mode 100644
1 +import type { AssistantMessage } from "@earendil-works/pi-ai";
3 +export const JOB_VERSION = 1 as const;
4 +export const RECORD_VERSION = 1 as const;
5 +export const FAILURE_VERSION = 1 as const;
7 +export interface ModelRef {
8 + provider: string;
9 + id: string;
12 +export interface LearningSource {
13 + cwd: string;
14 + sessionPath: string | null;
15 + sessionId: string;
16 + sessionName: string | null;
17 + leafId: string | null;
18 + agentModel: ModelRef | null;
21 +export interface GoodJobJob {
22 + version: typeof JOB_VERSION;
23 + id: string;
24 + createdAt: string;
25 + praise: string;
26 + source: LearningSource;
27 + analysisModel: ModelRef | null;
30 +export interface Learning {
31 + achievement: string;
32 + evidence: string[];
33 + successfulBehaviors: string[];
34 + candidateRule: string | null;
37 +export interface GoodJobRecord {
38 + version: typeof RECORD_VERSION;
39 + id: string;
40 + createdAt: string;
41 + completedAt: string;
42 + praise: string;
43 + source: LearningSource;
44 + analysisModel: ModelRef;
45 + learning: Learning;
46 + usage: {
47 + input: number;
48 + output: number;
49 + cacheRead: number;
50 + cacheWrite: number;
51 + totalTokens: number;
52 + cost: number;
53 + };
56 +export interface GoodJobFailure {
57 + version: typeof FAILURE_VERSION;
58 + job: GoodJobJob;
59 + failedAt: string;
60 + error: string;
63 +const CONTROL_CHARACTERS = /[\x00-\x1F\x7F-\x9F]/g;
64 +const TRIGGER = /^(?:gj|good\s+job)[.!?]*$/i;
65 +const MAX_ACHIEVEMENT_CHARS = 180;
66 +const MAX_ITEM_CHARS = 500;
67 +const MAX_RULE_CHARS = 700;
68 +const MAX_ITEMS = 8;
70 +export function isGoodJobTrigger(text: string): boolean {
71 + return TRIGGER.test(text.trim());
74 +export function cleanText(text: string, maximum: number): string {
75 + const cleaned = text
76 + .replace(CONTROL_CHARACTERS, " ")
77 + .replace(/\s+/g, " ")
78 + .trim();
79 + return Array.from(cleaned).slice(0, maximum).join("");
82 +function isRecord(value: unknown): value is Record<string, unknown> {
83 + return value !== null && typeof value === "object" && !Array.isArray(value);
86 +function cleanStringArray(value: unknown): string[] | undefined {
87 + if (!Array.isArray(value)) return undefined;
88 + const strings = value
89 + .slice(0, MAX_ITEMS)
90 + .map((item) =>
91 + typeof item === "string" ? cleanText(item, MAX_ITEM_CHARS) : "",
92 + )
93 + .filter(Boolean);
94 + return strings.length > 0 ? strings : undefined;
97 +function jsonObject(text: string): unknown {
98 + const trimmed = text.trim();
99 + const unfenced = trimmed
100 + .replace(/^```(?:json)?\s*/i, "")
101 + .replace(/\s*```$/, "")
102 + .trim();
103 + const start = unfenced.indexOf("{");
104 + const end = unfenced.lastIndexOf("}");
105 + if (start < 0 || end < start) throw new Error("analysis did not return JSON");
106 + return JSON.parse(unfenced.slice(start, end + 1));
109 +export function parseLearning(text: string): Learning {
110 + const value = jsonObject(text);
111 + if (!isRecord(value)) throw new Error("analysis returned a non-object");
112 + const achievement =
113 + typeof value.achievement === "string"
114 + ? cleanText(value.achievement, MAX_ACHIEVEMENT_CHARS)
115 + : "";
116 + const evidence = cleanStringArray(value.evidence);
117 + const successfulBehaviors = cleanStringArray(
118 + value.successful_behaviors ?? value.successfulBehaviors,
119 + );
120 + const candidateValue = value.candidate_rule ?? value.candidateRule;
121 + const candidateRule =
122 + candidateValue === null
123 + ? null
124 + : typeof candidateValue === "string"
125 + ? cleanText(candidateValue, MAX_RULE_CHARS)
126 + : undefined;
127 + if (!achievement || !evidence || !successfulBehaviors)
128 + throw new Error("analysis JSON is missing required learning fields");
129 + if (candidateRule === undefined)
130 + throw new Error("analysis JSON is missing candidate_rule");
131 + return { achievement, evidence, successfulBehaviors, candidateRule };
134 +export function responseText(response: AssistantMessage): string {
135 + return response.content
136 + .filter(
137 + (part): part is { type: "text"; text: string } => part.type === "text",
139 + .map((part) => part.text)
140 + .join("\n");
143 +export function analysisPrompt(praise: string): string {
144 + return `The user just praised the preceding coding-agent work with: ${JSON.stringify(praise)}
146 +Analyze what concretely went well across the full conversation above.
147 +Infer causes only when supported by the transcript.
148 +Focus on reusable agent behavior, not compliments or personality.
149 +Do not reproduce credentials, secrets, long source excerpts, or private data.
150 +Return exactly one JSON object with this shape:
152 + "achievement": "one concrete summary, at most 180 characters",
153 + "evidence": ["observable result or user-visible outcome"],
154 + "successful_behaviors": ["specific agent decision or behavior that contributed"],
155 + "candidate_rule": "concise reusable instruction for future agents, or null when evidence is insufficient"
157 +Use 1-8 concise items per array.
158 +No markdown fences or commentary.`;
161 +export function lastAgentModel(messages: readonly unknown[]): ModelRef | null {
162 + for (let index = messages.length - 1; index >= 0; index--) {
163 + const message = messages[index];
164 + if (!isRecord(message) || message.role !== "assistant") continue;
165 + if (
166 + typeof message.provider !== "string" ||
167 + typeof message.model !== "string"
169 + continue;
170 + return { provider: message.provider, id: message.model };
172 + return null;
175 +export function boundedError(error: unknown): string {
176 + const message = error instanceof Error ? error.message : String(error);
177 + return cleanText(message, 300) || "unknown error";

extensions/good-job/implementation.ts

Added
new file mode 100644
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";
6 +import {
7 + buildSessionContext,
8 + convertToLlm,
9 + type ExtensionContext,
10 + SessionManager,
11 + SettingsManager,
12 +} from "@earendil-works/pi-coding-agent";
13 +import {
14 + analysisPrompt,
15 + boundedError,
16 + type GoodJobJob,
17 + type GoodJobRecord,
18 + JOB_VERSION,
19 + lastAgentModel,
20 + type ModelRef,
21 + parseLearning,
22 + RECORD_VERSION,
23 + responseText,
24 +} from "./core.js";
25 +import {
26 + claimJob,
27 + commitFailure,
28 + commitRecord,
29 + counts,
30 + enqueueJob,
31 + ensureLayout,
32 + type GoodJobLayout,
33 + goodJobDataDirectory,
34 + layout,
35 + loadRecords,
36 + pendingJobIds,
37 + recoverProcessing,
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 = {
49 + model?: string;
50 + thinkingLevel?: ThinkingLevel;
51 +};
53 +const THINKING_LEVELS = new Set<ThinkingLevel>([
54 + "minimal",
55 + "low",
56 + "medium",
57 + "high",
58 + "xhigh",
59 + "max",
60 +]);
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;
81 + return {
82 + provider: trimmed.slice(0, separator),
83 + id: trimmed.slice(separator + 1),
84 + };
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>;
91 + const merged = {
92 + ...(isObject(global.goodJob) ? global.goodJob : {}),
93 + ...(isObject(project.goodJob) ? project.goodJob : {}),
94 + };
95 + const thinkingLevel = merged.thinkingLevel;
96 + if (
97 + thinkingLevel !== undefined &&
98 + (typeof thinkingLevel !== "string" ||
99 + !THINKING_LEVELS.has(thinkingLevel as ThinkingLevel))
101 + throw new Error(
102 + "goodJob.thinkingLevel must be minimal, low, medium, high, xhigh, or max",
103 + );
104 + return {
105 + model:
106 + typeof merged.model === "string" && merged.model.trim()
107 + ? merged.model.trim()
108 + : undefined,
109 + thinkingLevel: thinkingLevel as ThinkingLevel | undefined,
110 + };
113 +function sourceFor(
114 + ctx: ExtensionContext,
115 + messages: readonly unknown[],
116 +): GoodJobJob["source"] {
117 + return {
118 + cwd: ctx.cwd,
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),
124 + };
127 +function completionContext(
128 + conversation: readonly Message[],
129 + praise: string,
130 +): Message[] {
131 + return [
132 + ...conversation,
134 + role: "user",
135 + content: [{ type: "text", text: analysisPrompt(praise) }],
136 + timestamp: Date.now(),
137 + },
138 + ];
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(),
149 + job.source.leafId,
150 + ).messages;
151 + return convertToLlm(context);
154 +function findExecutable(
155 + name: string,
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);
160 + try {
161 + accessSync(candidate, constants.X_OK);
162 + return candidate;
163 + } catch {
164 + // Keep searching PATH.
167 + return undefined;
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: [] }
179 + : undefined;
181 + if (platform === "darwin")
182 + return existsSync("/usr/bin/open")
183 + ? { command: "/usr/bin/open", args: [] }
184 + : undefined;
185 + const executable = findExecutable("xdg-open", env);
186 + return executable ? { command: executable, args: [] } : undefined;
189 +export function openDirectory(
190 + path: string,
191 + opener = openerFor(),
192 +): Promise<void> {
193 + if (!opener)
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], {
197 + detached: true,
198 + stdio: "ignore",
199 + windowsHide: true,
200 + });
201 + child.once("error", reject);
202 + child.once("spawn", () => {
203 + child.unref();
204 + resolve();
205 + });
206 + });
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)
240 + ctx.ui.notify(
241 + "good-job: directory opening unavailable; no platform opener found",
242 + "info",
243 + );
245 + if (!existsSync(this.paths.root)) return;
246 + await this.recoverAndPump(ctx, generation);
249 + async stop(ctx: ExtensionContext): Promise<void> {
250 + this.generation++;
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(),
263 + );
264 + const snapshot = convertToLlm(sessionContext.messages);
265 + const job: GoodJobJob = {
266 + version: JOB_VERSION,
267 + id: randomUUID(),
268 + createdAt: new Date().toISOString(),
269 + praise: praise.trim(),
270 + source: sourceFor(ctx, sessionContext.messages),
271 + analysisModel: this.analysisModel(ctx),
272 + };
273 + await ensureLayout(this.paths);
274 + await enqueueJob(job, this.paths);
275 + this.snapshots.set(job.id, snapshot);
276 + if (ctx.hasUI)
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);
286 + return;
288 + if (command === "show") {
289 + await this.show(id, ctx);
290 + return;
292 + if (command === "status") {
293 + await this.status(ctx);
294 + return;
296 + if (command === "open") {
297 + await this.open(ctx);
298 + return;
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);
312 + if (!configured)
313 + throw new Error(
314 + `invalid goodJob.model ${JSON.stringify(this.settings.model)}; expected provider/model`,
315 + );
316 + return configured;
319 + private async recoverAndPump(
320 + ctx: ExtensionContext,
321 + generation: number,
322 + ): Promise<void> {
323 + await ensureLayout(this.paths);
324 + await recoverProcessing(this.paths);
325 + if (generation === this.generation) void this.pump(ctx, generation);
328 + private pump(
329 + ctx: ExtensionContext,
330 + generation: number,
331 + preferredId?: string,
332 + ): Promise<void> {
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)
341 + ctx.ui.notify(
342 + `good-job queue failed: ${boundedError(error)}`,
343 + "error",
344 + );
345 + })
346 + .finally(() => {
347 + this.pumpPromise = undefined;
348 + if (this.pumpRequested && generation === this.generation)
349 + void this.pump(ctx, generation);
350 + });
351 + return this.pumpPromise;
354 + private async pumpJobs(
355 + ctx: ExtensionContext,
356 + generation: number,
357 + preferredId?: string,
358 + ): Promise<void> {
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);
363 + try {
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);
371 + } finally {
372 + this.stopSpinner(ctx);
376 + private async process(
377 + job: GoodJobJob,
378 + claimPath: string,
379 + ctx: ExtensionContext,
380 + generation: number,
381 + ): Promise<void> {
382 + const controller = new AbortController();
383 + this.activeController = controller;
384 + try {
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,
390 + );
391 + if (!model)
392 + throw new Error(
393 + `analysis model ${job.analysisModel.provider}/${job.analysisModel.id} is unavailable`,
394 + );
395 + const snapshot = this.snapshots.get(job.id) ?? contextFromSession(job);
396 + const response = await ctx.modelRegistry.complete(
397 + model,
399 + systemPrompt:
400 + "Extract evidence-backed, reusable lessons from praised coding-agent work.",
401 + messages: completionContext(snapshot, job.praise),
402 + },
404 + maxTokens: MAX_TOKENS,
405 + reasoning: this.settings.thinkingLevel,
406 + cacheRetention: "none",
407 + sessionId: job.id,
408 + signal: controller.signal,
409 + },
410 + );
411 + if (controller.signal.aborted || generation !== this.generation) return;
412 + if (response.stopReason !== "stop")
413 + throw new Error(
414 + response.errorMessage ||
415 + `analysis stopped with ${response.stopReason}`,
416 + );
417 + const learning = parseLearning(responseText(response));
418 + const record: GoodJobRecord = {
419 + version: RECORD_VERSION,
420 + id: job.id,
421 + createdAt: job.createdAt,
422 + completedAt: new Date().toISOString(),
423 + praise: job.praise,
424 + source: job.source,
425 + analysisModel: job.analysisModel,
426 + learning,
427 + usage: {
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,
434 + },
435 + };
436 + await commitRecord(record, claimPath, this.paths);
437 + this.snapshots.delete(job.id);
438 + if (ctx.hasUI)
439 + ctx.ui.notify(
440 + `good-job learned · ${record.learning.achievement}`,
441 + "info",
442 + );
443 + } catch (error) {
444 + if (controller.signal.aborted || generation !== this.generation) return;
445 + try {
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);
451 + if (ctx.hasUI)
452 + ctx.ui.notify(`good-job failed: ${boundedError(error)}`, "error");
453 + } finally {
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 = () => {
465 + const frame =
466 + SPINNER[
467 + Math.floor((Date.now() - this.spinnerStartedAt) / 120) %
468 + SPINNER.length
469 + ] ?? SPINNER[0];
470 + ctx.ui.setStatus(
471 + STATUS_KEY,
472 + ctx.ui.theme.fg(
473 + "accent",
474 + `${frame} good-job learning${this.spinnerCount > 1 ? ` (${this.spinnerCount})` : ""}`,
475 + ),
476 + );
477 + };
478 + render();
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)
492 + ctx.ui.notify(
493 + `${loaded.errors.length} unreadable good-job record${loaded.errors.length === 1 ? "" : "s"}`,
494 + "warning",
495 + );
496 + if (loaded.records.length === 0) {
497 + ctx.ui.notify("No good-job learnings yet", "info");
498 + return;
500 + const selected = await showLearningList(
501 + ctx,
502 + loaded.records,
503 + await counts(this.paths),
504 + );
505 + if (!selected) return;
506 + const record = loaded.records.find(
507 + (candidate) => candidate.id === selected,
508 + );
509 + if (record) await showLearningDetail(ctx, record);
512 + private async show(id: string, ctx: ExtensionContext): Promise<void> {
513 + if (!id) {
514 + ctx.ui.notify("Usage: /good-job show <id>", "warning");
515 + return;
517 + const loaded = await loadRecords(this.paths);
518 + const matches = loaded.records.filter((record) => record.id.startsWith(id));
519 + if (matches.length !== 1) {
520 + ctx.ui.notify(
521 + matches.length === 0
522 + ? `Unknown good-job id: ${id}`
523 + : `Ambiguous good-job id: ${id}`,
524 + "warning",
525 + );
526 + return;
528 + await showLearningDetail(ctx, matches[0] as GoodJobRecord);
531 + private async status(ctx: ExtensionContext): Promise<void> {
532 + const state = await counts(this.paths);
533 + ctx.ui.notify(
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"}`,
541 + this.paths.root,
542 + ].join(" · "),
543 + state.failed ? "warning" : "info",
544 + );
547 + private async open(ctx: ExtensionContext): Promise<void> {
548 + await ensureLayout(this.paths);
549 + try {
550 + await openDirectory(this.paths.root, this.opener);
551 + } catch (error) {
552 + ctx.ui.notify(`good-job open failed: ${boundedError(error)}`, "error");
553 + return;
555 + ctx.ui.notify(`Opened ${basename(this.paths.root)}`, "info");
559 +export function createGoodJobRuntime(
560 + root = goodJobDataDirectory(),
561 +): GoodJobRuntime {
562 + return new Runtime(root);

extensions/good-job/index.ts

Added
new file mode 100644
1 +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2 +import type { AutocompleteItem } from "@earendil-works/pi-tui";
3 +import { boundedError, isGoodJobTrigger } from "./core.js";
4 +import type { GoodJobRuntime } from "./implementation.js";
6 +const SUBCOMMANDS = ["list", "show", "status", "open"] as const;
8 +export default function goodJobExtension(pi: ExtensionAPI): void {
9 + let runtime: Promise<GoodJobRuntime> | undefined;
10 + let generation = 0;
11 + let sessionReady: Promise<void> = Promise.resolve();
12 + const getRuntime = () =>
13 + (runtime ??= import("./implementation.js").then(
14 + ({ createGoodJobRuntime }) => createGoodJobRuntime(),
15 + ));
17 + pi.registerCommand("good-job", {
18 + description: "List, inspect, and locate praised-work learnings",
19 + getArgumentCompletions(prefix): AutocompleteItem[] | null {
20 + const normalized = prefix.trimStart().toLowerCase();
21 + if (normalized.includes(" ")) return null;
22 + const matches = SUBCOMMANDS.filter((command) =>
23 + command.startsWith(normalized),
24 + ).map((command) => ({ value: command, label: command }));
25 + return matches.length ? matches : null;
26 + },
27 + async handler(args, ctx) {
28 + await sessionReady;
29 + await (await getRuntime()).runCommand(args, ctx);
30 + },
31 + });
33 + pi.on("input", async (event, ctx) => {
34 + if (event.source === "extension" || !isGoodJobTrigger(event.text))
35 + return { action: "continue" };
36 + try {
37 + await sessionReady;
38 + await (await getRuntime()).capture(event.text, ctx);
39 + } catch (error) {
40 + const message = error instanceof Error ? error.message : String(error);
41 + if (ctx.hasUI)
42 + ctx.ui.notify(`good-job could not queue: ${message}`, "error");
43 + }
44 + return { action: "handled" };
45 + });
47 + pi.on("session_start", (_event, ctx) => {
48 + const currentGeneration = ++generation;
49 + const ui = ctx.hasUI ? ctx.ui : undefined;
50 + sessionReady = getRuntime()
51 + .then((loaded) => {
52 + if (generation === currentGeneration) return loaded.start(ctx);
53 + })
54 + .catch((error) => {
55 + if (generation === currentGeneration)
56 + ui?.notify(
57 + `good-job startup failed: ${boundedError(error)}`,
58 + "error",
59 + );
60 + });
61 + });
63 + pi.on("session_shutdown", async (_event, ctx) => {
64 + generation++;
65 + await sessionReady;
66 + const loaded = await runtime?.catch(() => undefined);
67 + if (loaded) await loaded.stop(ctx);
68 + });

extensions/good-job/mise.toml

Added
new file mode 100644
1 +[tasks.fmt]
2 +description = "Format good-job"
3 +depends = ["//:install"]
4 +run = [
5 + "biome check --write .",
6 + "rumdl fmt README.md",
7 + "taplo format mise.toml",
8 +]
10 +[tasks.lint]
11 +description = "Verify good-job formatting and lint"
12 +depends = ["//:install"]
13 +run = [
14 + "biome ci .",
15 + "rumdl check README.md",
16 + "taplo format --check mise.toml",
19 +[tasks.bench]
20 +description = "Benchmark loading persisted good-job records"
21 +depends = ["//:install"]
22 +run = "npm run bench"

extensions/good-job/package.json

Added
new file mode 100644
1 +{
2 + "name": "@bugabinga/pi-ext-good-job",
3 + "private": true,
4 + "type": "module",
5 + "main": "index.ts",
6 + "license": "MIT",
7 + "description": "Turn explicit praise into durable coding-agent learnings.",
8 + "keywords": [
9 + "pi",
10 + "pi-extension"
11 + ],
12 + "peerDependencies": {
13 + "@earendil-works/pi-ai": "*",
14 + "@earendil-works/pi-coding-agent": "*",
15 + "@earendil-works/pi-tui": "*"
16 + },
17 + "devDependencies": {
18 + "@marcfargas/pi-test-harness": "^0.6.1",
19 + "vitest": "^4.1.9"
20 + },
21 + "scripts": {
22 + "bench": "node --no-warnings --experimental-strip-types --experimental-loader ../../scripts/ts-js-loader.mjs __benches__/storage.bench.ts",
23 + "test": "vitest run --root ../.. ../../extensions/good-job",
24 + "test:harness": "vitest run --root ../.. ../../extensions/good-job/__tests__/harness.test.ts"
25 + }

extensions/good-job/storage.ts

Added
new file mode 100644
1 +import { randomUUID } from "node:crypto";
2 +import { mkdir, open, readdir, readFile, rename, rm } from "node:fs/promises";
3 +import { homedir } from "node:os";
4 +import { basename, dirname, join, posix, win32 } from "node:path";
5 +import type {
6 + GoodJobFailure,
7 + GoodJobJob,
8 + GoodJobRecord,
9 + LearningSource,
10 + ModelRef,
11 +} from "./core.js";
12 +import {
13 + boundedError,
14 + FAILURE_VERSION,
15 + JOB_VERSION,
16 + RECORD_VERSION,
17 +} from "./core.js";
19 +export interface GoodJobLayout {
20 + root: string;
21 + pending: string;
22 + processing: string;
23 + failed: string;
24 + records: string;
27 +export interface GoodJobCounts {
28 + pending: number;
29 + processing: number;
30 + failed: number;
31 + records: number;
34 +export interface ClaimedJob {
35 + job: GoodJobJob;
36 + path: string;
39 +export interface LoadedRecords {
40 + records: GoodJobRecord[];
41 + errors: string[];
44 +export function goodJobDataDirectory(
45 + env: NodeJS.ProcessEnv = process.env,
46 + platform = process.platform,
47 + home = homedir(),
48 +): string {
49 + if (platform === "win32") {
50 + const base = env.LOCALAPPDATA?.trim() || env.APPDATA?.trim();
51 + return win32.join(
52 + base || win32.join(home, "AppData", "Local"),
53 + "pi",
54 + "good-job",
55 + );
56 + }
57 + if (platform === "darwin")
58 + return posix.join(home, "Library", "Application Support", "pi", "good-job");
59 + return posix.join(
60 + env.XDG_DATA_HOME?.trim() || posix.join(home, ".local", "share"),
61 + "pi",
62 + "good-job",
63 + );
66 +export function layout(root = goodJobDataDirectory()): GoodJobLayout {
67 + return {
68 + root,
69 + pending: join(root, "queue", "pending"),
70 + processing: join(root, "queue", "processing"),
71 + failed: join(root, "queue", "failed"),
72 + records: join(root, "records"),
73 + };
76 +export async function ensureLayout(paths: GoodJobLayout): Promise<void> {
77 + await Promise.all(
78 + [paths.pending, paths.processing, paths.failed, paths.records].map(
79 + (directory) => mkdir(directory, { recursive: true, mode: 0o700 }),
80 + ),
81 + );
84 +function isNodeError(error: unknown): error is NodeJS.ErrnoException {
85 + return error instanceof Error && "code" in error;
88 +async function jsonFiles(directory: string): Promise<string[]> {
89 + try {
90 + return (await readdir(directory))
91 + .filter((file) => file.endsWith(".json"))
92 + .sort();
93 + } catch (error) {
94 + if (isNodeError(error) && error.code === "ENOENT") return [];
95 + throw error;
96 + }
99 +async function syncDirectory(directory: string): Promise<void> {
100 + if (process.platform === "win32") return;
101 + try {
102 + const handle = await open(directory, "r");
103 + try {
104 + await handle.sync();
105 + } finally {
106 + await handle.close();
108 + } catch {
109 + // File fsync plus rename is the portable durability floor.
113 +export async function atomicWriteJson(
114 + target: string,
115 + value: unknown,
116 +): Promise<void> {
117 + const directory = dirname(target);
118 + await mkdir(directory, { recursive: true, mode: 0o700 });
119 + const temporary = join(
120 + directory,
121 + `.${basename(target)}.${process.pid}.${randomUUID()}.tmp`,
122 + );
123 + const file = await open(temporary, "wx", 0o600);
124 + try {
125 + await file.writeFile(`${JSON.stringify(value)}\n`, "utf8");
126 + await file.sync();
127 + } catch (error) {
128 + await file.close().catch(() => {});
129 + await rm(temporary, { force: true });
130 + throw error;
132 + await file.close();
133 + try {
134 + await rename(temporary, target);
135 + await syncDirectory(directory);
136 + } catch (error) {
137 + await rm(temporary, { force: true });
138 + throw error;
142 +function modelRef(value: unknown): value is ModelRef {
143 + return (
144 + isObject(value) &&
145 + typeof value.provider === "string" &&
146 + value.provider.length > 0 &&
147 + typeof value.id === "string" &&
148 + value.id.length > 0
149 + );
152 +function source(value: unknown): value is LearningSource {
153 + return (
154 + isObject(value) &&
155 + typeof value.cwd === "string" &&
156 + (value.sessionPath === null || typeof value.sessionPath === "string") &&
157 + typeof value.sessionId === "string" &&
158 + (value.sessionName === null || typeof value.sessionName === "string") &&
159 + (value.leafId === null || typeof value.leafId === "string") &&
160 + (value.agentModel === null || modelRef(value.agentModel))
161 + );
164 +function isObject(value: unknown): value is Record<string, unknown> {
165 + return value !== null && typeof value === "object" && !Array.isArray(value);
168 +function stringArray(value: unknown): value is string[] {
169 + return (
170 + Array.isArray(value) &&
171 + value.length > 0 &&
172 + value.every((item) => typeof item === "string" && item.length > 0)
173 + );
176 +function nonnegativeInteger(value: unknown): value is number {
177 + return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
180 +function recordUsage(value: unknown): boolean {
181 + return (
182 + isObject(value) &&
183 + nonnegativeInteger(value.input) &&
184 + nonnegativeInteger(value.output) &&
185 + nonnegativeInteger(value.cacheRead) &&
186 + nonnegativeInteger(value.cacheWrite) &&
187 + nonnegativeInteger(value.totalTokens) &&
188 + typeof value.cost === "number" &&
189 + Number.isFinite(value.cost) &&
190 + value.cost >= 0
191 + );
194 +export function parseJob(value: unknown): GoodJobJob | undefined {
195 + if (
196 + !isObject(value) ||
197 + value.version !== JOB_VERSION ||
198 + typeof value.id !== "string" ||
199 + typeof value.createdAt !== "string" ||
200 + typeof value.praise !== "string" ||
201 + !source(value.source) ||
202 + !(value.analysisModel === null || modelRef(value.analysisModel))
204 + return undefined;
205 + return value as unknown as GoodJobJob;
208 +export function parseRecord(value: unknown): GoodJobRecord | undefined {
209 + if (
210 + !isObject(value) ||
211 + value.version !== RECORD_VERSION ||
212 + typeof value.id !== "string" ||
213 + typeof value.createdAt !== "string" ||
214 + typeof value.completedAt !== "string" ||
215 + typeof value.praise !== "string" ||
216 + !source(value.source) ||
217 + !modelRef(value.analysisModel) ||
218 + !isObject(value.learning) ||
219 + typeof value.learning.achievement !== "string" ||
220 + value.learning.achievement.length === 0 ||
221 + !stringArray(value.learning.evidence) ||
222 + !stringArray(value.learning.successfulBehaviors) ||
223 + !(
224 + value.learning.candidateRule === null ||
225 + typeof value.learning.candidateRule === "string"
226 + ) ||
227 + !recordUsage(value.usage)
229 + return undefined;
230 + return value as unknown as GoodJobRecord;
233 +async function readJson(path: string): Promise<unknown> {
234 + return JSON.parse(await readFile(path, "utf8"));
237 +export async function enqueueJob(
238 + job: GoodJobJob,
239 + paths: GoodJobLayout,
240 +): Promise<void> {
241 + if (!parseJob(job))
242 + throw new Error("refusing to persist invalid good-job job");
243 + await atomicWriteJson(join(paths.pending, `${job.id}.json`), job);
246 +export async function claimJob(
247 + id: string,
248 + paths: GoodJobLayout,
249 +): Promise<ClaimedJob | undefined> {
250 + const pending = join(paths.pending, `${id}.json`);
251 + const processing = join(
252 + paths.processing,
253 + `${id}--${process.pid}--${randomUUID()}.json`,
254 + );
255 + await mkdir(paths.processing, { recursive: true, mode: 0o700 });
256 + try {
257 + await rename(pending, processing);
258 + } catch (error) {
259 + if (isNodeError(error) && error.code === "ENOENT") return undefined;
260 + throw error;
262 + const job = parseJob(await readJson(processing));
263 + if (job) return { job, path: processing };
264 + await moveInvalidJob(processing, id, paths, "invalid queued job schema");
265 + return undefined;
268 +async function moveInvalidJob(
269 + path: string,
270 + id: string,
271 + paths: GoodJobLayout,
272 + error: string,
273 +): Promise<void> {
274 + const failed = {
275 + version: FAILURE_VERSION,
276 + job: null,
277 + failedAt: new Date().toISOString(),
278 + error,
279 + };
280 + await atomicWriteJson(join(paths.failed, `${id}.json`), failed);
281 + await rm(path, { force: true });
284 +export async function pendingJobIds(paths: GoodJobLayout): Promise<string[]> {
285 + return (await jsonFiles(paths.pending)).map((file) => file.slice(0, -5));
288 +export async function recoverProcessing(paths: GoodJobLayout): Promise<void> {
289 + for (const file of await jsonFiles(paths.processing)) {
290 + const claim = parseClaimFile(file);
291 + const processing = join(paths.processing, file);
292 + if (!claim) {
293 + await moveInvalidJob(
294 + processing,
295 + file.slice(0, -5),
296 + paths,
297 + "invalid processing claim name",
298 + );
299 + continue;
301 + const recordFile = `${claim.id}.json`;
302 + if (
303 + (await exists(join(paths.records, recordFile))) ||
304 + (await exists(join(paths.failed, recordFile)))
305 + ) {
306 + await rm(processing, { force: true });
307 + continue;
309 + if (claim.pid !== process.pid && processExists(claim.pid)) continue;
310 + const pending = join(paths.pending, recordFile);
311 + if (await exists(pending)) {
312 + await rm(processing, { force: true });
313 + continue;
315 + await rename(processing, pending);
319 +function parseClaimFile(file: string): { id: string; pid: number } | undefined {
320 + const match = /^(.*)--([1-9][0-9]*)--[^/\\]+\.json$/.exec(file);
321 + if (!match?.[1] || !match[2]) return undefined;
322 + const pid = Number(match[2]);
323 + return Number.isSafeInteger(pid) ? { id: match[1], pid } : undefined;
326 +function processExists(pid: number): boolean {
327 + try {
328 + process.kill(pid, 0);
329 + return true;
330 + } catch (error) {
331 + return !(isNodeError(error) && error.code === "ESRCH");
335 +async function exists(path: string): Promise<boolean> {
336 + try {
337 + const file = await open(path, "r");
338 + await file.close();
339 + return true;
340 + } catch (error) {
341 + if (isNodeError(error) && error.code === "ENOENT") return false;
342 + throw error;
346 +export async function commitRecord(
347 + record: GoodJobRecord,
348 + claimPath: string,
349 + paths: GoodJobLayout,
350 +): Promise<void> {
351 + if (!parseRecord(record))
352 + throw new Error("refusing to persist invalid good-job record");
353 + await atomicWriteJson(join(paths.records, `${record.id}.json`), record);
354 + await rm(claimPath, { force: true });
357 +export async function commitFailure(
358 + job: GoodJobJob,
359 + error: unknown,
360 + claimPath: string,
361 + paths: GoodJobLayout,
362 +): Promise<void> {
363 + const failure: GoodJobFailure = {
364 + version: FAILURE_VERSION,
365 + job,
366 + failedAt: new Date().toISOString(),
367 + error: boundedError(error),
368 + };
369 + await atomicWriteJson(join(paths.failed, `${job.id}.json`), failure);
370 + await rm(claimPath, { force: true });
373 +export async function loadRecords(
374 + paths: GoodJobLayout,
375 +): Promise<LoadedRecords> {
376 + const files = await jsonFiles(paths.records);
377 + // Records are independent files; concurrent reads avoid serial filesystem
378 + // latency when opening a large learning list, especially on Windows.
379 + const loaded = await Promise.all(
380 + files.map(async (file) => {
381 + try {
382 + const record = parseRecord(await readJson(join(paths.records, file)));
383 + if (!record) throw new Error("invalid record schema");
384 + return { record };
385 + } catch (error) {
386 + return { error: `${file}: ${boundedError(error)}` };
388 + }),
389 + );
390 + const records: GoodJobRecord[] = [];
391 + const errors: string[] = [];
392 + for (const result of loaded) {
393 + if (result.record) records.push(result.record);
394 + else if (result.error) errors.push(result.error);
396 + records.sort((left, right) =>
397 + right.completedAt.localeCompare(left.completedAt),
398 + );
399 + return { records, errors };
402 +export async function counts(paths: GoodJobLayout): Promise<GoodJobCounts> {
403 + const [pending, processing, failed, records] = await Promise.all([
404 + jsonFiles(paths.pending),
405 + jsonFiles(paths.processing),
406 + jsonFiles(paths.failed),
407 + jsonFiles(paths.records),
408 + ]);
409 + return {
410 + pending: pending.length,
411 + processing: processing.length,
412 + failed: failed.length,
413 + records: records.length,
414 + };

extensions/good-job/ui.ts

Added
new file mode 100644
1 +import {
2 + DynamicBorder,
3 + type ExtensionContext,
4 + getMarkdownTheme,
5 + type Theme,
6 +} from "@earendil-works/pi-coding-agent";
7 +import {
8 + Container,
9 + type Focusable,
10 + Input,
11 + Markdown,
12 + matchesKey,
13 + Text,
14 + truncateToWidth,
15 +} from "@earendil-works/pi-tui";
16 +import type { GoodJobRecord } from "./core.js";
17 +import type { GoodJobCounts } from "./storage.js";
19 +function oneLine(text: string, maximum = 100): string {
20 + const compact = text.replace(/\s+/g, " ").trim();
21 + return Array.from(compact).length > maximum
22 + ? `${Array.from(compact)
23 + .slice(0, maximum - 1)
24 + .join("")}…`
25 + : compact;
28 +function dateLabel(timestamp: string): string {
29 + const date = new Date(timestamp);
30 + return Number.isNaN(date.valueOf())
31 + ? "unknown date"
32 + : date.toISOString().slice(0, 10);
35 +function projectLabel(record: GoodJobRecord): string {
36 + const normalized = record.source.cwd.replaceAll("\\", "/").replace(/\/$/, "");
37 + return normalized.split("/").at(-1) || record.source.cwd;
40 +function markdownText(text: string): string {
41 + return text.replace(/^([#>*+-])\s/gm, "\\$1 ");
44 +export function formatLearningMarkdown(record: GoodJobRecord): string {
45 + const evidence = record.learning.evidence
46 + .map((item) => `- ${markdownText(item)}`)
47 + .join("\n");
48 + const behaviors = record.learning.successfulBehaviors
49 + .map((item) => `- ${markdownText(item)}`)
50 + .join("\n");
51 + const rule = record.learning.candidateRule
52 + ? markdownText(record.learning.candidateRule)
53 + : "No durable rule proposed.";
54 + const sourceModel = record.source.agentModel
55 + ? `${record.source.agentModel.provider}/${record.source.agentModel.id}`
56 + : "unknown agent model";
57 + return [
58 + "## Achievement",
59 + markdownText(record.learning.achievement),
60 + "",
61 + "## Evidence",
62 + evidence,
63 + "",
64 + "## Successful behaviors",
65 + behaviors,
66 + "",
67 + "## Candidate rule",
68 + rule,
69 + "",
70 + `*${dateLabel(record.completedAt)} · ${markdownText(projectLabel(record))} · ${markdownText(sourceModel)} · ${record.id.slice(0, 8)}*`,
71 + ].join("\n");
74 +function matchingRecords(
75 + records: readonly GoodJobRecord[],
76 + query: string,
77 +): GoodJobRecord[] {
78 + const words = query.toLowerCase().trim().split(/\s+/).filter(Boolean);
79 + if (words.length === 0) return [...records];
80 + return records.filter((record) => {
81 + const haystack = [
82 + record.learning.achievement,
83 + record.learning.candidateRule ?? "",
84 + ...record.learning.successfulBehaviors,
85 + projectLabel(record),
86 + record.id,
87 + ]
88 + .join(" ")
89 + .toLowerCase();
90 + return words.every((word) => haystack.includes(word));
91 + });
94 +export class LearningListComponent implements Focusable {
95 + private readonly search = new Input();
96 + private selected = 0;
97 + private _focused = false;
99 + constructor(
100 + private readonly theme: Theme,
101 + private readonly records: readonly GoodJobRecord[],
102 + private readonly counts: GoodJobCounts,
103 + private readonly requestRender: () => void,
104 + private readonly done: (id: string | null) => void,
105 + ) {}
107 + get focused(): boolean {
108 + return this._focused;
111 + set focused(value: boolean) {
112 + this._focused = value;
113 + this.search.focused = value;
116 + handleInput(data: string): void {
117 + const matches = matchingRecords(this.records, this.search.getValue());
118 + if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
119 + this.done(null);
120 + return;
122 + if (matchesKey(data, "up")) {
123 + this.selected =
124 + matches.length === 0
125 + ? 0
126 + : (this.selected - 1 + matches.length) % matches.length;
127 + this.requestRender();
128 + return;
130 + if (matchesKey(data, "down")) {
131 + this.selected =
132 + matches.length === 0 ? 0 : (this.selected + 1) % matches.length;
133 + this.requestRender();
134 + return;
136 + if (matchesKey(data, "enter")) {
137 + this.done(matches[this.selected]?.id ?? null);
138 + return;
140 + const before = this.search.getValue();
141 + this.search.handleInput(data);
142 + if (this.search.getValue() !== before) {
143 + this.selected = 0;
144 + this.requestRender();
148 + render(width: number): string[] {
149 + const safeWidth = Math.max(1, width);
150 + const matches = matchingRecords(this.records, this.search.getValue());
151 + this.selected = Math.min(this.selected, Math.max(0, matches.length - 1));
152 + const visible = windowed(matches, this.selected, 7);
153 + const first = matches.indexOf(visible[0] as GoodJobRecord);
154 + const queue = this.counts.pending + this.counts.processing;
155 + const status = [
156 + `${this.records.length} learnings`,
157 + queue ? `${queue} queued` : "",
158 + this.counts.failed ? `${this.counts.failed} failed` : "",
160 + .filter(Boolean)
161 + .join(" · ");
162 + const lines = [
163 + this.theme.fg("border", "─".repeat(safeWidth)),
164 + `${this.theme.fg("success", "✓")} ${this.theme.fg("accent", this.theme.bold("GOOD JOB"))} ${this.theme.fg(this.counts.failed ? "warning" : "dim", status)}`,
165 + `search ${this.search.render(Math.max(1, safeWidth - 8))[0] ?? ""}`,
166 + "",
167 + ];
168 + if (visible.length === 0) {
169 + lines.push(this.theme.fg("warning", "No matching learnings."));
170 + } else {
171 + for (const [offset, record] of visible.entries()) {
172 + const selected = first + offset === this.selected;
173 + const marker = selected ? "▸" : " ";
174 + const achievement = `${marker} ${oneLine(record.learning.achievement, 120)}`;
175 + lines.push(
176 + selected ? this.theme.fg("accent", achievement) : achievement,
177 + this.theme.fg(
178 + "dim",
179 + ` ${dateLabel(record.completedAt)} · ${projectLabel(record)} · ${record.id.slice(0, 8)}`,
180 + ),
181 + );
184 + lines.push(
185 + "",
186 + this.theme.fg(
187 + "dim",
188 + "type to filter · ↑↓ navigate · enter show · esc close",
189 + ),
190 + this.theme.fg("border", "─".repeat(safeWidth)),
191 + );
192 + return lines.map((line) => truncateToWidth(line, safeWidth));
195 + invalidate(): void {
196 + this.search.invalidate();
200 +function windowed<T>(
201 + items: readonly T[],
202 + selected: number,
203 + maximum: number,
204 +): T[] {
205 + if (items.length <= maximum) return [...items];
206 + const half = Math.floor(maximum / 2);
207 + const start = Math.min(
208 + Math.max(0, selected - half),
209 + Math.max(0, items.length - maximum),
210 + );
211 + return items.slice(start, start + maximum);
214 +export async function showLearningList(
215 + ctx: ExtensionContext,
216 + records: readonly GoodJobRecord[],
217 + counts: GoodJobCounts,
218 +): Promise<string | null> {
219 + if (ctx.mode !== "tui") {
220 + ctx.ui.notify(
221 + records
222 + .slice(0, 10)
223 + .map(
224 + (record) =>
225 + `${record.id.slice(0, 8)} ${dateLabel(record.completedAt)} ${oneLine(record.learning.achievement)}`,
227 + .join("\n"),
228 + "info",
229 + );
230 + return null;
232 + return ctx.ui.custom<string | null>(
233 + (tui, theme, _keybindings, done) =>
234 + new LearningListComponent(
235 + theme,
236 + records,
237 + counts,
238 + () => tui.requestRender(),
239 + done,
240 + ),
241 + );
244 +export async function showLearningDetail(
245 + ctx: ExtensionContext,
246 + record: GoodJobRecord,
247 +): Promise<void> {
248 + const markdown = formatLearningMarkdown(record);
249 + if (ctx.mode !== "tui") {
250 + ctx.ui.notify(markdown, "info");
251 + return;
253 + await ctx.ui.custom<void>((_tui, theme, _keybindings, done) => {
254 + const container = new Container();
255 + const border = () =>
256 + new DynamicBorder((text: string) => theme.fg("accent", text));
257 + container.addChild(border());
258 + container.addChild(
259 + new Text(
260 + `${theme.fg("success", "✓")} ${theme.fg("accent", theme.bold("GOOD JOB"))}`,
261 + 1,
262 + 0,
263 + ),
264 + );
265 + container.addChild(new Markdown(markdown, 1, 1, getMarkdownTheme()));
266 + container.addChild(new Text(theme.fg("dim", "enter/esc/q close"), 1, 0));
267 + container.addChild(border());
268 + return {
269 + render: (width: number) =>
270 + container.render(width).map((line) => truncateToWidth(line, width)),
271 + handleInput: (data: string) => {
272 + if (
273 + matchesKey(data, "enter") ||
274 + matchesKey(data, "escape") ||
275 + matchesKey(data, "q")
277 + done();
278 + },
279 + invalidate: () => container.invalidate(),
280 + };
281 + });

package-lock.json

Modified
219 219 "typebox": "*"
222 + "extensions/good-job": {
223 + "name": "@bugabinga/pi-ext-good-job",
224 + "license": "MIT",
225 + "devDependencies": {
226 + "@marcfargas/pi-test-harness": "^0.6.1",
227 + "vitest": "^4.1.9"
228 + },
229 + "peerDependencies": {
230 + "@earendil-works/pi-ai": "*",
231 + "@earendil-works/pi-coding-agent": "*",
232 + "@earendil-works/pi-tui": "*"
234 + },
222 235 "extensions/intellij": {
223 236 "name": "@bugabinga/pi-ext-intellij",
224 237 "version": "0.0.0",
1550 1563 "resolved": "extensions/goldfish",
1551 1564 "link": true
1566 + "node_modules/@bugabinga/pi-ext-good-job": {
1567 + "resolved": "extensions/good-job",
1568 + "link": true
1569 + },
1553 1570 "node_modules/@bugabinga/pi-ext-intellij": {
1554 1571 "resolved": "extensions/intellij",
1555 1572 "link": true