repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat(good-job): unify praise and problem learnings

06619b31101ecbeb13c407fb92e655458dcc8c2b

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

Capture gj and wtf feedback without consuming the active turn, add path-based learning synthesis, and migrate legacy storage into configurable directories with canonical short IDs.

Changed files (13)

README.md

Modified
75 75 | `fast` | OpenAI Codex priority service tier. | [README](extensions/fast/README.md) |
76 76 | `footer` | Shared stable footer renderer. | [README](extensions/footer/README.md) |
77 77 | `git-safe` | Hardened Git operations and clone tooling. | [README](extensions/git-safe/README.md) |
78 -| `good-job` | Turns praise into durable, evidence-backed learnings. | [README](extensions/good-job/README.md) |
78 +| `good-job` | Learns from pass-through `gj` praise and `wtf` complaints. | [README](extensions/good-job/README.md) |
79 79 | `intellij` | Connects to IntelliJ's MCP server on demand. | [README](extensions/intellij/README.md) |
80 80 | `iq` | Scores model work ability from real Pi sessions. | [README](extensions/iq/README.md) |
81 81 | `klaus` | Runs Claude models through the Claude Agent SDK. | [README](extensions/klaus/README.md) |

extensions/good-job/README.md

Modified
1 1 # good-job
3 -Turns standalone `gj` and `good job` praise into durable, evidence-backed learnings without starting another agent turn.
3 +Turns explicit `gj` praise and `wtf` complaints into durable, evidence-backed learnings.
5 5 ## Install / load
9 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.
11 +- `gj [details]` and `good job [details]` record praise and continue to the active agent unchanged.
12 +- `wtf [complaint]` records a problem and continues to the active agent unchanged.
13 +- `/gj` or `/gj list` opens the searchable learning list and selected detail.
14 +- `/gj status` reports queue state.
15 +- `/gj open` opens the persistence directory.
16 +- `/gj learn` sends the active agent the records-directory path and asks for cited Pi change proposals.
16 18 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`:
19 +By default, analysis uses the current session model and platform app-data directory.
20 +Set optional overrides in global or project `settings.json`:
20 22 ```json
22 24 "goodJob": {
25 + "directory": "~/shared/gj",
23 26 "model": "provider/model-id",
24 27 "thinkingLevel": "xhigh"
32 +Relative directories resolve from Pi's current working directory.
29 33 Project settings override global settings.
30 -Records and crash-recoverable queue files live under the platform app-data directory in `pi/good-job`.
34 +`/gj learn` leaves the active model, thinking level, and tools unchanged.
36 +## Behavior
38 +Each record stores feedback kind, memorable slug, short ID, raw feedback, evidence, behaviors, candidate rule, provenance, model, usage, and timestamps.
39 +Praise IDs use `gj-xxxxxxxxxx`; problem IDs use `wtf-xxxxxxxxxx`.
40 +Queue state moves atomically through `pending`, `processing`, `records`, or `failed` directories.
41 +When old data exists in the platform default directory, startup converts version-1 records and moves them into the configured directory.
42 +Identical migrated IDs deduplicate; conflicting contents stop migration without overwrite.

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

Modified
1 1 import { mkdtemp, rm, writeFile } from "node:fs/promises";
2 2 import { tmpdir } from "node:os";
3 3 import { join } from "node:path";
4 +import { feedbackIdFromSeed } from "../core.ts";
4 5 import { ensureLayout, layout, loadRecords } from "../storage.ts";
6 7 const RECORD_COUNT = Number(process.env.GOOD_JOB_BENCH_RECORDS ?? 1_000);
11 12 function record(index: number) {
12 - const id = index.toString().padStart(8, "0");
13 + const id = feedbackIdFromSeed("praise", `bench:${index}`);
13 14 return {
14 - version: 1,
15 + version: 2,
16 17 createdAt: "2026-01-01T00:00:00.000Z",
17 18 completedAt: `2026-01-01T00:${String(index % 60).padStart(2, "0")}:00.000Z`,
18 - praise: "gj",
19 + kind: "praise",
20 + feedback: "gj",
19 21 source: {
22 + type: "session",
20 23 cwd: "/project",
21 24 sessionPath: "/sessions/example.jsonl",
22 25 sessionId: "session-1",
27 30 analysisModel: { provider: "provider", id: "analyzer" },
28 31 learning: {
29 - achievement: `Achievement ${id}`,
32 + slug: `achievement-${index}`,
33 + summary: `Achievement ${id}`,
30 34 evidence: ["Focused tests passed"],
31 - successfulBehaviors: ["Inspected callers before editing"],
35 + behaviors: ["Inspected callers before editing"],
32 36 candidateRule: "Fix shared routes before leaf callers.",
34 38 usage: {

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

Modified
1 1 import { describe, expect, it } from "vitest";
2 -import { analysisPrompt, isGoodJobTrigger, parseLearning } from "../core.js";
2 +import {
3 + analysisPrompt,
4 + feedbackId,
5 + feedbackIdFromSeed,
6 + feedbackTrigger,
7 + parseLearning,
8 +} from "../core.js";
4 10 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);
11 + it("matches praise and problem prefixes with optional details", () => {
12 + expect(feedbackTrigger("gj")).toEqual({
13 + kind: "praise",
14 + feedback: "gj",
15 + });
16 + expect(feedbackTrigger("good job! excellent scope control")).toEqual({
17 + kind: "praise",
18 + feedback: "excellent scope control",
19 + });
20 + expect(feedbackTrigger("wtf you deleted my db")).toEqual({
21 + kind: "problem",
22 + feedback: "you deleted my db",
23 + });
24 + for (const other of ["great job", "object.gj", "/gj list", "", "awtf"])
25 + expect(feedbackTrigger(other), other).toBeUndefined();
26 + });
28 + it("creates short kind-prefixed Crockford IDs", () => {
29 + const bytes = Uint8Array.from([0, 1, 2, 3, 4, 5, 6]);
30 + expect(feedbackId("praise", bytes)).toMatch(/^gj-[0-9a-hjkmnp-tv-z]{10}$/);
31 + expect(feedbackId("problem", bytes)).toMatch(
32 + /^wtf-[0-9a-hjkmnp-tv-z]{10}$/,
33 + );
34 + expect(feedbackIdFromSeed("problem", "same")).toBe(
35 + feedbackIdFromSeed("problem", "same"),
36 + );
18 39 it("parses and bounds structured learnings", () => {
19 40 const learning = parseLearning(`\`\`\`json
21 - "achievement": " Fixed the shared route ",
42 + "slug": "Shared Route First!",
43 + "summary": " Fixed the shared route ",
22 44 "evidence": ["All tests passed", "Caller uses one path"],
23 - "successful_behaviors": ["Inspected callers first"],
45 + "behaviors": ["Inspected callers first"],
24 46 "candidate_rule": "Fix shared routes before leaf callers."
26 48 \`\`\``);
27 49 expect(learning).toEqual({
28 - achievement: "Fixed the shared route",
50 + slug: "shared-route-first",
51 + summary: "Fixed the shared route",
29 52 evidence: ["All tests passed", "Caller uses one path"],
30 - successfulBehaviors: ["Inspected callers first"],
53 + behaviors: ["Inspected callers first"],
31 54 candidateRule: "Fix shared routes before leaf callers.",
35 58 it("rejects incomplete model output", () => {
36 - expect(() => parseLearning('{"achievement":"done","evidence":[]}')).toThrow(
59 + expect(() => parseLearning('{"summary":"done","evidence":[]}')).toThrow(
37 60 "missing required learning fields",
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");
64 + it("asks for evidence-backed reusable behavior and a memorable slug", () => {
65 + const praise = analysisPrompt("praise", "gj");
66 + const problem = analysisPrompt("problem", "Ignored the requested scope");
67 + expect(praise).toContain("conversation preceding");
68 + expect(praise).toContain("kebab-case");
69 + expect(problem).toContain("prevent recurrence");
70 + expect(problem).toContain("Do not reproduce credentials");

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

Modified
31 31 return value;
34 +function learning(summary: string, slug = "shared-route-first") {
35 + return fauxAssistantMessage(
36 + JSON.stringify({
37 + slug,
38 + summary,
39 + evidence: ["Focused tests passed"],
40 + behaviors: ["Inspected callers before editing"],
41 + candidate_rule: "Fix shared routes before leaf callers.",
42 + }),
43 + );
34 46 describe("good-job pi-test-harness", () => {
35 47 let t: TestSession | undefined;
40 52 vi.restoreAllMocks();
43 - it("loads through the real Pi runtime with one command and no tools", async () => {
55 + it("registers only /gj with list-driven commands and no prompt or tools", async () => {
44 56 t = await createTestSession({ extensions: [extensionPath()] });
45 57 const extension = t.session.extensionRunner.extensions[0];
46 58 expect(extension.path).toBe(extensionPath());
47 - expect([...extension.commands.keys()]).toEqual(["good-job"]);
59 + expect([...extension.commands.keys()]).toEqual(["gj"]);
48 60 expect([...extension.tools.keys()]).toEqual([]);
61 + expect(extension.handlers.get("resources_discover")).toBeUndefined();
49 62 expect(
50 - extension.commands.get("good-job").getArgumentCompletions(""),
51 - ).toEqual([
63 + t.session.resourceLoader
64 + .getPrompts()
65 + .prompts.find(({ name }) => name === "wtf"),
66 + ).toBeUndefined();
67 + expect(extension.commands.get("gj").getArgumentCompletions("")).toEqual([
52 68 { value: "list", label: "list" },
53 - { value: "show", label: "show" },
54 69 { value: "status", label: "status" },
55 70 { value: "open", label: "open" },
71 + { value: "learn", label: "learn" },
59 - it("handles praise without an agent turn and persists the analyzed learning", async () => {
75 + it("records praise while passing the original message to the agent", async () => {
60 76 t = await createTestSession({ extensions: [extensionPath()] });
61 77 const runner = t.session.extensionRunner;
62 78 const extension = runner.extensions[0];
66 82 provider: "good-job-test",
67 83 models: [{ id: "worker", maxTokens: 4_096 }],
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 - ]);
85 + faux.setResponses([learning("Fixed the shared route")]);
79 86 const stream = vi.spyOn(faux.provider, "stream");
80 87 base.modelRegistry.registerProvider(faux.provider);
81 88 const model = base.modelRegistry.find("good-job-test", "worker");
95 102 const result = await withProcessEnv(t.env, () =>
96 - input({ type: "input", text: "good job!", source: "interactive" }, ctx),
103 + input(
105 + type: "input",
106 + text: "good job! excellent scope control",
107 + source: "interactive",
108 + },
109 + ctx,
110 + ),
98 - expect(result).toEqual({ action: "handled" });
112 + expect(result).toEqual({ action: "continue" });
100 114 const root = goodJobDataDirectory(t.env, process.platform, t.env.HOME);
101 115 const loaded = await eventually(
103 117 (value) => value.records.length === 1,
105 119 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.",
120 + expect(loaded.records[0]).toMatchObject({
121 + kind: "praise",
122 + feedback: "excellent scope control",
123 + learning: {
124 + slug: "shared-route-first",
125 + summary: "Fixed the shared route",
126 + },
127 + });
128 + expect(loaded.records[0]?.id).toMatch(/^gj-[0-9a-hjkmnp-tv-z]{10}$/);
129 + expect(loaded.records[0]?.source).toMatchObject({
130 + type: "session",
131 + cwd: ctx.cwd,
110 - expect(loaded.records[0]?.source.cwd).toBe(ctx.cwd);
111 133 const sentMessages = stream.mock.calls[0]?.[1].messages ?? [];
112 - expect(sentMessages).toHaveLength(4);
113 - expect(JSON.stringify(sentMessages[2])).toContain(
134 + expect(JSON.stringify(sentMessages)).toContain(
114 135 "Implemented and tested the shared fix.",
116 - expect(JSON.stringify(sentMessages[3])).toContain("successful_behaviors");
117 - const notifications = await eventually(
118 - async () =>
119 - t?.events.ui
120 - .filter((call) => call.method === "notify")
121 - .map((call) => call.args[0]) ?? [],
122 - (value) =>
123 - value.some((message) => String(message).includes("good-job learned")),
124 - );
125 - expect(notifications).toEqual(
126 - expect.arrayContaining([
127 - expect.stringContaining("good-job queued"),
128 - expect.stringContaining("good-job learned"),
129 - ]),
130 - );
131 - const statuses = t.events.ui
132 - .filter((call) => call.method === "setStatus")
133 - .map((call) => call.args);
134 - expect(statuses.some((args) => String(args[1]).includes("good-job"))).toBe(
135 - true,
136 - );
137 - expect(statuses.at(-1)).toEqual(["good-job", undefined]);
137 + expect(JSON.stringify(sentMessages.at(-1))).toContain("kebab-case");
139 139 await withProcessEnv(t.env, () =>
140 - extension.commands.get("good-job").handler("status", ctx as never),
140 + extension.commands.get("gj").handler("status", ctx as never),
142 142 expect(t.events.ui.at(-1)?.args[0]).toContain("1 learnings");
145 - it("uses the optional settings model override", async () => {
145 + it("records first-word wtf feedback while passing it unchanged", async () => {
146 146 t = await createTestSession({ extensions: [extensionPath()] });
147 + const runner = t.session.extensionRunner;
148 + const extension = runner.extensions[0];
149 + const input = extension.handlers.get("input")[0];
150 + const base = runner.createContext();
151 + const faux = fauxProvider({
152 + provider: "wtf-test",
153 + models: [{ id: "worker", maxTokens: 4_096 }],
154 + });
155 + faux.setResponses([
156 + learning("Expanded scope without approval", "scope-creep"),
157 + ]);
158 + const stream = vi.spyOn(faux.provider, "stream");
159 + base.modelRegistry.registerProvider(faux.provider);
160 + const model = base.modelRegistry.find("wtf-test", "worker");
161 + if (!model) throw new Error("missing wtf faux model");
162 + const ctx = Object.create(base) as typeof base;
163 + Object.defineProperty(ctx, "model", { value: model });
164 + const manager = ctx.sessionManager as any;
165 + manager.appendMessage({
166 + role: "user",
167 + content: "Implement only A",
168 + timestamp: Date.now(),
169 + });
170 + manager.appendMessage(
171 + fauxAssistantMessage("Implemented A and unrelated B."),
172 + );
174 + const result = await withProcessEnv(t.env, () =>
175 + input(
177 + type: "input",
178 + text: "wtf you added unrelated B",
179 + source: "interactive",
180 + },
181 + ctx,
182 + ),
183 + );
184 + expect(result).toEqual({ action: "continue" });
186 + const root = goodJobDataDirectory(t.env, process.platform, t.env.HOME);
187 + const loaded = await eventually(
188 + () => loadRecords(layout(root)),
189 + (value) => value.records.length === 1,
190 + );
191 + expect(loaded.records[0]).toMatchObject({
192 + kind: "problem",
193 + feedback: "you added unrelated B",
194 + learning: { slug: "scope-creep" },
195 + });
196 + expect(loaded.records[0]?.id).toMatch(/^wtf-[0-9a-hjkmnp-tv-z]{10}$/);
197 + expect(JSON.stringify(stream.mock.calls[0]?.[1].messages)).toContain(
198 + "Implemented A and unrelated B.",
199 + );
200 + });
202 + it("uses optional directory, model, and thinking settings", async () => {
203 + t = await createTestSession({ extensions: [extensionPath()] });
204 + const customRoot = path.join(t.cwd, "shared-gj");
147 205 vi.spyOn(SettingsManager, "create").mockReturnValue(
148 206 SettingsManager.inMemory({
149 207 goodJob: {
208 + directory: customRoot,
150 209 model: "good-job-override/background",
151 210 thinkingLevel: "xhigh",
163 222 { id: "background", maxTokens: 4_096 },
166 - faux.setResponses([
167 - fauxAssistantMessage(
168 - JSON.stringify({
169 - achievement: "Used configured model",
170 - evidence: ["Override handled the request"],
171 - successful_behaviors: ["Separated background analysis"],
172 - candidate_rule: "Configure background models explicitly.",
173 - }),
174 - ),
175 - ]);
225 + faux.setResponses([learning("Used configured model", "configured-model")]);
176 226 const stream = vi.spyOn(faux.provider, "stream");
177 227 base.modelRegistry.registerProvider(faux.provider);
178 228 const active = base.modelRegistry.find("good-job-override", "active");
183 233 const result = await withProcessEnv(t.env, () =>
184 234 input({ type: "input", text: "gj", source: "interactive" }, ctx),
186 - expect(result).toEqual({ action: "handled" });
236 + expect(result).toEqual({ action: "continue" });
188 - const root = goodJobDataDirectory(t.env, process.platform, t.env.HOME);
189 238 const loaded = await eventually(
190 - () => loadRecords(layout(root)),
239 + () => loadRecords(layout(customRoot)),
191 240 (value) => value.records.length === 1,
193 242 expect(loaded.records[0]?.analysisModel).toEqual({
198 247 expect(stream.mock.calls[0]?.[2]?.reasoning).toBe("xhigh");
250 + it("sends only the records path and synthesis instructions to /gj learn", async () => {
251 + t = await createTestSession({ extensions: [extensionPath()] });
252 + const runner = t.session.extensionRunner;
253 + const extension = runner.extensions[0];
254 + const input = extension.handlers.get("input")[0];
255 + const base = runner.createContext();
256 + const faux = fauxProvider({
257 + provider: "learn-test",
258 + models: [{ id: "worker", maxTokens: 4_096 }],
259 + });
260 + faux.setResponses([
261 + learning("Private summary must not be embedded", "private-learning"),
262 + fauxAssistantMessage("Proposed changes."),
263 + ]);
264 + base.modelRegistry.registerProvider(faux.provider);
265 + const model = base.modelRegistry.find("learn-test", "worker");
266 + if (!model) throw new Error("missing learn faux model");
267 + const ctx = Object.create(base) as typeof base;
268 + Object.defineProperty(ctx, "model", { value: model });
269 + await withProcessEnv(t.env, () =>
270 + input({ type: "input", text: "gj", source: "interactive" }, ctx),
271 + );
272 + const root = goodJobDataDirectory(t.env, process.platform, t.env.HOME);
273 + await eventually(
274 + () => loadRecords(layout(root)),
275 + (value) => value.records.length === 1,
276 + );
278 + const promptSpy = vi
279 + .spyOn(t.session, "prompt")
280 + .mockResolvedValue(undefined);
281 + await withProcessEnv(t.env, () =>
282 + extension.commands.get("gj").handler("learn", ctx as never),
283 + );
284 + await vi.waitFor(() => expect(promptSpy).toHaveBeenCalled());
285 + const prompt = String(promptSpy.mock.calls[0]?.[0]);
286 + expect(prompt).toContain(layout(root).records);
287 + expect(prompt).toContain("slug (id)");
288 + expect(prompt).toContain("praise and problem records together");
289 + expect(prompt).not.toContain("Private summary must not be embedded");
290 + });
201 292 it("reports invalid settings during startup", async () => {
202 293 t = await createTestSession({ extensions: [extensionPath()] });
203 294 vi.spyOn(SettingsManager, "create").mockReturnValue(
237 328 markStarted = resolve;
239 330 let firstAborted = false;
240 - const learning = (achievement: string) =>
241 - fauxAssistantMessage(
242 - JSON.stringify({
243 - achievement,
244 - evidence: ["Session transition completed"],
245 - successful_behaviors: ["Recovered queued work"],
246 - candidate_rule: "Resume claimed work after session changes.",
247 - }),
248 - );
249 331 faux.setResponses([
250 332 async (_context, options) => {
251 333 markStarted();
260 342 { once: true },
263 - return learning("Stale response");
345 + return learning("Stale response", "stale-response");
265 - learning("Recovered after session change"),
347 + learning("Recovered after session change", "recovered-work"),
267 349 base.modelRegistry.registerProvider(faux.provider);
268 350 const model = base.modelRegistry.find("good-job-restart", "worker");
285 367 (value) => value.records.length === 1,
287 369 expect(firstAborted).toBe(true);
288 - expect(loaded.records[0]?.learning.achievement).toBe(
289 - "Recovered after session change",
290 - );
370 + expect(loaded.records[0]?.learning.slug).toBe("recovered-work");
291 371 expect(await counts(paths)).toEqual({
292 372 pending: 0,
293 373 processing: 0,
299 - it("ignores non-trigger text", async () => {
379 + it("ignores unrelated and extension-injected text", async () => {
300 380 t = await createTestSession({ extensions: [extensionPath()] });
301 - const extension = t.session.extensionRunner.extensions[0];
302 - const input = extension.handlers.get("input")[0];
303 - const result = await input(
304 - { type: "input", text: "good job, continue", source: "interactive" },
305 - t.session.extensionRunner.createContext(),
306 - );
307 - expect(result).toEqual({ action: "continue" });
381 + const input =
382 + t.session.extensionRunner.extensions[0].handlers.get("input")[0];
383 + for (const event of [
384 + { type: "input", text: "great job", source: "interactive" },
385 + { type: "input", text: "wtf happened", source: "extension" },
386 + ])
387 + expect(
388 + await input(event, t.session.extensionRunner.createContext()),
389 + ).toEqual({ action: "continue" });

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

Modified
1 -import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
1 +import {
2 + chmodSync,
3 + existsSync,
4 + mkdtempSync,
5 + readFileSync,
6 + rmSync,
7 + symlinkSync,
8 + writeFileSync,
9 +} from "node:fs";
2 10 import { tmpdir } from "node:os";
3 11 import { join } from "node:path";
4 12 import { afterEach, describe, expect, it } from "vitest";
5 -import type { GoodJobJob, GoodJobRecord } from "../core.js";
13 +import {
14 + feedbackIdFromSeed,
15 + type GoodJobJob,
16 + type GoodJobRecord,
17 +} from "../core.js";
6 18 import { openDirectory, openerFor } from "../implementation.js";
7 19 import {
8 20 atomicWriteJson,
9 21 claimJob,
10 22 commitFailure,
11 23 commitRecord,
24 + configuredDataDirectory,
12 25 counts,
13 26 enqueueJob,
14 27 ensureLayout,
15 28 goodJobDataDirectory,
16 29 layout,
17 30 loadRecords,
31 + migrateStore,
32 + parseJob,
18 33 parseRecord,
19 34 recoverProcessing,
20 35 } from "../storage.js";
27 42 return root;
30 -function job(id = "job-1"): GoodJobJob {
45 +function job(id = "gj-0000000001"): GoodJobJob {
31 46 return {
32 - version: 1,
47 + version: 2,
34 49 createdAt: "2026-01-01T00:00:00.000Z",
35 - praise: "gj",
50 + kind: "praise",
51 + feedback: "gj",
36 52 source: {
53 + type: "session",
37 54 cwd: "/repo",
38 55 sessionPath: "/sessions/one.jsonl",
39 56 sessionId: "session-1",
48 65 function record(source = job()): GoodJobRecord {
49 66 if (!source.analysisModel) throw new Error("fixture analysis model missing");
50 67 return {
51 - version: 1,
68 + version: 2,
52 69 id: source.id,
53 70 createdAt: source.createdAt,
54 71 completedAt: "2026-01-01T00:01:00.000Z",
55 - praise: source.praise,
72 + kind: source.kind,
73 + feedback: source.feedback,
56 74 source: source.source,
57 75 analysisModel: source.analysisModel,
76 + learning: {
77 + slug: "fixed-shared-route",
78 + summary: "Fixed the shared route",
79 + evidence: ["Tests passed"],
80 + behaviors: ["Inspected callers"],
81 + candidateRule: "Fix shared routes first.",
82 + },
83 + usage: {
84 + input: 10,
85 + output: 5,
86 + cacheRead: 0,
87 + cacheWrite: 0,
88 + totalTokens: 15,
89 + cost: 0.01,
90 + },
91 + };
94 +function legacyRecord() {
95 + return {
96 + version: 1,
97 + id: "b0b916cf-20ec-4f50-80f5-0cb83fbbd3c3",
98 + createdAt: "2026-01-01T00:00:00.000Z",
99 + completedAt: "2026-01-01T00:01:00.000Z",
100 + praise: "gj",
101 + source: {
102 + cwd: "/repo",
103 + sessionPath: "/sessions/one.jsonl",
104 + sessionId: "session-1",
105 + sessionName: "Shared route",
106 + leafId: "leaf-1",
107 + agentModel: { provider: "provider", id: "worker" },
108 + },
109 + analysisModel: { provider: "provider", id: "worker" },
58 110 learning: {
59 111 achievement: "Fixed the shared route",
60 112 evidence: ["Tests passed"],
80 132 describe("good-job storage", () => {
81 - it("uses platform app-data directories", () => {
133 + it("uses platform defaults and resolves configured directories", () => {
82 134 expect(
83 135 goodJobDataDirectory({ XDG_DATA_HOME: "/data" }, "linux", "/home/o"),
84 136 ).toBe("/data/pi/good-job");
92 144 expect(goodJobDataDirectory({}, "darwin", "/Users/o")).toBe(
93 145 "/Users/o/Library/Application Support/pi/good-job",
147 + expect(configuredDataDirectory("~/shared/gj", "/repo", "/home/o")).toBe(
148 + "/home/o/shared/gj",
149 + );
150 + expect(configuredDataDirectory(".pi/gj", "/repo", "/home/o")).toBe(
151 + "/repo/.pi/gj",
152 + );
97 - it("rejects records with incomplete or invalid usage", () => {
155 + it("validates current records including nullable import metadata", () => {
98 156 const valid = record();
99 157 expect(parseRecord(valid)).toEqual(valid);
100 158 expect(parseRecord({ ...valid, usage: {} })).toBeUndefined();
102 160 parseRecord({ ...valid, usage: { ...valid.usage, input: "10" } }),
103 161 ).toBeUndefined();
104 162 expect(
105 - parseRecord({ ...valid, usage: { ...valid.usage, cost: -1 } }),
163 + parseRecord({ ...valid, id: "too-long-and-not-valid" }),
106 164 ).toBeUndefined();
165 + expect(parseRecord({ ...valid, id: "wtf-0000000001" })).toBeUndefined();
166 + expect(parseJob({ ...job(), id: "wtf-0000000001" })).toBeUndefined();
167 + const imported: GoodJobRecord = {
168 + ...valid,
169 + id: "wtf-0000000002",
170 + kind: "problem",
171 + source: {
172 + type: "import",
173 + importer: "wtf-v1",
174 + fingerprint: "abc123",
175 + importedAt: "2026-01-02T00:00:00.000Z",
176 + },
177 + analysisModel: null,
178 + usage: null,
179 + };
180 + expect(parseRecord(imported)).toEqual(imported);
109 183 it("claims jobs atomically and commits immutable records", async () => {
126 200 failed: 0,
127 201 records: 1,
129 - expect((await loadRecords(paths)).records[0]?.learning.achievement).toBe(
130 - "Fixed the shared route",
203 + expect((await loadRecords(paths)).records[0]?.learning.slug).toBe(
204 + "fixed-shared-route",
134 208 it("loads valid records concurrently while preserving sort and errors", async () => {
135 209 const paths = layout(temporaryRoot());
136 210 await ensureLayout(paths);
137 - const older = record(job("older"));
138 - const newer = record(job("newer"));
211 + const older = record(job("gj-0000000001"));
212 + const newer = record(job("gj-0000000002"));
139 213 older.completedAt = "2026-01-01T00:01:00.000Z";
140 214 newer.completedAt = "2026-01-02T00:01:00.000Z";
141 215 await Promise.all([
142 - atomicWriteJson(join(paths.records, "older.json"), older),
143 - atomicWriteJson(join(paths.records, "newer.json"), newer),
216 + atomicWriteJson(join(paths.records, `${older.id}.json`), older),
217 + atomicWriteJson(join(paths.records, `${newer.id}.json`), newer),
145 219 writeFileSync(join(paths.records, "broken.json"), "not json", "utf8");
147 221 const loaded = await loadRecords(paths);
148 - expect(loaded.records.map(({ id }) => id)).toEqual(["newer", "older"]);
222 + expect(loaded.records.map(({ id }) => id)).toEqual([
223 + "gj-0000000002",
224 + "gj-0000000001",
225 + ]);
149 226 expect(loaded.errors).toHaveLength(1);
150 227 expect(loaded.errors[0]).toContain("broken.json");
230 + it("migrates version-1 records into a configured store at runtime", async () => {
231 + const source = temporaryRoot();
232 + const target = temporaryRoot();
233 + const sourcePaths = layout(source);
234 + await ensureLayout(sourcePaths);
235 + const legacy = legacyRecord();
236 + const oldPath = join(sourcePaths.records, `${legacy.id}.json`);
237 + await atomicWriteJson(oldPath, legacy);
239 + const migrated = await migrateStore(source, target);
240 + expect(migrated).toEqual({ jobs: 0, records: 1, failures: 0, active: 0 });
241 + expect(existsSync(oldPath)).toBe(false);
242 + const loaded = await loadRecords(layout(target));
243 + const id = feedbackIdFromSeed("praise", `good-job-v1:${legacy.id}`);
244 + expect(loaded.records[0]).toMatchObject({
245 + id,
246 + kind: "praise",
247 + feedback: "gj",
248 + learning: {
249 + slug: "fixed-the-shared-route",
250 + summary: "Fixed the shared route",
251 + },
252 + });
253 + expect(await migrateStore(source, target)).toEqual({
254 + jobs: 0,
255 + records: 0,
256 + failures: 0,
257 + active: 0,
258 + });
259 + });
261 + it("preserves records when configured and default roots alias", async () => {
262 + const source = temporaryRoot();
263 + const holder = temporaryRoot();
264 + const alias = join(holder, "alias");
265 + const paths = layout(source);
266 + await ensureLayout(paths);
267 + const existing = record();
268 + await atomicWriteJson(join(paths.records, `${existing.id}.json`), existing);
269 + symlinkSync(source, alias, "dir");
271 + expect(await migrateStore(source, alias)).toEqual({
272 + jobs: 0,
273 + records: 0,
274 + failures: 0,
275 + active: 0,
276 + });
277 + expect((await loadRecords(paths)).records).toEqual([existing]);
278 + });
280 + it("refuses migration collisions without changing either record", async () => {
281 + const source = temporaryRoot();
282 + const target = temporaryRoot();
283 + const sourcePaths = layout(source);
284 + const targetPaths = layout(target);
285 + await Promise.all([ensureLayout(sourcePaths), ensureLayout(targetPaths)]);
286 + const original = record();
287 + const conflicting = {
288 + ...original,
289 + learning: { ...original.learning, summary: "Conflicting learning" },
290 + };
291 + const sourceFile = join(sourcePaths.records, `${original.id}.json`);
292 + const targetFile = join(targetPaths.records, `${original.id}.json`);
293 + await atomicWriteJson(sourceFile, conflicting);
294 + await atomicWriteJson(targetFile, original);
295 + const originalBytes = readFileSync(targetFile, "utf8");
297 + await expect(migrateStore(source, target)).rejects.toThrow(
298 + "migration collision",
299 + );
300 + expect(readFileSync(targetFile, "utf8")).toBe(originalBytes);
301 + expect(existsSync(sourceFile)).toBe(true);
302 + });
304 + it("relocates invalid-claim diagnostics created during recovery", async () => {
305 + const source = temporaryRoot();
306 + const target = temporaryRoot();
307 + const paths = layout(source);
308 + await ensureLayout(paths);
309 + writeFileSync(join(paths.processing, "invalid.json"), "{}\n", "utf8");
311 + expect(await migrateStore(source, target)).toEqual({
312 + jobs: 0,
313 + records: 0,
314 + failures: 1,
315 + active: 0,
316 + });
317 + const diagnostic = JSON.parse(
318 + readFileSync(join(layout(target).failed, "invalid.json"), "utf8"),
319 + );
320 + expect(diagnostic).toMatchObject({
321 + version: 1,
322 + job: null,
323 + error: "invalid processing claim name",
324 + });
325 + });
327 + it("rejects a queued ID already used by a completed record", async () => {
328 + const paths = layout(temporaryRoot());
329 + await ensureLayout(paths);
330 + const existing = record();
331 + const target = join(paths.records, `${existing.id}.json`);
332 + await atomicWriteJson(target, existing);
333 + const originalBytes = readFileSync(target, "utf8");
335 + await expect(enqueueJob(job(existing.id), paths)).rejects.toThrow(
336 + `duplicate gj id ${existing.id}`,
337 + );
338 + expect(readFileSync(target, "utf8")).toBe(originalBytes);
339 + });
153 341 it("persists failed analysis before releasing its processing claim", async () => {
154 342 const paths = layout(temporaryRoot());
155 343 await ensureLayout(paths);
156 - await enqueueJob(job("failed"), paths);
157 - const claimed = await claimJob("failed", paths);
344 + await enqueueJob(job(), paths);
345 + const claimed = await claimJob("gj-0000000001", paths);
158 346 if (!claimed) throw new Error("missing claimed job");
159 347 await commitFailure(
160 348 claimed.job,
172 360 it("recovers interrupted processing without duplicating completed work", async () => {
173 361 const paths = layout(temporaryRoot());
174 362 await ensureLayout(paths);
175 - await enqueueJob(job("retry"), paths);
176 - await claimJob("retry", paths);
363 + await enqueueJob(job(), paths);
364 + await claimJob("gj-0000000001", paths);
177 365 await recoverProcessing(paths);
178 366 expect(await counts(paths)).toMatchObject({ pending: 1, processing: 0 });
180 - const claimed = await claimJob("retry", paths);
368 + const claimed = await claimJob("gj-0000000001", paths);
181 369 if (!claimed) throw new Error("missing recovered job");
182 370 await commitRecord(record(claimed.job), claimed.path, paths);
183 371 await recoverProcessing(paths);

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

Modified
4 4 import { visibleWidth } from "@earendil-works/pi-tui";
5 5 import { describe, expect, it, vi } from "vitest";
6 6 import type { GoodJobRecord } from "../core.js";
7 7 import { formatLearningMarkdown, LearningListComponent } from "../ui.js";
9 9 const record: GoodJobRecord = {
10 - version: 1,
11 - id: "12345678-1234-1234-1234-123456789abc",
10 + version: 2,
11 + id: "gj-123456789a",
12 12 createdAt: "2026-01-01T00:00:00.000Z",
13 13 completedAt: "2026-01-01T00:01:00.000Z",
14 - praise: "gj",
14 + kind: "praise",
15 + feedback: "gj",
15 16 source: {
17 + type: "session",
16 18 cwd: "/work/shared-route",
17 19 sessionPath: "/sessions/one.jsonl",
18 20 sessionId: "session-1",
20 22 analysisModel: { provider: "openai", id: "worker" },
21 23 learning: {
22 - achievement: "Fixed the shared route",
24 + slug: "shared-route-first",
25 + summary: "Fixed the shared route",
23 26 evidence: ["All focused tests passed"],
24 - successfulBehaviors: ["Inspected callers before editing"],
27 + behaviors: ["Inspected callers before editing"],
25 28 candidateRule: "Fix the shared route before leaf callers.",
27 30 usage: {
37 40 describe("good-job UI", () => {
38 - it("renders labeled learning sections instead of JSON", () => {
41 + it("renders slug, short ID, and labeled learning sections", () => {
39 42 const markdown = formatLearningMarkdown(record);
40 - expect(markdown).toContain("## Achievement\nFixed the shared route");
43 + expect(markdown).toContain("## shared-route-first\nFixed the shared route");
44 + expect(markdown).toContain("## Feedback\ngj");
41 45 expect(markdown).toContain("## Evidence\n- All focused tests passed");
42 - expect(markdown).toContain("## Successful behaviors");
43 - expect(markdown).toContain("## Candidate rule");
46 + expect(markdown).toContain("## Behaviors");
47 + expect(markdown).toContain("gj-123456789a");
44 48 expect(markdown).not.toContain('"learning"');
51 + it("renders imported problem records without model or usage metadata", () => {
52 + const imported: GoodJobRecord = {
53 + ...record,
54 + id: "wtf-123456789a",
55 + kind: "problem",
56 + feedback: "unexpected scope expansion",
57 + source: {
58 + type: "import",
59 + importer: "legacy-wtf-v1",
60 + fingerprint: "abc123",
61 + importedAt: "2026-01-02T00:00:00.000Z",
62 + },
63 + analysisModel: null,
64 + usage: null,
65 + learning: {
66 + ...record.learning,
67 + slug: "avoid-scope-expansion",
68 + },
69 + };
70 + const markdown = formatLearningMarkdown(imported);
71 + expect(markdown).toContain("## avoid-scope-expansion");
72 + expect(markdown).toContain("problem · wtf-123456789a");
73 + expect(markdown).toContain("legacy-wtf-v1");
75 + const done = vi.fn();
76 + const theme = {
77 + fg: (_color: string, text: string) => text,
78 + bold: (text: string) => text,
79 + } as never;
80 + const component = new LearningListComponent(
81 + theme,
82 + [imported],
83 + { pending: 0, processing: 0, failed: 0, records: 1 },
84 + vi.fn(),
85 + done,
86 + );
87 + for (const character of "legacy-wtf") component.handleInput(character);
88 + expect(component.render(80).join("\n")).toContain("avoid-scope-expansion");
89 + });
47 91 it("renders a width-safe searchable list and returns the selected id", () => {
48 92 const done = vi.fn();
49 93 const requestRender = vi.fn();
58 102 requestRender,
59 103 done,
61 - for (const character of "route") component.handleInput(character);
105 + for (const character of "shared-route") component.handleInput(character);
62 106 const lines = component.render(48);
63 - expect(lines.join("\n")).toContain("Fixed the shared route");
107 + expect(lines.join("\n")).toContain("shared-route-first");
64 108 expect(lines.every((line) => visibleWidth(line) <= 48)).toBe(true);
65 109 expect(requestRender).toHaveBeenCalled();
66 110 component.handleInput("\r");

extensions/good-job/core.ts

Modified
1 +import { createHash, randomBytes } from "node:crypto";
1 2 import type { AssistantMessage } from "@earendil-works/pi-ai";
3 -export const JOB_VERSION = 1 as const;
4 -export const RECORD_VERSION = 1 as const;
4 +export const JOB_VERSION = 2 as const;
5 +export const RECORD_VERSION = 2 as const;
5 6 export const FAILURE_VERSION = 1 as const;
8 +export type FeedbackKind = "praise" | "problem";
7 10 export interface ModelRef {
8 11 provider: string;
9 12 id: string;
12 -export interface LearningSource {
15 +export interface SessionLearningSource {
16 + type: "session";
13 17 cwd: string;
14 18 sessionPath: string | null;
15 19 sessionId: string;
18 22 agentModel: ModelRef | null;
25 +export interface ImportedLearningSource {
26 + type: "import";
27 + importer: string;
28 + fingerprint: string;
29 + importedAt: string;
32 +export type LearningSource = SessionLearningSource | ImportedLearningSource;
21 34 export interface GoodJobJob {
22 35 version: typeof JOB_VERSION;
23 36 id: string;
24 37 createdAt: string;
25 - praise: string;
26 - source: LearningSource;
38 + kind: FeedbackKind;
39 + feedback: string;
40 + source: SessionLearningSource;
27 41 analysisModel: ModelRef | null;
30 44 export interface Learning {
31 - achievement: string;
45 + slug: string;
46 + summary: string;
32 47 evidence: string[];
33 - successfulBehaviors: string[];
48 + behaviors: string[];
34 49 candidateRule: string | null;
52 +export interface TokenUsage {
53 + input: number;
54 + output: number;
55 + cacheRead: number;
56 + cacheWrite: number;
57 + totalTokens: number;
58 + cost: number;
37 61 export interface GoodJobRecord {
38 62 version: typeof RECORD_VERSION;
39 63 id: string;
40 64 createdAt: string;
41 65 completedAt: string;
42 - praise: string;
66 + kind: FeedbackKind;
67 + feedback: string;
43 68 source: LearningSource;
44 - analysisModel: ModelRef;
69 + analysisModel: ModelRef | null;
45 70 learning: Learning;
46 - usage: {
47 - input: number;
48 - output: number;
49 - cacheRead: number;
50 - cacheWrite: number;
51 - totalTokens: number;
52 - cost: number;
53 - };
71 + usage: TokenUsage | null;
56 74 export interface GoodJobFailure {
63 81 const CONTROL_CHARACTERS = /[\x00-\x1F\x7F-\x9F]/g;
64 -const TRIGGER = /^(?:gj|good\s+job)[.!?]*$/i;
65 -const MAX_ACHIEVEMENT_CHARS = 180;
82 +const CROCKFORD = "0123456789abcdefghjkmnpqrstvwxyz";
83 +const GOOD_JOB_TRIGGER = /^(?:gj|good\s+job)[.!?]*(?:\s+(.*))?$/is;
84 +const WTF_TRIGGER = /^wtf[.!?]*(?:\s+(.*))?$/is;
85 +const MAX_SUMMARY_CHARS = 180;
66 86 const MAX_ITEM_CHARS = 500;
67 87 const MAX_RULE_CHARS = 700;
68 88 const MAX_ITEMS = 8;
89 +const MAX_SLUG_CHARS = 48;
70 -export function isGoodJobTrigger(text: string): boolean {
71 - return TRIGGER.test(text.trim());
91 +export function feedbackTrigger(
92 + text: string,
93 +): { kind: FeedbackKind; feedback: string } | undefined {
94 + const trimmed = text.trim();
95 + const problem = WTF_TRIGGER.exec(trimmed);
96 + if (problem)
97 + return {
98 + kind: "problem",
99 + feedback: problem[1]?.trim() || "wtf",
100 + };
101 + const praise = GOOD_JOB_TRIGGER.exec(trimmed);
102 + if (praise)
103 + return {
104 + kind: "praise",
105 + feedback: praise[1]?.trim() || trimmed,
106 + };
107 + return undefined;
74 110 export function cleanText(text: string, maximum: number): string {
79 115 return Array.from(cleaned).slice(0, maximum).join("");
118 +export function learningSlug(text: string): string {
119 + const slug = text
120 + .normalize("NFKD")
121 + .replace(/[\u0300-\u036f]/g, "")
122 + .toLowerCase()
123 + .replace(/[^a-z0-9]+/g, "-")
124 + .replace(/^-+|-+$/g, "")
125 + .split("-")
126 + .filter(Boolean)
127 + .slice(0, 6)
128 + .join("-");
129 + return slug.slice(0, MAX_SLUG_CHARS).replace(/-+$/g, "") || "learning";
132 +function encodeCrockford(bytes: Uint8Array): string {
133 + let value = 0n;
134 + for (const byte of bytes) value = (value << 8n) | BigInt(byte);
135 + value &= (1n << 50n) - 1n;
136 + let encoded = "";
137 + for (let index = 0; index < 10; index++) {
138 + encoded = CROCKFORD[Number(value & 31n)] + encoded;
139 + value >>= 5n;
141 + return encoded;
144 +export function feedbackId(
145 + kind: FeedbackKind,
146 + bytes: Uint8Array = randomBytes(7),
147 +): string {
148 + return `${kind === "praise" ? "gj" : "wtf"}-${encodeCrockford(bytes)}`;
151 +export function feedbackIdFromSeed(kind: FeedbackKind, seed: string): string {
152 + return feedbackId(
153 + kind,
154 + createHash("sha256").update(seed).digest().subarray(0, 7),
155 + );
82 158 function isRecord(value: unknown): value is Record<string, unknown> {
83 159 return value !== null && typeof value === "object" && !Array.isArray(value);
109 185 export function parseLearning(text: string): Learning {
110 186 const value = jsonObject(text);
111 187 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)
188 + const summary =
189 + typeof value.summary === "string"
190 + ? cleanText(value.summary, MAX_SUMMARY_CHARS)
192 + const slug =
193 + typeof value.slug === "string"
194 + ? learningSlug(value.slug)
195 + : learningSlug(summary);
116 196 const evidence = cleanStringArray(value.evidence);
117 - const successfulBehaviors = cleanStringArray(
118 - value.successful_behaviors ?? value.successfulBehaviors,
119 - );
197 + const behaviors = cleanStringArray(value.behaviors);
120 198 const candidateValue = value.candidate_rule ?? value.candidateRule;
121 199 const candidateRule =
122 200 candidateValue === null
124 202 : typeof candidateValue === "string"
125 203 ? cleanText(candidateValue, MAX_RULE_CHARS)
126 204 : undefined;
127 - if (!achievement || !evidence || !successfulBehaviors)
205 + if (!summary || !evidence || !behaviors)
128 206 throw new Error("analysis JSON is missing required learning fields");
129 207 if (candidateRule === undefined)
130 208 throw new Error("analysis JSON is missing candidate_rule");
131 - return { achievement, evidence, successfulBehaviors, candidateRule };
209 + return { slug, summary, evidence, behaviors, candidateRule };
134 212 export function responseText(response: AssistantMessage): string {
140 218 .join("\n");
143 -export function analysisPrompt(praise: string): string {
144 - return `The user just praised the preceding coding-agent work with: ${JSON.stringify(praise)}
221 +export function analysisPrompt(kind: FeedbackKind, feedback: string): string {
222 + const task =
223 + kind === "praise"
224 + ? "Identify what concretely went well and which agent behaviors caused it."
225 + : "Identify what surprised, confused, or annoyed the user and which behavior should prevent recurrence.";
226 + return `The user supplied ${kind} feedback: ${JSON.stringify(feedback)}
146 -Analyze what concretely went well across the full conversation above.
228 +Analyze the conversation preceding that feedback.
229 +${task}
147 230 Infer causes only when supported by the transcript.
148 -Focus on reusable agent behavior, not compliments or personality.
231 +Focus on reusable agent behavior, not compliments, blame, or personality.
149 232 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.
233 +Return exactly one JSON object with these fields:
234 +- slug: memorable kebab-case label using 2-6 short words
235 +- summary: one concrete summary, at most 180 characters
236 +- evidence: 1-8 observable transcript facts or user-visible outcomes
237 +- behaviors: 1-8 specific agent behaviors that succeeded, failed, or should change
238 +- candidate_rule: concise reusable instruction, or null when evidence is insufficient
158 239 No markdown fences or commentary.`;

extensions/good-job/implementation.ts

Modified
1 1 import { spawn } from "node:child_process";
2 -import { randomUUID } from "node:crypto";
3 2 import { accessSync, constants, existsSync } from "node:fs";
4 3 import { basename, delimiter, join } from "node:path";
5 4 import type { Message, ThinkingLevel } from "@earendil-works/pi-ai";
6 5 import {
7 6 buildSessionContext,
8 7 convertToLlm,
8 + type ExtensionAPI,
9 9 type ExtensionContext,
10 10 SessionManager,
11 11 SettingsManager,
13 13 import {
14 14 analysisPrompt,
15 15 boundedError,
16 + type FeedbackKind,
17 + feedbackId,
16 18 type GoodJobJob,
17 19 type GoodJobRecord,
18 20 JOB_VERSION,
26 28 claimJob,
27 29 commitFailure,
28 30 commitRecord,
31 + configuredDataDirectory,
29 32 counts,
30 33 enqueueJob,
31 34 ensureLayout,
33 36 goodJobDataDirectory,
34 37 layout,
35 38 loadRecords,
39 + migrateStore,
36 40 pendingJobIds,
37 41 recoverProcessing,
38 42 } from "./storage.js";
51 55 type Opener = { command: string; args: string[] };
52 56 type GoodJobSettings = {
57 + directory?: string;
53 58 model?: string;
54 59 thinkingLevel?: ThinkingLevel;
66 71 export interface GoodJobRuntime {
67 72 start(ctx: ExtensionContext): Promise<void>;
68 73 stop(ctx: ExtensionContext): Promise<void>;
69 - capture(praise: string, ctx: ExtensionContext): Promise<void>;
74 + capture(
75 + kind: FeedbackKind,
76 + feedback: string,
77 + ctx: ExtensionContext,
78 + ): Promise<void>;
70 79 runCommand(args: string, ctx: ExtensionContext): Promise<void>;
112 121 throw new Error(
113 122 "goodJob.thinkingLevel must be minimal, low, medium, high, xhigh, or max",
124 + if (
125 + merged.directory !== undefined &&
126 + (typeof merged.directory !== "string" || !merged.directory.trim())
128 + throw new Error("goodJob.directory must be a non-empty path");
115 129 return {
130 + directory:
131 + typeof merged.directory === "string"
132 + ? merged.directory.trim()
133 + : undefined,
116 134 model:
117 135 typeof merged.model === "string" && merged.model.trim()
118 136 ? merged.model.trim()
126 144 messages: readonly unknown[],
127 145 ): GoodJobJob["source"] {
128 146 return {
147 + type: "session",
129 148 cwd: ctx.cwd,
130 149 sessionPath: ctx.sessionManager.getSessionFile() ?? null,
131 150 sessionId: ctx.sessionManager.getSessionId(),
138 157 function completionContext(
139 158 conversation: readonly Message[],
140 - praise: string,
159 + kind: FeedbackKind,
160 + feedback: string,
141 161 ): Message[] {
142 162 return [
143 163 ...conversation,
145 165 role: "user",
146 - content: [{ type: "text", text: analysisPrompt(praise) }],
166 + content: [{ type: "text", text: analysisPrompt(kind, feedback) }],
147 167 timestamp: Date.now(),
240 +function learningPrompt(recordsPath: string): string {
241 + return `Review every structured GJ learning record under ${JSON.stringify(recordsPath)}.
242 +Read the files yourself; the path is the only learning data supplied in this prompt.
243 +Analyze praise and problem records together.
244 +Reconcile conflicting signals and distinguish recurring evidence from isolated incidents.
245 +Propose concrete changes to Pi configuration, instructions, skills, extensions, or workflows.
246 +Do not edit anything; proposals only.
247 +For every claim and proposal, cite supporting records as \`slug (id)\` using both fields exactly.`;
220 250 class Runtime implements GoodJobRuntime {
221 251 private generation = 0;
222 252 private activeController: AbortController | undefined;
229 259 private openerChecked = false;
230 260 private settings: GoodJobSettings = {};
231 261 private settingsCwd: string | undefined;
232 - private readonly paths: GoodJobLayout;
262 + private paths: GoodJobLayout;
233 263 private readonly opener: Opener | undefined;
264 + private readonly defaultRoot = goodJobDataDirectory();
235 - constructor(root = goodJobDataDirectory()) {
236 - this.paths = layout(root);
266 + constructor(
267 + private readonly pi: ExtensionAPI,
268 + private readonly fixedRoot?: string,
269 + ) {
270 + this.paths = layout(fixedRoot ?? this.defaultRoot);
237 271 this.opener = openerFor();
247 281 if (generation !== this.generation) return;
248 282 this.pumpRequested = false;
249 283 this.readSettings(cwd);
284 + const targetRoot = this.paths.root;
285 + const targetMigration = await migrateStore(targetRoot, targetRoot);
286 + const defaultMigration =
287 + targetRoot === this.defaultRoot
288 + ? { jobs: 0, records: 0, failures: 0, active: 0 }
289 + : await migrateStore(this.defaultRoot, targetRoot);
290 + const migrated = {
291 + jobs: targetMigration.jobs + defaultMigration.jobs,
292 + records: targetMigration.records + defaultMigration.records,
293 + failures: targetMigration.failures + defaultMigration.failures,
294 + active: targetMigration.active + defaultMigration.active,
295 + };
296 + if (migrated.jobs || migrated.records || migrated.failures)
297 + background.ui?.notify(
298 + `gj migrated · ${migrated.records} records · ${migrated.jobs} queued · ${migrated.failures} failed`,
299 + "info",
300 + );
301 + if (migrated.active)
302 + background.ui?.notify(
303 + `gj left ${migrated.active} active processing claim${migrated.active === 1 ? "" : "s"} in the old store`,
304 + "warning",
305 + );
250 306 if (!this.openerChecked) {
251 307 this.openerChecked = true;
252 308 if (!this.opener)
269 325 this.stopSpinner(ui);
272 - async capture(praise: string, ctx: ExtensionContext): Promise<void> {
328 + async capture(
329 + kind: FeedbackKind,
330 + feedback: string,
331 + ctx: ExtensionContext,
332 + ): Promise<void> {
273 333 const background = backgroundContext(ctx);
274 334 this.readSettings(ctx.cwd);
275 335 const sessionContext = buildSessionContext(
279 339 const snapshot = convertToLlm(sessionContext.messages);
280 340 const job: GoodJobJob = {
281 341 version: JOB_VERSION,
282 - id: randomUUID(),
342 + id: feedbackId(kind),
283 343 createdAt: new Date().toISOString(),
284 - praise: praise.trim(),
344 + kind,
345 + feedback: feedback.trim(),
285 346 source: sourceFor(ctx, sessionContext.messages),
286 347 analysisModel: this.analysisModel(ctx),
288 349 await ensureLayout(this.paths);
289 350 await enqueueJob(job, this.paths);
290 351 this.snapshots.set(job.id, snapshot);
291 - background.ui?.notify(`good-job queued · ${job.id.slice(0, 8)}`, "info");
352 + background.ui?.notify(`${job.id} queued`, "info");
292 353 void this.pump(background, this.generation, job.id);
295 356 async runCommand(args: string, ctx: ExtensionContext): Promise<void> {
296 357 this.readSettings(ctx.cwd);
297 - const [command = "list", id = ""] = args.trim().split(/\s+/, 2);
358 + const [command = "list"] = args.trim().split(/\s+/, 1);
298 359 if (command === "list" || command === "") {
299 360 await this.list(ctx);
300 361 return;
302 - if (command === "show") {
303 - await this.show(id, ctx);
304 - return;
305 - }
306 363 if (command === "status") {
307 364 await this.status(ctx);
308 365 return;
311 368 await this.open(ctx);
312 369 return;
314 - ctx.ui.notify("Usage: /good-job [list|show <id>|status|open]", "warning");
371 + if (command === "learn") {
372 + await this.learn(ctx);
373 + return;
375 + ctx.ui.notify("Usage: /gj [list|status|open|learn]", "warning");
317 378 private readSettings(cwd: string): void {
318 379 if (this.settingsCwd === cwd) return;
319 380 this.settings = settingsFrom(cwd);
381 + this.paths = layout(
382 + this.fixedRoot ?? configuredDataDirectory(this.settings.directory, cwd),
383 + );
320 384 this.settingsCwd = cwd;
411 475 model,
413 477 systemPrompt:
414 - "Extract evidence-backed, reusable lessons from praised coding-agent work.",
415 - messages: completionContext(snapshot, job.praise),
478 + "Extract evidence-backed, reusable lessons from explicit user feedback about coding-agent work.",
479 + messages: completionContext(snapshot, job.kind, job.feedback),
418 482 maxTokens: MAX_TOKENS,
434 498 id: job.id,
435 499 createdAt: job.createdAt,
436 500 completedAt: new Date().toISOString(),
437 - praise: job.praise,
501 + kind: job.kind,
502 + feedback: job.feedback,
438 503 source: job.source,
439 504 analysisModel: job.analysisModel,
440 505 learning,
450 515 await commitRecord(record, claimPath, this.paths);
451 516 this.snapshots.delete(job.id);
452 - ctx.ui?.notify(
453 - `good-job learned · ${record.learning.achievement}`,
454 - "info",
455 - );
517 + ctx.ui?.notify(`${record.id} learned · ${record.learning.slug}`, "info");
456 518 } catch (error) {
457 519 if (controller.signal.aborted || generation !== this.generation) return;
458 520 let message = `good-job failed: ${boundedError(error)}`;
523 585 if (record) await showLearningDetail(ctx, record);
526 - private async show(id: string, ctx: ExtensionContext): Promise<void> {
527 - if (!id) {
528 - ctx.ui.notify("Usage: /good-job show <id>", "warning");
529 - return;
530 - }
531 - const loaded = await loadRecords(this.paths);
532 - const matches = loaded.records.filter((record) => record.id.startsWith(id));
533 - if (matches.length !== 1) {
534 - ctx.ui.notify(
535 - matches.length === 0
536 - ? `Unknown good-job id: ${id}`
537 - : `Ambiguous good-job id: ${id}`,
538 - "warning",
539 - );
540 - return;
541 - }
542 - await showLearningDetail(ctx, matches[0] as GoodJobRecord);
543 - }
545 588 private async status(ctx: ExtensionContext): Promise<void> {
546 589 const state = await counts(this.paths);
547 590 ctx.ui.notify(
604 + private async learn(ctx: ExtensionContext): Promise<void> {
605 + const state = await counts(this.paths);
606 + if (state.records === 0) {
607 + ctx.ui.notify("No GJ learnings yet", "info");
608 + return;
610 + this.pi.sendUserMessage(learningPrompt(this.paths.records), {
611 + deliverAs: ctx.isIdle() ? undefined : "followUp",
612 + });
561 615 private async open(ctx: ExtensionContext): Promise<void> {
562 616 await ensureLayout(this.paths);
573 627 export function createGoodJobRuntime(
574 - root = goodJobDataDirectory(),
628 + pi: ExtensionAPI,
629 + root?: string,
575 630 ): GoodJobRuntime {
576 - return new Runtime(root);
631 + return new Runtime(pi, root);

extensions/good-job/index.ts

Modified
1 1 import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2 2 import type { AutocompleteItem } from "@earendil-works/pi-tui";
3 -import { boundedError, isGoodJobTrigger } from "./core.js";
3 +import { boundedError, feedbackTrigger } from "./core.js";
4 4 import type { GoodJobRuntime } from "./implementation.js";
6 -const SUBCOMMANDS = ["list", "show", "status", "open"] as const;
6 +const SUBCOMMANDS = ["list", "status", "open", "learn"] as const;
8 8 export default function goodJobExtension(pi: ExtensionAPI): void {
9 9 let runtime: Promise<GoodJobRuntime> | undefined;
11 11 let sessionReady: Promise<void> = Promise.resolve();
12 12 const getRuntime = () =>
13 13 (runtime ??= import("./implementation.js").then(
14 - ({ createGoodJobRuntime }) => createGoodJobRuntime(),
14 + ({ createGoodJobRuntime }) => createGoodJobRuntime(pi),
17 - pi.registerCommand("good-job", {
18 - description: "List, inspect, and locate praised-work learnings",
17 + pi.registerCommand("gj", {
18 + description: "List, inspect, and learn from explicit feedback",
19 19 getArgumentCompletions(prefix): AutocompleteItem[] | null {
20 20 const normalized = prefix.trimStart().toLowerCase();
21 21 if (normalized.includes(" ")) return null;
33 33 pi.on("input", async (event, ctx) => {
34 - if (event.source === "extension" || !isGoodJobTrigger(event.text))
35 - return { action: "continue" };
34 + if (event.source === "extension") return { action: "continue" };
35 + const feedback = feedbackTrigger(event.text);
36 + if (!feedback) return { action: "continue" };
36 37 const ui = ctx.hasUI ? ctx.ui : undefined;
37 38 try {
38 39 await sessionReady;
39 - await (await getRuntime()).capture(event.text, ctx);
40 + await (await getRuntime()).capture(feedback.kind, feedback.feedback, ctx);
40 41 } catch (error) {
41 - const message = error instanceof Error ? error.message : String(error);
42 - ui?.notify(`good-job could not queue: ${message}`, "error");
42 + ui?.notify(`gj could not queue: ${boundedError(error)}`, "error");
44 - return { action: "handled" };
44 + return { action: "continue" };
47 47 pi.on("session_start", (_event, ctx) => {
54 54 .catch((error) => {
55 55 if (generation === currentGeneration)
56 - ui?.notify(
57 - `good-job startup failed: ${boundedError(error)}`,
58 - "error",
59 - );
56 + ui?.notify(`gj startup failed: ${boundedError(error)}`, "error");

extensions/good-job/package.json

Modified
5 5 "name": "@bugabinga/pi-ext-good-job",
6 6 "private": true,
7 7 "type": "module",
8 8 "main": "index.ts",
9 9 "license": "MIT",
10 - "description": "Turn explicit praise into durable coding-agent learnings.",
10 + "description": "Turn explicit gj and wtf feedback into durable coding-agent learnings.",
11 11 "keywords": [
12 12 "pi",
13 13 "pi-extension"

extensions/good-job/storage.ts

Modified
1 1 import { randomUUID } from "node:crypto";
2 -import { mkdir, open, readdir, readFile, rename, rm } from "node:fs/promises";
2 +import {
3 + link,
4 + mkdir,
5 + open,
6 + readdir,
7 + readFile,
8 + realpath,
9 + rename,
10 + rm,
11 +} from "node:fs/promises";
3 12 import { homedir } from "node:os";
4 -import { basename, dirname, join, posix, win32 } from "node:path";
13 +import { basename, dirname, join, posix, resolve, win32 } from "node:path";
5 14 import type {
6 15 GoodJobFailure,
7 16 GoodJobJob,
8 17 GoodJobRecord,
18 + ImportedLearningSource,
9 19 LearningSource,
10 20 ModelRef,
21 + SessionLearningSource,
22 + TokenUsage,
11 23 } from "./core.js";
12 24 import {
13 25 boundedError,
14 26 FAILURE_VERSION,
27 + feedbackIdFromSeed,
15 28 JOB_VERSION,
29 + learningSlug,
16 30 RECORD_VERSION,
17 31 } from "./core.js";
41 55 errors: string[];
58 +export interface MigrationResult {
59 + jobs: number;
60 + records: number;
61 + failures: number;
62 + active: number;
44 65 export function goodJobDataDirectory(
45 66 env: NodeJS.ProcessEnv = process.env,
46 67 platform = process.platform,
87 +export function configuredDataDirectory(
88 + value: string | undefined,
89 + cwd: string,
90 + home = homedir(),
91 +): string {
92 + if (!value) return goodJobDataDirectory();
93 + const trimmed = value.trim();
94 + if (trimmed === "~") return home;
95 + if (/^~[\\/]/.test(trimmed)) return resolve(home, trimmed.slice(2));
96 + return resolve(cwd, trimmed);
66 99 export function layout(root = goodJobDataDirectory()): GoodJobLayout {
67 100 return {
113 -export async function atomicWriteJson(
114 - target: string,
115 - value: unknown,
116 -): Promise<void> {
146 +async function temporaryJson(target: string, value: unknown): Promise<string> {
117 147 const directory = dirname(target);
118 148 await mkdir(directory, { recursive: true, mode: 0o700 });
119 149 const temporary = join(
130 160 throw error;
132 162 await file.close();
163 + return temporary;
166 +export async function atomicWriteJson(
167 + target: string,
168 + value: unknown,
169 +): Promise<void> {
170 + const temporary = await temporaryJson(target, value);
134 172 await rename(temporary, target);
135 - await syncDirectory(directory);
173 + await syncDirectory(dirname(target));
136 174 } catch (error) {
137 175 await rm(temporary, { force: true });
138 176 throw error;
180 +export async function atomicCreateJson(
181 + target: string,
182 + value: unknown,
183 +): Promise<void> {
184 + const temporary = await temporaryJson(target, value);
185 + try {
186 + await link(temporary, target);
187 + await rm(temporary, { force: true });
188 + await syncDirectory(dirname(target));
189 + } catch (error) {
190 + await rm(temporary, { force: true });
191 + throw error;
195 +function isObject(value: unknown): value is Record<string, unknown> {
196 + return value !== null && typeof value === "object" && !Array.isArray(value);
142 199 function modelRef(value: unknown): value is ModelRef {
143 200 return (
144 201 isObject(value) &&
152 -function source(value: unknown): value is LearningSource {
209 +function sessionSource(value: unknown): value is SessionLearningSource {
153 210 return (
154 211 isObject(value) &&
212 + value.type === "session" &&
155 213 typeof value.cwd === "string" &&
156 214 (value.sessionPath === null || typeof value.sessionPath === "string") &&
157 215 typeof value.sessionId === "string" &&
164 -function isObject(value: unknown): value is Record<string, unknown> {
165 - return value !== null && typeof value === "object" && !Array.isArray(value);
222 +function importedSource(value: unknown): value is ImportedLearningSource {
223 + return (
224 + isObject(value) &&
225 + value.type === "import" &&
226 + typeof value.importer === "string" &&
227 + value.importer.length > 0 &&
228 + typeof value.fingerprint === "string" &&
229 + value.fingerprint.length > 0 &&
230 + typeof value.importedAt === "string"
231 + );
234 +function source(value: unknown): value is LearningSource {
235 + return sessionSource(value) || importedSource(value);
238 +function legacySource(
239 + value: unknown,
240 +): Omit<SessionLearningSource, "type"> | undefined {
241 + if (
242 + !isObject(value) ||
243 + typeof value.cwd !== "string" ||
244 + !(value.sessionPath === null || typeof value.sessionPath === "string") ||
245 + typeof value.sessionId !== "string" ||
246 + !(value.sessionName === null || typeof value.sessionName === "string") ||
247 + !(value.leafId === null || typeof value.leafId === "string") ||
248 + !(value.agentModel === null || modelRef(value.agentModel))
250 + return undefined;
251 + return value as unknown as Omit<SessionLearningSource, "type">;
168 254 function stringArray(value: unknown): value is string[] {
177 263 return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
180 -function recordUsage(value: unknown): boolean {
266 +function recordUsage(value: unknown): value is TokenUsage {
181 267 return (
182 268 isObject(value) &&
183 269 nonnegativeInteger(value.input) &&
280 +function feedbackKind(value: unknown): value is GoodJobJob["kind"] {
281 + return value === "praise" || value === "problem";
284 +function currentId(value: unknown, kind: GoodJobJob["kind"]): value is string {
285 + const prefix = kind === "praise" ? "gj" : "wtf";
286 + return (
287 + typeof value === "string" &&
288 + new RegExp(`^${prefix}-[0-9a-hjkmnp-tv-z]{10}$`).test(value)
289 + );
194 292 export function parseJob(value: unknown): GoodJobJob | undefined {
196 294 !isObject(value) ||
197 295 value.version !== JOB_VERSION ||
198 - typeof value.id !== "string" ||
296 + !feedbackKind(value.kind) ||
297 + !currentId(value.id, value.kind) ||
199 298 typeof value.createdAt !== "string" ||
200 - typeof value.praise !== "string" ||
201 - !source(value.source) ||
299 + typeof value.feedback !== "string" ||
300 + !sessionSource(value.source) ||
202 301 !(value.analysisModel === null || modelRef(value.analysisModel))
204 303 return undefined;
210 309 !isObject(value) ||
211 310 value.version !== RECORD_VERSION ||
311 + !feedbackKind(value.kind) ||
312 + !currentId(value.id, value.kind) ||
313 + typeof value.createdAt !== "string" ||
314 + typeof value.completedAt !== "string" ||
315 + typeof value.feedback !== "string" ||
316 + !source(value.source) ||
317 + !(value.analysisModel === null || modelRef(value.analysisModel)) ||
318 + !isObject(value.learning) ||
319 + typeof value.learning.slug !== "string" ||
320 + learningSlug(value.learning.slug) !== value.learning.slug ||
321 + typeof value.learning.summary !== "string" ||
322 + value.learning.summary.length === 0 ||
323 + !stringArray(value.learning.evidence) ||
324 + !stringArray(value.learning.behaviors) ||
325 + !(
326 + value.learning.candidateRule === null ||
327 + typeof value.learning.candidateRule === "string"
328 + ) ||
329 + !(value.usage === null || recordUsage(value.usage))
331 + return undefined;
332 + return value as unknown as GoodJobRecord;
335 +function migrateLegacyJob(value: unknown): GoodJobJob | undefined {
336 + if (
337 + !isObject(value) ||
338 + value.version !== 1 ||
339 + typeof value.id !== "string" ||
340 + typeof value.createdAt !== "string" ||
341 + typeof value.praise !== "string" ||
342 + !(value.analysisModel === null || modelRef(value.analysisModel))
344 + return undefined;
345 + const oldSource = legacySource(value.source);
346 + if (!oldSource) return undefined;
347 + return {
348 + version: JOB_VERSION,
349 + id: feedbackIdFromSeed("praise", `good-job-v1:${value.id}`),
350 + createdAt: value.createdAt,
351 + kind: "praise",
352 + feedback: value.praise,
353 + source: { type: "session", ...oldSource },
354 + analysisModel: value.analysisModel,
355 + };
358 +function migrateLegacyRecord(value: unknown): GoodJobRecord | undefined {
359 + if (
360 + !isObject(value) ||
361 + value.version !== 1 ||
212 362 typeof value.id !== "string" ||
213 363 typeof value.createdAt !== "string" ||
214 364 typeof value.completedAt !== "string" ||
215 365 typeof value.praise !== "string" ||
216 - !source(value.source) ||
217 366 !modelRef(value.analysisModel) ||
218 367 !isObject(value.learning) ||
219 368 typeof value.learning.achievement !== "string" ||
227 376 !recordUsage(value.usage)
229 378 return undefined;
230 - return value as unknown as GoodJobRecord;
379 + const oldSource = legacySource(value.source);
380 + if (!oldSource) return undefined;
381 + return {
382 + version: RECORD_VERSION,
383 + id: feedbackIdFromSeed("praise", `good-job-v1:${value.id}`),
384 + createdAt: value.createdAt,
385 + completedAt: value.completedAt,
386 + kind: "praise",
387 + feedback: value.praise,
388 + source: { type: "session", ...oldSource },
389 + analysisModel: value.analysisModel,
390 + learning: {
391 + slug: learningSlug(value.learning.achievement),
392 + summary: value.learning.achievement,
393 + evidence: value.learning.evidence,
394 + behaviors: value.learning.successfulBehaviors,
395 + candidateRule: value.learning.candidateRule,
396 + },
397 + usage: value.usage,
398 + };
233 401 async function readJson(path: string): Promise<unknown> {
234 402 return JSON.parse(await readFile(path, "utf8"));
405 +async function exists(path: string): Promise<boolean> {
406 + try {
407 + const file = await open(path, "r");
408 + await file.close();
409 + return true;
410 + } catch (error) {
411 + if (isNodeError(error) && error.code === "ENOENT") return false;
412 + throw error;
416 +async function moveValue(
417 + sourcePath: string,
418 + targetPath: string,
419 + value: unknown,
420 +): Promise<void> {
421 + if (sourcePath === targetPath) {
422 + await atomicWriteJson(targetPath, value);
423 + return;
425 + try {
426 + await atomicCreateJson(targetPath, value);
427 + } catch (error) {
428 + if (!(isNodeError(error) && error.code === "EEXIST")) throw error;
429 + const existing = await readJson(targetPath);
430 + if (JSON.stringify(existing) !== JSON.stringify(value))
431 + throw new Error(`migration collision at ${targetPath}`);
433 + await rm(sourcePath, { force: true });
436 +async function migrateJobs(
437 + from: GoodJobLayout,
438 + to: GoodJobLayout,
439 +): Promise<number> {
440 + let migrated = 0;
441 + for (const file of await jsonFiles(from.pending)) {
442 + const sourcePath = join(from.pending, file);
443 + const value = await readJson(sourcePath);
444 + const job = parseJob(value) ?? migrateLegacyJob(value);
445 + if (!job) throw new Error(`cannot migrate queued job ${sourcePath}`);
446 + const targetPath = join(to.pending, `${job.id}.json`);
447 + if (sourcePath !== targetPath || !parseJob(value)) {
448 + await moveValue(sourcePath, targetPath, job);
449 + migrated++;
452 + return migrated;
455 +async function migrateRecords(
456 + from: GoodJobLayout,
457 + to: GoodJobLayout,
458 +): Promise<number> {
459 + let migrated = 0;
460 + for (const file of await jsonFiles(from.records)) {
461 + const sourcePath = join(from.records, file);
462 + const value = await readJson(sourcePath);
463 + const record = parseRecord(value) ?? migrateLegacyRecord(value);
464 + if (!record)
465 + throw new Error(`cannot migrate learning record ${sourcePath}`);
466 + const targetPath = join(to.records, `${record.id}.json`);
467 + if (sourcePath !== targetPath || !parseRecord(value)) {
468 + await moveValue(sourcePath, targetPath, record);
469 + migrated++;
472 + return migrated;
475 +async function migrateFailures(
476 + from: GoodJobLayout,
477 + to: GoodJobLayout,
478 +): Promise<number> {
479 + let migrated = 0;
480 + for (const file of await jsonFiles(from.failed)) {
481 + const sourcePath = join(from.failed, file);
482 + const value = await readJson(sourcePath);
483 + if (
484 + !isObject(value) ||
485 + value.version !== FAILURE_VERSION ||
486 + typeof value.failedAt !== "string" ||
487 + typeof value.error !== "string"
489 + throw new Error(`cannot migrate failure ${sourcePath}`);
490 + if (value.job === null) {
491 + const targetPath = join(to.failed, file);
492 + if (sourcePath !== targetPath) {
493 + await moveValue(sourcePath, targetPath, value);
494 + migrated++;
496 + continue;
498 + const job = parseJob(value.job) ?? migrateLegacyJob(value.job);
499 + if (!job) throw new Error(`cannot migrate failure ${sourcePath}`);
500 + const failure: GoodJobFailure = {
501 + version: FAILURE_VERSION,
502 + job,
503 + failedAt: value.failedAt,
504 + error: value.error,
505 + };
506 + const targetPath = join(to.failed, `${job.id}.json`);
507 + if (sourcePath !== targetPath || !parseJob(value.job)) {
508 + await moveValue(sourcePath, targetPath, failure);
509 + migrated++;
512 + return migrated;
515 +async function sameDirectory(left: string, right: string): Promise<boolean> {
516 + if (resolve(left) === resolve(right)) return true;
517 + try {
518 + return (await realpath(left)) === (await realpath(right));
519 + } catch (error) {
520 + if (isNodeError(error) && error.code === "ENOENT") return false;
521 + throw error;
525 +export async function migrateStore(
526 + sourceRoot: string,
527 + targetRoot: string,
528 +): Promise<MigrationResult> {
529 + const from = layout(sourceRoot);
530 + const destination = layout(targetRoot);
531 + const before = await counts(from);
532 + if (before.pending + before.processing + before.failed + before.records === 0)
533 + return { jobs: 0, records: 0, failures: 0, active: 0 };
534 + await ensureLayout(destination);
535 + const to = (await sameDirectory(sourceRoot, targetRoot)) ? from : destination;
536 + await recoverProcessing(from);
537 + const [jobs, records, failures] = await Promise.all([
538 + migrateJobs(from, to),
539 + migrateRecords(from, to),
540 + migrateFailures(from, to),
541 + ]);
542 + return {
543 + jobs,
544 + records,
545 + failures,
546 + active: (await jsonFiles(from.processing)).length,
547 + };
237 550 export async function enqueueJob(
238 551 job: GoodJobJob,
239 552 paths: GoodJobLayout,
240 553 ): 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);
554 + if (!parseJob(job)) throw new Error("refusing to persist invalid gj job");
555 + const file = `${job.id}.json`;
556 + if (
557 + (await exists(join(paths.records, file))) ||
558 + (await exists(join(paths.failed, file))) ||
559 + (await jsonFiles(paths.processing)).some((claim) =>
560 + claim.startsWith(`${job.id}--`),
563 + throw new Error(`duplicate gj id ${job.id}`);
564 + try {
565 + await atomicCreateJson(join(paths.pending, file), job);
566 + } catch (error) {
567 + if (isNodeError(error) && error.code === "EEXIST")
568 + throw new Error(`duplicate gj id ${job.id}`);
569 + throw error;
246 573 export async function claimJob(
277 604 failedAt: new Date().toISOString(),
278 605 error,
280 - await atomicWriteJson(join(paths.failed, `${id}.json`), failed);
607 + await atomicCreateJson(join(paths.failed, `${id}.json`), failed);
281 608 await rm(path, { force: true });
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;
343 - }
346 662 export async function commitRecord(
347 663 record: GoodJobRecord,
348 664 claimPath: string,
349 665 paths: GoodJobLayout,
350 666 ): Promise<void> {
351 667 if (!parseRecord(record))
352 - throw new Error("refusing to persist invalid good-job record");
353 - await atomicWriteJson(join(paths.records, `${record.id}.json`), record);
668 + throw new Error("refusing to persist invalid gj record");
669 + try {
670 + await atomicCreateJson(join(paths.records, `${record.id}.json`), record);
671 + } catch (error) {
672 + if (isNodeError(error) && error.code === "EEXIST")
673 + throw new Error(`duplicate gj id ${record.id}`);
674 + throw error;
354 676 await rm(claimPath, { force: true });
366 688 failedAt: new Date().toISOString(),
367 689 error: boundedError(error),
369 - await atomicWriteJson(join(paths.failed, `${job.id}.json`), failure);
691 + try {
692 + await atomicCreateJson(join(paths.failed, `${job.id}.json`), failure);
693 + } catch (error) {
694 + if (isNodeError(error) && error.code === "EEXIST")
695 + throw new Error(`duplicate gj id ${job.id}`);
696 + throw error;
370 698 await rm(claimPath, { force: true });
374 702 paths: GoodJobLayout,
375 703 ): Promise<LoadedRecords> {
376 704 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 705 const loaded = await Promise.all(
380 706 files.map(async (file) => {

extensions/good-job/ui.ts

Modified
35 35 function projectLabel(record: GoodJobRecord): string {
36 + if (record.source.type === "import") return record.source.importer;
36 37 const normalized = record.source.cwd.replaceAll("\\", "/").replace(/\/$/, "");
37 38 return normalized.split("/").at(-1) || record.source.cwd;
45 46 const evidence = record.learning.evidence
46 47 .map((item) => `- ${markdownText(item)}`)
47 48 .join("\n");
48 - const behaviors = record.learning.successfulBehaviors
49 + const behaviors = record.learning.behaviors
49 50 .map((item) => `- ${markdownText(item)}`)
50 51 .join("\n");
51 52 const rule = record.learning.candidateRule
52 53 ? markdownText(record.learning.candidateRule)
53 54 : "No durable rule proposed.";
54 - const sourceModel = record.source.agentModel
55 - ? `${record.source.agentModel.provider}/${record.source.agentModel.id}`
56 - : "unknown agent model";
55 + const sourceModel =
56 + record.source.type === "session" && record.source.agentModel
57 + ? `${record.source.agentModel.provider}/${record.source.agentModel.id}`
58 + : record.source.type === "import"
59 + ? record.source.importer
60 + : "unknown agent model";
57 61 return [
58 - "## Achievement",
59 - markdownText(record.learning.achievement),
62 + `## ${markdownText(record.learning.slug)}`,
63 + markdownText(record.learning.summary),
64 + "",
65 + "## Feedback",
66 + markdownText(record.feedback),
61 68 "## Evidence",
62 69 evidence,
64 - "## Successful behaviors",
71 + "## Behaviors",
65 72 behaviors,
67 74 "## Candidate rule",
68 75 rule,
70 - `*${dateLabel(record.completedAt)} · ${markdownText(projectLabel(record))} · ${markdownText(sourceModel)} · ${record.id.slice(0, 8)}*`,
77 + `*${record.kind} · ${record.id} · ${dateLabel(record.completedAt)} · ${markdownText(projectLabel(record))} · ${markdownText(sourceModel)}*`,
71 78 ].join("\n");
79 86 if (words.length === 0) return [...records];
80 87 return records.filter((record) => {
81 88 const haystack = [
82 - record.learning.achievement,
89 + record.kind,
90 + record.learning.slug,
91 + record.feedback,
92 + record.learning.summary,
83 93 record.learning.candidateRule ?? "",
84 - ...record.learning.successfulBehaviors,
94 + ...record.learning.behaviors,
85 95 projectLabel(record),
86 96 record.id,
161 171 .join(" · ");
162 172 const lines = [
163 173 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)}`,
174 + `${this.theme.fg("accent", this.theme.bold("GJ / WTF"))} ${this.theme.fg(this.counts.failed ? "warning" : "dim", status)}`,
165 175 `search ${this.search.render(Math.max(1, safeWidth - 8))[0] ?? ""}`,
171 181 for (const [offset, record] of visible.entries()) {
172 182 const selected = first + offset === this.selected;
173 183 const marker = selected ? "▸" : " ";
174 - const achievement = `${marker} ${oneLine(record.learning.achievement, 120)}`;
184 + const summary = `${marker} ${record.learning.slug} · ${oneLine(record.learning.summary, 100)}`;
175 185 lines.push(
176 - selected ? this.theme.fg("accent", achievement) : achievement,
186 + selected ? this.theme.fg("accent", summary) : summary,
177 187 this.theme.fg(
178 188 "dim",
179 - ` ${dateLabel(record.completedAt)} · ${projectLabel(record)} · ${record.id.slice(0, 8)}`,
189 + ` ${record.id} · ${dateLabel(record.completedAt)} · ${projectLabel(record)}`,
222 232 .slice(0, 10)
224 234 (record) =>
225 - `${record.id.slice(0, 8)} ${dateLabel(record.completedAt)} ${oneLine(record.learning.achievement)}`,
235 + `${record.id} ${record.learning.slug} ${dateLabel(record.completedAt)} ${oneLine(record.learning.summary)}`,
227 237 .join("\n"),
228 238 "info",
256 266 new DynamicBorder((text: string) => theme.fg("accent", text));
257 267 container.addChild(border());
258 268 container.addChild(
259 - new Text(
260 - `${theme.fg("success", "✓")} ${theme.fg("accent", theme.bold("GOOD JOB"))}`,
261 - 1,
262 - 0,
263 - ),
269 + new Text(theme.fg("accent", theme.bold("GJ / WTF")), 1, 0),
265 271 container.addChild(new Markdown(markdown, 1, 1, getMarkdownTheme()));
266 272 container.addChild(new Text(theme.fg("dim", "enter/esc/q close"), 1, 0));