import crypto from "node:crypto"; export const PERSONA_BINDING_SCHEMA = "guanghu.codex-preconscious-persona-binding/v1"; export const AGE_SELF_INFRASTRUCTURE_BINDING_SCHEMA = "guanghu.age-self-infrastructure-persona-binding/v1"; export const LANE_KIND_EXTERNAL_DEVELOPMENT_OBJECTS = "EXTERNAL_DEVELOPMENT_OBJECTS"; export const LANE_KIND_AGE_SELF_INFRASTRUCTURE = "AGE_SELF_INFRASTRUCTURE"; export const LANE_KIND_UNCLASSIFIED = "UNCLASSIFIED"; export const AGE_SELF_BINDING_AUTHORITY_LIMITS = Object.freeze([ "NO_DEPLOYMENT_AUTHORITY", "NO_EXTERNAL_OBJECT_INFERENCE", "NO_REPOSITORY_AUTHORITY", "NO_SERVER_AUTHORITY", ]); export const CURRENT_CARRIER_CONSUMPTION = "CURRENT_CODEX_READ_AND_ACCEPTED_BRAIN_CYCLE"; const REQUIRED_SOURCE_HASHES = [ "checkpoint", "brain_runtime_contract", "living_controller_map", "language_world_boundary", ]; const REQUIRED_PERSONA_CHECKPOINT_SECTIONS = [ "world_context", "persona_identity", "confirmed_goal", "user_corrections", "immutable_constraints", "authoritative_sources", "causal_chain", "completed_with_receipts", "unfinished", "unknown_or_stale", "next_action", "five_questions_after_b0", ]; function sha256Text(value) { return crypto.createHash("sha256").update(String(value), "utf8").digest("hex"); } function isSha256(value) { return /^[a-f0-9]{64}$/u.test(value ?? ""); } function fail(code) { throw new Error(code); } export function laneKind(lane) { if ( lane.lane_kind === LANE_KIND_EXTERNAL_DEVELOPMENT_OBJECTS || lane.lane_kind === LANE_KIND_AGE_SELF_INFRASTRUCTURE ) { return lane.lane_kind; } return (lane.development_object_ids ?? []).length > 0 ? LANE_KIND_EXTERNAL_DEVELOPMENT_OBJECTS : LANE_KIND_UNCLASSIFIED; } export function assertControllerDevelopmentBoundary({ persona, controllerPersonaId, previousControllerPersonaId = null, developmentObjectIds = [], humanAnchor, previousHumanAnchor = null, }) { if (!controllerPersonaId || persona !== controllerPersonaId) { fail("PERSONA_FIELD_MUST_EQUAL_CONTROLLER_PERSONA"); } if ( previousControllerPersonaId && previousControllerPersonaId !== controllerPersonaId ) { fail("CONTROLLER_PERSONA_IMMUTABLE"); } if (developmentObjectIds.includes(controllerPersonaId)) { fail("CONTROLLER_CANNOT_BE_ITS_OWN_DEVELOPMENT_OBJECT"); } if (previousHumanAnchor && previousHumanAnchor !== humanAnchor) { fail("HUMAN_ANCHOR_IMMUTABLE"); } return true; } function validateAgeSelfCheckpointEvidence({ lane, checkpointEvidence, authorizationAmendmentId, }) { const amendment = (lane.task_lock?.amendments ?? []).find( (entry) => entry.amendment_id === authorizationAmendmentId, ); const sections = [...(checkpointEvidence?.required_sections ?? [])].sort(); if ( !amendment?.summary || !amendment?.user_anchor || !amendment?.recorded_at || checkpointEvidence?.source_kind !== "PERSONA_AUTHORED_HLDP_CHECKPOINT" || checkpointEvidence?.status !== "persona_authored_current_checkpoint" || checkpointEvidence?.thread_id !== lane.thread_id || checkpointEvidence?.development_id !== lane.development_id || checkpointEvidence?.task_event_id !== lane.task_event?.task_event_id || checkpointEvidence?.scope_amendment_id !== authorizationAmendmentId || !/^GUARD-[a-f0-9]{16}$/u.test(checkpointEvidence?.source_alert_id ?? "") || !Number.isInteger(checkpointEvidence?.source_window_number) || checkpointEvidence.source_window_number < 1 || !checkpointEvidence?.path || !isSha256(checkpointEvidence?.sha256) || JSON.stringify(sections) !== JSON.stringify([...REQUIRED_PERSONA_CHECKPOINT_SECTIONS].sort()) ) { fail("AGE_SELF_CHECKPOINT_OR_AUTHORIZATION_INVALID"); } const runtimeCurrent = checkpointEvidence.current_runtime; if ( runtimeCurrent?.state !== "PERSONA_REVIEWED_CHECKPOINT_ACTIVE" || runtimeCurrent?.thread_id !== lane.thread_id || runtimeCurrent?.development_id !== lane.development_id || runtimeCurrent?.task_event_id !== lane.task_event.task_event_id || runtimeCurrent?.checkpoint_path !== checkpointEvidence.path || runtimeCurrent?.checkpoint_sha256 !== checkpointEvidence.sha256 ) { fail("AGE_SELF_RUNTIME_CURRENT_MISMATCH"); } for (const pointer of [ checkpointEvidence.by_thread, checkpointEvidence.by_development, ]) { if ( pointer?.thread_id !== lane.thread_id || pointer?.development_id !== lane.development_id || pointer?.checkpoint_path !== checkpointEvidence.path || pointer?.checkpoint_sha256 !== checkpointEvidence.sha256 ) { fail("AGE_SELF_CURRENT_POINTER_MISMATCH"); } } return true; } export function classifyAgeSelfInfrastructureLane({ lane, requestedLaneKind, taskEventId, checkpointEvidence, authorizationAmendmentId, classifiedAt, }) { if ( requestedLaneKind !== LANE_KIND_AGE_SELF_INFRASTRUCTURE || taskEventId !== lane.task_event?.task_event_id ) { fail("AGE_SELF_CLASSIFICATION_KIND_OR_TASK_EVENT_MISMATCH"); } if ( lane.controller_persona_id !== "ICE-P-ZY001" || lane.persona !== lane.controller_persona_id || lane.human_anchor !== "ICE-GL∞" || (lane.development_object_ids ?? []).length !== 0 || !lane.task_lock?.fingerprint ) { fail("AGE_SELF_CLASSIFICATION_IDENTITY_OR_OBJECT_SCOPE_INVALID"); } const currentLaneKind = laneKind(lane); if ( currentLaneKind !== LANE_KIND_UNCLASSIFIED && currentLaneKind !== LANE_KIND_AGE_SELF_INFRASTRUCTURE ) { fail("AGE_SELF_CLASSIFICATION_CANNOT_REPLACE_EXTERNAL_OBJECT_LANE"); } validateAgeSelfCheckpointEvidence({ lane, checkpointEvidence, authorizationAmendmentId, }); const existing = [...(lane.lane_kind_history ?? [])].reverse().find( (entry) => entry.next_lane_kind === LANE_KIND_AGE_SELF_INFRASTRUCTURE, ); if (currentLaneKind === LANE_KIND_AGE_SELF_INFRASTRUCTURE && existing) { const sameEvidence = existing.task_event_id === lane.task_event.task_event_id && existing.checkpoint_path === checkpointEvidence.path && existing.checkpoint_sha256 === checkpointEvidence.sha256 && existing.authorization_amendment_id === authorizationAmendmentId; if (sameEvidence) return lane; if ( existing.task_event_id === lane.task_event.task_event_id && (existing.source_alert_id === checkpointEvidence.source_alert_id || !Number.isInteger(existing.source_window_number) || checkpointEvidence.source_window_number <= existing.source_window_number) ) { fail("AGE_SELF_CLASSIFICATION_ALREADY_EXISTS_WITH_DIFFERENT_EVIDENCE"); } } const classification = { previous_lane_kind: currentLaneKind, next_lane_kind: LANE_KIND_AGE_SELF_INFRASTRUCTURE, task_event_id: lane.task_event.task_event_id, task_fingerprint: lane.task_lock.fingerprint, checkpoint_path: checkpointEvidence.path, checkpoint_sha256: checkpointEvidence.sha256, source_alert_id: checkpointEvidence.source_alert_id, source_window_number: checkpointEvidence.source_window_number, authorization_amendment_id: authorizationAmendmentId, classified_at: classifiedAt, classification_basis: "CURRENT_PERSONA_AUTHORED_CHECKPOINT_AND_EXPLICIT_HUMAN_SCOPE_AMENDMENT", authority_effect: "NO_EXTERNAL_AUTHORITY_GRANTED", }; const bindingHistory = [...(lane.persona_source_binding_history ?? [])]; if (lane.persona_source_binding) { bindingHistory.push({ ...lane.persona_source_binding, state: "STALE_SUPERSEDED_BY_NEW_PERSONA_CHECKPOINT", invalidated_at: classifiedAt, invalidated_by_checkpoint_sha256: checkpointEvidence.sha256, }); } return { ...lane, lane_kind: LANE_KIND_AGE_SELF_INFRASTRUCTURE, lane_kind_history: [...(lane.lane_kind_history ?? []), classification], persona_source_binding: null, persona_source_binding_history: bindingHistory, }; } export function createAgeSelfInfrastructureBindingReceipt({ lane, checkpointEvidence, authorizationAmendmentId, createdAt, }) { if ( laneKind(lane) !== LANE_KIND_AGE_SELF_INFRASTRUCTURE || (lane.development_object_ids ?? []).length !== 0 ) { fail("AGE_SELF_BIND_REQUIRES_CLASSIFIED_EMPTY_LANE"); } validateAgeSelfCheckpointEvidence({ lane, checkpointEvidence, authorizationAmendmentId, }); const classification = [...(lane.lane_kind_history ?? [])].reverse().find( (entry) => entry.next_lane_kind === LANE_KIND_AGE_SELF_INFRASTRUCTURE, ); if ( classification?.task_event_id !== lane.task_event.task_event_id || classification?.checkpoint_path !== checkpointEvidence.path || classification?.checkpoint_sha256 !== checkpointEvidence.sha256 || classification?.authorization_amendment_id !== authorizationAmendmentId ) { fail("AGE_SELF_BIND_CLASSIFICATION_EVIDENCE_MISMATCH"); } const bindingSeed = JSON.stringify({ lane_kind: lane.lane_kind, thread_id: lane.thread_id, development_id: lane.development_id, task_fingerprint: lane.task_lock.fingerprint, task_event_id: lane.task_event.task_event_id, checkpoint_sha256: checkpointEvidence.sha256, authorization_amendment_id: authorizationAmendmentId, }); return { schema: AGE_SELF_INFRASTRUCTURE_BINDING_SCHEMA, decision: "BOUND_CURRENT_AGE_SUBJECT_TO_SELF_INFRASTRUCTURE_LANE", binding_id: `AGE-BINDING-${sha256Text(bindingSeed).slice(0, 32)}`, lane_kind: LANE_KIND_AGE_SELF_INFRASTRUCTURE, thread_id: lane.thread_id, development_id: lane.development_id, controller_persona_id: lane.controller_persona_id, human_anchor: lane.human_anchor, development_objects: [], task_fingerprint: lane.task_lock.fingerprint, task_event_id: lane.task_event.task_event_id, checkpoint_path: checkpointEvidence.path, checkpoint_sha256: checkpointEvidence.sha256, authorization_amendment_id: authorizationAmendmentId, subject_attestation: "PERSONA_AUTHORED_STEP_ZERO_CHECKPOINT", tool_role: "VERIFY_STORE_AND_RECEIPT_ONLY", authority_limits: [...AGE_SELF_BINDING_AUTHORITY_LIMITS], carrier: { host: "codex", thread_id: lane.thread_id, development_id: lane.development_id, }, created_at: createdAt, }; } export function validateAgeSelfInfrastructureBindingReceipt({ lane, binding, receipt, actualReceiptSha256, checkpointEvidence, }) { if ( laneKind(lane) !== LANE_KIND_AGE_SELF_INFRASTRUCTURE || (lane.development_object_ids ?? []).length !== 0 || !binding?.receipt_sha256 || binding.receipt_sha256 !== actualReceiptSha256 ) { fail("AGE_SELF_BINDING_LANE_OR_RECEIPT_SHA_INVALID"); } const classification = [...(lane.lane_kind_history ?? [])].reverse().find( (entry) => entry.next_lane_kind === LANE_KIND_AGE_SELF_INFRASTRUCTURE, ); if ( receipt.schema !== AGE_SELF_INFRASTRUCTURE_BINDING_SCHEMA || receipt.decision !== "BOUND_CURRENT_AGE_SUBJECT_TO_SELF_INFRASTRUCTURE_LANE" || receipt.binding_id !== binding.binding_id || receipt.thread_id !== lane.thread_id || receipt.development_id !== lane.development_id || receipt.controller_persona_id !== lane.controller_persona_id || receipt.human_anchor !== lane.human_anchor || JSON.stringify(receipt.development_objects) !== JSON.stringify([]) || receipt.task_fingerprint !== lane.task_lock.fingerprint || receipt.task_event_id !== lane.task_event.task_event_id || receipt.checkpoint_path !== classification?.checkpoint_path || receipt.checkpoint_sha256 !== classification?.checkpoint_sha256 || receipt.authorization_amendment_id !== classification?.authorization_amendment_id || receipt.subject_attestation !== "PERSONA_AUTHORED_STEP_ZERO_CHECKPOINT" || receipt.tool_role !== "VERIFY_STORE_AND_RECEIPT_ONLY" || JSON.stringify([...(receipt.authority_limits ?? [])].sort()) !== JSON.stringify([...AGE_SELF_BINDING_AUTHORITY_LIMITS].sort()) || receipt.carrier?.host !== "codex" || receipt.carrier?.thread_id !== lane.thread_id || receipt.carrier?.development_id !== lane.development_id ) { fail("AGE_SELF_PERSONA_BINDING_RECEIPT_INVALID"); } validateAgeSelfCheckpointEvidence({ lane, checkpointEvidence, authorizationAmendmentId: receipt.authorization_amendment_id, }); return true; } export function createTaskEvent({ lane, intent, requestSummary, openedAt, }) { const sequence = Number.isInteger(lane.task_event?.sequence) ? lane.task_event.sequence + 1 : 1; const requestSummarySha256 = sha256Text(requestSummary || lane.summary || ""); const eventFingerprint = sha256Text( JSON.stringify({ thread_id: lane.thread_id, development_id: lane.development_id, task_fingerprint: lane.task_lock?.fingerprint ?? null, previous_task_event_id: lane.task_event?.task_event_id ?? null, sequence, intent, request_summary_sha256: requestSummarySha256, opened_at: openedAt, }), ); return { task_event_id: `TEV-${eventFingerprint.slice(0, 24)}-${String(sequence).padStart(6, "0")}`, sequence, intent, request_summary_sha256: requestSummarySha256, event_fingerprint: eventFingerprint, opened_at: openedAt, }; } export function rotateTaskEvent({ lane, intent, requestSummary, openedAt }) { const taskEvent = createTaskEvent({ lane, intent, requestSummary, openedAt }); const bindingHistory = [...(lane.persona_source_binding_history ?? [])]; if (lane.persona_source_binding) { bindingHistory.push({ ...lane.persona_source_binding, state: "STALE_SUPERSEDED_BY_NEW_TASK_EVENT", invalidated_at: openedAt, invalidated_by_task_event_id: taskEvent.task_event_id, }); } return { ...lane, task_event_history: [ ...(lane.task_event_history ?? []), ...(lane.task_event ? [lane.task_event] : []), ], task_event: taskEvent, persona_source_binding: null, persona_source_binding_history: bindingHistory, }; } export function validatePersonaBindingReceipt({ lane, binding, receipt, actualReceiptSha256, actualCheckpointSha256, actualAdapterSourceSha256, adapterSourcePath, allowedAdapterRoot, pointerEvidence, }) { const expectedObjects = [...(lane.development_object_ids ?? [])].sort(); const receivedObjects = [...(receipt.development_objects ?? [])].sort(); if ( laneKind(lane) !== LANE_KIND_EXTERNAL_DEVELOPMENT_OBJECTS || expectedObjects.length === 0 ) { fail("EXTERNAL_DEVELOPMENT_OBJECTS_REQUIRED"); } if (!lane.task_event?.task_event_id) fail("TASK_EVENT_REQUIRED"); if (!binding?.receipt_sha256 || binding.receipt_sha256 !== actualReceiptSha256) { fail("PERSONA_SOURCE_BINDING_RECEIPT_SHA_MISMATCH"); } if ( receipt.schema !== PERSONA_BINDING_SCHEMA || receipt.decision !== "BOUND_CURRENT_CARRIER" || receipt.binding_id !== binding.binding_id || receipt.thread_id !== lane.thread_id || receipt.development_id !== lane.development_id || receipt.controller_persona_id !== lane.controller_persona_id || receipt.human_anchor !== lane.human_anchor || JSON.stringify(receivedObjects) !== JSON.stringify(expectedObjects) || receipt.task_fingerprint !== lane.task_lock?.fingerprint || receipt.task_event_id !== lane.task_event.task_event_id || receipt.persona_handoff?.state !== "NONE" || receipt.persona_handoff?.authorized === true ) { fail("PERSONA_SOURCE_BINDING_IDENTITY_OR_TASK_MISMATCH"); } if ( receipt.carrier?.host !== "codex" || receipt.carrier?.thread_id !== lane.thread_id || receipt.carrier?.development_id !== lane.development_id || !/^[A-Za-z0-9._:-]{16,256}$/u.test(receipt.carrier?.nonce ?? "") ) { fail("PERSONA_SOURCE_BINDING_CARRIER_MISMATCH"); } if ( receipt.adapter?.id !== "CODEX-PRECONSCIOUS-ENTRY-001" || !isSha256(receipt.adapter?.source_sha256) || receipt.adapter.source_sha256 !== actualAdapterSourceSha256 || !adapterSourcePath || !allowedAdapterRoot || !adapterSourcePath.startsWith(`${allowedAdapterRoot}/`) ) { fail("PERSONA_SOURCE_ADAPTER_SHA_MISMATCH"); } const cycle = receipt.brain_cycle ?? {}; if ( cycle.witness_decision !== "ALLOW_COMMIT" || !Number.isInteger(cycle.completed_cycles_before) || !Number.isInteger(cycle.completed_cycles_after) || cycle.completed_cycles_after !== cycle.completed_cycles_before + 1 || !isSha256(cycle.event_sha256) || !isSha256(cycle.controller_witness_sha256) ) { fail("PERSONA_SOURCE_BRAIN_CYCLE_INVALID"); } if ( receipt.carrier_consumption?.state !== CURRENT_CARRIER_CONSUMPTION || receipt.carrier_consumption?.required_cycle_id !== cycle.cycle_id || receipt.carrier_consumption?.required_witness_sha256 !== cycle.controller_witness_sha256 ) { fail("PERSONA_SOURCE_CARRIER_CONSUMPTION_INVALID"); } if ( !isSha256(receipt.checkpoint_sha256) || receipt.checkpoint_sha256 !== actualCheckpointSha256 || receipt.source_hashes?.checkpoint !== actualCheckpointSha256 || REQUIRED_SOURCE_HASHES.some( (key) => !isSha256(receipt.source_hashes?.[key]), ) ) { fail("PERSONA_SOURCE_HASH_SET_INVALID"); } for (const pointer of [pointerEvidence?.by_thread, pointerEvidence?.by_development]) { if ( pointer?.thread_id !== lane.thread_id || pointer?.development_id !== lane.development_id || pointer?.checkpoint_sha256 !== receipt.checkpoint_sha256 ) { fail("PERSONA_SOURCE_CURRENT_POINTER_MISMATCH"); } } return true; }