← Files Uni Lecture TutorARCHIVED FILE

skills/automatic-lecture-learning/scripts/ult_state.py

28.5 KB · Nov 30, 2026 · 18:13 UTC

↓ Download file

See the change to this file →

"""Optional offline helper for trusted package use. No network, persistence, grading or document inspection."""
from ult_safe_io import safe_error
import argparse, copy, json, sys
from pathlib import Path
from collections import deque
from ult_dependency_guard import require_approved_dependencies
require_approved_dependencies()
from referencing import Registry
from jsonschema import Draft202012Validator, FormatChecker
from ult_invariants import mastery, element_complete, first_unfinished, fully_covered
from ult_policy import course_active_slots, course_assessment_active, course_profiles
ROOT=Path(__file__).resolve().parents[1]/'references'
LIMIT=2_000_000
class Invalid(ValueError): pass

def require(ok,message):
    if not ok: raise Invalid(message)

def unique_pairs(pairs):
    d={}
    for k,v in pairs:
        require(k not in d,'duplicate JSON key')
        d[k]=v
    return d

def read_json(path):
    from ult_safe_io import read_json as bounded_read
    try:return bounded_read(path,LIMIT,max_nodes=600000)
    except (ValueError,OSError) as e:raise Invalid(safe_error(e)) from e

def valid_unicode(text):
    # Reject lone UTF-16 surrogate code points, even when escaped in JSON.
    require(not any(0xD800 <= ord(c) <= 0xDFFF for c in text),'invalid Unicode scalar value')

def strict_json(value):
    # The schema uses integers only. Python JSON Schema accepts integral floats;
    # reject those before indexing or arithmetic, and bound nesting and size.
    todo=[(value,0)];n=0
    while todo:
        v,depth=todo.pop();n+=1
        require(n<=300000 and depth<=64,'JSON structure limit exceeded')
        if type(v) is dict:
            require(all(type(k) is str for k in v),'invalid JSON key type')
            for k in v:valid_unicode(k)
            todo.extend((x,depth+1) for x in v.values())
        elif type(v) is list:todo.extend((x,depth+1) for x in v)
        else:
            require(type(v) in (str,int,bool,type(None)),'non-JSON or non-integer numeric value')
            if type(v) is str:valid_unicode(v)

def structural(state,schema='course-checkpoint.schema.json'):
    strict_json(state)
    # Resolve only bundled schema/internal refs; no remote retrieval.
    validator=Draft202012Validator(json.loads((ROOT/schema).read_text()),format_checker=FormatChecker(),registry=Registry())
    error=next(validator.iter_errors(state),None)
    if error:
        from ult_safe_io import schema_error
        raise Invalid(schema_error(error))

def index(items,key='id'):
    out={}
    for item in items:
        require(item[key] not in out,'duplicate '+key);out[item[key]]=item
    return out

def in_ranges(page,ranges):return any(a['start']<=page<=a['end'] for a in ranges)
def covers(ranges, start,end):
    cursor=start
    for a in sorted(ranges,key=lambda v:v['start']):
        if a['end']<cursor:continue
        if a['start']>cursor:break
        cursor=max(cursor,a['end']+1)
        if cursor>end:return True
    return False

def validate(state):
    structural(state)
    courses=index(state['courses']); active=state.get('active_course');require(active is None or active in courses,'unknown active course'); active_tasks=[]
    events=state.get('navigation_events',[])
    if 'handoff' in state:require(state['handoff']['saved_revision']<=state['revision'],'handoff revision ahead of state')
    if state['mode']=='exam':require(state['phase'] in ('exam','recover','paused','intake','feedback'),'exam mode conflicts with teaching phase')
    index(events,'action_id')
    revisions=[e['revision'] for e in events]
    require(revisions==sorted(set(revisions)) and all(0<r<=state['revision'] for r in revisions),'invalid navigation event revisions')
    if events:require(state.get('last_action_id')==events[-1]['action_id'],'navigation head mismatch')
    for cid,c in courses.items():
        lectures=index(c['lectures']); concepts=index(c['concepts']); tasks=index(c.get('tasks',[]));
        require(c.get('active_lecture') is None or c['active_lecture'] in lectures,'unknown active lecture')
        elements={lid:index(l.get('elements',[])) for lid,l in lectures.items()}
        def anchor(a):
            lid=a['lecture_id'];require(lid in lectures,'unknown anchor lecture');l=lectures[lid]
            if 'page' in a:require(a['page']<=l.get('pages',100000),'anchor page outside lecture')
            if 'element_id' in a:
                require(a['element_id'] in elements[lid],'unknown anchor element'); el=elements[lid][a['element_id']]
                require('page' not in a or 'page' not in el or a['page']==el['page'],'anchor element page mismatch')
                require('step' not in a or a['step']==el.get('step'),'anchor element step mismatch')
                require(a['element']==el['label'],'anchor element label mismatch')
        def usable_anchor(a):
            l=lectures[a['lecture_id']]
            if 'element_id' in a:
                el=elements[l['id']][a['element_id']]
                return el['inspection']=='inspected' and not el.get('gap') and ('pages' not in l or 'page' in el)
            if 'page' not in a or not in_ranges(a['page'],l['inspected']):return False
            candidates=[e for e in elements[l['id']].values() if e.get('page')==a['page'] and e['label']==a['element'] and ('step' not in a or a['step']==e.get('step'))]
            # Legacy page anchors are reports, not a way around a known unreadable element.
            return len(candidates)==1 and candidates[0]['inspection']=='inspected' and not candidates[0].get('gap')
        for lid,l in lectures.items():
            if l.get('inventory_complete'):
                require('pages' in l and elements[lid] and all('page' in el for el in elements[lid].values()) and len({el['page'] for el in elements[lid].values()})==l['pages'] and covers(l['inspected'],1,l['pages']),'complete inventory requires inspected element on every page')
                require(all(el['inspection']=='inspected' for el in elements[lid].values()),'complete inventory contains unreadable or mapped elements')
            for k in ('inspected','taught','notes','skipped'):
                for a in l[k]:
                    require(a['start']<=a['end']<=l.get('pages',100000),'invalid page interval')
                    if k in ('taught','notes'):require(covers(l['inspected'],a['start'],a['end']),'coverage outside inspected ranges')
            if 'next' in l:
                anchor(l['next']);require(l['next']['lecture_id']==lid,'cross-lecture next anchor')
                target=elements[lid].get(l['next'].get('element_id'))
                if target is None:
                    matches=[e for e in elements[lid].values() if e['label']==l['next']['element'] and e.get('page')==l['next'].get('page')]
                    if len(matches)==1:target=matches[0]
                require(target is None or not element_complete(target),'next anchor already complete')
                if target is not None and 'element_id' in l['next']:
                    require(l['next']['element']==target['label'],'next label mismatch')
                    require(l['next'].get('page')==target.get('page') and l['next'].get('step')==target.get('step'),'next locator incomplete or inconsistent')
            step_keys=set()
            for el in elements[lid].values():
                if 'step_group' in el:
                    require(el['kind']=='proof' and 'step' in el,'step group needs a numbered proof element')
                    key=(el['step_group'],el['step']);require(key not in step_keys,'duplicate step in explicit proof group');step_keys.add(key)
                if 'page' in el:
                    require(el['page']<=l.get('pages',100000),'element page outside lecture')
                    if el['inspection']=='inspected':require(in_ranges(el['page'],l['inspected']),'element outside inspected range')
                if el['teaching'] in ('taught','partial') or el['notes']=='delivered' or el['vocabulary']=='delivered':require(el['inspection']=='inspected','teaching without inspection')
                require((el['notes']=='deferred')==(el['vocabulary']=='deferred'),'notes/vocabulary deferral inconsistent')
                if el['notes']=='delivered':require(el['vocabulary'] in ('delivered','not_required'),'notes/vocabulary pair inconsistent')
                if el['vocabulary']=='delivered':require(el['notes']=='delivered','vocabulary without notes')
                if 'page' in el and in_ranges(el['page'],l['taught']):require(el['teaching']=='taught' or el['kind']=='admin','page marked taught with unfinished element')
                if 'page' in el and in_ranges(el['page'],l['notes']):require(el['notes'] in ('delivered','not_required') and el['vocabulary'] in ('delivered','not_required'),'page notes marked complete with unfinished pair')
            for ex in index(l.get('exercises',[])).values():
                anchor(ex['anchor']);require(ex['anchor']['lecture_id']==lid,'exercise outside owning lecture')
                require(all(x in concepts for x in ex['concept_ids']),'unknown exercise concept')
                if 'solution_anchor' in ex:anchor(ex['solution_anchor'])
        attempts={}; item_metadata={}
        prereqs={k:set(v['prerequisites']) for k,v in concepts.items()}
        for k,v in concepts.items():
            require(len(prereqs[k])==len(v['prerequisites']),'duplicate prerequisite')
            reqs=v.get('prerequisite_skills',[]);require(len({r['concept_id'] for r in reqs})==len(reqs),'duplicate skill prerequisite')
            require(all(r['concept_id'] in prereqs[k] for r in reqs),'skill requirement lacks registered prerequisite')
            for a in v['anchors']:anchor(a)
            for x in v.get('variants',[]):anchor(x['anchor'])
            skill_events=[(o['attempt_id'],o['skill']) for o in v['observations'] if 'attempt_id' in o]
            require(len(skill_events)==len(set(skill_events)),'duplicate attempt skill within concept')
            dates=[o['date'] for o in v['observations'] if o.get('date')]
            require(dates==sorted(dates),'observation dates not chronological')
            for o in v['observations']:
                for field in ('content_sha256','family_id'):
                    if o.get(field):require(item_metadata.setdefault((o['item_id'],field),o[field])==o[field],'conflicting lecture item identity')
                bindings=o.get('source_bindings',[]);require(len({b['lecture_id'] for b in bindings})==len(bindings),'duplicate observation source binding')
                require(all(b['lecture_id'] in {a['lecture_id'] for a in v['anchors']} and lectures[b['lecture_id']].get('source_sha256')==b['source_sha256'] for b in bindings),'observation source version mismatch')
                require(state['history_trust']=='available_context' or o.get('trust')!='observed','reported checkpoint cannot contain observed history; import to demote')
                if o.get('trust')=='observed' and state['history_trust']=='available_context':
                    require(any(usable_anchor(a) for a in v['anchors']),'observed evidence lacks usable inspected source anchor')
                if o['outcome']=='revealed':require(o['assistance']=='reveal','revealed outcome without reveal assistance')
                if o['outcome']=='skipped':require(o['assistance']!='reveal','skipped item with reveal assistance')
                if 'attempt_id' in o:
                    signature=(o['item_id'],o.get('date'),o['assistance'],o.get('trust','user_reported'))
                    require(attempts.setdefault(o['attempt_id'],signature)==signature,'attempt identity inconsistent across concepts')
        profiles=course_profiles(c,state['history_trust'])
        for k,v in concepts.items():require(v['status']==profiles[k]['status'],'mastery status unsupported by course-wide evidence')
        edges=set()
        for e in c.get('edges',[]):
            key=(e['from'],e['to'],e['kind']);require(key not in edges,'duplicate edge');edges.add(key)
            require(e['from'] in concepts and e['to'] in concepts and e['from']!=e['to'],'invalid edge reference');require(e['anchors'],'edge missing provenance')
            for a in e['anchors']:anchor(a)
            if e['kind']=='requires':prereqs[e['from']].add(e['to'])
        # Bounded Kahn cycle detection; prerequisite direction does not affect cycles.
        require(all(p in concepts for ps in prereqs.values() for p in ps),'unknown prerequisite')
        dependents={k:[] for k in prereqs};degree={k:len(v) for k,v in prereqs.items()}
        for k,ps in prereqs.items():
            for p in ps:dependents[p].append(k)
        roots=deque(k for k,v in degree.items() if not v);visited=0
        while roots:
            k=roots.popleft();visited+=1
            for child in dependents[k]:
                degree[child]-=1
                if not degree[child]:roots.append(child)
        require(visited==len(prereqs),'cyclic prerequisites')
        for tid,t in tasks.items():
            require(t['lecture_id'] in lectures,'unknown task lecture');anchor(t['anchor']);require(t['anchor']['lecture_id']==t['lecture_id'],'task anchor mismatch');require(t.get('concept_id') is None or t['concept_id'] in concepts,'unknown task concept')
            if t['status']=='revealed':require(t['assistance']=='reveal','revealed task without reveal assistance')
            if t['status']=='active':
                active_tasks.append((cid,t));require(cid==active and c.get('active_lecture')==t['lecture_id'],'active task outside active lecture')
                require(state['phase'] in ('wait','review'),'active task outside assessment phase')
                require(usable_anchor(t['anchor']),'active task lacks usable inspected source anchor')
        if 'pending' in c:
            anchor(c['pending']);require(cid==active and c.get('active_lecture')==c['pending']['lecture_id'],'pending outside active course or lecture')
            require(state['phase'] in ('wait','review','recover','paused'),'pending task outside assessment or recovery phase')
            if state['phase'] in ('wait','review'):require(usable_anchor(c['pending']),'active pending task lacks usable inspected source anchor')
            active_here=[t for t in tasks.values() if t['status']=='active']
            if active_here:require(c['pending']==active_here[0]['anchor'],'pending and active task disagree')
            require(c.get('exam',{}).get('status')!='active','pending task conflicts with active exam')
        for a in c.get('deferred_notes',[]):
            anchor(a)
            if 'element_id' in a:
                el=elements[a['lecture_id']][a['element_id']]
                require(not element_complete(el),'deferred notes already complete')
        for f in c.get('return_stack',[]):
            anchor(f['anchor']);require(f.get('task_id') is None or f['task_id'] in tasks,'unknown return task')
            if 'task_id' in f:require(tasks[f['task_id']]['lecture_id']==f['anchor']['lecture_id'],'return task outside anchor lecture')
        for e in index(c.get('errors',[])).values():require(e['concept_id'] in concepts,'unknown error concept');anchor(e['anchor'])
        for q in c.get('review_queue',[]):require(q['concept_id'] in concepts,'unknown review concept')
        if 'exam' in c:
            e=c['exam'];items=e['item_ids'];require(items and len(set(items))==len(items),'invalid exam item list');require(e['lecture_ids'] and len(set(e['lecture_ids']))==len(e['lecture_ids']) and all(l in lectures for l in e['lecture_ids']),'invalid exam scope');require(e['current_index']<=len(items),'exam index out of bounds');rs=index(e['responses'],'item_id');require(set(rs)<=set(items),'unknown exam response');require(e['status']!='active' or (cid==active and e['current_index']<len(items) and state['phase']=='exam' and state['mode']=='exam'),'invalid active exam');require(e['status']!='complete' or (e['current_index']==len(items) and set(rs)==set(items)),'incomplete completed exam')
            i=e['current_index'];require(set(items[:i])<=set(rs)<=set(items[:i+1]),'exam response order or prior gap')
            require(e['status']!='paused' or i<len(items),'paused exam at terminal index; reconcile as complete')
            for response in rs.values():
                require(e.get('assessment_mode','independent')=='guided' or (response['assistance']=='none' and response['outcome']!='revealed'),'independent course exam forbids assisted or revealed response')
                if response['outcome']=='revealed':require(response['assistance']=='reveal','revealed exam answer without reveal assistance')
                if response['outcome']=='skipped':require(response['assistance']!='reveal','skipped exam item with reveal assistance')
    slots=course_active_slots(state)
    require(len(slots)<=1,'multiple active assessments in course checkpoint')
    require(all(cid==active for cid,_,_ in slots),'pending assessment outside active course')
    require(not slots or slots[0][1]!='legacy_pending' or state['phase'] in ('wait','review','recover'),'pending task outside assessment or recovery phase')
    require(state['phase']!='wait' or len(active_tasks)==1 or (active in courses and 'pending' in courses[active]),'wait without pending task')
    if state['phase']=='complete':
        require(active in courses and courses[active]['lectures'] and all(fully_covered(l,covers) for l in courses[active]['lectures']) and not courses[active].get('deferred_notes') and not courses[active].get('return_stack') and not courses[active].get('pending'),'completion unsupported by coverage')
    if state['mode']=='exam' and state['phase']=='feedback':require(active in courses and courses[active].get('exam',{}).get('status')=='complete','exam feedback requires completed exam')
    if state['phase']=='exam':require(state['mode']=='exam' and active in courses and courses[active].get('exam',{}).get('status')=='active','exam phase without active exam')
    return {'valid':True,'history_verified':False,'revision':state['revision'],'courses':len(courses)}

def migrate(state):
    require(isinstance(state,dict),'checkpoint must be object')
    version=state.get('schema_version')
    if version in ('2.3.0','2.4.0','2.5.0'):
        structural(state,{'2.3.0':'migrations/course-checkpoint-v23.schema.json','2.4.0':'migrations/course-checkpoint-v24.schema.json','2.5.0':'migrations/course-checkpoint-v25.schema.json'}[version]);s=copy.deepcopy(state);s['schema_version']='2.5.1'
        return prepare_import(s)
    require(version=='2.0.0','unsupported legacy version')
    structural(state,'migrations/course-checkpoint-v2.schema.json'); s=copy.deepcopy(state)
    s.update(schema_version='2.5.1',revision=0,phase='recover',depth='balanced',focus='learn',history_trust='user_reported',completeness='partial')
    for c in s['courses']:
        for k in c['concepts']:
            k['status']='unknown'
            for o in k['observations']:o['trust']='user_reported'
    validate(s);return s

def prepare_import(state):
    """Reset external trust; never treat caller-supplied flags as verified history."""
    require(isinstance(state,dict),'checkpoint must be object')
    if state.get('schema_version') in ('2.0.0','2.3.0','2.4.0','2.5.0'):return migrate(state)
    structural(state);s=copy.deepcopy(state)
    s.update(history_trust='user_reported',phase='recover',completeness='partial')
    # Imported inventory is a report, never a new verified source audit.
    for c in s['courses']:
        for l in c['lectures']:l.pop('inventory_complete',None)
    for c in s['courses']:
        for k in c['concepts']:
            k['status']='unknown'
            for o in k['observations']:o['trust']='user_reported'
        for t in c.get('tasks',[]):
            if t['status']=='active':t['status']='suspended'
        if c.get('exam',{}).get('status')=='active':c['exam']['status']='paused'
        if 'exam' in c and any(v['assistance']!='none' or v['outcome']=='revealed' for v in c['exam']['responses']):c['exam']['assessment_mode']='guided'
        exam=c.get('exam')
        if exam and exam['status']=='paused' and exam['current_index']==len(exam['item_ids']):
            # Only repair a terminal state if every item really has a recorded response.
            if len(exam['responses'])==len(exam['item_ids']) and {x['item_id'] for x in exam['responses']}==set(exam['item_ids']):exam['status']='complete'
    validate(s);return s

def decide(state,event):
    validate(state); strict_json(event); schema={'type':'object','additionalProperties':False,'properties':{'action_id':{'type':'string','pattern':'^[a-z][a-z0-9_-]{0,31}$'},'expected_revision':{'type':'integer','minimum':0},'course_id':{'type':'string'},'lecture_id':{'type':'string'},'kind':{'enum':['continue','hint','reveal','pause','resume','simplify','deepen','example','review','save']}},'required':['action_id','expected_revision','kind']};require(Draft202012Validator(schema).is_valid(event),'invalid event')
    def result(route,**kw):return {'route':route,'revision':state['revision'],'action_id':event['action_id'],'evidence_credit':False,**kw}
    if event['action_id']==state.get('last_action_id') or any(e['action_id']==event['action_id'] for e in state.get('navigation_events',[])) or event['expected_revision']!=state['revision']:return result('reconcile_stale')
    courses={c['id']:c for c in state['courses']}; c=courses.get(state.get('active_course')); lid=c.get('active_lecture') if c else None
    if ('course_id' in event and event['course_id']!=state.get('active_course')) or ('lecture_id' in event and event['lecture_id']!=lid):return result('reconcile_stale')
    kind=event['kind'];phase=state['phase']
    if kind=='pause':return result('pause')
    if kind=='save':return result('export_checkpoint')
    if kind=='resume':return result('recover_verified_anchor')
    if not c or phase in ('paused','recover','intake'):return result('recover_verified_anchor')
    if not lid and phase!='exam' and not (phase=='feedback' and state['mode']=='exam'):return result('recover_verified_anchor')
    if phase=='feedback' and state['mode']=='exam':
        if kind in ('continue','review'):return result('exam_exit_review')
        return result('explicit_exam_mode_change_or_reveal_request')
    if kind!='continue':
        if phase=='exam' and kind in ('hint','reveal','simplify','deepen','example','review'):return result('explicit_exam_mode_change_or_reveal_request')
        return result({'hint':'offer_nonleaking_hint','reveal':'explicit_reveal','simplify':'same_anchor_brief','deepen':'same_anchor_deep','example':'same_anchor_example','review':'review_current_scope'}[kind])
    if phase=='exam':
        exam=c['exam'];i=exam['current_index'];item=exam['item_ids'][i];answered=any(x['item_id']==item for x in exam['responses']);return result('exam_results' if i+1==len(exam['item_ids']) else 'exam_next',item_id=item,skip_ungraded=not answered)
    pending=phase in ('wait','review') and ('pending' in c or any(t['status']=='active' for t in c.get('tasks',[])))
    if c.get('deferred_notes'):return result('finish_deferred_notes_then_resume',skip_ungraded=pending)
    if c.get('return_stack'):return result('return_prerequisite_anchor',anchor=c['return_stack'][-1]['anchor'],skip_ungraded=pending)
    l=next(x for x in c['lectures'] if x['id']==lid)
    candidate,reachable=first_unfinished(l)
    if candidate:return result('resume_anchor' if reachable else 'recover_verified_anchor',anchor=candidate,skip_ungraded=pending)
    if l.get('elements') and l.get('next'):return result('recover_verified_anchor',skip_ungraded=pending)
    if 'next' in l:return result('recover_verified_anchor',anchor=l['next'],skip_ungraded=pending)
    if phase=='complete':return result('review_current_scope')
    if fully_covered(l,covers):
        # Propose, do not commit, the next lecture in registry order. The
        # caller must revalidate source, membership and any unresolved gaps.
        i=next(i for i,x in enumerate(c['lectures']) if x['id']==lid)
        for nxt in c['lectures'][i+1:]:
            if fully_covered(nxt,covers):continue
            target,reachable=first_unfinished(nxt)
            if target and reachable:return result('next_lecture_candidate',anchor=target,candidate_only=True,skip_ungraded=pending)
            return result('recover_verified_anchor',lecture_id=nxt['id'],skip_ungraded=pending)
        if all(fully_covered(x,covers) for x in c['lectures']):return result('review_current_scope',candidate_only=True,skip_ungraded=pending)
    # Absence of next is not evidence of full coverage; explicit source verification is still necessary.
    return result('verify_completion_or_recover',skip_ungraded=pending)

def apply_navigation(state,event):
    """Apply only safe navigation metadata to a copy; never assert teaching or grading.

    Callers must store with compare-and-set on revision if they need durable idempotency.
    Returning a new state does not persist it or prove the underlying source.
    """
    decision=decide(state,event)
    if decision['route']=='reconcile_stale':return {'state':copy.deepcopy(state),'decision':decision,'changed':False}
    # Read-only or pedagogical decisions do not commit progress. A real host must
    # confirm source evidence and perform its own state commit after teaching.
    route=decision['route']
    safe_routes={'pause','same_anchor_brief','same_anchor_deep','exam_next','exam_results','exam_exit_review'}
    skip_pending=event['kind']=='continue' and decision.get('skip_ungraded',False) and state['phase'] in ('wait','review')
    if route not in safe_routes and not skip_pending:return {'state':copy.deepcopy(state),'decision':decision,'changed':False}
    out=copy.deepcopy(state);courses={c['id']:c for c in out['courses']};c=courses.get(out.get('active_course'))
    if skip_pending:
        require(c is not None,'missing active course')
        for task in c.get('tasks',[]):
            if task['status']=='active':task['status']='skipped'
        c.pop('pending',None)
        # Deferred notes and return frames remain until verified teaching.
        out['phase']='recover' if route=='recover_verified_anchor' else 'teach'
        route='skip_pending'
    elif route=='pause':
        if c:
            for task in c.get('tasks',[]):
                if task['status']=='active':task['status']='suspended'
            if c.get('exam',{}).get('status')=='active':c['exam']['status']='paused'
        if 'exam' in c and any(v['assistance']!='none' or v['outcome']=='revealed' for v in c['exam']['responses']):c['exam']['assessment_mode']='guided'
        out['phase']='paused'
    elif route in ('same_anchor_brief','same_anchor_deep'):out['depth']='brief' if route=='same_anchor_brief' else 'deep'
    elif route=='exam_exit_review':
        out.update(mode='guided',phase='review',focus='revision')
    else:
        exam=c['exam'];i=exam['current_index'];item=exam['item_ids'][i];existing={a['item_id'] for a in exam['responses']}
        require(set(exam['item_ids'][:i])<=existing,'prior exam responses missing; recover first')
        if item not in existing:exam['responses'].append({'item_id':item,'outcome':'skipped','assistance':'none'})
        exam['current_index']=i+1
        if i+1==len(exam['item_ids']):exam['status']='complete';out['phase']='feedback'
    out['revision']+=1;out['last_action_id']=event['action_id']
    ledger=out.setdefault('navigation_events',[])
    require(len(ledger)<2000,'navigation ledger full; export and reconcile before continuing')
    ledger.append({'action_id':event['action_id'],'revision':out['revision'],'route':route})
    validate(out)
    return {'state':out,'decision':decision,'changed':True}

def main():
    parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('command',choices=['validate','migrate','import','decide','apply','profile']);parser.add_argument('checkpoint');parser.add_argument('event',nargs='?');parser.add_argument('--local-context',action='store_true',help='Caller attests actual current-context observations; not proof or authentication');a=parser.parse_args()
    try:
        s=read_json(a.checkpoint)
        if a.command in ('decide','apply','profile') and not a.local_context:s=prepare_import(s)
        if a.command in ('decide','apply'):
            require(a.event is not None,'event required');v=(decide if a.command=='decide' else apply_navigation)(s,read_json(a.event))
        elif a.command=='migrate':v=migrate(s)
        elif a.command=='import':v=prepare_import(s)
        elif a.command=='profile':
            validate(s);require(not course_assessment_active(s),'profile deferred during active course assessment');v={'history_verified':False,'courses':{c['id']:course_profiles(c,s['history_trust']) for c in s['courses']}}
        else:v=validate(s)
        print(json.dumps(v,ensure_ascii=True,indent=2));return 0
    except (Invalid,OSError,RecursionError) as e:print(json.dumps({'valid':False,'error':safe_error(e) if isinstance(e,Invalid) else 'input unavailable or too deeply nested'}));return 2
if __name__=='__main__':sys.exit(main())

SHA-256: a854b03639ea72c6b1d30e6ac3f106dd6416bf248515c15731f9a8a901f495cf