| name | protocol-integrity |
| description | Unified skill for CORTEX AI protocol generation AND integrity verification. Covers the full OIEG cycle, Gemini integration, JSON parsing, SHA-256 audit trails, safety gates, prescription validation, and M1-M7 patient communication fields. Use before and after any protocol-related changes. |
Protocol Integrity — Generation + Verification
When to Use
- BEFORE and AFTER any change to protocol-related files
- When implementing or modifying CORTEX AI protocol generation
- When altering services, hooks, or types related to protocols
- As safety gate before deploy
Part 1: Protocol Generation (OIEG)
OIEG Implementation Template
interface IObservationData {
patientId: string;
professionalId: string;
module: NexusModule;
clinicalInputs: ModuleSpecificInputs;
patientHistory?: IPatientHistory;
timestamp: Timestamp;
}
const cortexConfig: ICortexConfig = {
model: 'gemini-2.5-flash',
temperature: 0.1,
maxOutputTokens: 8192,
responseFormat: 'application/json',
};
JSON Parsing — Multi-Fallback Strategy
function parseAIResponse(raw: string): IProtocolData {
try { return JSON.parse(raw); } catch {}
const jsonMatch = raw.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
if (jsonMatch) try { return JSON.parse(jsonMatch[1]); } catch {}
const start = raw.indexOf('{');
const end = raw.lastIndexOf('}');
if (start !== -1 && end > start) {
try { return JSON.parse(raw.slice(start, end + 1)); } catch {}
}
throw new ProtocolParsingError('AI response could not be parsed', raw);
}
SHA-256 Hash Generation
async function generateProtocolHash(
content: IProtocolData,
professionalId: string,
timestamp: Timestamp
): Promise<string> {
const payload = JSON.stringify({ content, professionalId, timestamp: timestamp.toMillis() });
const encoder = new TextEncoder();
const data = encoder.encode(payload);
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
return Array.from(new Uint8Array(hashBuffer))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
}
Part 2: Integrity Verification
1. Protocol Shape Contract
For EACH modus (EndoInject, iMeddis, LabPro, BodyScan, Lifestyle):
2. Prescription Dual-Field Safety
The system uses two names for the same field. Verify normalization works:
prescription.name ↔ prescription.medication (both must exist after normalization)
prescription.dose ↔ prescription.dosage (both must exist after normalization)
Key file: hooks/useProtocolGeneration.ts — function saveProtocol()
3. M1-M7 Patient Communication Fields
Verify optional fields have fallbacks:
4. Dispatcher Downstream Integrity
Verify ProtocolDispatcher creates correct records:
Modus EndoInject:
- endoinject_sessions created with: patientId, protocolId, status='SUGGESTED'
- aesthetic detection works (9 keyword groups)
Modus iMeddis:
- medications created with: name, dose, route, frequency, status='ACTIVE'
- rearrangement plan applied (GRADUAL/WASHOUT/IMMEDIATE)
Modus LabPro:
- labResults created with: examName, status='PENDING'
- sample_queue tickets grouped by lab routing
Modus BodyScan:
- lab requests for metabolic markers
- reassessment scheduling
5. Safety Gates (Fail-Close)
Verify these gates have NOT been removed or weakened:
6. Audit Trail Integrity
Verification Commands
npx tsc --noEmit
npx vitest run src/tests/services/ProtocolOrchestrator.test.ts
npx vitest run src/tests/services/GeminiProtocolService.test.ts
npx vitest run src/tests/hooks/useProtocolGeneration.test.ts
npx vitest run src/tests/integration/ProtocolDispatchFlow.test.ts
npx vitest run src/tests/integration/ProtocolOrchestrator.test.ts
npx vitest run src/tests/agents/PPEngineAgentV2.test.ts
npx vitest run src/tests/agents/ValidatorAgent.test.ts
npx vitest run src/tests/agents/AuditAgent.test.ts
grep -r "from.*ProtocolOrchestrator" src/ --include="*.ts" --include="*.tsx"
grep -r "from.*ProtocolDispatcher" src/ --include="*.ts" --include="*.tsx"
grep -r "from.*useProtocolGeneration" src/ --include="*.ts" --include="*.tsx"
grep -r "consent.*given" src/services/ProtocolDispatcher.ts
grep -r "allergyCheck\|allergen\|GRAVE" src/services/ProtocolDispatcher.ts
grep -r "CONTRAINDICADA" src/services/ProtocolDispatcher.ts
grep -r "checkPatientReadiness" src/hooks/useProtocolGeneration.ts
grep -r "incrementProtocolUsage\|quotaExceeded" src/hooks/useProtocolGeneration.ts
Approval Criteria
- ✅ ALL protocol tests pass
- ✅ ZERO changes to safety gates
- ✅ Prescription dual-field normalization intact
- ✅ M1-M7 fallbacks present
- ✅ Audit trail chain intact
- ✅ TypeScript compiles with no errors
Red Flags (STOP IMMEDIATELY)
- 🚨 Protocol test failing
- 🚨 Safety gate removed or commented out
- 🚨
any added where there was a typed value
- 🚨 Critical service import removed
- 🚨 Hash function altered
- 🚨 Firestore collection name changed