Repository navigation
Expand file tree
/
Copy pathstudy.py
More file actions
executable file
·2872 lines (2578 loc) · 119 KB
/
Copy pathstudy.py
File metadata and controls
executable file
·2872 lines (2578 loc) · 119 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
"""
Offline CLI multiple-choice quiz - bank-agnostic, session-based.
A "session" is a subdir of banks/ holding a tests.md file, e.g.
banks/linux/tests.md
banks/aws/tests.md
banks/windows-ad/tests.md
Drop a new banks/<name>/tests.md and it shows up automatically - no code change.
Per-session stats (right/wrong counters, a RECENT_N-slot shift register for weak-drill,
and a full ordered per-question attempt log 'history': [["YYYY-MM-DD HH:MM",
outcome], …] where outcome = 1 right / 0 wrong / "p" partial, scored as wrong)
live in results/<session>@<device>.json (one file per device, merged for display).
Bank format (per question):
## Test 1 - Title (N Q)
1. Question text? (Select 2)
- [ ] wrong - **[x] correct** - [ ] wrong
- *why explanation shown after you answer*
Usage:
study # menu: pick a session, then a test
study mybank # pick a test within mybank
study mybank 3 # run mybank Test 3
study mybank all # pool ALL of mybank's questions into one run
study mybank 3 shuffle # shuffle question order (options always shuffle)
study mybank weak # re-drill only un-cleared weak spots
study mybank new # drill only NEW/unseen Qs (never answered / edited)
study mybank all shuffle # exam-sim: whole bank, shuffled
study mybank history # show past runs + weak spots
study mybank practice_exam # 90 Q, 90 min, domain-weighted, /900 (menu p)
study set # list this host's settings (synced per-device)
study set end_summary off # e.g. hide the end-of-run WHY-review block
study subnet # subnetting practice drill (10 Qs, worked solutions)
study subnet 20 # …20 questions
study subnet history # past drill scores + most-missed /n
study subnet hard # hard drill: all /n, wildcards, hosts->prefix
study ref # print the subnetting table
study ref mybank # print a bank's quick ref (banks/<s>/ref.md)
study sync # commit+push THIS device's records, pull others'
study update # pull the engine, then your data repo
study --lint # validate every bank (broken questions)
In-quiz slash commands: /exit /skip /ref /flag [N] /sync /help (/sync, /help also at the menus)
"""
import glob
import hashlib
import json
import os
import random
import re
import socket
import subprocess
import sys
import tempfile
import time
import unicodedata
from datetime import datetime
import signal
try: # closing the terminal = a normal pause, not a lost run
signal.signal(signal.SIGHUP, lambda *_: (_ for _ in ()).throw(KeyboardInterrupt()))
except (AttributeError, ValueError):
pass
try:
# line editing for input(): arrow keys move the cursor instead of
# printing ^[[D, plus Home/End, Ctrl+A/E, backspace mid-line
import readline # noqa: F401
except ImportError:
pass
# ── paths / constants ───────────────────────────────────────────────────────
# realpath: works when run via a symlink (e.g. ~/.local/bin/study)
HERE = os.path.dirname(os.path.realpath(__file__)) # the engine (this repo)
CONF_FILE = os.path.join(os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config"),
"study", "config.toml")
def _data_dir():
"""Your data repo (banks + results): $STUDY_DATA, else config.toml data = "...",
else ~/.local/share/study. Kept apart from the engine so updates never touch it."""
if os.environ.get("STUDY_DATA"):
return os.path.expanduser(os.environ["STUDY_DATA"])
try:
for line in open(CONF_FILE, encoding="utf-8"):
m = re.match(r'\s*data\s*=\s*"([^"]+)"', line)
if m:
return os.path.expanduser(m.group(1))
except OSError:
pass
return os.path.join(os.environ.get("XDG_DATA_HOME") or os.path.expanduser("~/.local/share"), "study")
def _conf(key, default):
"""A key = value line from config.toml (strings in quotes, true/false bare)."""
try:
for line in open(CONF_FILE, encoding="utf-8"):
m = re.match(r'\s*' + key + r'\s*=\s*"?([^"#\n]*?)"?\s*(#.*)?$', line)
if m:
v = m.group(1).strip()
return {"true": True, "false": False}.get(v.lower(), v)
except OSError:
pass
return default
def _version():
try:
return open(os.path.join(HERE, "VERSION"), encoding="utf-8").read().strip()
except OSError:
return "?"
def _auto_update():
"""Once a day on launch: fast-forward the engine if upstream moved and the
checkout is clean, then restart on the new code. Silent on any failure.
Off with auto_update = false in config.toml or STUDY_NO_UPDATE=1."""
if os.environ.get("STUDY_NO_UPDATE") or _conf("auto_update", True) is False:
return
stamp = os.path.join(os.environ.get("XDG_CACHE_HOME") or os.path.expanduser("~/.cache"),
"study", "last_update_check")
try:
if time.time() - os.path.getmtime(stamp) < 86400:
return
except OSError:
pass
try:
os.makedirs(os.path.dirname(stamp), exist_ok=True)
q = dict(cwd=HERE, capture_output=True, text=True, timeout=8)
if subprocess.run(["git", "fetch", "-q"], **q).returncode:
return
open(stamp, "w").close()
behind = subprocess.run(["git", "rev-list", "--count", "HEAD..@{u}"], **q).stdout.strip()
dirty = subprocess.run(["git", "status", "--porcelain", "-uno"], **q).stdout.strip()
if behind in ("", "0") or dirty:
return
old = _version()
if subprocess.run(["git", "merge", "-q", "--ff-only", "@{u}"], **q).returncode:
return
print(f"{GRY}study updated {old} -> {_version()}{RST}", flush=True)
os.environ["STUDY_NO_UPDATE"] = "1"
os.execv(sys.executable, [sys.executable, os.path.realpath(__file__)] + sys.argv[1:])
except Exception:
return
DATA = _data_dir()
BANKS_DIR = os.path.join(DATA, "banks") # your own/private banks (win on a name clash)
SHIPPED_BANKS = os.path.join(HERE, "banks") # banks that ship with the engine
BANK_ROOTS = [BANKS_DIR] + ([SHIPPED_BANKS] if os.path.realpath(SHIPPED_BANKS) != os.path.realpath(BANKS_DIR) else [])
def bank_dir(session):
"""banks/<session> from the data repo if it has one, else the shipped copy."""
for root in BANK_ROOTS:
d = os.path.join(root, session)
if os.path.isfile(os.path.join(d, "tests.md")) or os.path.isdir(os.path.join(d, "drafts")):
return d
return os.path.join(BANKS_DIR, session)
REF_SESSION = None # bank whose ref.md /ref prints during a quiz
RUN_QS = [] # [(test_num, q)] of the current run, for /flag N
RUN_POS = 0 # current question number (1-based) in the run
RESULTS_DIR = os.path.join(DATA, "results")
# This device's tag - each machine writes only its OWN results file
# (results/<session>@<device>.json) so git push/pull never conflicts.
# Display merges every device's file back into one unified view.
# Override with QUIZ_DEVICE=name if the hostname is ugly/duplicated.
DEVICE = re.sub(r"[^A-Za-z0-9_-]", "-",
(os.environ.get("QUIZ_DEVICE") or socket.gethostname().split(".")[0]
or "device"))
LETTERS = "ABCDEFGHIJ" # option labels; lint flags questions with more
DEFAULT_PASS = 75 # % when a bank sets no pass mark
DEFAULT_MASTERY = 90 # % for "mastered" (green)
RECENT_N = 3 # weak retires after this many correct in a row
MENU_RUNS = 7 # past full-run scores shown per test in the menu
TITLE_MAX = 30 # menu test titles cut to this many cells (…)
NEW_ID_RE = re.compile(r"^T\d+:[0-9a-f]{12}$") # current qid format
# mock exams: bank -> question count, minutes, domain weights (% by the first
# char of each question's @obj tag), scaled pass mark (100-900 scale)
# mock exams: banks/<name>/exam.json, e.g.
# {"n": 90, "mins": 90, "pass": 750, "pbq": 5, "weights": {"1": 12, "2": 22}}
# question count, minutes, scaled pass mark (100-900), PBQs first, and domain
# weights (% by the first char of each question's @obj tag). No file = no mock.
def _load_exams():
out = {}
for f in [f for r in reversed(BANK_ROOTS) for f in glob.glob(os.path.join(r, "*", "exam.json"))]:
try:
j = json.load(open(f, encoding="utf-8"))
except (OSError, ValueError):
continue
if isinstance(j, dict):
out[os.path.basename(os.path.dirname(f))] = j
return out
EXAMS = _load_exams()
MOCK = {b: c for b, c in EXAMS.items()
if isinstance(c.get("n"), int) and isinstance(c.get("mins"), (int, float))
and isinstance(c.get("pass"), int) and isinstance(c.get("weights"), dict) and c["weights"]
and type(c.get("n")) is int and c["n"] > 0}
for _c in MOCK.values():
_c.setdefault("pbq", 0)
ANSI_RE = re.compile(r"\x1b\[[0-9;]*m")
# ANSI colours
GRN, YEL, RED, GRY, CYN, RST = (
"\033[92m", "\033[93m", "\033[91m", "\033[90m", "\033[96m", "\033[0m")
# ── per-host settings (synced) ──────────────────────────────────────────────
# Each machine has results/settings@<device>.json - tracked in git like the
# results files, so it syncs. A host reads only its OWN settings; defaults
# below fill any gaps. Change one with: study set <key> <value>
SETTINGS_PATH = os.path.join(RESULTS_DIR, f"settings@{DEVICE}.json")
DEFAULT_SETTINGS = {
# Show the end-of-run "── WHY you missed these ──" review block.
# The explanations already appear inline as you answer, so this is optional.
"end_summary": True,
}
def load_config():
"""This host's settings merged over DEFAULT_SETTINGS (bad file = defaults)."""
cfg = dict(DEFAULT_SETTINGS)
try:
with open(SETTINGS_PATH, encoding="utf-8") as f:
user = json.load(f)
if isinstance(user, dict):
cfg.update(user)
except (ValueError, OSError):
pass
return cfg
def save_config(cfg):
"""Write this host's settings file atomically."""
os.makedirs(RESULTS_DIR, exist_ok=True)
_atomic_write_json(SETTINGS_PATH, cfg)
CONFIG = load_config()
# ── sessions / banks ────────────────────────────────────────────────────────
def list_sessions():
"""Sorted session names: every banks/<name>/tests.md that exists."""
out = set()
for root in BANK_ROOTS:
try:
for name in os.listdir(root):
if os.path.isfile(os.path.join(root, name, "tests.md")):
out.add(name)
except OSError:
pass
return sorted(out)
def bank_path(session):
"""Path to a session's question bank: banks/<session>/tests.md."""
return os.path.join(bank_dir(session), "tests.md")
def results_path(session, device=None):
"""This device's own results file: results/<session>@<device>.json."""
return os.path.join(RESULTS_DIR, f"{session}@{device or DEVICE}.json")
def device_files(session):
"""Every device's results file for this session, plus a legacy
results/<session>.json if one exists (pre per-device layout)."""
out = []
legacy = os.path.join(RESULTS_DIR, f"{session}.json")
if os.path.exists(legacy):
out.append(legacy)
try:
for name in sorted(os.listdir(RESULTS_DIR)):
if name.startswith(f"{session}@") and name.endswith(".json"):
out.append(os.path.join(RESULTS_DIR, name))
except OSError:
pass
return out
def parse_bank(path, keep_empty=False):
"""Return {test_num: {"title", "questions", "passmark", "mastery"}}.
Thresholds: session defaults via top-of-file comments
<!-- passmark: 80 --> <!-- mastery: 95 -->
per-test overrides on the '## Test N - Title' line
<!-- pass: 90 --> <!-- master: 98 -->
Fallbacks: DEFAULT_PASS / DEFAULT_MASTERY.
keep_empty=True keeps option-less questions (lint uses it to flag them).
"""
with open(path, encoding="utf-8") as f:
lines = f.read().splitlines()
tests = {}
cur_test = None
cur_q = None
session_pass = DEFAULT_PASS
session_mastery = DEFAULT_MASTERY
pass_default_re = re.compile(r"<!--\s*passmark:\s*(\d+)\s*-->", re.I)
mastery_default_re = re.compile(r"<!--\s*mastery:\s*(\d+)\s*-->", re.I)
pass_test_re = re.compile(r"<!--\s*pass:\s*(\d+)\s*-->", re.I)
mastery_test_re = re.compile(r"<!--\s*master:\s*(\d+)\s*-->", re.I)
test_re = re.compile(r"^##\s+Test\s+(\d+)\s*-\s*(.*)$", re.I)
q_re = re.compile(r"^(\d+)\.\s+(.*)$")
opt_re = re.compile(r"\[([ xX])\]\s*(.+?)\s*(?=-\s*\[|$)")
note_re = re.compile(r"^\s*-?\s*\*(.+)\*\s*$")
typed_re = re.compile(r"^\s*-\s*\[=\]\s*(.+?)\s*$")
# multi-part PBQ part: - [p] prompt :: A opt · B opt = answer | alt
part_re = re.compile(r"^\s*-\s*\[p\]\s*(.+?)\s*$")
# objective tag + optional source id of the old question it replaces:
# - @1.4.ports ~5.3
obj_re = re.compile(r"^\s*-\s*@(\S+)(?:\s+~(\S+))?\s*$")
def parse_opts(text):
"""[(option_text, is_correct)] from one line of '- [ ] / - [x]' items."""
clean = text.replace("*", "")
return [(t.strip(), m.lower() == "x")
for m, t in opt_re.findall(clean) if t.strip()]
def flush_q():
"""Close the current question and append it to its test."""
nonlocal cur_q
if cur_test is not None and cur_q and (cur_q["options"] or keep_empty):
tests[cur_test]["questions"].append(cur_q)
cur_q = None
for line in lines:
# session-default thresholds (only before any test starts)
if cur_test is None:
pd = pass_default_re.search(line)
if pd:
session_pass = int(pd.group(1))
md = mastery_default_re.search(line)
if md:
session_mastery = int(md.group(1))
m = test_re.match(line)
if m:
flush_q()
n = int(m.group(1))
title = m.group(2).strip()
if "not yet captured" in title.lower():
cur_test = None
continue
# per-test overrides, then strip the comments out of the title
po = pass_test_re.search(title)
mo = mastery_test_re.search(title)
passmark = int(po.group(1)) if po else None
mastery = int(mo.group(1)) if mo else None
title = mastery_test_re.sub("", pass_test_re.sub("", title)).strip()
# drop a trailing "(N Q)" count - the menu appends the real count
title = re.sub(r"\s*\(\d+\s*Q\)\s*$", "", title, flags=re.I).strip()
cur_test = n
tests[n] = {"title": title, "questions": [],
"_passmark": passmark, "_mastery": mastery}
continue
if cur_test is None:
continue
# a '### ...' section (e.g. "### Test N key facts") ends the last
# question so its trailing bullets don't get slurped as its note
if line.lstrip().startswith("#"):
flush_q()
continue
nm = note_re.match(line)
# an unindented '- **summary**' bullet is a section key fact, not
# the last question's note (it used to overwrite that note)
if nm and line.startswith("- **") and cur_q is not None and cur_q["note"]:
continue
if nm and cur_q is not None and "[" not in line:
cur_q["note"] = nm.group(1).strip()
continue
m = q_re.match(line.strip())
if m and not line.strip().startswith("- "):
flush_q()
q = m.group(2).strip()
multi = "select" in q.lower()
cur_q = {"q": q, "options": [], "note": "", "multi": multi}
cur_q["options"].extend(parse_opts(line))
continue
om = obj_re.match(line)
if om and cur_q is not None:
cur_q["obj"] = om.group(1)
if om.group(2):
cur_q["src"] = om.group(2)
continue
pm = part_re.match(line)
if pm and cur_q is not None:
prompt, _, ans = pm.group(1).rpartition(" = ")
prompt, _, opts = prompt.partition(" :: ")
alts = [a.strip().strip("`") for a in ans.split(" | ") if a.strip()]
cur_q.setdefault("parts", []).append(
{"prompt": prompt.strip(), "opts": opts.strip(), "alts": alts})
cur_q["options"] = [("pbq", True)]
continue
tm = typed_re.match(line)
if tm and cur_q is not None:
alts = [a.strip().strip("`") for a in tm.group(1).split(" | ") if a.strip()]
cur_q["typed"] = alts
cur_q["options"] = [(alts[0], True)]
continue
if cur_q is not None and "[" in line:
cur_q["options"].extend(parse_opts(line))
flush_q()
# resolve each test's effective thresholds (override -> session default)
for t in tests.values():
t["passmark"] = t.pop("_passmark") or session_pass
t["mastery"] = t.pop("_mastery") or session_mastery
return tests
# ── stats (per session) ─────────────────────────────────────────────────────
_BANKS = {} # session -> parsed bank cache
def qid(test_num, q):
"""Stable id for a question: test + short hash of the FULL normalised text
(the old 40-char prefix let two Qs with the same opening share stats)."""
norm = " ".join(q["q"].lower().split())
return f"T{test_num}:{hashlib.sha1(norm.encode()).hexdigest()[:12]}"
def _bank(session):
"""Cached parse of a session's bank ({} if missing)."""
if session not in _BANKS:
try:
_BANKS[session] = parse_bank(bank_path(session))
except OSError:
_BANKS[session] = {}
return _BANKS[session]
def bank_ids(session):
"""Set of qids for questions CURRENTLY in the bank."""
return {qid(n, q) for n, t in _bank(session).items() for q in t["questions"]}
def _legacy_map(session):
"""old id (test + first 40 chars) -> [(test_num, question)] in the bank."""
mp = {}
for n, t in _bank(session).items():
for q in t["questions"]:
mp.setdefault(f"T{n}:{q['q'][:40]}", []).append((n, q))
return mp
def _rebuild_recent(st):
"""RECENT_N-slot register from the tail of history (full-correct = 1)."""
if st.get("history"):
st["recent"] = [1 if o == 1 else 0 for _, o in st["history"][-RECENT_N:]]
def _merge_stat(dst, src):
"""Fold src stats into dst (dst = newer data wins the register)."""
for k in ("seen", "right", "wrong"):
dst[k] = dst.get(k, 0) + src.get(k, 0)
dst["history"] = sorted(dst.get("history", []) + src.get("history", []),
key=lambda h: h[0])
dst["recent"] = (dst.get("recent") or src.get("recent") or [])[-RECENT_N:]
_rebuild_recent(dst)
dst.setdefault("q", src.get("q", ""))
def _split_shared(data, n, targets, st, title):
"""Several Qs shared ONE legacy id (same 40-char opening). Rebuild each
Q's own stats from the run log: every full run of test n answered each
of them once; the run's 'missed' list says which were wrong.
Returns {qid: stats}, or None if the log doesn't account for `st`."""
runs = [r for r in data.get("runs", []) if r.get("title") == title]
out = {}
for tn, q in targets:
s = {"seen": 0, "right": 0, "wrong": 0, "recent": [], "history": [],
"q": q["q"]}
for r in runs:
ok = q["q"][:60] not in r.get("missed", [])
s["seen"] += 1
s["right" if ok else "wrong"] += 1
s["recent"] = (s["recent"] + [1 if ok else 0])[-RECENT_N:]
s["history"].append([r["ts"][:16].replace("T", " "), 1 if ok else 0])
out[qid(tn, q)] = s
tot = {k: sum(s[k] for s in out.values()) for k in ("seen", "right", "wrong")}
if tot != {k: st.get(k, 0) for k in ("seen", "right", "wrong")}:
return None
return out
def migrate_ids(session, data):
"""Re-key legacy 40-char-prefix ids to full-text hash ids, in place.
Shared legacy ids are SPLIT per question from the run log (never cloned).
Keys that match nothing in the bank move to data['orphans'] once, so they
stop being rescanned and never count in stats. Returns True if changed."""
qs = data.get("questions", {})
legacy = [k for k in qs if not NEW_ID_RE.match(k)]
if not legacy:
return False
mp = _legacy_map(session)
tests = _bank(session)
orphans = data.setdefault("orphans", {})
for old in legacy:
st = qs.pop(old)
targets = mp.get(old)
if not targets:
orphans[old] = st # reworded/removed question
continue
if len(targets) == 1:
parts = {qid(*targets[0]): st}
else:
n = targets[0][0]
parts = _split_shared(data, n, targets, st, tests[n]["title"])
if parts is None: # can't reconstruct: give it to the Q whose
exact = [t for t in targets if t[1]["q"] == st.get("q")] # text was
parts = {qid(*(exact or targets)[0]): st} # recorded
for new, s in parts.items():
if new in qs:
_merge_stat(qs[new], s)
else:
qs[new] = s
return True
class CorruptResults(Exception):
"""A results file exists but can't be trusted (bad JSON / not a dict)."""
def _read_json(path):
"""None if missing. Raises CorruptResults if the file EXISTS but is
unreadable/unparseable/not a results object, so a bad file is never
mistaken for 'no history' and overwritten."""
if not os.path.exists(path):
return None
try:
with open(path, encoding="utf-8") as f:
data = json.load(f)
except ValueError as e: # JSONDecodeError + UnicodeDecodeError
raise CorruptResults(f"{path}: {e}")
if not isinstance(data, dict):
raise CorruptResults(f"{path}: not a results object")
return data
def _atomic_write_json(path, data):
"""Write to a unique temp file, fsync, rename over, fsync the dir - a
Ctrl-C/crash mid-write leaves the old file intact."""
d = os.path.dirname(path) or "."
fd, tmp = tempfile.mkstemp(dir=d, prefix=".tmp-", suffix=".json")
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
f.flush()
os.fsync(f.fileno())
os.replace(tmp, path)
except BaseException:
if os.path.exists(tmp):
os.unlink(tmp)
raise
try:
dfd = os.open(d, os.O_RDONLY)
try:
os.fsync(dfd)
finally:
os.close(dfd)
except OSError:
pass
def load_own(session):
"""Only THIS device's file - what run() mutates and saves back.
Never load the merged blob here or stats double-count after a sync.
A corrupt OWN file aborts (saving over it would wipe history)."""
path = results_path(session)
try:
data = _read_json(path) or {}
except CorruptResults as e:
sys.exit(f"{RED}corrupt results file {e}\nNot touching it. "
f"Restore with: git checkout -- {os.path.relpath(path, DATA)}{RST}")
data.setdefault("runs", [])
data.setdefault("questions", {})
data.setdefault("tests", {})
migrate_ids(session, data) # persisted on next save
return data
def load_results(session):
"""Unified read across ALL devices (own + synced peers) for display.
Counters sum; history concatenates + sorts by timestamp; the RECENT_N-slot
'recent' register is REBUILT from the merged history's last RECENT_N outcomes
(not file mtime, which git pull rewrites). A corrupt PEER file (half
pull, conflict markers) is warned about and skipped, never fatal."""
files = device_files(session)
merged = {"runs": [], "questions": {}, "tests": {}}
fallback_ts = {}
own = os.path.abspath(results_path(session))
for p in files:
try:
d = _read_json(p)
except CorruptResults as e:
if os.path.abspath(p) == own:
load_own(session) # aborts with restore instructions
print(f"{YEL}warning: skipping unreadable peer file {e}{RST}",
file=sys.stderr)
continue
if not isinstance(d, dict):
continue
migrate_ids(session, d) # in-memory only; peers' files untouched
merged["runs"].extend(d.get("runs", []))
newest = max((r.get("ts", "") for r in d.get("runs", [])), default="")
for qidk, st in d.get("questions", {}).items():
m = merged["questions"].setdefault(
qidk, {"seen": 0, "right": 0, "wrong": 0, "recent": [],
"history": [], "q": st.get("q", "")})
m["seen"] += st.get("seen", 0)
m["right"] += st.get("right", 0)
m["wrong"] += st.get("wrong", 0)
m["history"].extend(st.get("history", []))
# no-history legacy entries: register from the device that
# practised most recently (by run timestamp, not file order)
if st.get("recent") and newest >= fallback_ts.get(qidk, ""):
m["_recent_fallback"] = st["recent"]
fallback_ts[qidk] = newest
if st.get("q"):
m["q"] = st["q"]
for tnum, ts in d.get("tests", {}).items():
m = merged["tests"].setdefault(tnum, {})
if ts.get("last"):
m["last"] = max(ts["last"], m.get("last", ""))
merged["runs"].sort(key=lambda r: r.get("ts", ""))
for m in merged["questions"].values():
m["history"].sort(key=lambda h: h[0]) # chronological across devices
fb = m.pop("_recent_fallback", [])
if m["history"]:
m["recent"] = [1 if o == 1 else 0 for _, o in m["history"][-RECENT_N:]]
else: # legacy entries with no history log
m["recent"] = fb[-RECENT_N:]
return merged
def save_results(session, data):
"""Write only this device's own file (atomically)."""
os.makedirs(RESULTS_DIR, exist_ok=True)
_atomic_write_json(results_path(session), data)
def is_weak(st):
"""Weak = ever missed AND last RECENT_N outcomes not all fully-correct.
'recent' is a RECENT_N-slot shift register (1=fully correct, 0=wrong/
partial): RECENT_N in a row retires it; a later miss re-arms it."""
return st.get("wrong", 0) > 0 and st.get("recent", [])[-RECENT_N:] != [1] * RECENT_N
def fmt_date(iso):
"""'2026-01-28' -> '28jan26'."""
if not iso:
return None
try:
day = datetime.strptime(iso.replace("T", " ").split()[0], "%Y-%m-%d")
return day.strftime("%d%b%y").lower()
except (ValueError, IndexError):
return None
def score_cell(avg, passmark, mastery=DEFAULT_MASTERY):
"""Colour a rolling avg: <pass red, pass..<mastery orange, >=mastery green."""
if avg is None:
return f"{GRY} - {RST}"
if avg >= mastery:
col = GRN
elif avg >= passmark:
col = YEL # orange-ish
else:
col = RED
return f"{col}{avg:>3d}%{RST}"
# ── lint ────────────────────────────────────────────────────────────────────
def lint():
"""Validate every bank's structure; return 1 if any blocking problem."""
sessions = list_sessions()
if not sessions:
print(f"{RED}No banks found under {BANKS_DIR}{RST}")
return 1
problems = 0
for s in sessions:
tests = parse_bank(bank_path(s), keep_empty=True)
print(f"\n{CYN}{s}{RST} ({len(tests)} tests)")
if not tests:
print(f" {RED}✗ no tests parsed{RST}")
problems += 1
continue
for n in sorted(tests):
t = tests[n]
qs = t["questions"]
issues = []
seen_ids = {}
for i, q in enumerate(qs, 1):
ncorrect = sum(1 for _, c in q["options"] if c)
if q.get("parts"):
for j, pt in enumerate(q["parts"], 1):
if not pt["alts"] or not pt["prompt"]:
issues.append(f"Q{i}: part {j} missing prompt or '= answer'")
elif pt["opts"] and not all(
re.fullmatch(r"[a-j]+", a.lower()) for a in pt["alts"]):
issues.append(f"Q{i}: part {j} has options but a non-letter answer")
elif q.get("typed"):
pass
elif not q["options"]:
issues.append(f"Q{i}: no options")
elif ncorrect == 0:
issues.append(f"Q{i}: no correct answer marked")
elif len(q["options"]) < 2:
issues.append(f"Q{i}: <2 options")
if not q.get("typed") and len(q["options"]) > len(LETTERS):
issues.append(f"Q{i}: too many options (max {len(LETTERS)})")
k = qid(n, q)
if k in seen_ids:
issues.append(f"Q{i}: duplicate question text (same as Q{seen_ids[k]})")
seen_ids.setdefault(k, i)
if not q["note"]:
issues.append(f"Q{i}: no *why* note")
status = f"{GRN}ok{RST}" if not issues else f"{RED}{len(issues)} issue(s){RST}"
print(f" Test {n:<2} {len(qs):>2} Q {status}")
for msg in issues:
sev = RED if any(w in msg for w in ("no correct", "no options", "part ",
"too many", "duplicate")) else YEL
print(f" {sev}- {msg}{RST}")
if sev == RED:
problems += 1
if problems:
print(f"\n{RED}✗ {problems} blocking problem(s){RST}")
else:
print(f"\n{GRN}✓ all banks valid{RST}")
return 1 if problems else 0
# ── quiz run ────────────────────────────────────────────────────────────────
RESUME_PATH = os.path.join(RESULTS_DIR, f"resume@{DEVICE}.json")
def _resume_own():
try:
d = _read_json(RESUME_PATH)
except CorruptResults as e:
print(f"{YEL}⚠ paused-run file unreadable, starting it fresh: {e}{RST}")
d = None
if not isinstance(d, dict):
d = {}
d.setdefault("active", {})
d.setdefault("consumed", [])
return d
def _resume_all():
"""Paused runs from EVERY device (synced), minus any a device has consumed.
Returns {key: state}, newest state per key."""
files = glob.glob(os.path.join(RESULTS_DIR, "resume@*.json"))
docs = []
for f in files:
try:
d = _read_json(f)
except CorruptResults as e:
print(f"{YEL}⚠ skipping unreadable paused-run file: {e}{RST}")
continue
if isinstance(d, dict):
docs.append(d)
gone = {u for d in docs for u in d.get("consumed", [])}
out = {}
for d in docs:
for k, st in d.get("active", {}).items():
if st.get("uid") in gone:
continue
if k not in out or st.get("ts", "") > out[k].get("ts", ""):
out[k] = st
return out
def _resume_consume(key, uid):
d = _resume_own()
d["active"].pop(key, None)
if uid and uid not in d["consumed"]:
d["consumed"] = (d["consumed"] + [uid])[-300:]
os.makedirs(RESULTS_DIR, exist_ok=True)
_atomic_write_json(RESUME_PATH, d)
def _resume_put(key, state):
d = _resume_own()
d["active"][key] = state
os.makedirs(RESULTS_DIR, exist_ok=True)
_atomic_write_json(RESUME_PATH, d)
def _jsonable(x):
if isinstance(x, (set, frozenset)):
return sorted(x)
if isinstance(x, (list, tuple)):
return [_jsonable(v) for v in x]
if isinstance(x, dict):
return {k: _jsonable(v) for k, v in x.items()}
return x
def run_key(session, test_num_of, weak_only, unseen_only, mock):
if mock:
base = "mock"
elif test_num_of:
base = f"T{test_num_of}"
else:
base = "all"
flags = "".join(f"+{n}" for n, on in (("weak", weak_only), ("new", unseen_only)) if on)
return f"{session}:{base}{flags}"
def _fmt_secs(t):
t = int(t)
h, m, sec = t // 3600, t % 3600 // 60, t % 60
return f"{h}h {m:02d}m {sec:02d}s" if h else f"{m}m {sec:02d}s"
Q_CAP = 300 # max secs one question can add to the run timer
def _flag_cmd(low):
"""/flag or /flag N inside a quiz. True if it was a /flag command."""
m = re.fullmatch(r"/f(?:lag)?\s*(\d*)", low)
if not m:
return False
n = m.group(1)
if not n:
n = input(f" {YEL}Which question number to flag? "
f"(Enter = this one, Q{RUN_POS}) {RST}").strip() or str(RUN_POS)
if not n.isdigit() or not 1 <= int(n) <= min(RUN_POS, len(RUN_QS)):
print(f" {YEL}pick a question you've seen: 1–{RUN_POS}{RST}")
return True
why = input(f" {YEL}What's weird? (optional, Enter to skip) {RST}").strip()
tn, q = RUN_QS[int(n) - 1]
path = os.path.join(RESULTS_DIR, f"flags@{DEVICE}.json")
d = _read_json(path) if os.path.exists(path) else {}
d.setdefault("flags", []).append({"ts": datetime.now().isoformat(timespec="seconds"), "bank": REF_SESSION,
"test": tn, "id": qid(tn, q), "q": q["q"][:200], "why": why,
"fixed": False})
os.makedirs(RESULTS_DIR, exist_ok=True)
_atomic_write_json(path, d)
print(f" {GRN}⚑ flagged Q{n} (Test {tn}) - 'study flags' lists them{RST}")
return True
def cmd_flags():
"""List open flagged questions from every device."""
out = []
for f in sorted(glob.glob(os.path.join(RESULTS_DIR, "flags@*.json"))):
d = _read_json(f)
dev = os.path.basename(f)[6:-5]
for e in d.get("flags", []):
if not e.get("fixed"):
out.append((e.get("ts", ""), dev, e))
if not out:
print(f"{GRN}No open flags.{RST}")
return 0
for ts, dev, e in sorted(out, key=lambda x: x[0]):
print(f"{YEL}⚑{RST} {ts[:16]} {GRY}{dev}{RST} {e.get('bank')} T{e.get('test')} "
f"{e.get('q', '')[:90]}")
if e.get("why"):
print(f" {CYN}› {e['why']}{RST}")
print(f"{GRY}{len(out)} open flag(s){RST}")
return 0
class Quit(Exception):
"""Raised by ask() on /exit - ends a run but still saves it."""
def part_item(prompt):
"""'Incident 2 actor' / 'Control 3 (...)' -> 2 / 3: the numbered stem
item a PBQ part is about, or None."""
m = re.match(r"[A-Z][a-z]+ (\d+)\b", prompt)
return m.group(1) if m else None
def show_stem(stem, hl=None):
"""A stem may embed command output: '¶' = newline, shown as an
indented block (grey) so ipconfig/show output reads like a terminal.
hl = item number to highlight (the line starting with that number)."""
if "¶" not in stem:
return stem
head, *body = stem.split("¶")
# an inline option list 'A foo · B bar · C baz' -> one option per line
out = []
for ln in body:
if LETTER_OPTS_RE.match(ln):
out += [f" {L}) {t}" for L, t in
re.findall(r"([A-J]) (.+?)(?= · [A-J] |$)", ln.strip())]
else:
out.append(ln)
def fmt(ln):
if hl and re.match(rf"\s*{hl}\s", ln):
return f" {YEL}▶{RST} {YEL}{ln.strip()}{RST}"
return f" {ln.rstrip()}"
block = "\n".join(fmt(ln) for ln in out)
return f"{head.rstrip()}\n{block}"
# IOS shorthand the exam/IOS accept interchangeably; typed answers compare
# after expansion, so 'int gi0/20; shut' == 'interface g0/20; shutdown'
IOS_HEADS = {"interface", "int", "shutdown", "shut", "no", "access-list",
"copy", "write", "wr", "line", "ip", "switchport", "show", "sh",
"hostname", "enable", "username", "vlan", "router", "network",
"spanning-tree", "crypto", "logging", "snmp-server", "ntp",
"transport", "channel-group", "description", "service",
"conf", "configure"}
IOS_WORDS = {"int": "interface", "shut": "shutdown", "sh": "show",
"run": "running-config", "start": "startup-config",
"conf": "configure", "t": "terminal", "wr": "write",
"mem": "memory", "br": "brief", "https": "443", "http": "80",
"ssh": "22", "telnet": "23", "www": "80", "domain": "53"}
IFACE_RE = re.compile(r"^(gigabitethernet|gig|gi|g|fastethernet|fa|f|"
r"tengigabitethernet|te|ethernet|eth|e)(\d.*)$", re.I)
IFACE_FULL = {"g": "gigabitethernet", "f": "fastethernet", "t": "tengigabitethernet",
"e": "ethernet"}
def ios_norm(toks):
out = []
for i, w in enumerate(toks):
lw = w.lower()
if lw == "vlan" and i + 1 < len(toks) and toks[i + 1].isdigit() and \
i and toks[i - 1].lower() in ("interface", "int"):
continue # 'interface vlan 30' == 'interface vlan30'
if i and toks[i - 1].lower() == "vlan" and lw.isdigit() and \
i > 1 and toks[i - 2].lower() in ("interface", "int"):
out.append("vlan" + lw)
continue
m = IFACE_RE.match(lw)
if m:
out.append(IFACE_FULL[m.group(1)[0]] + m.group(2))
continue
if lw in ("https", "http", "ssh", "telnet", "www", "domain") and \
not (i and toks[i - 1].lower() == "eq"):
out.append(w) # only port keywords after 'eq' map
continue
if lw == "t" and not (i and toks[i - 1].lower() in ("conf", "configure")):
out.append(w)
continue
out.append(IOS_WORDS.get(lw, w))
# 'host X' == 'X 0.0.0.0' in ACLs
j = 0
res = []
while j < len(out):
if out[j].lower() == "host" and j + 1 < len(out):
res += [out[j + 1], "0.0.0.0"]
j += 2
continue
res.append(out[j])
j += 1
# 'write' alone == 'write memory'
res = [x for k, x in enumerate(res)]
if res[:1] == ["write"] and (len(res) == 1 or res[1] == ";"):
res.insert(1, "memory")
return res
WIN_CMDS = {"ping", "tracert", "pathping", "ipconfig", "netstat", "nslookup", "arp",
"route", "netsh", "nbtstat", "getmac", "gpupdate", "gpresult", "robocopy", "net"}
# Linux iproute2 accepts any unambiguous prefix: ip a / addr / address, ip n / neigh / neighbour,
# show = s = list = ls. Only applied after `ip` (or `sudo ip`), and only when the next
# word is a Linux object, so Cisco's `ip route 0.0.0.0 ...` and `ip helper-address` are untouched.
IP2_OBJ = {"a": "address", "ad": "address", "add": None, "addr": "address", "addre": "address",
"addres": "address", "address": "address",
"l": "link", "li": "link", "lin": "link", "link": "link",
"n": "neighbour", "ne": "neighbour", "nei": "neighbour", "neigh": "neighbour",
"neighbor": "neighbour", "neighbour": "neighbour",
"r": "route", "ro": "route", "rou": "route", "rout": "route", "route": "route"}
IP2_VERB = {"s": "show", "sh": "show", "sho": "show", "show": "show", "list": "show",
"ls": "show", "lst": "show", "a": "add", "ad": "add", "add": "add",
"d": "delete", "del": "delete", "delete": "delete", "f": "flush", "flush": "flush"}
def linux_ip_norm(toks):
lo = [t.lower() for t in toks]
i = 1 if lo[:1] == ["sudo"] else 0
if lo[i:i + 1] != ["ip"] or len(lo) < i + 2:
return toks
obj = IP2_OBJ.get(lo[i + 1])