brandiejanow's picture
Deploy tested private workspace
2b13ae5 verified
Raw History Blame Contribute Delete
11.4 kB
(function(root){'use strict';function probability(p){if(typeof p!=='number'||!Number.isFinite(p)||p<0||p>1)throw Error('Probability must be between 0 and 1.');return p}function brier(p,y){probability(p);if(y!==0&&y!==1)throw Error('Outcome must be 0 or 1.');return (p-y)**2}function equilibria(m){if(!Array.isArray(m)||m.length!==4||m.some(x=>!Array.isArray(x)||x.length!==2||x.some(v=>typeof v!=='number'||!Number.isFinite(v))))throw Error('Enter four finite payoff pairs.');return m.map((v,i)=>v[0]>=m[i^2][0]&&v[1]>=m[i^1][1]?i:-1).filter(i=>i>=0)}function expected(p,yes,no){probability(p);if(!Number.isFinite(yes)||!Number.isFinite(no))throw Error('Enter finite outcome values.');return p*yes+(1-p)*no}function routeQuestion(question){
if(typeof question!=='string'||!question.trim())throw Error('Enter a question first.');
const q=question.toLowerCase();
const decision=/\b(should|recommend|best option|worth it|worth continuing|worth my time|waste of time|worth developing|worth pursuing|decide|decision|choose|choice|opportunity cost|which option|better off|worth my time)\b/.test(q);
const forecast=decision||/\b(will|forecast|predict|probability|likelihood|likely|chances|outlook|future|by 20\d{2})\b/.test(q);
const strategy=/\b(negotia\w*|competit\w*|rival\w*|bargain\w*|incentive\w*|strategic interaction|game theory|partner\w*|cooperat\w*|respond|retaliat\w*|interdependent)\b/.test(q);
const counter=decision||/\b(what if|counterfactual|alternative\w*|instead|versus|scenario\w*|if .{1,120}\bwould)\b/.test(q);
return [
{id:'research',name:'Empirical research',active:true,reason:'Establish the facts, baseline and relevant research.'},
{id:'verification',name:'Verification',active:true,reason:'Check important claims against evidence and document uncertainty.'},
{id:'forecasting',name:'Forecasting',active:forecast,reason:'Consider measurable future outcomes where evidence permits.'},
{id:'strategy',name:'Strategic interaction',active:strategy,reason:'Examine incentives, choices and responses among parties.'},
{id:'counterfactual',name:'Counterfactual inquiry',active:counter,reason:'Compare plausible alternative circumstances or decisions.'},
{id:'decision',name:'Decision science',active:decision,reason:'Evaluate options against stated objectives and opportunity costs.'}
]}
function answerKind(value){
if(value===null)return 'unknown';
if(typeof value!=='string'||!value.trim())return 'missing';
if(/^(?:i (?:do not|don't) know|not sure|unknown|unsure|n\/a|not applicable|no idea|prefer not to say|skip|yes|no)[.! ]*$/i.test(value.trim()))return 'unknown';
return 'provided';
}
function clarificationPlan(question,context=''){
const routes=routeQuestion(question), q=question.trim(), all=q+'\n'+String(context||'');
const is=id=>routes.some(r=>r.id===id&&r.active);
const fields=[];
const field=(id,prompt,why,example)=>fields.push({id,prompt,why,example});
// Treat explicit labeled inputs as already provided; do not infer facts from keywords alone.
const stated=labels=>{const re=new RegExp('(?:^|\\n|;)\\s*(?:'+labels+')\\s*:\\s*([^\\n;]+)','im');const m=all.match(re);return !!m&&answerKind(m[1])==='provided'};
const dateSpecified=/\b(?:by|before|until|through|during|in|within|over|after|between)\s+(?:the\s+)?(?:end of\s+)?(?:20\d{2}|(?:next\s+)?\d+\s+(?:days?|weeks?|months?|years?)|next\s+(?:week|month|year|quarter)|(?:January|February|March|April|May|June|July|August|September|October|November|December)\b)/i.test(all)||/\b20\d{2}-\d{2}-\d{2}\b/.test(all)||stated('time horizon|deadline|timeframe|evaluation date');
const project=/\b(research initiative|initiative|project|business|company|organization|programme|program|startup|venture|website|platform)\b/i.test(q);
const personal=/\b(i|my|me|our|we)\b/i.test(q);
const decision=is('decision');
const subjective=/\b(matter|worth|successful|succeed|success|better|improve|important|valuable|relevant|grow|effective|good idea|make a difference)\b/i.test(q);
const unclear=/^(?:what is|what about|is|will|does|should|can)\s+(?:this|that|it|they|he|she|we|i)(?:\s|\?|$)/i.test(q)&&q.split(/\s+/).length<10;
if(decision){
if(!stated('current situation|baseline|project|subject|background|evidence'))field('baseline',project?'What is the initiative, what stage is it at, and what has it achieved so far?':'What decision are you facing, and what is the current situation?','We need the actual starting point rather than assumptions about your circumstances.','A short anonymized description, existing results, and relevant evidence or a public source.');
if(!stated('goal|objective|success|success criteria|desired outcome'))field('objective','What outcome matters most to you, and how would you recognize success?','A recommendation depends on your objective. Different objectives can favor different choices.','Income, time saved, research use, career prospects, personal satisfaction, or another outcome.');
if(!stated('alternatives|options|choices'))field('alternatives','What realistic alternatives are you considering?','We need a genuine comparison, including maintaining, reducing or stopping the current activity where relevant.','Continue at the present level; reduce involvement; take a paid role; pursue a specific alternative.');
if(!stated('constraints|costs|resources|budget|available time'))field('constraints','What constraints or commitments affect these choices?','Time, resources and obligations can change whether an option is feasible or worthwhile.','Approximate time, costs, budget, responsibilities or unacceptable risks. Ranges are fine.');
if(!dateSpecified)field('horizon','When would you want to see results or reconsider the decision?','The best option can differ over six months and five years.','Six months, one year, or a specific date.');
}else if(is('forecasting')){
if(unclear||personal&&project&&!stated('current situation|baseline|project|subject|background|evidence'))field('baseline','What exactly are we forecasting, and what is known about its current situation?','The subject and starting point must be identified.','An organization, observable event or project and relevant facts.');
if(subjective&&!stated('metric|outcome|success criteria|threshold|definition'))field('metric','What observable outcome would count as success or change?','A forecast needs an outcome that can be checked rather than a subjective impression.','An institution adopts the research, revenue reaches a threshold, or a specific event occurs.');
if(!dateSpecified)field('horizon','By when should the outcome occur or be measured?','Probabilities depend on a defined time horizon.','By December 31 of a specified year, or within the next 12 months.');
}else if(personal&&/\b(behavio[u]?r|feel\w*|relationship|partner|friend|boss|colleague|think of me|care about me|trust|intentions?|motives?)\b/i.test(q)){
if(!stated('observations|evidence|current situation|background'))field('observations','What have you directly observed, and what is your interpretation?','We need to separate observable events from possible explanations or another person’s unknown intentions.','Anonymized actions, statements, frequency and relevant changes over time.');
if(!stated('goal|objective|desired outcome'))field('objective','What are you trying to understand or decide?','This determines whether research, a conditional forecast or decision analysis is appropriate.','An explanation of the behavior, a comparison of options or a measurable future outcome.');
}else if(unclear&&!String(context||'').trim()){
field('subject','What are you referring to, and what would you like to know about it?','The question does not identify the subject clearly.','Name the subject and the specific issue.');
}
return fields;
}
function intakeAssessment(fields,answers={}){
const missing=fields.filter(f=>answerKind(answers[f.id])==='missing').map(f=>f.id);
const unknown=fields.filter(f=>answerKind(answers[f.id])==='unknown').map(f=>f.id);
return {state:missing.length?'needs clarification':unknown.length?'conditional planning only':'initial questions addressed; evidence not verified',missing,unknown};
}
const sourceLimits=Object.freeze({count:20,fileBytes:10*1024*1024,totalBytes:50*1024*1024,textBytes:1024*1024,excerptChars:100000});
function sourceURL(value){
if(typeof value!=='string'||!value.trim()||value.length>4096)throw Error('Enter a complete website URL (up to 4096 characters).');
let u;try{u=new URL(value.trim())}catch(e){throw Error('Enter a complete HTTP or HTTPS URL.')}
if(!['http:','https:'].includes(u.protocol)||!u.hostname||u.username||u.password)throw Error('Use a public HTTP(S) URL without embedded credentials.');
return u.href;
}
function filePolicy(name,size){
const ext=String(name||'').toLowerCase().split('.').pop();
const text=['txt','md','csv','tsv','json','jsonl'];
const binary=['pdf','docx','xlsx','pptx','png','jpg','jpeg','webp'];
if(!text.includes(ext)&&!binary.includes(ext))throw Error('Unsupported file format.');
if(!Number.isInteger(size)||size<=0||size>sourceLimits.fileBytes)throw Error('Each file must be nonempty and no larger than 10 MiB.');
return text.includes(ext)&&size<=sourceLimits.textBytes?'local-text':'attachment-only';
}
function sourceSummary(records,scope){
if(!['expand','supplied','verify'].includes(scope))throw Error('Select a research scope.');
if(!Array.isArray(records))throw Error('Invalid source records.');
return {scope,total:records.length,links:records.filter(x=>x.kind==='link').length,textAvailable:records.filter(x=>x.status==='text available, unverified').length,attachmentOnly:records.filter(x=>x.status==='attached, not extracted').length,verified:0,needsSources:scope==='supplied'&&records.length===0};
}
function exportSources(records,includeText=false){
return records.map(r=>({id:r.id,kind:r.kind,title:r.title,provenance:'user supplied',status:r.status,verified:false,addedAt:r.addedAt,...(r.url?{url:r.url}:{}),...(r.kind==='file'?{fileName:r.fileName,size:r.size,mediaType:r.mediaType,originalFileIncluded:false}:{}),...(r.notes?{notes:r.notes}:{}),...(typeof r.text==='string'?{textIncluded:includeText,...(includeText?{text:r.text}:{textLength:r.text.length})}:{})}));
}
function resolveView(fragment){return String(fragment||'').replace(/^#/,'').toLowerCase()==='instruments'?'instruments':'home'}
function makeShareSummary(data){
const field=(name,max,required=true)=>{const s=typeof data[name]==='string'?data[name].trim():'';if(required&&!s)throw Error('Complete the '+name+' field.');if(s.length>max)throw Error('The '+name+' field is too long.');return s};
const title=field('title',140),outcome=field('outcome',420),caveat=field('caveat',240),raw=field('reference',300,false);
const reference=raw?sourceURL(raw):'';
return {title,outcome,caveat,reference,status:'User-prepared summary · not independently verified'};
}
function shareSummaryText(card){
return ['Forecasting Lab | Result summary',card.title,'Finding: '+card.outcome,'Uncertainty: '+card.caveat,card.reference?'Reference: '+card.reference:'',card.status].filter(Boolean).join('\n\n');
}
const api={makeShareSummary,shareSummaryText,resolveView,brier,equilibria,expected,routeQuestion,clarificationPlan,intakeAssessment,answerKind,sourceLimits,sourceURL,filePolicy,sourceSummary,exportSources};if(typeof module!=='undefined')module.exports=api;else root.Engine=api})(typeof globalThis!=='undefined'?globalThis:this);