repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

refactor(good-job): analyze feedback in child sessions

d7e094ec4449d7abcf4a23420124d8e19d8b3b97

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (8)

extensions/AGENTS.md

Modified
86 86 ## Model calls
88 -Nested model calls must use `ctx.modelRegistry`, never Pi AI compatibility dispatchers, so extension-registered providers work.
88 +Prefer a parent-linked child `AgentSession` over `ctx.modelRegistry.complete()` for nested model work so Pi session tracking records it.
89 +When a direct model call is necessary, use `ctx.modelRegistry`, never Pi AI compatibility dispatchers, so extension-registered providers work.
90 91 ## Imports

extensions/good-job/README.md

Modified
15 15 - `/gj open` opens the persistence directory.
16 16 - `/gj learn` sends the active agent the records-directory path and asks for cited Pi change proposals.
18 -There are no tools.
18 +There are no user-facing tools.
19 +Background analysis exposes only an internal schema-constrained `submit_learning` tool to its child session.
19 20 By default, analysis uses the current session model and platform app-data directory.
20 21 Set optional overrides in global or project `settings.json`:

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

Modified
1 1 import path from "node:path";
2 -import { fauxAssistantMessage, fauxProvider } from "@earendil-works/pi-ai";
2 +import {
3 + fauxAssistantMessage,
4 + fauxProvider,
5 + fauxToolCall,
6 + getCurrentTools,
7 +} from "@earendil-works/pi-ai";
3 8 import { SettingsManager } from "@earendil-works/pi-coding-agent";
4 9 import { afterEach, describe, expect, it, vi } from "vitest";
5 10 import {
34 39 function learning(summary: string, slug = "shared-route-first") {
35 40 return fauxAssistantMessage(
36 - JSON.stringify({
41 + fauxToolCall("submit_learning", {
37 42 slug,
38 43 summary,
39 44 evidence: ["Focused tests passed"],
40 45 behaviors: ["Inspected callers before editing"],
41 46 candidate_rule: "Fix shared routes before leaf callers.",
48 + { stopReason: "toolUse" },
46 52 describe("good-job pi-test-harness", () => {
47 53 let t: TestSession | undefined;
49 - afterEach(() => {
50 - t?.dispose();
51 - t = undefined;
52 - vi.restoreAllMocks();
55 + afterEach(async () => {
56 + try {
57 + await t?.session.extensionRunner.emit({
58 + type: "session_shutdown",
59 + reason: "quit",
60 + });
61 + } finally {
62 + t?.dispose();
63 + t = undefined;
64 + vi.restoreAllMocks();
65 + }
55 68 it("registers only /gj with list-driven commands and no prompt or tools", async () => {
83 96 models: [{ id: "worker", maxTokens: 4_096 }],
85 98 faux.setResponses([learning("Fixed the shared route")]);
86 - const stream = vi.spyOn(faux.provider, "stream");
99 + const stream = vi.spyOn(faux.provider, "streamSimple");
87 100 base.modelRegistry.registerProvider(faux.provider);
88 101 const model = base.modelRegistry.find("good-job-test", "worker");
89 102 if (!model) throw new Error("missing faux model");
135 148 "Implemented and tested the shared fix.",
137 150 expect(JSON.stringify(sentMessages.at(-1))).toContain("kebab-case");
151 + expect(getCurrentTools(sentMessages).map(({ name }) => name)).toEqual([
152 + "submit_learning",
153 + ]);
139 155 await withProcessEnv(t.env, () =>
140 156 extension.commands.get("gj").handler("status", ctx as never),
142 158 expect(t.events.ui.at(-1)?.args[0]).toContain("1 learnings");
161 + it("rejects analysis that does not submit structured learning", async () => {
162 + t = await createTestSession({ extensions: [extensionPath()] });
163 + const runner = t.session.extensionRunner;
164 + const extension = runner.extensions[0];
165 + const input = extension.handlers.get("input")[0];
166 + const base = runner.createContext();
167 + const faux = fauxProvider({
168 + provider: "good-job-unstructured",
169 + models: [{ id: "worker", maxTokens: 4_096 }],
170 + });
171 + faux.setResponses([fauxAssistantMessage('{"summary":"not submitted"}')]);
172 + base.modelRegistry.registerProvider(faux.provider);
173 + const model = base.modelRegistry.find("good-job-unstructured", "worker");
174 + if (!model) throw new Error("missing unstructured faux model");
175 + const ctx = Object.create(base) as typeof base;
176 + Object.defineProperty(ctx, "model", { value: model });
178 + await withProcessEnv(t.env, () =>
179 + input({ type: "input", text: "gj", source: "interactive" }, ctx),
180 + );
182 + const paths = layout(
183 + goodJobDataDirectory(t.env, process.platform, t.env.HOME),
184 + );
185 + await eventually(
186 + () => counts(paths),
187 + (value) => value.failed === 1,
188 + );
189 + expect(await counts(paths)).toEqual({
190 + pending: 0,
191 + processing: 0,
192 + failed: 1,
193 + records: 0,
194 + });
195 + expect(
196 + t.events.ui
197 + .filter((call) => call.method === "notify")
198 + .map((call) => String(call.args[0]))
199 + .find((message) => message.includes("good-job failed")),
200 + ).toContain("without calling submit_learning");
201 + });
145 203 it("records first-word wtf feedback while passing it unchanged", async () => {
146 204 t = await createTestSession({ extensions: [extensionPath()] });
147 205 const runner = t.session.extensionRunner;
155 213 faux.setResponses([
156 214 learning("Expanded scope without approval", "scope-creep"),
158 - const stream = vi.spyOn(faux.provider, "stream");
216 + const stream = vi.spyOn(faux.provider, "streamSimple");
159 217 base.modelRegistry.registerProvider(faux.provider);
160 218 const model = base.modelRegistry.find("wtf-test", "worker");
161 219 if (!model) throw new Error("missing wtf faux model");
218 276 const faux = fauxProvider({
219 277 provider: "good-job-override",
220 278 models: [
221 - { id: "active", maxTokens: 4_096 },
222 - { id: "background", maxTokens: 4_096 },
280 + id: "active",
281 + maxTokens: 4_096,
282 + reasoning: true,
283 + thinkingLevelMap: { xhigh: "xhigh" },
284 + },
286 + id: "background",
287 + maxTokens: 4_096,
288 + reasoning: true,
289 + thinkingLevelMap: { xhigh: "xhigh" },
290 + },
225 293 faux.setResponses([learning("Used configured model", "configured-model")]);
226 - const stream = vi.spyOn(faux.provider, "stream");
294 + Object.assign(faux.getModel("active"), {
295 + thinkingLevelMap: { xhigh: "xhigh" },
296 + });
297 + Object.assign(faux.getModel("background"), {
298 + thinkingLevelMap: { xhigh: "xhigh" },
299 + });
300 + const stream = vi.spyOn(faux.provider, "streamSimple");
227 301 base.modelRegistry.registerProvider(faux.provider);
228 302 const active = base.modelRegistry.find("good-job-override", "active");
229 303 if (!active) throw new Error("missing active faux model");

extensions/good-job/core.ts

Modified
1 1 import { createHash, randomBytes } from "node:crypto";
2 -import type { AssistantMessage } from "@earendil-works/pi-ai";
2 +import { Type } from "typebox";
4 4 export const JOB_VERSION = 2 as const;
5 5 export const RECORD_VERSION = 2 as const;
88 88 const MAX_ITEMS = 8;
89 89 const MAX_SLUG_CHARS = 48;
91 +export const LearningSubmissionSchema = Type.Object(
92 + {
93 + slug: Type.String({
94 + maxLength: MAX_SLUG_CHARS,
95 + pattern: "^[a-z0-9]+(?:-[a-z0-9]+){1,5}$",
96 + description: "Memorable kebab-case label using 2-6 short words.",
97 + }),
98 + summary: Type.String({
99 + minLength: 1,
100 + maxLength: MAX_SUMMARY_CHARS,
101 + description: "One concrete summary.",
102 + }),
103 + evidence: Type.Array(
104 + Type.String({ minLength: 1, maxLength: MAX_ITEM_CHARS }),
106 + minItems: 1,
107 + maxItems: MAX_ITEMS,
108 + description: "Observable transcript facts or user-visible outcomes.",
109 + },
110 + ),
111 + behaviors: Type.Array(
112 + Type.String({ minLength: 1, maxLength: MAX_ITEM_CHARS }),
114 + minItems: 1,
115 + maxItems: MAX_ITEMS,
116 + description:
117 + "Specific agent behaviors that succeeded, failed, or should change.",
118 + },
119 + ),
120 + candidate_rule: Type.Union(
121 + [Type.String({ minLength: 1, maxLength: MAX_RULE_CHARS }), Type.Null()],
123 + description:
124 + "Concise reusable instruction, or null when evidence is insufficient.",
125 + },
126 + ),
127 + },
128 + { additionalProperties: false },
91 131 export function feedbackTrigger(
92 132 text: string,
93 133 ): { kind: FeedbackKind; feedback: string } | undefined {
209 249 return { slug, summary, evidence, behaviors, candidateRule };
212 -export function responseText(response: AssistantMessage): string {
213 - return response.content
214 - .filter(
215 - (part): part is { type: "text"; text: string } => part.type === "text",
216 - )
217 - .map((part) => part.text)
218 - .join("\n");
221 252 export function analysisPrompt(kind: FeedbackKind, feedback: string): string {
222 253 const task =
223 254 kind === "praise"
230 261 Infer causes only when supported by the transcript.
231 262 Focus on reusable agent behavior, not compliments, blame, or personality.
232 263 Do not reproduce credentials, secrets, long source excerpts, or private data.
233 -Return exactly one JSON object with these fields:
264 +Call submit_learning exactly once with these fields:
234 265 - slug: memorable kebab-case label using 2-6 short words
235 266 - summary: one concrete summary, at most 180 characters
236 267 - evidence: 1-8 observable transcript facts or user-visible outcomes
237 268 - behaviors: 1-8 specific agent behaviors that succeeded, failed, or should change
238 269 - candidate_rule: concise reusable instruction, or null when evidence is insufficient
239 -No markdown fences or commentary.`;
270 +Output no prose.`;
242 273 export function lastAgentModel(messages: readonly unknown[]): ModelRef | null {

extensions/good-job/implementation.ts

Modified
1 1 import { spawn } from "node:child_process";
2 2 import { accessSync, constants, existsSync } from "node:fs";
3 -import { basename, delimiter, join } from "node:path";
4 -import type { Message, ThinkingLevel } from "@earendil-works/pi-ai";
3 +import { basename, delimiter, dirname, join } from "node:path";
4 +import type {
5 + AssistantMessage,
6 + Model,
7 + ThinkingLevel,
8 +} from "@earendil-works/pi-ai";
5 9 import {
6 10 buildSessionContext,
7 - convertToLlm,
11 + createAgentSession,
12 + createEventBus,
13 + DefaultResourceLoader,
14 + defineTool,
8 15 type ExtensionAPI,
9 16 type ExtensionContext,
17 + type FileEntry,
18 + getAgentDir,
19 + ModelRuntime,
20 + type SessionEntry,
10 21 SessionManager,
11 22 SettingsManager,
12 23 } from "@earendil-works/pi-coding-agent";
18 29 type GoodJobJob,
19 30 type GoodJobRecord,
20 31 JOB_VERSION,
32 + type Learning,
33 + LearningSubmissionSchema,
21 34 lastAgentModel,
22 35 type ModelRef,
23 36 parseLearning,
24 37 RECORD_VERSION,
25 - responseText,
26 38 } from "./core.js";
27 39 import {
28 40 claimJob,
46 58 const SPINNER = ["◐", "◓", "◑", "◒"] as const;
47 59 const MAX_TOKENS = 1_200;
49 -type ContextSnapshot = Message[];
50 61 type BackgroundContext = {
51 62 modelRegistry: ExtensionContext["modelRegistry"];
52 63 ui?: ExtensionContext["ui"];
157 -function completionContext(
158 - conversation: readonly Message[],
159 - kind: FeedbackKind,
160 - feedback: string,
161 -): Message[] {
162 - return [
163 - ...conversation,
164 - {
165 - role: "user",
166 - content: [{ type: "text", text: analysisPrompt(kind, feedback) }],
167 - timestamp: Date.now(),
168 - },
169 - ];
172 -function contextFromSession(job: GoodJobJob): ContextSnapshot {
173 - if (!job.source.sessionPath)
174 - throw new Error("source session was ephemeral and is no longer available");
175 - const manager = SessionManager.open(job.source.sessionPath);
176 - if (job.source.leafId && !manager.getEntry(job.source.leafId))
177 - throw new Error(`source session leaf ${job.source.leafId} is missing`);
178 - const context = buildSessionContext(
179 - manager.getEntries(),
180 - job.source.leafId,
181 - ).messages;
182 - return convertToLlm(context);
185 168 function findExecutable(
186 169 name: string,
187 170 env: NodeJS.ProcessEnv,
198 181 return undefined;
184 +function copyRegisteredProviders(
185 + registry: ExtensionContext["modelRegistry"],
186 + runtime: ModelRuntime,
187 +): void {
188 + for (const providerId of registry.getRegisteredProviderIds()) {
189 + const native = registry.getRegisteredNativeProvider(providerId);
190 + if (native) {
191 + runtime.registerNativeProvider(native);
192 + continue;
194 + const config = registry.getRegisteredProviderConfig(providerId);
195 + if (config) runtime.registerProvider(providerId, config);
201 199 export function openerFor(
202 200 platform = process.platform,
203 201 env: NodeJS.ProcessEnv = process.env,
252 250 private activeController: AbortController | undefined;
253 251 private pumpPromise: Promise<void> | undefined;
254 252 private pumpRequested = false;
255 - private readonly snapshots = new Map<string, ContextSnapshot>();
253 + private readonly snapshots = new Map<string, SessionEntry[]>();
256 254 private spinnerTimer: ReturnType<typeof setInterval> | undefined;
257 255 private spinnerStartedAt = 0;
258 256 private spinnerCount = 0;
336 334 ctx.sessionManager.getEntries(),
337 335 ctx.sessionManager.getLeafId(),
339 - const snapshot = convertToLlm(sessionContext.messages);
340 337 const job: GoodJobJob = {
341 338 version: JOB_VERSION,
342 339 id: feedbackId(kind),
349 346 await ensureLayout(this.paths);
350 347 await enqueueJob(job, this.paths);
351 - this.snapshots.set(job.id, snapshot);
348 + this.snapshots.set(
349 + job.id,
350 + structuredClone(ctx.sessionManager.getEntries()),
351 + );
352 352 background.ui?.notify(`${job.id} queued`, "info");
353 353 void this.pump(background, this.generation, job.id);
470 470 throw new Error(
471 471 `analysis model ${job.analysisModel.provider}/${job.analysisModel.id} is unavailable`,
473 - const snapshot = this.snapshots.get(job.id) ?? contextFromSession(job);
474 - const response = await ctx.modelRegistry.complete(
473 + const { learning, response } = await this.runChildAnalysis(
474 + job,
475 475 model,
476 - {
477 - systemPrompt:
478 - "Extract evidence-backed, reusable lessons from explicit user feedback about coding-agent work.",
479 - messages: completionContext(snapshot, job.kind, job.feedback),
480 - },
481 - {
482 - maxTokens: MAX_TOKENS,
483 - reasoning: this.settings.thinkingLevel,
484 - cacheRetention: "none",
485 - sessionId: job.id,
486 - signal: controller.signal,
487 - },
476 + ctx,
477 + controller.signal,
489 479 if (controller.signal.aborted || generation !== this.generation) return;
490 - if (response.stopReason !== "stop")
491 - throw new Error(
492 - response.errorMessage ||
493 - `analysis stopped with ${response.stopReason}`,
494 - );
495 - const learning = parseLearning(responseText(response));
496 480 const record: GoodJobRecord = {
497 481 version: RECORD_VERSION,
498 482 id: job.id,
518 + private async runChildAnalysis(
519 + job: GoodJobJob,
520 + model: Model<any>,
521 + ctx: BackgroundContext,
522 + signal: AbortSignal,
523 + ): Promise<{ learning: Learning; response: AssistantMessage }> {
524 + const sourcePath = job.source.sessionPath;
525 + let manager: SessionManager;
526 + if (sourcePath) {
527 + manager = SessionManager.forkFrom(
528 + sourcePath,
529 + job.source.cwd,
530 + dirname(sourcePath),
531 + { parentSession: sourcePath },
532 + );
533 + } else {
534 + const snapshot = this.snapshots.get(job.id);
535 + if (!snapshot)
536 + throw new Error(
537 + "source session was ephemeral and its snapshot is unavailable",
538 + );
539 + const header: FileEntry = {
540 + type: "session",
541 + version: 3,
542 + id: job.source.sessionId,
543 + timestamp: job.createdAt,
544 + cwd: job.source.cwd,
545 + };
546 + manager = SessionManager.inMemory(job.source.cwd, undefined, [
547 + header,
548 + ...snapshot,
549 + ]);
551 + if (job.source.leafId) {
552 + if (!manager.getEntry(job.source.leafId))
553 + throw new Error(`source session leaf ${job.source.leafId} is missing`);
554 + manager.branch(job.source.leafId);
556 + manager.appendSessionInfo(`good-job · ${job.id}`);
558 + const agentDir = getAgentDir();
559 + const childRuntime = await ModelRuntime.create({
560 + authPath: join(agentDir, "auth.json"),
561 + modelsPath: join(agentDir, "models.json"),
562 + refreshOnCreate: false,
563 + signal,
564 + });
565 + copyRegisteredProviders(ctx.modelRegistry, childRuntime);
567 + const settingsManager = SettingsManager.create(job.source.cwd, agentDir);
568 + const resourceLoader = new DefaultResourceLoader({
569 + cwd: job.source.cwd,
570 + agentDir,
571 + settingsManager,
572 + eventBus: createEventBus(),
573 + noExtensions: true,
574 + noSkills: true,
575 + noPromptTemplates: true,
576 + noThemes: true,
577 + noContextFiles: true,
578 + });
579 + await resourceLoader.reload();
580 + signal.throwIfAborted();
582 + const childModel = {
583 + ...model,
584 + maxTokens:
585 + model.maxTokens > 0
586 + ? Math.min(model.maxTokens, MAX_TOKENS)
587 + : MAX_TOKENS,
588 + };
589 + let learning: Learning | undefined;
590 + let duplicateSubmission = false;
591 + const submitLearningTool = defineTool<
592 + typeof LearningSubmissionSchema,
593 + Learning
594 + >({
595 + name: "submit_learning",
596 + label: "Submit Learning",
597 + description: "Submit the final structured learning and finish analysis.",
598 + parameters: LearningSubmissionSchema,
599 + constrainedSampling: { type: "json_schema", strict: "prefer" },
600 + async execute(_toolCallId, params) {
601 + if (learning) {
602 + duplicateSubmission = true;
603 + throw new Error("submit_learning may be called exactly once");
605 + const parsed = parseLearning(JSON.stringify(params));
606 + learning = parsed;
607 + return {
608 + content: [{ type: "text", text: "Learning submitted." }],
609 + details: parsed,
610 + terminate: true,
611 + };
612 + },
613 + });
614 + let child:
615 + | Awaited<ReturnType<typeof createAgentSession>>["session"]
616 + | undefined;
617 + try {
618 + const created = await createAgentSession({
619 + cwd: job.source.cwd,
620 + agentDir,
621 + model: childModel,
622 + thinkingLevel: this.settings.thinkingLevel,
623 + modelRuntime: childRuntime,
624 + resourceLoader,
625 + settingsManager,
626 + sessionManager: manager,
627 + tools: [submitLearningTool.name],
628 + customTools: [submitLearningTool],
629 + });
630 + child = created.session;
631 + const abortChild = () => void child?.abort();
632 + signal.addEventListener("abort", abortChild, { once: true });
633 + try {
634 + await child.prompt(analysisPrompt(job.kind, job.feedback), {
635 + expandPromptTemplates: false,
636 + source: "extension",
637 + });
638 + } finally {
639 + signal.removeEventListener("abort", abortChild);
641 + signal.throwIfAborted();
642 + const finalAssistant = [...child.messages]
643 + .reverse()
644 + .find(
645 + (message): message is AssistantMessage =>
646 + message.role === "assistant",
647 + );
648 + if (!finalAssistant)
649 + throw new Error(
650 + "child analysis finished without an assistant response",
651 + );
652 + if (duplicateSubmission)
653 + throw new Error("analysis called submit_learning more than once");
654 + if (!learning)
655 + throw new Error(
656 + finalAssistant.errorMessage ||
657 + "analysis finished without calling submit_learning",
658 + );
659 + return { learning, response: finalAssistant };
660 + } finally {
661 + if (child) {
662 + if (!child.isIdle) await child.abort();
663 + child.dispose();
534 668 private startSpinner(ctx: BackgroundContext, count: number): void {
535 669 const { ui } = ctx;
536 670 this.stopSpinner(ui);

extensions/good-job/index.ts

Modified
9 9 let runtime: Promise<GoodJobRuntime> | undefined;
10 10 let generation = 0;
11 11 let sessionReady: Promise<void> = Promise.resolve();
12 + let startupTimer: ReturnType<typeof setTimeout> | undefined;
12 13 const getRuntime = () =>
13 14 (runtime ??= import("./implementation.js").then(
14 15 ({ createGoodJobRuntime }) => createGoodJobRuntime(pi),
25 26 return matches.length ? matches : null;
27 28 async handler(args, ctx) {
28 - await sessionReady;
29 + await ensureStarted(ctx);
29 30 await (await getRuntime()).runCommand(args, ctx);
36 37 if (!feedback) return { action: "continue" };
37 38 const ui = ctx.hasUI ? ctx.ui : undefined;
38 39 try {
39 - await sessionReady;
40 + await ensureStarted(ctx);
40 41 await (await getRuntime()).capture(feedback.kind, feedback.feedback, ctx);
41 42 } catch (error) {
42 43 ui?.notify(`gj could not queue: ${boundedError(error)}`, "error");
44 45 return { action: "continue" };
47 - pi.on("session_start", (_event, ctx) => {
48 - const currentGeneration = ++generation;
48 + const startRuntime = (
49 + ctx: Parameters<GoodJobRuntime["start"]>[0],
50 + expectedGeneration = generation,
51 + ) => {
52 + const currentGeneration = expectedGeneration;
53 + if (generation !== currentGeneration) return Promise.resolve();
49 54 const ui = ctx.hasUI ? ctx.ui : undefined;
50 55 sessionReady = getRuntime()
51 56 .then((loaded) => {
55 60 if (generation === currentGeneration)
56 61 ui?.notify(`gj startup failed: ${boundedError(error)}`, "error");
63 + return sessionReady;
64 + };
66 + const ensureStarted = (ctx: Parameters<GoodJobRuntime["start"]>[0]) => {
67 + if (startupTimer) {
68 + clearTimeout(startupTimer);
69 + startupTimer = undefined;
70 + return startRuntime(ctx);
71 + }
72 + return sessionReady;
73 + };
75 + pi.on("session_start", (_event, ctx) => {
76 + const currentGeneration = ++generation;
77 + if (startupTimer) clearTimeout(startupTimer);
78 + startupTimer = setTimeout(() => {
79 + startupTimer = undefined;
80 + void startRuntime(ctx, currentGeneration);
81 + }, 50);
82 + startupTimer.unref?.();
60 85 pi.on("session_shutdown", async (_event, ctx) => {
61 86 generation++;
87 + if (startupTimer) {
88 + clearTimeout(startupTimer);
89 + startupTimer = undefined;
90 + }
62 91 await sessionReady;
63 92 const loaded = await runtime?.catch(() => undefined);
64 93 if (loaded) await loaded.stop(ctx);

extensions/good-job/package.json

Modified
12 12 "peerDependencies": {
13 13 "@earendil-works/pi-ai": "*",
14 14 "@earendil-works/pi-coding-agent": "*",
15 - "@earendil-works/pi-tui": "*"
15 + "@earendil-works/pi-tui": "*",
16 + "typebox": "*"
17 18 "devDependencies": {
18 19 "@marcfargas/pi-test-harness": "^0.6.1",

extensions/good-job/storage.ts

Modified
209 -function sessionSource(value: unknown): value is SessionLearningSource {
209 +function sessionSourceFields(
210 + value: unknown,
211 +): value is Omit<SessionLearningSource, "type"> {
210 212 return (
211 213 isObject(value) &&
212 - value.type === "session" &&
213 214 typeof value.cwd === "string" &&
214 215 (value.sessionPath === null || typeof value.sessionPath === "string") &&
215 216 typeof value.sessionId === "string" &&
223 +function sessionSource(value: unknown): value is SessionLearningSource {
224 + return (
225 + isObject(value) && value.type === "session" && sessionSourceFields(value)
226 + );
222 229 function importedSource(value: unknown): value is ImportedLearningSource {
223 230 return (
224 231 isObject(value) &&
238 245 function legacySource(
239 246 value: unknown,
240 247 ): 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))
249 - )
250 - return undefined;
251 - return value as unknown as Omit<SessionLearningSource, "type">;
248 + return sessionSourceFields(value)
249 + ? (value as Omit<SessionLearningSource, "type">)
250 + : undefined;
254 253 function stringArray(value: unknown): value is string[] {
281 280 return value === "praise" || value === "problem";
283 +const CURRENT_ID = /^(gj|wtf)-[0-9a-hjkmnp-tv-z]{10}$/;
284 285 function currentId(value: unknown, kind: GoodJobJob["kind"]): value is string {
285 286 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 - );
287 + return typeof value === "string" && CURRENT_ID.exec(value)?.[1] === prefix;
292 290 export function parseJob(value: unknown): GoodJobJob | undefined {