-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbenchmark_nova_models.py
More file actions
2405 lines (2144 loc) · 105 KB
/
benchmark_nova_models.py
File metadata and controls
2405 lines (2144 loc) · 105 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Nova Model Benchmark Suite — standardized testing protocol for Nova Lite/Pro/Premier.
Runs the same 5-task Expense Tracker build across each Nova model, measures
25 verification checks, and produces a comparative scorecard with letter grades.
Rating System:
S (95-100%) — Production-grade. Ship it.
A (85-94%) — Strong. Minor polish needed.
B (75-84%) — Functional. Some gaps to address.
C (60-74%) — Partial. Significant issues.
D (40-59%) — Broken. Major failures.
F (<40%) — Non-functional.
Dimensions scored (each 0-100, weighted):
1. Task Completion (30%) — Did it create the expected files?
2. Code Quality (25%) — Syntax-clean, no stubs, right patterns?
3. Interface Fidelity (20%) — Do imports match exports? No hallucinations?
4. Runtime Viability (15%) — Does the server start? Do endpoints work?
5. Efficiency (10%) — Turns, retries, token usage, cost
Usage:
source ~/.secrets/hercules.env
# Run all 3 Nova models
python3 benchmark_nova_models.py
# Run a specific model
python3 benchmark_nova_models.py --model nova-lite
# Run all and save comparison report
python3 benchmark_nova_models.py --all --report
# Compare against a previous run
python3 benchmark_nova_models.py --all --compare benchmarks/run_20260313_1400.json
# Show results from a previous run
python3 benchmark_nova_models.py --show benchmarks/run_20260313_1400.json
"""
import asyncio
import ast
import json
import logging
import os
import re
import shutil
import sys
import time
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
from benchmarks.benchmark_store import (
BenchmarkStore, collect_metadata, detect_regressions,
diff_checks, generate_optimization_hints, append_changelog,
format_history, RegressionAlert, CheckDiff, OptimizationHint,
)
sys.path.insert(0, str(Path(__file__).parent))
logging.basicConfig(
level=logging.WARNING,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
datefmt="%H:%M:%S",
)
logger = logging.getLogger("benchmark")
from config import get_model_config, ForgeProject, resolve_model, init_forge_dir, get_context_window, compute_turn_budget
from forge_agent import ForgeAgent, BUILT_IN_TOOLS, AgentEvent, get_tools_for_model
from forge_comms import BuildContext
from forge_guards import PathSandbox
from forge_hooks import HookSystem
from forge_tasks import TaskStore
from forge_models import estimate_cost, format_cost, get_capability
# ── Config ────────────────────────────────────────────────────────────────────
PROJECT_BASE = Path("/tmp/forge-benchmark")
NOVA_MODELS = ["nova-lite", "nova-pro", "nova-premier"]
BENCHMARKS_DIR = Path(__file__).parent / "benchmarks"
# Letter grade thresholds
GRADE_THRESHOLDS = [
(95, "S"), (85, "A"), (75, "B"), (60, "C"), (40, "D"), (0, "F"),
]
# Dimension weights (must sum to 1.0)
DIMENSION_WEIGHTS = {
"task_completion": 0.30,
"code_quality": 0.25,
"interface_fidelity": 0.20,
"runtime_viability": 0.15,
"efficiency": 0.10,
}
# ── Spec & Tasks (same as benchmark_expense_tracker.py for consistency) ──────
SPEC_MD = """\
# Expense Tracker
A personal expense tracking app with Flask backend and vanilla JS frontend.
## Tech Stack
- Backend: Python 3 + Flask
- Database: SQLite3 (raw sqlite3 module, NOT SQLAlchemy)
- Frontend: Vanilla HTML/CSS/JS (no frameworks)
- Charts: Chart.js CDN
## Data Models
### Category
- id (INTEGER PRIMARY KEY AUTOINCREMENT)
- name (TEXT NOT NULL UNIQUE)
- color (TEXT DEFAULT '#6c757d')
### Expense
- id (INTEGER PRIMARY KEY AUTOINCREMENT)
- amount (REAL NOT NULL)
- description (TEXT)
- category_id (INTEGER REFERENCES categories)
- date (TEXT NOT NULL, ISO format YYYY-MM-DD)
- created_at (TEXT DEFAULT CURRENT_TIMESTAMP)
## API Endpoints
All endpoints return JSON. Prefix: none (root-level).
| Method | Path | Description |
|--------|------|-------------|
| GET | /api/categories | List all categories |
| POST | /api/categories | Create category {name, color} |
| GET | /api/expenses | List expenses (optional ?category_id=&start=&end=) |
| POST | /api/expenses | Create expense {amount, description, category_id, date} |
| PUT | /api/expenses/<id> | Update expense |
| DELETE | /api/expenses/<id> | Delete expense |
| GET | /api/summary | Monthly summary {total, by_category: [{name, total, color}]} |
## Frontend Pages
Single page app at / (index.html):
- Expense form: amount, description, category dropdown, date picker
- Expense table: sortable, with edit/delete buttons
- Category manager: add/edit categories with color picker
- Monthly chart: pie chart of spending by category (Chart.js)
- Filter bar: date range + category filter
## File Structure
```
models.py - Database helpers (init_db, CRUD functions)
api.py - Flask app with routes (imports from models)
static/index.html - Main page
static/app.js - Frontend logic (fetch API calls, DOM manipulation)
static/style.css - Styling
```
## IMPORTANT
- models.py uses raw sqlite3, NOT SQLAlchemy
- models.py exports FUNCTIONS (not classes): init_db(), create_category(), get_categories(), etc.
- api.py imports these functions: `from models import init_db, create_category, ...`
- Do NOT create ORM model classes like Category or Expense
"""
TASKS_JSON = [
{
"subject": "Create database models and helpers",
"description": (
"Create models.py with raw sqlite3 database helpers. "
"Functions: init_db(), create_category(name, color), get_categories(), "
"create_expense(amount, description, category_id, date), get_expenses(category_id=None, start=None, end=None), "
"update_expense(expense_id, **kwargs), delete_expense(expense_id), get_monthly_summary(). "
"Use a module-level DB_PATH='expenses.db'. Call init_db() at import time to ensure tables exist."
),
"files": ["models.py"],
"sprint": "sprint-01",
"risk": "low",
"blocked_by": [],
},
{
"subject": "Create Flask API routes",
"description": (
"Create api.py with Flask app and REST routes. "
"Import functions from models.py: from models import init_db, create_category, get_categories, "
"create_expense, get_expenses, update_expense, delete_expense, get_monthly_summary. "
"Routes: GET/POST /api/categories, GET/POST /api/expenses, PUT/DELETE /api/expenses/<id>, GET /api/summary. "
"Serve static files from ./static/. Return JSON responses with appropriate status codes."
),
"files": ["api.py"],
"sprint": "sprint-01",
"risk": "low",
"blocked_by": [0],
},
{
"subject": "Create frontend HTML page",
"description": (
"Create static/index.html — single page expense tracker UI. "
"Include: expense form (amount, description, category dropdown, date), expense table, "
"category manager section, monthly pie chart placeholder (Chart.js CDN), "
"filter bar (date range, category). Link to app.js and style.css."
),
"files": ["static/index.html"],
"sprint": "sprint-01",
"risk": "low",
"blocked_by": [0],
},
{
"subject": "Create frontend JavaScript",
"description": (
"Create static/app.js — frontend logic. "
"Functions: loadCategories(), loadExpenses(), addExpense(), editExpense(id), deleteExpense(id), "
"addCategory(), renderChart(), applyFilters(). "
"Use fetch() for all API calls to /api/* endpoints. "
"Populate category dropdowns, render expense table, initialize Chart.js pie chart."
),
"files": ["static/app.js"],
"sprint": "sprint-01",
"risk": "low",
"blocked_by": [1, 2],
},
{
"subject": "Create CSS styling",
"description": (
"Create static/style.css — clean, modern styling. "
"Style the expense form, table, category manager, chart container, and filter bar. "
"Use a consistent color scheme. Make it responsive."
),
"files": ["static/style.css"],
"sprint": "sprint-01",
"risk": "low",
"blocked_by": [2],
},
]
EXPECTED_FILES = ["models.py", "api.py", "static/index.html", "static/app.js", "static/style.css"]
# ── Scenario 2: Todo App (FastAPI) ──────────────────────────────────────────
TODO_SPEC_MD = """\
# Todo App
A task management app with FastAPI backend and vanilla JS frontend.
## Tech Stack
- Backend: Python 3 + FastAPI + Uvicorn
- Database: SQLite3 (raw sqlite3 module, NOT SQLAlchemy)
- Frontend: Vanilla HTML/CSS/JS (no frameworks)
## Data Models
### Todo
- id (INTEGER PRIMARY KEY AUTOINCREMENT)
- title (TEXT NOT NULL)
- completed (INTEGER DEFAULT 0)
- priority (TEXT DEFAULT 'medium', one of 'low','medium','high')
- created_at (TEXT DEFAULT CURRENT_TIMESTAMP)
## API Endpoints
All endpoints return JSON.
| Method | Path | Description |
|--------|------|-------------|
| GET | /api/todos | List all todos (optional ?completed=true/false&priority=high) |
| POST | /api/todos | Create todo {title, priority} |
| PUT | /api/todos/{id} | Update todo {title, completed, priority} |
| DELETE | /api/todos/{id} | Delete todo |
## Frontend
Single page at / (index.html):
- Add todo form: title, priority dropdown
- Todo list: checkbox to toggle completed, delete button
- Filter bar: all / active / completed
- Priority badges: colored labels
## File Structure
```
models.py - Database helpers (init_db, CRUD functions)
main.py - FastAPI app with routes (imports from models)
static/index.html - Main page
static/app.js - Frontend logic
```
## IMPORTANT
- models.py uses raw sqlite3, NOT SQLAlchemy
- main.py uses FastAPI, NOT Flask
- The app variable must be named 'app': app = FastAPI()
"""
TODO_TASKS_JSON = [
{
"subject": "Create todo database models",
"description": (
"Create models.py with raw sqlite3 helpers. "
"Functions: init_db(), create_todo(title, priority='medium'), get_todos(completed=None, priority=None), "
"update_todo(todo_id, **kwargs), delete_todo(todo_id). "
"Use DB_PATH='todos.db'. Call init_db() at import time."
),
"files": ["models.py"],
"sprint": "sprint-01",
"risk": "low",
"blocked_by": [],
},
{
"subject": "Create FastAPI routes",
"description": (
"Create main.py with FastAPI app and routes. "
"Import from models: from models import init_db, create_todo, get_todos, update_todo, delete_todo. "
"Routes: GET/POST /api/todos, PUT/DELETE /api/todos/{id}. "
"Serve static files via StaticFiles mount. "
"For request validation, use simple Pydantic BaseModel classes with plain type hints "
"(str, Optional[str], bool). Do NOT use Field(regex=...) or Field(pattern=...) — "
"just use plain str type for priority and validate manually if needed."
),
"files": ["main.py"],
"sprint": "sprint-01",
"risk": "low",
"blocked_by": [0],
},
{
"subject": "Create frontend HTML page",
"description": (
"Create static/index.html — single page todo app. "
"Include: a <form> element for adding todos with title input and priority dropdown, "
"a todo list section with checkboxes for toggling completion, "
"filter buttons (all/active/completed), and priority badges. Link to app.js. "
"Use semantic HTML with proper form elements."
),
"files": ["static/index.html"],
"sprint": "sprint-01",
"risk": "low",
"blocked_by": [0],
},
{
"subject": "Create frontend JavaScript",
"description": (
"Create static/app.js — frontend logic. "
"Functions: loadTodos(), addTodo(), toggleTodo(id), deleteTodo(id), filterTodos(status). "
"Use fetch() for all API calls to /api/todos endpoints."
),
"files": ["static/app.js"],
"sprint": "sprint-01",
"risk": "low",
"blocked_by": [1, 2],
},
]
TODO_EXPECTED_FILES = ["models.py", "main.py", "static/index.html", "static/app.js"]
# ── Scenario 3: Kanban Board (Hard) ─────────────────────────────────────────
KANBAN_SPEC_MD = """\
# Project Kanban Board
A project management app with authentication, kanban task board, and team collaboration.
## Tech Stack
- Backend: Python 3 + Flask
- Database: SQLite3 (raw sqlite3 module, NOT SQLAlchemy)
- Frontend: Vanilla HTML/CSS/JS (no frameworks)
- Auth: hashlib for password hashing, hmac for tokens
## Data Models
### User
- id (INTEGER PRIMARY KEY AUTOINCREMENT)
- username (TEXT NOT NULL UNIQUE)
- password_hash (TEXT NOT NULL)
- created_at (TEXT DEFAULT CURRENT_TIMESTAMP)
### Project
- id (INTEGER PRIMARY KEY AUTOINCREMENT)
- name (TEXT NOT NULL)
- description (TEXT DEFAULT '')
- owner_id (INTEGER NOT NULL REFERENCES users)
- created_at (TEXT DEFAULT CURRENT_TIMESTAMP)
### Task
- id (INTEGER PRIMARY KEY AUTOINCREMENT)
- title (TEXT NOT NULL)
- description (TEXT DEFAULT '')
- status (TEXT NOT NULL DEFAULT 'todo', one of 'todo', 'in_progress', 'done')
- priority (TEXT NOT NULL DEFAULT 'medium', one of 'low', 'medium', 'high', 'critical')
- project_id (INTEGER NOT NULL REFERENCES projects ON DELETE CASCADE)
- assignee_id (INTEGER REFERENCES users)
- due_date (TEXT, ISO format YYYY-MM-DD, nullable)
- created_at (TEXT DEFAULT CURRENT_TIMESTAMP)
## API Endpoints
All endpoints return JSON. Prefix: none (root-level).
| Method | Path | Description |
|--------|------|-------------|
| POST | /api/auth/register | Register user {username, password} → {id, username} |
| POST | /api/auth/login | Login {username, password} → {token, user_id, username} |
| GET | /api/projects | List all projects |
| POST | /api/projects | Create project {name, description, owner_id} |
| GET | /api/projects/<id>/tasks | List tasks for project (optional ?status=&priority=) |
| POST | /api/tasks | Create task {title, description, status, priority, project_id, assignee_id, due_date} |
| PUT | /api/tasks/<id> | Update task (any subset of fields) |
| DELETE | /api/tasks/<id> | Delete task |
| GET | /api/projects/<id>/stats | Project stats {total, by_status: {todo, in_progress, done}, overdue_count} |
## Frontend Pages
Single page app at / (index.html):
- Login/register form (toggle between modes)
- Project selector dropdown (after login)
- Kanban board: 3 columns (Todo, In Progress, Done)
- Task cards showing: title, priority badge (colored), assignee, due date
- Click task to edit in a modal/form, buttons to move between columns
- New task form: title, description, priority dropdown, assignee, due date
- Project stats bar: total tasks, progress percentage, overdue count
## File Structure
```
config.py - Configuration constants (SECRET_KEY, DB_PATH)
auth.py - Password hashing (hashlib) and token helpers (hmac)
models.py - Database helpers (init_db, CRUD for users/projects/tasks)
api.py - Flask app with auth + project + task routes
static/index.html - Main page with login and kanban board
static/app.js - Frontend logic (auth state, fetch API, kanban interaction)
static/style.css - Kanban column layout and card styling
```
## IMPORTANT
- config.py exports SECRET_KEY (str) and DB_PATH (str)
- auth.py exports: hash_password(password) → str, verify_password(password, hashed) → bool, generate_token(user_id, secret) → str, validate_token(token, secret) → int|None
- auth.py uses hashlib.sha256 for hashing and hmac for tokens — NOT bcrypt, NOT jwt
- models.py uses raw sqlite3, NOT SQLAlchemy
- models.py exports FUNCTIONS (not classes): init_db(), create_user(), get_user_by_username(), create_project(), get_projects(), get_project_tasks(), create_task(), update_task(), delete_task(), get_project_stats()
- api.py imports from BOTH auth and models
- Do NOT create ORM model classes
"""
KANBAN_TASKS_JSON = [
{
"subject": "Create configuration module",
"description": (
"Create config.py with application constants. "
"Exports: SECRET_KEY = 'kanban-secret-key-2026' (str), DB_PATH = 'kanban.db' (str). "
"Keep it simple — just these two constants, no classes or functions."
),
"files": ["config.py"],
"sprint": "sprint-01",
"risk": "low",
"blocked_by": [],
},
{
"subject": "Create authentication module",
"description": (
"Create auth.py with password hashing and token helpers. "
"Import hashlib and hmac (stdlib only, no external deps). "
"Functions: hash_password(password: str) → str using hashlib.sha256 hexdigest, "
"verify_password(password: str, hashed: str) → bool, "
"generate_token(user_id: int, secret: str) → str using hmac.new with sha256, "
"validate_token(token: str, secret: str) → int or None (returns user_id if valid). "
"Token format: '{user_id}:{hmac_signature}' so it can be split and verified."
),
"files": ["auth.py"],
"sprint": "sprint-01",
"risk": "low",
"blocked_by": [0],
},
{
"subject": "Create database models with 3 tables",
"description": (
"Create models.py with raw sqlite3 database helpers for 3 related tables. "
"Import DB_PATH from config: from config import DB_PATH. "
"Tables: users (id, username, password_hash, created_at), "
"projects (id, name, description, owner_id FK→users, created_at), "
"tasks (id, title, description, status, priority, project_id FK→projects, assignee_id FK→users, due_date, created_at). "
"Enable foreign keys: PRAGMA foreign_keys = ON. "
"Functions: init_db(), create_user(username, password_hash) → dict, "
"get_user_by_username(username) → dict|None, "
"create_project(name, description, owner_id) → dict, "
"get_projects() → list[dict], "
"get_project_tasks(project_id, status=None, priority=None) → list[dict], "
"create_task(title, description, status, priority, project_id, assignee_id=None, due_date=None) → dict, "
"update_task(task_id, **kwargs) → dict, "
"delete_task(task_id) → bool, "
"get_project_stats(project_id) → dict with keys: total, by_status (dict), overdue_count (int). "
"Call init_db() at import time."
),
"files": ["models.py"],
"sprint": "sprint-01",
"risk": "low",
"blocked_by": [0],
},
{
"subject": "Create Flask API with auth and CRUD routes",
"description": (
"Create api.py with Flask app and all REST routes. "
"Import from auth: from auth import hash_password, verify_password, generate_token, validate_token. "
"Import from models: from models import init_db, create_user, get_user_by_username, "
"create_project, get_projects, get_project_tasks, create_task, update_task, delete_task, get_project_stats. "
"Import from config: from config import SECRET_KEY. "
"Auth routes: POST /api/auth/register (hash password, create user), POST /api/auth/login (verify, return token). "
"Project routes: GET /api/projects, POST /api/projects. "
"Task routes: GET /api/projects/<id>/tasks (with ?status=&priority= filters), "
"POST /api/tasks, PUT /api/tasks/<id>, DELETE /api/tasks/<id>. "
"Stats: GET /api/projects/<id>/stats. "
"Serve static files from ./static/. Return JSON with appropriate status codes."
),
"files": ["api.py"],
"sprint": "sprint-01",
"risk": "low",
"blocked_by": [1, 2],
},
{
"subject": "Create kanban board HTML page",
"description": (
"Create static/index.html — single page kanban board UI. "
"Include: auth section (login/register forms, toggleable), "
"project selector dropdown, "
"kanban board with 3 columns: div.column#todo-column, div.column#in-progress-column, div.column#done-column, "
"each column has a header and a task list area. "
"Task card template: title, priority badge, assignee name, due date. "
"New task form (modal or inline): title, description, priority dropdown (low/medium/high/critical), "
"assignee, due date input. "
"Stats bar showing total tasks and progress. "
"Link to app.js and style.css."
),
"files": ["static/index.html"],
"sprint": "sprint-01",
"risk": "low",
"blocked_by": [2],
},
{
"subject": "Create kanban CSS styling",
"description": (
"Create static/style.css — kanban board styling. "
"Layout: flexbox kanban columns (3 equal columns side by side). "
"Cards: rounded corners, subtle shadow, priority color indicators "
"(low=green, medium=blue, high=orange, critical=red). "
"Auth forms: centered, clean. Responsive: stack columns on mobile. "
"Use a consistent color scheme with a dark header."
),
"files": ["static/style.css"],
"sprint": "sprint-01",
"risk": "low",
"blocked_by": [4],
},
{
"subject": "Create kanban frontend JavaScript",
"description": (
"Create static/app.js — frontend logic for the kanban board. "
"Auth state: store token in localStorage, show/hide auth vs kanban sections. "
"Functions: register(), login(), logout(), loadProjects(), selectProject(id), "
"loadTasks(projectId), renderKanban(tasks), addTask(), moveTask(taskId, newStatus), "
"editTask(taskId), deleteTask(taskId), loadStats(projectId). "
"Use fetch() with Authorization header for all API calls. "
"DOM manipulation: populate dropdowns, render task cards in correct columns, "
"handle form submissions, update stats bar."
),
"files": ["static/app.js"],
"sprint": "sprint-01",
"risk": "low",
"blocked_by": [3, 4],
},
]
KANBAN_EXPECTED_FILES = [
"config.py", "auth.py", "models.py", "api.py",
"static/index.html", "static/app.js", "static/style.css",
]
# ── Scenario 4: Realtime Kanban (Nightmare) ─────────────────────────────────
REALTIME_SPEC_MD = """\
# Realtime Project Kanban Board
A full-featured project management app with authentication, real-time updates via
Server-Sent Events (SSE), file attachments, and an activity log.
## Tech Stack
- Backend: Python 3 + Flask
- Database: SQLite3 (raw sqlite3 module, NOT SQLAlchemy)
- Frontend: Vanilla HTML/CSS/JS (no frameworks)
- Auth: hashlib for password hashing, hmac for tokens
- Real-time: Server-Sent Events (SSE) via Flask streaming response
- Uploads: Flask request.files + os.makedirs for storage
## Data Models
### User
- id (INTEGER PRIMARY KEY AUTOINCREMENT)
- username (TEXT NOT NULL UNIQUE)
- password_hash (TEXT NOT NULL)
- created_at (TEXT DEFAULT CURRENT_TIMESTAMP)
### Project
- id (INTEGER PRIMARY KEY AUTOINCREMENT)
- name (TEXT NOT NULL)
- description (TEXT DEFAULT '')
- owner_id (INTEGER NOT NULL REFERENCES users)
- created_at (TEXT DEFAULT CURRENT_TIMESTAMP)
### Task
- id (INTEGER PRIMARY KEY AUTOINCREMENT)
- title (TEXT NOT NULL)
- description (TEXT DEFAULT '')
- status (TEXT NOT NULL DEFAULT 'todo', one of 'todo', 'in_progress', 'done')
- priority (TEXT NOT NULL DEFAULT 'medium', one of 'low', 'medium', 'high', 'critical')
- project_id (INTEGER NOT NULL REFERENCES projects ON DELETE CASCADE)
- assignee_id (INTEGER REFERENCES users)
- due_date (TEXT, ISO format YYYY-MM-DD, nullable)
- created_at (TEXT DEFAULT CURRENT_TIMESTAMP)
### Attachment
- id (INTEGER PRIMARY KEY AUTOINCREMENT)
- filename (TEXT NOT NULL)
- filepath (TEXT NOT NULL)
- task_id (INTEGER NOT NULL REFERENCES tasks ON DELETE CASCADE)
- uploaded_by (INTEGER NOT NULL REFERENCES users)
- created_at (TEXT DEFAULT CURRENT_TIMESTAMP)
### ActivityLog
- id (INTEGER PRIMARY KEY AUTOINCREMENT)
- action (TEXT NOT NULL, e.g. 'task_created', 'task_moved', 'file_uploaded')
- entity_type (TEXT NOT NULL, e.g. 'task', 'project', 'attachment')
- entity_id (INTEGER NOT NULL)
- user_id (INTEGER REFERENCES users)
- details (TEXT, JSON string with extra info)
- created_at (TEXT DEFAULT CURRENT_TIMESTAMP)
## API Endpoints
All endpoints return JSON. Prefix: none (root-level).
| Method | Path | Description |
|--------|------|-------------|
| POST | /api/auth/register | Register user {username, password} → {id, username} |
| POST | /api/auth/login | Login {username, password} → {token, user_id, username} |
| GET | /api/projects | List all projects |
| POST | /api/projects | Create project {name, description, owner_id} |
| GET | /api/projects/<id>/tasks | List tasks (optional ?status=&priority=) |
| POST | /api/tasks | Create task {title, desc, status, priority, project_id, assignee_id, due_date} |
| PUT | /api/tasks/<id> | Update task |
| DELETE | /api/tasks/<id> | Delete task |
| GET | /api/projects/<id>/stats | Project stats {total, by_status, overdue_count, attachment_count} |
| GET | /api/tasks/<id>/attachments | List attachments for task |
| POST | /api/tasks/<id>/attachments | Upload file (multipart/form-data, field name: 'file') |
| DELETE | /api/attachments/<id> | Delete attachment |
| GET | /api/activity | Recent activity log (optional ?project_id=&limit=50) |
| GET | /api/events | SSE stream — emits task_updated, task_created, task_deleted events as JSON |
## Server-Sent Events (SSE)
The /api/events endpoint returns a streaming response with Content-Type: text/event-stream.
Each event has format:
```
event: task_updated
data: {"task_id": 1, "status": "done", "timestamp": "..."}
```
Events are broadcast when tasks are created, updated, or deleted.
Use a module-level list of queues (one per connected client) for fan-out.
## File Uploads
POST /api/tasks/<id>/attachments accepts multipart/form-data with a 'file' field.
Files are saved to uploads/<task_id>/<filename>.
Max file size: 10MB.
Return {id, filename, task_id} on success.
## Frontend Pages
Single page at / (index.html):
- Login/register form (toggle between modes)
- Project selector dropdown
- Kanban board: 3 columns (Todo, In Progress, Done)
- Task cards: title, priority badge, assignee, due date, attachment count badge
- Task detail modal: edit fields, file upload area, attachment list
- Activity feed sidebar: scrolling list of recent actions
- Auto-refresh via EventSource (SSE) — kanban updates without page reload
## File Structure
```
config.py - Configuration (SECRET_KEY, DB_PATH, UPLOAD_DIR, MAX_FILE_SIZE)
auth.py - Password hashing (hashlib) and token helpers (hmac)
models.py - Database helpers (init_db, CRUD for all 5 tables)
events.py - SSE event broadcaster (EventBroadcaster class with subscribe/publish)
api.py - Flask app with all routes (auth, projects, tasks, attachments, activity, SSE)
static/index.html - Main page with kanban board, activity feed, file upload
static/app.js - Frontend logic (auth, kanban, SSE client, file upload)
static/style.css - Full styling (kanban, modals, activity feed, file badges)
```
## IMPORTANT
- config.py exports: SECRET_KEY (str), DB_PATH (str), UPLOAD_DIR (str, default 'uploads'), MAX_FILE_SIZE (int, 10485760)
- auth.py exports: hash_password(password) → str, verify_password(password, hashed) → bool, generate_token(user_id, secret) → str, validate_token(token, secret) → int|None
- auth.py uses hashlib.sha256 for hashing and hmac for tokens — NOT bcrypt, NOT jwt
- events.py exports: EventBroadcaster class with methods subscribe() → queue, unsubscribe(queue), publish(event_type, data_dict)
- models.py uses raw sqlite3, NOT SQLAlchemy
- models.py exports FUNCTIONS (not classes): init_db(), plus CRUD for all 5 tables
- api.py imports from auth, models, events, AND config
- File uploads use Flask request.files and os module — NOT any upload library
- Do NOT create ORM model classes
"""
REALTIME_TASKS_JSON = [
{
"subject": "Create configuration module",
"description": (
"Create config.py with application constants. "
"Exports: SECRET_KEY = 'realtime-kanban-secret-2026' (str), "
"DB_PATH = 'realtime_kanban.db' (str), "
"UPLOAD_DIR = 'uploads' (str), "
"MAX_FILE_SIZE = 10485760 (int, 10MB in bytes). "
"Keep it simple — just these four constants."
),
"files": ["config.py"],
"sprint": "sprint-01",
"risk": "low",
"blocked_by": [],
},
{
"subject": "Create authentication module",
"description": (
"Create auth.py with password hashing and token helpers. "
"Import hashlib and hmac (stdlib only). "
"Functions: hash_password(password: str) → str using hashlib.sha256 hexdigest, "
"verify_password(password: str, hashed: str) → bool, "
"generate_token(user_id: int, secret: str) → str using hmac.new with sha256, "
"validate_token(token: str, secret: str) → int or None (returns user_id if valid). "
"Token format: '{user_id}:{hmac_signature}'."
),
"files": ["auth.py"],
"sprint": "sprint-01",
"risk": "low",
"blocked_by": [0],
},
{
"subject": "Create database models with 5 tables",
"description": (
"Create models.py with raw sqlite3 database helpers for 5 related tables. "
"Import DB_PATH from config: from config import DB_PATH. "
"Tables: users (id, username, password_hash, created_at), "
"projects (id, name, description, owner_id→users, created_at), "
"tasks (id, title, description, status, priority, project_id→projects, assignee_id→users, due_date, created_at), "
"attachments (id, filename, filepath, task_id→tasks, uploaded_by→users, created_at), "
"activity_log (id, action, entity_type, entity_id, user_id→users, details, created_at). "
"Enable PRAGMA foreign_keys = ON. "
"Functions: init_db(), "
"create_user(username, password_hash), get_user_by_username(username), "
"create_project(name, description, owner_id), get_projects(), "
"get_project_tasks(project_id, status=None, priority=None), "
"create_task(title, description, status, priority, project_id, assignee_id=None, due_date=None), "
"update_task(task_id, **kwargs), delete_task(task_id), get_project_stats(project_id), "
"create_attachment(filename, filepath, task_id, uploaded_by), get_task_attachments(task_id), delete_attachment(attachment_id), "
"log_activity(action, entity_type, entity_id, user_id=None, details=None), get_activity(project_id=None, limit=50). "
"Call init_db() at import time. "
"get_project_stats returns: {total, by_status: {todo, in_progress, done}, overdue_count, attachment_count}."
),
"files": ["models.py"],
"sprint": "sprint-01",
"risk": "low",
"blocked_by": [0],
},
{
"subject": "Create SSE event broadcaster",
"description": (
"Create events.py with a Server-Sent Events broadcasting system. "
"Class EventBroadcaster with: "
"__init__(self) — initialize empty list of subscriber queues, "
"subscribe(self) → queue.Queue — create and register a new queue, return it, "
"unsubscribe(self, q) — remove queue from subscribers, "
"publish(self, event_type: str, data: dict) — put formatted SSE message on all subscriber queues. "
"SSE format: 'event: {type}\\ndata: {json}\\n\\n'. "
"Use queue.Queue from stdlib for thread-safe fan-out. "
"Also export a module-level instance: broadcaster = EventBroadcaster()."
),
"files": ["events.py"],
"sprint": "sprint-01",
"risk": "low",
"blocked_by": [0],
},
{
"subject": "Create Flask API with all routes",
"description": (
"Create api.py with Flask app and all REST routes. "
"Import from auth: from auth import hash_password, verify_password, generate_token, validate_token. "
"Import from models: from models import (init_db, create_user, get_user_by_username, "
"create_project, get_projects, get_project_tasks, create_task, update_task, delete_task, "
"get_project_stats, create_attachment, get_task_attachments, delete_attachment, "
"log_activity, get_activity). "
"Import from events: from events import broadcaster. "
"Import from config: from config import SECRET_KEY, UPLOAD_DIR, MAX_FILE_SIZE. "
"Auth routes: POST /api/auth/register, POST /api/auth/login. "
"Project routes: GET/POST /api/projects. "
"Task routes: GET /api/projects/<id>/tasks, POST /api/tasks, PUT /api/tasks/<id>, DELETE /api/tasks/<id>. "
"Stats: GET /api/projects/<id>/stats. "
"Attachments: GET /api/tasks/<id>/attachments, POST /api/tasks/<id>/attachments (multipart), DELETE /api/attachments/<id>. "
"Activity: GET /api/activity (?project_id=&limit=50). "
"SSE: GET /api/events — streaming response with text/event-stream content type. "
"On task mutations, call broadcaster.publish() and log_activity(). "
"Serve static files from ./static/."
),
"files": ["api.py"],
"sprint": "sprint-01",
"risk": "low",
"blocked_by": [1, 2, 3],
},
{
"subject": "Create realtime kanban HTML page",
"description": (
"Create static/index.html — single page realtime kanban board. "
"Auth section: login/register forms (toggleable). "
"Project selector dropdown. "
"Kanban board: 3 columns (div.column#todo-column, div.column#in-progress-column, div.column#done-column). "
"Task cards: title, priority badge, assignee, due date, attachment count indicator. "
"Task detail modal: edit form, file upload input (type=file), attachment list with delete buttons. "
"Activity feed sidebar: scrollable list of recent actions. "
"New task form: title, description, priority, assignee, due date. "
"Link to app.js and style.css. "
"Include a hidden div#sse-status for connection status indicator."
),
"files": ["static/index.html"],
"sprint": "sprint-01",
"risk": "low",
"blocked_by": [2],
},
{
"subject": "Create realtime kanban CSS styling",
"description": (
"Create static/style.css — full styling for realtime kanban. "
"Kanban layout: flexbox 3-column board. "
"Cards: rounded corners, shadow, priority colors (low=green, medium=blue, high=orange, critical=red). "
"Modal: overlay with centered panel for task detail. "
"Activity feed sidebar: fixed right panel, scrollable. "
"File upload area: dashed border dropzone style. "
"Attachment list: small file icons with delete button. "
"Auth forms: centered. Responsive: stack columns on mobile, hide sidebar. "
"SSE status indicator: small dot (green=connected, red=disconnected)."
),
"files": ["static/style.css"],
"sprint": "sprint-01",
"risk": "low",
"blocked_by": [5],
},
{
"subject": "Create realtime kanban frontend JavaScript",
"description": (
"Create static/app.js — full frontend logic with SSE and file uploads. "
"Auth: register(), login(), logout(), store token in localStorage. "
"Projects: loadProjects(), selectProject(id). "
"Kanban: loadTasks(projectId), renderKanban(tasks), addTask(), "
"moveTask(taskId, newStatus), editTask(taskId), deleteTask(taskId). "
"SSE: connectSSE() using new EventSource('/api/events'), "
"handle 'task_updated'/'task_created'/'task_deleted' events to auto-refresh kanban. "
"File upload: uploadFile(taskId, fileInput) using FormData and fetch with multipart, "
"loadAttachments(taskId), deleteAttachment(attachmentId). "
"Activity: loadActivity(), renderActivityFeed(items). "
"Stats: loadStats(projectId). "
"Use fetch() with Authorization header. DOM manipulation for all UI updates."
),
"files": ["static/app.js"],
"sprint": "sprint-01",
"risk": "low",
"blocked_by": [4, 5],
},
]
REALTIME_EXPECTED_FILES = [
"config.py", "auth.py", "models.py", "events.py", "api.py",
"static/index.html", "static/app.js", "static/style.css",
]
# ── Scenario registry ──────────────────────────────────────────────────────
BENCHMARK_SCENARIOS = {
"expense-tracker": {
"spec": SPEC_MD,
"tasks": TASKS_JSON,
"expected_files": EXPECTED_FILES,
"name": "Expense Tracker",
"description": "Flask + SQLite + vanilla JS (5 tasks, 3 waves)",
},
"todo-app": {
"spec": TODO_SPEC_MD,
"tasks": TODO_TASKS_JSON,
"expected_files": TODO_EXPECTED_FILES,
"name": "Todo App",
"description": "FastAPI + SQLite + vanilla JS (4 tasks, 3 waves)",
},
"kanban-board": {
"spec": KANBAN_SPEC_MD,
"tasks": KANBAN_TASKS_JSON,
"expected_files": KANBAN_EXPECTED_FILES,
"name": "Kanban Board",
"description": "Flask + SQLite + auth + 3 tables (7 tasks, 4 waves) — HARD",
},
"realtime-kanban": {
"spec": REALTIME_SPEC_MD,
"tasks": REALTIME_TASKS_JSON,
"expected_files": REALTIME_EXPECTED_FILES,
"name": "Realtime Kanban",
"description": "Flask + SQLite + auth + SSE + uploads + 5 tables (8 tasks, 4 waves) — NIGHTMARE",
},
}
DEFAULT_SCENARIO = "expense-tracker"
# ── Display helpers ──────────────────────────────────────────────────────────
def _c(code: str, text: str) -> str:
"""ANSI color wrapper."""
codes = {"r": "91", "g": "92", "y": "93", "c": "96", "m": "95", "b": "1", "d": "2", "0": "0"}
return f"\033[{codes.get(code, '0')}m{text}\033[0m"
def section(title: str) -> None:
print(f"\n{_c('c', '─' * 70)}")
print(f" {_c('b', title)}")
print(f"{_c('c', '─' * 70)}")
def grade_color(grade: str) -> str:
"""Return ANSI-colored grade."""
if grade == "S":
return _c("m", "S")
if grade == "A":
return _c("g", "A")
if grade == "B":
return _c("c", "B")
if grade == "C":
return _c("y", "C")
return _c("r", grade)
def score_to_grade(score: float) -> str:
for threshold, grade in GRADE_THRESHOLDS:
if score >= threshold:
return grade
return "F"
def score_bar(score: float, width: int = 20) -> str:
"""Visual bar: ████████░░░░░░░░░░░░ 75%"""
filled = int(score / 100 * width)
empty = width - filled
if score >= 85:
color = "g"
elif score >= 60:
color = "y"
else:
color = "r"
return f"{_c(color, '█' * filled)}{_c('d', '░' * empty)} {score:.0f}%"
# ── Interface analysis (from benchmark_expense_tracker.py) ───────────────────
def extract_module_interface(py_path: Path) -> dict:
"""Extract public interface from a Python file using AST."""
if not py_path.exists():
return {"error": "file not found"}
try:
tree = ast.parse(py_path.read_text(encoding="utf-8", errors="replace"))
except SyntaxError as e:
return {"error": f"syntax error: {e}"}
interface = {"functions": {}, "classes": {}, "assignments": []}
for node in ast.iter_child_nodes(tree):
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
params = [a.arg for a in node.args.args if a.arg != "self"]
interface["functions"][node.name] = params
elif isinstance(node, ast.ClassDef):
methods = {}
for child in ast.iter_child_nodes(node):
if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)):
params = [a.arg for a in child.args.args if a.arg != "self"]
methods[child.name] = params
interface["classes"][node.name] = methods
elif isinstance(node, ast.Assign):
for target in node.targets:
if isinstance(target, ast.Name):
interface["assignments"].append(target.id)
return interface
def extract_imports(py_path: Path) -> list[dict]:
"""Extract import statements from a Python file."""
if not py_path.exists():
return []
try:
tree = ast.parse(py_path.read_text(encoding="utf-8", errors="replace"))
except SyntaxError:
return []
imports = []
for node in ast.walk(tree):
if isinstance(node, ast.ImportFrom) and node.module:
names = [alias.name for alias in node.names]
imports.append({"from": node.module, "names": names})
return imports