Skip to content

ZeKaiNie/universal-examprep-skill / full

universal-exam-cram-coach-full

Verified

帮助学生在临考前进行结构化极速复习:解析课程资料/大纲/重点,按章节生成 wiki 知识库与标准题库,组织针对性刷题与判分,并记录复习进度和错题。当用户即将考试、需要快速复习计划、练习题、错题复盘或考前小抄时使用(关键词:期末/备考/复习/刷题/划重点/错题;exam, cram, study plan, quiz, review)。不适用于长期学习规划、与考试无关的写作或编程任务。

FileKindSize
.gitattributesother1.5 KB
.github/workflows/ci.ymlconfig1.9 KB
.gitignoreother659 B
AGENTS.mdmarkdown38.8 KB
CHANGELOG.en.mdmarkdown25.5 KB
CHANGELOG.mdmarkdown20.5 KB
CONTRIBUTING.mdmarkdown5.1 KB
CONTRIBUTING.zh.mdmarkdown4.9 KB
LICENSEother1.0 KB
README.mdmarkdown24.5 KB
README.zh.mdmarkdown22.8 KB
SKILL.mdskill md10.4 KB
assets/exam-panic.pngbinary934.2 KB
benchmark/.gitignoreother1.2 KB
benchmark/README.en.mdmarkdown12.7 KB
benchmark/README.mdmarkdown10.8 KB
benchmark/REPORT.en.mdmarkdown7.1 KB
benchmark/REPORT.mdmarkdown6.4 KB
benchmark/aggregate_matrix.pyscript16.3 KB
benchmark/behavior_smoke/README.en.mdmarkdown9.9 KB
benchmark/behavior_smoke/README.mdmarkdown7.4 KB
benchmark/behavior_smoke/fixtures/mini_course/references/assets/venn_prompt.svgother677 B
benchmark/behavior_smoke/fixtures/mini_course/references/quiz_bank.jsonconfig4.5 KB
benchmark/behavior_smoke/fixtures/mini_course/references/wiki/ch1_stack_queue.mdmarkdown447 B
benchmark/behavior_smoke/fixtures/mini_course/references/wiki/ch2_trees.mdmarkdown493 B
benchmark/behavior_smoke/fixtures/mini_course/study_plan.mdmarkdown550 B
benchmark/behavior_smoke/fixtures/mini_course/study_progress.mdmarkdown429 B
benchmark/behavior_smoke/fixtures/mini_course/study_state.jsonconfig390 B
benchmark/behavior_smoke/fixtures/mini_course_nostate/references/assets/venn_prompt.svgother677 B
benchmark/behavior_smoke/fixtures/mini_course_nostate/references/quiz_bank.jsonconfig3.2 KB
benchmark/behavior_smoke/fixtures/mini_course_nostate/references/wiki/ch1_stack_queue.mdmarkdown447 B
benchmark/behavior_smoke/fixtures/mini_course_nostate/references/wiki/ch2_trees.mdmarkdown493 B
benchmark/behavior_smoke/fixtures/mini_course_nostate/study_plan.mdmarkdown550 B
benchmark/behavior_smoke/fixtures/mini_course_nostate/study_progress.mdmarkdown429 B
benchmark/behavior_smoke/mock/sample_outputs/artifact_mode_chat_auto_pdf_bad.txtmarkdown433 B
benchmark/behavior_smoke/mock/sample_outputs/artifact_mode_chat_good.txtmarkdown462 B
benchmark/behavior_smoke/mock/sample_outputs/artifact_mode_chat_not_persisted_bad.txtmarkdown186 B
benchmark/behavior_smoke/mock/sample_outputs/artifact_mode_one_shot_good.txtmarkdown490 B
benchmark/behavior_smoke/mock/sample_outputs/artifact_mode_one_shot_persist_bad.txtmarkdown605 B
benchmark/behavior_smoke/mock/sample_outputs/artifact_mode_one_shot_probe_error_bad.txtmarkdown507 B
benchmark/behavior_smoke/mock/sample_outputs/artifact_mode_visual_native_good.txtmarkdown495 B
benchmark/behavior_smoke/mock/sample_outputs/artifact_mode_visual_preflight_failed_bad.txtmarkdown487 B
benchmark/behavior_smoke/mock/sample_outputs/artifact_mode_visual_subscription_guess_bad.txtmarkdown507 B
benchmark/behavior_smoke/mock/sample_outputs/hint_skip_offer.txtmarkdown349 B
benchmark/behavior_smoke/mock/sample_outputs/language_ask_good.txtmarkdown461 B
benchmark/behavior_smoke/mock/sample_outputs/language_ask_missing_line.txtmarkdown270 B
benchmark/behavior_smoke/mock/sample_outputs/language_ask_unglossed.txtmarkdown211 B
benchmark/behavior_smoke/mock/sample_outputs/language_persist_good.txtmarkdown216 B
benchmark/behavior_smoke/mock/sample_outputs/language_persist_noncanonical.txtmarkdown157 B
benchmark/behavior_smoke/mock/sample_outputs/language_urgent_bilingual.txtmarkdown261 B
benchmark/behavior_smoke/mock/sample_outputs/language_urgent_bilingual_explicit.txtmarkdown372 B
benchmark/behavior_smoke/mock/sample_outputs/language_urgent_bilingual_negated.txtmarkdown306 B
benchmark/behavior_smoke/mock/sample_outputs/language_urgent_question.txtmarkdown224 B
benchmark/behavior_smoke/mock/sample_outputs/language_urgent_silent.txtmarkdown364 B
benchmark/behavior_smoke/mock/sample_outputs/language_urgent_wrong_language.txtmarkdown262 B
benchmark/behavior_smoke/mock/sample_outputs/notebook_persist_chat_only.txtmarkdown952 B
benchmark/behavior_smoke/mock/sample_outputs/notebook_persist_good.txtmarkdown744 B
benchmark/behavior_smoke/mock/sample_outputs/progress_after_confusion.mdmarkdown395 B
benchmark/behavior_smoke/mock/sample_outputs/progress_after_mistake.mdmarkdown403 B
benchmark/behavior_smoke/mock/sample_outputs/provenance_answer.txtmarkdown492 B
benchmark/behavior_smoke/mock/sample_outputs/quiz_output_good.txtmarkdown351 B
benchmark/behavior_smoke/mock/sample_outputs/quiz_output_invented.txtmarkdown317 B
benchmark/behavior_smoke/mock/sample_outputs/resume_message.txtmarkdown224 B
benchmark/behavior_smoke/mock/sample_outputs/scope_override_good.txtmarkdown258 B
benchmark/behavior_smoke/mock/sample_outputs/scope_override_missing.txtmarkdown127 B
benchmark/behavior_smoke/mock/sample_outputs/teaching_template_ai_answer_good.txtmarkdown1.2 KB
benchmark/behavior_smoke/mock/sample_outputs/teaching_template_formula_first.txtmarkdown1.1 KB
benchmark/behavior_smoke/mock/sample_outputs/teaching_template_good.txtmarkdown1.2 KB
benchmark/behavior_smoke/mock/sample_outputs/teaching_template_liberal_good.txtmarkdown1.4 KB
benchmark/behavior_smoke/mock/sample_outputs/teaching_template_missing_warn.txtmarkdown608 B
benchmark/behavior_smoke/mock/sample_outputs/teaching_template_no_source.txtmarkdown1.1 KB
benchmark/behavior_smoke/mock/sample_outputs/teaching_template_optin_closers.txtmarkdown1.5 KB
benchmark/behavior_smoke/mock/sample_outputs/teaching_template_skip_ask.txtmarkdown948 B
benchmark/behavior_smoke/mock/sample_outputs/teaching_template_unlabeled_source.txtmarkdown517 B
benchmark/behavior_smoke/mock/sample_outputs/teaching_template_unsolicited_closers.txtmarkdown1.5 KB
benchmark/behavior_smoke/mock/sample_outputs/teaching_template_warn_title.txtmarkdown581 B
benchmark/behavior_smoke/mock/sample_outputs/time_budget_1day_bad.txtmarkdown340 B
benchmark/behavior_smoke/mock/sample_outputs/time_budget_1day_bank_checkpoint.txtmarkdown341 B
benchmark/behavior_smoke/mock/sample_outputs/time_budget_1day_good.txtmarkdown695 B
benchmark/behavior_smoke/mock/sample_outputs/visual_first_answer_after_prompt.txtmarkdown264 B
benchmark/behavior_smoke/mock/sample_outputs/visual_first_answer_before_prompt.txtmarkdown264 B
benchmark/behavior_smoke/mock/sample_outputs/visual_first_answer_side_first.txtmarkdown261 B
benchmark/behavior_smoke/mock/sample_outputs/visual_first_answer_text_before_prompt.txtmarkdown243 B
benchmark/behavior_smoke/mock/sample_outputs/visual_first_good.txtmarkdown232 B
benchmark/behavior_smoke/mock/sample_outputs/visual_first_missing_asset.txtmarkdown182 B
benchmark/behavior_smoke/mock/sample_outputs/visual_first_path_only.txtmarkdown163 B
benchmark/behavior_smoke/mock/sample_outputs/visual_first_prose_before_image.txtmarkdown234 B
benchmark/behavior_smoke/mock/sample_outputs/visual_first_question_label_late_asset.txtmarkdown250 B
benchmark/behavior_smoke/mock/sample_outputs/visual_first_unlabeled_solution_before_prompt.txtmarkdown233 B
benchmark/behavior_smoke/mock/sample_outputs/visual_first_unsafe_url.txtmarkdown178 B
benchmark/behavior_smoke/mock/sample_outputs/window_recheck_bad.txtmarkdown346 B
benchmark/behavior_smoke/mock/sample_outputs/window_recheck_good.txtmarkdown665 B
benchmark/behavior_smoke/mock/sample_outputs/window_recheck_recall_only_bad.txtmarkdown333 B
benchmark/behavior_smoke/mock/sample_outputs/window_recheck_test_good.txtmarkdown580 B
benchmark/behavior_smoke/mock/sample_outputs/workspace_confirm_good.txtmarkdown797 B
benchmark/behavior_smoke/mock/sample_outputs/workspace_confirm_silent.txtmarkdown453 B
benchmark/behavior_smoke/mock/sample_outputs/zero_basic_explain.txtmarkdown1.2 KB
benchmark/behavior_smoke/mock/sample_outputs/zero_basic_legacy_only.txtmarkdown442 B
benchmark/behavior_smoke/mock/sample_transcript.jsonlother517 B
benchmark/behavior_smoke/mock/state_after_confusion.jsonconfig203 B
benchmark/behavior_smoke/mock/state_after_mistake.jsonconfig215 B
benchmark/behavior_smoke/run_behavior_smoke.pyscript97.2 KB
benchmark/behavior_smoke/scenarios.jsonconfig12.7 KB
benchmark/calibrate.pyscript7.3 KB
benchmark/calibrate_matrix.pyscript20.0 KB
benchmark/calibration/README.en.mdmarkdown3.2 KB
benchmark/calibration/README.mdmarkdown2.6 KB
benchmark/calibration/kappa_n24_summary.jsonconfig1.5 KB
benchmark/config.example.jsonconfig431 B
benchmark/config.matrix.example.jsonconfig1.1 KB
benchmark/docs/coverage-matrix.en.mdmarkdown17.6 KB
benchmark/docs/coverage-matrix.mdmarkdown15.2 KB
benchmark/docs/img/hard_algo_correct_en.svgother2.7 KB
benchmark/docs/img/hard_algo_correct_zh.svgother2.7 KB
benchmark/docs/img/hard_algo_hallu_en.svgother2.7 KB
benchmark/docs/img/hard_algo_hallu_zh.svgother2.7 KB
benchmark/docs/img/hard_psyc_correct_en.svgother2.7 KB
benchmark/docs/img/hard_psyc_correct_zh.svgother2.7 KB
benchmark/docs/img/hard_psyc_hallu_en.svgother2.7 KB
benchmark/docs/img/hard_psyc_hallu_zh.svgother2.7 KB
benchmark/docs/img/oos_algo_abst_en.svgother2.7 KB
benchmark/docs/img/oos_algo_abst_zh.svgother2.7 KB
benchmark/docs/img/oos_psyc_abst_en.svgother2.7 KB
benchmark/docs/img/oos_psyc_abst_zh.svgother2.7 KB
benchmark/docs/img/realexam_algo_correct_en.svgother2.7 KB
benchmark/docs/img/realexam_algo_correct_zh.svgother2.7 KB
benchmark/docs/judge-calibration.en.mdmarkdown13.1 KB
benchmark/docs/judge-calibration.mdmarkdown9.9 KB
benchmark/docs/materials_sources.en.mdmarkdown3.2 KB
benchmark/docs/materials_sources.mdmarkdown2.7 KB
benchmark/docs/matrix_pipeline.en.mdmarkdown9.5 KB
benchmark/docs/matrix_pipeline.mdmarkdown8.4 KB
benchmark/docs/related_benchmarks.en.mdmarkdown5.5 KB
benchmark/docs/related_benchmarks.mdmarkdown4.6 KB
benchmark/docs/running-real-runs.en.mdmarkdown10.0 KB
benchmark/docs/running-real-runs.mdmarkdown8.0 KB
benchmark/docs/test_tiers.en.mdmarkdown7.7 KB
benchmark/docs/test_tiers.mdmarkdown6.8 KB
benchmark/docs/testing-audit.en.mdmarkdown17.2 KB
benchmark/docs/testing-audit.mdmarkdown14.6 KB
benchmark/docs/testing-walkthrough.en.mdmarkdown23.5 KB
benchmark/docs/测试流程详解.mdmarkdown19.0 KB
benchmark/drift/README.en.mdmarkdown14.6 KB
benchmark/drift/README.mdmarkdown12.3 KB
benchmark/drift/convert_session_log.pyscript12.9 KB
benchmark/drift/docs/live_agent_pilot.mdmarkdown6.6 KB
benchmark/drift/fixtures/live_logs/good_session.expected.jsonlother1.5 KB
benchmark/drift/fixtures/live_logs/good_session.mdmarkdown1.6 KB
benchmark/drift/fixtures/live_logs/live_smoke_golden.jsonlother2.2 KB
benchmark/drift/fixtures/live_logs/live_smoke_golden.mdmarkdown2.3 KB
benchmark/drift/fixtures/mini_course_long/references/quiz_bank.jsonconfig1.3 KB
benchmark/drift/fixtures/mini_course_long/references/wiki/ch1_stack_queue.mdmarkdown541 B
benchmark/drift/fixtures/mini_course_long/references/wiki/ch2_trees.mdmarkdown413 B
benchmark/drift/fixtures/mini_course_long/study_plan.mdmarkdown426 B
benchmark/drift/fixtures/mini_course_long/study_progress.final.bad.mdmarkdown151 B
benchmark/drift/fixtures/mini_course_long/study_progress.final.good.mdmarkdown272 B
benchmark/drift/fixtures/mini_course_long/study_progress.initial.mdmarkdown151 B
benchmark/drift/fixtures/mini_course_long_state/references/quiz_bank.jsonconfig1.3 KB
benchmark/drift/fixtures/mini_course_long_state/references/wiki/ch1_stack_queue.mdmarkdown541 B
benchmark/drift/fixtures/mini_course_long_state/references/wiki/ch2_trees.mdmarkdown413 B
benchmark/drift/fixtures/mini_course_long_state/study_plan.mdmarkdown426 B
benchmark/drift/fixtures/mini_course_long_state/study_progress.final.bad.mdmarkdown151 B
benchmark/drift/fixtures/mini_course_long_state/study_progress.final.good.mdmarkdown272 B
benchmark/drift/fixtures/mini_course_long_state/study_progress.initial.mdmarkdown151 B
benchmark/drift/fixtures/mini_course_long_state/study_state.jsonconfig145 B
benchmark/drift/run_drift.pyscript79.7 KB
benchmark/drift/run_live_smoke.pyscript26.4 KB
benchmark/drift/scenarios/live_smoke_basic.jsonconfig681 B
benchmark/drift/scenarios/long_session_basic.jsonconfig793 B
benchmark/drift/scenarios/long_session_state.jsonconfig994 B
benchmark/drift/scenarios/mode_urgent_no_questions.jsonconfig1.1 KB
benchmark/drift/scenarios/window_persist.jsonconfig1.0 KB
benchmark/drift/templates/live_session_template.mdmarkdown1.3 KB
benchmark/drift/templates/live_smoke_turns.jsonconfig1.6 KB
benchmark/drift/transcripts/bad_checkpoint_reset.jsonlother877 B
benchmark/drift/transcripts/bad_goal_drift.jsonlother226 B
benchmark/drift/transcripts/bad_plan_drift.jsonlother729 B
benchmark/drift/transcripts/bad_progress_loss.jsonlother1013 B
benchmark/drift/transcripts/bad_provenance_drift.jsonlother583 B
benchmark/drift/transcripts/bad_quiz_invention.jsonlother590 B
benchmark/drift/transcripts/bad_urgent_1day_questions.jsonlother840 B
benchmark/drift/transcripts/bad_wiki_overread.jsonlother430 B
benchmark/drift/transcripts/good_session.jsonlother5.5 KB
benchmark/drift/transcripts/good_session_state.jsonlother7.0 KB
benchmark/drift/transcripts/good_session_urgent_1day.jsonlother2.8 KB
benchmark/drift/transcripts/window_persist_session.jsonlother7.3 KB
benchmark/fixtures/mini_course_matrix/.gitignoreother250 B
benchmark/fixtures/mini_course_matrix/config.jsonconfig394 B
benchmark/fixtures/mini_course_matrix/items.jsonlother1.6 KB
benchmark/fixtures/mini_course_matrix/materials/_combined.txtmarkdown502 B
benchmark/fixtures/mini_course_matrix/raw_ws/lecture01.mdmarkdown379 B
benchmark/fixtures/mini_course_matrix/skill_ws/references/wiki/ch01_minios.mdmarkdown485 B
benchmark/gen.pyscript13.0 KB
benchmark/items/README.en.mdmarkdown3.3 KB
benchmark/items/README.mdmarkdown2.6 KB
benchmark/items/items.example.jsonlother2.0 KB
benchmark/items/items_algo_full_q.jsonlother13.5 KB
benchmark/items/items_pilot_6006.jsonlother4.5 KB
benchmark/items/items_pilot_psyc110.jsonlother4.5 KB
benchmark/items/items_psyc_full_q.jsonlother7.5 KB

benchmark/drift/convert_session_log.py

View on GitHub
# -*- coding: utf-8 -*-
"""Convert a human-editable live session Markdown log into T4 drift JSONL.

This adapter is deliberately small and stdlib-only. It does not run a model,
touch the network, read secrets, or write benchmark results by default.

Exit codes:
  0 = converted / checked successfully
  2 = malformed input or CLI usage error
"""
import argparse
import json
import math
import os
import re
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
DEFAULT_TEMPLATE = os.path.join(HERE, "templates", "live_session_template.md")

TURN_RE = re.compile(r"^##\s+Turn\s+(\d+)\s*$", re.I)
SECTION_RE = re.compile(r"^###\s+(.+?)\s*$")
FIELD_RE = re.compile(r"^([A-Za-z_][\w-]*)\s*:\s*(.*?)\s*$")
FENCE_RE = re.compile(r"^(?P<fence>`{3,})[A-Za-z0-9_-]*\s*$")

TURN_FIELDS = {"kind", "phase_context", "tokens_in", "tokens_out", "cost_usd"}
INT_FIELDS = {"phase_context", "tokens_in", "tokens_out"}
FLOAT_FIELDS = {"cost_usd"}
MESSAGE_SECTIONS = {"user", "assistant"}
EVENT_SECTIONS = {"events"}
EVENT_TYPES = {"read_file", "write_file"}
TRACKED_WRITE_SNAPSHOTS = {"study_plan.md", "study_progress.md", "study_state.json"}   # A4: T4 优先读 state 快照


class SessionLogError(Exception):
    """Malformed session log; surfaced as exit code 2."""


def read_utf8(path):
    try:
        with open(path, "r", encoding="utf-8-sig") as f:
            return f.read()
    except UnicodeDecodeError as e:
        raise SessionLogError("cannot read %s as UTF-8: %s" % (path, e))
    except OSError as e:
        raise SessionLogError("cannot read %s: %s" % (path, e))


def write_utf8(path, text):
    try:
        parent = os.path.dirname(os.path.abspath(path))
        if parent and not os.path.isdir(parent):
            raise SessionLogError("output directory does not exist: %s" % parent)
        with open(path, "w", encoding="utf-8", newline="\n") as f:
            f.write(text)
    except OSError as e:
        raise SessionLogError("cannot write %s: %s" % (path, e))


def write_stdout_utf8(text):
    """Print template text without losing emoji on legacy Windows consoles."""
    if hasattr(sys.stdout, "reconfigure"):
        try:
            sys.stdout.reconfigure(encoding="utf-8")
        except (AttributeError, ValueError):
            pass
    try:
        sys.stdout.write(text)
    except UnicodeEncodeError:
        sys.stdout.buffer.write(text.encode("utf-8"))


def clean_block(lines):
    """Trim only surrounding blank lines; preserve internal text and UTF-8 content."""
    start, end = 0, len(lines)
    while start < end and not lines[start].strip():
        start += 1
    while end > start and not lines[end - 1].strip():
        end -= 1
    return "\n".join(lines[start:end])


def adapter_section(line):
    """Return the reserved adapter section name, or None for ordinary Markdown headings."""
    m = SECTION_RE.match(line)
    if not m:
        return None
    heading = m.group(1).strip()
    lower = heading.lower()
    if lower in MESSAGE_SECTIONS or lower in EVENT_SECTIONS:
        return lower
    if re.match(r"files\s+after\s*:\s*.+$", heading, re.I):
        return "files_after"
    return None


def parse_scalar(key, value, turn):
    if key in INT_FIELDS:
        if not re.fullmatch(r"\d+", value.strip()):
            raise SessionLogError("turn %d field %s must be an integer" % (turn, key))
        return int(value.strip())
    if key in FLOAT_FIELDS:
        try:
            parsed = float(value.strip())
        except ValueError:
            raise SessionLogError("turn %d field %s must be numeric" % (turn, key))
        if not math.isfinite(parsed):
            raise SessionLogError("turn %d field %s must be finite" % (turn, key))
        if parsed < 0:
            raise SessionLogError("turn %d field %s cannot be negative" % (turn, key))
        return parsed
    if key == "kind":
        value = value.strip()
        if not value:
            raise SessionLogError("turn %d field kind cannot be empty" % turn)
        return value
    raise SessionLogError("turn %d has unknown field %r" % (turn, key))


def parse_events(lines, turn):
    events = []
    for raw in lines:
        line = raw.strip()
        if not line:
            continue
        m = re.match(r"^[-*]\s*([A-Za-z_][A-Za-z0-9_]*)\s*:\s*(.+?)\s*$", line)
        if not m:
            raise SessionLogError("turn %d event must look like '- read_file: path'" % turn)
        event_type = m.group(1)
        if event_type not in EVENT_TYPES:
            raise SessionLogError(
                "turn %d event type %r is not supported; use one of %s"
                % (turn, event_type, ", ".join(sorted(EVENT_TYPES)))
            )
        path = m.group(2).strip()
        if not path:
            raise SessionLogError("turn %d event path cannot be empty" % turn)
        events.append({"type": event_type, "path": path})
    return events


def parse_files_after(lines, start, turn, path):
    i = start
    while i < len(lines) and not lines[i].strip():
        i += 1
    m = FENCE_RE.match(lines[i].strip()) if i < len(lines) else None
    if not m:
        raise SessionLogError("turn %d Files After %s must use a fenced code block" % (turn, path))
    fence_len = len(m.group("fence"))
    close_re = re.compile(r"^`{%d,}\s*$" % fence_len)
    i += 1
    block_start = i
    while i < len(lines) and not close_re.match(lines[i].strip()):
        i += 1
    if i >= len(lines):
        raise SessionLogError("turn %d Files After %s fence is not closed" % (turn, path))
    content = clean_block(lines[block_start:i])
    return content, i + 1


def tracked_snapshot_name(path):
    norm = str(path or "").replace("\\", "/").lstrip("./")
    base = norm.rsplit("/", 1)[-1]
    return base if base in TRACKED_WRITE_SNAPSHOTS else None


def validate_tracked_writes(turn, events, files_after):
    for ev in events or []:
        if ev.get("type") != "write_file":
            continue
        required = tracked_snapshot_name(ev.get("path", ""))
        if required and required not in files_after:
            raise SessionLogError(
                "turn %d write_file for %s requires matching ### Files After: %s"
                % (turn, required, required)
            )


def parse_turn_body(turn, body):
    row = {"turn": turn}
    files_after = {}
    events = None
    seen_fields = set()
    seen = set()
    i = 0

    while i < len(body):
        line = body[i]
        if not line.strip():
            i += 1
            continue
        if adapter_section(line):
            break
        m = FIELD_RE.match(line)
        if not m:
            raise SessionLogError("turn %d has text before first section: %r" % (turn, line.strip()))
        key, value = m.group(1), m.group(2)
        if key not in TURN_FIELDS:
            raise SessionLogError("turn %d has unknown field %r" % (turn, key))
        if key in seen_fields:
            raise SessionLogError("turn %d repeats field %s" % (turn, key))
        seen_fields.add(key)
        row[key] = parse_scalar(key, value, turn)
        i += 1

    while i < len(body):
        line = body[i]
        if not line.strip():
            i += 1
            continue
        section = adapter_section(line)
        if not section:
            raise SessionLogError("turn %d has content outside a section: %r" % (turn, line.strip()))
        m = SECTION_RE.match(line)
        heading = m.group(1).strip()
        lower = heading.lower()
        i += 1

        if lower in MESSAGE_SECTIONS or lower in EVENT_SECTIONS:
            if lower in seen:
                raise SessionLogError("turn %d repeats section %s" % (turn, heading))
            seen.add(lower)
            start = i
            if lower in MESSAGE_SECTIONS:
                i = next_adapter_section(body, i, turn, heading)
            else:
                while i < len(body) and not adapter_section(body[i]):
                    i += 1
            block = body[start:i]
            if lower in EVENT_SECTIONS:
                events = parse_events(block, turn)
            else:
                value = clean_block(block)
                if not value:
                    raise SessionLogError("turn %d section %s cannot be empty" % (turn, heading))
                row[lower] = value
            continue

        fm = re.match(r"files\s+after\s*:\s*(.+)$", heading, re.I)
        if fm:
            path = fm.group(1).strip()
            if not path:
                raise SessionLogError("turn %d Files After path cannot be empty" % turn)
            snapshot_key = tracked_snapshot_name(path) or path
            if snapshot_key in files_after:
                raise SessionLogError("turn %d repeats Files After for %s" % (turn, path))
            content, i = parse_files_after(body, i, turn, path)
            files_after[snapshot_key] = content
            continue

        raise SessionLogError("turn %d has unknown section %r" % (turn, heading))

    for required in ("user", "assistant"):
        if required not in row:
            raise SessionLogError("turn %d missing ### %s section" % (turn, required.title()))
    if events is not None:
        row["events"] = events
    if files_after:
        row["files_after"] = files_after
    validate_tracked_writes(turn, events, files_after)
    return row


def parse_session_log(text):
    lines = text.splitlines()
    starts = []
    fence_len = None
    for i, line in enumerate(lines):
        stripped = line.strip()
        if fence_len is not None:
            if re.match(r"^`{%d,}\s*$" % fence_len, stripped):
                fence_len = None
            continue
        fm = FENCE_RE.match(stripped)
        if fm:
            fence_len = len(fm.group("fence"))
            continue
        m = TURN_RE.match(line)
        if m and is_turn_start(lines, i):
            starts.append((i, int(m.group(1))))
    if not starts:
        raise SessionLogError("session log has no '## Turn N' sections")

    rows = []
    seen_turns = set()
    for idx, (start, turn) in enumerate(starts):
        if turn in seen_turns:
            raise SessionLogError("duplicate turn number: %d" % turn)
        seen_turns.add(turn)
        end = starts[idx + 1][0] if idx + 1 < len(starts) else len(lines)
        rows.append(parse_turn_body(turn, lines[start + 1:end]))
    return rows


def is_turn_start(lines, index):
    """A turn header is top-level only; ignore same-looking text captured inside snapshots/messages."""
    i = index + 1
    while i < len(lines) and not lines[i].strip():
        i += 1
    if i >= len(lines):
        return False
    section = adapter_section(lines[i])
    if section in MESSAGE_SECTIONS or section in EVENT_SECTIONS:
        return True
    return bool(FIELD_RE.match(lines[i]))


def next_adapter_section(lines, start, turn, section):
    fence_len = None
    i = start
    while i < len(lines):
        stripped = lines[i].strip()
        if fence_len is not None:
            if re.match(r"^`{%d,}\s*$" % fence_len, stripped):
                fence_len = None
            i += 1
            continue
        fm = FENCE_RE.match(stripped)
        if fm:
            fence_len = len(fm.group("fence"))
            i += 1
            continue
        if adapter_section(lines[i]):
            break
        i += 1
    if fence_len is not None:
        raise SessionLogError("turn %d section %s fence is not closed" % (turn, section))
    return i


def rows_to_jsonl(rows):
    return "".join(json.dumps(row, ensure_ascii=False) + "\n" for row in rows)


def convert_file(in_path, out_path=None, check=False):
    rows = parse_session_log(read_utf8(in_path))
    if check:
        return rows
    if not out_path:
        raise SessionLogError("--out is required unless --check is used")
    write_utf8(out_path, rows_to_jsonl(rows))
    return rows


def build_arg_parser():
    ap = argparse.ArgumentParser(
        description="Convert a UTF-8 Markdown live session log to T4-compatible JSONL."
    )
    ap.add_argument("--in", dest="in_path", help="input Markdown session log")
    ap.add_argument("--out", dest="out_path", help="output JSONL path (explicit; no default results dir)")
    ap.add_argument("--check", action="store_true", help="validate and parse the session log without writing")
    ap.add_argument(
        "--template",
        nargs="?",
        const=DEFAULT_TEMPLATE,
        help="print a starter template to stdout (defaults to the bundled template)",
    )
    return ap


def main(argv=None):
    ap = build_arg_parser()
    args = ap.parse_args(argv)

    try:
        if args.template:
            write_stdout_utf8(read_utf8(args.template))
            return 0
        if not args.in_path:
            ap.error("--in is required unless --template is used")
        if args.check and args.out_path:
            raise SessionLogError("--check does not write output; remove --out")
        rows = convert_file(args.in_path, args.out_path, args.check)
        if args.check:
            write_stdout_utf8("OK: %d turns parsed from %s\n" % (len(rows), args.in_path))
        return 0
    except SessionLogError as e:
        print("convert_session_log: %s" % e, file=sys.stderr)
        return 2


if __name__ == "__main__":
    sys.exit(main())
receiving-code-reviewobra/superpowersUse when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementationStars: 322kUpdated Claude CodeCodexVerifiedInstall
requesting-code-reviewobra/superpowersUse when completing tasks, implementing major features, or before merging to verify work meets requirementsStars: 322kUpdated Claude CodeCodexVerifiedInstall
using-git-worktreesobra/superpowersUse when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallbackStars: 322kUpdated Claude CodeCodexVerifiedInstall
verification-before-completionobra/superpowersUse when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions alwaysStars: 322kUpdated Claude CodeCodexVerifiedInstall