pi-ext bugabingas pi extensions
owned by bugabinga
README Source History Refs Compare Notes Search feat(good-job): unify praise and problem learnings 06619b31101ecbeb13c407fb92e655458dcc8c2b
Oliver Jan Krylow <oliver@bugabinga.net > · 20 Sep 2026
SSH signature · not checked
Browse files Compare 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) 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 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.
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`:
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.
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}` );
16 17 createdAt:
"2026-01-01T00:00:00.000Z" ,
17 18 completedAt:
`2026-01-01T00:${ String (index % 60). padStart (2, "0")}:00.000Z` ,
21 24 sessionPath:
"/sessions/example.jsonl" ,
22 25 sessionId:
"session-1" ,
27 30 analysisModel : {
provider :
"provider" ,
id :
"analyzer" },
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." ,
extensions/good-job/__tests__/core.test.ts Modified 1 1 import { describe, expect, it }
from "vitest" ;
2 - import { analysisPrompt, isGoodJobTrigger, parseLearning }
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 [
10 - "good job, now continue" ,
15 - expect (
isGoodJobTrigger (other), other).
toBe (
false );
11 + it (
"matches praise and problem prefixes with optional details" , ()
=> {
12 + expect (
feedbackTrigger (
"gj" )).
toEqual ({
16 + expect (
feedbackTrigger (
"good job! excellent scope control" )).
toEqual ({
18 + feedback:
"excellent scope control" ,
20 + expect (
feedbackTrigger (
"wtf you deleted my db" )).
toEqual ({
22 + feedback:
"you deleted my db" ,
24 + for (
const other
of [
"great job" ,
"object.gj" ,
"/gj list" ,
"" ,
"awtf" ])
25 + expect (
feedbackTrigger (other), other).
toBeUndefined ();
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}$ / ,
34 + expect (
feedbackIdFromSeed (
"problem" ,
"same" )).
toBe (
35 + feedbackIdFromSeed (
"problem" ,
"same" ),
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." 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 34 + function learning (summary
: string , slug
= "shared-route-first" ) {
35 + return fauxAssistantMessage (
39 + evidence: [
"Focused tests passed" ],
40 + behaviors: [
"Inspected callers before editing" ],
41 + candidate_rule:
"Fix shared routes before leaf callers." ,
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 ();
50 - extension.commands.
get (
"good-job" ).
getArgumentCompletions (
"" ),
63 + t.session.resourceLoader
65 + .prompts.
find (({ name })
=> name
=== "wtf" ),
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 }],
70 - fauxAssistantMessage (
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." ,
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),
106 + text:
"good job! excellent scope control" ,
107 + source:
"interactive" ,
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 ({
122 + feedback:
"excellent scope control" ,
124 + slug:
"shared-route-first" ,
125 + summary:
"Fixed the shared route" ,
128 + expect (loaded.records[
0 ]?.
id ).
toMatch (
/ ^ gj-[0-9a-hjkmnp-tv-z] {10}$ / );
129 + expect (loaded.records[
0 ]?.
source ).
toMatchObject ({
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 (
120 - .
filter ((call)
=> call.
method === "notify" )
121 - .
map ((call)
=> call.args[
0 ])
?? [],
123 - value.
some ((message)
=> String (message).
includes (
"good-job learned" )),
125 - expect (notifications).
toEqual (
126 - expect.
arrayContaining ([
127 - expect.
stringContaining (
"good-job queued" ),
128 - expect.
stringContaining (
"good-job learned" ),
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 (
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 }],
155 + faux.
setResponses ([
156 + learning (
"Expanded scope without approval" ,
"scope-creep" ),
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 ({
167 + content:
"Implement only A" ,
168 + timestamp:
Date .
now (),
170 + manager.
appendMessage (
171 + fauxAssistantMessage (
"Implemented A and unrelated B." ),
174 + const result
= await withProcessEnv (t.env, ()
=> 178 + text:
"wtf you added unrelated B" ,
179 + source:
"interactive" ,
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 ,
191 + expect (loaded.records[
0 ]).
toMatchObject ({
193 + feedback:
"you added unrelated B" ,
194 + learning: { slug:
"scope-creep" },
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." ,
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 ({
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 (
169 - achievement:
"Used configured model" ,
170 - evidence: [
"Override handled the request" ],
171 - successful_behaviors: [
"Separated background analysis" ],
172 - candidate_rule:
"Configure background models explicitly." ,
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 }],
260 + faux.
setResponses ([
261 + learning (
"Private summary must not be embedded" ,
"private-learning" ),
262 + fauxAssistantMessage (
"Proposed changes." ),
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),
272 + const root
= goodJobDataDirectory (t.env,
process .
platform , t.env.HOME);
274 + ()
=> loadRecords (
layout (
root )),
275 + (value)
=> value.records.
length === 1 ,
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 ),
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" );
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 (
244 - evidence: [
"Session transition completed" ],
245 - successful_behaviors: [
"Recovered queued work" ],
246 - candidate_rule:
"Resume claimed work after session changes." ,
249 331 faux.
setResponses ([
250 332 async (_context, options)
=> {
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" ,
370 + expect (loaded.records[
0 ]?.learning.slug).
toBe (
"recovered-work" );
291 371 expect (
await counts (paths)).
toEqual ({
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 (),
307 - expect (result).
toEqual ({ action:
"continue" });
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" },
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" ;
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" ;
6 18 import { openDirectory, openerFor }
from "../implementation.js" ;
24 + configuredDataDirectory,
15 28 goodJobDataDirectory,
20 35 }
from "../storage.js" ;
30 - function job (id
= "job-1" )
: GoodJobJob {
45 + function job (id
= "gj-0000000001" )
: GoodJobJob {
34 49 createdAt:
"2026-01-01T00:00:00.000Z" ,
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" );
53 70 createdAt: source.createdAt,
54 71 completedAt:
"2026-01-01T00:01:00.000Z" ,
55 - praise: source.praise,
73 + feedback: source.feedback,
56 74 source: source.
source ,
57 75 analysisModel: source.analysisModel,
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." ,
94 + function legacyRecord () {
97 + id:
"b0b916cf-20ec-4f50-80f5-0cb83fbbd3c3" ,
98 + createdAt:
"2026-01-01T00:00:00.000Z" ,
99 + completedAt:
"2026-01-01T00:01:00.000Z" ,
103 + sessionPath:
"/sessions/one.jsonl" ,
104 + sessionId:
"session-1" ,
105 + sessionName:
"Shared route" ,
107 + agentModel: { provider:
"provider" , id:
"worker" },
109 + analysisModel: { provider:
"provider" , id:
"worker" },
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" , ()
=> {
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" ,
150 + expect (
configuredDataDirectory (
".pi/gj" ,
"/repo" ,
"/home/o" )).
toBe (
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 ();
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 = {
169 + id:
"wtf-0000000002" ,
173 + importer:
"wtf-v1" ,
174 + fingerprint:
"abc123" ,
175 + importedAt:
"2026-01-02T00:00:00.000Z" ,
177 + analysisModel:
null ,
180 + expect (
parseRecord (imported)).
toEqual (imported);
109 183 it (
"claims jobs atomically and commits immutable records" ,
async ()
=> {
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 ([
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 ({
249 + slug:
"fixed-the-shared-route" ,
250 + summary:
"Fixed the shared route" ,
253 + expect (
await migrateStore (source, target)).
toEqual ({
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 ({
277 + expect ((
await loadRecords (paths)).records).
toEqual ([existing]);
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
= {
289 + learning: {
... original.learning, summary:
"Conflicting learning" },
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" ,
300 + expect (
readFileSync (targetFile,
"utf8" )).
toBe (originalBytes);
301 + expect (
existsSync (sourceFile)).
toBe (
true );
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 ({
317 + const diagnostic
= JSON .
parse (
318 + readFileSync (
join (
layout (target).failed,
"invalid.json" ),
"utf8" ),
320 + expect (diagnostic).
toMatchObject ({
323 + error:
"invalid processing claim name" ,
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 }` ,
338 + expect (
readFileSync (target,
"utf8" )).
toBe (originalBytes);
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 (
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 = {
11 - id:
"12345678-1234-1234-1234-123456789abc" ,
11 + id:
"gj-123456789a" ,
12 12 createdAt:
"2026-01-01T00:00:00.000Z" ,
13 13 completedAt:
"2026-01-01T00:01:00.000Z" ,
16 18 cwd:
"/work/shared-route" ,
17 19 sessionPath:
"/sessions/one.jsonl" ,
18 20 sessionId:
"session-1" ,
20 22 analysisModel : {
provider :
"openai" ,
id :
"worker" },
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." ,
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 = {
54 + id:
"wtf-123456789a" ,
56 + feedback:
"unexpected scope expansion" ,
59 + importer:
"legacy-wtf-v1" ,
60 + fingerprint:
"abc123" ,
61 + importedAt:
"2026-01-02T00:00:00.000Z" ,
63 + analysisModel:
null ,
67 + slug:
"avoid-scope-expansion" ,
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 ();
77 + fg : (_color
: string , text
: string )
=> text,
78 + bold : (text
: string )
=> text,
80 + const component
= new LearningListComponent (
83 + { pending:
0 , processing:
0 , failed:
0 , records:
1 },
87 + for (
const character
of "legacy-wtf" ) component.
handleInput (character);
88 + expect (component.
render (
80 ).
join (
"\n" )).
toContain (
"avoid-scope-expansion" );
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 ();
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 {
12 - export interface LearningSource {
15 + export interface SessionLearningSource {
14 18 sessionPath
: string | null ;
18 22 agentModel : ModelRef
| null ;
25 + export interface ImportedLearningSource {
28 + fingerprint
: string ;
32 + export type LearningSource = SessionLearningSource | ImportedLearningSource ;
21 34 export interface GoodJobJob {
22 35 version
: typeof JOB_VERSION;
26 - source
: LearningSource ;
40 + source
: SessionLearningSource ;
27 41 analysisModel
: ModelRef | null ;
30 44 export interface Learning {
31 - achievement
: string ;
32 47 evidence
: string [];
33 - successfulBehaviors
: string [];
48 + behaviors
: string [];
34 49 candidateRule
: string | null ;
52 + export interface TokenUsage {
57 + totalTokens
: number ;
37 61 export interface GoodJobRecord {
38 62 version
: typeof RECORD_VERSION;
41 65 completedAt
: string ;
43 68 source
: LearningSource ;
44 - analysisModel
: ModelRef ;
69 + analysisModel
: ModelRef | null ;
45 70 learning
: Learning ;
51 - totalTokens
: number ;
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 (
93 + )
: { kind
: FeedbackKind ; feedback
: string }
| undefined {
94 + const trimmed
= text.
trim ();
95 + const problem
= WTF_TRIGGER.
exec (trimmed);
99 + feedback: problem[
1 ]?.
trim ()
|| "wtf" ,
101 + const praise
= GOOD_JOB_TRIGGER.
exec (trimmed);
105 + feedback: praise[
1 ]?.
trim ()
|| trimmed,
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 {
121 + .
replace (
/[\u0300-\u036f]/ g ,
"" )
123 + .
replace (
/[ ^ a-z0-9] + / g ,
"-" )
124 + .
replace (
/ ^ - +| - +$ / g ,
"" )
129 + return slug.
slice (
0 , MAX_SLUG_CHARS).
replace (
/- +$ / g ,
"" )
|| "learning" ;
132 + function encodeCrockford (bytes
: Uint8Array )
: string {
134 + for (
const byte
of bytes) value
= (value
<< 8 n )
| BigInt (byte);
135 + value
&= (
1 n << 50 n )
- 1 n ;
137 + for (
let index
= 0 ; index
< 10 ; index
++ ) {
138 + encoded
= CROCKFORD[
Number (value
& 31 n )]
+ encoded;
144 + export function feedbackId (
145 + kind
: FeedbackKind ,
146 + bytes
: Uint8Array = randomBytes (
7 ),
148 + return `${kind === "praise" ? "gj" : "wtf"}-${ encodeCrockford (bytes)}` ;
151 + export function feedbackIdFromSeed (kind
: FeedbackKind , seed
: string )
: string {
154 + createHash (
"sha256" ).
update (seed).
digest ().
subarray (
0 ,
7 ),
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)
189 + typeof value.
summary === "string" 190 + ? cleanText (value.
summary , MAX_SUMMARY_CHARS)
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,
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)
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 {
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 {
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. 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" ;
9 9 type ExtensionContext,
17 19 type GoodJobRecord,
31 + configuredDataDirectory,
33 36 goodJobDataDirectory,
38 42 } from
"./storage.js" ;
51 55 type Opener = { command
: string ; args
: string [] };
52 56 type GoodJobSettings = {
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 >;
77 + ctx
: ExtensionContext ,
70 79 runCommand (args
: string , ctx
: ExtensionContext )
: Promise <
void >;
113 122 "goodJob.thinkingLevel must be minimal, low, medium, high, xhigh, or max" ,
125 + merged.directory
!== undefined && 126 + (
typeof merged.directory
!== "string" || ! merged.directory.
trim ())
128 + throw new Error (
"goodJob.directory must be a non-empty path" );
131 + typeof merged.directory
=== "string" 132 + ? merged.directory.
trim ()
117 135 typeof merged.model
=== "string" && merged.model.
trim ()
118 136 ? merged.model.
trim ()
126 144 messages : readonly unknown[],
127 145 ): GoodJobJob[
"source" ] {
130 149 sessionPath: ctx.sessionManager.
getSessionFile ()
?? null ,
131 150 sessionId: ctx.sessionManager.
getSessionId (),
138 157 function completionContext (
139 158 conversation
: readonly Message [],
159 + kind
: FeedbackKind ,
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 );
267 + private readonly pi: ExtensionAPI,
268 + private readonly fixedRoot
?: string,
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);
291 + jobs: targetMigration.jobs
+ defaultMigration.jobs,
292 + records: targetMigration.records
+ defaultMigration.records,
293 + failures: targetMigration.failures
+ defaultMigration.failures,
294 + active: targetMigration.active
+ defaultMigration.active,
296 + if (migrated.jobs
|| migrated.records
|| migrated.failures)
297 + background.ui?.
notify (
298 + `gj migrated · ${migrated.records} records · ${migrated.jobs} queued · ${migrated.failures} failed` ,
301 + if (migrated.active)
302 + background.ui?.
notify (
303 + `gj left ${migrated.active} active processing claim${migrated.active === 1 ? "" : "s"} in the old store` ,
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> {
329 + kind: FeedbackKind,
331 + ctx: ExtensionContext,
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,
342 + id:
feedbackId (kind),
283 343 createdAt:
new Date ().
toISOString (),
284 - praise: praise.
trim (),
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);
302 - if (command === "show") {
303 - await this.show(id, ctx);
306 363 if (command === "status") {
307 364 await this.status(ctx);
311 368 await this.
open (ctx);
314 - ctx.ui.
notify (
"Usage: /good-job [list|show <id>|status|open]" ,
"warning" );
371 + if (command
=== "learn" ) {
372 + await this.
learn (ctx);
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),
320 384 this.settingsCwd
= cwd;
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,
435 499 createdAt : job.createdAt,
436 500 completedAt :
new Date ().
toISOString (),
437 - praise : job.praise,
502 + feedback : job.feedback,
438 503 source : job.
source ,
439 504 analysisModel : job.analysisModel,
450 515 await commitRecord (record, claimPath, this.paths);
451 516 this.snapshots.
delete (job.
id );
453 - `good-job learned · ${record.learning.achievement}` ,
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> {
528 - ctx.ui.
notify (
"Usage: /good-job show <id>" ,
"warning" );
531 - const loaded
= await loadRecords (this.paths);
532 - const matches
= loaded.records.
filter ((record)
=> record.
id .
startsWith (id));
533 - if (matches.length !== 1) {
535 - matches.
length === 0 536 - ? `Unknown good-job id: ${id}` 537 - : `Ambiguous good-job id: ${id}` ,
542 - await
showLearningDetail (ctx, matches[
0 ] as GoodJobRecord);
545 588 private async
status (ctx: ExtensionContext):
Promise <void> {
546 589 const state
= await counts (this.paths);
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" );
610 + this.pi.sendUserMessage(
learningPrompt (this.paths.records), {
611 + deliverAs: ctx.
isIdle ()
? undefined : "followUp" ,
561 615 private async
open (ctx: ExtensionContext):
Promise <void> {
562 616 await
ensureLayout (this.paths);
573 627 export function createGoodJobRuntime (
574 - root
= goodJobDataDirectory (),
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 ;
38 39 await sessionReady;
39 - await (
await getRuntime ()).
capture (
event .
text , ctx);
40 + await (
await getRuntime ()).
capture (feedback.kind, feedback.feedback, ctx);
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)
57 - `good-job startup failed: ${ boundedError (error)}` ,
56 + ui?.
notify (
`gj startup failed: ${ boundedError (error)}` ,
"error" );
extensions/good-job/package.json Modified 5 5 "name" :
"@bugabinga/pi-ext-good-job" ,
10 - "description" :
"Turn explicit praise into durable coding-agent learnings." ,
10 + "description" :
"Turn explicit gj and wtf feedback into durable coding-agent learnings." ,
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" ;
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" ;
18 + ImportedLearningSource,
21 + SessionLearningSource,
11 23 }
from "./core.js" ;
17 31 }
from "./core.js" ;
58 + export interface MigrationResult {
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 ,
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 {
113 - export async function atomicWriteJson (
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 (
132 162 await file.
close ();
166 + export async function atomicWriteJson (
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 });
180 + export async function atomicCreateJson (
184 + const temporary
= await temporaryJson (target, value);
186 + await link (temporary, target);
187 + await rm (temporary, { force:
true });
188 + await syncDirectory (
dirname (target));
190 + await rm (temporary, { force:
true });
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 {
144 201 isObject (value)
&& 152 - function source (value
: unknown )
: value
is LearningSource {
209 + function sessionSource (value
: unknown )
: value
is SessionLearningSource {
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 {
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" 234 + function source (value
: unknown )
: value
is LearningSource {
235 + return sessionSource (value)
|| importedSource (value);
238 + function legacySource (
240 + )
: Omit <
SessionLearningSource ,
"type" >
| undefined {
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))
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 {
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" ;
287 + typeof value
=== "string" && 288 + new RegExp (
`^${prefix}-[0-9a-hjkmnp-tv-z]{10}$` ).
test (value)
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)
|| 326 + value.learning.candidateRule
=== null || 327 + typeof value.learning.candidateRule
=== "string" 329 + ! (value.usage
=== null || recordUsage (value.usage))
332 + return value
as unknown as GoodJobRecord ;
335 + function migrateLegacyJob (value
: unknown )
: GoodJobJob | undefined {
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))
345 + const oldSource
= legacySource (value.
source );
346 + if (
! oldSource)
return undefined ;
348 + version: JOB_VERSION,
349 + id:
feedbackIdFromSeed (
"praise" ,
`good-job-v1:${value. id }` ),
350 + createdAt: value.createdAt,
352 + feedback: value.praise,
353 + source: { type:
"session" ,
... oldSource },
354 + analysisModel: value.analysisModel,
358 + function migrateLegacyRecord (value
: unknown )
: GoodJobRecord | undefined {
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 ;
382 + version: RECORD_VERSION,
383 + id:
feedbackIdFromSeed (
"praise" ,
`good-job-v1:${value. id }` ),
384 + createdAt: value.createdAt,
385 + completedAt: value.completedAt,
387 + feedback: value.praise,
388 + source: { type:
"session" ,
... oldSource },
389 + analysisModel: value.analysisModel,
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,
397 + usage: value.usage,
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 > {
407 + const file
= await open (path,
"r" );
408 + await file.
close ();
411 + if (
isNodeError (error)
&& error.
code === "ENOENT" )
return false ;
416 + async function moveValue (
417 + sourcePath
: string ,
418 + targetPath
: string ,
421 + if (sourcePath
=== targetPath) {
422 + await atomicWriteJson (targetPath, value);
426 + await atomicCreateJson (targetPath, value);
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 ,
439 + )
: Promise <
number > {
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);
455 + async function migrateRecords (
456 + from
: GoodJobLayout ,
458 + )
: Promise <
number > {
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);
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);
475 + async function migrateFailures (
476 + from
: GoodJobLayout ,
478 + )
: Promise <
number > {
480 + for (
const file
of await jsonFiles (from.failed)) {
481 + const sourcePath
= join (from.failed, file);
482 + const value
= await readJson (sourcePath);
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);
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,
503 + failedAt: value.failedAt,
504 + error: value.error,
506 + const targetPath
= join (to.failed,
`${job. id }.json` );
507 + if (sourcePath
!== targetPath
|| ! parseJob (value.job)) {
508 + await moveValue (sourcePath, targetPath, failure);
515 + async function sameDirectory (left
: string , right
: string )
: Promise <
boolean > {
516 + if (
resolve (left)
=== resolve (right))
return true ;
518 + return (
await realpath (left))
=== (
await realpath (right));
520 + if (
isNodeError (error)
&& error.
code === "ENOENT" )
return false ;
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),
546 + active: (
await jsonFiles (from.processing)).
length ,
237 550 export async function enqueueJob (
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` ;
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 }` );
565 + await atomicCreateJson (
join (paths.pending, file), job);
567 + if (
isNodeError (error)
&& error.
code === "EEXIST" )
568 + throw new Error (
`duplicate gj id ${job. id }` );
246 573 export async function claimJob (
277 604 failedAt :
new Date ().
toISOString (),
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 > {
337 - const file
= await open (path,
"r" );
338 - await file.
close ();
341 - if (
isNodeError (error)
&& error.
code === "ENOENT" )
return false ;
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" );
670 + await atomicCreateJson (
join (paths.records,
`${record. id }.json` ), record);
672 + if (
isNodeError (error)
&& error.
code === "EEXIST" )
673 + throw new Error (
`duplicate gj id ${record. id }` );
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);
692 + await atomicCreateJson (
join (paths.failed,
`${job. id }.json` ), failure);
694 + if (
isNodeError (error)
&& error.
code === "EEXIST" )
695 + throw new Error (
`duplicate gj id ${job. id }` );
370 698 await rm (claimPath, { force:
true });
374 702 paths : GoodJobLayout,
375 703 ):
Promise < LoadedRecords
> {
376 704 const files
= await jsonFiles (paths.records);
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)}` )
48 - const behaviors
= record.learning.successfulBehaviors
49 + const behaviors
= record.learning.behaviors
49 50 .
map ((item)
=> `- ${ markdownText (item)}` )
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" ;
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" ;
59 - markdownText (record.learning.achievement),
62 + `## ${ markdownText (record.learning.slug)}` ,
63 + markdownText (record.learning.
summary ),
66 + markdownText (record.feedback),
64 - "## Successful behaviors" ,
67 74 "## Candidate 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)}*` ,
79 86 if (words.
length === 0 )
return [
... records];
80 87 return records.
filter ((record)
=> {
82 - record.learning.achievement,
90 + record.learning.slug,
92 + record.learning.
summary ,
83 93 record.learning.candidateRule
?? "" ,
84 - ... record.learning.successfulBehaviors,
94 + ... record.learning.behaviors,
85 95 projectLabel (record),
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)}` ;
176 - selected
? this.theme.
fg (
"accent" , achievement)
: achievement,
186 + selected
? this.theme.
fg (
"accent" , summary)
: summary,
179 - ` ${ dateLabel (record.completedAt)} · ${ projectLabel (record)} · ${record. id . slice (0, 8)}` ,
189 + ` ${record. id } · ${ dateLabel (record.completedAt)} · ${ projectLabel (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 )}` ,
256 266 new DynamicBorder ((text
: string )
=> theme.
fg (
"accent" , text));
257 267 container.
addChild (
border ());
258 268 container.
addChild (
260 - `${theme. fg ("success", "✓")} ${theme. fg ("accent", theme. bold ("GOOD JOB"))}` ,
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 ));