# Approved module interfaces

Python modules are imported from the package directory (standalone scripts, not installed namespace).

## data.py / protocol.py
Reuse Suite26 mint_data.Table / Prepared / Preprocessor / load_fold / common_feature_names / assert_future / shuffle_history / build_history. Table has x,course_meta,course,student,semester,grade,y,faculty,sample_id,feature_names,faculty_names and subset(indices). Prepared(x,course_meta,course_id,table). Preprocessor v2 x concatenates standardized table.x + finite flags of all table.x + faculty onehot. course_meta remains 34 values/flags. build_history adds embargo=0, permitting bank.semester < query.semester-embargo. Table schemas identical train/query.
protocol.faculty_weights(table): mean-one inverse faculty count.
protocol.choose_origins(table,target_semester,n_origins=2,min_rows=2000,min_faculty_rows=30,min_positive=5,min_negative=20,min_train_rows=5000,coverage=1.0): return (list of latest eligible integer semester origins in ascending order, pandas support audit). SAME term origin%3==target%3. Each origin must have earlier train >= min_train_rows and every eligible faculty prior train >=min_faculty_rows. min_rows applies to TOTAL semester rows; min_faculty_rows applies to each validation faculty and its earlier training rows. Eligible cells meet faculty-row/positive/negative constraints. Audit all semesters/faculties with fields semester,faculty,rows,positives,negatives,train_rows,train_faculty_rows,same_term,eligible,reason,origin_eligible,selected. UnsupportedOriginsError(audit) if none; callers print/save full audit on failure. protocol.prior_evidence(bank_table,query_table,embargo=0) returns float32 [N,2] strict earlier cumulative faculty failure/performance priors; performance known grade/10 else 1-y; defaults .1,.65. protocol.origin_cells(audit,origin) returns eligible faculty names.

## memory.py (root owns)
MEMORY_NAMES 14 dimensions: failure_supported,performance_supported,performance_sd,failure_relevance_contrast,effective_support_log,retained_history_log,full_history_log,recency_log,same_course_mass,observed_grade_mass,attention_entropy,history_present,prior_failure,prior_performance.
Reader(n_courses,meta_dim=34,hidden=24): shared course encoder course ID embedding + metadata MLP, normalized output; root logits course relevance + learned age decay + same-course bonus. auxiliary failure/grade heads train only. .config dictionary, .root_logits(batch), .evidence(batch,path_bias=None,uniform=False,no_outcomes=False), returns (summaries, attention).
reader_fingerprint(reader,include_heads=True).
EvidenceProvider(bank:Prepared,query:Prepared,history:HistoryIndex,reader=None,path_strength=0,mode='learned',device='cpu',batch_size=2048,embargo=0,cache=True): mode current/deterministic/learned; .raw=query.x; .raw_names; .memory_names; .comparable_features=2*len(table.feature_names); .reader_hash; .features(indices,path=()) returns [len(indices),14] or [len,0] current; .root_features(); .batch(indices) torch tensors on device; .path_bias(indices,path) numpy shape[len,H]; path tuple entries (feature_index,threshold,left_bool). Skip non-comparable ancestor indices. .assert_immutable(); .diagnostics() returns per-query pandas dataframe. Learned cache only course base[N,hidden] and logits[N,H]; no N*H*raw_dim tensor. Frozen hash checks before forest fit/predict. Interventions .clone(intervention,seed=...): no_memory,no_outcomes,uniform_attention,no_path,history_8,shuffled_history; memory interventions alone, raw features unchanged; clone shares permissible bank/query, recomputes strict histories.
pretrain_reader(reader,provider,weights,epochs=3,max_rows=120000,batch_size=512,lr=.001,seed=...,context=None) returns list epoch dictionaries, prints context incl seed. Weighted BCE+.15 grade MSE+.002 normalized attention concentration. Retrieval-only gradient audit separated auxiliary heads. Provider may cache=False for fitting.

## native.py (root owns)
BoostConfig(trees=128,depth=4,bins=63,min_leaf=40,min_hessian=1.,l2=5.,split_penalty=0.,learning_rate=.05,leaf_clip=2.).
Booster(config).fit(provider,y,weights=None,callback=None): hard tree growth, callback(model,number_of_trees) each iteration; .trees list nested dict nodes, leaf nodes {'leaf':float,'rows':N,'hessian':H}; internal nodes feature index over raw then memory, threshold,left,right,gain,rows,hessian,path (ancestor triples), soft_scale. .intercept,.config,.reader_hash,.raw_names.
.tree_values(tree,provider,indices=None) exact hard contribution; .decision_function(provider,trees=None); .predict_proba(provider,trees=None) returns 1D failure scores; .diagnostics() returns (JSONsummary,pandas nodes); .to_dict()/.from_dict(state).
ArrayProvider(x,names=None): raw only,reader_hash=None, features(empty),root_features(empty),assert_immutable.
split_gain(GL,HL,GR,HR,l2,penalty=0).

## adapt.py (root owns)
propose(reader,train_provider,forest,weights,epochs=1,max_rows=10000,batch_size=128,lr=.0002,max_trees=8,temperature=1.,seed=...,context=None) returns list log dictionaries, modifies reader in place. Select <=8 attention-sensitive memory-split trees; full reference hard logits and selected hard terms fixed at start; differentiable sigmoid subtree proposals; main BCE+.2 auxiliary. Log main retrieval gradient separately. If no eligible tree, explicit skipped record. Caller MUST create new provider and regrow entire forest from intercept afterward. Proposal reference grows config max_trees in selection and refit; final forest scores selected tree budget.

## experiment.py (assigned independent module)
VARIANTS=('stock','native','deterministic','global','path','mcgb'), score columns suite27_<variant>.
Config dataclass depth_grid=(3,4),tree_grid=(32,64,96,128),path_grid=(0.,1.5), max_trees=128, bins=63,min_leaf=40,min_hessian=1.,l2=5.,learning_rate=.05,leaf_clip=2., max_history=32,history_embargo=0,hidden=24,reader_epochs=3,reader_max_rows=120000,reader_batch=512,reader_lr=.001,adapt_epochs=1,adapt_max_rows=10000,adapt_batch=128,adapt_lr=.0002,adapt_trees=8,device='cpu',batch_size=2048,seeds=(20261002,),variants=VARIANTS.
select_recipes(history:Table,origins:list,origin_audit:DataFrame,config:Config,out_dir:Path) -> dict variant -> {depth,trees,path_strength,cycle,development_ap}; writes selection cells/summary/reader_training/adaptation and selected recipes JSON, prints all, trains independently at each origin. Weights faculty balanced, no class balancing. Every candidate same eligible cells/origins/seeds. AP average over faculty-origin-seed cells, undefined AP excluded by protocol. Ties prefer cycle0/fewer trees/shallower/less path. Stock HGB equal access independently selected trees/depth, early_stopping=False. One-class class-aware score helper. Can optimize shared frozen root caches but no mixing states across origins.
refit_variant(history,target,variant,recipe,config,seed) -> (bundle dict, 1D scores, artifacts dict). Artifacts keys reader_log/adapt_log (list),tree_summary(dict),tree_nodes(DataFrame),memory_diagnostics(DataFrame),provider (runtime-only),model (runtime-only). Bundle format_version1, variant,seed,recipe,preprocessor state,reader_config/state or None,forest (Boosterstate) or stock_model (HGB),max_history,history_embargo. Optional coadapt intermediate max_trees fixed, final refit selectedtrees. fit reader anew on full history, matching selected recipe.
load_bundle(bundle,history,target,device='cpu') -> (model,provider,scores); enforce reader hash pair. Stock appropriate classes mapping. No bank duplication in checkpoint.
interventions(model,provider,y,variant,seed) -> (per-faculty DataFrame, score_frame DataFrame) all memory interventions, changed_score_fraction/mean_abs/max_abs deltas vs baseline. Raw/stock return headered emptyframes. No_outcomes removes grade+failure values together; do not overclaim causal gain.
regimes(table,scores,provider,variant,seed) -> DataFrame all faculties history=0,1-4,5-16,17+ plus known/unknowncourse; metrics with row/positive support.

## CLI/reporting (assigned independent module)
Copy/adapt Suite26 mint_metrics.py to evaluation.py: CORE_MODELS six suite27 names, primary mcgb, component ladder(native,stock),(deterministic,native),(global,deterministic),(path,global),(mcgb,path). Retain rigorous keyed references/bootstrap/operational threshold. Add priorMINT aliases suite26_mint/memory/tree->p_suite26_mint etc. Print ALL fold/fac metrics, all operational confusions/budgets, bootstrap. student_workload always stable columns even empty heldout.
runtime.py atomic_json(path,value),atomic_csv(path,frame),atomic_torch(path,value),file_hash(path),code_hashes() current .py/.sh,versions(),seed_all(seed),score_frame(table,fold,scores) with sample_id,student_id,course_id,semester ordinal converted raw original? Match Suite26 score_frame contract: inspect previous train file. print_table(title,frame),safe_json.
train_suite27.py root/cache/structured/out/faculties/folds/dev-folds/holdout-folds/seeds/variants/config grids/support args, reference dirs, bootstrap, threads/device, preflight/resume/no-diagnostics. Default root /root/disk_3tb/earlywarning/30072026 and result suite27_memory_conditioned_boosting. Common schema intersection across allrequestedfolds. Print all candidate origin support before fitting. Catch UnsupportedOriginsError print and save failureaudit production; preflight nooutput files. Manifest configuration/source/runtime/all inputs SHA256; mismatch refuses resume. Eachfold complete marker with allartifact hashes; only completefolds resumable. checkpoints model_<variant>_seed_<seed>.pt; keyed predictions perseed and averageoverseeds scorecolumn; per-faculty files accepted refs. aggregate write_report, studentworkload, seedvariation. target labels reporting only.
predict_suite27.py --checkpoint --cache-dir --structured-dir --out-file --device verifies original inputs/source/schema; reload same canonicalfold and print allfacmetrics.
run_suite27.sh unbufferedpython bashpipefail tee append stdout+stderr, timestamps. PYTHON override otherwise /root/miniconda3/envs/Huy/bin/python3 ifexists elsepython3. log default /root/disk_3tb/earlywarning/30072026/log/suite27_memory_conditioned_boosting.log SUITE27_LOG_DIR /SUITE27_LOG_FILE overrides.
collect_suite27_reports.py --results-dir --out-file [--include-predictions], excludes weights and default predictions but includes useful CSV/JSON/log/text and manifest.
smoke_test.sh generates fixture 16studentsfold1/2, allsix2-4treesdepth2epochs1, originminrows8,minfaculty4,pos1,neg1,mintrain8,origins1; runmain thenreload/resume/collector. requirements tested broadcompatible.
