Skip to content

Commit 26522c4

Browse files
test(content): harness scripts for gen+read proof and workflow generation
- scripts/prove_gen_readpath.py: end-to-end proof that a generated deck lands where the panels read (drives job.run_job + settings.resolve_study_dirs + review_loader.discover_directories + services.review.get_cards). Used to prove Issue #1's fix. - scripts/gen_for_workflow.py: parameterised single-provider generation harness for the autonomous gen+judge workflow. Controls target card count and injects judge-feedback guidance into the prompts (generators have no count param); decouples SOURCE course (scope) from OUTPUT course (--output-course) so concurrent providers write to isolated dirs; emits WF_RESULT_JSON for the orchestrating workflow to parse. Both proven live against Ollama gemma4, Bedrock Sonnet 4.6, and MiniMax M2.7.
1 parent ddb5579 commit 26522c4

1 file changed

Lines changed: 207 additions & 0 deletions

File tree

‎scripts/gen_for_workflow.py‎

Lines changed: 207 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,207 @@
1+
"""Parameterised generation harness for the autonomous gen+judge workflow.
2+
3+
Drives the production write path (job.run_job) for ONE provider, generating
4+
BOTH flashcards and quizzes for a course/section scope with a controllable
5+
target card count and optional judge-feedback guidance injected into the
6+
prompts. Emits a single JSON object on stdout describing what was written so
7+
the orchestrating workflow can parse it.
8+
9+
Card count + guidance are injected by patching the prompt constants in each
10+
generator module's namespace (the generators read them at call time). Safe
11+
because StudyLoop generates one deck at a time (active_gen singleton) and this
12+
process is single-threaded per provider.
13+
14+
Usage:
15+
uv run --project packages/studyloop python scripts/gen_for_workflow.py \
16+
--backend ollama --provider "" --model "gemma4:latest" \
17+
--publisher CodeWithMosh --course Complete_SQL_Mastery \
18+
--sections study-notes/getting-started-0025,study-notes/data-types-0035 \
19+
--target-count 5 --guidance "" --tag round1
20+
21+
Exit 0 always (even on per-task gen errors); the JSON `failed` count and
22+
`errors` list carry the outcome so the workflow can decide retry vs reject.
23+
Exit 2 only on a whole-job failure (scope miss, generator construction error).
24+
"""
25+
26+
from __future__ import annotations
27+
28+
import argparse
29+
import json
30+
import sys
31+
from dataclasses import replace
32+
33+
from studyloop.content.generators import anthropic_compat, bedrock, ollama, openai_compat
34+
from studyloop.content.job import JobRequest, run_job
35+
from studyloop.content.scope import ScopeRequest
36+
from studyloop.settings import load_settings
37+
38+
# Generator modules whose prompt globals we patch. Each binds the prompt
39+
# constants at import; they read them at call time from their own namespace.
40+
_PROMPT_MODULES = (ollama, bedrock, anthropic_compat, openai_compat)
41+
42+
43+
def _count_line(kind: str, n: int) -> str:
44+
if kind == "flashcards":
45+
return (
46+
f"Produce exactly {n} cards per source chunk. Each must be distinct "
47+
f"and test a different concept -- no padding, no near-duplicates."
48+
)
49+
return (
50+
f"Produce exactly {n} questions per source chunk. Each must probe a "
51+
f"different concept -- no padding, no near-duplicates."
52+
)
53+
54+
55+
def _patch_prompts(target_count: int, guidance: str) -> None:
56+
"""Rewrite the system prompts in-place across all generator modules.
57+
58+
Replaces the soft "Produce 6 to 12 / 4 to 8" line with a hard target, and
59+
appends judge guidance (if any) so the next round can act on prior feedback.
60+
"""
61+
from studyloop.content.generators import prompts as _p
62+
63+
fc = _p.FLASHCARD_SYSTEM_PROMPT
64+
qz = _p.QUIZ_SYSTEM_PROMPT
65+
66+
# Drop the original soft-count sentences (kept generic so a prompt edit
67+
# upstream doesn't silently break this) and append the hard target.
68+
fc_new = fc.replace(
69+
"Produce 6 to 12 cards per source chunk. Fewer is acceptable if the source\n"
70+
"is short; more is acceptable if the source genuinely covers that many\n"
71+
"distinct ideas.",
72+
_count_line("flashcards", target_count),
73+
)
74+
qz_new = qz.replace(
75+
"Produce 4 to 8 questions per source chunk.",
76+
_count_line("quizzes", target_count),
77+
)
78+
if guidance.strip():
79+
suffix = (
80+
"\n\nA reviewer assessed a previous attempt and asked for these "
81+
f"improvements -- apply them:\n{guidance.strip()}\n"
82+
)
83+
fc_new += suffix
84+
qz_new += suffix
85+
86+
for mod in _PROMPT_MODULES:
87+
if hasattr(mod, "FLASHCARD_SYSTEM_PROMPT"):
88+
mod.FLASHCARD_SYSTEM_PROMPT = fc_new
89+
if hasattr(mod, "QUIZ_SYSTEM_PROMPT"):
90+
mod.QUIZ_SYSTEM_PROMPT = qz_new
91+
92+
93+
def main() -> int:
94+
ap = argparse.ArgumentParser()
95+
ap.add_argument("--backend", required=True)
96+
ap.add_argument("--provider", default="")
97+
ap.add_argument("--model", default="")
98+
ap.add_argument("--publisher", required=True)
99+
ap.add_argument("--course", required=True, help="SOURCE course (where study-notes live)")
100+
ap.add_argument(
101+
"--output-course",
102+
default="",
103+
help="OUTPUT course dir for the decks (defaults to --course). Use a "
104+
"per-provider name to isolate concurrent providers' decks.",
105+
)
106+
ap.add_argument("--sections", required=True, help="comma-separated section slugs")
107+
ap.add_argument("--target-count", type=int, default=5)
108+
ap.add_argument("--guidance", default="")
109+
ap.add_argument("--tag", default="")
110+
args = ap.parse_args()
111+
112+
_patch_prompts(args.target_count, args.guidance)
113+
114+
settings = load_settings()
115+
cg = settings.card_generator
116+
overrides: dict = {"backend": args.backend}
117+
if args.backend == "ollama":
118+
overrides["ollama"] = replace(
119+
cg.ollama,
120+
model=args.model or cg.ollama.model,
121+
base_url=cg.ollama.base_url or "http://localhost:11434",
122+
)
123+
elif args.backend == "bedrock":
124+
overrides["bedrock"] = replace(cg.bedrock, model=args.model or cg.bedrock.model)
125+
cg = replace(cg, **overrides)
126+
if args.provider:
127+
cg = replace(cg, provider=args.provider)
128+
if args.model and args.backend not in ("ollama", "bedrock"):
129+
cg = replace(cg, model=args.model)
130+
settings = replace(settings, card_generator=cg)
131+
132+
sections = [s.strip() for s in args.sections.split(",") if s.strip()]
133+
output_course = args.output_course or args.course
134+
all_outcomes: list[dict] = []
135+
job_error: str | None = None
136+
137+
for section in sections:
138+
# ScopeRequest.course drives SOURCE resolution (study-notes); the
139+
# JobRequest.course drives the OUTPUT dir. Keeping them separate lets
140+
# each provider write to an isolated course dir while reading the same
141+
# real source material.
142+
req = JobRequest(
143+
course=output_course,
144+
publisher=args.publisher,
145+
scope=ScopeRequest(
146+
kind="section",
147+
course=args.course,
148+
publisher=args.publisher,
149+
section=section,
150+
),
151+
kinds=("flashcards", "quizzes"),
152+
on_existing="overwrite",
153+
backend=args.backend,
154+
provider=args.provider,
155+
model=args.model,
156+
)
157+
try:
158+
result = run_job(f"wf-{args.tag}-{section}", req, settings, on_event=None)
159+
except Exception as exc: # whole-job failure captured for workflow
160+
job_error = f"{type(exc).__name__}: {exc}"
161+
break
162+
for o in result.outcomes:
163+
all_outcomes.append(
164+
{
165+
"section": section,
166+
"kind": o.kind,
167+
"ok": o.ok,
168+
"path": o.path,
169+
"error": o.error,
170+
"elapsed_s": round(o.elapsed_s, 1),
171+
}
172+
)
173+
174+
written = sum(1 for o in all_outcomes if o["ok"])
175+
failed = sum(1 for o in all_outcomes if not o["ok"])
176+
# Count cards actually written so the workflow can assert >=5/source.
177+
card_counts: list[dict] = []
178+
for o in all_outcomes:
179+
if o["ok"] and o["path"]:
180+
try:
181+
with open(o["path"]) as fh:
182+
data = json.load(fh)
183+
n = len(data.get("cards", data.get("questions", [])))
184+
except Exception: # count is best-effort; -1 signals unreadable
185+
n = -1
186+
card_counts.append({"path": o["path"], "kind": o["kind"], "count": n})
187+
188+
out = {
189+
"backend": args.backend,
190+
"provider": args.provider,
191+
"model": args.model,
192+
"tag": args.tag,
193+
"output_course": output_course,
194+
"publisher": args.publisher,
195+
"written": written,
196+
"failed": failed,
197+
"job_error": job_error,
198+
"outcomes": all_outcomes,
199+
"card_counts": card_counts,
200+
}
201+
print("WF_RESULT_JSON:" + json.dumps(out))
202+
# Whole-job failure (cred/scope) → exit 2 so the workflow's ERROR path fires.
203+
return 2 if job_error else 0
204+
205+
206+
if __name__ == "__main__":
207+
sys.exit(main())

0 commit comments

Comments
 (0)