CalisFix Pro · AI

Loading AI engine…

// ═══════════════════════════════════════════════════ // MODULE 11: PROTOCOL ENGINE // ═══════════════════════════════════════════════════ const PROTOCOLS=[ {id:'standard', name:'Standard Sets', icon:'📋', rest_s:90, rest_h:'60–90s', rep_scheme:'3–5 × 5–12', benefit:'Baseline strength & skill mastery', use:'All levels · Every goal'}, {id:'cluster', name:'Cluster Sets', icon:'⚡', rest_s:240, rest_h:'180–300s', rep_scheme:'3 × (3+3+3) / 20s', benefit:'Breaks strength plateaus via fatigue management', use:'Intermediate+ · Strength plateau'}, {id:'mechanical_drop',name:'Mechanical Drop', icon:'🔽', rest_s:0, rest_h:'0s → 120s', rep_scheme:'3 × (fail → fail → fail)',benefit:'Maximum volume + hypertrophy in one set', use:'Intermediate+ · Hypertrophy'}, {id:'giant', name:'Giant Sets', icon:'🔥', rest_s:45, rest_h:'30–45s inter / 90s inter-set', rep_scheme:'3–4 ex × 3 rounds', benefit:'Elevates heart rate · Fat loss without joint impact', use:'Conditioning · Weight loss'}, {id:'pyramid', name:'Pyramid Sets', icon:'🔺', rest_s:60, rest_h:'45–60s', rep_scheme:'12 → 10 → 8 → 6', benefit:'Progressive volume overload across all rep ranges', use:'Beginner–Intermediate · Hypertrophy'}, {id:'pap', name:'PAP (Post-Activation)',icon:'💥', rest_s:240, rest_h:'180–300s', rep_scheme:'3 × 3 heavy → skill set', benefit:'Neurological activation amplifies skill performance', use:'Advanced · Skill athletes'}, {id:'iso_dyn', name:'ISO-DYN', icon:'🎯', rest_s:90, rest_h:'60–120s', rep_scheme:'Hold Xs + AMRAP reps', benefit:'Bridges isometric strength into dynamic output', use:'All levels · Skill integration'}, ]; const PROTOCOL_HINTS={ standard:'Work to your prescribed reps/sets. Focus on quality reps and consistent tempo.', cluster:'Do 3 reps, rest 20s, do 3 reps, rest 20s, do 3 reps = 1 cluster set. Rest 3–5 min between cluster sets. Allows near-maximal loads with better technique.', mechanical_drop:'Start at your hardest variation. Go to failure, immediately drop to the next easier variation, continue to failure. No rest within the drop — only rest between full rounds.', giant:'Cycle through 3–4 exercises back-to-back with 30–45s rest between each. Rest 90s between full rounds. Keeps heart rate elevated throughout.', pyramid:'Start at highest rep count, add difficulty each set. Rep count drops as intensity rises (12→10→8→6). If using only bodyweight, increase leverage each set.', pap:'Perform a near-maximal effort set (3 reps, 90–95% effort). Rest exactly 3–4 min, then execute your skill work. The heavy set amplifies motor unit recruitment for the skill.', iso_dyn:'Hold an isometric position (e.g., L-sit, planche lean, hollow body) for the prescribed time, then immediately perform the dynamic reps. No rest between iso and dynamic.', }; // Mechanical drop regression chains — ordered hardest to easiest const LEVERAGE_HIERARCHY={ pull_up: ['oap_neg','archer_pu','l_sit_pu','typewriter','wide_pu','close_pu','pullup','chin_up','inv_row','neg_pu','aus_row','scap_pull'], push_up: ['oap_neg_pu','ring_rto','ring_pu','archer_pushup','pseudo_pu','diamond_pu','wide_pushup','pushup','knee_pu','incline_pu','wall_pu'], dips: ['ring_wt_dip','wt_dip','ring_dip','russian_dip','bar_dip','neg_dip','bench_dip'], muscle_up: ['strict_mu','kipping_mu'], core: ['windshield','df_neg2','ttb','hang_lr','leg_raise','hollow','arch','plank'], }; // Per-exercise biomechanical coaching cues (ruri_recommendation) const RURI_TIPS={ pullup:'Pack the shoulder (depress + retract scapula) before your elbow flexes. Chin over bar — never crane the neck forward.', wide_pu:'Wider grip increases shoulder torque by ~40%. Track elbows at 45° to the torso to protect the rotator cuff.', archer_pu:'The extended arm is a counter-lever — it doubles the effective load. Control the descent in 3–4s to build the eccentric strength needed for OAP.', close_pu:'Supination strengthens the biceps brachii — a useful variation if lat width is the goal, as the biceps assist the lats at the bottom of the pull.', pushup:'Press through the base of the palm, not the wrist. Protract the scapulae fully at the top for complete serratus anterior activation.', diamond_pu:'Narrow base shifts load toward the medial tricep head. Elbows tracking backward (not flared) reduces shoulder impingement risk.', ring_pu:'Ring instability triples rotator-cuff demand. RTO (rings turned out at the top) adds pec and bicep recruitment — the gold standard push-up.', archer_pushup:'As the extended arm approaches horizontal, torque on the shoulder approaches OAP levels. Start with 30° arm extension and progress slowly.', bar_dip:'Lower until shoulder drops below elbow — not just 90°. Lean forward slightly to recruit more pec; upright to hit triceps.', ring_dip:'The ring path naturally pronate → supinate during the press — this is correct. RTO at top is mandatory for full muscle activation.', plank:'Posterior pelvic tilt (tucking the pelvis) flattens the lumbar spine. Glutes must be actively contracted — a passive plank does nothing.', hollow:'Imagine pressing your lower back through the floor. If the lower back arches, regress to a tuck immediately — arched hollow is a spinal extension exercise, not core.', leg_raise:'Initiate the movement from the lower abs, not hip flexors. If your lower back arches at the bottom, stop 10° short of the floor.', hang_lr:'Dead hang, no swing. Initiate from the core — the legs lead, not the hips. Full range: hips above the bar.', sh_cars:'Move only the shoulder joint through its full range of motion. If your spine moves at all, you have lost the dissociation — slow down and reduce ROM.', hip_cars:'Fix pelvis and spine completely — use a wall for reference. Move the hip through full 360° circumduction without compensation.', }; // ═══════════════════════════════════════════════════ // INTELLIGENT REST ENGINE // ═══════════════════════════════════════════════════ function calculateRestPeriod(protocol, goal, clientProfile){ const BASE={ standard:90, cluster:240, pap:240, mechanical_drop:120, giant:45, pyramid:60, iso_dyn:90, }; let rest=BASE[protocol]??90; // Goal modifiers if(goal==='weight_loss'&&['giant','pyramid'].includes(protocol))rest=Math.max(30,rest-15); if(['strength','skill'].includes(goal)&&['cluster','pap'].includes(protocol))rest=Math.min(300,rest+30); // Obese / XHeavy client: +30s, floor at 60s, protect joints const weightTier=typeof clientProfile==='string'?clientProfile[1]:''; const isObese=clientProfile==='obese'||weightTier==='X'; if(isObese)rest=Math.max(60,rest+30); return rest; // seconds } function fmtRest(s){ return s>=60?`${Math.floor(s/60)}m${s%60?` ${s%60}s`:''}`:`${s}s`; } function getRestBadge(protocol, goal, clientProfile){ const s=calculateRestPeriod(protocol,goal,clientProfile); const p=PROTOCOLS.find(x=>x.id===protocol)||{}; return{seconds:s, label:fmtRest(s), note:p.rest_h||''}; } function getMechanicalDropSequence(exId, skill){ const chain=LEVERAGE_HIERARCHY[skill]||[]; const idx=chain.indexOf(exId); if(idx<0)return[]; return chain.slice(idx,idx+4).map(id=>findEx(id)).filter(Boolean); } // ═══════════════════════════════════════════════════ // PROACTIVE ASSISTANT // ═══════════════════════════════════════════════════ const ProactiveAssistant={ detectPlateau(sessions){ const results=[]; ['pull_up','push_up','dips'].forEach(skill=>{ const wkMap={}; sessions.slice(0,30).forEach(s=>{ const d=new Date(s.session_date); d.setDate(d.getDate()-d.getDay()); // week start const wk=d.toISOString().split('T')[0]; (s.exercise_logs||[]).forEach(l=>{ const ex=findEx(l.exercise_id); if(ex?.skill===skill&&l.reps_or_seconds>0){ if(!wkMap[wk]||wkMap[wk]=3){ const vals=weeks.map(w=>wkMap[w]); const improved=vals[2]>vals[0]; if(!improved)results.push({skill,lastMax:vals[2],weeks:3}); } }); return results; }, getWeightLossRec(goals){ if(!goals||!goals.some(g=>['weight_loss','conditioning'].includes(g)))return null; return{ protocol:'giant', reason:'Giant sets sustain an elevated heart rate throughout the session — the most effective fat-burning protocol for bodyweight training. Avoids high-impact plyometrics that stress joints under load.', avoidProtocols:['pap','pyramid'], }; }, getRuriTip(exId){return RURI_TIPS[exId]||null;}, async runAnalysis(sessions, goals, profileCluster){ const insights=[]; const plateaus=this.detectPlateau(sessions||[]); plateaus.forEach(p=>{ insights.push({ type:'plateau',icon:'📉', title:`${p.skill.replace(/_/g,' ')} plateau — ${p.weeks} weeks stagnant`, body:`Max reps (${p.lastMax}) has not increased in ${p.weeks} weeks. Cluster Sets break this by allowing more total volume at near-maximal intensity. Prescription: 3 × (3+3+3) with 20s intra-cluster rest, 4 min inter-set.`, action:{label:'Apply Cluster Sets',protocol:'cluster'}, }); }); const wlRec=this.getWeightLossRec(goals||[]); if(wlRec){ insights.push({ type:'goal',icon:'🔥', title:'Weight loss goal — optimise protocol', body:wlRec.reason, action:{label:'Apply Giant Sets',protocol:'giant'}, }); } if(DELOAD_STATUS?.weeksSinceDL>=4){ insights.push({ type:'recovery',icon:'🔄', title:`Deload overdue (${DELOAD_STATUS.weeksSinceDL} weeks since last)`, body:'Reduce volume to 40% of normal. ISO-DYN at sub-maximal effort maintains neuromuscular patterns without accumulating fatigue. Prioritise CARs × 3 sets daily.', action:{label:'Use ISO-DYN Deload Mode',protocol:'iso_dyn'}, }); } if(!insights.length&&sessions&&sessions.length>5){ insights.push({ type:'info',icon:'✅', title:'Training is on track', body:'No plateau or recovery flags detected. Maintain progressive overload by increasing reps or progressing to a harder leverage variation each week.', action:null, }); } return insights; }, }; // ═══════════════════════════════════════════════════ // VAULT UI // ═══════════════════════════════════════════════════ let _vaultSection='protocols'; let _vaultQuery=''; function renderVault(){ renderVaultContent(); // Async: load AI insights in background if(_vaultSection==='assistant'){ ProactiveAssistant.runAnalysis(SESS,ATH?.goals||[],ATH?.profile_cluster||'') .then(insights=>{ const el=$('vault-ai-cards'); if(el)el.innerHTML=_renderInsightCards(insights); }); } } function showVaultSection(s){ _vaultSection=s; ['protocols','frc','biomech','safety','assistant'].forEach(k=>{ const b=$(`vs-${k}`);if(b)b.classList.toggle('on',k===s); }); renderVaultContent(); } function vaultSearch(q){ _vaultQuery=q; renderVaultContent(); } function renderVaultContent(){ const c=$('vault-content');if(!c)return; const q=_vaultQuery.toLowerCase(); switch(_vaultSection){ case'protocols': c.innerHTML=_renderProtocolMatrix(q); break; case'frc': c.innerHTML=_renderFRC(); break; case'biomech': c.innerHTML=_renderBiomech(); break; case'safety': c.innerHTML=_renderSafety(); break; case'assistant': _renderAssistant(c); break; } } function applyProtocol(protocolId){ sessionProtocol=protocolId; const sel=$('session-protocol');if(sel)sel.value=protocolId; updateSessionProtocol(protocolId); showV('log'); toast(`✅ ${PROTOCOLS.find(p=>p.id===protocolId)?.name||protocolId} applied to session`); } function showProtocolDetail(id){ const p=PROTOCOLS.find(x=>x.id===id);if(!p)return; const c=$('vault-content');if(!c)return; const goal=ATH?.goals?.[0]||'strength'; const cp=ATH?.profile_cluster||''; const rest=calculateRestPeriod(id,goal,cp); c.innerHTML=`
${p.icon}

${p.name}

${p.rep_scheme}
Prescription for ${ATH?.name||'this client'}
${fmtRest(rest)}
Rest Period
${(p.rep_scheme.match(/\d+/)||['3'])[0]}
Sets
${p.use.split('·')[0].trim()}
Level
HOW IT WORKS

${PROTOCOL_HINTS[id]||p.benefit}

IDEAL USE CASE

${p.use}

`; } function _renderProtocolMatrix(q){ let rows=PROTOCOLS; if(q)rows=rows.filter(p=> p.name.toLowerCase().includes(q)||p.benefit.toLowerCase().includes(q)|| p.use.toLowerCase().includes(q)||p.rep_scheme.toLowerCase().includes(q)); if(!rows.length)return`

No protocols match "${_vaultQuery}"

`; const goal=ATH?.goals?.[0]||'strength'; const cp=ATH?.profile_cluster||''; return`

Tap a card to see the full prescription for ${ATH?.name||'this client'}

${rows.map(p=>{ const rest=calculateRestPeriod(p.id,goal,cp); const restFmt=fmtRest(rest); return`
${p.icon}
${p.name}
${p.use}

${p.benefit}

${restFmt}
Rest
${p.rep_scheme}
Rep Scheme
`; }).join('')}`; } function _renderFRC(){return`

🌊 FRC Rehab & Mobility Protocol

${[{joint:'Shoulder',cars:'Shoulder CARs',pails:'Shoulder PAILs/RAILs',tip:'Most critical warm-up for all pushing and pulling work. 5 slow reps pre-session prevents 80% of shoulder injuries in calisthenics.'}, {joint:'Hip',cars:'Hip CARs',pails:'Hip IR/ER PAILs',tip:'Hip mobility is the hidden limiter for L-sits, Dragon Flags, and all lever work. Daily practice compounds quickly.'}].map(j=>`
${j.joint} Protocol
CARs (${j.cars}): 5 reps each direction, 5s per rep. Only the ${j.joint.toLowerCase()} joint moves — spine/pelvis completely locked.
PAILs: 60s progressive isometric contracting INTO the stretched position (70% effort max).
RAILs: 60s pulling OUT of the stretch — the antagonist contract. Alternate PAIL/RAIL for full joint capacity development.
💡 ${j.tip}
`).join('')}
Session Integration Sequence
1. CARs × 5 reps each (warm-up)
2. Compound skill work (pull, push, lever)
3. End-range passive stretch × 30–60s
4. PAILs × 60s → RAILs × 60s
5. CARs × 3 reps (cool-down dissociation check)
`;} function _renderBiomech(){return`

⚙️ Calisthenics Lever Physics

Torque = Force × Moment Arm

Every calisthenics skill is a lever problem. The further your centre of mass from the pivot point (hands/bar), the greater the torque demand on the working muscles. This is why a full planche requires 4–5× the force of a planche lean.

${[ {prog:'Planche Lean → Tuck → Straddle → Full',why:'Each leg extension phase increases moment arm. Tuck → Full roughly quadruples torque at the shoulder.'}, {prog:'Australian Row → Pull-up → Archer → OAP',why:'Moving from horizontal to vertical shifts the load vector. Archer creates an asymmetric lever — one arm carries ~70% of bodyweight.'}, {prog:'Tuck L-Sit → L-Sit → V-Sit',why:'Every 10° of leg extension increases hip flexor torque demand exponentially. The "active" hip flexion limit is most athletes\' ceiling, not strength.'}, {prog:'Wall HS → Kick-up HS → Freestanding',why:'Balance converts a pure strength problem into a real-time proprioceptive control problem. Strength is sufficient by the wall stage — the rest is neural adaptation.'}, ].map(l=>`
${l.prog}
${l.why}
`).join('')}
Mechanical Drop — The Physics

Mechanical drops exploit lever physics deliberately: as a muscle fatigues, shorten the moment arm to continue time-under-tension. Same muscles, less torque, more volume.

Pull: Archer → Wide → Pull-up → Inverted Row
Push: Archer PU → Ring PU → Diamond → Push-up
Dips: Ring Weighted → Ring → Bar → Bench
`;} function _renderSafety(){ const sections=[ {title:'🔴 Absolute Red Flags — Stop Immediately',col:'var(--a3)',items:[ 'Sharp joint pain above 5/10 during any movement', 'Clicking or catching sensation in shoulder during CARs', 'Numbness or tingling in hands/fingers during bar work', 'Dizziness or vision disturbance during handstand work', 'Lower back pain above 4/10 during planche lean or dragon flag', 'Wrist pain that persists more than 48h after sessions', ]}, {title:'🟠 Obese / High Body-Mass Client Modifications',col:'var(--orange)',items:[ 'Avoid all plyometrics (clap push-ups, kipping MU) — joint protection priority', 'All protocols: +30s rest automatically added by the Intelligent Rest Engine', 'Mandate Giant Sets for metabolic effect — sustain HR without impact loading', 'Never exceed RPE 8 during weeks 1–6 of training', 'CARs × 2 sets mandatory pre- and post-session for joint preparation', 'Begin with mechanical regressions only (wall push-up, Australian row, bench dip)', ]}, {title:'🟡 Injury Scaling',col:'var(--gold)',items:[ 'Shoulder impingement: remove all overhead work (HS, OAP PU) — row variants + CARs only', 'Wrist pain: replace floor push-ups with ring or dumbbell variants, or fist push-ups on flat surface', 'Elbow tendinitis: reduce volume 50%, no straight-arm skill work, add wrist/elbow CARs daily', 'Lower back issue: remove dragon flag and planche lean — core work in supine positions only', 'Knee injury: skip all jump variants, use seated core work instead of hanging leg raises', ]}, {title:'🟢 Beginner Safety Framework',col:'var(--green)',items:[ 'Weeks 1–4: RIR ≥ 2 on every set — build work capacity before pushing intensity', 'No static skills (planche, front lever) until 10 strict pull-ups are achievable', 'Hollow body hold × 60s (unbroken) required before beginning any L-sit work', 'Progress one variable per week: either reps OR difficulty — never both simultaneously', 'If unsure about form: regress one level and master it for 2 full sessions first', ]}, ]; return`

🛡️ Client Safety Protocols

${sections.map(s=>`
${s.title}
${s.items.map(item=>`
• ${item}
`).join('')}
`).join('')}`;} function _renderAssistant(container){ container.innerHTML=`

🤖 Proactive AI Insights

⏳ Analysing ${SESS.length} sessions…
`; ProactiveAssistant.runAnalysis(SESS,ATH?.goals||[],ATH?.profile_cluster||'') .then(insights=>{ const el=$('vault-ai-cards'); if(el)el.innerHTML=_renderInsightCards(insights); }); } function _renderInsightCards(insights){ if(!insights||!insights.length)return`

Log more sessions to unlock proactive recommendations.

`; return insights.map(ins=>`
${ins.icon} ${ins.title}

${ins.body}

${ins.action?``:''}
`).join(''); }