# AI16 factual retrieval reproduction. Base R + its bundled tools package only.
# Rscript actual-source-study.R [native_source_directory] [output_directory]
# Reads three native CSVs, never JS/model JSON/answer tables. It recreates SHA256
# selection, authored documents/questions, exact ranking keys and finite metrics.
# It is a source-study program, not a general Unicode NFKC library. All compiled
# text in this retained study is already NFKC, as checked by the Python source
# audit. UTF-8 letter/number tokenization and case conversion are applied here.
# MovieLens README, citation and original use conditions remain applicable.

# The calling environment may supply the Unix name C.UTF-8 on Windows.
# Do not silently decode non-ASCII native titles in the fallback ASCII locale.
if(!isTRUE(l10n_info()[['UTF-8']])){
  if(.Platform$OS.type=='windows') suppressWarnings(Sys.setlocale('LC_CTYPE','.UTF-8'))
  if(!isTRUE(l10n_info()[['UTF-8']])) stop('Run this UTF-8 source study in a UTF-8 LC_CTYPE locale.')
}
markUTF8 <- function(x){ok<-validUTF8(x);Encoding(x[ok])<-'UTF-8';x}
argv <- markUTF8(commandArgs(trailingOnly=TRUE))
allArgs <- markUTF8(commandArgs())
fileArg <- sub('^--file=','',allArgs[grepl('^--file=',allArgs)][1])
here <- dirname(normalizePath(fileArg,mustWork=TRUE))
sourceDir <- if(length(argv)) normalizePath(argv[1],mustWork=TRUE) else file.path(dirname(here),'ai16-sources')
outDir <- if(length(argv)>1) argv[2] else file.path(here,'reproduced-r')
dir.create(outDir,recursive=TRUE,showWarnings=FALSE)
files <- c(country='actual32-country-observations-2024.csv',person='movielens-original-movies.csv',company='actual30-Apple-product-sales-FY2019-2024.csv')
expectedMD5 <- c(country='20579b4e1d4e3e016bf3340ab82d117e',person='ed94fab72b62442ef8150d9446e000d6',company='9c72921fbcf7b4617d54c9671b3ca391')
stopifnot(all(unname(tools::md5sum(file.path(sourceDir,files)))==expectedMD5))
raw <- lapply(files,function(f)read.csv(file.path(sourceDir,f),colClasses='character',check.names=FALSE,na.strings=NULL,fileEncoding='UTF-8-BOM'))
stopifnot(identical(vapply(raw,nrow,0L),c(country=32L,person=9742L,company=30L)))

# SHA256 for a batch of the declared ASCII selection messages (one block each).
# All arithmetic additions fit exactly within binary64; bit operations use safe
# unsigned 16-bit halves, avoiding R's reserved signed integer NA word.
u32 <- 4294967296; base <- 65536
bx <- function(x,y)as.double(bitwXor(as.integer(x%%base),as.integer(y%%base)))+base*as.double(bitwXor(as.integer(floor(x/base)),as.integer(floor(y/base))))
ba <- function(x,y)as.double(bitwAnd(as.integer(x%%base),as.integer(y%%base)))+base*as.double(bitwAnd(as.integer(floor(x/base)),as.integer(floor(y/base))))
bn <- function(x)u32-1-x
rr <- function(x,n)floor(x/2^n)+(x%%2^n)*2^(32-n)
hx <- function(s)strtoi(substr(s,1,4),16L)*base+strtoi(substr(s,5,8),16L)
K <- vapply(strsplit(paste('428a2f98 71374491 b5c0fbcf e9b5dba5 3956c25b 59f111f1 923f82a4 ab1c5ed5','d807aa98 12835b01 243185be 550c7dc3 72be5d74 80deb1fe 9bdc06a7 c19bf174','e49b69c1 efbe4786 0fc19dc6 240ca1cc 2de92c6f 4a7484aa 5cb0a9dc 76f988da','983e5152 a831c66d b00327c8 bf597fc7 c6e00bf3 d5a79147 06ca6351 14292967','27b70a85 2e1b2138 4d2c6dfc 53380d13 650a7354 766a0abb 81c2c92e 92722c85','a2bfe8a1 a81a664b c24b8b70 c76c51a3 d192e819 d6990624 f40e3585 106aa070','19a4c116 1e376c08 2748774c 34b0bcb5 391c0cb3 4ed8aa4a 5b9cca4f 682e6ff3','748f82ee 78a5636f 84c87814 8cc70208 90befffa a4506ceb bef9a3f7 c67178f2'), ' +')[[1]],hx,0.0)
H <- vapply(strsplit('6a09e667 bb67ae85 3c6ef372 a54ff53a 510e527f 9b05688c 1f83d9ab 5be0cd19',' ')[[1]],hx,0.0)
shaBatch <- function(strings){
 n<-length(strings); if(!n)return(character()); bytes<-lapply(strings,function(s)as.integer(charToRaw(enc2utf8(s))));stopifnot(all(lengths(bytes)<=55),all(vapply(bytes,function(x)all(x<128),TRUE)))
 block<-matrix(0,n,64)
 for(i in seq_len(n)){m<-length(bytes[[i]]);if(m)block[i,seq_len(m)]<-bytes[[i]];block[i,m+1]<-128;bits<-m*8;block[i,63]<-floor(bits/256);block[i,64]<-bits%%256}
 w<-vector('list',64)
 for(t in 1:16)w[[t]]<-as.vector(block[,(4*t-3):(4*t),drop=FALSE]%*%c(16777216,65536,256,1))
 for(t in 17:64){x<-w[[t-15]];y<-w[[t-2]];s0<-bx(bx(rr(x,7),rr(x,18)),floor(x/8));s1<-bx(bx(rr(y,17),rr(y,19)),floor(y/1024));w[[t]]<-(w[[t-16]]+s0+w[[t-7]]+s1)%%u32}
 v<-lapply(H,function(x)rep(x,n));a<-v[[1]];b<-v[[2]];c<-v[[3]];d<-v[[4]];e<-v[[5]];f<-v[[6]];g<-v[[7]];h<-v[[8]]
 for(t in 1:64){S1<-bx(bx(rr(e,6),rr(e,11)),rr(e,25));ch<-bx(ba(e,f),ba(bn(e),g));t1<-(h+S1+ch+K[t]+w[[t]])%%u32;S0<-bx(bx(rr(a,2),rr(a,13)),rr(a,22));maj<-bx(bx(ba(a,b),ba(a,c)),ba(b,c));t2<-(S0+maj)%%u32;h<-g;g<-f;f<-e;e<-(d+t1)%%u32;d<-c;c<-b;b<-a;a<-(t1+t2)%%u32}
 ans<-list(a,b,c,d,e,f,g,h);out<-rep('',n)
 for(j in 1:8){z<-(ans[[j]]+H[j])%%u32;out<-paste0(out,sprintf('%04x%04x',as.integer(floor(z/base)),as.integer(z%%base)))}
 out
}
stopifnot(identical(shaBatch(c('','abc')),c('e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855','ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad')))
key <- function(prefix,id)shaBatch(paste0(prefix,'|',id))
models<-setNames(lapply(files,function(x)list(documents=list(),queries=list())),names(files))
addDoc<-function(kind,id,text,native,row,answer){
 at<-gregexpr(answer,text,fixed=TRUE)[[1]];stopifnot(at[1]>0);start<-tail(at,1)-1
 models[[kind]]$documents[[length(models[[kind]]$documents)+1]]<<-list(id=id,text=text,sourceRow=as.character(row),nativeID=native,answerText=answer,answerStart=start,answerEnd=start+nchar(answer,type='chars'))
}
addQuery<-function(kind,id,text,gold,answer,role,group,type)models[[kind]]$queries[[length(models[[kind]]$queries)+1]]<<-list(id=id,text=text,gold=gold,answerText=answer,role=role,group=group,queryType=type)
countries<-unique(raw$country$countryISO3);countries<-countries[order(key('AI16-country-role',countries),countries,method='radix')];roles<-setNames(c(rep('train',8),rep('validation',4),rep('test',4)),countries)
for(i in seq_len(nrow(raw$country))){r<-raw$country[i,];id<-paste('WB',r$countryISO3,r$indicatorID,r$date,sep=':');a<-r$originalValueToken
 addDoc('country',id,paste0('World Bank observation. Country ',r$countryName,' (',r$countryISO3,'). Indicator ',r$indicatorName,'; code ',r$indicatorID,'. Observation year ',r$date,'. Recorded value ',a,' annual percent.'),paste(r$countryISO3,r$indicatorID,sep=':'),r$sourceRow,a)
 addQuery('country',paste0('query:',id),paste0('What is the recorded ',r$indicatorName,' for ',r$countryName,' in ',r$date,'?'),id,a,unname(roles[r$countryISO3]),r$countryISO3,'native-name lookup')
}
movie<-raw$person;corpusSHA<-key('AI16-person-corpus',movie$movieId);chosen<-order(corpusSHA,movie$movieId,method='radix')[1:240];querySHA<-rep('',nrow(movie));querySHA[chosen]<-key('AI16-person-query',movie$movieId[chosen]);qc<-chosen[order(querySHA[chosen],movie$movieId[chosen],method='radix')][1:24];movieRoles<-setNames(c(rep('train',12),rep('validation',6),rep('test',6)),movie$movieId[qc])
ledger<-list()
for(i in seq_len(nrow(movie))){r<-movie[i,];selected<-i%in%chosen;role<-unname(movieRoles[r$movieId]);if(is.na(role))role<-''
 ledger[[i]]<-list(sourceRow=i,movieId=r$movieId,title=r$title,genres=r$genres,corpusSHA=corpusSHA[i],in240Corpus=tolower(as.character(selected)),querySHA=querySHA[i],queryRole=role)
 if(!selected)next;id<-paste0('MovieLens:movie:',r$movieId);addDoc('person',id,paste0('MovieLens catalog record. Movie ID ',r$movieId,'. Title ',r$title,'. Recorded genres ',r$genres,'.'),r$movieId,i,r$genres)
 if(nzchar(role))addQuery('person',paste0('query:',id),paste0('What genres are recorded for the film ',r$title,'?'),id,r$genres,role,r$movieId,'native-name lookup')
}
for(i in seq_len(nrow(raw$company))){r<-raw$company[i,];id<-paste('Apple',r$product,r$fiscalYear,sep=':');y<-as.integer(r$fiscalYear);role<-if(y<=2021)'train'else if(y==2022)'validation'else'test';a<-r$originalUSDMillionsToken
 addDoc('company',id,paste0('Apple annual filing observation. Product group ',r$product,'. Fiscal year ',r$fiscalYear,'. Net sales in nominal USD millions ',a,'. Filing fiscal year ',r$sourceFilingFY,'.'),paste(r$product,r$fiscalYear,sep=':'),i,a)
 addQuery('company',paste0('query:',id),paste0('What are Apple ',r$product,' net sales in nominal USD millions for fiscal year ',r$fiscalYear,'?'),id,a,role,r$fiscalYear,'native-name lookup')
}
for(i in seq_len(nrow(raw$country))){r<-raw$country[i,];if(r$indicatorID!='NY.GDP.MKTP.KD.ZG')next;id<-paste('WB',r$countryISO3,r$indicatorID,r$date,sep=':');addQuery('country',paste0('alias:',id),paste0('How fast did the economy expand in ',r$countryName,' during ',r$date,'?'),id,r$originalValueToken,unname(roles[r$countryISO3]),r$countryISO3,'authored paraphrase challenge')}
topics<-list()
for(i in chosen){r<-movie[i,];if(!grepl('\\([0-9]{4}\\)[[:space:]]*$',r$title))next;year<-sub('.*\\(([0-9]{4})\\)[[:space:]]*$','\\1',r$title)
 for(genre in strsplit(r$genres,'|',fixed=TRUE)[[1]])if(genre!='(no genres listed)'){g<-paste(year,genre,sep='|');topics[[g]]<-c(topics[[g]],paste0('MovieLens:movie:',r$movieId))}}
groups<-names(topics);groups<-groups[order(key('AI16-person-topic-query',groups),groups,method='radix')][1:12]
for(i in seq_along(groups)){g<-groups[i];p<-strsplit(g,'|',fixed=TRUE)[[1]];gold<-sort(topics[[g]],method='radix');role<-if(i<=6)'train'else if(i<=9)'validation'else'test';addQuery('person',paste0('topic:',g),paste0('Which movie catalog records list ',p[2],' and a release year of ',p[1],'?'),gold,paste(gold,collapse=' | '),role,g,'authored multi-relevant catalog challenge')}
aliases<-c(iPhone='handset',iPad='tablet',Mac='computer')
for(i in seq_len(nrow(raw$company))){r<-raw$company[i,];alias<-unname(aliases[r$product]);if(is.na(alias))next;id<-paste('Apple',r$product,r$fiscalYear,sep=':');y<-as.integer(r$fiscalYear);role<-if(y<=2021)'train'else if(y==2022)'validation'else'test';addQuery('company',paste0('alias:',id),paste0('What are Apple ',alias,' net sales in nominal USD millions for fiscal year ',r$fiscalYear,'?'),id,r$originalUSDMillionsToken,role,r$fiscalYear,'authored paraphrase challenge')}

# Nonnegative integer limbs, base 10^6. The common denominator LCM(1..N+60)
# makes every rarity and RRF ranking comparison exact, including equal scores.
# Published R fractions may be unreduced; their rational values are exact.
B<-1e6
trim<-function(x){while(length(x)>1&&tail(x,1)==0)x<-head(x,-1);x}
bmul<-function(x,k){out<-numeric(length(x));carry<-0;for(i in seq_along(x)){v<-x[i]*k+carry;out[i]<-v%%B;carry<-floor(v/B)};while(carry>0){out<-c(out,carry%%B);carry<-floor(carry/B)};trim(out)}
badd<-function(x,y){n<-max(length(x),length(y));length(x)<-n;length(y)<-n;x[is.na(x)]<-0;y[is.na(y)]<-0;out<-numeric(n);carry<-0;for(i in seq_len(n)){v<-x[i]+y[i]+carry;out[i]<-v%%B;carry<-floor(v/B)};if(carry)out<-c(out,carry);trim(out)}
bdiv<-function(x,k){out<-numeric(length(x));carry<-0;for(i in rev(seq_along(x))){v<-carry*B+x[i];out[i]<-floor(v/k);carry<-v%%k};stopifnot(carry==0);trim(out)}
bstr<-function(x){x<-trim(x);if(length(x)==1)return(sprintf('%.0f',x));paste0(sprintf('%.0f',tail(x,1)),paste(sprintf('%06.0f',rev(head(x,-1))),collapse=''))}
commonDenominator<-function(limit){D<-1;for(p in 2:limit){prime<-all(p%%seq_len(max(1,floor(sqrt(p))))[-1]!=0);if(!prime)next;power<-p;while(power*p<=limit)power<-power*p;D<-bmul(D,power)};D}
rankKeys<-function(keys,ids){str<-vapply(keys,bstr,'');pad<-paste0(strrep('0',max(nchar(str))-nchar(str)),str);order(pad,ids,decreasing=c(TRUE,FALSE),method='radix')}
gcd<-function(a,b){while(b!=0){t<-a%%b;a<-b;b<-t};a}
rat<-function(n,d=1){stopifnot(d>0);g<-gcd(n,d);c(n/g,d/g)}
radd<-function(a,b)rat(a[1]*b[2]+b[1]*a[2],a[2]*b[2])
rstr<-function(x)if(x[2]==1)sprintf('%.0f',x[1])else paste(sprintf('%.0f',x),collapse='/')
rmean<-function(xs){z<-Reduce(radd,xs,init=c(0,1));rat(z[1],z[2]*length(xs))}
words<-function(s){s<-tolower(enc2utf8(s));m<-gregexpr('[\\p{L}\\p{N}]+',s,perl=TRUE)[[1]];if(m[1]<0)return(character());regmatches(s,list(m))[[1]]}
metric<-function(ids,gold){hits<-0;first<-0;ap6<-0;for(i in seq_len(min(3,length(ids))))if(ids[i]%in%gold){hits<-hits+1;if(!first)first<-i;ap6<-ap6+hits*6/i};list(hits=hits,precision=rat(hits,3),recall=rat(hits,length(gold)),RR=if(first)rat(1,first)else rat(0),AP=rat(ap6,6*length(gold)),coverage=rat(min(3,length(ids)),3))}
rowAppend<-function(x,row)c(x,list(row))
docRows<-queryRows<-scoreRows<-evalRows<-summaryRows<-selectRows<-chunkRows<-quoteRows<-list()
for(kind in names(models)){
 docs<-models[[kind]]$documents;qs<-models[[kind]]$queries;ids<-vapply(docs,function(d)d$id,'');tf<-lapply(docs,function(d)table(words(d$text)));df<-table(unlist(lapply(tf,names),use.names=FALSE));D<-commonDenominator(length(docs)+60);Ds<-bstr(D);parts<-lapply(seq_len(length(docs)+60),function(k)bdiv(D,k));results<-list()
 for(d in docs)docRows<-rowAppend(docRows,c(list(case=kind),d))
 for(q in qs)queryRows<-rowAppend(queryRows,list(case=kind,queryID=q$id,text=q$text,goldIDs=paste(q$gold,collapse='|'),answerText=q$answerText,role=q$role,group=q$group,queryType=q$queryType))
 for(q in qs){qt<-table(words(q$text));ov<-numeric(length(docs));rare<-vector('list',length(docs))
  for(i in seq_along(docs)){v<-tf[[i]][names(qt)];v[is.na(v)]<-0;coef<-as.numeric(qt)*as.numeric(v);ov[i]<-sum(coef);rk<-0
   for(j in which(coef>0)){den<-1+as.integer(df[names(qt)[j]]);rk<-badd(rk,bmul(parts[[den]],coef[j]))};rare[[i]]<-rk}
  orders<-list(overlap=order(-ov,ids,method='radix'),rarity=rankKeys(rare,ids));ranks<-lapply(orders,function(o){r<-integer(length(o));r[o]<-seq_along(o);r})
  rrf<-lapply(seq_along(ids),function(i)badd(parts[[60+ranks$overlap[i]]],parts[[60+ranks$rarity[i]]]))
  orders$rrf<-rankKeys(rrf,ids);ranks$rrf<-integer(length(ids));ranks$rrf[orders$rrf]<-seq_along(ids)
  for(i in seq_along(ids))scoreRows<-rowAppend(scoreRows,list(case=kind,queryID=q$id,documentID=ids[i],overlapScore=sprintf('%.0f',ov[i]),rarityScore=paste0(bstr(rare[[i]]),'/',Ds),rrfScore=paste0(bstr(rrf[[i]]),'/',Ds),overlapRank=ranks$overlap[i],rarityRank=ranks$rarity[i],rrfRank=ranks$rrf[i]))
  ev<-lapply(orders,function(o)metric(ids[o],q$gold));results<-rowAppend(results,list(query=q,orders=orders,metrics=ev))
  for(p in names(ev)){m<-ev[[p]];er<-list(case=kind,queryID=q$id,role=q$role,queryType=q$queryType,profile=p,topIDs=paste(head(ids[orders[[p]]],3),collapse='|'),goldCount=length(q$gold),hits=m$hits);for(k in c('precision','recall','RR','AP','coverage'))er[[k]]<-rstr(m[[k]]);evalRows<-rowAppend(evalRows,er)}
 }
 val<-list()
 for(p in c('overlap','rarity','rrf'))for(role in c('train','validation','test')){
  rr0<-Filter(function(r)r$query$role==role,results);sr<-list(case=kind,profile=p,role=role,queries=length(rr0));for(k in c('precision','recall','RR','AP'))sr[[paste0('mean',k)]]<-rstr(rmean(lapply(rr0,function(r)r$metrics[[p]][[k]])));summaryRows<-rowAppend(summaryRows,sr)
  if(role=='validation')val[[p]]<-rmean(lapply(rr0,function(r)r$metrics[[p]]$RR))
 }
 selected<-'overlap';for(p in c('rarity','rrf'))if(val[[p]][1]*val[[selected]][2]>val[[selected]][1]*val[[p]][2])selected<-p
 sr<-Filter(function(r)r$case==kind&&r$profile==selected&&r$role=='test',summaryRows)[[1]]
 selectRows<-rowAppend(selectRows,list(case=kind,selectedProfile=selected,validationRR=rstr(val[[selected]]),testPrecision=sr$meanprecision,testRecall=sr$meanrecall,testRR=sr$meanRR,testAP=sr$meanAP))
 for(r in results){q<-r$query;remaining<-96;supplied<-list()
  for(i in head(r$orders[[selected]],3)){d<-docs[[i]];text<-d$text;mm<-gregexpr('[\\p{L}\\p{N}]+',text,perl=TRUE)[[1]];stopifnot(mm[1]>0);starts<-as.integer(mm)-1;ends<-starts+attr(mm,'match.length');N<-length(starts)
   for(start in seq(0,N-1,24)){end<-min(start+32,N);n<-min(remaining,end-start);prefix<-if(n)substr(text,starts[start+1]+1,ends[start+n])else''
    chunkRows<-rowAppend(chunkRows,list(case=kind,queryID=q$id,documentID=d$id,tokenStart=start,tokenEnd=end,start=starts[start+1],end=ends[end],text=substr(text,starts[start+1]+1,ends[end]),wordTokens=end-start,selectedWordTokens=n,selectedEnd=if(n)ends[start+n]else'',selectedText=prefix,truncated=tolower(as.character(n>0&&n<end-start))))
    if(n){supplied<-rowAppend(supplied,list(id=d$id,text=prefix));remaining<-remaining-n}
   }
  }
  gd<-Filter(function(d)d$id%in%q$gold,docs)[[1]];quote<-gd$answerText
  quoteRows<-rowAppend(quoteRows,list(case=kind,queryID=q$id,goldDocumentID=gd$id,quote=quote,literalInOriginal=tolower(as.character(grepl(quote,gd$text,fixed=TRUE))),literalInSupplied=tolower(as.character(any(vapply(supplied,function(s)s$id==gd$id&&grepl(quote,s$text,fixed=TRUE),TRUE)))),usedWordTokens=96-remaining))
 }
}
writeRows<-function(name,rows){d<-do.call(rbind,lapply(rows,function(r)as.data.frame(r,stringsAsFactors=FALSE,check.names=FALSE)));write.csv(d,file.path(outDir,name),row.names=FALSE,na='',fileEncoding='UTF-8');list(file=name,rows=nrow(d),columns=ncol(d),bodyFields=nrow(d)*ncol(d))}
outputs<-list(writeRows('derived302-documents.csv',docRows),writeRows('derived132-queries.csv',queryRows),writeRows('derived9742-movie-ledger.csv',ledger),writeRows('derived11616-all-candidate-scores.csv',scoreRows),writeRows('derived396-query-evaluations.csv',evalRows),writeRows('derived27-role-means.csv',summaryRows),writeRows('derived3-selected-profiles.csv',selectRows),writeRows('derived-all-context-chunks.csv',chunkRows),writeRows('derived132-literal-citation-checks.csv',quoteRows))
write.csv(do.call(rbind,lapply(outputs,as.data.frame)),file.path(outDir,'manifest.csv'),row.names=FALSE)
cat('PASS:302 documents;132 authored queries;11616 corpus/query pairs;34848 exact score values;9 derived CSVs.\n')
cat('Pure R SHA256 selection; integer-limb exact ranking keys; reduced small rational metrics. Rarity/RRF fractions may be unreduced. No learned embeddings or generation.\n')
print(do.call(rbind,lapply(selectRows,as.data.frame)),row.names=FALSE)
