Skip to content

Commit 2365388

Browse files
feat(workflow): autonomous generate+judge+validate+report across 3 providers
scripts/gen_quality_workflow.js — a self-contained Workflow-tool script that: - phase 'Generate+Judge': runs all 3 providers (Bedrock Sonnet 4.6, MiniMax M2.7, Ollama gemma4) concurrently via parallel() so a stuck provider never blocks the others. Each runs an INSIDE-the-script judge loop: generate 5 cards/source for BOTH flashcards + quizzes → Opus-4.8 judge scores real content quality (schema-valid is the floor) → if approved break, else feed the judge's reasons back into the next round's prompt and regenerate. - Ceiling/abort rules so it cannot spin: max 4 quality rounds/provider; a generation ERROR (not a quality reject) gets 2 retries then FAILED with the error captured; every loop guarded by budget.remaining() > 100k. - Each provider writes to an isolated output course (Complete_SQL_Mastery__<key>) so concurrent runs + the judge + Playwright never clobber each other. - phase 'Validate': per-provider agent asserts /api/courses + /api/cards and drives Playwright MCP to confirm the panels render the decks. - phase 'Report': writes docs/handoffs/2026-06-01-gen-quality-workflow-report.md and the workflow returns structured results for the STEP-3 orchestrator. Bedrock model id corrected from the spec's invalid raw id (...-20251101-v1:0) to the working inference-profile id us.anthropic.claude-sonnet-4-6.
1 parent 26522c4 commit 2365388

1 file changed

Lines changed: 328 additions & 0 deletions

File tree

‎scripts/gen_quality_workflow.js‎

Lines changed: 328 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,328 @@
1+
export const meta = {
2+
name: 'studyloop-gen-quality',
3+
description: 'Autonomous generate+judge loop across 3 LLM providers, then Playwright-validate the panels and write a report',
4+
phases: [
5+
{ title: 'Generate+Judge', detail: 'per-provider judge-loop-until-approved (max 4 rounds), Opus-4.8 judge' },
6+
{ title: 'Validate', detail: 'Playwright walks Quiz + Flashcard panels for each generated deck' },
7+
{ title: 'Report', detail: 'synthesise per-provider rounds, verdicts, Playwright results' },
8+
],
9+
}
10+
11+
// ---------------------------------------------------------------------------
12+
// Config — providers proven live during STEP-2 recon (see handoff).
13+
// IMPORTANT model-id correction: the spec named the Bedrock model
14+
// `us.anthropic.claude-sonnet-4-6-20251101-v1:0`, but that raw foundation-model
15+
// id is NOT directly invocable in this account/region (ValidationException:
16+
// "provided model identifier is invalid"). The cross-region INFERENCE-PROFILE
17+
// id `us.anthropic.claude-sonnet-4-6` works and was proven (5+5, 0 errors).
18+
// ---------------------------------------------------------------------------
19+
const REPO = '/Users/user/code/personal/tools/StudyLoop'
20+
const PUBLISHER = 'CodeWithMosh'
21+
const SOURCE_COURSE = 'Complete_SQL_Mastery'
22+
const SECTIONS = 'study-notes/getting-started-0025,study-notes/data-types-0035'
23+
const TARGET_COUNT = 5
24+
const MAX_QUALITY_ROUNDS = 4
25+
const MAX_GEN_ERROR_RETRIES = 2
26+
const BUDGET_FLOOR = 100_000
27+
const SERVER = 'http://127.0.0.1:8567'
28+
29+
const PROVIDERS = [
30+
{
31+
key: 'bedrock',
32+
label: 'AWS Bedrock — Claude Sonnet 4.6',
33+
backend: 'bedrock',
34+
provider: '',
35+
model: 'us.anthropic.claude-sonnet-4-6',
36+
outputCourse: 'Complete_SQL_Mastery__bedrock',
37+
},
38+
{
39+
key: 'minimax',
40+
label: 'MiniMax M2.7',
41+
backend: 'anthropic_compat',
42+
provider: 'minimax',
43+
model: 'MiniMax-M2.7',
44+
outputCourse: 'Complete_SQL_Mastery__minimax',
45+
},
46+
{
47+
key: 'ollama',
48+
label: 'Ollama — gemma4:latest',
49+
backend: 'ollama',
50+
provider: '',
51+
model: 'gemma4:latest',
52+
outputCourse: 'Complete_SQL_Mastery__ollama',
53+
},
54+
]
55+
56+
// Schemas -------------------------------------------------------------------
57+
const GEN_SCHEMA = {
58+
type: 'object',
59+
additionalProperties: true,
60+
required: ['written', 'failed', 'job_error', 'output_course', 'card_counts'],
61+
properties: {
62+
written: { type: 'integer' },
63+
failed: { type: 'integer' },
64+
job_error: { type: ['string', 'null'] },
65+
output_course: { type: 'string' },
66+
publisher: { type: 'string' },
67+
card_counts: {
68+
type: 'array',
69+
items: {
70+
type: 'object',
71+
additionalProperties: true,
72+
properties: {
73+
path: { type: 'string' },
74+
kind: { type: 'string' },
75+
count: { type: 'integer' },
76+
},
77+
},
78+
},
79+
outcomes: { type: 'array', items: { type: 'object', additionalProperties: true } },
80+
},
81+
}
82+
83+
const VERDICT_SCHEMA = {
84+
type: 'object',
85+
additionalProperties: false,
86+
required: ['approved', 'flashcard_score', 'quiz_score', 'reasons'],
87+
properties: {
88+
approved: { type: 'boolean' },
89+
flashcard_score: { type: 'integer', description: '1-10 content-quality score' },
90+
quiz_score: { type: 'integer', description: '1-10 content-quality score' },
91+
reasons: {
92+
type: 'string',
93+
description: 'If approved: a one-line justification. If rejected: SPECIFIC, actionable improvements to feed back into the next generation prompt.',
94+
},
95+
strengths: { type: 'string' },
96+
weaknesses: { type: 'string' },
97+
},
98+
}
99+
100+
const VALIDATE_SCHEMA = {
101+
type: 'object',
102+
additionalProperties: false,
103+
required: ['provider_key', 'api_ok', 'rendered', 'flashcard_count', 'quiz_count', 'notes'],
104+
properties: {
105+
provider_key: { type: 'string' },
106+
api_ok: { type: 'boolean' },
107+
rendered: { type: 'boolean' },
108+
flashcard_count: { type: 'integer' },
109+
quiz_count: { type: 'integer' },
110+
sample_flashcard_front: { type: 'string' },
111+
sample_quiz_question: { type: 'string' },
112+
notes: { type: 'string' },
113+
},
114+
}
115+
116+
// Helpers -------------------------------------------------------------------
117+
function genCommand(p, round, guidanceFile) {
118+
// guidanceFile is a path whose contents (if any) are passed as --guidance.
119+
// We read it inline via $(cat ...) so judge feedback from the prior round
120+
// flows into the prompt. Empty file => empty guidance => first-round prompt.
121+
const guidanceArg = guidanceFile
122+
? `--guidance "$(cat ${guidanceFile} 2>/dev/null)"`
123+
: '--guidance ""'
124+
return [
125+
`cd ${REPO} &&`,
126+
`uv run --project packages/studyloop python scripts/gen_for_workflow.py`,
127+
`--backend ${p.backend} --provider "${p.provider}" --model "${p.model}"`,
128+
`--publisher ${PUBLISHER} --course ${SOURCE_COURSE}`,
129+
`--output-course "${p.outputCourse}"`,
130+
`--sections "${SECTIONS}"`,
131+
`--target-count ${TARGET_COUNT} ${guidanceArg} --tag ${p.key}-r${round}`,
132+
].join(' ')
133+
}
134+
135+
// Per-provider judge loop ----------------------------------------------------
136+
async function runProvider(p) {
137+
const guidanceFile = `/tmp/sl-guidance-${p.key}.txt`
138+
let qualityRound = 0
139+
let genErrorRetries = 0
140+
let lastVerdict = null
141+
let lastGen = null
142+
const history = []
143+
144+
// Seed the guidance file empty (first round = base prompt).
145+
await agent(
146+
`Run EXACTLY this Bash command to reset the guidance file, then reply "ok": ` +
147+
`printf '' > ${guidanceFile}`,
148+
{ label: `${p.key}:init`, phase: 'Generate+Judge' },
149+
)
150+
151+
while (qualityRound < MAX_QUALITY_ROUNDS && budget.remaining() > BUDGET_FLOOR) {
152+
const round = qualityRound + 1
153+
154+
// --- GENERATE (deterministic Python via a mechanical agent) ---
155+
const cmd = genCommand(p, round, guidanceFile)
156+
const gen = await agent(
157+
`You are a command runner. Run EXACTLY this command with the Bash tool, ` +
158+
`verbatim. CRITICAL: pass timeout=540000 to the Bash tool (generation is ` +
159+
`slow — up to 8 minutes for the local model). Wait for it to finish:\n\n` +
160+
`${cmd}\n\n` +
161+
`It prints one line beginning "WF_RESULT_JSON:". Parse the JSON object ` +
162+
`after that prefix and return it as your structured output. Do not modify ` +
163+
`the command, do not add flags, do not interpret the results — just run ` +
164+
`and return the parsed JSON. If the command produces no WF_RESULT_JSON line ` +
165+
`(e.g. it crashed), return an object with written=0, failed=1, ` +
166+
`job_error set to the stderr tail, output_course as in the command, and ` +
167+
`card_counts as an empty array.`,
168+
{ label: `${p.key}:gen:r${round}`, phase: 'Generate+Judge', schema: GEN_SCHEMA },
169+
)
170+
lastGen = gen
171+
172+
if (!gen || gen.job_error || gen.failed > 0) {
173+
// Generation ERROR (not a quality reject): retry up to MAX_GEN_ERROR_RETRIES.
174+
genErrorRetries++
175+
const errMsg = gen ? (gen.job_error || `${gen.failed} task(s) failed`) : 'agent returned null'
176+
history.push({ round, kind: 'gen_error', detail: errMsg, retry: genErrorRetries })
177+
log(`[${p.key}] generation error (retry ${genErrorRetries}/${MAX_GEN_ERROR_RETRIES}): ${errMsg}`)
178+
if (genErrorRetries > MAX_GEN_ERROR_RETRIES) {
179+
return {
180+
provider: p.key, label: p.label, status: 'FAILED',
181+
reason: `generation errored ${genErrorRetries}x: ${errMsg}`,
182+
rounds: qualityRound, genErrorRetries, history, lastGen,
183+
outputCourse: p.outputCourse,
184+
}
185+
}
186+
continue // retry generation without consuming a quality round
187+
}
188+
189+
// --- JUDGE (Opus 4.8 reads the actual deck files) ---
190+
const paths = (gen.card_counts || []).map((c) => c.path)
191+
const verdict = await agent(
192+
`You are a strict educational-content quality judge. Read these generated ` +
193+
`study-deck JSON files (use the Read tool on each absolute path):\n` +
194+
paths.map((p2) => `- ${p2}`).join('\n') +
195+
`\n\nThey were generated from CodeWithMosh "Complete SQL Mastery" lesson ` +
196+
`notes by the provider "${p.label}". There are flashcard decks ` +
197+
`(front/back) and quiz decks (question/answerOptions with one isCorrect).\n\n` +
198+
`Schema-validity is the FLOOR, not the bar — they already parsed. Judge ` +
199+
`the actual CONTENT quality for a senior engineer learning SQL:\n` +
200+
`- Flashcards: do they test real understanding (why/when, trade-offs), ` +
201+
`are answers self-contained and correct, no trivia, no near-duplicates?\n` +
202+
`- Quizzes: is exactly one option correct, are distractors plausible (not ` +
203+
`throwaway), are rationales educational, is the SQL accurate?\n` +
204+
`- Each deck should have about ${TARGET_COUNT} items.\n\n` +
205+
`Score flashcards and quizzes 1-10. APPROVE only if BOTH are >= 7 and the ` +
206+
`content is genuinely useful and accurate. If you reject, "reasons" MUST be ` +
207+
`specific, actionable instructions that will be fed verbatim into the next ` +
208+
`generation prompt (e.g. "Quiz distractors for JOIN questions are obviously ` +
209+
`wrong — make them reflect common JOIN mistakes like confusing INNER vs LEFT").`,
210+
{ label: `${p.key}:judge:r${round}`, phase: 'Generate+Judge', schema: VERDICT_SCHEMA, model: 'opus' },
211+
)
212+
lastVerdict = verdict
213+
history.push({
214+
round, kind: 'judge', approved: verdict?.approved,
215+
flashcard_score: verdict?.flashcard_score, quiz_score: verdict?.quiz_score,
216+
reasons: verdict?.reasons,
217+
})
218+
qualityRound++
219+
220+
if (verdict && verdict.approved) {
221+
return {
222+
provider: p.key, label: p.label, status: 'APPROVED',
223+
rounds: qualityRound, genErrorRetries, verdict, history,
224+
outputCourse: p.outputCourse, cardCounts: gen.card_counts,
225+
}
226+
}
227+
228+
// Feed the judge's reasons into the next round's prompt via the guidance file.
229+
const reasons = (verdict && verdict.reasons) || 'Improve overall depth, accuracy, and distractor quality.'
230+
await agent(
231+
`Run EXACTLY this Bash command to write the reviewer feedback to the guidance ` +
232+
`file, then reply "ok". Use a heredoc so quoting is safe:\n\n` +
233+
`cat > ${guidanceFile} <<'SLEOF'\n${reasons}\nSLEOF`,
234+
{ label: `${p.key}:feedback:r${round}`, phase: 'Generate+Judge' },
235+
)
236+
log(`[${p.key}] round ${round} rejected (fc=${verdict?.flashcard_score} quiz=${verdict?.quiz_score}); regenerating with feedback`)
237+
}
238+
239+
// Hit the ceiling (or budget) without approval.
240+
const reason = budget.remaining() <= BUDGET_FLOOR
241+
? `budget floor reached after ${qualityRound} round(s)`
242+
: `not approved after ${MAX_QUALITY_ROUNDS} rounds`
243+
return {
244+
provider: p.key, label: p.label, status: 'FAILED',
245+
reason, rounds: qualityRound, genErrorRetries, lastVerdict, history,
246+
outputCourse: p.outputCourse, cardCounts: lastGen ? lastGen.card_counts : [],
247+
}
248+
}
249+
250+
// === Phase 1: Generate + Judge (providers run independently) ===============
251+
phase('Generate+Judge')
252+
log(`Starting gen+judge for ${PROVIDERS.length} providers (max ${MAX_QUALITY_ROUNDS} rounds each)`)
253+
// parallel() so one slow/stuck provider never blocks the others; each thunk
254+
// runs its own full judge-loop and resolves to a verdict (or null on throw).
255+
const genResults = (
256+
await parallel(PROVIDERS.map((p) => () => runProvider(p)))
257+
).map((r, i) => r || {
258+
provider: PROVIDERS[i].key, label: PROVIDERS[i].label,
259+
status: 'FAILED', reason: 'provider thunk threw / returned null',
260+
rounds: 0, history: [], outputCourse: PROVIDERS[i].outputCourse,
261+
})
262+
263+
// === Phase 2: Validate via Playwright + API ================================
264+
phase('Validate')
265+
const validateResults = await parallel(
266+
PROVIDERS.map((p) => () => {
267+
const r = genResults.find((g) => g.provider === p.key)
268+
// Only validate providers that produced decks (APPROVED or FAILED-on-quality
269+
// still wrote files; FAILED-on-gen-error may have none).
270+
return agent(
271+
`Validate that the StudyLoop Quiz and Flashcard panels render the decks for ` +
272+
`course "${p.outputCourse}". The web server is already running at ${SERVER}.\n\n` +
273+
`Step 1 (API assertion, hard): run with Bash:\n` +
274+
` curl -s "${SERVER}/api/courses"\n` +
275+
`Confirm an entry with name "${p.outputCourse}" exists and note its ` +
276+
`flashcard_count and quiz_count.\n` +
277+
`Then run:\n` +
278+
` curl -s "${SERVER}/api/cards/${p.outputCourse}?mode=flashcards"\n` +
279+
` curl -s "${SERVER}/api/cards/${p.outputCourse}?mode=quiz"\n` +
280+
`Count the items in each array and capture one sample front + one sample question.\n\n` +
281+
`Step 2 (render check): use the Playwright MCP browser tools to navigate to ` +
282+
`${SERVER}/#flashcards, snapshot the page, and confirm the course ` +
283+
`"${p.outputCourse}" appears in the course list with its flashcard/quiz counts. ` +
284+
`If Playwright tools are unavailable, set rendered=false and say so in notes — ` +
285+
`the API assertion is the authoritative one.\n\n` +
286+
`Return the structured result. api_ok=true only if the course is in ` +
287+
`/api/courses AND both /api/cards calls returned non-empty arrays.`,
288+
{ label: `validate:${p.key}`, phase: 'Validate', schema: VALIDATE_SCHEMA },
289+
).then((v) => v || {
290+
provider_key: p.key, api_ok: false, rendered: false,
291+
flashcard_count: 0, quiz_count: 0, notes: 'validate agent returned null',
292+
})
293+
}),
294+
)
295+
296+
// === Phase 3: Report =======================================================
297+
phase('Report')
298+
const reportPayload = JSON.stringify({ genResults, validateResults }, null, 2)
299+
await agent(
300+
`Write a markdown report to ${REPO}/docs/handoffs/2026-06-01-gen-quality-workflow-report.md ` +
301+
`summarising this autonomous generation+quality run. Use the Write tool.\n\n` +
302+
`Here is the structured data (per-provider judge results and Playwright/API ` +
303+
`validation):\n\n\`\`\`json\n${reportPayload}\n\`\`\`\n\n` +
304+
`The report MUST include:\n` +
305+
`1. A summary table: provider | status (APPROVED/FAILED) | quality rounds | ` +
306+
`gen-error retries | flashcard score | quiz score | API ok | rendered.\n` +
307+
`2. For each provider: the judge's final reasons, strengths, weaknesses, and ` +
308+
`the round-by-round history.\n` +
309+
`3. Any provider that hit the ceiling (4 rounds) or budget floor WITHOUT ` +
310+
`approval — call these out prominently as needing attention.\n` +
311+
`4. Playwright/API validation results per provider (counts + sample content).\n` +
312+
`5. A short "what needs human decision" section.\n` +
313+
`Be precise and factual; do not invent data not present in the JSON. ` +
314+
`Reply with the absolute path you wrote.`,
315+
{ label: 'report:write', phase: 'Report' },
316+
)
317+
318+
// Return the structured data so the orchestrator (STEP 3) can act on it.
319+
const approved = genResults.filter((r) => r.status === 'APPROVED').map((r) => r.provider)
320+
const failed = genResults.filter((r) => r.status !== 'APPROVED').map((r) => r.provider)
321+
return {
322+
approved,
323+
failed,
324+
allApproved: failed.length === 0,
325+
genResults,
326+
validateResults,
327+
reportPath: `${REPO}/docs/handoffs/2026-06-01-gen-quality-workflow-report.md`,
328+
}

0 commit comments

Comments
 (0)