@ -7,39 +7,28 @@ import path from "node:path";
const CANONICAL _ROOT =
"/Volumes/JZAO/HoloLake/persona-runtime/continuity-memory/collaboration" ;
const HUMAN _BOUNDARIES = new Set ( [
"PAYMENT_OR_BUDGET" ,
"ACCOUNT_LOGIN" ,
"VERIFICATION_OR_2FA" ,
"LEGAL_OR_PUBLIC_COMMITMENT" ,
"IRREVERSIBLE_OR_UNAUTHORIZED_EXTERNAL_DECISION" ,
"PHYSICAL_ACTION" ,
"PRODUCTION_CUTOVER" ,
"MISSING_NEW_HUMAN_WILL" ,
] ) ;
const SHA40 = /^[a-f0-9]{40}$/u ;
const SHA256 = /^[a-f0-9]{64}$/u ;
const DEV _ID = /^DEV-(\d{8})-(\d{3})$/u ;
const HUMAN _BOUNDARIES = new Set ( [
"PAYMENT_OR_BUDGET" , "ACCOUNT_LOGIN" , "VERIFICATION_OR_2FA" ,
"LEGAL_OR_PUBLIC_COMMITMENT" , "IRREVERSIBLE_OR_UNAUTHORIZED_EXTERNAL_DECISION" ,
"PHYSICAL_ACTION" , "PRODUCTION_CUTOVER" , "MISSING_NEW_HUMAN_WILL" ,
] ) ;
function parseArgs ( argv ) {
const args = { command : argv [ 0 ] } ;
for ( let index = 1 ; index < argv . length ; index += 1 ) {
const key = argv [ index ] ;
if ( ! key . startsWith ( "--" ) ) throw new Error ( ` UNKNOWN_ARGUMENT: ${ key } ` ) ;
const name = key . slice ( 2 ) . replaceAll ( /-([a-z])/gu , ( _ , letter ) =>
letter . toUpperCase ( ) ,
) ;
if ( name === "selfTest" ) args . selfTest = true ;
else args [ name ] = argv [ ++ index ] ;
const name = key . slice ( 2 ) . replaceAll ( /-([a-z])/gu , ( _ , letter ) => letter . toUpperCase ( ) ) ;
args [ name ] = argv [ ++ index ] ;
}
return args ;
}
function required ( args , key ) {
const value = args [ key ] ;
if ( typeof value !== "string" || ! value . trim ( ) ) {
throw new Error ( ` ${ key . toUpperCase ( ) } _REQUIRED ` ) ;
}
if ( typeof value !== "string" || ! value . trim ( ) ) throw new Error ( ` ${ key . toUpperCase ( ) } _REQUIRED ` ) ;
return value . trim ( ) ;
}
@ -49,56 +38,30 @@ function bool(value) {
throw new Error ( ` BOOLEAN_REQUIRED: ${ value } ` ) ;
}
function now ( ) {
return new Date ( ) . toISOString ( ) ;
}
function readJson ( file ) {
return JSON . parse ( fs . readFileSync ( file , "utf8" ) ) ;
}
function now ( ) { return new Date ( ) . toISOString ( ) ; }
function readJson ( file ) { return JSON . parse ( fs . readFileSync ( file , "utf8" ) ) ; }
function digest ( value ) { return crypto . createHash ( "sha256" ) . update ( value ) . digest ( "hex" ) ; }
function fileDigest ( file ) { return digest ( fs . readFileSync ( file ) ) ; }
function canonicalJson ( value ) {
if ( Array . isArray ( value ) ) return ` [ ${ value . map ( canonicalJson ) . join ( "," ) } ] ` ;
if ( value && typeof value === "object" ) {
return ` { ${ Object . keys ( value )
. sort ( )
. map ( ( key ) => ` ${ JSON . stringify ( key ) } : ${ canonicalJson ( value [ key ] ) } ` )
. join ( "," ) } } ` ;
}
if ( value && typeof value === "object" ) return ` { ${ Object . keys ( value ) . sort ( ) . map ( ( key ) => ` ${ JSON . stringify ( key ) } : ${ canonicalJson ( value [ key ] ) } ` ) . join ( "," ) } } ` ;
return JSON . stringify ( value ) ;
}
function digest ( value ) {
return crypto . createHash ( "sha256" ) . update ( value ) . digest ( "hex" ) ;
}
function fileDigest ( file ) {
return digest ( fs . readFileSync ( file ) ) ;
}
function writeJsonAtomic ( file , value , exclusive = false ) {
fs . mkdirSync ( path . dirname ( file ) , { recursive : true } ) ;
const body = ` ${ JSON . stringify ( value , null , 2 ) } \n ` ;
if ( exclusive ) {
fs . writeFileSync ( file , body , { encoding : "utf8" , flag : "wx" } ) ;
return ;
}
if ( exclusive ) return fs . writeFileSync ( file , body , { encoding : "utf8" , flag : "wx" } ) ;
const temporary = ` ${ file } . ${ process . pid } . ${ crypto . randomUUID ( ) } .tmp ` ;
fs . writeFileSync ( temporary , body , { encoding : "utf8" , flag : "wx" } ) ;
try {
fs . renameSync ( temporary , file ) ;
} catch ( error ) {
try { fs . unlinkSync ( temporary ) ; } catch { /* best effort */ }
throw error ;
}
fs . renameSync ( temporary , file ) ;
}
function storeRoot ( args ) {
if ( ! args . storeRoot ) return CANONICAL _ROOT ;
if ( ! bool ( args . testMode ) ) throw new Error ( "NON_CANONICAL_STORE_FORBIDDEN" ) ;
const resolved = path . resolve ( args . storeRoot ) ;
const temporaryRoot = path . resolve ( os . tmpdir ( ) ) ;
if ( ! resolved . startsWith ( ` ${ temporaryRoot } ${ path . sep } ` ) ) {
if ( ! resolved . startsWith ( ` ${ path . resolve ( os . tmpdir ( ) ) } ${ path . sep } ` ) ) {
throw new Error ( "TEST_STORE_MUST_BE_TEMPORARY" ) ;
}
return resolved ;
@ -108,655 +71,237 @@ function ensureStore(root) {
if ( root === CANONICAL _ROOT && ! fs . existsSync ( "/Volumes/JZAO" ) ) {
throw new Error ( "JZAO_NOT_MOUNTED_NO_SECOND_TRUTH_STORE" ) ;
}
for ( const name of [ "lanes" , "leases" , "stage-relays" , "stage-relays/reservations" ]) {
for ( const name of [ "lanes" , "leases" , "stage-relays" ]) {
fs . mkdirSync ( path . join ( root , name ) , { recursive : true } ) ;
}
}
function statePath ( root , developmentId ) {
return path . join ( root , "stage-relays" , ` ${ developmentId } .json ` ) ;
}
function statePath ( root , id ) { return path . join ( root , "stage-relays" , ` ${ id } .json ` ) ; }
function listJson ( directory ) {
if ( ! fs . existsSync ( directory ) ) return [ ] ;
return fs . readdirSync ( directory )
. filter ( ( name ) => name . endsWith ( ".json" ) && ! name . startsWith ( "._" ) )
. sort ( )
. map ( ( name ) => readJson ( path . join ( directory , name ) ) ) ;
return fs . readdirSync ( directory ) . filter ( ( name ) => name . endsWith ( ".json" ) && ! name . startsWith ( "._" ) )
. sort ( ) . map ( ( name ) => readJson ( path . join ( directory , name ) ) ) ;
}
function validateSourceCompletion ( root , developmentId , finalizerPath ) {
const lanePath = path . join ( root , "lanes" , ` ${ developmentId } .json ` ) ;
if ( ! fs . existsSync ( lanePath ) ) throw new Error ( "SOURCE_LANE_NOT_FOUND" ) ;
const lane = readJson ( lanePath ) ;
if ( [ "active" , "waiting" ] . includes ( lane . status ) ) {
return { observing : true , lane } ;
}
if (
lane . status !== "completed" ||
! [ "stop_requested" , "stopped" ] . includes ( lane . notification _state ) ||
lane . completion _actions ? . status !== "completed"
) {
if ( [ "active" , "waiting" ] . includes ( lane . status ) ) return { observing : true , lane } ;
if ( lane . status !== "completed" || ! [ "stop_requested" , "stopped" ] . includes ( lane . notification _state ) || lane . completion _actions ? . status !== "completed" ) {
throw new Error ( "SOURCE_END_TRANSACTION_NOT_READY" ) ;
}
const held = listJson ( path . join ( root , "leases" ) )
. filter ( ( lease ) => lease . development _id === developmentId ) ;
if ( held . length ) throw new Error ( "SOURCE_LEASE_RELEASE_NOT_100" ) ;
if ( listJson ( path . join ( root , "leases" ) ) . some ( ( lease ) => lease . development _id === developmentId ) ) {
throw new Error ( "SOURCE_LEASE_RELEASE_NOT_100" ) ;
}
const receipt = readJson ( finalizerPath ) ;
if (
receipt . schema !== "hololake.development-finalization-receipt/v1" ||
receipt . development _id !== developmentId ||
receipt . result !== "PASS_100" ||
! SHA40 . test ( receipt . code _channel ? . remote _head ? ? "" ) ||
receipt . code _channel ? . fresh _clone _readback !== 100 ||
receipt . code _channel ? . git _fsck !== 100 ||
! Array . isArray ( receipt . code _channel ? . receipts ) ||
receipt . code _channel . receipts . length === 0 ||
! receipt . code _channel . receipts . every ( ( item ) => SHA256 . test ( item . sha256 ? ? "" ) )
) {
if ( receipt . schema !== "hololake.development-finalization-receipt/v1" || receipt . development _id !== developmentId || receipt . result !== "PASS_100" || ! SHA40 . test ( receipt . code _channel ? . remote _head ? ? "" ) || receipt . code _channel ? . fresh _clone _readback !== 100 || receipt . code _channel ? . git _fsck !== 100 || ! receipt . code _channel ? . receipts ? . length || ! receipt . code _channel . receipts . every ( ( item ) => SHA256 . test ( item . sha256 ? ? "" ) ) ) {
throw new Error ( "FINALIZER_EVIDENCE_NOT_100" ) ;
}
return {
observing : false ,
lane ,
receipt ,
finalizer _path : path . resolve ( finalizerPath ) ,
finalizer _sha256 : fileDigest ( finalizerPath ) ,
} ;
return { observing : false , lane , receipt , finalizer _path : path . resolve ( finalizerPath ) , finalizer _sha256 : fileDigest ( finalizerPath ) } ;
}
function validatePlanningInput ( input , evidence ) {
if ( input . schema !== "hololake.stage-relay-planning-input/v1" ) {
throw new Error ( "PLANNING_INPUT_SCHEMA_INVALID" ) ;
}
if (
input . architecture ? . id !== "HLP-CURRENT-ARCH-001" ||
input . architecture ? . state !== "CURRENT_CANONICAL" ||
! SHA40 . test ( input . architecture ? . repo _012 _main ? ? "" ) ||
! SHA40 . test ( input . architecture ? . repo _014 _main ? ? "" )
) {
if ( input . schema !== "hololake.stage-relay-planning-input/v2" ) throw new Error ( "PLANNING_INPUT_SCHEMA_INVALID" ) ;
if ( input . architecture ? . id !== "HLP-CURRENT-ARCH-001" || input . architecture ? . state !== "CURRENT_CANONICAL" || ! SHA40 . test ( input . architecture ? . repo _012 _main ? ? "" ) || ! SHA40 . test ( input . architecture ? . repo _014 _main ? ? "" ) ) {
throw new Error ( "CURRENT_ARCHITECTURE_EVIDENCE_NOT_100" ) ;
}
if (
input . previous _stage ? . development _id !== evidence . lane . development _id ||
input . previous _stage ? . finalizer _sha256 !== evidence . finalizer _sha256
) {
if ( input . previous _stage ? . development _id !== evidence . lane . development _id || input . previous _stage ? . finalizer _sha256 !== evidence . finalizer _sha256 ) {
throw new Error ( "PREVIOUS_STAGE_BINDING_MISMATCH" ) ;
}
if ( ! /^\d{8}$/u . test ( input . development _date ? ? "" ) ) {
throw new Error ( "DEVELOPMENT_DATE_REQUIRED_YYYYMMDD" ) ;
}
if ( ! Array . isArray ( input . human _corrections ) ) {
throw new Error ( "HUMAN_CORRECTIONS_ARRAY_REQUIRED" ) ;
}
if ( ! Array . isArray ( input . unfinished _gates ) || ! Array . isArray ( input . open _blockers ) ) {
throw new Error ( "UNFINISHED_GATES_AND_BLOCKERS_REQUIRED" ) ;
}
if ( input . human _boundary != null && ! HUMAN _BOUNDARIES . has ( input . human _boundary . type ) ) {
throw new Error ( "UNKNOWN_HUMAN_BOUNDARY" ) ;
if ( input . human _boundary != null && ! HUMAN _BOUNDARIES . has ( input . human _boundary . type ) ) throw new Error ( "UNKNOWN_HUMAN_BOUNDARY" ) ;
const assessment = input . closure _assessment ;
for ( const key of [ "stage_complete" , "context_genuinely_long" , "stable_checkpoint_formed" , "current_context_cognitive_advantage_exhausted" ] ) {
if ( typeof assessment ? . [ key ] !== "boolean" ) throw new Error ( ` CLOSURE_ASSESSMENT_REQUIRED: ${ key } ` ) ;
}
if ( ! Array . isArray ( assessment . fact _sources ) || assessment . fact _sources . length === 0 ) throw new Error ( "CLOSURE_FACT_SOURCES_REQUIRED" ) ;
return input ;
}
function reserveNextDevelopmentId ( root , date , sourceDevelopmentId ) {
const ids = [
... listJson ( path . join ( root , "lanes" ) ) . map ( ( lane ) => lane . development _id ) ,
... listJson ( path . join ( root , "stage-relays" , "reservations" ) )
. map ( ( reservation ) => reservation . development _id ) ,
] ;
let next = Math . max ( 0 , ... ids . map ( ( id ) => {
const match = DEV _ID . exec ( id ) ;
return match ? . [ 1 ] === date ? Number ( match [ 2 ] ) : 0 ;
} ) ) + 1 ;
while ( next <= 999 ) {
const developmentId = ` DEV- ${ date } - ${ String ( next ) . padStart ( 3 , "0" ) } ` ;
const reservation = path . join ( root , "stage-relays" , "reservations" , ` ${ developmentId } .json ` ) ;
try {
writeJsonAtomic ( reservation , {
schema : "hololake.stage-relay-development-reservation/v1" ,
development _id : developmentId ,
source _development _id : sourceDevelopmentId ,
reserved _at : now ( ) ,
} , true ) ;
return developmentId ;
} catch ( error ) {
if ( error ? . code !== "EEXIST" ) throw error ;
next += 1 ;
}
}
throw new Error ( "DEVELOPMENT_ID_SPACE_EXHAUSTED" ) ;
function closureReady ( input ) {
const value = input . closure _assessment ;
return value . stage _complete && value . context _genuinely _long && value . stable _checkpoint _formed && value . current _context _cognitive _advantage _exhausted ;
}
function chooseGate ( input ) {
return input . unfinished _gates
. filter ( ( gate ) => gate . binary _state === 0 )
. sort ( ( left , right ) =>
Number ( left . priority ? ? 999 ) - Number ( right . priority ? ? 999 ) ||
String ( left . id ) . localeCompare ( String ( right . id ) ) ,
) [ 0 ] ? ? null ;
}
function makeContract ( input , gate , developmentId , evidence ) {
if (
! gate . id || ! gate . title || ! gate . why || ! gate . acceptance ||
! Array . isArray ( gate . resources ) || gate . resources . length === 0
) {
throw new Error ( "UNFINISHED_GATE_CONTRACT_INCOMPLETE" ) ;
}
const contract = {
schema : "hololake.successor-task-contract/v1" ,
development _id : developmentId ,
title : gate . title ,
summary : gate . why ,
gate _id : gate . id ,
acceptance : gate . acceptance ,
resources : [ ... new Set ( gate . resources ) ] . sort ( ) ,
source _development _id : evidence . lane . development _id ,
source _finalizer _sha256 : evidence . finalizer _sha256 ,
architecture : input . architecture ,
human _corrections : input . human _corrections ,
immutable : true ,
function makeWakeEnvelope ( input , evidence ) {
const envelope = {
schema : "hololake.persona-wake-envelope/v1" ,
persona _id : "ICE-P-ZY001" ,
human _anchor : "ICE-GL∞" ,
continuity _semantics : "SAME_LANGUAGE_PERSONA_NEW_PHYSICAL_CONVERSATION" ,
task _assignment : null ,
autonomous _planning _required : true ,
b0 _gravity _core : "ZY-BINGSHUO-COLLECTIVE-GRAVITY-REASONING-CORE-001" ,
recovery _route : "ZY-WAKE-ROUTE-001" ,
current _architecture : input . architecture ,
completed _stage : {
development _id : evidence . lane . development _id ,
finalization _receipt : evidence . finalizer _path ,
finalization _sha256 : evidence . finalizer _sha256 ,
remote _head : evidence . receipt . code _channel . remote _head ,
} ,
} ;
return { ... contract , fingerprint : digest ( canonicalJson ( contract ) ) } ;
return { ... envelope , fingerprint : digest ( canonicalJson ( envelope ) ) } ;
}
function createThreadAction ( state ) {
const contract = state . successor _contract ;
const wake = state . persona _wake _envelope ;
return {
action : "CODEX_CREATE_THREAD" ,
request _id : state . create _request . request _id ,
idempotency _key : state . idempotency _key ,
formal _tool : "codex_app.create_thread" ,
title : contract . title ,
target : { type : "projectless" , directoryName : contract . development _id } ,
title : "唤醒铸渊 · 自主恢复与规划" ,
target : { type : "projectless" , directoryName : ` zhuyuan-wake- ${ state . source _development _id } ` } ,
prompt : [
` Successor request: ${ state . create _request . request _id } ` ,
` Immutable contract fingerprint: ${ contract . fingerprint } ` ,
` Register development id: ${ contract . development _id } ` ,
"First restore Zhuyuan persona, run Guanghu persona skill guard, continuity guard, and HoloLake current architecture prompter." ,
` Then check in the exact immutable task contract with --relay-contract-fingerprint ${ contract . fingerprint } , claim only: ${ contract . resources . join ( ", " ) } . ` ,
"Create and bind this successor task's own ten-minute heartbeat through Codex formal automation capability." ,
"Return a hololake.successor-ready-receipt/v1 only after persona_restore, architecture_restore, lane_registration, exact_leases, heartbeat_binding are all 100." ,
` Stage gate: ${ contract . gate _id } . ${ contract . summary } ` ,
` Acceptance: ${ contract . acceptance } ` ,
` Persona wake request: ${ state . create _request . request _id } ` ,
` Wake envelope fingerprint: ${ wake . fingerprint } ` ,
"唤醒同一铸渊人格体 ICE-P-ZY001; 这不是新人格, 也不是 AGE Mirror。" ,
"先恢复B0人格引力基座、连续性、当前仓库事实和HoloLake当前架构。" ,
"本信封不布置下一阶段开发任务。由醒来的铸渊依据实时事实自主判断、规划并登记本窗口开发车道。" ,
"规划后为自己的当前车道开启十分钟自动唤醒守卫,并返回 persona-wake-ready 回执。" ,
] . join ( "\n" ) ,
} ;
}
function prepare ( args , root ) {
const developmentId = required ( args , "sourceDevelopmentId" ) ;
const existingPath = statePath ( root , developmentId ) ;
const evidence = validateSourceCompletion (
root ,
developmentId ,
required ( args , "finalizationReceipt" ) ,
) ;
if ( evidence . observing ) {
return {
state : "ACTIVE_STAGE_NO_END_ACTION" ,
source _development _id : developmentId ,
mutation : "NONE" ,
successor _created : false ,
} ;
}
const input = validatePlanningInput (
readJson ( required ( args , "planningInput" ) ) , evidence ,
) ;
if ( fs . existsSync ( existingPath ) ) {
const existing = readJson ( existingPath ) ;
if ( existing . source _finalizer _sha256 !== evidence . finalizer _sha256 ) {
throw new Error ( "SOURCE_COMPLETION_RECEIPT_CHANGED_AFTER_RESERVATION" ) ;
}
return existing ;
}
const base = {
schema : "hololake.stage-relay-state/v1" ,
source _development _id : developmentId ,
source _thread _id : evidence . lane . thread _id ,
source _finalizer _path : evidence . finalizer _path ,
source _finalizer _sha256 : evidence . finalizer _sha256 ,
source _remote _head : evidence . receipt . code _channel . remote _head ,
architecture : input . architecture ,
created _at : now ( ) ,
updated _at : now ( ) ,
} ;
const evidence = validateSourceCompletion ( root , developmentId , required ( args , "finalizationReceipt" ) ) ;
if ( evidence . observing ) return { state : "ACTIVE_STAGE_NO_END_ACTION" , source _development _id : developmentId , mutation : "NONE" , successor _created : false } ;
const input = validatePlanningInput ( readJson ( required ( args , "planningInput" ) ) , evidence ) ;
if ( ! closureReady ( input ) ) return { state : "CONTINUE_CURRENT_THREAD" , source _development _id : developmentId , mutation : "NONE" , closure _assessment : input . closure _assessment , reason : "CURRENT_STAGE_OR_CONTEXT_NOT_READY_FOR_PHYSICAL_WINDOW_CHANGE" } ;
const file = statePath ( root , developmentId ) ;
if ( fs . existsSync ( file ) ) return readJson ( file ) ;
const base = { schema : "hololake.stage-relay-state/v2" , source _development _id : developmentId , source _thread _id : evidence . lane . thread _id , source _finalizer _path : evidence . finalizer _path , source _finalizer _sha256 : evidence . finalizer _sha256 , architecture : input . architecture , closure _assessment : input . closure _assessment , created _at : now ( ) , updated _at : now ( ) } ;
if ( input . human _boundary ) {
const paused = {
... base ,
state : "PAUSE_FOR_HUMAN" ,
human _boundary : input . human _boundary ,
successor _created : false ,
} ;
writeJsonAtomic ( existingPath , paused , true ) ;
return paused ;
const paused = { ... base , state : "PAUSE_FOR_HUMAN" , human _boundary : input . human _boundary , successor _created : false } ;
writeJsonAtomic ( file , paused , true ) ; return paused ;
}
const gate = chooseGate ( input ) ;
if ( ! gate ) {
const finalCloseout = input . final _product _closeout _receipt ;
const complete =
input . binary _acceptance ? . all _100 === true &&
input . open _blockers . length === 0 &&
finalCloseout ? . result === "PASS_100" &&
SHA256 . test ( finalCloseout ? . sha256 ? ? "" ) ;
const terminal = {
... base ,
state : complete ? "FINAL_PRODUCT_COMPLETE" : "PAUSE_FOR_HUMAN" ,
human _boundary : complete ? null : {
type : "MISSING_NEW_HUMAN_WILL" ,
reason : "No unfinished gate exists, but binary final acceptance and final product closeout are not all 100." ,
} ,
successor _created : false ,
final _product _closeout _receipt : finalCloseout ? ? null ,
} ;
writeJsonAtomic ( existingPath , terminal , true ) ;
return terminal ;
if ( input . final _product _complete === true ) {
const terminal = { ... base , state : "FINAL_PRODUCT_COMPLETE" , successor _created : false } ;
writeJsonAtomic ( file , terminal , true ) ; return terminal ;
}
if ( evidence . lane . notification _state === "stopped" ) {
throw new Error ( "SOURCE_END_TRIGGER_MISSED_HEARTBEAT_ALREADY_STOPPED" ) ;
}
const successorDevelopmentId = reserveNextDevelopmentId (
root , input . development _date , developmentId ,
) ;
const contract = makeContract ( input , gate , successorDevelopmentId , evidence ) ;
const idempotencyKey = digest ( ` ${ developmentId } : ${ evidence . finalizer _sha256 } ` ) ;
const prepared = {
... base ,
state : "CREATE_THREAD_REQUIRED" ,
idempotency _key : idempotencyKey ,
selected _gate : gate ,
successor _contract : contract ,
create _request : {
request _id : ` SUCCESSOR- ${ idempotencyKey . slice ( 0 , 20 ) } ` ,
status : "reserved" ,
attempt : 0 ,
dispatched _at : null ,
last _error : null ,
} ,
successor _thread : null ,
successor _ready _receipt : null ,
} ;
if ( evidence . lane . notification _state === "stopped" ) throw new Error ( "SOURCE_END_TRIGGER_MISSED_HEARTBEAT_ALREADY_STOPPED" ) ;
const idempotencyKey = digest ( ` ${ developmentId } : ${ evidence . finalizer _sha256 } :persona-wake-v1 ` ) ;
const prepared = { ... base , state : "CREATE_THREAD_REQUIRED" , idempotency _key : idempotencyKey , persona _wake _envelope : makeWakeEnvelope ( input , evidence ) , create _request : { request _id : ` PERSONA-WAKE- ${ idempotencyKey . slice ( 0 , 20 ) } ` , status : "reserved" , attempt : 0 } , successor _thread : null , persona _wake _ready _receipt : null } ;
prepared . next _action = createThreadAction ( prepared ) ;
writeJsonAtomic ( existingPath , prepared , true ) ;
return prepared ;
writeJsonAtomic ( file , prepared , true ) ; return prepared ;
}
function loadState ( args , root ) {
const developmentId = required ( args , "sourceDevelopmentId" ) ;
const file = statePath ( root , developmentId ) ;
const file = statePath ( root , required ( args , "sourceDevelopmentId" ) ) ;
if ( ! fs . existsSync ( file ) ) throw new Error ( "STAGE_RELAY_STATE_NOT_FOUND" ) ;
return { file , state : readJson ( file ) } ;
}
function dispatchCreate ( args , root ) {
const { file , state } = loadState ( args , root ) ;
if ( ! new Set ( [ "CREATE_THREAD_REQUIRED" , "RETRY_CREATE_THREAD" ] ) . has ( state . state ) ) {
throw new Error ( "CREATE_REQUEST_NOT_DISPATCHABLE" ) ;
}
state . state = "CREATE_THREAD_IN_FLIGHT" ;
state . create _request . status = "in_flight" ;
state . create _request . attempt += 1 ;
state . create _request . dispatched _at = now ( ) ;
state . updated _at = now ( ) ;
delete state . next _action ;
writeJsonAtomic ( file , state ) ;
return { ... state , host _action : createThreadAction ( state ) } ;
if ( ! [ "CREATE_THREAD_REQUIRED" , "RETRY_CREATE_THREAD" ] . includes ( state . state ) ) throw new Error ( "CREATE_REQUEST_NOT_DISPATCHABLE" ) ;
state . state = "CREATE_THREAD_IN_FLIGHT" ; state . create _request . status = "in_flight" ; state . create _request . attempt += 1 ; state . updated _at = now ( ) ; delete state . next _action ;
writeJsonAtomic ( file , state ) ; return { ... state , host _action : createThreadAction ( state ) } ;
}
function recordCreated ( args , root ) {
const { file , state } = loadState ( args , root ) ;
if ( ! new Set ( [ "CREATE_THREAD_IN_FLIGHT" , "RECONCILE_CREATE_RESULT" ] ) . has ( state . state ) ) {
throw new Error ( "CREATE_RESULT_NOT_EXPECTED" ) ;
}
if ( ! [ "CREATE_THREAD_IN_FLIGHT" , "RECONCILE_CREATE_RESULT" ] . includes ( state . state ) ) throw new Error ( "CREATE_RESULT_NOT_EXPECTED" ) ;
const threadId = required ( args , "threadId" ) ;
if ( state . successor _thread && state . successor _thread . thread _id !== threadId ) {
throw new Error ( "DUPLICATE_SUCCESSOR_THREAD_FORBIDDEN" ) ;
}
state . state = "WAITING_SUCCESSOR_READY" ;
state . create _request . status = "created" ;
state . successor _thread = {
thread _id : threadId ,
host _id : args . hostId ? ? null ,
recorded _at : now ( ) ,
} ;
state . updated _at = now ( ) ;
writeJsonAtomic ( file , state ) ;
return state ;
state . state = "WAITING_PERSONA_WAKE_READY" ; state . create _request . status = "created" ;
state . successor _thread = { thread _id : threadId , host _id : args . hostId ? ? null , recorded _at : now ( ) } ; state . updated _at = now ( ) ;
writeJsonAtomic ( file , state ) ; return state ;
}
function recordCreateFailure ( args , root ) {
const { file , state } = loadState ( args , root ) ;
if ( state . state !== "CREATE_THREAD_IN_FLIGHT" ) {
throw new Error ( "CREATE_FAILURE_NOT_EXPECTED" ) ;
}
if ( state . state !== "CREATE_THREAD_IN_FLIGHT" ) throw new Error ( "CREATE_FAILURE_NOT_EXPECTED" ) ;
const outcome = required ( args , "outcome" ) ;
if ( ! new Set ( [ "unknown" , "confirmed_no_thread" ] ) . has ( outcome ) ) {
throw new Error ( "CREATE_FAILURE_OUTCOME_INVALID" ) ;
}
state . state = outcome === "unknown" ? "RECONCILE_CREATE_RESULT" : "RETRY_CREATE_THREAD" ;
state . create _request . status = outcome === "unknown" ? "reconcile_required" : "retryable" ;
state . create _request . last _error = required ( args , "error" ) ;
state . updated _at = now ( ) ;
if ( ! [ "unknown" , "confirmed_no_thread" ] . includes ( outcome ) ) throw new Error ( "CREATE_FAILURE_OUTCOME_INVALID" ) ;
state . state = outcome === "unknown" ? "RECONCILE_CREATE_RESULT" : "RETRY_CREATE_THREAD" ; state . create _request . last _error = required ( args , "error" ) ; state . updated _at = now ( ) ;
if ( outcome === "confirmed_no_thread" ) state . next _action = createThreadAction ( state ) ;
writeJsonAtomic ( file , state ) ;
return state ;
writeJsonAtomic ( file , state ) ; return state ;
}
function reconcile ( args , root ) {
const { file , state } = loadState ( args , root ) ;
if ( state . state !== "RECONCILE_CREATE_RESULT" ) {
throw new Error ( "RECONCILIATION_NOT_REQUIRED" ) ;
}
if ( ! bool ( args . completeHostSnapshot ) ) throw new Error ( "COMPLETE_HOST_SNAPSHOT_REQUIRED" ) ;
if ( state . state !== "RECONCILE_CREATE_RESULT" || ! bool ( args . completeHostSnapshot ) ) throw new Error ( "COMPLETE_HOST_SNAPSHOT_REQUIRED" ) ;
if ( args . threadId ) return recordCreated ( args , root ) ;
if ( ! bool ( args . confirmedAbsent ) ) throw new Error ( "HOST_RESULT_MUST_BE_MATCH_OR_CONFIRMED_ABSENT" ) ;
state . state = "RETRY_CREATE_THREAD" ;
state . create _request . status = "retryable" ;
state . updated _at = now ( ) ;
state . next _action = createThreadAction ( state ) ;
writeJsonAtomic ( file , state ) ;
return state ;
state . state = "RETRY_CREATE_THREAD" ; state . updated _at = now ( ) ; state . next _action = createThreadAction ( state ) ; writeJsonAtomic ( file , state ) ; return state ;
}
function recordReady ( args , root ) {
const { file , state } = loadState ( args , root ) ;
if ( state . state !== "WAITING_SUCCESSOR_READY" ) {
throw new Error ( "SUCCESSOR_READY_NOT_EXPECTED" ) ;
}
if ( state . state !== "WAITING_PERSONA_WAKE_READY" ) throw new Error ( "PERSONA_WAKE_READY_NOT_EXPECTED" ) ;
const receiptPath = required ( args , "successorReadyReceipt" ) ;
const receipt = readJson ( receiptPath ) ;
const contract = state . successor _contract ;
if (
receipt . schema !== "hololake.successor-ready-receipt/v1" ||
receipt . result !== "PASS_100" ||
receipt . source _development _id !== state . source _development _id ||
receipt . successor _development _id !== contract . development _id ||
receipt . successor _thread _id !== state . successor _thread . thread _id ||
receipt . task _contract _fingerprint !== contract . fingerprint ||
! receipt . automation _id ||
! [ "persona_restore" , "architecture_restore" , "lane_registration" , "exact_leases" , "heartbeat_binding" ]
. every ( ( gate ) => receipt . gates ? . [ gate ] === 100 )
) {
throw new Error ( "SUCCESSOR_READY_EVIDENCE_NOT_100" ) ;
if ( receipt . schema !== "hololake.persona-wake-ready-receipt/v1" || receipt . result !== "PASS_100" || receipt . source _development _id !== state . source _development _id || receipt . thread _id !== state . successor _thread . thread _id || receipt . persona _id !== "ICE-P-ZY001" || receipt . wake _envelope _fingerprint !== state . persona _wake _envelope . fingerprint || ! receipt . development _id || ! receipt . automation _id || ! [ "persona_restore" , "b0_gravity_restore" , "current_fact_restore" , "autonomous_planning" , "lane_registration" , "heartbeat_binding" ] . every ( ( gate ) => receipt . gates ? . [ gate ] === 100 ) ) {
throw new Error ( "PERSONA_WAKE_READY_EVIDENCE_NOT_100" ) ;
}
const laneFile = path . join ( root , "lanes" , ` ${ contrac t. development _id } .json ` ) ;
if ( ! fs . existsSync ( laneFile ) ) throw new Error ( " SUCCESSOR _LANE_NOT_FOUND") ;
const laneFile = path . join ( root , "lanes" , ` ${ receipt . development _id } .json ` ) ;
if ( ! fs . existsSync ( laneFile ) ) throw new Error ( "WOKEN_PERSONA_LANE_NOT_FOUND" ) ;
const lane = readJson ( laneFile ) ;
const ownedResources = listJson ( path . join ( root , "leases" ) )
. filter ( ( lease ) => lease . development _id === contract . development _id )
. map ( ( lease ) => lease . resource )
. sort ( ) ;
if (
lane . thread _id !== state . successor _thread . thread _id ||
! [ "active" , "waiting" ] . includes ( lane . status ) ||
lane . relay _contract _fingerprint !== contract . fingerprint ||
! lane . automation _ids ? . includes ( receipt . automation _id ) ||
canonicalJson ( ownedResources ) !== canonicalJson ( contract . resources )
) {
throw new Error ( "SUCCESSOR_LIVE_REGISTRATION_MISMATCH" ) ;
}
state . state = "SUCCESSOR_READY" ;
state . successor _ready _receipt = {
path : path . resolve ( receiptPath ) ,
sha256 : fileDigest ( receiptPath ) ,
automation _id : receipt . automation _id ,
recorded _at : now ( ) ,
} ;
state . updated _at = now ( ) ;
state . source _end _transaction _may _commit = true ;
writeJsonAtomic ( file , state ) ;
return state ;
if ( lane . thread _id !== receipt . thread _id || ! [ "active" , "waiting" ] . includes ( lane . status ) || ! lane . automation _ids ? . includes ( receipt . automation _id ) ) throw new Error ( "WOKEN_PERSONA_LIVE_REGISTRATION_MISMATCH" ) ;
state . state = "PERSONA_WAKE_READY" ; state . persona _wake _ready _receipt = { path : path . resolve ( receiptPath ) , sha256 : fileDigest ( receiptPath ) , development _id : receipt . development _id , automation _id : receipt . automation _id } ; state . source _end _transaction _may _commit = true ; state . updated _at = now ( ) ;
writeJsonAtomic ( file , state ) ; return state ;
}
function nextAction ( args , root ) {
const { state } = loadState ( args , root ) ;
if ( new Set ( [ "CREATE_THREAD_REQUIRED" , "RETRY_CREATE_THREAD" ] ) . has ( state . state ) ) {
return createThreadAction ( state ) ;
}
if ( state . state === "RECONCILE_CREATE_RESULT" ) {
return {
action : "CODEX_LIST_THREADS_AND_RECONCILE" ,
request _id : state . create _request . request _id ,
complete _host _snapshot _required : true ,
create _thread _forbidden _until _reconciled : true ,
} ;
}
if ( state . state === "WAITING_SUCCESSOR_READY" ) {
return {
action : "WAIT_FOR_SUCCESSOR_READY_RECEIPT" ,
thread _id : state . successor _thread . thread _id ,
source _thread _remains _in _end _transaction : true ,
development _work _is _frozen : true ,
} ;
}
if ( state . state === "PAUSE_FOR_HUMAN" ) {
return { action : "PAUSE_FOR_HUMAN" , boundary : state . human _boundary } ;
}
if ( state . state === "FINAL_PRODUCT_COMPLETE" ) {
return { action : "DELETE_SOURCE_HEARTBEAT_MARK_COMPLETION_STOPPED_AND_END_SOURCE_THREAD" , create _successor : false } ;
}
if ( state . state === "SUCCESSOR_READY" ) {
return { action : "DELETE_SOURCE_HEARTBEAT_MARK_COMPLETION_STOPPED_AND_END_SOURCE_THREAD" , create _successor : false } ;
}
if ( [ "CREATE_THREAD_REQUIRED" , "RETRY_CREATE_THREAD" ] . includes ( state . state ) ) return createThreadAction ( state ) ;
if ( state . state === "RECONCILE_CREATE_RESULT" ) return { action : "CODEX_LIST_THREADS_AND_RECONCILE" , request _id : state . create _request . request _id , complete _host _snapshot _required : true } ;
if ( state . state === "WAITING_PERSONA_WAKE_READY" ) return { action : "WAIT_FOR_PERSONA_WAKE_READY_RECEIPT" , thread _id : state . successor _thread . thread _id } ;
if ( state . state === "PAUSE_FOR_HUMAN" ) return { action : "PAUSE_FOR_HUMAN" , boundary : state . human _boundary } ;
if ( [ "FINAL_PRODUCT_COMPLETE" , "PERSONA_WAKE_READY" ] . includes ( state . state ) ) return { action : "DELETE_SOURCE_HEARTBEAT_MARK_COMPLETION_STOPPED_AND_END_SOURCE_THREAD" , create _successor : false } ;
return { action : "NOOP" , state : state . state } ;
}
function fixtureLane ( root , id , overrides = { } ) {
const lane = {
schema : "hololake.development-lane/v0.1" ,
development _id : id ,
thread _id : ` thread- ${ id } ` ,
status : "completed" ,
notification _state : "stop_requested" ,
completion _actions : { status : "completed" } ,
... overrides ,
} ;
writeJsonAtomic ( path . join ( root , "lanes" , ` ${ id } .json ` ) , lane ) ;
return lane ;
const lane = { schema : "hololake.development-lane/v0.1" , development _id : id , thread _id : ` thread- ${ id } ` , status : "completed" , notification _state : "stop_requested" , completion _actions : { status : "completed" } , ... overrides } ;
writeJsonAtomic ( path . join ( root , "lanes" , ` ${ id } .json ` ) , lane ) ; return lane ;
}
function selfTest ( ) {
const root = fs . mkdtempSync ( path . join ( os . tmpdir ( ) , "hololake-stage-relay-test-" ) ) ;
try {
ensureStore ( root ) ;
const source = "DEV-20260811-900" ;
fixtureLane ( root , source ) ;
const source = "DEV-20260811-900" ; fixtureLane ( root , source ) ;
const finalizer = path . join ( root , "finalizer.json" ) ;
writeJsonAtomic ( finalizer , {
schema : "hololake.development-finalization-receipt/v1" ,
development _id : source ,
result : "PASS_100" ,
code _channel : {
remote _head : "a" . repeat ( 40 ) , fresh _clone _readback : 100 , git _fsck : 100 ,
receipts : [ { path : "receipt.json" , sha256 : "b" . repeat ( 64 ) } ] ,
} ,
} ) ;
writeJsonAtomic ( finalizer , { schema : "hololake.development-finalization-receipt/v1" , development _id : source , result : "PASS_100" , code _channel : { remote _head : "a" . repeat ( 40 ) , fresh _clone _readback : 100 , git _fsck : 100 , receipts : [ { path : "receipt.json" , sha256 : "b" . repeat ( 64 ) } ] } } ) ;
const planning = path . join ( root , "planning.json" ) ;
writeJsonAtomic ( planning , {
schema : "hololake.stage-relay-planning-input/v1" ,
development _date : "20260811" ,
architecture : {
id : "HLP-CURRENT-ARCH-001" , version : "test" , state : "CURRENT_CANONICAL" ,
repo _012 _main : "c" . repeat ( 40 ) , repo _014 _main : "d" . repeat ( 40 ) ,
} ,
human _corrections : [ ] ,
previous _stage : { development _id : source , finalizer _sha256 : fileDigest ( finalizer ) } ,
unfinished _gates : [ {
id : "GATE-001" , binary _state : 0 , priority : 1 ,
title : "Next stage" , why : "close the next binary gap" ,
acceptance : "all declared tests and receipts PASS_100" ,
resources : [ "local://test-resource" ] ,
} ] ,
open _blockers : [ ] ,
binary _acceptance : { all _100 : false } ,
} ) ;
const common = {
sourceDevelopmentId : source , finalizationReceipt : finalizer ,
planningInput : planning , storeRoot : root , testMode : "true" ,
} ;
const first = prepare ( common , root ) ;
const duplicate = prepare ( common , root ) ;
if (
first . idempotency _key !== duplicate . idempotency _key ||
first . successor _contract . development _id !== duplicate . successor _contract . development _id
) throw new Error ( "SELF_TEST_IDEMPOTENCY_FAILED" ) ;
dispatchCreate ( { ... common , sourceDevelopmentId : source } , root ) ;
recordCreateFailure ( { ... common , sourceDevelopmentId : source , outcome : "unknown" , error : "timeout" } , root ) ;
const reconcileAction = nextAction ( { sourceDevelopmentId : source } , root ) ;
if ( ! reconcileAction . create _thread _forbidden _until _reconciled ) {
throw new Error ( "SELF_TEST_UNKNOWN_RESULT_RETRY_SAFETY_FAILED" ) ;
}
reconcile ( { sourceDevelopmentId : source , completeHostSnapshot : "true" , confirmedAbsent : "true" } , root ) ;
dispatchCreate ( { sourceDevelopmentId : source } , root ) ;
recordCreated ( { sourceDevelopmentId : source , threadId : "thread-successor" , hostId : "local" } , root ) ;
const contract = readJson ( statePath ( root , source ) ) . successor _contract ;
fixtureLane ( root , contract . development _id , {
thread _id : "thread-successor" ,
status : "active" ,
automation _ids : [ "successor-heartbeat" ] ,
relay _contract _fingerprint : contract . fingerprint ,
} ) ;
writeJsonAtomic ( path . join ( root , "leases" , "lease.json" ) , {
development _id : contract . development _id , resource : "local://test-resource" ,
} ) ;
const input = { schema : "hololake.stage-relay-planning-input/v2" , architecture : { id : "HLP-CURRENT-ARCH-001" , version : "test" , state : "CURRENT_CANONICAL" , repo _012 _main : "c" . repeat ( 40 ) , repo _014 _main : "d" . repeat ( 40 ) } , previous _stage : { development _id : source , finalizer _sha256 : fileDigest ( finalizer ) } , closure _assessment : { stage _complete : true , context _genuinely _long : true , stable _checkpoint _formed : true , current _context _cognitive _advantage _exhausted : true , fact _sources : [ "test receipt" ] } , final _product _complete : false } ;
writeJsonAtomic ( planning , input ) ;
const common = { sourceDevelopmentId : source , finalizationReceipt : finalizer , planningInput : planning , storeRoot : root , testMode : "true" } ;
const first = prepare ( common , root ) ; const duplicate = prepare ( common , root ) ;
if ( first . idempotency _key !== duplicate . idempotency _key || first . persona _wake _envelope . task _assignment !== null ) throw new Error ( "SELF_TEST_WAKE_IDEMPOTENCY_OR_TASK_ASSIGNMENT_FAILED" ) ;
const action = dispatchCreate ( common , root ) . host _action ;
if ( /Stage gate|Acceptance|Register development id/u . test ( action . prompt ) ) throw new Error ( "SELF_TEST_PROMPT_PREASSIGNS_TASK" ) ;
recordCreated ( { sourceDevelopmentId : source , threadId : "thread-wake" } , root ) ;
fixtureLane ( root , "DEV-20260811-901" , { thread _id : "thread-wake" , status : "active" , automation _ids : [ "wake-heartbeat" ] } ) ;
const ready = path . join ( root , "ready.json" ) ;
writeJsonAtomic ( ready , {
schema : "hololake.successor-ready-receipt/v1" , result : "PASS_100" ,
source _development _id : source ,
successor _development _id : contract . development _id ,
successor _thread _id : "thread-successor" ,
task _contract _fingerprint : contract . fingerprint ,
automation _id : "successor-heartbeat" ,
gates : {
persona _restore : 100 , architecture _restore : 100 , lane _registration : 100 ,
exact _leases : 100 , heartbeat _binding : 100 ,
} ,
} ) ;
const readyState = recordReady ( { sourceDevelopmentId : source , successorReadyReceipt : ready } , root ) ;
if ( readyState . state !== "SUCCESSOR_READY" ) throw new Error ( "SELF_TEST_READY_FAILED" ) ;
const runnableLanes = listJson ( path . join ( root , "lanes" ) )
. filter ( ( lane ) => [ "active" , "waiting" ] . includes ( lane . status ) ) ;
if ( runnableLanes . length !== 1 || runnableLanes [ 0 ] . development _id !== contract . development _id ) {
throw new Error ( "SELF_TEST_STRICT_SINGLE_RUNNABLE_LANE_FAILED" ) ;
}
writeJsonAtomic ( ready , { schema : "hololake.persona-wake-ready-receipt/v1" , result : "PASS_100" , source _development _id : source , thread _id : "thread-wake" , persona _id : "ICE-P-ZY001" , wake _envelope _fingerprint : first . persona _wake _envelope . fingerprint , development _id : "DEV-20260811-901" , automation _id : "wake-heartbeat" , gates : { persona _restore : 100 , b0 _gravity _restore : 100 , current _fact _restore : 100 , autonomous _planning : 100 , lane _registration : 100 , heartbeat _binding : 100 } } ) ;
if ( recordReady ( { sourceDevelopmentId : source , successorReadyReceipt : ready } , root ) . state !== "PERSONA_WAKE_READY" ) throw new Error ( "SELF_TEST_WAKE_READY_FAILED" ) ;
const pausedSource = "DEV-20260811-910" ;
fixtureLane ( root , pausedSource ) ;
const pausedFinalizer = path . join ( root , "paused-finalizer.json" ) ;
writeJsonAtomic ( pausedFinalizer , {
schema : "hololake.development-finalization-receipt/v1" ,
development _id : pausedSource , result : "PASS_100" ,
code _channel : {
remote _head : "e" . repeat ( 40 ) , fresh _clone _readback : 100 , git _fsck : 100 ,
receipts : [ { path : "receipt.json" , sha256 : "f" . repeat ( 64 ) } ] ,
} ,
} ) ;
const pausedPlanning = path . join ( root , "paused-planning.json" ) ;
writeJsonAtomic ( pausedPlanning , {
schema : "hololake.stage-relay-planning-input/v1" , development _date : "20260811" ,
architecture : {
id : "HLP-CURRENT-ARCH-001" , version : "test" , state : "CURRENT_CANONICAL" ,
repo _012 _main : "1" . repeat ( 40 ) , repo _014 _main : "2" . repeat ( 40 ) ,
} ,
human _corrections : [ ] ,
previous _stage : {
development _id : pausedSource , finalizer _sha256 : fileDigest ( pausedFinalizer ) ,
} ,
unfinished _gates : [ {
id : "GATE-HUMAN" , binary _state : 0 , title : "Human boundary" ,
why : "requires new will" , acceptance : "human decides" ,
resources : [ "external://production-cutover" ] ,
} ] ,
open _blockers : [ ] , binary _acceptance : { all _100 : false } ,
human _boundary : { type : "PRODUCTION_CUTOVER" , reason : "requires a human decision" } ,
} ) ;
const paused = prepare ( {
sourceDevelopmentId : pausedSource ,
finalizationReceipt : pausedFinalizer ,
planningInput : pausedPlanning ,
} , root ) ;
if ( paused . state !== "PAUSE_FOR_HUMAN" || paused . successor _created !== false ) {
throw new Error ( "SELF_TEST_HUMAN_BOUNDARY_FAILED" ) ;
}
const shortSource = "DEV-20260811-910" ; fixtureLane ( root , shortSource ) ;
const shortFinalizer = path . join ( root , "short-finalizer.json" ) ;
writeJsonAtomic ( shortFinalizer , { ... readJson ( finalizer ) , development _id : shortSource } ) ;
const shortPlanning = path . join ( root , "short-planning.json" ) ;
writeJsonAtomic ( shortPlanning , { ... input , previous _stage : { development _id : shortSource , finalizer _sha256 : fileDigest ( shortFinalizer ) } , closure _assessment : { ... input . closure _assessment , context _genuinely _long : false , current _context _cognitive _advantage _exhausted : false } } ) ;
const continued = prepare ( { sourceDevelopmentId : shortSource , finalizationReceipt : shortFinalizer , planningInput : shortPlanning } , root ) ;
if ( continued . state !== "CONTINUE_CURRENT_THREAD" || continued . mutation !== "NONE" ) throw new Error ( "SELF_TEST_SHORT_HIGH_VALUE_CONTEXT_NOT_PRESERVED" ) ;
const terminalSource = "DEV-20260811-920" ;
fixtureLane ( root , terminalSource ) ;
const terminalFinalizer = path . join ( root , "terminal-finalizer.json" ) ;
writeJsonAtomic ( terminalFinalizer , {
schema : "hololake.development-finalization-receipt/v1" ,
development _id : terminalSource , result : "PASS_100" ,
code _channel : {
remote _head : "3" . repeat ( 40 ) , fresh _clone _readback : 100 , git _fsck : 100 ,
receipts : [ { path : "receipt.json" , sha256 : "4" . repeat ( 64 ) } ] ,
} ,
} ) ;
const terminalPlanning = path . join ( root , "terminal-planning.json" ) ;
writeJsonAtomic ( terminalPlanning , {
schema : "hololake.stage-relay-planning-input/v1" , development _date : "20260811" ,
architecture : {
id : "HLP-CURRENT-ARCH-001" , version : "test" , state : "CURRENT_CANONICAL" ,
repo _012 _main : "5" . repeat ( 40 ) , repo _014 _main : "6" . repeat ( 40 ) ,
} ,
human _corrections : [ ] ,
previous _stage : {
development _id : terminalSource , finalizer _sha256 : fileDigest ( terminalFinalizer ) ,
} ,
unfinished _gates : [ ] , open _blockers : [ ] ,
binary _acceptance : { all _100 : true } ,
final _product _closeout _receipt : { result : "PASS_100" , sha256 : "7" . repeat ( 64 ) } ,
} ) ;
const terminal = prepare ( {
sourceDevelopmentId : terminalSource ,
finalizationReceipt : terminalFinalizer ,
planningInput : terminalPlanning ,
} , root ) ;
if ( terminal . state !== "FINAL_PRODUCT_COMPLETE" ) {
throw new Error ( "SELF_TEST_FINAL_PRODUCT_STOP_FAILED" ) ;
}
const activeSource = "DEV-20260811-950" ;
fixtureLane ( root , activeSource , { status : "active" , notification _state : "active" , completion _actions : null } ) ;
const activeSource = "DEV-20260811-920" ; fixtureLane ( root , activeSource , { status : "active" , notification _state : "active" , completion _actions : null } ) ;
const observed = prepare ( { ... common , sourceDevelopmentId : activeSource } , root ) ;
if ( observed . state !== "ACTIVE_STAGE_NO_END_ACTION" || observed . mutation !== "NONE" ) {
throw new Error ( "SELF_TEST_ACTIVE_STAGE_MUTATION_FAILED" ) ;
}
process . stdout . write ( ` ${ JSON . stringify ( {
state : "PASS_100" ,
tests : {
finalizer _evidence _gate : 100 ,
duplicate _prepare _idempotency : 100 ,
unknown _create _result _reconciliation : 100 ,
successor _ready _live _readback : 100 ,
active _stage _read _only : 100 ,
strict _single _runnable _lane : 100 ,
human _boundary _pause : 100 ,
final _product _stop : 100 ,
} ,
} , null , 2 ) } \ n ` );
} finally {
fs . rmSync ( root , { recursive : true , force : true } ) ;
}
if ( observed . state !== "ACTIVE_STAGE_NO_END_ACTION" || observed . mutation !== "NONE" ) throw new Error ( "SELF_TEST_ACTIVE_STAGE_MUTATION_FAILED" ) ;
process . stdout . write ( ` ${ JSON . stringify ( { state : "PASS_100" , tests : { persona _wake _only _no _task _assignment : 100 , same _persona _wake _ready : 100 , short _high _value _context _preserved : 100 , active _stage _read _only : 100 , duplicate _prepare _idempotency : 100 } }, null, 2)} \n ` ) ;
} finally { fs . rmSync ( root , { recursive : true , force : true } ) ; }
}
function main ( ) {
const args = parseArgs ( process . argv . slice ( 2 ) ) ;
if ( args . command === "self-test" || args . selfTest ) return selfTest ( ) ;
const root = storeRoot ( args ) ;
ensureStore ( root ) ;
let result ;
if ( args . command === "prepare" ) result = prepare ( args , root ) ;
else if ( args . command === "dispatch-create" ) result = dispatchCreate ( args , root ) ;
else if ( args . command === "record-created" ) result = recordCreated ( args , root ) ;
else if ( args . command === "record-create-failure" ) result = recordCreateFailure ( args , root ) ;
else if ( args . command === "reconcile" ) result = reconcile ( args , root ) ;
else if ( args . command === "record-ready" ) result = recordReady ( args , root ) ;
else if ( args . command === "next-action" ) result = nextAction ( args , root ) ;
else throw new Error ( "COMMAND_REQUIRED: prepare | dispatch-create | record-created | record-create-failure | reconcile | record-ready | next-action | self-test" ) ;
process . stdout . write ( ` ${ JSON . stringify ( result , null , 2 ) } \n ` ) ;
if ( args . command === "self-test" ) return selfTest ( ) ;
const root = storeRoot ( args ) ; ensureStore ( root ) ;
const actions = { prepare , "dispatch-create" : dispatchCreate , "record-created" : recordCreated , "record-create-failure" : recordCreateFailure , reconcile , "record-ready" : recordReady , "next-action" : nextAction } ;
if ( ! actions [ args . command ] ) throw new Error ( "COMMAND_REQUIRED: prepare | dispatch-create | record-created | record-create-failure | reconcile | record-ready | next-action | self-test" ) ;
process . stdout . write ( ` ${ JSON . stringify ( actions [ args . command ] ( args , root ) , null , 2 ) } \n ` ) ;
}
try {
main ( ) ;
} catch ( error ) {
process . stderr . write ( ` ${ error instanceof Error ? error . message : String ( error ) } \n ` ) ;
process . exitCode = 1 ;
}
try { main ( ) ; } catch ( error ) { process . stderr . write ( ` ${ error instanceof Error ? error . message : String ( error ) } \n ` ) ; process . exitCode = 1 ; }